List:Commits« Previous MessageNext Message »
From:Mattias Jonsson Date:November 28 2010 8:22pm
Subject:bzr push into mysql-trunk branch (mattias.jonsson:3206 to 3207) WL#5217
View as plain text  
 3207 Mattias Jonsson	2010-11-28
      WL#5217: Add explicit partition selection
      
      Work-in-progress, code complete.
      
      Needs additional tests and reviews.
     @ include/my_base.h
        Added new handler error
     @ mysql-test/r/partition_mgm_err.result
        Temporary change, since I raised the maximum number of partitions
     @ mysql-test/r/wl2682.result
        Temporary test file, will be renamed/merged
     @ mysql-test/r/wl5217.result
        Temporary test file, will be renamed/merged
     @ mysql-test/suite/parts/r/partition_exch_qa_13.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_exch_qa_2.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc0_archive.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc0_innodb.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc0_memory.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc0_myisam.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc1_archive.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc1_innodb.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc1_memory.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc1_myisam.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc2_archive.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc2_innodb.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc2_memory.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_mgm_lc2_myisam.result
        Correction of error message
     @ mysql-test/suite/parts/r/partition_repair_myisam.result
        Quoting partition, since it is now a reserved word
     @ mysql-test/t/partition_mgm_err.test
        Temporary change, since I raised the maximum number of partitions
     @ mysql-test/t/wl2682.test
        Temporary test file, will be renamed/merged
     @ mysql-test/t/wl5217.test
        Temporary test file, will be renamed/merged
     @ mysys/hash.c
        Updated function header
     @ mysys/my_handler.c
        Corrected comment
     @ mysys/my_handler_errors.h
        Added handler error text
     @ sql/ha_partition.cc
        Added partition name hash on partition area on table_share.
        Changed used_partitions to lock/read_partitions.
        Skipping locking (external_lock, store_lock, start_stmt) when not to be used.
        Removed dead code.
     @ sql/ha_partition.h
        Added bitmap to store locked partitions.
        Added private functions for populating partition name hash
        on table_share.
     @ sql/handler.cc
        Added asserts for required locks for different SE API calls.
     @ sql/handler.h
        Removed unused variable and added debug asserts.
     @ sql/mysqld.cc
        Added handler statistic variable for external lock count.
     @ sql/opt_range.cc
        Changed used_partitions to lock/read_partitions.
     @ sql/partition_info.cc
        Added function for pruning as specified in the PARTITION() clause.
     @ sql/partition_info.h
        Changed used_partitions to read/lock_partitions.
        Added function to prune according to PARTITION() clause.
     @ sql/share/errmsg-utf8.txt
        Added three new error messages.
        Corrected one error message.
     @ sql/sql_base.cc
        Adding call to prune partitions according to PARTITION() clause,
        done as last thing in open_tables() function.
     @ sql/sql_class.h
        Added handler statistics variable for external_lock count.
     @ sql/sql_const.h
        Added define for number of partitions before using
        partition name hash.
        TODO: Benchmark for best value, increase max number of partitions?
     @ sql/sql_lex.cc
        Added argument for including partition name list.
     @ sql/sql_lex.h
        Added argument for including partition name list.
     @ sql/sql_parse.cc
        Added argument for including partition name list.
     @ sql/sql_partition.cc
        Using table's mem_root instead of thd's.
        Changed used_partitions to read/lock_partitions.
     @ sql/sql_yacc.yy
        Added PARTITON () clause as allowed syntax (see WL#5217).
        Made PARTITION_SYM a reserved word. This reduced the shift/reduce
        conflicts by 3 and did not increase any new conflicts when
        added the PARTITION () clause in table_factor.
     @ sql/table.cc
        Added helper function for partition name hash.
     @ sql/table.h
        Added structures to handle partition names used in the
        PARTITION () clause.

    added:
      mysql-test/r/wl2682.result
      mysql-test/r/wl5217.result
      mysql-test/t/wl2682.test
      mysql-test/t/wl5217.test
    modified:
      include/my_base.h
      mysql-test/r/partition_mgm_err.result
      mysql-test/suite/parts/r/partition_exch_qa_13.result
      mysql-test/suite/parts/r/partition_exch_qa_2.result
      mysql-test/suite/parts/r/partition_mgm_lc0_archive.result
      mysql-test/suite/parts/r/partition_mgm_lc0_innodb.result
      mysql-test/suite/parts/r/partition_mgm_lc0_memory.result
      mysql-test/suite/parts/r/partition_mgm_lc0_myisam.result
      mysql-test/suite/parts/r/partition_mgm_lc1_archive.result
      mysql-test/suite/parts/r/partition_mgm_lc1_innodb.result
      mysql-test/suite/parts/r/partition_mgm_lc1_memory.result
      mysql-test/suite/parts/r/partition_mgm_lc1_myisam.result
      mysql-test/suite/parts/r/partition_mgm_lc2_archive.result
      mysql-test/suite/parts/r/partition_mgm_lc2_innodb.result
      mysql-test/suite/parts/r/partition_mgm_lc2_memory.result
      mysql-test/suite/parts/r/partition_mgm_lc2_myisam.result
      mysql-test/suite/parts/r/partition_repair_myisam.result
      mysql-test/suite/parts/t/partition_repair_myisam.test
      mysql-test/t/partition_mgm_err.test
      mysys/hash.c
      mysys/my_handler.c
      mysys/my_handler_errors.h
      sql/ha_partition.cc
      sql/ha_partition.h
      sql/handler.cc
      sql/handler.h
      sql/mysqld.cc
      sql/opt_range.cc
      sql/partition_info.cc
      sql/partition_info.h
      sql/share/errmsg-utf8.txt
      sql/sql_base.cc
      sql/sql_class.h
      sql/sql_const.h
      sql/sql_lex.cc
      sql/sql_lex.h
      sql/sql_parse.cc
      sql/sql_partition.cc
      sql/sql_yacc.yy
      sql/table.cc
      sql/table.h
 3206 Alexander Nozdrin	2010-11-24 [merge]
      Auto-merge from mysql-trunk-merge (WL#2775).

    added:
      mysql-test/extra/rpl_tests/rpl_change_master.test
      mysql-test/extra/rpl_tests/rpl_crash_safe.inc
      mysql-test/extra/rpl_tests/rpl_crash_safe.test
      mysql-test/include/not_master_info_table.inc
      mysql-test/include/not_relay_log_info_table.inc
      mysql-test/suite/rpl/r/rpl_change_master_crash_safe.result
      mysql-test/suite/rpl/r/rpl_migration_crash_safe.result
      mysql-test/suite/rpl/r/rpl_mixed_crash_safe.result
      mysql-test/suite/rpl/r/rpl_row_crash_safe.result
      mysql-test/suite/rpl/r/rpl_stm_crash_safe.result
      mysql-test/suite/rpl/t/rpl_change_master_crash_safe-slave.opt
      mysql-test/suite/rpl/t/rpl_change_master_crash_safe.test
      mysql-test/suite/rpl/t/rpl_migration_crash_safe.test
      mysql-test/suite/rpl/t/rpl_mixed_crash_safe-slave.opt
      mysql-test/suite/rpl/t/rpl_mixed_crash_safe.test
      mysql-test/suite/rpl/t/rpl_row_crash_safe-slave.opt
      mysql-test/suite/rpl/t/rpl_row_crash_safe.test
      mysql-test/suite/rpl/t/rpl_stm_crash_safe-slave.opt
      mysql-test/suite/rpl/t/rpl_stm_crash_safe.test
      sql/rpl_info_table.cc
      sql/rpl_info_table.h
      sql/rpl_info_table_access.cc
      sql/rpl_info_table_access.h
      sql/rpl_info_values.cc
      sql/rpl_info_values.h
    modified:
      client/mysqldump.c
      mysql-test/collections/default.experimental
      mysql-test/extra/rpl_tests/rpl_flsh_tbls.test
      mysql-test/r/1st.result
      mysql-test/r/connect.result
      mysql-test/r/information_schema.result
      mysql-test/r/log_tables.result
      mysql-test/r/log_tables_upgrade.result
      mysql-test/r/mysql_upgrade.result
      mysql-test/r/mysql_upgrade_ssl.result
      mysql-test/r/mysqlcheck.result
      mysql-test/r/system_mysql_db.result
      mysql-test/suite/funcs_1/r/is_columns_mysql.result
      mysql-test/suite/funcs_1/r/is_key_column_usage.result
      mysql-test/suite/funcs_1/r/is_statistics.result
      mysql-test/suite/funcs_1/r/is_statistics_mysql.result
      mysql-test/suite/funcs_1/r/is_table_constraints.result
      mysql-test/suite/funcs_1/r/is_table_constraints_mysql.result
      mysql-test/suite/funcs_1/r/is_tables_mysql.result
      mysql-test/suite/perfschema/r/pfs_upgrade_lc0.result
      mysql-test/suite/perfschema/r/pfs_upgrade_lc1.result
      mysql-test/suite/perfschema/r/pfs_upgrade_lc2.result
      mysql-test/suite/rpl/r/rpl_change_master.result
      mysql-test/suite/rpl/t/rpl_change_master.test
      mysql-test/suite/rpl/t/rpl_flushlog_loop.test
      mysql-test/suite/rpl/t/rpl_rotate_logs.test
      mysql-test/suite/rpl/t/rpl_seconds_behind_master.test
      mysql-test/suite/rpl/t/rpl_show_master_info_file.test
      mysql-test/suite/rpl/t/rpl_stm_flsh_tbls.test
      mysql-test/suite/rpl/t/rpl_sync.test
      mysql-test/suite/sys_vars/t/master_info_repository_basic.test
      mysql-test/suite/sys_vars/t/relay_log_info_repository_basic.test
      mysql-test/t/system_mysql_db_fix40123.test
      mysql-test/t/system_mysql_db_fix50030.test
      mysql-test/t/system_mysql_db_fix50117.test
      scripts/mysql_install_db.pl.in
      scripts/mysql_install_db.sh
      scripts/mysql_system_tables.sql
      sql/CMakeLists.txt
      sql/Makefile.am
      sql/lock.cc
      sql/log_event.cc
      sql/rpl_info.h
      sql/rpl_info_factory.cc
      sql/rpl_info_factory.h
      sql/rpl_info_file.cc
      sql/rpl_info_file.h
      sql/rpl_info_handler.cc
      sql/rpl_info_handler.h
      sql/rpl_rli.h
      sql/rpl_slave.cc
      sql/rpl_slave.h
      sql/server_ids.h
      sql/share/errmsg-utf8.txt
      sql/sql_base.cc
      sql/sql_base.h
      sql/sql_binlog.cc
      sql/sql_class.h
      sql/sql_parse.cc
      sql/sql_parse.h
      sql/sys_vars.cc
      sql/table.cc
      sql/table.h
=== modified file 'include/my_base.h'
--- a/include/my_base.h	2010-06-25 09:34:37 +0000
+++ b/include/my_base.h	2010-11-28 18:24:58 +0000
@@ -443,7 +443,9 @@ enum ha_base_keytype {
 #define HA_ERR_FILE_TOO_SHORT	  175	 /* File too short */
 #define HA_ERR_WRONG_CRC	  176	 /* Wrong CRC on page */
 #define HA_ERR_TOO_MANY_CONCURRENT_TRXS 177 /*Too many active concurrent transactions */
-#define HA_ERR_LAST               177    /* Copy of last error nr */
+/* There's no explicitly listed partition in table for the given value */
+#define HA_ERR_NOT_IN_LOCK_PARTITIONS 178
+#define HA_ERR_LAST               178    /* Copy of last error nr */
 
 /* Number of different errors */
 #define HA_ERR_ERRORS            (HA_ERR_LAST - HA_ERR_FIRST + 1)

=== modified file 'mysql-test/r/partition_mgm_err.result'
--- a/mysql-test/r/partition_mgm_err.result	2009-09-15 15:07:52 +0000
+++ b/mysql-test/r/partition_mgm_err.result	2010-11-28 18:24:58 +0000
@@ -98,8 +98,10 @@ PARTITION BY KEY (a)
 (PARTITION x0, PARTITION x1);
 ALTER TABLE t1 ADD PARTITION PARTITIONS 0;
 ERROR HY000: At least one partition must be added
-ALTER TABLE t1 ADD PARTITION PARTITIONS 1024;
+ALTER TABLE t1 ADD PARTITION PARTITIONS 17000;
 ERROR HY000: Too many partitions (including subpartitions) were defined
+ALTER TABLE t1 ADD PARTITION PARTITIONS 1024;
+ALTER TABLE t1 COALESCE PARTITION 1024;
 ALTER TABLE t1 DROP PARTITION x0;
 ERROR HY000: DROP PARTITION can only be used on RANGE/LIST partitions
 ALTER TABLE t1 COALESCE PARTITION 1;

=== added file 'mysql-test/r/wl2682.result'
--- a/mysql-test/r/wl2682.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/wl2682.result	2010-11-28 18:24:58 +0000
@@ -0,0 +1,336 @@
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+CREATE TABLE `t1` (
+`id` int(11) default NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1
+PARTITION BY RANGE (id) (
+PARTITION p0 VALUES LESS THAN (6) ENGINE = MyISAM,
+PARTITION p1 VALUES LESS THAN (11) ENGINE = MyISAM,
+PARTITION p2 VALUES LESS THAN (16) ENGINE = MyISAM,
+PARTITION p3 VALUES LESS THAN (21) ENGINE = MyISAM);
+INSERT INTO `t1` VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10),
+(11), (12), (13), (14), (15), (16), (17), (18), (19), (20);
+SELECT * FROM t1;
+id
+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+SELECT * FROM t1 PARTITION (p0);
+id
+1
+2
+3
+4
+5
+SELECT * FROM t1 PARTITION (p1);
+id
+6
+7
+8
+9
+10
+SELECT * FROM t1 PARTITION (p2);
+id
+11
+12
+13
+14
+15
+SELECT * FROM t1 PARTITION (p3);
+id
+16
+17
+18
+19
+20
+SELECT * FROM t1 PARTITION (p3) WHERE id = 2;
+id
+SELECT * FROM t1 PARTITION (foo);
+ERROR HY000: partition 'foo' doesn't exist
+CREATE TABLE `t2` (
+`id` int(11) NOT NULL DEFAULT 0,
+PRIMARY KEY (`id`)
+) ENGINE=MyISAM DEFAULT CHARSET=latin1
+PARTITION BY RANGE (id) (
+PARTITION p0 VALUES LESS THAN (6) ENGINE = MyISAM,
+PARTITION p1 VALUES LESS THAN (11) ENGINE = MyISAM,
+PARTITION p2 VALUES LESS THAN (16) ENGINE = MyISAM,
+PARTITION p3 VALUES LESS THAN (21) ENGINE = MyISAM);
+INSERT INTO `t2` VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10),
+(11), (12), (13), (14), (15), (16), (17), (18), (19), (20);
+SELECT * FROM t2;
+id
+1
+2
+3
+4
+5
+6
+7
+8
+9
+10
+11
+12
+13
+14
+15
+16
+17
+18
+19
+20
+SELECT * FROM t2 PARTITION (p0);
+id
+1
+2
+3
+4
+5
+SELECT * FROM t2 PARTITION (p1);
+id
+6
+7
+8
+9
+10
+SELECT * FROM t2 PARTITION (p2);
+id
+11
+12
+13
+14
+15
+SELECT * FROM t2 PARTITION (p3);
+id
+16
+17
+18
+19
+20
+SELECT * FROM t2 PARTITION (p3) ORDER BY id;
+id
+16
+17
+18
+19
+20
+SELECT * FROM t2 PARTITION (p3) WHERE id = 2;
+id
+SELECT * FROM t2 PARTITION (foo);
+ERROR HY000: partition 'foo' doesn't exist
+DROP TABLE IF EXISTS `t3`;
+Warnings:
+Note	1051	Unknown table 'test.t3'
+CREATE TABLE `t3` (
+`id` int(32) default NULL,
+`name` varchar(32) default NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1 
+PARTITION BY LIST (id) (
+PARTITION p0 VALUES IN (1,3,5,7),
+PARTITION p1 VALUES IN (0,2,4,6,8),
+PARTITION p2 VALUES IN (9,10,11,12,13)
+);
+INSERT INTO `t3` VALUES (1,'first'), (3,'third'),(5,'fifth'),(7,'seventh'),(0,'zilch'),(2,'second'),(4,'fourth'),(6,'sixth'),(8,'eighth'),(9,'ninth'),(10,'tenth'),(11,'eleventh'),(12,'twelfth'),(13,'thirteenth');
+SELECT * FROM `t3`;
+id	name
+1	first
+3	third
+5	fifth
+7	seventh
+0	zilch
+2	second
+4	fourth
+6	sixth
+8	eighth
+9	ninth
+10	tenth
+11	eleventh
+12	twelfth
+13	thirteenth
+SELECT * FROM `t3` PARTITION (p0);
+id	name
+1	first
+3	third
+5	fifth
+7	seventh
+SELECT * FROM `t3` PARTITION (p1);
+id	name
+0	zilch
+2	second
+4	fourth
+6	sixth
+8	eighth
+SELECT * FROM `t3` PARTITION (p2);
+id	name
+9	ninth
+10	tenth
+11	eleventh
+12	twelfth
+13	thirteenth
+SELECT * FROM `t3` PARTITION (p2) ORDER BY id;
+id	name
+9	ninth
+10	tenth
+11	eleventh
+12	twelfth
+13	thirteenth
+DROP TABLE IF EXISTS `t4`;
+Warnings:
+Note	1051	Unknown table 'test.t4'
+CREATE TABLE `t4` (
+`id` int(32) default NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1 PARTITION BY HASH (id) ;
+INSERT INTO `t4` SELECT * FROM `t2`;
+INSERT INTO `t4` SELECT * FROM `t2` ORDER BY id;
+CREATE TABLE `t5` (
+id int(32),
+name varchar(64),
+purchased date)
+PARTITION BY RANGE( YEAR(purchased) )
+SUBPARTITION BY HASH( TO_DAYS(purchased) ) (
+PARTITION p0 VALUES LESS THAN (1990) (
+SUBPARTITION s0,
+SUBPARTITION s1
+),
+PARTITION p1 VALUES LESS THAN (2000) (
+SUBPARTITION s2,
+SUBPARTITION s3
+),
+PARTITION p2 VALUES LESS THAN MAXVALUE (
+SUBPARTITION s4,
+SUBPARTITION s5
+)
+);
+INSERT INTO `t5` VALUES (1, 'aaaaaaa', '2006-01-05 00:00:00');
+INSERT INTO `t5` VALUES (2, 'bbbbbbb', '2005-08-05 00:00:00');
+INSERT INTO `t5` VALUES (3, 'ccccccc', '1985-08-07 00:00:00');
+INSERT INTO `t5` VALUES (4, 'ddddddd', '2000-01-01 00:00:00');
+INSERT INTO `t5` VALUES (5, 'eeeeeee', '1999-12-01 00:00:00');
+INSERT INTO `t5` VALUES (6, 'fffffff', '2003-11-12 00:00:00');
+INSERT INTO `t5` VALUES (7, 'ggggggg', '1990-01-05 00:00:00');
+INSERT INTO `t5` VALUES (8, 'hhhhhhh', '1978-01-05 00:00:00');
+INSERT INTO `t5` VALUES (9, 'iiiiiii', '1979-01-05 00:00:00');
+INSERT INTO `t5` VALUES (10, 'jjjjjjj', '1992-01-05 00:00:00');
+INSERT INTO `t5` VALUES (11, 'kkkkkkk', '1993-01-05 00:00:00');
+INSERT INTO `t5` VALUES (12, 'mmmmmmm', '1994-01-05 00:00:00');
+INSERT INTO `t5` VALUES (13, 'nnnnnnn', '1989-01-05 00:00:00');
+INSERT INTO `t5` VALUES (14, 'ooooooo', '1983-12-05 00:00:00');
+INSERT INTO `t5` VALUES (15, 'ppppppp', '1986-06-05 00:00:00');
+INSERT INTO `t5` VALUES (16, 'qqqqqqq', '1974-04-11 00:00:00');
+INSERT INTO `t5` VALUES (17, 'qqqqqqq', '1960-03-15 00:00:00');
+INSERT INTO `t5` VALUES (18, 'sssssss', '1950-09-23 00:00:00');
+INSERT INTO `t5` VALUES (19, 'ttttttt', '1999-08-02 00:00:00');
+INSERT INTO `t5` VALUES (20, 'uuuuuuu', '1994-05-28 00:00:00');
+SELECT * FROM `t5`;
+id	name	purchased
+8	hhhhhhh	1978-01-05
+13	nnnnnnn	1989-01-05
+14	ooooooo	1983-12-05
+18	sssssss	1950-09-23
+3	ccccccc	1985-08-07
+9	iiiiiii	1979-01-05
+15	ppppppp	1986-06-05
+16	qqqqqqq	1974-04-11
+17	qqqqqqq	1960-03-15
+5	eeeeeee	1999-12-01
+12	mmmmmmm	1994-01-05
+7	ggggggg	1990-01-05
+10	jjjjjjj	1992-01-05
+11	kkkkkkk	1993-01-05
+19	ttttttt	1999-08-02
+20	uuuuuuu	1994-05-28
+2	bbbbbbb	2005-08-05
+6	fffffff	2003-11-12
+1	aaaaaaa	2006-01-05
+4	ddddddd	2000-01-01
+SELECT * FROM `t5` PARTITION(p0) ORDER BY id;
+id	name	purchased
+3	ccccccc	1985-08-07
+8	hhhhhhh	1978-01-05
+9	iiiiiii	1979-01-05
+13	nnnnnnn	1989-01-05
+14	ooooooo	1983-12-05
+15	ppppppp	1986-06-05
+16	qqqqqqq	1974-04-11
+17	qqqqqqq	1960-03-15
+18	sssssss	1950-09-23
+SELECT * FROM `t5` PARTITION(s0) ORDER BY id;
+id	name	purchased
+8	hhhhhhh	1978-01-05
+13	nnnnnnn	1989-01-05
+14	ooooooo	1983-12-05
+18	sssssss	1950-09-23
+SELECT * FROM `t5` PARTITION(s1) ORDER BY id;
+id	name	purchased
+3	ccccccc	1985-08-07
+9	iiiiiii	1979-01-05
+15	ppppppp	1986-06-05
+16	qqqqqqq	1974-04-11
+17	qqqqqqq	1960-03-15
+SELECT * FROM `t5` PARTITION(p1) ORDER BY id;
+id	name	purchased
+5	eeeeeee	1999-12-01
+7	ggggggg	1990-01-05
+10	jjjjjjj	1992-01-05
+11	kkkkkkk	1993-01-05
+12	mmmmmmm	1994-01-05
+19	ttttttt	1999-08-02
+20	uuuuuuu	1994-05-28
+SELECT * FROM `t5` PARTITION(s2) ORDER BY id;
+id	name	purchased
+5	eeeeeee	1999-12-01
+12	mmmmmmm	1994-01-05
+SELECT * FROM `t5` PARTITION(s3) ORDER BY id;
+id	name	purchased
+7	ggggggg	1990-01-05
+10	jjjjjjj	1992-01-05
+11	kkkkkkk	1993-01-05
+19	ttttttt	1999-08-02
+20	uuuuuuu	1994-05-28
+SELECT * FROM `t5` PARTITION(p2) ORDER BY id;
+id	name	purchased
+1	aaaaaaa	2006-01-05
+2	bbbbbbb	2005-08-05
+4	ddddddd	2000-01-01
+6	fffffff	2003-11-12
+SELECT * FROM `t5` PARTITION(s4) ORDER BY id;
+id	name	purchased
+2	bbbbbbb	2005-08-05
+6	fffffff	2003-11-12
+SELECT * FROM `t5` PARTITION(s5) ORDER BY id;
+id	name	purchased
+1	aaaaaaa	2006-01-05
+4	ddddddd	2000-01-01
+drop table t1,t2,t3,t4,t5;
+create table t1 (a int) partition by hash(a) partitions 3;
+insert into t1 values(1),(2),(3);
+explain partitions select * from t1 where a=1;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	p1	system	NULL	NULL	NULL	NULL	1	
+explain partitions select * from t1 partition (p1) where a=1;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	p1	system	NULL	NULL	NULL	NULL	1	
+explain partitions select * from t1 partition (p1) where a=1 or a=2;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	p1	system	NULL	NULL	NULL	NULL	1	
+explain partitions select * from t1 partition (p2) where a=1;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+drop table t1;

=== added file 'mysql-test/r/wl5217.result'
--- a/mysql-test/r/wl5217.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/wl5217.result	2010-11-28 18:24:58 +0000
@@ -0,0 +1,410 @@
+# Original tests for WL#5217
+# First test that the syntax is OK
+CREATE TABLE t1
+(a INT NOT NULL,
+b varchar (64),
+INDEX (b,a),
+PRIMARY KEY (a))
+ENGINE = InnoDB
+PARTITION BY RANGE (a)
+SUBPARTITION BY HASH (a) SUBPARTITIONS 2
+(PARTITION pNeg VALUES LESS THAN (0)
+(SUBPARTITION subp0,
+SUBPARTITION subp1),
+PARTITION `p0-9` VALUES LESS THAN (10)
+(SUBPARTITION subp2,
+SUBPARTITION subp3),
+PARTITION `p10-99` VALUES LESS THAN (100)
+(SUBPARTITION subp4,
+SUBPARTITION subp5),
+PARTITION `p100-99999` VALUES LESS THAN (100000)
+(SUBPARTITION subp6,
+SUBPARTITION subp7));
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `a` int(11) NOT NULL,
+  `b` varchar(64) DEFAULT NULL,
+  PRIMARY KEY (`a`),
+  KEY `b` (`b`,`a`)
+) ENGINE=InnoDB DEFAULT CHARSET=latin1
+/*!50100 PARTITION BY RANGE (a)
+SUBPARTITION BY HASH (a)
+(PARTITION pNeg VALUES LESS THAN (0)
+ (SUBPARTITION subp0 ENGINE = InnoDB,
+  SUBPARTITION subp1 ENGINE = InnoDB),
+ PARTITION `p0-9` VALUES LESS THAN (10)
+ (SUBPARTITION subp2 ENGINE = InnoDB,
+  SUBPARTITION subp3 ENGINE = InnoDB),
+ PARTITION `p10-99` VALUES LESS THAN (100)
+ (SUBPARTITION subp4 ENGINE = InnoDB,
+  SUBPARTITION subp5 ENGINE = InnoDB),
+ PARTITION `p100-99999` VALUES LESS THAN (100000)
+ (SUBPARTITION subp6 ENGINE = InnoDB,
+  SUBPARTITION subp7 ENGINE = InnoDB)) */
+SHOW CREATE TABLE t1 PARTITION (subp0);
+ERROR 42000: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PARTITION (subp0)' at line 1
+# Not a correct partition list
+INSERT INTO t1 PARTITION () VALUES (1, "error");
+ERROR 42000: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ') VALUES (1, "error")' at line 1
+INSERT INTO t1 PARTITION (pNonExisting) VALUES (1, "error");
+ERROR HY000: partition 'pNonExisting' doesn't exist
+INSERT INTO t1 PARTITION (pNeg, pNonExisting) VALUES (1, "error");
+ERROR HY000: partition 'pNonExisting' doesn't exist
+# Duplicate partitions and overlapping partitions and subpartitios is OK
+INSERT INTO t1 PARTITION (pNeg, pNeg) VALUES (-1, "pNeg(-subp1)");
+INSERT INTO t1 PARTITION (pNeg, subp0) VALUES (-3, "pNeg(-subp1)");
+INSERT INTO t1 PARTITION (pNeg, subp0) VALUES (-2, "(pNeg-)subp0");
+# should be correct
+INSERT INTO t1 PARTITION (`p100-99999`) VALUES (100, "`p100-99999`(-subp6)"), (101, "`p100-99999`(-subp7)"), (1000, "`p100-99999`(-subp6)");
+INSERT INTO t1 PARTITION(`p10-99`,subp3) VALUES (1, "subp3"), (10, "p10-99");
+# Not matching partitions with inserted value
+INSERT INTO t1 PARTITION (pNeg, pNeg) VALUES (1, "error");
+ERROR HY000: Found a row not matching the given partition set
+INSERT INTO t1 PARTITION (pNeg, subp0) VALUES (1, "error");
+ERROR HY000: Found a row not matching the given partition set
+INSERT INTO t1 PARTITION (`p100-99999`) VALUES (1, "error"), (10, "error");
+ERROR HY000: Found a row not matching the given partition set
+INSERT INTO t1 VALUES (1000000, "error"), (9999999, "error");
+ERROR HY000: Table has no partition for value 1000000
+INSERT INTO t1 PARTITION (pNeg, subp4) VALUES (-7, "pNeg(-subp1)"), (-10, "pNeg(-subp0)"), (-1, "pNeg(-subp1)"), (-99, "pNeg(-subp1)");
+Got one of the listed errors
+SELECT * FROM t1;
+a	b
+-2	(pNeg-)subp0
+10	p10-99
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+1	subp3
+100	`p100-99999`(-subp6)
+1000	`p100-99999`(-subp6)
+101	`p100-99999`(-subp7)
+SELECT PARTITION_NAME, SUBPARTITION_NAME, TABLE_ROWS
+FROM INFORMATION_SCHEMA.PARTITIONS
+WHERE TABLE_SCHEMA = 'test'
+AND TABLE_NAME = 't1';
+PARTITION_NAME	SUBPARTITION_NAME	TABLE_ROWS
+pNeg	subp0	1
+pNeg	subp1	2
+p0-9	subp2	0
+p0-9	subp3	1
+p10-99	subp4	1
+p10-99	subp5	0
+p100-99999	subp6	2
+p100-99999	subp7	1
+SELECT * FROM t1 PARTITION (pNonexistent);
+ERROR HY000: partition 'pNonexistent' doesn't exist
+SELECT * FROM t1 PARTITION (subp2);
+a	b
+SELECT * FROM t1 PARTITION (subp2,pNeg) AS TableAlias;
+a	b
+-2	(pNeg-)subp0
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+SELECT * FROM t1 PARTITION (subp3) AS TableAlias;
+a	b
+1	subp3
+SELECT COUNT(*) FROM t1 PARTITION (`p10-99`);
+COUNT(*)
+1
+SELECT * FROM t1 WHERE a = 1000000;
+a	b
+SELECT * FROM t1 PARTITION (pNeg) WHERE a = 100;
+a	b
+# Test that EXPLAIN PARTITION works
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (pNonexistent);
+ERROR HY000: partition 'pNonexistent' doesn't exist
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (subp2);
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	p0-9_subp2	index	NULL	b	71	NULL	2	Using index
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (subp2,pNeg) AS TableAlias;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	TableAlias	pNeg_subp0,pNeg_subp1,p0-9_subp2	index	NULL	b	71	NULL	4	Using index
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (subp3) AS TableAlias;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	TableAlias	p0-9_subp3	index	NULL	b	71	NULL	2	Using index
+EXPLAIN PARTITIONS SELECT COUNT(*) FROM t1 PARTITION (`p10-99`);
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	p10-99_subp4,p10-99_subp5	index	NULL	PRIMARY	4	NULL	2	Using index
+EXPLAIN PARTITIONS SELECT * FROM t1 WHERE a = 1000000;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (pNeg) WHERE a = 100;
+id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+# Test that it actually prunes the partitions
+# Test that open/lock/unlock/close is also pruned
+# Test what happens when no partition can be found
+SELECT * FROM t1 PARTITION (pNeg) WHERE a = 100;
+a	b
+# Test how it changes the alias/keywords/reserved words
+SELECT * FROM t1 PARTITION;
+ERROR 42000: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1
+SELECT * FROM t1 `PARTITION`;
+a	b
+-2	(pNeg-)subp0
+10	p10-99
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+1	subp3
+100	`p100-99999`(-subp6)
+1000	`p100-99999`(-subp6)
+101	`p100-99999`(-subp7)
+SELECT * FROM t1 AS PARTITION;
+ERROR 42000: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PARTITION' at line 1
+SELECT * FROM t1 AS `PARTITION`;
+a	b
+-2	(pNeg-)subp0
+10	p10-99
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+1	subp3
+100	`p100-99999`(-subp6)
+1000	`p100-99999`(-subp6)
+101	`p100-99999`(-subp7)
+# Test REPLACE
+REPLACE INTO t1 PARTITION (subp0) VALUES (-21, 'Should fail!');
+ERROR HY000: Found a row not matching the given partition set
+REPLACE INTO t1 PARTITION (subp1) VALUES (-21, 'Insert by REPLACE');
+SELECT * FROM t1 PARTITION (pNeg);
+a	b
+-2	(pNeg-)subp0
+-21	Insert by REPLACE
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+REPLACE INTO t1 PARTITION (subp1) VALUES (-21, 'REPLACEd by REPLACE');
+SELECT * FROM t1 PARTITION (pNeg);
+a	b
+-2	(pNeg-)subp0
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+-21	REPLACEd by REPLACE
+# Test LOAD
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`);
+a	b
+-2	(pNeg-)subp0
+10	p10-99
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+-21	REPLACEd by REPLACE
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`) INTO OUTFILE 'loadtest.txt';
+ALTER TABLE t1 TRUNCATE PARTITION pNeg, `p10-99`;
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`);
+a	b
+LOAD DATA INFILE 'loadtest.txt' INTO TABLE t1 PARTITION (pNeg);
+ERROR HY000: Found a row not matching the given partition set
+# Should be rolled back if possible
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`);
+a	b
+LOAD DATA INFILE 'loadtest.txt' INTO TABLE t1 PARTITION (pNeg, subp4, subp5);
+# Test UPDATE
+FLUSH STATUS;
+UPDATE t1 PARTITION(subp0) SET b = concat(b, ', Updated');
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	0
+HANDLER_EXTERNAL_LOCK	4
+HANDLER_READ_FIRST	1
+HANDLER_READ_KEY	2
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	0
+HANDLER_READ_RND_NEXT	2
+HANDLER_UPDATE	1
+HANDLER_WRITE	10
+FLUSH STATUS;
+UPDATE t1 PARTITION(subp0) SET b = concat(b, ', Updated2') WHERE a = 100;
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	0
+HANDLER_EXTERNAL_LOCK	4
+HANDLER_READ_FIRST	0
+HANDLER_READ_KEY	0
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	0
+HANDLER_READ_RND_NEXT	0
+HANDLER_UPDATE	0
+HANDLER_WRITE	10
+FLUSH STATUS;
+UPDATE t1 PARTITION(subp0) SET a = -2, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	0
+HANDLER_EXTERNAL_LOCK	4
+HANDLER_READ_FIRST	0
+HANDLER_READ_KEY	0
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	0
+HANDLER_READ_RND_NEXT	0
+HANDLER_UPDATE	0
+HANDLER_WRITE	10
+FLUSH STATUS;
+UPDATE t1 PARTITION(`p100-99999`) SET a = -2, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+ERROR HY000: Found a row not matching the given partition set
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	0
+HANDLER_EXTERNAL_LOCK	6
+HANDLER_READ_FIRST	0
+HANDLER_READ_KEY	4
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	1
+HANDLER_READ_RND_NEXT	0
+HANDLER_UPDATE	0
+HANDLER_WRITE	10
+FLUSH STATUS;
+UPDATE t1 PARTITION(`p100-99999`, pNeg) SET a = -2, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+Got one of the listed errors
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	0
+HANDLER_EXTERNAL_LOCK	10
+HANDLER_READ_FIRST	0
+HANDLER_READ_KEY	4
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	1
+HANDLER_READ_RND_NEXT	0
+HANDLER_UPDATE	0
+HANDLER_WRITE	11
+FLUSH STATUS;
+UPDATE t1 PARTITION(`p100-99999`, pNeg) SET a = -222, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	1
+HANDLER_EXTERNAL_LOCK	10
+HANDLER_READ_FIRST	0
+HANDLER_READ_KEY	4
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	1
+HANDLER_READ_RND_NEXT	0
+HANDLER_UPDATE	0
+HANDLER_WRITE	11
+SELECT * FROM t1;
+a	b
+-2	(pNeg-)subp0, Updated
+10	p10-99
+-3	pNeg(-subp1)
+-1	pNeg(-subp1)
+-21	REPLACEd by REPLACE
+1	subp3
+1000	`p100-99999`(-subp6)
+-222	`p100-99999`(-subp6), Updated from a = 100
+101	`p100-99999`(-subp7)
+# Test of non matching partition (i.e ER_NO_PARTITION_FOUND)
+FLUSH STATUS;
+UPDATE t1 SET b = concat(b, ', Updated2') WHERE a = 1000000;
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	0
+HANDLER_EXTERNAL_LOCK	18
+HANDLER_READ_FIRST	0
+HANDLER_READ_KEY	0
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	0
+HANDLER_READ_RND_NEXT	0
+HANDLER_UPDATE	0
+HANDLER_WRITE	10
+# Test DELETE
+FLUSH STATUS;
+DELETE FROM t1 PARTITION (pNeg) WHERE a = -1;
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	1
+HANDLER_EXTERNAL_LOCK	6
+HANDLER_READ_FIRST	0
+HANDLER_READ_KEY	2
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	0
+HANDLER_READ_RND_NEXT	0
+HANDLER_UPDATE	0
+HANDLER_WRITE	10
+FLUSH STATUS;
+DELETE FROM t1 PARTITION (subp1) WHERE b like '%subp1%';
+SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+VARIABLE_NAME	VARIABLE_VALUE
+HANDLER_DELETE	1
+HANDLER_EXTERNAL_LOCK	4
+HANDLER_READ_FIRST	1
+HANDLER_READ_KEY	2
+HANDLER_READ_LAST	0
+HANDLER_READ_NEXT	0
+HANDLER_READ_PREV	0
+HANDLER_READ_RND	0
+HANDLER_READ_RND_NEXT	3
+HANDLER_UPDATE	0
+HANDLER_WRITE	10
+FLUSH STATUS;
+# Test multi-table DELETE
+# Test TRUNCATE TABLE (should fail, since one should use
+# ALTER TABLE ... TRUNCATE PARTITION instead)
+TRUNCATE TABLE t1 PARTITION(`p10-99`);
+ERROR 42000: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'PARTITION(`p10-99`)' at line 1
+# Test on non partitioned table
+ALTER TABLE t1 REMOVE PARTITIONING;
+SELECT * FROM t1 PARTITION (pNeg);
+ERROR HY000: PARTITION () clause on non partitioned table
+DROP TABLE t1;

=== modified file 'mysql-test/suite/parts/r/partition_exch_qa_13.result'
--- a/mysql-test/suite/parts/r/partition_exch_qa_13.result	2010-10-29 10:34:33 +0000
+++ b/mysql-test/suite/parts/r/partition_exch_qa_13.result	2010-11-28 18:24:58 +0000
@@ -101,7 +101,7 @@ a	b
 9	Nine
 INSERT INTO t_10 VALUES (10, "TEN");
 ALTER TABLE tp EXCHANGE PARTITION p0 WITH TABLE t_10;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 SELECT * FROM tp WHERE a < 11;
 a	b
 2	Two
@@ -131,7 +131,7 @@ a	b
 8	Eight
 INSERT INTO t_1000 VALUES (99, "Ninetynine");
 ALTER TABLE tp1 EXCHANGE PARTITION p2 WITH TABLE t_1000;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 SELECT * FROM tp1 WHERE a < 1000 AND a > 98;
 a	b
 112	Hundred twelve
@@ -209,7 +209,7 @@ a	b
 188	Hundred eighty-eight
 INSERT INTO tsp_03 VALUES (20, "Twenty");
 ALTER TABLE tsp EXCHANGE PARTITION sp03 WITH TABLE tsp_03;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 SELECT * FROM tsp;
 a	b
 112	Hundred twelve

=== modified file 'mysql-test/suite/parts/r/partition_exch_qa_2.result'
--- a/mysql-test/suite/parts/r/partition_exch_qa_2.result	2010-10-29 10:34:33 +0000
+++ b/mysql-test/suite/parts/r/partition_exch_qa_2.result	2010-11-28 18:24:58 +0000
@@ -127,9 +127,9 @@ ERROR HY000: Table to exchange with part
 ALTER TABLE tsp EXCHANGE PARTITION p0 WITH TABLE t_10;
 ERROR HY000: Subpartitioned table, use subpartition instead of partition
 ALTER TABLE tp EXCHANGE PARTITION p0 WITH TABLE t_100;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 ALTER TABLE tp EXCHANGE PARTITION p2 WITH TABLE t_10;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE IF EXISTS t_10;
 DROP TABLE IF EXISTS t_100;
 DROP TABLE IF EXISTS t_1000;

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc0_archive.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc0_archive.result	2010-08-16 14:22:16 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc0_archive.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc0_innodb.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc0_innodb.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc0_innodb.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc0_memory.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc0_memory.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc0_memory.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc0_myisam.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc0_myisam.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc0_myisam.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc1_archive.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc1_archive.result	2010-08-16 14:22:16 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc1_archive.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc1_innodb.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc1_innodb.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc1_innodb.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc1_memory.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc1_memory.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc1_memory.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc1_myisam.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc1_myisam.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc1_myisam.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc2_archive.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc2_archive.result	2010-08-16 14:22:16 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc2_archive.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc2_innodb.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc2_innodb.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc2_innodb.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc2_memory.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc2_memory.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc2_memory.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_mgm_lc2_myisam.result'
--- a/mysql-test/suite/parts/r/partition_mgm_lc2_myisam.result	2010-06-23 10:48:39 +0000
+++ b/mysql-test/suite/parts/r/partition_mgm_lc2_myisam.result	2010-11-28 18:24:58 +0000
@@ -135,7 +135,7 @@ Partc	YES
 ALTER TABLE TableA EXCHANGE PARTITION parta WITH TABLE TableB;
 INSERT INTO TableB VALUES (11);
 ALTER TABLE TableA EXCHANGE PARTITION Partc WITH TABLE TableB;
-ERROR HY000: Found row that does not match the partition
+ERROR HY000: Found a row that does not match the partition
 DROP TABLE TableB;
 SELECT * FROM TableA;
 a

=== modified file 'mysql-test/suite/parts/r/partition_repair_myisam.result'
--- a/mysql-test/suite/parts/r/partition_repair_myisam.result	2010-06-17 17:17:17 +0000
+++ b/mysql-test/suite/parts/r/partition_repair_myisam.result	2010-11-28 18:24:58 +0000
@@ -270,7 +270,7 @@ PARTITIONS 7;
 SELECT COUNT(*) FROM t1_will_crash;
 COUNT(*)
 33
-SELECT (b % 7) AS partition, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
+SELECT (b % 7) AS `partition`, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
 partition	rows
 0	2
 1	5
@@ -279,7 +279,7 @@ partition	rows
 4	4
 5	4
 6	8
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash ORDER BY partition, b, a;
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash ORDER BY `partition`, b, a;
 partition	b	a	length(c)
 0	0	 lost	64
 0	7	z lost	64
@@ -342,7 +342,7 @@ test.t1_will_crash	repair	status	OK
 SELECT COUNT(*) FROM t1_will_crash;
 COUNT(*)
 29
-SELECT (b % 7) AS partition, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
+SELECT (b % 7) AS `partition`, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
 partition	rows
 1	4
 2	5
@@ -350,7 +350,7 @@ partition	rows
 4	4
 5	4
 6	7
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash ORDER BY partition, b, a;
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash ORDER BY `partition`, b, a;
 partition	b	a	length(c)
 1	1	abc	64
 1	8	tuw	64
@@ -426,9 +426,9 @@ Table	Op	Msg_type	Msg_text
 test.t1_will_crash	repair	info	Delete link points outside datafile at 340
 test.t1_will_crash	repair	info	Delete link points outside datafile at 340
 test.t1_will_crash	repair	status	OK
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash
 WHERE (b % 7) = 6
-ORDER BY partition, b, a;
+ORDER BY `partition`, b, a;
 partition	b	a	length(c)
 6	6	jkl	64
 6	13	ooo	64
@@ -445,18 +445,18 @@ FLUSH TABLES;
 # table, depending if one reads via index or direct on datafile.
 # Since crash when reuse of deleted row space, CHECK MEDIUM or EXTENDED
 # is required (MEDIUM is default) to verify correct behavior!
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash
 WHERE (b % 7) = 6
-ORDER BY partition, b, a;
+ORDER BY `partition`, b, a;
 partition	b	a	length(c)
 6	6	jkl	64
 6	13	ooo	64
 6	34	6 row 2	64
 6	83	 	64
 6	97	zzzzzZzzzzz	64
-SELECT (b % 7) AS partition, b, a FROM (SELECT b,a FROM t1_will_crash) q
+SELECT (b % 7) AS `partition`, b, a FROM (SELECT b,a FROM t1_will_crash) q
 WHERE (b % 7) = 6
-ORDER BY partition, b, a;
+ORDER BY `partition`, b, a;
 partition	b	a
 6	6	jkl
 6	13	ooo
@@ -479,7 +479,7 @@ test.t1_will_crash	repair	status	OK
 SELECT COUNT(*) FROM t1_will_crash;
 COUNT(*)
 29
-SELECT (b % 7) AS partition, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
+SELECT (b % 7) AS `partition`, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
 partition	rows
 1	4
 2	4
@@ -487,7 +487,7 @@ partition	rows
 4	4
 5	4
 6	8
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash ORDER BY partition, b, a;
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash ORDER BY `partition`, b, a;
 partition	b	a	length(c)
 1	1	abc	64
 1	8	tuw	64

=== modified file 'mysql-test/suite/parts/t/partition_repair_myisam.test'
--- a/mysql-test/suite/parts/t/partition_repair_myisam.test	2010-06-17 21:17:30 +0000
+++ b/mysql-test/suite/parts/t/partition_repair_myisam.test	2010-11-28 18:24:58 +0000
@@ -190,8 +190,8 @@ eval INSERT INTO t1_will_crash VALUES
   ('6 row 7 (crash before completely written to datafile)', 27, '$lt$lt');
 --enable_query_log
 SELECT COUNT(*) FROM t1_will_crash;
-SELECT (b % 7) AS partition, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash ORDER BY partition, b, a;
+SELECT (b % 7) AS `partition`, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash ORDER BY `partition`, b, a;
 FLUSH TABLES;
 # testing p0, p1, p3, p6(1)
 --echo # truncating p0 to simulate an empty datafile (not recovered!)
@@ -216,8 +216,8 @@ OPTIMIZE TABLE t1_will_crash;
 CHECK TABLE t1_will_crash;
 REPAIR TABLE t1_will_crash;
 SELECT COUNT(*) FROM t1_will_crash;
-SELECT (b % 7) AS partition, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash ORDER BY partition, b, a;
+SELECT (b % 7) AS `partition`, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash ORDER BY `partition`, b, a;
 FLUSH TABLES;
 
 # testing p2, p4, p6(2, 3)
@@ -254,9 +254,9 @@ FLUSH TABLES;
 #ALTER TABLE t1_will_crash OPTIMIZE PARTITION p6;
 ALTER TABLE t1_will_crash CHECK PARTITION p6;
 ALTER TABLE t1_will_crash REPAIR PARTITION p6;
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash
 WHERE (b % 7) = 6
-ORDER BY partition, b, a;
+ORDER BY `partition`, b, a;
 FLUSH TABLES;
 
 --echo #
@@ -268,18 +268,18 @@ FLUSH TABLES;
 --echo # table, depending if one reads via index or direct on datafile.
 --echo # Since crash when reuse of deleted row space, CHECK MEDIUM or EXTENDED
 --echo # is required (MEDIUM is default) to verify correct behavior!
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash
 WHERE (b % 7) = 6
-ORDER BY partition, b, a;
-SELECT (b % 7) AS partition, b, a FROM (SELECT b,a FROM t1_will_crash) q
+ORDER BY `partition`, b, a;
+SELECT (b % 7) AS `partition`, b, a FROM (SELECT b,a FROM t1_will_crash) q
 WHERE (b % 7) = 6
-ORDER BY partition, b, a;
+ORDER BY `partition`, b, a;
 # NOTE: REBUILD PARTITION without CHECK before, 2 + (1) records will be lost!
 #ALTER TABLE t1_will_crash REBUILD PARTITION p6;
 ALTER TABLE t1_will_crash CHECK PARTITION p6;
 ALTER TABLE t1_will_crash REPAIR PARTITION p6;
 SELECT COUNT(*) FROM t1_will_crash;
-SELECT (b % 7) AS partition, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
-SELECT (b % 7) AS partition, b, a, length(c) FROM t1_will_crash ORDER BY partition, b, a;
+SELECT (b % 7) AS `partition`, COUNT(*) AS rows FROM t1_will_crash GROUP BY (b % 7);
+SELECT (b % 7) AS `partition`, b, a, length(c) FROM t1_will_crash ORDER BY `partition`, b, a;
 ALTER TABLE t1_will_crash CHECK PARTITION all EXTENDED;
 DROP TABLE t1_will_crash;

=== modified file 'mysql-test/t/partition_mgm_err.test'
--- a/mysql-test/t/partition_mgm_err.test	2009-09-15 15:07:52 +0000
+++ b/mysql-test/t/partition_mgm_err.test	2010-11-28 18:24:58 +0000
@@ -147,7 +147,11 @@ PARTITION BY KEY (a)
 ALTER TABLE t1 ADD PARTITION PARTITIONS 0;
 
 --error ER_TOO_MANY_PARTITIONS_ERROR
+ALTER TABLE t1 ADD PARTITION PARTITIONS 17000;
+#--error ER_TOO_MANY_PARTITIONS_ERROR
 ALTER TABLE t1 ADD PARTITION PARTITIONS 1024;
+ALTER TABLE t1 COALESCE PARTITION 1024;
+
 
 --error ER_ONLY_ON_RANGE_LIST_PARTITION
 ALTER TABLE t1 DROP PARTITION x0;

=== added file 'mysql-test/t/wl2682.test'
--- a/mysql-test/t/wl2682.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/wl2682.test	2010-11-28 18:24:58 +0000
@@ -0,0 +1,154 @@
+#
+# WL# 2682
+# Partition select tests.
+#
+-- source include/have_partition.inc
+
+--disable_warnings
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+--enable_warnings
+
+CREATE TABLE `t1` (
+`id` int(11) default NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1
+PARTITION BY RANGE (id) (
+PARTITION p0 VALUES LESS THAN (6) ENGINE = MyISAM,
+PARTITION p1 VALUES LESS THAN (11) ENGINE = MyISAM,
+PARTITION p2 VALUES LESS THAN (16) ENGINE = MyISAM,
+PARTITION p3 VALUES LESS THAN (21) ENGINE = MyISAM);
+
+INSERT INTO `t1` VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10),
+(11), (12), (13), (14), (15), (16), (17), (18), (19), (20);
+
+SELECT * FROM t1;
+SELECT * FROM t1 PARTITION (p0);
+SELECT * FROM t1 PARTITION (p1);
+SELECT * FROM t1 PARTITION (p2);
+SELECT * FROM t1 PARTITION (p3);
+SELECT * FROM t1 PARTITION (p3) WHERE id = 2;
+--error ER_NO_SUCH_PARTITION
+SELECT * FROM t1 PARTITION (foo);
+
+# now try indexes
+CREATE TABLE `t2` (
+`id` int(11) NOT NULL DEFAULT 0,
+PRIMARY KEY (`id`)
+) ENGINE=MyISAM DEFAULT CHARSET=latin1
+PARTITION BY RANGE (id) (
+PARTITION p0 VALUES LESS THAN (6) ENGINE = MyISAM,
+PARTITION p1 VALUES LESS THAN (11) ENGINE = MyISAM,
+PARTITION p2 VALUES LESS THAN (16) ENGINE = MyISAM,
+PARTITION p3 VALUES LESS THAN (21) ENGINE = MyISAM);
+
+INSERT INTO `t2` VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10),
+(11), (12), (13), (14), (15), (16), (17), (18), (19), (20);
+
+SELECT * FROM t2;
+SELECT * FROM t2 PARTITION (p0);
+SELECT * FROM t2 PARTITION (p1);
+SELECT * FROM t2 PARTITION (p2);
+SELECT * FROM t2 PARTITION (p3);
+SELECT * FROM t2 PARTITION (p3) ORDER BY id;
+SELECT * FROM t2 PARTITION (p3) WHERE id = 2;
+--error ER_NO_SUCH_PARTITION
+SELECT * FROM t2 PARTITION (foo);
+
+
+DROP TABLE IF EXISTS `t3`;
+CREATE TABLE `t3` (
+  `id` int(32) default NULL,
+  `name` varchar(32) default NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1 
+PARTITION BY LIST (id) (
+  PARTITION p0 VALUES IN (1,3,5,7),
+  PARTITION p1 VALUES IN (0,2,4,6,8),
+  PARTITION p2 VALUES IN (9,10,11,12,13)
+);
+
+INSERT INTO `t3` VALUES (1,'first'), (3,'third'),(5,'fifth'),(7,'seventh'),(0,'zilch'),(2,'second'),(4,'fourth'),(6,'sixth'),(8,'eighth'),(9,'ninth'),(10,'tenth'),(11,'eleventh'),(12,'twelfth'),(13,'thirteenth');
+
+SELECT * FROM `t3`;
+SELECT * FROM `t3` PARTITION (p0);
+SELECT * FROM `t3` PARTITION (p1);
+SELECT * FROM `t3` PARTITION (p2);
+SELECT * FROM `t3` PARTITION (p2) ORDER BY id;
+
+DROP TABLE IF EXISTS `t4`;
+CREATE TABLE `t4` (
+  `id` int(32) default NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1 PARTITION BY HASH (id) ;
+
+INSERT INTO `t4` SELECT * FROM `t2`;
+INSERT INTO `t4` SELECT * FROM `t2` ORDER BY id;
+# not sure how to do this, since names could be anything
+#SELECT * FROM `t4` PARTITION (p0);
+#SELECT * FROM `t4` PARTITION (p1);
+#SELECT * FROM `t4` PARTITION (p2);
+#SELECT * FROM `t4` PARTITION (p3);
+#SELECT * FROM `t4` PARTITION (p3) ORDER BY id;
+
+CREATE TABLE `t5` (
+  id int(32),
+  name varchar(64),
+  purchased date)
+PARTITION BY RANGE( YEAR(purchased) )
+    SUBPARTITION BY HASH( TO_DAYS(purchased) ) (
+        PARTITION p0 VALUES LESS THAN (1990) (
+            SUBPARTITION s0,
+            SUBPARTITION s1
+        ),
+        PARTITION p1 VALUES LESS THAN (2000) (
+            SUBPARTITION s2,
+            SUBPARTITION s3
+        ),
+        PARTITION p2 VALUES LESS THAN MAXVALUE (
+            SUBPARTITION s4,
+            SUBPARTITION s5
+        )
+    );
+
+INSERT INTO `t5` VALUES (1, 'aaaaaaa', '2006-01-05 00:00:00');
+INSERT INTO `t5` VALUES (2, 'bbbbbbb', '2005-08-05 00:00:00');
+INSERT INTO `t5` VALUES (3, 'ccccccc', '1985-08-07 00:00:00');
+INSERT INTO `t5` VALUES (4, 'ddddddd', '2000-01-01 00:00:00');
+INSERT INTO `t5` VALUES (5, 'eeeeeee', '1999-12-01 00:00:00');
+INSERT INTO `t5` VALUES (6, 'fffffff', '2003-11-12 00:00:00');
+INSERT INTO `t5` VALUES (7, 'ggggggg', '1990-01-05 00:00:00');
+INSERT INTO `t5` VALUES (8, 'hhhhhhh', '1978-01-05 00:00:00');
+INSERT INTO `t5` VALUES (9, 'iiiiiii', '1979-01-05 00:00:00');
+INSERT INTO `t5` VALUES (10, 'jjjjjjj', '1992-01-05 00:00:00');
+INSERT INTO `t5` VALUES (11, 'kkkkkkk', '1993-01-05 00:00:00');
+INSERT INTO `t5` VALUES (12, 'mmmmmmm', '1994-01-05 00:00:00');
+INSERT INTO `t5` VALUES (13, 'nnnnnnn', '1989-01-05 00:00:00');
+INSERT INTO `t5` VALUES (14, 'ooooooo', '1983-12-05 00:00:00');
+INSERT INTO `t5` VALUES (15, 'ppppppp', '1986-06-05 00:00:00');
+INSERT INTO `t5` VALUES (16, 'qqqqqqq', '1974-04-11 00:00:00');
+INSERT INTO `t5` VALUES (17, 'qqqqqqq', '1960-03-15 00:00:00');
+INSERT INTO `t5` VALUES (18, 'sssssss', '1950-09-23 00:00:00');
+INSERT INTO `t5` VALUES (19, 'ttttttt', '1999-08-02 00:00:00');
+INSERT INTO `t5` VALUES (20, 'uuuuuuu', '1994-05-28 00:00:00');
+
+SELECT * FROM `t5`;
+SELECT * FROM `t5` PARTITION(p0) ORDER BY id;
+SELECT * FROM `t5` PARTITION(s0) ORDER BY id;
+SELECT * FROM `t5` PARTITION(s1) ORDER BY id;
+SELECT * FROM `t5` PARTITION(p1) ORDER BY id;
+SELECT * FROM `t5` PARTITION(s2) ORDER BY id;
+SELECT * FROM `t5` PARTITION(s3) ORDER BY id;
+SELECT * FROM `t5` PARTITION(p2) ORDER BY id;
+SELECT * FROM `t5` PARTITION(s4) ORDER BY id;
+SELECT * FROM `t5` PARTITION(s5) ORDER BY id;
+
+--disable_warnings
+drop table t1,t2,t3,t4,t5;
+--enable_warnings
+
+# Tests for working together with partition pruning.
+create table t1 (a int) partition by hash(a) partitions 3;
+insert into t1 values(1),(2),(3);
+explain partitions select * from t1 where a=1;
+explain partitions select * from t1 partition (p1) where a=1;
+explain partitions select * from t1 partition (p1) where a=1 or a=2;
+explain partitions select * from t1 partition (p2) where a=1;
+
+drop table t1;

=== added file 'mysql-test/t/wl5217.test'
--- a/mysql-test/t/wl5217.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/wl5217.test	2010-11-28 18:24:58 +0000
@@ -0,0 +1,174 @@
+--source include/have_innodb.inc
+--source include/have_partition.inc
+
+--echo # Original tests for WL#5217
+
+let $get_handler_status_counts= SELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS
+WHERE VARIABLE_NAME = 'HANDLER_EXTERNAL_LOCK' OR
+VARIABLE_NAME = 'HANDLER_UPDATE' OR
+VARIABLE_NAME = 'HANDLER_DELETE' OR
+VARIABLE_NAME = 'HANDLER_WRITE' OR
+VARIABLE_NAME LIKE 'HANDLER_READ_%';
+
+--echo # First test that the syntax is OK
+CREATE TABLE t1
+(a INT NOT NULL,
+ b varchar (64),
+ INDEX (b,a),
+ PRIMARY KEY (a))
+ENGINE = InnoDB
+PARTITION BY RANGE (a)
+SUBPARTITION BY HASH (a) SUBPARTITIONS 2
+(PARTITION pNeg VALUES LESS THAN (0)
+ (SUBPARTITION subp0,
+  SUBPARTITION subp1),
+ PARTITION `p0-9` VALUES LESS THAN (10)
+ (SUBPARTITION subp2,
+  SUBPARTITION subp3),
+ PARTITION `p10-99` VALUES LESS THAN (100)
+ (SUBPARTITION subp4,
+  SUBPARTITION subp5),
+ PARTITION `p100-99999` VALUES LESS THAN (100000)
+ (SUBPARTITION subp6,
+  SUBPARTITION subp7));
+
+SHOW CREATE TABLE t1;
+--error ER_PARSE_ERROR
+SHOW CREATE TABLE t1 PARTITION (subp0);
+--echo # Not a correct partition list
+--error ER_PARSE_ERROR
+INSERT INTO t1 PARTITION () VALUES (1, "error");
+--error ER_NO_SUCH_PARTITION
+INSERT INTO t1 PARTITION (pNonExisting) VALUES (1, "error");
+--error ER_NO_SUCH_PARTITION
+INSERT INTO t1 PARTITION (pNeg, pNonExisting) VALUES (1, "error");
+--echo # Duplicate partitions and overlapping partitions and subpartitios is OK
+INSERT INTO t1 PARTITION (pNeg, pNeg) VALUES (-1, "pNeg(-subp1)");
+INSERT INTO t1 PARTITION (pNeg, subp0) VALUES (-3, "pNeg(-subp1)");
+INSERT INTO t1 PARTITION (pNeg, subp0) VALUES (-2, "(pNeg-)subp0");
+
+--echo # should be correct
+INSERT INTO t1 PARTITION (`p100-99999`) VALUES (100, "`p100-99999`(-subp6)"), (101, "`p100-99999`(-subp7)"), (1000, "`p100-99999`(-subp6)");
+INSERT INTO t1 PARTITION(`p10-99`,subp3) VALUES (1, "subp3"), (10, "p10-99");
+
+--echo # Not matching partitions with inserted value
+--error ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET
+INSERT INTO t1 PARTITION (pNeg, pNeg) VALUES (1, "error");
+--error ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET
+INSERT INTO t1 PARTITION (pNeg, subp0) VALUES (1, "error");
+--error ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET
+INSERT INTO t1 PARTITION (`p100-99999`) VALUES (1, "error"), (10, "error");
+--error ER_NO_PARTITION_FOR_GIVEN_VALUE
+INSERT INTO t1 VALUES (1000000, "error"), (9999999, "error");
+--error ER_DUP_ENTRY,ER_DUP_KEY
+INSERT INTO t1 PARTITION (pNeg, subp4) VALUES (-7, "pNeg(-subp1)"), (-10, "pNeg(-subp0)"), (-1, "pNeg(-subp1)"), (-99, "pNeg(-subp1)");
+
+SELECT * FROM t1;
+SELECT PARTITION_NAME, SUBPARTITION_NAME, TABLE_ROWS
+FROM INFORMATION_SCHEMA.PARTITIONS
+WHERE TABLE_SCHEMA = 'test'
+AND TABLE_NAME = 't1';
+--error ER_NO_SUCH_PARTITION
+SELECT * FROM t1 PARTITION (pNonexistent);
+SELECT * FROM t1 PARTITION (subp2);
+SELECT * FROM t1 PARTITION (subp2,pNeg) AS TableAlias;
+SELECT * FROM t1 PARTITION (subp3) AS TableAlias;
+SELECT COUNT(*) FROM t1 PARTITION (`p10-99`);
+SELECT * FROM t1 WHERE a = 1000000;
+SELECT * FROM t1 PARTITION (pNeg) WHERE a = 100;
+
+--echo # Test that EXPLAIN PARTITION works
+--error ER_NO_SUCH_PARTITION
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (pNonexistent);
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (subp2);
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (subp2,pNeg) AS TableAlias;
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (subp3) AS TableAlias;
+EXPLAIN PARTITIONS SELECT COUNT(*) FROM t1 PARTITION (`p10-99`);
+EXPLAIN PARTITIONS SELECT * FROM t1 WHERE a = 1000000;
+EXPLAIN PARTITIONS SELECT * FROM t1 PARTITION (pNeg) WHERE a = 100;
+--echo # Test that it actually prunes the partitions
+--echo # Test that open/lock/unlock/close is also pruned
+
+--echo # Test what happens when no partition can be found
+SELECT * FROM t1 PARTITION (pNeg) WHERE a = 100;
+--echo # Test how it changes the alias/keywords/reserved words
+--error ER_PARSE_ERROR
+SELECT * FROM t1 PARTITION;
+SELECT * FROM t1 `PARTITION`;
+--error ER_PARSE_ERROR
+SELECT * FROM t1 AS PARTITION;
+SELECT * FROM t1 AS `PARTITION`;
+
+--echo # Test REPLACE
+--error ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET
+REPLACE INTO t1 PARTITION (subp0) VALUES (-21, 'Should fail!');
+REPLACE INTO t1 PARTITION (subp1) VALUES (-21, 'Insert by REPLACE');
+SELECT * FROM t1 PARTITION (pNeg);
+REPLACE INTO t1 PARTITION (subp1) VALUES (-21, 'REPLACEd by REPLACE');
+SELECT * FROM t1 PARTITION (pNeg);
+
+--echo # Test LOAD
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`);
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`) INTO OUTFILE 'loadtest.txt';
+ALTER TABLE t1 TRUNCATE PARTITION pNeg, `p10-99`;
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`);
+--error ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET
+LOAD DATA INFILE 'loadtest.txt' INTO TABLE t1 PARTITION (pNeg);
+--echo # Should be rolled back if possible
+SELECT * FROM t1 PARTITION (pNeg, `p10-99`);
+LOAD DATA INFILE 'loadtest.txt' INTO TABLE t1 PARTITION (pNeg, subp4, subp5);
+
+--echo # Test UPDATE
+FLUSH STATUS;
+UPDATE t1 PARTITION(subp0) SET b = concat(b, ', Updated');
+# Can HANDLER% status variables be trusted from I_S.SESSION_STATUS, since it
+# may be implemted as a storage engine itself?
+eval $get_handler_status_counts;
+FLUSH STATUS;
+UPDATE t1 PARTITION(subp0) SET b = concat(b, ', Updated2') WHERE a = 100;
+eval $get_handler_status_counts;
+FLUSH STATUS;
+UPDATE t1 PARTITION(subp0) SET a = -2, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+eval $get_handler_status_counts;
+FLUSH STATUS;
+--error ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET
+UPDATE t1 PARTITION(`p100-99999`) SET a = -2, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+eval $get_handler_status_counts;
+FLUSH STATUS;
+--error ER_DUP_ENTRY,ER_DUP_KEY
+UPDATE t1 PARTITION(`p100-99999`, pNeg) SET a = -2, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+eval $get_handler_status_counts;
+FLUSH STATUS;
+UPDATE t1 PARTITION(`p100-99999`, pNeg) SET a = -222, b = concat(b, ', Updated from a = 100')
+WHERE a = 100;
+eval $get_handler_status_counts;
+SELECT * FROM t1;
+--echo # Test of non matching partition (i.e ER_NO_PARTITION_FOUND)
+FLUSH STATUS;
+UPDATE t1 SET b = concat(b, ', Updated2') WHERE a = 1000000;
+eval $get_handler_status_counts;
+--echo # Test DELETE
+FLUSH STATUS;
+DELETE FROM t1 PARTITION (pNeg) WHERE a = -1;
+eval $get_handler_status_counts;
+FLUSH STATUS;
+DELETE FROM t1 PARTITION (subp1) WHERE b like '%subp1%';
+eval $get_handler_status_counts;
+FLUSH STATUS;
+--echo # Test multi-table DELETE
+
+
+--echo # Test TRUNCATE TABLE (should fail, since one should use
+--echo # ALTER TABLE ... TRUNCATE PARTITION instead)
+--error ER_PARSE_ERROR
+TRUNCATE TABLE t1 PARTITION(`p10-99`);
+
+--echo # Test on non partitioned table
+ALTER TABLE t1 REMOVE PARTITIONING;
+--error ER_PARTITION_CLAUSE_ON_NONPARTITIONED
+SELECT * FROM t1 PARTITION (pNeg);
+
+DROP TABLE t1;

=== modified file 'mysys/hash.c'
--- a/mysys/hash.c	2010-07-08 21:20:08 +0000
+++ b/mysys/hash.c	2010-11-28 18:24:58 +0000
@@ -67,6 +67,7 @@ static my_hash_value_type calc_hash(cons
   @param[in]     get_key      get the key for the hash
   @param[in]     free_element pointer to the function that
                               does cleanup
+  @param[in]     flags        flags set in the hash
   @return        inidicates success or failure of initialization
     @retval 0 success
     @retval 1 failure

=== modified file 'mysys/my_handler.c'
--- a/mysys/my_handler.c	2010-07-23 20:16:29 +0000
+++ b/mysys/my_handler.c	2010-11-28 18:24:58 +0000
@@ -587,7 +587,7 @@ void my_handler_error_register(void)
   /*
     If you got compilation error here about compile_time_assert array, check
     that every HA_ERR_xxx constant has a corresponding error message in
-    handler_error_messages[] list (check mysys/ma_handler_errors.h and
+    handler_error_messages[] list (check mysys/my_handler_errors.h and
     include/my_base.h).
   */
   compile_time_assert(HA_ERR_FIRST + array_elements(handler_error_messages) ==

=== modified file 'mysys/my_handler_errors.h'
--- a/mysys/my_handler_errors.h	2009-09-23 21:32:31 +0000
+++ b/mysys/my_handler_errors.h	2010-11-28 18:24:58 +0000
@@ -65,7 +65,8 @@ static const char *handler_error_message
   "Got a fatal error during initialzaction of handler",
   "File to short; Expected more data in file",
   "Read page with wrong checksum",
-  "Too many active concurrent transactions"
+  "Too many active concurrent transactions",
+  "Record not matching the given partition set"
 };
 
 #endif /* MYSYS_MY_HANDLER_ERRORS_INCLUDED */

=== modified file 'sql/ha_partition.cc'
--- a/sql/ha_partition.cc	2010-10-21 11:34:17 +0000
+++ b/sql/ha_partition.cc	2010-11-28 18:24:58 +0000
@@ -1188,6 +1188,8 @@ int ha_partition::handle_opt_partitions(
 
   @retval TRUE  Error/Not supported
   @retval FALSE Success
+
+  @note Called if open_table_from_share fails and ::is_crashed().
 */
 
 bool ha_partition::check_and_repair(THD *thd)
@@ -1794,6 +1796,16 @@ void ha_partition::update_create_info(HA
 }
 
 
+/**
+  Change the internal TABLE_SHARE pointer
+
+  @param table_arg    TABLE object
+  @param share        New share to use
+
+  @note Is used in error handling in ha_delete_table.
+  All handlers should exist (used_partitions should not be used)
+*/
+
 void ha_partition::change_table_ptr(TABLE *table_arg, TABLE_SHARE *share)
 {
   handler **file_array;
@@ -2497,6 +2509,101 @@ err1:
 ****************************************************************************/
 
 
+bool ha_partition::insert_partition_name_in_hash(const char *name, uint part_id,
+                                                 bool is_subpart)
+{
+  PART_NAME_DEF *part_def;
+  uchar *part_name;
+  uint part_name_length;
+  /*
+    Calculate and store the length here, to avoid doing it when
+    searching the hash.
+  */
+  part_name_length= strlen(name);
+  /**
+    Must use memory that lives as long as table_share.
+    Freed in ha_data_partition_destroy.
+    Since we use my_multi_malloc, then my_free(part_def) will also free
+    part_name, as a part of my_hash_free.
+  */
+  if (!my_multi_malloc(MY_WME,
+                       &part_def, sizeof(PART_NAME_DEF),
+                       &part_name, part_name_length + 1,
+                       NULL))
+    return true;
+  memcpy(part_name, name, part_name_length + 1);
+  part_def->partition_name= part_name;
+  part_def->length= part_name_length;
+  part_def->part_id= part_id;
+  part_def->is_subpart= is_subpart;
+  if (my_hash_insert(&table_share->ha_part_data->partition_name_hash,
+                     (uchar *) part_def))
+    return true;
+  return false;
+}
+
+
+/**
+  Populate the partition_name_hash in table_share->ha_part_data.
+
+  @note table_share->LOCK_ha_data mutex must be hold.
+*/
+
+bool ha_partition::populate_partition_name_hash()
+{
+  List_iterator<partition_element> part_it(m_part_info->partitions);
+  uint num_parts= m_part_info->num_parts;
+  uint num_subparts= m_part_info->num_subparts;
+  uint tot_names;
+  uint i= 0;
+#ifndef DBUG_OFF
+  if (table_share->tmp_table == NO_TMP_TABLE)
+    mysql_mutex_assert_owner(&table_share->LOCK_ha_data);
+#endif
+
+  DBUG_ENTER("ha_partition::populate_partition_name_hash");
+  tot_names= m_is_sub_partitioned ? m_tot_parts + num_parts : num_parts;
+  if (my_hash_init(&table_share->ha_part_data->partition_name_hash,
+                          system_charset_info, tot_names, 0, 0,
+                          (my_hash_get_key) get_part_name,
+                          my_free, 0))
+  {
+    DBUG_RETURN(TRUE);
+  }
+
+  do
+  {
+    partition_element *part_elem= part_it++;
+    DBUG_ASSERT(part_elem->part_state == PART_NORMAL);
+    if (part_elem->part_state == PART_NORMAL)
+    {
+      if (insert_partition_name_in_hash(part_elem->partition_name,
+                                        i, false))
+        goto err;
+      if (m_is_sub_partitioned)
+      {
+        List_iterator<partition_element>
+                                    subpart_it(part_elem->subpartitions);
+        partition_element *sub_elem;
+        uint j= 0;
+        do
+        {
+          sub_elem= subpart_it++;
+          if (insert_partition_name_in_hash(sub_elem->partition_name,
+                                            i * num_subparts + j, true))
+            goto err;
+
+        } while (++j < num_subparts);
+      }
+    }
+  } while (++i < num_parts);
+  DBUG_RETURN(FALSE);
+err:
+  my_hash_free(&table_share->ha_part_data->partition_name_hash);
+  DBUG_RETURN(TRUE);
+}
+
+
 /**
   A destructor for partition-specific TABLE_SHARE data.
 */
@@ -2506,6 +2613,8 @@ void ha_data_partition_destroy(HA_DATA_P
   if (ha_part_data)
   {
     mysql_mutex_destroy(&ha_part_data->LOCK_auto_inc);
+    if (ha_part_data->partition_name_hash.records > 0)
+      my_hash_free(&ha_part_data->partition_name_hash);
   }
 }
 
@@ -2584,15 +2693,24 @@ int ha_partition::open(const char *name,
   if (bitmap_init(&m_bulk_insert_started, NULL, m_tot_parts + 1, FALSE))
     DBUG_RETURN(1);
   bitmap_clear_all(&m_bulk_insert_started);
-  /* Initialize the bitmap we use to determine what partitions are used */
+  /* Initialize the bitmap we use to keep track of locked partitions */
+  if (bitmap_init(&m_locked_partitions, NULL, m_tot_parts, FALSE))
+  {
+    bitmap_free(&m_bulk_insert_started);
+    DBUG_RETURN(1);
+  }
+  bitmap_clear_all(&m_locked_partitions);
+  /* Initialize the bitmap we use to determine what partitions are locked */
+  DBUG_ASSERT(m_part_info);
+  /* Initialize the bitmap for used partitions */
   if (!is_clone)
   {
-    if (bitmap_init(&(m_part_info->used_partitions), NULL, m_tot_parts, TRUE))
+    if (m_part_info->set_partition_bitmaps(NULL))
     {
       bitmap_free(&m_bulk_insert_started);
+      bitmap_free(&m_locked_partitions);
       DBUG_RETURN(1);
     }
-    bitmap_set_all(&(m_part_info->used_partitions));
   }
 
   file= m_file;
@@ -2652,23 +2770,27 @@ int ha_partition::open(const char *name,
     mysql_mutex_lock(&table_share->LOCK_ha_data);
   if (!table_share->ha_part_data)
   {
-    /* currently only needed for auto_increment */
+    /* currently only needed for auto_increment and partition_name_hash */
     table_share->ha_part_data= (HA_DATA_PARTITION*)
                                    alloc_root(&table_share->mem_root,
                                               sizeof(HA_DATA_PARTITION));
     if (!table_share->ha_part_data)
     {
-      if (is_not_tmp_table)
-        mysql_mutex_unlock(&table_share->LOCK_ha_data);
-      goto err_handler;
+      goto unlock_err_handler;
     }
     DBUG_PRINT("info", ("table_share->ha_part_data 0x%p",
                         table_share->ha_part_data));
+    /* zeros both auto_increment variables and partition_name_hash.records */
     bzero(table_share->ha_part_data, sizeof(HA_DATA_PARTITION));
     table_share->ha_part_data_destroy= ha_data_partition_destroy;
     mysql_mutex_init(key_PARTITION_LOCK_auto_inc,
                      &table_share->ha_part_data->LOCK_auto_inc,
                      MY_MUTEX_INIT_FAST);
+    if (m_tot_parts > MAX_PARTITIONS_BEFORE_HASH)
+    {
+      if (populate_partition_name_hash())
+        goto unlock_err_handler;
+    }
   }
   if (is_not_tmp_table)
     mysql_mutex_unlock(&table_share->LOCK_ha_data);
@@ -2687,13 +2809,15 @@ int ha_partition::open(const char *name,
   info(HA_STATUS_VARIABLE | HA_STATUS_CONST);
   DBUG_RETURN(0);
 
+unlock_err_handler:
+  if (is_not_tmp_table)
+    mysql_mutex_unlock(&table_share->LOCK_ha_data);
 err_handler:
   DEBUG_SYNC(ha_thd(), "partition_open_error");
   while (file-- != m_file)
     (*file)->ha_close();
   bitmap_free(&m_bulk_insert_started);
-  if (!is_clone)
-    bitmap_free(&(m_part_info->used_partitions));
+  bitmap_free(&m_locked_partitions);
 
   DBUG_RETURN(error);
 }
@@ -2740,8 +2864,8 @@ int ha_partition::close(void)
   DBUG_ASSERT(table->s == table_share);
   delete_queue(&m_queue);
   bitmap_free(&m_bulk_insert_started);
-  if (!is_clone)
-    bitmap_free(&(m_part_info->used_partitions));
+  bitmap_free(&m_locked_partitions);
+  DBUG_ASSERT(m_part_info);
   file= m_file;
 
 repeat:
@@ -2803,41 +2927,59 @@ repeat:
 
 int ha_partition::external_lock(THD *thd, int lock_type)
 {
-  bool first= TRUE;
   uint error;
-  handler **file;
+  uint i, first_used_partition;
+  MY_BITMAP *used_partitions;
   DBUG_ENTER("ha_partition::external_lock");
 
   DBUG_ASSERT(!auto_increment_lock && !auto_increment_safe_stmt_log_lock);
-  file= m_file;
   m_lock_type= lock_type;
 
-repeat:
-  do
+  if (m_lock_type == F_UNLCK)
+    used_partitions= &m_locked_partitions;
+  else
+    used_partitions= &(m_part_info->lock_partitions);
+  first_used_partition= bitmap_get_first_set(used_partitions);
+  DBUG_ASSERT(first_used_partition != MY_BIT_NONE);
+  for (i= first_used_partition; i < m_tot_parts; i++)
   {
-    DBUG_PRINT("info", ("external_lock(thd, %d) iteration %d",
-                        lock_type, (int) (file - m_file)));
-    if ((error= (*file)->ha_external_lock(thd, lock_type)))
+    if (bitmap_is_set(used_partitions, i))
     {
-      if (F_UNLCK != lock_type)
-        goto err_handler;
+      DBUG_PRINT("info", ("external_lock(thd, %d) part %d", lock_type, i));
+      if ((error= m_file[i]->ha_external_lock(thd, lock_type)))
+      {
+        if (lock_type != F_UNLCK)
+          goto err_handler;
+      }
+      DBUG_PRINT("info", ("external_lock part %u lock %d", i, lock_type));
+      if (lock_type != F_UNLCK)
+        bitmap_set_bit(&m_locked_partitions, i);
     }
-  } while (*(++file));
+  }
+  if (m_lock_type == F_UNLCK)
+    bitmap_clear_all(used_partitions);
 
-  if (first && m_added_file && m_added_file[0])
+  if (m_added_file && m_added_file[0])
   {
+    handler **file= m_added_file;
     DBUG_ASSERT(lock_type == F_UNLCK);
-    file= m_added_file;
-    first= FALSE;
-    goto repeat;
+    do
+    {
+      (void) (*file)->ha_external_lock(thd, lock_type);
+    } while (*(++file));
   }
   DBUG_RETURN(0);
 
 err_handler:
-  while (file-- != m_file)
+  for (i= first_used_partition; i < m_tot_parts; i++)
   {
-    (*file)->ha_external_lock(thd, F_UNLCK);
+    if (bitmap_is_set(&m_locked_partitions, i))
+    {
+      (void) m_file[i]->ha_external_lock(thd, F_UNLCK);
+    }
   }
+  m_lock_type= F_UNLCK;
+  bitmap_clear_all(&m_locked_partitions);
   DBUG_RETURN(error);
 }
 
@@ -2892,14 +3034,19 @@ THR_LOCK_DATA **ha_partition::store_lock
 					 THR_LOCK_DATA **to,
 					 enum thr_lock_type lock_type)
 {
-  handler **file;
+  uint i, first_used_partition;
   DBUG_ENTER("ha_partition::store_lock");
-  file= m_file;
-  do
+
+  first_used_partition= bitmap_get_first_set(&(m_part_info->lock_partitions));
+  DBUG_ASSERT(first_used_partition != MY_BIT_NONE);
+  for (i= first_used_partition; i < m_tot_parts; i++)
   {
-    DBUG_PRINT("info", ("store lock %d iteration", (int) (file - m_file)));
-    to= (*file)->store_lock(thd, to, lock_type);
-  } while (*(++file));
+    if (bitmap_is_set(&(m_part_info->lock_partitions), i))
+    {
+      DBUG_PRINT("info", ("store lock %d iteration", i));
+      to= m_file[i]->store_lock(thd, to, lock_type);
+    }
+  }
   DBUG_RETURN(to);
 }
 
@@ -2923,15 +3070,17 @@ THR_LOCK_DATA **ha_partition::store_lock
 int ha_partition::start_stmt(THD *thd, thr_lock_type lock_type)
 {
   int error= 0;
-  handler **file;
+  uint i, first_used_partition;
   DBUG_ENTER("ha_partition::start_stmt");
 
-  file= m_file;
-  do
+  first_used_partition= bitmap_get_first_set(&(m_part_info->lock_partitions));
+  DBUG_ASSERT(first_used_partition != MY_BIT_NONE);
+  for (i= first_used_partition; i < m_tot_parts; i++)
   {
-    if ((error= (*file)->start_stmt(thd, lock_type)))
-      break;
-  } while (*(++file));
+    if (bitmap_is_set(&(m_part_info->lock_partitions), i))
+      if ((error= m_file[i]->start_stmt(thd, lock_type)))
+        break;
+  }
   DBUG_RETURN(error);
 }
 
@@ -3008,7 +3157,7 @@ bool ha_partition::was_semi_consistent_r
 {
   DBUG_ENTER("ha_partition::was_semi_consistent_read");
   DBUG_ASSERT(m_last_part < m_tot_parts &&
-              bitmap_is_set(&(m_part_info->used_partitions), m_last_part));
+              bitmap_is_set(&(m_part_info->read_partitions), m_last_part));
   DBUG_RETURN(m_file[m_last_part]->was_semi_consistent_read());
 }
 
@@ -3033,13 +3182,15 @@ bool ha_partition::was_semi_consistent_r
 */
 void ha_partition::try_semi_consistent_read(bool yes)
 {
-  handler **file;
+  uint i, first_used_partition;
   DBUG_ENTER("ha_partition::try_semi_consistent_read");
   
-  for (file= m_file; *file; file++)
+  first_used_partition= bitmap_get_first_set(&(m_part_info->read_partitions));
+  DBUG_ASSERT(first_used_partition != MY_BIT_NONE);
+  for (i= first_used_partition; i < m_tot_parts; i++)
   {
-    if (bitmap_is_set(&(m_part_info->used_partitions), (file - m_file)))
-      (*file)->try_semi_consistent_read(yes);
+    if (bitmap_is_set(&(m_part_info->read_partitions), i))
+      m_file[i]->try_semi_consistent_read(yes);
   }
   DBUG_VOID_RETURN;
 }
@@ -3095,9 +3246,6 @@ int ha_partition::write_row(uchar * buf)
   my_bitmap_map *old_map;
   THD *thd= ha_thd();
   timestamp_auto_set_type orig_timestamp_type= table->timestamp_field_type;
-#ifdef NOT_NEEDED
-  uchar *rec0= m_rec0;
-#endif
   DBUG_ENTER("ha_partition::write_row");
   DBUG_ASSERT(buf == m_rec0);
 
@@ -3133,26 +3281,20 @@ int ha_partition::write_row(uchar * buf)
   }
 
   old_map= dbug_tmp_use_all_columns(table, table->read_set);
-#ifdef NOT_NEEDED
-  if (likely(buf == rec0))
-#endif
-    error= m_part_info->get_partition_id(m_part_info, &part_id,
-                                         &func_value);
-#ifdef NOT_NEEDED
-  else
-  {
-    set_field_ptr(m_part_field_array, buf, rec0);
-    error= m_part_info->get_partition_id(m_part_info, &part_id,
-                                         &func_value);
-    set_field_ptr(m_part_field_array, rec0, buf);
-  }
-#endif
+  error= m_part_info->get_partition_id(m_part_info, &part_id, &func_value);
   dbug_tmp_restore_column_map(table->read_set, old_map);
   if (unlikely(error))
   {
     m_part_info->err_value= func_value;
     goto exit;
   }
+  if (!bitmap_is_set(&(m_part_info->lock_partitions), part_id))
+  {
+    DBUG_PRINT("info", ("Write to non-locked partition %u (func_value: %ld)",
+                        part_id, (long) func_value));
+    error= HA_ERR_NOT_IN_LOCK_PARTITIONS;
+    goto exit;
+  }
   m_last_part= part_id;
   DBUG_PRINT("info", ("Insert in partition %d", part_id));
   start_part_bulk_insert(thd, part_id);
@@ -3217,7 +3359,12 @@ int ha_partition::update_row(const uchar
     m_part_info->err_value= func_value;
     goto exit;
   }
-
+  DBUG_ASSERT(bitmap_is_set(&(m_part_info->read_partitions), old_part_id));
+  if (!bitmap_is_set(&(m_part_info->lock_partitions), new_part_id))
+  {
+    error= HA_ERR_NOT_IN_LOCK_PARTITIONS;
+    goto exit;
+  }
   m_last_part= new_part_id;
   start_part_bulk_insert(thd, new_part_id);
   if (new_part_id == old_part_id)
@@ -3311,6 +3458,11 @@ int ha_partition::delete_row(const uchar
     DBUG_RETURN(error);
   }
   m_last_part= part_id;
+  /* Should never call delete_row on a partition which is not read */
+  DBUG_ASSERT(bitmap_is_set(&(m_part_info->read_partitions), part_id));
+  DBUG_ASSERT(bitmap_is_set(&(m_part_info->lock_partitions), part_id));
+  if (!bitmap_is_set(&(m_part_info->lock_partitions), part_id))
+    DBUG_RETURN(HA_ERR_NOT_IN_LOCK_PARTITIONS);
   tmp_disable_binlog(thd);
   error= m_file[part_id]->ha_delete_row(buf);
   reenable_binlog(thd);
@@ -3490,6 +3642,7 @@ void ha_partition::start_part_bulk_inser
   if (!bitmap_is_set(&m_bulk_insert_started, part_id) &&
       bitmap_is_set(&m_bulk_insert_started, m_tot_parts))
   {
+    DBUG_ASSERT(bitmap_is_set(&(m_part_info->lock_partitions), part_id));
     old_buffer_size= thd->variables.read_buff_size;
     /* Update read_buffer_size for this partition */
     thd->variables.read_buff_size= estimate_read_buffer_size(old_buffer_size);
@@ -3674,9 +3827,9 @@ int ha_partition::rnd_init(bool scan)
   }
 
   /* Now we see what the index of our first important partition is */
-  DBUG_PRINT("info", ("m_part_info->used_partitions: 0x%lx",
-                      (long) m_part_info->used_partitions.bitmap));
-  part_id= bitmap_get_first_set(&(m_part_info->used_partitions));
+  DBUG_PRINT("info", ("m_part_info->read_partitions: 0x%lx",
+                      (long) m_part_info->read_partitions.bitmap));
+  part_id= bitmap_get_first_set(&(m_part_info->read_partitions));
   DBUG_PRINT("info", ("m_part_spec.start_part %d", part_id));
 
   if (MY_BIT_NONE == part_id)
@@ -3705,7 +3858,7 @@ int ha_partition::rnd_init(bool scan)
   {
     for (i= part_id; i < m_tot_parts; i++)
     {
-      if (bitmap_is_set(&(m_part_info->used_partitions), i))
+      if (bitmap_is_set(&(m_part_info->read_partitions), i))
       {
         if ((error= m_file[i]->ha_rnd_init(scan)))
           goto err;
@@ -3721,7 +3874,7 @@ int ha_partition::rnd_init(bool scan)
 err:
   while ((int)--i >= (int)part_id)
   {
-    if (bitmap_is_set(&(m_part_info->used_partitions), i))
+    if (bitmap_is_set(&(m_part_info->read_partitions), i))
       m_file[i]->ha_rnd_end();
   }
 err1:
@@ -3760,7 +3913,7 @@ int ha_partition::rnd_end()
     file= m_file;
     do
     {
-      if (bitmap_is_set(&(m_part_info->used_partitions), (file - m_file)))
+      if (bitmap_is_set(&(m_part_info->read_partitions), (file - m_file)))
         (*file)->ha_rnd_end();
     } while (*(++file));
     break;
@@ -3838,7 +3991,7 @@ int ha_partition::rnd_next(uchar *buf)
     
     /* Shift to next partition */
     while (++part_id < m_tot_parts &&
-           !bitmap_is_set(&(m_part_info->used_partitions), part_id))
+           !bitmap_is_set(&(m_part_info->read_partitions), part_id))
       ;
     if (part_id >= m_tot_parts)
     {
@@ -3890,6 +4043,7 @@ end_dont_reset_start_part:
 void ha_partition::position(const uchar *record)
 {
   handler *file= m_file[m_last_part];
+  DBUG_ASSERT(bitmap_is_set(&(m_part_info->read_partitions), m_last_part));
   DBUG_ENTER("ha_partition::position");
 
   file->position(record);
@@ -3944,6 +4098,7 @@ int ha_partition::rnd_pos(uchar * buf, u
   part_id= uint2korr((const uchar *) pos);
   DBUG_ASSERT(part_id < m_tot_parts);
   file= m_file[part_id];
+  DBUG_ASSERT(bitmap_is_set(&(m_part_info->read_partitions), part_id));
   m_last_part= part_id;
   DBUG_RETURN(file->ha_rnd_pos(buf, (pos + PARTITION_BYTES_IN_POS)));
 }
@@ -4075,7 +4230,7 @@ int ha_partition::index_init(uint inx, b
   do
   {
     /* TODO RONM: Change to index_init() when code is stable */
-    if (bitmap_is_set(&(m_part_info->used_partitions), (file - m_file)))
+    if (bitmap_is_set(&(m_part_info->read_partitions), (file - m_file)))
       if ((error= (*file)->ha_index_init(inx, sorted)))
       {
         DBUG_ASSERT(0);                           // Should never happen
@@ -4114,7 +4269,7 @@ int ha_partition::index_end()
   {
     int tmp;
     /* TODO RONM: Change to index_end() when code is stable */
-    if (bitmap_is_set(&(m_part_info->used_partitions), (file - m_file)))
+    if (bitmap_is_set(&(m_part_info->read_partitions), (file - m_file)))
       if ((tmp= (*file)->ha_index_end()))
         error= tmp;
   } while (*(++file));
@@ -4394,11 +4549,11 @@ int ha_partition::index_read_idx_map(uch
     get_partition_set(table, buf, index, &m_start_key, &m_part_spec);
 
     /* How can it be more than one partition with the current use? */
-    DBUG_ASSERT(m_part_spec.start_part == m_part_spec.end_part);
+    DBUG_ASSERT(m_part_spec.start_part >= m_part_spec.end_part);
 
     for (part= m_part_spec.start_part; part <= m_part_spec.end_part; part++)
     {
-      if (bitmap_is_set(&(m_part_info->used_partitions), part))
+      if (bitmap_is_set(&(m_part_info->read_partitions), part))
       {
         error= m_file[part]->ha_index_read_idx_map(buf, index, key,
                                                    keypart_map, find_flag);
@@ -4649,7 +4804,7 @@ int ha_partition::partition_scan_set_up(
       Verify this, also bitmap must have at least one bit set otherwise
       the result from this table is the empty set.
     */
-    uint start_part= bitmap_get_first_set(&(m_part_info->used_partitions));
+    uint start_part= bitmap_get_first_set(&(m_part_info->read_partitions));
     if (start_part == MY_BIT_NONE)
     {
       DBUG_PRINT("info", ("scan with no partition to scan"));
@@ -4765,7 +4920,7 @@ int ha_partition::handle_unordered_scan_
     int error;
     handler *file;
 
-    if (!(bitmap_is_set(&(m_part_info->used_partitions), i)))
+    if (!(bitmap_is_set(&(m_part_info->read_partitions), i)))
       continue;
     file= m_file[i];
     m_part_spec.start_part= i;
@@ -4856,7 +5011,7 @@ int ha_partition::handle_ordered_index_s
   DBUG_PRINT("info", ("m_part_spec.start_part %d", m_part_spec.start_part));
   for (i= m_part_spec.start_part; i <= m_part_spec.end_part; i++)
   {
-    if (!(bitmap_is_set(&(m_part_info->used_partitions), i)))
+    if (!(bitmap_is_set(&(m_part_info->read_partitions), i)))
       continue;
     uchar *rec_buf_ptr= rec_buf(i);
     int error;
@@ -5131,6 +5286,10 @@ int ha_partition::info(uint flag)
 {
   DBUG_ENTER("ha_partition::info");
 
+#ifndef DBUG_OFF
+  if (bitmap_is_set_all(&(m_part_info->read_partitions)))
+    DBUG_PRINT("info", ("All partitions are used"));
+#endif /* DBUG_OFF */
   if (flag & HA_STATUS_AUTO)
   {
     bool auto_inc_is_first_in_idx= (table_share->next_number_keypart == 0);
@@ -5152,6 +5311,13 @@ int ha_partition::info(uint flag)
                                  table_share->ha_part_data->next_auto_inc_val;
       else
       {
+        /*
+          The auto-inc mutex in the table_share is locked, so we do not need
+          to have the handlers locked.
+          HA_STATUS_NO_LOCK is not checked, since we cannot skip locking
+          the mutex, because it is initialized.
+          TODO: Verify this in InnoDB with UNIV_DEBUG!
+        */
         handler *file, **file_array;
         ulonglong auto_increment_value= 0;
         file_array= m_file;
@@ -5211,7 +5377,7 @@ int ha_partition::info(uint flag)
     file_array= m_file;
     do
     {
-      if (bitmap_is_set(&(m_part_info->used_partitions), (file_array - m_file)))
+      if (bitmap_is_set(&(m_part_info->read_partitions), (file_array - m_file)))
       {
         file= *file_array;
         file->info(HA_STATUS_VARIABLE);
@@ -5294,7 +5460,7 @@ int ha_partition::info(uint flag)
       file= *file_array;
       /* Get variables if not already done */
       if (!(flag & HA_STATUS_VARIABLE) ||
-          !bitmap_is_set(&(m_part_info->used_partitions),
+          !bitmap_is_set(&(m_part_info->read_partitions),
                          (file_array - m_file)))
         file->info(HA_STATUS_VARIABLE);
       if (file->stats.records > max_records)
@@ -5352,6 +5518,7 @@ void ha_partition::get_dynamic_partition
                                               uint part_id)
 {
   handler *file= m_file[part_id];
+  DBUG_ASSERT(bitmap_is_set(&(m_part_info->read_partitions), part_id));
   file->info(HA_STATUS_CONST | HA_STATUS_TIME | HA_STATUS_VARIABLE |
              HA_STATUS_NO_LOCK);
 
@@ -5842,22 +6009,35 @@ int ha_partition::extra(enum ha_extra_fu
     0                    Success
 
   DESCRIPTION
-    Called at end of each statement to reste buffers
+    Called at end of each statement to reset buffers
 */
 
 int ha_partition::reset(void)
 {
-  int result= 0, tmp;
-  handler **file;
+  int result= 0;
   DBUG_ENTER("ha_partition::reset");
-  if (m_part_info)
-    bitmap_set_all(&m_part_info->used_partitions);
-  file= m_file;
-  do
+
+  /* TODO: Verify what to do if m_lock_type != and == F_UNLCK */
+  /* May not have m_part_info set (in case of failed open or prune). */
+  if (m_part_info && m_part_info->bitmaps_are_initialized)
   {
-    if ((tmp= (*file)->ha_reset()))
-      result= tmp;
-  } while (*(++file));
+    handler **file= m_file;
+    int tmp;
+    /*
+      TODO: Optimize loop with bitmap_get_first_set, and implement a faster
+      bitmap_get_next_set(*MY_BITMAP, current_bit).
+    */
+    do
+    {
+      if (bitmap_is_set(&(m_part_info->lock_partitions), file - m_file))
+      {
+        if ((tmp= (*file)->ha_reset()))
+          result= tmp;
+      }
+    } while (*(++file));
+    /* Be sure used_partitions are set if no pruning in the next statement */
+    m_part_info->set_partition_bitmaps(NULL);
+  }
   DBUG_RETURN(result);
 }
 
@@ -5957,14 +6137,11 @@ int ha_partition::loop_extra(enum ha_ext
 {
   int result= 0, tmp;
   handler **file;
-  bool is_select;
   DBUG_ENTER("ha_partition::loop_extra()");
   
-  is_select= (thd_sql_command(ha_thd()) == SQLCOM_SELECT);
   for (file= m_file; *file; file++)
   {
-    if (!is_select ||
-        bitmap_is_set(&(m_part_info->used_partitions), file - m_file))
+    if (bitmap_is_set(&(m_part_info->lock_partitions), file - m_file))
     {
       if ((tmp= (*file)->extra(operation)))
         result= tmp;
@@ -6054,9 +6231,11 @@ void ha_partition::late_extra_no_cache(u
 
 const key_map *ha_partition::keys_to_use_for_scanning()
 {
+  uint first_used_partition;
   DBUG_ENTER("ha_partition::keys_to_use_for_scanning");
 
-  DBUG_RETURN(m_file[0]->keys_to_use_for_scanning());
+  first_used_partition= bitmap_get_first_set(&(m_part_info->read_partitions));
+  DBUG_RETURN(m_file[first_used_partition]->keys_to_use_for_scanning());
 }
 
 #define MAX_PARTS_FOR_OPTIMIZER_CALLS 10
@@ -6071,8 +6250,8 @@ void ha_partition::partitions_optimizer_
                                                           uint *num_used_parts,
                                                           uint *check_min_num)
 {
-  *first= bitmap_get_first_set(&(m_part_info->used_partitions));
-  *num_used_parts= bitmap_bits_set(&(m_part_info->used_partitions));
+  *first= bitmap_get_first_set(&(m_part_info->read_partitions));
+  *num_used_parts= bitmap_bits_set(&(m_part_info->read_partitions));
   *check_min_num= min(MAX_PARTS_FOR_OPTIMIZER_CALLS, *num_used_parts);
 }
 
@@ -6093,10 +6272,11 @@ double ha_partition::scan_time()
   uint first, part_id, num_used_parts, check_min_num, partitions_called= 0;
   DBUG_ENTER("ha_partition::scan_time");
 
-  partitions_optimizer_call_preparations(&first, &num_used_parts, &check_min_num);
+  partitions_optimizer_call_preparations(&first, &num_used_parts,
+                                         &check_min_num);
   for (part_id= first; partitions_called < num_used_parts ; part_id++)
   {
-    if (!bitmap_is_set(&(m_part_info->used_partitions), part_id))
+    if (!bitmap_is_set(&(m_part_info->read_partitions), part_id))
       continue;
     scan_time+= m_file[part_id]->scan_time();
     partitions_called++;
@@ -6126,12 +6306,12 @@ ha_rows ha_partition::estimate_rows(bool
 {
   ha_rows rows, estimated_rows= 0;
   uint first, part_id, num_used_parts, check_min_num, partitions_called= 0;
-  DBUG_ENTER("ha_partition::records_in_range");
+  DBUG_ENTER("ha_partition::estimate_rows");
 
   partitions_optimizer_call_preparations(&first, &num_used_parts, &check_min_num);
   for (part_id= first; partitions_called < num_used_parts ; part_id++)
   {
-    if (!bitmap_is_set(&(m_part_info->used_partitions), part_id))
+    if (!bitmap_is_set(&(m_part_info->read_partitions), part_id))
       continue;
     if (is_records_in_range)
       rows= m_file[part_id]->records_in_range(inx, min_key, max_key);
@@ -6231,11 +6411,7 @@ double ha_partition::read_time(uint inde
 /**
   Number of rows in table. see handler.h
 
-  SYNOPSIS
-    records()
-
-  RETURN VALUE
-    Number of total rows in a partitioned table.
+  @return Number of records in the table (after pruning!)
 */
 
 ha_rows ha_partition::records()
@@ -6247,10 +6423,13 @@ ha_rows ha_partition::records()
   file= m_file;
   do
   {
-    rows= (*file)->records();
-    if (rows == HA_POS_ERROR)
-      DBUG_RETURN(HA_POS_ERROR);
-    tot_rows+= rows;
+    if (bitmap_is_set(&(m_part_info->read_partitions), file - m_file))
+    {
+      rows= (*file)->records();
+      if (rows == HA_POS_ERROR)
+        DBUG_RETURN(HA_POS_ERROR);
+      tot_rows+= rows;
+    }
   } while (*(++file));
   DBUG_RETURN(tot_rows);
 }
@@ -6308,9 +6487,12 @@ uint8 ha_partition::table_cache_type()
 
 const char *ha_partition::index_type(uint inx)
 {
+  uint first_used_partition;
   DBUG_ENTER("ha_partition::index_type");
 
-  DBUG_RETURN(m_file[0]->index_type(inx));
+  first_used_partition= bitmap_get_first_set(&(m_part_info->read_partitions));
+  DBUG_ASSERT(first_used_partition != MY_BIT_NONE);
+  DBUG_RETURN(m_file[first_used_partition]->index_type(inx));
 }
 
 
@@ -6319,6 +6501,7 @@ enum row_type ha_partition::get_row_type
   handler **file;
   enum row_type type= (*m_file)->get_row_type();
 
+  DBUG_ASSERT(bitmap_is_set_all(&(m_part_info->read_partitions)));
   for (file= m_file, file++; *file; file++)
   {
     enum row_type part_type= (*file)->get_row_type();
@@ -6722,7 +6905,8 @@ void ha_partition::release_auto_incremen
   if (table->s->next_number_keypart)
   {
     for (uint i= 0; i < m_tot_parts; i++)
-      m_file[i]->ha_release_auto_increment();
+      if (bitmap_is_set(&(m_part_info->lock_partitions), i))
+        m_file[i]->ha_release_auto_increment();
   }
   else if (next_insert_id)
   {
@@ -6789,6 +6973,7 @@ int ha_partition::disable_indexes(uint m
   handler **file;
   int error= 0;
 
+  DBUG_ASSERT(bitmap_is_set_all(&(m_part_info->lock_partitions)));
   for (file= m_file; *file; file++)
   {
     if ((error= (*file)->ha_disable_indexes(mode)))
@@ -6813,6 +6998,7 @@ int ha_partition::enable_indexes(uint mo
   handler **file;
   int error= 0;
 
+  DBUG_ASSERT(bitmap_is_set_all(&(m_part_info->lock_partitions)));
   for (file= m_file; *file; file++)
   {
     if ((error= (*file)->ha_enable_indexes(mode)))
@@ -6837,6 +7023,7 @@ int ha_partition::indexes_are_disabled(v
   handler **file;
   int error= 0;
 
+  DBUG_ASSERT(bitmap_is_set_all(&(m_part_info->lock_partitions)));
   for (file= m_file; *file; file++)
   {
     if ((error= (*file)->indexes_are_disabled()))

=== modified file 'sql/ha_partition.h'
--- a/sql/ha_partition.h	2010-10-29 10:34:33 +0000
+++ b/sql/ha_partition.h	2010-11-28 18:24:58 +0000
@@ -164,6 +164,8 @@ private:
   ha_rows   m_bulk_inserted_rows;
   /** used for prediction of start_bulk_insert rows */
   enum_monotonicity_info m_part_func_monotonicity_info;
+  /** keep track of locked partitions */
+  MY_BITMAP m_locked_partitions;
 public:
   handler *clone(MEM_ROOT *mem_root);
   virtual void set_part_info(partition_info *part_info)
@@ -264,6 +266,9 @@ private:
                                  uint part_id,
                                  partition_element *p_elem);
   partition_element *find_partition_element(uint part_id);
+  bool insert_partition_name_in_hash(const char *name, uint part_id,
+                                     bool is_subpart);
+  bool populate_partition_name_hash();
 
 public:
 
@@ -367,10 +372,13 @@ public:
   virtual bool is_fatal_error(int error, uint flags)
   {
     if (!handler::is_fatal_error(error, flags) ||
-        error == HA_ERR_NO_PARTITION_FOUND)
+        error == HA_ERR_NO_PARTITION_FOUND ||
+        error == HA_ERR_NOT_IN_LOCK_PARTITIONS)
       return FALSE;
     return TRUE;
   }
+
+
   /*
     -------------------------------------------------------------------------
     MODULE full table scan

=== modified file 'sql/handler.cc'
--- a/sql/handler.cc	2010-10-21 12:18:25 +0000
+++ b/sql/handler.cc	2010-11-28 18:24:58 +0000
@@ -2127,6 +2127,8 @@ int handler::ha_open(TABLE *table_arg, c
 
   table= table_arg;
   DBUG_ASSERT(table->s == table_share);
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
+  DBUG_PRINT("info", ("old m_lock_type: %d F_UNLCK %d", m_lock_type, F_UNLCK));
   DBUG_ASSERT(alloc_root_inited(&table->mem_root));
 
   if ((error=open(name,mode,test_if_locked)))
@@ -2184,12 +2186,16 @@ int handler::ha_close(void)
   }
 #endif
   DBUG_ASSERT(m_psi == NULL);
+  /* Can be closed early?, TODO: verify this DBUG_ASSERT */
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
   return close();
 }
 
 int handler::ha_rnd_next(uchar *buf)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2202,6 +2208,8 @@ int handler::ha_rnd_next(uchar *buf)
 int handler::ha_rnd_pos(uchar *buf, uchar *pos)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2216,6 +2224,8 @@ int handler::ha_index_read_map(uchar *bu
                                enum ha_rkey_function find_flag)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2230,6 +2240,8 @@ int handler::ha_index_read_idx_map(uchar
                                    enum ha_rkey_function find_flag)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2242,6 +2254,8 @@ int handler::ha_index_read_idx_map(uchar
 int handler::ha_index_next(uchar * buf)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2254,6 +2268,8 @@ int handler::ha_index_next(uchar * buf)
 int handler::ha_index_prev(uchar * buf)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2266,6 +2282,8 @@ int handler::ha_index_prev(uchar * buf)
 int handler::ha_index_first(uchar * buf)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2278,6 +2296,8 @@ int handler::ha_index_first(uchar * buf)
 int handler::ha_index_last(uchar * buf)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2290,6 +2310,8 @@ int handler::ha_index_last(uchar * buf)
 int handler::ha_index_next_same(uchar *buf, const uchar *key, uint keylen)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2303,6 +2325,8 @@ int handler::ha_index_read(uchar *buf, c
                            enum ha_rkey_function find_flag)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2315,6 +2339,8 @@ int handler::ha_index_read(uchar *buf, c
 int handler::ha_index_read_last(uchar *buf, const uchar *key, uint key_len)
 {
   int result;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
@@ -2519,6 +2545,8 @@ int handler::update_auto_increment()
   bool append= FALSE;
   THD *thd= table->in_use;
   struct system_variables *variables= &thd->variables;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   DBUG_ENTER("handler::update_auto_increment");
 
   /*
@@ -2766,6 +2794,8 @@ void handler::get_auto_increment(ulonglo
 
 void handler::ha_release_auto_increment()
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   release_auto_increment();
   insert_id_for_cur_row= 0;
   auto_inc_interval_for_cur_row.replace(0, 0, 0);
@@ -2989,6 +3019,9 @@ void handler::print_error(int error, myf
   case HA_ERR_TOO_MANY_CONCURRENT_TRXS:
     textno= ER_TOO_MANY_CONCURRENT_TRXS;
     break;
+  case HA_ERR_NOT_IN_LOCK_PARTITIONS:
+    textno=ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET;
+    break;
   default:
     {
       /* The error was "unknown" to this function.
@@ -3182,6 +3215,8 @@ err:
 */
 uint handler::get_dup_key(int error)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   DBUG_ENTER("handler::get_dup_key");
   table->file->errkey  = (uint) -1;
   if (error == HA_ERR_FOUND_DUPP_KEY || error == HA_ERR_FOREIGN_DUPLICATE_KEY ||
@@ -3213,6 +3248,7 @@ int handler::delete_table(const char *na
   int error= 0;
   int enoent_or_zero= ENOENT;                   // Error if no file was deleted
   char buff[FN_REFLEN];
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
 
   for (const char **ext=bas_ext(); *ext ; ext++)
   {
@@ -3287,6 +3323,8 @@ void handler::drop_table(const char *nam
 int handler::ha_check(THD *thd, HA_CHECK_OPT *check_opt)
 {
   int error;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
 
   if ((table->s->mysql_version >= MYSQL_VERSION_ID) &&
       (check_opt->sql_flags & TT_FOR_UPGRADE))
@@ -3347,7 +3385,6 @@ handler::mark_trx_read_write()
 int handler::ha_repair(THD* thd, HA_CHECK_OPT* check_opt)
 {
   int result;
-
   mark_trx_read_write();
 
   if ((result= repair(thd, check_opt)))
@@ -3366,6 +3403,8 @@ int
 handler::ha_bulk_update_row(const uchar *old_data, uchar *new_data,
                             uint *dup_key_found)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return bulk_update_row(old_data, new_data, dup_key_found);
@@ -3381,6 +3420,8 @@ handler::ha_bulk_update_row(const uchar 
 int
 handler::ha_delete_all_rows()
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return delete_all_rows();
@@ -3396,6 +3437,8 @@ handler::ha_delete_all_rows()
 int
 handler::ha_truncate()
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return truncate();
@@ -3411,6 +3454,8 @@ handler::ha_truncate()
 int
 handler::ha_reset_auto_increment(ulonglong value)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return reset_auto_increment(value);
@@ -3426,6 +3471,8 @@ handler::ha_reset_auto_increment(ulonglo
 int
 handler::ha_optimize(THD* thd, HA_CHECK_OPT* check_opt)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return optimize(thd, check_opt);
@@ -3441,6 +3488,8 @@ handler::ha_optimize(THD* thd, HA_CHECK_
 int
 handler::ha_analyze(THD* thd, HA_CHECK_OPT* check_opt)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   mark_trx_read_write();
 
   return analyze(thd, check_opt);
@@ -3456,6 +3505,8 @@ handler::ha_analyze(THD* thd, HA_CHECK_O
 bool
 handler::ha_check_and_repair(THD *thd)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_UNLCK);
   mark_trx_read_write();
 
   return check_and_repair(thd);
@@ -3471,6 +3522,8 @@ handler::ha_check_and_repair(THD *thd)
 int
 handler::ha_disable_indexes(uint mode)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   mark_trx_read_write();
 
   return disable_indexes(mode);
@@ -3486,6 +3539,8 @@ handler::ha_disable_indexes(uint mode)
 int
 handler::ha_enable_indexes(uint mode)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   mark_trx_read_write();
 
   return enable_indexes(mode);
@@ -3501,6 +3556,8 @@ handler::ha_enable_indexes(uint mode)
 int
 handler::ha_discard_or_import_tablespace(my_bool discard)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return discard_or_import_tablespace(discard);
@@ -3518,6 +3575,8 @@ handler::ha_discard_or_import_tablespace
 void
 handler::ha_prepare_for_alter()
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type != F_UNLCK);
   mark_trx_read_write();
 
   prepare_for_alter();
@@ -3533,6 +3592,7 @@ handler::ha_prepare_for_alter()
 int
 handler::ha_rename_table(const char *from, const char *to)
 {
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
   mark_trx_read_write();
 
   return rename_table(from, to);
@@ -3548,6 +3608,7 @@ handler::ha_rename_table(const char *fro
 int
 handler::ha_delete_table(const char *name)
 {
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
   mark_trx_read_write();
 
   return delete_table(name);
@@ -3563,6 +3624,7 @@ handler::ha_delete_table(const char *nam
 void
 handler::ha_drop_table(const char *name)
 {
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
   mark_trx_read_write();
 
   return drop_table(name);
@@ -3578,6 +3640,7 @@ handler::ha_drop_table(const char *name)
 int
 handler::ha_create(const char *name, TABLE *form, HA_CREATE_INFO *info)
 {
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
   mark_trx_read_write();
 
   return create(name, form, info);
@@ -3594,6 +3657,7 @@ int
 handler::ha_create_handler_files(const char *name, const char *old_name,
                         int action_flag, HA_CREATE_INFO *info)
 {
+  DBUG_ASSERT(m_lock_type == F_UNLCK);
   mark_trx_read_write();
 
   return create_handler_files(name, old_name, action_flag, info);
@@ -3614,6 +3678,8 @@ handler::ha_change_partitions(HA_CREATE_
                      const uchar *pack_frm_data,
                      size_t pack_frm_len)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return change_partitions(create_info, path, copied, deleted,
@@ -3630,6 +3696,8 @@ handler::ha_change_partitions(HA_CREATE_
 int
 handler::ha_drop_partitions(const char *path)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return drop_partitions(path);
@@ -3645,6 +3713,8 @@ handler::ha_drop_partitions(const char *
 int
 handler::ha_rename_partitions(const char *path)
 {
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   mark_trx_read_write();
 
   return rename_partitions(path);
@@ -5709,6 +5779,11 @@ int handler::ha_external_lock(THD *thd, 
     taken a table lock), ha_release_auto_increment() was too.
   */
   DBUG_ASSERT(next_insert_id == 0);
+  /* Consecutive calls for lock without unlocking in between is not allowed */
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              ((lock_type != F_UNLCK && m_lock_type == F_UNLCK) ||
+               lock_type == F_UNLCK));
+              
 
   if (MYSQL_HANDLER_RDLOCK_START_ENABLED() ||
       MYSQL_HANDLER_WRLOCK_START_ENABLED() ||
@@ -5731,6 +5806,8 @@ int handler::ha_external_lock(THD *thd, 
     }
   }
 
+  ha_statistic_increment(&SSV::ha_external_lock_count);
+
   MYSQL_START_TABLE_WAIT(locker, &state, m_psi,
                          PSI_TABLE_EXTERNAL_LOCK, MAX_KEY, lock_type);
   /*
@@ -5775,6 +5852,8 @@ int handler::ha_external_lock(THD *thd, 
 
 /** @brief
   Check handler usage and reset state of file to after 'open'
+
+  @note can be called regardless of it is locked or not.
 */
 int handler::ha_reset()
 {
@@ -5800,6 +5879,8 @@ int handler::ha_write_row(uchar *buf)
 {
   int error;
   Log_func *log_func= Write_rows_log_event::binlog_row_logging_function;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
   DBUG_ENTER("handler::ha_write_row");
@@ -5825,6 +5906,8 @@ int handler::ha_write_row(uchar *buf)
 int handler::ha_update_row(const uchar *old_data, uchar *new_data)
 {
   int error;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   Log_func *log_func= Update_rows_log_event::binlog_row_logging_function;
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 
@@ -5854,6 +5937,8 @@ int handler::ha_update_row(const uchar *
 int handler::ha_delete_row(const uchar *buf)
 {
   int error;
+  DBUG_ASSERT(table_share->tmp_table != NO_TMP_TABLE ||
+              m_lock_type == F_WRLCK);
   Log_func *log_func= Delete_rows_log_event::binlog_row_logging_function;
   MYSQL_TABLE_WAIT_VARIABLES(locker, state) /* no ';' */
 

=== modified file 'sql/handler.h'
--- a/sql/handler.h	2010-11-05 16:23:32 +0000
+++ b/sql/handler.h	2010-11-28 18:24:58 +0000
@@ -1440,7 +1440,6 @@ public:
   uint ref_length;
   FT_INFO *ft_handler;
   enum {NONE=0, INDEX, RND} inited;
-  bool locked;
   bool implicit_emptied;                /* Can be !=0 only if HEAP */
   const Item *pushed_cond;
 
@@ -1509,15 +1508,19 @@ public:
     key_used_on_scan(MAX_KEY), active_index(MAX_KEY),
     ref_length(sizeof(my_off_t)),
     ft_handler(0), inited(NONE),
-    locked(FALSE), implicit_emptied(0),
+    implicit_emptied(0),
     pushed_cond(0), pushed_idx_cond(NULL), pushed_idx_cond_keyno(MAX_KEY),
     next_insert_id(0), insert_id_for_cur_row(0),
     auto_inc_intervals_count(0),
     m_psi(NULL), m_lock_type(F_UNLCK)
-    {}
+    {
+      DBUG_PRINT("info",
+                 ("handler created F_UNLCK %d F_RDLCK %d F_WRLCK %d",
+                  F_UNLCK, F_RDLCK, F_UNLCK));
+    }
   virtual ~handler(void)
   {
-    DBUG_ASSERT(locked == FALSE);
+    DBUG_ASSERT(m_lock_type == F_UNLCK);
     DBUG_ASSERT(inited == NONE);
   }
   virtual handler *clone(MEM_ROOT *mem_root);
@@ -1856,6 +1859,7 @@ public:
   */
   virtual int rnd_pos_by_record(uchar *record)
     {
+      DBUG_ASSERT(table_flags() & HA_PRIMARY_KEY_REQUIRED_FOR_POSITION);
       position(record);
       return ha_rnd_pos(record, ref);
     }

=== modified file 'sql/mysqld.cc'
--- a/sql/mysqld.cc	2010-11-09 20:10:44 +0000
+++ b/sql/mysqld.cc	2010-11-28 18:24:58 +0000
@@ -6565,6 +6565,7 @@ SHOW_VAR status_vars[]= {
   {"Handler_commit",           (char*) offsetof(STATUS_VAR, ha_commit_count), SHOW_LONG_STATUS},
   {"Handler_delete",           (char*) offsetof(STATUS_VAR, ha_delete_count), SHOW_LONG_STATUS},
   {"Handler_discover",         (char*) offsetof(STATUS_VAR, ha_discover_count), SHOW_LONG_STATUS},
+  {"Handler_external_lock",    (char*) offsetof(STATUS_VAR, ha_external_lock_count), SHOW_LONG_STATUS},
   {"Handler_mrr_init",         (char*) offsetof(STATUS_VAR, ha_multi_range_read_init_count),  SHOW_LONG_STATUS},
   {"Handler_prepare",          (char*) offsetof(STATUS_VAR, ha_prepare_count),  SHOW_LONG_STATUS},
   {"Handler_read_first",       (char*) offsetof(STATUS_VAR, ha_read_first_count), SHOW_LONG_STATUS},

=== modified file 'sql/opt_range.cc'
--- a/sql/opt_range.cc	2010-09-28 15:17:29 +0000
+++ b/sql/opt_range.cc	2010-11-28 18:24:58 +0000
@@ -2660,7 +2660,7 @@ static void dbug_print_singlepoint_range
     This function assumes that all partitions are marked as unused when it
     is invoked. The function analyzes the condition, finds partitions that
     need to be used to retrieve the records that match the condition, and 
-    marks them as used by setting appropriate bit in part_info->used_partitions
+    marks them as used by setting appropriate bit in part_info->read_partitions
     In the worst case all partitions are marked as used.
 
   NOTE
@@ -2721,7 +2721,7 @@ bool prune_partitions(THD *thd, TABLE *t
   thd->no_errors=1;				// Don't warn about NULL
   thd->mem_root=&alloc;
 
-  bitmap_clear_all(&part_info->used_partitions);
+  bitmap_clear_all(&part_info->read_partitions);
 
   prune_param.key= prune_param.range_param.key_parts;
   SEL_TREE *tree;
@@ -2804,6 +2804,11 @@ end:
   thd->no_errors=0;
   thd->mem_root= range_par->old_root;
   free_root(&alloc,MYF(0));			// Return memory & allocator
+  /* Must be a subset of the locked partitions */
+  bitmap_intersect(&(prune_param.part_info->read_partitions),
+                   &(prune_param.part_info->lock_partitions));
+  if (bitmap_is_clear_all(&(prune_param.part_info->read_partitions)))
+    retval= TRUE;
   DBUG_RETURN(retval);
 }
 
@@ -2879,7 +2884,7 @@ static void mark_full_partition_used_no_
 {
   DBUG_ENTER("mark_full_partition_used_no_parts");
   DBUG_PRINT("enter", ("Mark partition %u as used", part_id));
-  bitmap_set_bit(&part_info->used_partitions, part_id);
+  bitmap_set_bit(&part_info->read_partitions, part_id);
   DBUG_VOID_RETURN;
 }
 
@@ -2895,7 +2900,7 @@ static void mark_full_partition_used_wit
   for (; start != end; start++)
   {
     DBUG_PRINT("info", ("1:Mark subpartition %u as used", start));
-    bitmap_set_bit(&part_info->used_partitions, start);
+    bitmap_set_bit(&part_info->read_partitions, start);
   }
   DBUG_VOID_RETURN;
 }
@@ -2923,7 +2928,7 @@ static int find_used_partitions_imerge_l
   MY_BITMAP all_merges;
   uint bitmap_bytes;
   my_bitmap_map *bitmap_buf;
-  uint n_bits= ppar->part_info->used_partitions.n_bits;
+  uint n_bits= ppar->part_info->read_partitions.n_bits;
   bitmap_bytes= bitmap_buffer_size(n_bits);
   if (!(bitmap_buf= (my_bitmap_map*) alloc_root(ppar->range_param.mem_root,
                                                 bitmap_bytes)))
@@ -2949,14 +2954,14 @@ static int find_used_partitions_imerge_l
     }
 
     if (res != -1)
-      bitmap_intersect(&all_merges, &ppar->part_info->used_partitions);
+      bitmap_intersect(&all_merges, &ppar->part_info->read_partitions);
 
     if (bitmap_is_clear_all(&all_merges))
       return 0;
 
-    bitmap_clear_all(&ppar->part_info->used_partitions);
+    bitmap_clear_all(&ppar->part_info->read_partitions);
   }
-  memcpy(ppar->part_info->used_partitions.bitmap, all_merges.bitmap,
+  memcpy(ppar->part_info->read_partitions.bitmap, all_merges.bitmap,
          bitmap_bytes);
   return 1;
 }
@@ -3315,7 +3320,7 @@ int find_used_partitions(PART_PRUNE_PARA
       {
         for (uint i= 0; i < ppar->part_info->num_subparts; i++)
           if (bitmap_is_set(&ppar->subparts_bitmap, i))
-            bitmap_set_bit(&ppar->part_info->used_partitions,
+            bitmap_set_bit(&ppar->part_info->read_partitions,
                            part_id * ppar->part_info->num_subparts + i);
       }
       goto pop_and_go_right;
@@ -3377,7 +3382,7 @@ int find_used_partitions(PART_PRUNE_PARA
         while ((part_id= ppar->part_iter.get_next(&ppar->part_iter)) !=
                 NOT_A_PARTITION_ID)
         {
-          bitmap_set_bit(&part_info->used_partitions,
+          bitmap_set_bit(&part_info->read_partitions,
                          part_id * part_info->num_subparts + subpart_id);
         }
         res= 1; /* Some partitions were marked as used */
@@ -3456,7 +3461,8 @@ pop_and_go_right:
 
 static void mark_all_partitions_as_used(partition_info *part_info)
 {
-  bitmap_set_all(&part_info->used_partitions);
+  bitmap_copy(&(part_info->read_partitions),
+              &(part_info->lock_partitions));
 }
 
 

=== modified file 'sql/partition_info.cc'
--- a/sql/partition_info.cc	2010-10-01 16:11:50 +0000
+++ b/sql/partition_info.cc	2010-11-28 18:24:58 +0000
@@ -27,6 +27,8 @@
 #include "partition_info.h"
 #include "sql_parse.h"                        // test_if_data_home_dir
 #include "sql_acl.h"                          // *_ACL
+#include "table.h"                            // TABLE_LIST
+#include "my_bitmap.h"                        // bitmap*
 
 #ifdef WITH_PARTITION_STORAGE_ENGINE
 #include "ha_partition.h"
@@ -34,17 +36,21 @@
 
 partition_info *partition_info::get_clone()
 {
+  DBUG_ENTER("partition_info::get_clone");
   if (!this)
-    return 0;
+    DBUG_RETURN(NULL);
   List_iterator<partition_element> part_it(partitions);
   partition_element *part;
   partition_info *clone= new partition_info();
   if (!clone)
   {
     mem_alloc_error(sizeof(partition_info));
-    return NULL;
+    DBUG_RETURN(NULL);
   }
   memcpy(clone, this, sizeof(partition_info));
+  memset(&(clone->read_partitions), 0, sizeof(clone->read_partitions));
+  memset(&(clone->lock_partitions), 0, sizeof(clone->lock_partitions));
+  clone->bitmaps_are_initialized= FALSE;
   clone->partitions.empty();
 
   while ((part= (part_it++)))
@@ -55,7 +61,7 @@ partition_info *partition_info::get_clon
     if (!part_clone)
     {
       mem_alloc_error(sizeof(partition_element));
-      return NULL;
+      DBUG_RETURN(NULL);
     }
     memcpy(part_clone, part, sizeof(partition_element));
     part_clone->subpartitions.empty();
@@ -65,16 +71,176 @@ partition_info *partition_info::get_clon
       if (!subpart_clone)
       {
         mem_alloc_error(sizeof(partition_element));
-        return NULL;
+        DBUG_RETURN(NULL);
       }
       memcpy(subpart_clone, subpart, sizeof(partition_element));
       part_clone->subpartitions.push_back(subpart_clone);
     }
     clone->partitions.push_back(part_clone);
   }
-  return clone;
+  DBUG_RETURN(clone);
 }
 
+
+/**
+  Set read/lock_partitions bitmap over non pruned partitions
+
+  @param table_list   Possible TABLE_LIST which can contain
+                      list of partition names to query
+
+  @return Operation status
+    @retval FALSE  OK
+    @retval TRUE   Failed to allocate memory for bitmap or list of partitions
+                   did not match
+
+  @note OK to call multiple times without the need for free_bitmaps.
+*/
+
+bool partition_info::set_partition_bitmaps(TABLE_LIST *table_list)
+{
+  DBUG_ENTER("partition_info::set_partition_bitmaps");
+
+  DBUG_ASSERT(bitmaps_are_initialized);
+  DBUG_ASSERT(table);
+#ifdef NOT_USED
+  if (!bitmaps_are_initialized && init_bitmaps())
+    DBUG_RETURN(TRUE);
+#else
+  if (!bitmaps_are_initialized)
+    DBUG_RETURN(TRUE);
+#endif /* NOT_USED */
+
+  if (table_list &&
+      table_list->partition_names &&
+      table_list->partition_names->elements)
+  {
+    List_iterator<String> partition_names_it(*(table_list->partition_names));
+    uint num_names= table_list->partition_names->elements;
+    uint i= 0;
+    HASH *part_name_hash;
+    DBUG_ASSERT(table && table->s && table->s->ha_part_data);
+    part_name_hash= &table->s->ha_part_data->partition_name_hash;
+    if (num_names < 1)
+      DBUG_RETURN(TRUE);
+
+    bitmap_clear_all(&read_partitions);
+
+    /* No check for duplicate names or overlapping partitions/subpartitions. */
+    if (part_name_hash->records > 0)
+    {
+      /* Search possible by HASH in table_share->ha_part_data. */
+      do
+      {
+        String *part_name_str= partition_names_it++;
+        const char *part_name= part_name_str->c_ptr_safe();
+        PART_NAME_DEF *part_def;
+        part_def= (PART_NAME_DEF*) my_hash_search(part_name_hash,
+                                                  (const uchar*) part_name,
+                                                  strlen(part_name));
+        if (!part_def)
+        {
+          my_error(ER_NO_SUCH_PARTITION, MYF(0), part_name);
+          DBUG_RETURN(TRUE);
+        }
+
+        if (part_def->is_subpart)
+        {
+          bitmap_set_bit(&read_partitions, part_def->part_id);
+        }
+        else
+        {
+          if (is_sub_partitioned())
+          {
+            /* Mark all subpartitions in the partition */
+            uint j, start= part_def->part_id * num_subparts;
+            uint end= start + num_subparts;
+            for (j= start; j < end; j++)
+              bitmap_set_bit(&read_partitions, j);
+          }
+          else
+            bitmap_set_bit(&read_partitions, part_def->part_id);
+        }
+
+        DBUG_PRINT("info", ("Found partition %u is_subpart %d for name %s",
+                            part_def->part_id, part_def->is_subpart,
+                            part_name));
+      } while (++i < num_names);
+    }
+    else
+    {
+      /* Search must be done through walking through the part_elems. */
+      do
+      {
+        String *part_name_str= partition_names_it++;
+        const char *part_name= part_name_str->c_ptr_safe();
+        List_iterator<partition_element> part_it(partitions);
+        uint part_count= 0;
+        do
+        {
+          partition_element *part_elem= part_it++;
+          if (is_sub_partitioned())
+          {
+            /* Check if it matches the whole partition.  */
+            if (!(my_strcasecmp(system_charset_info, part_elem->partition_name,
+                                part_name)))
+            {
+              /* Mark all subpartitions in the partition */
+              uint j;
+              for (j= 0; j < num_subparts; j++)
+              {
+                bitmap_set_bit(&read_partitions,
+                               (part_count * num_subparts + j));
+              }
+              goto next_name;
+            }
+            /* Check if it matches the a subpartition.  */
+            List_iterator<partition_element>
+              subpart_it(part_elem->subpartitions);
+            uint subpart_count= 0;
+            do
+            {
+              partition_element *subpart_elem= subpart_it++;
+              if (!(my_strcasecmp(system_charset_info,
+                                   subpart_elem->partition_name,
+                                   part_name)))
+              {
+                bitmap_set_bit(&read_partitions,
+                           part_count * num_subparts + subpart_count);
+                goto next_name;
+              }
+            } while (++subpart_count < num_subparts);
+          }
+          else
+          {
+            if (!(my_strcasecmp(system_charset_info, part_elem->partition_name,
+                                 part_name)))
+            {
+              bitmap_set_bit(&read_partitions, part_count);
+              goto next_name;
+            }
+          }
+        } while (++part_count < num_parts);
+
+        my_error(ER_NO_SUCH_PARTITION, MYF(0), part_name);
+        DBUG_RETURN(TRUE);
+
+next_name:
+        DBUG_PRINT("info", ("Found partition %u for name %s",
+                            part_count, part_name));
+        ;
+      } while (++i < num_names);
+    }
+  }
+  else
+  {
+    bitmap_set_all(&read_partitions);
+    DBUG_PRINT("info", ("Set all partitions"));
+  }
+  bitmap_copy(&lock_partitions, &read_partitions);
+  DBUG_RETURN(FALSE);
+}
+
+
 /*
   Create a memory area where default partition names are stored and fill it
   up with the names.

=== modified file 'sql/partition_info.h'
--- a/sql/partition_info.h	2010-10-21 09:49:16 +0000
+++ b/sql/partition_info.h	2010-11-28 18:24:58 +0000
@@ -23,6 +23,7 @@
 #include "partition_element.h"
 
 class partition_info;
+struct TABLE_LIST;
 
 /* Some function typedefs */
 typedef int (*get_part_id_func)(partition_info *part_info,
@@ -44,6 +45,8 @@ public:
 
   List<char> part_field_list;
   List<char> subpart_field_list;
+
+  TABLE *table;
   
   /* 
     If there is no subpartitioning, use only this func to get partition ids.
@@ -111,14 +114,30 @@ public:
   struct st_ddl_log_memory_entry *frm_log_entry;
 
   /* 
-    A bitmap of partitions used by the current query. 
+    Bitmaps of partitions used by the current query. 
+    * read_partitions  - partitions to be used for reading.
+    * lock_partitions  - partitions that must be locked (read or write).
+    Usually read_partitions is the same set as lock_partitions, but
+    in case of UPDATE the WHERE clause can limit the read_partitions set,
+    but not neccesarily the lock_partitions set.
     Usage pattern:
-    * The handler->extra(HA_EXTRA_RESET) call at query start/end sets all
-      partitions to be unused.
-    * Before index/rnd_init(), partition pruning code sets the bits for used
-      partitions.
-  */
-  MY_BITMAP used_partitions;
+    * Initialized in ha_partition::open().
+    * read+lock_partitions is set  according to explicit PARTITION,
+      WL#5217, in open_and_lock_tables().
+    * Bits in read_partitions can be cleared in prune_partitions()
+      in the optimizing step.
+      (WL#4443 is about allowing prune_partitions() to affect lock_partitions
+      and be done before locking too).
+    * When the partition enabled handler get an external_lock call it locks
+      all partitions in lock_partitions (and remembers which partitions it
+      locked, so that it can unlock them later). In case of LOCK TABLES it will
+      lock all partitions, and keep them locked while lock_partitions can
+      change for each statement under LOCK TABLES.
+    * Freed at the same time item_free_list is freed.
+  */
+  MY_BITMAP read_partitions;
+  MY_BITMAP lock_partitions;
+  bool bitmaps_are_initialized;
 
   union {
     longlong *range_int_array;
@@ -219,6 +238,7 @@ public:
     restore_part_field_ptrs(NULL), restore_subpart_field_ptrs(NULL),
     part_expr(NULL), subpart_expr(NULL), item_free_list(NULL),
     first_log_entry(NULL), exec_log_entry(NULL), frm_log_entry(NULL),
+    bitmaps_are_initialized(FALSE),
     list_array(NULL), err_value(0),
     part_info_string(NULL),
     part_func_string(NULL), subpart_func_string(NULL),
@@ -248,6 +268,7 @@ public:
   ~partition_info() {}
 
   partition_info *get_clone();
+  bool set_partition_bitmaps(TABLE_LIST *table_list);
   /* Answers the question if subpartitioning is used for a certain table */
   bool is_sub_partitioned()
   {

=== modified file 'sql/share/errmsg-utf8.txt'
--- a/sql/share/errmsg-utf8.txt	2010-11-15 16:43:41 +0000
+++ b/sql/share/errmsg-utf8.txt	2010-11-28 18:24:58 +0000
@@ -6418,8 +6418,8 @@ ER_TABLES_DIFFERENT_METADATA
   eng "Tables have different definitions"
   swe "Tabellerna har olika definitioner"
 ER_ROW_DOES_NOT_MATCH_PARTITION
-  eng "Found row that does not match the partition"
-  swe "Hittade rad som inte passar i partitionen"
+  eng "Found a row that does not match the partition"
+  swe "Hittade en rad som inte passar i partitionen"
 ER_BINLOG_CACHE_SIZE_GREATER_THAN_MAX
   eng "Option binlog_cache_size (%lu) is greater than max_binlog_cache_size (%lu); setting binlog_cache_size equal to max_binlog_cache_size."
 ER_WARN_INDEX_NOT_APPLICABLE
@@ -6446,3 +6446,30 @@ ER_RPL_INFO_DATA_TOO_LONG
   eng "Data for column '%s' too long"
 ER_CANT_LOCK_RPL_INFO_TABLE
         eng "You can't use locks with rpl info tables."
+
+ER_PARTITION_CLAUSE_ON_NONPARTITIONED
+  eng "PARTITION () clause on non partitioned table"
+  swe "PARTITION () klausul för en icke partitionerad tabell"
+ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET
+  eng "Found a row not matching the given partition set"
+  swe "Hittade en rad som inte passar i någon given partition"
+ER_NO_SUCH_PARTITION 
+  cze "partion '%-.64s' neexistuje"
+  dan "partition '%-.64s' eksisterer ikke"
+  nla "partition '%-.64s' bestaat niet"
+  eng "partition '%-.64s' doesn't exist"
+  est "partition '%-.64s' ei eksisteeri"
+  fre "La partition '%-.64s' n'existe pas"
+  ger "Die partition '%-.64s' existiert nicht"
+  hun "A '%-.64s' partition nem letezik"
+  ita "La tabella particione '%-.64s' non esiste"
+  nor "Partition '%-.64s' doesn't exist"
+  norwegian-ny "Partition '%-.64s' doesn't exist"
+  pol "Partition '%-.64s' doesn't exist"
+  por "Particion '%-.64s' n�o existe"
+  rum "Partition '%-.64s' nu exista"
+  serbian "Partition '%-.64s' ne postoji"
+  slo "Partition '%-.64s' doesn't exist"
+  spa "Particion '%-.64s' no existe"
+  swe "Det finns ingen partition som heter '%-.64s'"
+

=== modified file 'sql/sql_base.cc'
--- a/sql/sql_base.cc	2010-11-15 16:43:41 +0000
+++ b/sql/sql_base.cc	2010-11-28 18:24:58 +0000
@@ -4635,6 +4635,43 @@ open_tables_check_upgradable_mdl(THD *th
 }
 
 
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+static bool prune_partition_locks(TABLE_LIST *tables)
+{
+  TABLE_LIST *table;
+  DBUG_ENTER("prune_partition_locks");
+  for (table= tables; table; table= table->next_global)
+  {
+    /* Avoid to lock/start_stmt partitions not used in the statement. */
+    if (!table->placeholder())
+    {
+      if (table->table->part_info)
+      {
+        /*
+          Initialize and set partitions bitmaps, using table's mem_root,
+          destroyed in closefrm().
+        */
+        if (table->table->part_info->set_partition_bitmaps(table))
+          DBUG_RETURN(TRUE);
+        /*
+          TODO: Add prune_partitions() here as WL#4443.
+          Needs all items and conds fixed (as in first part in JOIN::optimize,
+          mysql_prepare_delete).
+        */
+      }
+      else if (table->partition_names && table->partition_names->elements)
+      {
+        /* Don't allow PARTITION () clause on a nonpartitioned table */
+        my_error(ER_PARTITION_CLAUSE_ON_NONPARTITIONED, MYF(0));
+        DBUG_RETURN(TRUE);
+      }
+    }
+  }
+  DBUG_RETURN(FALSE);
+}
+#endif /* WITH_PARTITION_STORAGE_ENGINE */
+
+
 /**
   Open all tables in list
 
@@ -4896,6 +4933,15 @@ restart:
     }
   }
 
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+  /* Prune partitions to avoid unneccesary locks */
+  if (prune_partition_locks(tables))
+  {
+    error= TRUE;
+    goto err;
+  }
+#endif
+
 err:
   thd_proc_info(thd, 0);
   free_root(&new_frm_mem, MYF(0));              // Free pre-alloced block

=== modified file 'sql/sql_class.h'
--- a/sql/sql_class.h	2010-11-15 16:43:41 +0000
+++ b/sql/sql_class.h	2010-11-28 18:24:58 +0000
@@ -516,6 +516,7 @@ typedef struct system_status_var
   ulong ha_discover_count;
   ulong ha_savepoint_count;
   ulong ha_savepoint_rollback_count;
+  ulong ha_external_lock_count;
 
   /* KEY_CACHE parts. These are copies of the original */
   ulong key_blocks_changed;

=== modified file 'sql/sql_const.h'
--- a/sql/sql_const.h	2010-07-13 17:29:44 +0000
+++ b/sql/sql_const.h	2010-11-28 18:24:58 +0000
@@ -105,6 +105,7 @@
 #define HOST_CACHE_SIZE		128
 #define MAX_ACCEPT_RETRY	10	// Test accept this many times
 #define MAX_FIELDS_BEFORE_HASH	32
+#define MAX_PARTITIONS_BEFORE_HASH 7
 #define USER_VARS_HASH_SIZE     16
 #define TABLE_OPEN_CACHE_MIN    400
 #define TABLE_OPEN_CACHE_DEFAULT 400

=== modified file 'sql/sql_lex.cc'
--- a/sql/sql_lex.cc	2010-11-10 11:26:45 +0000
+++ b/sql/sql_lex.cc	2010-11-28 18:24:58 +0000
@@ -2014,12 +2014,13 @@ bool st_select_lex_node::inc_in_sum_expr
 uint st_select_lex_node::get_in_sum_expr()           { return 0; }
 TABLE_LIST* st_select_lex_node::get_table_list()     { return 0; }
 List<Item>* st_select_lex_node::get_item_list()      { return 0; }
-TABLE_LIST *st_select_lex_node::add_table_to_list (THD *thd, Table_ident *table,
+TABLE_LIST *st_select_lex_node::add_table_to_list(THD *thd, Table_ident *table,
 						  LEX_STRING *alias,
 						  ulong table_join_options,
 						  thr_lock_type flags,
                                                   enum_mdl_type mdl_type,
 						  List<Index_hint> *hints,
+                                                  List<String> *partition_names,
                                                   LEX_STRING *option)
 {
   return 0;

=== modified file 'sql/sql_lex.h'
--- a/sql/sql_lex.h	2010-11-10 11:26:45 +0000
+++ b/sql/sql_lex.h	2010-11-28 18:24:58 +0000
@@ -481,6 +481,7 @@ public:
 					thr_lock_type flags= TL_UNLOCK,
                                         enum_mdl_type mdl_type= MDL_SHARED_READ,
 					List<Index_hint> *hints= 0,
+                                        List<String> *partition_names= 0,
                                         LEX_STRING *option= 0);
   virtual void set_lock_for_tables(thr_lock_type lock_type) {}
 
@@ -792,6 +793,7 @@ public:
 				thr_lock_type flags= TL_UNLOCK,
                                 enum_mdl_type mdl_type= MDL_SHARED_READ,
 				List<Index_hint> *hints= 0,
+                                List<String> *partition_names= 0,
                                 LEX_STRING *option= 0);
   TABLE_LIST* get_table_list();
   bool init_nested_join(THD *thd);

=== modified file 'sql/sql_parse.cc'
--- a/sql/sql_parse.cc	2010-11-15 16:43:41 +0000
+++ b/sql/sql_parse.cc	2010-11-28 18:24:58 +0000
@@ -5778,6 +5778,7 @@ TABLE_LIST *st_select_lex::add_table_to_
 					     thr_lock_type lock_type,
 					     enum_mdl_type mdl_type,
 					     List<Index_hint> *index_hints_arg,
+                                             List<String> *partition_names,
                                              LEX_STRING *option)
 {
   register TABLE_LIST *ptr;
@@ -5922,6 +5923,9 @@ TABLE_LIST *st_select_lex::add_table_to_
   */
   table_list.link_in_list(ptr, &ptr->next_local);
   ptr->next_name_resolution_table= NULL;
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+  ptr->partition_names= partition_names;
+#endif /* WITH_PARTITION_STORAGE_ENGINE */
   /* Link table in global list (all used tables) */
   lex->add_to_query_tables(ptr);
   ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type);

=== modified file 'sql/sql_partition.cc'
--- a/sql/sql_partition.cc	2010-11-08 14:35:45 +0000
+++ b/sql/sql_partition.cc	2010-11-28 18:24:58 +0000
@@ -1321,38 +1321,43 @@ void check_range_capable_PF(TABLE *table
 
 
 /*
-  Set up partition bitmap
+  Set up partition bitmaps
 
-  SYNOPSIS
-    set_up_partition_bitmap()
-    thd                  Thread object
-    part_info            Reference to partitioning data structure
+    @param thd           Thread object
+    @param part_info     Reference to partitioning data structure
 
-  RETURN VALUE
-    TRUE                 Memory allocation failure
-    FALSE                Success
+  @return Operation status
+    @retval TRUE         Memory allocation failure
+    @retval FALSE        Success
 
-  DESCRIPTION
-    Allocate memory for bitmap of the partitioned table
+    Allocate memory for bitmaps of the partitioned table
     and initialise it.
 */
 
-static bool set_up_partition_bitmap(THD *thd, partition_info *part_info)
+static bool set_up_partition_bitmaps(THD *thd, partition_info *part_info)
 {
   uint32 *bitmap_buf;
   uint bitmap_bits= part_info->num_subparts? 
                      (part_info->num_subparts* part_info->num_parts):
                       part_info->num_parts;
   uint bitmap_bytes= bitmap_buffer_size(bitmap_bits);
-  DBUG_ENTER("set_up_partition_bitmap");
+  DBUG_ENTER("set_up_partition_bitmaps");
 
-  if (!(bitmap_buf= (uint32*)thd->alloc(bitmap_bytes)))
+  DBUG_ASSERT(!part_info->bitmaps_are_initialized);
+
+  /* Allocate for both read and lock_partitions */
+  if (!(bitmap_buf= (uint32*) alloc_root(&part_info->table->mem_root,
+                                         bitmap_bytes * 2)))
   {
-    mem_alloc_error(bitmap_bytes);
+    mem_alloc_error(bitmap_bytes * 2);
     DBUG_RETURN(TRUE);
   }
-  bitmap_init(&part_info->used_partitions, bitmap_buf, bitmap_bytes*8, FALSE);
-  bitmap_set_all(&part_info->used_partitions);
+  bitmap_init(&part_info->read_partitions, bitmap_buf, bitmap_bits, FALSE);
+  /* Use the second half of the allocated buffer for lock_partitions */
+  bitmap_init(&part_info->lock_partitions, bitmap_buf + (bitmap_bytes / 4),
+              bitmap_bits, FALSE);
+  part_info->bitmaps_are_initialized= TRUE;
+  part_info->set_partition_bitmaps(NULL);
   DBUG_RETURN(FALSE);
 }
 
@@ -1872,7 +1877,7 @@ bool fix_partition_func(THD *thd, TABLE 
       (table->s->db_type()->partition_flags() & HA_CAN_PARTITION_UNIQUE))) &&
                check_unique_keys(table)))
     goto end;
-  if (unlikely(set_up_partition_bitmap(thd, part_info)))
+  if (unlikely(set_up_partition_bitmaps(thd, part_info)))
     goto end;
   if (unlikely(part_info->set_up_charset_field_preps()))
   {
@@ -3996,7 +4001,7 @@ err:
 
   DESCRIPTION
     This function is called to prune the range of partitions to scan by
-    checking the used_partitions bitmap.
+    checking the read_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.
@@ -4013,7 +4018,7 @@ void prune_partition_set(const TABLE *ta
   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))
+    if (bitmap_is_set(&(part_info->read_partitions), i))
     {
       DBUG_PRINT("info", ("Partition %d is set", i));
       if (last_partition == -1)
@@ -4095,7 +4100,7 @@ void get_partition_set(const TABLE *tabl
         */
         get_full_part_id_from_key(table,buf,key_info,key_spec,part_spec);
         /*
-          Check if range can be adjusted by looking in used_partitions
+          Check if range can be adjusted by looking in read_partitions
         */
         prune_partition_set(table, part_spec);
         DBUG_VOID_RETURN;
@@ -4147,7 +4152,7 @@ void get_partition_set(const TABLE *tabl
           get_full_part_id_from_key(table,buf,key_info,key_spec,part_spec);
           clear_indicator_in_key_fields(key_info);
           /*
-            Check if range can be adjusted by looking in used_partitions
+            Check if range can be adjusted by looking in read_partitions
           */
           prune_partition_set(table, part_spec);
           DBUG_VOID_RETURN; 
@@ -4217,7 +4222,7 @@ void get_partition_set(const TABLE *tabl
   if (found_part_field)
     clear_indicator_in_key_fields(key_info);
   /*
-    Check if range can be adjusted by looking in used_partitions
+    Check if range can be adjusted by looking in read_partitions
   */
   prune_partition_set(table, part_spec);
   DBUG_VOID_RETURN;
@@ -4366,6 +4371,7 @@ bool mysql_unpack_partition(THD *thd,
   }
   table->part_info= part_info;
   table->file->set_part_info(part_info);
+  part_info->table= table;
   if (!part_info->default_engine_type)
     part_info->default_engine_type= default_db_type;
   DBUG_ASSERT(part_info->default_engine_type == default_db_type);
@@ -7165,20 +7171,19 @@ void mem_alloc_error(size_t size)
 }
 
 #ifdef WITH_PARTITION_STORAGE_ENGINE
-/*
-  Return comma-separated list of used partitions in the provided given string
+/**
+  Return comma-separated list of used partitions in the provided given string.
 
-  SYNOPSIS
-    make_used_partitions_str()
-      part_info  IN  Partitioning info
-      parts_str  OUT The string to fill
+    @param      part_info  Partitioning info
+    @param[out] parts_str  The string to fill
 
-  DESCRIPTION
-    Generate a list of used partitions (from bits in part_info->used_partitions
+    Generate a list of used partitions (from bits in part_info->read_partitions
     bitmap), asd store it into the provided String object.
     
-  NOTE
+    @note
     The produced string must not be longer then MAX_PARTITIONS * (1 + FN_LEN).
+    In case of UPDATE, only the partitions read is given, not the partitions
+    that was written or locked.
 */
 
 void make_used_partitions_str(partition_info *part_info, String *parts_str)
@@ -7196,7 +7201,7 @@ void make_used_partitions_str(partition_
       List_iterator<partition_element> it2(head_pe->subpartitions);
       while ((pe= it2++))
       {
-        if (bitmap_is_set(&part_info->used_partitions, partition_id))
+        if (bitmap_is_set(&part_info->read_partitions, partition_id))
         {
           if (parts_str->length())
             parts_str->append(',');
@@ -7216,7 +7221,7 @@ void make_used_partitions_str(partition_
   {
     while ((pe= it++))
     {
-      if (bitmap_is_set(&part_info->used_partitions, partition_id))
+      if (bitmap_is_set(&part_info->read_partitions, partition_id))
       {
         if (parts_str->length())
           parts_str->append(',');

=== modified file 'sql/sql_yacc.yy'
--- a/sql/sql_yacc.yy	2010-11-05 12:03:40 +0000
+++ b/sql/sql_yacc.yy	2010-11-28 18:24:58 +0000
@@ -780,10 +780,10 @@ bool my_yyoverflow(short **a, YYSTYPE **
 
 %pure_parser                                    /* We have threads */
 /*
-  Currently there are 167 shift/reduce conflicts.
+  Currently there are 164 shift/reduce conflicts.
   We should not introduce new conflicts any more.
 */
-%expect 167
+%expect 164
 
 /*
    Comments for TOKENS.
@@ -1170,9 +1170,9 @@ bool my_yyoverflow(short **a, YYSTYPE **
 %token  PARAM_MARKER
 %token  PARSER_SYM
 %token  PARTIAL                       /* SQL-2003-N */
-%token  PARTITIONING_SYM
-%token  PARTITIONS_SYM
 %token  PARTITION_SYM                 /* SQL-2003-R */
+%token  PARTITIONS_SYM
+%token  PARTITIONING_SYM
 %token  PASSWORD
 %token  PHASE_SYM
 %token  PLUGINS_SYM
@@ -1506,7 +1506,7 @@ bool my_yyoverflow(short **a, YYSTYPE **
         btree_or_rtree
 
 %type <string_list>
-        using_list
+        using_list opt_use_partition use_partition
 
 %type <key_part>
         key_part
@@ -9417,6 +9417,22 @@ normal_join:
         | CROSS JOIN_SYM {}
         ;
 
+/*
+  table PARTITION (list of partitions), reusing using_list instead of creating
+  a new rule for partition_list.
+*/
+opt_use_partition:
+          /* empty */ { $$= 0;}
+        | use_partition
+        ;
+        
+use_partition:
+          PARTITION_SYM '(' using_list ')' have_partitioning
+          {
+            $$= $3;
+          }
+        ;
+  
 /* 
    This is a flattening of the rules <table factor> and <table primary>
    in the SQL:2003 standard, since we don't have <sample clause>
@@ -9430,13 +9446,14 @@ table_factor:
             SELECT_LEX *sel= Select;
             sel->table_join_options= 0;
           }
-          table_ident opt_table_alias opt_key_definition
+          table_ident opt_use_partition opt_table_alias opt_key_definition
           {
-            if (!($$= Select->add_table_to_list(YYTHD, $2, $3,
+            if (!($$= Select->add_table_to_list(YYTHD, $2, $4,
                                                 Select->get_table_join_options(),
                                                 YYPS->m_lock_type,
                                                 YYPS->m_mdl_type,
-                                                Select->pop_index_hints())))
+                                                Select->pop_index_hints(),
+                                                $3)))
               MYSQL_YYABORT;
             Select->add_joined_table($$);
           }
@@ -9506,7 +9523,7 @@ table_factor:
               if (ti == NULL)
                 MYSQL_YYABORT;
               if (!($$= sel->add_table_to_list(lex->thd,
-                                               new Table_ident(unit), $5, 0,
+                                               ti, $5, 0,
                                                TL_READ, MDL_SHARED_READ)))
 
                 MYSQL_YYABORT;
@@ -10494,6 +10511,19 @@ table_name:
           }
         ;
 
+table_name_with_opt_use_partition:
+          table_ident opt_use_partition
+          {
+            if (!Select->add_table_to_list(YYTHD, $1, NULL,
+                                           TL_OPTION_UPDATING,
+                                           YYPS->m_lock_type,
+                                           YYPS->m_mdl_type,
+                                           NULL,
+                                           $2))
+              MYSQL_YYABORT;
+          }
+        ;
+
 table_alias_ref_list:
           table_alias_ref
         | table_alias_ref_list ',' table_alias_ref
@@ -10617,7 +10647,7 @@ insert2:
         ;
 
 insert_table:
-          table_name
+          table_name_with_opt_use_partition
           {
             LEX *lex=Lex;
             lex->field_list.empty();
@@ -10817,11 +10847,13 @@ delete:
         ;
 
 single_multi:
-          FROM table_ident
+          FROM table_ident opt_use_partition
           {
             if (!Select->add_table_to_list(YYTHD, $2, NULL, TL_OPTION_UPDATING,
                                            YYPS->m_lock_type,
-                                           YYPS->m_mdl_type))
+                                           YYPS->m_mdl_type,
+                                           NULL,
+                                           $3))
               MYSQL_YYABORT;
             YYPS->m_lock_type= TL_READ_DEFAULT;
             YYPS->m_mdl_type= MDL_SHARED_READ;
@@ -11583,18 +11615,18 @@ load:
             if (!(lex->exchange= new sql_exchange($7.str, 0, $2)))
               MYSQL_YYABORT;
           }
-          opt_duplicate INTO TABLE_SYM table_ident
+          opt_duplicate INTO TABLE_SYM table_ident opt_use_partition
           {
             LEX *lex=Lex;
             if (!Select->add_table_to_list(YYTHD, $12, NULL, TL_OPTION_UPDATING,
-                                           $4, MDL_SHARED_WRITE))
+                                           $4, MDL_SHARED_WRITE, NULL, $13))
               MYSQL_YYABORT;
             lex->field_list.empty();
             lex->update_list.empty();
             lex->value_list.empty();
           }
           opt_load_data_charset
-          { Lex->exchange->cs= $14; }
+          { Lex->exchange->cs= $15; }
           opt_xml_rows_identified_by
           opt_field_term opt_line_term opt_ignore_lines opt_field_or_var_spec
           opt_load_data_set_spec
@@ -12532,7 +12564,6 @@ keyword:
         | OPTIONS_SYM           {}
         | OWNER_SYM             {}
         | PARSER_SYM            {}
-        | PARTITION_SYM         {}
         | PORT_SYM              {}
         | PREPARE_SYM           {}
         | REMOVE_SYM            {}

=== modified file 'sql/table.cc'
--- a/sql/table.cc	2010-11-15 16:43:41 +0000
+++ b/sql/table.cc	2010-11-28 18:24:58 +0000
@@ -204,6 +204,17 @@ static uchar *get_field_name(Field **buf
 }
 
 
+/**
+  A function to return the partition name from a partition element
+*/
+uchar *get_part_name(PART_NAME_DEF *part, size_t *length,
+                            my_bool not_used __attribute__((unused)))
+{
+  *length= part->length;
+  return part->partition_name;
+}
+
+
 /*
   Returns pointer to '.frm' extension of the file name.
 
@@ -1969,8 +1980,9 @@ int open_table_from_share(THD *thd, TABL
     }
     outparam->part_info->is_auto_partitioned= share->auto_partitioned;
     DBUG_PRINT("info", ("autopartitioned: %u", share->auto_partitioned));
-    /* we should perform the fix_partition_func in either local or
-       caller's arena depending on work_part_info_used value
+    /*
+      We should perform the fix_partition_func in either local or
+      caller's arena depending on work_part_info_used value.
     */
     if (!work_part_info_used)
       tmp= fix_partition_func(thd, outparam, is_create_table);
@@ -2121,6 +2133,7 @@ int closefrm(register TABLE *table, bool
 #ifdef WITH_PARTITION_STORAGE_ENGINE
   if (table->part_info)
   {
+    /* Allocated through table->mem_root, freed below */
     free_items(table->part_info->item_free_list);
     table->part_info->item_free_list= 0;
     table->part_info= 0;

=== modified file 'sql/table.h'
--- a/sql/table.h	2010-11-15 16:43:41 +0000
+++ b/sql/table.h	2010-11-28 18:24:58 +0000
@@ -487,6 +487,18 @@ typedef struct st_table_field_def
 
 
 #ifdef WITH_PARTITION_STORAGE_ENGINE
+/** Struct to be used for partition_name_hash */
+typedef struct st_part_name_def
+{
+  uchar *partition_name;
+  uint length;
+  uint32 part_id;
+  my_bool is_subpart;
+} PART_NAME_DEF;
+
+uchar *get_part_name(PART_NAME_DEF *part, size_t *length,
+                     my_bool not_used __attribute__((unused)));
+
 /**
   Partition specific ha_data struct.
 */
@@ -495,6 +507,11 @@ typedef struct st_ha_data_partition
   bool auto_inc_initialized;
   mysql_mutex_t LOCK_auto_inc;                 /**< protecting auto_inc val */
   ulonglong next_auto_inc_val;                 /**< first non reserved value */
+  /**
+    Hash of partition names. Initialized in the first ha_partition::open()
+    for the table_share. After that it is read-only, i.e. no locking required.
+  */
+  HASH partition_name_hash;
 } HA_DATA_PARTITION;
 #endif
 
@@ -1710,6 +1727,11 @@ struct TABLE_LIST
 
   MDL_request mdl_request;
 
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+  /* List to carry partition names from PARTITION (...) clause in statement */
+  List<String> *partition_names;
+#endif /* WITH_PARTITION_STORAGE_ENGINE */
+
   void calc_md5(char *buffer);
   void set_underlying_merge();
   int view_check_option(THD *thd, bool ignore_failure);

No bundle (reason: useless for push emails).
Thread
bzr push into mysql-trunk branch (mattias.jonsson:3206 to 3207) WL#5217Mattias Jonsson28 Nov