diff --git a/mysql-test/extra/binlog_tests/blackhole.test b/mysql-test/extra/binlog_tests/blackhole.test
index 05e59838168e10677f6cd95b885a91e002401f13..80f998359ba00fcdba271088774abb258f3aff96 100644
--- a/mysql-test/extra/binlog_tests/blackhole.test
+++ b/mysql-test/extra/binlog_tests/blackhole.test
@@ -121,11 +121,7 @@ select * from t2;
 select * from t3;
 
 let $VERSION=`select version()`;
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
---replace_regex /table_id: [0-9]+/table_id: #/
-show binlog events;
-
+source include/show_binlog_events.inc;
 drop table t1,t2,t3;
 
 #
@@ -157,10 +153,7 @@ start transaction;
 insert into t1 values(2);
 rollback;
 set autocommit=1;
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
---replace_regex /table_id: [0-9]+/table_id: #/
-show binlog events;
+source include/show_binlog_events.inc;
 drop table if exists t1;
 
 # End of 5.0 tests
diff --git a/mysql-test/extra/binlog_tests/drop_temp_table.test b/mysql-test/extra/binlog_tests/drop_temp_table.test
index 9c8647395bf02974c87b5f5d5a4bf50848444315..87f94eff987feea71c2497a16f30827fb32d3074 100644
--- a/mysql-test/extra/binlog_tests/drop_temp_table.test
+++ b/mysql-test/extra/binlog_tests/drop_temp_table.test
@@ -23,10 +23,7 @@ connection con2;
 # To be sure that logging has been done, we use a user lock.
 select get_lock("a",10);
 let $VERSION=`select version()`;
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
---replace_regex /table_id: [0-9]+/table_id: #/
-show binlog events;
+source include/show_binlog_events.inc;
 drop database `drop-temp+table-test`;
 
 # End of 4.1 tests
diff --git a/mysql-test/extra/binlog_tests/insert_select-binlog.test b/mysql-test/extra/binlog_tests/insert_select-binlog.test
index 07da4a1907f61a8b0aecdf31750abf32679fae6c..b09eebcb996c8e28ae52496be103816cf256f07b 100644
--- a/mysql-test/extra/binlog_tests/insert_select-binlog.test
+++ b/mysql-test/extra/binlog_tests/insert_select-binlog.test
@@ -18,9 +18,7 @@ insert into t1 select * from t2;
 # The above should produce an error, but still be in the binlog;
 # verify the binlog :
 let $VERSION=`select version()`;
---replace_result $VERSION VERSION
---replace_regex /table_id: [0-9]+/table_id: #/
-show binlog events;
+source include/show_binlog_events.inc;
 select * from t1;
 drop table t1, t2;
 
@@ -33,9 +31,7 @@ reset master;
 create table t2(unique(a)) select a from t1;
 # The above should produce an error, *and* not appear in the binlog
 let $VERSION=`select version()`;
---replace_result $VERSION VERSION
---replace_regex /table_id: [0-9]+/table_id: #/
-show binlog events;
+source include/show_binlog_events.inc;
 drop table t1;
 
 # End of 4.1 tests
diff --git a/mysql-test/extra/rpl_tests/rpl_ddl.test b/mysql-test/extra/rpl_tests/rpl_ddl.test
index 15794e5e035d81c92d581dd87d25737b94a4eb68..e40532f005f8daab20975ca4c8bc3ccb49765884 100644
--- a/mysql-test/extra/rpl_tests/rpl_ddl.test
+++ b/mysql-test/extra/rpl_tests/rpl_ddl.test
@@ -1,31 +1,128 @@
-######################## rpl_ddl.test ########################
-#                                                            #
-# DDL statements (sometimes with implicit COMMIT) executed   #
-# by the master and it's propagation into the slave          #
-#                                                            #
-##############################################################
-
+################# extra/rpl_tests/rpl_ddl.test ########################
+#                                                                     #
+# DDL statements (sometimes with implicit COMMIT) and other stuff     #
+# executed on the master and it's propagation into the slave.         #
+#                                                                     #
+# The variables                                                       #
+#    $engine_type       -- storage engine to be tested/used for the   #
+#                          permanent tables within the master         #
+#    $temp_engine_type  -- storage engine which supports TEMPORARY    #
+#                          tables <> $engine_type                     #
+#                          $temp_engine_type must point to an all     #
+#                          time available storage engine              #
+#                          2007-02 MySQL 5.1 MyISAM and MEMORY only   #
+#    $show_binlog       -- print binlog entries                       #
+#                          0 - no (default) + fits to the file with   #
+#                              results                                #
+#                          1 - yes (important for debugging)          #
+#                          This variable is used within               #
+#                          include/rpl_stmt_seq.inc.                  #
+#    $manipulate        -- Manipulation of the binary logs            #
+#                          0 - do nothing                             #
+#                          1 - so that the output of SHOW BINLOG      #
+#                              EVENTS IN <current log> contains only  #
+#                              commands of the current test sequence  #
+#                              This is especially useful, if the      #
+#                              $show_binlog is set to 1 and many      #
+#                              subtest are executed.                  #
+#                          This variable is used within               #
+#                          include/rpl_stmt_seq.inc.                  #
+# have to be set before sourcing this script.                         #
+#                                                                     #
+# General assumption about the ideal replication behaviour:           #
+#    Whatever on the master is executed the content of the slave must #
+#    be in sync with it.                                              #
+#                                                                     #
+#    Tests of special interest:                                       #
+#    a) Which DDL commands cause an implicit COMMIT ?                 #
+#       This is also of interest outside of replication.              #
+#    b) Transactions modifying table content ending with              #
+#       - explicit COMMIT or ROLLBACK                                 #
+#       - implicit COMMIT because the connection to the master        #
+#         executed a corresponding DDL statement or runs in           #
+#         AUTOCOMMIT mode                                             #
+#       - something similar to "implicit COMMIT" if the storage       #
+#         engine (master) is not transactional                        #
+#    c) Command which change no data like SELECT or SHOW              #
+#       They do not change anything within the master but             #
+#       this must be also valid for the slave.                        #
+#                                                                     #
+#######################################################################
+
+# Last update:
+# 2007-02-12 ML: - slave needs AUTOCOMMIT = 1, because we want to check only
+#                  the propagation of actions of the master connection.
+#                - replace comments via SQL by "--echo ..."
+#                - remove some bugs within the testscripts
+#                - remove the use of include/rpl_stmt_seq2.inc
+#              
+#
+# NOTES:
+# 2006-11-15 Lars: Matthias (ML) is the "owner" of this test case.
+#                  So, please get him to review it whenever you want to
+#                  do changes to it.
+#
+# PLEASE BE CAREFUL, WHEN MODIFYING THE TESTS !!
 #
-# NOTE, PLEASE BE CAREFUL, WHEN MODIFYING THE TESTS !!
+#    Typical test architecture (--> include/rpl_stmt_seq.inc)
+#    --------------------------------------------------------
+#    1. Master (no AUTOCOMMIT!): INSERT INTO mysqltest1.t1 without commit
+#    2. Master and slave: Check the content of mysqltest1.t1
+#    3. Master (no AUTOCOMMIT!): EXECUTE the statement to be tested
+#    4. Master and slave: Check the content of mysqltest1.t1
+#    5. Master (no AUTOCOMMIT!): ROLLBACK
+#    6. Master and slave: Check the content of mysqltest1.t1
+#       If the previous into mysqltest1.t1 inserted row is visible,
+#       than the statement to be tested caused an explicit COMMIT
+#       (statement = COMMIT) or an implicit COMMIT (example CREATE TABLE).
+#       If the previous into mysqltest1.t1 inserted row is not visible,
+#       than the statement to be tested caused either an explicit ROLLBACK
+#       (statement = ROLLBACK), an implicit ROLLBACK (deadlock etc. but
+#       not tested here) or it does not cause any transaction end. 
+#    7. Flush the logs
+#            
+#    Some rules:
+#    -----------
+#    1. Any use of mysqltest1.t1 within the statement to be tested must be
+#       avoided if possible. The only known exception is around LOCK TABLE.
+#               
+#    2. The test logics needs for
+#           master connection: AUTOCOMMIT = 0
+#           slave  connection: AUTOCOMMIT = 1
+#       The master connection  is the actor and the slave connection is 
+#       only an observer. I.e. the slave connection must not influence
+#       the activities of master connection.
 #
-#      1. !All! objects to be dropped, renamed, altered ... must be created
-#         in AUTOCOMMIT= 1 mode before AUTOCOMMIT is set to 0 and the test
-#         sequences start.
+#    3. !All! objects to be dropped, renamed, altered ... must be created
+#       before the tests start.
+#       --> less switching of AUTOCOMMIT mode on master side.
 #
-#      2. Never use a test object, which was direct or indirect affected by a
-#         preceeding test sequence again.
-#         Except table d1.t1 where ONLY DML is allowed.
+#    4. Never use a test object, which was direct or indirect affected by a
+#       preceeding test sequence again.
+#       If one preceeding test sequence hits a (sometimes not visible,
+#       because the sql error code of the statement might be 0) bug
+#       and these rules are ignored, a following test sequence might earn ugly
+#       effects like failing 'sync_slave_with_master', crashes of the slave or
+#       abort of the test case etc.. This means during analysis the first look
+#       points into a totally wrong area.
+#       Except table mysqltest1.t1 where ONLY DML is allowed.
 #
-#         If one preceeding test sequence hits a (sometimes not good visible,
-#         because the sql error code of the statement might be 0) bug
-#         and these rules are ignored, a following test sequence might earn ugly
-#         effects like failing 'sync_slave_with_master', crashes of the slave or
-#         abort of the test case etc..
+#    5. This file is used in several tests (t/rpl_ddl_<whatever>.test).
+#         Please be aware that every change of the current file affects
+#         the results of these tests.
 #
-#      3. The assignment of the DDL command to be tested to $my_stmt can
-#         be a bit difficult. "'" must be avoided, because the test
-#         routine "include/rpl_stmt_seq.inc" performs a
-#         eval SELECT CONCAT('######## ','$my_stmt','  ########') as "";
+# ML: Some maybe banal hints:
+#     1. The fact that we have here a master - slave replication does
+#        not cause that many general MySQL properties do not apply.
+#        Example:
+#        The connection to the slave is just a simple session and not a however
+#        magic working "copy" of the master session or something similar.
+#        - TEMPORARY TABLES and @variables are session specific
+#        - the slave session cannot see these things of the master.
+#     2. The slave connection must not call sync_slave_with_master.
+#     3. SHOW STATUS SLAVE must be run within the slave connection.
+#     4. Testcase analysis becomes much more comfortable if 
+#        $show_binlog within include/rpl_stmt_seq.inc is set to 1.
 #
 
 ###############################################################
@@ -33,8 +130,10 @@
 ###############################################################
 # The sync_slave_with_master is needed to make the xids deterministic.
 sync_slave_with_master;
-connection master;
 
+--echo
+--echo -------- switch to master -------
+connection master;
 SET AUTOCOMMIT = 1;
 #
 # 1. DROP all objects, which probably already exist, but must be created here
@@ -47,7 +146,7 @@ DROP DATABASE IF EXISTS mysqltest3;
 #
 # 2. CREATE all objects needed
 #    working database is mysqltest1
-#    working (transactional!) is mysqltest1.t1 
+#    working table (transactional!) is mysqltest1.t1 
 #
 CREATE DATABASE mysqltest1;
 CREATE DATABASE mysqltest2;
@@ -73,25 +172,23 @@ eval CREATE TABLE mysqltest1.t16 (f1 BIGINT) ENGINE=$engine_type;
 eval CREATE TABLE mysqltest1.t17 (f1 BIGINT) ENGINE=$engine_type;
 eval CREATE TABLE mysqltest1.t18 (f1 BIGINT) ENGINE=$engine_type;
 eval CREATE TABLE mysqltest1.t19 (f1 BIGINT) ENGINE=$engine_type;
-CREATE TEMPORARY TABLE mysqltest1.t23 (f1 BIGINT);
+eval CREATE TEMPORARY TABLE mysqltest1.t23 (f1 BIGINT) ENGINE=$temp_engine_type;
 
 #
 # 3. master sessions: never do AUTOCOMMIT
-#    slave  sessions: never do AUTOCOMMIT
+#    slave  sessions: do AUTOCOMMIT
 #
 SET AUTOCOMMIT = 0;
 use mysqltest1;
 sync_slave_with_master;
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SET AUTOCOMMIT = 0;
+SET AUTOCOMMIT = 1;
 use mysqltest1;
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
 
 # We don't want to abort the whole test if one statement sent
@@ -99,6 +196,21 @@ SELECT '-------- switch to master -------' as "";
 # sequences are nearly independend of the previous statements. 
 --disable_abort_on_error
 
+###############################################################
+# Banal case: commands which should never commit
+# Just for checking if the test sequence is usable
+###############################################################
+
+let $my_stmt= SELECT 1;
+let $my_master_commit= false;
+let $my_slave_commit= false;
+--source include/rpl_stmt_seq.inc
+
+let $my_stmt= SELECT COUNT(*) FROM t1;
+let $my_master_commit= false;
+let $my_slave_commit= false;
+--source include/rpl_stmt_seq.inc
+
 ###############################################################
 # Banal case: (explicit) COMMIT and ROLLBACK
 # Just for checking if the test sequence is usable
@@ -143,84 +255,64 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW TABLES LIKE 't2';
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 SHOW TABLES LIKE 't2';
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-# Note: Since this test is executed with a skip-innodb slave, the
-# slave incorrectly commits the insert.  One can *not* have InnoDB on
-# master and MyISAM on slave and expect that a transactional rollback
-# after a CREATE TEMPORARY TABLE should work correctly on the slave.
-# For this to work properly the handler on the slave must be able to 
-# handle transactions (e.g. InnoDB or NDB).
+
 let $my_stmt= DROP TEMPORARY TABLE mysqltest1.t23;
 let $my_master_commit= false;
-let $my_slave_commit= true;
+let $my_slave_commit= false;
 --source include/rpl_stmt_seq.inc
 SHOW TABLES LIKE 't23';
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 SHOW TABLES LIKE 't23';
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
 let $my_stmt= RENAME TABLE mysqltest1.t3 to mysqltest1.t20;
 let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW TABLES LIKE 't20';
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 SHOW TABLES LIKE 't20';
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
 let $my_stmt= ALTER TABLE mysqltest1.t4 ADD column f2 BIGINT;
 let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 describe mysqltest1.t4;
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 describe mysqltest1.t4;
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
-let $my_stmt= CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE=;
+let $my_stmt= CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= $engine_type;
 let $my_master_commit= true;
 let $my_slave_commit= true;
---source include/rpl_stmt_seq2.inc
-
-# Note: Since this test is executed with a skip-innodb slave, the
-# slave incorrectly commits the insert.  One can *not* have InnoDB on
-# master and MyISAM on slave and expect that a transactional rollback
-# after a CREATE TEMPORARY TABLE should work correctly on the slave.
-# For this to work properly the handler on the slave must be able to 
-# handle transactions (e.g. InnoDB or NDB).
+--source include/rpl_stmt_seq.inc
+
 let $engine='';
 let $eng_type='';
 
-let $my_stmt= CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT);
+let $my_stmt= CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT) ENGINE=$temp_engine_type;
 let $my_master_commit= false;
-let $my_slave_commit= true;
+let $my_slave_commit= false;
 --source include/rpl_stmt_seq.inc
 
 let $my_stmt= TRUNCATE TABLE mysqltest1.t7;
@@ -228,9 +320,12 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SELECT * FROM mysqltest1.t7;
---echo -------- switch to slave --------
 sync_slave_with_master;
+--echo
+--echo -------- switch to slave --------
+connection slave;
 SELECT * FROM mysqltest1.t7;
+--echo
 --echo -------- switch to master -------
 connection master;
 
@@ -238,8 +333,13 @@ connection master;
 # Cases with LOCK/UNLOCK
 ###############################################################
 
-# MySQL insists in locking mysqltest1.t1, because rpl_stmt_seq performs an
-# INSERT into this table.
+# Attention:
+#    We have to LOCK mysqltest1.t1 here, though it violates the testing
+#    philosophy. 
+#    Mysql response in case without previous LOCK TABLES mysqltest1.t1
+#    is:
+#        SELECT MAX(...) FROM mysqltest1.t1 is
+#          ERROR HY000: Table 't1' was not locked with LOCK TABLES
 let $my_stmt= LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ;
 let $my_master_commit= true;
 let $my_slave_commit= true;
@@ -253,8 +353,9 @@ let $my_slave_commit= false;
 --source include/rpl_stmt_seq.inc
 
 # With prior read locking
-# Note that this test generate an error since the rpl_stmt_seq.inc
-# tries to insert into t1.
+# Attention:
+#    This subtest generates an error since the rpl_stmt_seq.inc
+#    tries to insert into t1.
 LOCK TABLES mysqltest1.t1 READ;
 let $my_stmt= UNLOCK TABLES;
 let $my_master_commit= false;
@@ -277,30 +378,26 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW INDEX FROM mysqltest1.t6;
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 SHOW INDEX FROM mysqltest1.t6;
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
 let $my_stmt= CREATE INDEX my_idx5 ON mysqltest1.t5(f1);
 let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW INDEX FROM mysqltest1.t5;
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 SHOW INDEX FROM mysqltest1.t5;
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
 ###############################################################
 # Cases with DATABASE
@@ -311,35 +408,31 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW DATABASES LIKE "mysqltest2";
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 SHOW DATABASES LIKE "mysqltest2";
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
 let $my_stmt= CREATE DATABASE mysqltest3;
 let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW DATABASES LIKE "mysqltest3";
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 SHOW DATABASES LIKE "mysqltest3";
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 
 # End of 4.1 tests
 
 ###############################################################
-# Cases with stored procedures
+# Cases with STORED PROCEDUREs
 ###############################################################
 let $my_stmt= CREATE PROCEDURE p1() READS SQL DATA SELECT "this is p1";
 let $my_master_commit= true;
@@ -348,12 +441,13 @@ let $my_slave_commit= true;
 --vertical_results
 --replace_column 5 # 6 #
 SHOW PROCEDURE STATUS LIKE 'p1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 --replace_column 5 # 6 #
 SHOW PROCEDURE STATUS LIKE 'p1';
+--echo
+--echo -------- switch to master -------
 connection master;
 --horizontal_results
 
@@ -364,12 +458,13 @@ let $my_slave_commit= true;
 --vertical_results
 --replace_column 5 # 6 #
 SHOW PROCEDURE STATUS LIKE 'p1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 --replace_column 5 # 6 #
 SHOW PROCEDURE STATUS LIKE 'p1';
+--echo
+--echo -------- switch to master -------
 connection master;
 --horizontal_results
 
@@ -379,11 +474,12 @@ let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 --vertical_results
 SHOW PROCEDURE STATUS LIKE 'p1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SHOW PROCEDURE STATUS LIKE 'p1';
+--echo
+--echo -------- switch to master -------
 connection master;
 --horizontal_results
 
@@ -395,11 +491,12 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW CREATE VIEW v1;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SHOW CREATE VIEW v1;
+--echo
+--echo -------- switch to master -------
 connection master;
 
 let $my_stmt= ALTER VIEW v1 AS select f1 from t1;
@@ -407,11 +504,12 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW CREATE VIEW v1;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SHOW CREATE VIEW v1;
+--echo
+--echo -------- switch to master -------
 connection master;
 
 let $my_stmt= DROP VIEW IF EXISTS v1;
@@ -420,12 +518,13 @@ let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 --error 1146
 SHOW CREATE VIEW v1;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 --error 1146
 SHOW CREATE VIEW v1;
+--echo
+--echo -------- switch to master -------
 connection master;
 
 ###############################################################
@@ -436,11 +535,12 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW TRIGGERS;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SHOW TRIGGERS;
+--echo
+--echo -------- switch to master -------
 connection master;
 
 let $my_stmt= DROP TRIGGER trg1;
@@ -448,11 +548,12 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SHOW TRIGGERS;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SHOW TRIGGERS;
+--echo
+--echo -------- switch to master -------
 connection master;
 
 ###############################################################
@@ -463,11 +564,12 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SELECT user FROM mysql.user WHERE user = 'user1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SELECT user FROM mysql.user WHERE user = 'user1';
+--echo
+--echo -------- switch to master -------
 connection master;
 
 let $my_stmt= RENAME USER user1@localhost TO rename1@localhost;
@@ -475,11 +577,12 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SELECT user FROM mysql.user WHERE user = 'rename1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SELECT user FROM mysql.user WHERE user = 'rename1';
+--echo
+--echo -------- switch to master -------
 connection master;
 
 let $my_stmt= DROP USER rename1@localhost;
@@ -487,21 +590,21 @@ let $my_master_commit= true;
 let $my_slave_commit= true;
 --source include/rpl_stmt_seq.inc
 SELECT user FROM mysql.user WHERE user = 'rename1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
+--echo
+--echo -------- switch to slave --------
 connection slave;
 SELECT user FROM mysql.user WHERE user = 'rename1';
-connection master;
 
 ###############################################################
 # Cleanup
 ###############################################################
---disable_warnings
-DROP DATABASE IF EXISTS mysqltest1;
-DROP DATABASE IF EXISTS mysqltest2;
-DROP DATABASE IF EXISTS mysqltest3;
+use test;
+--echo
+--echo -------- switch to master -------
+connection master;
+DROP DATABASE mysqltest1;
+# mysqltest2 was alreday DROPPED some tests before.
+DROP DATABASE mysqltest3;
 --enable_warnings
 
 -- source include/master-slave-end.inc
-
diff --git a/mysql-test/extra/rpl_tests/rpl_log.test b/mysql-test/extra/rpl_tests/rpl_log.test
index b6d6cb8f308663aeafb1b2e58a6bf0d96c25b2a4..932fcdf670b35f73eb66586f1e2049d34a84e5af 100644
--- a/mysql-test/extra/rpl_tests/rpl_log.test
+++ b/mysql-test/extra/rpl_tests/rpl_log.test
@@ -88,10 +88,7 @@ connection master;
 
 eval create table t2 (n int)ENGINE=$engine_type;
 insert into t2 values (1);
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
---replace_regex /\/\* xid=.* \*\//\/* XID *\// /table_id: [0-9]+/table_id: #/
-show binlog events;
+source include/show_binlog_events.inc;
 --replace_result $VERSION VERSION
 --replace_column 2 # 5 #
 --replace_regex /\/\* xid=.* \*\//\/* XID *\// /table_id: [0-9]+/table_id: #/
@@ -142,10 +139,7 @@ insert into t1 values (NULL, 1);
 reset master;
 set insert_id=5;
 insert into t1 values (NULL, last_insert_id()), (NULL, last_insert_id());
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
---replace_regex /\/\* xid=.* \*\//\/* XID *\// /table_id: [0-9]+/table_id: #/
-show binlog events;
+source include/show_binlog_events.inc;
 select * from t1;
 drop table t1;
 
diff --git a/mysql-test/extra/rpl_tests/rpl_ndb_ddl.test b/mysql-test/extra/rpl_tests/rpl_ndb_ddl.test
deleted file mode 100644
index 26c368589baf8b2f9e3fd2c21dd0f91f792755e3..0000000000000000000000000000000000000000
--- a/mysql-test/extra/rpl_tests/rpl_ndb_ddl.test
+++ /dev/null
@@ -1,507 +0,0 @@
-######################## rpl_ddl.test ########################
-#                                                            #
-# DDL statements (sometimes with implicit COMMIT) executed   #
-# by the master and it's propagation into the slave          #
-#                                                            #
-##############################################################
-
-#
-# NOTE, PLEASE BE CAREFUL, WHEN MODIFYING THE TESTS !!
-#
-#      1. !All! objects to be dropped, renamed, altered ... must be created
-#         in AUTOCOMMIT= 1 mode before AUTOCOMMIT is set to 0 and the test
-#         sequences start.
-#
-#      2. Never use a test object, which was direct or indirect affected by a
-#         preceeding test sequence again.
-#         Except table d1.t1 where ONLY DML is allowed.
-#
-#         If one preceeding test sequence hits a (sometimes not good visible,
-#         because the sql error code of the statement might be 0) bug
-#         and these rules are ignored, a following test sequence might earn ugly
-#         effects like failing 'sync_slave_with_master', crashes of the slave or
-#         abort of the test case etc..
-#
-#      3. The assignment of the DDL command to be tested to $my_stmt can
-#         be a bit difficult. "'" must be avoided, because the test
-#         routine "include/rpl_stmt_seq.inc" performs a
-#         eval SELECT CONCAT('######## ','$my_stmt','  ########') as "";
-#
-
-###############################################################
-# Some preparations
-###############################################################
-# The sync_slave_with_master is needed to make the xids deterministic.
-sync_slave_with_master;
-connection master;
-
-SET AUTOCOMMIT = 1;
-#
-# 1. DROP all objects, which probably already exist, but must be created here
-#
---disable_warnings
-DROP DATABASE IF EXISTS mysqltest1;
-DROP DATABASE IF EXISTS mysqltest2;
-DROP DATABASE IF EXISTS mysqltest3;
---enable_warnings
-#
-# 2. CREATE all objects needed
-#    working database is mysqltest1
-#    working (transactional!) is mysqltest1.t1 
-#
-CREATE DATABASE mysqltest1;
-CREATE DATABASE mysqltest2;
-eval CREATE TABLE mysqltest1.t1 (f1 BIGINT) ENGINE=$engine_type;
-INSERT INTO mysqltest1.t1 SET f1= 0;
-eval CREATE TABLE mysqltest1.t2 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t3 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t4 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t5 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t6 (f1 BIGINT) ENGINE=$engine_type;
-CREATE INDEX my_idx6 ON mysqltest1.t6(f1);
-eval CREATE TABLE mysqltest1.t7 (f1 BIGINT) ENGINE=$engine_type;
-INSERT INTO mysqltest1.t7 SET f1= 0;
-eval CREATE TABLE mysqltest1.t8 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t9 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t10 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t11 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t12 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t13 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t14 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t15 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t16 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t17 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t18 (f1 BIGINT) ENGINE=$engine_type;
-eval CREATE TABLE mysqltest1.t19 (f1 BIGINT) ENGINE=$engine_type;
-CREATE TEMPORARY TABLE mysqltest1.t23 (f1 BIGINT);
-
-#
-# 3. master sessions: never do AUTOCOMMIT
-#    slave  sessions: never do AUTOCOMMIT
-#
-SET AUTOCOMMIT = 0;
-use mysqltest1;
-sync_slave_with_master;
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SET AUTOCOMMIT = 0;
-use mysqltest1;
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-
-# We don't want to abort the whole test if one statement sent
-# to the server gets an error, because the following test
-# sequences are nearly independend of the previous statements. 
---disable_abort_on_error
-
-###############################################################
-# Banal case: (explicit) COMMIT and ROLLBACK
-# Just for checking if the test sequence is usable
-###############################################################
-
-let $my_stmt= COMMIT;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-
-let $my_stmt= ROLLBACK;
-let $my_master_commit= false;
-let $my_slave_commit= false;
---source include/rpl_stmt_seq.inc
-
-###############################################################
-# Cases with commands very similar to COMMIT
-###############################################################
-
-let $my_stmt= SET AUTOCOMMIT=1;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SET AUTOCOMMIT=0;
-
-let $my_stmt= START TRANSACTION;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-
-let $my_stmt= BEGIN;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-
-###############################################################
-# Cases with (BASE) TABLES and (UPDATABLE) VIEWs
-###############################################################
-
-let $my_stmt= DROP TABLE mysqltest1.t2;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW TABLES LIKE 't2';
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SHOW TABLES LIKE 't2';
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-# Note: Since this test is executed with a skip-innodb slave, the
-# slave incorrectly commits the insert.  One can *not* have InnoDB on
-# master and MyISAM on slave and expect that a transactional rollback
-# after a CREATE TEMPORARY TABLE should work correctly on the slave.
-# For this to work properly the handler on the slave must be able to 
-# handle transactions (e.g. InnoDB or NDB).
-let $my_stmt= DROP TEMPORARY TABLE mysqltest1.t23;
-let $my_master_commit= false;
-let $my_slave_commit= false;
---source include/rpl_stmt_seq.inc
-SHOW TABLES LIKE 't23';
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SHOW TABLES LIKE 't23';
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-let $my_stmt= RENAME TABLE mysqltest1.t3 to mysqltest1.t20;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW TABLES LIKE 't20';
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SHOW TABLES LIKE 't20';
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-let $my_stmt= ALTER TABLE mysqltest1.t4 ADD column f2 BIGINT;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-describe mysqltest1.t4;
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-describe mysqltest1.t4;
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-let $my_stmt= CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE=;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq2.inc
-
-# Note: Since this test is executed with a skip-innodb slave, the
-# slave incorrectly commits the insert.  One can *not* have InnoDB on
-# master and MyISAM on slave and expect that a transactional rollback
-# after a CREATE TEMPORARY TABLE should work correctly on the slave.
-# For this to work properly the handler on the slave must be able to 
-# handle transactions (e.g. InnoDB or NDB).
-let $engine='';
-let $eng_type='';
-
-let $my_stmt= CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT);
-let $my_master_commit= false;
-let $my_slave_commit= false;
---source include/rpl_stmt_seq.inc
-
-let $my_stmt= TRUNCATE TABLE mysqltest1.t7;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SELECT * FROM mysqltest1.t7;
---echo -------- switch to slave --------
-sync_slave_with_master;
-SELECT * FROM mysqltest1.t7;
---echo -------- switch to master -------
-connection master;
-
-###############################################################
-# Cases with LOCK/UNLOCK
-###############################################################
-
-# MySQL insists in locking mysqltest1.t1, because rpl_stmt_seq performs an
-# INSERT into this table.
-let $my_stmt= LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-UNLOCK TABLES;
-
-# No prior locking
-let $my_stmt= UNLOCK TABLES;
-let $my_master_commit= false;
-let $my_slave_commit= false;
---source include/rpl_stmt_seq.inc
-
-# With prior read locking
-# Note that this test generate an error since the rpl_stmt_seq.inc
-# tries to insert into t1.
-LOCK TABLES mysqltest1.t1 READ;
-let $my_stmt= UNLOCK TABLES;
-let $my_master_commit= false;
-let $my_slave_commit= false;
---source include/rpl_stmt_seq.inc
-
-# With prior write locking
-LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ;
-let $my_stmt= UNLOCK TABLES;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-
-###############################################################
-# Cases with INDEXES
-###############################################################
-
-let $my_stmt= DROP INDEX my_idx6 ON mysqltest1.t6;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW INDEX FROM mysqltest1.t6;
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SHOW INDEX FROM mysqltest1.t6;
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-let $my_stmt= CREATE INDEX my_idx5 ON mysqltest1.t5(f1);
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW INDEX FROM mysqltest1.t5;
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SHOW INDEX FROM mysqltest1.t5;
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-###############################################################
-# Cases with DATABASE
-###############################################################
-
-let $my_stmt= DROP DATABASE mysqltest2;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW DATABASES LIKE "mysqltest2";
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SHOW DATABASES LIKE "mysqltest2";
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-let $my_stmt= CREATE DATABASE mysqltest3;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW DATABASES LIKE "mysqltest3";
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-SHOW DATABASES LIKE "mysqltest3";
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-
-# End of 4.1 tests
-
-###############################################################
-# Cases with stored procedures
-###############################################################
-let $my_stmt= CREATE PROCEDURE p1() READS SQL DATA SELECT "this is p1";
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
---vertical_results
---replace_column 5 # 6 #
-SHOW PROCEDURE STATUS LIKE 'p1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
---replace_column 5 # 6 #
-SHOW PROCEDURE STATUS LIKE 'p1';
-connection master;
---horizontal_results
-
-let $my_stmt= ALTER PROCEDURE p1 COMMENT "I have been altered";
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
---vertical_results
---replace_column 5 # 6 #
-SHOW PROCEDURE STATUS LIKE 'p1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
---replace_column 5 # 6 #
-SHOW PROCEDURE STATUS LIKE 'p1';
-connection master;
---horizontal_results
-
-let $my_stmt= DROP PROCEDURE p1;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
---vertical_results
-SHOW PROCEDURE STATUS LIKE 'p1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SHOW PROCEDURE STATUS LIKE 'p1';
-connection master;
---horizontal_results
-
-###############################################################
-# Cases with VIEWs
-###############################################################
-let $my_stmt= CREATE OR REPLACE VIEW v1 as select * from t1;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW CREATE VIEW v1;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SHOW CREATE VIEW v1;
-connection master;
-
-let $my_stmt= ALTER VIEW v1 AS select f1 from t1;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW CREATE VIEW v1;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SHOW CREATE VIEW v1;
-connection master;
-
-let $my_stmt= DROP VIEW IF EXISTS v1;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
---error 1146
-SHOW CREATE VIEW v1;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
---error 1146
-SHOW CREATE VIEW v1;
-connection master;
-
-###############################################################
-# Cases with TRIGGERs
-###############################################################
-let $my_stmt= CREATE TRIGGER trg1 BEFORE INSERT ON t1 FOR EACH ROW SET @a:=1;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW TRIGGERS;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SHOW TRIGGERS;
-connection master;
-
-let $my_stmt= DROP TRIGGER trg1;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SHOW TRIGGERS;
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SHOW TRIGGERS;
-connection master;
-
-###############################################################
-# Cases with USERs
-###############################################################
-let $my_stmt= CREATE USER user1@localhost;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SELECT user FROM mysql.user WHERE user = 'user1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SELECT user FROM mysql.user WHERE user = 'user1';
-connection master;
-
-let $my_stmt= RENAME USER user1@localhost TO rename1@localhost;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SELECT user FROM mysql.user WHERE user = 'rename1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SELECT user FROM mysql.user WHERE user = 'rename1';
-connection master;
-
-let $my_stmt= DROP USER rename1@localhost;
-let $my_master_commit= true;
-let $my_slave_commit= true;
---source include/rpl_stmt_seq.inc
-SELECT user FROM mysql.user WHERE user = 'rename1';
---disable_query_log
-SELECT '-------- switch to slave -------' as "";
---enable_query_log
-connection slave;
-SELECT user FROM mysql.user WHERE user = 'rename1';
-connection master;
-
-###############################################################
-# Cleanup
-###############################################################
---disable_warnings
-DROP DATABASE IF EXISTS mysqltest1;
-DROP DATABASE IF EXISTS mysqltest2;
-DROP DATABASE IF EXISTS mysqltest3;
---enable_warnings
-
--- source include/master-slave-end.inc
-
diff --git a/mysql-test/extra/rpl_tests/rpl_row_delayed_ins.test b/mysql-test/extra/rpl_tests/rpl_row_delayed_ins.test
index 0e235f8838f2332ae96e642fb4497af16a7a1a56..c4e6dbc84c2e650137ed48d57c434cc0f634afa6 100644
--- a/mysql-test/extra/rpl_tests/rpl_row_delayed_ins.test
+++ b/mysql-test/extra/rpl_tests/rpl_row_delayed_ins.test
@@ -15,9 +15,7 @@ SELECT * FROM t1 ORDER BY a;
 sync_slave_with_master;
 
 connection master;
---replace_result $VERSION VERSION
---replace_regex /table_id: [0-9]+/table_id: #/
-show binlog events;
+source include/show_binlog_events.inc;
 sync_slave_with_master;
 SELECT * FROM t1 ORDER BY a;
 connection master;
diff --git a/mysql-test/extra/rpl_tests/rpl_truncate_helper.test b/mysql-test/extra/rpl_tests/rpl_truncate_helper.test
index 7f1506c401010d05d79a1d7b68a84744122d9fcd..64a8de7c6a08e0ec554a8776d866c2aa83aab56c 100644
--- a/mysql-test/extra/rpl_tests/rpl_truncate_helper.test
+++ b/mysql-test/extra/rpl_tests/rpl_truncate_helper.test
@@ -37,6 +37,4 @@ SELECT * FROM t1;
 connection master;
 DROP TABLE t1;
 let $SERVER_VERSION=`select version()`;
---replace_result $SERVER_VERSION SERVER_VERSION
---replace_regex /\/\* xid=[0-9]+ \*\//\/* xid= *\// /table_id: [0-9]+/table_id: #/
-SHOW BINLOG EVENTS;
+source include/show_binlog_events.inc;
diff --git a/mysql-test/include/rpl_events.inc b/mysql-test/include/rpl_events.inc
index b8fac61c38376b68727d49f0630b8efae0ab7a20..04885f31997ceb4680ee1fbf55757afea4891f30 100644
--- a/mysql-test/include/rpl_events.inc
+++ b/mysql-test/include/rpl_events.inc
@@ -15,8 +15,7 @@ drop table if exists t1,t2;
 eval CREATE TABLE `t1` (
   `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
   `c` VARCHAR(50) NOT NULL,
-  `ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
-CURRENT_TIMESTAMP,
+  `ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
   PRIMARY KEY (`id`)
 ) ENGINE=$engine_type DEFAULT CHARSET=utf8;
 
@@ -35,7 +34,7 @@ SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name
 --echo "in the master"
 --enable_info
 --replace_column 3 TIMESTAMP
-SELECT * FROM t1;
+SELECT * FROM t1 WHERE c = 'from justonce' OR c = 'manually' ORDER BY id;
 --disable_info
 
 sync_slave_with_master;
@@ -43,7 +42,7 @@ sync_slave_with_master;
 --echo "in the slave"
 --enable_info
 --replace_column 3 TIMESTAMP
-SELECT * FROM t1;
+SELECT * FROM t1 WHERE c = 'from justonce' OR c = 'manually' ORDER BY id;
 --disable_info
 
 SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name = 'justonce';
@@ -99,6 +98,21 @@ sync_slave_with_master;
 --echo "in the slave"
 SELECT db, name, status, originator FROM mysql.event WHERE db = 'test';
 
+# test the DISABLE ON SLAVE for setting event SLAVESIDE_DISABLED as status
+# on CREATE EVENT
+
+CREATE EVENT test.slave_terminate ON SCHEDULE EVERY 3 SECOND 
+DO INSERT INTO t1(c) VALUES ('from slave_terminate');
+SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name = 'slave_terminate';
+
+DROP EVENT test.slave_terminate;
+
+CREATE EVENT test.slave_terminate ON SCHEDULE EVERY 3 SECOND 
+DISABLE ON SLAVE DO INSERT INTO t1(c) VALUES ('from slave_terminate');
+SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name = 'slave_terminate';
+
+DROP EVENT test.slave_terminate;
+
 --echo "in the master"
 connection master;
 DROP TABLE t1;
diff --git a/mysql-test/include/rpl_stmt_seq.inc b/mysql-test/include/rpl_stmt_seq.inc
index 3c91505d0d6a0c89987e92cfe7e3ee9eb690ca10..6c944dc4729de789c897581ffe5eac557b48180f 100644
--- a/mysql-test/include/rpl_stmt_seq.inc
+++ b/mysql-test/include/rpl_stmt_seq.inc
@@ -1,30 +1,51 @@
-# include/rpl_stmt_seq.inc
-#
-# Please be very careful when editing this routine, because the handling of 
-# the $variables is extreme sensitive. 
-#
+################### include/rpl_stmt_seq.inc ###########################
+#                                                                      #
+# Check if a given SQL statement (->$my_stmt) / AUTOCOMMIT mode /      #
+# storage engine somehow involved causes COMMIT or ROLLBACK.           #
+#                                                                      #
+#                                                                      #
+# The typical test sequence                                            #
+# -------------------------                                            #
+# 1. master connection: INSERT without commit                          #
+#    check table content of master and slave                           #
+# 2. master connection: EXECUTE the statement                          #
+#    check table content of master and slave                           #
+# 3. master connection: ROLLBACK                                       #
+#    check table content of master and slave                           #
+# 4. flush the logs                                                    #
+#                                                                      #
+# The variables                                                        #
+#    $show_binlog       -- print binlog entries                        #
+#                          0 - default + fits to the file with         #
+#                              results                                 #
+#                          1 - useful for debugging                    #
+#                          This variable is used within                #
+#                          include/rpl_stmt_seq.inc.                   #
+#    $manipulate        -- Manipulation of the binary logs             #
+#                          0 - do nothing                              #
+#                          1 - so that the output of SHOW BINLOG       #
+#                              EVENTS IN <current log> contains only   #
+#                              commands of the current test sequence   #
+#                              This is especially useful, if the       #
+#                              $show_binlog is set to 1 and many       #
+#                              subtest are executed.                   #
+#                          This variable is used within                #
+#                          include/rpl_stmt_seq.inc.                   #
+# have to be set before sourcing this script.                          #
+#                                                                      #
+# Please be very careful when editing this routine, because the        #
+# handling of the $variables is extreme sensitive.                     #
+#                                                                      #
+########################################################################
 
-###############################################################
-# Debug options : To debug this test script
-###############################################################
-let $show_binlog= 0;
-let $manipulate= 1;
-
-######## The typical test sequence
-# 1. INSERT without commit
-#    check table content of master and slave
-# 2. EXECUTE the statement
-#    check table content of master and slave
-# 3. ROLLBACK
-#    check table content of master and slave
-# 4. flush the logs
+# Last update:
+# 2007-02-12 ML Replace comments via SQL by "--echo ..."
+#
 
 let $VERSION=`select version()`;
 
---disable_query_log
-# SELECT '######## new test sequence ########' as "";
-eval SELECT CONCAT('######## ','$my_stmt','  ########') as "";
---enable_query_log
+--echo
+--echo ######## $my_stmt ########
 
 
 ###############################################################
@@ -49,11 +70,10 @@ let $_log_num_s= `select @aux`;
 ###############################################################
 # INSERT 
 ###############################################################
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-# Maybe it would be smarter to use a table with autoincrement column.
+# Maybe it would be smarter to use a table with an autoincrement column.
 let $MAX= `SELECT MAX(f1) FROM t1` ;
 eval INSERT INTO t1 SET f1= $MAX + 1;
 # results before DDL(to be tested)
@@ -66,10 +86,9 @@ eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
 }
 sync_slave_with_master;
 
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 # results before DDL(to be tested)
 SELECT MAX(f1) FROM t1;
 if ($show_binlog)
@@ -82,10 +101,9 @@ eval SHOW BINLOG EVENTS IN 'slave-bin.$_log_num_s';
 ###############################################################
 # command to be tested
 ###############################################################
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 eval $my_stmt;
 # Devaluate $my_stmt, to detect script bugs
 let $my_stmt= ERROR: YOU FORGOT TO FILL IN THE STATEMENT;
@@ -99,10 +117,9 @@ eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
 }
 sync_slave_with_master;
 
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 # results after DDL(to be tested)
 SELECT MAX(f1) FROM t1;
 if ($show_binlog)
@@ -115,10 +132,9 @@ eval SHOW BINLOG EVENTS IN 'slave-bin.$_log_num_s';
 ###############################################################
 # ROLLBACK
 ###############################################################
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 ROLLBACK;
 # results after final ROLLBACK
 SELECT MAX(f1) FROM t1;
@@ -140,10 +156,9 @@ eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
 }
 sync_slave_with_master;
 
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 # results after final ROLLBACK
 SELECT MAX(f1) FROM t1;
 --disable_query_log
@@ -172,19 +187,17 @@ if ($manipulate)
 # - flush the master and the slave log
 #   ---> both start to write into new logs with incremented number
 # - increment $_log_num_n
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
 flush logs;
 # sleep 1;
 # eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
 sync_slave_with_master;
 
+--echo
+--echo -------- switch to slave --------
 connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
 # the final content of the binary log
 flush logs;
 # The next sleep is urgent needed.
@@ -195,7 +208,6 @@ flush logs;
 inc $_log_num_n;
 }
 
+--echo
+--echo -------- switch to master -------
 connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
diff --git a/mysql-test/include/rpl_stmt_seq2.inc b/mysql-test/include/rpl_stmt_seq2.inc
deleted file mode 100644
index 7671a6a857c6400b17cd21e4b910338951d707a1..0000000000000000000000000000000000000000
--- a/mysql-test/include/rpl_stmt_seq2.inc
+++ /dev/null
@@ -1,201 +0,0 @@
-# include/rpl_stmt_seq.inc
-#
-# Please be very careful when editing this routine, because the handling of 
-# the $variables is extreme sensitive. 
-#
-
-###############################################################
-# Debug options : To debug this test script
-###############################################################
-let $show_binlog= 0;
-let $manipulate= 1;
-
-######## The typical test sequence
-# 1. INSERT without commit
-#    check table content of master and slave
-# 2. EXECUTE the statement
-#    check table content of master and slave
-# 3. ROLLBACK
-#    check table content of master and slave
-# 4. flush the logs
-
-let $VERSION=`select version()`;
-
---disable_query_log
-# SELECT '######## new test sequence ########' as "";
-eval SELECT CONCAT('######## ','$my_stmt',' $engine_type','  ########') as "";
---enable_query_log
-
-
-###############################################################
-# Predict the number of the current log
-###############################################################
-# Disable the logging of the log number computation. 
---disable_query_log
-# $_log_num_n should contain the number of the current binlog in numeric style.
-# If this routine is called for the first time, $_log_num will not initialized
-# and contain the value '' instead of '1'. So we will correct it here.
-#
-eval set @aux= IF('$_log_num_n' = '', '1', '$_log_num_n');
-let $_log_num_n= `SELECT @aux`;
-eval set @aux= LPAD('$_log_num_n',6,'0');
-#              SELECT @aux AS "@aux is";
-#
-# $_log_num_s should contain the number of the current binlog in string style.
-let $_log_num_s= `select @aux`;
-# eval SELECT '$log_num' ;
---enable_query_log
-
-###############################################################
-# INSERT 
-###############################################################
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-# Maybe it would be smarter to use a table with autoincrement column.
-let $MAX= `SELECT MAX(f1) FROM t1` ;
-eval INSERT INTO t1 SET f1= $MAX + 1;
-# results before DDL(to be tested)
-SELECT MAX(f1) FROM t1;
-if ($show_binlog)
-{
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
-eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
-}
-sync_slave_with_master;
-
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-# results before DDL(to be tested)
-SELECT MAX(f1) FROM t1;
-if ($show_binlog)
-{
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
-eval SHOW BINLOG EVENTS IN 'slave-bin.$_log_num_s';
-}
-
-###############################################################
-# command to be tested
-###############################################################
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-eval $my_stmt $engine_type;
-# Devaluate $my_stmt, to detect script bugs
-let $my_stmt= ERROR: YOU FORGOT TO FILL IN THE STATEMENT;
-# results after DDL(to be tested)
-SELECT MAX(f1) FROM t1;
-if ($show_binlog)
-{
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
-eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
-}
-sync_slave_with_master;
-
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-# results after DDL(to be tested)
-SELECT MAX(f1) FROM t1;
-if ($show_binlog)
-{
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
-eval SHOW BINLOG EVENTS IN 'slave-bin.$_log_num_s';
-}
-
-###############################################################
-# ROLLBACK
-###############################################################
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-ROLLBACK;
-# results after final ROLLBACK
-SELECT MAX(f1) FROM t1;
-# Try to detect if the DDL command caused that the INSERT is committed
-# $MAX holds the highest/last value just before the insert of MAX + 1
---disable_query_log
-eval SELECT CONCAT(CONCAT('TEST-INFO: MASTER: The INSERT is ',
-               IF(MAX(f1) = $MAX + 1, 'committed', 'not committed')),
-               IF((MAX(f1) = $MAX + 1) XOR NOT $my_master_commit,
-                ' (Succeeded)',
-                ' (Failed)')) AS "" 
-               FROM mysqltest1.t1;
---enable_query_log
-if ($show_binlog)
-{
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
-eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
-}
-sync_slave_with_master;
-
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-# results after final ROLLBACK
-SELECT MAX(f1) FROM t1;
---disable_query_log
-eval SELECT CONCAT(CONCAT('TEST-INFO: SLAVE:  The INSERT is ',
-               IF(MAX(f1) = $MAX + 1, 'committed', 'not committed')),
-               IF((MAX(f1) = $MAX + 1) XOR NOT $my_slave_commit,
-                ' (Succeeded)',
-                ' (Failed)')) AS "" 
-               FROM mysqltest1.t1;
---enable_query_log
-if ($show_binlog)
-{
---replace_result $VERSION VERSION
---replace_column 2 # 5 #
-eval SHOW BINLOG EVENTS IN 'slave-bin.$_log_num_s';
-}
-
-###############################################################
-# Manipulate binlog
-###############################################################
-if ($manipulate)
-{
-#### Manipulate the binary logs,
-# so that the output of SHOW BINLOG EVENTS IN <current log>
-# contains only commands of the current test sequence.
-# - flush the master and the slave log
-#   ---> both start to write into new logs with incremented number
-# - increment $_log_num_n
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
-flush logs;
-# sleep 1;
-# eval SHOW BINLOG EVENTS IN 'master-bin.$_log_num_s';
-sync_slave_with_master;
-
-connection slave;
---disable_query_log
-SELECT '-------- switch to slave --------' as "";
---enable_query_log
-# the final content of the binary log
-flush logs;
-# The next sleep is urgent needed.
-# Without this sleep the slaves crashes often, when the SHOW BINLOG
-# is executed.   :-(
-# sleep 1;
-# eval SHOW BINLOG EVENTS IN 'slave-bin.$_log_num_s';
-inc $_log_num_n;
-}
-
-connection master;
---disable_query_log
-SELECT '-------- switch to master -------' as "";
---enable_query_log
diff --git a/mysql-test/include/rpl_udf.inc b/mysql-test/include/rpl_udf.inc
index 424bacc42169151061628eb7720f2f80a3e81ab5..d9e19cda484a8a94ddd36f450f8bd977dc920bb8 100644
--- a/mysql-test/include/rpl_udf.inc
+++ b/mysql-test/include/rpl_udf.inc
@@ -45,6 +45,7 @@ sync_with_master;
 # Check to see that UDF CREATE statements were replicated
 --echo "Running on the slave"
 --enable_info
+--replace_column 3 UDF_LIB
 SELECT * FROM mysql.func;
 --disable_info
 
diff --git a/mysql-test/include/show_binlog_events.inc b/mysql-test/include/show_binlog_events.inc
index 0aad243562b3c04ffa20588ace77c75a541c8e35..7377b4a0fed225f110d0bcb8920e5734d2ede28c 100644
--- a/mysql-test/include/show_binlog_events.inc
+++ b/mysql-test/include/show_binlog_events.inc
@@ -1,5 +1,5 @@
 --let $binlog_start=106
 --replace_result $binlog_start <binlog_start>
 --replace_column 2 # 4 # 5 #
---replace_regex /table_id: [0-9]+/table_id: #/
+--replace_regex /\/\* xid=.* \*\//\/* XID *\// /table_id: [0-9]+/table_id: #/
 --eval show binlog events from $binlog_start
diff --git a/mysql-test/r/binlog_row_binlog.result b/mysql-test/r/binlog_row_binlog.result
index 3db2fde1f1e3282ced48a8df66f347f107c983d6..6fcaad010d29777a376f1ec0163c0fbd813cdba2 100644
--- a/mysql-test/r/binlog_row_binlog.result
+++ b/mysql-test/r/binlog_row_binlog.result
@@ -8,18 +8,18 @@ commit;
 begin;
 insert t2 values (5);
 commit;
-source include/show_binlog_events.inc;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int) engine=innodb
-master-bin.000001	#	Query	1	#	use `test`; create table t2 (a int) engine=innodb
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int) engine=innodb
+master-bin.000001	#	Query	#	#	use `test`; create table t2 (a int) engine=innodb
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 drop table t1,t2;
 reset master;
 create table t1 (n int) engine=innodb;
@@ -254,58 +254,58 @@ INSERT INTO user SET host='localhost', user='@#@', password=password('Just a tes
 UPDATE user SET password=password('Another password') WHERE host='localhost' AND user='@#@';
 DELETE FROM user WHERE host='localhost' AND user='@#@';
 use test;
-source include/show_binlog_events.inc;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (id tinyint auto_increment primary key)
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; drop table t1
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int)
-master-bin.000001	#	Query	1	#	use `test`; CREATE TABLE IF NOT EXISTS `t2` (
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (id tinyint auto_increment primary key)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; drop table t1
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int)
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE IF NOT EXISTS `t2` (
   `a` int(11) DEFAULT NULL
 )
-master-bin.000001	#	Query	1	#	use `test`; CREATE TABLE IF NOT EXISTS `t3` (
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE IF NOT EXISTS `t3` (
   `a` int(11) DEFAULT NULL
 )
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.user)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.user)
-master-bin.000001	#	Update_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.user)
-master-bin.000001	#	Delete_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.user)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.user)
+master-bin.000001	#	Update_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.user)
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
 drop table t1,t2,t3,tt1;
 create table t1 (a int not null auto_increment, primary key (a)) engine=myisam;
 set @@session.auto_increment_increment=1, @@session.auto_increment_offset=1;
 insert delayed into t1 values (207);
 insert delayed into t1 values (null);
 insert delayed into t1 values (300);
-source include/show_binlog_events.inc;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (id tinyint auto_increment primary key)
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; drop table t1
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int)
-master-bin.000001	#	Query	1	#	use `test`; CREATE TABLE IF NOT EXISTS `t2` (
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (id tinyint auto_increment primary key)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; drop table t1
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int)
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE IF NOT EXISTS `t2` (
   `a` int(11) DEFAULT NULL
 )
-master-bin.000001	#	Query	1	#	use `test`; CREATE TABLE IF NOT EXISTS `t3` (
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE IF NOT EXISTS `t3` (
   `a` int(11) DEFAULT NULL
 )
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.user)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.user)
-master-bin.000001	#	Update_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.user)
-master-bin.000001	#	Delete_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE `t1`,`t2`,`t3` /* generated by server */
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int not null auto_increment, primary key (a)) engine=myisam
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.user)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.user)
+master-bin.000001	#	Update_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.user)
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE `t1`,`t2`,`t3` /* generated by server */
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int not null auto_increment, primary key (a)) engine=myisam
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 insert delayed into t1 values (null),(null),(null),(null);
 insert delayed into t1 values (null),(null),(400),(null);
 11 == 11
@@ -328,12 +328,12 @@ drop table if exists t3;
 create table t3 (a int(11) NOT NULL AUTO_INCREMENT, b text, PRIMARY KEY (a) ) engine=innodb;
 show master status;
 File	Position	Binlog_Do_DB	Binlog_Ignore_DB
-master-bin.000001	342		
+master-bin.000001	346		
 insert into t3(b) values ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
 insert into t3(b) values ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
 insert into t3(b) values ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
 insert into t3(b) values ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
 show master status /* must show new binlog index after rotating */;
 File	Position	Binlog_Do_DB	Binlog_Ignore_DB
-master-bin.000002	102		
+master-bin.000002	106		
 drop table t3;
diff --git a/mysql-test/r/binlog_row_blackhole.result b/mysql-test/r/binlog_row_blackhole.result
index f370232e2c383e0ed74860faff07cd8f983d13f5..8e90ac4f30b0792a4894e5db9ade97370d766c38 100644
--- a/mysql-test/r/binlog_row_blackhole.result
+++ b/mysql-test/r/binlog_row_blackhole.result
@@ -104,23 +104,22 @@ select * from t2;
 a
 select * from t3;
 a
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; drop table t1,t2
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int) engine=blackhole
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; create table t2 (a varchar(200)) engine=blackhole
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; alter table t1 add b int
-master-bin.000001	#	Query	1	#	use `test`; alter table t1 drop b
-master-bin.000001	#	Query	1	#	use `test`; create table t3 like t1
+master-bin.000001	#	Query	#	#	use `test`; drop table t1,t2
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int) engine=blackhole
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; create table t2 (a varchar(200)) engine=blackhole
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; alter table t1 add b int
+master-bin.000001	#	Query	#	#	use `test`; alter table t1 drop b
+master-bin.000001	#	Query	#	#	use `test`; create table t3 like t1
 drop table t1,t2,t3;
 CREATE TABLE t1(a INT, b INT) ENGINE=BLACKHOLE;
 DELETE FROM t1 WHERE a=10;
@@ -143,12 +142,11 @@ start transaction;
 insert into t1 values(2);
 rollback;
 set autocommit=1;
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int) engine=blackhole
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; COMMIT
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int) engine=blackhole
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; COMMIT
 drop table if exists t1;
diff --git a/mysql-test/r/binlog_row_ctype_ucs.result b/mysql-test/r/binlog_row_ctype_ucs.result
index d1ba431e152971c8cb1a6eed2664cec2390bed70..4f4e7bcedd785f1b0dda5dbb731d168a2084024c 100644
--- a/mysql-test/r/binlog_row_ctype_ucs.result
+++ b/mysql-test/r/binlog_row_ctype_ucs.result
@@ -3,10 +3,10 @@ create table t2 (c char(30)) charset=ucs2;
 set @v=convert('abc' using ucs2);
 reset master;
 insert into t2 values (@v);
-show binlog events from 106;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	106	Table_map	1	145	table_id: # (test.t2)
-master-bin.000001	145	Write_rows	1	235	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 flush logs;
 /*!40019 SET @@session.max_insert_delayed_threads=0*/;
 /*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
diff --git a/mysql-test/r/binlog_row_drop_tmp_tbl.result b/mysql-test/r/binlog_row_drop_tmp_tbl.result
index 2b09fe069e380c056e625c60ebd538159e113106..503076d66d994c4193a0b5da80eb4e02a0b84273 100644
--- a/mysql-test/r/binlog_row_drop_tmp_tbl.result
+++ b/mysql-test/r/binlog_row_drop_tmp_tbl.result
@@ -11,8 +11,7 @@ get_lock("a",10)
 select get_lock("a",10);
 get_lock("a",10)
 1
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	create database `drop-temp+table-test`
+master-bin.000001	#	Query	#	#	create database `drop-temp+table-test`
 drop database `drop-temp+table-test`;
diff --git a/mysql-test/r/binlog_row_insert_select.result b/mysql-test/r/binlog_row_insert_select.result
index 407adc874fb85ef27b8ddfd6042fda628f43036c..cd6ddafc47bdf7ca1d12321dc5208b1e3128d20d 100644
--- a/mysql-test/r/binlog_row_insert_select.result
+++ b/mysql-test/r/binlog_row_insert_select.result
@@ -6,7 +6,7 @@ insert into t2 values(1),(2);
 reset master;
 insert into t1 select * from t2;
 ERROR 23000: Duplicate entry '2' for key 'a'
-source include/show_binlog_events.inc;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
 master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
@@ -20,6 +20,6 @@ insert into t1 values(1),(1);
 reset master;
 create table t2(unique(a)) select a from t1;
 ERROR 23000: Duplicate entry '1' for key 'a'
-source include/show_binlog_events.inc;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 drop table t1;
diff --git a/mysql-test/r/binlog_row_mix_innodb_myisam.result b/mysql-test/r/binlog_row_mix_innodb_myisam.result
index 3c2f9a63f383c9530537182ebed2b7b0a11bb62e..6ac942176c75d4655692eed91e6da3380d00dabc 100644
--- a/mysql-test/r/binlog_row_mix_innodb_myisam.result
+++ b/mysql-test/r/binlog_row_mix_innodb_myisam.result
@@ -8,12 +8,12 @@ insert into t2 select * from t1;
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -25,12 +25,12 @@ Warnings:
 Warning	1196	Some non-transactional changed tables couldn't be rolled back
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; ROLLBACK
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; ROLLBACK
 delete from t1;
 delete from t2;
 reset master;
@@ -45,16 +45,16 @@ Warning	1196	Some non-transactional changed tables couldn't be rolled back
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; savepoint my_savepoint
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; rollback to savepoint my_savepoint
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; savepoint my_savepoint
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; rollback to savepoint my_savepoint
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -74,18 +74,18 @@ a
 7
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; savepoint my_savepoint
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; rollback to savepoint my_savepoint
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; savepoint my_savepoint
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; rollback to savepoint my_savepoint
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -100,12 +100,12 @@ get_lock("a",10)
 1
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; ROLLBACK
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; ROLLBACK
 delete from t1;
 delete from t2;
 reset master;
@@ -113,11 +113,11 @@ insert into t1 values(9);
 insert into t2 select * from t1;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 delete from t1;
 delete from t2;
 reset master;
@@ -126,24 +126,24 @@ begin;
 insert into t2 select * from t1;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 insert into t1 values(11);
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 alter table t2 engine=INNODB;
 delete from t1;
 delete from t2;
@@ -154,12 +154,12 @@ insert into t2 select * from t1;
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -181,10 +181,10 @@ rollback to savepoint my_savepoint;
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -202,12 +202,12 @@ a
 18
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 alter table t2 engine=MyISAM;
@@ -254,28 +254,28 @@ get_lock("lock1",60)
 1
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Delete_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; alter table t2 engine=MyISAM
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; drop table t1,t2
-master-bin.000001	#	Query	1	#	use `test`; create table t0 (n int)
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t0)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t0)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; create table t2 (n int) engine=innodb
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; alter table t2 engine=MyISAM
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; drop table t1,t2
+master-bin.000001	#	Query	#	#	use `test`; create table t0 (n int)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t0)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t0)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; create table t2 (n int) engine=innodb
 do release_lock("lock1");
 drop table t0,t2;
 set autocommit=0;
@@ -357,37 +357,37 @@ a	b
 DROP TABLE t1,t2;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE if exists t2
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE IF EXISTS t2
-master-bin.000001	#	Query	1	#	use `test`; CREATE TABLE t2 (a int, b int, primary key (a)) engine=innodb
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; TRUNCATE table t2
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t2)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE t2
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; TRUNCATE table t2
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE `t1` /* generated by server */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE if exists t2
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE IF EXISTS t2
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t2 (a int, b int, primary key (a)) engine=innodb
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE table t2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t2
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE table t2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE `t1` /* generated by server */
 reset master;
 create table t1 (a int) engine=innodb;
 create table t2 (a int) engine=myisam;
diff --git a/mysql-test/r/binlog_stm_binlog.result b/mysql-test/r/binlog_stm_binlog.result
index b26cfeded6b2cdc9955ec648d0442da12d515086..66fe3e4027052950ecf93967ede4b62b614f06e2 100644
--- a/mysql-test/r/binlog_stm_binlog.result
+++ b/mysql-test/r/binlog_stm_binlog.result
@@ -26,10 +26,10 @@ master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int) engine=innodb
 master-bin.000001	#	Query	#	#	use `test`; create table t2 (a int) engine=innodb
 master-bin.000001	#	Query	#	#	use `test`; BEGIN
 master-bin.000001	#	Query	#	#	use `test`; insert t1 values (5)
-master-bin.000001	#	Xid	#	#	COMMIT /* xid=17 */
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 master-bin.000001	#	Query	#	#	use `test`; BEGIN
 master-bin.000001	#	Query	#	#	use `test`; insert t2 values (5)
-master-bin.000001	#	Xid	#	#	COMMIT /* xid=20 */
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 drop table t1,t2;
 reset master;
 create table t1 (n int) engine=innodb;
diff --git a/mysql-test/r/binlog_stm_blackhole.result b/mysql-test/r/binlog_stm_blackhole.result
index d382c94fba99459baf7073df0ffbb98197f99648..bf2fdfa616b2ab86622271a9705e178afa3432d5 100644
--- a/mysql-test/r/binlog_stm_blackhole.result
+++ b/mysql-test/r/binlog_stm_blackhole.result
@@ -104,24 +104,23 @@ select * from t2;
 a
 select * from t3;
 a
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; drop table t1,t2
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int) engine=blackhole
-master-bin.000001	#	Query	1	#	use `test`; delete from t1 where a=10
-master-bin.000001	#	Query	1	#	use `test`; update t1 set a=11 where a=15
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(1)
-master-bin.000001	#	Query	1	#	use `test`; insert ignore into t1 values(1)
-master-bin.000001	#	Query	1	#	use `test`; replace into t1 values(100)
-master-bin.000001	#	Query	1	#	use `test`; create table t2 (a varchar(200)) engine=blackhole
-master-bin.000001	#	Begin_load_query	1	#	;file_id=1;block_len=581
-master-bin.000001	#	Execute_load_query	1	#	use `test`; load data infile '../std_data_ln/words.dat' into table t2 ;file_id=1
-master-bin.000001	#	Query	1	#	use `test`; alter table t1 add b int
-master-bin.000001	#	Query	1	#	use `test`; alter table t1 drop b
-master-bin.000001	#	Query	1	#	use `test`; create table t3 like t1
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 select * from t3
-master-bin.000001	#	Query	1	#	use `test`; replace into t1 select * from t3
+master-bin.000001	#	Query	#	#	use `test`; drop table t1,t2
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int) engine=blackhole
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where a=10
+master-bin.000001	#	Query	#	#	use `test`; update t1 set a=11 where a=15
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(1)
+master-bin.000001	#	Query	#	#	use `test`; insert ignore into t1 values(1)
+master-bin.000001	#	Query	#	#	use `test`; replace into t1 values(100)
+master-bin.000001	#	Query	#	#	use `test`; create table t2 (a varchar(200)) engine=blackhole
+master-bin.000001	#	Begin_load_query	#	#	;file_id=1;block_len=581
+master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../std_data_ln/words.dat' into table t2 ;file_id=1
+master-bin.000001	#	Query	#	#	use `test`; alter table t1 add b int
+master-bin.000001	#	Query	#	#	use `test`; alter table t1 drop b
+master-bin.000001	#	Query	#	#	use `test`; create table t3 like t1
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 select * from t3
+master-bin.000001	#	Query	#	#	use `test`; replace into t1 select * from t3
 drop table t1,t2,t3;
 CREATE TABLE t1(a INT, b INT) ENGINE=BLACKHOLE;
 DELETE FROM t1 WHERE a=10;
@@ -144,11 +143,10 @@ start transaction;
 insert into t1 values(2);
 rollback;
 set autocommit=1;
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (a int) engine=blackhole
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(1)
-master-bin.000001	#	Query	1	#	use `test`; COMMIT
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (a int) engine=blackhole
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(1)
+master-bin.000001	#	Query	#	#	use `test`; COMMIT
 drop table if exists t1;
diff --git a/mysql-test/r/binlog_stm_drop_tmp_tbl.result b/mysql-test/r/binlog_stm_drop_tmp_tbl.result
index 96481341bd60306492da291903295c3bb08bef40..dc4349dea59982424d57eb9d0ba74ab635e75165 100644
--- a/mysql-test/r/binlog_stm_drop_tmp_tbl.result
+++ b/mysql-test/r/binlog_stm_drop_tmp_tbl.result
@@ -11,12 +11,11 @@ get_lock("a",10)
 select get_lock("a",10);
 get_lock("a",10)
 1
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	create database `drop-temp+table-test`
-master-bin.000001	#	Query	1	#	use `drop-temp+table-test`; create temporary table shortn1 (a int)
-master-bin.000001	#	Query	1	#	use `drop-temp+table-test`; create temporary table `table:name` (a int)
-master-bin.000001	#	Query	1	#	use `drop-temp+table-test`; create temporary table shortn2 (a int)
-master-bin.000001	#	Query	1	#	use `drop-temp+table-test`; DROP /*!40005 TEMPORARY */ TABLE IF EXISTS `drop-temp+table-test`.`shortn2`,`drop-temp+table-test`.`table:name`,`drop-temp+table-test`.`shortn1`
+master-bin.000001	#	Query	#	#	create database `drop-temp+table-test`
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; create temporary table shortn1 (a int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; create temporary table `table:name` (a int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; create temporary table shortn2 (a int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP /*!40005 TEMPORARY */ TABLE IF EXISTS `drop-temp+table-test`.`shortn2`,`drop-temp+table-test`.`table:name`,`drop-temp+table-test`.`shortn1`
 drop database `drop-temp+table-test`;
diff --git a/mysql-test/r/binlog_stm_insert_select.result b/mysql-test/r/binlog_stm_insert_select.result
index 41ff0c1c728f4b073cf460c402fdb81da3acbbeb..a93a8edf4aa3f7f51d45236877f779479f64cdc8 100644
--- a/mysql-test/r/binlog_stm_insert_select.result
+++ b/mysql-test/r/binlog_stm_insert_select.result
@@ -6,10 +6,9 @@ insert into t2 values(1),(2);
 reset master;
 insert into t1 select * from t2;
 ERROR 23000: Duplicate entry '2' for key 'a'
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	200	use `test`; insert into t1 select * from t2
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 select * from t2
 select * from t1;
 a
 1
@@ -20,7 +19,6 @@ insert into t1 values(1),(1);
 reset master;
 create table t2(unique(a)) select a from t1;
 ERROR 23000: Duplicate entry '1' for key 'a'
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: VERSION, Binlog ver: 4
 drop table t1;
diff --git a/mysql-test/r/binlog_stm_mix_innodb_myisam.result b/mysql-test/r/binlog_stm_mix_innodb_myisam.result
index bf8258faec80cb844727e1673243f885a3bcd31f..c74fb17d600988f8a97a5dd82a9a98a72d69e1f2 100644
--- a/mysql-test/r/binlog_stm_mix_innodb_myisam.result
+++ b/mysql-test/r/binlog_stm_mix_innodb_myisam.result
@@ -8,10 +8,10 @@ insert into t2 select * from t1;
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(1)
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(1)
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -23,10 +23,10 @@ Warnings:
 Warning	1196	Some non-transactional changed tables couldn't be rolled back
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(2)
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
-master-bin.000001	#	Query	1	#	use `test`; ROLLBACK
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(2)
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; ROLLBACK
 delete from t1;
 delete from t2;
 reset master;
@@ -41,13 +41,13 @@ Warning	1196	Some non-transactional changed tables couldn't be rolled back
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(3)
-master-bin.000001	#	Query	1	#	use `test`; savepoint my_savepoint
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(4)
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
-master-bin.000001	#	Query	1	#	use `test`; rollback to savepoint my_savepoint
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(3)
+master-bin.000001	#	Query	#	#	use `test`; savepoint my_savepoint
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(4)
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; rollback to savepoint my_savepoint
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -67,14 +67,14 @@ a
 7
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(5)
-master-bin.000001	#	Query	1	#	use `test`; savepoint my_savepoint
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(6)
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
-master-bin.000001	#	Query	1	#	use `test`; rollback to savepoint my_savepoint
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(7)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(5)
+master-bin.000001	#	Query	#	#	use `test`; savepoint my_savepoint
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(6)
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; rollback to savepoint my_savepoint
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(7)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -89,10 +89,10 @@ get_lock("a",10)
 1
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(8)
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
-master-bin.000001	#	Query	1	#	use `test`; ROLLBACK
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(8)
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; ROLLBACK
 delete from t1;
 delete from t2;
 reset master;
@@ -100,9 +100,9 @@ insert into t1 values(9);
 insert into t2 select * from t1;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(9)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(9)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
 delete from t1;
 delete from t2;
 reset master;
@@ -111,19 +111,19 @@ begin;
 insert into t2 select * from t1;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(10)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(10)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
 insert into t1 values(11);
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(10)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(11)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(10)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(11)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 alter table t2 engine=INNODB;
 delete from t1;
 delete from t2;
@@ -134,10 +134,10 @@ insert into t2 select * from t1;
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(12)
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 select * from t1
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(12)
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 select * from t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -159,9 +159,9 @@ rollback to savepoint my_savepoint;
 commit;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(14)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(14)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 reset master;
@@ -177,12 +177,12 @@ select a from t1 order by a;
 a
 16
 18
-show binlog events from <binlog_start>s;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(16)
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(18)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(16)
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(18)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
 delete from t1;
 delete from t2;
 alter table t2 engine=MyISAM;
@@ -229,29 +229,29 @@ get_lock("lock1",60)
 1
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(16)
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values(18)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; delete from t1
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; delete from t2
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; alter table t2 engine=MyISAM
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values (1)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; insert into t2 values (20)
-master-bin.000001	#	Query	1	#	use `test`; drop table t1,t2
-master-bin.000001	#	Query	1	#	use `test`; create temporary table ti (a int) engine=innodb
-master-bin.000001	#	Query	1	#	use `test`; insert into ti values(1)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; create temporary table t1 (a int) engine=myisam
-master-bin.000001	#	Query	1	#	use `test`; insert t1 values (1)
-master-bin.000001	#	Query	1	#	use `test`; create table t0 (n int)
-master-bin.000001	#	Query	1	#	use `test`; insert t0 select * from t1
-master-bin.000001	#	Query	1	#	use `test`; insert into t0 select GET_LOCK("lock1",null)
-master-bin.000001	#	Query	1	#	use `test`; create table t2 (n int) engine=innodb
-master-bin.000001	#	Query	1	#	use `test`; DROP /*!40005 TEMPORARY */ TABLE IF EXISTS `test`.`t1`,`test`.`ti`
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(16)
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values(18)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; delete from t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; delete from t2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; alter table t2 engine=MyISAM
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values (1)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; insert into t2 values (20)
+master-bin.000001	#	Query	#	#	use `test`; drop table t1,t2
+master-bin.000001	#	Query	#	#	use `test`; create temporary table ti (a int) engine=innodb
+master-bin.000001	#	Query	#	#	use `test`; insert into ti values(1)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; create temporary table t1 (a int) engine=myisam
+master-bin.000001	#	Query	#	#	use `test`; insert t1 values (1)
+master-bin.000001	#	Query	#	#	use `test`; create table t0 (n int)
+master-bin.000001	#	Query	#	#	use `test`; insert t0 select * from t1
+master-bin.000001	#	Query	#	#	use `test`; insert into t0 select GET_LOCK("lock1",null)
+master-bin.000001	#	Query	#	#	use `test`; create table t2 (n int) engine=innodb
+master-bin.000001	#	Query	#	#	use `test`; DROP /*!40005 TEMPORARY */ TABLE IF EXISTS `test`.`t1`,`test`.`ti`
 do release_lock("lock1");
 drop table t0,t2;
 set autocommit=0;
@@ -333,28 +333,28 @@ a	b
 DROP TABLE t1,t2;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 values (1,1),(1,2)
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE if exists t2
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 values (3,3)
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE IF EXISTS t2
-master-bin.000001	#	Query	1	#	use `test`; CREATE TABLE t2 (a int, b int, primary key (a)) engine=innodb
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 VALUES (4,4)
-master-bin.000001	#	Query	1	#	use `test`; TRUNCATE table t2
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 VALUES (5,5)
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE t2
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 values (6,6)
-master-bin.000001	#	Query	1	#	use `test`; CREATE TEMPORARY TABLE t2 (a int, b int, primary key (a)) engine=innodb
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 values (7,7)
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 values (8,8)
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 values (9,9)
-master-bin.000001	#	Query	1	#	use `test`; TRUNCATE table t2
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t1 values (10,10)
-master-bin.000001	#	Query	1	#	use `test`; BEGIN
-master-bin.000001	#	Query	1	#	use `test`; INSERT INTO t2 values (100,100)
-master-bin.000001	#	Xid	1	#	COMMIT /* xid= */
-master-bin.000001	#	Query	1	#	use `test`; DROP TABLE t1,t2
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 values (1,1),(1,2)
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE if exists t2
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 values (3,3)
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE IF EXISTS t2
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t2 (a int, b int, primary key (a)) engine=innodb
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (4,4)
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE table t2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (5,5)
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t2
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 values (6,6)
+master-bin.000001	#	Query	#	#	use `test`; CREATE TEMPORARY TABLE t2 (a int, b int, primary key (a)) engine=innodb
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 values (7,7)
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 values (8,8)
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 values (9,9)
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE table t2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 values (10,10)
+master-bin.000001	#	Query	#	#	use `test`; BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t2 values (100,100)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1,t2
 reset master;
 create table t1 (a int) engine=innodb;
 create table t2 (a int) engine=myisam;
diff --git a/mysql-test/r/ctype_cp932_binlog_row.result b/mysql-test/r/ctype_cp932_binlog_row.result
index 482e7b108f91749c26ddb3be1e067daea9124e92..39d7727b58ad411d14bf1e3dac8d6c2953cf9c29 100644
--- a/mysql-test/r/ctype_cp932_binlog_row.result
+++ b/mysql-test/r/ctype_cp932_binlog_row.result
@@ -8,9 +8,9 @@ SET @var1= x'8300';
 EXECUTE stmt1 USING @var1;
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	use `test`; CREATE TABLE t1(f1 blob)
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1(f1 blob)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 SELECT HEX(f1) FROM t1;
 HEX(f1)
 8300
diff --git a/mysql-test/r/ctype_ucs.result b/mysql-test/r/ctype_ucs.result
index a65b19695ec0d29e8504d272259bdd64fdc4eb81..fcfe5d6345b8c2662a570600670e0321f2e2f1bd 100644
--- a/mysql-test/r/ctype_ucs.result
+++ b/mysql-test/r/ctype_ucs.result
@@ -839,6 +839,24 @@ lily
 river
 drop table t1;
 deallocate prepare stmt;
+set names latin1;
+set character_set_connection=ucs2;
+select soundex(''),soundex('he'),soundex('hello all folks'),soundex('#3556 in bugdb');
+soundex('')	soundex('he')	soundex('hello all folks')	soundex('#3556 in bugdb')
+	H000	H4142	I51231
+select hex(soundex('')),hex(soundex('he')),hex(soundex('hello all folks')),hex(soundex('#3556 in bugdb'));
+hex(soundex(''))	hex(soundex('he'))	hex(soundex('hello all folks'))	hex(soundex('#3556 in bugdb'))
+	0048003000300030	00480034003100340032	004900350031003200330031
+select 'mood' sounds like 'mud';
+'mood' sounds like 'mud'
+1
+select hex(soundex(_ucs2 0x041004110412));
+hex(soundex(_ucs2 0x041004110412))
+0410003000300030
+select hex(soundex(_ucs2 0x00BF00C0));
+hex(soundex(_ucs2 0x00BF00C0))
+00C0003000300030
+set names latin1;
 create table t1(a blob, b text charset utf8, c text charset ucs2);
 select data_type, character_octet_length, character_maximum_length
 from information_schema.columns where table_name='t1';
diff --git a/mysql-test/r/ctype_utf8.result b/mysql-test/r/ctype_utf8.result
index 37ef5e2756fdbe90feedbe5c242fb40a5b4e4623..380cf2f227db59c614211b5d20a6d94c18ddd7e9 100644
--- a/mysql-test/r/ctype_utf8.result
+++ b/mysql-test/r/ctype_utf8.result
@@ -854,6 +854,18 @@ select * from t1 where soundex(a) = soundex('test');
 id	a
 1	Test
 drop table t1;
+select soundex(_utf8 0xE99885E8A788E99A8FE697B6E69BB4E696B0E79A84E696B0E997BB);
+soundex(_utf8 0xE99885E8A788E99A8FE697B6E69BB4E696B0E79A84E696B0E997BB)
+阅000
+select hex(soundex(_utf8 0xE99885E8A788E99A8FE697B6E69BB4E696B0E79A84E696B0E997BB));
+hex(soundex(_utf8 0xE99885E8A788E99A8FE697B6E69BB4E696B0E79A84E696B0E997BB))
+E99885303030
+select soundex(_utf8 0xD091D092D093);
+soundex(_utf8 0xD091D092D093)
+Б000
+select hex(soundex(_utf8 0xD091D092D093));
+hex(soundex(_utf8 0xD091D092D093))
+D091303030
 SET collation_connection='utf8_general_ci';
 create table t1 select repeat('a',4000) a;
 delete from t1;
diff --git a/mysql-test/r/delete.result b/mysql-test/r/delete.result
index ba4e93863125eaaa43f3bc58978a9e35b0a3d3c9..4bdf1c770d34ae219902df77bca2d5a9ab1f5a2d 100644
--- a/mysql-test/r/delete.result
+++ b/mysql-test/r/delete.result
@@ -214,3 +214,12 @@ select count(*) from t1;
 count(*)
 0
 drop table t1;
+CREATE TABLE t1 (a INT);
+INSERT INTO t1 VALUES (1);
+DELETE FROM t1 ORDER BY x;
+ERROR 42S22: Unknown column 'x' in 'order clause'
+DELETE FROM t1 ORDER BY t2.x;
+ERROR 42S22: Unknown column 't2.x' in 'order clause'
+DELETE FROM t1 ORDER BY (SELECT x);
+ERROR 42S22: Unknown column 'x' in 'field list'
+DROP TABLE t1;
diff --git a/mysql-test/r/events_scheduling.result b/mysql-test/r/events_scheduling.result
index d885dc3a0485af6c8a7ff54e635830dedffa68ca..12f270748a6d2ced4e4385d6a55377c68609a009 100644
--- a/mysql-test/r/events_scheduling.result
+++ b/mysql-test/r/events_scheduling.result
@@ -69,7 +69,7 @@ OK
 SELECT IF(LAST_EXECUTED-ENDS < 3, 'OK', 'ERROR') FROM INFORMATION_SCHEMA.EVENTS WHERE EVENT_SCHEMA=DATABASE() AND EVENT_NAME='start_n_end' AND ENDS IS NOT NULL;
 IF(LAST_EXECUTED-ENDS < 3, 'OK', 'ERROR')
 OK
-DROP EVENT start_n_end;
+DROP EVENT IF EXISTS events_test.start_n_end;
 "Already dropped because ended. Therefore an error."
 DROP EVENT only_one_time;
 ERROR HY000: Unknown event 'only_one_time'
diff --git a/mysql-test/r/federated_server.result b/mysql-test/r/federated_server.result
index 7a1a6e0970d45cdb509aa0a4d9e52d2741c494e4..a3e7cd793a67e76c2726faa7573c40303c5d9497 100644
--- a/mysql-test/r/federated_server.result
+++ b/mysql-test/r/federated_server.result
@@ -20,6 +20,14 @@ CREATE TABLE first_db.t1 (
 `name` varchar(64) NOT NULL default ''
     )
 DEFAULT CHARSET=latin1;
+DROP TABLE IF EXISTS first_db.t2;
+Warnings:
+Note	1051	Unknown table 't2'
+CREATE TABLE first_db.t2 (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    )
+DEFAULT CHARSET=latin1;
 use second_db;
 DROP TABLE IF EXISTS second_db.t1;
 Warnings:
@@ -29,6 +37,14 @@ CREATE TABLE second_db.t1 (
 `name` varchar(64) NOT NULL default ''
     )
 DEFAULT CHARSET=latin1;
+DROP TABLE IF EXISTS second_db.t2;
+Warnings:
+Note	1051	Unknown table 't2'
+CREATE TABLE second_db.t2 (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    )
+DEFAULT CHARSET=latin1;
 drop server if exists 'server_one';
 create server 'server_one' foreign data wrapper 'mysql' options
 (HOST '127.0.0.1',
@@ -60,10 +76,10 @@ CREATE TABLE federated.old (
     )
 ENGINE="FEDERATED" DEFAULT CHARSET=latin1
 CONNECTION='mysql://root@127.0.0.1:SLAVE_PORT/first_db/t1';
-INSERT INTO federated.old (id, name) values (1, 'federated.old url');
+INSERT INTO federated.old (id, name) values (1, 'federated.old-> first_db.t1, url format');
 SELECT * FROM federated.old;
 id	name
-1	federated.old url
+1	federated.old-> first_db.t1, url format
 DROP TABLE IF EXISTS federated.old2;
 Warnings:
 Note	1051	Unknown table 'old2'
@@ -72,8 +88,37 @@ CREATE TABLE federated.old2 (
 `name` varchar(64) NOT NULL default ''
     )
 ENGINE="FEDERATED" DEFAULT CHARSET=latin1
+CONNECTION='mysql://root@127.0.0.1:SLAVE_PORT/first_db/t2';
+INSERT INTO federated.old2 (id, name) values (1, 'federated.old2-> first_db.t2, url format');
+SELECT * FROM federated.old2;
+id	name
+1	federated.old2-> first_db.t2, url format
+DROP TABLE IF EXISTS federated.urldb2t1;
+Warnings:
+Note	1051	Unknown table 'urldb2t1'
+CREATE TABLE federated.urldb2t1 (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    )
+ENGINE="FEDERATED" DEFAULT CHARSET=latin1
 CONNECTION='mysql://root@127.0.0.1:SLAVE_PORT/second_db/t1';
-INSERT INTO federated.old2 (id, name) values (1, 'federated.old2 url');
+INSERT INTO federated.urldb2t1 (id, name) values (1, 'federated.urldb2t1 -> second_db.t1, url format');
+SELECT * FROM federated.urldb2t1;
+id	name
+1	federated.urldb2t1 -> second_db.t1, url format
+DROP TABLE IF EXISTS federated.urldb2t2;
+Warnings:
+Note	1051	Unknown table 'urldb2t2'
+CREATE TABLE federated.urldb2t2 (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    )
+ENGINE="FEDERATED" DEFAULT CHARSET=latin1
+CONNECTION='mysql://root@127.0.0.1:SLAVE_PORT/second_db/t2';
+INSERT INTO federated.urldb2t2 (id, name) values (1, 'federated.urldb2t2 -> second_db.t2, url format');
+SELECT * FROM federated.urldb2t2;
+id	name
+1	federated.urldb2t2 -> second_db.t2, url format
 DROP TABLE IF EXISTS federated.t1;
 Warnings:
 Note	1051	Unknown table 't1'
@@ -83,18 +128,38 @@ CREATE TABLE federated.t1 (
     )
 ENGINE="FEDERATED" DEFAULT CHARSET=latin1
 CONNECTION='server_one';
-INSERT INTO federated.t1 (id, name) values (1, 'server_one, new scheme');
+INSERT INTO federated.t1 (id, name) values (1, 'server_one, new scheme, first_db.t1');
 SELECT * FROM federated.t1;
 id	name
-1	federated.old url
-1	server_one, new scheme
+1	federated.old-> first_db.t1, url format
+1	server_one, new scheme, first_db.t1
+DROP TABLE IF EXISTS federated.whatever;
+Warnings:
+Note	1051	Unknown table 'whatever'
+CREATE TABLE federated.whatever (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    )
+ENGINE="FEDERATED" DEFAULT CHARSET=latin1
+CONNECTION='server_one/t1';
+INSERT INTO federated.whatever (id, name) values (1, 'server_one, new scheme, whatever, first_db.t1');
+SELECT * FROM federated.whatever;
+id	name
+1	federated.old-> first_db.t1, url format
+1	server_one, new scheme, first_db.t1
+1	server_one, new scheme, whatever, first_db.t1
 ALTER SERVER 'server_one' options(DATABASE 'second_db');
-flush tables;
-INSERT INTO federated.t1 (id, name) values (1, 'server_two, new scheme');
+INSERT INTO federated.t1 (id, name) values (1, 'server_two, new scheme, second_db.t1');
 SELECT * FROM federated.t1;
 id	name
-1	federated.old2 url
-1	server_two, new scheme
+1	federated.urldb2t1 -> second_db.t1, url format
+1	server_two, new scheme, second_db.t1
+INSERT INTO federated.whatever (id, name) values (1, 'server_two, new scheme, whatever, second_db.t1');
+SELECT * FROM federated.whatever;
+id	name
+1	federated.urldb2t1 -> second_db.t1, url format
+1	server_two, new scheme, second_db.t1
+1	server_two, new scheme, whatever, second_db.t1
 drop table federated.t1;
 drop server 'server_one';
 drop server 'server_two';
@@ -104,6 +169,116 @@ drop table first_db.t1;
 drop table second_db.t1;
 drop database first_db;
 drop database second_db;
+create database db_legitimate;
+create database db_bogus;
+use db_legitimate;
+CREATE TABLE db_legitimate.t1 (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    );
+INSERT INTO db_legitimate.t1 VALUES ('1','this is legitimate');
+use db_bogus;
+CREATE TABLE db_bogus.t1 (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    )
+;
+INSERT INTO db_bogus.t1 VALUES ('2','this is bogus');
+create server 's1' foreign data wrapper 'mysql' options
+(HOST '127.0.0.1',
+DATABASE 'db_legitimate',
+USER 'root',
+PASSWORD '',
+PORT SLAVE_PORT,
+SOCKET '',
+OWNER 'root');
+create user guest_select@localhost;
+grant select on federated.* to guest_select@localhost;
+create user guest_super@localhost;
+grant select,SUPER,RELOAD on *.* to guest_super@localhost;
+create user guest_usage@localhost;
+grant usage on *.* to guest_usage@localhost;
+CREATE TABLE federated.t1 (
+`id` int(20) NOT NULL,
+`name` varchar(64) NOT NULL default ''
+    ) ENGINE = FEDERATED CONNECTION = 's1';
+select * from federated.t1;
+id	name
+1	this is legitimate
+alter server s1 options (database 'db_bogus');
+ERROR 42000: Access denied; you need the SUPER privilege for this operation
+flush tables;
+select * from federated.t1;
+id	name
+1	this is legitimate
+alter server s1 options (database 'db_bogus');
+ERROR 42000: Access denied; you need the SUPER privilege for this operation
+flush tables;
+select * from federated.t1;
+id	name
+1	this is legitimate
+alter server s1 options (database 'db_bogus');
+flush tables;
+select * from federated.t1;
+id	name
+2	this is bogus
+drop server if exists 's1';
+ERROR 42000: Access denied; you need the SUPER privilege for this operation
+create server 's1' foreign data wrapper 'mysql' options
+(HOST '127.0.0.1',
+DATABASE 'db_legitimate',
+USER 'root',
+PASSWORD '',
+PORT SLAVE_PORT,
+SOCKET '',
+OWNER 'root');
+ERROR 42000: Access denied; you need the SUPER privilege for this operation
+drop server 's1';
+create server 's1' foreign data wrapper 'mysql' options
+(HOST '127.0.0.1',
+DATABASE 'db_legitimate',
+USER 'root',
+PASSWORD '',
+PORT SLAVE_PORT,
+SOCKET '',
+OWNER 'root');
+flush tables;
+select * from federated.t1;
+id	name
+1	this is legitimate
+drop database db_legitimate;
+drop database db_bogus;
+drop user guest_super@localhost;
+drop user guest_usage@localhost;
+drop user guest_select@localhost;
+drop table federated.t1;
+drop server 's1';
+# End of 5.1 tests
+use test;
+create procedure p1 ()
+begin
+DECLARE v INT DEFAULT 0;
+DECLARE e INT DEFAULT 0;
+DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET e = e + 1;
+WHILE v < 10000 do
+CREATE SERVER s
+FOREIGN DATA WRAPPER mysql
+OPTIONS (USER 'Remote', HOST '192.168.1.106', DATABASE 'test');
+ALTER SERVER s OPTIONS (USER 'Remote');
+DROP SERVER s;
+SET v = v + 1;
+END WHILE;
+SELECT e > 0;
+END//
+use test;
+call p1();
+call p1();
+e > 0
+1
+e > 0
+1
+drop procedure p1;
+drop server if exists s;
 DROP TABLE IF EXISTS federated.t1;
 DROP DATABASE IF EXISTS federated;
 DROP TABLE IF EXISTS federated.t1;
diff --git a/mysql-test/r/func_gconcat.result b/mysql-test/r/func_gconcat.result
index 57b0a2aec25bcb58138a8f5bace33ab41a42709e..4c7baac051aa3acd2167183bbd4b5a62c42307e8 100644
--- a/mysql-test/r/func_gconcat.result
+++ b/mysql-test/r/func_gconcat.result
@@ -734,3 +734,13 @@ f2	group_concat(f1)
 aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa	1
 bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb	2
 drop table t1;
+CREATE TABLE t1(a TEXT, b CHAR(20));
+INSERT INTO t1 VALUES ("one.1","one.1"),("two.2","two.2"),("one.3","one.3");
+SELECT GROUP_CONCAT(DISTINCT UCASE(a)) FROM t1;
+GROUP_CONCAT(DISTINCT UCASE(a))
+ONE.1,TWO.2,ONE.3
+SELECT GROUP_CONCAT(DISTINCT UCASE(b)) FROM t1;
+GROUP_CONCAT(DISTINCT UCASE(b))
+ONE.1,TWO.2,ONE.3
+DROP TABLE t1;
+End of 5.0 tests
diff --git a/mysql-test/r/gis.result b/mysql-test/r/gis.result
index 8f81c7c4b66483081788cfa12214b3e581a90d6f..63a92fa3a628348c485a3804237a1c5241a2c52b 100644
--- a/mysql-test/r/gis.result
+++ b/mysql-test/r/gis.result
@@ -730,6 +730,12 @@ point(b, b) IS NULL	linestring(b) IS NULL	polygon(b) IS NULL	multipoint(b) IS NU
 1	1	1	1	1	1	1
 0	1	1	1	1	1	1
 drop table t1;
+CREATE TABLE t1(a POINT) ENGINE=MyISAM;
+INSERT INTO t1 VALUES (NULL);
+SELECT * FROM t1;
+a
+NULL
+DROP TABLE t1;
 End of 4.1 tests
 create table t1 (s1 geometry not null,s2 char(100));
 create trigger t1_bu before update on t1 for each row set new.s1 = null;
@@ -764,6 +770,17 @@ create table t1 (g geometry not null);
 insert into t1 values(default);
 ERROR 22003: Cannot get geometry object from data you send to the GEOMETRY field
 drop table t1;
+CREATE TABLE t1 (a GEOMETRY);
+CREATE VIEW v1 AS SELECT GeomFromwkb(ASBINARY(a)) FROM t1;
+CREATE VIEW v2 AS SELECT a FROM t1;
+DESCRIBE v1;
+Field	Type	Null	Key	Default	Extra
+GeomFromwkb(ASBINARY(a))	geometry	YES		NULL	
+DESCRIBE v2;
+Field	Type	Null	Key	Default	Extra
+a	geometry	YES		NULL	
+DROP VIEW v1,v2;
+DROP TABLE t1;
 create table t1 (f1 tinyint(1), f2 char(1), f3 varchar(1), f4 geometry, f5 datetime);
 create view v1 as select * from t1;
 desc v1;
diff --git a/mysql-test/r/group_by.result b/mysql-test/r/group_by.result
index 5cff5fec7ed16022e1de1d38004cc1675ce39a19..c7464bb21d26591a2ecbe2c3c3153148dcd1a441 100644
--- a/mysql-test/r/group_by.result
+++ b/mysql-test/r/group_by.result
@@ -1141,4 +1141,9 @@ EXPLAIN SELECT 1 FROM t2 WHERE a IN
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	PRIMARY	t2	index	NULL	a	5	NULL	4	Using where; Using index
 2	DEPENDENT SUBQUERY	t1	ALL	NULL	NULL	NULL	NULL	256	Using where
+SHOW VARIABLES LIKE 'old';
+Variable_name	Value
+old	OFF
+SET @@old = off;
+ERROR HY000: Variable 'old' is a read only variable
 DROP TABLE t1, t2;
diff --git a/mysql-test/r/heap_btree.result b/mysql-test/r/heap_btree.result
index fd789a39d88a3de2cf82cda06106d7cb5a13d6b5..ab4b892170a59173689efb40efda246dcc1967a9 100644
--- a/mysql-test/r/heap_btree.result
+++ b/mysql-test/r/heap_btree.result
@@ -280,6 +280,33 @@ a
 1
 1
 drop table t1;
+CREATE TABLE t1 (
+c1 CHAR(3),
+c2 INTEGER,
+KEY USING BTREE(c1),
+KEY USING BTREE(c2)
+) ENGINE= MEMORY;
+INSERT INTO t1 VALUES ('ABC',0), ('A',0), ('B',0), ('C',0);
+UPDATE t1 SET c2= c2 + 1 WHERE c1 = 'A';
+SELECT * FROM t1;
+c1	c2
+ABC	0
+A	1
+B	0
+C	0
+DROP TABLE t1;
+CREATE TABLE t1 (
+c1 ENUM('1', '2'),
+UNIQUE USING BTREE(c1)
+) ENGINE= MEMORY DEFAULT CHARSET= utf8;
+INSERT INTO t1 VALUES('1'), ('2');
+DROP TABLE t1;
+CREATE TABLE t1 (
+c1 SET('1', '2'),
+UNIQUE USING BTREE(c1)
+) ENGINE= MEMORY DEFAULT CHARSET= utf8;
+INSERT INTO t1 VALUES('1'), ('2');
+DROP TABLE t1;
 End of 4.1 tests
 CREATE TABLE t1(val INT, KEY USING BTREE(val)) ENGINE=memory;
 INSERT INTO t1 VALUES(0);
diff --git a/mysql-test/r/insert_update.result b/mysql-test/r/insert_update.result
index c7351258266acd01b781569ff1f3196b2d696698..fed66ed47a7b41b38bd1133bf4cb317bc886326f 100644
--- a/mysql-test/r/insert_update.result
+++ b/mysql-test/r/insert_update.result
@@ -258,3 +258,81 @@ SELECT LAST_INSERT_ID();
 LAST_INSERT_ID()
 1
 DROP TABLE t1;
+SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO';
+CREATE TABLE `t1` (
+`id` int(11) PRIMARY KEY auto_increment,
+`f1` varchar(10) NOT NULL UNIQUE
+);
+INSERT IGNORE INTO t1 (f1) VALUES ("test1")
+ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+INSERT IGNORE INTO t1 (f1) VALUES ("test1")
+ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+LAST_INSERT_ID()
+1
+SELECT * FROM t1;
+id	f1
+1	test1
+INSERT IGNORE INTO t1 (f1) VALUES ("test2")
+ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT * FROM t1;
+id	f1
+1	test1
+2	test2
+INSERT IGNORE INTO t1 (f1) VALUES ("test2")
+ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+LAST_INSERT_ID()
+2
+SELECT * FROM t1;
+id	f1
+1	test1
+2	test2
+INSERT IGNORE INTO t1 (f1) VALUES ("test3")
+ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+LAST_INSERT_ID()
+3
+SELECT * FROM t1;
+id	f1
+1	test1
+2	test2
+3	test3
+DROP TABLE t1;
+CREATE TABLE `t1` (
+`id` int(11) PRIMARY KEY auto_increment,
+`f1` varchar(10) NOT NULL UNIQUE
+);
+INSERT IGNORE INTO t1 (f1) VALUES ("test1")
+ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+LAST_INSERT_ID()
+1
+SELECT * FROM t1;
+id	f1
+1	test1
+INSERT IGNORE INTO t1 (f1) VALUES ("test1"),("test4")
+ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+LAST_INSERT_ID()
+2
+SELECT * FROM t1;
+id	f1
+1	test1
+2	test4
+DROP TABLE t1;
+CREATE TABLE `t1` (
+`id` int(11) PRIMARY KEY auto_increment,
+`f1` varchar(10) NOT NULL UNIQUE,
+tim1 timestamp default '2003-01-01 00:00:00' on update current_timestamp
+);
+INSERT INTO t1 (f1) VALUES ("test1");
+SELECT id, f1 FROM t1;
+id	f1
+1	test1
+REPLACE INTO t1 VALUES (0,"test1",null);
+SELECT id, f1 FROM t1;
+id	f1
+0	test1
+DROP TABLE t1;
+SET SQL_MODE='';
diff --git a/mysql-test/r/myisam.result b/mysql-test/r/myisam.result
index bb666b2e499f0fc5b97caf31fae731263bc761ff..dcb471510cd751b02da165c3fcc26b9727ba6e54 100644
--- a/mysql-test/r/myisam.result
+++ b/mysql-test/r/myisam.result
@@ -943,6 +943,156 @@ SHOW TABLE STATUS LIKE 't1';
 Name	Engine	Version	Row_format	Rows	Avg_row_length	Data_length	Max_data_length	Index_length	Data_free	Auto_increment	Create_time	Update_time	Check_time	Collation	Checksum	Create_options	Comment
 t1	MyISAM	10	Dynamic	X	X	X	72057594037927935	X	X	X	X	X	X	latin1_swedish_ci	X	max_rows=4100100100 avg_row_length=70100	
 DROP TABLE t1;
+CREATE TABLE t1 (c1 TEXT NOT NULL, KEY c1 (c1(10))) ENGINE=MyISAM;
+INSERT INTO t1 VALUES
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+(''), (''), (''), (''),
+(' B'), (' B'), (' B'), (' B');
+SELECT DISTINCT COUNT(*) FROM t1 WHERE c1 = '';
+COUNT(*)
+4
+SELECT DISTINCT length(c1), c1 FROM t1 WHERE c1 = '';
+length(c1)	c1
+0	
+SELECT DISTINCT COUNT(*) FROM t1 IGNORE INDEX (c1) WHERE c1 = '';
+COUNT(*)
+4
+SELECT DISTINCT length(c1), c1 FROM t1 IGNORE INDEX (c1) WHERE c1 = '';
+length(c1)	c1
+0	
+SELECT DISTINCT length(c1), c1 FROM t1 ORDER BY c1;
+length(c1)	c1
+0	
+2		A
+2	 B
+DROP TABLE t1;
 End of 4.1 tests
 set storage_engine=MyISAM;
 drop table if exists t1,t2,t3;
diff --git a/mysql-test/r/range.result b/mysql-test/r/range.result
index 5cd7e3ebfbd12a5391c23e99e14c8b861e3d8382..d9efe21c5d0fe1be3540928901fd48dd2b052015 100644
--- a/mysql-test/r/range.result
+++ b/mysql-test/r/range.result
@@ -717,6 +717,147 @@ d8c4177d225791924.30714720
 d8c4177d2380fc201.39666693
 d8c4177d24ccef970.14957924
 DROP TABLE t1;
+create table t1 (
+c1  char(10), c2  char(10), c3  char(10), c4  char(10),
+c5  char(10), c6  char(10), c7  char(10), c8  char(10),
+c9  char(10), c10 char(10), c11 char(10), c12 char(10),
+c13 char(10), c14 char(10), c15 char(10), c16 char(10),
+index(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12,c13,c14,c15,c16)
+);
+insert into t1 (c1) values ('1'),('1'),('1'),('1');
+select * from t1 where
+c1 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4",
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c2 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c3 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c4 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+"abcdefg5", "123456785", "qwertyui5", "asddfg5", 
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c5 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4",
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c6 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4",
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c7 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c8 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c9 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+and c10 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+"abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+"abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+"abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+"abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+"abcdefg5", "123456785", "qwertyui5", "asddfg5",
+"abcdefg6", "123456786", "qwertyui6", "asddfg6",
+"abcdefg7", "123456787", "qwertyui7", "asddfg7",
+"abcdefg8", "123456788", "qwertyui8", "asddfg8",
+"abcdefg9", "123456789", "qwertyui9", "asddfg9",
+"abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+"abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+"abcdefgC", "12345678C", "qwertyuiC", "asddfgC");
+c1	c2	c3	c4	c5	c6	c7	c8	c9	c10	c11	c12	c13	c14	c15	c16
+drop table t1;
 End of 4.1 tests
 CREATE TABLE t1 (
 id int(11) NOT NULL auto_increment,
diff --git a/mysql-test/r/rpl_ddl.result b/mysql-test/r/rpl_ddl.result
index ace86532b124ac6f38f8779090013fa9e4434681..d41462de621e43550c68b045c11ecac73daebd93 100644
--- a/mysql-test/r/rpl_ddl.result
+++ b/mysql-test/r/rpl_ddl.result
@@ -4,45 +4,47 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+
+-------- switch to master -------
 SET AUTOCOMMIT = 1;
 DROP DATABASE IF EXISTS mysqltest1;
 DROP DATABASE IF EXISTS mysqltest2;
 DROP DATABASE IF EXISTS mysqltest3;
 CREATE DATABASE mysqltest1;
 CREATE DATABASE mysqltest2;
-CREATE TABLE mysqltest1.t1 (f1 BIGINT) ENGINE="InnoDB";
+CREATE TABLE mysqltest1.t1 (f1 BIGINT) ENGINE=InnoDB;
 INSERT INTO mysqltest1.t1 SET f1= 0;
-CREATE TABLE mysqltest1.t2 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t3 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t4 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t5 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t6 (f1 BIGINT) ENGINE="InnoDB";
+CREATE TABLE mysqltest1.t2 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t3 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t4 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t5 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t6 (f1 BIGINT) ENGINE=InnoDB;
 CREATE INDEX my_idx6 ON mysqltest1.t6(f1);
-CREATE TABLE mysqltest1.t7 (f1 BIGINT) ENGINE="InnoDB";
+CREATE TABLE mysqltest1.t7 (f1 BIGINT) ENGINE=InnoDB;
 INSERT INTO mysqltest1.t7 SET f1= 0;
-CREATE TABLE mysqltest1.t8 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t9 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t10 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t11 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t12 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t13 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t14 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t15 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t16 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t17 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t18 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TABLE mysqltest1.t19 (f1 BIGINT) ENGINE="InnoDB";
-CREATE TEMPORARY TABLE mysqltest1.t23 (f1 BIGINT);
+CREATE TABLE mysqltest1.t8 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t9 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t10 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t11 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t12 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t13 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t14 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t15 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t16 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t17 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t18 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TABLE mysqltest1.t19 (f1 BIGINT) ENGINE=InnoDB;
+CREATE TEMPORARY TABLE mysqltest1.t23 (f1 BIGINT) ENGINE=MEMORY;
 SET AUTOCOMMIT = 0;
 use mysqltest1;
 
 -------- switch to slave --------
-SET AUTOCOMMIT = 0;
+SET AUTOCOMMIT = 1;
 use mysqltest1;
 
 -------- switch to master -------
 
-######## COMMIT  ########
+######## SELECT 1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 0 + 1;
@@ -56,7 +58,9 @@ MAX(f1)
 0
 
 -------- switch to master -------
-COMMIT;
+SELECT 1;
+1
+1
 SELECT MAX(f1) FROM t1;
 MAX(f1)
 1
@@ -64,32 +68,110 @@ MAX(f1)
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
-1
+0
 
 -------- switch to master -------
 ROLLBACK;
 SELECT MAX(f1) FROM t1;
 MAX(f1)
+0
+
+TEST-INFO: MASTER: The INSERT is not committed (Succeeded)
+
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
+
+-------- switch to master -------
+
+######## SELECT COUNT(*) FROM t1 ########
+
+-------- switch to master -------
+INSERT INTO t1 SET f1= 0 + 1;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
 1
 
-TEST-INFO: MASTER: The INSERT is committed (Succeeded)
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+-------- switch to master -------
+SELECT COUNT(*) FROM t1;
+COUNT(*)
+2
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
+
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+-------- switch to master -------
+ROLLBACK;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+TEST-INFO: MASTER: The INSERT is not committed (Succeeded)
 
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
+0
+
+TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
+
+-------- switch to master -------
+
+######## COMMIT ########
+
+-------- switch to master -------
+INSERT INTO t1 SET f1= 0 + 1;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
 1
 
-TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+-------- switch to master -------
+COMMIT;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
+
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
 
 -------- switch to master -------
-flush logs;
+ROLLBACK;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
+
+TEST-INFO: MASTER: The INSERT is committed (Succeeded)
 
 -------- switch to slave --------
-flush logs;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
+
+TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
 -------- switch to master -------
 
-######## ROLLBACK  ########
+######## ROLLBACK ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 1 + 1;
@@ -129,14 +211,8 @@ MAX(f1)
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
 -------- switch to master -------
-flush logs;
 
--------- switch to slave --------
-flush logs;
-
--------- switch to master -------
-
-######## SET AUTOCOMMIT=1  ########
+######## SET AUTOCOMMIT=1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 1 + 1;
@@ -175,16 +251,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SET AUTOCOMMIT=0;
 
-######## START TRANSACTION  ########
+######## START TRANSACTION ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 2 + 1;
@@ -224,14 +294,8 @@ MAX(f1)
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
 -------- switch to master -------
-flush logs;
 
--------- switch to slave --------
-flush logs;
-
--------- switch to master -------
-
-######## BEGIN  ########
+######## BEGIN ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 3 + 1;
@@ -270,15 +334,9 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 
-######## DROP TABLE mysqltest1.t2  ########
+######## DROP TABLE mysqltest1.t2 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 4 + 1;
@@ -317,12 +375,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TABLES LIKE 't2';
 Tables_in_mysqltest1 (t2)
@@ -333,7 +385,7 @@ Tables_in_mysqltest1 (t2)
 
 -------- switch to master -------
 
-######## DROP TEMPORARY TABLE mysqltest1.t23  ########
+######## DROP TEMPORARY TABLE mysqltest1.t23 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 5 + 1;
@@ -368,15 +420,9 @@ TEST-INFO: MASTER: The INSERT is not committed (Succeeded)
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
-6
-
-TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
-
--------- switch to master -------
-flush logs;
+5
 
--------- switch to slave --------
-flush logs;
+TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
 -------- switch to master -------
 SHOW TABLES LIKE 't23';
@@ -388,7 +434,7 @@ Tables_in_mysqltest1 (t23)
 
 -------- switch to master -------
 
-######## RENAME TABLE mysqltest1.t3 to mysqltest1.t20  ########
+######## RENAME TABLE mysqltest1.t3 to mysqltest1.t20 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 5 + 1;
@@ -399,7 +445,7 @@ MAX(f1)
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
-6
+5
 
 -------- switch to master -------
 RENAME TABLE mysqltest1.t3 to mysqltest1.t20;
@@ -427,12 +473,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TABLES LIKE 't20';
 Tables_in_mysqltest1 (t20)
@@ -445,7 +485,7 @@ t20
 
 -------- switch to master -------
 
-######## ALTER TABLE mysqltest1.t4 ADD column f2 BIGINT  ########
+######## ALTER TABLE mysqltest1.t4 ADD column f2 BIGINT ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 6 + 1;
@@ -484,12 +524,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 describe mysqltest1.t4;
 Field	Type	Null	Key	Default	Extra
@@ -504,7 +538,7 @@ f2	bigint(20)	YES		NULL
 
 -------- switch to master -------
 
-######## CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= "InnoDB"  ########
+######## CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= InnoDB ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 7 + 1;
@@ -518,7 +552,7 @@ MAX(f1)
 7
 
 -------- switch to master -------
-CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= "InnoDB";
+CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= InnoDB;
 SELECT MAX(f1) FROM t1;
 MAX(f1)
 8
@@ -543,15 +577,9 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 
-######## CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT)  ########
+######## CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT) ENGINE=MEMORY ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 8 + 1;
@@ -565,7 +593,7 @@ MAX(f1)
 8
 
 -------- switch to master -------
-CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT);
+CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT) ENGINE=MEMORY;
 SELECT MAX(f1) FROM t1;
 MAX(f1)
 9
@@ -586,19 +614,13 @@ TEST-INFO: MASTER: The INSERT is not committed (Succeeded)
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
-9
-
-TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
-
--------- switch to master -------
-flush logs;
+8
 
--------- switch to slave --------
-flush logs;
+TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
 -------- switch to master -------
 
-######## TRUNCATE TABLE mysqltest1.t7  ########
+######## TRUNCATE TABLE mysqltest1.t7 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 8 + 1;
@@ -609,7 +631,7 @@ MAX(f1)
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
-9
+8
 
 -------- switch to master -------
 TRUNCATE TABLE mysqltest1.t7;
@@ -637,21 +659,17 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT * FROM mysqltest1.t7;
 f1
+
 -------- switch to slave --------
 SELECT * FROM mysqltest1.t7;
 f1
+
 -------- switch to master -------
 
-######## LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ  ########
+######## LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 9 + 1;
@@ -690,16 +708,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 UNLOCK TABLES;
 
-######## UNLOCK TABLES  ########
+######## UNLOCK TABLES ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 10 + 1;
@@ -738,16 +750,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 LOCK TABLES mysqltest1.t1 READ;
 
-######## UNLOCK TABLES  ########
+######## UNLOCK TABLES ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 10 + 1;
@@ -787,16 +793,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ;
 
-######## UNLOCK TABLES  ########
+######## UNLOCK TABLES ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 10 + 1;
@@ -836,14 +836,8 @@ MAX(f1)
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
 -------- switch to master -------
-flush logs;
 
--------- switch to slave --------
-flush logs;
-
--------- switch to master -------
-
-######## DROP INDEX my_idx6 ON mysqltest1.t6  ########
+######## DROP INDEX my_idx6 ON mysqltest1.t6 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 11 + 1;
@@ -882,12 +876,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW INDEX FROM mysqltest1.t6;
 Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_part	Packed	Null	Index_type	Comment
@@ -898,7 +886,7 @@ Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_par
 
 -------- switch to master -------
 
-######## CREATE INDEX my_idx5 ON mysqltest1.t5(f1)  ########
+######## CREATE INDEX my_idx5 ON mysqltest1.t5(f1) ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 12 + 1;
@@ -937,12 +925,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW INDEX FROM mysqltest1.t5;
 Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_part	Packed	Null	Index_type	Comment
@@ -955,7 +937,7 @@ t5	1	my_idx5	1	f1	A	NULL	NULL	NULL	YES	BTREE
 
 -------- switch to master -------
 
-######## DROP DATABASE mysqltest2  ########
+######## DROP DATABASE mysqltest2 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 13 + 1;
@@ -994,12 +976,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW DATABASES LIKE "mysqltest2";
 Database (mysqltest2)
@@ -1010,7 +986,7 @@ Database (mysqltest2)
 
 -------- switch to master -------
 
-######## CREATE DATABASE mysqltest3  ########
+######## CREATE DATABASE mysqltest3 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 14 + 1;
@@ -1049,12 +1025,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW DATABASES LIKE "mysqltest3";
 Database (mysqltest3)
@@ -1067,7 +1037,7 @@ mysqltest3
 
 -------- switch to master -------
 
-######## CREATE PROCEDURE p1() READS SQL DATA SELECT "this is p1"  ########
+######## CREATE PROCEDURE p1() READS SQL DATA SELECT "this is p1" ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 15 + 1;
@@ -1106,12 +1076,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
@@ -1122,7 +1086,8 @@ Modified	#
 Created	#
 Security_type	DEFINER
 Comment	
-	-------- switch to slave -------
+
+-------- switch to slave --------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
 Name	p1
@@ -1133,7 +1098,9 @@ Created	#
 Security_type	DEFINER
 Comment	
 
-######## ALTER PROCEDURE p1 COMMENT "I have been altered"  ########
+-------- switch to master -------
+
+######## ALTER PROCEDURE p1 COMMENT "I have been altered" ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 16 + 1;
@@ -1172,12 +1139,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
@@ -1188,7 +1149,8 @@ Modified	#
 Created	#
 Security_type	DEFINER
 Comment	I have been altered
-	-------- switch to slave -------
+
+-------- switch to slave --------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
 Name	p1
@@ -1199,7 +1161,9 @@ Created	#
 Security_type	DEFINER
 Comment	I have been altered
 
-######## DROP PROCEDURE p1  ########
+-------- switch to master -------
+
+######## DROP PROCEDURE p1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 17 + 1;
@@ -1239,17 +1203,14 @@ MAX(f1)
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
 -------- switch to master -------
-flush logs;
+SHOW PROCEDURE STATUS LIKE 'p1';
 
 -------- switch to slave --------
-flush logs;
+SHOW PROCEDURE STATUS LIKE 'p1';
 
 -------- switch to master -------
-SHOW PROCEDURE STATUS LIKE 'p1';
-	-------- switch to slave -------
-SHOW PROCEDURE STATUS LIKE 'p1';
 
-######## CREATE OR REPLACE VIEW v1 as select * from t1  ########
+######## CREATE OR REPLACE VIEW v1 as select * from t1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 18 + 1;
@@ -1288,23 +1249,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
-######## ALTER VIEW v1 AS select f1 from t1  ########
+-------- switch to master -------
+
+######## ALTER VIEW v1 AS select f1 from t1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 19 + 1;
@@ -1343,23 +1300,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
-######## DROP VIEW IF EXISTS v1  ########
+-------- switch to master -------
+
+######## DROP VIEW IF EXISTS v1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 20 + 1;
@@ -1398,21 +1351,17 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW CREATE VIEW v1;
 ERROR 42S02: Table 'mysqltest1.v1' doesn't exist
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW CREATE VIEW v1;
 ERROR 42S02: Table 'mysqltest1.v1' doesn't exist
 
-######## CREATE TRIGGER trg1 BEFORE INSERT ON t1 FOR EACH ROW SET @a:=1  ########
+-------- switch to master -------
+
+######## CREATE TRIGGER trg1 BEFORE INSERT ON t1 FOR EACH ROW SET @a:=1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 21 + 1;
@@ -1451,23 +1400,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 trg1	INSERT	t1	SET @a:=1	BEFORE	NULL		root@localhost
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 trg1	INSERT	t1	SET @a:=1	BEFORE	NULL		root@localhost
 
-######## DROP TRIGGER trg1  ########
+-------- switch to master -------
+
+######## DROP TRIGGER trg1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 22 + 1;
@@ -1506,21 +1451,17 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 
-######## CREATE USER user1@localhost  ########
+-------- switch to master -------
+
+######## CREATE USER user1@localhost ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 23 + 1;
@@ -1559,23 +1500,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT user FROM mysql.user WHERE user = 'user1';
 user
 user1
 
--------- switch to slave -------
+-------- switch to slave --------
 SELECT user FROM mysql.user WHERE user = 'user1';
 user
 user1
 
-######## RENAME USER user1@localhost TO rename1@localhost  ########
+-------- switch to master -------
+
+######## RENAME USER user1@localhost TO rename1@localhost ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 24 + 1;
@@ -1614,23 +1551,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
 rename1
 
--------- switch to slave -------
+-------- switch to slave --------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
 rename1
 
-######## DROP USER rename1@localhost  ########
+-------- switch to master -------
+
+######## DROP USER rename1@localhost ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 25 + 1;
@@ -1669,19 +1602,15 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
 
--------- switch to slave -------
+-------- switch to slave --------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
-DROP DATABASE IF EXISTS mysqltest1;
-DROP DATABASE IF EXISTS mysqltest2;
-DROP DATABASE IF EXISTS mysqltest3;
+use test;
+
+-------- switch to master -------
+DROP DATABASE mysqltest1;
+DROP DATABASE mysqltest3;
diff --git a/mysql-test/r/rpl_events.result b/mysql-test/r/rpl_events.result
index 332d8cf1c0cd376e3ac178930aa109069e0acdd9..bff1a814a6dfa2b7ad817ca04864ec95b3ba12de 100644
--- a/mysql-test/r/rpl_events.result
+++ b/mysql-test/r/rpl_events.result
@@ -11,8 +11,7 @@ drop table if exists t1,t2;
 CREATE TABLE `t1` (
 `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
 `c` VARCHAR(50) NOT NULL,
-`ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
-CURRENT_TIMESTAMP,
+`ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
 INSERT INTO t1 (c) VALUES ('manually');
@@ -22,13 +21,13 @@ SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name
 db	name	status	originator
 test	justonce	ENABLED	1
 "in the master"
-SELECT * FROM t1;
+SELECT * FROM t1 WHERE c = 'from justonce' OR c = 'manually' ORDER BY id;
 id	c	ts
 1	manually	TIMESTAMP
 2	from justonce	TIMESTAMP
 affected rows: 2
 "in the slave"
-SELECT * FROM t1;
+SELECT * FROM t1 WHERE c = 'from justonce' OR c = 'manually' ORDER BY id;
 id	c	ts
 1	manually	TIMESTAMP
 2	from justonce	TIMESTAMP
@@ -69,6 +68,18 @@ db	name	status	originator
 "in the slave"
 SELECT db, name, status, originator FROM mysql.event WHERE db = 'test';
 db	name	status	originator
+CREATE EVENT test.slave_terminate ON SCHEDULE EVERY 3 SECOND 
+DO INSERT INTO t1(c) VALUES ('from slave_terminate');
+SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name = 'slave_terminate';
+db	name	status	originator
+test	slave_terminate	ENABLED	2
+DROP EVENT test.slave_terminate;
+CREATE EVENT test.slave_terminate ON SCHEDULE EVERY 3 SECOND 
+DISABLE ON SLAVE DO INSERT INTO t1(c) VALUES ('from slave_terminate');
+SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name = 'slave_terminate';
+db	name	status	originator
+test	slave_terminate	SLAVESIDE_DISABLED	2
+DROP EVENT test.slave_terminate;
 "in the master"
 DROP TABLE t1;
 set binlog_format=statement;
@@ -77,8 +88,7 @@ drop table if exists t1,t2;
 CREATE TABLE `t1` (
 `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
 `c` VARCHAR(50) NOT NULL,
-`ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE
-CURRENT_TIMESTAMP,
+`ts` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 PRIMARY KEY (`id`)
 ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
 INSERT INTO t1 (c) VALUES ('manually');
@@ -88,13 +98,13 @@ SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name
 db	name	status	originator
 test	justonce	ENABLED	1
 "in the master"
-SELECT * FROM t1;
+SELECT * FROM t1 WHERE c = 'from justonce' OR c = 'manually' ORDER BY id;
 id	c	ts
 1	manually	TIMESTAMP
 2	from justonce	TIMESTAMP
 affected rows: 2
 "in the slave"
-SELECT * FROM t1;
+SELECT * FROM t1 WHERE c = 'from justonce' OR c = 'manually' ORDER BY id;
 id	c	ts
 1	manually	TIMESTAMP
 2	from justonce	TIMESTAMP
@@ -135,5 +145,17 @@ db	name	status	originator
 "in the slave"
 SELECT db, name, status, originator FROM mysql.event WHERE db = 'test';
 db	name	status	originator
+CREATE EVENT test.slave_terminate ON SCHEDULE EVERY 3 SECOND 
+DO INSERT INTO t1(c) VALUES ('from slave_terminate');
+SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name = 'slave_terminate';
+db	name	status	originator
+test	slave_terminate	ENABLED	2
+DROP EVENT test.slave_terminate;
+CREATE EVENT test.slave_terminate ON SCHEDULE EVERY 3 SECOND 
+DISABLE ON SLAVE DO INSERT INTO t1(c) VALUES ('from slave_terminate');
+SELECT db, name, status, originator FROM mysql.event WHERE db = 'test' AND name = 'slave_terminate';
+db	name	status	originator
+test	slave_terminate	SLAVESIDE_DISABLED	2
+DROP EVENT test.slave_terminate;
 "in the master"
 DROP TABLE t1;
diff --git a/mysql-test/r/rpl_incident.result b/mysql-test/r/rpl_incident.result
index 5becaf37068f64e991300666bc4076473ccdf3e2..a9547832ed9a6a74d64a52a5f200eadb9d36c8c8 100644
--- a/mysql-test/r/rpl_incident.result
+++ b/mysql-test/r/rpl_incident.result
@@ -12,10 +12,7 @@ a
 1
 2
 3
-SET @saved = @@debug;
-SET SESSION debug="d,incident_database_resync_on_replace";
 REPLACE INTO t1 VALUES (4);
-SET SESSION debug=@saved;
 SELECT * FROM t1;
 a
 1
@@ -47,7 +44,7 @@ Replicate_Do_Table
 Replicate_Ignore_Table	
 Replicate_Wild_Do_Table	
 Replicate_Wild_Ignore_Table	
-Last_Errno	1583
+Last_Errno	1586
 Last_Error	The incident LOST_EVENTS occured on the master. Message: <none>
 Skip_Counter	0
 Exec_Master_Log_Pos	#
diff --git a/mysql-test/r/rpl_ndb_charset.result b/mysql-test/r/rpl_ndb_charset.result
index 41dd57917029f7673352ee117f2f4d0c70a59222..ed9b3cfbfa888873cfecdad8185103a6f9a6d4ab 100644
--- a/mysql-test/r/rpl_ndb_charset.result
+++ b/mysql-test/r/rpl_ndb_charset.result
@@ -109,39 +109,39 @@ a	b
 1	cp850_general_ci
 drop database mysqltest2;
 drop database mysqltest3;
-show binlog events from 105;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	drop database if exists mysqltest2
-master-bin.000001	#	Query	1	#	drop database if exists mysqltest3
-master-bin.000001	#	Query	1	#	create database mysqltest2 character set latin2
-master-bin.000001	#	Query	1	#	create database mysqltest3
-master-bin.000001	#	Query	1	#	drop database mysqltest3
-master-bin.000001	#	Query	1	#	create database mysqltest3
-master-bin.000001	#	Query	1	#	use `mysqltest2`; create table t1 (a int auto_increment primary key, b varchar(100))
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `mysqltest2`; truncate table t1
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `mysqltest2`; truncate table t1
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	drop database mysqltest2
-master-bin.000001	#	Query	1	#	drop database mysqltest3
+master-bin.000001	#	Query	#	#	drop database if exists mysqltest2
+master-bin.000001	#	Query	#	#	drop database if exists mysqltest3
+master-bin.000001	#	Query	#	#	create database mysqltest2 character set latin2
+master-bin.000001	#	Query	#	#	create database mysqltest3
+master-bin.000001	#	Query	#	#	drop database mysqltest3
+master-bin.000001	#	Query	#	#	create database mysqltest3
+master-bin.000001	#	Query	#	#	use `mysqltest2`; create table t1 (a int auto_increment primary key, b varchar(100))
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `mysqltest2`; truncate table t1
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `mysqltest2`; truncate table t1
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	drop database mysqltest2
+master-bin.000001	#	Query	#	#	drop database mysqltest3
 select "--- --global--" as "";
 
 --- --global--
diff --git a/mysql-test/r/rpl_ndb_ddl.result b/mysql-test/r/rpl_ndb_ddl.result
index f5d8073be9477312c2c04ece0448988f62fd3d8e..aeaca1e7de0dae8a1c71cb4f1a812cfe8ba19710 100644
--- a/mysql-test/r/rpl_ndb_ddl.result
+++ b/mysql-test/r/rpl_ndb_ddl.result
@@ -4,45 +4,47 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+
+-------- switch to master -------
 SET AUTOCOMMIT = 1;
 DROP DATABASE IF EXISTS mysqltest1;
 DROP DATABASE IF EXISTS mysqltest2;
 DROP DATABASE IF EXISTS mysqltest3;
 CREATE DATABASE mysqltest1;
 CREATE DATABASE mysqltest2;
-CREATE TABLE mysqltest1.t1 (f1 BIGINT) ENGINE="NDB";
+CREATE TABLE mysqltest1.t1 (f1 BIGINT) ENGINE=NDB;
 INSERT INTO mysqltest1.t1 SET f1= 0;
-CREATE TABLE mysqltest1.t2 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t3 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t4 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t5 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t6 (f1 BIGINT) ENGINE="NDB";
+CREATE TABLE mysqltest1.t2 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t3 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t4 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t5 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t6 (f1 BIGINT) ENGINE=NDB;
 CREATE INDEX my_idx6 ON mysqltest1.t6(f1);
-CREATE TABLE mysqltest1.t7 (f1 BIGINT) ENGINE="NDB";
+CREATE TABLE mysqltest1.t7 (f1 BIGINT) ENGINE=NDB;
 INSERT INTO mysqltest1.t7 SET f1= 0;
-CREATE TABLE mysqltest1.t8 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t9 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t10 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t11 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t12 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t13 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t14 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t15 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t16 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t17 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t18 (f1 BIGINT) ENGINE="NDB";
-CREATE TABLE mysqltest1.t19 (f1 BIGINT) ENGINE="NDB";
-CREATE TEMPORARY TABLE mysqltest1.t23 (f1 BIGINT);
+CREATE TABLE mysqltest1.t8 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t9 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t10 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t11 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t12 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t13 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t14 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t15 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t16 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t17 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t18 (f1 BIGINT) ENGINE=NDB;
+CREATE TABLE mysqltest1.t19 (f1 BIGINT) ENGINE=NDB;
+CREATE TEMPORARY TABLE mysqltest1.t23 (f1 BIGINT) ENGINE=MEMORY;
 SET AUTOCOMMIT = 0;
 use mysqltest1;
 
 -------- switch to slave --------
-SET AUTOCOMMIT = 0;
+SET AUTOCOMMIT = 1;
 use mysqltest1;
 
 -------- switch to master -------
 
-######## COMMIT  ########
+######## SELECT 1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 0 + 1;
@@ -56,7 +58,9 @@ MAX(f1)
 0
 
 -------- switch to master -------
-COMMIT;
+SELECT 1;
+1
+1
 SELECT MAX(f1) FROM t1;
 MAX(f1)
 1
@@ -64,32 +68,110 @@ MAX(f1)
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
-1
+0
 
 -------- switch to master -------
 ROLLBACK;
 SELECT MAX(f1) FROM t1;
 MAX(f1)
+0
+
+TEST-INFO: MASTER: The INSERT is not committed (Succeeded)
+
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
+
+-------- switch to master -------
+
+######## SELECT COUNT(*) FROM t1 ########
+
+-------- switch to master -------
+INSERT INTO t1 SET f1= 0 + 1;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
 1
 
-TEST-INFO: MASTER: The INSERT is committed (Succeeded)
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+-------- switch to master -------
+SELECT COUNT(*) FROM t1;
+COUNT(*)
+2
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
 
 -------- switch to slave --------
 SELECT MAX(f1) FROM t1;
 MAX(f1)
+0
+
+-------- switch to master -------
+ROLLBACK;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+TEST-INFO: MASTER: The INSERT is not committed (Succeeded)
+
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
+
+TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
+
+-------- switch to master -------
+
+######## COMMIT ########
+
+-------- switch to master -------
+INSERT INTO t1 SET f1= 0 + 1;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
 1
 
-TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+0
 
 -------- switch to master -------
-flush logs;
+COMMIT;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
 
 -------- switch to slave --------
-flush logs;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
 
 -------- switch to master -------
+ROLLBACK;
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
 
-######## ROLLBACK  ########
+TEST-INFO: MASTER: The INSERT is committed (Succeeded)
+
+-------- switch to slave --------
+SELECT MAX(f1) FROM t1;
+MAX(f1)
+1
+
+TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
+
+-------- switch to master -------
+
+######## ROLLBACK ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 1 + 1;
@@ -128,15 +210,9 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 
-######## SET AUTOCOMMIT=1  ########
+######## SET AUTOCOMMIT=1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 1 + 1;
@@ -175,16 +251,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SET AUTOCOMMIT=0;
 
-######## START TRANSACTION  ########
+######## START TRANSACTION ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 2 + 1;
@@ -223,15 +293,9 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 
-######## BEGIN  ########
+######## BEGIN ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 3 + 1;
@@ -271,14 +335,8 @@ MAX(f1)
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
 -------- switch to master -------
-flush logs;
 
--------- switch to slave --------
-flush logs;
-
--------- switch to master -------
-
-######## DROP TABLE mysqltest1.t2  ########
+######## DROP TABLE mysqltest1.t2 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 4 + 1;
@@ -317,12 +375,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TABLES LIKE 't2';
 Tables_in_mysqltest1 (t2)
@@ -333,7 +385,7 @@ Tables_in_mysqltest1 (t2)
 
 -------- switch to master -------
 
-######## DROP TEMPORARY TABLE mysqltest1.t23  ########
+######## DROP TEMPORARY TABLE mysqltest1.t23 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 5 + 1;
@@ -372,12 +424,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TABLES LIKE 't23';
 Tables_in_mysqltest1 (t23)
@@ -388,7 +434,7 @@ Tables_in_mysqltest1 (t23)
 
 -------- switch to master -------
 
-######## RENAME TABLE mysqltest1.t3 to mysqltest1.t20  ########
+######## RENAME TABLE mysqltest1.t3 to mysqltest1.t20 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 5 + 1;
@@ -427,12 +473,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TABLES LIKE 't20';
 Tables_in_mysqltest1 (t20)
@@ -445,7 +485,7 @@ t20
 
 -------- switch to master -------
 
-######## ALTER TABLE mysqltest1.t4 ADD column f2 BIGINT  ########
+######## ALTER TABLE mysqltest1.t4 ADD column f2 BIGINT ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 6 + 1;
@@ -484,12 +524,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 describe mysqltest1.t4;
 Field	Type	Null	Key	Default	Extra
@@ -504,7 +538,7 @@ f2	bigint(20)	YES		NULL
 
 -------- switch to master -------
 
-######## CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= "NDB"  ########
+######## CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= NDB ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 7 + 1;
@@ -518,7 +552,7 @@ MAX(f1)
 7
 
 -------- switch to master -------
-CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= "NDB";
+CREATE TABLE mysqltest1.t21 (f1 BIGINT) ENGINE= NDB;
 SELECT MAX(f1) FROM t1;
 MAX(f1)
 8
@@ -543,15 +577,9 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 
-######## CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT)  ########
+######## CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT) ENGINE=MEMORY ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 8 + 1;
@@ -565,7 +593,7 @@ MAX(f1)
 8
 
 -------- switch to master -------
-CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT);
+CREATE TEMPORARY TABLE mysqltest1.t22 (f1 BIGINT) ENGINE=MEMORY;
 SELECT MAX(f1) FROM t1;
 MAX(f1)
 9
@@ -590,15 +618,9 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 
-######## TRUNCATE TABLE mysqltest1.t7  ########
+######## TRUNCATE TABLE mysqltest1.t7 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 8 + 1;
@@ -637,21 +659,17 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT * FROM mysqltest1.t7;
 f1
+
 -------- switch to slave --------
 SELECT * FROM mysqltest1.t7;
 f1
+
 -------- switch to master -------
 
-######## LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ  ########
+######## LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 9 + 1;
@@ -690,16 +708,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 UNLOCK TABLES;
 
-######## UNLOCK TABLES  ########
+######## UNLOCK TABLES ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 10 + 1;
@@ -738,16 +750,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 LOCK TABLES mysqltest1.t1 READ;
 
-######## UNLOCK TABLES  ########
+######## UNLOCK TABLES ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 10 + 1;
@@ -787,16 +793,10 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is not committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 LOCK TABLES mysqltest1.t1 WRITE, mysqltest1.t8 READ;
 
-######## UNLOCK TABLES  ########
+######## UNLOCK TABLES ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 10 + 1;
@@ -836,14 +836,8 @@ MAX(f1)
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
 -------- switch to master -------
-flush logs;
 
--------- switch to slave --------
-flush logs;
-
--------- switch to master -------
-
-######## DROP INDEX my_idx6 ON mysqltest1.t6  ########
+######## DROP INDEX my_idx6 ON mysqltest1.t6 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 11 + 1;
@@ -882,12 +876,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW INDEX FROM mysqltest1.t6;
 Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_part	Packed	Null	Index_type	Comment
@@ -898,7 +886,7 @@ Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_par
 
 -------- switch to master -------
 
-######## CREATE INDEX my_idx5 ON mysqltest1.t5(f1)  ########
+######## CREATE INDEX my_idx5 ON mysqltest1.t5(f1) ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 12 + 1;
@@ -937,12 +925,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW INDEX FROM mysqltest1.t5;
 Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_part	Packed	Null	Index_type	Comment
@@ -955,7 +937,7 @@ t5	1	my_idx5	1	f1	A	0	NULL	NULL	YES	BTREE
 
 -------- switch to master -------
 
-######## DROP DATABASE mysqltest2  ########
+######## DROP DATABASE mysqltest2 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 13 + 1;
@@ -994,12 +976,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW DATABASES LIKE "mysqltest2";
 Database (mysqltest2)
@@ -1010,7 +986,7 @@ Database (mysqltest2)
 
 -------- switch to master -------
 
-######## CREATE DATABASE mysqltest3  ########
+######## CREATE DATABASE mysqltest3 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 14 + 1;
@@ -1049,12 +1025,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW DATABASES LIKE "mysqltest3";
 Database (mysqltest3)
@@ -1067,7 +1037,7 @@ mysqltest3
 
 -------- switch to master -------
 
-######## CREATE PROCEDURE p1() READS SQL DATA SELECT "this is p1"  ########
+######## CREATE PROCEDURE p1() READS SQL DATA SELECT "this is p1" ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 15 + 1;
@@ -1106,12 +1076,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
@@ -1122,7 +1086,8 @@ Modified	#
 Created	#
 Security_type	DEFINER
 Comment	
-	-------- switch to slave -------
+
+-------- switch to slave --------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
 Name	p1
@@ -1133,7 +1098,9 @@ Created	#
 Security_type	DEFINER
 Comment	
 
-######## ALTER PROCEDURE p1 COMMENT "I have been altered"  ########
+-------- switch to master -------
+
+######## ALTER PROCEDURE p1 COMMENT "I have been altered" ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 16 + 1;
@@ -1172,12 +1139,6 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
@@ -1188,7 +1149,8 @@ Modified	#
 Created	#
 Security_type	DEFINER
 Comment	I have been altered
-	-------- switch to slave -------
+
+-------- switch to slave --------
 SHOW PROCEDURE STATUS LIKE 'p1';
 Db	mysqltest1
 Name	p1
@@ -1199,7 +1161,9 @@ Created	#
 Security_type	DEFINER
 Comment	I have been altered
 
-######## DROP PROCEDURE p1  ########
+-------- switch to master -------
+
+######## DROP PROCEDURE p1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 17 + 1;
@@ -1239,17 +1203,14 @@ MAX(f1)
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
 -------- switch to master -------
-flush logs;
+SHOW PROCEDURE STATUS LIKE 'p1';
 
 -------- switch to slave --------
-flush logs;
+SHOW PROCEDURE STATUS LIKE 'p1';
 
 -------- switch to master -------
-SHOW PROCEDURE STATUS LIKE 'p1';
-	-------- switch to slave -------
-SHOW PROCEDURE STATUS LIKE 'p1';
 
-######## CREATE OR REPLACE VIEW v1 as select * from t1  ########
+######## CREATE OR REPLACE VIEW v1 as select * from t1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 18 + 1;
@@ -1288,23 +1249,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
-######## ALTER VIEW v1 AS select f1 from t1  ########
+-------- switch to master -------
+
+######## ALTER VIEW v1 AS select f1 from t1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 19 + 1;
@@ -1343,23 +1300,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW CREATE VIEW v1;
 View	Create View
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `t1`.`f1` AS `f1` from `t1`
 
-######## DROP VIEW IF EXISTS v1  ########
+-------- switch to master -------
+
+######## DROP VIEW IF EXISTS v1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 20 + 1;
@@ -1398,21 +1351,17 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW CREATE VIEW v1;
 ERROR 42S02: Table 'mysqltest1.v1' doesn't exist
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW CREATE VIEW v1;
 ERROR 42S02: Table 'mysqltest1.v1' doesn't exist
 
-######## CREATE TRIGGER trg1 BEFORE INSERT ON t1 FOR EACH ROW SET @a:=1  ########
+-------- switch to master -------
+
+######## CREATE TRIGGER trg1 BEFORE INSERT ON t1 FOR EACH ROW SET @a:=1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 21 + 1;
@@ -1451,23 +1400,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 trg1	INSERT	t1	SET @a:=1	BEFORE	NULL		root@localhost
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 trg1	INSERT	t1	SET @a:=1	BEFORE	NULL		root@localhost
 
-######## DROP TRIGGER trg1  ########
+-------- switch to master -------
+
+######## DROP TRIGGER trg1 ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 22 + 1;
@@ -1506,21 +1451,17 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 
--------- switch to slave -------
+-------- switch to slave --------
 SHOW TRIGGERS;
 Trigger	Event	Table	Statement	Timing	Created	sql_mode	Definer
 
-######## CREATE USER user1@localhost  ########
+-------- switch to master -------
+
+######## CREATE USER user1@localhost ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 23 + 1;
@@ -1559,23 +1500,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT user FROM mysql.user WHERE user = 'user1';
 user
 user1
 
--------- switch to slave -------
+-------- switch to slave --------
 SELECT user FROM mysql.user WHERE user = 'user1';
 user
 user1
 
-######## RENAME USER user1@localhost TO rename1@localhost  ########
+-------- switch to master -------
+
+######## RENAME USER user1@localhost TO rename1@localhost ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 24 + 1;
@@ -1614,23 +1551,19 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
 rename1
 
--------- switch to slave -------
+-------- switch to slave --------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
 rename1
 
-######## DROP USER rename1@localhost  ########
+-------- switch to master -------
+
+######## DROP USER rename1@localhost ########
 
 -------- switch to master -------
 INSERT INTO t1 SET f1= 25 + 1;
@@ -1669,20 +1602,15 @@ MAX(f1)
 
 TEST-INFO: SLAVE:  The INSERT is committed (Succeeded)
 
--------- switch to master -------
-flush logs;
-
--------- switch to slave --------
-flush logs;
-
 -------- switch to master -------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
 
--------- switch to slave -------
+-------- switch to slave --------
 SELECT user FROM mysql.user WHERE user = 'rename1';
 user
-DROP DATABASE IF EXISTS mysqltest1;
-DROP DATABASE IF EXISTS mysqltest2;
-DROP DATABASE IF EXISTS mysqltest3;
-ERROR HY000: Can't execute the given command because you have active locked tables or an active transaction
+use test;
+
+-------- switch to master -------
+DROP DATABASE mysqltest1;
+DROP DATABASE mysqltest3;
diff --git a/mysql-test/r/rpl_ndb_log.result b/mysql-test/r/rpl_ndb_log.result
index 8d305e27bed7b36be4fd365b1ff03e750505ce6f..8d443780039599900edc75b6be694940ed6ee9d1 100644
--- a/mysql-test/r/rpl_ndb_log.result
+++ b/mysql-test/r/rpl_ndb_log.result
@@ -35,14 +35,14 @@ master-bin.000001	#	Write_rows	1	#	table_id: #
 master-bin.000001	#	Write_rows	1	#	table_id: #
 master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 master-bin.000001	#	Query	1	#	COMMIT
-show binlog events from 105 limit 1;
+show binlog events from 106 limit 1;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=NDB
-show binlog events from 105 limit 2;
+show binlog events from 106 limit 2;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=NDB
 master-bin.000001	#	Query	1	#	BEGIN
-show binlog events from 105 limit 2,1;
+show binlog events from 106 limit 2,1;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
 flush logs;
@@ -56,26 +56,25 @@ flush logs;
 stop slave;
 create table t2 (n int)ENGINE=NDB;
 insert into t2 values (1);
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=NDB
-master-bin.000001	#	Query	1	#	BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.ndb_apply_status)
-master-bin.000001	#	Write_rows	1	#	table_id: #
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	COMMIT
-master-bin.000001	#	Query	1	#	use `test`; drop table t1
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (word char(20) not null)ENGINE=NDB
-master-bin.000001	#	Query	1	#	BEGIN
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Table_map	1	#	table_id: # (mysql.ndb_apply_status)
-master-bin.000001	#	Write_rows	1	#	table_id: #
-master-bin.000001	#	Write_rows	1	#	table_id: #
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	COMMIT
-master-bin.000001	#	Rotate	1	#	master-bin.000002;pos=4
+master-bin.000001	#	Query	#	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=NDB
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.ndb_apply_status)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	use `test`; drop table t1
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (word char(20) not null)ENGINE=NDB
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (mysql.ndb_apply_status)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Rotate	#	#	master-bin.000002;pos=4
 show binlog events in 'master-bin.000002';
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000002	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
@@ -89,13 +88,13 @@ master-bin.000002	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 master-bin.000002	#	Query	1	#	COMMIT
 show binary logs;
 Log_name	File_size
-master-bin.000001	1774
-master-bin.000002	616
+master-bin.000001	1775
+master-bin.000002	617
 start slave;
 show binary logs;
 Log_name	File_size
-slave-bin.000001	1869
-slave-bin.000002	201
+slave-bin.000001	1870
+slave-bin.000002	202
 show binlog events in 'slave-bin.000001' from 4;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 slave-bin.000001	#	Format_desc	2	#	Server ver: VERSION, Binlog ver: 4
@@ -129,7 +128,7 @@ slave-bin.000002	#	Write_rows	2	#	table_id: # flags: STMT_END_F
 slave-bin.000002	#	Query	2	#	COMMIT
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_PORT	1	master-bin.000002	616	#	#	master-bin.000002	Yes	Yes				#			0		0	616	#	None		0	No						#
+#	127.0.0.1	root	MASTER_PORT	1	master-bin.000002	617	#	#	master-bin.000002	Yes	Yes				#			0		0	617	#	None		0	No						#
 show binlog events in 'slave-bin.000005' from 4;
 ERROR HY000: Error when executing command SHOW BINLOG EVENTS: Could not find target log
 DROP TABLE t1;
@@ -140,11 +139,10 @@ insert into t1 values (NULL, 1);
 reset master;
 set insert_id=5;
 insert into t1 values (NULL, last_insert_id()), (NULL, last_insert_id());
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 select * from t1;
 a	b
 1	1
diff --git a/mysql-test/r/rpl_ndb_multi.result b/mysql-test/r/rpl_ndb_multi.result
index a42bccbf9a564becd838089ff157424483493930..760114f36393d1f30d86742365b615b3cf9c9ea9 100644
--- a/mysql-test/r/rpl_ndb_multi.result
+++ b/mysql-test/r/rpl_ndb_multi.result
@@ -26,11 +26,11 @@ stop slave;
 SELECT @the_pos:=Position,@the_file:=SUBSTRING_INDEX(FILE, '/', -1)
 FROM mysql.ndb_binlog_index WHERE epoch = <the_epoch> ;
 @the_pos:=Position	@the_file:=SUBSTRING_INDEX(FILE, '/', -1)
-105	master-bin1.000001
+106	master-bin1.000001
 CHANGE MASTER TO
 master_port=<MASTER_PORT1>,
 master_log_file = 'master-bin1.000001',
-master_log_pos = 105 ;
+master_log_pos = 106 ;
 start slave;
 INSERT INTO t1 VALUES ("row2","will go away",2),("row3","will change",3),("row4","D",4);
 DELETE FROM t1 WHERE c3 = 1;
diff --git a/mysql-test/r/rpl_row_basic_11bugs.result b/mysql-test/r/rpl_row_basic_11bugs.result
index ce0e70138c282325b6277e6c3605694aa14983f7..1025b96558948c86f302062508a00c17fa0293a6 100644
--- a/mysql-test/r/rpl_row_basic_11bugs.result
+++ b/mysql-test/r/rpl_row_basic_11bugs.result
@@ -24,11 +24,11 @@ SHOW TABLES;
 Tables_in_test_ignore
 t2
 INSERT INTO t2 VALUES (3,3), (4,4);
-SHOW BINLOG EVENTS FROM 105;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	105	Query	1	198	use `test`; CREATE TABLE t1 (a INT, b INT)
-master-bin.000001	198	Table_map	1	238	table_id: # (test.t1)
-master-bin.000001	238	Write_rows	1	285	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b INT)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 **** On Slave ****
 SHOW DATABASES;
 Database
@@ -54,10 +54,10 @@ DELETE FROM t1 WHERE a = 0;
 UPDATE t1 SET a=99 WHERE a = 0;
 SHOW BINLOG EVENTS;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	105	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	105	Query	1	191	use `test`; CREATE TABLE t1 (a INT)
-master-bin.000001	191	Table_map	1	230	table_id: # (test.t1)
-master-bin.000001	230	Write_rows	1	269	table_id: # flags: STMT_END_F
+master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
+master-bin.000001	106	Query	1	192	use `test`; CREATE TABLE t1 (a INT)
+master-bin.000001	192	Table_map	1	231	table_id: # (test.t1)
+master-bin.000001	231	Write_rows	1	270	table_id: # flags: STMT_END_F
 DROP TABLE t1;
 ================ Test for BUG#17620 ================
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
diff --git a/mysql-test/r/rpl_row_charset.result b/mysql-test/r/rpl_row_charset.result
index 2462dd0b505df485ccd7a029035fd7639425d6ce..e51f3e57d1f1bdad91a2da19aaeddc0083afeb6c 100644
--- a/mysql-test/r/rpl_row_charset.result
+++ b/mysql-test/r/rpl_row_charset.result
@@ -109,39 +109,39 @@ a	b
 1	cp850_general_ci
 drop database mysqltest2;
 drop database mysqltest3;
-show binlog events from 105;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Query	1	#	drop database if exists mysqltest2
-master-bin.000001	#	Query	1	#	drop database if exists mysqltest3
-master-bin.000001	#	Query	1	#	create database mysqltest2 character set latin2
-master-bin.000001	#	Query	1	#	create database mysqltest3
-master-bin.000001	#	Query	1	#	drop database mysqltest3
-master-bin.000001	#	Query	1	#	create database mysqltest3
-master-bin.000001	#	Query	1	#	use `mysqltest2`; create table t1 (a int auto_increment primary key, b varchar(100))
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `mysqltest2`; truncate table t1
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `mysqltest2`; truncate table t1
-master-bin.000001	#	Table_map	1	#	table_id: # (mysqltest2.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	drop database mysqltest2
-master-bin.000001	#	Query	1	#	drop database mysqltest3
+master-bin.000001	#	Query	#	#	drop database if exists mysqltest2
+master-bin.000001	#	Query	#	#	drop database if exists mysqltest3
+master-bin.000001	#	Query	#	#	create database mysqltest2 character set latin2
+master-bin.000001	#	Query	#	#	create database mysqltest3
+master-bin.000001	#	Query	#	#	drop database mysqltest3
+master-bin.000001	#	Query	#	#	create database mysqltest3
+master-bin.000001	#	Query	#	#	use `mysqltest2`; create table t1 (a int auto_increment primary key, b varchar(100))
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `mysqltest2`; truncate table t1
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `mysqltest2`; truncate table t1
+master-bin.000001	#	Table_map	#	#	table_id: # (mysqltest2.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	drop database mysqltest2
+master-bin.000001	#	Query	#	#	drop database mysqltest3
 select "--- --global--" as "";
 
 --- --global--
diff --git a/mysql-test/r/rpl_row_create_table.result b/mysql-test/r/rpl_row_create_table.result
index d89afb3e5f354149c17575bac44b23fd3b14b78b..e76ce5b962d3f2e4101b3fb81bc9ad58b00e62c5 100644
--- a/mysql-test/r/rpl_row_create_table.result
+++ b/mysql-test/r/rpl_row_create_table.result
@@ -8,30 +8,30 @@ CREATE TABLE t1 (a INT, b INT);
 CREATE TABLE t2 (a INT, b INT) ENGINE=Merge;
 CREATE TABLE t3 (a INT, b INT) CHARSET=utf8;
 CREATE TABLE t4 (a INT, b INT) ENGINE=Merge CHARSET=utf8;
-SHOW BINLOG EVENTS FROM 215;
+SHOW BINLOG EVENTS FROM 216;
 Log_name	#
-Pos	215
+Pos	216
 Event_type	Query
 Server_id	#
-End_log_pos	308
+End_log_pos	309
 Info	use `test`; CREATE TABLE t1 (a INT, b INT)
 Log_name	#
-Pos	308
+Pos	309
 Event_type	Query
 Server_id	#
-End_log_pos	414
+End_log_pos	415
 Info	use `test`; CREATE TABLE t2 (a INT, b INT) ENGINE=Merge
 Log_name	#
-Pos	414
+Pos	415
 Event_type	Query
 Server_id	#
-End_log_pos	520
+End_log_pos	521
 Info	use `test`; CREATE TABLE t3 (a INT, b INT) CHARSET=utf8
 Log_name	#
-Pos	520
+Pos	521
 Event_type	Query
 Server_id	#
-End_log_pos	639
+End_log_pos	640
 Info	use `test`; CREATE TABLE t4 (a INT, b INT) ENGINE=Merge CHARSET=utf8
 **** On Master ****
 SHOW CREATE TABLE t1;
@@ -127,7 +127,7 @@ NULL	5	10
 NULL	6	12
 CREATE TABLE t7 (UNIQUE(b)) SELECT a,b FROM tt3;
 ERROR 23000: Duplicate entry '2' for key 'b'
-SHOW BINLOG EVENTS FROM 1097;
+SHOW BINLOG EVENTS FROM 1098;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 CREATE TABLE t7 (a INT, b INT UNIQUE);
 INSERT INTO t7 SELECT a,b FROM tt3;
@@ -137,11 +137,11 @@ a	b
 1	2
 2	4
 3	6
-SHOW BINLOG EVENTS FROM 1097;
+SHOW BINLOG EVENTS FROM 1098;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-#	1097	Query	#	1197	use `test`; CREATE TABLE t7 (a INT, b INT UNIQUE)
-#	1197	Table_map	#	1237	table_id: # (test.t7)
-#	1237	Write_rows	#	1293	table_id: # flags: STMT_END_F
+#	1098	Query	#	1198	use `test`; CREATE TABLE t7 (a INT, b INT UNIQUE)
+#	1198	Table_map	#	1238	table_id: # (test.t7)
+#	1238	Write_rows	#	1294	table_id: # flags: STMT_END_F
 SELECT * FROM t7 ORDER BY a,b;
 a	b
 1	2
@@ -154,10 +154,10 @@ INSERT INTO t7 SELECT a,b FROM tt4;
 ROLLBACK;
 Warnings:
 Warning	1196	Some non-transactional changed tables couldn't be rolled back
-SHOW BINLOG EVENTS FROM 1293;
+SHOW BINLOG EVENTS FROM 1294;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-#	1293	Table_map	#	1333	table_id: # (test.t7)
-#	1333	Write_rows	#	1389	table_id: # flags: STMT_END_F
+#	1294	Table_map	#	1334	table_id: # (test.t7)
+#	1334	Write_rows	#	1390	table_id: # flags: STMT_END_F
 SELECT * FROM t7 ORDER BY a,b;
 a	b
 1	2
@@ -192,10 +192,10 @@ Create Table	CREATE TABLE `t9` (
   `a` int(11) DEFAULT NULL,
   `b` int(11) DEFAULT NULL
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1
-SHOW BINLOG EVENTS FROM 1389;
+SHOW BINLOG EVENTS FROM 1390;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-#	1389	Query	#	1475	use `test`; CREATE TABLE t8 LIKE t4
-#	1475	Query	#	1614	use `test`; CREATE TABLE `t9` (
+#	1390	Query	#	1476	use `test`; CREATE TABLE t8 LIKE t4
+#	1476	Query	#	1615	use `test`; CREATE TABLE `t9` (
   `a` int(11) DEFAULT NULL,
   `b` int(11) DEFAULT NULL
 )
@@ -274,33 +274,33 @@ a
 3
 SHOW BINLOG EVENTS;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-#	4	Format_desc	#	105	Server ver: #, Binlog ver: #
-#	105	Query	#	191	use `test`; CREATE TABLE t1 (a INT)
-#	191	Table_map	#	230	table_id: # (test.t1)
-#	230	Write_rows	#	274	table_id: # flags: STMT_END_F
-#	274	Query	#	342	use `test`; BEGIN
-#	342	Query	#	125	use `test`; CREATE TABLE `t2` (
+#	4	Format_desc	#	106	Server ver: #, Binlog ver: #
+#	106	Query	#	192	use `test`; CREATE TABLE t1 (a INT)
+#	192	Table_map	#	231	table_id: # (test.t1)
+#	231	Write_rows	#	275	table_id: # flags: STMT_END_F
+#	275	Query	#	343	use `test`; BEGIN
+#	343	Query	#	125	use `test`; CREATE TABLE `t2` (
   `a` int(11) DEFAULT NULL
 ) ENGINE=InnoDB
-#	467	Table_map	#	164	table_id: # (test.t2)
-#	506	Write_rows	#	208	table_id: # flags: STMT_END_F
-#	550	Xid	#	577	COMMIT /* XID */
-#	577	Query	#	645	use `test`; BEGIN
-#	645	Query	#	125	use `test`; CREATE TABLE `t3` (
+#	468	Table_map	#	164	table_id: # (test.t2)
+#	507	Write_rows	#	208	table_id: # flags: STMT_END_F
+#	551	Xid	#	578	COMMIT /* XID */
+#	578	Query	#	646	use `test`; BEGIN
+#	646	Query	#	125	use `test`; CREATE TABLE `t3` (
   `a` int(11) DEFAULT NULL
 ) ENGINE=InnoDB
-#	770	Table_map	#	164	table_id: # (test.t3)
-#	809	Write_rows	#	208	table_id: # flags: STMT_END_F
-#	853	Xid	#	880	COMMIT /* XID */
-#	880	Query	#	948	use `test`; BEGIN
-#	948	Query	#	125	use `test`; CREATE TABLE `t4` (
+#	771	Table_map	#	164	table_id: # (test.t3)
+#	810	Write_rows	#	208	table_id: # flags: STMT_END_F
+#	854	Xid	#	881	COMMIT /* XID */
+#	881	Query	#	949	use `test`; BEGIN
+#	949	Query	#	125	use `test`; CREATE TABLE `t4` (
   `a` int(11) DEFAULT NULL
 ) ENGINE=InnoDB
-#	1073	Table_map	#	164	table_id: # (test.t4)
-#	1112	Write_rows	#	208	table_id: # flags: STMT_END_F
-#	1156	Xid	#	1183	COMMIT /* XID */
-#	1183	Table_map	#	1222	table_id: # (test.t1)
-#	1222	Write_rows	#	1266	table_id: # flags: STMT_END_F
+#	1074	Table_map	#	164	table_id: # (test.t4)
+#	1113	Write_rows	#	208	table_id: # flags: STMT_END_F
+#	1157	Xid	#	1184	COMMIT /* XID */
+#	1184	Table_map	#	1223	table_id: # (test.t1)
+#	1223	Write_rows	#	1267	table_id: # flags: STMT_END_F
 SHOW TABLES;
 Tables_in_test
 t1
@@ -365,17 +365,17 @@ a
 9
 SHOW BINLOG EVENTS;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-#	4	Format_desc	#	105	Server ver: #, Binlog ver: #
-#	105	Query	#	191	use `test`; CREATE TABLE t1 (a INT)
-#	191	Table_map	#	230	table_id: # (test.t1)
-#	230	Write_rows	#	274	table_id: # flags: STMT_END_F
-#	274	Query	#	374	use `test`; CREATE TABLE t2 (a INT) ENGINE=INNODB
-#	374	Query	#	442	use `test`; BEGIN
-#	442	Table_map	#	39	table_id: # (test.t2)
-#	481	Write_rows	#	83	table_id: # flags: STMT_END_F
-#	525	Table_map	#	122	table_id: # (test.t2)
-#	564	Write_rows	#	161	table_id: # flags: STMT_END_F
-#	603	Xid	#	630	COMMIT /* XID */
+#	4	Format_desc	#	106	Server ver: #, Binlog ver: #
+#	106	Query	#	192	use `test`; CREATE TABLE t1 (a INT)
+#	192	Table_map	#	231	table_id: # (test.t1)
+#	231	Write_rows	#	275	table_id: # flags: STMT_END_F
+#	275	Query	#	375	use `test`; CREATE TABLE t2 (a INT) ENGINE=INNODB
+#	375	Query	#	443	use `test`; BEGIN
+#	443	Table_map	#	39	table_id: # (test.t2)
+#	482	Write_rows	#	83	table_id: # flags: STMT_END_F
+#	526	Table_map	#	122	table_id: # (test.t2)
+#	565	Write_rows	#	161	table_id: # flags: STMT_END_F
+#	604	Xid	#	631	COMMIT /* XID */
 SELECT * FROM t2 ORDER BY a;
 a
 1
@@ -394,10 +394,10 @@ INSERT INTO t2 SELECT a+2 FROM tt2;
 ROLLBACK;
 SELECT * FROM t2 ORDER BY a;
 a
-SHOW BINLOG EVENTS FROM 630;
+SHOW BINLOG EVENTS FROM 631;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-#	630	Query	#	80	use `test`; TRUNCATE TABLE t2
-#	710	Xid	#	737	COMMIT /* XID */
+#	631	Query	#	80	use `test`; TRUNCATE TABLE t2
+#	711	Xid	#	738	COMMIT /* XID */
 SELECT * FROM t2 ORDER BY a;
 a
 DROP TABLE t1,t2;
diff --git a/mysql-test/r/rpl_row_delayed_ins.result b/mysql-test/r/rpl_row_delayed_ins.result
index e07a06f42fa8c354e9179d92297d7c07d477a8a3..800a39bd567d0ce0ba15cb3014a6ad50ee00023a 100644
--- a/mysql-test/r/rpl_row_delayed_ins.result
+++ b/mysql-test/r/rpl_row_delayed_ins.result
@@ -14,17 +14,16 @@ a
 1
 2
 3
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	105	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	105	Query	1	225	use `test`; create table t1(a int not null primary key) engine=myisam
-master-bin.000001	225	Table_map	1	264	table_id: # (test.t1)
-master-bin.000001	264	Write_rows	1	298	table_id: # flags: STMT_END_F
-master-bin.000001	298	Table_map	1	337	table_id: # (test.t1)
-master-bin.000001	337	Write_rows	1	371	table_id: # flags: STMT_END_F
-master-bin.000001	371	Table_map	1	410	table_id: # (test.t1)
-master-bin.000001	410	Write_rows	1	444	table_id: # flags: STMT_END_F
-master-bin.000001	444	Query	1	519	use `test`; flush tables
+master-bin.000001	#	Query	#	#	use `test`; create table t1(a int not null primary key) engine=myisam
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; flush tables
 SELECT * FROM t1 ORDER BY a;
 a
 1
diff --git a/mysql-test/r/rpl_row_drop.result b/mysql-test/r/rpl_row_drop.result
index cdf52ceb9b927178a762ac5b36cf70ceadc3780a..89654ebf16549d1aa14d8992fe5424c009fa14bd 100644
--- a/mysql-test/r/rpl_row_drop.result
+++ b/mysql-test/r/rpl_row_drop.result
@@ -43,10 +43,10 @@ t2
 DROP TABLE t1,t2;
 SHOW BINLOG EVENTS;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	105	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	105	Query	1	191	use `test`; CREATE TABLE t1 (a int)
-master-bin.000001	191	Query	1	277	use `test`; CREATE TABLE t2 (a int)
-master-bin.000001	277	Query	1	381	use `test`; DROP TABLE `t1` /* generated by server */
+master-bin.000001	4	Format_desc	1	106	Server ver: VERSION, Binlog ver: 4
+master-bin.000001	106	Query	1	192	use `test`; CREATE TABLE t1 (a int)
+master-bin.000001	192	Query	1	278	use `test`; CREATE TABLE t2 (a int)
+master-bin.000001	278	Query	1	382	use `test`; DROP TABLE `t1` /* generated by server */
 SHOW TABLES;
 Tables_in_test
 t2
diff --git a/mysql-test/r/rpl_row_flsh_tbls.result b/mysql-test/r/rpl_row_flsh_tbls.result
index d5b8dc48009e37f32fa331da8e2508086394afca..942a6b83bf6100343b0aac7d9b8faedc0f9d4881 100644
--- a/mysql-test/r/rpl_row_flsh_tbls.result
+++ b/mysql-test/r/rpl_row_flsh_tbls.result
@@ -12,13 +12,13 @@ create table t4 (a int);
 insert into t4 select * from t3;
 rename table t1 to t5, t2 to t1;
 flush no_write_to_binlog tables;
-SHOW BINLOG EVENTS FROM 618 ;
+SHOW BINLOG EVENTS FROM 619 ;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; rename table t1 to t5, t2 to t1
 select * from t3;
 a
 flush tables;
-SHOW BINLOG EVENTS FROM 618 ;
+SHOW BINLOG EVENTS FROM 619 ;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; rename table t1 to t5, t2 to t1
 master-bin.000001	#	Query	1	#	use `test`; flush tables
diff --git a/mysql-test/r/rpl_row_inexist_tbl.result b/mysql-test/r/rpl_row_inexist_tbl.result
index d482f6f5e9402c79405e4a449c0635315ff1c15b..7d0d7504ee716571fc5051562c5a135c8b5a9c5b 100644
--- a/mysql-test/r/rpl_row_inexist_tbl.result
+++ b/mysql-test/r/rpl_row_inexist_tbl.result
@@ -39,7 +39,7 @@ Replicate_Wild_Ignore_Table
 Last_Errno	1146
 Last_Error	Error 'Table 'test.t1' doesn't exist' on opening table `test`.`t1`
 Skip_Counter	0
-Exec_Master_Log_Pos	523
+Exec_Master_Log_Pos	524
 Relay_Log_Space	#
 Until_Condition	None
 Until_Log_File	
diff --git a/mysql-test/r/rpl_row_log.result b/mysql-test/r/rpl_row_log.result
index b1116b9e7c1ccd7df16c3626e1bd39b7897388ed..5d252d72bd18ef70e68aa79324cc4998749b649f 100644
--- a/mysql-test/r/rpl_row_log.result
+++ b/mysql-test/r/rpl_row_log.result
@@ -26,14 +26,14 @@ master-bin.000001	#	Query	1	#	use `test`; drop table t1
 master-bin.000001	#	Query	1	#	use `test`; create table t1 (word char(20) not null)ENGINE=MyISAM
 master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
 master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-show binlog events from 105 limit 1;
+show binlog events from 106 limit 1;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=MyISAM
-show binlog events from 105 limit 2;
+show binlog events from 106 limit 2;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=MyISAM
 master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-show binlog events from 105 limit 2,1;
+show binlog events from 106 limit 2,1;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 flush logs;
@@ -47,17 +47,16 @@ flush logs;
 stop slave;
 create table t2 (n int)ENGINE=MyISAM;
 insert into t2 values (1);
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=MyISAM
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Query	1	#	use `test`; drop table t1
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (word char(20) not null)ENGINE=MyISAM
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Rotate	1	#	master-bin.000002;pos=4
+master-bin.000001	#	Query	#	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=MyISAM
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; drop table t1
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (word char(20) not null)ENGINE=MyISAM
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Rotate	#	#	master-bin.000002;pos=4
 show binlog events in 'master-bin.000002';
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000002	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
@@ -67,13 +66,13 @@ master-bin.000002	#	Table_map	1	#	table_id: # (test.t2)
 master-bin.000002	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 show binary logs;
 Log_name	File_size
-master-bin.000001	1259
-master-bin.000002	376
+master-bin.000001	1260
+master-bin.000002	377
 start slave;
 show binary logs;
 Log_name	File_size
-slave-bin.000001	1357
-slave-bin.000002	277
+slave-bin.000001	1358
+slave-bin.000002	278
 show binlog events in 'slave-bin.000001' from 4;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 slave-bin.000001	#	Format_desc	2	#	Server ver: VERSION, Binlog ver: 4
@@ -94,7 +93,7 @@ slave-bin.000002	#	Table_map	1	#	table_id: # (test.t2)
 slave-bin.000002	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_PORT	1	master-bin.000002	376	#	#	master-bin.000002	Yes	Yes				#			0		0	376	#	None		0	No						#
+#	127.0.0.1	root	MASTER_PORT	1	master-bin.000002	377	#	#	master-bin.000002	Yes	Yes				#			0		0	377	#	None		0	No						#
 show binlog events in 'slave-bin.000005' from 4;
 ERROR HY000: Error when executing command SHOW BINLOG EVENTS: Could not find target log
 DROP TABLE t1;
@@ -105,11 +104,10 @@ insert into t1 values (NULL, 1);
 reset master;
 set insert_id=5;
 insert into t1 values (NULL, last_insert_id()), (NULL, last_insert_id());
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 select * from t1;
 a	b
 1	1
diff --git a/mysql-test/r/rpl_row_log_innodb.result b/mysql-test/r/rpl_row_log_innodb.result
index b1adcdd05e8858a0136b13879ad8911dccd35b1e..ff1fabb35cbb72cbea0ec0496c78526ad0b06558 100644
--- a/mysql-test/r/rpl_row_log_innodb.result
+++ b/mysql-test/r/rpl_row_log_innodb.result
@@ -28,14 +28,14 @@ master-bin.000001	#	Query	1	#	use `test`; create table t1 (word char(20) not nul
 master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
 master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 master-bin.000001	#	Xid	1	#	COMMIT /* XID */
-show binlog events from 105 limit 1;
+show binlog events from 106 limit 1;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=InnoDB
-show binlog events from 105 limit 2;
+show binlog events from 106 limit 2;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=InnoDB
 master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-show binlog events from 105 limit 2,1;
+show binlog events from 106 limit 2,1;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 flush logs;
@@ -49,19 +49,18 @@ flush logs;
 stop slave;
 create table t2 (n int)ENGINE=InnoDB;
 insert into t2 values (1);
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=InnoDB
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* XID */
-master-bin.000001	#	Query	1	#	use `test`; drop table t1
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (word char(20) not null)ENGINE=InnoDB
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
-master-bin.000001	#	Xid	1	#	COMMIT /* XID */
-master-bin.000001	#	Rotate	1	#	master-bin.000002;pos=4
+master-bin.000001	#	Query	#	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=InnoDB
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; drop table t1
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (word char(20) not null)ENGINE=InnoDB
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Rotate	#	#	master-bin.000002;pos=4
 show binlog events in 'master-bin.000002';
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000002	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
@@ -72,13 +71,13 @@ master-bin.000002	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 master-bin.000002	#	Xid	1	#	COMMIT /* XID */
 show binary logs;
 Log_name	File_size
-master-bin.000001	1313
-master-bin.000002	403
+master-bin.000001	1314
+master-bin.000002	404
 start slave;
 show binary logs;
 Log_name	File_size
-slave-bin.000001	1411
-slave-bin.000002	304
+slave-bin.000001	1412
+slave-bin.000002	305
 show binlog events in 'slave-bin.000001' from 4;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 slave-bin.000001	#	Format_desc	2	#	Server ver: VERSION, Binlog ver: 4
@@ -102,7 +101,7 @@ slave-bin.000002	#	Write_rows	1	#	table_id: # flags: STMT_END_F
 slave-bin.000002	#	Xid	1	#	COMMIT /* XID */
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_PORT	1	master-bin.000002	403	#	#	master-bin.000002	Yes	Yes				#			0		0	403	#	None		0	No						#
+#	127.0.0.1	root	MASTER_PORT	1	master-bin.000002	404	#	#	master-bin.000002	Yes	Yes				#			0		0	404	#	None		0	No						#
 show binlog events in 'slave-bin.000005' from 4;
 ERROR HY000: Error when executing command SHOW BINLOG EVENTS: Could not find target log
 DROP TABLE t1;
@@ -113,11 +112,10 @@ insert into t1 values (NULL, 1);
 reset master;
 set insert_id=5;
 insert into t1 values (NULL, last_insert_id()), (NULL, last_insert_id());
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Table_map	1	#	table_id: # (test.t1)
-master-bin.000001	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 select * from t1;
 a	b
 1	1
diff --git a/mysql-test/r/rpl_row_reset_slave.result b/mysql-test/r/rpl_row_reset_slave.result
index a93db7b2c7ee1b4bc0e5c87f88d806327abd366a..657dad302667115be443ad8ccca45202c3971b16 100644
--- a/mysql-test/r/rpl_row_reset_slave.result
+++ b/mysql-test/r/rpl_row_reset_slave.result
@@ -6,12 +6,12 @@ drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	105	#	#	master-bin.000001	Yes	Yes				#			0		0	105	#	None		0	No						#
+#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	106	#	#	master-bin.000001	Yes	Yes				#			0		0	106	#	None		0	No						#
 stop slave;
 change master to master_user='test';
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	test	MASTER_PORT	1	master-bin.000001	105	#	#	master-bin.000001	No	No				#			0		0	105	#	None		0	No						#
+#	127.0.0.1	test	MASTER_PORT	1	master-bin.000001	106	#	#	master-bin.000001	No	No				#			0		0	106	#	None		0	No						#
 reset slave;
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
@@ -19,7 +19,7 @@ Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File
 start slave;
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	105	#	#	master-bin.000001	Yes	Yes				#			0		0	105	#	None		0	No						#
+#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	106	#	#	master-bin.000001	Yes	Yes				#			0		0	106	#	None		0	No						#
 stop slave;
 reset slave;
 start slave;
diff --git a/mysql-test/r/rpl_row_until.result b/mysql-test/r/rpl_row_until.result
index 6d0da57baeb70642a2a430fa10a6a91796ee009f..cffcf12a31b3bb2d0a21e30294bceda0d17149ce 100644
--- a/mysql-test/r/rpl_row_until.result
+++ b/mysql-test/r/rpl_row_until.result
@@ -21,7 +21,7 @@ n
 4
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	743	slave-relay-bin.000004	#	master-bin.000001	#	No							0		0	314	#	Master	master-bin.000001	311	No						#
+#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	744	slave-relay-bin.000004	#	master-bin.000001	#	No							0		0	315	#	Master	master-bin.000001	311	No						#
 start slave until master_log_file='master-no-such-bin.000001', master_log_pos=291;
 select * from t1;
 n
@@ -31,7 +31,7 @@ n
 4
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	743	slave-relay-bin.000004	#	master-bin.000001	#	No							0		0	314	#	Master	master-no-such-bin.000001	291	No						#
+#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	744	slave-relay-bin.000004	#	master-bin.000001	#	No							0		0	315	#	Master	master-no-such-bin.000001	291	No						#
 start slave until relay_log_file='slave-relay-bin.000004', relay_log_pos=728;
 select * from t2;
 n
@@ -39,13 +39,13 @@ n
 2
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	743	slave-relay-bin.000004	#	master-bin.000001	#	No							0		0	589	#	Relay	slave-relay-bin.000004	728	No						#
+#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	744	slave-relay-bin.000004	#	master-bin.000001	#	No							0		0	590	#	Relay	slave-relay-bin.000004	728	No						#
 start slave;
 stop slave;
 start slave until master_log_file='master-bin.000001', master_log_pos=740;
 show slave status;
 Slave_IO_State	Master_Host	Master_User	Master_Port	Connect_Retry	Master_Log_File	Read_Master_Log_Pos	Relay_Log_File	Relay_Log_Pos	Relay_Master_Log_File	Slave_IO_Running	Slave_SQL_Running	Replicate_Do_DB	Replicate_Ignore_DB	Replicate_Do_Table	Replicate_Ignore_Table	Replicate_Wild_Do_Table	Replicate_Wild_Ignore_Table	Last_Errno	Last_Error	Skip_Counter	Exec_Master_Log_Pos	Relay_Log_Space	Until_Condition	Until_Log_File	Until_Log_Pos	Master_SSL_Allowed	Master_SSL_CA_File	Master_SSL_CA_Path	Master_SSL_Cert	Master_SSL_Cipher	Master_SSL_Key	Seconds_Behind_Master
-#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	743	slave-relay-bin.000004	#	master-bin.000001	Yes	No							0		0	743	#	Master	master-bin.000001	740	No						#
+#	127.0.0.1	root	MASTER_MYPORT	1	master-bin.000001	744	slave-relay-bin.000004	#	master-bin.000001	Yes	No							0		0	744	#	Master	master-bin.000001	740	No						#
 start slave until master_log_file='master-bin', master_log_pos=561;
 ERROR HY000: Incorrect parameter or combination of parameters for START SLAVE UNTIL
 start slave until master_log_file='master-bin.000001', master_log_pos=561, relay_log_pos=12;
diff --git a/mysql-test/r/rpl_stm_log.result b/mysql-test/r/rpl_stm_log.result
index 8d912dacff36a328e200119674efe0645fb6cdc5..f69ad8a57c161b48bbeb166000417cbcd5980aa9 100644
--- a/mysql-test/r/rpl_stm_log.result
+++ b/mysql-test/r/rpl_stm_log.result
@@ -47,17 +47,16 @@ flush logs;
 stop slave;
 create table t2 (n int)ENGINE=MyISAM;
 insert into t2 values (1);
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Query	1	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=MyISAM
-master-bin.000001	#	Intvar	1	#	INSERT_ID=1
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values (NULL)
-master-bin.000001	#	Query	1	#	use `test`; drop table t1
-master-bin.000001	#	Query	1	#	use `test`; create table t1 (word char(20) not null)ENGINE=MyISAM
-master-bin.000001	#	Begin_load_query	1	#	;file_id=1;block_len=581
-master-bin.000001	#	Execute_load_query	1	#	use `test`; load data infile '../std_data_ln/words.dat' into table t1 ignore 1 lines ;file_id=1
-master-bin.000001	#	Rotate	1	#	master-bin.000002;pos=4
+master-bin.000001	#	Query	#	#	use `test`; create table t1(n int not null auto_increment primary key)ENGINE=MyISAM
+master-bin.000001	#	Intvar	#	#	INSERT_ID=1
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values (NULL)
+master-bin.000001	#	Query	#	#	use `test`; drop table t1
+master-bin.000001	#	Query	#	#	use `test`; create table t1 (word char(20) not null)ENGINE=MyISAM
+master-bin.000001	#	Begin_load_query	#	#	;file_id=1;block_len=581
+master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../std_data_ln/words.dat' into table t1 ignore 1 lines ;file_id=1
+master-bin.000001	#	Rotate	#	#	master-bin.000002;pos=4
 show binlog events in 'master-bin.000002';
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000002	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
@@ -103,12 +102,11 @@ insert into t1 values (NULL, 1);
 reset master;
 set insert_id=5;
 insert into t1 values (NULL, last_insert_id()), (NULL, last_insert_id());
-show binlog events;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	#	Format_desc	1	#	Server ver: VERSION, Binlog ver: 4
-master-bin.000001	#	Intvar	1	#	LAST_INSERT_ID=1
-master-bin.000001	#	Intvar	1	#	INSERT_ID=5
-master-bin.000001	#	Query	1	#	use `test`; insert into t1 values (NULL, last_insert_id()), (NULL, last_insert_id())
+master-bin.000001	#	Intvar	#	#	LAST_INSERT_ID=1
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; insert into t1 values (NULL, last_insert_id()), (NULL, last_insert_id())
 select * from t1;
 a	b
 1	1
diff --git a/mysql-test/r/rpl_truncate_2myisam.result b/mysql-test/r/rpl_truncate_2myisam.result
index 7e15ae0ba45543ce5ffdf8f753ffa3fff3fec2f0..c7ef28ba56bee783489e45766de500fe8ae0b0da 100644
--- a/mysql-test/r/rpl_truncate_2myisam.result
+++ b/mysql-test/r/rpl_truncate_2myisam.result
@@ -29,13 +29,12 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
-master-bin.000001	214	Query	1	311	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Query	1	391	use `test`; TRUNCATE TABLE t1
-master-bin.000001	391	Query	1	467	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=MIXED;
 SET GLOBAL  BINLOG_FORMAT=MIXED;
@@ -61,13 +60,12 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
-master-bin.000001	214	Query	1	311	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Query	1	391	use `test`; TRUNCATE TABLE t1
-master-bin.000001	391	Query	1	467	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=ROW;
 SET GLOBAL  BINLOG_FORMAT=ROW;
@@ -93,14 +91,13 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
-master-bin.000001	214	Table_map	1	254	table_id: # (test.t1)
-master-bin.000001	254	Write_rows	1	301	table_id: # flags: STMT_END_F
-master-bin.000001	301	Query	1	381	use `test`; TRUNCATE TABLE t1
-master-bin.000001	381	Query	1	457	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=STATEMENT;
 SET GLOBAL  BINLOG_FORMAT=STATEMENT;
@@ -126,13 +123,12 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
-master-bin.000001	214	Query	1	311	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Query	1	388	use `test`; DELETE FROM t1
-master-bin.000001	388	Query	1	464	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Query	#	#	use `test`; DELETE FROM t1
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=MIXED;
 SET GLOBAL  BINLOG_FORMAT=MIXED;
@@ -158,13 +154,12 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
-master-bin.000001	214	Query	1	311	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Query	1	388	use `test`; DELETE FROM t1
-master-bin.000001	388	Query	1	464	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Query	#	#	use `test`; DELETE FROM t1
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=ROW;
 SET GLOBAL  BINLOG_FORMAT=ROW;
@@ -191,12 +186,11 @@ a	b
 3	3
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
-master-bin.000001	214	Table_map	1	254	table_id: # (test.t1)
-master-bin.000001	254	Write_rows	1	301	table_id: # flags: STMT_END_F
-master-bin.000001	301	Table_map	1	341	table_id: # (test.t1)
-master-bin.000001	341	Delete_rows	1	388	table_id: # flags: STMT_END_F
-master-bin.000001	388	Query	1	464	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=MyISAM
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
diff --git a/mysql-test/r/rpl_truncate_3innodb.result b/mysql-test/r/rpl_truncate_3innodb.result
index 46baa01896651115d5dd396d3f0987cee970f739..7ce48c2e983b4e4d22f5d9a27e5cca28c81e7fbc 100644
--- a/mysql-test/r/rpl_truncate_3innodb.result
+++ b/mysql-test/r/rpl_truncate_3innodb.result
@@ -29,15 +29,14 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
-master-bin.000001	214	Query	1	97	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Xid	1	338	COMMIT /* xid= */
-master-bin.000001	338	Query	1	80	use `test`; TRUNCATE TABLE t1
-master-bin.000001	418	Xid	1	445	COMMIT /* xid= */
-master-bin.000001	445	Query	1	521	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=MIXED;
 SET GLOBAL  BINLOG_FORMAT=MIXED;
@@ -63,15 +62,14 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
-master-bin.000001	214	Query	1	97	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Xid	1	338	COMMIT /* xid= */
-master-bin.000001	338	Query	1	80	use `test`; TRUNCATE TABLE t1
-master-bin.000001	418	Xid	1	445	COMMIT /* xid= */
-master-bin.000001	445	Query	1	521	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=ROW;
 SET GLOBAL  BINLOG_FORMAT=ROW;
@@ -97,16 +95,15 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
-master-bin.000001	214	Table_map	1	40	table_id: # (test.t1)
-master-bin.000001	254	Write_rows	1	87	table_id: # flags: STMT_END_F
-master-bin.000001	301	Xid	1	328	COMMIT /* xid= */
-master-bin.000001	328	Query	1	80	use `test`; TRUNCATE TABLE t1
-master-bin.000001	408	Xid	1	435	COMMIT /* xid= */
-master-bin.000001	435	Query	1	511	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=STATEMENT;
 SET GLOBAL  BINLOG_FORMAT=STATEMENT;
@@ -132,15 +129,14 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
-master-bin.000001	214	Query	1	97	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Xid	1	338	COMMIT /* xid= */
-master-bin.000001	338	Query	1	77	use `test`; DELETE FROM t1
-master-bin.000001	415	Xid	1	442	COMMIT /* xid= */
-master-bin.000001	442	Query	1	518	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DELETE FROM t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=MIXED;
 SET GLOBAL  BINLOG_FORMAT=MIXED;
@@ -166,15 +162,14 @@ SELECT * FROM t1;
 a	b
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
-master-bin.000001	214	Query	1	97	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
-master-bin.000001	311	Xid	1	338	COMMIT /* xid= */
-master-bin.000001	338	Query	1	77	use `test`; DELETE FROM t1
-master-bin.000001	415	Xid	1	442	COMMIT /* xid= */
-master-bin.000001	442	Query	1	518	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1 VALUES (1,1), (2,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DELETE FROM t1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
 **** On Master ****
 SET SESSION BINLOG_FORMAT=ROW;
 SET GLOBAL  BINLOG_FORMAT=ROW;
@@ -201,14 +196,13 @@ a	b
 3	3
 **** On Master ****
 DROP TABLE t1;
-SHOW BINLOG EVENTS;
+show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
-master-bin.000001	4	Format_desc	1	106	Server ver: SERVER_VERSION, Binlog ver: 4
-master-bin.000001	106	Query	1	214	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
-master-bin.000001	214	Table_map	1	40	table_id: # (test.t1)
-master-bin.000001	254	Write_rows	1	87	table_id: # flags: STMT_END_F
-master-bin.000001	301	Xid	1	328	COMMIT /* xid= */
-master-bin.000001	328	Table_map	1	40	table_id: # (test.t1)
-master-bin.000001	368	Delete_rows	1	87	table_id: # flags: STMT_END_F
-master-bin.000001	415	Xid	1	442	COMMIT /* xid= */
-master-bin.000001	442	Query	1	518	use `test`; DROP TABLE t1
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a INT, b LONG) ENGINE=InnoDB
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; DROP TABLE t1
diff --git a/mysql-test/r/rpl_udf.result b/mysql-test/r/rpl_udf.result
index 3a01de1c65c6839299637a646e34794c61fedccc..6587632bca09c5ada339665134cc5121d73eb055 100644
--- a/mysql-test/r/rpl_udf.result
+++ b/mysql-test/r/rpl_udf.result
@@ -22,8 +22,8 @@ affected rows: 2
 "Running on the slave"
 SELECT * FROM mysql.func;
 name	ret	dl	type
-myfunc_double	1	udf_example.dll	function
-myfunc_int	2	udf_example.dll	function
+myfunc_double	1	UDF_LIB	function
+myfunc_int	2	UDF_LIB	function
 affected rows: 2
 "Running on the master"
 CREATE TABLE t1(sum INT, price FLOAT(24)) ENGINE=MyISAM;
@@ -174,8 +174,8 @@ affected rows: 2
 "Running on the slave"
 SELECT * FROM mysql.func;
 name	ret	dl	type
-myfunc_int	2	udf_example.dll	function
-myfunc_double	1	udf_example.dll	function
+myfunc_int	2	UDF_LIB	function
+myfunc_double	1	UDF_LIB	function
 affected rows: 2
 "Running on the master"
 CREATE TABLE t1(sum INT, price FLOAT(24)) ENGINE=MyISAM;
diff --git a/mysql-test/r/sp-code.result b/mysql-test/r/sp-code.result
index 67b030f87a426f4220f3e90eb29105d9afbb49fc..588f4329368c439f15f7cf9b067e9a4a33f07523 100644
--- a/mysql-test/r/sp-code.result
+++ b/mysql-test/r/sp-code.result
@@ -621,3 +621,20 @@ Pos	Instruction
 0	stmt 2 "CREATE INDEX idx ON t1 (c1)"
 DROP PROCEDURE p1;
 End of 5.0 tests.
+CREATE PROCEDURE p1() 
+BEGIN 
+DECLARE dummy int default 0;
+CASE 12 
+WHEN 12 
+THEN SET dummy = 0;
+END CASE;
+END//
+SHOW PROCEDURE CODE p1;
+Pos	Instruction
+0	set dummy@0 0
+1	set_case_expr (6) 0 12
+2	jump_if_not 5(6) (case_expr@0 = 12)
+3	set dummy@0 0
+4	jump 6
+5	error 1339
+DROP PROCEDURE p1;
diff --git a/mysql-test/r/subselect.result b/mysql-test/r/subselect.result
index 8bc9350bd6c74ef0104055c6c77c450b407ca764..089fb10aaae9f0a6f9d7fdb143bd78f11ed844c5 100644
--- a/mysql-test/r/subselect.result
+++ b/mysql-test/r/subselect.result
@@ -3905,6 +3905,48 @@ COUNT(*)	a
 2	2
 3	3
 DROP TABLE t1,t2;
+CREATE TABLE t1 (a int, b int);
+CREATE TABLE t2 (m int, n int);
+INSERT INTO t1 VALUES (2,2), (2,2), (3,3), (3,3), (3,3), (4,4);
+INSERT INTO t2 VALUES (1,11), (2,22), (3,32), (4,44), (4,44);
+SELECT COUNT(*) c, a,
+(SELECT GROUP_CONCAT(COUNT(a)) FROM t2 WHERE m = a)
+FROM t1 GROUP BY a;
+c	a	(SELECT GROUP_CONCAT(COUNT(a)) FROM t2 WHERE m = a)
+2	2	2
+3	3	3
+1	4	1,1
+SELECT COUNT(*) c, a,
+(SELECT GROUP_CONCAT(COUNT(a)+1) FROM t2 WHERE m = a)
+FROM t1 GROUP BY a;
+c	a	(SELECT GROUP_CONCAT(COUNT(a)+1) FROM t2 WHERE m = a)
+2	2	3
+3	3	4
+1	4	2,2
+DROP table t1,t2;
+CREATE TABLE t1 (a int, b int);
+INSERT INTO t1 VALUES (2,22),(1,11),(2,22);
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 0 GROUP BY a;
+a
+1
+2
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 1 GROUP BY a;
+a
+SELECT a FROM t1 t0
+WHERE (SELECT COUNT(t0.b) FROM t1 t WHERE t.b>20) GROUP BY a;
+a
+1
+2
+SET @@sql_mode='ansi';
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 0 GROUP BY a;
+ERROR HY000: Invalid use of group function
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 1 GROUP BY a;
+ERROR HY000: Invalid use of group function
+SELECT a FROM t1 t0
+WHERE (SELECT COUNT(t0.b) FROM t1 t WHERE t.b>20) GROUP BY a;
+ERROR HY000: Invalid use of group function
+SET @@sql_mode=default;
+DROP TABLE t1;
 CREATE TABLE t1 (s1 char(1));
 INSERT INTO t1 VALUES ('a');
 SELECT * FROM t1 WHERE _utf8'a' = ANY (SELECT s1 FROM t1);
diff --git a/mysql-test/r/subselect3.result b/mysql-test/r/subselect3.result
index 2727a18c8d8713c0c439d712a9b888e48545a603..4b8ece1c9315c518a5be8c95dcc150c62b6131da 100644
--- a/mysql-test/r/subselect3.result
+++ b/mysql-test/r/subselect3.result
@@ -661,12 +661,6 @@ SELECT * FROM t1 GROUP by t1.a
 HAVING (MAX(t1.b) > (SELECT MAX(t2.b) FROM t2 WHERE t2.c < t1.c
 HAVING MAX(t2.b+t1.a) < 10));
 a	b	c
-SELECT a, AVG(b), (SELECT t.c FROM t1 AS t WHERE t1.a=t.a AND t.b=AVG(t1.b))
-AS test FROM t1 GROUP BY a;
-a	AVG(b)	test
-1	4.0000	NULL
-2	2.0000	k
-3	2.5000	NULL
 SELECT a,b,c FROM t1 WHERE b in (9,3,4) ORDER BY b,c;
 a	b	c
 1	3	c
diff --git a/mysql-test/t/binlog_row_mix_innodb_myisam.test b/mysql-test/t/binlog_row_mix_innodb_myisam.test
index 14aeb1f3428054c7a52fac298d80222be35a239f..335a05be14610b9ddfc46000bd03d402b92850f0 100644
--- a/mysql-test/t/binlog_row_mix_innodb_myisam.test
+++ b/mysql-test/t/binlog_row_mix_innodb_myisam.test
@@ -20,7 +20,7 @@
 # ER_SERVER_SHUTDOWN (i.e. disconnection just rolls back transaction
 # and does not make slave to stop)
 flush logs;
---exec $MYSQL_BINLOG --start-position=519 $MYSQLTEST_VARDIR/log/master-bin.000001 > $MYSQLTEST_VARDIR/tmp/mix_innodb_myisam_binlog.output
+--exec $MYSQL_BINLOG --start-position=520 $MYSQLTEST_VARDIR/log/master-bin.000001 > $MYSQLTEST_VARDIR/tmp/mix_innodb_myisam_binlog.output
 --replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
 eval select
 (@a:=load_file("$MYSQLTEST_VARDIR/tmp/mix_innodb_myisam_binlog.output"))
diff --git a/mysql-test/t/binlog_stm_mix_innodb_myisam.test b/mysql-test/t/binlog_stm_mix_innodb_myisam.test
index 4069cda04064cd1a9186a0f0095b9983043c98e4..72651c13be77f82228102b5abaebd3d22cf11e75 100644
--- a/mysql-test/t/binlog_stm_mix_innodb_myisam.test
+++ b/mysql-test/t/binlog_stm_mix_innodb_myisam.test
@@ -12,7 +12,7 @@
 # ER_SERVER_SHUTDOWN (i.e. disconnection just rolls back transaction
 # and does not make slave to stop)
 flush logs;
---exec $MYSQL_BINLOG --start-position=556 $MYSQLTEST_VARDIR/log/master-bin.000001 > $MYSQLTEST_VARDIR/tmp/mix_innodb_myisam_binlog.output
+--exec $MYSQL_BINLOG --start-position=555 $MYSQLTEST_VARDIR/log/master-bin.000001 > $MYSQLTEST_VARDIR/tmp/mix_innodb_myisam_binlog.output
 --replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
 eval select
 (@a:=load_file("$MYSQLTEST_VARDIR/tmp/mix_innodb_myisam_binlog.output"))
diff --git a/mysql-test/t/ctype_ucs.test b/mysql-test/t/ctype_ucs.test
index 5a3720dc4317fe7612f32675fc74342e853d9826..c3320159c417d4bcb1e61dbdb67f2ab599f71b6f 100644
--- a/mysql-test/t/ctype_ucs.test
+++ b/mysql-test/t/ctype_ucs.test
@@ -572,6 +572,20 @@ select utext from t1 where utext like '%%';
 drop table t1;
 deallocate prepare stmt;
 
+#
+# Bug#22638 SOUNDEX broken for international characters
+#
+set names latin1;
+set character_set_connection=ucs2;
+select soundex(''),soundex('he'),soundex('hello all folks'),soundex('#3556 in bugdb');
+select hex(soundex('')),hex(soundex('he')),hex(soundex('hello all folks')),hex(soundex('#3556 in bugdb'));
+select 'mood' sounds like 'mud';
+# Cyrillic A, BE, VE
+select hex(soundex(_ucs2 0x041004110412));
+# Make sure that "U+00BF INVERTED QUESTION MARK" is not considered as letter
+select hex(soundex(_ucs2 0x00BF00C0));
+set names latin1;
+
 #
 # Bug #14290: character_maximum_length for text fields
 #
diff --git a/mysql-test/t/ctype_utf8.test b/mysql-test/t/ctype_utf8.test
index 47a43258be195d012a712856ab97e65756117fb2..c0060b7b81324b28b6fda20ae111cd1e2ee6d3dc 100644
--- a/mysql-test/t/ctype_utf8.test
+++ b/mysql-test/t/ctype_utf8.test
@@ -702,6 +702,14 @@ select * from t1 where soundex(a) = soundex('TEST');
 select * from t1 where soundex(a) = soundex('test');
 drop table t1;
 
+#
+# Bug#22638 SOUNDEX broken for international characters
+#
+select soundex(_utf8 0xE99885E8A788E99A8FE697B6E69BB4E696B0E79A84E696B0E997BB);
+select hex(soundex(_utf8 0xE99885E8A788E99A8FE697B6E69BB4E696B0E79A84E696B0E997BB));
+select soundex(_utf8 0xD091D092D093);
+select hex(soundex(_utf8 0xD091D092D093));
+
 
 SET collation_connection='utf8_general_ci';
 -- source include/ctype_filesort.inc
diff --git a/mysql-test/t/delete.test b/mysql-test/t/delete.test
index 306447dbd5a1e4c47fa57451de313ed5a0c16ba9..36d627209dbca4986ec33205f528773feb131a01 100644
--- a/mysql-test/t/delete.test
+++ b/mysql-test/t/delete.test
@@ -203,3 +203,21 @@ select * from t1 where a is null;
 delete from t1 where a is null;
 select count(*) from t1;
 drop table t1;
+
+#
+# Bug #26186: delete order by, sometimes accept unknown column
+#
+CREATE TABLE t1 (a INT); INSERT INTO t1 VALUES (1);
+
+--error ER_BAD_FIELD_ERROR
+DELETE FROM t1 ORDER BY x;
+
+# even columns from a table not used in query (and not even existing)
+--error ER_BAD_FIELD_ERROR
+DELETE FROM t1 ORDER BY t2.x;
+
+# subquery (as long as the subquery from is valid or DUAL)
+--error ER_BAD_FIELD_ERROR
+DELETE FROM t1 ORDER BY (SELECT x);
+
+DROP TABLE t1;
diff --git a/mysql-test/t/disabled.def b/mysql-test/t/disabled.def
index c8d768df1192b97a7ea9c28288b16e1f8ccf1564..fd64becbc001d7f5ef9664dad425c4c95b9c665c 100644
--- a/mysql-test/t/disabled.def
+++ b/mysql-test/t/disabled.def
@@ -22,9 +22,11 @@ rpl_ndb_2innodb          : BUG#19227 2006-04-20 pekka pk delete apparently not r
 rpl_ndb_2myisam          : BUG#19227 Seems to pass currently
 rpl_ndb_dd_partitions    : BUG#19259 2006-04-21 rpl_ndb_dd_partitions fails on s/AMD
 rpl_ndb_ddl              : BUG#18946 result file needs update + test needs to checked
+rpl_ddl                  : BUG#26418 2007-03-01 mleich Slave out of sync after CREATE/DROP TEMPORARY TABLE + ROLLBACK on master
 rpl_ndb_innodb2ndb       : Bug #19710  Cluster replication to partition table fails on DELETE FROM statement
 rpl_ndb_myisam2ndb       : Bug #19710  Cluster replication to partition table fails on DELETE FROM statement
 rpl_row_blob_innodb      : BUG#18980 2006-04-10 kent    Test fails randomly
+rpl_udf                  : BUG#27564 2007-03-31 lars New test case for rpl of UDF shows valgrind failure
 synchronization          : Bug#24529  	Test 'synchronization' fails on Mac pushbuild; Also on Linux 64 bit.
 
 # the below testcase have been reworked to avoid the bug, test contains comment, keep bug open
diff --git a/mysql-test/t/events_scheduling.test b/mysql-test/t/events_scheduling.test
index e3b55685e655f0a072174d1e7380726db1b17a0d..f7d4c3c14d6f349f27cbc0cc73d8c3a492814f16 100644
--- a/mysql-test/t/events_scheduling.test
+++ b/mysql-test/t/events_scheduling.test
@@ -51,7 +51,7 @@ SELECT IF(SUM(a) >  0, 'OK', 'ERROR') FROM table_4;
 DROP EVENT two_sec;
 SELECT IF(TIME_TO_SEC(TIMEDIFF(ENDS,STARTS))=6, 'OK', 'ERROR') FROM INFORMATION_SCHEMA.EVENTS WHERE EVENT_SCHEMA=DATABASE() AND EVENT_NAME='start_n_end' AND ENDS IS NOT NULL;
 SELECT IF(LAST_EXECUTED-ENDS < 3, 'OK', 'ERROR') FROM INFORMATION_SCHEMA.EVENTS WHERE EVENT_SCHEMA=DATABASE() AND EVENT_NAME='start_n_end' AND ENDS IS NOT NULL;
-DROP EVENT start_n_end;
+DROP EVENT IF EXISTS events_test.start_n_end;
 --echo "Already dropped because ended. Therefore an error."
 --error ER_EVENT_DOES_NOT_EXIST
 DROP EVENT only_one_time;
diff --git a/mysql-test/t/federated_server.test b/mysql-test/t/federated_server.test
index 3e47d9bc95d45221442523028c863ec6070dd04b..b2075b8e262b565676c7505c03f03c13a25bce5a 100644
--- a/mysql-test/t/federated_server.test
+++ b/mysql-test/t/federated_server.test
@@ -17,6 +17,13 @@ CREATE TABLE first_db.t1 (
     )
   DEFAULT CHARSET=latin1;
 
+DROP TABLE IF EXISTS first_db.t2;
+CREATE TABLE first_db.t2 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    )
+  DEFAULT CHARSET=latin1;
+
 use second_db;
 DROP TABLE IF EXISTS second_db.t1;
 CREATE TABLE second_db.t1 (
@@ -25,6 +32,13 @@ CREATE TABLE second_db.t1 (
     )
   DEFAULT CHARSET=latin1;
 
+DROP TABLE IF EXISTS second_db.t2;
+CREATE TABLE second_db.t2 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    )
+  DEFAULT CHARSET=latin1;
+
 connection master;
 
 drop server if exists 'server_one';
@@ -61,7 +75,7 @@ eval CREATE TABLE federated.old (
   ENGINE="FEDERATED" DEFAULT CHARSET=latin1
   CONNECTION='mysql://root@127.0.0.1:$SLAVE_MYPORT/first_db/t1';
 
-INSERT INTO federated.old (id, name) values (1, 'federated.old url');
+INSERT INTO federated.old (id, name) values (1, 'federated.old-> first_db.t1, url format');
 
 SELECT * FROM federated.old;
 
@@ -72,9 +86,32 @@ eval CREATE TABLE federated.old2 (
     `name` varchar(64) NOT NULL default ''
     )
   ENGINE="FEDERATED" DEFAULT CHARSET=latin1
+  CONNECTION='mysql://root@127.0.0.1:$SLAVE_MYPORT/first_db/t2';
+
+INSERT INTO federated.old2 (id, name) values (1, 'federated.old2-> first_db.t2, url format');
+SELECT * FROM federated.old2;
+
+DROP TABLE IF EXISTS federated.urldb2t1;
+--replace_result $SLAVE_MYPORT SLAVE_PORT
+eval CREATE TABLE federated.urldb2t1 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    )
+  ENGINE="FEDERATED" DEFAULT CHARSET=latin1
   CONNECTION='mysql://root@127.0.0.1:$SLAVE_MYPORT/second_db/t1';
+INSERT INTO federated.urldb2t1 (id, name) values (1, 'federated.urldb2t1 -> second_db.t1, url format');
+SELECT * FROM federated.urldb2t1;
 
-INSERT INTO federated.old2 (id, name) values (1, 'federated.old2 url');
+DROP TABLE IF EXISTS federated.urldb2t2;
+--replace_result $SLAVE_MYPORT SLAVE_PORT
+eval CREATE TABLE federated.urldb2t2 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    )
+  ENGINE="FEDERATED" DEFAULT CHARSET=latin1
+  CONNECTION='mysql://root@127.0.0.1:$SLAVE_MYPORT/second_db/t2';
+INSERT INTO federated.urldb2t2 (id, name) values (1, 'federated.urldb2t2 -> second_db.t2, url format');
+SELECT * FROM federated.urldb2t2;
 
 DROP TABLE IF EXISTS federated.t1;
 CREATE TABLE federated.t1 (
@@ -84,17 +121,30 @@ CREATE TABLE federated.t1 (
   ENGINE="FEDERATED" DEFAULT CHARSET=latin1
   CONNECTION='server_one';
 
-INSERT INTO federated.t1 (id, name) values (1, 'server_one, new scheme');
+INSERT INTO federated.t1 (id, name) values (1, 'server_one, new scheme, first_db.t1');
 
 SELECT * FROM federated.t1;
 
+DROP TABLE IF EXISTS federated.whatever;
+CREATE TABLE federated.whatever (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    )
+  ENGINE="FEDERATED" DEFAULT CHARSET=latin1
+  CONNECTION='server_one/t1';
+INSERT INTO federated.whatever (id, name) values (1, 'server_one, new scheme, whatever, first_db.t1');
+SELECT * FROM federated.whatever;
+
 ALTER SERVER 'server_one' options(DATABASE 'second_db');
 
-flush tables;
+# FLUSH TABLES is now unneccessary
 
-INSERT INTO federated.t1 (id, name) values (1, 'server_two, new scheme');
+INSERT INTO federated.t1 (id, name) values (1, 'server_two, new scheme, second_db.t1');
 SELECT * FROM federated.t1;
 
+INSERT INTO federated.whatever (id, name) values (1, 'server_two, new scheme, whatever, second_db.t1');
+SELECT * FROM federated.whatever;
+
 drop table federated.t1;
 
 drop server 'server_one';
@@ -107,4 +157,166 @@ drop table second_db.t1;
 drop database first_db;
 drop database second_db;
 
+#
+# Bug#25671 - CREATE/DROP/ALTER SERVER should require privileges
+#
+# Changes to SERVER declarations should require SUPER privilege.
+# Based upon test case by Giuseppe Maxia
+
+create database db_legitimate;
+create database db_bogus;
+
+use db_legitimate;
+CREATE TABLE db_legitimate.t1 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    );
+INSERT INTO db_legitimate.t1 VALUES ('1','this is legitimate');
+
+use db_bogus;
+CREATE TABLE db_bogus.t1 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    )
+  ;
+INSERT INTO db_bogus.t1 VALUES ('2','this is bogus');
+
+connection master;
+--replace_result $SLAVE_MYPORT SLAVE_PORT
+eval create server 's1' foreign data wrapper 'mysql' options
+  (HOST '127.0.0.1',
+  DATABASE 'db_legitimate',
+  USER 'root',
+  PASSWORD '',
+  PORT $SLAVE_MYPORT,
+  SOCKET '',
+  OWNER 'root');
+
+create user guest_select@localhost;
+grant select on federated.* to guest_select@localhost;
+
+create user guest_super@localhost;
+grant select,SUPER,RELOAD on *.* to guest_super@localhost;
+
+create user guest_usage@localhost;
+grant usage on *.* to guest_usage@localhost;
+
+CREATE TABLE federated.t1 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    ) ENGINE = FEDERATED CONNECTION = 's1';
+
+select * from federated.t1;
+
+connect (conn_select,127.0.0.1,guest_select,,federated,$MASTER_MYPORT);
+connect (conn_usage,127.0.0.1,guest_usage,,,$MASTER_MYPORT);
+connect (conn_super,127.0.0.1,guest_super,,,$MASTER_MYPORT);
+
+connection conn_select;
+--error ER_SPECIFIC_ACCESS_DENIED_ERROR
+alter server s1 options (database 'db_bogus');
+
+connection master;
+flush tables;
+select * from federated.t1;
+
+connection conn_usage;
+--error ER_SPECIFIC_ACCESS_DENIED_ERROR
+alter server s1 options (database 'db_bogus');
+
+connection master;
+flush tables;
+select * from federated.t1;
+
+connection conn_super;
+alter server s1 options (database 'db_bogus');
+
+connection master;
+flush tables;
+select * from federated.t1;
+
+connection conn_select;
+--error ER_SPECIFIC_ACCESS_DENIED_ERROR
+drop server if exists 's1';
+--replace_result $SLAVE_MYPORT SLAVE_PORT
+--error ER_SPECIFIC_ACCESS_DENIED_ERROR
+eval create server 's1' foreign data wrapper 'mysql' options
+  (HOST '127.0.0.1',
+  DATABASE 'db_legitimate',
+  USER 'root',
+  PASSWORD '',
+  PORT $SLAVE_MYPORT,
+  SOCKET '',
+  OWNER 'root');
+
+connection conn_super;
+drop server 's1';
+--replace_result $SLAVE_MYPORT SLAVE_PORT
+eval create server 's1' foreign data wrapper 'mysql' options
+  (HOST '127.0.0.1',
+  DATABASE 'db_legitimate',
+  USER 'root',
+  PASSWORD '',
+  PORT $SLAVE_MYPORT,
+  SOCKET '',
+  OWNER 'root');
+
+connection master;
+flush tables;
+select * from federated.t1;
+
+# clean up test
+connection slave;
+drop database db_legitimate;
+drop database db_bogus;
+
+disconnect conn_select;
+disconnect conn_usage;
+disconnect conn_super;
+
+connection master;
+drop user guest_super@localhost;
+drop user guest_usage@localhost;
+drop user guest_select@localhost;
+drop table federated.t1;
+drop server 's1';
+
+
+--echo # End of 5.1 tests
+
+
+#
+# Bug#25721 - deadlock with ALTER/CREATE SERVER
+#
+connect (other,localhost,root,,);
+connection master;
+use test;
+delimiter //;
+create procedure p1 ()
+begin
+  DECLARE v INT DEFAULT 0;
+  DECLARE e INT DEFAULT 0;
+  DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET e = e + 1;
+  WHILE v < 10000 do
+    CREATE SERVER s
+      FOREIGN DATA WRAPPER mysql
+      OPTIONS (USER 'Remote', HOST '192.168.1.106', DATABASE 'test');
+    ALTER SERVER s OPTIONS (USER 'Remote');
+	DROP SERVER s;
+    SET v = v + 1;
+  END WHILE;
+  SELECT e > 0;
+END//
+delimiter ;//
+connection other;
+use test;
+send call p1();
+connection master;
+call p1();
+connection other;
+reap;
+drop procedure p1;
+drop server if exists s;
+
+
 source include/federated_cleanup.inc;
diff --git a/mysql-test/t/func_gconcat.test b/mysql-test/t/func_gconcat.test
index c141fd370f861e3a2f99df57b9acec7b69daf73e..431d582be5049ce43dd9a1a4998b2723982b8f6f 100644
--- a/mysql-test/t/func_gconcat.test
+++ b/mysql-test/t/func_gconcat.test
@@ -497,4 +497,14 @@ select f2,group_concat(f1) from t1 group by f2;
 --disable_metadata
 drop table t1;
 
-# End of 4.1 tests
+#
+# Bug #26815: Unexpected built-in function behavior: group_concat(distinct
+# substring_index())
+# 
+CREATE TABLE t1(a TEXT, b CHAR(20));
+INSERT INTO t1 VALUES ("one.1","one.1"),("two.2","two.2"),("one.3","one.3");
+SELECT GROUP_CONCAT(DISTINCT UCASE(a)) FROM t1;
+SELECT GROUP_CONCAT(DISTINCT UCASE(b)) FROM t1;
+DROP TABLE t1;
+
+--echo End of 5.0 tests
diff --git a/mysql-test/t/gis.test b/mysql-test/t/gis.test
index 9cf42070f2f4a00a65524e825d13460a968274b3..a3952dbc3da71bab10c3982e252f5848f9b9c5a9 100644
--- a/mysql-test/t/gis.test
+++ b/mysql-test/t/gis.test
@@ -424,6 +424,14 @@ from t1;
 
 drop table t1;
 
+#
+# Bug #27164: Crash when mixing InnoDB and MyISAM Geospatial tables
+#
+CREATE TABLE t1(a POINT) ENGINE=MyISAM;
+INSERT INTO t1 VALUES (NULL);
+SELECT * FROM t1;
+DROP TABLE t1;
+
 --echo End of 4.1 tests
 
 #
@@ -472,6 +480,18 @@ create table t1 (g geometry not null);
 insert into t1 values(default);
 drop table t1;
 
+#
+# Bug #27300: create view with geometry functions lost columns types 
+#
+CREATE TABLE t1 (a GEOMETRY);
+CREATE VIEW v1 AS SELECT GeomFromwkb(ASBINARY(a)) FROM t1;
+CREATE VIEW v2 AS SELECT a FROM t1;
+DESCRIBE v1;
+DESCRIBE v2;
+
+DROP VIEW v1,v2;
+DROP TABLE t1;
+
 #
 # Bug #11335 View redefines column types
 #
diff --git a/mysql-test/t/group_by.test b/mysql-test/t/group_by.test
index a331874576436baa7622929570a69e8acddb9e9d..fb9c09d47638b11f1337102b3cbf90c11d6557e1 100644
--- a/mysql-test/t/group_by.test
+++ b/mysql-test/t/group_by.test
@@ -755,7 +755,8 @@ SET SQL_MODE = '';
 
 #
 # Bug #21174: Index degrades sort performance and 
-#             optimizer does not honor IGNORE INDEX
+#             optimizer does not honor IGNORE INDEX.
+#             a.k.a WL3527.
 #
 CREATE TABLE t1 (a INT, b INT,
                  PRIMARY KEY (a),
@@ -819,4 +820,8 @@ EXPLAIN SELECT a, SUM(b) FROM t2 IGNORE INDEX (a) GROUP BY a LIMIT 2;
 EXPLAIN SELECT 1 FROM t2 WHERE a IN
   (SELECT a FROM t1 USE INDEX (i2) IGNORE INDEX (i2));
 
+SHOW VARIABLES LIKE 'old';  
+--error ER_INCORRECT_GLOBAL_LOCAL_VAR
+SET @@old = off;  
+
 DROP TABLE t1, t2;
diff --git a/mysql-test/t/heap_btree.test b/mysql-test/t/heap_btree.test
index 68aa79834fc8dc4cf6fc0eaef5e5959d8ef1ad74..4e7102806d6fd29317373aa046b8e0a72be6a1ce 100644
--- a/mysql-test/t/heap_btree.test
+++ b/mysql-test/t/heap_btree.test
@@ -182,6 +182,37 @@ delete from t1 where a >= 2;
 select a from t1 order by a;
 drop table t1;
 
+#
+# Bug#26996 - Update of a Field in a Memory Table ends with wrong result
+#
+CREATE TABLE t1 (
+  c1 CHAR(3),
+  c2 INTEGER,
+  KEY USING BTREE(c1),
+  KEY USING BTREE(c2)
+) ENGINE= MEMORY;
+INSERT INTO t1 VALUES ('ABC',0), ('A',0), ('B',0), ('C',0);
+UPDATE t1 SET c2= c2 + 1 WHERE c1 = 'A';
+SELECT * FROM t1;
+DROP TABLE t1;
+
+#
+# Bug#24985 - UTF8 ENUM primary key on MEMORY using BTREE
+#             causes incorrect duplicate entries
+#
+CREATE TABLE t1 (
+  c1 ENUM('1', '2'),
+  UNIQUE USING BTREE(c1)
+) ENGINE= MEMORY DEFAULT CHARSET= utf8;
+INSERT INTO t1 VALUES('1'), ('2');
+DROP TABLE t1;
+CREATE TABLE t1 (
+  c1 SET('1', '2'),
+  UNIQUE USING BTREE(c1)
+) ENGINE= MEMORY DEFAULT CHARSET= utf8;
+INSERT INTO t1 VALUES('1'), ('2');
+DROP TABLE t1;
+
 --echo End of 4.1 tests
 
 #
@@ -205,3 +236,4 @@ INSERT INTO t1 VALUES(NULL),(NULL);
 DROP TABLE t1;
 
 --echo End of 5.0 tests
+
diff --git a/mysql-test/t/insert_update.test b/mysql-test/t/insert_update.test
index 1ed1e8657acb64624513bfade26bbae24c27c269..f0d87ea956d68cabc118727058d7ebd7417dd1f2 100644
--- a/mysql-test/t/insert_update.test
+++ b/mysql-test/t/insert_update.test
@@ -195,3 +195,55 @@ SELECT LAST_INSERT_ID();
 INSERT t1 (f2) VALUES ('test') ON DUPLICATE KEY UPDATE f1 = LAST_INSERT_ID(f1);
 SELECT LAST_INSERT_ID();
 DROP TABLE t1;
+
+#
+# Bug#23233: 0 as LAST_INSERT_ID() after INSERT .. ON DUPLICATE in the
+#            NO_AUTO_VALUE_ON_ZERO mode.
+#
+SET SQL_MODE='NO_AUTO_VALUE_ON_ZERO';
+CREATE TABLE `t1` (
+  `id` int(11) PRIMARY KEY auto_increment,
+  `f1` varchar(10) NOT NULL UNIQUE
+);
+INSERT IGNORE INTO t1 (f1) VALUES ("test1")
+	ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+INSERT IGNORE INTO t1 (f1) VALUES ("test1")
+	ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+SELECT * FROM t1;
+INSERT IGNORE INTO t1 (f1) VALUES ("test2")
+	ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT * FROM t1;
+INSERT IGNORE INTO t1 (f1) VALUES ("test2")
+	ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+SELECT * FROM t1;
+INSERT IGNORE INTO t1 (f1) VALUES ("test3")
+	ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+SELECT * FROM t1;
+DROP TABLE t1;
+CREATE TABLE `t1` (
+  `id` int(11) PRIMARY KEY auto_increment,
+  `f1` varchar(10) NOT NULL UNIQUE
+);
+INSERT IGNORE INTO t1 (f1) VALUES ("test1")
+	ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+SELECT * FROM t1;
+INSERT IGNORE INTO t1 (f1) VALUES ("test1"),("test4")
+	ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id);
+SELECT LAST_INSERT_ID();
+SELECT * FROM t1;
+DROP TABLE t1;
+CREATE TABLE `t1` (
+  `id` int(11) PRIMARY KEY auto_increment,
+  `f1` varchar(10) NOT NULL UNIQUE,
+  tim1 timestamp default '2003-01-01 00:00:00' on update current_timestamp
+);
+INSERT INTO t1 (f1) VALUES ("test1");
+SELECT id, f1 FROM t1;
+REPLACE INTO t1 VALUES (0,"test1",null);
+SELECT id, f1 FROM t1;
+DROP TABLE t1;
+SET SQL_MODE='';
diff --git a/mysql-test/t/myisam.test b/mysql-test/t/myisam.test
index 4281030fc3cea7244998475639d891b30c03206a..8f7357d1c9803fecd73fcac63b125f8e2a1027f8 100644
--- a/mysql-test/t/myisam.test
+++ b/mysql-test/t/myisam.test
@@ -874,6 +874,150 @@ CREATE TABLE t1 (c1 TEXT) AVG_ROW_LENGTH=70100 MAX_ROWS=4100100100;
 SHOW TABLE STATUS LIKE 't1';
 DROP TABLE t1;
 
+#
+# Bug#26231 - select count(*) on myisam table returns wrong value
+#             when index is used
+#
+CREATE TABLE t1 (c1 TEXT NOT NULL, KEY c1 (c1(10))) ENGINE=MyISAM;
+# Fill at least two key blocks. "Tab, A" must be in both blocks. 
+INSERT INTO t1 VALUES
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)), (CHAR(9,65)),
+  (''), (''), (''), (''),
+  (' B'), (' B'), (' B'), (' B');
+SELECT DISTINCT COUNT(*) FROM t1 WHERE c1 = '';
+SELECT DISTINCT length(c1), c1 FROM t1 WHERE c1 = '';
+SELECT DISTINCT COUNT(*) FROM t1 IGNORE INDEX (c1) WHERE c1 = '';
+SELECT DISTINCT length(c1), c1 FROM t1 IGNORE INDEX (c1) WHERE c1 = '';
+SELECT DISTINCT length(c1), c1 FROM t1 ORDER BY c1;
+DROP TABLE t1;
+
 --echo End of 4.1 tests
 
 
diff --git a/mysql-test/t/range.test b/mysql-test/t/range.test
index b1cec049ab24c6f2ff1c0db5a2453bc95785e545..06c2ef248c43825ccff1c480071e6382c14cc14d 100644
--- a/mysql-test/t/range.test
+++ b/mysql-test/t/range.test
@@ -568,6 +568,149 @@ SELECT s.oxid FROM t1 v, t1 s
 
 DROP TABLE t1;
 
+# BUG#26624 high mem usage (crash) in range optimizer (depends on order of fields in where)
+create table t1 (
+  c1  char(10), c2  char(10), c3  char(10), c4  char(10),
+  c5  char(10), c6  char(10), c7  char(10), c8  char(10),
+  c9  char(10), c10 char(10), c11 char(10), c12 char(10),
+  c13 char(10), c14 char(10), c15 char(10), c16 char(10),
+  index(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12,c13,c14,c15,c16)
+);
+insert into t1 (c1) values ('1'),('1'),('1'),('1');
+
+# This must run without crash and fast:
+select * from t1 where
+     c1 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4",
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c2 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c3 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c4 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5", 
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c5 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4",
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c6 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4",
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c7 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c8 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c9 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC")
+ and c10 in ("abcdefgh", "123456789", "qwertyuio", "asddfgh", 
+            "abcdefg1", "123456781", "qwertyui1", "asddfg1", 
+            "abcdefg2", "123456782", "qwertyui2", "asddfg2", 
+            "abcdefg3", "123456783", "qwertyui3", "asddfg3", 
+            "abcdefg4", "123456784", "qwertyui4", "asddfg4", 
+            "abcdefg5", "123456785", "qwertyui5", "asddfg5",
+            "abcdefg6", "123456786", "qwertyui6", "asddfg6",
+            "abcdefg7", "123456787", "qwertyui7", "asddfg7",
+            "abcdefg8", "123456788", "qwertyui8", "asddfg8",
+            "abcdefg9", "123456789", "qwertyui9", "asddfg9",
+            "abcdefgA", "12345678A", "qwertyuiA", "asddfgA",
+            "abcdefgB", "12345678B", "qwertyuiB", "asddfgB",
+            "abcdefgC", "12345678C", "qwertyuiC", "asddfgC");
+drop table t1;
 --echo End of 4.1 tests
 
 #
diff --git a/mysql-test/t/rpl_ddl.test b/mysql-test/t/rpl_ddl.test
index ca1c25c5f090debc14e894de35b8dc7fb9212654..80df16a7a004494b16d28ee727da6db261e7e323 100644
--- a/mysql-test/t/rpl_ddl.test
+++ b/mysql-test/t/rpl_ddl.test
@@ -22,13 +22,11 @@
 #         effects like failing 'sync_slave_with_master', crashes of the slave or
 #         abort of the test case etc..
 #
-#      3. The assignment of the DDL command to be tested to $my_stmt can
-#         be a bit difficult. "'" must be avoided, because the test
-#        routine "include/rpl_stmt_seq.inc" performs a
-#         eval SELECT CONCAT('######## ','$my_stmt','  ########') as "";
-#
 --source include/not_ndb_default.inc
---source include/have_innodb.inc
 --source include/master-slave.inc
-let $engine_type= "InnoDB";
+--source include/have_innodb.inc
+let $engine_type= InnoDB;
+let $temp_engine_type= MEMORY;
+let $show_binlog = 0;
+let $manipulate = 0;
 -- source extra/rpl_tests/rpl_ddl.test
diff --git a/mysql-test/t/rpl_incident-master.opt b/mysql-test/t/rpl_incident-master.opt
new file mode 100644
index 0000000000000000000000000000000000000000..912801debc405dbf07089ebc8bdc241c92254bfe
--- /dev/null
+++ b/mysql-test/t/rpl_incident-master.opt
@@ -0,0 +1 @@
+--loose-debug=+d,incident_database_resync_on_replace
diff --git a/mysql-test/t/rpl_incident.test b/mysql-test/t/rpl_incident.test
index 9c30d29b6fde7d2b31aedcafd5fc91210aed0cf4..c52f26317ade5fe256818e4188b686db832e2989 100644
--- a/mysql-test/t/rpl_incident.test
+++ b/mysql-test/t/rpl_incident.test
@@ -7,13 +7,9 @@ CREATE TABLE t1 (a INT);
 INSERT INTO t1 VALUES (1),(2),(3);
 SELECT * FROM t1;
 
-SET @saved = @@debug;
-SET SESSION debug="d,incident_database_resync_on_replace";
-
 # This will generate an incident log event and store it in the binary
 # log before the replace statement.
 REPLACE INTO t1 VALUES (4);
-SET SESSION debug=@saved;
 --save_master_pos
 SELECT * FROM t1;
 
diff --git a/mysql-test/t/rpl_ndb_ddl.test b/mysql-test/t/rpl_ndb_ddl.test
index 0c503e56c9c96cdc610942fb1f6c6cc968bdda61..ca7a4ce496879979b68d510d2c676bac60d0c1d2 100644
--- a/mysql-test/t/rpl_ndb_ddl.test
+++ b/mysql-test/t/rpl_ndb_ddl.test
@@ -1,4 +1,4 @@
-######################## rpl_ddl.test ########################
+#################### rpl_ndb_ddl.test ########################
 #                                                            #
 # DDL statements (sometimes with implicit COMMIT) executed   #
 # by the master and it's propagation into the slave          #
@@ -22,14 +22,11 @@
 #         effects like failing 'sync_slave_with_master', crashes of the slave or
 #         abort of the test case etc..
 #
-#      3. The assignment of the DDL command to be tested to $my_stmt can
-#         be a bit difficult. "'" must be avoided, because the test
-#         routine "include/rpl_stmt_seq.inc" performs a
-#         eval SELECT CONCAT('######## ','$my_stmt','  ########') as "";
-#
 
---source include/have_ndb.inc
 --source include/master-slave.inc
-let $engine_type= "NDB";
--- source extra/rpl_tests/rpl_ndb_ddl.test
-
+--source include/have_ndb.inc
+let $engine_type= NDB;
+let $temp_engine_type= MEMORY;
+let $show_binlog = 0;
+let $manipulate = 0;
+-- source extra/rpl_tests/rpl_ddl.test
diff --git a/mysql-test/t/rpl_row_create_table.test b/mysql-test/t/rpl_row_create_table.test
index e00494a3a1330891994252da2a3adf3b4ad633c4..d1b26f9e3f418244d69605217f859e0418d2493c 100644
--- a/mysql-test/t/rpl_row_create_table.test
+++ b/mysql-test/t/rpl_row_create_table.test
@@ -21,7 +21,7 @@ DROP TABLE IF EXISTS t1,t2,t3,t4,t5,t6,t7,t8,t9;
 # Set the default storage engine to different values on master and
 # slave. We need to stop the slave for the server variable to take
 # effect, since the variable is only read on start-up.
-connection slave;
+sync_slave_with_master;
 --disable_query_log
 set @storage_engine = @@global.storage_engine;
 STOP SLAVE;
diff --git a/mysql-test/t/sp-code.test b/mysql-test/t/sp-code.test
index 97bc29fcad28b610b148e84fc6caddb710e186a4..1b33680cfaf903df8308019ec985b3cb8d5a9958 100644
--- a/mysql-test/t/sp-code.test
+++ b/mysql-test/t/sp-code.test
@@ -447,3 +447,21 @@ DROP PROCEDURE p1;
 
 
 --echo End of 5.0 tests.
+
+#
+# Bug #26303: reserve() not called before qs_append() may lead to buffer
+# overflow
+#
+DELIMITER //;
+CREATE PROCEDURE p1() 
+BEGIN 
+  DECLARE dummy int default 0;
+
+  CASE 12 
+    WHEN 12 
+    THEN SET dummy = 0;
+  END CASE;
+END//
+DELIMITER ;//
+SHOW PROCEDURE CODE p1;
+DROP PROCEDURE p1;
diff --git a/mysql-test/t/subselect.test b/mysql-test/t/subselect.test
index 0f42b3e06a5419757e2aa1f0bf4c1b14467bf70a..88c34bdb9b92e9c5f240884b665c0c160bc8a127 100644
--- a/mysql-test/t/subselect.test
+++ b/mysql-test/t/subselect.test
@@ -2765,6 +2765,50 @@ SELECT COUNT(*), a
 DROP TABLE t1,t2;
 
 #
+# Bug #27229: GROUP_CONCAT in subselect with COUNT() as an argument 
+#  
+
+CREATE TABLE t1 (a int, b int);
+CREATE TABLE t2 (m int, n int);
+INSERT INTO t1 VALUES (2,2), (2,2), (3,3), (3,3), (3,3), (4,4);
+INSERT INTO t2 VALUES (1,11), (2,22), (3,32), (4,44), (4,44);
+
+SELECT COUNT(*) c, a,
+       (SELECT GROUP_CONCAT(COUNT(a)) FROM t2 WHERE m = a)
+  FROM t1 GROUP BY a;
+
+SELECT COUNT(*) c, a,
+       (SELECT GROUP_CONCAT(COUNT(a)+1) FROM t2 WHERE m = a)
+  FROM t1 GROUP BY a;
+
+DROP table t1,t2;
+
+#
+# Bug #27348: SET FUNCTION used in  a subquery from WHERE condition 
+#  
+
+CREATE TABLE t1 (a int, b int);
+INSERT INTO t1 VALUES (2,22),(1,11),(2,22);
+
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 0 GROUP BY a;
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 1 GROUP BY a;
+
+SELECT a FROM t1 t0
+  WHERE (SELECT COUNT(t0.b) FROM t1 t WHERE t.b>20) GROUP BY a;
+
+SET @@sql_mode='ansi';
+--error 1111
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 0 GROUP BY a;
+--error 1111
+SELECT a FROM t1 WHERE (SELECT COUNT(b) FROM DUAL) > 1 GROUP BY a;
+
+--error 1111
+SELECT a FROM t1 t0
+  WHERE (SELECT COUNT(t0.b) FROM t1 t WHERE t.b>20) GROUP BY a;
+
+SET @@sql_mode=default;
+DROP TABLE t1;
+
 # Bug#20835 (literal string with =any values)
 #
 CREATE TABLE t1 (s1 char(1));
diff --git a/mysql-test/t/subselect3.test b/mysql-test/t/subselect3.test
index e3703c0da1671f97eb23d970fc0758413e7e1d06..e8eae3e2452a37f98684fae51dc391707c076e9a 100644
--- a/mysql-test/t/subselect3.test
+++ b/mysql-test/t/subselect3.test
@@ -507,8 +507,9 @@ SELECT a, MAX(b), (SELECT t.c FROM t1 AS t WHERE t1.a=t.a AND t.b=MAX(t1.b))
 SELECT * FROM t1 GROUP by t1.a
   HAVING (MAX(t1.b) > (SELECT MAX(t2.b) FROM t2 WHERE t2.c < t1.c
                                                 HAVING MAX(t2.b+t1.a) < 10));
-SELECT a, AVG(b), (SELECT t.c FROM t1 AS t WHERE t1.a=t.a AND t.b=AVG(t1.b))
-  AS test FROM t1 GROUP BY a;
+#FIXME: Enable this test after fixing bug #27321
+#SELECT a, AVG(b), (SELECT t.c FROM t1 AS t WHERE t1.a=t.a AND t.b=AVG(t1.b))
+#  AS test FROM t1 GROUP BY a;
 
 SELECT a,b,c FROM t1 WHERE b in (9,3,4) ORDER BY b,c;
 
diff --git a/mysys/my_pread.c b/mysys/my_pread.c
index 7a09c21e0392290eed8260269e84f9fa7893fbe5..f8f0fa49c10f04b66991b76334bc0fc496d6318b 100644
--- a/mysys/my_pread.c
+++ b/mysys/my_pread.c
@@ -37,7 +37,7 @@ uint my_pread(File Filedes, byte *Buffer, uint Count, my_off_t offset,
     errno=0;					/* Linux doesn't reset this */
 #endif
 #ifndef HAVE_PREAD
-    off_t old_offset;
+    os_off_t old_offset;
 
     pthread_mutex_lock(&my_file_info[Filedes].mutex);
     /*
@@ -45,7 +45,7 @@ uint my_pread(File Filedes, byte *Buffer, uint Count, my_off_t offset,
       before seeking to the given offset
     */
 
-    error= (old_offset= (off_t)lseek(Filedes, 0L, MY_SEEK_CUR)) == -1L ||
+    error= (old_offset= lseek(Filedes, 0L, MY_SEEK_CUR)) == -1L ||
            lseek(Filedes, offset, MY_SEEK_SET) == -1L;
 
     if (!error)                                 /* Seek was successful */
@@ -116,7 +116,7 @@ uint my_pwrite(int Filedes, const byte *Buffer, uint Count, my_off_t offset,
   {
 #ifndef HAVE_PREAD
     int error= 0;
-    off_t old_offset;
+    os_off_t old_offset;
     writenbytes= (uint) -1;
     pthread_mutex_lock(&my_file_info[Filedes].mutex);
 
@@ -124,7 +124,7 @@ uint my_pwrite(int Filedes, const byte *Buffer, uint Count, my_off_t offset,
       As we cannot change the file pointer, we save the old position,
       before seeking to the given offset
     */
-    error= ((old_offset= (off_t)lseek(Filedes, 0L, MY_SEEK_CUR)) == -1L ||
+    error= ((old_offset= lseek(Filedes, 0L, MY_SEEK_CUR)) == -1L ||
             lseek(Filedes, offset, MY_SEEK_SET) == -1L);
 
     if (!error)                                 /* Seek was successful */
diff --git a/mysys/my_pthread.c b/mysys/my_pthread.c
index db01602f4ab4062d0d17f4287fde123adbd868fa..d8182b67442aafeb2b0700c849069b1ab513fd35 100644
--- a/mysys/my_pthread.c
+++ b/mysys/my_pthread.c
@@ -29,8 +29,6 @@
 #define SCHED_POLICY SCHED_OTHER
 #endif
 
-uint thd_lib_detected= 0;
-
 uint thd_lib_detected;
 
 #ifndef my_pthread_setprio
diff --git a/mysys/my_redel.c b/mysys/my_redel.c
index 606d301e1d007d1b0dc9e6aa2a4d3d60e1290e7b..b12cf098283694c417c25dd5ac712f89b0628544 100644
--- a/mysys/my_redel.c
+++ b/mysys/my_redel.c
@@ -59,7 +59,7 @@ int my_redel(const char *org_name, const char *tmp_name, myf MyFlags)
 		  MyFlags))
       goto end;
   }
-  else if (my_delete(org_name,MyFlags))
+  else if (my_delete_allow_opened(org_name, MyFlags))
       goto end;
   if (my_rename(tmp_name,org_name,MyFlags))
     goto end;
diff --git a/sql/events.cc b/sql/events.cc
index 5931c0a95d47914786a194d39e1a3590a35f823a..df2f1124f38dc4ba5fae00239cf5c63c50e626e9 100644
--- a/sql/events.cc
+++ b/sql/events.cc
@@ -351,7 +351,7 @@ Events::create_event(THD *thd, Event_parse_data *parse_data, bool if_not_exists)
     else /* Binlog the create event. */
     {
       event_queue->create_event(thd, new_element);
-      if (mysql_bin_log.is_open())
+      if (mysql_bin_log.is_open() && (thd->query_length > 0))
       {
         thd->clear_error();
         thd->binlog_query(THD::MYSQL_QUERY_TYPE,
@@ -426,7 +426,7 @@ Events::update_event(THD *thd, Event_parse_data *parse_data, sp_name *rename_to)
     {
       event_queue->update_event(thd, parse_data->dbname, parse_data->name,
                                 new_element);
-      if (mysql_bin_log.is_open())
+      if (mysql_bin_log.is_open() && (thd->query_length > 0))
       {
         thd->clear_error();
         thd->binlog_query(THD::MYSQL_QUERY_TYPE,
@@ -480,7 +480,7 @@ Events::drop_event(THD *thd, LEX_STRING dbname, LEX_STRING name, bool if_exists)
   {
     event_queue->drop_event(thd, dbname, name);
     /* Binlog the drop event. */
-    if (mysql_bin_log.is_open())
+    if (mysql_bin_log.is_open() && (thd->query_length > 0))
     {
       thd->clear_error();
       thd->binlog_query(THD::MYSQL_QUERY_TYPE,
diff --git a/sql/field.h b/sql/field.h
index ac168c1b650acaa1730b716eb1b5f3eda54fc715..b2169dac5b603154d50b2083cb557b74ca4b6fdf 100644
--- a/sql/field.h
+++ b/sql/field.h
@@ -1353,7 +1353,7 @@ public:
   int  store_decimal(const my_decimal *);
   void get_key_image(char *buff,uint length,imagetype type);
   uint size_of() const { return sizeof(*this); }
-  int  reset(void) { return !maybe_null(); }
+  int  reset(void) { return !maybe_null() || Field_blob::reset(); }
 };
 #endif /*HAVE_SPATIAL*/
 
diff --git a/sql/field_conv.cc b/sql/field_conv.cc
index 88d3661566889b20fdddc4b810925d0581f738da..a718a4028975541bcc0b4e2a963bb7e8b82dbe7a 100644
--- a/sql/field_conv.cc
+++ b/sql/field_conv.cc
@@ -173,7 +173,7 @@ set_field_to_null_with_conversions(Field *field, bool no_conversions)
   if (field == field->table->next_number_field)
   {
     field->table->auto_increment_field_not_null= FALSE;
-    return 0;					// field is set in handler.cc
+    return 0;				  // field is set in fill_record()
   }
   if (field->table->in_use->count_cuted_fields == CHECK_FIELD_WARN)
   {
diff --git a/sql/ha_ndbcluster_binlog.cc b/sql/ha_ndbcluster_binlog.cc
index 060bc0beff4069b468feffe5b928b4443591c297..074e71671c7f2ad42bb490d015857935b0167562 100644
--- a/sql/ha_ndbcluster_binlog.cc
+++ b/sql/ha_ndbcluster_binlog.cc
@@ -500,7 +500,7 @@ static int ndbcluster_reset_logs(THD *thd)
 static int
 ndbcluster_binlog_index_purge_file(THD *thd, const char *file)
 {
-  if (!ndb_binlog_running)
+  if (!ndb_binlog_running || thd->slave_thread)
     return 0;
 
   DBUG_ENTER("ndbcluster_binlog_index_purge_file");
diff --git a/sql/handler.cc b/sql/handler.cc
index 0ecfce9349eb897ac3f920a122ca2ffc5e780960..617bf9ee378cef9378f274be3af865ff1111a943 100644
--- a/sql/handler.cc
+++ b/sql/handler.cc
@@ -1753,7 +1753,6 @@ int handler::update_auto_increment()
   bool append= FALSE;
   THD *thd= table->in_use;
   struct system_variables *variables= &thd->variables;
-  bool auto_increment_field_not_null;
   DBUG_ENTER("handler::update_auto_increment");
 
   /*
@@ -1761,11 +1760,9 @@ int handler::update_auto_increment()
     than the interval, but not smaller.
   */
   DBUG_ASSERT(next_insert_id >= auto_inc_interval_for_cur_row.minimum());
-  auto_increment_field_not_null= table->auto_increment_field_not_null;
-  table->auto_increment_field_not_null= FALSE; // to reset for next row
 
   if ((nr= table->next_number_field->val_int()) != 0 ||
-      auto_increment_field_not_null &&
+      table->auto_increment_field_not_null &&
       thd->variables.sql_mode & MODE_NO_AUTO_VALUE_ON_ZERO)
   {
     /*
diff --git a/sql/item.cc b/sql/item.cc
index c79356071306a7096c21fb4991ead95d2d6b461c..613b72ad05ead046afb8853b3edaaf7a136328ff 100644
--- a/sql/item.cc
+++ b/sql/item.cc
@@ -1088,7 +1088,7 @@ bool Item_splocal::set_value(THD *thd, sp_rcontext *ctx, Item **it)
   Item_case_expr methods
 *****************************************************************************/
 
-Item_case_expr::Item_case_expr(int case_expr_id)
+Item_case_expr::Item_case_expr(uint case_expr_id)
   :Item_sp_variable( C_STRING_WITH_LEN("case_expr")),
    m_case_expr_id(case_expr_id)
 {
@@ -1125,6 +1125,8 @@ Item_case_expr::this_item_addr(THD *thd, Item **)
 
 void Item_case_expr::print(String *str)
 {
+  if (str->reserve(MAX_INT_WIDTH + sizeof("case_expr@")))
+    return;                                    /* purecov: inspected */
   VOID(str->append(STRING_WITH_LEN("case_expr@")));
   str->qs_append(m_case_expr_id);
 }
@@ -1289,15 +1291,18 @@ void Item::split_sum_func2(THD *thd, Item **ref_pointer_array,
       Exception is Item_direct_view_ref which we need to convert to
       Item_ref to allow fields from view being stored in tmp table.
     */
+    Item_aggregate_ref *item_ref;
     uint el= fields.elements;
-    Item *new_item, *real_itm= real_item();
+    Item *real_itm= real_item();
 
     ref_pointer_array[el]= real_itm;
-    if (!(new_item= new Item_aggregate_ref(&thd->lex->current_select->context,
+    if (!(item_ref= new Item_aggregate_ref(&thd->lex->current_select->context,
                                            ref_pointer_array + el, 0, name)))
       return;                                   // fatal_error is set
+    if (type() == SUM_FUNC_ITEM)
+      item_ref->depended_from= ((Item_sum *) this)->depended_from(); 
     fields.push_front(real_itm);
-    thd->change_item_tree(ref, new_item);
+    thd->change_item_tree(ref, item_ref);
   }
 }
 
@@ -4358,13 +4363,16 @@ Field *Item::tmp_table_field_from_field_type(TABLE *table, bool fixed_length)
   case MYSQL_TYPE_MEDIUM_BLOB:
   case MYSQL_TYPE_LONG_BLOB:
   case MYSQL_TYPE_BLOB:
-  case MYSQL_TYPE_GEOMETRY:
     if (this->type() == Item::TYPE_HOLDER)
       field= new Field_blob(max_length, maybe_null, name, collation.collation,
                             1);
     else
       field= new Field_blob(max_length, maybe_null, name, collation.collation);
     break;					// Blob handled outside of case
+  case MYSQL_TYPE_GEOMETRY:
+    return new Field_geom(max_length, maybe_null, name, table->s,
+                          (Field::geometry_type)
+                          ((Item_geometry_func *)this)->get_geometry_type());
   }
   if (field)
     field->init(table);
diff --git a/sql/item.h b/sql/item.h
index 87380b53bfb9e081dcd9dae9ebd5722d13958737..bf662b987329e025a19ffb9d4adef442a218436c 100644
--- a/sql/item.h
+++ b/sql/item.h
@@ -1116,7 +1116,7 @@ inline Item_result Item_splocal::result_type() const
 class Item_case_expr :public Item_sp_variable
 {
 public:
-  Item_case_expr(int case_expr_id);
+  Item_case_expr(uint case_expr_id);
 
 public:
   Item *this_item();
@@ -1135,7 +1135,7 @@ public:
   void print(String *str);
 
 private:
-  int m_case_expr_id;
+  uint m_case_expr_id;
 };
 
 /*****************************************************************************
diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc
index a011a2884c810f4fe947fc72f9e04e5a1b0f0098..e6f951bfc7bbcc447a180d79c842642ccbeba1f9 100644
--- a/sql/item_strfunc.cc
+++ b/sql/item_strfunc.cc
@@ -1813,7 +1813,8 @@ void Item_func_soundex::fix_length_and_dec()
 {
   collation.set(args[0]->collation);
   max_length=args[0]->max_length;
-  set_if_bigger(max_length,4);
+  set_if_bigger(max_length, 4 * collation.collation->mbminlen);
+  tmp_value.set_charset(collation.collation);
 }
 
 
@@ -1823,14 +1824,15 @@ void Item_func_soundex::fix_length_and_dec()
   else return 0
 */
 
-static char soundex_toupper(char ch)
+static int soundex_toupper(int ch)
 {
   return (ch >= 'a' && ch <= 'z') ? ch - 'a' + 'A' : ch;
 }
 
-static char get_scode(char *ptr)
+
+static char get_scode(int wc)
 {
-  uchar ch= soundex_toupper(*ptr);
+  int ch= soundex_toupper(wc);
   if (ch < 'A' || ch > 'Z')
   {
 					// Thread extended alfa (country spec)
@@ -1840,46 +1842,121 @@ static char get_scode(char *ptr)
 }
 
 
+static bool my_uni_isalpha(int wc)
+{
+  /*
+    Return true for all Basic Latin letters: a..z A..Z.
+    Return true for all Unicode characters with code higher than U+00C0:
+    - characters between 'z' and U+00C0 are controls and punctuations.
+    - "U+00C0 LATIN CAPITAL LETTER A WITH GRAVE" is the first letter after 'z'.
+  */
+  return (wc >= 'a' && wc <= 'z') ||
+         (wc >= 'A' && wc <= 'Z') ||
+         (wc >= 0xC0);
+}
+
+
 String *Item_func_soundex::val_str(String *str)
 {
   DBUG_ASSERT(fixed == 1);
   String *res  =args[0]->val_str(str);
   char last_ch,ch;
   CHARSET_INFO *cs= collation.collation;
+  my_wc_t wc;
+  uint nchars;
+  int rc;
 
-  if ((null_value=args[0]->null_value))
+  if ((null_value= args[0]->null_value))
     return 0; /* purecov: inspected */
 
-  if (tmp_value.alloc(max(res->length(),4)))
+  if (tmp_value.alloc(max(res->length(), 4 * cs->mbminlen)))
     return str; /* purecov: inspected */
   char *to= (char *) tmp_value.ptr();
-  char *from= (char *) res->ptr(), *end=from+res->length();
-  tmp_value.set_charset(cs);
+  char *to_end= to + tmp_value.alloced_length();
+  char *from= (char *) res->ptr(), *end= from + res->length();
   
-  while (from != end && !my_isalpha(cs,*from)) // Skip pre-space
-    from++; /* purecov: inspected */
-  if (from == end)
-    return &my_empty_string;		// No alpha characters.
-  *to++ = soundex_toupper(*from);	// Copy first letter
-  last_ch = get_scode(from);		// code of the first letter
-					// for the first 'double-letter check.
-					// Loop on input letters until
-					// end of input (null) or output
-					// letter code count = 3
-  for (from++ ; from < end ; from++)
-  {
-    if (!my_isalpha(cs,*from))
-      continue;
-    ch=get_scode(from);
+  for ( ; ; ) /* Skip pre-space */
+  {
+    if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
+      return &my_empty_string; /* EOL or invalid byte sequence */
+    
+    if (rc == 1 && cs->ctype)
+    {
+      /* Single byte letter found */
+      if (my_isalpha(cs, *from))
+      {
+        last_ch= get_scode(*from);       // Code of the first letter
+        *to++= soundex_toupper(*from++); // Copy first letter
+        break;
+      }
+      from++;
+    }
+    else
+    {
+      from+= rc;
+      if (my_uni_isalpha(wc))
+      {
+        /* Multibyte letter found */
+        wc= soundex_toupper(wc);
+        last_ch= get_scode(wc);     // Code of the first letter
+        if ((rc= cs->cset->wc_mb(cs, wc, (uchar*) to, (uchar*) to_end)) <= 0)
+        {
+          /* Extra safety - should not really happen */
+          DBUG_ASSERT(false);
+          return &my_empty_string;
+        }
+        to+= rc;
+        break;
+      }
+    }
+  }
+  
+  /*
+     last_ch is now set to the first 'double-letter' check.
+     loop on input letters until end of input
+  */
+  for (nchars= 1 ; ; )
+  {
+    if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
+      break; /* EOL or invalid byte sequence */
+
+    if (rc == 1 && cs->ctype)
+    {
+      if (!my_isalpha(cs, *from++))
+        continue;
+    }
+    else
+    {
+      from+= rc;
+      if (!my_uni_isalpha(wc))
+        continue;
+    }
+    
+    ch= get_scode(wc);
     if ((ch != '0') && (ch != last_ch)) // if not skipped or double
     {
-       *to++ = ch;			// letter, copy to output
-       last_ch = ch;			// save code of last input letter
-    }					// for next double-letter check
+      // letter, copy to output
+      if ((rc= cs->cset->wc_mb(cs, (my_wc_t) ch,
+                               (uchar*) to, (uchar*) to_end)) <= 0)
+      {
+        // Extra safety - should not really happen
+        DBUG_ASSERT(false);
+        break;
+      }
+      to+= rc;
+      nchars++;
+      last_ch= ch;  // save code of last input letter
+    }               // for next double-letter check
   }
-  for (end=(char*) tmp_value.ptr()+4 ; to < end ; to++)
-    *to = '0';
-  *to=0;				// end string
+  
+  /* Pad up to 4 characters with DIGIT ZERO, if the string is shorter */
+  if (nchars < 4) 
+  {
+    uint nbytes= (4 - nchars) * cs->mbminlen;
+    cs->cset->fill(cs, to, nbytes, '0');
+    to+= nbytes;
+  }
+
   tmp_value.length((uint) (to-tmp_value.ptr()));
   return &tmp_value;
 }
diff --git a/sql/item_sum.cc b/sql/item_sum.cc
index cd67f83af1725746862e6314da125cbef7702840..7c3762d4785cab959097adc2ceff9fdafde0b018 100644
--- a/sql/item_sum.cc
+++ b/sql/item_sum.cc
@@ -61,9 +61,9 @@ bool Item_sum::init_sum_func_check(THD *thd)
   /* Save a pointer to object to be used in items for nested set functions */
   thd->lex->in_sum_func= this;
   nest_level= thd->lex->current_select->nest_level;
-  nest_level_tables_count= thd->lex->current_select->join->tables;
   ref_by= 0;
   aggr_level= -1;
+  aggr_sel= NULL;
   max_arg_level= -1;
   max_sum_func_level= -1;
   return FALSE;
@@ -149,9 +149,14 @@ bool Item_sum::check_sum_func(THD *thd, Item **ref)
     if (register_sum_func(thd, ref))
       return TRUE;
     invalid= aggr_level < 0 && !(allow_sum_func & (1 << nest_level));
+    if (!invalid && thd->variables.sql_mode & MODE_ANSI)
+      invalid= aggr_level < 0 && max_arg_level < nest_level;
   }
   if (!invalid && aggr_level < 0)
+  {
     aggr_level= nest_level;
+    aggr_sel= thd->lex->current_select;
+  }
   /*
     By this moment we either found a subquery where the set function is
     to be aggregated  and assigned a value that is  >= 0 to aggr_level,
@@ -161,8 +166,9 @@ bool Item_sum::check_sum_func(THD *thd, Item **ref)
     Additionally we have to check whether possible nested set functions
     are acceptable here: they are not, if the level of aggregation of
     some of them is less than aggr_level.
-  */ 
-  invalid= aggr_level <= max_sum_func_level;
+  */
+  if (!invalid) 
+    invalid= aggr_level <= max_sum_func_level;
   if (invalid)  
   {
     my_message(ER_INVALID_GROUP_FUNC_USE, ER(ER_INVALID_GROUP_FUNC_USE),
@@ -212,7 +218,6 @@ bool Item_sum::check_sum_func(THD *thd, Item **ref)
 bool Item_sum::register_sum_func(THD *thd, Item **ref)
 {
   SELECT_LEX *sl;
-  SELECT_LEX *aggr_sl= NULL;
   nesting_map allow_sum_func= thd->lex->allow_sum_func;
   for (sl= thd->lex->current_select->master_unit()->outer_select() ;
        sl && sl->nest_level > max_arg_level;
@@ -222,7 +227,7 @@ bool Item_sum::register_sum_func(THD *thd, Item **ref)
     {
       /* Found the most nested subquery where the function can be aggregated */
       aggr_level= sl->nest_level;
-      aggr_sl= sl;
+      aggr_sel= sl;
     }
   }
   if (sl && (allow_sum_func & (1 << sl->nest_level)))
@@ -233,21 +238,22 @@ bool Item_sum::register_sum_func(THD *thd, Item **ref)
       The set function will be aggregated in this subquery.
     */   
     aggr_level= sl->nest_level;
-    aggr_sl= sl;
+    aggr_sel= sl;
+
   }
   if (aggr_level >= 0)
   {
     ref_by= ref;
-    /* Add the object to the list of registered objects assigned to aggr_sl */
-    if (!aggr_sl->inner_sum_func_list)
+    /* Add the object to the list of registered objects assigned to aggr_sel */
+    if (!aggr_sel->inner_sum_func_list)
       next= this;
     else
     {
-      next= aggr_sl->inner_sum_func_list->next;
-      aggr_sl->inner_sum_func_list->next= this;
+      next= aggr_sel->inner_sum_func_list->next;
+      aggr_sel->inner_sum_func_list->next= this;
     }
-    aggr_sl->inner_sum_func_list= this;
-    aggr_sl->with_sum_func= 1;
+    aggr_sel->inner_sum_func_list= this;
+    aggr_sel->with_sum_func= 1;
 
     /* 
       Mark Item_subselect(s) as containing aggregate function all the way up
@@ -265,11 +271,11 @@ bool Item_sum::register_sum_func(THD *thd, Item **ref)
       has aggregate functions directly referenced (i.e. not through a sub-select).
     */
     for (sl= thd->lex->current_select; 
-         sl && sl != aggr_sl && sl->master_unit()->item;
+         sl && sl != aggr_sel && sl->master_unit()->item;
          sl= sl->master_unit()->outer_select() )
       sl->master_unit()->item->with_sum_func= 1;
   }
-  thd->lex->current_select->mark_as_dependent(aggr_sl);
+  thd->lex->current_select->mark_as_dependent(aggr_sel);
   return FALSE;
 }
 
@@ -299,10 +305,10 @@ Item_sum::Item_sum(List<Item> &list) :arg_count(list.elements),
 
 Item_sum::Item_sum(THD *thd, Item_sum *item):
   Item_result_field(thd, item), arg_count(item->arg_count),
+  aggr_sel(item->aggr_sel),
   nest_level(item->nest_level), aggr_level(item->aggr_level),
   quick_group(item->quick_group), used_tables_cache(item->used_tables_cache),
-  forced_const(item->forced_const), 
-  nest_level_tables_count(item->nest_level_tables_count)
+  forced_const(item->forced_const) 
 {
   if (arg_count <= 2)
     args=tmp_args;
@@ -413,7 +419,7 @@ Field *Item_sum::create_tmp_field(bool group, TABLE *table,
     break;
   case STRING_RESULT:
     if (max_length/collation.collation->mbmaxlen <= 255 ||
-        max_length/collation.collation->mbmaxlen >=UINT_MAX16 ||
+        convert_blob_length >=UINT_MAX16 ||
         !convert_blob_length)
       return make_string_field(table);
     field= new Field_varstring(convert_blob_length, maybe_null,
@@ -449,8 +455,7 @@ void Item_sum::update_used_tables ()
     used_tables_cache&= PSEUDO_TABLE_BITS;
 
     /* the aggregate function is aggregated into its local context */
-    if (aggr_level == nest_level)
-      used_tables_cache |=  (1 << nest_level_tables_count) - 1;
+    used_tables_cache |=  (1 << aggr_sel->join->tables) - 1;
   }
 }
 
diff --git a/sql/item_sum.h b/sql/item_sum.h
index 5756402c1b1e892c686b329615983d58b349d044..5cf4f93af0ee0d105e36ed1411298e29a5f688ba 100644
--- a/sql/item_sum.h
+++ b/sql/item_sum.h
@@ -233,6 +233,7 @@ public:
   Item_sum *next; /* next in the circular chain of registered objects  */
   uint arg_count;
   Item_sum *in_sum_func;  /* embedding set function if any */ 
+  st_select_lex * aggr_sel; /* select where the function is aggregated       */ 
   int8 nest_level;        /* number of the nesting level of the set function */
   int8 aggr_level;        /* nesting level of the aggregating subquery       */
   int8 max_arg_level;     /* max level of unbound column references          */
@@ -242,7 +243,6 @@ public:
 protected:  
   table_map used_tables_cache;
   bool forced_const;
-  byte nest_level_tables_count;
 
 public:  
 
@@ -365,6 +365,8 @@ public:
   bool init_sum_func_check(THD *thd);
   bool check_sum_func(THD *thd, Item **ref);
   bool register_sum_func(THD *thd, Item **ref);
+  st_select_lex *depended_from() 
+    { return (nest_level == aggr_level ? 0 : aggr_sel); }
 };
 
 
diff --git a/sql/lex.h b/sql/lex.h
index 6e0f1c711f2b7ca5ff029bf00b2697cb43b52302..45155da76927c02fbf8d0f2acb2cb8d0e7e5d690 100644
--- a/sql/lex.h
+++ b/sql/lex.h
@@ -467,7 +467,6 @@ static SYMBOL symbols[] = {
   { "SIGNED",		SYM(SIGNED_SYM)},
   { "SIMPLE",		SYM(SIMPLE_SYM)},
   { "SLAVE",            SYM(SLAVE)},
-  { "SLAVESIDE_DISABLE",		SYM(SLAVESIDE_DISABLE_SYM)}, 
   { "SNAPSHOT",         SYM(SNAPSHOT_SYM)},
   { "SMALLINT",		SYM(SMALLINT)},
   { "SOCKET",		SYM(SOCKET_SYM)},
diff --git a/sql/log_event.cc b/sql/log_event.cc
index 286d63723540dcf070dbc7aab9774601f6ee3e4e..e3c94b5e1c96c5573a4d200f7d886b0f0e5d8a23 100644
--- a/sql/log_event.cc
+++ b/sql/log_event.cc
@@ -7892,8 +7892,8 @@ Incident_log_event::Incident_log_event(const char *buf, uint event_len,
   m_incident= static_cast<Incident>(uint2korr(buf + common_header_len));
   char const *ptr= buf + common_header_len + post_header_len;
   char const *const str_end= buf + event_len;
-  uint8 len;
-  const char *str;
+  uint8 len= 0;                   // Assignment to keep compiler happy
+  const char *str= NULL;          // Assignment to keep compiler happy
   read_str(&ptr, str_end, &str, &len);
   m_message.str= const_cast<char*>(str);
   m_message.length= len;
@@ -7956,9 +7956,9 @@ Incident_log_event::print(FILE *file,
 
 #if defined(HAVE_REPLICATION) && !defined(MYSQL_CLIENT)
 int
-Incident_log_event::exec_event(st_relay_log_info *rli)
+Incident_log_event::do_apply_event(RELAY_LOG_INFO const *rli)
 {
-  DBUG_ENTER("Incident_log_event::exec_event");
+  DBUG_ENTER("Incident_log_event::do_apply_event");
   slave_print_msg(ERROR_LEVEL, rli, ER_SLAVE_INCIDENT,
                   ER(ER_SLAVE_INCIDENT),
                   description(),
diff --git a/sql/log_event.h b/sql/log_event.h
index 500f3533c92bd58924cab713410d90945bde948e..515432916211c8e6eaba4b430f523d8fa358c893 100644
--- a/sql/log_event.h
+++ b/sql/log_event.h
@@ -2588,7 +2588,7 @@ public:
 #endif
 
 #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
-  virtual int exec_event(struct st_relay_log_info *rli);
+  virtual int do_apply_event(RELAY_LOG_INFO const *rli);
 #endif
 
   virtual bool write_data_header(IO_CACHE *file);
diff --git a/sql/mysql_priv.h b/sql/mysql_priv.h
index 9a0bed8d31856375359be70d1f0156d601b88a7c..2bc8c2071d2a2cfe4f54319852f18da2f346efd5 100644
--- a/sql/mysql_priv.h
+++ b/sql/mysql_priv.h
@@ -1445,6 +1445,9 @@ void close_system_tables(THD *thd, Open_tables_state *backup);
 TABLE *open_system_table_for_update(THD *thd, TABLE_LIST *one_table);
 
 bool close_cached_tables(THD *thd, bool wait_for_refresh, TABLE_LIST *tables, bool have_lock = FALSE);
+bool close_cached_connection_tables(THD *thd, bool wait_for_refresh,
+                                    LEX_STRING *connect_string,
+                                    bool have_lock = FALSE);
 void copy_field_from_tmp_record(Field *field,int offset);
 bool fill_record(THD *thd, Field **field, List<Item> &values,
                  bool ignore_errors);
diff --git a/sql/mysqld.cc b/sql/mysqld.cc
index 9efe389a11fdc9a74552a8ea3c2d9caa80bc73ec..5031496158bff2e1984d9962a4fbfb3b823dcd18 100644
--- a/sql/mysqld.cc
+++ b/sql/mysqld.cc
@@ -6271,7 +6271,7 @@ The minimum value for this variable is 4096.",
    (gptr*) &global_system_variables.net_write_timeout,
    (gptr*) &max_system_variables.net_write_timeout, 0, GET_ULONG,
    REQUIRED_ARG, NET_WRITE_TIMEOUT, 1, LONG_TIMEOUT, 0, 1, 0},
-  { "old_mode", OPT_OLD_MODE, "Use compatible behaviour.", 
+  { "old", OPT_OLD_MODE, "Use compatible behavior.", 
     (gptr*) &global_system_variables.old_mode,
     (gptr*) &max_system_variables.old_mode, 0, GET_BOOL, NO_ARG, 
     0, 0, 0, 0, 0, 0},
diff --git a/sql/opt_range.cc b/sql/opt_range.cc
index 03d97a294ad7cee0471c2bcb27f7087f7c507381..f5cf79bd609a41495ae830bab4b4987f91c4f867 100644
--- a/sql/opt_range.cc
+++ b/sql/opt_range.cc
@@ -84,7 +84,7 @@ static int sel_cmp(Field *f,char *a,char *b,uint8 a_flag,uint8 b_flag);
 
 static char is_null_string[2]= {1,0};
 
-
+class RANGE_OPT_PARAM;
 /*
   A construction block of the SEL_ARG-graph.
   
@@ -170,6 +170,89 @@ static char is_null_string[2]= {1,0};
    - get_quick_select()   - Walk the SEL_ARG, materialize the key intervals,
                             and create QUICK_RANGE_SELECT object that will
                             read records within these intervals.
+
+  4. SPACE COMPLEXITY NOTES 
+
+    SEL_ARG graph is a representation of an ordered disjoint sequence of
+    intervals over the ordered set of index tuple values.
+
+    For multi-part keys, one can construct a WHERE expression such that its
+    list of intervals will be of combinatorial size. Here is an example:
+     
+      (keypart1 IN (1,2, ..., n1)) AND 
+      (keypart2 IN (1,2, ..., n2)) AND 
+      (keypart3 IN (1,2, ..., n3))
+    
+    For this WHERE clause the list of intervals will have n1*n2*n3 intervals
+    of form
+     
+      (keypart1, keypart2, keypart3) = (k1, k2, k3), where 1 <= k{i} <= n{i}
+    
+    SEL_ARG graph structure aims to reduce the amount of required space by
+    "sharing" the elementary intervals when possible (the pic at the
+    beginning of this comment has examples of such sharing). The sharing may 
+    prevent combinatorial blowup:
+
+      There are WHERE clauses that have combinatorial-size interval lists but
+      will be represented by a compact SEL_ARG graph.
+      Example:
+        (keypartN IN (1,2, ..., n1)) AND 
+        ...
+        (keypart2 IN (1,2, ..., n2)) AND 
+        (keypart1 IN (1,2, ..., n3))
+
+    but not in all cases:
+
+    - There are WHERE clauses that do have a compact SEL_ARG-graph
+      representation but get_mm_tree() and its callees will construct a
+      graph of combinatorial size.
+      Example:
+        (keypart1 IN (1,2, ..., n1)) AND 
+        (keypart2 IN (1,2, ..., n2)) AND 
+        ...
+        (keypartN IN (1,2, ..., n3))
+
+    - There are WHERE clauses for which the minimal possible SEL_ARG graph
+      representation will have combinatorial size.
+      Example:
+        By induction: Let's take any interval on some keypart in the middle:
+
+           kp15=c0
+        
+        Then let's AND it with this interval 'structure' from preceding and
+        following keyparts:
+
+          (kp14=c1 AND kp16=c3) OR keypart14=c2) (*)
+        
+        We will obtain this SEL_ARG graph:
+ 
+             kp14     $      kp15      $      kp16
+                      $                $
+         +---------+  $   +---------+  $   +---------+
+         | kp14=c1 |--$-->| kp15=c0 |--$-->| kp16=c3 |
+         +---------+  $   +---------+  $   +---------+
+              |       $                $              
+         +---------+  $   +---------+  $             
+         | kp14=c2 |--$-->| kp15=c0 |  $             
+         +---------+  $   +---------+  $             
+                      $                $
+                      
+       Note that we had to duplicate "kp15=c0" and there was no way to avoid
+       that. 
+       The induction step: AND the obtained expression with another "wrapping"
+       expression like (*).
+       When the process ends because of the limit on max. number of keyparts 
+       we'll have:
+
+         WHERE clause length  is O(3*#max_keyparts)
+         SEL_ARG graph size   is O(2^(#max_keyparts/2))
+
+       (it is also possible to construct a case where instead of 2 in 2^n we
+        have a bigger constant, e.g. 4, and get a graph with 4^(31/2)= 2^31
+        nodes)
+
+    We avoid consuming too much memory by setting a limit on the number of
+    SEL_ARG object we can construct during one range analysis invocation.
 */
 
 class SEL_ARG :public Sql_alloc
@@ -200,6 +283,8 @@ public:
   enum leaf_color { BLACK,RED } color;
   enum Type { IMPOSSIBLE, MAYBE, MAYBE_KEY, KEY_RANGE } type;
 
+  enum { MAX_SEL_ARGS = 16000 };
+
   SEL_ARG() {}
   SEL_ARG(SEL_ARG &);
   SEL_ARG(Field *,const char *,const char *);
@@ -271,7 +356,7 @@ public:
     return new SEL_ARG(field, part, min_value, arg->max_value,
 		       min_flag, arg->max_flag, maybe_flag | arg->maybe_flag);
   }
-  SEL_ARG *clone(SEL_ARG *new_parent,SEL_ARG **next);
+  SEL_ARG *clone(RANGE_OPT_PARAM *param, SEL_ARG *new_parent, SEL_ARG **next);
 
   bool copy_min(SEL_ARG* arg)
   {						// Get overlapping range
@@ -423,7 +508,6 @@ public:
   {
     return parent->left == this ? &parent->left : &parent->right;
   }
-  SEL_ARG *clone_tree();
 
 
   /*
@@ -466,6 +550,7 @@ public:
     }
     return !field->key_cmp(min_val, max_val);
   }
+  SEL_ARG *clone_tree(RANGE_OPT_PARAM *param);
 };
 
 class SEL_IMERGE;
@@ -545,6 +630,8 @@ public:
     using_real_indexes==TRUE
   */
   uint real_keynr[MAX_KEY];
+  /* Number of SEL_ARG objects allocated by SEL_ARG::clone_tree operations */
+  uint alloced_sel_args; 
 };
 
 class PARAM : public RANGE_OPT_PARAM
@@ -634,8 +721,9 @@ static void print_quick(QUICK_SELECT_I *quick, const key_map *needed_reg);
 static SEL_TREE *tree_and(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2);
 static SEL_TREE *tree_or(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2);
 static SEL_ARG *sel_add(SEL_ARG *key1,SEL_ARG *key2);
-static SEL_ARG *key_or(SEL_ARG *key1,SEL_ARG *key2);
-static SEL_ARG *key_and(SEL_ARG *key1,SEL_ARG *key2,uint clone_flag);
+static SEL_ARG *key_or(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2);
+static SEL_ARG *key_and(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2,
+                        uint clone_flag);
 static bool get_range(SEL_ARG **e1,SEL_ARG **e2,SEL_ARG *root1);
 bool get_quick_keys(PARAM *param,QUICK_RANGE_SELECT *quick,KEY_PART *key,
 			   SEL_ARG *key_tree,char *min_key,uint min_key_flag,
@@ -860,6 +948,7 @@ int imerge_list_or_tree(RANGE_OPT_PARAM *param,
   return im1->is_empty();
 }
 
+
 /***************************************************************************
 ** Basic functions for SQL_SELECT and QUICK_RANGE_SELECT
 ***************************************************************************/
@@ -1510,12 +1599,18 @@ SEL_ARG::SEL_ARG(Field *field_,uint8 part_,char *min_value_,char *max_value_,
   left=right= &null_element;
 }
 
-SEL_ARG *SEL_ARG::clone(SEL_ARG *new_parent,SEL_ARG **next_arg)
+SEL_ARG *SEL_ARG::clone(RANGE_OPT_PARAM *param, SEL_ARG *new_parent, 
+                        SEL_ARG **next_arg)
 {
   SEL_ARG *tmp;
+
+  /* Bail out if we have already generated too many SEL_ARGs */
+  if (++param->alloced_sel_args > MAX_SEL_ARGS)
+    return 0;
+
   if (type != KEY_RANGE)
   {
-    if (!(tmp= new SEL_ARG(type)))
+    if (!(tmp= new (param->mem_root) SEL_ARG(type)))
       return 0;					// out of memory
     tmp->prev= *next_arg;			// Link into next/prev chain
     (*next_arg)->next=tmp;
@@ -1523,20 +1618,21 @@ SEL_ARG *SEL_ARG::clone(SEL_ARG *new_parent,SEL_ARG **next_arg)
   }
   else
   {
-    if (!(tmp= new SEL_ARG(field,part, min_value,max_value,
-			   min_flag, max_flag, maybe_flag)))
+    if (!(tmp= new (param->mem_root) SEL_ARG(field,part, min_value,max_value,
+                                             min_flag, max_flag, maybe_flag)))
       return 0;					// OOM
     tmp->parent=new_parent;
     tmp->next_key_part=next_key_part;
     if (left != &null_element)
-      tmp->left=left->clone(tmp,next_arg);
+      if (!(tmp->left=left->clone(param, tmp, next_arg)))
+	return 0;				// OOM
 
     tmp->prev= *next_arg;			// Link into next/prev chain
     (*next_arg)->next=tmp;
     (*next_arg)= tmp;
 
     if (right != &null_element)
-      if (!(tmp->right= right->clone(tmp,next_arg)))
+      if (!(tmp->right= right->clone(param, tmp, next_arg)))
 	return 0;				// OOM
   }
   increment_use_count(1);
@@ -1614,11 +1710,12 @@ static int sel_cmp(Field *field, char *a,char *b,uint8 a_flag,uint8 b_flag)
 }
 
 
-SEL_ARG *SEL_ARG::clone_tree()
+SEL_ARG *SEL_ARG::clone_tree(RANGE_OPT_PARAM *param)
 {
   SEL_ARG tmp_link,*next_arg,*root;
   next_arg= &tmp_link;
-  root= clone((SEL_ARG *) 0, &next_arg);
+  if (!(root= clone(param, (SEL_ARG *) 0, &next_arg)))
+    return 0;
   next_arg->next=0;				// Fix last link
   tmp_link.next->prev=0;			// Fix first link
   if (root)					// If not OOM
@@ -2120,6 +2217,7 @@ int SQL_SELECT::test_quick_select(THD *thd, key_map keys_to_use,
       param.real_keynr[param.keys++]=idx;
     }
     param.key_parts_end=key_parts;
+    param.alloced_sel_args= 0;
 
     /* Calculate cost of full index read for the shortest covering index */
     if (!head->covering_keys.is_clear_all())
@@ -2512,6 +2610,7 @@ bool prune_partitions(THD *thd, TABLE *table, Item *pprune_cond)
   range_par->using_real_indexes= FALSE;
   range_par->remove_jump_scans= FALSE;
   range_par->real_keynr[0]= 0;
+  range_par->alloced_sel_args= 0;
 
   thd->no_errors=1;				// Don't warn about NULL
   thd->mem_root=&alloc;
@@ -5242,7 +5341,8 @@ static SEL_TREE *get_mm_tree(RANGE_OPT_PARAM *param,COND *cond)
       while ((item=li++))
       {
 	SEL_TREE *new_tree=get_mm_tree(param,item);
-	if (param->thd->is_fatal_error)
+	if (param->thd->is_fatal_error || 
+            param->alloced_sel_args > SEL_ARG::MAX_SEL_ARGS)
 	  DBUG_RETURN(0);	// out of memory
 	tree=tree_and(param,tree,new_tree);
 	if (tree && tree->type == SEL_TREE::IMPOSSIBLE)
@@ -5818,9 +5918,9 @@ tree_and(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2)
     tree1->type=SEL_TREE::KEY_SMALLER;
     DBUG_RETURN(tree1);
   }
-
   key_map  result_keys;
   result_keys.clear_all();
+  
   /* Join the trees key per key */
   SEL_ARG **key1,**key2,**end;
   for (key1= tree1->keys,key2= tree2->keys,end=key1+param->keys ;
@@ -5833,7 +5933,7 @@ tree_and(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2)
 	flag|=CLONE_KEY1_MAYBE;
       if (*key2 && !(*key2)->simple_key())
 	flag|=CLONE_KEY2_MAYBE;
-      *key1=key_and(*key1,*key2,flag);
+      *key1=key_and(param, *key1, *key2, flag);
       if (*key1 && (*key1)->type == SEL_ARG::IMPOSSIBLE)
       {
 	tree1->type= SEL_TREE::IMPOSSIBLE;
@@ -5841,8 +5941,8 @@ tree_and(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2)
       }
       result_keys.set_bit(key1 - tree1->keys);
 #ifdef EXTRA_DEBUG
-      if (*key1)
-        (*key1)->test_use_count(*key1);
+        if (*key1 && param->alloced_sel_args < SEL_ARG::MAX_SEL_ARGS) 
+          (*key1)->test_use_count(*key1);
 #endif
     }
   }
@@ -5994,13 +6094,14 @@ tree_or(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2)
     for (key1= tree1->keys,key2= tree2->keys,end= key1+param->keys ;
          key1 != end ; key1++,key2++)
     {
-      *key1=key_or(*key1,*key2);
+      *key1=key_or(param, *key1, *key2);
       if (*key1)
       {
         result=tree1;				// Added to tree1
         result_keys.set_bit(key1 - tree1->keys);
 #ifdef EXTRA_DEBUG
-        (*key1)->test_use_count(*key1);
+        if (param->alloced_sel_args < SEL_ARG::MAX_SEL_ARGS) 
+          (*key1)->test_use_count(*key1);
 #endif
       }
     }
@@ -6058,14 +6159,15 @@ tree_or(RANGE_OPT_PARAM *param,SEL_TREE *tree1,SEL_TREE *tree2)
 /* And key trees where key1->part < key2 -> part */
 
 static SEL_ARG *
-and_all_keys(SEL_ARG *key1,SEL_ARG *key2,uint clone_flag)
+and_all_keys(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2, 
+             uint clone_flag)
 {
   SEL_ARG *next;
   ulong use_count=key1->use_count;
 
   if (key1->elements != 1)
   {
-    key2->use_count+=key1->elements-1;
+    key2->use_count+=key1->elements-1; //psergey: why we don't count that key1 has n-k-p?
     key2->increment_use_count((int) key1->elements-1);
   }
   if (key1->type == SEL_ARG::MAYBE_KEY)
@@ -6077,7 +6179,7 @@ and_all_keys(SEL_ARG *key1,SEL_ARG *key2,uint clone_flag)
   {
     if (next->next_key_part)
     {
-      SEL_ARG *tmp=key_and(next->next_key_part,key2,clone_flag);
+      SEL_ARG *tmp= key_and(param, next->next_key_part, key2, clone_flag);
       if (tmp && tmp->type == SEL_ARG::IMPOSSIBLE)
       {
 	key1=key1->tree_delete(next);
@@ -6086,6 +6188,8 @@ and_all_keys(SEL_ARG *key1,SEL_ARG *key2,uint clone_flag)
       next->next_key_part=tmp;
       if (use_count)
 	next->increment_use_count(use_count);
+      if (param->alloced_sel_args > SEL_ARG::MAX_SEL_ARGS)
+        break;
     }
     else
       next->next_key_part=key2;
@@ -6102,8 +6206,10 @@ and_all_keys(SEL_ARG *key1,SEL_ARG *key2,uint clone_flag)
 
   SYNOPSIS
     key_and()
-      key1   First argument, root of its RB-tree
-      key2   Second argument, root of its RB-tree
+      param   Range analysis context (needed to track if we have allocated
+              too many SEL_ARGs)
+      key1    First argument, root of its RB-tree
+      key2    Second argument, root of its RB-tree
 
   RETURN
     RB-tree root of the resulting SEL_ARG graph.
@@ -6111,7 +6217,7 @@ and_all_keys(SEL_ARG *key1,SEL_ARG *key2,uint clone_flag)
 */
 
 static SEL_ARG *
-key_and(SEL_ARG *key1, SEL_ARG *key2, uint clone_flag)
+key_and(RANGE_OPT_PARAM *param, SEL_ARG *key1, SEL_ARG *key2, uint clone_flag)
 {
   if (!key1)
     return key2;
@@ -6127,9 +6233,9 @@ key_and(SEL_ARG *key1, SEL_ARG *key2, uint clone_flag)
     // key1->part < key2->part
     key1->use_count--;
     if (key1->use_count > 0)
-      if (!(key1= key1->clone_tree()))
+      if (!(key1= key1->clone_tree(param)))
 	return 0;				// OOM
-    return and_all_keys(key1,key2,clone_flag);
+    return and_all_keys(param, key1, key2, clone_flag);
   }
 
   if (((clone_flag & CLONE_KEY2_MAYBE) &&
@@ -6147,14 +6253,14 @@ key_and(SEL_ARG *key1, SEL_ARG *key2, uint clone_flag)
     if (key1->use_count > 1)
     {
       key1->use_count--;
-      if (!(key1=key1->clone_tree()))
+      if (!(key1=key1->clone_tree(param)))
 	return 0;				// OOM
       key1->use_count++;
     }
     if (key1->type == SEL_ARG::MAYBE_KEY)
     {						// Both are maybe key
-      key1->next_key_part=key_and(key1->next_key_part,key2->next_key_part,
-				 clone_flag);
+      key1->next_key_part=key_and(param, key1->next_key_part, 
+                                  key2->next_key_part, clone_flag);
       if (key1->next_key_part &&
 	  key1->next_key_part->type == SEL_ARG::IMPOSSIBLE)
 	return key1;
@@ -6165,7 +6271,7 @@ key_and(SEL_ARG *key1, SEL_ARG *key2, uint clone_flag)
       if (key2->next_key_part)
       {
 	key1->use_count--;			// Incremented in and_all_keys
-	return and_all_keys(key1,key2,clone_flag);
+	return and_all_keys(param, key1, key2, clone_flag);
       }
       key2->use_count--;			// Key2 doesn't have a tree
     }
@@ -6201,7 +6307,8 @@ key_and(SEL_ARG *key1, SEL_ARG *key2, uint clone_flag)
     }
     else if (get_range(&e2,&e1,key2))
       continue;
-    SEL_ARG *next=key_and(e1->next_key_part,e2->next_key_part,clone_flag);
+    SEL_ARG *next=key_and(param, e1->next_key_part, e2->next_key_part,
+                          clone_flag);
     e1->increment_use_count(1);
     e2->increment_use_count(1);
     if (!next || next->type != SEL_ARG::IMPOSSIBLE)
@@ -6249,7 +6356,7 @@ get_range(SEL_ARG **e1,SEL_ARG **e2,SEL_ARG *root1)
 
 
 static SEL_ARG *
-key_or(SEL_ARG *key1,SEL_ARG *key2)
+key_or(RANGE_OPT_PARAM *param, SEL_ARG *key1,SEL_ARG *key2)
 {
   if (!key1)
   {
@@ -6297,7 +6404,7 @@ key_or(SEL_ARG *key1,SEL_ARG *key2)
     {
       swap_variables(SEL_ARG *,key1,key2);
     }
-    if (key1->use_count > 0 || !(key1=key1->clone_tree()))
+    if (key1->use_count > 0 || !(key1=key1->clone_tree(param)))
       return 0;					// OOM
   }
 
@@ -6441,7 +6548,7 @@ key_or(SEL_ARG *key1,SEL_ARG *key2)
       {						// tmp.min. <= x <= tmp.max
 	tmp->maybe_flag|= key.maybe_flag;
 	key.increment_use_count(key1->use_count+1);
-	tmp->next_key_part=key_or(tmp->next_key_part,key.next_key_part);
+	tmp->next_key_part= key_or(param, tmp->next_key_part, key.next_key_part);
 	if (!cmp)				// Key2 is ready
 	  break;
 	key.copy_max_to_min(tmp);
@@ -6472,7 +6579,7 @@ key_or(SEL_ARG *key1,SEL_ARG *key2)
 	tmp->increment_use_count(key1->use_count+1);
 	/* Increment key count as it may be used for next loop */
 	key.increment_use_count(1);
-	new_arg->next_key_part=key_or(tmp->next_key_part,key.next_key_part);
+	new_arg->next_key_part= key_or(param, tmp->next_key_part, key.next_key_part);
 	key1=key1->insert(new_arg);
 	break;
       }
diff --git a/sql/rpl_rli.cc b/sql/rpl_rli.cc
index 16e13f049e3aecd4da98a085b12a563a1bdcb320..b0db355154e95ab3344c7ee025983344cd1d7ca2 100644
--- a/sql/rpl_rli.cc
+++ b/sql/rpl_rli.cc
@@ -969,7 +969,7 @@ err:
      strtol() conversions needed for log names comparison. We don't need to
      compare them each time this function is called, we only need to do this
      when current log name changes. If we have UNTIL_MASTER_POS condition we
-     need to do this only after Rotate_log_event::exec_event() (which is
+     need to do this only after Rotate_log_event::do_apply_event() (which is
      rare, so caching gives real benifit), and if we have UNTIL_RELAY_POS
      condition then we should invalidate cached comarison value after
      inc_group_relay_log_pos() which called for each group of events (so we
@@ -1093,12 +1093,12 @@ void st_relay_log_info::cleanup_context(THD *thd, bool error)
 
   DBUG_ASSERT(sql_thd == thd);
   /*
-    1) Instances of Table_map_log_event, if ::exec_event() was called on them,
+    1) Instances of Table_map_log_event, if ::do_apply_event() was called on them,
     may have opened tables, which we cannot be sure have been closed (because
     maybe the Rows_log_event have not been found or will not be, because slave
     SQL thread is stopping, or relay log has a missing tail etc). So we close
     all thread's tables. And so the table mappings have to be cancelled.
-    2) Rows_log_event::exec_event() may even have started statements or
+    2) Rows_log_event::do_apply_event() may even have started statements or
     transactions on them, which we need to rollback in case of error.
     3) If finding a Format_description_log_event after a BEGIN, we also need
     to rollback before continuing with the next events.
diff --git a/sql/set_var.cc b/sql/set_var.cc
index fef6fccfd06e9a2d265bf0174ada00a054b3f78d..7f55556c134c7189f999441a419abfa38fdfb035 100644
--- a/sql/set_var.cc
+++ b/sql/set_var.cc
@@ -356,6 +356,8 @@ sys_var_thd_ulong	sys_net_retry_count("net_retry_count",
 					    &SV::net_retry_count,
 					    0, fix_net_retry_count);
 sys_var_thd_bool	sys_new_mode("new", &SV::new_mode);
+sys_var_bool_ptr_readonly sys_old_mode("old", 
+                                       &global_system_variables.old_mode);
 sys_var_thd_bool	sys_old_alter_table("old_alter_table",
 					    &SV::old_alter_table);
 sys_var_thd_bool	sys_old_passwords("old_passwords", &SV::old_passwords);
@@ -942,6 +944,7 @@ SHOW_VAR init_vars[]= {
   {sys_net_retry_count.name,  (char*) &sys_net_retry_count,	    SHOW_SYS},
   {sys_net_write_timeout.name,(char*) &sys_net_write_timeout,       SHOW_SYS},
   {sys_new_mode.name,         (char*) &sys_new_mode,                SHOW_SYS},
+  {sys_old_mode.name,         (char*) &sys_old_mode,                SHOW_SYS},
   {sys_old_alter_table.name,  (char*) &sys_old_alter_table,         SHOW_SYS},
   {sys_old_passwords.name,    (char*) &sys_old_passwords,           SHOW_SYS},
   {"open_files_limit",	      (char*) &open_files_limit,	    SHOW_LONG},
diff --git a/sql/set_var.h b/sql/set_var.h
index 8887d91ec69f9326c6428f7787a95ed0505f785b..eac03fce61005a35ecc2633d1c017bcb4fd57925 100644
--- a/sql/set_var.h
+++ b/sql/set_var.h
@@ -169,6 +169,16 @@ public:
 };
 
 
+class sys_var_bool_ptr_readonly :public sys_var_bool_ptr
+{
+public:
+  sys_var_bool_ptr_readonly(const char *name_arg, my_bool *value_arg)
+    :sys_var_bool_ptr(name_arg, value_arg)
+  {}
+  bool is_readonly() const { return 1; }
+};
+
+
 class sys_var_str :public sys_var
 {
 public:
diff --git a/sql/sql_base.cc b/sql/sql_base.cc
index d88b6a3adfce4d5db4e8e5b783c87f739da021e1..82cce335f00398564a9bbfef12b1a5b48310f415 100644
--- a/sql/sql_base.cc
+++ b/sql/sql_base.cc
@@ -858,6 +858,7 @@ void free_io_cache(TABLE *table)
   DBUG_VOID_RETURN;
 }
 
+
 /*
   Close all tables which aren't in use by any thread
 
@@ -969,6 +970,71 @@ bool close_cached_tables(THD *thd, bool if_wait_for_refresh,
 }
 
 
+/*
+  Close all tables which match specified connection string or
+  if specified string is NULL, then any table with a connection string.
+*/
+
+bool close_cached_connection_tables(THD *thd, bool if_wait_for_refresh,
+                                    LEX_STRING *connection, bool have_lock)
+{
+  uint idx;
+  TABLE_LIST tmp, *tables= NULL;
+  bool result= FALSE;
+  DBUG_ENTER("close_cached_connections");
+  DBUG_ASSERT(thd);
+
+  bzero(&tmp, sizeof(TABLE_LIST));
+  
+  if (!have_lock)
+    VOID(pthread_mutex_lock(&LOCK_open));
+  
+  for (idx= 0; idx < table_def_cache.records; idx++)
+  {
+    TABLE_SHARE *share= (TABLE_SHARE *) hash_element(&table_def_cache, idx);
+
+    /* Ignore if table is not open or does not have a connect_string */
+    if (!share->connect_string.length || !share->ref_count)
+      continue;
+
+    /* Compare the connection string */
+    if (connection &&
+        (connection->length > share->connect_string.length ||
+         (connection->length < share->connect_string.length &&
+          (share->connect_string.str[connection->length] != '/' &&
+           share->connect_string.str[connection->length] != '\\')) ||
+         strncasecmp(connection->str, share->connect_string.str,
+                     connection->length)))
+      continue;
+
+    /* close_cached_tables() only uses these elements */
+    tmp.db= share->db.str;
+    tmp.table_name= share->table_name.str;
+    tmp.next_local= tables;
+
+    tables= (TABLE_LIST *) memdup_root(thd->mem_root, (char*)&tmp, 
+                                       sizeof(TABLE_LIST));
+  }
+
+  if (tables)
+    result= close_cached_tables(thd, FALSE, tables, TRUE);
+  
+  if (!have_lock)
+    VOID(pthread_mutex_unlock(&LOCK_open));
+  
+  if (if_wait_for_refresh)
+  {
+    pthread_mutex_lock(&thd->mysys_var->mutex);
+    thd->mysys_var->current_mutex= 0;
+    thd->mysys_var->current_cond= 0;
+    thd->proc_info=0;
+    pthread_mutex_unlock(&thd->mysys_var->mutex);
+  }
+
+  DBUG_RETURN(result);
+}
+
+
 /*
   Mark all tables in the list which were used by current substatement
   as free for reuse.
@@ -2272,6 +2338,9 @@ TABLE *open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
   table->insert_values= 0;
   table->fulltext_searched= 0;
   table->file->ft_handler= 0;
+  /* Catch wrong handling of the auto_increment_field_not_null. */
+  DBUG_ASSERT(!table->auto_increment_field_not_null);
+  table->auto_increment_field_not_null= FALSE;
   if (table->timestamp_field)
     table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
   table->pos_in_table_list= table_list;
@@ -5772,7 +5841,6 @@ bool setup_tables_and_check_access(THD *thd,
   TABLE_LIST *leaves_tmp= NULL;
   bool first_table= true;
 
-  thd->leaf_count= 0;
   if (setup_tables(thd, context, from_clause, tables,
                    &leaves_tmp, select_insert))
     return TRUE;
@@ -5790,7 +5858,6 @@ bool setup_tables_and_check_access(THD *thd,
       return TRUE;
     }
     first_table= 0;
-    thd->leaf_count++;
   }
   return FALSE;
 }
@@ -6174,6 +6241,11 @@ err_no_arena:
     values        values to fill with
     ignore_errors TRUE if we should ignore errors
 
+  NOTE
+    fill_record() may set table->auto_increment_field_not_null and a
+    caller should make sure that it is reset after their last call to this
+    function.
+
   RETURN
     FALSE   OK
     TRUE    error occured
@@ -6186,27 +6258,52 @@ fill_record(THD * thd, List<Item> &fields, List<Item> &values,
   List_iterator_fast<Item> f(fields),v(values);
   Item *value, *fld;
   Item_field *field;
+  TABLE *table= 0;
   DBUG_ENTER("fill_record");
 
+  /*
+    Reset the table->auto_increment_field_not_null as it is valid for
+    only one row.
+  */
+  if (fields.elements)
+  {
+    /*
+      On INSERT or UPDATE fields are checked to be from the same table,
+      thus we safely can take table from the first field.
+    */
+    fld= (Item_field*)f++;
+    if (!(field= fld->filed_for_view_update()))
+    {
+      my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
+      goto err;
+    }
+    table= field->field->table;
+    table->auto_increment_field_not_null= FALSE;
+    f.rewind();
+  }
   while ((fld= f++))
   {
     if (!(field= fld->filed_for_view_update()))
     {
       my_error(ER_NONUPDATEABLE_COLUMN, MYF(0), fld->name);
-      DBUG_RETURN(TRUE);
+      goto err;
     }
     value=v++;
     Field *rfield= field->field;
-    TABLE *table= rfield->table;
+    table= rfield->table;
     if (rfield == table->next_number_field)
       table->auto_increment_field_not_null= TRUE;
     if ((value->save_in_field(rfield, 0) < 0) && !ignore_errors)
     {
       my_message(ER_UNKNOWN_ERROR, ER(ER_UNKNOWN_ERROR), MYF(0));
-      DBUG_RETURN(TRUE);
+      goto err;
     }
   }
   DBUG_RETURN(thd->net.report_error);
+err:
+  if (table)
+    table->auto_increment_field_not_null= FALSE;
+  DBUG_RETURN(TRUE);
 }
 
 
@@ -6255,6 +6352,11 @@ fill_record_n_invoke_before_triggers(THD *thd, List<Item> &fields,
     values        list of fields
     ignore_errors TRUE if we should ignore errors
 
+  NOTE
+    fill_record() may set table->auto_increment_field_not_null and a
+    caller should make sure that it is reset after their last call to this
+    function.
+
   RETURN
     FALSE   OK
     TRUE    error occured
@@ -6265,19 +6367,38 @@ fill_record(THD *thd, Field **ptr, List<Item> &values, bool ignore_errors)
 {
   List_iterator_fast<Item> v(values);
   Item *value;
+  TABLE *table= 0;
   DBUG_ENTER("fill_record");
 
   Field *field;
+  /*
+    Reset the table->auto_increment_field_not_null as it is valid for
+    only one row.
+  */
+  if (*ptr)
+  {
+    /*
+      On INSERT or UPDATE fields are checked to be from the same table,
+      thus we safely can take table from the first field.
+    */
+    table= (*ptr)->table;
+    table->auto_increment_field_not_null= FALSE;
+  }
   while ((field = *ptr++))
   {
     value=v++;
-    TABLE *table= field->table;
+    table= field->table;
     if (field == table->next_number_field)
       table->auto_increment_field_not_null= TRUE;
     if (value->save_in_field(field, 0) == -1)
-      DBUG_RETURN(TRUE);
+      goto err;
   }
   DBUG_RETURN(thd->net.report_error);
+
+err:
+  if (table)
+    table->auto_increment_field_not_null= FALSE;
+  DBUG_RETURN(TRUE);
 }
 
 
diff --git a/sql/sql_class.h b/sql/sql_class.h
index a9915fce4efb4977a447c62a1e0f9c70931d2ff1..66914bdf908d454e737fd0b3fa06b7b4c114ffc2 100644
--- a/sql/sql_class.h
+++ b/sql/sql_class.h
@@ -1270,7 +1270,7 @@ public:
     return first_successful_insert_id_in_prev_stmt;
   }
   /*
-    Used by Intvar_log_event::exec_event() and by "SET INSERT_ID=#"
+    Used by Intvar_log_event::do_apply_event() and by "SET INSERT_ID=#"
     (mysqlbinlog). We'll soon add a variant which can take many intervals in
     argument.
   */
@@ -1412,9 +1412,6 @@ public:
   partition_info *work_part_info;
 #endif
 
-  /* pass up the count of "leaf" tables in a JOIN out of setup_tables() */
-  byte leaf_count;
-
   THD();
   ~THD();
 
diff --git a/sql/sql_delete.cc b/sql/sql_delete.cc
index 0ff5c4e5b5085e5d2b49bf3913e5becca587b90f..d300edd6e187c8bd427857353f3d942d3831ea8e 100644
--- a/sql/sql_delete.cc
+++ b/sql/sql_delete.cc
@@ -54,6 +54,27 @@ bool mysql_delete(THD *thd, TABLE_LIST *table_list, COND *conds,
   if (mysql_prepare_delete(thd, table_list, &conds))
     DBUG_RETURN(TRUE);
 
+  /* check ORDER BY even if it can be ignored */
+  if (order && order->elements)
+  {
+    TABLE_LIST   tables;
+    List<Item>   fields;
+    List<Item>   all_fields;
+
+    bzero((char*) &tables,sizeof(tables));
+    tables.table = table;
+    tables.alias = table_list->alias;
+
+      if (select_lex->setup_ref_array(thd, order->elements) ||
+	  setup_order(thd, select_lex->ref_pointer_array, &tables,
+                    fields, all_fields, (ORDER*) order->first))
+    {
+      delete select;
+      free_underlaid_joins(thd, &thd->lex->select_lex);
+      DBUG_RETURN(TRUE);
+    }
+  }
+
   const_cond= (!conds || conds->const_item());
   safe_update=test(thd->options & OPTION_SAFE_UPDATES);
   if (safe_update && const_cond)
@@ -155,23 +176,7 @@ bool mysql_delete(THD *thd, TABLE_LIST *table_list, COND *conds,
   {
     uint         length= 0;
     SORT_FIELD  *sortorder;
-    TABLE_LIST   tables;
-    List<Item>   fields;
-    List<Item>   all_fields;
     ha_rows examined_rows;
-
-    bzero((char*) &tables,sizeof(tables));
-    tables.table = table;
-    tables.alias = table_list->alias;
-
-      if (select_lex->setup_ref_array(thd, order->elements) ||
-	  setup_order(thd, select_lex->ref_pointer_array, &tables,
-                    fields, all_fields, (ORDER*) order->first))
-    {
-      delete select;
-      free_underlaid_joins(thd, &thd->lex->select_lex);
-      DBUG_RETURN(TRUE);
-    }
     
     if ((!select || table->quick_keys.is_clear_all()) && limit != HA_POS_ERROR)
       usable_index= get_index_for_order(table, (ORDER*)(order->first), limit);
diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc
index 773383c2c2d721ed9a579ae7770204a7eb815286..c0e0203ed86657b51400473089323affed60be65 100644
--- a/sql/sql_insert.cc
+++ b/sql/sql_insert.cc
@@ -753,6 +753,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *table_list,
      table->next_number_field->val_int() : 0));
   table->next_number_field=0;
   thd->count_cuted_fields= CHECK_FIELD_IGNORE;
+  table->auto_increment_field_not_null= FALSE;
   if (duplic != DUP_ERROR || ignore)
     table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
   if (duplic == DUP_REPLACE &&
@@ -2466,14 +2467,12 @@ bool mysql_insert_select_prepare(THD *thd)
   DBUG_ASSERT(select_lex->leaf_tables != 0);
   lex->leaf_tables_insert= select_lex->leaf_tables;
   /* skip all leaf tables belonged to view where we are insert */
-  for (first_select_leaf_table= select_lex->leaf_tables->next_leaf,
-       thd->leaf_count --;
+  for (first_select_leaf_table= select_lex->leaf_tables->next_leaf;
        first_select_leaf_table &&
        first_select_leaf_table->belong_to_view &&
        first_select_leaf_table->belong_to_view ==
        lex->leaf_tables_insert->belong_to_view;
-       first_select_leaf_table= first_select_leaf_table->next_leaf,
-       thd->leaf_count --)
+       first_select_leaf_table= first_select_leaf_table->next_leaf)
   {}
   select_lex->leaf_tables= first_select_leaf_table;
   DBUG_RETURN(FALSE);
@@ -2691,6 +2690,7 @@ select_insert::~select_insert()
   if (table)
   {
     table->next_number_field=0;
+    table->auto_increment_field_not_null= FALSE;
     table->file->ha_reset();
   }
   thd->count_cuted_fields= CHECK_FIELD_IGNORE;
diff --git a/sql/sql_list.h b/sql/sql_list.h
index af30cbe0d6a6add735ff8af51a094c476279f0f7..ba61a931e043d01c8bebe1c19c1ae3b22028c9ba 100644
--- a/sql/sql_list.h
+++ b/sql/sql_list.h
@@ -23,7 +23,7 @@
 class Sql_alloc
 {
 public:
-  static void *operator new(size_t size)
+  static void *operator new(size_t size) throw ()
   {
     return (void*) sql_alloc((uint) size);
   }
@@ -31,9 +31,9 @@ public:
   {
     return (void*) sql_alloc((uint) size);
   }
-  static void *operator new[](size_t size, MEM_ROOT *mem_root)
+  static void *operator new[](size_t size, MEM_ROOT *mem_root) throw ()
   { return (void*) alloc_root(mem_root, (uint) size); }
-  static void *operator new(size_t size, MEM_ROOT *mem_root)
+  static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
   { return (void*) alloc_root(mem_root, (uint) size); }
   static void operator delete(void *ptr, size_t size) { TRASH(ptr, size); }
   static void operator delete(void *ptr, MEM_ROOT *mem_root)
diff --git a/sql/sql_load.cc b/sql/sql_load.cc
index cf356a4b336759b0152147a8b5325a22c905e7ba..7d2c2281bbac935a8144ba39a58b620c5cb5db68 100644
--- a/sql/sql_load.cc
+++ b/sql/sql_load.cc
@@ -512,6 +512,7 @@ err:
     mysql_unlock_tables(thd, thd->lock);
     thd->lock=0;
   }
+  table->auto_increment_field_not_null= FALSE;
   thd->abort_on_warning= 0;
   DBUG_RETURN(error);
 }
@@ -609,8 +610,6 @@ read_fixed_length(THD *thd, COPY_INFO &info, TABLE_LIST *table_list,
       {
 	uint length;
 	byte save_chr;
-        if (field == table->next_number_field)
-          table->auto_increment_field_not_null= TRUE;
 	if ((length=(uint) (read_info.row_end-pos)) >
 	    field->field_length)
 	  length=field->field_length;
diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc
index 31ab6e37cb6d23e3f64321dc44f7dedf32cdde13..17f1c73dbcbea80834f06484556fa8d7d79f779b 100644
--- a/sql/sql_parse.cc
+++ b/sql/sql_parse.cc
@@ -4303,6 +4303,10 @@ create_sp_error:
     int error;
     LEX *lex= thd->lex;
     DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER"));
+
+    if (check_global_access(thd, SUPER_ACL))
+      break;
+
     if ((error= create_server(thd, &lex->server_options)))
     {
       DBUG_PRINT("info", ("problem creating server <%s>",
@@ -4318,6 +4322,10 @@ create_sp_error:
     int error;
     LEX *lex= thd->lex;
     DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER"));
+
+    if (check_global_access(thd, SUPER_ACL))
+      break;
+
     if ((error= alter_server(thd, &lex->server_options)))
     {
       DBUG_PRINT("info", ("problem altering server <%s>",
@@ -4333,9 +4341,13 @@ create_sp_error:
     int err_code;
     LEX *lex= thd->lex;
     DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER"));
+
+    if (check_global_access(thd, SUPER_ACL))
+      break;
+
     if ((err_code= drop_server(thd, &lex->server_options)))
     {
-      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_EXISTS)
+      if (! lex->drop_if_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST)
       {
         DBUG_PRINT("info", ("problem dropping server %s",
                             lex->server_options.server_name));
diff --git a/sql/sql_select.cc b/sql/sql_select.cc
index 582df11c8c140c75e0e6567e2abd32792b6a58ab..7fd290fe4524e8abd9af06ca71f2227ac6bcffec 100644
--- a/sql/sql_select.cc
+++ b/sql/sql_select.cc
@@ -413,7 +413,12 @@ JOIN::prepare(Item ***rref_pointer_array,
                                     tables_list, &select_lex->leaf_tables,
                                     FALSE, SELECT_ACL, SELECT_ACL))
       DBUG_RETURN(-1);
-  tables= thd->leaf_count;
+ 
+  TABLE_LIST *table_ptr;
+  for (table_ptr= select_lex->leaf_tables;
+       table_ptr;
+       table_ptr= table_ptr->next_leaf)
+    tables++;
 
   if (setup_wild(thd, tables_list, fields_list, &all_fields, wild_num) ||
       select_lex->setup_ref_array(thd, og_num) ||
@@ -8977,20 +8982,19 @@ static Field *create_tmp_field_from_item(THD *thd, Item *item, TABLE *table,
   
     enum enum_field_types type;
     /*
-      DATE/TIME fields have STRING_RESULT result type. To preserve
-      type they needed to be handled separately.
+      DATE/TIME and GEOMETRY fields have STRING_RESULT result type. 
+      To preserve type they needed to be handled separately.
     */
     if ((type= item->field_type()) == MYSQL_TYPE_DATETIME ||
         type == MYSQL_TYPE_TIME || type == MYSQL_TYPE_DATE ||
-        type == MYSQL_TYPE_TIMESTAMP)
+        type == MYSQL_TYPE_TIMESTAMP || type == MYSQL_TYPE_GEOMETRY)
       new_field= item->tmp_table_field_from_field_type(table, 1);
     /* 
       Make sure that the blob fits into a Field_varstring which has 
       2-byte lenght. 
     */
     else if (item->max_length/item->collation.collation->mbmaxlen > 255 &&
-             item->max_length/item->collation.collation->mbmaxlen < UINT_MAX16
-             && convert_blob_length)
+             convert_blob_length < UINT_MAX16 && convert_blob_length)
       new_field= new Field_varstring(convert_blob_length, maybe_null,
                                      item->name, table->s,
                                      item->collation.collation);
@@ -9417,13 +9421,19 @@ create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
     {
       if (item->with_sum_func && type != Item::SUM_FUNC_ITEM)
       {
-	/*
-	  Mark that the we have ignored an item that refers to a summary
-	  function. We need to know this if someone is going to use
-	  DISTINCT on the result.
-	*/
-	param->using_indirect_summary_function=1;
-	continue;
+        if (item->used_tables() & OUTER_REF_TABLE_BIT)
+          item->update_used_tables();
+        if (type == Item::SUBSELECT_ITEM ||
+            (item->used_tables() & ~OUTER_REF_TABLE_BIT))
+        {
+	  /*
+	    Mark that the we have ignored an item that refers to a summary
+	    function. We need to know this if someone is going to use
+	    DISTINCT on the result.
+	  */
+	  param->using_indirect_summary_function=1;
+	  continue;
+        }
       }
       if (item->const_item() && (int) hidden_field_count <= 0)
         continue; // We don't have to store this
@@ -9608,6 +9618,7 @@ create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
     share->default_values= table->record[1]+alloc_length;
   }
   copy_func[0]=0;				// End marker
+  param->func_count= copy_func - param->items_to_copy; 
 
   setup_tmp_table_column_bitmaps(table, bitmaps);
 
@@ -13824,6 +13835,7 @@ count_field_types(TMP_TABLE_PARAM *param, List<Item> &fields,
 	if (!sum_item->quick_group)
 	  param->quick_group=0;			// UDF SUM function
 	param->sum_func_count++;
+        param->func_count++;
 
 	for (uint i=0 ; i < sum_item->arg_count ; i++)
 	{
diff --git a/sql/sql_servers.cc b/sql/sql_servers.cc
index 7b3b71cdd9a060c89d1bcfb5553c77d219fa55ae..d21864e857258d0ee3ea3db39dae97e8256c7846 100644
--- a/sql/sql_servers.cc
+++ b/sql/sql_servers.cc
@@ -16,6 +16,21 @@
 
 /*
   The servers are saved in the system table "servers"
+  
+  Currently, when the user performs an ALTER SERVER or a DROP SERVER
+  operation, it will cause all open tables which refer to the named
+  server connection to be flushed. This may cause some undesirable
+  behaviour with regard to currently running transactions. It is 
+  expected that the DBA knows what s/he is doing when s/he performs
+  the ALTER SERVER or DROP SERVER operation.
+  
+  TODO:
+  It is desirable for us to implement a callback mechanism instead where
+  callbacks can be registered for specific server protocols. The callback
+  will be fired when such a server name has been created/altered/dropped
+  or when statistics are to be gathered such as how many actual connections.
+  Storage engines etc will be able to make use of the callback so that
+  currently running transactions etc will not be disrupted.
 */
 
 #include "mysql_priv.h"
@@ -25,15 +40,43 @@
 #include "sp_head.h"
 #include "sp.h"
 
-static my_bool servers_load(THD *thd, TABLE_LIST *tables);
-HASH servers_cache;
-pthread_mutex_t servers_cache_mutex;                // To init the hash
-uint servers_cache_initialised=FALSE;
-/* Version of server table. incremented by servers_load */
-static uint servers_version=0;
+/*
+  We only use 1 mutex to guard the data structures - THR_LOCK_servers.
+  Read locked when only reading data and write-locked for all other access.
+*/
+
+static HASH servers_cache;
 static MEM_ROOT mem;
 static rw_lock_t THR_LOCK_servers;
 
+static bool get_server_from_table_to_cache(TABLE *table);
+
+/* insert functions */
+static int insert_server(THD *thd, FOREIGN_SERVER *server_options);
+static int insert_server_record(TABLE *table, FOREIGN_SERVER *server);
+static int insert_server_record_into_cache(FOREIGN_SERVER *server);
+static void prepare_server_struct_for_insert(LEX_SERVER_OPTIONS *server_options,
+                                             FOREIGN_SERVER *server);
+/* drop functions */ 
+static int delete_server_record(TABLE *table,
+                                char *server_name,
+                                int server_name_length);
+static int delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options);
+
+/* update functions */
+static void prepare_server_struct_for_update(LEX_SERVER_OPTIONS *server_options,
+                                             FOREIGN_SERVER *existing,
+                                             FOREIGN_SERVER *altered);
+static int update_server(THD *thd, FOREIGN_SERVER *existing, 
+					     FOREIGN_SERVER *altered);
+static int update_server_record(TABLE *table, FOREIGN_SERVER *server);
+static int update_server_record_in_cache(FOREIGN_SERVER *existing,
+                                         FOREIGN_SERVER *altered);
+/* utility functions */
+static void merge_server_struct(FOREIGN_SERVER *from, FOREIGN_SERVER *to);
+
+
+
 static byte *servers_cache_get_key(FOREIGN_SERVER *server, uint *length,
 			       my_bool not_used __attribute__((unused)))
 {
@@ -46,6 +89,7 @@ static byte *servers_cache_get_key(FOREIGN_SERVER *server, uint *length,
   DBUG_RETURN((byte*) server->server_name);
 }
 
+
 /*
   Initialize structures responsible for servers used in federated
   server scheme information for them from the server
@@ -65,35 +109,27 @@ static byte *servers_cache_get_key(FOREIGN_SERVER *server, uint *length,
     1	Could not initialize servers
 */
 
-my_bool servers_init(bool dont_read_servers_table)
+bool servers_init(bool dont_read_servers_table)
 {
   THD  *thd;
-  my_bool return_val= 0;
+  bool return_val= FALSE;
   DBUG_ENTER("servers_init");
 
   /* init the mutex */
-  if (pthread_mutex_init(&servers_cache_mutex, MY_MUTEX_INIT_FAST))
-    DBUG_RETURN(1);
-
   if (my_rwlock_init(&THR_LOCK_servers, NULL))
-    DBUG_RETURN(1);
+    DBUG_RETURN(TRUE);
 
   /* initialise our servers cache */
   if (hash_init(&servers_cache, system_charset_info, 32, 0, 0,
                 (hash_get_key) servers_cache_get_key, 0, 0))
   {
-    return_val= 1; /* we failed, out of memory? */
+    return_val= TRUE; /* we failed, out of memory? */
     goto end;
   }
 
   /* Initialize the mem root for data */
   init_alloc_root(&mem, ACL_ALLOC_BLOCK_SIZE, 0);
 
-  /*
-    at this point, the cache is initialised, let it be known
-  */
-  servers_cache_initialised= TRUE;
-
   if (dont_read_servers_table)
     goto end;
 
@@ -101,7 +137,7 @@ my_bool servers_init(bool dont_read_servers_table)
     To be able to run this from boot, we allocate a temporary THD
   */
   if (!(thd=new THD))
-    DBUG_RETURN(1);
+    DBUG_RETURN(TRUE);
   thd->thread_stack= (char*) &thd;
   thd->store_globals();
   /*
@@ -131,19 +167,13 @@ end:
     TRUE   Error
 */
 
-static my_bool servers_load(THD *thd, TABLE_LIST *tables)
+static bool servers_load(THD *thd, TABLE_LIST *tables)
 {
   TABLE *table;
   READ_RECORD read_record_info;
-  my_bool return_val= TRUE;
+  bool return_val= TRUE;
   DBUG_ENTER("servers_load");
 
-  if (!servers_cache_initialised)
-    DBUG_RETURN(0);
-
-  /* need to figure out how to utilise this variable */
-  servers_version++; /* servers updated */
-
   /* first, send all cached rows to sleep with the fishes, oblivion!
      I expect this crappy comment replaced */
   free_root(&mem, MYF(MY_MARK_BLOCKS_FREE));
@@ -157,7 +187,7 @@ static my_bool servers_load(THD *thd, TABLE_LIST *tables)
       goto end;
   }
 
-  return_val=0;
+  return_val= FALSE;
 
 end:
   end_read_record(&read_record_info);
@@ -184,10 +214,10 @@ end:
     TRUE   Failure
 */
 
-my_bool servers_reload(THD *thd)
+bool servers_reload(THD *thd)
 {
   TABLE_LIST tables[1];
-  my_bool return_val= 1;
+  bool return_val= TRUE;
   DBUG_ENTER("servers_reload");
 
   if (thd->locked_tables)
@@ -197,10 +227,9 @@ my_bool servers_reload(THD *thd)
     close_thread_tables(thd);
   }
 
-  /*
-    To avoid deadlocks we should obtain table locks before
-    obtaining servers_cache->lock mutex.
-  */
+  DBUG_PRINT("info", ("locking servers_cache"));
+  rw_wrlock(&THR_LOCK_servers);
+
   bzero((char*) tables, sizeof(tables));
   tables[0].alias= tables[0].table_name= (char*) "servers";
   tables[0].db= (char*) "mysql";
@@ -213,12 +242,6 @@ my_bool servers_reload(THD *thd)
     goto end;
   }
 
-  DBUG_PRINT("info", ("locking servers_cache"));
-  VOID(pthread_mutex_lock(&servers_cache_mutex));
-
-  //old_servers_cache= servers_cache;
-  //old_mem=mem;
-
   if ((return_val= servers_load(thd, tables)))
   {					// Error. Revert to old list
     /* blast, for now, we have no servers, discuss later way to preserve */
@@ -227,14 +250,14 @@ my_bool servers_reload(THD *thd)
     servers_free();
   }
 
-  DBUG_PRINT("info", ("unlocking servers_cache"));
-  VOID(pthread_mutex_unlock(&servers_cache_mutex));
-
 end:
   close_thread_tables(thd);
+  DBUG_PRINT("info", ("unlocking servers_cache"));
+  rw_unlock(&THR_LOCK_servers);
   DBUG_RETURN(return_val);
 }
 
+
 /*
   Initialize structures responsible for servers used in federated
   server scheme information for them from the server
@@ -261,7 +284,8 @@ end:
     1	could not insert server struct into global servers cache
 */
 
-my_bool get_server_from_table_to_cache(TABLE *table)
+static bool 
+get_server_from_table_to_cache(TABLE *table)
 {
   /* alloc a server struct */
   char *ptr;
@@ -309,68 +333,6 @@ my_bool get_server_from_table_to_cache(TABLE *table)
   DBUG_RETURN(FALSE);
 }
 
-/*
-  SYNOPSIS
-    server_exists_in_table()
-      THD   *thd - thread pointer
-      LEX_SERVER_OPTIONS *server_options - pointer to Lex->server_options
-
-  NOTES
-    This function takes a LEX_SERVER_OPTIONS struct, which is very much the
-    same type of structure as a FOREIGN_SERVER, it contains the values parsed
-    in any one of the [CREATE|DELETE|DROP] SERVER statements. Using the
-    member "server_name", index_read_idx either founds the record and returns
-    1, or doesn't find the record, and returns 0
-
-  RETURN VALUES
-    0   record not found
-    1	record found
-*/
-
-my_bool server_exists_in_table(THD *thd, LEX_SERVER_OPTIONS *server_options)
-{
-  int result= 1;
-  int error= 0;
-  TABLE_LIST tables;
-  TABLE *table;
-  DBUG_ENTER("server_exists");
-
-  bzero((char*) &tables, sizeof(tables));
-  tables.db= (char*) "mysql";
-  tables.alias= tables.table_name= (char*) "servers";
-
-  /* need to open before acquiring THR_LOCK_plugin or it will deadlock */
-  if (! (table= open_ltable(thd, &tables, TL_WRITE)))
-    DBUG_RETURN(TRUE);
-
-  table->use_all_columns();
-
-  rw_wrlock(&THR_LOCK_servers);
-  VOID(pthread_mutex_lock(&servers_cache_mutex));
-
-  /* set the field that's the PK to the value we're looking for */
-  table->field[0]->store(server_options->server_name,
-                         server_options->server_name_length,
-                         system_charset_info);
-
-  if ((error= table->file->index_read_idx(table->record[0], 0,
-                                   (byte *)table->field[0]->ptr, HA_WHOLE_KEY,
-                                   HA_READ_KEY_EXACT)))
-  {
-    if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
-    {
-      table->file->print_error(error, MYF(0));
-      result= -1;
-    }
-    result= 0;
-    DBUG_PRINT("info",("record for server '%s' not found!",
-                       server_options->server_name));
-  }
-
-  VOID(pthread_mutex_unlock(&servers_cache_mutex));
-  rw_unlock(&THR_LOCK_servers);
-  DBUG_RETURN(result);
-}
 
 /*
   SYNOPSIS
@@ -382,15 +344,18 @@ my_bool server_exists_in_table(THD *thd, LEX_SERVER_OPTIONS *server_options)
     This function takes a server object that is has all members properly
     prepared, ready to be inserted both into the mysql.servers table and
     the servers cache.
+	
+    THR_LOCK_servers must be write locked.
 
   RETURN VALUES
     0  - no error
     other - error code
 */
 
-int insert_server(THD *thd, FOREIGN_SERVER *server)
+static int 
+insert_server(THD *thd, FOREIGN_SERVER *server)
 {
-  int error= 0;
+  int error= -1;
   TABLE_LIST tables;
   TABLE *table;
 
@@ -402,13 +367,7 @@ int insert_server(THD *thd, FOREIGN_SERVER *server)
 
   /* need to open before acquiring THR_LOCK_plugin or it will deadlock */
   if (! (table= open_ltable(thd, &tables, TL_WRITE)))
-    DBUG_RETURN(TRUE);
-
-  /* lock mutex to make sure no changes happen */
-  VOID(pthread_mutex_lock(&servers_cache_mutex));
-
-  /* lock table */
-  rw_wrlock(&THR_LOCK_servers);
+    goto end;
 
   /* insert the server into the table */
   if ((error= insert_server_record(table, server)))
@@ -419,12 +378,10 @@ int insert_server(THD *thd, FOREIGN_SERVER *server)
     goto end;
 
 end:
-  /* unlock the table */
-  rw_unlock(&THR_LOCK_servers);
-  VOID(pthread_mutex_unlock(&servers_cache_mutex));
   DBUG_RETURN(error);
 }
 
+
 /*
   SYNOPSIS
     int insert_server_record_into_cache()
@@ -434,13 +391,16 @@ end:
     This function takes a FOREIGN_SERVER pointer to an allocated (root mem)
     and inserts it into the global servers cache
 
+    THR_LOCK_servers must be write locked.
+
   RETURN VALUE
     0   - no error
     >0  - error code
 
 */
 
-int insert_server_record_into_cache(FOREIGN_SERVER *server)
+static int 
+insert_server_record_into_cache(FOREIGN_SERVER *server)
 {
   int error=0;
   DBUG_ENTER("insert_server_record_into_cache");
@@ -461,6 +421,7 @@ int insert_server_record_into_cache(FOREIGN_SERVER *server)
   DBUG_RETURN(error);
 }
 
+
 /*
   SYNOPSIS
     store_server_fields()
@@ -478,7 +439,8 @@ int insert_server_record_into_cache(FOREIGN_SERVER *server)
 
 */
 
-void store_server_fields(TABLE *table, FOREIGN_SERVER *server)
+static void 
+store_server_fields(TABLE *table, FOREIGN_SERVER *server)
 {
 
   table->use_all_columns();
@@ -539,6 +501,7 @@ void store_server_fields(TABLE *table, FOREIGN_SERVER *server)
 
   */
 
+static
 int insert_server_record(TABLE *table, FOREIGN_SERVER *server)
 {
   int error;
@@ -605,9 +568,11 @@ int insert_server_record(TABLE *table, FOREIGN_SERVER *server)
 
 int drop_server(THD *thd, LEX_SERVER_OPTIONS *server_options)
 {
-  int error= 0;
+  int error;
   TABLE_LIST tables;
   TABLE *table;
+  LEX_STRING name= { server_options->server_name, 
+                     server_options->server_name_length };
 
   DBUG_ENTER("drop_server");
   DBUG_PRINT("info", ("server name server->server_name %s",
@@ -617,28 +582,35 @@ int drop_server(THD *thd, LEX_SERVER_OPTIONS *server_options)
   tables.db= (char*) "mysql";
   tables.alias= tables.table_name= (char*) "servers";
 
-  /* need to open before acquiring THR_LOCK_plugin or it will deadlock */
-  if (! (table= open_ltable(thd, &tables, TL_WRITE)))
-    DBUG_RETURN(TRUE);
-
   rw_wrlock(&THR_LOCK_servers);
-  VOID(pthread_mutex_lock(&servers_cache_mutex));
 
+  /* hit the memory hit first */
+  if ((error= delete_server_record_in_cache(server_options)))
+    goto end;
 
-  if ((error= delete_server_record(table,
-                                   server_options->server_name,
-                                   server_options->server_name_length)))
+  if (! (table= open_ltable(thd, &tables, TL_WRITE)))
+  {
+    error= my_errno;
     goto end;
+  }
 
+  error= delete_server_record(table, name.str, name.length);
 
-  if ((error= delete_server_record_in_cache(server_options)))
-    goto end;
+  /* close the servers table before we call closed_cached_connection_tables */
+  close_thread_tables(thd);
+
+  if (close_cached_connection_tables(thd, TRUE, &name))
+  {
+    push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+                        ER_UNKNOWN_ERROR, "Server connection in use");
+  }
 
 end:
-  VOID(pthread_mutex_unlock(&servers_cache_mutex));
   rw_unlock(&THR_LOCK_servers);
   DBUG_RETURN(error);
 }
+
+
 /*
 
   SYNOPSIS
@@ -657,10 +629,10 @@ end:
 
 */
 
-int delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options)
+static int 
+delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options)
 {
-
-  int error= 0;
+  int error= ER_FOREIGN_SERVER_DOESNT_EXIST;
   FOREIGN_SERVER *server;
   DBUG_ENTER("delete_server_record_in_cache");
 
@@ -676,7 +648,7 @@ int delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options)
     DBUG_PRINT("info", ("server_name %s length %d not found!",
                         server_options->server_name,
                         server_options->server_name_length));
-    // what should be done if not found in the cache?
+    goto end;
   }
   /*
     We succeded in deletion of the server to the table, now delete
@@ -686,14 +658,15 @@ int delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options)
                      server->server_name,
                      server->server_name_length));
 
-  if (server)
-    VOID(hash_delete(&servers_cache, (byte*) server));
-
-  servers_version++; /* servers updated */
+  VOID(hash_delete(&servers_cache, (byte*) server));
+  
+  error= 0;
 
+end:
   DBUG_RETURN(error);
 }
 
+
 /*
 
   SYNOPSIS
@@ -713,6 +686,8 @@ int delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options)
     table for the particular server via the call to update_server_record,
     and in the servers_cache via update_server_record_in_cache. 
 
+    THR_LOCK_servers must be write locked.
+
   RETURN VALUE
     0 - no error
     >0 - error code
@@ -721,7 +696,7 @@ int delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options)
 
 int update_server(THD *thd, FOREIGN_SERVER *existing, FOREIGN_SERVER *altered)
 {
-  int error= 0;
+  int error;
   TABLE *table;
   TABLE_LIST tables;
   DBUG_ENTER("update_server");
@@ -731,19 +706,26 @@ int update_server(THD *thd, FOREIGN_SERVER *existing, FOREIGN_SERVER *altered)
   tables.alias= tables.table_name= (char*)"servers";
 
   if (!(table= open_ltable(thd, &tables, TL_WRITE)))
-    DBUG_RETURN(1);
+  {
+    error= my_errno;
+    goto end;
+  }
 
-  rw_wrlock(&THR_LOCK_servers);
   if ((error= update_server_record(table, altered)))
     goto end;
 
-  update_server_record_in_cache(existing, altered);
+  error= update_server_record_in_cache(existing, altered);
+
+  /*
+	Perform a reload so we don't have a 'hole' in our mem_root
+  */
+  servers_load(thd, &tables);
 
 end:
-  rw_unlock(&THR_LOCK_servers);
   DBUG_RETURN(error);
 }
 
+
 /*
 
   SYNOPSIS
@@ -760,6 +742,8 @@ end:
     HASH, then the updated record inserted, in essence replacing the old
     record.
 
+    THR_LOCK_servers must be write locked.
+
   RETURN VALUE
     0 - no error
     1 - error
@@ -790,13 +774,13 @@ int update_server_record_in_cache(FOREIGN_SERVER *existing,
   {
     DBUG_PRINT("info", ("had a problem inserting server %s at %lx",
                         altered->server_name, (long unsigned int) altered));
-    error= 1;
+    error= ER_OUT_OF_RESOURCES;
   }
 
-  servers_version++; /* servers updated */
   DBUG_RETURN(error);
 }
 
+
 /*
 
   SYNOPSIS
@@ -829,9 +813,9 @@ void merge_server_struct(FOREIGN_SERVER *from, FOREIGN_SERVER *to)
     to->password= strdup_root(&mem, from->password);
   if (to->port == -1)
     to->port= from->port;
-  if (!to->socket)
+  if (!to->socket && from->socket)
     to->socket= strdup_root(&mem, from->socket);
-  if (!to->scheme)
+  if (!to->scheme && from->scheme)
     to->scheme= strdup_root(&mem, from->scheme);
   if (!to->owner)
     to->owner= strdup_root(&mem, from->owner);
@@ -839,6 +823,7 @@ void merge_server_struct(FOREIGN_SERVER *from, FOREIGN_SERVER *to)
   DBUG_VOID_RETURN;
 }
 
+
 /*
 
   SYNOPSIS
@@ -861,7 +846,9 @@ void merge_server_struct(FOREIGN_SERVER *from, FOREIGN_SERVER *to)
 
 */
 
-int update_server_record(TABLE *table, FOREIGN_SERVER *server)
+
+static int 
+update_server_record(TABLE *table, FOREIGN_SERVER *server)
 {
   int error=0;
   DBUG_ENTER("update_server_record");
@@ -876,10 +863,7 @@ int update_server_record(TABLE *table, FOREIGN_SERVER *server)
                                    HA_READ_KEY_EXACT)))
   {
     if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
-    {
       table->file->print_error(error, MYF(0));
-      error= 1;
-    }
     DBUG_PRINT("info",("server not found!"));
     error= ER_FOREIGN_SERVER_DOESNT_EXIST;
   }
@@ -899,6 +883,7 @@ end:
   DBUG_RETURN(error);
 }
 
+
 /*
 
   SYNOPSIS
@@ -914,11 +899,11 @@ end:
 
 */
 
-int delete_server_record(TABLE *table,
-                         char *server_name,
-                         int server_name_length)
+static int 
+delete_server_record(TABLE *table,
+                     char *server_name, int server_name_length)
 {
-  int error= 0;
+  int error;
   DBUG_ENTER("delete_server_record");
   table->use_all_columns();
 
@@ -930,10 +915,7 @@ int delete_server_record(TABLE *table,
                                    HA_READ_KEY_EXACT)))
   {
     if (error != HA_ERR_KEY_NOT_FOUND && error != HA_ERR_END_OF_FILE)
-    {
       table->file->print_error(error, MYF(0));
-      error= 1;
-    }
     DBUG_PRINT("info",("server not found!"));
     error= ER_FOREIGN_SERVER_DOESNT_EXIST;
   }
@@ -962,28 +944,35 @@ int delete_server_record(TABLE *table,
 
 int create_server(THD *thd, LEX_SERVER_OPTIONS *server_options)
 {
-  int error;
+  int error= ER_FOREIGN_SERVER_EXISTS;
   FOREIGN_SERVER *server;
 
   DBUG_ENTER("create_server");
   DBUG_PRINT("info", ("server_options->server_name %s",
                       server_options->server_name));
 
+  rw_wrlock(&THR_LOCK_servers);
+
+  /* hit the memory first */
+  if (hash_search(&servers_cache, (byte*) server_options->server_name,
+				   server_options->server_name_length))
+    goto end;
+
   server= (FOREIGN_SERVER *)alloc_root(&mem,
                                        sizeof(FOREIGN_SERVER));
 
-  if ((error= prepare_server_struct_for_insert(server_options, server)))
-    goto end;
+  prepare_server_struct_for_insert(server_options, server);
 
-  if ((error= insert_server(thd, server)))
-    goto end;
+  error= insert_server(thd, server);
 
   DBUG_PRINT("info", ("error returned %d", error));
 
 end:
+  rw_unlock(&THR_LOCK_servers);
   DBUG_RETURN(error);
 }
 
+
 /*
 
   SYNOPSIS
@@ -1000,37 +989,44 @@ end:
 
 int alter_server(THD *thd, LEX_SERVER_OPTIONS *server_options)
 {
-  int error= 0;
+  int error= ER_FOREIGN_SERVER_DOESNT_EXIST;
   FOREIGN_SERVER *altered, *existing;
+  LEX_STRING name= { server_options->server_name, 
+                     server_options->server_name_length };
   DBUG_ENTER("alter_server");
   DBUG_PRINT("info", ("server_options->server_name %s",
                       server_options->server_name));
 
+  rw_wrlock(&THR_LOCK_servers);
+
+  if (!(existing= (FOREIGN_SERVER *) hash_search(&servers_cache,
+                                                 (byte*) name.str,
+                                                 name.length)))
+    goto end;
+
   altered= (FOREIGN_SERVER *)alloc_root(&mem,
                                         sizeof(FOREIGN_SERVER));
 
-  VOID(pthread_mutex_lock(&servers_cache_mutex));
+  prepare_server_struct_for_update(server_options, existing, altered);
 
-  if (!(existing= (FOREIGN_SERVER *) hash_search(&servers_cache,
-                                                 (byte*) server_options->server_name,
-                                               server_options->server_name_length)))
-  {
-    error= ER_FOREIGN_SERVER_DOESNT_EXIST;
-    goto end;
-  }
+  error= update_server(thd, existing, altered);
 
-  if ((error= prepare_server_struct_for_update(server_options, existing, altered)))
-    goto end;
+  /* close the servers table before we call closed_cached_connection_tables */
+  close_thread_tables(thd);
 
-  if ((error= update_server(thd, existing, altered)))
-    goto end;
+  if (close_cached_connection_tables(thd, FALSE, &name))
+  {
+    push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+                        ER_UNKNOWN_ERROR, "Server connection in use");
+  }
 
 end:
   DBUG_PRINT("info", ("error returned %d", error));
-  VOID(pthread_mutex_unlock(&servers_cache_mutex));
+  rw_unlock(&THR_LOCK_servers);
   DBUG_RETURN(error);
 }
 
+
 /*
 
   SYNOPSIS
@@ -1041,19 +1037,17 @@ end:
   NOTES
 
   RETURN VALUE
-    0 - no error
+    none
 
 */
 
-int prepare_server_struct_for_insert(LEX_SERVER_OPTIONS *server_options,
-                                     FOREIGN_SERVER *server)
+static void
+prepare_server_struct_for_insert(LEX_SERVER_OPTIONS *server_options,
+                                 FOREIGN_SERVER *server)
 {
-  int error;
   char *unset_ptr= (char*)"";
   DBUG_ENTER("prepare_server_struct");
 
-  error= 0;
-
   /* these two MUST be set */
   server->server_name= strdup_root(&mem, server_options->server_name);
   server->server_name_length= server_options->server_name_length;
@@ -1083,7 +1077,7 @@ int prepare_server_struct_for_insert(LEX_SERVER_OPTIONS *server_options,
   server->owner= server_options->owner ?
     strdup_root(&mem, server_options->owner) : unset_ptr;
 
-  DBUG_RETURN(error);
+  DBUG_VOID_RETURN;
 }
 
 /*
@@ -1099,13 +1093,12 @@ int prepare_server_struct_for_insert(LEX_SERVER_OPTIONS *server_options,
 
 */
 
-int prepare_server_struct_for_update(LEX_SERVER_OPTIONS *server_options,
-                                     FOREIGN_SERVER *existing,
-                                     FOREIGN_SERVER *altered)
+static void
+prepare_server_struct_for_update(LEX_SERVER_OPTIONS *server_options,
+                                 FOREIGN_SERVER *existing,
+                                 FOREIGN_SERVER *altered)
 {
-  int error;
   DBUG_ENTER("prepare_server_struct_for_update");
-  error= 0;
 
   altered->server_name= strdup_root(&mem, server_options->server_name);
   altered->server_name_length= server_options->server_name_length;
@@ -1156,7 +1149,7 @@ int prepare_server_struct_for_update(LEX_SERVER_OPTIONS *server_options,
     (strcmp(server_options->owner, existing->owner))) ?
       strdup_root(&mem, server_options->owner) : 0;
 
-  DBUG_RETURN(error);
+  DBUG_VOID_RETURN;
 }
 
 /*
@@ -1175,16 +1168,65 @@ int prepare_server_struct_for_update(LEX_SERVER_OPTIONS *server_options,
 void servers_free(bool end)
 {
   DBUG_ENTER("servers_free");
-  if (!servers_cache_initialised)
+  if (!hash_inited(&servers_cache))
+    DBUG_VOID_RETURN;
+  if (!end)
+  {
+    free_root(&mem, MYF(MY_MARK_BLOCKS_FREE));
+	my_hash_reset(&servers_cache);
     DBUG_VOID_RETURN;
-  VOID(pthread_mutex_destroy(&servers_cache_mutex));
-  servers_cache_initialised=0;
+  }
+  rwlock_destroy(&THR_LOCK_servers);
   free_root(&mem,MYF(0));
   hash_free(&servers_cache);
   DBUG_VOID_RETURN;
 }
 
 
+/*
+  SYNOPSIS
+
+  clone_server(MEM_ROOT *mem_root, FOREIGN_SERVER *orig, FOREIGN_SERVER *buff)
+
+  Create a clone of FOREIGN_SERVER. If the supplied mem_root is of
+  thd->mem_root then the copy is automatically disposed at end of statement.
+
+  NOTES
+
+  ARGS
+   MEM_ROOT pointer (strings are copied into this mem root) 
+   FOREIGN_SERVER pointer (made a copy of)
+   FOREIGN_SERVER buffer (if not-NULL, this pointer is returned)
+
+  RETURN VALUE
+   FOREIGN_SEVER pointer (copy of one supplied FOREIGN_SERVER)
+*/
+
+static FOREIGN_SERVER *clone_server(MEM_ROOT *mem, const FOREIGN_SERVER *server,
+                                    FOREIGN_SERVER *buffer)
+{
+  DBUG_ENTER("sql_server.cc:clone_server");
+
+  if (!buffer)
+    buffer= (FOREIGN_SERVER *) alloc_root(mem, sizeof(FOREIGN_SERVER));
+
+  buffer->server_name= strmake_root(mem, server->server_name,
+                                    server->server_name_length);
+  buffer->port= server->port;
+  buffer->server_name_length= server->server_name_length;
+  
+  /* TODO: We need to examine which of these can really be NULL */
+  buffer->db= server->db ? strdup_root(mem, server->db) : NULL;
+  buffer->scheme= server->scheme ? strdup_root(mem, server->scheme) : NULL;
+  buffer->username= server->username? strdup_root(mem, server->username): NULL;
+  buffer->password= server->password? strdup_root(mem, server->password): NULL;
+  buffer->socket= server->socket ? strdup_root(mem, server->socket) : NULL;
+  buffer->owner= server->owner ? strdup_root(mem, server->owner) : NULL;
+  buffer->host= server->host ? strdup_root(mem, server->host) : NULL;
+
+ DBUG_RETURN(buffer);
+}
+
 
 /*
 
@@ -1199,11 +1241,11 @@ void servers_free(bool end)
 
 */
 
-FOREIGN_SERVER *get_server_by_name(const char *server_name)
+FOREIGN_SERVER *get_server_by_name(MEM_ROOT *mem, const char *server_name,
+                                   FOREIGN_SERVER *buff)
 {
-  ulong error_num=0;
   uint server_name_length;
-  FOREIGN_SERVER *server= 0;
+  FOREIGN_SERVER *server;
   DBUG_ENTER("get_server_by_name");
   DBUG_PRINT("info", ("server_name %s", server_name));
 
@@ -1212,12 +1254,11 @@ FOREIGN_SERVER *get_server_by_name(const char *server_name)
   if (! server_name || !strlen(server_name))
   {
     DBUG_PRINT("info", ("server_name not defined!"));
-    error_num= 1;
     DBUG_RETURN((FOREIGN_SERVER *)NULL);
   }
 
   DBUG_PRINT("info", ("locking servers_cache"));
-  VOID(pthread_mutex_lock(&servers_cache_mutex));
+  rw_rdlock(&THR_LOCK_servers);
   if (!(server= (FOREIGN_SERVER *) hash_search(&servers_cache,
                                                (byte*) server_name,
                                                server_name_length)))
@@ -1226,8 +1267,12 @@ FOREIGN_SERVER *get_server_by_name(const char *server_name)
                         server_name, server_name_length));
     server= (FOREIGN_SERVER *) NULL;
   }
+  /* otherwise, make copy of server */
+  else
+    server= clone_server(mem, server, buff);
+
   DBUG_PRINT("info", ("unlocking servers_cache"));
-  VOID(pthread_mutex_unlock(&servers_cache_mutex));
+  rw_unlock(&THR_LOCK_servers);
   DBUG_RETURN(server);
 
 }
diff --git a/sql/sql_servers.h b/sql/sql_servers.h
index 23b8cefd5bb1f0ba4e4bd46f8995ce4224026960..63c691893d1ec39ab1c7711775a8d3b82925d9ae 100644
--- a/sql/sql_servers.h
+++ b/sql/sql_servers.h
@@ -25,40 +25,19 @@ typedef struct st_federated_server
 } FOREIGN_SERVER;
 
 /* cache handlers */
-my_bool servers_init(bool dont_read_server_table);
-my_bool servers_reload(THD *thd);
-my_bool get_server_from_table_to_cache(TABLE *table);
+bool servers_init(bool dont_read_server_table);
+bool servers_reload(THD *thd);
 void servers_free(bool end=0);
 
 /* insert functions */
 int create_server(THD *thd, LEX_SERVER_OPTIONS *server_options);
-int insert_server(THD *thd, FOREIGN_SERVER *server_options);
-int insert_server_record(TABLE *table, FOREIGN_SERVER *server);
-int insert_server_record_into_cache(FOREIGN_SERVER *server);
-void store_server_fields_for_insert(TABLE *table, FOREIGN_SERVER *server);
-void store_server_fields_for_insert(TABLE *table,
-                                    FOREIGN_SERVER *existing,
-                                    FOREIGN_SERVER *altered);
-int prepare_server_struct_for_insert(LEX_SERVER_OPTIONS *server_options,
-                                     FOREIGN_SERVER *server);
 
 /* drop functions */ 
 int drop_server(THD *thd, LEX_SERVER_OPTIONS *server_options);
-int delete_server_record(TABLE *table,
-                         char *server_name,
-                         int server_name_length);
-int delete_server_record_in_cache(LEX_SERVER_OPTIONS *server_options);
 
 /* update functions */
 int alter_server(THD *thd, LEX_SERVER_OPTIONS *server_options);
-int prepare_server_struct_for_update(LEX_SERVER_OPTIONS *server_options,
-                                     FOREIGN_SERVER *existing,
-                                     FOREIGN_SERVER *altered);
-int update_server(THD *thd, FOREIGN_SERVER *existing, FOREIGN_SERVER *altered);
-int update_server_record(TABLE *table, FOREIGN_SERVER *server);
-int update_server_record_in_cache(FOREIGN_SERVER *existing,
-                                  FOREIGN_SERVER *altered);
-/* utility functions */
-void merge_server_struct(FOREIGN_SERVER *from, FOREIGN_SERVER *to);
-FOREIGN_SERVER *get_server_by_name(const char *server_name);
-my_bool server_exists_in_table(THD *thd, char *server_name);
+
+/* lookup functions */
+FOREIGN_SERVER *get_server_by_name(MEM_ROOT *mem, const char *server_name,
+                                   FOREIGN_SERVER *server_buffer);
diff --git a/sql/sql_table.cc b/sql/sql_table.cc
index bb3f293941e12c9baac612038dae300ee5419fe4..3eb47ebae6ee7355cb61a202b65eb9fd5f60b8e7 100644
--- a/sql/sql_table.cc
+++ b/sql/sql_table.cc
@@ -6838,7 +6838,9 @@ copy_data_between_tables(TABLE *from,TABLE *to,
       copy_ptr->do_copy(copy_ptr);
     }
     prev_insert_id= to->file->next_insert_id;
-    if ((error=to->file->ha_write_row((byte*) to->record[0])))
+    error=to->file->write_row((byte*) to->record[0]);
+    to->auto_increment_field_not_null= FALSE;
+    if (error)
     {
       if (!ignore ||
           to->file->is_fatal_error(error, HA_CHECK_DUP))
diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy
index 03123617e33667a2b63b82b756e98d9b38045d56..36b0922479668989769796d731e6b4670ea1cff6 100644
--- a/sql/sql_yacc.yy
+++ b/sql/sql_yacc.yy
@@ -1774,7 +1774,7 @@ opt_ev_status: /* empty */ { $$= 0; }
             Lex->event_parse_data->status= Event_basic::ENABLED;
             $$= 1;
           }
-        | SLAVESIDE_DISABLE_SYM
+        | DISABLE_SYM ON SLAVE
           {
             Lex->event_parse_data->status= Event_basic::SLAVESIDE_DISABLED;
             $$= 1;
diff --git a/sql/table.h b/sql/table.h
index 6e435c9b3e343bc73f3c27c375a7aa459c2e9129..94df89ef992ae645d53650fbeb25c039585350cc 100644
--- a/sql/table.h
+++ b/sql/table.h
@@ -439,6 +439,11 @@ struct st_table {
   my_bool no_cache;
   /* To signal that we should reset query_id for tables and cols */
   my_bool clear_query_id;
+  /*
+    To indicate that a non-null value of the auto_increment field
+    was provided by the user or retrieved from the current record.
+    Used only in the MODE_NO_AUTO_VALUE_ON_ZERO mode.
+  */
   my_bool auto_increment_field_not_null;
   my_bool insert_or_update;             /* Can be used by the handler */
   my_bool alias_name_used;		/* true if table_name is alias */
diff --git a/storage/federated/ha_federated.cc b/storage/federated/ha_federated.cc
index 441c1785e74b2d83c281b0cdf3ff7d6569b1f4fe..aa7184268f5c6f868084dcd67a4b0a020bee82b7 100644
--- a/storage/federated/ha_federated.cc
+++ b/storage/federated/ha_federated.cc
@@ -43,23 +43,55 @@
   The create table will simply create the .frm file, and within the
   "CREATE TABLE" SQL, there SHALL be any of the following :
 
-  comment=scheme://username:password@hostname:port/database/tablename
-  comment=scheme://username@hostname/database/tablename
-  comment=scheme://username:password@hostname/database/tablename
-  comment=scheme://username:password@hostname/database/tablename
+  connection=scheme://username:password@hostname:port/database/tablename
+  connection=scheme://username@hostname/database/tablename
+  connection=scheme://username:password@hostname/database/tablename
+  connection=scheme://username:password@hostname/database/tablename
+
+  - OR -
+
+  As of 5.1 (See worklog #3031), federated now allows you to use a non-url
+  format, taking advantage of mysql.servers:
+
+  connection="connection_one"
+  connection="connection_one/table_foo"
 
   An example would be:
 
-  comment=mysql://username:password@hostname:port/database/tablename
+  connection=mysql://username:password@hostname:port/database/tablename
 
-  ***IMPORTANT***
+  or, if we had:
+
+  create server 'server_one' foreign data wrapper 'mysql' options
+  (HOST '127.0.0.1',
+  DATABASE 'db1',
+  USER 'root',
+  PASSWORD '',
+  PORT 3306,
+  SOCKET '',
+  OWNER 'root');
+
+  CREATE TABLE federated.t1 (
+    `id` int(20) NOT NULL,
+    `name` varchar(64) NOT NULL default ''
+    )
+  ENGINE="FEDERATED" DEFAULT CHARSET=latin1
+  CONNECTION='server_one';
+
+  So, this will have been the equivalent of
 
-  This is a first release, conceptual release
-  Only 'mysql://' is supported at this release.
+  CONNECTION="mysql://root@127.0.0.1:3306/db1/t1"
 
+  Then, we can also change the server to point to a new schema:
 
-  This comment connection string is necessary for the handler to be
-  able to connect to the foreign server.
+  ALTER SERVER 'server_one' options(DATABASE 'db2');
+
+  All subsequent calls will now be against db2.t1! Guess what? You don't
+  have to perform an alter table!
+
+  This connecton="connection string" is necessary for the handler to be
+  able to connect to the foreign server, either by URL, or by server
+  name. 
 
 
   The basic flow is this:
@@ -166,7 +198,7 @@
       KEY other_key (other))
        ENGINE="FEDERATED"
        DEFAULT CHARSET=latin1
-       COMMENT='root@127.0.0.1:9306/federated/test_federated';
+       CONNECTION='mysql://root@127.0.0.1:9306/federated/test_federated';
 
    Notice the "COMMENT" and "ENGINE" field? This is where you
    respectively set the engine type, "FEDERATED" and foreign
@@ -263,7 +295,7 @@
     To run these tests, go into ./mysql-test (based in the directory you
     built the server in)
 
-    ./mysql-test-run federatedd
+    ./mysql-test-run federated
 
     To run the test, or if you want to run the test and have debug info:
 
@@ -311,7 +343,7 @@
     -------------
 
     These were the files that were modified or created for this
-    Federated handler to work:
+    Federated handler to work, in 5.0:
 
     ./configure.in
     ./sql/Makefile.am
@@ -329,6 +361,13 @@
     ./sql/ha_federated.cc
     ./sql/ha_federated.h
 
+    In 5.1
+
+    my:~/mysql-build/mysql-5.1-bkbits patg$ ls storage/federated/
+    CMakeLists.txt                  Makefile.in                     ha_federated.h                  plug.in
+    Makefile                        SCCS                            libfederated.a
+    Makefile.am                     ha_federated.cc                 libfederated_a-ha_federated.o
+
 */
 
 
@@ -546,42 +585,39 @@ static int parse_url_error(FEDERATED_SHARE *share, TABLE *table, int error_num)
   int buf_len;
   DBUG_ENTER("ha_federated parse_url_error");
 
-  if (share->connection_string)
-  {
-    DBUG_PRINT("info",
-               ("error: parse_url. Returning error code %d \
-                freeing share->connection_string %lx",
-                error_num, (long unsigned int) share->connection_string));
-    my_free((gptr) share->connection_string, MYF(0));
-    share->connection_string= 0;
-  }
   buf_len= min(table->s->connect_string.length,
                FEDERATED_QUERY_BUFFER_SIZE-1);
   strmake(buf, table->s->connect_string.str, buf_len);
   my_error(error_num, MYF(0), buf);
   DBUG_RETURN(error_num);
 }
+
 /*
   retrieve server object which contains server meta-data 
   from the system table given a server's name, set share
   connection parameter members
 */
-int get_connection(FEDERATED_SHARE *share)
+int get_connection(MEM_ROOT *mem_root, FEDERATED_SHARE *share)
 {
   int error_num= ER_FOREIGN_SERVER_DOESNT_EXIST;
   char error_buffer[FEDERATED_QUERY_BUFFER_SIZE];
-  FOREIGN_SERVER *server;
+  FOREIGN_SERVER *server, server_buffer;
   DBUG_ENTER("ha_federated::get_connection");
 
+  /*
+    get_server_by_name() clones the server if exists and allocates
+	copies of strings in the supplied mem_root
+  */
   if (!(server=
-       get_server_by_name(share->connection_string)))
+       get_server_by_name(mem_root, share->connection_string, &server_buffer)))
   {
     DBUG_PRINT("info", ("get_server_by_name returned > 0 error condition!"));
     /* need to come up with error handling */
     error_num=1;
     goto error;
   }
-  DBUG_PRINT("info", ("get_server_by_name returned server at %lx", (long unsigned int) server));
+  DBUG_PRINT("info", ("get_server_by_name returned server at %lx",
+                      (long unsigned int) server));
 
   /*
     Most of these should never be empty strings, error handling will
@@ -590,29 +626,22 @@ int get_connection(FEDERATED_SHARE *share)
     except there are errors in the trace file of the share being overrun 
     at the address of the share.
   */
-  if (server->server_name)
-    share->server_name= server->server_name;
-  share->server_name_length= server->server_name_length ?
-    server->server_name_length : 0;
-  if (server->username)
-    share->username= server->username;
-  if (server->password)
-    share->password= server->password;
-  if (server->db)
-    share->database= server->db;
-
-  share->port= server->port ? (ushort) server->port : MYSQL_PORT;
-
-  if (server->host)
-    share->hostname= server->host;
-  if (server->socket)
-    share->socket= server->socket;
-  else if (strcmp(share->hostname, my_localhost) == 0)
-    share->socket= my_strdup(MYSQL_UNIX_ADDR, MYF(0));
-  if (server->scheme)
-    share->scheme= server->scheme;
-  else
-    share->scheme= NULL;
+  share->server_name_length= server->server_name_length;
+  share->server_name= server->server_name;
+  share->username= server->username;
+  share->password= server->password;
+  share->database= server->db;
+#ifndef I_AM_PARANOID
+  share->port= server->port > 0 && server->port < 65536 ? 
+#else
+  share->port= server->port > 1023 && server->port < 65536 ? 
+#endif
+               (ushort) server->port : MYSQL_PORT;
+  share->hostname= server->host;
+  if (!(share->socket= server->socket) &&
+      !strcmp(share->hostname, my_localhost))
+    share->socket= (char *) MYSQL_UNIX_ADDR;
+  share->scheme= server->scheme;
 
   DBUG_PRINT("info", ("share->username %s", share->username));
   DBUG_PRINT("info", ("share->password %s", share->password));
@@ -635,6 +664,7 @@ error:
 
   SYNOPSIS
     parse_url()
+    mem_root            MEM_ROOT pointer for memory allocation
     share               pointer to FEDERATED share
     table               pointer to current TABLE class
     table_create_flag   determines what error to throw
@@ -684,7 +714,7 @@ error:
 
 */
 
-static int parse_url(FEDERATED_SHARE *share, TABLE *table,
+static int parse_url(MEM_ROOT *mem_root, FEDERATED_SHARE *share, TABLE *table,
                      uint table_create_flag)
 {
   uint error_num= (table_create_flag ?
@@ -698,20 +728,19 @@ static int parse_url(FEDERATED_SHARE *share, TABLE *table,
   DBUG_PRINT("info", ("Length: %d", table->s->connect_string.length));
   DBUG_PRINT("info", ("String: '%.*s'", table->s->connect_string.length,
                       table->s->connect_string.str));
-  share->connection_string= my_strndup(table->s->connect_string.str,
-                                       table->s->connect_string.length,
-                                       MYF(0));
+  share->connection_string= strmake_root(mem_root, table->s->connect_string.str,
+                                       table->s->connect_string.length);
 
-  // Add a null for later termination of table name
-  share->connection_string[table->s->connect_string.length]= 0;
   DBUG_PRINT("info",("parse_url alloced share->connection_string %lx",
                      (long unsigned int) share->connection_string));
 
   DBUG_PRINT("info",("share->connection_string %s",share->connection_string));
-  /* No delimiters, must be a straight connection name */
-  if ( (!strchr(share->connection_string, '/')) &&
-       (!strchr(share->connection_string, '@')) &&
-       (!strchr(share->connection_string, ';')))
+  /*
+    No :// or @ in connection string. Must be a straight connection name of
+    either "servername" or "servername/tablename"
+  */
+  if ( (!strstr(share->connection_string, "://") &&
+       (!strchr(share->connection_string, '@'))))
   {
 
     DBUG_PRINT("info",
@@ -720,17 +749,51 @@ static int parse_url(FEDERATED_SHARE *share, TABLE *table,
                 share->connection_string,
                 (long unsigned int) share->connection_string));
 
+    /* ok, so we do a little parsing, but not completely! */
     share->parsed= FALSE;
-    if ((error_num= get_connection(share)))
-      goto error;
+    /*
+      If there is a single '/' in the connection string, this means the user is
+      specifying a table name
+    */
+
+    if ((share->table_name= strchr(share->connection_string, '/')))
+    {
+      share->connection_string[share->table_name - share->connection_string]= '\0';
+      share->table_name++;
+      share->table_name_length= strlen(share->table_name);
 
+      DBUG_PRINT("info", 
+                 ("internal format, parsed table_name share->connection_string \
+                  %s share->table_name %s", 
+                  share->connection_string, share->table_name));
+
+      /*
+        there better not be any more '/'s !
+      */
+      if (strchr(share->table_name, '/'))
+        goto error;
+
+    }
     /*
-      connection specifies everything but, resort to
-      expecting remote and foreign table names to match
+      otherwise, straight server name, use tablename of federated table
+      as remote table name
     */
-    share->table_name= table->s->table_name.str;
-    share->table_name_length= table->s->table_name.length;
-    share->table_name[share->table_name_length]= '\0';
+    else
+    {
+      /*
+        connection specifies everything but, resort to
+        expecting remote and foreign table names to match
+      */
+      share->table_name= strmake_root(mem_root, table->s->table_name.str,
+                                      (share->table_name_length= table->s->table_name.length));
+      DBUG_PRINT("info", 
+                 ("internal format, default table_name share->connection_string \
+                  %s share->table_name %s", 
+                  share->connection_string, share->table_name));
+    }
+
+    if ((error_num= get_connection(mem_root, share)))
+      goto error;
   }
   else
   {
@@ -816,7 +879,7 @@ Then password is a null string, so set to NULL
   if (!share->port)
   {
     if (strcmp(share->hostname, my_localhost) == 0)
-      share->socket= my_strdup(MYSQL_UNIX_ADDR, MYF(0));
+      share->socket= (char *) MYSQL_UNIX_ADDR;
     else
       share->port= MYSQL_PORT;
   }
@@ -1420,22 +1483,26 @@ err:
 
 static FEDERATED_SHARE *get_share(const char *table_name, TABLE *table)
 {
-  char *select_query;
   char query_buffer[FEDERATED_QUERY_BUFFER_SIZE];
   Field **field;
   String query(query_buffer, sizeof(query_buffer), &my_charset_bin);
   FEDERATED_SHARE *share= NULL, tmp_share;
+  MEM_ROOT mem_root;
+  DBUG_ENTER("ha_federated.cc::get_share");
+
   /*
     In order to use this string, we must first zero it's length,
     or it will contain garbage
   */
   query.length(0);
 
+  init_alloc_root(&mem_root, 256, 0);
+
   pthread_mutex_lock(&federated_mutex);
 
   tmp_share.share_key= table_name;
   tmp_share.share_key_length= strlen(table_name);
-  if (parse_url(&tmp_share, table, 0))
+  if (parse_url(&mem_root, &tmp_share, table, 0))
     goto error;
 
   /* TODO: change tmp_share.scheme to LEX_STRING object */
@@ -1456,24 +1523,17 @@ static FEDERATED_SHARE *get_share(const char *table_name, TABLE *table)
     query.length(query.length() - sizeof_trailing_comma);
 
     query.append(STRING_WITH_LEN(" FROM `"));
+    query.append(tmp_share.table_name, tmp_share.table_name_length);
+    query.append(STRING_WITH_LEN("`"));
+    DBUG_PRINT("info", ("calling alloc_root"));
 
-    if (!(share= (FEDERATED_SHARE *)
-          my_multi_malloc(MYF(MY_WME),
-                          &share, sizeof(*share),
-                          &select_query,
-                          query.length()+table->s->connect_string.length+1,
-                          NullS)))
+    if (!(share= (FEDERATED_SHARE *) memdup_root(&mem_root, (char*)&tmp_share, sizeof(*share))) ||
+        !(share->select_query= (char*) strmake_root(&mem_root, query.ptr(), query.length())))
       goto error;
 
-    memcpy(share, &tmp_share, sizeof(tmp_share));
-
-    share->table_name_length= strlen(share->table_name);
-    /* TODO: share->table_name to LEX_STRING object */
-    query.append(share->table_name, share->table_name_length);
-    query.append(STRING_WITH_LEN("`"));
-    share->select_query= select_query;
-    strmov(share->select_query, query.ptr());
     share->use_count= 0;
+    share->mem_root= mem_root;
+
     DBUG_PRINT("info",
                ("share->select_query %s", share->select_query));
 
@@ -1482,17 +1542,18 @@ static FEDERATED_SHARE *get_share(const char *table_name, TABLE *table)
     thr_lock_init(&share->lock);
     pthread_mutex_init(&share->mutex, MY_MUTEX_INIT_FAST);
   }
+  else
+    free_root(&mem_root, MYF(0)); /* prevents memory leak */
+
   share->use_count++;
   pthread_mutex_unlock(&federated_mutex);
 
-  return share;
+  DBUG_RETURN(share);
 
 error:
   pthread_mutex_unlock(&federated_mutex);
-  my_free((gptr) tmp_share.connection_string, MYF(MY_ALLOW_ZERO_PTR));
-  tmp_share.connection_string= 0;
-  my_free((gptr) share, MYF(MY_ALLOW_ZERO_PTR));
-  return NULL;
+  free_root(&mem_root, MYF(0));
+  DBUG_RETURN(NULL);
 }
 
 
@@ -1504,23 +1565,16 @@ error:
 
 static int free_share(FEDERATED_SHARE *share)
 {
+  MEM_ROOT mem_root= share->mem_root;
   DBUG_ENTER("free_share");
 
   pthread_mutex_lock(&federated_mutex);
   if (!--share->use_count)
   {
     hash_delete(&federated_open_tables, (byte*) share);
-    if (share->parsed)
-      my_free((gptr) share->socket, MYF(MY_ALLOW_ZERO_PTR));
-    /*if (share->connection_string)
-    {
-    */
-      my_free((gptr) share->connection_string, MYF(MY_ALLOW_ZERO_PTR));
-      share->connection_string= 0;
-      /*}*/
     thr_lock_delete(&share->lock);
     VOID(pthread_mutex_destroy(&share->mutex));
-    my_free((gptr) share, MYF(0));
+    free_root(&mem_root, MYF(0));
   }
   pthread_mutex_unlock(&federated_mutex);
 
@@ -1589,6 +1643,8 @@ int ha_federated::open(const char *name, int mode, uint test_if_locked)
   mysql_options(mysql,MYSQL_SET_CHARSET_NAME,
                 this->table->s->table_charset->csname);
 
+  DBUG_PRINT("info", ("calling mysql_real_connect hostname %s user %s",
+			share->hostname, share->username));
   if (!mysql || !mysql_real_connect(mysql,
                                    share->hostname,
                                    share->username,
@@ -2831,15 +2887,13 @@ int ha_federated::create(const char *name, TABLE *table_arg,
                          HA_CREATE_INFO *create_info)
 {
   int retval;
+  THD *thd= current_thd;
   FEDERATED_SHARE tmp_share; // Only a temporary share, to test the url
   DBUG_ENTER("ha_federated::create");
 
-  if (!(retval= parse_url(&tmp_share, table_arg, 1)))
+  if (!(retval= parse_url(thd->mem_root, &tmp_share, table_arg, 1)))
     retval= check_foreign_data_source(&tmp_share, 1);
 
-  /* free this because strdup created it in parse_url */
-  my_free((gptr) tmp_share.connection_string, MYF(MY_ALLOW_ZERO_PTR));
-  tmp_share.connection_string= 0;
   DBUG_RETURN(retval);
 
 }
diff --git a/storage/federated/ha_federated.h b/storage/federated/ha_federated.h
index bbc2b2fe9f878456eaae077247755729748a6979..4d2eefdd98663e897d9f598e5d682223264af77b 100644
--- a/storage/federated/ha_federated.h
+++ b/storage/federated/ha_federated.h
@@ -43,6 +43,8 @@
   The example implements the minimum of what you will probably need.
 */
 typedef struct st_federated_share {
+  MEM_ROOT mem_root;
+
   bool parsed;
   /* this key is unique db/tablename */
   const char *share_key;
@@ -67,6 +69,7 @@ typedef struct st_federated_share {
   char *sport;
   int share_key_length;
   ushort port;
+
   uint table_name_length, server_name_length, connect_string_length, use_count;
   pthread_mutex_t mutex;
   THR_LOCK lock;
diff --git a/storage/heap/ha_heap.cc b/storage/heap/ha_heap.cc
index 5831ec6167ac6265b1c1d73a586968aec5135268..8c378f7334f0fdb8a6c39d89fefc8f20a66ee2c7 100644
--- a/storage/heap/ha_heap.cc
+++ b/storage/heap/ha_heap.cc
@@ -628,7 +628,10 @@ int ha_heap::create(const char *name, TABLE *table_arg,
       seg->length=  (uint) key_part->length;
       seg->flag=    key_part->key_part_flag;
 
-      seg->charset= field->charset();
+      if (field->flags & (ENUM_FLAG | SET_FLAG))
+        seg->charset= &my_charset_bin;
+      else
+        seg->charset= field->charset();
       if (field->null_ptr)
       {
 	seg->null_bit= field->null_bit;
diff --git a/storage/heap/hp_write.c b/storage/heap/hp_write.c
index 86e79c9d7ecbab87e91c0dc9db12f4b2d4713fe5..19215fcf01733c1e17bdf80f24351c75754f0158 100644
--- a/storage/heap/hp_write.c
+++ b/storage/heap/hp_write.c
@@ -105,7 +105,6 @@ int hp_rb_write_key(HP_INFO *info, HP_KEYDEF *keyinfo, const byte *record,
   heap_rb_param custom_arg;
   uint old_allocated;
 
-  info->last_pos= NULL; /* For heap_rnext/heap_rprev */
   custom_arg.keyseg= keyinfo->seg;
   custom_arg.key_length= hp_rb_make_key(keyinfo, info->recbuf, record, recpos);
   if (keyinfo->flag & HA_NOSAME)
diff --git a/storage/myisam/ha_myisam.cc b/storage/myisam/ha_myisam.cc
index 8fe4d988dbc67fc9adf63a48c8c608d0e993e6f7..d31f5b7e792e4d159b7dcd6bab8753b620fe1a88 100644
--- a/storage/myisam/ha_myisam.cc
+++ b/storage/myisam/ha_myisam.cc
@@ -635,6 +635,9 @@ bool ha_myisam::check_if_locking_is_allowed(uint sql_command,
 
 int ha_myisam::open(const char *name, int mode, uint test_if_locked)
 {
+  MI_KEYDEF *keyinfo;
+  MI_COLUMNDEF *recinfo= 0;
+  uint recs;
   uint i;
 
   /*
@@ -657,6 +660,26 @@ int ha_myisam::open(const char *name, int mode, uint test_if_locked)
 
   if (!(file=mi_open(name, mode, test_if_locked | HA_OPEN_FROM_SQL_LAYER)))
     return (my_errno ? my_errno : -1);
+  if (!table->s->tmp_table) /* No need to perform a check for tmp table */
+  {
+    if ((my_errno= table2myisam(table, &keyinfo, &recinfo, &recs)))
+    {
+      /* purecov: begin inspected */
+      DBUG_PRINT("error", ("Failed to convert TABLE object to MyISAM "
+                           "key and column definition"));
+      goto err;
+      /* purecov: end */
+    }
+    if (check_definition(keyinfo, recinfo, table->s->keys, recs,
+                         file->s->keyinfo, file->s->rec,
+                         file->s->base.keys, file->s->base.fields, true))
+    {
+      /* purecov: begin inspected */
+      my_errno= HA_ERR_CRASHED;
+      goto err;
+      /* purecov: end */
+    }
+  }
   
   if (test_if_locked & (HA_OPEN_IGNORE_IF_LOCKED | HA_OPEN_TMP_TABLE))
     VOID(mi_extra(file, HA_EXTRA_NO_WAIT_LOCK, 0));
@@ -677,7 +700,18 @@ int ha_myisam::open(const char *name, int mode, uint test_if_locked)
         (struct st_mysql_ftparser *)parser->plugin->info;
     table->key_info[i].block_size= file->s->keyinfo[i].block_length;
   }
-  return (0);
+  my_errno= 0;
+  goto end;
+ err:
+  this->close();
+ end:
+  /*
+    Both recinfo and keydef are allocated by my_multi_malloc(), thus only
+    recinfo must be freed.
+  */
+  if (recinfo)
+    my_free((gptr) recinfo, MYF(0));
+  return my_errno;
 }
 
 int ha_myisam::close(void)
@@ -1023,6 +1057,22 @@ int ha_myisam::repair(THD *thd, MI_CHECK &param, bool do_optimize)
   ha_rows rows= file->state->records;
   DBUG_ENTER("ha_myisam::repair");
 
+  /*
+    Normally this method is entered with a properly opened table. If the
+    repair fails, it can be repeated with more elaborate options. Under
+    special circumstances it can happen that a repair fails so that it
+    closed the data file and cannot re-open it. In this case file->dfile
+    is set to -1. We must not try another repair without an open data
+    file. (Bug #25289)
+  */
+  if (file->dfile == -1)
+  {
+    sql_print_information("Retrying repair of: '%s' failed. "
+                          "Please try REPAIR EXTENDED or myisamchk",
+                          table->s->path.str);
+    DBUG_RETURN(HA_ADMIN_FAILED);
+  }
+
   param.db_name=    table->s->db.str;
   param.table_name= table->alias;
   param.tmpfile_createflag = O_RDWR | O_TRUNC;
diff --git a/storage/myisam/mi_create.c b/storage/myisam/mi_create.c
index 5dd4a98127edc118a2e41fbcc98b460ea1c761d8..71d377c8b6b070e5c1b21095706699fcdb0ba561 100644
--- a/storage/myisam/mi_create.c
+++ b/storage/myisam/mi_create.c
@@ -573,6 +573,10 @@ int mi_create(const char *name,uint keys,MI_KEYDEF *keydefs,
 
   pthread_mutex_lock(&THR_LOCK_myisam);
 
+  /*
+    NOTE: For test_if_reopen() we need a real path name. Hence we need
+    MY_RETURN_REAL_PATH for every fn_format(filename, ...).
+  */
   if (ci->index_file_name)
   {
     char *iext= strrchr(ci->index_file_name, '.');
@@ -584,13 +588,14 @@ int mi_create(const char *name,uint keys,MI_KEYDEF *keydefs,
       if ((path= strrchr(ci->index_file_name, FN_LIBCHAR)))
         *path= '\0';
       fn_format(filename, name, ci->index_file_name, MI_NAME_IEXT,
-                MY_REPLACE_DIR | MY_UNPACK_FILENAME | MY_APPEND_EXT);
+                MY_REPLACE_DIR | MY_UNPACK_FILENAME |
+                MY_RETURN_REAL_PATH | MY_APPEND_EXT);
     }
     else
     {
       fn_format(filename, ci->index_file_name, "", MI_NAME_IEXT,
-                MY_UNPACK_FILENAME | (have_iext ? MY_REPLACE_EXT :
-                                      MY_APPEND_EXT));
+                MY_UNPACK_FILENAME | MY_RETURN_REAL_PATH |
+                (have_iext ? MY_REPLACE_EXT : MY_APPEND_EXT));
     }
     fn_format(linkname, name, "", MI_NAME_IEXT,
               MY_UNPACK_FILENAME|MY_APPEND_EXT);
@@ -603,10 +608,11 @@ int mi_create(const char *name,uint keys,MI_KEYDEF *keydefs,
   }
   else
   {
+    char *iext= strrchr(name, '.');
+    int have_iext= iext && !strcmp(iext, MI_NAME_IEXT);
     fn_format(filename, name, "", MI_NAME_IEXT,
-              (MY_UNPACK_FILENAME |
-               (flags & HA_DONT_TOUCH_DATA) ? MY_RETURN_REAL_PATH : 0) |
-                MY_APPEND_EXT);
+              MY_UNPACK_FILENAME | MY_RETURN_REAL_PATH |
+              (have_iext ? MY_REPLACE_EXT : MY_APPEND_EXT));
     linkname_ptr=0;
     /* Replace the current file */
     create_flag=MY_DELETE_OLD;
@@ -618,6 +624,9 @@ int mi_create(const char *name,uint keys,MI_KEYDEF *keydefs,
     A TRUNCATE command checks for the table in the cache only and could
     be fooled to believe, the table is not open.
     Pull the emergency brake in this situation. (Bug #8306)
+
+    NOTE: The filename is compared against unique_file_name of every
+    open table. Hence we need a real path here.
   */
   if (test_if_reopen(filename))
   {
diff --git a/storage/myisam/mi_range.c b/storage/myisam/mi_range.c
index 2cdb02b2c809709673818b69b9999942e1b332ab..c7ab6731a2c9bb828aeb16eb0f7425bad6d15aa2 100644
--- a/storage/myisam/mi_range.c
+++ b/storage/myisam/mi_range.c
@@ -138,8 +138,42 @@ static ha_rows _mi_record_pos(MI_INFO *info, const byte *key,
   if (!(nextflag & (SEARCH_FIND | SEARCH_NO_FIND | SEARCH_LAST)))
     key_len=USE_WHOLE_KEY;
 
+  /*
+    my_handler.c:mi_compare_text() has a flag 'skip_end_space'.
+    This is set in my_handler.c:ha_key_cmp() in dependence on the
+    compare flags 'nextflag' and the column type.
+
+    TEXT columns are of type HA_KEYTYPE_VARTEXT. In this case the
+    condition is skip_end_space= ((nextflag & (SEARCH_FIND |
+    SEARCH_UPDATE)) == SEARCH_FIND).
+
+    SEARCH_FIND is used for an exact key search. The combination
+    SEARCH_FIND | SEARCH_UPDATE is used in write/update/delete
+    operations with a comment like "Not real duplicates", whatever this
+    means. From the condition above we can see that 'skip_end_space' is
+    always false for these operations. The result is that trailing space
+    counts in key comparison and hence, emtpy strings ('', string length
+    zero, but not NULL) compare less that strings starting with control
+    characters and these in turn compare less than strings starting with
+    blanks.
+
+    When estimating the number of records in a key range, we request an
+    exact search for the minimum key. This translates into a plain
+    SEARCH_FIND flag. Using this alone would lead to a 'skip_end_space'
+    compare. Empty strings would be expected above control characters.
+    Their keys would not be found because they are located below control
+    characters.
+
+    This is the reason that we add the SEARCH_UPDATE flag here. It makes
+    the key estimation compare in the same way like key write operations
+    do. Olny so we will find the keys where they have been inserted.
+
+    Adding the flag unconditionally does not hurt as it is used in the
+    above mentioned condition only. So it can safely be used together
+    with other flags.
+  */
   pos=_mi_search_pos(info,keyinfo,key_buff,key_len,
-		     nextflag | SEARCH_SAVE_BUFF,
+		     nextflag | SEARCH_SAVE_BUFF | SEARCH_UPDATE,
 		     info->s->state.key_root[inx]);
   if (pos >= 0.0)
   {
diff --git a/storage/myisam/mi_search.c b/storage/myisam/mi_search.c
index 8d2b68a97f0b83b02283d63d3fe5c3188d1f3f03..d313619e00722940f17a1afa92b74b5a90a56999 100644
--- a/storage/myisam/mi_search.c
+++ b/storage/myisam/mi_search.c
@@ -926,11 +926,16 @@ uint _mi_get_binary_pack_key(register MI_KEYDEF *keyinfo, uint nod_flag,
   /*
     Keys are compressed the following way:
 
-    prefix length    Packed length of prefix for the prev key. (1 or 3 bytes)
+    prefix length    Packed length of prefix common with prev key (1 or 3 bytes)
     for each key segment:
       [is null]        Null indicator if can be null (1 byte, zero means null)
       [length]         Packed length if varlength (1 or 3 bytes)
+      key segment      'length' bytes of key segment value
     pointer          Reference to the data file (last_keyseg->length).
+
+    get_key_length() is a macro. It gets the prefix length from 'page'
+    and puts it into 'length'. It increments 'page' by 1 or 3, depending
+    on the packed length of the prefix length.
   */
   get_key_length(length,page);
   if (length)
@@ -945,34 +950,44 @@ uint _mi_get_binary_pack_key(register MI_KEYDEF *keyinfo, uint nod_flag,
       my_errno=HA_ERR_CRASHED;
       DBUG_RETURN(0);                                 /* Wrong key */
     }
-    from=key;  from_end=key+length;
+    /* Key is packed against prev key, take prefix from prev key. */
+    from= key;
+    from_end= key + length;
   }
   else
   {
-    from=page; from_end=page_end;               /* Not packed key */
+    /* Key is not packed against prev key, take all from page buffer. */
+    from= page;
+    from_end= page_end;
   }
 
   /*
-    The trouble is that key is split in two parts:
-     The first part is in from ...from_end-1.
-     The second part starts at page
+    The trouble is that key can be split in two parts:
+      The first part (prefix) is in from .. from_end - 1.
+      The second part starts at page.
+    The split can be at every byte position. So we need to check for
+    the end of the first part before using every byte.
   */
   for (keyseg=keyinfo->seg ; keyseg->type ;keyseg++)
   {
     if (keyseg->flag & HA_NULL_PART)
     {
+      /* If prefix is used up, switch to rest. */
       if (from == from_end) { from=page;  from_end=page_end; }
       if (!(*key++ = *from++))
         continue;                               /* Null part */
     }
     if (keyseg->flag & (HA_VAR_LENGTH_PART | HA_BLOB_PART | HA_SPACE_PACK))
     {
-      /* Get length of dynamic length key part */
+      /* If prefix is used up, switch to rest. */
       if (from == from_end) { from=page;  from_end=page_end; }
+      /* Get length of dynamic length key part */
       if ((length= (*key++ = *from++)) == 255)
       {
+        /* If prefix is used up, switch to rest. */
         if (from == from_end) { from=page;  from_end=page_end; }
         length= (uint) ((*key++ = *from++)) << 8;
+        /* If prefix is used up, switch to rest. */
         if (from == from_end) { from=page;  from_end=page_end; }
         length+= (uint) ((*key++ = *from++));
       }
@@ -992,14 +1007,26 @@ uint _mi_get_binary_pack_key(register MI_KEYDEF *keyinfo, uint nod_flag,
     key+=length;
     from+=length;
   }
+  /*
+    Last segment (type == 0) contains length of data pointer.
+    If we have mixed key blocks with data pointer and key block pointer,
+    we have to copy both.
+  */
   length=keyseg->length+nod_flag;
   if ((tmp=(uint) (from_end-from)) <= length)
   {
+    /* Remaining length is less or equal max possible length. */
     memcpy(key+tmp,page,length-tmp);            /* Get last part of key */
     *page_pos= page+length-tmp;
   }
   else
   {
+    /*
+      Remaining length is greater than max possible length.
+      This can happen only if we switched to the new key bytes already.
+      'page_end' is calculated with MI_MAX_KEY_BUFF. So it can be far
+      behind the real end of the key.
+    */
     if (from_end != page_end)
     {
       DBUG_PRINT("error",("Error when unpacking key"));
@@ -1007,6 +1034,7 @@ uint _mi_get_binary_pack_key(register MI_KEYDEF *keyinfo, uint nod_flag,
       my_errno=HA_ERR_CRASHED;
       DBUG_RETURN(0);                                 /* Error */
     }
+    /* Copy data pointer and, if appropriate, key block pointer. */
     memcpy((byte*) key,(byte*) from,(size_t) length);
     *page_pos= from+length;
   }
diff --git a/storage/ndb/src/common/util/version.c b/storage/ndb/src/common/util/version.c
index b2ebb87c14452ab7ba3ea082aeeb4af91a72ecf9..f309a3d4ad54e3da965e3d9459b0611e9a4a0dae 100644
--- a/storage/ndb/src/common/util/version.c
+++ b/storage/ndb/src/common/util/version.c
@@ -91,7 +91,8 @@ void ndbSetOwnVersion() {}
 
 #ifndef TEST_VERSION
 struct NdbUpGradeCompatible ndbCompatibleTable_full[] = {
-  { MAKE_VERSION(5,1,NDB_VERSION_BUILD), MAKE_VERSION(5,1,0), UG_Range},
+  { MAKE_VERSION(5,1,NDB_VERSION_BUILD), MAKE_VERSION(5,1,18), UG_Range},
+  { MAKE_VERSION(5,1,17), MAKE_VERSION(5,1,0), UG_Range},
   { MAKE_VERSION(5,0,NDB_VERSION_BUILD), MAKE_VERSION(5,0,12), UG_Range},
   { MAKE_VERSION(5,0,11), MAKE_VERSION(5,0,2), UG_Range},
   { MAKE_VERSION(4,1,NDB_VERSION_BUILD), MAKE_VERSION(4,1,15), UG_Range },