sql_partition.cc 222 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
/* Copyright (C) 2005 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   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 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/*
18
  This file is a container for general functionality related
19
  to partitioning introduced in MySQL version 5.1. It contains functionality
20 21
  used by all handlers that support partitioning, such as
  the partitioning handler itself and the NDB handler.
22

unknown's avatar
unknown committed
23
  The first version was written by Mikael Ronstrom.
24 25 26 27 28

  This 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
29
  called KEY partitioning), where the MySQL server will use an internal
30 31 32 33 34 35
  hash function.
  There are quite a few defaults that can be used as well.
*/

/* Some general useful functions */

36
#define MYSQL_LEX 1
37 38 39 40 41
#include "mysql_priv.h"
#include <errno.h>
#include <m_ctype.h>
#include "md5.h"

42
#ifdef WITH_PARTITION_STORAGE_ENGINE
unknown's avatar
unknown committed
43
#include "ha_partition.h"
44 45 46
/*
  Partition related functions declarations and some static constants;
*/
47 48 49 50 51 52 53 54 55
const LEX_STRING partition_keywords[]=
{
  { (char *) STRING_WITH_LEN("HASH") },
  { (char *) STRING_WITH_LEN("RANGE") },
  { (char *) STRING_WITH_LEN("LIST") }, 
  { (char *) STRING_WITH_LEN("KEY") },
  { (char *) STRING_WITH_LEN("MAXVALUE") },
  { (char *) STRING_WITH_LEN("LINEAR ") }
};
56 57 58 59 60 61 62 63
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= ",";
64 65
static char buff[22];

unknown's avatar
unknown committed
66
int get_partition_id_list(partition_info *part_info,
67 68
                           uint32 *part_id,
                           longlong *func_value);
unknown's avatar
unknown committed
69
int get_partition_id_range(partition_info *part_info,
70 71
                            uint32 *part_id,
                            longlong *func_value);
unknown's avatar
unknown committed
72
int get_partition_id_hash_nosub(partition_info *part_info,
73 74
                                 uint32 *part_id,
                                 longlong *func_value);
unknown's avatar
unknown committed
75
int get_partition_id_key_nosub(partition_info *part_info,
76 77
                                uint32 *part_id,
                                longlong *func_value);
unknown's avatar
unknown committed
78
int get_partition_id_linear_hash_nosub(partition_info *part_info,
79 80
                                        uint32 *part_id,
                                        longlong *func_value);
unknown's avatar
unknown committed
81
int get_partition_id_linear_key_nosub(partition_info *part_info,
82 83
                                       uint32 *part_id,
                                       longlong *func_value);
unknown's avatar
unknown committed
84
int get_partition_id_range_sub_hash(partition_info *part_info,
85 86
                                     uint32 *part_id,
                                     longlong *func_value);
unknown's avatar
unknown committed
87
int get_partition_id_range_sub_key(partition_info *part_info,
88 89
                                    uint32 *part_id,
                                    longlong *func_value);
unknown's avatar
unknown committed
90
int get_partition_id_range_sub_linear_hash(partition_info *part_info,
91 92
                                            uint32 *part_id,
                                            longlong *func_value);
unknown's avatar
unknown committed
93
int get_partition_id_range_sub_linear_key(partition_info *part_info,
94 95
                                           uint32 *part_id,
                                           longlong *func_value);
unknown's avatar
unknown committed
96
int get_partition_id_list_sub_hash(partition_info *part_info,
97 98
                                    uint32 *part_id,
                                    longlong *func_value);
unknown's avatar
unknown committed
99
int get_partition_id_list_sub_key(partition_info *part_info,
100 101
                                   uint32 *part_id,
                                   longlong *func_value);
unknown's avatar
unknown committed
102
int get_partition_id_list_sub_linear_hash(partition_info *part_info,
103 104
                                           uint32 *part_id,
                                           longlong *func_value);
unknown's avatar
unknown committed
105
int get_partition_id_list_sub_linear_key(partition_info *part_info,
106 107
                                          uint32 *part_id,
                                          longlong *func_value);
108 109 110 111
uint32 get_partition_id_hash_sub(partition_info *part_info); 
uint32 get_partition_id_key_sub(partition_info *part_info); 
uint32 get_partition_id_linear_hash_sub(partition_info *part_info); 
uint32 get_partition_id_linear_key_sub(partition_info *part_info); 
unknown's avatar
unknown committed
112 113
#endif

unknown's avatar
unknown committed
114 115 116 117 118 119
static uint32 get_next_partition_via_walking(PARTITION_ITERATOR*);
static uint32 get_next_subpartition_via_walking(PARTITION_ITERATOR*);
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,
120
                                           char *min_value, char *max_value,
unknown's avatar
unknown committed
121 122 123 124
                                           uint flags,
                                           PARTITION_ITERATOR *part_iter);
int get_part_iter_for_interval_via_walking(partition_info *part_info,
                                           bool is_subpart,
125
                                           char *min_value, char *max_value,
unknown's avatar
unknown committed
126 127 128
                                           uint flags,
                                           PARTITION_ITERATOR *part_iter);
static void set_up_range_analysis_info(partition_info *part_info);
unknown's avatar
unknown committed
129 130 131 132

/*
  A routine used by the parser to decide whether we are specifying a full
  partitioning or if only partitions to add or to split.
unknown's avatar
unknown committed
133

unknown's avatar
unknown committed
134 135 136
  SYNOPSIS
    is_partition_management()
    lex                    Reference to the lex object
unknown's avatar
unknown committed
137

unknown's avatar
unknown committed
138 139 140
  RETURN VALUE
    TRUE                   Yes, it is part of a management partition command
    FALSE                  No, not a management partition command
unknown's avatar
unknown committed
141

unknown's avatar
unknown committed
142
  DESCRIPTION
143 144
    This needs to be outside of WITH_PARTITION_STORAGE_ENGINE since it is
    used from the sql parser that doesn't have any #ifdef's
unknown's avatar
unknown committed
145 146 147 148 149 150
*/

my_bool is_partition_management(LEX *lex)
{
  return (lex->sql_command == SQLCOM_ALTER_TABLE &&
          (lex->alter_info.flags == ALTER_ADD_PARTITION ||
unknown's avatar
unknown committed
151
           lex->alter_info.flags == ALTER_REORGANIZE_PARTITION));
unknown's avatar
unknown committed
152 153
}

154
#ifdef WITH_PARTITION_STORAGE_ENGINE
unknown's avatar
unknown committed
155
/*
unknown's avatar
unknown committed
156 157
  A support function to check if a name is in a list of strings

unknown's avatar
unknown committed
158
  SYNOPSIS
unknown's avatar
unknown committed
159 160 161 162
    is_name_in_list()
    name               String searched for
    list_names         A list of names searched in

unknown's avatar
unknown committed
163 164 165 166 167
  RETURN VALUES
    TRUE               String found
    FALSE              String not found
*/

unknown's avatar
unknown committed
168 169
bool is_name_in_list(char *name,
                          List<char> list_names)
unknown's avatar
unknown committed
170
{
unknown's avatar
unknown committed
171 172
  List_iterator<char> names_it(list_names);
  uint no_names= list_names.elements;
unknown's avatar
unknown committed
173
  uint i= 0;
unknown's avatar
unknown committed
174

unknown's avatar
unknown committed
175 176
  do
  {
unknown's avatar
unknown committed
177 178
    char *list_name= names_it++;
    if (!(my_strcasecmp(system_charset_info, name, list_name)))
unknown's avatar
unknown committed
179 180 181 182 183 184
      return TRUE;
  } while (++i < no_names);
  return FALSE;
}


unknown's avatar
unknown committed
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

/*
  Set-up defaults for partitions. 

  SYNOPSIS
    partition_default_handling()
    table                         Table object
    table_name                    Table name to use when getting no_parts
    db_name                       Database name to use when getting no_parts
    part_info                     Partition info to set up

  RETURN VALUES
    TRUE                          Error
    FALSE                         Success
*/

201
bool partition_default_handling(TABLE *table, partition_info *part_info,
202
                                bool is_create_table_ind,
203
                                const char *normalized_path)
unknown's avatar
unknown committed
204 205 206 207 208
{
  DBUG_ENTER("partition_default_handling");

  if (part_info->use_default_no_partitions)
  {
209 210
    if (!is_create_table_ind &&
        table->file->get_no_parts(normalized_path, &part_info->no_parts))
unknown's avatar
unknown committed
211 212 213 214
    {
      DBUG_RETURN(TRUE);
    }
  }
215
  else if (part_info->is_sub_partitioned() &&
unknown's avatar
unknown committed
216 217 218
           part_info->use_default_no_subpartitions)
  {
    uint no_parts;
219 220
    if (!is_create_table_ind &&
        (table->file->get_no_parts(normalized_path, &no_parts)))
unknown's avatar
unknown committed
221 222 223 224 225 226 227
    {
      DBUG_RETURN(TRUE);
    }
    DBUG_ASSERT(part_info->no_parts > 0);
    part_info->no_subparts= no_parts / part_info->no_parts;
    DBUG_ASSERT((no_parts % part_info->no_parts) == 0);
  }
228 229
  part_info->set_up_defaults_for_partitioning(table->file,
                                              (ulonglong)0, (uint)0);
unknown's avatar
unknown committed
230 231 232 233
  DBUG_RETURN(FALSE);
}


234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
/*
  Check that the reorganized table will not have duplicate partitions.

  SYNOPSIS
    check_reorganise_list()
    new_part_info      New partition info
    old_part_info      Old partition info
    list_part_names    The list of partition names that will go away and can be reused in the
                       new table.

  RETURN VALUES
    TRUE               Inacceptable name conflict detected.
    FALSE              New names are OK.

  DESCRIPTION
    Can handle that the 'new_part_info' and 'old_part_info' the same
    in which case it checks that the list of names in the partitions
    doesn't contain any duplicated names.
*/

bool check_reorganise_list(partition_info *new_part_info,
                           partition_info *old_part_info,
                           List<char> list_part_names)
{
  uint new_count, old_count;
  uint no_new_parts= new_part_info->partitions.elements;
  uint no_old_parts= old_part_info->partitions.elements;
  List_iterator<partition_element> new_parts_it(new_part_info->partitions);
  bool same_part_info= (new_part_info == old_part_info);
  DBUG_ENTER("check_reorganise_list");

  new_count= 0;
  do
  {
    List_iterator<partition_element> old_parts_it(old_part_info->partitions);
    char *new_name= (new_parts_it++)->partition_name;
    new_count++;
    old_count= 0;
    do
    {
      char *old_name= (old_parts_it++)->partition_name;
      old_count++;
      if (same_part_info && old_count == new_count)
        break;
      if (!(my_strcasecmp(system_charset_info, old_name, new_name)))
      {
unknown's avatar
unknown committed
280
        if (!is_name_in_list(old_name, list_part_names))
281 282 283 284 285 286 287 288
          DBUG_RETURN(TRUE);
      }
    } while (old_count < no_old_parts);
  } while (new_count < no_new_parts);
  DBUG_RETURN(FALSE);
}


289 290 291
/*
  A useful routine used by update_row for partition handlers to calculate
  the partition ids of the old and the new record.
unknown's avatar
unknown committed
292

293 294 295 296 297 298
  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
unknown's avatar
unknown committed
299 300 301
    out:old_part_id         The returned partition id of old record 
    out:new_part_id         The returned partition id of new record

302 303 304 305 306 307 308
  RETURN VALUE
    0                       Success
    > 0                     Error code
*/

int get_parts_for_update(const byte *old_data, byte *new_data,
                         const byte *rec0, partition_info *part_info,
309 310
                         uint32 *old_part_id, uint32 *new_part_id,
                         longlong *new_func_value)
311 312 313
{
  Field **part_field_array= part_info->full_part_field_array;
  int error;
314
  longlong old_func_value;
315 316
  DBUG_ENTER("get_parts_for_update");

unknown's avatar
unknown committed
317
  DBUG_ASSERT(new_data == rec0);
318
  set_field_ptr(part_field_array, old_data, rec0);
319 320
  error= part_info->get_partition_id(part_info, old_part_id,
                                     &old_func_value);
321 322 323 324 325 326 327 328 329 330
  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
  {
331 332 333
    if (unlikely(error= part_info->get_partition_id(part_info,
                                                    new_part_id,
                                                    new_func_value)))
334 335 336 337 338 339 340 341 342 343 344 345 346
    {
      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);
347 348
    error= part_info->get_partition_id(part_info, new_part_id,
                                       new_func_value);
349 350 351 352 353 354 355 356 357 358 359 360 361 362
    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.
unknown's avatar
unknown committed
363

364 365 366 367 368
  SYNOPSIS
    get_part_for_delete()
    buf                     Buffer of old record
    rec0                    Reference to table->record[0]
    part_info               Reference to partition information
unknown's avatar
unknown committed
369 370
    out:part_id             The returned partition id to delete from

371 372 373
  RETURN VALUE
    0                       Success
    > 0                     Error code
unknown's avatar
unknown committed
374

375 376 377 378 379 380 381 382 383 384
  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 byte *buf, const byte *rec0,
                        partition_info *part_info, uint32 *part_id)
{
  int error;
385
  longlong func_value;
386 387 388 389
  DBUG_ENTER("get_part_for_delete");

  if (likely(buf == rec0))
  {
390 391
    if (unlikely((error= part_info->get_partition_id(part_info, part_id,
                                                     &func_value))))
392 393 394 395 396 397 398 399 400
    {
      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);
401
    error= part_info->get_partition_id(part_info, part_id, &func_value);
402 403 404 405 406 407 408 409 410 411 412 413
    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);
}


/*
unknown's avatar
unknown committed
414 415 416
  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.
417 418 419 420 421

  SYNOPSIS
    set_up_field_array()
    table                TABLE object for which partition fields are set-up
    sub_part             Is the table subpartitioned as well
unknown's avatar
unknown committed
422

423 424 425
  RETURN VALUE
    TRUE                 Error, some field didn't meet requirements
    FALSE                Ok, partition field array set-up
unknown's avatar
unknown committed
426

427
  DESCRIPTION
unknown's avatar
unknown committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452

    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.
453
*/
unknown's avatar
unknown committed
454

455
static bool set_up_field_array(TABLE *table,
unknown's avatar
unknown committed
456
                              bool is_sub_part)
457 458
{
  Field **ptr, *field, **field_array;
unknown's avatar
unknown committed
459 460 461
  uint no_fields= 0;
  uint size_field_array;
  uint i= 0;
unknown's avatar
unknown committed
462
  partition_info *part_info= table->part_info;
463 464 465 466 467 468 469 470 471
  int result= FALSE;
  DBUG_ENTER("set_up_field_array");

  ptr= table->field;
  while ((field= *(ptr++))) 
  {
    if (field->flags & GET_FIXED_FIELDS_FLAG)
      no_fields++;
  }
unknown's avatar
unknown committed
472 473 474 475 476 477 478 479
  if (no_fields == 0)
  {
    /*
      We are using hidden key as partitioning field
    */
    DBUG_ASSERT(!is_sub_part);
    DBUG_RETURN(result);
  }
480 481 482 483
  size_field_array= (no_fields+1)*sizeof(Field*);
  field_array= (Field**)sql_alloc(size_field_array);
  if (unlikely(!field_array))
  {
unknown's avatar
unknown committed
484
    mem_alloc_error(size_field_array);
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
    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))
      {
        field_array[i++]= field;

        /*
          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[no_fields]= 0;
unknown's avatar
unknown committed
515
  if (!is_sub_part)
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
  {
    part_info->part_field_array= field_array;
    part_info->no_part_fields= no_fields;
  }
  else
  {
    part_info->subpart_field_array= field_array;
    part_info->no_subpart_fields= no_fields;
  }
  DBUG_RETURN(result);
}


/*
  Create a field array including all fields of both the partitioning and the
  subpartitioning functions.
unknown's avatar
unknown committed
532

533 534 535 536
  SYNOPSIS
    create_full_part_field_array()
    table                TABLE object for which partition fields are set-up
    part_info            Reference to partitioning data structure
unknown's avatar
unknown committed
537

538 539 540
  RETURN VALUE
    TRUE                 Memory allocation of field array failed
    FALSE                Ok
unknown's avatar
unknown committed
541

542 543 544 545 546 547 548 549 550 551 552 553 554
  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(TABLE *table,
                                         partition_info *part_info)
{
  bool result= FALSE;
  DBUG_ENTER("create_full_part_field_array");

555
  if (!part_info->is_sub_partitioned())
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
  {
    part_info->full_part_field_array= part_info->part_field_array;
    part_info->no_full_part_fields= part_info->no_part_fields;
  }
  else
  {
    Field **ptr, *field, **field_array;
    uint no_part_fields=0, size_field_array;
    ptr= table->field;
    while ((field= *(ptr++)))
    {
      if (field->flags & FIELD_IN_PART_FUNC_FLAG)
        no_part_fields++;
    }
    size_field_array= (no_part_fields+1)*sizeof(Field*);
    field_array= (Field**)sql_alloc(size_field_array);
    if (unlikely(!field_array))
    {
unknown's avatar
unknown committed
574
      mem_alloc_error(size_field_array);
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
      result= TRUE;
      goto end;
    }
    no_part_fields= 0;
    ptr= table->field;
    while ((field= *(ptr++)))
    {
      if (field->flags & FIELD_IN_PART_FUNC_FLAG)
        field_array[no_part_fields++]= field;
    }
    field_array[no_part_fields]=0;
    part_info->full_part_field_array= field_array;
    part_info->no_full_part_fields= no_part_fields;
  }
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).
unknown's avatar
unknown committed
598

599 600 601
  SYNOPSIS
    clear_indicator_in_key_fields()
    key_info                  Reference to find the key fields
unknown's avatar
unknown committed
602 603 604 605 606 607 608 609 610 611 612 613

  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.
614 615 616 617 618 619 620 621 622 623 624 625 626
*/

static void clear_indicator_in_key_fields(KEY *key_info)
{
  KEY_PART_INFO *key_part;
  uint key_parts= key_info->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.
unknown's avatar
unknown committed
627

628 629 630
  SYNOPSIS
    set_indicator_in_key_fields
    key_info                  Reference to find the key fields
unknown's avatar
unknown committed
631 632 633

  RETURN VALUE
    NONE
634 635 636 637 638 639 640 641 642 643 644 645 646 647
*/

static void set_indicator_in_key_fields(KEY *key_info)
{
  KEY_PART_INFO *key_part;
  uint key_parts= key_info->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.
unknown's avatar
unknown committed
648

649 650 651
  SYNOPSIS
    check_fields_in_PF()
    ptr                  Partition field array
unknown's avatar
unknown committed
652 653 654
    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

655 656 657 658 659 660 661 662
  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");
unknown's avatar
unknown committed
663

664 665
  *all_fields= TRUE;
  *some_fields= FALSE;
666 667 668 669 670
  if ((!ptr) || !(*ptr))
  {
    *all_fields= FALSE;
    DBUG_VOID_RETURN;
  }
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
  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.
unknown's avatar
unknown committed
686

687 688 689
  SYNOPSIS
    clear_field_flag()
    table                TABLE object for which partition fields are set-up
unknown's avatar
unknown committed
690 691 692

  RETURN VALUE
    NONE
693 694 695 696 697 698 699 700 701 702 703 704 705 706
*/

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;
}


/*
unknown's avatar
unknown committed
707 708 709
  find_field_in_table_sef finds the field given its name. All fields get
  GET_FIXED_FIELDS_FLAG set.

710 711 712 713 714 715
  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
unknown's avatar
unknown committed
716

717 718 719
  RETURN VALUE
    TRUE                 Fields in list of fields not part of table
    FALSE                All fields ok and array created
unknown's avatar
unknown committed
720

721
  DESCRIPTION
unknown's avatar
unknown committed
722 723 724 725
    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.

726 727
*/

unknown's avatar
unknown committed
728

729 730 731
static bool handle_list_of_fields(List_iterator<char> it,
                                  TABLE *table,
                                  partition_info *part_info,
unknown's avatar
unknown committed
732
                                  bool is_sub_part)
733 734 735 736
{
  Field *field;
  bool result;
  char *field_name;
unknown's avatar
unknown committed
737
  bool is_list_empty= TRUE;
738 739 740 741
  DBUG_ENTER("handle_list_of_fields");

  while ((field_name= it++))
  {
unknown's avatar
unknown committed
742
    is_list_empty= FALSE;
743 744 745 746 747 748 749 750 751 752 753
    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;
    }
  }
unknown's avatar
unknown committed
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
  if (is_list_empty)
  {
    uint primary_key= table->s->primary_key;
    if (primary_key != MAX_KEY)
    {
      uint no_key_parts= table->key_info[primary_key].key_parts, i;
      /*
        In the case of an empty list we use primary key as partition key.
      */
      for (i= 0; i < no_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);
791 792 793 794 795 796
end:
  DBUG_RETURN(result);
}


/*
unknown's avatar
unknown committed
797 798 799 800 801
  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.

802 803 804 805 806 807 808
  SYNOPSIS
    fix_fields_part_func()
    thd                  The thread object
    tables               A list of one table, the partitioned table
    func_expr            The item tree reference of the partition function
    part_info            Reference to partitioning data structure
    sub_part             Is the table subpartitioned as well
unknown's avatar
unknown committed
809

810 811 812 813
  RETURN VALUE
    TRUE                 An error occurred, something was wrong with the
                         partition function.
    FALSE                Ok, a partition field array was created
unknown's avatar
unknown committed
814

815
  DESCRIPTION
unknown's avatar
unknown committed
816 817 818 819 820 821
    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.
822 823 824 825 826 827 828

    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.
unknown's avatar
unknown committed
829
*/
830

unknown's avatar
unknown committed
831 832 833 834
static bool fix_fields_part_func(THD *thd, TABLE_LIST *tables,
                                 Item* func_expr, partition_info *part_info,
                                 bool is_sub_part)
{
835 836
  bool result= TRUE;
  TABLE *table= tables->table;
unknown's avatar
unknown committed
837
  TABLE_LIST *save_table_list, *save_first_table, *save_last_table;
838
  int error;
unknown's avatar
unknown committed
839
  Name_resolution_context *context;
unknown's avatar
unknown committed
840
  const char *save_where;
841 842
  DBUG_ENTER("fix_fields_part_func");

unknown's avatar
unknown committed
843
  context= thd->lex->current_context();
844 845
  table->map= 1; //To ensure correct calculation of const item
  table->get_fields_in_item_tree= TRUE;
unknown's avatar
unknown committed
846 847 848
  save_table_list= context->table_list;
  save_first_table= context->first_name_resolution_table;
  save_last_table= context->last_name_resolution_table;
849
  context->table_list= tables;
unknown's avatar
unknown committed
850 851
  context->first_name_resolution_table= tables;
  context->last_name_resolution_table= NULL;
852
  func_expr->walk(&Item::change_context_processor, 0, (byte*) context);
unknown's avatar
unknown committed
853
  save_where= thd->where;
854 855
  thd->where= "partition function";
  error= func_expr->fix_fields(thd, (Item**)0);
unknown's avatar
unknown committed
856 857 858
  context->table_list= save_table_list;
  context->first_name_resolution_table= save_first_table;
  context->last_name_resolution_table= save_last_table;
859 860 861 862 863 864
  if (unlikely(error))
  {
    DBUG_PRINT("info", ("Field in partition function not part of table"));
    clear_field_flag(table);
    goto end;
  }
unknown's avatar
unknown committed
865
  thd->where= save_where;
866 867 868 869 870 871
  if (unlikely(func_expr->const_item()))
  {
    my_error(ER_CONST_EXPR_IN_PARTITION_FUNC_ERROR, MYF(0));
    clear_field_flag(table);
    goto end;
  }
unknown's avatar
unknown committed
872
  result= set_up_field_array(table, is_sub_part);
873 874 875 876 877 878 879 880
end:
  table->get_fields_in_item_tree= FALSE;
  table->map= 0; //Restore old value
  DBUG_RETURN(result);
}


/*
unknown's avatar
unknown committed
881 882
  Check that the primary key contains all partition fields if defined

883 884 885
  SYNOPSIS
    check_primary_key()
    table                TABLE object for which partition fields are set-up
unknown's avatar
unknown committed
886

887 888 889 890 891
  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
unknown's avatar
unknown committed
892 893 894 895 896 897

  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.
898 899 900 901 902
*/

static bool check_primary_key(TABLE *table)
{
  uint primary_key= table->s->primary_key;
unknown's avatar
unknown committed
903 904
  bool all_fields, some_fields;
  bool result= FALSE;
905 906 907 908 909
  DBUG_ENTER("check_primary_key");

  if (primary_key < MAX_KEY)
  {
    set_indicator_in_key_fields(table->key_info+primary_key);
unknown's avatar
unknown committed
910
    check_fields_in_PF(table->part_info->full_part_field_array,
911 912 913 914 915 916 917 918 919 920 921 922 923
                        &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);
}


/*
unknown's avatar
unknown committed
924 925
  Check that unique keys contains all partition fields

926 927 928
  SYNOPSIS
    check_unique_keys()
    table                TABLE object for which partition fields are set-up
unknown's avatar
unknown committed
929

930 931 932 933 934
  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
unknown's avatar
unknown committed
935 936 937 938 939 940

  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.
941 942 943 944
*/

static bool check_unique_keys(TABLE *table)
{
unknown's avatar
unknown committed
945 946 947 948
  bool all_fields, some_fields;
  bool result= FALSE;
  uint keys= table->s->keys;
  uint i;
949
  DBUG_ENTER("check_unique_keys");
unknown's avatar
unknown committed
950

951 952 953 954 955
  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);
unknown's avatar
unknown committed
956
      check_fields_in_PF(table->part_info->full_part_field_array,
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
                         &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.
unknown's avatar
unknown committed
1014

1015 1016 1017
  SYNOPSIS
    check_range_capable_PF()
    table                TABLE object for which partition fields are set-up
unknown's avatar
unknown committed
1018

1019 1020 1021 1022 1023 1024 1025
  DESCRIPTION
    Support for this is not implemented yet.
*/

void check_range_capable_PF(TABLE *table)
{
  DBUG_ENTER("check_range_capable_PF");
unknown's avatar
unknown committed
1026

1027 1028 1029 1030
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062
/*
  Set up partition bitmap

  SYNOPSIS
    set_up_partition_bitmap()
    thd                  Thread object
    part_info            Reference to partitioning data structure

  RETURN VALUE
    TRUE                 Memory allocation failure
    FALSE                Success

  DESCRIPTION
    Allocate memory for bitmap of the partitioned table
    and initialise it.
*/

static bool set_up_partition_bitmap(THD *thd, partition_info *part_info)
{
  uint32 *bitmap_buf;
  uint bitmap_bits= part_info->no_subparts? 
                     (part_info->no_subparts* part_info->no_parts):
                      part_info->no_parts;
  uint bitmap_bytes= bitmap_buffer_size(bitmap_bits);
  DBUG_ENTER("set_up_partition_bitmap");

  if (!(bitmap_buf= (uint32*)thd->alloc(bitmap_bytes)))
  {
    mem_alloc_error(bitmap_bytes);
    DBUG_RETURN(TRUE);
  }
  bitmap_init(&part_info->used_partitions, bitmap_buf, bitmap_bytes*8, FALSE);
unknown's avatar
unknown committed
1063
  bitmap_set_all(&part_info->used_partitions);
unknown's avatar
unknown committed
1064 1065 1066 1067
  DBUG_RETURN(FALSE);
}


1068 1069
/*
  Set up partition key maps
unknown's avatar
unknown committed
1070

1071 1072 1073 1074
  SYNOPSIS
    set_up_partition_key_maps()
    table                TABLE object for which partition fields are set-up
    part_info            Reference to partitioning data structure
unknown's avatar
unknown committed
1075

1076 1077
  RETURN VALUES
    None
unknown's avatar
unknown committed
1078

1079
  DESCRIPTION
unknown's avatar
unknown committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
    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
1090 1091 1092 1093 1094
*/

static void set_up_partition_key_maps(TABLE *table,
                                      partition_info *part_info)
{
unknown's avatar
unknown committed
1095 1096
  uint keys= table->s->keys;
  uint i;
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112
  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);
1113
    if (part_info->is_sub_partitioned())
1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    {
      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;
}


/*
unknown's avatar
unknown committed
1131 1132
  Set up function pointers for partition function

1133
  SYNOPSIS
unknown's avatar
unknown committed
1134
    set_up_partition_func_pointers()
1135
    part_info            Reference to partitioning data structure
unknown's avatar
unknown committed
1136 1137 1138 1139 1140 1141 1142 1143 1144

  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.
1145 1146 1147 1148
*/

static void set_up_partition_func_pointers(partition_info *part_info)
{
unknown's avatar
unknown committed
1149 1150
  DBUG_ENTER("set_up_partition_func_pointers");

1151
  if (part_info->is_sub_partitioned())
1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182
  {
    if (part_info->part_type == RANGE_PARTITION)
    {
      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_partition_id= get_partition_id_range_sub_linear_key;
          part_info->get_subpartition_id= get_partition_id_linear_key_sub;
        }
        else
        {
          part_info->get_partition_id= get_partition_id_range_sub_key;
          part_info->get_subpartition_id= get_partition_id_key_sub;
        }
      }
      else
      {
        if (part_info->linear_hash_ind)
        {
          part_info->get_partition_id= get_partition_id_range_sub_linear_hash;
          part_info->get_subpartition_id= get_partition_id_linear_hash_sub;
        }
        else
        {
          part_info->get_partition_id= get_partition_id_range_sub_hash;
          part_info->get_subpartition_id= get_partition_id_hash_sub;
        }
      }
    }
unknown's avatar
unknown committed
1183
    else /* LIST Partitioning */
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
    {
      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_partition_id= get_partition_id_list_sub_linear_key;
          part_info->get_subpartition_id= get_partition_id_linear_key_sub;
        }
        else
        {
          part_info->get_partition_id= get_partition_id_list_sub_key;
          part_info->get_subpartition_id= get_partition_id_key_sub;
        }
      }
      else
      {
        if (part_info->linear_hash_ind)
        {
          part_info->get_partition_id= get_partition_id_list_sub_linear_hash;
          part_info->get_subpartition_id= get_partition_id_linear_hash_sub;
        }
        else
        {
          part_info->get_partition_id= get_partition_id_list_sub_hash;
          part_info->get_subpartition_id= get_partition_id_hash_sub;
        }
      }
    }
  }
unknown's avatar
unknown committed
1214
  else /* No subpartitioning */
1215 1216 1217 1218 1219 1220 1221
  {
    part_info->get_part_partition_id= NULL;
    part_info->get_subpartition_id= NULL;
    if (part_info->part_type == RANGE_PARTITION)
      part_info->get_partition_id= get_partition_id_range;
    else if (part_info->part_type == LIST_PARTITION)
      part_info->get_partition_id= get_partition_id_list;
unknown's avatar
unknown committed
1222
    else /* HASH partitioning */
1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239
    {
      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;
      }
    }
  }
unknown's avatar
unknown committed
1240
  DBUG_VOID_RETURN;
1241
}
unknown's avatar
unknown committed
1242 1243


1244 1245 1246
/*
  For linear hashing we need a mask which is on the form 2**n - 1 where
  2**n >= no_parts. Thus if no_parts is 6 then mask is 2**3 - 1 = 8 - 1 = 7.
unknown's avatar
unknown committed
1247

1248 1249 1250 1251
  SYNOPSIS
    set_linear_hash_mask()
    part_info            Reference to partitioning data structure
    no_parts             Number of parts in linear hash partitioning
unknown's avatar
unknown committed
1252 1253 1254

  RETURN VALUE
    NONE
1255 1256 1257 1258 1259
*/

static void set_linear_hash_mask(partition_info *part_info, uint no_parts)
{
  uint mask;
unknown's avatar
unknown committed
1260

1261 1262 1263 1264 1265 1266 1267 1268 1269
  for (mask= 1; mask < no_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.
unknown's avatar
unknown committed
1270

1271 1272 1273 1274 1275
  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
    no_parts            Number of partitions in HASH partitioned part
unknown's avatar
unknown committed
1276

1277 1278
  RETURN VALUE
    part_id             The calculated partition identity (starting at 0)
unknown's avatar
unknown committed
1279

1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290
  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 no_parts)
{
  uint32 part_id= (uint32)(hash_value & mask);
unknown's avatar
unknown committed
1291

1292 1293 1294
  if (part_id >= no_parts)
  {
    uint new_mask= ((mask + 1) >> 1) - 1;
1295
    part_id= (uint32)(hash_value & new_mask);
1296 1297 1298 1299 1300
  }
  return part_id;
}

/*
unknown's avatar
unknown committed
1301 1302
  fix partition functions

1303 1304 1305 1306 1307
  SYNOPSIS
    fix_partition_func()
    thd                  The thread object
    name                 The name of the partitioned table
    table                TABLE object for which partition fields are set-up
unknown's avatar
unknown committed
1308 1309
    create_table_ind     Indicator of whether openfrm was called as part of
                         CREATE or ALTER TABLE
unknown's avatar
unknown committed
1310

1311
  RETURN VALUE
unknown's avatar
unknown committed
1312 1313
    TRUE                 Error
    FALSE                Success
unknown's avatar
unknown committed
1314

1315 1316 1317 1318
  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.
unknown's avatar
unknown committed
1319 1320 1321 1322 1323 1324 1325

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.
1326 1327
*/

unknown's avatar
unknown committed
1328 1329
bool fix_partition_func(THD *thd, const char* name, TABLE *table,
                        bool is_create_table_ind)
1330 1331 1332 1333 1334 1335 1336
{
  bool result= TRUE;
  uint dir_length, home_dir_length;
  TABLE_LIST tables;
  TABLE_SHARE *share= table->s;
  char db_name_string[FN_REFLEN];
  char* db_name;
unknown's avatar
unknown committed
1337
  partition_info *part_info= table->part_info;
1338
  enum_mark_columns save_mark_used_columns= thd->mark_used_columns;
1339
  Item *thd_free_list= thd->free_list;
1340 1341
  DBUG_ENTER("fix_partition_func");

unknown's avatar
unknown committed
1342 1343 1344 1345
  if (part_info->fixed)
  {
    DBUG_RETURN(FALSE);
  }
1346 1347
  thd->mark_used_columns= MARK_COLUMNS_NONE;
  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
1348
  /*
unknown's avatar
unknown committed
1349 1350 1351
    Set-up the TABLE_LIST object to be a list with a single table
    Set the object to zero to create NULL pointers and set alias
    and real name to table name and get database name from file name.
1352 1353 1354
  */

  bzero((void*)&tables, sizeof(TABLE_LIST));
unknown's avatar
unknown committed
1355
  tables.alias= tables.table_name= (char*) share->table_name.str;
1356
  tables.table= table;
unknown's avatar
unknown committed
1357 1358
  tables.next_local= 0;
  tables.next_name_resolution_table= 0;
1359 1360 1361 1362 1363 1364 1365
  strmov(db_name_string, name);
  dir_length= dirname_length(db_name_string);
  db_name_string[dir_length - 1]= 0;
  home_dir_length= dirname_length(db_name_string);
  db_name= &db_name_string[home_dir_length];
  tables.db= db_name;

1366
  if (!is_create_table_ind ||
1367
       thd->lex->sql_command != SQLCOM_CREATE_TABLE)
unknown's avatar
unknown committed
1368
  {
1369
    if (partition_default_handling(table, part_info,
1370
                                   is_create_table_ind,
1371
                                   table->s->normalized_path.str))
unknown's avatar
unknown committed
1372 1373 1374 1375
    {
      DBUG_RETURN(TRUE);
    }
  }
1376
  thd->free_list= part_info->item_free_list;
1377
  if (part_info->is_sub_partitioned())
1378 1379 1380
  {
    DBUG_ASSERT(part_info->subpart_type == HASH_PARTITION);
    /*
unknown's avatar
unknown committed
1381 1382
      Subpartition is defined. We need to verify that subpartitioning
      function is correct.
1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394
    */
    if (part_info->linear_hash_ind)
      set_linear_hash_mask(part_info, part_info->no_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, &tables,
unknown's avatar
unknown committed
1395 1396
                                        part_info->subpart_expr, part_info,
                                        TRUE)))
1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
        goto end;
      if (unlikely(part_info->subpart_expr->result_type() != INT_RESULT))
      {
        my_error(ER_PARTITION_FUNC_NOT_ALLOWED_ERROR, MYF(0),
                 "SUBPARTITION");
        goto end;
      }
    }
  }
  DBUG_ASSERT(part_info->part_type != NOT_A_PARTITION);
  /*
unknown's avatar
unknown committed
1408 1409
    Partition is defined. We need to verify that partitioning
    function is correct.
1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435
  */
  if (part_info->part_type == HASH_PARTITION)
  {
    if (part_info->linear_hash_ind)
      set_linear_hash_mask(part_info, part_info->no_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, &tables, part_info->part_expr,
                                        part_info, FALSE)))
        goto end;
      if (unlikely(part_info->part_expr->result_type() != INT_RESULT))
      {
        my_error(ER_PARTITION_FUNC_NOT_ALLOWED_ERROR, MYF(0), part_str);
        goto end;
      }
      part_info->part_result_type= INT_RESULT;
    }
  }
  else
  {
1436
    const char *error_str;
1437 1438
    if (part_info->part_type == RANGE_PARTITION)
    {
1439
      error_str= partition_keywords[PKW_RANGE].str; 
unknown's avatar
unknown committed
1440
      if (unlikely(part_info->check_range_constants()))
1441 1442 1443 1444
        goto end;
    }
    else if (part_info->part_type == LIST_PARTITION)
    {
1445
      error_str= partition_keywords[PKW_LIST].str; 
unknown's avatar
unknown committed
1446
      if (unlikely(part_info->check_list_constants()))
1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
        goto end;
    }
    else
    {
      DBUG_ASSERT(0);
      my_error(ER_INCONSISTENT_PARTITION_INFO_ERROR, MYF(0));
      goto end;
    }
    if (unlikely(part_info->no_parts < 1))
    {
      my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), error_str);
      goto end;
    }
    if (unlikely(fix_fields_part_func(thd, &tables, part_info->part_expr,
                                      part_info, FALSE)))
      goto end;
    if (unlikely(part_info->part_expr->result_type() != INT_RESULT))
    {
      my_error(ER_PARTITION_FUNC_NOT_ALLOWED_ERROR, MYF(0), part_str);
      goto end;
    }
  }
  if (unlikely(create_full_part_field_array(table, part_info)))
    goto end;
  if (unlikely(check_primary_key(table)))
    goto end;
unknown's avatar
unknown committed
1473 1474
  if (unlikely((!(table->s->db_type->partition_flags &&
      (table->s->db_type->partition_flags() & HA_CAN_PARTITION_UNIQUE))) &&
1475 1476
               check_unique_keys(table)))
    goto end;
unknown's avatar
unknown committed
1477 1478
  if (unlikely(set_up_partition_bitmap(thd, part_info)))
    goto end;
1479 1480 1481
  check_range_capable_PF(table);
  set_up_partition_key_maps(table, part_info);
  set_up_partition_func_pointers(part_info);
unknown's avatar
unknown committed
1482
  part_info->fixed= TRUE;
unknown's avatar
unknown committed
1483
  set_up_range_analysis_info(part_info);
1484 1485
  result= FALSE;
end:
1486
  thd->free_list= thd_free_list;
1487 1488
  thd->mark_used_columns= save_mark_used_columns;
  DBUG_PRINT("info", ("thd->mark_used_columns: %d", thd->mark_used_columns));
1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502
  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)
{
1503
  uint len_written= my_write(fptr, (const byte*)buf, len, MYF(0));
unknown's avatar
unknown committed
1504

1505 1506 1507 1508 1509 1510
  if (likely(len == len_written))
    return 0;
  else
    return 1;
}

1511 1512 1513 1514 1515
static int add_string_object(File fptr, String *string)
{
  return add_write(fptr, string->ptr(), string->length());
}

1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
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);
unknown's avatar
unknown committed
1554

1555 1556 1557 1558 1559 1560
  err+= add_space(fptr);
  return err + add_begin_parenthesis(fptr);
}

static int add_hash(File fptr)
{
1561
  return add_part_key_word(fptr, partition_keywords[PKW_HASH].str);
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572
}

static int add_partition(File fptr)
{
  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);
unknown's avatar
unknown committed
1573

1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585
  return err + add_partition(fptr);
}

static int add_partition_by(File fptr)
{
  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);
unknown's avatar
unknown committed
1586

1587 1588 1589 1590 1591 1592 1593
  return err + add_partition_by(fptr);
}

static int add_key_partition(File fptr, List<char> field_list)
{
  uint i, no_fields;
  int err;
unknown's avatar
unknown committed
1594

1595
  List_iterator<char> part_it(field_list);
1596
  err= add_part_key_word(fptr, partition_keywords[PKW_KEY].str);
1597 1598
  no_fields= field_list.elements;
  i= 0;
unknown's avatar
unknown committed
1599
  while (i < no_fields)
1600 1601
  {
    const char *field_str= part_it++;
1602 1603 1604 1605 1606 1607 1608 1609
    String field_string("", 0, system_charset_info);
    THD *thd= current_thd;
    ulonglong save_options= thd->options;
    thd->options= 0;
    append_identifier(thd, &field_string, field_str,
                      strlen(field_str));
    thd->options= save_options;
    err+= add_string_object(fptr, &field_string);
1610 1611
    if (i != (no_fields-1))
      err+= add_comma(fptr);
unknown's avatar
unknown committed
1612 1613
    i++;
  }
1614 1615 1616
  return err;
}

1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631
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->options;

  thd->options= 0;
  append_identifier(thd, &name_string, name,
                    strlen(name));
  thd->options= save_options;
  err= add_string_object(fptr, &name_string);
  return err;
}

1632 1633 1634 1635 1636 1637 1638
static int add_int(File fptr, longlong number)
{
  llstr(number, buff);
  return add_string(fptr, buff);
}

static int add_keyword_string(File fptr, const char *keyword,
1639
                              bool should_use_quotes, 
1640 1641 1642
                              const char *keystr)
{
  int err= add_string(fptr, keyword);
unknown's avatar
unknown committed
1643

1644 1645 1646
  err+= add_space(fptr);
  err+= add_equal(fptr);
  err+= add_space(fptr);
1647 1648
  if (should_use_quotes)
    err+= add_string(fptr, "'");
1649
  err+= add_string(fptr, keystr);
1650 1651
  if (should_use_quotes)
    err+= add_string(fptr, "'");
1652 1653 1654 1655 1656 1657
  return err + add_space(fptr);
}

static int add_keyword_int(File fptr, const char *keyword, longlong num)
{
  int err= add_string(fptr, keyword);
unknown's avatar
unknown committed
1658

1659 1660 1661 1662 1663 1664 1665
  err+= add_space(fptr);
  err+= add_equal(fptr);
  err+= add_space(fptr);
  err+= add_int(fptr, num);
  return err + add_space(fptr);
}

unknown's avatar
unknown committed
1666
static int add_engine(File fptr, handlerton *engine_type)
1667
{
unknown's avatar
unknown committed
1668 1669
  const char *engine_str= hton2plugin[engine_type->slot]->name.str;
  DBUG_PRINT("info", ("ENGINE: %s", engine_str));
1670 1671 1672 1673 1674 1675 1676
  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;
unknown's avatar
unknown committed
1677

1678
  err+= add_space(fptr);
1679
  if (p_elem->tablespace_name)
unknown's avatar
unknown committed
1680
    err+= add_keyword_string(fptr,"TABLESPACE", FALSE,
1681
                             p_elem->tablespace_name);
1682 1683 1684 1685 1686 1687 1688
  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 (p_elem->data_file_name)
1689 1690
    err+= add_keyword_string(fptr, "DATA DIRECTORY", TRUE, 
                             p_elem->data_file_name);
1691
  if (p_elem->index_file_name)
1692 1693
    err+= add_keyword_string(fptr, "INDEX DIRECTORY", TRUE, 
                             p_elem->index_file_name);
1694
  if (p_elem->part_comment)
1695
    err+= add_keyword_string(fptr, "COMMENT", TRUE, p_elem->part_comment);
1696 1697 1698 1699 1700 1701 1702
  return err + add_engine(fptr,p_elem->engine_type);
}

static int add_partition_values(File fptr, partition_info *part_info,
                         partition_element *p_elem)
{
  int err= 0;
unknown's avatar
unknown committed
1703

1704 1705
  if (part_info->part_type == RANGE_PARTITION)
  {
1706
    err+= add_string(fptr, " VALUES LESS THAN ");
unknown's avatar
unknown committed
1707
    if (p_elem->range_value != LONGLONG_MAX)
1708 1709
    {
      err+= add_begin_parenthesis(fptr);
unknown's avatar
unknown committed
1710
      err+= add_int(fptr, p_elem->range_value);
1711 1712 1713
      err+= add_end_parenthesis(fptr);
    }
    else
1714
      err+= add_string(fptr, partition_keywords[PKW_MAXVALUE].str);
1715 1716 1717 1718
  }
  else if (part_info->part_type == LIST_PARTITION)
  {
    uint i;
unknown's avatar
unknown committed
1719
    List_iterator<longlong> list_val_it(p_elem->list_val_list);
1720
    err+= add_string(fptr, " VALUES IN ");
unknown's avatar
unknown committed
1721
    uint no_items= p_elem->list_val_list.elements;
1722
    err+= add_begin_parenthesis(fptr);
1723 1724 1725 1726 1727 1728 1729 1730 1731 1732
    if (p_elem->has_null_value)
    {
      err+= add_string(fptr, "NULL");
      if (no_items == 0)
      {
        err+= add_end_parenthesis(fptr);
        goto end;
      }
      err+= add_comma(fptr);
    }
1733 1734 1735
    i= 0;
    do
    {
unknown's avatar
unknown committed
1736 1737
      longlong *list_value= list_val_it++;
      err+= add_int(fptr, *list_value);
1738 1739 1740 1741 1742
      if (i != (no_items-1))
        err+= add_comma(fptr);
    } while (++i < no_items);
    err+= add_end_parenthesis(fptr);
  }
1743
end:
1744
  return err;
1745 1746 1747 1748 1749 1750
}

/*
  Generate the partition syntax from the partition data structure.
  Useful for support of generating defaults, SHOW CREATE TABLES
  and easy partition management.
unknown's avatar
unknown committed
1751

1752 1753 1754 1755 1756 1757
  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
1758
    show_partition_options     Should we display partition options
unknown's avatar
unknown committed
1759

1760 1761 1762
  RETURN VALUES
    NULL error
    buf, buf_length            Buffer and its length
unknown's avatar
unknown committed
1763

1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
  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,
1786
                                bool use_sql_alloc,
1787
                                bool show_partition_options)
1788
{
unknown's avatar
unknown committed
1789
  uint i,j, tot_no_parts, no_subparts, no_parts;
1790
  partition_element *part_elem;
unknown's avatar
unknown committed
1791
  partition_element *save_part_elem= NULL;
1792 1793 1794
  ulonglong buffer_length;
  char path[FN_REFLEN];
  int err= 0;
unknown's avatar
unknown committed
1795
  List_iterator<partition_element> part_it(part_info->partitions);
1796 1797
  File fptr;
  char *buf= NULL; //Return buffer
unknown's avatar
unknown committed
1798 1799
  DBUG_ENTER("generate_partition_syntax");

1800 1801 1802
  if (unlikely(((fptr= create_temp_file(path,mysql_tmpdir,"psy", 
                                        O_RDWR | O_BINARY | O_TRUNC |  
                                        O_TEMPORARY, MYF(MY_WME)))) < 0))
1803
    DBUG_RETURN(NULL);
unknown's avatar
unknown committed
1804 1805
#ifndef __WIN__
  unlink(path);
1806 1807 1808 1809 1810 1811
#endif
  err+= add_space(fptr);
  err+= add_partition_by(fptr);
  switch (part_info->part_type)
  {
    case RANGE_PARTITION:
1812
      err+= add_part_key_word(fptr, partition_keywords[PKW_RANGE].str);
1813 1814
      break;
    case LIST_PARTITION:
1815
      err+= add_part_key_word(fptr, partition_keywords[PKW_LIST].str);
1816 1817 1818
      break;
    case HASH_PARTITION:
      if (part_info->linear_hash_ind)
1819
        err+= add_string(fptr, partition_keywords[PKW_LINEAR].str);
1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835
      if (part_info->list_of_part_fields)
        err+= add_key_partition(fptr, part_info->part_field_list);
      else
        err+= add_hash(fptr);
      break;
    default:
      DBUG_ASSERT(0);
      /* We really shouldn't get here, no use in continuing from here */
      current_thd->fatal_error();
      DBUG_RETURN(NULL);
  }
  if (part_info->part_expr)
    err+= add_string_len(fptr, part_info->part_func_string,
                         part_info->part_func_len);
  err+= add_end_parenthesis(fptr);
  err+= add_space(fptr);
unknown's avatar
unknown committed
1836 1837 1838 1839 1840 1841 1842
  if ((!part_info->use_default_no_partitions) &&
       part_info->use_default_partitions)
  {
    err+= add_string(fptr, "PARTITIONS ");
    err+= add_int(fptr, part_info->no_parts);
    err+= add_space(fptr);
  }
1843
  if (part_info->is_sub_partitioned())
1844 1845 1846
  {
    err+= add_subpartition_by(fptr);
    /* Must be hash partitioning for subpartitioning */
1847 1848
    if (part_info->linear_hash_ind)
      err+= add_string(fptr, partition_keywords[PKW_LINEAR].str);
1849 1850 1851 1852 1853 1854 1855 1856 1857
    if (part_info->list_of_subpart_fields)
      err+= add_key_partition(fptr, part_info->subpart_field_list);
    else
      err+= add_hash(fptr);
    if (part_info->subpart_expr)
      err+= add_string_len(fptr, part_info->subpart_func_string,
                           part_info->subpart_func_len);
    err+= add_end_parenthesis(fptr);
    err+= add_space(fptr);
unknown's avatar
unknown committed
1858 1859 1860 1861 1862 1863 1864 1865
    if ((!part_info->use_default_no_subpartitions) && 
          part_info->use_default_subpartitions)
    {
      err+= add_string(fptr, "SUBPARTITIONS ");
      err+= add_int(fptr, part_info->no_subparts);
      err+= add_space(fptr);
    }
  }
1866
  tot_no_parts= part_info->partitions.elements;
1867
  no_subparts= part_info->no_subparts;
unknown's avatar
unknown committed
1868

1869
  if (!part_info->use_default_partitions)
1870
  {
1871
    bool first= TRUE;
unknown's avatar
unknown committed
1872 1873 1874
    err+= add_begin_parenthesis(fptr);
    i= 0;
    do
1875
    {
1876 1877 1878
      part_elem= part_it++;
      if (part_elem->part_state != PART_TO_BE_DROPPED &&
          part_elem->part_state != PART_REORGED_DROPPED)
unknown's avatar
unknown committed
1879
      {
1880
        if (!first)
unknown's avatar
unknown committed
1881
        {
1882 1883
          err+= add_comma(fptr);
          err+= add_space(fptr);
unknown's avatar
unknown committed
1884
        }
1885
        first= FALSE;
unknown's avatar
unknown committed
1886
        err+= add_partition(fptr);
1887
        err+= add_name_string(fptr, part_elem->partition_name);
unknown's avatar
unknown committed
1888
        err+= add_partition_values(fptr, part_info, part_elem);
1889 1890
        if (!part_info->is_sub_partitioned() ||
            part_info->use_default_subpartitions)
1891
        {
1892 1893
          if (show_partition_options)
            err+= add_partition_options(fptr, part_elem);
1894 1895
        }
        else
unknown's avatar
unknown committed
1896 1897 1898 1899 1900 1901 1902 1903 1904
        {
          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);
1905
            err+= add_name_string(fptr, part_elem->partition_name);
1906 1907
            if (show_partition_options)
              err+= add_partition_options(fptr, part_elem);
unknown's avatar
unknown committed
1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
            if (j != (no_subparts-1))
            {
              err+= add_comma(fptr);
              err+= add_space(fptr);
            }
            else
              err+= add_end_parenthesis(fptr);
          } while (++j < no_subparts);
        }
      }
      if (i == (tot_no_parts-1))
        err+= add_end_parenthesis(fptr);
    } while (++i < tot_no_parts);
1921
  }
1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936
  if (err)
    goto close_file;
  buffer_length= my_seek(fptr, 0L,MY_SEEK_END,MYF(0));
  if (unlikely(buffer_length == MY_FILEPOS_ERROR))
    goto close_file;
  if (unlikely(my_seek(fptr, 0L, MY_SEEK_SET, MYF(0)) == MY_FILEPOS_ERROR))
    goto close_file;
  *buf_length= (uint)buffer_length;
  if (use_sql_alloc)
    buf= sql_alloc(*buf_length+1);
  else
    buf= my_malloc(*buf_length+1, MYF(MY_WME));
  if (!buf)
    goto close_file;

1937
  if (unlikely(my_read(fptr, (byte*)buf, *buf_length, MYF(MY_FNABP))))
1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955
  {
    if (!use_sql_alloc)
      my_free(buf, MYF(0));
    else
      buf= NULL;
  }
  else
    buf[*buf_length]= 0;

close_file:
  my_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.
unknown's avatar
unknown committed
1956

1957 1958 1959 1960
  SYNOPSIS
    partition_key_modified
    table                TABLE object for which partition fields are set-up
    fields               A list of the to be modifed
unknown's avatar
unknown committed
1961

1962 1963 1964 1965 1966 1967 1968 1969
  RETURN VALUES
    TRUE                 Need special handling of UPDATE
    FALSE                Normal UPDATE handling is ok
*/

bool partition_key_modified(TABLE *table, List<Item> &fields)
{
  List_iterator_fast<Item> f(fields);
unknown's avatar
unknown committed
1970
  partition_info *part_info= table->part_info;
1971 1972
  Item_field *item_field;
  DBUG_ENTER("partition_key_modified");
unknown's avatar
unknown committed
1973

1974 1975
  if (!part_info)
    DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
1976 1977
  if (table->s->db_type->partition_flags &&
      (table->s->db_type->partition_flags() & HA_CAN_UPDATE_PARTITION_KEY))
1978 1979 1980 1981 1982 1983 1984 1985 1986
    DBUG_RETURN(FALSE);
  f.rewind();
  while ((item_field=(Item_field*) f++))
    if (item_field->field->flags & FIELD_IN_PART_FUNC_FLAG)
      DBUG_RETURN(TRUE);
  DBUG_RETURN(FALSE);
}


1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997
/*
  A function to handle correct handling of NULL values in partition
  functions.
  SYNOPSIS
    part_val_int()
    item_expr                 The item expression to evaluate
  RETURN VALUES
    The value of the partition function, LONGLONG_MIN if any null value
    in function
*/

1998
static inline longlong part_val_int(Item *item_expr)
1999 2000 2001 2002 2003 2004 2005 2006
{
  longlong value= item_expr->val_int();
  if (item_expr->null_value)
    value= LONGLONG_MIN;
  return value;
}


2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026
/*
  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_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.
*/

/*
  Calculate hash value for KEY partitioning using an array of fields.
unknown's avatar
unknown committed
2027

2028 2029 2030
  SYNOPSIS
    calculate_key_value()
    field_array             An array of the fields in KEY partitioning
unknown's avatar
unknown committed
2031

2032 2033
  RETURN VALUE
    hash_value calculated
unknown's avatar
unknown committed
2034

2035 2036 2037 2038 2039 2040 2041 2042 2043
  DESCRIPTION
    Uses the hash function on the character set of the field. Integer and
    floating point fields use the binary character set by default.
*/

static uint32 calculate_key_value(Field **field_array)
{
  uint32 hashnr= 0;
  ulong nr2= 4;
unknown's avatar
unknown committed
2044

2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
  do
  {
    Field *field= *field_array;
    if (field->is_null())
    {
      hashnr^= (hashnr << 1) | 1;
    }
    else
    {
      uint len= field->pack_length();
      ulong nr1= 1;
      CHARSET_INFO *cs= field->charset();
      cs->coll->hash_sort(cs, (uchar*)field->ptr, len, &nr1, &nr2);
      hashnr^= (uint32)nr1;
    }
  } while (*(++field_array));
  return hashnr;
}


/*
  A simple support function to calculate part_id given local part and
  sub part.
unknown's avatar
unknown committed
2068

2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
  SYNOPSIS
    get_part_id_for_sub()
    loc_part_id             Local partition id
    sub_part_id             Subpartition id
    no_subparts             Number of subparts
*/

inline
static uint32 get_part_id_for_sub(uint32 loc_part_id, uint32 sub_part_id,
                                  uint no_subparts)
{
  return (uint32)((loc_part_id * no_subparts) + sub_part_id);
}


/*
  Calculate part_id for (SUB)PARTITION BY HASH
unknown's avatar
unknown committed
2086

2087 2088 2089 2090
  SYNOPSIS
    get_part_id_hash()
    no_parts                 Number of hash partitions
    part_expr                Item tree of hash function
2091
    out:func_value      Value of hash function
unknown's avatar
unknown committed
2092

2093 2094 2095 2096 2097 2098
  RETURN VALUE
    Calculated partition id
*/

inline
static uint32 get_part_id_hash(uint no_parts,
2099 2100
                               Item *part_expr,
                               longlong *func_value)
2101 2102
{
  DBUG_ENTER("get_part_id_hash");
2103
  *func_value= part_val_int(part_expr);
2104
  longlong int_hash_id= *func_value % no_parts;
2105
  DBUG_RETURN(int_hash_id < 0 ? -int_hash_id : int_hash_id);
2106 2107 2108 2109 2110
}


/*
  Calculate part_id for (SUB)PARTITION BY LINEAR HASH
unknown's avatar
unknown committed
2111

2112 2113 2114 2115 2116 2117
  SYNOPSIS
    get_part_id_linear_hash()
    part_info           A reference to the partition_info struct where all the
                        desired information is given
    no_parts            Number of hash partitions
    part_expr           Item tree of hash function
2118
    out:func_value      Value of hash function
unknown's avatar
unknown committed
2119

2120 2121 2122 2123 2124 2125 2126
  RETURN VALUE
    Calculated partition id
*/

inline
static uint32 get_part_id_linear_hash(partition_info *part_info,
                                      uint no_parts,
2127 2128
                                      Item *part_expr,
                                      longlong *func_value)
2129 2130
{
  DBUG_ENTER("get_part_id_linear_hash");
unknown's avatar
unknown committed
2131

2132
  *func_value= part_val_int(part_expr);
2133
  DBUG_RETURN(get_part_id_from_linear_hash(*func_value,
2134 2135 2136 2137 2138 2139 2140
                                           part_info->linear_hash_mask,
                                           no_parts));
}


/*
  Calculate part_id for (SUB)PARTITION BY KEY
unknown's avatar
unknown committed
2141

2142 2143 2144 2145
  SYNOPSIS
    get_part_id_key()
    field_array         Array of fields for PARTTION KEY
    no_parts            Number of KEY partitions
unknown's avatar
unknown committed
2146

2147 2148 2149 2150 2151 2152
  RETURN VALUE
    Calculated partition id
*/

inline
static uint32 get_part_id_key(Field **field_array,
2153 2154
                              uint no_parts,
                              longlong *func_value)
2155 2156
{
  DBUG_ENTER("get_part_id_key");
2157 2158
  *func_value= calculate_key_value(field_array);
  DBUG_RETURN(*func_value % no_parts);
2159 2160 2161 2162 2163
}


/*
  Calculate part_id for (SUB)PARTITION BY LINEAR KEY
unknown's avatar
unknown committed
2164

2165 2166 2167 2168 2169 2170
  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
    no_parts            Number of KEY partitions
unknown's avatar
unknown committed
2171

2172 2173 2174 2175 2176 2177 2178
  RETURN VALUE
    Calculated partition id
*/

inline
static uint32 get_part_id_linear_key(partition_info *part_info,
                                     Field **field_array,
2179 2180
                                     uint no_parts,
                                     longlong *func_value)
2181 2182
{
  DBUG_ENTER("get_partition_id_linear_key");
unknown's avatar
unknown committed
2183

2184 2185
  *func_value= calculate_key_value(field_array);
  DBUG_RETURN(get_part_id_from_linear_hash(*func_value,
2186 2187 2188 2189 2190 2191 2192 2193
                                           part_info->linear_hash_mask,
                                           no_parts));
}

/*
  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.
unknown's avatar
unknown committed
2194

2195 2196 2197 2198
  SYNOPSIS
    get_partition_id()
    part_info           A reference to the partition_info struct where all the
                        desired information is given
unknown's avatar
unknown committed
2199 2200
    out:part_id         The partition id is returned through this pointer

2201
  RETURN VALUE
2202 2203 2204 2205 2206
    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.
unknown's avatar
unknown committed
2207

2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236
  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 14 different variants of this function which are called
    through a function pointer.

    get_partition_id_list
    get_partition_id_range
    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_range_sub_hash
    get_partition_id_range_sub_key
    get_partition_id_range_sub_linear_hash
    get_partition_id_range_sub_linear_key
    get_partition_id_list_sub_hash
    get_partition_id_list_sub_key
    get_partition_id_list_sub_linear_hash
    get_partition_id_list_sub_linear_key
*/

/*
  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.
unknown's avatar
unknown committed
2237

2238 2239 2240 2241
  SYNOPSIS
    get_part_partition_id()
    part_info           A reference to the partition_info struct where all the
                        desired information is given
unknown's avatar
unknown committed
2242 2243
    out:part_id         The partition id is returned through this pointer

2244
  RETURN VALUE
2245 2246 2247 2248 2249
    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.
unknown's avatar
unknown committed
2250

2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264
  DESCRIPTION
    
    It is actually 6 different variants of this function which are called
    through a function pointer.

    get_partition_id_list
    get_partition_id_range
    get_partition_id_hash_nosub
    get_partition_id_key_nosub
    get_partition_id_linear_hash_nosub
    get_partition_id_linear_key_nosub
*/


unknown's avatar
unknown committed
2265
int get_partition_id_list(partition_info *part_info,
2266 2267
                           uint32 *part_id,
                           longlong *func_value)
2268 2269
{
  LIST_PART_ENTRY *list_array= part_info->list_array;
unknown's avatar
unknown committed
2270
  int list_index;
2271
  longlong list_value;
unknown's avatar
unknown committed
2272 2273
  int min_list_index= 0;
  int max_list_index= part_info->no_list_values - 1;
2274
  longlong part_func_value= part_val_int(part_info->part_expr);
unknown's avatar
unknown committed
2275 2276
  DBUG_ENTER("get_partition_id_list");

2277 2278 2279 2280 2281 2282 2283 2284 2285
  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;
  }
2286
  *func_value= part_func_value;
2287 2288 2289 2290 2291 2292 2293
  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)
unknown's avatar
unknown committed
2294 2295 2296
    {
      if (!list_index)
        goto notfound;
2297
      max_list_index= list_index - 1;
unknown's avatar
unknown committed
2298 2299 2300
    }
    else
    {
2301
      *part_id= (uint32)list_array[list_index].partition_id;
unknown's avatar
unknown committed
2302
      DBUG_RETURN(0);
2303 2304
    }
  }
unknown's avatar
unknown committed
2305
notfound:
2306
  *part_id= 0;
unknown's avatar
unknown committed
2307
  DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
2308 2309 2310
}


unknown's avatar
unknown committed
2311
/*
2312 2313
  Find the sub-array part_info->list_array that corresponds to given interval

unknown's avatar
unknown committed
2314 2315 2316 2317 2318 2319 2320 2321
  SYNOPSIS 
    get_list_array_idx_for_endpoint()
      part_info         Partitioning info (partitioning type must be LIST)
      left_endpoint     TRUE  - the interval is [a; +inf) or (a; +inf)
                        FALSE - the interval is (-inf; a] or (-inf; a)
      include_endpoint  TRUE iff the interval includes the endpoint

  DESCRIPTION
2322
    This function finds the sub-array of part_info->list_array where values of
unknown's avatar
unknown committed
2323 2324 2325
    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 
2326
       sought sub-array starts at some index idx and continues till array end.
unknown's avatar
unknown committed
2327 2328 2329 2330
       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
2331
       sought sub-array starts at array start and continues till some last 
unknown's avatar
unknown committed
2332 2333 2334 2335 2336 2337 2338
       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->no_list_values is
       returned.

  NOTE
2339
    The caller will call this function and then will run along the sub-array of
unknown's avatar
unknown committed
2340 2341 2342 2343 2344 2345
    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
2346
    The edge of corresponding sub-array of part_info->list_array
unknown's avatar
unknown committed
2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357
*/

uint32 get_list_array_idx_for_endpoint(partition_info *part_info,
                                       bool left_endpoint,
                                       bool include_endpoint)
{
  DBUG_ENTER("get_list_array_idx_for_endpoint");
  LIST_PART_ENTRY *list_array= part_info->list_array;
  uint list_index;
  longlong list_value;
  uint min_list_index= 0, max_list_index= part_info->no_list_values - 1;
2358
  /* Get the partitioning function value for the endpoint */
2359
  longlong part_func_value= part_val_int(part_info->part_expr);
unknown's avatar
unknown committed
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382
  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 
    {
      DBUG_RETURN(list_index + test(left_endpoint ^ include_endpoint));
    }
  }
notfound:
  if (list_value < part_func_value)
    list_index++;
  DBUG_RETURN(list_index);
}

2383

unknown's avatar
unknown committed
2384
int get_partition_id_range(partition_info *part_info,
2385 2386
                            uint32 *part_id,
                            longlong *func_value)
2387 2388 2389
{
  longlong *range_array= part_info->range_int_array;
  uint max_partition= part_info->no_parts - 1;
unknown's avatar
unknown committed
2390 2391 2392
  uint min_part_id= 0;
  uint max_part_id= max_partition;
  uint loc_part_id;
2393
  longlong part_func_value= part_val_int(part_info->part_expr);
unknown's avatar
unknown committed
2394 2395
  DBUG_ENTER("get_partition_id_int_range");

2396 2397 2398 2399 2400
  if (part_info->part_expr->null_value)
  {
    *part_id= 0;
    DBUG_RETURN(0);
  }
2401 2402 2403
  while (max_part_id > min_part_id)
  {
    loc_part_id= (max_part_id + min_part_id + 1) >> 1;
unknown's avatar
unknown committed
2404
    if (range_array[loc_part_id] <= part_func_value)
2405 2406 2407 2408 2409 2410 2411 2412 2413
      min_part_id= loc_part_id + 1;
    else
      max_part_id= loc_part_id - 1;
  }
  loc_part_id= max_part_id;
  if (part_func_value >= range_array[loc_part_id])
    if (loc_part_id != max_partition)
      loc_part_id++;
  *part_id= (uint32)loc_part_id;
2414
  *func_value= part_func_value;
2415 2416 2417 2418 2419 2420
  if (loc_part_id == max_partition &&
      range_array[loc_part_id] != LONGLONG_MAX &&
      part_func_value >= range_array[loc_part_id])
    DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);

  DBUG_PRINT("exit",("partition: %d", *part_id));
unknown's avatar
unknown committed
2421
  DBUG_RETURN(0);
2422 2423
}

unknown's avatar
unknown committed
2424 2425

/*
2426 2427
  Find the sub-array of part_info->range_int_array that covers given interval
 
unknown's avatar
unknown committed
2428 2429 2430 2431 2432 2433 2434 2435 2436
  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
2437
    This function finds the sub-array of part_info->range_int_array where the
unknown's avatar
unknown committed
2438
    elements have non-empty intersections with the given interval.
2439
 
unknown's avatar
unknown committed
2440 2441 2442 2443 2444 2445 2446
    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
2447
       sought sub-array starts at some index idx and continues till array end.
unknown's avatar
unknown committed
2448 2449 2450 2451 2452
       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
2453
       sought sub-array starts at array start and continues till some last
unknown's avatar
unknown committed
2454 2455 2456 2457 2458 2459 2460 2461 2462
       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->no_parts is
       returned.
       
  RETURN
2463
    The edge of corresponding part_info->range_int_array sub-array.
unknown's avatar
unknown committed
2464 2465 2466 2467 2468 2469 2470 2471 2472 2473
*/

uint32 get_partition_id_range_for_endpoint(partition_info *part_info,
                                           bool left_endpoint,
                                           bool include_endpoint)
{
  DBUG_ENTER("get_partition_id_range_for_endpoint");
  longlong *range_array= part_info->range_int_array;
  uint max_partition= part_info->no_parts - 1;
  uint min_part_id= 0, max_part_id= max_partition, loc_part_id;
2474
  /* Get the partitioning function value for the endpoint */
2475
  longlong part_func_value= part_val_int(part_info->part_expr);
2476

unknown's avatar
unknown committed
2477 2478 2479
  while (max_part_id > min_part_id)
  {
    loc_part_id= (max_part_id + min_part_id + 1) >> 1;
unknown's avatar
unknown committed
2480
    if (range_array[loc_part_id] <= part_func_value)
unknown's avatar
unknown committed
2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507
      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 && 
      part_func_value >= range_array[loc_part_id+1])
  {
     loc_part_id++;
  }
  if (left_endpoint)
  {
    if (part_func_value >= range_array[loc_part_id])
      loc_part_id++;
  }
  else 
  {
    if (part_func_value == range_array[loc_part_id])
      loc_part_id += test(include_endpoint);
    else if (part_func_value > range_array[loc_part_id])
      loc_part_id++;
    loc_part_id++;
  }
  DBUG_RETURN(loc_part_id);
}


unknown's avatar
unknown committed
2508
int get_partition_id_hash_nosub(partition_info *part_info,
2509 2510
                                 uint32 *part_id,
                                 longlong *func_value)
2511
{
2512 2513
  *part_id= get_part_id_hash(part_info->no_parts, part_info->part_expr,
                             func_value);
unknown's avatar
unknown committed
2514
  return 0;
2515 2516 2517
}


unknown's avatar
unknown committed
2518
int get_partition_id_linear_hash_nosub(partition_info *part_info,
2519 2520
                                        uint32 *part_id,
                                        longlong *func_value)
2521 2522
{
  *part_id= get_part_id_linear_hash(part_info, part_info->no_parts,
2523
                                    part_info->part_expr, func_value);
unknown's avatar
unknown committed
2524
  return 0;
2525 2526 2527
}


unknown's avatar
unknown committed
2528
int get_partition_id_key_nosub(partition_info *part_info,
2529 2530
                                uint32 *part_id,
                                longlong *func_value)
2531
{
2532 2533
  *part_id= get_part_id_key(part_info->part_field_array,
                            part_info->no_parts, func_value);
unknown's avatar
unknown committed
2534
  return 0;
2535 2536 2537
}


unknown's avatar
unknown committed
2538
int get_partition_id_linear_key_nosub(partition_info *part_info,
2539 2540
                                       uint32 *part_id,
                                       longlong *func_value)
2541 2542 2543
{
  *part_id= get_part_id_linear_key(part_info,
                                   part_info->part_field_array,
2544
                                   part_info->no_parts, func_value);
unknown's avatar
unknown committed
2545
  return 0;
2546 2547 2548
}


unknown's avatar
unknown committed
2549
int get_partition_id_range_sub_hash(partition_info *part_info,
2550 2551
                                     uint32 *part_id,
                                     longlong *func_value)
2552 2553 2554
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2555
  longlong local_func_value;
unknown's avatar
unknown committed
2556
  int error;
2557
  DBUG_ENTER("get_partition_id_range_sub_hash");
unknown's avatar
unknown committed
2558

2559 2560
  if (unlikely((error= get_partition_id_range(part_info, &loc_part_id,
                                              func_value))))
2561
  {
unknown's avatar
unknown committed
2562
    DBUG_RETURN(error);
2563 2564
  }
  no_subparts= part_info->no_subparts;
2565 2566
  sub_part_id= get_part_id_hash(no_subparts, part_info->subpart_expr,
                                &local_func_value);
2567
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2568
  DBUG_RETURN(0);
2569 2570 2571
}


unknown's avatar
unknown committed
2572
int get_partition_id_range_sub_linear_hash(partition_info *part_info,
2573 2574
                                            uint32 *part_id,
                                            longlong *func_value)
2575 2576 2577
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2578
  longlong local_func_value;
unknown's avatar
unknown committed
2579
  int error;
2580
  DBUG_ENTER("get_partition_id_range_sub_linear_hash");
unknown's avatar
unknown committed
2581

2582 2583
  if (unlikely((error= get_partition_id_range(part_info, &loc_part_id,
                                              func_value))))
2584
  {
unknown's avatar
unknown committed
2585
    DBUG_RETURN(error);
2586 2587 2588
  }
  no_subparts= part_info->no_subparts;
  sub_part_id= get_part_id_linear_hash(part_info, no_subparts,
2589 2590
                                       part_info->subpart_expr,
                                       &local_func_value);
2591
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2592
  DBUG_RETURN(0);
2593 2594 2595
}


unknown's avatar
unknown committed
2596
int get_partition_id_range_sub_key(partition_info *part_info,
2597 2598
                                    uint32 *part_id,
                                    longlong *func_value)
2599 2600 2601
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2602
  longlong local_func_value;
unknown's avatar
unknown committed
2603
  int error;
2604
  DBUG_ENTER("get_partition_id_range_sub_key");
unknown's avatar
unknown committed
2605

2606 2607
  if (unlikely((error= get_partition_id_range(part_info, &loc_part_id,
                                              func_value))))
2608
  {
unknown's avatar
unknown committed
2609
    DBUG_RETURN(error);
2610 2611
  }
  no_subparts= part_info->no_subparts;
2612 2613
  sub_part_id= get_part_id_key(part_info->subpart_field_array,
                               no_subparts, &local_func_value);
2614
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2615
  DBUG_RETURN(0);
2616 2617 2618
}


unknown's avatar
unknown committed
2619
int get_partition_id_range_sub_linear_key(partition_info *part_info,
2620 2621
                                           uint32 *part_id,
                                           longlong *func_value)
2622 2623 2624
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2625
  longlong local_func_value;
unknown's avatar
unknown committed
2626
  int error;
2627
  DBUG_ENTER("get_partition_id_range_sub_linear_key");
unknown's avatar
unknown committed
2628

2629 2630
  if (unlikely((error= get_partition_id_range(part_info, &loc_part_id,
                                              func_value))))
2631
  {
unknown's avatar
unknown committed
2632
    DBUG_RETURN(error);
2633 2634 2635 2636
  }
  no_subparts= part_info->no_subparts;
  sub_part_id= get_part_id_linear_key(part_info,
                                      part_info->subpart_field_array,
2637
                                      no_subparts, &local_func_value);
2638
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2639
  DBUG_RETURN(0);
2640 2641 2642
}


unknown's avatar
unknown committed
2643
int get_partition_id_list_sub_hash(partition_info *part_info,
2644 2645
                                    uint32 *part_id,
                                    longlong *func_value)
2646 2647 2648
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2649
  longlong local_func_value;
unknown's avatar
unknown committed
2650
  int error;
2651
  DBUG_ENTER("get_partition_id_list_sub_hash");
unknown's avatar
unknown committed
2652

2653 2654
  if (unlikely((error= get_partition_id_list(part_info, &loc_part_id,
                                             func_value))))
2655
  {
unknown's avatar
unknown committed
2656
    DBUG_RETURN(error);
2657 2658
  }
  no_subparts= part_info->no_subparts;
2659 2660
  sub_part_id= get_part_id_hash(no_subparts, part_info->subpart_expr,
                                &local_func_value);
2661
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2662
  DBUG_RETURN(0);
2663 2664 2665
}


unknown's avatar
unknown committed
2666
int get_partition_id_list_sub_linear_hash(partition_info *part_info,
2667 2668
                                           uint32 *part_id,
                                           longlong *func_value)
2669 2670 2671
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2672
  longlong local_func_value;
unknown's avatar
unknown committed
2673
  int error;
2674
  DBUG_ENTER("get_partition_id_list_sub_linear_hash");
unknown's avatar
unknown committed
2675

2676 2677
  if (unlikely((error= get_partition_id_list(part_info, &loc_part_id,
                                             func_value))))
2678
  {
unknown's avatar
unknown committed
2679
    DBUG_RETURN(error);
2680 2681
  }
  no_subparts= part_info->no_subparts;
2682 2683 2684
  sub_part_id= get_part_id_linear_hash(part_info, no_subparts,
                                       part_info->subpart_expr,
                                       &local_func_value);
2685
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2686
  DBUG_RETURN(0);
2687 2688 2689
}


unknown's avatar
unknown committed
2690
int get_partition_id_list_sub_key(partition_info *part_info,
2691 2692
                                   uint32 *part_id,
                                   longlong *func_value)
2693 2694 2695
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2696
  longlong local_func_value;
unknown's avatar
unknown committed
2697
  int error;
2698
  DBUG_ENTER("get_partition_id_range_sub_key");
unknown's avatar
unknown committed
2699

2700 2701
  if (unlikely((error= get_partition_id_list(part_info, &loc_part_id,
                                             func_value))))
2702
  {
unknown's avatar
unknown committed
2703
    DBUG_RETURN(error);
2704 2705
  }
  no_subparts= part_info->no_subparts;
2706 2707
  sub_part_id= get_part_id_key(part_info->subpart_field_array,
                               no_subparts, &local_func_value);
2708
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2709
  DBUG_RETURN(0);
2710 2711 2712
}


unknown's avatar
unknown committed
2713
int get_partition_id_list_sub_linear_key(partition_info *part_info,
2714 2715
                                          uint32 *part_id,
                                          longlong *func_value)
2716 2717 2718
{
  uint32 loc_part_id, sub_part_id;
  uint no_subparts;
2719
  longlong local_func_value;
unknown's avatar
unknown committed
2720
  int error;
2721
  DBUG_ENTER("get_partition_id_list_sub_linear_key");
unknown's avatar
unknown committed
2722

2723 2724
  if (unlikely((error= get_partition_id_list(part_info, &loc_part_id,
                                             func_value))))
2725
  {
unknown's avatar
unknown committed
2726
    DBUG_RETURN(error);
2727 2728 2729 2730
  }
  no_subparts= part_info->no_subparts;
  sub_part_id= get_part_id_linear_key(part_info,
                                      part_info->subpart_field_array,
2731
                                      no_subparts, &local_func_value);
2732
  *part_id= get_part_id_for_sub(loc_part_id, sub_part_id, no_subparts);
unknown's avatar
unknown committed
2733
  DBUG_RETURN(0);
2734 2735 2736 2737 2738
}


/*
  This function is used to calculate the subpartition id
unknown's avatar
unknown committed
2739

2740 2741 2742 2743
  SYNOPSIS
    get_subpartition_id()
    part_info           A reference to the partition_info struct where all the
                        desired information is given
unknown's avatar
unknown committed
2744

2745
  RETURN VALUE
unknown's avatar
unknown committed
2746 2747
    part_id             The subpartition identity

2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762
  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
*/

uint32 get_partition_id_hash_sub(partition_info *part_info)
{
2763 2764 2765
  longlong func_value;
  return get_part_id_hash(part_info->no_subparts, part_info->subpart_expr,
                          &func_value);
2766 2767 2768 2769 2770
}


uint32 get_partition_id_linear_hash_sub(partition_info *part_info)
{
2771
  longlong func_value;
2772
  return get_part_id_linear_hash(part_info, part_info->no_subparts,
2773
                                 part_info->subpart_expr, &func_value);
2774 2775 2776 2777 2778
}


uint32 get_partition_id_key_sub(partition_info *part_info)
{
2779
  longlong func_value;
2780
  return get_part_id_key(part_info->subpart_field_array,
2781
                         part_info->no_subparts, &func_value);
2782 2783 2784 2785 2786
}


uint32 get_partition_id_linear_key_sub(partition_info *part_info)
{
2787
  longlong func_value;
2788 2789
  return get_part_id_linear_key(part_info,
                                part_info->subpart_field_array,
2790
                                part_info->no_subparts, &func_value);
2791 2792 2793 2794
}


/*
unknown's avatar
unknown committed
2795 2796
  Set an indicator on all partition fields that are set by the key

2797 2798 2799 2800
  SYNOPSIS
    set_PF_fields_in_key()
    key_info                   Information about the index
    key_length                 Length of key
unknown's avatar
unknown committed
2801

2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841
  RETURN VALUE
    TRUE                       Found partition field set by key
    FALSE                      No partition field set by key
*/

static bool set_PF_fields_in_key(KEY *key_info, uint key_length)
{
  KEY_PART_INFO *key_part;
  bool found_part_field= FALSE;
  DBUG_ENTER("set_PF_fields_in_key");

  for (key_part= key_info->key_part; (int)key_length > 0; key_part++)
  {
    if (key_part->null_bit)
      key_length--;
    if (key_part->type == HA_KEYTYPE_BIT)
    {
      if (((Field_bit*)key_part->field)->bit_len)
        key_length--;
    }
    if (key_part->key_part_flag & (HA_BLOB_PART + HA_VAR_LENGTH_PART))
    {
      key_length-= HA_KEY_BLOB_LENGTH;
    }
    if (key_length < key_part->length)
      break;
    key_length-= key_part->length;
    if (key_part->field->flags & FIELD_IN_PART_FUNC_FLAG)
    {
      found_part_field= TRUE;
      key_part->field->flags|= GET_FIXED_FIELDS_FLAG;
    }
  }
  DBUG_RETURN(found_part_field);
}


/*
  We have found that at least one partition field was set by a key, now
  check if a partition function has all its fields bound or not.
unknown's avatar
unknown committed
2842

2843 2844 2845
  SYNOPSIS
    check_part_func_bound()
    ptr                     Array of fields NULL terminated (partition fields)
unknown's avatar
unknown committed
2846

2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871
  RETURN VALUE
    TRUE                    All fields in partition function are set
    FALSE                   Not all fields in partition function are set
*/

static bool check_part_func_bound(Field **ptr)
{
  bool result= TRUE;
  DBUG_ENTER("check_part_func_bound");

  for (; *ptr; ptr++)
  {
    if (!((*ptr)->flags & GET_FIXED_FIELDS_FLAG))
    {
      result= FALSE;
      break;
    }
  }
  DBUG_RETURN(result);
}


/*
  Get the id of the subpartitioning part by using the key buffer of the
  index scan.
unknown's avatar
unknown committed
2872

2873 2874 2875 2876 2877 2878
  SYNOPSIS
    get_sub_part_id_from_key()
    table         The table object
    buf           A buffer that can be used to evaluate the partition function
    key_info      The index object
    key_spec      A key_range containing key and key length
unknown's avatar
unknown committed
2879

2880 2881
  RETURN VALUES
    part_id       Subpartition id to use
unknown's avatar
unknown committed
2882

2883 2884 2885 2886 2887 2888 2889 2890 2891 2892
  DESCRIPTION
    Use key buffer to set-up record in buf, move field pointers and
    get the partition identity and restore field pointers afterwards.
*/

static uint32 get_sub_part_id_from_key(const TABLE *table,byte *buf,
                                       KEY *key_info,
                                       const key_range *key_spec)
{
  byte *rec0= table->record[0];
unknown's avatar
unknown committed
2893
  partition_info *part_info= table->part_info;
2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912
  uint32 part_id;
  DBUG_ENTER("get_sub_part_id_from_key");

  key_restore(buf, (byte*)key_spec->key, key_info, key_spec->length);
  if (likely(rec0 == buf))
    part_id= part_info->get_subpartition_id(part_info);
  else
  {
    Field **part_field_array= part_info->subpart_field_array;
    set_field_ptr(part_field_array, buf, rec0);
    part_id= part_info->get_subpartition_id(part_info);
    set_field_ptr(part_field_array, rec0, buf);
  }
  DBUG_RETURN(part_id);
}

/*
  Get the id of the partitioning part by using the key buffer of the
  index scan.
unknown's avatar
unknown committed
2913

2914 2915 2916 2917 2918 2919
  SYNOPSIS
    get_part_id_from_key()
    table         The table object
    buf           A buffer that can be used to evaluate the partition function
    key_info      The index object
    key_spec      A key_range containing key and key length
unknown's avatar
unknown committed
2920 2921
    out:part_id   Partition to use

2922 2923 2924
  RETURN VALUES
    TRUE          Partition to use not found
    FALSE         Ok, part_id indicates partition to use
unknown's avatar
unknown committed
2925

2926 2927 2928 2929
  DESCRIPTION
    Use key buffer to set-up record in buf, move field pointers and
    get the partition identity and restore field pointers afterwards.
*/
unknown's avatar
unknown committed
2930

2931 2932 2933 2934 2935
bool get_part_id_from_key(const TABLE *table, byte *buf, KEY *key_info,
                          const key_range *key_spec, uint32 *part_id)
{
  bool result;
  byte *rec0= table->record[0];
unknown's avatar
unknown committed
2936
  partition_info *part_info= table->part_info;
2937
  longlong func_value;
2938 2939 2940 2941
  DBUG_ENTER("get_part_id_from_key");

  key_restore(buf, (byte*)key_spec->key, key_info, key_spec->length);
  if (likely(rec0 == buf))
2942 2943
    result= part_info->get_part_partition_id(part_info, part_id,
                                             &func_value);
2944 2945 2946 2947
  else
  {
    Field **part_field_array= part_info->part_field_array;
    set_field_ptr(part_field_array, buf, rec0);
2948 2949
    result= part_info->get_part_partition_id(part_info, part_id,
                                             &func_value);
2950 2951 2952 2953 2954 2955 2956 2957
    set_field_ptr(part_field_array, rec0, buf);
  }
  DBUG_RETURN(result);
}

/*
  Get the partitioning id of the full PF by using the key buffer of the
  index scan.
unknown's avatar
unknown committed
2958

2959 2960 2961 2962 2963 2964
  SYNOPSIS
    get_full_part_id_from_key()
    table         The table object
    buf           A buffer that is used to evaluate the partition function
    key_info      The index object
    key_spec      A key_range containing key and key length
unknown's avatar
unknown committed
2965 2966
    out:part_spec A partition id containing start part and end part

2967 2968 2969
  RETURN VALUES
    part_spec
    No partitions to scan is indicated by end_part > start_part when returning
unknown's avatar
unknown committed
2970

2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
  DESCRIPTION
    Use key buffer to set-up record in buf, move field pointers if needed and
    get the partition identity and restore field pointers afterwards.
*/

void get_full_part_id_from_key(const TABLE *table, byte *buf,
                               KEY *key_info,
                               const key_range *key_spec,
                               part_id_range *part_spec)
{
  bool result;
unknown's avatar
unknown committed
2982
  partition_info *part_info= table->part_info;
2983
  byte *rec0= table->record[0];
2984
  longlong func_value;
2985 2986 2987 2988
  DBUG_ENTER("get_full_part_id_from_key");

  key_restore(buf, (byte*)key_spec->key, key_info, key_spec->length);
  if (likely(rec0 == buf))
2989 2990
    result= part_info->get_partition_id(part_info, &part_spec->start_part,
                                        &func_value);
2991 2992 2993 2994
  else
  {
    Field **part_field_array= part_info->full_part_field_array;
    set_field_ptr(part_field_array, buf, rec0);
2995 2996
    result= part_info->get_partition_id(part_info, &part_spec->start_part,
                                        &func_value);
2997 2998 2999 3000 3001 3002 3003
    set_field_ptr(part_field_array, rec0, buf);
  }
  part_spec->end_part= part_spec->start_part;
  if (unlikely(result))
    part_spec->start_part++;
  DBUG_VOID_RETURN;
}
3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040

/*
  Prune the set of partitions to use in query 

  SYNOPSIS
    prune_partition_set()
    table         The table object
    out:part_spec Contains start part, end part 

  DESCRIPTION
    This function is called to prune the range of partitions to scan by
    checking the used_partitions bitmap.
    If start_part > end_part at return it means no partition needs to be
    scanned. If start_part == end_part it always means a single partition
    needs to be scanned.

  RETURN VALUE
    part_spec
*/
void prune_partition_set(const TABLE *table, part_id_range *part_spec)
{
  int last_partition= -1;
  uint i;
  partition_info *part_info= table->part_info;

  DBUG_ENTER("prune_partition_set");
  for (i= part_spec->start_part; i <= part_spec->end_part; i++)
  {
    if (bitmap_is_set(&(part_info->used_partitions), i))
    {
      DBUG_PRINT("info", ("Partition %d is set", i));
      if (last_partition == -1)
        /* First partition found in set and pruned bitmap */
        part_spec->start_part= i;
      last_partition= i;
    }
  }
unknown's avatar
unknown committed
3041 3042 3043 3044
  if (last_partition == -1)
    /* No partition found in pruned bitmap */
    part_spec->start_part= part_spec->end_part + 1;  
  else //if (last_partition != -1)
3045 3046 3047 3048 3049
    part_spec->end_part= last_partition;

  DBUG_VOID_RETURN;
}

3050 3051
/*
  Get the set of partitions to use in query.
unknown's avatar
unknown committed
3052

3053 3054 3055 3056 3057 3058
  SYNOPSIS
    get_partition_set()
    table         The table object
    buf           A buffer that can be used to evaluate the partition function
    index         The index of the key used, if MAX_KEY no index used
    key_spec      A key_range containing key and key length
unknown's avatar
unknown committed
3059
    out:part_spec Contains start part, end part and indicator if bitmap is
3060
                  used for which partitions to scan
unknown's avatar
unknown committed
3061

3062 3063 3064 3065 3066 3067 3068 3069 3070
  DESCRIPTION
    This function is called to discover which partitions to use in an index
    scan or a full table scan.
    It returns a range of partitions to scan. If there are holes in this
    range with partitions that are not needed to scan a bit array is used
    to signal which partitions to use and which not to use.
    If start_part > end_part at return it means no partition needs to be
    scanned. If start_part == end_part it always means a single partition
    needs to be scanned.
unknown's avatar
unknown committed
3071

3072 3073 3074 3075 3076 3077
  RETURN VALUE
    part_spec
*/
void get_partition_set(const TABLE *table, byte *buf, const uint index,
                       const key_range *key_spec, part_id_range *part_spec)
{
unknown's avatar
unknown committed
3078
  partition_info *part_info= table->part_info;
3079
  uint no_parts= part_info->get_tot_partitions();
unknown's avatar
unknown committed
3080
  uint i, part_id;
3081 3082
  uint sub_part= no_parts;
  uint32 part_part= no_parts;
3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112
  KEY *key_info= NULL;
  bool found_part_field= FALSE;
  DBUG_ENTER("get_partition_set");

  part_spec->start_part= 0;
  part_spec->end_part= no_parts - 1;
  if ((index < MAX_KEY) && 
       key_spec->flag == (uint)HA_READ_KEY_EXACT &&
       part_info->some_fields_in_PF.is_set(index))
  {
    key_info= table->key_info+index;
    /*
      The index can potentially provide at least one PF-field (field in the
      partition function). Thus it is interesting to continue our probe.
    */
    if (key_spec->length == key_info->key_length)
    {
      /*
        The entire key is set so we can check whether we can immediately
        derive either the complete PF or if we can derive either
        the top PF or the subpartitioning PF. This can be established by
        checking precalculated bits on each index.
      */
      if (part_info->all_fields_in_PF.is_set(index))
      {
        /*
          We can derive the exact partition to use, no more than this one
          is needed.
        */
        get_full_part_id_from_key(table,buf,key_info,key_spec,part_spec);
3113 3114 3115 3116
        /*
          Check if range can be adjusted by looking in used_partitions
        */
        prune_partition_set(table, part_spec);
3117 3118
        DBUG_VOID_RETURN;
      }
3119
      else if (part_info->is_sub_partitioned())
3120 3121 3122 3123 3124
      {
        if (part_info->all_fields_in_SPF.is_set(index))
          sub_part= get_sub_part_id_from_key(table, buf, key_info, key_spec);
        else if (part_info->all_fields_in_PPF.is_set(index))
        {
unknown's avatar
unknown committed
3125 3126
          if (get_part_id_from_key(table,buf,key_info,
                                   key_spec,(uint32*)&part_part))
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158
          {
            /*
              The value of the RANGE or LIST partitioning was outside of
              allowed values. Thus it is certain that the result of this
              scan will be empty.
            */
            part_spec->start_part= no_parts;
            DBUG_VOID_RETURN;
          }
        }
      }
    }
    else
    {
      /*
        Set an indicator on all partition fields that are bound.
        If at least one PF-field was bound it pays off to check whether
        the PF or PPF or SPF has been bound.
        (PF = Partition Function, SPF = Subpartition Function and
         PPF = Partition Function part of subpartitioning)
      */
      if ((found_part_field= set_PF_fields_in_key(key_info,
                                                  key_spec->length)))
      {
        if (check_part_func_bound(part_info->full_part_field_array))
        {
          /*
            We were able to bind all fields in the partition function even
            by using only a part of the key. Calculate the partition to use.
          */
          get_full_part_id_from_key(table,buf,key_info,key_spec,part_spec);
          clear_indicator_in_key_fields(key_info);
3159 3160 3161 3162
          /*
            Check if range can be adjusted by looking in used_partitions
          */
          prune_partition_set(table, part_spec);
3163 3164
          DBUG_VOID_RETURN; 
        }
3165
        else if (part_info->is_sub_partitioned())
3166
        {
unknown's avatar
unknown committed
3167 3168 3169
          if (check_part_func_bound(part_info->subpart_field_array))
            sub_part= get_sub_part_id_from_key(table, buf, key_info, key_spec);
          else if (check_part_func_bound(part_info->part_field_array))
3170
          {
unknown's avatar
unknown committed
3171 3172 3173 3174 3175 3176
            if (get_part_id_from_key(table,buf,key_info,key_spec,&part_part))
            {
              part_spec->start_part= no_parts;
              clear_indicator_in_key_fields(key_info);
              DBUG_VOID_RETURN;
            }
3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205
          }
        }
      }
    }
  }
  {
    /*
      The next step is to analyse the table condition to see whether any
      information about which partitions to scan can be derived from there.
      Currently not implemented.
    */
  }
  /*
    If we come here we have found a range of sorts we have either discovered
    nothing or we have discovered a range of partitions with possible holes
    in it. We need a bitvector to further the work here.
  */
  if (!(part_part == no_parts && sub_part == no_parts))
  {
    /*
      We can only arrive here if we are using subpartitioning.
    */
    if (part_part != no_parts)
    {
      /*
        We know the top partition and need to scan all underlying
        subpartitions. This is a range without holes.
      */
      DBUG_ASSERT(sub_part == no_parts);
3206
      part_spec->start_part= part_part * part_info->no_subparts;
3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221
      part_spec->end_part= part_spec->start_part+part_info->no_subparts - 1;
    }
    else
    {
      DBUG_ASSERT(sub_part != no_parts);
      part_spec->start_part= sub_part;
      part_spec->end_part=sub_part+
                           (part_info->no_subparts*(part_info->no_parts-1));
      for (i= 0, part_id= sub_part; i < part_info->no_parts;
           i++, part_id+= part_info->no_subparts)
        ; //Set bit part_id in bit array
    }
  }
  if (found_part_field)
    clear_indicator_in_key_fields(key_info);
3222 3223 3224 3225
  /*
    Check if range can be adjusted by looking in used_partitions
  */
  prune_partition_set(table, part_spec);
3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246
  DBUG_VOID_RETURN;
}

/*
   If the table is partitioned we will read the partition info into the
   .frm file here.
   -------------------------------
   |  Fileinfo     64 bytes      |
   -------------------------------
   | Formnames     7 bytes       |
   -------------------------------
   | Not used    4021 bytes      |
   -------------------------------
   | Keyinfo + record            |
   -------------------------------
   | Padded to next multiple     |
   | of IO_SIZE                  |
   -------------------------------
   | Forminfo     288 bytes      |
   -------------------------------
   | Screen buffer, to make      |
unknown's avatar
unknown committed
3247
   |field names readable        |
3248 3249
   -------------------------------
   | Packed field info           |
unknown's avatar
unknown committed
3250
   |17 + 1 + strlen(field_name) |
3251 3252 3253 3254 3255 3256 3257 3258
   | + 1 end of file character   |
   -------------------------------
   | Partition info              |
   -------------------------------
   We provide the length of partition length in Fileinfo[55-58].

   Read the partition syntax from the frm file and parse it to get the
   data structures of the partitioning.
unknown's avatar
unknown committed
3259

3260 3261 3262
   SYNOPSIS
     mysql_unpack_partition()
     thd                           Thread object
unknown's avatar
unknown committed
3263
     part_buf                      Partition info from frm file
3264 3265
     part_info_len                 Length of partition syntax
     table                         Table object of partitioned table
unknown's avatar
unknown committed
3266 3267 3268
     create_table_ind              Is it called from CREATE TABLE
     default_db_type               What is the default engine of the table

3269 3270 3271
   RETURN VALUE
     TRUE                          Error
     FALSE                         Sucess
unknown's avatar
unknown committed
3272

3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283
   DESCRIPTION
     Read the partition syntax from the current position in the frm file.
     Initiate a LEX object, save the list of item tree objects to free after
     the query is done. Set-up partition info object such that parser knows
     it is called from internally. Call parser to create data structures
     (best possible recreation of item trees and so forth since there is no
     serialisation of these objects other than in parseable text format).
     We need to save the text of the partition functions since it is not
     possible to retrace this given an item tree.
*/

unknown's avatar
unknown committed
3284
bool mysql_unpack_partition(THD *thd, const uchar *part_buf,
unknown's avatar
unknown committed
3285 3286 3287
                            uint part_info_len,
                            uchar *part_state, uint part_state_len,
                            TABLE* table, bool is_create_table_ind,
unknown's avatar
unknown committed
3288
                            handlerton *default_db_type)
3289 3290 3291 3292
{
  Item *thd_free_list= thd->free_list;
  bool result= TRUE;
  partition_info *part_info;
3293
  CHARSET_INFO *old_character_set_client= thd->variables.character_set_client;
unknown's avatar
unknown committed
3294 3295
  LEX *old_lex= thd->lex;
  LEX lex;
3296
  DBUG_ENTER("mysql_unpack_partition");
unknown's avatar
unknown committed
3297

3298
  thd->lex= &lex;
3299
  thd->variables.character_set_client= system_charset_info;
3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318
  lex_start(thd, part_buf, part_info_len);
  /*
    We need to use the current SELECT_LEX since I need to keep the
    Name_resolution_context object which is referenced from the
    Item_field objects.
    This is not a nice solution since if the parser uses current_select
    for anything else it will corrupt the current LEX object.
  */
  thd->lex->current_select= old_lex->current_select; 
  /*
    All Items created is put into a free list on the THD object. This list
    is used to free all Item objects after completing a query. We don't
    want that to happen with the Item tree created as part of the partition
    info. This should be attached to the table object and remain so until
    the table object is released.
    Thus we move away the current list temporarily and start a new list that
    we then save in the partition info structure.
  */
  thd->free_list= NULL;
3319
  lex.part_info= new partition_info();/* Indicates MYSQLparse from this place */
unknown's avatar
unknown committed
3320 3321 3322 3323 3324 3325 3326 3327
  if (!lex.part_info)
  {
    mem_alloc_error(sizeof(partition_info));
    goto end;
  }
  lex.part_info->part_state= part_state;
  lex.part_info->part_state_len= part_state_len;
  DBUG_PRINT("info", ("Parse: %s", part_buf));
3328
  if (MYSQLparse((void*)thd) || thd->is_fatal_error)
3329 3330 3331 3332
  {
    free_items(thd->free_list);
    goto end;
  }
unknown's avatar
unknown committed
3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348
  /*
    The parsed syntax residing in the frm file can still contain defaults.
    The reason is that the frm file is sometimes saved outside of this
    MySQL Server and used in backup and restore of clusters or partitioned
    tables. It is not certain that the restore will restore exactly the
    same default partitioning.
    
    The easiest manner of handling this is to simply continue using the
    part_info we already built up during mysql_create_table if we are
    in the process of creating a table. If the table already exists we
    need to discover the number of partitions for the default parts. Since
    the handler object hasn't been created here yet we need to postpone this
    to the fix_partition_func method.
  */

  DBUG_PRINT("info", ("Successful parse"));
3349
  part_info= lex.part_info;
unknown's avatar
unknown committed
3350 3351 3352
  DBUG_PRINT("info", ("default engine = %d, default_db_type = %d",
             ha_legacy_type(part_info->default_engine_type),
             ha_legacy_type(default_db_type)));
3353
  if (is_create_table_ind && old_lex->sql_command == SQLCOM_CREATE_TABLE)
unknown's avatar
unknown committed
3354
  {
unknown's avatar
unknown committed
3355
    if (old_lex->like_name)
unknown's avatar
unknown committed
3356 3357 3358
    {
      /*
        This code is executed when we do a CREATE TABLE t1 LIKE t2
unknown's avatar
unknown committed
3359
        old_lex->like_name contains the t2 and the table we are opening has 
unknown's avatar
unknown committed
3360 3361
        name t1.
      */
unknown's avatar
unknown committed
3362
      Table_ident *table_ident= old_lex->like_name;
3363 3364 3365 3366
      char *src_db= table_ident->db.str ? table_ident->db.str : thd->db;
      char *src_table= table_ident->table.str;
      char buf[FN_REFLEN];
      build_table_filename(buf, sizeof(buf), src_db, src_table, "");
3367 3368
      if (partition_default_handling(table, part_info,
                                     FALSE, buf))
unknown's avatar
unknown committed
3369
      {
3370 3371
        result= TRUE;
        goto end;
unknown's avatar
unknown committed
3372 3373 3374
      }
    }
    else
3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388
    {
      /*
        When we come here we are doing a create table. In this case we
        have already done some preparatory work on the old part_info
        object. We don't really need this new partition_info object.
        Thus we go back to the old partition info object.
        We need to free any memory objects allocated on item_free_list
        by the parser since we are keeping the old info from the first
        parser call in CREATE TABLE.
        We'll ensure that this object isn't put into table cache also
        just to ensure we don't get into strange situations with the
        item objects.
      */
      free_items(thd->free_list);
3389
      part_info= thd->work_part_info;
3390 3391 3392
      thd->free_list= NULL;
      table->s->version= 0UL;
    }
unknown's avatar
unknown committed
3393
  }
unknown's avatar
unknown committed
3394
  table->part_info= part_info;
3395
  table->file->set_part_info(part_info);
unknown's avatar
unknown committed
3396
  if (part_info->default_engine_type == NULL)
unknown's avatar
unknown committed
3397
  {
3398
    part_info->default_engine_type= default_db_type;
unknown's avatar
unknown committed
3399
  }
3400 3401 3402 3403
  else
  {
    DBUG_ASSERT(part_info->default_engine_type == default_db_type);
  }
3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417
  part_info->item_free_list= thd->free_list;

  {
  /*
    This code part allocates memory for the serialised item information for
    the partition functions. In most cases this is not needed but if the
    table is used for SHOW CREATE TABLES or ALTER TABLE that modifies
    partition information it is needed and the info is lost if we don't
    save it here so unfortunately we have to do it here even if in most
    cases it is not needed. This is a consequence of that item trees are
    not serialisable.
  */
    uint part_func_len= part_info->part_func_len;
    uint subpart_func_len= part_info->subpart_func_len; 
unknown's avatar
unknown committed
3418 3419 3420 3421
    char *part_func_string= NULL;
    char *subpart_func_string= NULL;
    if ((part_func_len &&
        !((part_func_string= thd->alloc(part_func_len)))) ||
3422
        (subpart_func_len &&
unknown's avatar
unknown committed
3423
        !((subpart_func_string= thd->alloc(subpart_func_len)))))
3424
    {
unknown's avatar
unknown committed
3425
      mem_alloc_error(part_func_len);
3426 3427 3428 3429
      free_items(thd->free_list);
      part_info->item_free_list= 0;
      goto end;
    }
unknown's avatar
unknown committed
3430 3431
    if (part_func_len)
      memcpy(part_func_string, part_info->part_func_string, part_func_len);
3432 3433 3434 3435 3436 3437 3438 3439 3440
    if (subpart_func_len)
      memcpy(subpart_func_string, part_info->subpart_func_string,
             subpart_func_len);
    part_info->part_func_string= part_func_string;
    part_info->subpart_func_string= subpart_func_string;
  }

  result= FALSE;
end:
unknown's avatar
unknown committed
3441
  lex_end(thd->lex);
3442 3443
  thd->free_list= thd_free_list;
  thd->lex= old_lex;
3444
  thd->variables.character_set_client= old_character_set_client;
3445 3446
  DBUG_RETURN(result);
}
unknown's avatar
unknown committed
3447

3448

unknown's avatar
unknown committed
3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484
/*
  Set engine type on all partition element objects
  SYNOPSIS
    set_engine_all_partitions()
    part_info                  Partition info
    engine_type                Handlerton reference of engine
  RETURN VALUES
    NONE
*/

static
void
set_engine_all_partitions(partition_info *part_info,
                          handlerton *engine_type)
{
  uint i= 0;
  List_iterator<partition_element> part_it(part_info->partitions);
  do
  {
    partition_element *part_elem= part_it++;

    part_elem->engine_type= engine_type;
    if (part_info->is_sub_partitioned())
    {
      List_iterator<partition_element> sub_it(part_elem->subpartitions);
      uint j= 0;

      do
      {
        partition_element *sub_elem= sub_it++;

        sub_elem->engine_type= engine_type;
      } while (++j < part_info->no_subparts);
    }
  } while (++i < part_info->no_parts);
}
3485 3486
/*
  SYNOPSIS
unknown's avatar
unknown committed
3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498
    fast_end_partition()
    thd                           Thread object
    out:copied                    Number of records copied
    out:deleted                   Number of records deleted
    table_list                    Table list with the one table in it
    empty                         Has nothing been done
    lpt                           Struct to be used by error handler

  RETURN VALUES
    FALSE                         Success
    TRUE                          Failure

3499
  DESCRIPTION
unknown's avatar
unknown committed
3500 3501
    Support routine to handle the successful cases for partition
    management.
3502 3503
*/

unknown's avatar
unknown committed
3504 3505
static int fast_end_partition(THD *thd, ulonglong copied,
                              ulonglong deleted,
3506
                              TABLE *table,
unknown's avatar
unknown committed
3507 3508 3509
                              TABLE_LIST *table_list, bool is_empty,
                              ALTER_PARTITION_PARAM_TYPE *lpt,
                              bool written_bin_log)
3510
{
unknown's avatar
unknown committed
3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533
  int error;
  DBUG_ENTER("fast_end_partition");

  thd->proc_info="end";
  if (!is_empty)
    query_cache_invalidate3(thd, table_list, 0);
  error= ha_commit_stmt(thd);
  if (ha_commit(thd))
    error= 1;
  if (!error || is_empty)
  {
    char tmp_name[80];
    if ((!is_empty) && (!written_bin_log) &&
        (!thd->lex->no_write_to_binlog))
      write_bin_log(thd, FALSE, thd->query, thd->query_length);
    close_thread_tables(thd);
    my_snprintf(tmp_name, sizeof(tmp_name), ER(ER_INSERT_INFO),
                (ulong) (copied + deleted),
                (ulong) deleted,
                (ulong) 0);
    send_ok(thd,copied+deleted,0L,tmp_name);
    DBUG_RETURN(FALSE);
  }
3534
  table->file->print_error(error, MYF(0));
unknown's avatar
unknown committed
3535 3536 3537 3538
  DBUG_RETURN(TRUE);
}


3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566
/*
  Check engine mix that it is correct
  SYNOPSIS
    check_engine_condition()
    p_elem                   Partition element
    default_engine           Have user specified engine on table level
    inout::engine_type       Current engine used
    inout::first             Is it first partition
  RETURN VALUE
    TRUE                     Failed check
    FALSE                    Ok
  DESCRIPTION
    (specified partition handler ) specified table handler
    (NDB, NDB) NDB           OK
    (MYISAM, MYISAM) -       OK
    (MYISAM, -)      -       NOT OK
    (MYISAM, -)    MYISAM    OK
    (- , MYISAM)   -         NOT OK
    (- , -)        MYISAM    OK
    (-,-)          -         OK
    (NDB, MYISAM) *          NOT OK
*/

static bool check_engine_condition(partition_element *p_elem,
                                   bool default_engine,
                                   handlerton **engine_type,
                                   bool *first)
{
unknown's avatar
unknown committed
3567 3568 3569
  DBUG_ENTER("check_engine_condition");

  DBUG_PRINT("enter", ("def_eng = %u, first = %u", default_engine, *first));
3570
  if (*first && default_engine)
unknown's avatar
unknown committed
3571
  {
3572
    *engine_type= p_elem->engine_type;
unknown's avatar
unknown committed
3573
  }
3574 3575
  *first= FALSE;
  if ((!default_engine &&
unknown's avatar
unknown committed
3576 3577
      (p_elem->engine_type != (*engine_type) &&
       p_elem->engine_type)) ||
3578
      (default_engine &&
unknown's avatar
unknown committed
3579 3580 3581 3582
       p_elem->engine_type != (*engine_type)))
  {
    DBUG_RETURN(TRUE);
  }
3583
  else
unknown's avatar
unknown committed
3584 3585 3586
  {
    DBUG_RETURN(FALSE);
  }
3587 3588
}

unknown's avatar
unknown committed
3589 3590 3591
/*
  We need to check if engine used by all partitions can handle
  partitioning natively.
3592

unknown's avatar
unknown committed
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616
  SYNOPSIS
    check_native_partitioned()
    create_info            Create info in CREATE TABLE
    out:ret_val            Return value
    part_info              Partition info
    thd                    Thread object

  RETURN VALUES
  Value returned in bool ret_value
    TRUE                   Native partitioning supported by engine
    FALSE                  Need to use partition handler

  Return value from function
    TRUE                   Error
    FALSE                  Success
*/

static bool check_native_partitioned(HA_CREATE_INFO *create_info,bool *ret_val,
                                     partition_info *part_info, THD *thd)
{
  List_iterator<partition_element> part_it(part_info->partitions);
  bool first= TRUE;
  bool default_engine;
  handlerton *engine_type= create_info->db_type;
3617
  handlerton *old_engine_type= engine_type;
unknown's avatar
unknown committed
3618 3619
  uint i= 0;
  handler *file;
3620
  uint no_parts= part_info->partitions.elements;
unknown's avatar
unknown committed
3621 3622
  DBUG_ENTER("check_native_partitioned");

unknown's avatar
unknown committed
3623 3624
  default_engine= (create_info->used_fields & HA_CREATE_USED_ENGINE) ?
                   FALSE : TRUE;
unknown's avatar
unknown committed
3625 3626 3627
  DBUG_PRINT("info", ("engine_type = %u, default = %u",
                       ha_legacy_type(engine_type),
                       default_engine));
3628
  if (no_parts)
3629
  {
3630
    do
unknown's avatar
unknown committed
3631
    {
3632
      partition_element *part_elem= part_it++;
3633
      if (part_info->is_sub_partitioned() &&
3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660
          part_elem->subpartitions.elements)
      {
        uint no_subparts= part_elem->subpartitions.elements;
        uint j= 0;
        List_iterator<partition_element> sub_it(part_elem->subpartitions);
        do
        {
          partition_element *sub_elem= sub_it++;
          if (check_engine_condition(sub_elem, default_engine,
                                     &engine_type, &first))
            goto error;
        } while (++j < no_subparts);
        /*
          In case of subpartitioning and defaults we allow that only
          subparts have specified engines, as long as the parts haven't
          specified the wrong engine it's ok.
        */
        if (check_engine_condition(part_elem, FALSE,
                                   &engine_type, &first))
          goto error;
      }
      else if (check_engine_condition(part_elem, default_engine,
                                      &engine_type, &first))
        goto error;
    } while (++i < no_parts);
  }

unknown's avatar
unknown committed
3661 3662 3663 3664
  /*
    All engines are of the same type. Check if this engine supports
    native partitioning.
  */
3665 3666 3667 3668 3669

  if (!engine_type)
    engine_type= old_engine_type;
  DBUG_PRINT("info", ("engine_type = %s",
              ha_resolve_storage_engine_name(engine_type)));
unknown's avatar
unknown committed
3670 3671 3672 3673 3674 3675 3676 3677
  if (engine_type->partition_flags &&
      (engine_type->partition_flags() & HA_CAN_PARTITION))
  {
    create_info->db_type= engine_type;
    DBUG_PRINT("info", ("Changed to native partitioning"));
    *ret_val= TRUE;
  }
  DBUG_RETURN(FALSE);
3678 3679 3680 3681 3682
error:
  /*
    Mixed engines not yet supported but when supported it will need
    the partition handler
  */
unknown's avatar
unknown committed
3683
  my_error(ER_MIX_HANDLER_ERROR, MYF(0));
3684 3685
  *ret_val= FALSE;
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726
}


/*
  Prepare for ALTER TABLE of partition structure

  SYNOPSIS
    prep_alter_part_table()
    thd                        Thread object
    table                      Table object
    inout:alter_info           Alter information
    inout:create_info          Create info for CREATE TABLE
    old_db_type                Old engine type
    out:partition_changed      Boolean indicating whether partition changed
    out:fast_alter_partition   Boolean indicating whether fast partition
                               change is requested

  RETURN VALUES
    TRUE                       Error
    FALSE                      Success
    partition_changed
    fast_alter_partition

  DESCRIPTION
    This method handles all preparations for ALTER TABLE for partitioned
    tables
    We need to handle both partition management command such as Add Partition
    and others here as well as an ALTER TABLE that completely changes the
    partitioning and yet others that don't change anything at all. We start
    by checking the partition management variants and then check the general
    change patterns.
*/

uint prep_alter_part_table(THD *thd, TABLE *table, ALTER_INFO *alter_info,
                           HA_CREATE_INFO *create_info,
                           handlerton *old_db_type,
                           bool *partition_changed,
                           uint *fast_alter_partition)
{
  DBUG_ENTER("prep_alter_part_table");

3727 3728 3729 3730 3731 3732 3733 3734 3735
  /*
    We are going to manipulate the partition info on the table object
    so we need to ensure that the data structure of the table object
    is freed by setting version to 0. table->s->version= 0 forces a
    flush of the table object in close_thread_tables().
  */
  if (table->part_info)
    table->s->version= 0L;

3736 3737 3738
  thd->work_part_info= thd->lex->part_info;
  if (thd->work_part_info &&
      !(thd->work_part_info= thd->lex->part_info->get_clone()))
unknown's avatar
unknown committed
3739 3740
    DBUG_RETURN(TRUE);

unknown's avatar
unknown committed
3741 3742 3743 3744 3745 3746 3747 3748
  if (alter_info->flags &
      (ALTER_ADD_PARTITION | ALTER_DROP_PARTITION |
       ALTER_COALESCE_PARTITION | ALTER_REORGANIZE_PARTITION |
       ALTER_TABLE_REORG | ALTER_OPTIMIZE_PARTITION |
       ALTER_CHECK_PARTITION | ALTER_ANALYZE_PARTITION |
       ALTER_REPAIR_PARTITION | ALTER_REBUILD_PARTITION))
  {
    partition_info *tab_part_info= table->part_info;
unknown's avatar
unknown committed
3749
    partition_info *alt_part_info= thd->work_part_info;
3750
    uint flags= 0;
unknown's avatar
unknown committed
3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774
    if (!tab_part_info)
    {
      my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));
      DBUG_RETURN(TRUE);
    }
    if (alter_info->flags == ALTER_TABLE_REORG)
    {
      uint new_part_no, curr_part_no;
      ulonglong max_rows= table->s->max_rows;
      if (tab_part_info->part_type != HASH_PARTITION ||
          tab_part_info->use_default_no_partitions)
      {
        my_error(ER_REORG_NO_PARAM_ERROR, MYF(0));
        DBUG_RETURN(TRUE);
      }
      new_part_no= table->file->get_default_no_partitions(max_rows);
      curr_part_no= tab_part_info->no_parts;
      if (new_part_no == curr_part_no)
      {
        /*
          No change is needed, we will have the same number of partitions
          after the change as before. Thus we can reply ok immediately
          without any changes at all.
        */
3775 3776
        DBUG_RETURN(fast_end_partition(thd, ULL(0), ULL(0),
                                       table, NULL,
unknown's avatar
unknown committed
3777 3778 3779 3780 3781 3782 3783 3784 3785
                                       TRUE, NULL, FALSE));
      }
      else if (new_part_no > curr_part_no)
      {
        /*
          We will add more partitions, we use the ADD PARTITION without
          setting the flag for no default number of partitions
        */
        alter_info->flags|= ALTER_ADD_PARTITION;
unknown's avatar
unknown committed
3786
        thd->work_part_info->no_parts= new_part_no - curr_part_no;
unknown's avatar
unknown committed
3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803
      }
      else
      {
        /*
          We will remove hash partitions, we use the COALESCE PARTITION
          without setting the flag for no default number of partitions
        */
        alter_info->flags|= ALTER_COALESCE_PARTITION;
        alter_info->no_parts= curr_part_no - new_part_no;
      }
    }
    if (table->s->db_type->alter_table_flags &&
        (!(flags= table->s->db_type->alter_table_flags(alter_info->flags))))
    {
      my_error(ER_PARTITION_FUNCTION_FAILURE, MYF(0));
      DBUG_RETURN(1);
    }
3804 3805 3806 3807
    *fast_alter_partition=
      ((flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE)) != 0);
    DBUG_PRINT("info", ("*fast_alter_partition: %d  flags: 0x%x",
                        *fast_alter_partition, flags));
3808 3809
    if (((alter_info->flags & ALTER_ADD_PARTITION) ||
         (alter_info->flags & ALTER_REORGANIZE_PARTITION)) &&
unknown's avatar
unknown committed
3810 3811
         (thd->work_part_info->part_type != tab_part_info->part_type) &&
         (thd->work_part_info->part_type != NOT_A_PARTITION))
3812
    {
unknown's avatar
unknown committed
3813
      if (thd->work_part_info->part_type == RANGE_PARTITION)
3814 3815 3816 3817
      {
        my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0),
                 "RANGE", "LESS THAN");
      }
unknown's avatar
unknown committed
3818
      else if (thd->work_part_info->part_type == LIST_PARTITION)
3819
      {
unknown's avatar
unknown committed
3820
        DBUG_ASSERT(thd->work_part_info->part_type == LIST_PARTITION);
3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836
        my_error(ER_PARTITION_WRONG_VALUES_ERROR, MYF(0),
                 "LIST", "IN");
      }
      else if (tab_part_info->part_type == RANGE_PARTITION)
      {
        my_error(ER_PARTITION_REQUIRES_VALUES_ERROR, MYF(0),
                 "RANGE", "LESS THAN");
      }
      else
      {
        DBUG_ASSERT(tab_part_info->part_type == LIST_PARTITION);
        my_error(ER_PARTITION_REQUIRES_VALUES_ERROR, MYF(0),
                 "LIST", "IN");
      }
      DBUG_RETURN(TRUE);
    }
unknown's avatar
unknown committed
3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863
    if (alter_info->flags & ALTER_ADD_PARTITION)
    {
      /*
        We start by moving the new partitions to the list of temporary
        partitions. We will then check that the new partitions fit in the
        partitioning scheme as currently set-up.
        Partitions are always added at the end in ADD PARTITION.
      */
      uint no_new_partitions= alt_part_info->no_parts;
      uint no_orig_partitions= tab_part_info->no_parts;
      uint check_total_partitions= no_new_partitions + no_orig_partitions;
      uint new_total_partitions= check_total_partitions;
      /*
        We allow quite a lot of values to be supplied by defaults, however we
        must know the number of new partitions in this case.
      */
      if (thd->lex->no_write_to_binlog &&
          tab_part_info->part_type != HASH_PARTITION)
      {
        my_error(ER_NO_BINLOG_ERROR, MYF(0));
        DBUG_RETURN(TRUE);
      } 
      if (no_new_partitions == 0)
      {
        my_error(ER_ADD_PARTITION_NO_NEW_PARTITION, MYF(0));
        DBUG_RETURN(TRUE);
      }
3864
      if (tab_part_info->is_sub_partitioned())
unknown's avatar
unknown committed
3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881
      {
        if (alt_part_info->no_subparts == 0)
          alt_part_info->no_subparts= tab_part_info->no_subparts;
        else if (alt_part_info->no_subparts != tab_part_info->no_subparts)
        {
          my_error(ER_ADD_PARTITION_SUBPART_ERROR, MYF(0));
          DBUG_RETURN(TRUE);
        }
        check_total_partitions= new_total_partitions*
                                alt_part_info->no_subparts;
      }
      if (check_total_partitions > MAX_PARTITIONS)
      {
        my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));
        DBUG_RETURN(TRUE);
      }
      alt_part_info->part_type= tab_part_info->part_type;
3882
      alt_part_info->subpart_type= tab_part_info->subpart_type;
3883 3884 3885
      if (alt_part_info->set_up_defaults_for_partitioning(table->file,
                                                          ULL(0), 
                                                          tab_part_info->no_parts))
unknown's avatar
unknown committed
3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079
      {
        DBUG_RETURN(TRUE);
      }
/*
Handling of on-line cases:

ADD PARTITION for RANGE/LIST PARTITIONING:
------------------------------------------
For range and list partitions add partition is simply adding a
new empty partition to the table. If the handler support this we
will use the simple method of doing this. The figure below shows
an example of this and the states involved in making this change.
            
Existing partitions                                     New added partitions
------       ------        ------        ------      |  ------    ------
|    |       |    |        |    |        |    |      |  |    |    |    |
| p0 |       | p1 |        | p2 |        | p3 |      |  | p4 |    | p5 |
------       ------        ------        ------      |  ------    ------
PART_NORMAL  PART_NORMAL   PART_NORMAL   PART_NORMAL    PART_TO_BE_ADDED*2
PART_NORMAL  PART_NORMAL   PART_NORMAL   PART_NORMAL    PART_IS_ADDED*2

The first line is the states before adding the new partitions and the 
second line is after the new partitions are added. All the partitions are
in the partitions list, no partitions are placed in the temp_partitions
list.

ADD PARTITION for HASH PARTITIONING
-----------------------------------
This little figure tries to show the various partitions involved when
adding two new partitions to a linear hash based partitioned table with
four partitions to start with, which lists are used and the states they
pass through. Adding partitions to a normal hash based is similar except
that it is always all the existing partitions that are reorganised not
only a subset of them.

Existing partitions                                     New added partitions
------       ------        ------        ------      |  ------    ------
|    |       |    |        |    |        |    |      |  |    |    |    |
| p0 |       | p1 |        | p2 |        | p3 |      |  | p4 |    | p5 |
------       ------        ------        ------      |  ------    ------
PART_CHANGED PART_CHANGED  PART_NORMAL   PART_NORMAL    PART_TO_BE_ADDED
PART_IS_CHANGED*2          PART_NORMAL   PART_NORMAL    PART_IS_ADDED
PART_NORMAL  PART_NORMAL   PART_NORMAL   PART_NORMAL    PART_IS_ADDED

Reorganised existing partitions
------      ------
|    |      |    |
| p0'|      | p1'|
------      ------

p0 - p5 will be in the partitions list of partitions.
p0' and p1' will actually not exist as separate objects, there presence can
be deduced from the state of the partition and also the names of those
partitions can be deduced this way.

After adding the partitions and copying the partition data to p0', p1',
p4 and p5 from p0 and p1 the states change to adapt for the new situation
where p0 and p1 is dropped and replaced by p0' and p1' and the new p4 and
p5 are in the table again.

The first line above shows the states of the partitions before we start
adding and copying partitions, the second after completing the adding
and copying and finally the third line after also dropping the partitions
that are reorganised.
*/
      if (*fast_alter_partition &&
          tab_part_info->part_type == HASH_PARTITION)
      {
        uint part_no= 0, start_part= 1, start_sec_part= 1;
        uint end_part= 0, end_sec_part= 0;
        uint upper_2n= tab_part_info->linear_hash_mask + 1;
        uint lower_2n= upper_2n >> 1;
        bool all_parts= TRUE;
        if (tab_part_info->linear_hash_ind &&
            no_new_partitions < upper_2n)
        {
          /*
            An analysis of which parts needs reorganisation shows that it is
            divided into two intervals. The first interval is those parts
            that are reorganised up until upper_2n - 1. From upper_2n and
            onwards it starts again from partition 0 and goes on until
            it reaches p(upper_2n - 1). If the last new partition reaches
            beyond upper_2n - 1 then the first interval will end with
            p(lower_2n - 1) and start with p(no_orig_partitions - lower_2n).
            If lower_2n partitions are added then p0 to p(lower_2n - 1) will
            be reorganised which means that the two interval becomes one
            interval at this point. Thus only when adding less than
            lower_2n partitions and going beyond a total of upper_2n we
            actually get two intervals.

            To exemplify this assume we have 6 partitions to start with and
            add 1, 2, 3, 5, 6, 7, 8, 9 partitions.
            The first to add after p5 is p6 = 110 in bit numbers. Thus we
            can see that 10 = p2 will be partition to reorganise if only one
            partition.
            If 2 partitions are added we reorganise [p2, p3]. Those two
            cases are covered by the second if part below.
            If 3 partitions are added we reorganise [p2, p3] U [p0,p0]. This
            part is covered by the else part below.
            If 5 partitions are added we get [p2,p3] U [p0, p2] = [p0, p3].
            This is covered by the first if part where we need the max check
            to here use lower_2n - 1.
            If 7 partitions are added we get [p2,p3] U [p0, p4] = [p0, p4].
            This is covered by the first if part but here we use the first
            calculated end_part.
            Finally with 9 new partitions we would also reorganise p6 if we
            used the method below but we cannot reorganise more partitions
            than what we had from the start and thus we simply set all_parts
            to TRUE. In this case we don't get into this if-part at all.
          */
          all_parts= FALSE;
          if (no_new_partitions >= lower_2n)
          {
            /*
              In this case there is only one interval since the two intervals
              overlap and this starts from zero to last_part_no - upper_2n
            */
            start_part= 0;
            end_part= new_total_partitions - (upper_2n + 1);
            end_part= max(lower_2n - 1, end_part);
          }
          else if (new_total_partitions <= upper_2n)
          {
            /*
              Also in this case there is only one interval since we are not
              going over a 2**n boundary
            */
            start_part= no_orig_partitions - lower_2n;
            end_part= start_part + (no_new_partitions - 1);
          }
          else
          {
            /* We have two non-overlapping intervals since we are not
               passing a 2**n border and we have not at least lower_2n
               new parts that would ensure that the intervals become
               overlapping.
            */
            start_part= no_orig_partitions - lower_2n;
            end_part= upper_2n - 1;
            start_sec_part= 0;
            end_sec_part= new_total_partitions - (upper_2n + 1);
          }
        }
        List_iterator<partition_element> tab_it(tab_part_info->partitions);
        part_no= 0;
        do
        {
          partition_element *p_elem= tab_it++;
          if (all_parts ||
              (part_no >= start_part && part_no <= end_part) ||
              (part_no >= start_sec_part && part_no <= end_sec_part))
          {
            p_elem->part_state= PART_CHANGED;
          }
        } while (++part_no < no_orig_partitions);
      }
      /*
        Need to concatenate the lists here to make it possible to check the
        partition info for correctness using check_partition_info.
        For on-line add partition we set the state of this partition to
        PART_TO_BE_ADDED to ensure that it is known that it is not yet
        usable (becomes usable when partition is created and the switch of
        partition configuration is made.
      */
      {
        List_iterator<partition_element> alt_it(alt_part_info->partitions);
        uint part_count= 0;
        do
        {
          partition_element *part_elem= alt_it++;
          if (*fast_alter_partition)
            part_elem->part_state= PART_TO_BE_ADDED;
          if (tab_part_info->partitions.push_back(part_elem))
          {
            mem_alloc_error(1);
            DBUG_RETURN(TRUE);
          }
        } while (++part_count < no_new_partitions);
        tab_part_info->no_parts+= no_new_partitions;
      }
      /*
        If we specify partitions explicitly we don't use defaults anymore.
        Using ADD PARTITION also means that we don't have the default number
        of partitions anymore. We use this code also for Table reorganisations
        and here we don't set any default flags to FALSE.
      */
      if (!(alter_info->flags & ALTER_TABLE_REORG))
      {
        if (!alt_part_info->use_default_partitions)
        {
          DBUG_PRINT("info", ("part_info= %x", tab_part_info));
          tab_part_info->use_default_partitions= FALSE;
        }
        tab_part_info->use_default_no_partitions= FALSE;
4080
        tab_part_info->is_auto_partitioned= FALSE;
unknown's avatar
unknown committed
4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095
      }
    }
    else if (alter_info->flags == ALTER_DROP_PARTITION)
    {
      /*
        Drop a partition from a range partition and list partitioning is
        always safe and can be made more or less immediate. It is necessary
        however to ensure that the partition to be removed is safely removed
        and that REPAIR TABLE can remove the partition if for some reason the
        command to drop the partition failed in the middle.
      */
      uint part_count= 0;
      uint no_parts_dropped= alter_info->partition_names.elements;
      uint no_parts_found= 0;
      List_iterator<partition_element> part_it(tab_part_info->partitions);
4096 4097

      tab_part_info->is_auto_partitioned= FALSE;
unknown's avatar
unknown committed
4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131
      if (!(tab_part_info->part_type == RANGE_PARTITION ||
            tab_part_info->part_type == LIST_PARTITION))
      {
        my_error(ER_ONLY_ON_RANGE_LIST_PARTITION, MYF(0), "DROP");
        DBUG_RETURN(TRUE);
      }
      if (no_parts_dropped >= tab_part_info->no_parts)
      {
        my_error(ER_DROP_LAST_PARTITION, MYF(0));
        DBUG_RETURN(TRUE);
      }
      do
      {
        partition_element *part_elem= part_it++;
        if (is_name_in_list(part_elem->partition_name,
                            alter_info->partition_names))
        {
          /*
            Set state to indicate that the partition is to be dropped.
          */
          no_parts_found++;
          part_elem->part_state= PART_TO_BE_DROPPED;
        }
      } while (++part_count < tab_part_info->no_parts);
      if (no_parts_found != no_parts_dropped)
      {
        my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "DROP");
        DBUG_RETURN(TRUE);
      }
      if (table->file->is_fk_defined_on_table_or_index(MAX_KEY))
      {
        my_error(ER_ROW_IS_REFERENCED, MYF(0));
        DBUG_RETURN(TRUE);
      }
4132
      tab_part_info->no_parts-= no_parts_dropped;
unknown's avatar
unknown committed
4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176
    }
    else if ((alter_info->flags & ALTER_OPTIMIZE_PARTITION) ||
             (alter_info->flags & ALTER_ANALYZE_PARTITION) ||
             (alter_info->flags & ALTER_CHECK_PARTITION) ||
             (alter_info->flags & ALTER_REPAIR_PARTITION) ||
             (alter_info->flags & ALTER_REBUILD_PARTITION))
    {
      uint no_parts_opt= alter_info->partition_names.elements;
      uint part_count= 0;
      uint no_parts_found= 0;
      List_iterator<partition_element> part_it(tab_part_info->partitions);

      do
      {
        partition_element *part_elem= part_it++;
        if ((alter_info->flags & ALTER_ALL_PARTITION) ||
            (is_name_in_list(part_elem->partition_name,
                             alter_info->partition_names)))
        {
          /*
            Mark the partition as a partition to be "changed" by
            analyzing/optimizing/rebuilding/checking/repairing
          */
          no_parts_found++;
          part_elem->part_state= PART_CHANGED;
        }
      } while (++part_count < tab_part_info->no_parts);
      if (no_parts_found != no_parts_opt &&
          (!(alter_info->flags & ALTER_ALL_PARTITION)))
      {
        const char *ptr;
        if (alter_info->flags & ALTER_OPTIMIZE_PARTITION)
          ptr= "OPTIMIZE";
        else if (alter_info->flags & ALTER_ANALYZE_PARTITION)
          ptr= "ANALYZE";
        else if (alter_info->flags & ALTER_CHECK_PARTITION)
          ptr= "CHECK";
        else if (alter_info->flags & ALTER_REPAIR_PARTITION)
          ptr= "REPAIR";
        else
          ptr= "REBUILD";
        my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), ptr);
        DBUG_RETURN(TRUE);
      }
4177 4178 4179 4180 4181
      if (!(*fast_alter_partition))
      {
        table->file->print_error(HA_ERR_WRONG_COMMAND, MYF(0));
        DBUG_RETURN(TRUE);
      }
unknown's avatar
unknown committed
4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281
    }
    else if (alter_info->flags & ALTER_COALESCE_PARTITION)
    {
      uint no_parts_coalesced= alter_info->no_parts;
      uint no_parts_remain= tab_part_info->no_parts - no_parts_coalesced;
      List_iterator<partition_element> part_it(tab_part_info->partitions);
      if (tab_part_info->part_type != HASH_PARTITION)
      {
        my_error(ER_COALESCE_ONLY_ON_HASH_PARTITION, MYF(0));
        DBUG_RETURN(TRUE);
      }
      if (no_parts_coalesced == 0)
      {
        my_error(ER_COALESCE_PARTITION_NO_PARTITION, MYF(0));
        DBUG_RETURN(TRUE);
      }
      if (no_parts_coalesced >= tab_part_info->no_parts)
      {
        my_error(ER_DROP_LAST_PARTITION, MYF(0));
        DBUG_RETURN(TRUE);
      }
/*
Online handling:
COALESCE PARTITION:
-------------------
The figure below shows the manner in which partitions are handled when
performing an on-line coalesce partition and which states they go through
at start, after adding and copying partitions and finally after dropping
the partitions to drop. The figure shows an example using four partitions
to start with, using linear hash and coalescing one partition (always the
last partition).

Using linear hash then all remaining partitions will have a new reorganised
part.

Existing partitions                     Coalesced partition 
------       ------              ------   |      ------
|    |       |    |              |    |   |      |    |
| p0 |       | p1 |              | p2 |   |      | p3 |
------       ------              ------   |      ------
PART_NORMAL  PART_CHANGED        PART_NORMAL     PART_REORGED_DROPPED
PART_NORMAL  PART_IS_CHANGED     PART_NORMAL     PART_TO_BE_DROPPED
PART_NORMAL  PART_NORMAL         PART_NORMAL     PART_IS_DROPPED

Reorganised existing partitions
            ------
            |    |
            | p1'|
            ------

p0 - p3 is in the partitions list.
The p1' partition will actually not be in any list it is deduced from the
state of p1.
*/
      {
        uint part_count= 0, start_part= 1, start_sec_part= 1;
        uint end_part= 0, end_sec_part= 0;
        bool all_parts= TRUE;
        if (*fast_alter_partition &&
            tab_part_info->linear_hash_ind)
        {
          uint upper_2n= tab_part_info->linear_hash_mask + 1;
          uint lower_2n= upper_2n >> 1;
          all_parts= FALSE;
          if (no_parts_coalesced >= lower_2n)
          {
            all_parts= TRUE;
          }
          else if (no_parts_remain >= lower_2n)
          {
            end_part= tab_part_info->no_parts - (lower_2n + 1);
            start_part= no_parts_remain - lower_2n;
          }
          else
          {
            start_part= 0;
            end_part= tab_part_info->no_parts - (lower_2n + 1);
            end_sec_part= (lower_2n >> 1) - 1;
            start_sec_part= end_sec_part - (lower_2n - (no_parts_remain + 1));
          }
        }
        do
        {
          partition_element *p_elem= part_it++;
          if (*fast_alter_partition &&
              (all_parts ||
              (part_count >= start_part && part_count <= end_part) ||
              (part_count >= start_sec_part && part_count <= end_sec_part)))
            p_elem->part_state= PART_CHANGED;
          if (++part_count > no_parts_remain)
          {
            if (*fast_alter_partition)
              p_elem->part_state= PART_REORGED_DROPPED;
            else
              part_it.remove();
          }
        } while (part_count < tab_part_info->no_parts);
        tab_part_info->no_parts= no_parts_remain;
      }
      if (!(alter_info->flags & ALTER_TABLE_REORG))
4282
      {
unknown's avatar
unknown committed
4283
        tab_part_info->use_default_no_partitions= FALSE;
4284 4285
        tab_part_info->is_auto_partitioned= FALSE;
      }
unknown's avatar
unknown committed
4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300
    }
    else if (alter_info->flags == ALTER_REORGANIZE_PARTITION)
    {
      /*
        Reorganise partitions takes a number of partitions that are next
        to each other (at least for RANGE PARTITIONS) and then uses those
        to create a set of new partitions. So data is copied from those
        partitions into the new set of partitions. Those new partitions
        can have more values in the LIST value specifications or less both
        are allowed. The ranges can be different but since they are 
        changing a set of consecutive partitions they must cover the same
        range as those changed from.
        This command can be used on RANGE and LIST partitions.
      */
      uint no_parts_reorged= alter_info->partition_names.elements;
unknown's avatar
unknown committed
4301 4302
      uint no_parts_new= thd->work_part_info->partitions.elements;
      partition_info *alt_part_info= thd->work_part_info;
unknown's avatar
unknown committed
4303
      uint check_total_partitions;
4304 4305

      tab_part_info->is_auto_partitioned= FALSE;
unknown's avatar
unknown committed
4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
      if (no_parts_reorged > tab_part_info->no_parts)
      {
        my_error(ER_REORG_PARTITION_NOT_EXIST, MYF(0));
        DBUG_RETURN(TRUE);
      }
      if (!(tab_part_info->part_type == RANGE_PARTITION ||
            tab_part_info->part_type == LIST_PARTITION) &&
           (no_parts_new != no_parts_reorged))
      {
        my_error(ER_REORG_HASH_ONLY_ON_SAME_NO, MYF(0));
        DBUG_RETURN(TRUE);
      }
      check_total_partitions= tab_part_info->no_parts + no_parts_new;
      check_total_partitions-= no_parts_reorged;
      if (check_total_partitions > MAX_PARTITIONS)
      {
        my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));
        DBUG_RETURN(TRUE);
      }
4325 4326 4327 4328 4329 4330 4331 4332 4333
      alt_part_info->part_type= tab_part_info->part_type;
      alt_part_info->subpart_type= tab_part_info->subpart_type;
      DBUG_ASSERT(!alt_part_info->use_default_partitions);
      if (alt_part_info->set_up_defaults_for_partitioning(table->file,
                                                          ULL(0), 
                                                          0))
      {
        DBUG_RETURN(TRUE);
      }
unknown's avatar
unknown committed
4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458
/*
Online handling:
REORGANIZE PARTITION:
---------------------
The figure exemplifies the handling of partitions, their state changes and
how they are organised. It exemplifies four partitions where two of the
partitions are reorganised (p1 and p2) into two new partitions (p4 and p5).
The reason of this change could be to change range limits, change list
values or for hash partitions simply reorganise the partition which could
also involve moving them to new disks or new node groups (MySQL Cluster).

Existing partitions                                  
------       ------        ------        ------
|    |       |    |        |    |        |    |
| p0 |       | p1 |        | p2 |        | p3 |
------       ------        ------        ------
PART_NORMAL  PART_TO_BE_REORGED          PART_NORMAL
PART_NORMAL  PART_TO_BE_DROPPED          PART_NORMAL
PART_NORMAL  PART_IS_DROPPED             PART_NORMAL

Reorganised new partitions (replacing p1 and p2)
------      ------
|    |      |    |
| p4 |      | p5 |
------      ------
PART_TO_BE_ADDED
PART_IS_ADDED
PART_IS_ADDED

All unchanged partitions and the new partitions are in the partitions list
in the order they will have when the change is completed. The reorganised
partitions are placed in the temp_partitions list. PART_IS_ADDED is only a
temporary state not written in the frm file. It is used to ensure we write
the generated partition syntax in a correct manner.
*/
      {
        List_iterator<partition_element> tab_it(tab_part_info->partitions);
        uint part_count= 0;
        bool found_first= FALSE;
        bool found_last= FALSE;
        bool is_last_partition_reorged;
        uint drop_count= 0;
        longlong tab_max_range= 0, alt_max_range= 0;
        do
        {
          partition_element *part_elem= tab_it++;
          is_last_partition_reorged= FALSE;
          if (is_name_in_list(part_elem->partition_name,
                              alter_info->partition_names))
          {
            is_last_partition_reorged= TRUE;
            drop_count++;
            tab_max_range= part_elem->range_value;
            if (*fast_alter_partition &&
                tab_part_info->temp_partitions.push_back(part_elem))
            {
              mem_alloc_error(1);
              DBUG_RETURN(TRUE);
            }
            if (*fast_alter_partition)
              part_elem->part_state= PART_TO_BE_REORGED;
            if (!found_first)
            {
              uint alt_part_count= 0;
              found_first= TRUE;
              List_iterator<partition_element>
                                 alt_it(alt_part_info->partitions);
              do
              {
                partition_element *alt_part_elem= alt_it++;
                alt_max_range= alt_part_elem->range_value;
                if (*fast_alter_partition)
                  alt_part_elem->part_state= PART_TO_BE_ADDED;
                if (alt_part_count == 0)
                  tab_it.replace(alt_part_elem);
                else
                  tab_it.after(alt_part_elem);
              } while (++alt_part_count < no_parts_new);
            }
            else if (found_last)
            {
              my_error(ER_CONSECUTIVE_REORG_PARTITIONS, MYF(0));
              DBUG_RETURN(TRUE);
            }
            else
              tab_it.remove();
          }
          else
          {
            if (found_first)
              found_last= TRUE;
          }
        } while (++part_count < tab_part_info->no_parts);
        if (drop_count != no_parts_reorged)
        {
          my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "REORGANIZE");
          DBUG_RETURN(TRUE);
        }
        if (tab_part_info->part_type == RANGE_PARTITION &&
            ((is_last_partition_reorged &&
               alt_max_range < tab_max_range) ||
              (!is_last_partition_reorged &&
               alt_max_range != tab_max_range)))
        {
          /*
            For range partitioning the total resulting range before and
            after the change must be the same except in one case. This is
            when the last partition is reorganised, in this case it is
            acceptable to increase the total range.
            The reason is that it is not allowed to have "holes" in the
            middle of the ranges and thus we should not allow to reorganise
            to create "holes". Also we should not allow using REORGANIZE
            to drop data.
          */
          my_error(ER_REORG_OUTSIDE_RANGE, MYF(0));
          DBUG_RETURN(TRUE);
        }
        tab_part_info->no_parts= check_total_partitions;
      }
    }
    else
    {
      DBUG_ASSERT(FALSE);
    }
    *partition_changed= TRUE;
unknown's avatar
unknown committed
4459
    thd->work_part_info= tab_part_info;
unknown's avatar
unknown committed
4460 4461 4462
    if (alter_info->flags == ALTER_ADD_PARTITION ||
        alter_info->flags == ALTER_REORGANIZE_PARTITION)
    {
4463
      if (tab_part_info->use_default_subpartitions &&
4464 4465 4466 4467 4468
          !alt_part_info->use_default_subpartitions)
      {
        tab_part_info->use_default_subpartitions= FALSE;
        tab_part_info->use_default_no_subpartitions= FALSE;
      }
unknown's avatar
unknown committed
4469
      if (tab_part_info->check_partition_info((handlerton**)NULL,
4470
                                              table->file, ULL(0)))
unknown's avatar
unknown committed
4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491
      {
        DBUG_RETURN(TRUE);
      }
    }
  }
  else
  {
    /*
     When thd->lex->part_info has a reference to a partition_info the
     ALTER TABLE contained a definition of a partitioning.

     Case I:
       If there was a partition before and there is a new one defined.
       We use the new partitioning. The new partitioning is already
       defined in the correct variable so no work is needed to
       accomplish this.
       We do however need to update partition_changed to ensure that not
       only the frm file is changed in the ALTER TABLE command.

     Case IIa:
       There was a partitioning before and there is no new one defined.
unknown's avatar
unknown committed
4492
       Also the user has not specified to remove partitioning explicitly.
unknown's avatar
unknown committed
4493 4494 4495 4496 4497 4498 4499 4500

       We use the old partitioning also for the new table. We do this
       by assigning the partition_info from the table loaded in
       open_ltable to the partition_info struct used by mysql_create_table
       later in this method.

     Case IIb:
       There was a partitioning before and there is no new one defined.
unknown's avatar
unknown committed
4501
       The user has specified explicitly to remove partitioning
unknown's avatar
unknown committed
4502

unknown's avatar
unknown committed
4503 4504 4505
       Since the user has specified explicitly to remove partitioning
       we override the old partitioning info and create a new table using
       the specified engine.
unknown's avatar
unknown committed
4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527
       In this case the partition also is changed.

     Case III:
       There was no partitioning before altering the table, there is
       partitioning defined in the altered table. Use the new partitioning.
       No work needed since the partitioning info is already in the
       correct variable.

       In this case we discover one case where the new partitioning is using
       the same partition function as the default (PARTITION BY KEY or
       PARTITION BY LINEAR KEY with the list of fields equal to the primary
       key fields OR PARTITION BY [LINEAR] KEY() for tables without primary
       key)
       Also here partition has changed and thus a new table must be
       created.

     Case IV:
       There was no partitioning before and no partitioning defined.
       Obviously no work needed.
    */
    if (table->part_info)
    {
4528
      if (alter_info->flags & ALTER_REMOVE_PARTITIONING)
unknown's avatar
unknown committed
4529 4530
      {
        DBUG_PRINT("info", ("Remove partitioning"));
4531
        if (!(create_info->used_fields & HA_CREATE_USED_ENGINE))
unknown's avatar
unknown committed
4532 4533 4534 4535
        {
          DBUG_PRINT("info", ("No explicit engine used"));
          create_info->db_type= table->part_info->default_engine_type;
        }
unknown's avatar
unknown committed
4536 4537
        DBUG_PRINT("info", ("New engine type: %s",
                   hton2plugin[create_info->db_type->slot]->name.str));
4538
        thd->work_part_info= NULL;
unknown's avatar
unknown committed
4539 4540
        *partition_changed= TRUE;
      }
4541
      else if (!thd->work_part_info)
unknown's avatar
unknown committed
4542 4543 4544 4545 4546
      {
        /*
          Retain partitioning but possibly with a new storage engine
          beneath.
        */
unknown's avatar
unknown committed
4547
        thd->work_part_info= table->part_info;
4548
        if (create_info->used_fields & HA_CREATE_USED_ENGINE &&
unknown's avatar
unknown committed
4549 4550 4551 4552 4553
            create_info->db_type != table->part_info->default_engine_type)
        {
          /*
            Make sure change of engine happens to all partitions.
          */
4554
          DBUG_PRINT("info", ("partition changed"));
4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570
          if (table->part_info->is_auto_partitioned)
          {
            /*
              If the user originally didn't specify partitioning to be
              used we can remove it now.
            */
            thd->work_part_info= NULL;
          }
          else
          {
            /*
              Ensure that all partitions have the proper engine set-up
            */
            set_engine_all_partitions(thd->work_part_info,
                                      create_info->db_type);
          }
unknown's avatar
unknown committed
4571 4572 4573
          *partition_changed= TRUE;
        }
      }
unknown's avatar
unknown committed
4574
    }
unknown's avatar
unknown committed
4575
    if (thd->work_part_info)
unknown's avatar
unknown committed
4576
    {
unknown's avatar
unknown committed
4577
      partition_info *part_info= thd->work_part_info;
unknown's avatar
unknown committed
4578
      bool is_native_partitioned= FALSE;
unknown's avatar
unknown committed
4579 4580 4581 4582
      /*
        Need to cater for engine types that can handle partition without
        using the partition handler.
      */
unknown's avatar
unknown committed
4583
      if (thd->work_part_info != table->part_info)
4584 4585
      {
        DBUG_PRINT("info", ("partition changed"));
unknown's avatar
unknown committed
4586
        *partition_changed= TRUE;
4587
      }
unknown's avatar
unknown committed
4588
      if (create_info->db_type == &partition_hton)
unknown's avatar
unknown committed
4589 4590 4591 4592 4593
        part_info->default_engine_type= table->part_info->default_engine_type;
      else
        part_info->default_engine_type= create_info->db_type;
      if (check_native_partitioned(create_info, &is_native_partitioned,
                                   part_info, thd))
unknown's avatar
unknown committed
4594
      {
unknown's avatar
unknown committed
4595
        DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
4596
      }
unknown's avatar
unknown committed
4597
      if (!is_native_partitioned)
unknown's avatar
unknown committed
4598
      {
unknown's avatar
unknown committed
4599
        DBUG_ASSERT(create_info->db_type);
unknown's avatar
unknown committed
4600
        create_info->db_type= &partition_hton;
unknown's avatar
unknown committed
4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636
      }
    }
  }
  DBUG_RETURN(FALSE);
}


/*
  Change partitions, used to implement ALTER TABLE ADD/REORGANIZE/COALESCE
  partitions. This method is used to implement both single-phase and multi-
  phase implementations of ADD/REORGANIZE/COALESCE partitions.

  SYNOPSIS
    mysql_change_partitions()
    lpt                        Struct containing parameters

  RETURN VALUES
    TRUE                          Failure
    FALSE                         Success

  DESCRIPTION
    Request handler to add partitions as set in states of the partition

    Elements of the lpt parameters used:
    create_info                Create information used to create partitions
    db                         Database name
    table_name                 Table name
    copied                     Output parameter where number of copied
                               records are added
    deleted                    Output parameter where number of deleted
                               records are added
*/

static bool mysql_change_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
{
  char path[FN_REFLEN+1];
4637 4638
  int error;
  handler *file= lpt->table->file;
unknown's avatar
unknown committed
4639 4640 4641
  DBUG_ENTER("mysql_change_partitions");

  build_table_filename(path, sizeof(path), lpt->db, lpt->table_name, "");
4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652
  if ((error= file->change_partitions(lpt->create_info, path, &lpt->copied,
                                      &lpt->deleted, lpt->pack_frm_data,
                                      lpt->pack_frm_len)))
  {
    if (error != ER_OUTOFMEMORY)
      file->print_error(error, MYF(0));
    else
      lpt->thd->fatal_error();
    DBUG_RETURN(TRUE);
  }
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677
}


/*
  Rename partitions in an ALTER TABLE of partitions

  SYNOPSIS
    mysql_rename_partitions()
    lpt                        Struct containing parameters

  RETURN VALUES
    TRUE                          Failure
    FALSE                         Success

  DESCRIPTION
    Request handler to rename partitions as set in states of the partition

    Parameters used:
    db                         Database name
    table_name                 Table name
*/

static bool mysql_rename_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
{
  char path[FN_REFLEN+1];
4678
  int error;
unknown's avatar
unknown committed
4679 4680 4681
  DBUG_ENTER("mysql_rename_partitions");

  build_table_filename(path, sizeof(path), lpt->db, lpt->table_name, "");
4682 4683 4684 4685 4686 4687 4688
  if ((error= lpt->table->file->rename_partitions(path)))
  {
    if (error != 1)
      lpt->table->file->print_error(error, MYF(0));
    DBUG_RETURN(TRUE);
  }
  DBUG_RETURN(FALSE);
unknown's avatar
unknown committed
4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718
}


/*
  Drop partitions in an ALTER TABLE of partitions

  SYNOPSIS
    mysql_drop_partitions()
    lpt                        Struct containing parameters

  RETURN VALUES
    TRUE                          Failure
    FALSE                         Success
  DESCRIPTION
    Drop the partitions marked with PART_TO_BE_DROPPED state and remove
    those partitions from the list.

    Parameters used:
    table                       Table object
    db                          Database name
    table_name                  Table name
*/

static bool mysql_drop_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
{
  char path[FN_REFLEN+1];
  partition_info *part_info= lpt->table->part_info;
  List_iterator<partition_element> part_it(part_info->partitions);
  uint i= 0;
  uint remove_count= 0;
4719
  int error;
unknown's avatar
unknown committed
4720 4721 4722
  DBUG_ENTER("mysql_drop_partitions");

  build_table_filename(path, sizeof(path), lpt->db, lpt->table_name, "");
4723
  if ((error= lpt->table->file->drop_partitions(path)))
unknown's avatar
unknown committed
4724
  {
4725
    lpt->table->file->print_error(error, MYF(0));
unknown's avatar
unknown committed
4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741
    DBUG_RETURN(TRUE);
  }
  do
  {
    partition_element *part_elem= part_it++;
    if (part_elem->part_state == PART_IS_DROPPED)
    {
      part_it.remove();
      remove_count++;
    }
  } while (++i < part_info->no_parts);
  part_info->no_parts-= remove_count;
  DBUG_RETURN(FALSE);
}


4742 4743 4744 4745 4746 4747 4748 4749 4750
/*
  Insert log entry into list
  SYNOPSIS
    insert_part_info_log_entry_list()
    log_entry
  RETURN VALUES
    NONE
*/

4751 4752
static void insert_part_info_log_entry_list(partition_info *part_info,
                                            DDL_LOG_MEMORY_ENTRY *log_entry)
4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767
{
  log_entry->next_active_log_entry= part_info->first_log_entry;
  part_info->first_log_entry= log_entry;
}


/*
  Release all log entries for this partition info struct
  SYNOPSIS
    release_part_info_log_entries()
    first_log_entry                 First log entry in list to release
  RETURN VALUES
    NONE
*/

4768
static void release_part_info_log_entries(DDL_LOG_MEMORY_ENTRY *log_entry)
4769 4770 4771 4772 4773
{
  DBUG_ENTER("release_part_info_log_entries");

  while (log_entry)
  {
4774
    release_ddl_log_memory_entry(log_entry);
4775
    log_entry= log_entry->next_active_log_entry;
4776 4777 4778 4779 4780
  }
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
4781
/*
4782
  Log an delete/rename frm file
unknown's avatar
unknown committed
4783
  SYNOPSIS
4784
    write_log_replace_delete_frm()
4785 4786
    lpt                            Struct for parameters
    next_entry                     Next reference to use in log record
4787 4788 4789
    from_path                      Name to rename from
    to_path                        Name to rename to
    replace_flag                   TRUE if replace, else delete
unknown's avatar
unknown committed
4790
  RETURN VALUES
4791 4792
    TRUE                           Error
    FALSE                          Success
unknown's avatar
unknown committed
4793
  DESCRIPTION
4794
    Support routine that writes a replace or delete of an frm file into the
4795
    ddl log. It also inserts an entry that keeps track of used space into
4796
    the partition info object
unknown's avatar
unknown committed
4797 4798
*/

4799 4800 4801 4802 4803
static bool write_log_replace_delete_frm(ALTER_PARTITION_PARAM_TYPE *lpt,
                                         uint next_entry,
                                         const char *from_path,
                                         const char *to_path,
                                         bool replace_flag)
unknown's avatar
unknown committed
4804
{
4805 4806
  DDL_LOG_ENTRY ddl_log_entry;
  DDL_LOG_MEMORY_ENTRY *log_entry;
4807
  DBUG_ENTER("write_log_replace_delete_frm");
unknown's avatar
unknown committed
4808

4809
  if (replace_flag)
4810
    ddl_log_entry.action_type= DDL_LOG_REPLACE_ACTION;
4811
  else
4812 4813
    ddl_log_entry.action_type= DDL_LOG_DELETE_ACTION;
  ddl_log_entry.next_entry= next_entry;
4814
  ddl_log_entry.handler_name= reg_ext;
4815
  ddl_log_entry.name= to_path;
4816
  if (replace_flag)
4817 4818
    ddl_log_entry.from_name= from_path;
  if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
4819 4820 4821
  {
    DBUG_RETURN(TRUE);
  }
4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834
  insert_part_info_log_entry_list(lpt->part_info, log_entry);
  DBUG_RETURN(FALSE);
}


/*
  Log final partition changes in change partition
  SYNOPSIS
    write_log_changed_partitions()
    lpt                      Struct containing parameters
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846
  DESCRIPTION
    This code is used to perform safe ADD PARTITION for HASH partitions
    and COALESCE for HASH partitions and REORGANIZE for any type of
    partitions.
    We prepare entries for all partitions except the reorganised partitions
    in REORGANIZE partition, those are handled by
    write_log_dropped_partitions. For those partitions that are replaced
    special care is needed to ensure that this is performed correctly and
    this requires a two-phased approach with this log as a helper for this.

    This code is closely intertwined with the code in rename_partitions in
    the partition handler.
4847 4848
*/

4849 4850
static bool write_log_changed_partitions(ALTER_PARTITION_PARAM_TYPE *lpt,
                                         uint *next_entry, const char *path)
4851
{
4852
  DDL_LOG_ENTRY ddl_log_entry;
4853
  partition_info *part_info= lpt->part_info;
4854
  DDL_LOG_MEMORY_ENTRY *log_entry;
4855 4856 4857 4858 4859 4860
  char tmp_path[FN_LEN];
  char normal_path[FN_LEN];
  List_iterator<partition_element> part_it(part_info->partitions);
  uint temp_partitions= part_info->temp_partitions.elements;
  uint no_elements= part_info->partitions.elements;
  uint i= 0;
4861
  DBUG_ENTER("write_log_changed_partitions");
4862 4863 4864 4865 4866 4867 4868

  do
  {
    partition_element *part_elem= part_it++;
    if (part_elem->part_state == PART_IS_CHANGED ||
        (part_elem->part_state == PART_IS_ADDED && temp_partitions))
    {
unknown's avatar
unknown committed
4869
      if (part_info->is_sub_partitioned())
4870 4871 4872 4873 4874 4875 4876
      {
        List_iterator<partition_element> sub_it(part_elem->subpartitions);
        uint no_subparts= part_info->no_subparts;
        uint j= 0;
        do
        {
          partition_element *sub_elem= sub_it++;
4877 4878
          ddl_log_entry.next_entry= *next_entry;
          ddl_log_entry.handler_name=
4879 4880 4881 4882 4883 4884 4885 4886 4887
               ha_resolve_storage_engine_name(sub_elem->engine_type);
          create_subpartition_name(tmp_path, path,
                                   part_elem->partition_name,
                                   sub_elem->partition_name,
                                   TEMP_PART_NAME);
          create_subpartition_name(normal_path, path,
                                   part_elem->partition_name,
                                   sub_elem->partition_name,
                                   NORMAL_PART_NAME);
4888 4889
          ddl_log_entry.name= normal_path;
          ddl_log_entry.from_name= tmp_path;
4890
          if (part_elem->part_state == PART_IS_CHANGED)
4891
            ddl_log_entry.action_type= DDL_LOG_REPLACE_ACTION;
4892
          else
4893 4894
            ddl_log_entry.action_type= DDL_LOG_RENAME_ACTION;
          if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
4895 4896 4897 4898 4899 4900 4901 4902 4903 4904
          {
            DBUG_RETURN(TRUE);
          }
          *next_entry= log_entry->entry_pos;
          sub_elem->log_entry= log_entry;
          insert_part_info_log_entry_list(part_info, log_entry);
        } while (++j < no_subparts);
      }
      else
      {
4905 4906
        ddl_log_entry.next_entry= *next_entry;
        ddl_log_entry.handler_name=
4907 4908 4909 4910 4911 4912 4913
               ha_resolve_storage_engine_name(part_elem->engine_type);
        create_partition_name(tmp_path, path,
                              part_elem->partition_name,
                              TEMP_PART_NAME, TRUE);
        create_partition_name(normal_path, path,
                              part_elem->partition_name,
                              NORMAL_PART_NAME, TRUE);
4914 4915
        ddl_log_entry.name= normal_path;
        ddl_log_entry.from_name= tmp_path;
4916
        if (part_elem->part_state == PART_IS_CHANGED)
4917
          ddl_log_entry.action_type= DDL_LOG_REPLACE_ACTION;
4918
        else
4919 4920
          ddl_log_entry.action_type= DDL_LOG_RENAME_ACTION;
        if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
4921 4922 4923 4924
        {
          DBUG_RETURN(TRUE);
        }
        *next_entry= log_entry->entry_pos;
unknown's avatar
unknown committed
4925
        part_elem->log_entry= log_entry;
4926 4927 4928
        insert_part_info_log_entry_list(part_info, log_entry);
      }
    }
unknown's avatar
unknown committed
4929
  } while (++i < no_elements);
4930
  DBUG_RETURN(FALSE);
4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943
}


/*
  Log dropped partitions
  SYNOPSIS
    write_log_dropped_partitions()
    lpt                      Struct containing parameters
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
*/

4944 4945 4946 4947
static bool write_log_dropped_partitions(ALTER_PARTITION_PARAM_TYPE *lpt,
                                         uint *next_entry,
                                         const char *path,
                                         bool temp_list)
4948
{
4949
  DDL_LOG_ENTRY ddl_log_entry;
4950
  partition_info *part_info= lpt->part_info;
4951
  DDL_LOG_MEMORY_ENTRY *log_entry;
4952 4953
  char tmp_path[FN_LEN];
  List_iterator<partition_element> part_it(part_info->partitions);
4954 4955
  List_iterator<partition_element> temp_it(part_info->temp_partitions);
  uint no_temp_partitions= part_info->temp_partitions.elements;
4956
  uint no_elements= part_info->partitions.elements;
4957
  uint i= 0;
4958 4959
  DBUG_ENTER("write_log_dropped_partitions");

4960
  ddl_log_entry.action_type= DDL_LOG_DELETE_ACTION;
4961 4962 4963
  if (temp_list)
    no_elements= no_temp_partitions;
  while (no_elements--)
4964
  {
4965 4966 4967 4968 4969
    partition_element *part_elem;
    if (temp_list)
      part_elem= temp_it++;
    else
      part_elem= part_it++;
4970
    if (part_elem->part_state == PART_TO_BE_DROPPED ||
4971 4972
        part_elem->part_state == PART_TO_BE_ADDED ||
        part_elem->part_state == PART_CHANGED)
4973
    {
4974 4975 4976 4977 4978 4979 4980
      uint name_variant;
      if (part_elem->part_state == PART_CHANGED ||
          (part_elem->part_state == PART_TO_BE_ADDED &&
           no_temp_partitions))
        name_variant= TEMP_PART_NAME;
      else
        name_variant= NORMAL_PART_NAME;
unknown's avatar
unknown committed
4981
      if (part_info->is_sub_partitioned())
4982 4983 4984
      {
        List_iterator<partition_element> sub_it(part_elem->subpartitions);
        uint no_subparts= part_info->no_subparts;
4985
        uint j= 0;
4986 4987 4988
        do
        {
          partition_element *sub_elem= sub_it++;
4989 4990
          ddl_log_entry.next_entry= *next_entry;
          ddl_log_entry.handler_name=
4991
               ha_resolve_storage_engine_name(sub_elem->engine_type);
4992 4993 4994
          create_subpartition_name(tmp_path, path,
                                   part_elem->partition_name,
                                   sub_elem->partition_name,
4995
                                   name_variant);
4996 4997
          ddl_log_entry.name= tmp_path;
          if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
4998 4999 5000 5001
          {
            DBUG_RETURN(TRUE);
          }
          *next_entry= log_entry->entry_pos;
5002
          sub_elem->log_entry= log_entry;
5003
          insert_part_info_log_entry_list(part_info, log_entry);
5004
        } while (++j < no_subparts);
5005 5006 5007
      }
      else
      {
5008 5009
        ddl_log_entry.next_entry= *next_entry;
        ddl_log_entry.handler_name=
5010 5011 5012
               ha_resolve_storage_engine_name(part_elem->engine_type);
        create_partition_name(tmp_path, path,
                              part_elem->partition_name,
5013
                              name_variant, TRUE);
5014 5015
        ddl_log_entry.name= tmp_path;
        if (write_ddl_log_entry(&ddl_log_entry, &log_entry))
5016 5017 5018 5019
        {
          DBUG_RETURN(TRUE);
        }
        *next_entry= log_entry->entry_pos;
5020
        part_elem->log_entry= log_entry;
5021 5022 5023
        insert_part_info_log_entry_list(part_info, log_entry);
      }
    }
5024
  }
unknown's avatar
unknown committed
5025 5026 5027 5028
  DBUG_RETURN(FALSE);
}


5029
/*
5030
  Set execute log entry in ddl log for this partitioned table
5031 5032 5033 5034 5035 5036 5037 5038
  SYNOPSIS
    set_part_info_exec_log_entry()
    part_info                      Partition info object
    exec_log_entry                 Log entry
  RETURN VALUES
    NONE
*/

5039 5040
static void set_part_info_exec_log_entry(partition_info *part_info,
                                         DDL_LOG_MEMORY_ENTRY *exec_log_entry)
5041 5042 5043 5044 5045 5046
{
  part_info->exec_log_entry= exec_log_entry;
  exec_log_entry->next_active_log_entry= NULL;
}


unknown's avatar
unknown committed
5047
/*
5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058
  Write the log entry to ensure that the shadow frm file is removed at
  crash.
  SYNOPSIS
    write_log_drop_shadow_frm()
    lpt                      Struct containing parameters
    install_frm              Should we log action to install shadow frm or should
                             the action be to remove the shadow frm file.
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
  DESCRIPTION
5059
    Prepare an entry to the ddl log indicating a drop/install of the shadow frm
5060 5061 5062
    file and its corresponding handler file.
*/

5063
static bool write_log_drop_shadow_frm(ALTER_PARTITION_PARAM_TYPE *lpt)
5064
{
5065
  DDL_LOG_ENTRY ddl_log_entry;
5066
  partition_info *part_info= lpt->part_info;
5067 5068
  DDL_LOG_MEMORY_ENTRY *log_entry;
  DDL_LOG_MEMORY_ENTRY *exec_log_entry= NULL;
5069 5070
  char shadow_path[FN_LEN];
  DBUG_ENTER("write_log_drop_shadow_frm");
unknown's avatar
unknown committed
5071

5072 5073
  build_table_filename(shadow_path, sizeof(shadow_path), lpt->db,
                       lpt->table_name, "#");
5074
  pthread_mutex_lock(&LOCK_gdl);
5075 5076 5077 5078 5079 5080 5081
  if (write_log_replace_delete_frm(lpt, 0UL, NULL,
                                  (const char*)shadow_path, FALSE))
    goto error;
  log_entry= part_info->first_log_entry;
  if (write_execute_ddl_log_entry(log_entry->entry_pos,
                                    FALSE, &exec_log_entry))
    goto error;
5082
  pthread_mutex_unlock(&LOCK_gdl);
5083 5084 5085 5086
  set_part_info_exec_log_entry(part_info, exec_log_entry);
  DBUG_RETURN(FALSE);

error:
5087
  release_part_info_log_entries(part_info->first_log_entry);
5088
  pthread_mutex_unlock(&LOCK_gdl);
5089
  part_info->first_log_entry= NULL;
5090
  my_error(ER_DDL_LOG_ERROR, MYF(0));
5091 5092 5093 5094 5095 5096
  DBUG_RETURN(TRUE);
}


/*
  Log renaming of shadow frm to real frm name and dropping of old frm
unknown's avatar
unknown committed
5097
  SYNOPSIS
5098
    write_log_rename_frm()
unknown's avatar
unknown committed
5099 5100 5101 5102 5103
    lpt                      Struct containing parameters
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
  DESCRIPTION
5104 5105
    Prepare an entry to ensure that we complete the renaming of the frm
    file if failure occurs in the middle of the rename process.
unknown's avatar
unknown committed
5106 5107
*/

5108
static bool write_log_rename_frm(ALTER_PARTITION_PARAM_TYPE *lpt)
unknown's avatar
unknown committed
5109
{
5110
  DDL_LOG_ENTRY ddl_log_entry;
5111
  partition_info *part_info= lpt->part_info;
5112 5113
  DDL_LOG_MEMORY_ENTRY *log_entry;
  DDL_LOG_MEMORY_ENTRY *exec_log_entry= part_info->exec_log_entry;
5114
  char path[FN_LEN];
5115
  char shadow_path[FN_LEN];
5116
  DDL_LOG_MEMORY_ENTRY *old_first_log_entry= part_info->first_log_entry;
5117
  DBUG_ENTER("write_log_rename_frm");
unknown's avatar
unknown committed
5118

5119 5120 5121 5122 5123
  part_info->first_log_entry= NULL;
  build_table_filename(path, sizeof(path), lpt->db,
                       lpt->table_name, "");
  build_table_filename(shadow_path, sizeof(shadow_path), lpt->db,
                       lpt->table_name, "#");
5124
  pthread_mutex_lock(&LOCK_gdl);
5125
  if (write_log_replace_delete_frm(lpt, 0UL, shadow_path, path, TRUE))
5126 5127 5128 5129 5130 5131 5132
    goto error;
  log_entry= part_info->first_log_entry;
  part_info->frm_log_entry= log_entry;
  if (write_execute_ddl_log_entry(log_entry->entry_pos,
                                    FALSE, &exec_log_entry))
    goto error;
  release_part_info_log_entries(old_first_log_entry);
5133
  pthread_mutex_unlock(&LOCK_gdl);
5134 5135 5136
  DBUG_RETURN(FALSE);

error:
5137
  release_part_info_log_entries(part_info->first_log_entry);
5138
  pthread_mutex_unlock(&LOCK_gdl);
5139
  part_info->first_log_entry= old_first_log_entry;
5140
  part_info->frm_log_entry= NULL;
5141
  my_error(ER_DDL_LOG_ERROR, MYF(0));
5142
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5143 5144 5145 5146
}


/*
5147 5148
  Write the log entries to ensure that the drop partition command is completed
  even in the presence of a crash.
unknown's avatar
unknown committed
5149 5150

  SYNOPSIS
5151
    write_log_drop_partition()
unknown's avatar
unknown committed
5152 5153 5154 5155 5156
    lpt                      Struct containing parameters
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
  DESCRIPTION
5157
    Prepare entries to the ddl log indicating all partitions to drop and to
5158
    install the shadow frm file and remove the old frm file.
unknown's avatar
unknown committed
5159 5160
*/

5161
static bool write_log_drop_partition(ALTER_PARTITION_PARAM_TYPE *lpt)
unknown's avatar
unknown committed
5162
{
5163
  DDL_LOG_ENTRY ddl_log_entry;
5164
  partition_info *part_info= lpt->part_info;
5165 5166
  DDL_LOG_MEMORY_ENTRY *log_entry;
  DDL_LOG_MEMORY_ENTRY *exec_log_entry= part_info->exec_log_entry;
5167 5168
  char tmp_path[FN_LEN];
  char path[FN_LEN];
5169
  uint next_entry= 0;
5170
  DDL_LOG_MEMORY_ENTRY *old_first_log_entry= part_info->first_log_entry;
5171
  DBUG_ENTER("write_log_drop_partition");
unknown's avatar
unknown committed
5172

5173 5174 5175
  part_info->first_log_entry= NULL;
  build_table_filename(path, sizeof(path), lpt->db,
                       lpt->table_name, "");
5176 5177
  build_table_filename(tmp_path, sizeof(tmp_path), lpt->db,
                       lpt->table_name, "#");
5178
  pthread_mutex_lock(&LOCK_gdl);
5179 5180 5181
  if (write_log_dropped_partitions(lpt, &next_entry, (const char*)path,
                                   FALSE))
    goto error;
5182 5183
  if (write_log_replace_delete_frm(lpt, next_entry, (const char*)tmp_path,
                                  (const char*)path, TRUE))
5184 5185 5186 5187 5188 5189 5190
    goto error;
  log_entry= part_info->first_log_entry;
  part_info->frm_log_entry= log_entry;
  if (write_execute_ddl_log_entry(log_entry->entry_pos,
                                    FALSE, &exec_log_entry))
    goto error;
  release_part_info_log_entries(old_first_log_entry);
5191
  pthread_mutex_unlock(&LOCK_gdl);
5192 5193 5194
  DBUG_RETURN(FALSE);

error:
5195
  release_part_info_log_entries(part_info->first_log_entry);
5196
  pthread_mutex_unlock(&LOCK_gdl);
5197
  part_info->first_log_entry= old_first_log_entry;
5198
  part_info->frm_log_entry= NULL;
5199
  my_error(ER_DDL_LOG_ERROR, MYF(0));
5200
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5201 5202 5203 5204
}


/*
5205 5206 5207
  Write the log entries to ensure that the add partition command is not
  executed at all if a crash before it has completed

unknown's avatar
unknown committed
5208
  SYNOPSIS
5209
    write_log_add_change_partition()
unknown's avatar
unknown committed
5210 5211 5212 5213 5214
    lpt                      Struct containing parameters
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
  DESCRIPTION
5215
    Prepare entries to the ddl log indicating all partitions to drop and to
5216
    remove the shadow frm file.
5217
    We always inject entries backwards in the list in the ddl log since we
5218
    don't know the entry position until we have written it.
unknown's avatar
unknown committed
5219 5220
*/

5221
static bool write_log_add_change_partition(ALTER_PARTITION_PARAM_TYPE *lpt)
unknown's avatar
unknown committed
5222
{
5223
  partition_info *part_info= lpt->part_info;
5224 5225
  DDL_LOG_MEMORY_ENTRY *log_entry;
  DDL_LOG_MEMORY_ENTRY *exec_log_entry= NULL;
5226 5227 5228 5229
  char tmp_path[FN_LEN];
  char path[FN_LEN];
  uint next_entry= 0;
  DBUG_ENTER("write_log_add_change_partition");
unknown's avatar
unknown committed
5230

5231 5232
  build_table_filename(path, sizeof(path), lpt->db,
                       lpt->table_name, "");
5233 5234
  build_table_filename(tmp_path, sizeof(tmp_path), lpt->db,
                       lpt->table_name, "#");
5235
  pthread_mutex_lock(&LOCK_gdl);
5236 5237 5238 5239 5240 5241 5242 5243 5244 5245
  if (write_log_dropped_partitions(lpt, &next_entry, (const char*)path,
                                   FALSE))
    goto error;
  if (write_log_replace_delete_frm(lpt, next_entry, NULL, tmp_path,
                                  FALSE))
    goto error;
  log_entry= part_info->first_log_entry;
  if (write_execute_ddl_log_entry(log_entry->entry_pos,
                                    FALSE, &exec_log_entry))
    goto error;
5246
  pthread_mutex_unlock(&LOCK_gdl);
5247 5248 5249 5250
  set_part_info_exec_log_entry(part_info, exec_log_entry);
  DBUG_RETURN(FALSE);

error:
5251
  release_part_info_log_entries(part_info->first_log_entry);
5252
  pthread_mutex_unlock(&LOCK_gdl);
5253
  part_info->first_log_entry= NULL;
5254
  my_error(ER_DDL_LOG_ERROR, MYF(0));
5255
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5256 5257 5258 5259 5260 5261 5262 5263
}


/*
  Write description of how to complete the operation after first phase of
  change partitions.

  SYNOPSIS
5264
    write_log_final_change_partition()
unknown's avatar
unknown committed
5265 5266 5267 5268 5269 5270 5271 5272 5273 5274
    lpt                      Struct containing parameters
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
  DESCRIPTION
    We will write log entries that specify to remove all partitions reorganised,
    to rename others to reflect the new naming scheme and to install the shadow
    frm file.
*/

5275
static bool write_log_final_change_partition(ALTER_PARTITION_PARAM_TYPE *lpt)
unknown's avatar
unknown committed
5276
{
5277
  DDL_LOG_ENTRY ddl_log_entry;
5278
  partition_info *part_info= lpt->part_info;
5279 5280
  DDL_LOG_MEMORY_ENTRY *log_entry;
  DDL_LOG_MEMORY_ENTRY *exec_log_entry= part_info->exec_log_entry;
5281
  char path[FN_LEN];
5282
  char shadow_path[FN_LEN];
5283
  DDL_LOG_MEMORY_ENTRY *old_first_log_entry= part_info->first_log_entry;
5284 5285
  uint next_entry= 0;
  DBUG_ENTER("write_log_final_change_partition");
unknown's avatar
unknown committed
5286

5287 5288 5289 5290 5291
  part_info->first_log_entry= NULL;
  build_table_filename(path, sizeof(path), lpt->db,
                       lpt->table_name, "");
  build_table_filename(shadow_path, sizeof(shadow_path), lpt->db,
                       lpt->table_name, "#");
5292
  pthread_mutex_lock(&LOCK_gdl);
5293
  if (write_log_dropped_partitions(lpt, &next_entry, (const char*)path,
5294
                      lpt->alter_info->flags & ALTER_REORGANIZE_PARTITION))
5295 5296 5297
    goto error;
  if (write_log_changed_partitions(lpt, &next_entry, (const char*)path))
    goto error;
5298
  if (write_log_replace_delete_frm(lpt, 0UL, shadow_path, path, TRUE))
5299 5300 5301 5302 5303 5304 5305
    goto error;
  log_entry= part_info->first_log_entry;
  part_info->frm_log_entry= log_entry;
  if (write_execute_ddl_log_entry(log_entry->entry_pos,
                                    FALSE, &exec_log_entry))
    goto error;
  release_part_info_log_entries(old_first_log_entry);
5306
  pthread_mutex_unlock(&LOCK_gdl);
5307 5308 5309
  DBUG_RETURN(FALSE);

error:
5310
  release_part_info_log_entries(part_info->first_log_entry);
5311
  pthread_mutex_unlock(&LOCK_gdl);
5312
  part_info->first_log_entry= old_first_log_entry;
5313
  part_info->frm_log_entry= NULL;
5314
  my_error(ER_DDL_LOG_ERROR, MYF(0));
5315
  DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5316 5317 5318
}


5319
/*
5320
  Remove entry from ddl log and release resources for others to use
5321 5322 5323 5324 5325 5326 5327 5328

  SYNOPSIS
    write_log_completed()
    lpt                      Struct containing parameters
  RETURN VALUES
    TRUE                     Error
    FALSE                    Success
*/
5329

5330 5331
static void write_log_completed(ALTER_PARTITION_PARAM_TYPE *lpt,
                                bool dont_crash)
5332
{
5333
  partition_info *part_info= lpt->part_info;
5334
  uint count_loop= 0;
5335
  bool not_success;
5336
  DDL_LOG_MEMORY_ENTRY *log_entry= part_info->exec_log_entry;
5337
  DBUG_ENTER("write_log_completed");
unknown's avatar
unknown committed
5338

5339
  DBUG_ASSERT(log_entry);
5340
  pthread_mutex_lock(&LOCK_gdl);
5341
  if (write_execute_ddl_log_entry(0UL, TRUE, &log_entry))
5342 5343
  {
    /*
5344
      Failed to write, Bad...
5345 5346
      We have completed the operation but have log records to REMOVE
      stuff that shouldn't be removed. What clever things could one do
5347 5348
      here? An error output was written to the error output by the
      above method so we don't do anything here.
5349
    */
5350
    ;
5351 5352 5353
  }
  release_part_info_log_entries(part_info->first_log_entry);
  release_part_info_log_entries(part_info->exec_log_entry);
5354
  pthread_mutex_unlock(&LOCK_gdl);
5355 5356
  part_info->exec_log_entry= NULL;
  part_info->first_log_entry= NULL;
5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369
  DBUG_VOID_RETURN;
}


/*
   Release all log entries
   SYNOPSIS
     release_log_entries()
     part_info                  Partition info struct
   RETURN VALUES
     NONE
*/

5370
static void release_log_entries(partition_info *part_info)
5371
{
5372
  pthread_mutex_lock(&LOCK_gdl);
5373 5374
  release_part_info_log_entries(part_info->first_log_entry);
  release_part_info_log_entries(part_info->exec_log_entry);
5375
  pthread_mutex_unlock(&LOCK_gdl);
5376 5377
  part_info->first_log_entry= NULL;
  part_info->exec_log_entry= NULL;
5378 5379 5380
}


5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397
/*
  Get a lock on table name to avoid that anyone can open the table in
  a critical part of the ALTER TABLE.
  SYNOPSIS
    get_name_lock()
    lpt                        Struct carrying parameters
  RETURN VALUES
    FALSE                      Success
    TRUE                       Failure
*/

static int get_name_lock(ALTER_PARTITION_PARAM_TYPE *lpt)
{
  int error= 0;
  DBUG_ENTER("get_name_lock");

  bzero(&lpt->table_list, sizeof(lpt->table_list));
5398
  lpt->table_list.db= (char*)lpt->db;
5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453
  lpt->table_list.table= lpt->table;
  lpt->table_list.table_name= (char*)lpt->table_name;
  pthread_mutex_lock(&LOCK_open);
  error= lock_table_name(lpt->thd, &lpt->table_list, FALSE);
  pthread_mutex_unlock(&LOCK_open);
  DBUG_RETURN(error);
}


/*
  Unlock and close table before renaming and dropping partitions
  SYNOPSIS
    alter_close_tables()
    lpt                        Struct carrying parameters
  RETURN VALUES
    0
*/

static int alter_close_tables(ALTER_PARTITION_PARAM_TYPE *lpt)
{
  THD *thd= lpt->thd;
  TABLE *table= lpt->table;
  DBUG_ENTER("alter_close_tables");
  /*
    We need to also unlock tables and close all handlers.
    We set lock to zero to ensure we don't do this twice
    and we set db_stat to zero to ensure we don't close twice.
  */
  mysql_unlock_tables(thd, thd->lock);
  thd->lock= 0;
  table->file->close();
  table->db_stat= 0;
  DBUG_RETURN(0);
}


/*
  Release a lock name
  SYNOPSIS
    release_name_lock()
    lpt
  RETURN VALUES
    0
*/

static int release_name_lock(ALTER_PARTITION_PARAM_TYPE *lpt)
{
  DBUG_ENTER("release_name_lock");
  pthread_mutex_lock(&LOCK_open);
  unlock_table_name(lpt->thd, &lpt->table_list);
  pthread_mutex_unlock(&LOCK_open);
  DBUG_RETURN(0);
}


5454 5455 5456 5457 5458 5459 5460 5461 5462 5463
/*
  Handle errors for ALTER TABLE for partitioning
  SYNOPSIS
    handle_alter_part_error()
    lpt                        Struct carrying parameters
    not_completed              Was request in complete phase when error occurred
  RETURN VALUES
    NONE
*/

5464 5465 5466 5467
void handle_alter_part_error(ALTER_PARTITION_PARAM_TYPE *lpt,
                             bool not_completed,
                             bool drop_partition,
                             bool frm_install)
5468 5469 5470 5471 5472
{
  partition_info *part_info= lpt->part_info;
  DBUG_ENTER("handle_alter_part_error");

  if (!part_info->first_log_entry &&
unknown's avatar
Fixes  
unknown committed
5473 5474
      execute_ddl_log_entry(current_thd,
                            part_info->first_log_entry->entry_pos))
5475 5476
  {
    /*
5477 5478
      We couldn't recover from error, most likely manual interaction
      is required.
5479
    */
5480 5481
    write_log_completed(lpt, FALSE);
    release_log_entries(part_info);
5482 5483 5484 5485 5486
    if (not_completed)
    {
      if (drop_partition)
      {
        /* Table is still ok, but we left a shadow frm file behind. */
5487
        push_warning_printf(lpt->thd, MYSQL_ERROR::WARN_LEVEL_WARN, 1,
5488 5489 5490
                            "%s %s",
           "Operation was unsuccessful, table is still intact,",
           "but it is possible that a shadow frm file was left behind");
5491 5492 5493 5494
      }
      else
      {
        push_warning_printf(lpt->thd, MYSQL_ERROR::WARN_LEVEL_WARN, 1,
5495 5496 5497 5498 5499
                            "%s %s %s %s",
           "Operation was unsuccessful, table is still intact,",
           "but it is possible that a shadow frm file was left behind.",
           "It is also possible that temporary partitions are left behind,",
           "these could be empty or more or less filled with records");
5500 5501 5502 5503
      }
    }
    else
    {
5504
      if (frm_install)
5505 5506 5507 5508 5509
      {
        /*
           Failed during install of shadow frm file, table isn't intact
           and dropped partitions are still there
        */
5510
        push_warning_printf(lpt->thd, MYSQL_ERROR::WARN_LEVEL_WARN, 1,
5511 5512 5513 5514
                            "%s %s %s",
          "Failed during alter of partitions, table is no longer intact.",
          "The frm file is in an unknown state, and a backup",
          "is required.");
5515 5516 5517 5518
      }
      else if (drop_partition)
      {
        /*
5519 5520 5521 5522
          Table is ok, we have switched to new table but left dropped
          partitions still in their places. We remove the log records and
          ask the user to perform the action manually. We remove the log
          records and ask the user to perform the action manually.
5523
        */
5524
        push_warning_printf(lpt->thd, MYSQL_ERROR::WARN_LEVEL_WARN, 1,
5525 5526 5527
                            "%s %s",
              "Failed during drop of partitions, table is intact.",
              "Manual drop of remaining partitions is required");
5528
      }
5529
      else
5530
      {
5531
        /*
5532 5533 5534
          We failed during renaming of partitions. The table is most
          certainly in a very bad state so we give user warning and disable
          the table by writing an ancient frm version into it.
5535
        */
5536
        push_warning_printf(lpt->thd, MYSQL_ERROR::WARN_LEVEL_WARN, 1,
5537 5538 5539 5540
                            "%s %s %s",
           "Failed during renaming of partitions. We are now in a position",
           "where table is not reusable",
           "Table is disabled by writing ancient frm file version into it");
5541 5542
      }
    }
5543 5544 5545
  }
  else
  {
5546
    release_log_entries(part_info);
5547 5548 5549 5550
    if (not_completed)
    {
      /*
        We hit an error before things were completed but managed
5551 5552
        to recover from the error. An error occurred and we have
        restored things to original so no need for further action.
5553
      */
5554
      ;
5555 5556 5557 5558 5559 5560
    }
    else
    {
      /*
        We hit an error after we had completed most of the operation
        and were successful in a second attempt so the operation
5561 5562 5563
        actually is successful now. We need to issue a warning that
        even though we reported an error the operation was successfully
        completed.
5564
      */
5565 5566 5567
      push_warning_printf(lpt->thd, MYSQL_ERROR::WARN_LEVEL_WARN, 1,"%s %s",
         "Operation was successfully completed by failure handling,",
         "after failure of normal operation");
5568 5569 5570 5571 5572 5573
    }
  }
  DBUG_VOID_RETURN;
}


unknown's avatar
unknown committed
5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603
/*
  Actually perform the change requested by ALTER TABLE of partitions
  previously prepared.

  SYNOPSIS
    fast_alter_partition_table()
    thd                           Thread object
    table                         Table object
    alter_info                    ALTER TABLE info
    create_info                   Create info for CREATE TABLE
    table_list                    List of the table involved
    create_list                   The fields in the resulting table
    key_list                      The keys in the resulting table
    db                            Database name of new table
    table_name                    Table name of new table

  RETURN VALUES
    TRUE                          Error
    FALSE                         Success

  DESCRIPTION
    Perform all ALTER TABLE operations for partitioned tables that can be
    performed fast without a full copy of the original table.
*/

uint fast_alter_partition_table(THD *thd, TABLE *table,
                                ALTER_INFO *alter_info,
                                HA_CREATE_INFO *create_info,
                                TABLE_LIST *table_list,
                                List<create_field> *create_list,
5604
                                List<Key> *key_list, char *db,
unknown's avatar
unknown committed
5605 5606 5607 5608 5609 5610 5611 5612 5613 5614
                                const char *table_name,
                                uint fast_alter_partition)
{
  /* Set-up struct used to write frm files */
  ulonglong copied= 0;
  ulonglong deleted= 0;
  partition_info *part_info= table->part_info;
  ALTER_PARTITION_PARAM_TYPE lpt_obj;
  ALTER_PARTITION_PARAM_TYPE *lpt= &lpt_obj;
  bool written_bin_log= TRUE;
5615 5616
  bool not_completed= TRUE;
  bool frm_install= FALSE;
unknown's avatar
unknown committed
5617 5618 5619
  DBUG_ENTER("fast_alter_partition_table");

  lpt->thd= thd;
5620
  lpt->part_info= part_info;
5621
  lpt->alter_info= alter_info;
unknown's avatar
unknown committed
5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636
  lpt->create_info= create_info;
  lpt->create_list= create_list;
  lpt->key_list= key_list;
  lpt->db_options= create_info->table_options;
  if (create_info->row_type == ROW_TYPE_DYNAMIC)
    lpt->db_options|= HA_OPTION_PACK_RECORD;
  lpt->table= table;
  lpt->key_info_buffer= 0;
  lpt->key_count= 0;
  lpt->db= db;
  lpt->table_name= table_name;
  lpt->copied= 0;
  lpt->deleted= 0;
  lpt->pack_frm_data= NULL;
  lpt->pack_frm_len= 0;
unknown's avatar
unknown committed
5637
  thd->work_part_info= part_info;
unknown's avatar
unknown committed
5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652

  if (alter_info->flags & ALTER_OPTIMIZE_PARTITION ||
      alter_info->flags & ALTER_ANALYZE_PARTITION ||
      alter_info->flags & ALTER_CHECK_PARTITION ||
      alter_info->flags & ALTER_REPAIR_PARTITION)
  {
    /*
      In this case the user has specified that he wants a set of partitions
      to be optimised and the partition engine can handle optimising
      partitions natively without requiring a full rebuild of the
      partitions.

      In this case it is enough to call optimise_partitions, there is no
      need to change frm files or anything else.
    */
5653
    int error;
unknown's avatar
unknown committed
5654 5655
    written_bin_log= FALSE;
    if (((alter_info->flags & ALTER_OPTIMIZE_PARTITION) &&
5656
         (error= table->file->optimize_partitions(thd))) ||
unknown's avatar
unknown committed
5657
        ((alter_info->flags & ALTER_ANALYZE_PARTITION) &&
5658
         (error= table->file->analyze_partitions(thd))) ||
unknown's avatar
unknown committed
5659
        ((alter_info->flags & ALTER_CHECK_PARTITION) &&
5660
         (error= table->file->check_partitions(thd))) ||
unknown's avatar
unknown committed
5661
        ((alter_info->flags & ALTER_REPAIR_PARTITION) &&
5662
         (error= table->file->repair_partitions(thd))))
unknown's avatar
unknown committed
5663
    {
5664
      table->file->print_error(error, MYF(0));
unknown's avatar
unknown committed
5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708
      DBUG_RETURN(TRUE);
    }
  }
  else if (fast_alter_partition & HA_PARTITION_ONE_PHASE)
  {
    /*
      In the case where the engine supports one phase online partition
      changes it is not necessary to have any exclusive locks. The
      correctness is upheld instead by transactions being aborted if they
      access the table after its partition definition has changed (if they
      are still using the old partition definition).

      The handler is in this case responsible to ensure that all users
      start using the new frm file after it has changed. To implement
      one phase it is necessary for the handler to have the master copy
      of the frm file and use discovery mechanisms to renew it. Thus
      write frm will write the frm, pack the new frm and finally
      the frm is deleted and the discovery mechanisms will either restore
      back to the old or installing the new after the change is activated.

      Thus all open tables will be discovered that they are old, if not
      earlier as soon as they try an operation using the old table. One
      should ensure that this is checked already when opening a table,
      even if it is found in the cache of open tables.

      change_partitions will perform all operations and it is the duty of
      the handler to ensure that the frm files in the system gets updated
      in synch with the changes made and if an error occurs that a proper
      error handling is done.

      If the MySQL Server crashes at this moment but the handler succeeds
      in performing the change then the binlog is not written for the
      change. There is no way to solve this as long as the binlog is not
      transactional and even then it is hard to solve it completely.
 
      The first approach here was to downgrade locks. Now a different approach
      is decided upon. The idea is that the handler will have access to the
      ALTER_INFO when store_lock arrives with TL_WRITE_ALLOW_READ. So if the
      handler knows that this functionality can be handled with a lower lock
      level it will set the lock level to TL_WRITE_ALLOW_WRITE immediately.
      Thus the need to downgrade the lock disappears.
      1) Write the new frm, pack it and then delete it
      2) Perform the change within the handler
    */
5709 5710
    if (mysql_write_frm(lpt, WFRM_WRITE_SHADOW | WFRM_PACK_FRM) ||
        mysql_change_partitions(lpt))
unknown's avatar
unknown committed
5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738
    {
      DBUG_RETURN(TRUE);
    }
  }
  else if (alter_info->flags == ALTER_DROP_PARTITION)
  {
    /*
      Now after all checks and setting state on dropped partitions we can
      start the actual dropping of the partitions.

      Drop partition is actually two things happening. The first is that
      a lot of records are deleted. The second is that the behaviour of
      subsequent updates and writes and deletes will change. The delete
      part can be handled without any particular high lock level by
      transactional engines whereas non-transactional engines need to
      ensure that this change is done with an exclusive lock on the table.
      The second part, the change of partitioning does however require
      an exclusive lock to install the new partitioning as one atomic
      operation. If this is not the case, it is possible for two
      transactions to see the change in a different order than their
      serialisation order. Thus we need an exclusive lock for both
      transactional and non-transactional engines.

      For LIST partitions it could be possible to avoid the exclusive lock
      (and for RANGE partitions if they didn't rearrange range definitions
      after a DROP PARTITION) if one ensured that failed accesses to the
      dropped partitions was aborted for sure (thus only possible for
      transactional engines).
5739 5740 5741

      0) Write an entry that removes the shadow frm file if crash occurs 
      1) Write the new frm file as a shadow frm
5742
      2) Write the ddl log to ensure that the operation is completed
5743 5744
         even in the presence of a MySQL Server crash
      3) Lock the table in TL_WRITE_ONLY to ensure all other accesses to
5745 5746 5747 5748 5749 5750 5751
         the table have completed. This ensures that other threads can not
         execute on the table in parallel.
      4) Get a name lock on the table. This ensures that we can release all
         locks on the table and since no one can open the table, there can
         be no new threads accessing the table. They will be hanging on the
         name lock.
      5) Close all tables that have already been opened but didn't stumble on
5752 5753
         the abort locked previously. This is done as part of the
         get_name_lock call.
5754 5755
      6) We are now ready to release all locks we got in this thread.
      7) Write the bin log
5756 5757 5758 5759 5760 5761
         Unfortunately the writing of the binlog is not synchronised with
         other logging activities. So no matter in which order the binlog
         is written compared to other activities there will always be cases
         where crashes make strange things occur. In this placement it can
         happen that the ALTER TABLE DROP PARTITION gets performed in the
         master but not in the slaves if we have a crash, after writing the
5762 5763
         ddl log but before writing the binlog. A solution to this would
         require writing the statement first in the ddl log and then
5764 5765
         when recovering from the crash read the binlog and insert it into
         the binlog if not written already.
5766 5767 5768 5769 5770 5771 5772
      8) Install the previously written shadow frm file
      9) Prepare handlers for drop of partitions
      10) Drop the partitions
      11) Remove entries from ddl log
      12) Release name lock so that all other threads can access the table
          again.
      13) Complete query
5773 5774 5775

      We insert Error injections at all places where it could be interesting
      to test if recovery is properly done.
unknown's avatar
unknown committed
5776
    */
5777
    if (write_log_drop_shadow_frm(lpt) ||
5778
        ERROR_INJECT_CRASH("crash_drop_partition_1") ||
5779
        mysql_write_frm(lpt, WFRM_WRITE_SHADOW) ||
5780
        ERROR_INJECT_CRASH("crash_drop_partition_2") ||
5781
        write_log_drop_partition(lpt) ||
5782
        ERROR_INJECT_CRASH("crash_drop_partition_3") ||
5783 5784
        (not_completed= FALSE) ||
        abort_and_upgrade_lock(lpt) || /* Always returns 0 */
5785
        ERROR_INJECT_CRASH("crash_drop_partition_4") ||
5786 5787 5788 5789
        get_name_lock(lpt) ||
        ERROR_INJECT_CRASH("crash_drop_partition_5") ||
        alter_close_tables(lpt) ||
        ERROR_INJECT_CRASH("crash_drop_partition_6") ||
unknown's avatar
unknown committed
5790 5791
        ((!thd->lex->no_write_to_binlog) &&
         (write_bin_log(thd, FALSE,
5792
                        thd->query, thd->query_length), FALSE)) ||
5793
        ERROR_INJECT_CRASH("crash_drop_partition_7") ||
5794
        ((frm_install= TRUE), FALSE) ||
5795
        mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
5796
        ((frm_install= FALSE), FALSE) ||
5797
        ERROR_INJECT_CRASH("crash_drop_partition_8") ||
5798
        mysql_drop_partitions(lpt) ||
5799
        ERROR_INJECT_CRASH("crash_drop_partition_9") ||
5800
        (write_log_completed(lpt, FALSE), FALSE) ||
5801
        ERROR_INJECT_CRASH("crash_drop_partition_10") ||
5802
        (release_name_lock(lpt), FALSE)) 
unknown's avatar
unknown committed
5803
    {
5804
      handle_alter_part_error(lpt, not_completed, TRUE, frm_install);
unknown's avatar
unknown committed
5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820
      DBUG_RETURN(TRUE);
    }
  }
  else if ((alter_info->flags & ALTER_ADD_PARTITION) &&
           (part_info->part_type == RANGE_PARTITION ||
            part_info->part_type == LIST_PARTITION))
  {
    /*
      ADD RANGE/LIST PARTITIONS
      In this case there are no tuples removed and no tuples are added.
      Thus the operation is merely adding a new partition. Thus it is
      necessary to perform the change as an atomic operation. Otherwise
      someone reading without seeing the new partition could potentially
      miss updates made by a transaction serialised before it that are
      inserted into the new partition.

5821 5822
      0) Write an entry that removes the shadow frm file if crash occurs 
      1) Write the new frm file as a shadow frm file
5823
      2) Log the changes to happen in ddl log
unknown's avatar
unknown committed
5824 5825 5826 5827
      2) Add the new partitions
      3) Lock all partitions in TL_WRITE_ONLY to ensure that no users
         are still using the old partitioning scheme. Wait until all
         ongoing users have completed before progressing.
5828 5829 5830 5831 5832 5833 5834 5835 5836 5837
      4) Get a name lock on the table. This ensures that we can release all
         locks on the table and since no one can open the table, there can
         be no new threads accessing the table. They will be hanging on the
         name lock.
      5) Close all tables that have already been opened but didn't stumble on
         the abort locked previously. This is done as part of the
         get_name_lock call.
      6) Close all table handlers and unlock all handlers but retain name lock
      7) Write binlog
      8) Now the change is completed except for the installation of the
unknown's avatar
unknown committed
5838 5839
         new frm file. We thus write an action in the log to change to
         the shadow frm file
5840
      9) Install the new frm file of the table where the partitions are
5841
         added to the table.
5842 5843 5844 5845
      10)Wait until all accesses using the old frm file has completed
      11)Remove entries from ddl log
      12)Release name lock
      13)Complete query
unknown's avatar
unknown committed
5846
    */
5847
    if (write_log_add_change_partition(lpt) ||
5848
        ERROR_INJECT_CRASH("crash_add_partition_1") ||
5849
        mysql_write_frm(lpt, WFRM_WRITE_SHADOW) ||
5850
        ERROR_INJECT_CRASH("crash_add_partition_2") ||
5851
        mysql_change_partitions(lpt) ||
5852
        ERROR_INJECT_CRASH("crash_add_partition_3") ||
5853
        abort_and_upgrade_lock(lpt) || /* Always returns 0 */
5854 5855 5856 5857 5858
        ERROR_INJECT_CRASH("crash_add_partition_3") ||
        get_name_lock(lpt) ||
        ERROR_INJECT_CRASH("crash_add_partition_4") ||
        alter_close_tables(lpt) ||
        ERROR_INJECT_CRASH("crash_add_partition_5") ||
unknown's avatar
unknown committed
5859 5860 5861
        ((!thd->lex->no_write_to_binlog) &&
         (write_bin_log(thd, FALSE,
                        thd->query, thd->query_length), FALSE)) ||
5862
        ERROR_INJECT_CRASH("crash_add_partition_6") ||
5863
        write_log_rename_frm(lpt) ||
5864
        (not_completed= FALSE) ||
5865
        ERROR_INJECT_CRASH("crash_add_partition_7") ||
5866
        ((frm_install= TRUE), FALSE) ||
unknown's avatar
unknown committed
5867
        mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
5868
        ERROR_INJECT_CRASH("crash_add_partition_8") ||
5869
        (write_log_completed(lpt, FALSE), FALSE) ||
5870 5871
        ERROR_INJECT_CRASH("crash_add_partition_9") ||
        (release_name_lock(lpt), FALSE)) 
unknown's avatar
unknown committed
5872
    {
5873
      handle_alter_part_error(lpt, not_completed, FALSE, frm_install);
unknown's avatar
unknown committed
5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909
      DBUG_RETURN(TRUE);
    }
  }
  else
  {
    /*
      ADD HASH PARTITION/
      COALESCE PARTITION/
      REBUILD PARTITION/
      REORGANIZE PARTITION
 
      In this case all records are still around after the change although
      possibly organised into new partitions, thus by ensuring that all
      updates go to both the old and the new partitioning scheme we can
      actually perform this operation lock-free. The only exception to
      this is when REORGANIZE PARTITION adds/drops ranges. In this case
      there needs to be an exclusive lock during the time when the range
      changes occur.
      This is only possible if the handler can ensure double-write for a
      period. The double write will ensure that it doesn't matter where the
      data is read from since both places are updated for writes. If such
      double writing is not performed then it is necessary to perform the
      change with the usual exclusive lock. With double writes it is even
      possible to perform writes in parallel with the reorganisation of
      partitions.

      Without double write procedure we get the following procedure.
      The only difference with using double write is that we can downgrade
      the lock to TL_WRITE_ALLOW_WRITE. Double write in this case only
      double writes from old to new. If we had double writing in both
      directions we could perform the change completely without exclusive
      lock for HASH partitions.
      Handlers that perform double writing during the copy phase can actually
      use a lower lock level. This can be handled inside store_lock in the
      respective handler.

5910 5911 5912 5913 5914
      0) Write an entry that removes the shadow frm file if crash occurs 
      1) Write the shadow frm file of new partitioning
      2) Log such that temporary partitions added in change phase are
         removed in a crash situation
      3) Add the new partitions
unknown's avatar
unknown committed
5915
         Copy from the reorganised partitions to the new partitions
5916 5917 5918
      4) Log that operation is completed and log all complete actions
         needed to complete operation from here
      5) Lock all partitions in TL_WRITE_ONLY to ensure that no users
unknown's avatar
unknown committed
5919 5920
         are still using the old partitioning scheme. Wait until all
         ongoing users have completed before progressing.
5921 5922 5923 5924
      6) Get a name lock of the table
      7) Close all tables opened but not yet locked, after this call we are
         certain that no other thread is in the lock wait queue or has
         opened the table. The name lock will ensure that they are blocked
5925
         on the open call. This is achieved also by get_name_lock call.
5926 5927 5928 5929 5930 5931 5932 5933 5934
      8) Close all partitions opened by this thread, but retain name lock.
      9) Write bin log
      10) Prepare handlers for rename and delete of partitions
      11) Rename and drop the reorged partitions such that they are no
          longer used and rename those added to their real new names.
      12) Install the shadow frm file
      13) Release the name lock to enable other threads to start using the
          table again.
      14) Complete query
unknown's avatar
unknown committed
5935
    */
5936
    if (write_log_add_change_partition(lpt) ||
5937
        ERROR_INJECT_CRASH("crash_change_partition_1") ||
5938
        mysql_write_frm(lpt, WFRM_WRITE_SHADOW) ||
5939
        ERROR_INJECT_CRASH("crash_change_partition_2") ||
5940
        mysql_change_partitions(lpt) ||
5941 5942
        ERROR_INJECT_CRASH("crash_change_partition_3") ||
        write_log_final_change_partition(lpt) ||
5943
        ERROR_INJECT_CRASH("crash_change_partition_4") ||
5944 5945
        (not_completed= FALSE) ||
        abort_and_upgrade_lock(lpt) || /* Always returns 0 */
5946
        ERROR_INJECT_CRASH("crash_change_partition_5") ||
5947
        get_name_lock(lpt) ||
5948
        ERROR_INJECT_CRASH("crash_change_partition_6") ||
5949
        alter_close_tables(lpt) ||
5950
        ERROR_INJECT_CRASH("crash_change_partition_7") ||
unknown's avatar
unknown committed
5951 5952 5953
        ((!thd->lex->no_write_to_binlog) &&
         (write_bin_log(thd, FALSE,
                        thd->query, thd->query_length), FALSE)) ||
5954
        ERROR_INJECT_CRASH("crash_change_partition_8") ||
5955
        mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
5956
        ERROR_INJECT_CRASH("crash_change_partition_9") ||
5957
        mysql_drop_partitions(lpt) ||
5958
        ERROR_INJECT_CRASH("crash_change_partition_10") ||
5959
        mysql_rename_partitions(lpt) ||
5960
        ((frm_install= TRUE), FALSE) ||
5961
        ERROR_INJECT_CRASH("crash_change_partition_11") ||
5962
        (write_log_completed(lpt, FALSE), FALSE) ||
5963
        ERROR_INJECT_CRASH("crash_change_partition_12") ||
5964
        (release_name_lock(lpt), FALSE))
unknown's avatar
unknown committed
5965
    {
5966
      handle_alter_part_error(lpt, not_completed, FALSE, frm_install);
5967
      DBUG_RETURN(TRUE);
unknown's avatar
unknown committed
5968 5969 5970 5971 5972 5973 5974
    }
  }
  /*
    A final step is to write the query to the binlog and send ok to the
    user
  */
  DBUG_RETURN(fast_end_partition(thd, lpt->copied, lpt->deleted,
5975
                                 table, table_list, FALSE, lpt,
unknown's avatar
unknown committed
5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068
                                 written_bin_log));
}
#endif


/*
  Prepare for calling val_int on partition function by setting fields to
  point to the record where the values of the PF-fields are stored.

  SYNOPSIS
    set_field_ptr()
    ptr                 Array of fields to change ptr
    new_buf             New record pointer
    old_buf             Old record pointer

  DESCRIPTION
    Set ptr in field objects of field array to refer to new_buf record
    instead of previously old_buf. Used before calling val_int and after
    it is used to restore pointers to table->record[0].
    This routine is placed outside of partition code since it can be useful
    also for other programs.
*/

void set_field_ptr(Field **ptr, const byte *new_buf,
                   const byte *old_buf)
{
  my_ptrdiff_t diff= (new_buf - old_buf);
  DBUG_ENTER("set_field_ptr");

  do
  {
    (*ptr)->move_field_offset(diff);
  } while (*(++ptr));
  DBUG_VOID_RETURN;
}


/*
  Prepare for calling val_int on partition function by setting fields to
  point to the record where the values of the PF-fields are stored.
  This variant works on a key_part reference.
  It is not required that all fields are NOT NULL fields.

  SYNOPSIS
    set_key_field_ptr()
    key_info            key info with a set of fields to change ptr
    new_buf             New record pointer
    old_buf             Old record pointer

  DESCRIPTION
    Set ptr in field objects of field array to refer to new_buf record
    instead of previously old_buf. Used before calling val_int and after
    it is used to restore pointers to table->record[0].
    This routine is placed outside of partition code since it can be useful
    also for other programs.
*/

void set_key_field_ptr(KEY *key_info, const byte *new_buf,
                       const byte *old_buf)
{
  KEY_PART_INFO *key_part= key_info->key_part;
  uint key_parts= key_info->key_parts;
  uint i= 0;
  my_ptrdiff_t diff= (new_buf - old_buf);
  DBUG_ENTER("set_key_field_ptr");

  do
  {
    key_part->field->move_field_offset(diff);
    key_part++;
  } while (++i < key_parts);
  DBUG_VOID_RETURN;
}


/*
  SYNOPSIS
    mem_alloc_error()
    size                Size of memory attempted to allocate
    None

  RETURN VALUES
    None

  DESCRIPTION
    A routine to use for all the many places in the code where memory
    allocation error can happen, a tremendous amount of them, needs
    simple routine that signals this error.
*/

void mem_alloc_error(size_t size)
{
  my_error(ER_OUTOFMEMORY, MYF(0), size);
6069
}
unknown's avatar
unknown committed
6070

6071
#ifdef WITH_PARTITION_STORAGE_ENGINE
unknown's avatar
unknown committed
6072
/*
6073 6074
  Return comma-separated list of used partitions in the provided given string

unknown's avatar
unknown committed
6075 6076 6077 6078
  SYNOPSIS
    make_used_partitions_str()
      part_info  IN  Partitioning info
      parts_str  OUT The string to fill
6079 6080 6081 6082 6083 6084 6085

  DESCRIPTION
    Generate a list of used partitions (from bits in part_info->used_partitions
    bitmap), asd store it into the provided String object.
    
  NOTE
    The produced string must not be longer then MAX_PARTITIONS * (1 + FN_LEN).
unknown's avatar
unknown committed
6086 6087 6088 6089 6090 6091 6092 6093 6094
*/

void make_used_partitions_str(partition_info *part_info, String *parts_str)
{
  parts_str->length(0);
  partition_element *pe;
  uint partition_id= 0;
  List_iterator<partition_element> it(part_info->partitions);
  
6095
  if (part_info->is_sub_partitioned())
unknown's avatar
unknown committed
6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133
  {
    partition_element *head_pe;
    while ((head_pe= it++))
    {
      List_iterator<partition_element> it2(head_pe->subpartitions);
      while ((pe= it2++))
      {
        if (bitmap_is_set(&part_info->used_partitions, partition_id))
        {
          if (parts_str->length())
            parts_str->append(',');
          parts_str->append(head_pe->partition_name,
                           strlen(head_pe->partition_name),
                           system_charset_info);
          parts_str->append('_');
          parts_str->append(pe->partition_name,
                           strlen(pe->partition_name),
                           system_charset_info);
        }
        partition_id++;
      }
    }
  }
  else
  {
    while ((pe= it++))
    {
      if (bitmap_is_set(&part_info->used_partitions, partition_id))
      {
        if (parts_str->length())
          parts_str->append(',');
        parts_str->append(pe->partition_name, strlen(pe->partition_name),
                         system_charset_info);
      }
      partition_id++;
    }
  }
}
6134
#endif
unknown's avatar
unknown committed
6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171

/****************************************************************************
 * Partition interval analysis support
 ***************************************************************************/

/*
  Setup partition_info::* members related to partitioning range analysis

  SYNOPSIS
    set_up_partition_func_pointers()
      part_info  Partitioning info structure

  DESCRIPTION
    Assuming that passed partition_info structure already has correct values
    for members that specify [sub]partitioning type, table fields, and
    functions, set up partition_info::* members that are related to
    Partitioning Interval Analysis (see get_partitions_in_range_iter for its
    definition)

  IMPLEMENTATION
    There are two available interval analyzer functions:
    (1) get_part_iter_for_interval_via_mapping 
    (2) get_part_iter_for_interval_via_walking

    They both have limited applicability:
    (1) is applicable for "PARTITION BY <RANGE|LIST>(func(t.field))", where
    func is a monotonic function.
    
    (2) is applicable for 
      "[SUB]PARTITION BY <any-partitioning-type>(any_func(t.integer_field))"
      
    If both are applicable, (1) is preferred over (2).
    
    This function sets part_info::get_part_iter_for_interval according to
    this criteria, and also sets some auxilary fields that the function
    uses.
*/
6172
#ifdef WITH_PARTITION_STORAGE_ENGINE
unknown's avatar
unknown committed
6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201
static void set_up_range_analysis_info(partition_info *part_info)
{
  enum_monotonicity_info minfo;

  /* Set the catch-all default */
  part_info->get_part_iter_for_interval= NULL;
  part_info->get_subpart_iter_for_interval= NULL;

  /* 
    Check if get_part_iter_for_interval_via_mapping() can be used for 
    partitioning
  */
  switch (part_info->part_type) {
  case RANGE_PARTITION:
  case LIST_PARTITION:
    minfo= part_info->part_expr->get_monotonicity_info();
    if (minfo != NON_MONOTONIC)
    {
      part_info->range_analysis_include_bounds=
        test(minfo == MONOTONIC_INCREASING);
      part_info->get_part_iter_for_interval=
        get_part_iter_for_interval_via_mapping;
      goto setup_subparts;
    }
  default:
    ;
  }
   
  /*
6202
    Check if get_part_iter_for_interval_via_walking() can be used for
unknown's avatar
unknown committed
6203 6204 6205 6206 6207 6208 6209 6210
    partitioning
  */
  if (part_info->no_part_fields == 1)
  {
    Field *field= part_info->part_field_array[0];
    switch (field->type()) {
    case MYSQL_TYPE_TINY:
    case MYSQL_TYPE_SHORT:
6211
    case MYSQL_TYPE_INT24:
unknown's avatar
unknown committed
6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223
    case MYSQL_TYPE_LONG:
    case MYSQL_TYPE_LONGLONG:
      part_info->get_part_iter_for_interval=
        get_part_iter_for_interval_via_walking;
      break;
    default:
      ;
    }
  }

setup_subparts:
  /*
6224
    Check if get_part_iter_for_interval_via_walking() can be used for
unknown's avatar
unknown committed
6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263
    subpartitioning
  */
  if (part_info->no_subpart_fields == 1)
  {
    Field *field= part_info->subpart_field_array[0];
    switch (field->type()) {
    case MYSQL_TYPE_TINY:
    case MYSQL_TYPE_SHORT:
    case MYSQL_TYPE_LONG:
    case MYSQL_TYPE_LONGLONG:
      part_info->get_subpart_iter_for_interval=
        get_part_iter_for_interval_via_walking;
      break;
    default:
      ;
    }
  }
}


typedef uint32 (*get_endpoint_func)(partition_info*, bool left_endpoint,
                                    bool include_endpoint);

/*
  Partitioning Interval Analysis: Initialize the iterator for "mapping" case

  SYNOPSIS
    get_part_iter_for_interval_via_mapping()
      part_info   Partition info
      is_subpart  TRUE  - act for subpartitioning
                  FALSE - act for partitioning
      min_value   minimum field value, in opt_range key format.
      max_value   minimum field value, in opt_range key format.
      flags       Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE,
                  NO_MAX_RANGE.
      part_iter   Iterator structure to be initialized

  DESCRIPTION
    Initialize partition set iterator to walk over the interval in
6264 6265
    ordered-array-of-partitions (for RANGE partitioning) or 
    ordered-array-of-list-constants (for LIST partitioning) space.
unknown's avatar
unknown committed
6266 6267

  IMPLEMENTATION
6268
    This function is used when partitioning is done by
unknown's avatar
unknown committed
6269 6270 6271 6272 6273 6274 6275 6276
    <RANGE|LIST>(ascending_func(t.field)), and we can map an interval in
    t.field space into a sub-array of partition_info::range_int_array or
    partition_info::list_array (see get_partition_id_range_for_endpoint,
    get_list_array_idx_for_endpoint for details).
    
    The function performs this interval mapping, and sets the iterator to
    traverse the sub-array and return appropriate partitions.
    
6277
  RETURN
unknown's avatar
unknown committed
6278 6279 6280 6281 6282 6283 6284
    0 - No matching partitions (iterator not initialized)
    1 - Ok, iterator intialized for traversal of matching partitions.
   -1 - All partitions would match (iterator not initialized)
*/

int get_part_iter_for_interval_via_mapping(partition_info *part_info,
                                           bool is_subpart,
6285
                                           char *min_value, char *max_value,
unknown's avatar
unknown committed
6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306
                                           uint flags,
                                           PARTITION_ITERATOR *part_iter)
{
  DBUG_ASSERT(!is_subpart);
  Field *field= part_info->part_field_array[0];
  uint32             max_endpoint_val;
  get_endpoint_func  get_endpoint;
  uint field_len= field->pack_length_in_rec();

  if (part_info->part_type == RANGE_PARTITION)
  {
    get_endpoint=        get_partition_id_range_for_endpoint;
    max_endpoint_val=    part_info->no_parts;
    part_iter->get_next= get_next_partition_id_range;
  }
  else if (part_info->part_type == LIST_PARTITION)
  {
    get_endpoint=        get_list_array_idx_for_endpoint;
    max_endpoint_val=    part_info->no_list_values;
    part_iter->get_next= get_next_partition_id_list;
    part_iter->part_info= part_info;
6307
    part_iter->ret_null_part= part_iter->ret_null_part_orig= FALSE;
unknown's avatar
unknown committed
6308 6309 6310 6311
  }
  else
    DBUG_ASSERT(0);

6312 6313 6314 6315 6316 6317
  /* 
    Find minimum: Do special handling if the interval has left bound in form
     " NULL <= X ":
  */
  if (field->real_maybe_null() && part_info->has_null_value && 
      !(flags & (NO_MIN_RANGE | NEAR_MIN)) && *min_value)
6318
  {
6319 6320 6321
    part_iter->ret_null_part= part_iter->ret_null_part_orig= TRUE;
    part_iter->part_nums.start= part_iter->part_nums.cur= 0;
    if (*max_value && !(flags & NO_MAX_RANGE))
6322
    {
6323 6324 6325
      /* The right bound is X <= NULL, i.e. it is a "X IS NULL" interval */
      part_iter->part_nums.end= 0;
      return 1;
6326 6327
    }
  }
unknown's avatar
unknown committed
6328 6329
  else
  {
6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347
    if (flags & NO_MIN_RANGE)
      part_iter->part_nums.start= part_iter->part_nums.cur= 0;
    else
    {
      /*
        Store the interval edge in the record buffer, and call the
        function that maps the edge in table-field space to an edge
        in ordered-set-of-partitions (for RANGE partitioning) or 
        index-in-ordered-array-of-list-constants (for LIST) space.
      */
      store_key_image_to_rec(field, min_value, field_len);
      bool include_endp= part_info->range_analysis_include_bounds ||
                         !test(flags & NEAR_MIN);
      part_iter->part_nums.start= get_endpoint(part_info, 1, include_endp);
      part_iter->part_nums.cur= part_iter->part_nums.start;
      if (part_iter->part_nums.start == max_endpoint_val)
        return 0; /* No partitions */
    }
unknown's avatar
unknown committed
6348 6349 6350 6351
  }

  /* Find maximum, do the same as above but for right interval bound */
  if (flags & NO_MAX_RANGE)
6352
    part_iter->part_nums.end= max_endpoint_val;
unknown's avatar
unknown committed
6353 6354 6355 6356 6357
  else
  {
    store_key_image_to_rec(field, max_value, field_len);
    bool include_endp= part_info->range_analysis_include_bounds ||
                       !test(flags & NEAR_MAX);
6358
    part_iter->part_nums.end= get_endpoint(part_info, 0, include_endp);
6359 6360
    if (part_iter->part_nums.start == part_iter->part_nums.end &&
        !part_iter->ret_null_part)
unknown's avatar
unknown committed
6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371
      return 0; /* No partitions */
  }
  return 1; /* Ok, iterator initialized */
}


/* See get_part_iter_for_interval_via_walking for definition of what this is */
#define MAX_RANGE_TO_WALK 10


/*
6372
  Partitioning Interval Analysis: Initialize iterator to walk field interval
unknown's avatar
unknown committed
6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387

  SYNOPSIS
    get_part_iter_for_interval_via_walking()
      part_info   Partition info
      is_subpart  TRUE  - act for subpartitioning
                  FALSE - act for partitioning
      min_value   minimum field value, in opt_range key format.
      max_value   minimum field value, in opt_range key format.
      flags       Some combination of NEAR_MIN, NEAR_MAX, NO_MIN_RANGE,
                  NO_MAX_RANGE.
      part_iter   Iterator structure to be initialized

  DESCRIPTION
    Initialize partition set iterator to walk over interval in integer field
    space. That is, for "const1 <=? t.field <=? const2" interval, initialize 
6388 6389
    the iterator to return a set of [sub]partitions obtained with the
    following procedure:
unknown's avatar
unknown committed
6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402
      get partition id for t.field = const1,   return it
      get partition id for t.field = const1+1, return it
       ...                 t.field = const1+2, ...
       ...                           ...       ...
       ...                 t.field = const2    ...

  IMPLEMENTATION
    See get_partitions_in_range_iter for general description of interval
    analysis. We support walking over the following intervals: 
      "t.field IS NULL" 
      "c1 <=? t.field <=? c2", where c1 and c2 are finite. 
    Intervals with +inf/-inf, and [NULL, c1] interval can be processed but
    that is more tricky and I don't have time to do it right now.
6403

unknown's avatar
unknown committed
6404 6405 6406 6407 6408 6409 6410 6411
    Additionally we have these requirements:
    * number of values in the interval must be less then number of
      [sub]partitions, and 
    * Number of values in the interval must be less then MAX_RANGE_TO_WALK.
    
    The rationale behind these requirements is that if they are not met
    we're likely to hit most of the partitions and traversing the interval
    will only add overhead. So it's better return "all partitions used" in
6412
    that case.
unknown's avatar
unknown committed
6413 6414 6415 6416 6417 6418 6419 6420 6421

  RETURN
    0 - No matching partitions, iterator not initialized
    1 - Some partitions would match, iterator intialized for traversing them
   -1 - All partitions would match, iterator not initialized
*/

int get_part_iter_for_interval_via_walking(partition_info *part_info,
                                           bool is_subpart,
6422
                                           char *min_value, char *max_value,
unknown's avatar
unknown committed
6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460
                                           uint flags,
                                           PARTITION_ITERATOR *part_iter)
{
  Field *field;
  uint total_parts;
  partition_iter_func get_next_func;
  if (is_subpart)
  {
    field= part_info->subpart_field_array[0];
    total_parts= part_info->no_subparts;
    get_next_func=  get_next_subpartition_via_walking;
  }
  else
  {
    field= part_info->part_field_array[0];
    total_parts= part_info->no_parts;
    get_next_func=  get_next_partition_via_walking;
  }

  /* Handle the "t.field IS NULL" interval, it is a special case */
  if (field->real_maybe_null() && !(flags & (NO_MIN_RANGE | NO_MAX_RANGE)) &&
      *min_value && *max_value)
  {
    /* 
      We don't have a part_iter->get_next() function that would find which
      partition "t.field IS NULL" belongs to, so find partition that contains 
      NULL right here, and return an iterator over singleton set.
    */
    uint32 part_id;
    field->set_null();
    if (is_subpart)
    {
      part_id= part_info->get_subpartition_id(part_info);
      init_single_partition_iterator(part_id, part_iter);
      return 1; /* Ok, iterator initialized */
    }
    else
    {
unknown's avatar
unknown committed
6461
      longlong dummy;
6462 6463 6464 6465 6466
      int res= part_info->is_sub_partitioned() ?
                  part_info->get_part_partition_id(part_info, &part_id,
                                                   &dummy):
                  part_info->get_partition_id(part_info, &part_id, &dummy);
      if (!res)
unknown's avatar
unknown committed
6467 6468 6469 6470 6471 6472 6473 6474
      {
        init_single_partition_iterator(part_id, part_iter);
        return 1; /* Ok, iterator initialized */
      }
    }
    return 0; /* No partitions match */
  }

6475 6476 6477 6478 6479
  if ((field->real_maybe_null() && 
       ((!(flags & NO_MIN_RANGE) && *min_value) ||  // NULL <? X
        (!(flags & NO_MAX_RANGE) && *max_value))) ||  // X <? NULL
      (flags & (NO_MIN_RANGE | NO_MAX_RANGE)))    // -inf at any bound
  {
unknown's avatar
unknown committed
6480
    return -1; /* Can't handle this interval, have to use all partitions */
6481
  }
unknown's avatar
unknown committed
6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498
  
  /* Get integers for left and right interval bound */
  longlong a, b;
  uint len= field->pack_length_in_rec();
  store_key_image_to_rec(field, min_value, len);
  a= field->val_int();
  
  store_key_image_to_rec(field, max_value, len);
  b= field->val_int();

  a += test(flags & NEAR_MIN);
  b += test(!(flags & NEAR_MAX));
  uint n_values= b - a;
  
  if (n_values > total_parts || n_values > MAX_RANGE_TO_WALK)
    return -1;

6499
  part_iter->field_vals.start= part_iter->field_vals.cur= a;
6500
  part_iter->field_vals.end=   b;
unknown's avatar
unknown committed
6501 6502 6503 6504 6505 6506 6507 6508 6509 6510
  part_iter->part_info= part_info;
  part_iter->get_next=  get_next_func;
  return 1;
}


/*
  PARTITION_ITERATOR::get_next implementation: enumerate partitions in range

  SYNOPSIS
6511
    get_next_partition_id_range()
unknown's avatar
unknown committed
6512 6513 6514 6515 6516
      part_iter  Partition set iterator structure

  DESCRIPTION
    This is implementation of PARTITION_ITERATOR::get_next() that returns
    [sub]partition ids in [min_partition_id, max_partition_id] range.
6517
    The function conforms to partition_iter_func type.
unknown's avatar
unknown committed
6518 6519 6520 6521 6522 6523 6524 6525

  RETURN
    partition id
    NOT_A_PARTITION_ID if there are no more partitions
*/

uint32 get_next_partition_id_range(PARTITION_ITERATOR* part_iter)
{
6526 6527 6528
  if (part_iter->part_nums.cur == part_iter->part_nums.end)
  {
    part_iter->part_nums.cur= part_iter->part_nums.start;
unknown's avatar
unknown committed
6529
    return NOT_A_PARTITION_ID;
6530
  }
unknown's avatar
unknown committed
6531
  else
6532
    return part_iter->part_nums.cur++;
unknown's avatar
unknown committed
6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543
}


/*
  PARTITION_ITERATOR::get_next implementation for LIST partitioning

  SYNOPSIS
    get_next_partition_id_list()
      part_iter  Partition set iterator structure

  DESCRIPTION
6544
    This implementation of PARTITION_ITERATOR::get_next() is special for 
unknown's avatar
unknown committed
6545 6546
    LIST partitioning: it enumerates partition ids in 
    part_info->list_array[i] where i runs over [min_idx, max_idx] interval.
6547
    The function conforms to partition_iter_func type.
unknown's avatar
unknown committed
6548 6549 6550 6551 6552 6553 6554 6555

  RETURN 
    partition id
    NOT_A_PARTITION_ID if there are no more partitions
*/

uint32 get_next_partition_id_list(PARTITION_ITERATOR *part_iter)
{
6556
  if (part_iter->part_nums.cur == part_iter->part_nums.end)
6557
  {
6558
    if (part_iter->ret_null_part)
6559
    {
6560
      part_iter->ret_null_part= FALSE;
6561 6562
      return part_iter->part_info->has_null_part_id;
    }
6563 6564
    part_iter->part_nums.cur= part_iter->part_nums.start;
    part_iter->ret_null_part= part_iter->ret_null_part_orig;
unknown's avatar
unknown committed
6565
    return NOT_A_PARTITION_ID;
6566
  }
unknown's avatar
unknown committed
6567 6568
  else
    return part_iter->part_info->list_array[part_iter->
6569
                                            part_nums.cur++].partition_id;
unknown's avatar
unknown committed
6570 6571 6572 6573
}


/*
6574
  PARTITION_ITERATOR::get_next implementation: walk over field-space interval
unknown's avatar
unknown committed
6575 6576 6577 6578 6579 6580

  SYNOPSIS
    get_next_partition_via_walking()
      part_iter  Partitioning iterator

  DESCRIPTION
6581 6582 6583
    This implementation of PARTITION_ITERATOR::get_next() returns ids of
    partitions that contain records with partitioning field value within
    [start_val, end_val] interval.
6584
    The function conforms to partition_iter_func type.
unknown's avatar
unknown committed
6585 6586 6587 6588 6589 6590 6591 6592 6593 6594

  RETURN 
    partition id
    NOT_A_PARTITION_ID if there are no more partitioning.
*/

static uint32 get_next_partition_via_walking(PARTITION_ITERATOR *part_iter)
{
  uint32 part_id;
  Field *field= part_iter->part_info->part_field_array[0];
6595
  while (part_iter->field_vals.cur != part_iter->field_vals.end)
unknown's avatar
unknown committed
6596
  {
unknown's avatar
unknown committed
6597
    longlong dummy;
6598
    field->store(part_iter->field_vals.cur++, FALSE);
6599
    if (part_iter->part_info->is_sub_partitioned() &&
6600 6601 6602
        !part_iter->part_info->get_part_partition_id(part_iter->part_info,
                                                     &part_id, &dummy) ||
        !part_iter->part_info->get_partition_id(part_iter->part_info,
unknown's avatar
unknown committed
6603
                                                &part_id, &dummy))
unknown's avatar
unknown committed
6604 6605
      return part_id;
  }
6606 6607 6608
  //psergey-todo: return partition(part_func(NULL)) here...
  
  part_iter->field_vals.cur= part_iter->field_vals.start;
unknown's avatar
unknown committed
6609 6610 6611 6612 6613 6614 6615 6616 6617 6618
  return NOT_A_PARTITION_ID;
}


/* Same as get_next_partition_via_walking, but for subpartitions */

static uint32 get_next_subpartition_via_walking(PARTITION_ITERATOR *part_iter)
{
  uint32 part_id;
  Field *field= part_iter->part_info->subpart_field_array[0];
6619 6620 6621
  if (part_iter->field_vals.cur == part_iter->field_vals.end)
  {
    part_iter->field_vals.cur= part_iter->field_vals.start;
unknown's avatar
unknown committed
6622
    return NOT_A_PARTITION_ID;
6623 6624
  }
  field->store(part_iter->field_vals.cur++, FALSE);
unknown's avatar
unknown committed
6625 6626
  return part_iter->part_info->get_subpartition_id(part_iter->part_info);
}
6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646


/*
  Create partition names

  SYNOPSIS
    create_partition_name()
    out:out                   Created partition name string
    in1                       First part
    in2                       Second part
    name_variant              Normal, temporary or renamed partition name

  RETURN VALUE
    NONE

  DESCRIPTION
    This method is used to calculate the partition name, service routine to
    the del_ren_cre_table method.
*/

6647 6648 6649
void create_partition_name(char *out, const char *in1,
                           const char *in2, uint name_variant,
                           bool translate)
6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688
{
  char transl_part_name[FN_REFLEN];
  const char *transl_part;

  if (translate)
  {
    tablename_to_filename(in2, transl_part_name, FN_REFLEN);
    transl_part= transl_part_name;
  }
  else
    transl_part= in2;
  if (name_variant == NORMAL_PART_NAME)
    strxmov(out, in1, "#P#", transl_part, NullS);
  else if (name_variant == TEMP_PART_NAME)
    strxmov(out, in1, "#P#", transl_part, "#TMP#", NullS);
  else if (name_variant == RENAMED_PART_NAME)
    strxmov(out, in1, "#P#", transl_part, "#REN#", NullS);
}


/*
  Create subpartition name

  SYNOPSIS
    create_subpartition_name()
    out:out                   Created partition name string
    in1                       First part
    in2                       Second part
    in3                       Third part
    name_variant              Normal, temporary or renamed partition name

  RETURN VALUE
    NONE

  DESCRIPTION
  This method is used to calculate the subpartition name, service routine to
  the del_ren_cre_table method.
*/

6689 6690 6691
void create_subpartition_name(char *out, const char *in1,
                              const char *in2, const char *in3,
                              uint name_variant)
6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706
{
  char transl_part_name[FN_REFLEN], transl_subpart_name[FN_REFLEN];

  tablename_to_filename(in2, transl_part_name, FN_REFLEN);
  tablename_to_filename(in3, transl_subpart_name, FN_REFLEN);
  if (name_variant == NORMAL_PART_NAME)
    strxmov(out, in1, "#P#", transl_part_name,
            "#SP#", transl_subpart_name, NullS);
  else if (name_variant == TEMP_PART_NAME)
    strxmov(out, in1, "#P#", transl_part_name,
            "#SP#", transl_subpart_name, "#TMP#", NullS);
  else if (name_variant == RENAMED_PART_NAME)
    strxmov(out, in1, "#P#", transl_part_name,
            "#SP#", transl_subpart_name, "#REN#", NullS);
}
6707
#endif
unknown's avatar
unknown committed
6708