← Back to team overview

maria-developers team mailing list archive

bzr commit into MariaDB 5.1, with Maria 1.5:maria branch (monty:2764)

 

#At lp:maria based on revid:monty@xxxxxxxxxxxx-20091107103419-28zpi3oyre6kaf2l

 2764 Michael Widenius	2009-11-10 [merge]
      Temp commit for igor to look at failing join.test
      removed:
        mysql-test/include/have_dynamic_loading.inc
        mysys/mf_strip.c
        storage/innodb_plugin/README
        storage/innodb_plugin/handler/handler0vars.h
        storage/innodb_plugin/handler/win_delay_loader.cc
        storage/innodb_plugin/win-plugin/
        storage/innodb_plugin/win-plugin/README
        storage/innodb_plugin/win-plugin/win-plugin.diff
      added:
        mysql-test/extra/binlog_tests/binlog_failure_mixing_engines.test
        mysql-test/extra/rpl_tests/rpl_auto_increment_insert_view.test
        mysql-test/extra/rpl_tests/rpl_auto_increment_invoke_trigger.test
        mysql-test/extra/rpl_tests/rpl_autoinc_func_invokes_trigger.test
        mysql-test/include/have_case_insensitive_fs.inc
        mysql-test/include/have_debug_sync.inc
        mysql-test/include/have_dynamic_loading.inc
        mysql-test/include/have_mysql_upgrade.inc
        mysql-test/include/have_not_innodb_plugin.inc
        mysql-test/include/not_windows_embedded.inc
        mysql-test/lib/v1/incompatible.tests
        mysql-test/r/bug46760.result
        mysql-test/r/case_insensitive_fs.require
        mysql-test/r/debug_sync.result
        mysql-test/r/grant_lowercase_fs.result
        mysql-test/r/have_debug_sync.require
        mysql-test/r/innodb_bug44369.result
        mysql-test/r/innodb_bug46000.result
        mysql-test/r/innodb_bug47777.result
        mysql-test/r/locale.result
        mysql-test/r/lowercase_mixed_tmpdir_innodb.result
        mysql-test/r/not_true.require
        mysql-test/r/partition_innodb_builtin.result
        mysql-test/r/partition_innodb_plugin.result
        mysql-test/r/partition_open_files_limit.result
        mysql-test/r/sp-bugs.result
        mysql-test/r/subselect4.result
        mysql-test/std_data/binlog_transaction.000001
        mysql-test/std_data/latin1.xml
        mysql-test/suite/binlog/r/binlog_delete_and_flush_index.result
        mysql-test/suite/binlog/r/binlog_mixed_failure_mixing_engines.result
        mysql-test/suite/binlog/r/binlog_row_failure_mixing_engines.result
        mysql-test/suite/binlog/r/binlog_row_mysqlbinlog_verbose.result
        mysql-test/suite/binlog/r/binlog_stm_do_db.result
        mysql-test/suite/binlog/std_data/update-full-row.binlog
        mysql-test/suite/binlog/std_data/update-partial-row.binlog
        mysql-test/suite/binlog/std_data/write-full-row.binlog
        mysql-test/suite/binlog/std_data/write-partial-row.binlog
        mysql-test/suite/binlog/t/binlog_delete_and_flush_index.test
        mysql-test/suite/binlog/t/binlog_mixed_failure_mixing_engines.test
        mysql-test/suite/binlog/t/binlog_row_failure_mixing_engines.test
        mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_verbose.test
        mysql-test/suite/binlog/t/binlog_stm_do_db-master.opt
        mysql-test/suite/binlog/t/binlog_stm_do_db.test
        mysql-test/suite/federated/federated_debug-master.opt
        mysql-test/suite/federated/federated_debug.result
        mysql-test/suite/federated/federated_debug.test
        mysql-test/suite/innodb/r/innodb-consistent.result
        mysql-test/suite/innodb/r/innodb_bug44571.result
        mysql-test/suite/innodb/t/innodb-consistent-master.opt
        mysql-test/suite/innodb/t/innodb-consistent.test
        mysql-test/suite/innodb/t/innodb_bug44571.test
        mysql-test/suite/rpl/r/rpl_auto_increment_update_failure.result
        mysql-test/suite/rpl/r/rpl_mysql_upgrade.result
        mysql-test/suite/rpl/r/rpl_row_disabled_slave_key.result
        mysql-test/suite/rpl/t/rpl_auto_increment_update_failure.test
        mysql-test/suite/rpl/t/rpl_get_master_version_and_clock-slave.opt
        mysql-test/suite/rpl/t/rpl_mysql_upgrade.test
        mysql-test/suite/rpl/t/rpl_row_disabled_slave_key.test
        mysql-test/t/bug46760-master.opt
        mysql-test/t/bug46760.test
        mysql-test/t/debug_sync.test
        mysql-test/t/grant_lowercase_fs.test
        mysql-test/t/innodb_bug44369.test
        mysql-test/t/innodb_bug46000.test
        mysql-test/t/innodb_bug47777.test
        mysql-test/t/locale.test
        mysql-test/t/lowercase_mixed_tmpdir_innodb-master.opt
        mysql-test/t/lowercase_mixed_tmpdir_innodb-master.sh
        mysql-test/t/lowercase_mixed_tmpdir_innodb.test
        mysql-test/t/partition_innodb_builtin.test
        mysql-test/t/partition_innodb_plugin.test
        mysql-test/t/partition_open_files_limit-master.opt
        mysql-test/t/partition_open_files_limit.test
        mysql-test/t/sp-bugs.test
        mysql-test/t/status-master.opt
        mysql-test/t/subselect4.test
        sql/debug_sync.cc
        sql/debug_sync.h
        storage/innodb_plugin/mysql-test/innodb-consistent-master.opt
        storage/innodb_plugin/mysql-test/innodb-consistent.result
        storage/innodb_plugin/mysql-test/innodb-consistent.test
        storage/innodb_plugin/mysql-test/innodb_bug44369.result
        storage/innodb_plugin/mysql-test/innodb_bug44369.test
        storage/innodb_plugin/mysql-test/innodb_bug44571.result
        storage/innodb_plugin/mysql-test/innodb_bug44571.test
        storage/innodb_plugin/mysql-test/innodb_bug46000.result
        storage/innodb_plugin/mysql-test/innodb_bug46000.test
        storage/innodb_plugin/revert_gen.sh
        storage/innodb_plugin/scripts/export.sh
        storage/innodb_plugin/ut/ut0auxconf_have_gcc_atomics.c
      renamed:
        mysql-test/r/bug40113.result => mysql-test/r/innodb_lock_wait_timeout_1.result
        mysql-test/t/bug40113-master.opt => mysql-test/t/innodb_lock_wait_timeout_1-master.opt
        mysql-test/t/bug40113.test => mysql-test/t/innodb_lock_wait_timeout_1.test
      modified:
        .bzrignore
        CMakeLists.txt
        Makefile.am
        client/mysql.cc
        client/mysql_upgrade.c
        client/mysqlbinlog.cc
        client/mysqlcheck.c
        client/mysqlimport.c
        client/mysqlslap.c
        client/mysqltest.cc
        cmd-line-utils/readline/display.c
        configure.in
        extra/yassl/include/yassl_int.hpp
        extra/yassl/taocrypt/src/random.cpp
        include/my_dbug.h
        include/my_sys.h
        include/myisamchk.h
        include/mysql.h
        include/mysql.h.pp
        include/violite.h
        libmysql/libmysql.c
        libmysql/libmysql.def
        libmysqld/CMakeLists.txt
        libmysqld/Makefile.am
        libmysqld/lib_sql.cc
        libmysqld/libmysqld.c
        libmysqld/libmysqld.def
        mysql-test/collections/README.experimental
        mysql-test/collections/default.experimental
        mysql-test/extra/binlog_tests/binlog.test
        mysql-test/extra/binlog_tests/drop_temp_table.test
        mysql-test/extra/rpl_tests/rpl_auto_increment.test
        mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test
        mysql-test/extra/rpl_tests/rpl_failed_optimize.test
        mysql-test/extra/rpl_tests/rpl_loaddata.test
        mysql-test/extra/rpl_tests/rpl_row_sp006.test
        mysql-test/extra/rpl_tests/rpl_stm_000001.test
        mysql-test/include/check-warnings.test
        mysql-test/include/concurrent.inc
        mysql-test/include/have_example_plugin.inc
        mysql-test/include/have_simple_parser.inc
        mysql-test/include/have_udf.inc
        mysql-test/include/mix1.inc
        mysql-test/include/mtr_warnings.sql
        mysql-test/lib/My/ConfigFactory.pm
        mysql-test/lib/My/Platform.pm
        mysql-test/lib/My/SafeProcess/safe_kill_win.cc
        mysql-test/lib/My/SafeProcess/safe_process_win.cc
        mysql-test/lib/mtr_cases.pm
        mysql-test/lib/mtr_report.pm
        mysql-test/lib/v1/mtr_cases.pl
        mysql-test/mysql-stress-test.pl
        mysql-test/mysql-test-run.pl
        mysql-test/r/almost_full.result
        mysql-test/r/alter_table.result
        mysql-test/r/analyse.result
        mysql-test/r/archive.result
        mysql-test/r/bug46080.result
        mysql-test/r/create.result
        mysql-test/r/ctype_ldml.result
        mysql-test/r/delete.result
        mysql-test/r/distinct.result
        mysql-test/r/explain.result
        mysql-test/r/func_group.result
        mysql-test/r/func_in.result
        mysql-test/r/func_str.result
        mysql-test/r/gis-rtree.result
        mysql-test/r/gis.result
        mysql-test/r/grant.result
        mysql-test/r/grant3.result
        mysql-test/r/group_min_max.result
        mysql-test/r/information_schema_db.result
        mysql-test/r/innodb-autoinc.result
        mysql-test/r/innodb_mysql.result
        mysql-test/r/insert_select.result
        mysql-test/r/join.result
        mysql-test/r/lowercase_fs_off.result
        mysql-test/r/lowercase_table3.result
        mysql-test/r/myisam.result
        mysql-test/r/myisam_crash_before_flush_keys.result
        mysql-test/r/mysqlbinlog.result
        mysql-test/r/mysqltest.result
        mysql-test/r/olap.result
        mysql-test/r/order_by.result
        mysql-test/r/partition.result
        mysql-test/r/partition_csv.result
        mysql-test/r/partition_innodb.result
        mysql-test/r/partition_pruning.result
        mysql-test/r/ps_grant.result
        mysql-test/r/query_cache.result
        mysql-test/r/range.result
        mysql-test/r/select.result
        mysql-test/r/sp-error.result
        mysql-test/r/sp.result
        mysql-test/r/subselect.result
        mysql-test/r/subselect3.result
        mysql-test/r/system_mysql_db.result
        mysql-test/r/trigger_notembedded.result
        mysql-test/r/type_bit.result
        mysql-test/r/type_newdecimal.result
        mysql-test/r/udf.result
        mysql-test/r/update.result
        mysql-test/r/upgrade.result
        mysql-test/r/view_grant.result
        mysql-test/r/warnings.result
        mysql-test/r/windows.result
        mysql-test/r/xa.result
        mysql-test/std_data/Index.xml
        mysql-test/suite/binlog/r/binlog_killed_simulate.result
        mysql-test/suite/binlog/r/binlog_row_binlog.result
        mysql-test/suite/binlog/r/binlog_row_drop_tmp_tbl.result
        mysql-test/suite/binlog/r/binlog_row_mix_innodb_myisam.result
        mysql-test/suite/binlog/r/binlog_stm_binlog.result
        mysql-test/suite/binlog/r/binlog_stm_blackhole.result
        mysql-test/suite/binlog/r/binlog_stm_drop_tmp_tbl.result
        mysql-test/suite/binlog/r/binlog_stm_mix_innodb_myisam.result
        mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_db_filter.test
        mysql-test/suite/binlog/t/binlog_stm_unsafe_warning.test
        mysql-test/suite/federated/my.cnf
        mysql-test/suite/funcs_1/r/is_columns_mysql.result
        mysql-test/suite/funcs_1/r/is_statistics.result
        mysql-test/suite/innodb/r/innodb-zip.result
        mysql-test/suite/innodb/r/innodb_file_format.result
        mysql-test/suite/innodb/t/innodb-zip.test
        mysql-test/suite/innodb/t/innodb_file_format.test
        mysql-test/suite/innodb/t/innodb_information_schema.test
        mysql-test/suite/parts/inc/partition_auto_increment.inc
        mysql-test/suite/parts/r/partition_auto_increment_innodb.result
        mysql-test/suite/parts/r/partition_auto_increment_maria.result
        mysql-test/suite/parts/r/partition_auto_increment_memory.result
        mysql-test/suite/parts/r/partition_auto_increment_myisam.result
        mysql-test/suite/parts/r/partition_auto_increment_ndb.result
        mysql-test/suite/parts/r/partition_recover_myisam.result
        mysql-test/suite/parts/t/partition_auto_increment_archive.test
        mysql-test/suite/parts/t/partition_auto_increment_blackhole.test
        mysql-test/suite/parts/t/partition_recover_myisam.test
        mysql-test/suite/rpl/r/rpl_auto_increment.result
        mysql-test/suite/rpl/r/rpl_bug33931.result
        mysql-test/suite/rpl/r/rpl_do_grant.result
        mysql-test/suite/rpl/r/rpl_extraCol_innodb.result
        mysql-test/suite/rpl/r/rpl_extraCol_myisam.result
        mysql-test/suite/rpl/r/rpl_get_master_version_and_clock.result
        mysql-test/suite/rpl/r/rpl_idempotency.result
        mysql-test/suite/rpl/r/rpl_init_slave_errors.result
        mysql-test/suite/rpl/r/rpl_innodb_mixed_dml.result
        mysql-test/suite/rpl/r/rpl_loaddata.result
        mysql-test/suite/rpl/r/rpl_loaddata_fatal.result
        mysql-test/suite/rpl/r/rpl_loaddata_map.result
        mysql-test/suite/rpl/r/rpl_loaddatalocal.result
        mysql-test/suite/rpl/r/rpl_log_pos.result
        mysql-test/suite/rpl/r/rpl_packet.result
        mysql-test/suite/rpl/r/rpl_row_create_table.result
        mysql-test/suite/rpl/r/rpl_row_sp006_InnoDB.result
        mysql-test/suite/rpl/r/rpl_slave_load_remove_tmpfile.result
        mysql-test/suite/rpl/r/rpl_stm_log.result
        mysql-test/suite/rpl/t/disabled.def
        mysql-test/suite/rpl/t/rpl_bug33931.test
        mysql-test/suite/rpl/t/rpl_do_grant.test
        mysql-test/suite/rpl/t/rpl_drop_temp.test
        mysql-test/suite/rpl/t/rpl_err_ignoredtable.test
        mysql-test/suite/rpl/t/rpl_get_master_version_and_clock.test
        mysql-test/suite/rpl/t/rpl_idempotency.test
        mysql-test/suite/rpl/t/rpl_init_slave_errors.test
        mysql-test/suite/rpl/t/rpl_loaddatalocal.test
        mysql-test/suite/rpl/t/rpl_log_pos.test
        mysql-test/suite/rpl/t/rpl_packet.test
        mysql-test/suite/rpl/t/rpl_slave_load_remove_tmpfile.test
        mysql-test/suite/rpl_ndb/r/rpl_ndb_circular_simplex.result
        mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result
        mysql-test/suite/rpl_ndb/r/rpl_ndb_sp006.result
        mysql-test/suite/rpl_ndb/t/rpl_ndb_circular.test
        mysql-test/suite/rpl_ndb/t/rpl_ndb_circular_simplex.test
        mysql-test/t/almost_full.test
        mysql-test/t/alter_table.test
        mysql-test/t/analyse.test
        mysql-test/t/archive.test
        mysql-test/t/bug46080.test
        mysql-test/t/create.test
        mysql-test/t/ctype_ldml.test
        mysql-test/t/delete.test
        mysql-test/t/disabled.def
        mysql-test/t/distinct.test
        mysql-test/t/explain.test
        mysql-test/t/flush_read_lock_kill.test
        mysql-test/t/func_group.test
        mysql-test/t/func_in.test
        mysql-test/t/func_str.test
        mysql-test/t/gis-rtree.test
        mysql-test/t/gis.test
        mysql-test/t/grant3.test
        mysql-test/t/information_schema_db.test
        mysql-test/t/innodb-autoinc.test
        mysql-test/t/innodb_bug39438.test
        mysql-test/t/innodb_mysql.test
        mysql-test/t/insert_select.test
        mysql-test/t/join.test
        mysql-test/t/kill.test
        mysql-test/t/lowercase_fs_off.test
        mysql-test/t/lowercase_table3.test
        mysql-test/t/myisam-system.test
        mysql-test/t/myisam.test
        mysql-test/t/myisam_crash_before_flush_keys.test
        mysql-test/t/mysqlbinlog.test
        mysql-test/t/mysqltest.test
        mysql-test/t/named_pipe.test
        mysql-test/t/not_partition.test
        mysql-test/t/olap.test
        mysql-test/t/order_by.test
        mysql-test/t/partition.test
        mysql-test/t/partition_csv.test
        mysql-test/t/partition_innodb.test
        mysql-test/t/plugin.test
        mysql-test/t/plugin_load.test
        mysql-test/t/ps_not_windows.test
        mysql-test/t/query_cache.test
        mysql-test/t/range.test
        mysql-test/t/select.test
        mysql-test/t/sp-error.test
        mysql-test/t/sp.test
        mysql-test/t/subselect.test
        mysql-test/t/subselect3.test
        mysql-test/t/type_bit.test
        mysql-test/t/type_newdecimal.test
        mysql-test/t/udf.test
        mysql-test/t/update.test
        mysql-test/t/upgrade.test
        mysql-test/t/view_grant.test
        mysql-test/t/warnings.test
        mysql-test/t/windows.test
        mysql-test/t/xa.test
        mysql-test/valgrind.supp
        mysys/CMakeLists.txt
        mysys/Makefile.am
        mysys/hash.c
        mysys/mf_keycache.c
        mysys/my_copy.c
        mysys/my_getopt.c
        mysys/my_largepage.c
        mysys/my_static.c
        mysys/my_thr_init.c
        mysys/my_wincond.c
        mysys/thr_lock.c
        mysys/typelib.c
        regex/CMakeLists.txt
        scripts/make_win_bin_dist
        scripts/mysql_system_tables.sql
        scripts/mysql_system_tables_fix.sql
        sql-common/client.c
        sql-common/my_time.c
        sql/CMakeLists.txt
        sql/Makefile.am
        sql/event_data_objects.cc
        sql/events.cc
        sql/field.cc
        sql/field.h
        sql/ha_ndbcluster.cc
        sql/ha_ndbcluster_binlog.cc
        sql/ha_partition.cc
        sql/ha_partition.h
        sql/handler.cc
        sql/handler.h
        sql/item.cc
        sql/item.h
        sql/item_cmpfunc.cc
        sql/item_cmpfunc.h
        sql/item_func.cc
        sql/item_func.h
        sql/item_geofunc.cc
        sql/item_strfunc.cc
        sql/item_subselect.cc
        sql/item_sum.cc
        sql/item_timefunc.cc
        sql/item_xmlfunc.cc
        sql/log.cc
        sql/log_event.cc
        sql/log_event.h
        sql/log_event_old.cc
        sql/my_decimal.h
        sql/mysql_priv.h
        sql/mysqld.cc
        sql/opt_range.cc
        sql/opt_sum.cc
        sql/partition_info.cc
        sql/records.cc
        sql/repl_failsafe.cc
        sql/rpl_filter.cc
        sql/set_var.cc
        sql/set_var.h
        sql/share/errmsg.txt
        sql/slave.cc
        sql/slave.h
        sql/sp.cc
        sql/sp_head.cc
        sql/sql_acl.cc
        sql/sql_base.cc
        sql/sql_binlog.cc
        sql/sql_cache.cc
        sql/sql_class.cc
        sql/sql_class.h
        sql/sql_db.cc
        sql/sql_delete.cc
        sql/sql_handler.cc
        sql/sql_insert.cc
        sql/sql_lex.h
        sql/sql_load.cc
        sql/sql_locale.cc
        sql/sql_parse.cc
        sql/sql_partition.cc
        sql/sql_plugin.cc
        sql/sql_prepare.cc
        sql/sql_rename.cc
        sql/sql_repl.cc
        sql/sql_select.cc
        sql/sql_select.h
        sql/sql_show.cc
        sql/sql_table.cc
        sql/sql_tablespace.cc
        sql/sql_trigger.cc
        sql/sql_udf.cc
        sql/sql_update.cc
        sql/sql_view.cc
        sql/sql_yacc.yy
        sql/structs.h
        sql/table.cc
        sql/table.h
        sql/time.cc
        sql/udf_example.c
        sql/unireg.cc
        storage/archive/ha_archive.cc
        storage/blackhole/ha_blackhole.cc
        storage/csv/ha_tina.cc
        storage/federatedx/Makefile.am
        storage/federatedx/ha_federatedx.cc
        storage/heap/hp_write.c
        storage/innobase/dict/dict0dict.c
        storage/innobase/handler/ha_innodb.cc
        storage/innobase/handler/ha_innodb.h
        storage/innobase/os/os0proc.c
        storage/innobase/row/row0mysql.c
        storage/innodb_plugin/CMakeLists.txt
        storage/innodb_plugin/ChangeLog
        storage/innodb_plugin/Makefile.am
        storage/innodb_plugin/btr/btr0btr.c
        storage/innodb_plugin/btr/btr0sea.c
        storage/innodb_plugin/buf/buf0buf.c
        storage/innodb_plugin/buf/buf0flu.c
        storage/innodb_plugin/buf/buf0lru.c
        storage/innodb_plugin/buf/buf0rea.c
        storage/innodb_plugin/dict/dict0crea.c
        storage/innodb_plugin/dict/dict0dict.c
        storage/innodb_plugin/fil/fil0fil.c
        storage/innodb_plugin/fsp/fsp0fsp.c
        storage/innodb_plugin/handler/ha_innodb.cc
        storage/innodb_plugin/handler/ha_innodb.h
        storage/innodb_plugin/handler/handler0alter.cc
        storage/innodb_plugin/include/buf0buf.h
        storage/innodb_plugin/include/buf0buf.ic
        storage/innodb_plugin/include/buf0lru.h
        storage/innodb_plugin/include/buf0rea.h
        storage/innodb_plugin/include/buf0types.h
        storage/innodb_plugin/include/dict0crea.h
        storage/innodb_plugin/include/dict0dict.h
        storage/innodb_plugin/include/dict0mem.h
        storage/innodb_plugin/include/fsp0fsp.h
        storage/innodb_plugin/include/lock0lock.h
        storage/innodb_plugin/include/log0log.h
        storage/innodb_plugin/include/log0log.ic
        storage/innodb_plugin/include/log0recv.h
        storage/innodb_plugin/include/mtr0mtr.h
        storage/innodb_plugin/include/os0file.h
        storage/innodb_plugin/include/os0sync.h
        storage/innodb_plugin/include/page0page.h
        storage/innodb_plugin/include/page0page.ic
        storage/innodb_plugin/include/page0zip.h
        storage/innodb_plugin/include/rem0cmp.h
        storage/innodb_plugin/include/rem0rec.ic
        storage/innodb_plugin/include/row0ins.h
        storage/innodb_plugin/include/row0mysql.h
        storage/innodb_plugin/include/srv0srv.h
        storage/innodb_plugin/include/trx0rec.h
        storage/innodb_plugin/include/trx0rec.ic
        storage/innodb_plugin/include/trx0roll.h
        storage/innodb_plugin/include/trx0sys.ic
        storage/innodb_plugin/include/trx0trx.h
        storage/innodb_plugin/include/univ.i
        storage/innodb_plugin/include/ut0auxconf.h
        storage/innodb_plugin/include/ut0byte.h
        storage/innodb_plugin/include/ut0byte.ic
        storage/innodb_plugin/include/ut0ut.h
        storage/innodb_plugin/lock/lock0lock.c
        storage/innodb_plugin/log/log0log.c
        storage/innodb_plugin/log/log0recv.c
        storage/innodb_plugin/mem/mem0mem.c
        storage/innodb_plugin/mtr/mtr0mtr.c
        storage/innodb_plugin/mysql-test/innodb-analyze.test
        storage/innodb_plugin/mysql-test/innodb-zip.result
        storage/innodb_plugin/mysql-test/innodb-zip.test
        storage/innodb_plugin/mysql-test/innodb_bug34300.test
        storage/innodb_plugin/mysql-test/innodb_bug36169.test
        storage/innodb_plugin/mysql-test/innodb_bug36172.test
        storage/innodb_plugin/mysql-test/innodb_file_format.result
        storage/innodb_plugin/mysql-test/innodb_file_format.test
        storage/innodb_plugin/os/os0file.c
        storage/innodb_plugin/os/os0proc.c
        storage/innodb_plugin/page/page0cur.c
        storage/innodb_plugin/page/page0page.c
        storage/innodb_plugin/page/page0zip.c
        storage/innodb_plugin/plug.in.disabled
        storage/innodb_plugin/rem/rem0cmp.c
        storage/innodb_plugin/row/row0ins.c
        storage/innodb_plugin/row/row0merge.c
        storage/innodb_plugin/row/row0mysql.c
        storage/innodb_plugin/srv/srv0srv.c
        storage/innodb_plugin/srv/srv0start.c
        storage/innodb_plugin/sync/sync0rw.c
        storage/innodb_plugin/sync/sync0sync.c
        storage/innodb_plugin/thr/thr0loc.c
        storage/innodb_plugin/trx/trx0rec.c
        storage/innodb_plugin/trx/trx0roll.c
        storage/innodb_plugin/trx/trx0trx.c
        storage/innodb_plugin/ut/ut0auxconf_atomic_pthread_t_solaris.c
        storage/innodb_plugin/ut/ut0ut.c
        storage/maria/ha_maria.cc
        storage/myisam/ha_myisam.cc
        storage/myisam/mi_check.c
        storage/myisam/mi_search.c
        storage/myisam/mi_write.c
        storage/myisam/myisamchk.c
        storage/myisam/sort.c
        storage/myisammrg/myrg_open.c
        storage/mysql_storage_engine.cmake
        storage/ndb/src/kernel/blocks/dblqh/DblqhMain.cpp
        storage/ndb/src/kernel/blocks/suma/Suma.cpp
        storage/pbxt/src/discover_xt.cc
        storage/xtradb/handler/ha_innodb.cc
        storage/xtradb/handler/ha_innodb.h
        strings/ctype-simple.c
        strings/ctype-uca.c
        support-files/binary-configure.sh
        tests/mysql_client_test.c
        unittest/mysys/Makefile.am
        vio/vio.c
        vio/vio_priv.h
        vio/viosocket.c
        vio/viosslfactories.c
        mysql-test/r/innodb_lock_wait_timeout_1.result
        mysql-test/t/innodb_lock_wait_timeout_1.test

=== modified file '.bzrignore'
--- a/.bzrignore	2009-11-06 17:22:32 +0000
+++ b/.bzrignore	2009-11-10 15:15:12 +0000
@@ -1922,3 +1922,4 @@ libmysqld/examples/mysqltest.cc
 extra/libevent/event-config.h
 libmysqld/opt_table_elimination.cc
 libmysqld/ha_federatedx.cc
+libmysqld/debug_sync.cc

=== modified file 'CMakeLists.txt'
--- a/CMakeLists.txt	2009-10-03 19:24:13 +0000
+++ b/CMakeLists.txt	2009-11-10 15:15:12 +0000
@@ -66,6 +66,12 @@ IF(EXTRA_DEBUG)
   ADD_DEFINITIONS(-D EXTRA_DEBUG)
 ENDIF(EXTRA_DEBUG)
 
+IF(ENABLED_DEBUG_SYNC)
+  ADD_DEFINITIONS(-D ENABLED_DEBUG_SYNC)
+ENDIF(ENABLED_DEBUG_SYNC)
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DENABLED_DEBUG_SYNC")
+SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DENABLED_DEBUG_SYNC")
+
 # in some places we use DBUG_OFF
 SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -DDBUG_OFF")
 SET(CMAKE_CXX_FLAGS_RELWITHDEBINFO "${CMAKE_CXX_FLAGS_RELWITHDEBINFO} -DDBUG_OFF")
@@ -211,12 +217,16 @@ ENDIF(WITHOUT_DYNAMIC_PLUGINS)
 FILE(GLOB STORAGE_SUBDIRS storage/*)
 FOREACH(SUBDIR ${STORAGE_SUBDIRS})
   FILE(RELATIVE_PATH DIRNAME ${PROJECT_SOURCE_DIR}/storage ${SUBDIR})
-  STRING(TOUPPER ${DIRNAME} ENGINE)
-  STRING(TOLOWER ${DIRNAME} ENGINE_LOWER) 
   IF (EXISTS ${SUBDIR}/CMakeLists.txt)
     # Check  MYSQL_STORAGE_ENGINE macro is present
     FILE(STRINGS ${SUBDIR}/CMakeLists.txt HAVE_STORAGE_ENGINE REGEX MYSQL_STORAGE_ENGINE)
     IF(HAVE_STORAGE_ENGINE)
+      # Extract name of engine from HAVE_STORAGE_ENGINE
+      STRING(REGEX REPLACE ".*MYSQL_STORAGE_ENGINE\\((.*\)\\).*"
+           "\\1" ENGINE_NAME ${HAVE_STORAGE_ENGINE})
+      STRING(TOUPPER ${ENGINE_NAME} ENGINE)
+      STRING(TOLOWER ${ENGINE_NAME} ENGINE_LOWER) 
+    
       SET(ENGINE_BUILD_TYPE "DYNAMIC")
       # Read plug.in to find out if a plugin is mandatory and whether it supports
       # build as shared library (dynamic).
@@ -254,6 +264,7 @@ FOREACH(SUBDIR ${STORAGE_SUBDIRS})
           SET (MYSQLD_STATIC_ENGINE_LIBS ${MYSQLD_STATIC_ENGINE_LIBS} ${PLUGIN_NAME})
           SET (STORAGE_ENGINE_DEFS "${STORAGE_ENGINE_DEFS} -DWITH_${ENGINE}_STORAGE_ENGINE")
           SET (WITH_${ENGINE}_STORAGE_ENGINE TRUE)
+	  SET (${ENGINE}_DIR ${DIRNAME})
         ENDIF (ENGINE_BUILD_TYPE STREQUAL "STATIC")
       ENDIF(EXISTS ${SUBDIR}/plug.in)
 

=== modified file 'Makefile.am'
--- a/Makefile.am	2009-10-11 15:38:37 +0000
+++ b/Makefile.am	2009-11-10 15:15:12 +0000
@@ -1,4 +1,4 @@
-# Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
+# Copyright 2000-2008 MySQL AB, 2009 Sun Microsystems, Inc.
 # 
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -26,7 +26,7 @@ EXTRA_DIST =		INSTALL-SOURCE INSTALL-WIN
 SUBDIRS =		. include @docs_dirs@ @zlib_dir@ \
 			@readline_topdir@ sql-common scripts \
 			@pstack_dir@ \
-			@sql_union_dirs@ unittest storage plugin \
+			@sql_union_dirs@ storage \
 			@sql_server@ @man_dirs@ tests \
 			netware @libmysqld_dirs@ \
 			mysql-test support-files sql-bench @tools_dirs@ \
@@ -208,6 +208,10 @@ test-bt-fast:
 	-cd mysql-test ; MTR_BUILD_THREAD=auto \
 	    @PERL@ ./mysql-test-run.pl $(MTR_EXTRA_OPTIONS) --force --comment=stress --suite=stress
 
+test-bt-fast2:
+	-cd mysql-test ; MTR_BUILD_THREAD=auto \
+	    @PERL@ ./mysql-test-run.pl --force --comment=ps --ps-protocol --report-features
+
 test-bt-debug:
 	-cd mysql-test ; MTR_BUILD_THREAD=auto \
 	    @PERL@ ./mysql-test-run.pl $(MTR_EXTRA_OPTIONS) --comment=debug  --force --timer \
@@ -215,6 +219,8 @@ test-bt-debug:
 
 test-bt-debug-fast:
 
+test-bt-debug-fast:
+
 # Keep these for a while
 test-pl:	test
 test-full-pl:	test-full

=== modified file 'client/mysql.cc'
--- a/client/mysql.cc	2009-11-06 17:22:32 +0000
+++ b/client/mysql.cc	2009-11-10 15:15:12 +0000
@@ -1281,21 +1281,35 @@ sig_handler handle_sigint(int sig)
   MYSQL *kill_mysql= NULL;
 
   /* terminate if no query being executed, or we already tried interrupting */
-  if (!executing_query || interrupted_query)
+  /* terminate if no query being executed, or we already tried interrupting */
+  if (!executing_query || (interrupted_query == 2))
+  {
+    tee_fprintf(stdout, "Ctrl-C -- exit!\n");
     goto err;
+  }
 
   kill_mysql= mysql_init(kill_mysql);
   if (!mysql_real_connect(kill_mysql,current_host, current_user, opt_password,
                           "", opt_mysql_port, opt_mysql_unix_port,0))
+  {
+    tee_fprintf(stdout, "Ctrl-C -- sorry, cannot connect to server to kill query, giving up ...\n");
     goto err;
+  }
+
+  interrupted_query++;
+
+  /* mysqld < 5 does not understand KILL QUERY, skip to KILL CONNECTION */
+  if ((interrupted_query == 1) && (mysql_get_server_version(&mysql) < 50000))
+    interrupted_query= 2;
 
   /* kill_buffer is always big enough because max length of %lu is 15 */
-  sprintf(kill_buffer, "KILL /*!50000 QUERY */ %lu", mysql_thread_id(&mysql));
-  mysql_real_query(kill_mysql, kill_buffer, strlen(kill_buffer));
+  sprintf(kill_buffer, "KILL %s%lu",
+          (interrupted_query == 1) ? "QUERY " : "",
+          mysql_thread_id(&mysql));
+  tee_fprintf(stdout, "Ctrl-C -- sending \"%s\" to server ...\n", kill_buffer);
+  mysql_real_query(kill_mysql, kill_buffer, (uint) strlen(kill_buffer));
   mysql_close(kill_mysql);
-  tee_fprintf(stdout, "Query aborted by Ctrl+C\n");
-
-  interrupted_query= 1;
+  tee_fprintf(stdout, "Ctrl-C -- query aborted.\n");
 
   return;
 
@@ -2873,7 +2887,7 @@ com_help(String *buffer __attribute__((u
            "For developer information, including the MySQL Reference Manual, "
            "visit:\n"
            "   http://dev.mysql.com/\n";
-           "To buy MySQL Network Support, training, or other products, visit:\n"
+           "To buy MySQL Enterprise support, training, or other products, visit:\n"
            "   https://shop.mysql.com/\n";, INFO_INFO);
   put_info("List of all MySQL commands:", INFO_INFO);
   if (!named_cmds)

=== modified file 'client/mysql_upgrade.c'
--- a/client/mysql_upgrade.c	2009-11-06 17:22:32 +0000
+++ b/client/mysql_upgrade.c	2009-11-10 15:15:12 +0000
@@ -54,6 +54,8 @@ static char **defaults_argv;
 
 static my_bool not_used; /* Can't use GET_BOOL without a value pointer */
 
+static my_bool opt_write_binlog;
+
 #include <help_start.h>
 
 static struct my_option my_long_options[]=
@@ -124,6 +126,11 @@ static struct my_option my_long_options[
   {"verbose", 'v', "Display more output about the process",
    (uchar**) &opt_verbose, (uchar**) &opt_verbose, 0,
    GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
+  {"write-binlog", OPT_WRITE_BINLOG,
+   "All commands including mysqlcheck are binlogged. Enabled by default;"
+   "use --skip-write-binlog when commands should not be sent to replication slaves.",
+   (uchar**) &opt_write_binlog, (uchar**) &opt_write_binlog, 0, GET_BOOL, NO_ARG,
+   1, 0, 0, 0, 0, 0},
   {0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
 };
 
@@ -448,6 +455,8 @@ static int run_query(const char *query, 
   int ret;
   File fd;
   char query_file_path[FN_REFLEN];
+  const uchar sql_log_bin[]= "SET SQL_LOG_BIN=0;";
+
   DBUG_ENTER("run_query");
   DBUG_PRINT("enter", ("query: %s", query));
   if ((fd= create_temp_file(query_file_path, opt_tmpdir,
@@ -455,6 +464,22 @@ static int run_query(const char *query, 
                             MYF(MY_WME))) < 0)
     die("Failed to create temporary file for defaults");
 
+  /*
+    Master and slave should be upgraded separately. All statements executed
+    by mysql_upgrade will not be binlogged.
+    'SET SQL_LOG_BIN=0' is executed before any other statements.
+   */
+  if (!opt_write_binlog)
+  {
+    if (my_write(fd, sql_log_bin, sizeof(sql_log_bin)-1,
+                 MYF(MY_FNABP | MY_WME)))
+    {
+      my_close(fd, MYF(0));
+      my_delete(query_file_path, MYF(0));
+      die("Failed to write to '%s'", query_file_path);
+    }
+  }
+
   if (my_write(fd, (uchar*) query, strlen(query),
                MYF(MY_FNABP | MY_WME)))
   {
@@ -647,6 +672,7 @@ static int run_mysqlcheck_upgrade(void)
                   "--check-upgrade",
                   "--all-databases",
                   "--auto-repair",
+                  opt_write_binlog ? "--write-binlog" : "--skip-write-binlog",
                   NULL);
 }
 
@@ -661,6 +687,7 @@ static int run_mysqlcheck_fixnames(void)
                   "--all-databases",
                   "--fix-db-names",
                   "--fix-table-names",
+                  opt_write_binlog ? "--write-binlog" : "--skip-write-binlog",
                   NULL);
 }
 

=== modified file 'client/mysqlbinlog.cc'
--- a/client/mysqlbinlog.cc	2009-09-15 10:46:35 +0000
+++ b/client/mysqlbinlog.cc	2009-11-10 15:15:12 +0000
@@ -78,6 +78,9 @@ static const char* host = 0;
 static int port= 0;
 static uint my_end_arg;
 static const char* sock= 0;
+#ifdef HAVE_SMEM
+static char *shared_memory_base_name= 0;
+#endif
 static const char* user = 0;
 static char* pass = 0;
 static char *charset= 0;
@@ -726,7 +729,10 @@ Exit_status process_event(PRINT_EVENT_IN
 
     switch (ev_type) {
     case QUERY_EVENT:
-      if (shall_skip_database(((Query_log_event*)ev)->db))
+      if (strncmp(((Query_log_event*)ev)->query, "BEGIN", 5) && 
+          strncmp(((Query_log_event*)ev)->query, "COMMIT", 6) && 
+          strncmp(((Query_log_event*)ev)->query, "ROLLBACK", 8) &&  
+          shall_skip_database(((Query_log_event*)ev)->db))
         goto end;
       if (opt_base64_output_mode == BASE64_OUTPUT_ALWAYS)
       {
@@ -989,13 +995,13 @@ static struct my_option my_long_options[
     /* 'unspec' is not mentioned because it is just a placeholder. */
    "Determine when the output statements should be base64-encoded BINLOG "
    "statements: 'never' disables it and works only for binlogs without "
-   "row-based events; 'auto' is the default and prints base64 only when "
-   "necessary (i.e., for row-based events and format description events); "
-   "'decode-rows' suppresses BINLOG statements for row events, but does "
-   "not exit as an error if a row event is found, unlike 'never'; "
-   "'always' prints base64 whenever possible. 'always' is for debugging "
-   "only and should not be used in a production system. The default is "
-   "'auto'. --base64-output is a short form for --base64-output=always."
+   "row-based events; 'decode-rows' decodes row events into commented SQL "
+   "statements if the --verbose option is also given; 'auto' prints base64 "
+   "only when necessary (i.e., for row-based events and format description "
+   "events); 'always' prints base64 whenever possible. 'always' is for "
+   "debugging only and should not be used in a production system. If this "
+   "argument is not given, the default is 'auto'; if it is given with no "
+   "argument, 'always' is used."
    ,(uchar**) &opt_base64_output_mode_str,
    (uchar**) &opt_base64_output_mode_str,
    0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
@@ -1074,6 +1080,12 @@ static struct my_option my_long_options[
   {"set-charset", OPT_SET_CHARSET,
    "Add 'SET NAMES character_set' to the output.", (uchar**) &charset,
    (uchar**) &charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
+#ifdef HAVE_SMEM
+  {"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
+   "Base name of shared memory.", (uchar**) &shared_memory_base_name, 
+   (uchar**) &shared_memory_base_name, 
+   0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
+#endif
   {"short-form", 's', "Just show regular queries: no extra info and no "
    "row-based events. This is for testing only, and should not be used in "
    "production systems. If you want to suppress base64-output, consider "
@@ -1376,6 +1388,11 @@ static Exit_status safe_connect()
 
   if (opt_protocol)
     mysql_options(mysql, MYSQL_OPT_PROTOCOL, (char*) &opt_protocol);
+#ifdef HAVE_SMEM
+  if (shared_memory_base_name)
+    mysql_options(mysql, MYSQL_SHARED_MEMORY_BASE_NAME,
+                  shared_memory_base_name);
+#endif
   if (!mysql_real_connect(mysql, host, user, pass, 0, port, sock, 0))
   {
     error("Failed on connect: %s", mysql_error(mysql));

=== modified file 'client/mysqlcheck.c'
--- a/client/mysqlcheck.c	2009-07-14 17:08:38 +0000
+++ b/client/mysqlcheck.c	2009-09-28 06:24:19 +0000
@@ -652,6 +652,17 @@ static int use_db(char *database)
   return 0;
 } /* use_db */
 
+static int disable_binlog()
+{
+  const char *stmt= "SET SQL_LOG_BIN=0";
+  if (mysql_query(sock, stmt))
+  {
+    fprintf(stderr, "Failed to %s\n", stmt);
+    fprintf(stderr, "Error: %s\n", mysql_error(sock));
+    return 1;
+  }
+  return 0;
+}
 
 static int handle_request_for_tables(char *tables, uint length)
 {
@@ -844,6 +855,14 @@ int main(int argc, char **argv)
   if (dbConnect(current_host, current_user, opt_password))
     exit(EX_MYSQLERR);
 
+  if (!opt_write_binlog)
+  {
+    if (disable_binlog()) {
+      first_error= 1;
+      goto end;
+    }
+  }
+
   if (opt_auto_repair &&
       my_init_dynamic_array(&tables4repair, sizeof(char)*(NAME_LEN*2+2),16,64))
   {

=== modified file 'client/mysqlimport.c'
--- a/client/mysqlimport.c	2009-07-14 17:08:38 +0000
+++ b/client/mysqlimport.c	2009-09-17 16:34:24 +0000
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB
+/* Copyright (C) 2000-2006 MySQL AB, 2009 Sun Microsystems, Inc.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -583,7 +583,7 @@ error:
   counter--;
   pthread_cond_signal(&count_threshhold);
   pthread_mutex_unlock(&counter_mutex);
-  my_thread_end();
+  mysql_thread_end();
 
   return 0;
 }

=== modified file 'client/mysqlslap.c'
--- a/client/mysqlslap.c	2009-10-26 11:35:42 +0000
+++ b/client/mysqlslap.c	2009-11-10 15:15:12 +0000
@@ -1,4 +1,4 @@
-/* Copyright (C) 2005 MySQL AB
+/* Copyright (C) 2005 MySQL AB, 2009 Sun Microsystems, Inc.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -423,6 +423,7 @@ void concurrency_loop(MYSQL *mysql, uint
   stats *sptr;
   conclusions conclusion;
   unsigned long long client_limit;
+  int sysret;
 
   head_sptr= (stats *)my_malloc(sizeof(stats) * iterations, 
                                 MYF(MY_ZEROFILL|MY_FAE|MY_WME));
@@ -472,7 +473,10 @@ void concurrency_loop(MYSQL *mysql, uint
       run_query(mysql, "SET AUTOCOMMIT=0", strlen("SET AUTOCOMMIT=0"));
 
     if (pre_system)
-      if (system(pre_system)) { /* Ignore for now */ }
+      if ((sysret= system(pre_system)) != 0)
+        fprintf(stderr,
+                "Warning: Execution of pre_system option returned %d.\n", 
+                sysret);
 
     /* 
       Pre statements are always run after all other logic so they can 
@@ -487,8 +491,10 @@ void concurrency_loop(MYSQL *mysql, uint
       run_statements(mysql, post_statements);
 
     if (post_system)
-      if (system(post_system)) { /* Ignore for now */ }
-
+      if ((sysret= system(post_system)) != 0)
+        fprintf(stderr,
+                "Warning: Execution of post_system option returned %d.\n", 
+                sysret);
     /* We are finished with this run */
     if (auto_generate_sql_autoincrement || auto_generate_sql_guid_primary)
       drop_primary_key_list();
@@ -1942,7 +1948,7 @@ end:
   if (!opt_only_print) 
     mysql_close(mysql);
 
-  my_thread_end();
+  mysql_thread_end();
 
   pthread_mutex_lock(&counter_mutex);
   thread_counter--;

=== modified file 'client/mysqltest.cc'
--- a/client/mysqltest.cc	2009-10-15 21:52:31 +0000
+++ b/client/mysqltest.cc	2009-11-10 15:15:12 +0000
@@ -82,6 +82,9 @@ enum {
 static int record= 0, opt_sleep= -1;
 static char *opt_db= 0, *opt_pass= 0;
 const char *opt_user= 0, *opt_host= 0, *unix_sock= 0, *opt_basedir= "./";
+#ifdef HAVE_SMEM
+static char *shared_memory_base_name=0;
+#endif
 const char *opt_logdir= "";
 const char *opt_include= 0, *opt_charsets_dir;
 static int opt_port= 0;
@@ -429,6 +432,7 @@ static struct st_expected_errors saved_e
 struct st_command
 {
   char *query, *query_buf,*first_argument,*last_argument,*end;
+  DYNAMIC_STRING content;
   int first_word_len, query_len;
   my_bool abort_on_error;
   struct st_expected_errors expected_errors;
@@ -1152,6 +1156,8 @@ void free_used_memory()
   {
     struct st_command **q= dynamic_element(&q_lines, i, struct st_command**);
     my_free((*q)->query_buf,MYF(MY_ALLOW_ZERO_PTR));
+    if ((*q)->content.str)
+      dynstr_free(&(*q)->content);
     my_free((*q),MYF(0));
   }
   for (i= 0; i < 10; i++)
@@ -1177,6 +1183,7 @@ void free_used_memory()
     mysql_server_end();
 
   /* Don't use DBUG after mysql_server_end() */
+  DBUG_VIOLATION_HELPER_LEAVE;
   return;
 }
 
@@ -1543,7 +1550,7 @@ void show_diff(DYNAMIC_STRING* ds,
   else
     diff_name = 0;
 #else
-  diff_name = "diff";		// Otherwise always assume it's called diff
+  diff_name = "diff";           /* Otherwise always assume it's called diff */
 #endif
 
   if (diff_name)
@@ -3321,21 +3328,30 @@ void do_write_file_command(struct st_com
                      sizeof(write_file_args)/sizeof(struct command_arg),
                      ' ');
 
-  /* If no delimiter was provided, use EOF */
-  if (ds_delimiter.length == 0)
-    dynstr_set(&ds_delimiter, "EOF");
-
   if (!append && access(ds_filename.str, F_OK) == 0)
   {
     /* The file should not be overwritten */
     die("File already exist: '%s'", ds_filename.str);
   }
 
-  init_dynamic_string(&ds_content, "", 1024, 1024);
-  read_until_delimiter(&ds_content, &ds_delimiter);
-  DBUG_PRINT("info", ("Writing to file: %s", ds_filename.str));
-  str_to_file2(ds_filename.str, ds_content.str, ds_content.length, append);
-  dynstr_free(&ds_content);
+  ds_content= command->content;
+  /* If it hasn't been done already by a loop iteration, fill it in */
+  if (! ds_content.str)
+  {
+    /* If no delimiter was provided, use EOF */
+    if (ds_delimiter.length == 0)
+      dynstr_set(&ds_delimiter, "EOF");
+
+    init_dynamic_string(&ds_content, "", 1024, 1024);
+    read_until_delimiter(&ds_content, &ds_delimiter);
+    command->content= ds_content;
+  }
+  /* This function could be called even if "false", so check before printing */
+  if (cur_block->ok)
+  {
+    DBUG_PRINT("info", ("Writing to file: %s", ds_filename.str));
+    str_to_file2(ds_filename.str, ds_content.str, ds_content.length, append);
+  }
   dynstr_free(&ds_filename);
   dynstr_free(&ds_delimiter);
   DBUG_VOID_RETURN;
@@ -3478,12 +3494,17 @@ void do_diff_files(struct st_command *co
     die("command \"diff_files\" failed, file '%s' does not exist",
         ds_filename2.str);
 
-  if ((error= compare_files(ds_filename.str, ds_filename2.str)))
+  if ((error= compare_files(ds_filename.str, ds_filename2.str)) &&
+      match_expected_error(command, error, NULL) < 0)
   {
     /* Compare of the two files failed, append them to output
-       so the failure can be analyzed
+       so the failure can be analyzed, but only if it was not
+       expected to fail.
     */
     show_diff(&ds_res, ds_filename.str, ds_filename2.str);
+    log_file.write(&ds_res);
+    log_file.flush();
+    dynstr_set(&ds_res, 0);
   }
 
   dynstr_free(&ds_filename);
@@ -4910,6 +4931,8 @@ do_handle_error:
   <opts> - options to use for the connection
    * SSL - use SSL if available
    * COMPRESS - use compression if available
+   * SHM - use shared memory if available
+   * PIPE - use named pipe if available
 
 */
 
@@ -4918,6 +4941,7 @@ void do_connect(struct st_command *comma
   int con_port= opt_port;
   char *con_options;
   my_bool con_ssl= 0, con_compress= 0;
+  my_bool con_pipe= 0, con_shm= 0;
   struct st_connection* con_slot;
 
   static DYNAMIC_STRING ds_connection_name;
@@ -4928,6 +4952,9 @@ void do_connect(struct st_command *comma
   static DYNAMIC_STRING ds_port;
   static DYNAMIC_STRING ds_sock;
   static DYNAMIC_STRING ds_options;
+#ifdef HAVE_SMEM
+  static DYNAMIC_STRING ds_shm;
+#endif
   const struct command_arg connect_args[] = {
     { "connection name", ARG_STRING, TRUE, &ds_connection_name, "Name of the connection" },
     { "host", ARG_STRING, TRUE, &ds_host, "Host to connect to" },
@@ -4955,6 +4982,11 @@ void do_connect(struct st_command *comma
       die("Illegal argument for port: '%s'", ds_port.str);
   }
 
+#ifdef HAVE_SMEM
+  /* Shared memory */
+  init_dynamic_string(&ds_shm, ds_sock.str, 0, 0);
+#endif
+
   /* Sock */
   if (ds_sock.length)
   {
@@ -4993,6 +5025,10 @@ void do_connect(struct st_command *comma
       con_ssl= 1;
     else if (!strncmp(con_options, "COMPRESS", 8))
       con_compress= 1;
+    else if (!strncmp(con_options, "PIPE", 4))
+      con_pipe= 1;
+    else if (!strncmp(con_options, "SHM", 3))
+      con_shm= 1;
     else
       die("Illegal option to connect: %.*s", 
           (int) (end - con_options), con_options);
@@ -5043,6 +5079,31 @@ void do_connect(struct st_command *comma
   }
 #endif
 
+#ifdef __WIN__
+  if (con_pipe)
+  {
+    uint protocol= MYSQL_PROTOCOL_PIPE;
+    mysql_options(&con_slot->mysql, MYSQL_OPT_PROTOCOL, &protocol);
+  }
+#endif
+
+#ifdef HAVE_SMEM
+  if (con_shm)
+  {
+    uint protocol= MYSQL_PROTOCOL_MEMORY;
+    if (!ds_shm.length)
+      die("Missing shared memory base name");
+    mysql_options(&con_slot->mysql, MYSQL_SHARED_MEMORY_BASE_NAME, ds_shm.str);
+    mysql_options(&con_slot->mysql, MYSQL_OPT_PROTOCOL, &protocol);
+  }
+  else if(shared_memory_base_name)
+  {
+    mysql_options(&con_slot->mysql, MYSQL_SHARED_MEMORY_BASE_NAME,
+      shared_memory_base_name);
+  }
+#endif
+
+
   /* Use default db name */
   if (ds_database.length == 0)
     dynstr_set(&ds_database, opt_db);
@@ -5075,6 +5136,9 @@ void do_connect(struct st_command *comma
   dynstr_free(&ds_port);
   dynstr_free(&ds_sock);
   dynstr_free(&ds_options);
+#ifdef HAVE_SMEM
+  dynstr_free(&ds_shm);
+#endif
   DBUG_VOID_RETURN;
 }
 
@@ -5746,6 +5810,12 @@ static struct my_option my_long_options[
    0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
   {"server-file", 'F', "Read embedded server arguments from file.",
    0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
+#ifdef HAVE_SMEM
+  {"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
+   "Base name of shared memory.", (uchar**) &shared_memory_base_name, 
+   (uchar**) &shared_memory_base_name, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 
+   0, 0, 0},
+#endif
   {"silent", 's', "Suppress all normal output. Synonym for --quiet.",
    (uchar**) &silent, (uchar**) &silent, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
   {"skip-safemalloc", OPT_SKIP_SAFEMALLOC,
@@ -6809,8 +6879,10 @@ void run_query_stmt(MYSQL *mysql, struct
   MYSQL_STMT *stmt;
   DYNAMIC_STRING ds_prepare_warnings;
   DYNAMIC_STRING ds_execute_warnings;
+  ulonglong affected_rows;
   DBUG_ENTER("run_query_stmt");
   DBUG_PRINT("query", ("'%-.60s'", query));
+  LINT_INIT(affected_rows);
 
   /*
     Init a new stmt if it's not already one created for this connection
@@ -6950,32 +7022,43 @@ void run_query_stmt(MYSQL *mysql, struct
       */
     }
 
-    if (!disable_warnings)
+    /*
+      Need to grab affected rows information before getting
+      warnings here
+    */
     {
-      /* Get the warnings from execute */
+      ulonglong affected_rows;
+      LINT_INIT(affected_rows);
 
-      /* Append warnings to ds - if there are any */
-      if (append_warnings(&ds_execute_warnings, mysql) ||
-          ds_execute_warnings.length ||
-          ds_prepare_warnings.length ||
-          ds_warnings->length)
-      {
-        dynstr_append_mem(ds, "Warnings:\n", 10);
-	if (ds_warnings->length)
-	  dynstr_append_mem(ds, ds_warnings->str,
-			    ds_warnings->length);
-	if (ds_prepare_warnings.length)
-	  dynstr_append_mem(ds, ds_prepare_warnings.str,
-			    ds_prepare_warnings.length);
-	if (ds_execute_warnings.length)
-	  dynstr_append_mem(ds, ds_execute_warnings.str,
-			    ds_execute_warnings.length);
-      }
-    }
+      if (!disable_info)
+	affected_rows= mysql_affected_rows(mysql);
 
-    if (!disable_info)
-      append_info(ds, mysql_affected_rows(mysql), mysql_info(mysql));
+      if (!disable_warnings)
+      {
+	/* Get the warnings from execute */
 
+	/* Append warnings to ds - if there are any */
+	if (append_warnings(&ds_execute_warnings, mysql) ||
+	    ds_execute_warnings.length ||
+	    ds_prepare_warnings.length ||
+	    ds_warnings->length)
+	{
+	  dynstr_append_mem(ds, "Warnings:\n", 10);
+	  if (ds_warnings->length)
+	    dynstr_append_mem(ds, ds_warnings->str,
+			      ds_warnings->length);
+	  if (ds_prepare_warnings.length)
+	    dynstr_append_mem(ds, ds_prepare_warnings.str,
+			      ds_prepare_warnings.length);
+	  if (ds_execute_warnings.length)
+	    dynstr_append_mem(ds, ds_execute_warnings.str,
+			      ds_execute_warnings.length);
+	}
+      }
+
+      if (!disable_info)
+	append_info(ds, affected_rows, mysql_info(mysql));
+    }
   }
 
 end:
@@ -7224,6 +7307,10 @@ void run_query(struct st_connection *cn,
     run_query_normal(cn, command, flags, query, query_len,
 		     ds, &ds_warnings);
 
+  dynstr_free(&ds_warnings);
+  if (command->type == Q_EVAL)
+    dynstr_free(&eval_query);
+
   if (display_result_sorted)
   {
     /* Sort the result set and append it to result */
@@ -7254,11 +7341,8 @@ void run_query(struct st_connection *cn,
     check_require(ds, command->require_file);
   }
 
-  dynstr_free(&ds_warnings);
   if (ds == &ds_result)
     dynstr_free(&ds_result);
-  if (command->type == Q_EVAL)
-    dynstr_free(&eval_query);
   DBUG_VOID_RETURN;
 }
 
@@ -7704,6 +7788,11 @@ int main(int argc, char **argv)
   }
 #endif
 
+#ifdef HAVE_SMEM
+  if (shared_memory_base_name)
+    mysql_options(&con->mysql,MYSQL_SHARED_MEMORY_BASE_NAME,shared_memory_base_name);
+#endif
+
   if (!(con->name = my_strdup("default", MYF(MY_WME))))
     die("Out of memory");
 
@@ -7742,7 +7831,32 @@ int main(int argc, char **argv)
       command->type= Q_COMMENT;
     }
 
-    if (cur_block->ok)
+    my_bool ok_to_do= cur_block->ok;
+    /*
+      Some commands need to be "done" the first time if they may get
+      re-iterated over in a true context. This can only happen if there's 
+      a while loop at some level above the current block.
+    */
+    if (!ok_to_do)
+    {
+      if (command->type == Q_SOURCE ||
+          command->type == Q_ERROR ||
+          command->type == Q_WRITE_FILE ||
+          command->type == Q_APPEND_FILE ||
+	  command->type == Q_PERL)
+      {
+	for (struct st_block *stb= cur_block-1; stb >= block_stack; stb--)
+	{
+	  if (stb->cmd == cmd_while)
+	  {
+	    ok_to_do= 1;
+	    break;
+	  }
+	}
+      }
+    }
+
+    if (ok_to_do)
     {
       command->last_argument= command->first_argument;
       processed = 1;
@@ -8053,6 +8167,8 @@ int main(int argc, char **argv)
   if (parsing_disabled)
     die("Test ended with parsing disabled");
 
+  my_bool empty_result= FALSE;
+  
   /*
     The whole test has been executed _sucessfully_.
     Time to compare result or save it to record file.
@@ -8093,11 +8209,20 @@ int main(int argc, char **argv)
   }
   else
   {
-    die("The test didn't produce any output");
+    /* Empty output is an error *unless* we also have an empty result file */
+    if (! result_file_name || record ||
+        compare_files (log_file.file_name(), result_file_name))
+    {
+      die("The test didn't produce any output");
+    }
+    else 
+    {
+      empty_result= TRUE;  /* Meaning empty was expected */
+    }
   }
 
-  if (!command_executed && result_file_name)
-    die("No queries executed but result file found!");
+  if (!command_executed && result_file_name && !empty_result)
+    die("No queries executed but non-empty result file found!");
 
   verbose_msg("Test has succeeded!");
   timer_output();
@@ -8184,6 +8309,8 @@ void do_get_replace_column(struct st_com
   }
   my_free(start, MYF(0));
   command->last_argument= command->end;
+
+  DBUG_VOID_RETURN;
 }
 
 

=== modified file 'cmd-line-utils/readline/display.c'
--- a/cmd-line-utils/readline/display.c	2009-09-07 20:50:10 +0000
+++ b/cmd-line-utils/readline/display.c	2009-11-10 15:15:12 +0000
@@ -463,10 +463,10 @@ rl_redisplay ()
   int newlines, lpos, temp, modmark;
   char *prompt_this_line;
 #if defined (HANDLE_MULTIBYTE)
-  int num, n0;
+  int num, n0= 0;
   wchar_t wc;
   size_t wc_bytes;
-  int wc_width;
+  int wc_width= 0;
   mbstate_t ps;
   int _rl_wrapped_multicolumn = 0;
 #endif
@@ -824,7 +824,7 @@ rl_redisplay ()
 		  cpos_buffer_position = out;
 		  lb_linenum = newlines;
 		}
-	      for (i = in; i < in+wc_bytes; i++)
+	      for (i = in; i < in+(int)wc_bytes; i++)
 		line[out++] = rl_line_buffer[i];
 	      for (i = 0; i < wc_width; i++)
 		CHECK_LPOS();

=== modified file 'configure.in'
--- a/configure.in	2009-11-06 17:22:32 +0000
+++ b/configure.in	2009-11-10 15:15:12 +0000
@@ -15,7 +15,7 @@ AC_CANONICAL_SYSTEM
 # MySQL version number.
 #
 # Note: the following line must be parseable by win/configure.js:GetVersion()
-AM_INIT_AUTOMAKE(mysql, 5.1.38-maria-beta)
+AM_INIT_AUTOMAKE(mysql, 5.1.42-mariadb-beta)
 AM_CONFIG_HEADER([include/config.h:config.h.in])
 
 PROTOCOL_VERSION=10
@@ -1652,13 +1652,14 @@ then
   DEBUG_OPTIMIZE_CXX="-O"
   OPTIMIZE_CXXFLAGS="$MAX_CXX_OPTIMIZE"
 else
-  DEBUG_CXXFLAGS="-g"
   DEBUG_OPTIMIZE_CXX=""
   case $SYSTEM_TYPE in
     *solaris*)
+      DEBUG_CXXFLAGS="-g0"
       OPTIMIZE_CXXFLAGS="-O1"
       ;;
     *)
+      DEBUG_CXXFLAGS="-g"
       OPTIMIZE_CXXFLAGS="-O"
       ;;
   esac
@@ -1715,6 +1716,23 @@ else
   CXXFLAGS="$OPTIMIZE_CXXFLAGS $CXXFLAGS"
 fi
 
+# Debug Sync Facility. NOTE: depends on 'with_debug'. Must be behind it.
+AC_MSG_CHECKING(if Debug Sync Facility should be enabled.)
+AC_ARG_ENABLE(debug_sync,
+              AS_HELP_STRING([--enable-debug-sync],
+                             [Build a version with Debug Sync Facility]),
+              [ enable_debug_sync=$enableval ],
+              [ enable_debug_sync=$with_debug ])
+
+if test "$enable_debug_sync" != "no"
+then
+  AC_DEFINE([ENABLED_DEBUG_SYNC], [1],
+            [If Debug Sync Facility should be enabled])
+  AC_MSG_RESULT([yes]) 
+else
+  AC_MSG_RESULT([no])
+fi
+
 # If we should allow error injection tests
 AC_ARG_WITH(error-inject,
     AC_HELP_STRING([--with-error-inject],[Enable error injection in MySQL Server]),
@@ -2775,7 +2793,7 @@ server_scripts=
 
 dnl This probably should be cleaned up more - for now the threaded
 dnl client is just using plain-old libs.
-sql_client_dirs="strings regex mysys libmysql"
+sql_client_dirs="strings mysys dbug extra regex libmysql unittest"
 
 AM_CONDITIONAL(THREAD_SAFE_CLIENT, test "$THREAD_SAFE_CLIENT" != "no")
 
@@ -2803,12 +2821,20 @@ fi
 AC_SUBST(netware_dir)
 AM_CONDITIONAL(HAVE_NETWARE, test "$netware_dir" = "netware")
 
-if test "$with_server" = "yes" -o "$THREAD_SAFE_CLIENT" != "no"
+if test "$with_server" != "no" -o "$THREAD_SAFE_CLIENT" != "no"
 then
   AC_DEFINE([THREAD], [1],
             [Define if you want to have threaded code. This may be undef on client code])
+  # Avoid _PROGRAMS names
+  THREAD_LOBJECTS="thr_alarm.o thr_lock.o thr_mutex.o thr_rwlock.o my_pthread.o my_thr_init.o mf_keycache.o mf_keycaches.o waiting_threads.o"
+  AC_SUBST(THREAD_LOBJECTS)
+fi
+AM_CONDITIONAL(NEED_THREAD, test "$with_server" != "no" -o "$THREAD_SAFE_CLIENT" != "no")
+
+if test "$with_server" != "no"
+then
   server_scripts="mysqld_safe mysql_install_db"
-  sql_server_dirs="strings mysys dbug extra regex"
+  sql_server_dirs="strings mysys dbug extra regex storage plugin"
 
   sql_server="vio sql"
 fi
@@ -2834,9 +2860,10 @@ AC_SUBST(mysql_plugin_defs)
 
 
 # Now that sql_client_dirs and sql_server_dirs are stable, determine the union.
-# Start with the (longer) server list, add each client item not yet present.
-sql_union_dirs=" $sql_server_dirs "
-for DIR in $sql_client_dirs
+# We support client-only builds by "--without-server", but not vice versa,
+# so we start with the client list, then add each server item not yet present.
+sql_union_dirs=" $sql_client_dirs "
+for DIR in $sql_server_dirs
 do
   if echo " $sql_union_dirs " | grep " $DIR " >/dev/null
   then

=== modified file 'extra/yassl/include/yassl_int.hpp'
--- a/extra/yassl/include/yassl_int.hpp	2009-09-03 13:20:22 +0000
+++ b/extra/yassl/include/yassl_int.hpp	2009-11-10 15:15:12 +0000
@@ -441,7 +441,7 @@ public:
     const Ciphers&    GetCiphers()  const;
     const DH_Parms&   GetDH_Parms() const;
     const Stats&      GetStats()    const;
-    VerifyCallback getVerifyCallback() const;
+    VerifyCallback    getVerifyCallback() const;
     pem_password_cb   GetPasswordCb() const;
           void*       GetUserData()   const;
           bool        GetSessionCacheOff() const;

=== modified file 'extra/yassl/taocrypt/src/random.cpp'
--- a/extra/yassl/taocrypt/src/random.cpp	2007-01-29 15:54:40 +0000
+++ b/extra/yassl/taocrypt/src/random.cpp	2009-10-06 16:10:34 +0000
@@ -27,7 +27,6 @@
 #include <time.h>
 
 #if defined(_WIN32)
-    #define _WIN32_WINNT 0x0400
     #include <windows.h>
     #include <wincrypt.h>
 #else

=== modified file 'include/my_dbug.h'
--- a/include/my_dbug.h	2009-09-07 20:50:10 +0000
+++ b/include/my_dbug.h	2009-11-10 15:15:12 +0000
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000 MySQL AB
+/* Copyright (C) 2000 MySQL AB & 2009 Monty Program Ab
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -16,7 +16,30 @@
 #ifndef _dbug_h
 #define _dbug_h
 
-#ifdef  __cplusplus
+#if defined(__cplusplus) && !defined(DBUG_OFF)
+class Dbug_violation_helper
+{
+public:
+  inline Dbug_violation_helper() :
+    _entered(TRUE)
+  { }
+
+  inline ~Dbug_violation_helper()
+  {
+    assert(!_entered);
+  }
+
+  inline void leave()
+  {
+    _entered= FALSE;
+  }
+
+private:
+  bool _entered;
+};
+#endif /* C++ */
+
+#ifdef	__cplusplus
 extern "C" {
 #endif
 #if !defined(DBUG_OFF) && !defined(_lint)
@@ -30,34 +53,51 @@ struct _db_stack_frame_ {
 
 struct  _db_code_state_;
 extern  my_bool _dbug_on_;
-extern  my_bool _db_keyword_(struct _db_code_state_ *, const char *, int);
+extern  my_bool _db_keyword_(struct _db_code_state_ *cs, const char *keyword,
+                             int strict_flag);
+extern  int _db_strict_keyword_(const char *keyword);
 extern  int _db_explain_(struct _db_code_state_ *cs, char *buf, size_t len);
 extern  int _db_explain_init_(char *buf, size_t len);
 extern	int _db_is_pushed_(void);
 extern  void _db_setjmp_(void);
 extern  void _db_longjmp_(void);
 extern  void _db_process_(const char *name);
-extern  void _db_push_(const char *control);
-extern  void _db_pop_(void);
+extern	void _db_push_(const char *control);
+extern	void _db_pop_(void);
 extern  void _db_set_(const char *control);
 extern  void _db_set_init_(const char *control);
-extern void _db_enter_(const char *_func_, const char *_file_, uint _line_,
-                       struct _db_stack_frame_ *_stack_frame_);
+extern  void _db_enter_(const char *_func_, const char *_file_, uint _line_,
+                        struct _db_stack_frame_ *_stack_frame_);
 extern  void _db_return_(uint _line_, struct _db_stack_frame_ *_stack_frame_);
 extern  void _db_pargs_(uint _line_,const char *keyword);
 extern  void _db_doprnt_ _VARARGS((const char *format,...))
   ATTRIBUTE_FORMAT(printf, 1, 2);
-extern  void _db_dump_(uint _line_,const char *keyword,
+extern	void _db_dump_(uint _line_,const char *keyword,
                        const unsigned char *memory, size_t length);
-extern  void _db_end_(void);
-extern  void _db_lock_file_(void);
-extern  void _db_unlock_file_(void);
-extern  FILE *_db_fp_(void);
+extern	void _db_end_(void);
+extern	void _db_lock_file_(void);
+extern	void _db_unlock_file_(void);
+extern FILE *_db_fp_(void);
 extern  void _db_flush_();
 
+#ifdef __cplusplus
+
 #define DBUG_ENTER(a) struct _db_stack_frame_ _db_stack_frame_; \
+        Dbug_violation_helper dbug_violation_helper; \
         _db_enter_ (a,__FILE__,__LINE__,&_db_stack_frame_)
-#define DBUG_LEAVE _db_return_ (__LINE__, &_db_stack_frame_)
+#define DBUG_VIOLATION_HELPER_LEAVE dbug_violation_helper.leave()
+
+#else /* C */
+
+#define DBUG_ENTER(a) struct _db_stack_frame_ _db_stack_frame_; \
+        _db_enter_ (a,__FILE__,__LINE__,&_db_stack_frame_)
+#define DBUG_VIOLATION_HELPER_LEAVE do { } while(0)
+
+#endif /* C++ */
+
+#define DBUG_LEAVE \
+        DBUG_VIOLATION_HELPER_LEAVE; \
+        _db_return_ (__LINE__, &_db_stack_frame_)
 #define DBUG_RETURN(a1) do {DBUG_LEAVE; return(a1);} while(0)
 #define DBUG_VOID_RETURN do {DBUG_LEAVE; return;} while(0)
 #define DBUG_EXECUTE(keyword,a1) \
@@ -88,28 +128,15 @@ extern  void _db_flush_();
 #define DEBUGGER_OFF                    do { _dbug_on_= 0; } while(0)
 #define DEBUGGER_ON                     do { _dbug_on_= 1; } while(0)
 #define IF_DBUG(A) A
-#ifndef __WIN__
 #define DBUG_ABORT()                    (_db_flush_(), abort())
-#else
-/*
-  Avoid popup with abort/retry/ignore buttons. When BUG#31745 is fixed we can
-  call abort() instead of _exit(3) (now it would cause a "test signal" popup).
-*/
-#include <crtdbg.h>
-#define DBUG_ABORT() (_db_flush_(),\
-                     (void)_CrtSetReportMode(_CRT_ERROR, _CRTDBG_MODE_FILE),\
-                     (void)_CrtSetReportFile(_CRT_ERROR, _CRTDBG_FILE_STDERR),\
-                     _exit(3))
-#endif
-
 #else                                           /* No debugger */
 
 #define DBUG_ENTER(a1)
 #define DBUG_LEAVE
-#define DBUG_RETURN(a1)                 do { return(a1); } while(0)
-#define DBUG_VOID_RETURN                do { return; } while(0)
-#define DBUG_EXECUTE(keyword,a1)        do { } while(0)
-#define DBUG_EXECUTE_IF(keyword,a1)     do { } while(0)
+#define DBUG_RETURN(a1)             do { return(a1); } while(0)
+#define DBUG_VOID_RETURN            do { return; } while(0)
+#define DBUG_EXECUTE(keyword,a1)    do { } while(0)
+#define DBUG_EXECUTE_IF(keyword,a1) do { } while(0)
 #define DBUG_EVALUATE(keyword,a1,a2) (a2)
 #define DBUG_EVALUATE_IF(keyword,a1,a2) (a2)
 #define DBUG_PRINT(keyword,arglist)     do { } while(0)

=== modified file 'include/my_sys.h'
--- a/include/my_sys.h	2009-09-07 20:50:10 +0000
+++ b/include/my_sys.h	2009-11-10 15:15:12 +0000
@@ -69,6 +69,7 @@ extern int NEAR my_errno;		/* Last error
 #define MY_HOLD_ON_ERROR 256	/* my_realloc() ; Return old ptr on error */
 #define MY_DONT_OVERWRITE_FILE 2048 /* my_copy: Don't overwrite file */
 #define MY_THREADSAFE 2048      /* my_seek(): lock fd mutex */
+#define MY_SYNC       4096      /* my_copy(): sync dst file */
 
 #define MY_CHECK_ERROR	1	/* Params to my_end; Check open-close */
 #define MY_GIVE_INFO	2	/* Give time info about process*/
@@ -175,6 +176,16 @@ extern char *my_strndup(const char *from
 #define TRASH(A,B) /* nothing */
 #endif
 
+#if defined(ENABLED_DEBUG_SYNC)
+extern void (*debug_sync_C_callback_ptr)(const char *, size_t);
+#define DEBUG_SYNC_C(_sync_point_name_) do {                            \
+    if (debug_sync_C_callback_ptr != NULL)                              \
+      (*debug_sync_C_callback_ptr)(STRING_WITH_LEN(_sync_point_name_)); } \
+  while(0)
+#else
+#define DEBUG_SYNC_C(_sync_point_name_)
+#endif /* defined(ENABLED_DEBUG_SYNC) */
+
 #ifdef HAVE_LARGE_PAGES
 extern uint my_get_large_page_size(void);
 extern uchar * my_large_malloc(size_t size, myf my_flags);
@@ -727,7 +738,6 @@ extern int wild_compare(const char *str,
 extern WF_PACK *wf_comp(char * str);
 extern int wf_test(struct wild_file_pack *wf_pack,const char *name);
 extern void wf_end(struct wild_file_pack *buffer);
-extern size_t strip_sp(char * str);
 extern my_bool array_append_string_unique(const char *str,
                                           const char **array, size_t size);
 extern void get_date(char * to,int timeflag,time_t use_time);

=== modified file 'include/myisamchk.h'
--- a/include/myisamchk.h	2009-09-07 20:50:10 +0000
+++ b/include/myisamchk.h	2009-11-10 15:15:12 +0000
@@ -154,6 +154,10 @@ typedef struct st_handler_check_param
   char temp_filename[FN_REFLEN];
   IO_CACHE read_cache;
   enum_handler_stats_method stats_method;
+#ifdef THREAD
+  pthread_mutex_t print_msg_mutex;
+  my_bool need_print_msg_lock;
+#endif
 } HA_CHECK;
 
 

=== modified file 'include/mysql.h'
--- a/include/mysql.h	2009-10-02 10:36:28 +0000
+++ b/include/mysql.h	2009-11-10 15:15:12 +0000
@@ -558,6 +558,16 @@ unsigned long STDCALL mysql_real_escape_
 					       char *to,const char *from,
 					       unsigned long length);
 void		STDCALL mysql_debug(const char *debug);
+char *		STDCALL mysql_odbc_escape_string(MYSQL *mysql,
+						 char *to,
+						 unsigned long to_length,
+						 const char *from,
+						 unsigned long from_length,
+						 void *param,
+						 char *
+						 (*extend_buffer)
+						 (void *, char *to,
+						  unsigned long *length));
 void 		STDCALL myodbc_remove_escape(MYSQL *mysql,char *name);
 unsigned int	STDCALL mysql_thread_safe(void);
 my_bool		STDCALL mysql_embedded(void);

=== modified file 'include/mysql.h.pp'
--- a/include/mysql.h.pp	2009-10-02 10:36:28 +0000
+++ b/include/mysql.h.pp	2009-11-10 15:15:12 +0000
@@ -518,6 +518,16 @@ unsigned long mysql_real_escape_string(M
             char *to,const char *from,
             unsigned long length);
 void mysql_debug(const char *debug);
+char * mysql_odbc_escape_string(MYSQL *mysql,
+       char *to,
+       unsigned long to_length,
+       const char *from,
+       unsigned long from_length,
+       void *param,
+       char *
+       (*extend_buffer)
+       (void *, char *to,
+        unsigned long *length));
 void myodbc_remove_escape(MYSQL *mysql,char *name);
 unsigned int mysql_thread_safe(void);
 my_bool mysql_embedded(void);

=== modified file 'include/violite.h'
--- a/include/violite.h	2009-09-07 20:50:10 +0000
+++ b/include/violite.h	2009-11-10 15:15:12 +0000
@@ -44,7 +44,7 @@ enum enum_vio_type
 Vio*	vio_new(my_socket sd, enum enum_vio_type type, uint flags);
 #ifdef __WIN__
 Vio* vio_new_win32pipe(HANDLE hPipe);
-Vio* vio_new_win32shared_memory(NET *net,HANDLE handle_file_map,
+Vio* vio_new_win32shared_memory(HANDLE handle_file_map,
                                 HANDLE handle_map,
                                 HANDLE event_server_wrote,
                                 HANDLE event_server_read,
@@ -222,7 +222,11 @@ struct st_vio
   HANDLE  event_conn_closed;
   size_t  shared_memory_remain;
   char    *shared_memory_pos;
-  NET     *net;
 #endif /* HAVE_SMEM */
+#ifdef _WIN32
+  OVERLAPPED pipe_overlapped;
+  DWORD read_timeout_millis;
+  DWORD write_timeout_millis;
+#endif
 };
 #endif /* vio_violite_h_ */

=== modified file 'libmysql/libmysql.c'
--- a/libmysql/libmysql.c	2009-11-06 17:22:32 +0000
+++ b/libmysql/libmysql.c	2009-11-10 15:15:12 +0000
@@ -1642,6 +1642,20 @@ mysql_real_escape_string(MYSQL *mysql, c
   return (uint) escape_string_for_mysql(mysql->charset, to, 0, from, length);
 }
 
+
+char * STDCALL
+mysql_odbc_escape_string(MYSQL *mysql __attribute__((unused)),
+                         char *to __attribute__((unused)),
+                         ulong to_length __attribute__((unused)),
+                         const char *from __attribute__((unused)),
+                         ulong from_length __attribute__((unused)),
+                         void *param __attribute__((unused)),
+                         char * (*extend_buffer)(void *, char *, ulong *)
+                         __attribute__((unused)))
+{
+  return NULL;
+}
+
 void STDCALL
 myodbc_remove_escape(MYSQL *mysql,char *name)
 {

=== modified file 'libmysql/libmysql.def'
--- a/libmysql/libmysql.def	2009-10-04 22:22:57 +0000
+++ b/libmysql/libmysql.def	2009-11-10 15:15:12 +0000
@@ -78,6 +78,7 @@ EXPORTS
 	mysql_next_result
 	mysql_num_fields
 	mysql_num_rows
+	mysql_odbc_escape_string
 	mysql_options
 	mysql_stmt_param_count
 	mysql_stmt_param_metadata

=== modified file 'libmysqld/CMakeLists.txt'
--- a/libmysqld/CMakeLists.txt	2009-10-03 19:24:13 +0000
+++ b/libmysqld/CMakeLists.txt	2009-11-10 15:15:12 +0000
@@ -90,8 +90,10 @@ ENDFOREACH(rpath)
 FOREACH (ENGINE_LIB ${MYSQLD_STATIC_ENGINE_LIBS})
   INCLUDE(${CMAKE_SOURCE_DIR}/storage/${plugin_dir_${ENGINE_LIB}}/CMakeLists.txt)
   STRING(TOUPPER ${ENGINE_LIB} ENGINE_LIB_UPPER)
+  SET(ENGINE_DIR ${${ENGINE_LIB_UPPER}_DIR})
+  INCLUDE(${CMAKE_SOURCE_DIR}/storage/${ENGINE_DIR}/CMakeLists.txt)
   FOREACH(rpath ${${ENGINE_LIB_UPPER}_SOURCES})
-    SET(LIB_SOURCES ${LIB_SOURCES} ${CMAKE_SOURCE_DIR}/storage/${plugin_dir_${ENGINE_LIB}}/${rpath})
+    SET(LIB_SOURCES ${LIB_SOURCES} ${CMAKE_SOURCE_DIR}/storage/${ENGINE_DIR}/${rpath})
   ENDFOREACH(rpath)
 ENDFOREACH(ENGINE_LIB)
 
@@ -127,6 +129,7 @@ SET(LIBMYSQLD_SOURCES emb_qcache.cc libm
            ../sql/sql_list.cc ../sql/sql_load.cc ../sql/sql_locale.cc 
            ../sql/sql_binlog.cc ../sql/sql_manager.cc ../sql/sql_map.cc 
            ../sql/sql_parse.cc ../sql/sql_partition.cc ../sql/sql_plugin.cc 
+           ../sql/debug_sync.cc
            ../sql/sql_prepare.cc ../sql/sql_rename.cc ../sql/sql_repl.cc 
            ../sql/sql_select.cc ../sql/sql_servers.cc
            ../sql/sql_show.cc ../sql/sql_state.c ../sql/sql_string.cc
@@ -152,6 +155,14 @@ ADD_LIBRARY(mysqlserver STATIC ${LIBMYSQ
 ADD_DEPENDENCIES(mysqlserver GenServerSource GenError)
 TARGET_LINK_LIBRARIES(mysqlserver)
 
+# Add any additional libraries requested by engine(s)
+FOREACH (ENGINE_LIB ${MYSQLD_STATIC_ENGINE_LIBS})
+  STRING(TOUPPER ${ENGINE_LIB} ENGINE_LIB_UPPER)
+  IF(${ENGINE_LIB_UPPER}_LIBS)
+    TARGET_LINK_LIBRARIES(mysqlserver ${${ENGINE_LIB_UPPER}_LIBS})
+  ENDIF(${ENGINE_LIB_UPPER}_LIBS)
+ENDFOREACH(ENGINE_LIB)
+
 ADD_LIBRARY(libmysqld SHARED cmake_dummy.c libmysqld.def)
 ADD_DEPENDENCIES(libmysqld mysqlserver)
 TARGET_LINK_LIBRARIES(libmysqld mysqlserver wsock32)

=== modified file 'libmysqld/Makefile.am'
--- a/libmysqld/Makefile.am	2009-10-30 18:50:56 +0000
+++ b/libmysqld/Makefile.am	2009-11-10 15:15:12 +0000
@@ -74,6 +74,7 @@ sqlsources = derror.cc field.cc field_co
 	sp_head.cc sp_pcontext.cc sp.cc sp_cache.cc sp_rcontext.cc \
 	parse_file.cc sql_view.cc sql_trigger.cc my_decimal.cc \
 	rpl_filter.cc sql_partition.cc sql_builtin.cc sql_plugin.cc \
+	debug_sync.cc \
 	sql_tablespace.cc \
 	rpl_injector.cc my_user.c partition_info.cc \
 	sql_servers.cc event_parse_data.cc opt_table_elimination.cc

=== modified file 'libmysqld/lib_sql.cc'
--- a/libmysqld/lib_sql.cc	2009-09-07 20:50:10 +0000
+++ b/libmysqld/lib_sql.cc	2009-11-10 15:15:12 +0000
@@ -142,6 +142,8 @@ emb_advanced_command(MYSQL *mysql, enum 
   if (!skip_check)
     result= thd->is_error() ? -1 : 0;
 
+  thd->mysys_var= 0;
+
 #if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
   thd->profiling.finish_current_query();
 #endif
@@ -634,6 +636,7 @@ void *create_embedded_thd(int client_fla
 
   thread_count++;
   threads.append(thd);
+  thd->mysys_var= 0;
   return thd;
 err:
   delete(thd);

=== modified file 'libmysqld/libmysqld.c'
--- a/libmysqld/libmysqld.c	2008-02-28 17:55:46 +0000
+++ b/libmysqld/libmysqld.c	2009-09-25 11:39:05 +0000
@@ -164,6 +164,7 @@ mysql_real_connect(MYSQL *mysql,const ch
   port=0;
   unix_socket=0;
 
+  client_flag|=mysql->options.client_flag;
   /* Send client information for access check */
   client_flag|=CLIENT_CAPABILITIES;
   if (client_flag & CLIENT_MULTI_STATEMENTS)

=== modified file 'libmysqld/libmysqld.def'
--- a/libmysqld/libmysqld.def	2009-10-04 22:22:57 +0000
+++ b/libmysqld/libmysqld.def	2009-11-10 15:15:12 +0000
@@ -50,6 +50,7 @@ EXPORTS
 	mysql_next_result
 	mysql_num_fields
 	mysql_num_rows
+	mysql_odbc_escape_string
 	mysql_options
 	mysql_ping
 	mysql_query

=== modified file 'mysql-test/collections/README.experimental'
--- a/mysql-test/collections/README.experimental	2009-02-25 14:00:17 +0000
+++ b/mysql-test/collections/README.experimental	2009-08-13 13:29:19 +0000
@@ -23,3 +23,10 @@ The syntax is as follows:
    start with the same characters up to the last letter before the asterisk
    are considered experimental:
         main.a*  # get rid of main.alias, main.alibaba and main.agliolio
+
+6) Optionally, the test case may be followed by one or more platform
+   qualifiers beginning with @ or @!. The test will then be considered
+   experimental only/except on that platform. Basic OS names as
+   reported by $^O in Perl, or 'windows' are supported, this includes
+   solaris, linux, windows, aix, darwin, ...  Example:
+        main.alias  @aix @windows    # Fails on those

=== modified file 'mysql-test/collections/default.experimental'
--- a/mysql-test/collections/default.experimental	2009-08-13 20:45:01 +0000
+++ b/mysql-test/collections/default.experimental	2009-10-26 12:33:03 +0000
@@ -1,6 +1,45 @@
+# For easier human reading (MTR doesn't care), please keep entries
+# in alphabetical order. This also helps with merge conflict resolution.
+
+binlog.binlog_multi_engine               # joro : NDB tests marked as experimental as agreed with bochklin
+
 funcs_1.charset_collation_1              # depends on compile-time decisions
-binlog.binlog_tmp_table                  # Bug#45578: Test binlog_tmp_table fails ramdonly on PB2: Unknown table 't2'
-main.ctype_gbk_binlog                    # Bug#46010: main.ctype_gbk_binlog fails sporadically : Table 't2' already exists
-rpl.rpl_row_create_table                 # Bug#45576: rpl_row_create_table fails on PB2
+funcs_1.is_cml_ndb                       # joro : NDB tests marked as experimental as agreed with bochklin
+funcs_1.is_columns_ndb                   # joro : NDB tests marked as experimental as agreed with bochklin
+funcs_1.is_engines_ndb                   # joro : NDB tests marked as experimental as agreed with bochklin
+funcs_1.is_tables_ndb                    # joro : NDB tests marked as experimental as agreed with bochklin
+funcs_1.ndb*                             # joro : NDB tests marked as experimental as agreed with bochklin
+
+funcs_2.ndb_charset                      # joro : NDB tests marked as experimental as agreed with bochklin
+
+main.ctype_gbk_binlog  @solaris          # Bug#46010: main.ctype_gbk_binlog fails sporadically : Table 't2' already exists
+main.innodb-autoinc*                     # Bug#47809 2009-10-04 joro innodb-autoinc.test fails with valgrind errors with the innodb plugin
+main.plugin_load  @solaris               # Bug#42144
+
+ndb.*                                    # joro : NDB tests marked as experimental as agreed with bochklin
+
+rpl.rpl_cross_version*                   # Bug #43913 2009-10-26 joro rpl_cross_version can't pass on conflicts complainig clash with --slave-load-tm
+rpl.rpl_get_master_version_and_clock*    # Bug#46931 2009-08-26 alik rpl.rpl_get_master_version_and_clock fails on hpux11.31
+rpl.rpl_innodb_bug28430*  @solaris       # Bug#46029
+rpl.rpl_row_create_table*                # Bug#45576: rpl_row_create_table fails on PB2
+rpl.rpl_trigger*                         # Bug#47810 2009-10-04 joro rpl.rpl_trigger.test fails with valgrind errors with the innodb plugin
+
+rpl_ndb.*                                # joro : NDB tests marked as experimental as agreed with bochklin
 rpl_ndb.rpl_ndb_log                      # Bug#38998
-rpl.rpl_innodb_bug28430                  # Bug#46029
+
+stress.ddl_ndb                           # joro : NDB tests marked as experimental as agreed with bochklin
+
+parts.ndb_dd_backuprestore               # joro : NDB tests marked as experimental as agreed with bochklin
+parts.part_supported_sql_func_ndb        # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_alter1_1_ndb             # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_alter1_1_2_ndb           # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_alter1_2_ndb             # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_auto_increment_ndb       # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_basic_ndb                # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_engine_ndb               # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_int_ndb                  # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_mgm_lc0_ndb              # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_mgm_lc1_ndb              # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_mgm_lc2_ndb              # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_syntax_ndb               # joro : NDB tests marked as experimental as agreed with bochklin
+parts.partition_value_ndb                # joro : NDB tests marked as experimental as agreed with bochklin

=== modified file 'mysql-test/extra/binlog_tests/binlog.test'
--- a/mysql-test/extra/binlog_tests/binlog.test	2009-07-14 15:07:29 +0000
+++ b/mysql-test/extra/binlog_tests/binlog.test	2009-10-14 15:46:45 +0000
@@ -270,3 +270,42 @@ INSERT INTO test.t1 VALUES (1), (2);
 CREATE TABLE test.t2 SELECT * FROM test.t1;
 USE test;
 DROP TABLES t1, t2;
+
+#
+# Bug#46640
+# This test verifies if the server_id stored in the "format 
+# description BINLOG statement" will override the server_id 
+# of the server executing the statements.
+#
+
+connect (fresh,localhost,root,,test);
+connection fresh;
+
+RESET MASTER;
+CREATE TABLE t1 (a INT PRIMARY KEY);
+
+# Format description event, with server_id = 10;
+BINLOG '
+3u9kSA8KAAAAZgAAAGoAAAABAAQANS4xLjM1LW1hcmlhLWJldGExLWRlYnVnLWxvZwAAAAAAAAAA
+AAAAAAAAAAAAAAAAAADe72RIEzgNAAgAEgAEBAQEEgAAUwAEGggAAAAICAgC
+';
+
+# What server_id is logged for a statement? Should be our own, not the
+# one from the format description event.
+INSERT INTO t1 VALUES (1);
+
+# INSERT INTO t1 VALUES (2), with server_id=20. Check that this is logged
+# with our own server id, not the 20 from the BINLOG statement.
+BINLOG '
+3u9kSBMUAAAAKQAAAJEBAAAAABoAAAAAAAAABHRlc3QAAnQxAAEDAAA=
+3u9kSBcUAAAAIgAAALMBAAAQABoAAAAAAAEAAf/+AgAAAA==
+';
+
+# Show binlog events to check that server ids are correct.
+--replace_column 1 # 2 # 5 #
+--replace_regex /Server ver: .*, Binlog ver: .*/Server ver: #, Binlog ver: #/ /table_id: [0-9]+/table_id: #/
+SHOW BINLOG EVENTS;
+
+DROP TABLE t1;
+disconnect fresh;
+

=== added file 'mysql-test/extra/binlog_tests/binlog_failure_mixing_engines.test'
--- a/mysql-test/extra/binlog_tests/binlog_failure_mixing_engines.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/extra/binlog_tests/binlog_failure_mixing_engines.test	2009-10-06 00:54:00 +0000
@@ -0,0 +1,300 @@
+################################################################################
+# Let 
+#   - B be begin, C commit and R rollback.
+#   - T a statement that accesses and changes only transactional tables, i.e.
+#   T-tables
+#   - N a statement that accesses and changes only non-transactional tables,
+#   i.e, N-tables.
+#   - M be a mixed statement, i.e. a statement that updates both T- and 
+#   N-tables.
+#   - M* be a mixed statement that fails while updating either a T
+#   or N-table.
+#   - N* be a statement that fails while updating a N-table.
+#
+# In this test case, when changes are logged as rows either in the RBR or MIXED
+# modes, we check if a M* statement that happens early in a transaction is
+# written to the binary log outside the boundaries of the transaction and
+# wrapped up in a BEGIN/ROLLBACK. This is done to keep the slave consistent with
+# the master as the rollback will keep the changes on N-tables and undo them on
+# T-tables. In particular, we expect the following behavior:
+#
+#  1. B M* T C would generate in the binlog B M* R B T C.
+#  2. B M M* C would generate in the binlog B M M* C.
+#  3. B M* M* T C would generate in the binlog B M* R B M* R B T C.
+#
+# SBR is not considered in this test because a failing statement is written to
+# the binary along with the error code such that a slave executes and rolls it
+# back, thus undoing the effects on T-tables.
+#
+# Note that, in the first case, we are not preserving history from the master as
+# we are introducing a rollback that never happened. However, this seems to be
+# more acceptable than making the slave diverge. In the second case, the slave
+# will diverge as the changes on T-tables that originated from the M statement
+# are rolled back on the master but not on the slave. Unfortunately, we cannot 
+# simply roll the transaction back as this would undo any uncommitted changes
+# on T-tables.
+#
+# We check two more cases. First, INSERT...SELECT* which produces the following
+# results:
+#
+# 1. B T INSERT M...SELECT* C" with an error in INSERT M...SELECT* generates in
+# the binlog the following entries: "Nothing".
+# 2. B INSERT M...SELECT* C" with an error in INSERT M...SELECT* generates in
+# the binlog the following entries: B INSERT M...SELECT* R.
+#
+# Finally, we also check if any N statement that happens early in a transaction
+# (i.e. before any T or M statement) is written to the binary log outside the
+# boundaries of the transaction. In particular, we expect the following
+# behavior:
+#
+# 1. B N N T C would generate in the binlog B N C B N C B T C.
+# 2. B N N T R would generate in the binlog B N C B N C B T R.
+# 3. B N* N* T C would generate in the binlog B N R B N R B T C.
+# 4. B N* N* T R would generate in the binlog B N R B N R B T R.
+# 5. B N N T N T C would generate in the binlog B N C B N C B T N T C.
+# 6. B N N T N T R would generate in the binlog the B N C B N C B T N T R.
+# 
+# Such issues do not happen in SBR. In RBR and MBR, a full-fledged fix will be
+# pushed after the WL#2687.
+#
+# Please, remove this test case after pushing WL#2687.
+################################################################################
+
+
+--echo ###################################################################################
+--echo #                                   CONFIGURATION
+--echo ###################################################################################
+CREATE TABLE nt_1 (a text, b int PRIMARY KEY) ENGINE = MyISAM;
+CREATE TABLE nt_2 (a text, b int PRIMARY KEY) ENGINE = MyISAM;
+CREATE TABLE tt_1 (a text, b int PRIMARY KEY) ENGINE = Innodb;
+CREATE TABLE tt_2 (a text, b int PRIMARY KEY) ENGINE = Innodb;
+
+DELIMITER |;
+
+CREATE TRIGGER tr_i_tt_1_to_nt_1 BEFORE INSERT ON tt_1 FOR EACH ROW
+BEGIN
+  INSERT INTO nt_1 VALUES (NEW.a, NEW.b);
+END|
+
+CREATE TRIGGER tr_i_nt_2_to_tt_2 BEFORE INSERT ON nt_2 FOR EACH ROW
+BEGIN
+  INSERT INTO tt_2 VALUES (NEW.a, NEW.b);
+END|
+
+DELIMITER ;|
+
+--echo ###################################################################################
+--echo #                             CHECK HISTORY IN BINLOG
+--echo ###################################################################################
+--echo
+--echo
+--echo
+--echo *** "B M* T C" with error in M* generates in the binlog the "B M* R B T C" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+INSERT INTO nt_1 VALUES ("new text 1", 1);
+BEGIN;
+--error ER_DUP_ENTRY
+INSERT INTO tt_1 VALUES (USER(), 2), (USER(), 1);
+INSERT INTO tt_2 VALUES ("new text 3", 3);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+INSERT INTO tt_2 VALUES ("new text 4", 4);
+BEGIN;
+--error ER_DUP_ENTRY
+INSERT INTO nt_2 VALUES (USER(), 5), (USER(), 4);
+INSERT INTO tt_2 VALUES ("new text 6", 6);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B M M* T C" with error in M* generates in the binlog the "B M M* T C" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+INSERT INTO nt_1 VALUES ("new text 10", 10);
+BEGIN;
+INSERT INTO tt_1 VALUES ("new text 7", 7), ("new text 8", 8);
+--error ER_DUP_ENTRY
+INSERT INTO tt_1 VALUES (USER(), 9), (USER(), 10);
+INSERT INTO tt_2 VALUES ("new text 11", 11);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+INSERT INTO tt_2 VALUES ("new text 15", 15);
+BEGIN;
+INSERT INTO nt_2 VALUES ("new text 12", 12), ("new text 13", 13);
+--error ER_DUP_ENTRY
+INSERT INTO nt_2 VALUES (USER(), 14), (USER(), 15);
+INSERT INTO tt_2 VALUES ("new text 16", 16);
+COMMIT;
+--source include/show_binlog_events.inc
+
+
+--echo
+--echo
+--echo
+--echo *** "B M* M* T C" with error in M* generates in the binlog the "B M* R B M* R B T C" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+INSERT INTO nt_1 VALUES ("new text 18", 18);
+INSERT INTO nt_1 VALUES ("new text 20", 20);
+BEGIN;
+--error ER_DUP_ENTRY
+INSERT INTO tt_1 VALUES (USER(), 17), (USER(), 18);
+--error ER_DUP_ENTRY
+INSERT INTO tt_1 VALUES (USER(), 19), (USER(), 20);
+INSERT INTO tt_2 VALUES ("new text 21", 21);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+INSERT INTO tt_2 VALUES ("new text 23", 23);
+INSERT INTO tt_2 VALUES ("new text 25", 25);
+BEGIN;
+--error ER_DUP_ENTRY
+INSERT INTO nt_2 VALUES (USER(), 22), (USER(), 23);
+--error ER_DUP_ENTRY
+INSERT INTO nt_2 VALUES (USER(), 24), (USER(), 25);
+INSERT INTO tt_2 VALUES ("new text 26", 26);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B T INSERT M...SELECT* C" with an error in INSERT M...SELECT* generates
+--echo *** in the binlog the following entries: "Nothing".
+--echo *** There is a bug in that will be fixed after WL#2687. Please, check BUG#47175 for further details.
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+TRUNCATE TABLE nt_2;
+TRUNCATE TABLE tt_2;
+INSERT INTO tt_2 VALUES ("new text 7", 7);
+BEGIN;
+INSERT INTO tt_2 VALUES ("new text 27", 27);
+--error ER_DUP_ENTRY
+INSERT INTO nt_2(a, b) SELECT USER(), b FROM nt_1;
+INSERT INTO tt_2 VALUES ("new text 28", 28);
+ROLLBACK;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B INSERT M..SELECT* C" with an error in INSERT M...SELECT* generates
+--echo *** in the binlog the following entries: "B INSERT M..SELECT* R".
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+TRUNCATE TABLE nt_2;
+TRUNCATE TABLE tt_2;
+INSERT INTO tt_2 VALUES ("new text 7", 7);
+BEGIN;
+--error ER_DUP_ENTRY
+INSERT INTO nt_2(a, b) SELECT USER(), b FROM nt_1;
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B N N T C" generates in the binlog the "B N C B N C B T C" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+TRUNCATE TABLE nt_1;
+TRUNCATE TABLE tt_2;
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 1);
+INSERT INTO nt_1 VALUES (USER(), 2);
+INSERT INTO tt_2 VALUES (USER(), 3);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B N N T R" generates in the binlog the "B N C B N C B T R" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 4);
+INSERT INTO nt_1 VALUES (USER(), 5);
+INSERT INTO tt_2 VALUES (USER(), 6);
+ROLLBACK;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B N* N* T C" with error in N* generates in the binlog the "B N R B N R B T C" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+BEGIN;
+--error ER_DUP_ENTRY
+INSERT INTO nt_1 VALUES (USER(), 7), (USER(), 1);
+--error ER_DUP_ENTRY
+INSERT INTO nt_1 VALUES (USER(), 8), (USER(), 1);
+INSERT INTO tt_2 VALUES (USER(), 9);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B N* N* T R" with error in N* generates in the binlog the "B N R B N R B T R" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+BEGIN;
+--error ER_DUP_ENTRY
+INSERT INTO nt_1 VALUES (USER(), 10), (USER(), 1);
+--error ER_DUP_ENTRY
+INSERT INTO nt_1 VALUES (USER(), 11), (USER(), 1);
+INSERT INTO tt_2 VALUES (USER(), 12);
+ROLLBACK;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B N N T N T C" generates in the binlog the "B N C B N C B T N T C" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 13);
+INSERT INTO nt_1 VALUES (USER(), 14);
+INSERT INTO tt_2 VALUES (USER(), 15);
+INSERT INTO nt_1 VALUES (USER(), 16);
+INSERT INTO tt_2 VALUES (USER(), 17);
+COMMIT;
+--source include/show_binlog_events.inc
+
+--echo
+--echo
+--echo
+--echo *** "B N N T N T R" generates in the binlog the "B N C B N C B T N T R" entries
+--echo
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 18);
+INSERT INTO nt_1 VALUES (USER(), 19);
+INSERT INTO tt_2 VALUES (USER(), 20);
+INSERT INTO nt_1 VALUES (USER(), 21);
+INSERT INTO tt_2 VALUES (USER(), 22);
+ROLLBACK;
+--source include/show_binlog_events.inc
+
+--echo ###################################################################################
+--echo #                                        CLEAN
+--echo ###################################################################################
+
+DROP TABLE tt_1;
+DROP TABLE tt_2;
+DROP TABLE nt_1;
+DROP TABLE nt_2;

=== modified file 'mysql-test/extra/binlog_tests/drop_temp_table.test'
--- a/mysql-test/extra/binlog_tests/drop_temp_table.test	2007-06-15 16:56:11 +0000
+++ b/mysql-test/extra/binlog_tests/drop_temp_table.test	2009-11-03 10:20:08 +0000
@@ -1,27 +1,72 @@
 
 --disable_warnings
-drop database if exists `drop-temp+table-test`;
+DROP DATABASE IF EXISTS `drop-temp+table-test`;
 --enable_warnings
 
 connect (con1,localhost,root,,);
 connect (con2,localhost,root,,);
 connection con1;
-reset master;
-create database `drop-temp+table-test`;
-use `drop-temp+table-test`;
-create temporary table shortn1 (a int);
-create temporary table `table:name` (a int);
-create temporary table shortn2 (a int);
-select get_lock("a",10);
+RESET MASTER;
+CREATE DATABASE `drop-temp+table-test`;
+USE `drop-temp+table-test`;
+CREATE TEMPORARY TABLE shortn1 (a INT);
+CREATE TEMPORARY TABLE `table:name` (a INT);
+CREATE TEMPORARY TABLE shortn2 (a INT);
+
+##############################################################################
+# BUG#46572 DROP TEMPORARY table IF EXISTS does not have a consistent behavior
+# in ROW mode 
+# 
+# In RBR, 'DROP TEMPORARY TABLE ...' statement should never be binlogged no
+# matter if the tables exist or not. In contrast, both in SBR and MBR, the
+# statement should be always binlogged no matter if the tables exist or not.
+##############################################################################
+CREATE TEMPORARY TABLE tmp(c1 int);
+CREATE TEMPORARY TABLE tmp1(c1 int);
+CREATE TEMPORARY TABLE tmp2(c1 int);
+CREATE TEMPORARY TABLE tmp3(c1 int);
+CREATE TABLE t(c1 int);
+
+DROP TEMPORARY TABLE IF EXISTS tmp;
+
+--disable_warnings
+# Before fixing BUG#46572, 'DROP TEMPORARY TABLE IF EXISTS...' statement was
+# binlogged when the table did not exist in RBR.
+DROP TEMPORARY TABLE IF EXISTS tmp;
+
+# In RBR, 'DROP TEMPORARY TABLE ...' statement is never binlogged no matter if
+# the tables exist or not.
+DROP TEMPORARY TABLE IF EXISTS tmp, tmp1;
+DROP TEMPORARY TABLE tmp3;
+
+#In RBR, tmp2 will NOT be binlogged, because it is a temporary table.
+DROP TABLE IF EXISTS tmp2, t;
+
+#In RBR, tmp2 will be binlogged, because it does not exist and master do not know
+# whether it is a temporary table or not.
+DROP TABLE IF EXISTS tmp2, t;
+--enable_warnings
+
+SELECT GET_LOCK("a",10);
+
+#
+# BUG48216 Replication fails on all slaves after upgrade to 5.0.86 on master
+#
+# When the session is closed, any temporary tables of the session are dropped
+# and are binlogged. But it will be binlogged with a wrong database name when
+# the length of the database name('drop-temp-table-test') is greater than the
+# current database name('test').
+#
+USE test;
 disconnect con1;
 
 connection con2;
 # We want to SHOW BINLOG EVENTS, to know what was logged. But there is no
 # guarantee that logging of the terminated con1 has been done yet.
 # To be sure that logging has been done, we use a user lock.
-select get_lock("a",10);
-let $VERSION=`select version()`;
+SELECT GET_LOCK("a",10);
+let $VERSION=`SELECT VERSION()`;
 source include/show_binlog_events.inc;
-drop database `drop-temp+table-test`;
+DROP DATABASE `drop-temp+table-test`;
 
 # End of 4.1 tests

=== modified file 'mysql-test/extra/rpl_tests/rpl_auto_increment.test'
--- a/mysql-test/extra/rpl_tests/rpl_auto_increment.test	2009-04-08 16:55:26 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_auto_increment.test	2009-11-10 15:15:12 +0000
@@ -163,5 +163,81 @@ show create table t1;
 connection master;
 drop table t1;
 
+#
+# BUG#45999 Row based replication fails when auto_increment field = 0.  
+# Store engine of Slaves auto-generates new sequence numbers for
+# auto_increment fields if the values of them are 0. There is an inconsistency
+# between slave and master. When MODE_NO_AUTO_VALUE_ON_ZERO are masters treat 
+#
+source include/master-slave-reset.inc;
+
+connection master;
+--disable_warnings
+DROP TABLE IF EXISTS t1;
+DROP TABLE IF EXISTS t2;
+--enable_warnings
+
+eval CREATE TABLE t1 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY) ENGINE=$engine_type;
+eval CREATE TABLE t2 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY) ENGINE=$engine_type2;
+SET SQL_MODE='';
+# Value of the id will be 1;
+INSERT INTO t1 VALUES(NULL);
+INSERT INTO t2 VALUES(NULL);
+SELECT * FROM t1;
+SELECT * FROM t2;
+# Value of the id will be 2;
+INSERT INTO t1 VALUES();
+INSERT INTO t2 VALUES();
+SELECT * FROM t1;
+SELECT * FROM t2;
+# Value of the id will be 3. The master treats 0 as NULL or empty because
+# NO_AUTO_VALUE_ON_ZERO is not assign to SQL_MODE.
+INSERT INTO t1 VALUES(0);
+INSERT INTO t2 VALUES(0);
+SELECT * FROM t1;
+SELECT * FROM t2;
+
+SET SQL_MODE=NO_AUTO_VALUE_ON_ZERO;
+# Value of the id will be 0. The master does not treat 0 as NULL or empty
+# because NO_AUTO_VALUE_ON_ZERO has assigned to SQL_MODE.
+INSERT INTO t1 VALUES(0);
+INSERT INTO t2 VALUES(0);
+SELECT * FROM t1;
+SELECT * FROM t2;
+
+INSERT INTO t1 VALUES(4);
+INSERT INTO t2 VALUES(4);
+FLUSH LOGS;
+sync_slave_with_master;
+
+let $diff_table_1= master:test.t1;
+let $diff_table_2= slave:test.t1;
+source include/diff_tables.inc;
+
+let $diff_table_1= master:test.t2;
+let $diff_table_2= slave:test.t2;
+source include/diff_tables.inc;
+
+connection master;
+DROP TABLE t1;
+DROP TABLE t2;
+sync_slave_with_master;
+
+connection master;
+let $MYSQLD_DATADIR= `SELECT @@DATADIR`;
+--exec $MYSQL_BINLOG $MYSQLD_DATADIR/master-bin.000001 | $MYSQL test
+sync_slave_with_master;
+
+let $diff_table_1= master:test.t1;
+let $diff_table_2= slave:test.t1;
+source include/diff_tables.inc;
+
+let $diff_table_1= master:test.t2;
+let $diff_table_2= slave:test.t2;
+source include/diff_tables.inc;
+
 # End cleanup
+DROP TABLE t1;
+DROP TABLE t2;
+SET SQL_MODE='';
 sync_slave_with_master;

=== added file 'mysql-test/extra/rpl_tests/rpl_auto_increment_insert_view.test'
--- a/mysql-test/extra/rpl_tests/rpl_auto_increment_insert_view.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_auto_increment_insert_view.test	2009-09-30 23:19:36 +0000
@@ -0,0 +1,44 @@
+#
+# This test verifies if inserting data into view that invokes a 
+# trigger will make the autoinc values become inconsistent on 
+# master and slave.
+#
+connection master; 
+CREATE TABLE t1(i1 int not null auto_increment, c1 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t2(i1 int not null auto_increment, c2 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t3(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+eval create trigger tr16 $insert_action on t1 for each row insert into t3(a) values(new.c1);
+eval create trigger tr17 $insert_action on t2 for each row insert into t3(a) values(new.c2);
+begin;
+INSERT INTO t1(c1) VALUES (11), (12);
+INSERT INTO t2(c2) VALUES (13), (14);
+
+CREATE VIEW v16 AS SELECT c1, c2 FROM t1, t2;
+
+INSERT INTO v16(c1) VALUES (15),(16);
+INSERT INTO v16(c2) VALUES (17),(18);
+
+connection master1;
+INSERT INTO v16(c1) VALUES (19),(20);
+INSERT INTO v16(c2) VALUES (21),(22);
+
+connection master;
+INSERT INTO v16(c1) VALUES (23), (24);
+INSERT INTO v16(c1) VALUES (25), (26);
+commit;
+sync_slave_with_master;
+--echo #Test if the results are consistent on master and slave
+--echo #for 'INSERT DATA INTO VIEW WHICH INVOKES TRIGGERS'
+let $diff_table_1=master:test.t3;
+let $diff_table_2=slave:test.t3;
+source include/diff_tables.inc;
+
+connection master;
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP VIEW  v16;
+sync_slave_with_master;
+
+
+

=== added file 'mysql-test/extra/rpl_tests/rpl_auto_increment_invoke_trigger.test'
--- a/mysql-test/extra/rpl_tests/rpl_auto_increment_invoke_trigger.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_auto_increment_invoke_trigger.test	2009-09-30 23:19:36 +0000
@@ -0,0 +1,82 @@
+#
+# This test verifies if concurrent transactions that invoke a 
+# trigger that inserts more than one values into one or more 
+# tables with an auto_increment column will make the autoinc 
+# values become inconsistent on master and slave.
+#
+
+connection master;
+create table t1(a int, b int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+eval create trigger tr1 $trigger_action on t1 for each row insert into t2(a) values(6);
+
+create table t3(a int, b int) engine=innodb;
+create table t4(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t5(a int) engine=innodb;
+delimiter |;
+eval create trigger tr2 $trigger_action on t3 for each row begin
+    insert into t4(a) values(f1_insert_triggered());
+    insert into t4(a) values(f1_insert_triggered());
+    insert into t5(a) values(8);
+end |
+delimiter ;|
+
+create table t6(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+delimiter //;
+CREATE FUNCTION f1_insert_triggered() RETURNS INTEGER
+BEGIN
+   INSERT INTO t6(a) values(2),(3);
+   RETURN 1;
+END//
+delimiter ;//
+
+begin;
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+insert into t1(a,b) values(1,1),(2,1);
+insert into t3(a,b) values(1,1),(2,1);
+update t1 set a = a + 5 where b = 1;
+update t3 set a = a + 5 where b = 1;
+delete from t1 where b = 1;
+delete from t3 where b = 1;
+
+connection master1;
+#The default autocommit is set to 1, so the statement is auto committed
+insert into t2(a) values(3);
+insert into t4(a) values(3);
+
+connection master;
+commit;
+insert into t1(a,b) values(4,2);
+insert into t3(a,b) values(4,2);
+update t1 set a = a + 5 where b = 2;
+update t3 set a = a + 5 where b = 2;
+delete from t1 where b = 2;
+delete from t3 where b = 2;
+--echo # To verify if insert/update in an autoinc column causes statement to be logged in row format
+source include/show_binlog_events.inc;
+commit;
+
+connection master;
+sync_slave_with_master;
+--echo #Test if the results are consistent on master and slave
+--echo #for 'INVOKES A TRIGGER with $trigger_action action'
+let $diff_table_1=master:test.t2;
+let $diff_table_2=slave:test.t2;
+source include/diff_tables.inc;
+let $diff_table_1=master:test.t4;
+let $diff_table_2=slave:test.t4;
+source include/diff_tables.inc;
+let $diff_table_1=master:test.t6;
+let $diff_table_2=slave:test.t6;
+source include/diff_tables.inc;
+
+connection master;
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+DROP TABLE t5;
+DROP TABLE t6;
+DROP FUNCTION f1_insert_triggered;
+sync_slave_with_master;
+

=== added file 'mysql-test/extra/rpl_tests/rpl_autoinc_func_invokes_trigger.test'
--- a/mysql-test/extra/rpl_tests/rpl_autoinc_func_invokes_trigger.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_autoinc_func_invokes_trigger.test	2009-09-30 23:19:36 +0000
@@ -0,0 +1,57 @@
+#
+# This test verifies if concurrent transactions that call a 
+# function which invokes a 'after/before insert action' trigger 
+# that inserts more than one values into a table with autoinc 
+# column will make the autoinc values become inconsistent on 
+# master and slave.
+#
+
+connection master;
+create table t1(a int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t3(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+delimiter |;
+CREATE FUNCTION f1_two_inserts_trigger() RETURNS INTEGER
+BEGIN
+   INSERT INTO t2(a) values(2),(3);
+   INSERT INTO t2(a) values(2),(3);
+   RETURN 1;
+END |
+eval create trigger tr11 $insert_action on t2 for each row begin
+    insert into t3(a) values(new.a);
+    insert into t3(a) values(new.a);
+end |
+delimiter ;|
+begin;
+let $binlog_start= query_get_value("SHOW MASTER STATUS", Position, 1);
+insert into t1(a) values(f1_two_inserts_trigger());
+
+connection master1;
+#The default autocommit is set to 1, so the statement is auto committed
+insert into t2(a) values(4),(5);
+
+connection master;
+commit;
+insert into t1(a) values(f1_two_inserts_trigger());
+--echo # To verify if insert/update in an autoinc column causes statement to be logged in row format
+source include/show_binlog_events.inc;
+commit;
+
+connection master;
+sync_slave_with_master;
+--echo #Test if the results are consistent on master and slave
+--echo #for 'CALLS A FUNCTION which INVOKES A TRIGGER with $insert_action action'
+let $diff_table_1=master:test.t2;
+let $diff_table_2=slave:test.t2;
+source include/diff_tables.inc;
+let $diff_table_1=master:test.t3;
+let $diff_table_2=slave:test.t3;
+source include/diff_tables.inc;
+
+connection master;
+drop table t1;
+drop table t2;
+drop table t3;
+drop function f1_two_inserts_trigger;
+sync_slave_with_master;
+

=== modified file 'mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test'
--- a/mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test	2008-07-10 16:09:39 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test	2009-08-28 14:13:27 +0000
@@ -22,6 +22,8 @@ DROP TABLE IF EXISTS t1, t2,t3,t4,t5,t6,
 #          should stop the slave.               #
 #################################################
 
+call mtr.add_suppression("Slave: Unknown table 't6' Error_code: 1051");
+
 --echo **** Diff Table Def Start ****
 
 ##############################################

=== modified file 'mysql-test/extra/rpl_tests/rpl_failed_optimize.test'
--- a/mysql-test/extra/rpl_tests/rpl_failed_optimize.test	2006-05-05 17:08:40 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_failed_optimize.test	2009-09-27 22:03:05 +0000
@@ -22,3 +22,4 @@ connection master;
 select * from t1;
 commit;
 drop table t1;
+-- sync_slave_with_master

=== modified file 'mysql-test/extra/rpl_tests/rpl_loaddata.test'
--- a/mysql-test/extra/rpl_tests/rpl_loaddata.test	2008-11-13 19:19:00 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_loaddata.test	2009-10-27 15:15:53 +0000
@@ -158,4 +158,65 @@ LOAD DATA INFILE "../../std_data/words.d
 
 DROP TABLE IF EXISTS t1;
 
+# BUG#48297: Schema name is ignored when LOAD DATA is written into binlog,
+# replication aborts
+-- source include/master-slave-reset.inc
+
+-- let $db1= b48297_db1
+-- let $db2= b42897_db2
+
+-- connection master
+
+-- disable_warnings
+-- eval drop database if exists $db1
+-- eval drop database if exists $db2
+-- enable_warnings
+
+-- eval create database $db1
+-- eval create database $db2
+
+-- eval use $db1
+-- eval CREATE TABLE t1 (c1 VARCHAR(256)) engine=$engine_type;
+
+-- eval use $db2
+
+-- echo ### assertion: works with cross-referenced database
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- eval LOAD DATA LOCAL INFILE '$MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE $db1.t1
+
+-- eval use $db1
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- echo ### assertion: works with fully qualified name on current database
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- eval LOAD DATA LOCAL INFILE '$MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE $db1.t1
+
+-- echo ### assertion: works without fully qualified name on current database
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- eval LOAD DATA LOCAL INFILE '$MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE t1
+
+-- echo ### create connection without default database
+-- echo ### connect (conn2,localhost,root,,*NO-ONE*);
+connect (conn2,localhost,root,,*NO-ONE*);
+-- connection conn2
+-- echo ### assertion: works without stating the default database
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- eval LOAD DATA LOCAL INFILE '$MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE $db1.t1
+-- echo ### disconnect and switch back to master connection
+-- disconnect conn2
+-- connection master
+
+-- sync_slave_with_master
+-- eval use $db1
+
+let $diff_table_1=master:$db1.t1;
+let $diff_table_2=slave:$db1.t1;
+source include/diff_tables.inc;
+
+-- connection master
+
+-- eval DROP DATABASE $db1
+-- eval DROP DATABASE $db2
+
+-- sync_slave_with_master
+
 # End of 4.1 tests

=== modified file 'mysql-test/extra/rpl_tests/rpl_row_sp006.test'
--- a/mysql-test/extra/rpl_tests/rpl_row_sp006.test	2007-06-18 13:36:10 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_row_sp006.test	2009-09-04 01:33:45 +0000
@@ -9,29 +9,27 @@
 #############################################################################
 
 # Begin clean up test section
-connection master;
 --disable_warnings
-create database if not exists mysqltest1;
-DROP PROCEDURE IF EXISTS mysqltest1.p1;
-DROP PROCEDURE IF EXISTS mysqltest1.p2;
-DROP TABLE IF EXISTS mysqltest1.t2;
-DROP TABLE IF EXISTS mysqltest1.t1;
+DROP TABLE IF EXISTS t1;
+DROP TABLE IF EXISTS t2;
+DROP PROCEDURE IF EXISTS p1;
+DROP PROCEDURE IF EXISTS p2;
 --enable_warnings
 # End of cleanup
 
 # Begin test section 1
-eval CREATE TABLE IF NOT EXISTS mysqltest1.t1(name CHAR(16), birth DATE,PRIMARY KEY(name))ENGINE=$engine_type;
-eval CREATE TABLE IF NOT EXISTS mysqltest1.t2(name CHAR(16), age INT ,PRIMARY KEY(name))ENGINE=$engine_type;
+eval CREATE TABLE IF NOT EXISTS t1(name CHAR(16), birth DATE,PRIMARY KEY(name))ENGINE=$engine_type;
+eval CREATE TABLE IF NOT EXISTS t2(name CHAR(16), age INT ,PRIMARY KEY(name))ENGINE=$engine_type;
 
 delimiter |;
-CREATE PROCEDURE mysqltest1.p1()
+CREATE PROCEDURE p1()
 BEGIN
   DECLARE done INT DEFAULT 0;
   DECLARE spa CHAR(16);
   DECLARE spb INT;
   DECLARE cur1 CURSOR FOR SELECT name, 
        (YEAR(CURDATE())-YEAR(birth))-(RIGHT(CURDATE(),5)<RIGHT(birth,5)) 
-       FROM mysqltest1.t1;
+       FROM t1;
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
 
   OPEN cur1;
@@ -41,7 +39,7 @@ BEGIN
     FETCH cur1 INTO spa, spb;
     IF NOT done THEN
        START TRANSACTION;
-          INSERT INTO mysqltest1.t2 VALUES (spa,spb);
+          INSERT INTO t2 VALUES (spa,spb);
        COMMIT;
      END IF;
   UNTIL done END REPEAT;
@@ -49,30 +47,29 @@ BEGIN
   SET AUTOCOMMIT=1;
   CLOSE cur1;
 END|
-CREATE PROCEDURE mysqltest1.p2()
+CREATE PROCEDURE p2()
 BEGIN
-  INSERT INTO mysqltest1.t1 VALUES ('MySQL','1993-02-04'),('ROCKS', '1990-08-27'),('Texas', '1999-03-30'),('kyle','2005-1-1');
+  INSERT INTO t1 VALUES ('MySQL','1993-02-04'),('ROCKS', '1990-08-27'),('Texas', '1999-03-30'),('kyle','2005-1-1');
 END|
 delimiter ;|
 
-CALL mysqltest1.p2();
+CALL p2();
 sync_slave_with_master;
 
 connection master;
-CALL mysqltest1.p1();
+CALL p1();
 sync_slave_with_master;
 
 connection master;
 
---exec $MYSQL_DUMP --compact --order-by-primary --skip-extended-insert --no-create-info mysqltest1 > $MYSQLTEST_VARDIR/tmp/sp006_master.sql
---exec $MYSQL_DUMP_SLAVE --compact --order-by-primary --skip-extended-insert --no-create-info mysqltest1 > $MYSQLTEST_VARDIR/tmp/sp006_slave.sql
+--exec $MYSQL_DUMP --compact --order-by-primary --skip-extended-insert --no-create-info test > $MYSQLTEST_VARDIR/tmp/sp006_master.sql
+--exec $MYSQL_DUMP_SLAVE --compact --order-by-primary --skip-extended-insert --no-create-info test > $MYSQLTEST_VARDIR/tmp/sp006_slave.sql
 
 
-DROP PROCEDURE IF EXISTS mysqltest1.p1;
-DROP PROCEDURE IF EXISTS mysqltest1.p2;
-DROP TABLE IF EXISTS mysqltest1.t1;
-DROP TABLE IF EXISTS mysqltest1.t2;
-DROP DATABASE mysqltest1;
+DROP TABLE t1;
+DROP TABLE t2;
+DROP PROCEDURE p1;
+DROP PROCEDURE p2;
 
 # Lets compare. Note: If they match test will pass, if they do not match
 # the test will show that the diff statement failed and not reject file

=== modified file 'mysql-test/extra/rpl_tests/rpl_stm_000001.test'
--- a/mysql-test/extra/rpl_tests/rpl_stm_000001.test	2007-12-12 17:19:24 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_stm_000001.test	2009-10-20 18:00:07 +0000
@@ -93,7 +93,7 @@ kill @id;
 # We don't drop t3 as this is a temporary table
 drop table t2;
 connection master;
---error 1053,2013
+--error 1317,2013
 reap;
 connection slave;
 # The SQL slave thread should now have stopped because the query was killed on

=== modified file 'mysql-test/include/check-warnings.test'
--- a/mysql-test/include/check-warnings.test	2009-04-25 09:04:38 +0000
+++ b/mysql-test/include/check-warnings.test	2009-11-10 15:15:12 +0000
@@ -58,5 +58,5 @@ if (`select @result = 0`){
   skip OK;
 }
 --enable_query_log
-echo ^ Found warnings!!;
+echo ^ Found warnings in $log_error;
 exit;

=== modified file 'mysql-test/include/concurrent.inc'
--- a/mysql-test/include/concurrent.inc	2009-09-15 06:08:54 +0000
+++ b/mysql-test/include/concurrent.inc	2009-11-10 15:15:12 +0000
@@ -25,8 +25,6 @@
 #               new wrapper t/concurrent_innodb_safelog.test
 #
 
---source include/not_embedded.inc
-
 connection default;
 #
 # Show prerequisites for this test.

=== added file 'mysql-test/include/have_case_insensitive_fs.inc'
--- a/mysql-test/include/have_case_insensitive_fs.inc	1970-01-01 00:00:00 +0000
+++ b/mysql-test/include/have_case_insensitive_fs.inc	2009-10-27 08:09:19 +0000
@@ -0,0 +1,4 @@
+--require r/case_insensitive_fs.require
+--disable_query_log
+show variables like 'lower_case_file_system';
+--enable_query_log

=== added file 'mysql-test/include/have_debug_sync.inc'
--- a/mysql-test/include/have_debug_sync.inc	1970-01-01 00:00:00 +0000
+++ b/mysql-test/include/have_debug_sync.inc	2009-09-29 15:38:40 +0000
@@ -0,0 +1,5 @@
+--require r/have_debug_sync.require
+disable_query_log;
+let $value= query_get_value(SHOW VARIABLES LIKE 'debug_sync', Value, 1);
+eval SELECT ('$value' LIKE 'ON %') AS debug_sync;
+enable_query_log;

=== added file 'mysql-test/include/have_dynamic_loading.inc'
--- a/mysql-test/include/have_dynamic_loading.inc	1970-01-01 00:00:00 +0000
+++ b/mysql-test/include/have_dynamic_loading.inc	2009-09-04 20:02:17 +0000
@@ -0,0 +1,7 @@
+#
+# Whether server supports dynamic loading.
+#
+--require r/have_dynamic_loading.require
+disable_query_log;
+show variables like 'have_dynamic_loading';
+enable_query_log;

=== removed file 'mysql-test/include/have_dynamic_loading.inc'
--- a/mysql-test/include/have_dynamic_loading.inc	2009-05-22 17:53:25 +0000
+++ b/mysql-test/include/have_dynamic_loading.inc	1970-01-01 00:00:00 +0000
@@ -1,4 +0,0 @@
--- require r/have_dynamic_loading.require
-disable_query_log;
-show variables like 'have_dynamic_loading';
-enable_query_log;

=== modified file 'mysql-test/include/have_example_plugin.inc'
--- a/mysql-test/include/have_example_plugin.inc	2008-07-04 18:48:25 +0000
+++ b/mysql-test/include/have_example_plugin.inc	2009-09-04 20:02:17 +0000
@@ -2,10 +2,7 @@
 # Check if server has support for loading udf's
 # i.e it will support dlopen
 #
---require r/have_dynamic_loading.require
-disable_query_log;
-show variables like 'have_dynamic_loading';
-enable_query_log;
+--source include/have_dynamic_loading.inc
 
 #
 # Check if the variable EXAMPLE_PLUGIN is set

=== added file 'mysql-test/include/have_mysql_upgrade.inc'
--- a/mysql-test/include/have_mysql_upgrade.inc	1970-01-01 00:00:00 +0000
+++ b/mysql-test/include/have_mysql_upgrade.inc	2009-09-28 06:24:19 +0000
@@ -0,0 +1,4 @@
+--require r/have_mysql_upgrade.result
+--disable_query_log
+select LENGTH("$MYSQL_UPGRADE")>0 as have_mysql_upgrade;
+--enable_query_log

=== added file 'mysql-test/include/have_not_innodb_plugin.inc'
--- a/mysql-test/include/have_not_innodb_plugin.inc	1970-01-01 00:00:00 +0000
+++ b/mysql-test/include/have_not_innodb_plugin.inc	2009-09-25 09:26:49 +0000
@@ -0,0 +1,4 @@
+disable_query_log;
+--require r/not_true.require
+select (PLUGIN_LIBRARY LIKE 'ha_innodb_plugin%') as `TRUE` from information_schema.plugins where PLUGIN_NAME='InnoDB';
+enable_query_log;

=== modified file 'mysql-test/include/have_simple_parser.inc'
--- a/mysql-test/include/have_simple_parser.inc	2008-12-17 13:24:34 +0000
+++ b/mysql-test/include/have_simple_parser.inc	2009-09-04 20:02:17 +0000
@@ -2,10 +2,7 @@
 # Check if server has support for loading udf's
 # i.e it will support dlopen
 #
---require r/have_dynamic_loading.require
-disable_query_log;
-show variables like 'have_dynamic_loading';
-enable_query_log;
+--source include/have_dynamic_loading.inc
 
 #
 # Check if the variable SIMPLE_PARSER is set

=== modified file 'mysql-test/include/have_udf.inc'
--- a/mysql-test/include/have_udf.inc	2008-07-04 18:48:25 +0000
+++ b/mysql-test/include/have_udf.inc	2009-09-04 20:02:17 +0000
@@ -2,10 +2,7 @@
 # Check if server has support for loading udf's
 # i.e it will support dlopen
 #
---require r/have_dynamic_loading.require
-disable_query_log;
-show variables like 'have_dynamic_loading';
-enable_query_log;
+--source include/have_dynamic_loading.inc
 
 #
 # Check if the variable UDF_EXAMPLE_LIB is set

=== modified file 'mysql-test/include/mix1.inc'
--- a/mysql-test/include/mix1.inc	2009-09-15 06:08:54 +0000
+++ b/mysql-test/include/mix1.inc	2009-11-10 15:15:12 +0000
@@ -442,6 +442,8 @@ INSERT INTO t1(id, dept, age, name) VALU
 EXPLAIN SELECT DISTINCT t1.name, t1.dept FROM t1 WHERE t1.name='rs5';
 SELECT DISTINCT t1.name, t1.dept FROM t1 WHERE t1.name='rs5';
 DELETE FROM t1;
+--echo # Masking (#) number in "rows" column of the following EXPLAIN output, as it may vary (bug#47746).
+--replace_column 9 #
 EXPLAIN SELECT DISTINCT t1.name, t1.dept FROM t1 WHERE t1.name='rs5';
 SELECT DISTINCT t1.name, t1.dept FROM t1 WHERE t1.name='rs5';
 

=== modified file 'mysql-test/include/mtr_warnings.sql'
--- a/mysql-test/include/mtr_warnings.sql	2009-09-07 20:50:10 +0000
+++ b/mysql-test/include/mtr_warnings.sql	2009-11-10 15:15:12 +0000
@@ -132,7 +132,7 @@ INSERT INTO global_suppressions VALUES
 
  ("Error in Log_event::read_log_event\\\(\\\): 'Sanity check failed', data_len: 258, event_type: 49"),
 
- ("Statement is not safe to log in statement format"),
+ ("Statement may not be safe to log in statement format"),
 
  /* test case for Bug#bug29807 copies a stray frm into database */
  ("InnoDB: Error: table `test`.`bug29807` does not exist in the InnoDB internal"),
@@ -162,6 +162,8 @@ INSERT INTO global_suppressions VALUES
  ("Slave: Unknown column 'c7' in 't15' Error_code: 1054"),
  ("Slave: Can't DROP 'c7'.* 1091"),
  ("Slave: Key column 'c6'.* 1072"),
+ ("The slave I.O thread stops because a fatal error is encountered when it try to get the value of SERVER_ID variable from master."),
+ (".SELECT UNIX_TIMESTAMP... failed on master, do not trust column Seconds_Behind_Master of SHOW SLAVE STATUS"),
 
  /* Test case for Bug#31590 in order_by.test produces the following error */
  ("Out of sort memory; increase server sort buffer size"),
@@ -171,6 +173,7 @@ INSERT INTO global_suppressions VALUES
       this error message.
   */
  ("Can't find file: '.\\\\test\\\\\\?{8}.frm'"),
+ ("Slave: Unknown table 't1' Error_code: 1051"),
 
  /* maria-recovery.test has warning about missing log file */
  ("File '.*maria_log.000.*' not found \\(Errcode: 2\\)"),
@@ -217,7 +220,7 @@ BEGIN
     WHERE suspicious=1;
 
   IF @num_warnings > 0 THEN
-    SELECT file_name, line
+    SELECT line
         FROM error_log WHERE suspicious=1;
     --SELECT * FROM test_suppressions;
     -- Return 2 -> check failed

=== added file 'mysql-test/include/not_windows_embedded.inc'
--- a/mysql-test/include/not_windows_embedded.inc	1970-01-01 00:00:00 +0000
+++ b/mysql-test/include/not_windows_embedded.inc	2009-10-08 08:39:15 +0000
@@ -0,0 +1,11 @@
+let $is_win = `select convert(@@version_compile_os using latin1) IN ("Win32","Win64","Windows")`;
+let $is_embedded = `select version() like '%embedded%'`;
+#echo is_win: $is_win;
+#echo is_embedded: $is_embedded;
+if ($is_win)
+{
+  if ($is_embedded)
+  {
+    skip Not supported with embedded on windows;
+  }
+}

=== modified file 'mysql-test/lib/My/ConfigFactory.pm'
--- a/mysql-test/lib/My/ConfigFactory.pm	2009-10-07 22:57:43 +0000
+++ b/mysql-test/lib/My/ConfigFactory.pm	2009-11-10 15:15:12 +0000
@@ -7,6 +7,7 @@ use Carp;
 
 use My::Config;
 use My::Find;
+use My::Platform;
 
 use File::Basename;
 
@@ -207,8 +208,8 @@ my @mysqld_rules=
  { '#log-error' => \&fix_log_error },
  { 'general-log' => sub { return 1; } },
  { 'general-log-file' => \&fix_log },
- { 'slow-query-log-file' => \&fix_log_slow_queries },
  { 'slow-query-log' => sub { return 1; } },
+ { 'slow-query-log-file' => \&fix_log_slow_queries },
  { '#user' => sub { return shift->{ARGS}->{user} || ""; } },
  { '#password' => sub { return shift->{ARGS}->{password} || ""; } },
  { 'server-id' => \&fix_server_id, },
@@ -219,7 +220,13 @@ my @mysqld_rules=
  { 'ssl-key' => \&fix_ssl_server_key },
   );
 
-
+if (IS_WINDOWS)
+{
+  # For simplicity, we use the same names for shared memory and 
+  # named pipes.
+  push(@mysqld_rules, {'shared-memory-base-name' => \&fix_socket});
+}
+ 
 sub fix_ndb_mgmd_port {
   my ($self, $config, $group_name, $group)= @_;
   my $hostname= $group->value('HostName');
@@ -348,6 +355,16 @@ sub post_check_client_group {
     }
     $config->insert($client_group_name, $name_to, $option->value())
   }
+  
+  if (IS_WINDOWS)
+  {
+    # Shared memory base may or may not be defined (e.g not defined in embedded)
+    my $shm = $group_to_copy_from->option("shared-memory-base-name");
+    if (defined $shm)
+    {
+      $config->insert($client_group_name,"shared-memory-base-name", $shm->value());
+    }
+  }
 }
 
 
@@ -394,6 +411,7 @@ sub post_check_embedded_group {
     (
      '#log-error', # Embedded server writes stderr to mysqltest's log file
      'slave-net-timeout', # Embedded server are not build with replication
+     'shared-memory-base-name', # No shared memory for embedded
     );
 
   foreach my $option ( $mysqld->options(), $first_mysqld->options() ) {

=== modified file 'mysql-test/lib/My/Platform.pm'
--- a/mysql-test/lib/My/Platform.pm	2009-02-25 09:32:13 +0000
+++ b/mysql-test/lib/My/Platform.pm	2009-08-06 07:30:53 +0000
@@ -106,10 +106,13 @@ sub check_socket_path_length {
   my ($path)= @_;
 
   return 0 if IS_WINDOWS;
+  # This may not be true, but we can't test for it on AIX due to Perl bug
+  # See Bug #45771
+  return 0 if ($^O eq 'aix');
 
   require IO::Socket::UNIX;
 
-  my $truncated= 1; # Be negative
+  my $truncated= undef;
 
   # Create a tempfile name with same length as "path"
   my $tmpdir = tempdir( CLEANUP => 0);
@@ -122,6 +125,7 @@ sub check_socket_path_length {
        Local => $testfile,
        Listen => 1,
       );
+    $truncated= 1; # Be negatvie
 
     die "Could not create UNIX domain socket: $!"
       unless defined $sock;
@@ -133,6 +137,9 @@ sub check_socket_path_length {
 
   };
 
+  die "Unexpected failure when checking socket path length: $@"
+    if $@ and not defined $truncated;
+
   $sock= undef;  # Close socket
   rmtree($tmpdir); # Remove the tempdir and any socket file created
   return $truncated;

=== modified file 'mysql-test/lib/My/SafeProcess/safe_kill_win.cc'
--- a/mysql-test/lib/My/SafeProcess/safe_kill_win.cc	2008-10-08 20:02:32 +0000
+++ b/mysql-test/lib/My/SafeProcess/safe_kill_win.cc	2009-09-29 22:19:00 +0000
@@ -30,7 +30,7 @@ int main(int argc, const char** argv )
   DWORD pid= -1;
   HANDLE shutdown_event;
   char safe_process_name[32]= {0};
-  int retry_open_event= 100;
+  int retry_open_event= 2;
   /* Ignore any signals */
   signal(SIGINT,   SIG_IGN);
   signal(SIGBREAK, SIG_IGN);
@@ -51,15 +51,31 @@ int main(int argc, const char** argv )
   {
      /*
       Check if the process is alive, otherwise there is really
-      no idea to retry the open of the event
+      no sense to retry the open of the event
      */
     HANDLE process;
-    if ((process= OpenProcess(SYNCHRONIZE, FALSE, pid)) == NULL)
+    DWORD exit_code;
+    process= OpenProcess(SYNCHRONIZE| PROCESS_QUERY_INFORMATION, FALSE, pid);
+    if (!process)
     {
-      fprintf(stderr, "Could not open event or process %d, error: %d\n",
-            pid, GetLastError());
-      exit(3);
+      /* Already died */
+      exit(1);
+    }
+
+    if (!GetExitCodeProcess(process,&exit_code))
+    {
+       fprintf(stderr,  "GetExitCodeProcess failed, pid= %d, err= %d\n",
+         pid, GetLastError());
+       exit(1);
     }
+
+    if (exit_code != STILL_ACTIVE)
+    {
+       /* Already died */
+       CloseHandle(process);
+       exit(2);
+    }
+
     CloseHandle(process);
 
     if (retry_open_event--)

=== modified file 'mysql-test/lib/My/SafeProcess/safe_process_win.cc'
--- a/mysql-test/lib/My/SafeProcess/safe_process_win.cc	2009-09-17 22:46:10 +0000
+++ b/mysql-test/lib/My/SafeProcess/safe_process_win.cc	2009-11-10 15:15:12 +0000
@@ -50,9 +50,6 @@
            is killed.
 */
 
-/* Requires Windows 2000 or higher */
-#define _WIN32_WINNT 0x0500
-
 #include <windows.h>
 #include <stdio.h>
 #include <tlhelp32.h>
@@ -189,7 +186,14 @@ int main(int argc, const char** argv )
         die("No real args -> nothing to do");
       /* Copy the remaining args to child_arg */
       for (int j= i+1; j < argc; j++) {
-        to+= _snprintf(to, child_args + sizeof(child_args) - to, "%s ", argv[j]);
+	if (strchr (argv[j], ' ')) {
+	  /* Protect with "" if this arg contains a space */
+	  to+= _snprintf(to, child_args + sizeof(child_args) - to,
+                         "\"%s\" ", argv[j]);
+	} else {
+	  to+= _snprintf(to, child_args + sizeof(child_args) - to,
+	                 "%s ", argv[j]);
+	}
       }
       break;
     } else {

=== modified file 'mysql-test/lib/mtr_cases.pm'
--- a/mysql-test/lib/mtr_cases.pm	2009-11-06 17:24:38 +0000
+++ b/mysql-test/lib/mtr_cases.pm	2009-11-10 15:15:12 +0000
@@ -41,6 +41,7 @@ our $opt_with_ndbcluster_only;
 our $defaults_file;
 our $defaults_extra_file;
 our $reorder= 1;
+our $quick_collect;
 
 sub collect_option {
   my ($opt, $value)= @_;
@@ -68,6 +69,13 @@ require "mtr_misc.pl";
 my $do_test_reg;
 my $skip_test_reg;
 
+# Related to adding InnoDB plugin combinations
+my $lib_innodb_plugin;
+my $do_innodb_plugin;
+
+# If "Quick collect", set to 1 once a test to run has been found.
+my $some_test_found;
+
 sub init_pattern {
   my ($from, $what)= @_;
   return undef unless defined $from;
@@ -100,10 +108,23 @@ sub collect_test_cases ($$) {
   $do_test_reg= init_pattern($do_test, "--do-test");
   $skip_test_reg= init_pattern($skip_test, "--skip-test");
 
+  $lib_innodb_plugin=
+    my_find_file($::basedir,
+		 ["storage/innodb_plugin", "storage/innodb_plugin/.libs",
+		  "lib/mysql/plugin", "lib/mariadb/plugin", "lib/plugin"],
+		 ["ha_innodb_plugin.dll", "ha_innodb_plugin.so",
+		  "ha_innodb_plugin.sl"],
+		 NOT_REQUIRED);
+
+  $do_innodb_plugin= ($::mysql_version_id >= 50100 &&
+		      !(IS_WINDOWS && $::opt_embedded_server) &&
+		      $lib_innodb_plugin);
+
   foreach my $suite (split(",", $suites))
   {
     push(@$cases, collect_one_suite($suite, $opt_cases));
     $found_suites{$suite}= 1;
+    last if $some_test_found;
   }
 
   if ( @$opt_cases )
@@ -147,7 +168,7 @@ sub collect_test_cases ($$) {
     }
   }
 
-  if ( $reorder )
+  if ( $reorder && !$quick_collect)
   {
     # Reorder the test cases in an order that will make them faster to run
     my %sort_criteria;
@@ -398,7 +419,7 @@ sub collect_one_suite($)
   # Read combinations for this suite and build testcases x combinations
   # if any combinations exists
   # ----------------------------------------------------------------------
-  if ( ! $skip_combinations )
+  if ( ! $skip_combinations && ! $quick_collect )
   {
     my @combinations;
     my $combination_file= "$suitedir/combinations";
@@ -491,21 +512,16 @@ sub collect_one_suite($)
   # ----------------------------------------------------------------------
   # Testing InnoDB plugin.
   # ----------------------------------------------------------------------
-  my $lib_innodb_plugin=
-    mtr_file_exists(::vs_config_dirs('storage/innodb_plugin', 'ha_innodb_plugin.dll'),
-                    "$::basedir/storage/innodb_plugin/.libs/ha_innodb_plugin.so",
-                    "$::basedir/lib/mariadb/plugin/ha_innodb_plugin.so",
-                    "$::basedir/lib/mariadb/plugin/ha_innodb_plugin.dll",
-                    "$::basedir/lib/mysql/plugin/ha_innodb_plugin.so",
-                    "$::basedir/lib/mysql/plugin/ha_innodb_plugin.dll");
-  if ($::mysql_version_id >= 50100 && !(IS_WINDOWS && $::opt_embedded_server) &&
-      $lib_innodb_plugin)
+  if ($do_innodb_plugin)
   {
     my @new_cases;
+    my $sep= (IS_WINDOWS) ? ';' : ':';
 
     foreach my $test (@cases)
     {
-      next if ($test->{'skip'} || !$test->{'innodb_test'});
+      next if (!$test->{'innodb_test'});
+      # If skipped due to no builtin innodb, we can still run it with plugin
+      next if ($test->{'skip'} && $test->{comment} ne "No innodb support");
       # Exceptions
       next if ($test->{'name'} eq 'main.innodb'); # Failed with wrong errno (fk)
       next if ($test->{'name'} eq 'main.index_merge_innodb'); # Explain diff
@@ -515,6 +531,8 @@ sub collect_one_suite($)
       next if ($test->{'name'} eq 'sys_vars.innodb_lock_wait_timeout_basic');
       # Diff around innodb_thread_concurrency variable
       next if ($test->{'name'} eq 'sys_vars.innodb_thread_concurrency_basic');
+      # Can't work with InnoPlug. Test framework needs to be re-designed.
+      next if ($test->{'name'} eq 'main.innodb_bug46000');
       # Copy test options
       my $new_test= My::Test->new();
       while (my ($key, $value) = each(%$test))
@@ -525,23 +543,24 @@ sub collect_one_suite($)
         }
         else
         {
-          $new_test->{$key}= $value;
+          $new_test->{$key}= $value unless ($key eq 'skip');
         }
       }
       my $plugin_filename= basename($lib_innodb_plugin);
+      my $plugin_list= "innodb=$plugin_filename" . $sep . "innodb_locks=$plugin_filename";
       push(@{$new_test->{master_opt}}, '--ignore-builtin-innodb');
       push(@{$new_test->{master_opt}}, '--plugin-dir=' . dirname($lib_innodb_plugin));
-      push(@{$new_test->{master_opt}}, "--plugin_load=innodb=$plugin_filename;innodb_locks=$plugin_filename");
+      push(@{$new_test->{master_opt}}, "--plugin_load=$plugin_list");
       push(@{$new_test->{slave_opt}}, '--ignore-builtin-innodb');
       push(@{$new_test->{slave_opt}}, '--plugin-dir=' . dirname($lib_innodb_plugin));
-      push(@{$new_test->{slave_opt}}, "--plugin_load=innodb=$plugin_filename;innodb_locks=$plugin_filename");
+      push(@{$new_test->{slave_opt}}, "--plugin_load=$plugin_list");
       if ($new_test->{combination})
       {
-        $new_test->{combination}.= ' + InnoDB plugin';
+        $new_test->{combination}.= '+innodb_plugin';
       }
       else
       {
-        $new_test->{combination}= 'InnoDB plugin';
+        $new_test->{combination}= 'innodb_plugin';
       }
       push(@new_cases, $new_test);
     }
@@ -670,34 +689,10 @@ sub optimize_cases {
       }
     }
 
-      # =======================================================
-      # Check that engine selected by
-      # --default-storage-engine=<engine> is supported
-      # =======================================================
-      my %builtin_engines = ('myisam' => 1, 'memory' => 1);
-
-      foreach my $opt ( @{$tinfo->{master_opt}} ) {
-      my $default_engine=
-        mtr_match_prefix($opt, "--default-storage-engine=");
-
-      if (defined $default_engine){
-
-
-        my $engine_value= $::mysqld_variables{$default_engine};
-
-        if ( ! exists $::mysqld_variables{$default_engine} and
-             ! exists $builtin_engines{$default_engine} )
-        {
-          $tinfo->{'skip'}= 1;
-          $tinfo->{'comment'}=
-            "'$default_engine' not supported";
-        }
-
-        $tinfo->{'ndb_test'}= 1
-          if ( $default_engine =~ /^ndb/i );
-        $tinfo->{'innodb_test'}= 1
-          if ( $default_engine =~ /^innodb/i );
-      }
+    if ($quick_collect && ! $tinfo->{'skip'})
+    {
+      $some_test_found= 1;
+      return;
     }
   }
   @$cases= @new_cases;
@@ -1001,21 +996,24 @@ sub collect_one_test_case {
 
   if ($tinfo->{'federated_test'})
   {
-    # This is a test that need federated, enable it
+    # This is a test that needs federated, enable it
     push(@{$tinfo->{'master_opt'}}, "--loose-federated");
     push(@{$tinfo->{'slave_opt'}}, "--loose-federated");
   }
 
   if ( $tinfo->{'innodb_test'} )
   {
-    # This is a test that need innodb
+    # This is a test that needs innodb
     if ( $::mysqld_variables{'innodb'} eq "OFF" ||
          ! exists $::mysqld_variables{'innodb'} )
     {
       # innodb is not supported, skip it
       $tinfo->{'skip'}= 1;
+      # This comment is checked for running with innodb plugin (see above),
+      # please keep that in mind if changing the text.
       $tinfo->{'comment'}= "No innodb support";
-      return $tinfo;
+      # But continue processing if we may run it with innodb plugin
+      return $tinfo unless $do_innodb_plugin;
     }
   }
   else
@@ -1071,6 +1069,17 @@ sub collect_one_test_case {
     }
   }
 
+  if ( $tinfo->{'need_ssl'} )
+  {
+    # This is a test that needs ssl
+    if ( ! $::opt_ssl_supported ) {
+      # SSL is not supported, skip it
+      $tinfo->{'skip'}= 1;
+      $tinfo->{'comment'}= "No SSL support";
+      return $tinfo;
+    }
+  }
+
   # ----------------------------------------------------------------------
   # Find config file to use if not already selected in <testname>.opt file
   # ----------------------------------------------------------------------
@@ -1163,7 +1172,8 @@ my @tags=
  ["federated.inc", "federated_test", 1],
  ["include/not_embedded.inc", "not_embedded", 1],
  ["include/not_valgrind.inc", "not_valgrind", 1],
- ["include/have_example_plugin.inc", "example_plugin_test", 1]
+ ["include/have_example_plugin.inc", "example_plugin_test", 1],
+ ["include/have_ssl.inc", "need_ssl", 1],
 );
 
 

=== modified file 'mysql-test/lib/mtr_report.pm'
--- a/mysql-test/lib/mtr_report.pm	2009-09-07 20:50:10 +0000
+++ b/mysql-test/lib/mtr_report.pm	2009-11-10 15:15:12 +0000
@@ -134,8 +134,8 @@ sub mtr_report_test ($) {
           # an asterisk at the end, determine if the characters up to
           # but excluding the asterisk are the same
           if ( $exp ne "" && substr($exp, -1, 1) eq "*" ) {
-            $exp = substr($exp, 0, length($exp) - 1);
-            if ( substr($test_name, 0, length($exp)) ne $exp ) {
+            my $nexp = substr($exp, 0, length($exp) - 1);
+            if ( substr($test_name, 0, length($nexp)) ne $nexp ) {
               # no match, try next entry
               next;
             }
@@ -146,6 +146,7 @@ sub mtr_report_test ($) {
           }
         }
         $fail = "exp-fail";
+        $tinfo->{exp_fail}= 1;
         last;
       }
     }

=== added file 'mysql-test/lib/v1/incompatible.tests'
--- a/mysql-test/lib/v1/incompatible.tests	1970-01-01 00:00:00 +0000
+++ b/mysql-test/lib/v1/incompatible.tests	2009-07-16 12:05:46 +0000
@@ -0,0 +1,6 @@
+# This file lists tests that cannot run in MTR v1 for some reason.
+# They will be skipped.
+# Any text following white space after full test name is ignored
+# Only exact test names can be used, no regexp.
+
+main.fulltext_plugin   # Refers to $SIMPLE_PARSER_OPT which is not set

=== modified file 'mysql-test/lib/v1/mtr_cases.pl'
--- a/mysql-test/lib/v1/mtr_cases.pl	2008-11-14 14:39:12 +0000
+++ b/mysql-test/lib/v1/mtr_cases.pl	2009-07-31 09:22:57 +0000
@@ -32,6 +32,7 @@ sub mtr_options_from_test_file($$);
 
 my $do_test;
 my $skip_test;
+my %incompatible;
 
 sub init_pattern {
   my ($from, $what)= @_;
@@ -47,6 +48,15 @@ sub init_pattern {
 }
 
 
+sub collect_incomp_tests {
+  open (INCOMP, "lib/v1/incompatible.tests");
+  while (<INCOMP>)
+  {
+    next unless /^\w/;
+    s/\s.*\n//;		      # Ignore anything from first white space
+    $incompatible{$_}= 1;
+  }
+}
 
 ##############################################################################
 #
@@ -58,6 +68,8 @@ sub collect_test_cases ($) {
   $do_test= init_pattern($::opt_do_test, "--do-test");
   $skip_test= init_pattern($::opt_skip_test, "--skip-test");
 
+  collect_incomp_tests();
+
   my $suites= shift; # Semicolon separated list of test suites
   my $cases = [];    # Array of hash
 
@@ -528,6 +540,17 @@ sub collect_one_test_case($$$$$$$$$) {
   $tinfo->{'component_id'} = $component_id;
   push(@$cases, $tinfo);
 
+  # Remove "combinations" part of test name
+  my $test_base_name= $tinfo->{'name'};
+  $test_base_name=~ s/\s.*\n//;
+
+  if (exists ($incompatible{$test_base_name}))
+  {
+    $tinfo->{'skip'}= 1;
+    $tinfo->{'comment'}= "Test cannot run in mtr v1";
+    return;
+  }
+  
   # ----------------------------------------------------------------------
   # Skip some tests but include in list, just mark them to skip
   # ----------------------------------------------------------------------
@@ -841,7 +864,7 @@ sub collect_one_test_case($$$$$$$$$) {
     if ( $tinfo->{'innodb_test'} )
     {
       # This is a test that need innodb
-      if ( $::mysqld_variables{'innodb'} ne "TRUE" )
+      if ( $::mysqld_variables{'innodb'} eq "OFF" )
       {
 	# innodb is not supported, skip it
 	$tinfo->{'skip'}= 1;

=== modified file 'mysql-test/mysql-stress-test.pl'
--- a/mysql-test/mysql-stress-test.pl	2009-09-30 23:40:51 +0000
+++ b/mysql-test/mysql-stress-test.pl	2009-11-10 15:15:12 +0000
@@ -14,17 +14,16 @@
 # 
 # Design of stress script should allow one:
 # 
-#   - To stress test the mysqltest binary test engine.
-#   - To stress test the regular test suite and any additional test suites
-#     (such as mysql-test-extra-5.0).
-#   - To specify files with lists of tests both for initialization of
-#     stress db and for further testing itself.
-#   - To define the number of threads to be concurrently used in testing.
-#   - To define limitations for the test run. such as the number of tests or
-#     loops for execution or duration of testing, delay between test
-#     executions, and so forth.
-#   - To get a readable log file that can be used for identification of
-#     errors that occur during testing.
+#   - to use for stress testing mysqltest binary as test engine
+#   - to use for stress testing both regular test suite and any
+#     additional test suites (e.g. mysql-test-extra-5.0)
+#   - to specify files with lists of tests both for initialization of
+#     stress db and for further testing itself
+#   - to define number of threads that will be concurrently used in testing
+#   - to define limitations for test run. e.g. number of tests or loops
+#     for execution or duration of testing, delay between test executions, etc.
+#   - to get readable log file which can be used for identification of
+#     errors arose during testing
 # 
 # Basic scenarios:
 # 
@@ -58,6 +57,8 @@
 #       to reproduce and debug errors that was found in continued stress 
 #       testing
 #
+# 2009-01-28 OBN Additions and modifications per WL#4685
+#                
 ########################################################################
 
 use Config;
@@ -114,13 +115,15 @@ $opt_stress_mode="random";
 $opt_loop_count=0;
 $opt_test_count=0;
 $opt_test_duration=0;
-$opt_abort_on_error=0;
+# OBN: Changing abort-on-error default to -1 (for WL-4626/4685): -1 means no abort
+$opt_abort_on_error=-1;
 $opt_sleep_time = 0;
 $opt_threads=1;
 $pid_file="mysql_stress_test.pid";
 $opt_mysqltest= ($^O =~ /mswin32/i) ? "mysqltest.exe" : "mysqltest";
 $opt_check_tests_file="";
-@mysqltest_args=("--silent", "-v", "--skip-safemalloc");
+# OBM adding a setting for 'max-connect-retries=7' the default of 500 is to high  
+@mysqltest_args=("--silent", "-v", "--skip-safemalloc", "--max-connect-retries=7");
 
 # Client ip address
 $client_ip=inet_ntoa((gethostbyname(hostname()))[4]);
@@ -133,24 +136,31 @@ $client_ip=~ s/\.//g;
 #
 # S1 - Critical errors - cause immediately abort of testing. These errors
 #                        could be caused by server crash or impossibility
-#                        of test execution
+#                        of test execution. 
 #
 # S2 - Serious errors - these errors are bugs for sure as it knowns that 
 #                       they shouldn't appear during stress testing  
 #
-# S3 - Non-seriuos errros - these errors could be caused by fact that 
+# S3 - Unknown errors - Errors were returned but we don't know what they are 
+#                       so script can't determine if they are OK or not
+#
+# S4 - Non-seriuos errros - these errors could be caused by fact that 
 #                           we execute simultaneously statements that
 #                           affect tests executed by other threads
                             
 %error_strings = ( 'Failed in mysql_real_connect()' => S1,
+                   'Can\'t connect' => S1,       
                    'not found (Errcode: 2)' => S1 );
   
 %error_codes = ( 1012 => S2, 1015 => S2, 1021 => S2,
                  1027 => S2, 1037 => S2, 1038 => S2,
                  1039 => S2, 1040 => S2, 1046 => S2, 
-                 1180 => S2, 1181 => S2, 1203 => S2,
-                 1205 => S2, 1206 => S2, 1207 => S2, 
-                 1223 => S2, 2013 => S1);
+                 1053 => S2, 1180 => S2, 1181 => S2, 
+                 1203 => S2, 1205 => S4, 1206 => S2, 
+                 1207 => S2, 1213 => S4, 1223 => S2, 
+                 2002 => S1, 2003 => S1, 2006 => S1,
+                 2013 => S1 
+                 );
 
 share(%test_counters);
 %test_counters=( loop_count => 0, test_count=>0);
@@ -158,6 +168,35 @@ share(%test_counters);
 share($exiting);
 $exiting=0;
 
+# OBN Code and 'set_exit_code' function added by ES to set an exit code based on the error category returned 
+#     in combination with the --abort-on-error value see WL#4685)
+use constant ABORT_MAKEWEIGHT => 20;  
+share($gExitCode);
+$gExitCode = 0;   # global exit code
+sub set_exit_code {
+	my $severity = shift;
+	my $code = 0;
+	if ( $severity =~ /^S(\d+)/ ) {
+		$severity = $1;
+		$code = 11 - $severity; # S1=10, S2=9, ... -- as per WL
+	}
+	else {
+	# we know how we call the sub: severity should be S<num>; so, we should never be here...
+		print STDERR "Unknown severity format: $severity; setting to S1\n";
+		$severity = 1;
+	}
+	$abort = 0;
+	if ( $severity <= $opt_abort_on_error ) {
+		# the test finished with a failure severe enough to abort. We are adding the 'abort flag' to the exit code
+		$code += ABORT_MAKEWEIGHT;
+		# but are not exiting just yet -- we need to update global exit code first
+		$abort = 1;
+	}
+	lock $gExitCode; # we can use lock here because the script uses threads anyway
+	$gExitCode = $code if $code > $gExitCode;
+	kill INT, $$ if $abort; # this is just a way to call sig_INT_handler: it will set exiting flag, which should do the rest
+}
+
 share($test_counters_lock);
 $test_counters_lock=0;
 share($log_file_lock);
@@ -176,7 +215,8 @@ GetOptions("server-host=s", "server-logs
            "threads=s", "sleep-time=s", "loop-count=i", "test-count=i",
            "test-duration=i", "test-suffix=s", "check-tests-file", 
            "verbose", "log-error-details", "cleanup", "mysqltest=s", 
-           "abort-on-error", "help") || usage();
+           # OBN: (changing 'abort-on-error' to numberic for WL-4626/4685) 
+           "abort-on-error=i" => \$opt_abort_on_error, "help") || usage();
 
 usage() if ($opt_help);
 
@@ -563,7 +603,15 @@ EOF
 
   if ($opt_test_duration)
   {
-    sleep($opt_test_duration);
+  # OBN - At this point we need to wait for the duration of the test, hoever
+  #       we need to be able to quit if an 'abort-on-error' condition has happend 
+  #       with one of the children (WL#4685). Using solution by ES and replacing 
+  #       the 'sleep' command with a loop checking the abort condition every second
+  
+	foreach ( 1..$opt_test_duration ) {       
+		last if $exiting;                     
+		sleep 1;                              
+	}
     kill INT, $$;                             #Interrupt child threads
   }
 
@@ -580,6 +628,8 @@ EOF
   print "EXIT\n";
 }
 
+exit $gExitCode; # ES WL#4685: script should return a meaningful exit code
+
 sub test_init
 {
   my ($env)=@_;
@@ -681,7 +731,9 @@ sub test_execute
         {
           if (!exists($error_codes{$err_code}))
           {
-            $severity="S3";
+            # OBN Changing severity level to S4 from S3 as S3 now reserved
+            #     for the case where the error is unknown (for WL#4626/4685
+            $severity="S4";
             $err_code=0;
           }
           else
@@ -734,6 +786,7 @@ sub test_execute
     {
       push @{$env->{test_status}}, "Severity $severity: $total";
       $env->{errors}->{total}=+$total;
+      set_exit_code($severity);  
     }
   }
 
@@ -748,18 +801,20 @@ sub test_execute
 
   log_session_errors($env, $test_file);
 
-  if (!$exiting && ($signal_num == 2 || $signal_num == 15 || 
-      ($opt_abort_on_error && $env->{errors}->{S1} > 0)))
+  #OBN Removing the case of S1 and abort-on-error as that is now set 
+  #     inside the set_exit_code function (for WL#4626/4685)
+  #if (!$exiting && ($signal_num == 2 || $signal_num == 15 || 
+  #       ($opt_abort_on_error && $env->{errors}->{S1} > 0)))
+  if (!$exiting && ($signal_num == 2 || $signal_num == 15))
   {
-    #mysqltest was interrupted with INT or TERM signals or test was 
-    #ran with --abort-on-error option and we got errors with severity S1
+    #mysqltest was interrupted with INT or TERM signals 
     #so we assume that we should cancel testing and exit
     $exiting=1;
+    # OBN - Adjusted text to exclude case of S1 and abort-on-error that 
+    #       was mentioned (for WL#4626/4685)
     print STDERR<<EOF;
 WARNING:
-   mysqltest was interrupted with INT or TERM signals or test was 
-   ran with --abort-on-error option and we got errors with severity S1
-   (test cann't connect to the server or server crashed) so we assume that 
+   mysqltest was interrupted with INT or TERM signals  so we assume that 
    we should cancel testing and exit. Please check log file for this thread 
    in $stress_log_file or 
    inspect below output of the last test case executed with mysqltest to 
@@ -840,12 +895,23 @@ LOOP:
              $client_env{test_count}."]:".
              " TID ".$client_env{thread_id}.
              " test: '$test_name' ".
-             " Errors: ".join(" ",@{$client_env{test_status}}),"\n";
-      print "\n";
+             " Errors: ".join(" ",@{$client_env{test_status}}).
+                ( $exiting ? " (thread aborting)" : "" )."\n";
     }
   
-    sleep($opt_sleep_time) if($opt_sleep_time);
-
+    # OBN - At this point we need to wait until the 'wait' time between test
+    #       executions passes (in case it is specifed) passes, hoever we need
+    #       to be able to quit and break out of the test if an 'abort-on-error' 
+    #       condition has happend with one of the other children (WL#4685). 
+    #       Using solution by ES and replacing the 'sleep' command with a loop 
+    #       checking the abort condition every second
+  
+	if ( $opt_sleep_time ) {                
+		foreach ( 1..$opt_sleep_time ) {     
+			last if $exiting;               
+			sleep 1;                        
+		}                                   
+	}                                       
   }
 }
 
@@ -1119,6 +1185,9 @@ mysql-stress-test.pl --stress-basedir=<d
 --cleanup
   Force to clean up working directory (specified with --stress-basedir)
 
+--abort-on-error=<number>
+  Causes the script to abort if an error with severity <= number was encounterd
+
 --log-error-details
   Enable errors details in the global error log file. (Default: off)
 

=== modified file 'mysql-test/mysql-test-run.pl'
--- a/mysql-test/mysql-test-run.pl	2009-11-06 17:24:38 +0000
+++ b/mysql-test/mysql-test-run.pl	2009-11-10 15:15:12 +0000
@@ -150,7 +150,7 @@ our @opt_extra_mysqltest_opt;
 my $opt_compress;
 my $opt_ssl;
 my $opt_skip_ssl;
-my $opt_ssl_supported;
+our $opt_ssl_supported;
 my $opt_ps_protocol;
 my $opt_sp_protocol;
 my $opt_cursor_protocol;
@@ -216,6 +216,7 @@ sub check_timeout { return $opt_testcase
 
 my $opt_start;
 my $opt_start_dirty;
+my $start_only;
 my $opt_wait_all;
 my $opt_repeat= 1;
 my $opt_retry= 3;
@@ -339,7 +340,8 @@ sub main {
     for my $limit (2000, 1500, 1000, 500){
       $opt_parallel-- if ($sys_info->min_bogomips() < $limit);
     }
-    $opt_parallel= 8 if ($opt_parallel > 8);
+    my $max_par= $ENV{MTR_MAX_PARALLEL} || 8;
+    $opt_parallel= $max_par if ($opt_parallel > $max_par);
     $opt_parallel= $num_tests if ($opt_parallel > $num_tests);
     $opt_parallel= 1 if (IS_WINDOWS and $sys_info->isvm());
     $opt_parallel= 1 if ($opt_parallel < 1);
@@ -547,7 +549,8 @@ sub run_test_server ($$$) {
 	      }
 	    }
 	    $num_saved_datadir++;
-	    $num_failed_test++ unless $result->{retries};
+	    $num_failed_test++ unless ($result->{retries} ||
+                                       $result->{exp_fail});
 
             $test_failure= 1;
 	    if ( !$opt_force ) {
@@ -1052,6 +1055,9 @@ sub command_line_setup {
 
   if ( $opt_experimental )
   {
+    # $^O on Windows considered not generic enough
+    my $plat= (IS_WINDOWS) ? 'windows' : $^O;
+
     # read the list of experimental test cases from the file specified on
     # the command line
     open(FILE, "<", $opt_experimental) or mtr_error("Can't read experimental file: $opt_experimental");
@@ -1062,6 +1068,15 @@ sub command_line_setup {
       # remove comments (# foo) at the beginning of the line, or after a 
       # blank at the end of the line
       s/( +|^)#.*$//;
+      # If @ platform specifier given, use this entry only if it contains
+      # @<platform> or @!<xxx> where xxx != platform
+      if (/\@.*/)
+      {
+	next if (/\@!$plat/);
+	next unless (/\@$plat/ or /\@!/);
+	# Then remove @ and everything after it
+	s/\@.*$//;
+      }
       # remove whitespace
       s/^ +//;              
       s/ +$//;
@@ -1321,6 +1336,21 @@ sub command_line_setup {
     {
       mtr_error("Can't use --extern when using debugger");
     }
+    # Set one week timeout (check-testcase timeout will be 1/10th)
+    $opt_testcase_timeout= 7 * 24 * 60;
+    $opt_suite_timeout= 7 * 24 * 60;
+    # One day to shutdown
+    $opt_shutdown_timeout= 24 * 60;
+    # One day for PID file creation (this is given in seconds not minutes)
+    $opt_start_timeout= 24 * 60 * 60;
+  }
+
+  # --------------------------------------------------------------------------
+  # Modified behavior with --start options
+  # --------------------------------------------------------------------------
+  if ($opt_start or $opt_start_dirty) {
+    collect_option ('quick-collect', 1);
+    $start_only= 1;
   }
   if ($opt_debug)
   {
@@ -1334,7 +1364,7 @@ sub command_line_setup {
   # Check use of wait-all
   # --------------------------------------------------------------------------
 
-  if ($opt_wait_all && ! ($opt_start_dirty || $opt_start))
+  if ($opt_wait_all && ! $start_only)
   {
     mtr_error("--wait-all can only be used with --start or --start-dirty");
   }
@@ -1394,6 +1424,9 @@ sub command_line_setup {
     push(@valgrind_args, @default_valgrind_args)
       unless @valgrind_args;
 
+    # Make valgrind run in quiet mode so it only print errors
+    push(@valgrind_args, "--quiet" );
+
     mtr_report("Running valgrind with options \"",
 	       join(" ", @valgrind_args), "\"");
   }
@@ -1609,6 +1642,10 @@ sub collect_mysqld_features_from_running
     }
   }
 
+  # "Convert" innodb flag
+  $mysqld_variables{'innodb'}= "ON"
+    if ($mysqld_variables{'have_innodb'} eq "YES");
+
   # Parse version
   my $version_str= $mysqld_variables{'version'};
   if ( $version_str =~ /^([0-9]*)\.([0-9]*)\.([0-9]*)/ )
@@ -1909,11 +1946,11 @@ sub environment_setup {
   # --------------------------------------------------------------------------
   # Add the path where mysqld will find ha_example.so
   # --------------------------------------------------------------------------
-  if ($mysql_version_id >= 50100 && !(IS_WINDOWS && $opt_embedded_server)) {
+  if ($mysql_version_id >= 50100) {
     my $plugin_filename;
     if (IS_WINDOWS)
     {
-       $plugin_filename = "ha_example.dll"; 
+       $plugin_filename = "ha_example.dll";
     }
     else 
     {
@@ -1930,7 +1967,7 @@ sub environment_setup {
       ($lib_example_plugin ? dirname($lib_example_plugin) : "");
 
     $ENV{'HA_EXAMPLE_SO'}="'".$plugin_filename."'";
-    $ENV{'EXAMPLE_PLUGIN_LOAD'}="--plugin_load=;EXAMPLE=".$plugin_filename.";";
+    $ENV{'EXAMPLE_PLUGIN_LOAD'}="--plugin_load=EXAMPLE=".$plugin_filename;
   }
 
   # ----------------------------------------------------
@@ -3004,7 +3041,7 @@ sub run_testcase_check_skip_test($)
 
   if ( $tinfo->{'skip'} )
   {
-    mtr_report_test_skipped($tinfo);
+    mtr_report_test_skipped($tinfo) unless $start_only;
     return 1;
   }
 
@@ -3174,7 +3211,8 @@ test case was executed:\n";
       # Unknown process returned, most likley a crash, abort everything
       $tinfo->{comment}=
 	"The server $proc crashed while running ".
-	"'check testcase $mode test'";
+	"'check testcase $mode test'".
+	get_log_from_proc($proc, $tinfo->{name});
       $result= 3;
     }
 
@@ -3292,7 +3330,8 @@ sub run_on_all($$)
     else {
       # Unknown process returned, most likley a crash, abort everything
       $tinfo->{comment}.=
-	"The server $proc crashed while running '$run'";
+	"The server $proc crashed while running '$run'".
+	get_log_from_proc($proc, $tinfo->{name});
     }
 
     # Kill any check processes still running
@@ -3407,6 +3446,12 @@ sub run_testcase ($$) {
 
   mtr_verbose("Running test:", $tinfo->{name});
 
+  # Allow only alpanumerics pluss _ - + . in combination names
+  my $combination= $tinfo->{combination};
+  if ($combination && $combination !~ /^\w[-\w\.\+]+$/)
+  {
+    mtr_error("Combination '$combination' contains illegal characters");
+  }
   # -------------------------------------------------------
   # Init variables that can change between each test case
   # -------------------------------------------------------
@@ -3501,9 +3546,16 @@ sub run_testcase ($$) {
   # server exits
   # ----------------------------------------------------------------------
 
-  if ( $opt_start or $opt_start_dirty )
+  if ( $start_only )
   {
     mtr_print("\nStarted", started(all_servers()));
+    mtr_print("Using config for test", $tinfo->{name});
+    mtr_print("Port and socket path for server(s):");
+    foreach my $mysqld ( mysqlds() )
+    {
+      mtr_print ($mysqld->name() . "  " . $mysqld->value('port') .
+	      "  " . $mysqld->value('socket'));
+    }
     mtr_print("Waiting for server(s) to exit...");
     if ( $opt_wait_all ) {
       My::SafeProcess->wait_all();
@@ -3597,7 +3649,7 @@ sub run_testcase ($$) {
 	my $check_res;
 	if ( restart_forced_by_test() )
 	{
-	  stop_all_servers();
+	  stop_all_servers($opt_shutdown_timeout);
 	}
 	elsif ( $opt_check_testcases and
 	     $check_res= check_testcase($tinfo, "after"))
@@ -3614,7 +3666,7 @@ sub run_testcase ($$) {
               # test.
             } else {
               # Not checking warnings, so can do a hard shutdown.
-              stop_all_servers();
+	      stop_all_servers($opt_shutdown_timeout);
             }
 	    mtr_report("Resuming tests...\n");
 	  }
@@ -3696,7 +3748,8 @@ sub run_testcase ($$) {
     {
       # Server failed, probably crashed
       $tinfo->{comment}=
-	"Server $proc failed during test run";
+	"Server $proc failed during test run" .
+	get_log_from_proc($proc, $tinfo->{name});
 
       # ----------------------------------------------------
       # It's not mysqltest that has exited, kill it
@@ -3809,16 +3862,15 @@ sub pre_write_errorlog {
   }
 }
 
+# Extract server log from after the last occurrence of named test
+# Return as an array of lines
 #
-# Perform a rough examination of the servers
-# error log and write all lines that look
-# suspicious into $error_log.warnings
-#
-sub extract_warning_lines ($) {
-  my ($error_log) = @_;
+
+sub extract_server_log ($$) {
+  my ($error_log, $tname) = @_;
 
   # Open the servers .err log file and read all lines
-  # belonging to current tets into @lines
+  # belonging to current test into @lines
   my $Ferr = IO::File->new($error_log)
     or return [];
   my $last_pos= $last_warning_position->{$error_log}{seek_pos};
@@ -3849,8 +3901,37 @@ sub extract_warning_lines ($) {
       }
     }
   }
+  return @lines;
+}
+
+# Get log from server identified from its $proc object, from named test
+# Return as a single string
+#
+
+sub get_log_from_proc ($$) {
+  my ($proc, $name)= @_;
+  my $srv_log= "";
+
+  foreach my $mysqld (mysqlds()) {
+    if ($mysqld->{proc} eq $proc) {
+      my @srv_lines= extract_server_log($mysqld->value('#log-error'), $name);
+      $srv_log= "\nServer log from this test:\n" . join ("", @srv_lines);
+      last;
+    }
+  }
+  return $srv_log;
+}
 
-  # Write all suspicious lines to $error_log.warnings file
+# Perform a rough examination of the servers
+# error log and write all lines that look
+# suspicious into $error_log.warnings
+#
+sub extract_warning_lines ($$) {
+  my ($error_log, $tname) = @_;
+
+  my @lines= extract_server_log($error_log, $tname);
+
+# Write all suspicious lines to $error_log.warnings file
   my $warning_log = "$error_log.warnings";
   my $Fwarn = IO::File->new($warning_log, "w")
     or die("Could not open file '$warning_log' for writing: $!");
@@ -3858,16 +3939,9 @@ sub extract_warning_lines ($) {
 
   my @patterns =
     (
-     # The patterns for detection of [Warning] and [ERROR]
-     # in the server log files have been faulty for a longer period
-     # and correcting them shows a few additional harmless warnings.
-     # Thus those patterns are temporarily removed from the list
-     # of patterns. For more info see BUG#42408
-     # qr/^Warning:|mysqld: Warning|\[Warning\]/,
-     # qr/^Error:|\[ERROR\]/,
-     qr/^Warning:|mysqld: Warning/,
-     qr/^Error:/,
-     qr/^==.* at 0x/,
+     qr/^Warning:|mysqld: Warning|\[Warning\]/,
+     qr/^Error:|\[ERROR\]/,
+     qr/^==\d*==/, # valgrind errors
      qr/InnoDB: Warning|InnoDB: Error/,
      qr/^safe_mutex:|allocated at line/,
      qr/missing DBUG_RETURN/,
@@ -3933,7 +4007,7 @@ sub start_check_warnings ($$) {
   my $log_error= $mysqld->value('#log-error');
   # To be communicated to the test
   $ENV{MTR_LOG_ERROR}= $log_error;
-  extract_warning_lines($log_error);
+  extract_warning_lines($log_error, $tinfo->{name});
 
   my $args;
   mtr_init_args(\$args);
@@ -3980,7 +4054,7 @@ sub start_check_warnings ($$) {
 
 #
 # Loop through our list of processes and check the error log
-# for unexepcted errors and warnings
+# for unexpected errors and warnings
 #
 sub check_warnings ($) {
   my ($tinfo)= @_;
@@ -4067,7 +4141,8 @@ sub check_warnings ($) {
     else {
       # Unknown process returned, most likley a crash, abort everything
       $tinfo->{comment}=
-	"The server $proc crashed while running 'check warnings'";
+	"The server $proc crashed while running 'check warnings'".
+	get_log_from_proc($proc, $tinfo->{name});
       $result= 3;
     }
 
@@ -4083,13 +4158,15 @@ sub check_warnings ($) {
 }
 
 # Check for warnings generated during shutdown of a mysqld server.
-# If any, report them to master server, and return true; else just return false.
+# If any, report them to master server, and return true; else just return
+# false.
+
 sub check_warnings_post_shutdown {
   my ($server_socket)= @_;
   my $testname_hash= { };
   foreach my $mysqld ( mysqlds())
   {
-    my $testlist= extract_warning_lines($mysqld->value('#log-error'));
+    my $testlist= extract_warning_lines($mysqld->value('#log-error'), "");
     $testname_hash->{$_}= 1 for @$testlist;
   }
   my @warning_tests= keys(%$testname_hash);
@@ -4343,6 +4420,7 @@ sub mysqld_stop {
   mtr_init_args(\$args);
 
   mtr_add_arg($args, "--no-defaults");
+  mtr_add_arg($args, "--character-sets-dir=%s", $mysqld->value('character-sets-dir'));
   mtr_add_arg($args, "--user=%s", $opt_user);
   mtr_add_arg($args, "--password=");
   mtr_add_arg($args, "--port=%d", $mysqld->value('port'));
@@ -4392,7 +4470,7 @@ sub mysqld_arguments ($$$) {
 
   if (!using_extern() and $mysql_version_id >= 50106 )
   {
-    # Turn on logging to bothe tables and file
+    # Turn on logging to file and tables
     mtr_add_arg($args, "%s--log-output=table,file");
   }
 
@@ -4555,7 +4633,8 @@ sub mysqld_start ($$) {
 				 $opt_start_timeout,
 				 $mysqld->{'proc'}))
   {
-    mtr_error("Failed to start mysqld $mysqld->name()");
+    my $mname= $mysqld->name();
+    mtr_error("Failed to start mysqld $mname with command $exe");
   }
 
   # Remember options used when starting
@@ -4566,11 +4645,12 @@ sub mysqld_start ($$) {
 
 
 sub stop_all_servers () {
+  my $shutdown_timeout = $_[0] or 0;
 
   mtr_verbose("Stopping all servers...");
 
   # Kill all started servers
-  My::SafeProcess::shutdown(0, # shutdown timeout 0 => kill
+  My::SafeProcess::shutdown($shutdown_timeout,
 			    started(all_servers()));
 
   # Remove pidfiles
@@ -4940,7 +5020,8 @@ sub start_servers($) {
       my $logfile= $mysqld->value('#log-error');
       if ( defined $logfile and -f $logfile )
       {
-	$tinfo->{logfile}= mtr_fromfile($logfile);
+        my @srv_lines= extract_server_log($logfile, $tinfo->{name});
+	$tinfo->{logfile}= "Server log is:\n" . join ("", @srv_lines);
       }
       else
       {
@@ -5369,7 +5450,6 @@ sub valgrind_arguments {
   else
   {
     mtr_add_arg($args, "--tool=memcheck"); # From >= 2.1.2 needs this option
-    mtr_add_arg($args, "--alignment=8");
     mtr_add_arg($args, "--leak-check=yes");
     mtr_add_arg($args, "--num-callers=16");
     mtr_add_arg($args, "--suppressions=%s/valgrind.supp", $glob_mysql_test_dir)
@@ -5468,7 +5548,7 @@ Options to control what test suites or c
   staging-run           Run a limited number of tests (no slow tests). Used
                         for running staging trees with valgrind.
   enable-disabled       Run also tests marked as disabled
-  print_testcases       Don't run the tests but print details about all the
+  print-testcases       Don't run the tests but print details about all the
                         selected tests, in the order they would be run.
 
 Options that specify ports

=== modified file 'mysql-test/r/almost_full.result'
--- a/mysql-test/r/almost_full.result	2007-11-12 09:00:22 +0000
+++ b/mysql-test/r/almost_full.result	2009-08-25 13:56:50 +0000
@@ -1,3 +1,4 @@
+call mtr.add_suppression("The table 't1' is full");
 drop table if exists t1;
 set global myisam_data_pointer_size=2;
 CREATE TABLE t1 (a int auto_increment primary key not null, b longtext) ENGINE=MyISAM;

=== modified file 'mysql-test/r/alter_table.result'
--- a/mysql-test/r/alter_table.result	2009-10-28 07:52:34 +0000
+++ b/mysql-test/r/alter_table.result	2009-11-10 15:15:12 +0000
@@ -1175,4 +1175,74 @@ a
 42
 DROP TABLE t1;
 SET @@sql_mode=@save_sql_mode;
+#
+# Bug#45567: Fast ALTER TABLE broken for enum and set
+#
+DROP TABLE IF EXISTS t1;
+CREATE TABLE t1 (a ENUM('a1','a2'));
+INSERT INTO t1 VALUES ('a1'),('a2');
+# No copy: No modification
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2');
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+# No copy: Add new enumeration to the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','a3');
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+# Copy: Modify and add new to the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','xx','a5');
+affected rows: 2
+info: Records: 2  Duplicates: 0  Warnings: 0
+# Copy: Remove from the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','xx');
+affected rows: 2
+info: Records: 2  Duplicates: 0  Warnings: 0
+# Copy: Add new enumeration
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','a0','xx');
+affected rows: 2
+info: Records: 2  Duplicates: 0  Warnings: 0
+# No copy: Add new enumerations to the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','a0','xx','a5','a6');
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+DROP TABLE t1;
+CREATE TABLE t1 (a SET('a1','a2'));
+INSERT INTO t1 VALUES ('a1'),('a2');
+# No copy: No modification
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2');
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+# No copy: Add new to the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a3');
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+# Copy: Modify and add new to the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','xx','a5');
+affected rows: 2
+info: Records: 2  Duplicates: 0  Warnings: 0
+# Copy: Remove from the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','xx');
+affected rows: 2
+info: Records: 2  Duplicates: 0  Warnings: 0
+# Copy: Add new member
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a0','xx');
+affected rows: 2
+info: Records: 2  Duplicates: 0  Warnings: 0
+# No copy: Add new to the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a0','xx','a5','a6');
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+# Copy: Numerical incrase (pack lenght)
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a0','xx','a5','a6','a7','a8','a9','a10');
+affected rows: 2
+info: Records: 2  Duplicates: 0  Warnings: 0
+DROP TABLE t1;
+CREATE TABLE t1 (f1 TIMESTAMP NULL DEFAULT NULL,
+f2 INT(11) DEFAULT NULL) ENGINE=MYISAM DEFAULT CHARSET=utf8;
+INSERT INTO t1 VALUES (NULL, NULL), ("2009-10-09 11:46:19", 2);
+this should affect no rows as there is no real change
+ALTER TABLE t1 CHANGE COLUMN f1 f1_no_real_change TIMESTAMP NULL DEFAULT NULL;
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+DROP TABLE t1;
 End of 5.1 tests

=== modified file 'mysql-test/r/analyse.result'
--- a/mysql-test/r/analyse.result	2009-08-27 10:59:25 +0000
+++ b/mysql-test/r/analyse.result	2009-10-30 09:56:32 +0000
@@ -19,81 +19,10 @@ test.t1.empty_string			0	0	4	0	0.0000	NU
 test.t1.bool	N	Y	1	1	0	0	1.0000	NULL	ENUM('N','Y') NOT NULL
 test.t1.d	2002-03-03	2002-03-05	10	10	0	0	10.0000	NULL	ENUM('2002-03-03','2002-03-04','2002-03-05') NOT NULL
 create table t2 select * from t1 procedure analyse();
-select * from t2;
-Field_name	Min_value	Max_value	Min_length	Max_length	Empties_or_zeros	Nulls	Avg_value_or_avg_length	Std	Optimal_fieldtype
-test.t1.i	1	7	1	1	0	0	4.0000	2.2361	ENUM('1','3','5','7') NOT NULL
-test.t1.j	2	8	1	1	0	0	5.0000	2.2361	ENUM('2','4','6','8') NOT NULL
-test.t1.empty_string			0	0	4	0	0.0000	NULL	CHAR(0) NOT NULL
-test.t1.bool	N	Y	1	1	0	0	1.0000	NULL	ENUM('N','Y') NOT NULL
-test.t1.d	2002-03-03	2002-03-05	10	10	0	0	10.0000	NULL	ENUM('2002-03-03','2002-03-04','2002-03-05') NOT NULL
-drop table t1,t2;
+ERROR HY000: Incorrect usage of PROCEDURE and non-SELECT
+drop table t1;
 EXPLAIN SELECT 1 FROM (SELECT 1) a PROCEDURE ANALYSE();
 ERROR HY000: Incorrect usage of PROCEDURE and subquery
-create table t1 (a int not null);
-create table t2 select * from t1 where 0=1 procedure analyse();
-show create table t2;
-Table	Create Table
-t2	CREATE TABLE `t2` (
-  `Field_name` varbinary(255) NOT NULL DEFAULT '',
-  `Min_value` varbinary(255) DEFAULT NULL,
-  `Max_value` varbinary(255) DEFAULT NULL,
-  `Min_length` bigint(11) NOT NULL DEFAULT '0',
-  `Max_length` bigint(11) NOT NULL DEFAULT '0',
-  `Empties_or_zeros` bigint(11) NOT NULL DEFAULT '0',
-  `Nulls` bigint(11) NOT NULL DEFAULT '0',
-  `Avg_value_or_avg_length` varbinary(255) NOT NULL DEFAULT '',
-  `Std` varbinary(255) DEFAULT NULL,
-  `Optimal_fieldtype` varbinary(64) NOT NULL DEFAULT ''
-) ENGINE=MyISAM DEFAULT CHARSET=latin1
-select * from t1 where 0=1 procedure analyse();
-Field_name	Min_value	Max_value	Min_length	Max_length	Empties_or_zeros	Nulls	Avg_value_or_avg_length	Std	Optimal_fieldtype
-insert into t1 values(1);
-drop table t2;
-create table t2 select * from t1 where 0=1 procedure analyse();
-show create table t2;
-Table	Create Table
-t2	CREATE TABLE `t2` (
-  `Field_name` varbinary(255) NOT NULL DEFAULT '',
-  `Min_value` varbinary(255) DEFAULT NULL,
-  `Max_value` varbinary(255) DEFAULT NULL,
-  `Min_length` bigint(11) NOT NULL DEFAULT '0',
-  `Max_length` bigint(11) NOT NULL DEFAULT '0',
-  `Empties_or_zeros` bigint(11) NOT NULL DEFAULT '0',
-  `Nulls` bigint(11) NOT NULL DEFAULT '0',
-  `Avg_value_or_avg_length` varbinary(255) NOT NULL DEFAULT '',
-  `Std` varbinary(255) DEFAULT NULL,
-  `Optimal_fieldtype` varbinary(64) NOT NULL DEFAULT ''
-) ENGINE=MyISAM DEFAULT CHARSET=latin1
-select * from t2;
-Field_name	Min_value	Max_value	Min_length	Max_length	Empties_or_zeros	Nulls	Avg_value_or_avg_length	Std	Optimal_fieldtype
-insert into t2 select * from t1 procedure analyse();
-select * from t2;
-Field_name	Min_value	Max_value	Min_length	Max_length	Empties_or_zeros	Nulls	Avg_value_or_avg_length	Std	Optimal_fieldtype
-test.t1.a	1	1	1	1	0	0	1.0000	0.0000	ENUM('1') NOT NULL
-insert into t1 values(2);
-drop table t2;
-create table t2 select * from t1 where 0=1 procedure analyse();
-show create table t2;
-Table	Create Table
-t2	CREATE TABLE `t2` (
-  `Field_name` varbinary(255) NOT NULL DEFAULT '',
-  `Min_value` varbinary(255) DEFAULT NULL,
-  `Max_value` varbinary(255) DEFAULT NULL,
-  `Min_length` bigint(11) NOT NULL DEFAULT '0',
-  `Max_length` bigint(11) NOT NULL DEFAULT '0',
-  `Empties_or_zeros` bigint(11) NOT NULL DEFAULT '0',
-  `Nulls` bigint(11) NOT NULL DEFAULT '0',
-  `Avg_value_or_avg_length` varbinary(255) NOT NULL DEFAULT '',
-  `Std` varbinary(255) DEFAULT NULL,
-  `Optimal_fieldtype` varbinary(64) NOT NULL DEFAULT ''
-) ENGINE=MyISAM DEFAULT CHARSET=latin1
-select * from t2;
-Field_name	Min_value	Max_value	Min_length	Max_length	Empties_or_zeros	Nulls	Avg_value_or_avg_length	Std	Optimal_fieldtype
-insert into t2 select * from t1 procedure analyse();
-select * from t2;
-Field_name	Min_value	Max_value	Min_length	Max_length	Empties_or_zeros	Nulls	Avg_value_or_avg_length	Std	Optimal_fieldtype
-test.t1.a	1	2	1	1	0	0	1.5000	0.5000	ENUM('1','2') NOT NULL
-drop table t1,t2;
 create table t1 (v varchar(128));
 insert into t1 values ('abc'),('abc\'def\\hij\"klm\0opq'),('\''),('\"'),('\\'),('a\0'),('b\''),('c\"'),('d\\'),('\'b'),('\"c'),('\\d'),('a\0\0\0b'),('a\'\'\'\'b'),('a\"\"\"\"b'),('a\\\\\\\\b'),('\'\0\\\"'),('\'\''),('\"\"'),('\\\\'),('The\ZEnd');
 select * from t1 procedure analyse();
@@ -157,3 +86,40 @@ SELECT * FROM (SELECT * FROM t1) d PROCE
 ERROR HY000: Incorrect usage of PROCEDURE and subquery
 DROP TABLE t1;
 End of 4.1 tests
+#
+# Bug #48293: crash with procedure analyse, view with > 10 columns, 
+#  having clause...
+#
+CREATE TABLE t1(a INT, b INT, c INT, d INT, e INT,
+f INT, g INT, h INT, i INT, j INT,k INT);
+INSERT INTO t1 VALUES (),();
+CREATE ALGORITHM=TEMPTABLE VIEW v1 AS SELECT * FROM t1;
+#should have a derived table
+EXPLAIN SELECT * FROM v1;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	PRIMARY	<derived2>	ALL	NULL	NULL	NULL	NULL	2	
+2	DERIVED	t1	ALL	NULL	NULL	NULL	NULL	2	
+#should not crash
+SELECT * FROM v1 PROCEDURE analyse();
+ERROR HY000: Incorrect usage of PROCEDURE and view
+#should not crash
+SELECT * FROM t1 a, v1, t1 b PROCEDURE analyse();
+ERROR HY000: Incorrect usage of PROCEDURE and view
+#should not crash
+SELECT * FROM (SELECT * FROM t1 having a > 1) x PROCEDURE analyse();
+ERROR HY000: Incorrect usage of PROCEDURE and subquery
+#should not crash
+SELECT * FROM t1 a, (SELECT * FROM t1 having a > 1) x, t1 b PROCEDURE analyse();
+ERROR HY000: Incorrect usage of PROCEDURE and subquery
+#should not crash
+SELECT 1 FROM t1 group by a having a > 1 order by 1 PROCEDURE analyse();
+ERROR HY000: Can't use ORDER clause with this procedure
+DROP VIEW v1;
+DROP TABLE t1;
+CREATE TABLE t1(a INT);
+INSERT INTO t1 VALUES (1),(2);
+# should not crash
+CREATE TABLE t2 SELECT 1 FROM t1, t1 t3 GROUP BY t3.a PROCEDURE ANALYSE();
+ERROR HY000: Incorrect usage of PROCEDURE and non-SELECT
+DROP TABLE t1;
+End of 5.0 tests

=== modified file 'mysql-test/r/archive.result'
--- a/mysql-test/r/archive.result	2009-03-26 14:27:34 +0000
+++ b/mysql-test/r/archive.result	2009-09-10 06:58:13 +0000
@@ -12695,3 +12695,25 @@ a	b
 1	NULL
 2	NULL
 DROP TABLE t1;
+CREATE TABLE t1(a INT, b BLOB) ENGINE=archive;
+SELECT DATA_LENGTH, AVG_ROW_LENGTH FROM
+INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='t1' AND TABLE_SCHEMA='test';
+DATA_LENGTH	AVG_ROW_LENGTH
+8666	15
+INSERT INTO t1 VALUES(1, 'sampleblob1'),(2, 'sampleblob2');
+SELECT DATA_LENGTH, AVG_ROW_LENGTH FROM
+INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='t1' AND TABLE_SCHEMA='test';
+DATA_LENGTH	AVG_ROW_LENGTH
+8700	4350
+DROP TABLE t1;
+SET @save_join_buffer_size= @@join_buffer_size;
+SET @@join_buffer_size= 8228;
+CREATE TABLE t1(a CHAR(255)) ENGINE=archive;
+INSERT INTO t1 VALUES('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'),
+('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'),
+('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
+SELECT COUNT(t1.a) FROM t1, t1 a, t1 b, t1 c, t1 d, t1 e;
+COUNT(t1.a)
+729
+DROP TABLE t1;
+SET @@join_buffer_size= @save_join_buffer_size;

=== modified file 'mysql-test/r/bug46080.result'
--- a/mysql-test/r/bug46080.result	2009-07-13 11:17:14 +0000
+++ b/mysql-test/r/bug46080.result	2009-09-03 06:38:06 +0000
@@ -2,6 +2,8 @@
 # Bug #46080: group_concat(... order by) crashes server when
 #  sort_buffer_size cannot allocate
 #
+call mtr.add_suppression("Out of memory at line .*, 'my_alloc.c'");
+call mtr.add_suppression("needed .* byte .*k., memory in use: .* bytes .*k");
 CREATE TABLE t1(a CHAR(255));
 INSERT INTO t1 VALUES ('a');
 SET @@SESSION.sort_buffer_size=5*16*1000000;

=== added file 'mysql-test/r/bug46760.result'
--- a/mysql-test/r/bug46760.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/bug46760.result	2009-09-18 13:01:18 +0000
@@ -0,0 +1,43 @@
+#
+# Bug#46760: Fast ALTER TABLE no longer works for InnoDB
+#
+CREATE TABLE t1 (a INT) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1);
+# By using --enable_info and verifying that number of affected
+# rows is 0 we check that this ALTER TABLE is really carried
+# out as "fast/online" operation, i.e. without full-blown data
+# copying.
+#
+# I.e. info for the below statement should normally look like:
+#
+# affected rows: 0
+# info: Records: 0  Duplicates: 0  Warnings: 0
+ALTER TABLE t1 ALTER COLUMN a SET DEFAULT 10;
+affected rows: 0
+info: Records: 0  Duplicates: 0  Warnings: 0
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `a` int(11) DEFAULT '10'
+) ENGINE=InnoDB DEFAULT CHARSET=latin1
+DROP TABLE t1;
+#
+# MySQL Bug#39200: optimize table does not recognize 
+# ROW_FORMAT=COMPRESSED
+#
+CREATE TABLE t1 (a INT) ROW_FORMAT=compressed;
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `a` int(11) DEFAULT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=COMPRESSED
+OPTIMIZE TABLE t1;
+Table	Op	Msg_type	Msg_text
+test.t1	optimize	status	Table is already up to date
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `a` int(11) DEFAULT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=COMPRESSED
+DROP TABLE t1;
+End of 5.1 tests

=== added file 'mysql-test/r/case_insensitive_fs.require'
--- a/mysql-test/r/case_insensitive_fs.require	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/case_insensitive_fs.require	2009-10-27 08:09:19 +0000
@@ -0,0 +1,2 @@
+Variable_name	Value
+lower_case_file_system	ON

=== modified file 'mysql-test/r/create.result'
--- a/mysql-test/r/create.result	2009-09-23 11:03:47 +0000
+++ b/mysql-test/r/create.result	2009-11-10 15:15:12 +0000
@@ -1588,6 +1588,19 @@ CREATE TABLE IF NOT EXISTS t2 (a INTEGER
 SELECT a FROM t1;
 ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
 DROP TABLE t1, t2;
+#
+# BUG#46384 - mysqld segfault when trying to create table with same 
+#             name as existing view
+#
+CREATE TABLE t1 (a INT);
+CREATE TABLE t2 (a INT);
+INSERT INTO t1 VALUES (1),(2),(3);
+INSERT INTO t2 VALUES (1),(2),(3);
+CREATE VIEW v1 AS SELECT t1.a FROM t1, t2;
+CREATE TABLE v1 AS SELECT * FROM t1;
+ERROR 42S01: Table 'v1' already exists
+DROP VIEW v1;
+DROP TABLE t1,t2;
 End of 5.0 tests
 CREATE TABLE t1 (a int, b int);
 insert into t1 values (1,1),(1,2);

=== modified file 'mysql-test/r/ctype_ldml.result'
--- a/mysql-test/r/ctype_ldml.result	2009-06-04 09:35:29 +0000
+++ b/mysql-test/r/ctype_ldml.result	2009-10-19 13:23:53 +0000
@@ -41,6 +41,14 @@ efgh	efgh
 ijkl	ijkl
 DROP TABLE t1;
 #
+# Bug#45645 Mysql server close all connection and restart using lower function
+#
+CREATE TABLE t1 (a VARCHAR(10)) CHARACTER SET utf8 COLLATE utf8_test_ci;
+INSERT INTO t1 (a) VALUES ('hello!');
+SELECT * FROM t1 WHERE LOWER(a)=LOWER('N');
+a
+DROP TABLE t1;
+#
 # Bug#43827 Server closes connections and restarts
 #
 CREATE TABLE t1 (c1 VARCHAR(10) CHARACTER SET utf8 COLLATE utf8_test_ci);
@@ -321,3 +329,11 @@ Vv
 Xx
 Yy����������������������������
 drop table t1;
+Bug#46448 trailing spaces are not ignored when user collation maps space != 0x20
+set names latin1;
+show collation like 'latin1_test';
+Collation	Charset	Id	Default	Compiled	Sortlen
+latin1_test	latin1	99		Yes	1
+select "foo" = "foo " collate latin1_test;
+"foo" = "foo " collate latin1_test
+1

=== added file 'mysql-test/r/debug_sync.result'
--- a/mysql-test/r/debug_sync.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/debug_sync.result	2009-09-29 15:38:40 +0000
@@ -0,0 +1,277 @@
+SET DEBUG_SYNC= 'RESET';
+DROP TABLE IF EXISTS t1;
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: ''
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6           HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2           EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2           EXECUTE 2';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2                     HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2';
+SET DEBUG_SYNC='p0 SIGNAL s1                       EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1                       EXECUTE 2';
+SET DEBUG_SYNC='p0 SIGNAL s1                                 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6 EXECUTE 2';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6           HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6';
+SET DEBUG_SYNC='p0           WAIT_FOR s2           EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2           EXECUTE 2';
+SET DEBUG_SYNC='p0           WAIT_FOR s2                     HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2';
+SET DEBUG_SYNC='p0                                           HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 CLEAR';
+SET DEBUG_SYNC='p0 TEST';
+SET DEBUG_SYNC='RESET';
+set debug_sync='p0 signal s1 wait_for s2 timeout 6 execute 2 hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2 timeout 6 execute 2';
+set debug_sync='p0 signal s1 wait_for s2 timeout 6           hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2 timeout 6';
+set debug_sync='p0 signal s1 wait_for s2           execute 2 hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2           execute 2';
+set debug_sync='p0 signal s1 wait_for s2                     hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2';
+set debug_sync='p0 signal s1                       execute 2 hit_limit 3';
+set debug_sync='p0 signal s1                       execute 2';
+set debug_sync='p0 signal s1                                 hit_limit 3';
+set debug_sync='p0 signal s1';
+set debug_sync='p0           wait_for s2 timeout 6 execute 2 hit_limit 3';
+set debug_sync='p0           wait_for s2 timeout 6 execute 2';
+set debug_sync='p0           wait_for s2 timeout 6           hit_limit 3';
+set debug_sync='p0           wait_for s2 timeout 6';
+set debug_sync='p0           wait_for s2           execute 2 hit_limit 3';
+set debug_sync='p0           wait_for s2           execute 2';
+set debug_sync='p0           wait_for s2                     hit_limit 3';
+set debug_sync='p0           wait_for s2';
+set debug_sync='p0                                           hit_limit 3';
+set debug_sync='p0 clear';
+set debug_sync='p0 test';
+set debug_sync='reset';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6
+                EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='   p0 SIGNAL s1 WAIT_FOR s2';
+SET DEBUG_SYNC='p0    SIGNAL    s1    WAIT_FOR    s2';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2   ';
+SET DEBUG_SYNC='   p0 SIGNAL s1 WAIT_FOR s2   ';
+SET DEBUG_SYNC='   p0    SIGNAL    s1    WAIT_FOR    s2   ';
+SET DEBUG_SYNC='';
+ERROR 42000: Missing synchronization point name
+SET DEBUG_SYNC=' ';
+ERROR 42000: Missing synchronization point name
+SET DEBUG_SYNC='p0';
+ERROR 42000: Missing action after synchronization point name 'p0'
+SET DEBUG_SYNC='p0                                          EXECUTE 2';
+ERROR 42000: Missing action before EXECUTE
+SET DEBUG_SYNC='p0                                TIMEOUT 6 EXECUTE 2';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUT'
+SET DEBUG_SYNC='p0                                TIMEOUT 6';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUT'
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1';
+ERROR 42000: Illegal or out of order stuff: 'SIGNAL'
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1           EXECUTE 2';
+ERROR 42000: Illegal or out of order stuff: 'SIGNAL'
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1 TIMEOUT 6 EXECUTE 2';
+ERROR 42000: Illegal or out of order stuff: 'SIGNAL'
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1 TIMEOUT 6';
+ERROR 42000: Illegal or out of order stuff: 'SIGNAL'
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 6 SIGNAL s1 EXECUTE 2';
+ERROR 42000: Illegal or out of order stuff: 'SIGNAL'
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 6 SIGNAL s1';
+ERROR 42000: Illegal or out of order stuff: 'SIGNAL'
+SET DEBUG_SYNC='p0 TIMEOUT 6 WAIT_FOR s2 EXECUTE 2';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUT'
+SET DEBUG_SYNC='p0 TIMEOUT 6 WAIT_FOR s2';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUT'
+SET DEBUG_SYNC='p0                  SIGNAL s1 TIMEOUT 6 EXECUTE 2';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUT'
+SET DEBUG_SYNC='p0                  SIGNAL s1 TIMEOUT 6';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUT'
+SET DEBUG_SYNC='p0 EXECUTE 2 SIGNAL s1 TIMEOUT 6';
+ERROR 42000: Missing action before EXECUTE
+SET DEBUG_SYNC='p0 TIMEOUT 6 SIGNAL s1';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUT'
+SET DEBUG_SYNC='p0 EXECUTE 2 TIMEOUT 6 SIGNAL s1';
+ERROR 42000: Missing action before EXECUTE
+SET DEBUG_SYNC='p0 CLEAR HIT_LIMIT 3';
+ERROR 42000: Nothing must follow action CLEAR
+SET DEBUG_SYNC='CLEAR';
+ERROR 42000: Missing action after synchronization point name 'CLEAR'
+SET DEBUG_SYNC='p0 CLEAR p0';
+ERROR 42000: Nothing must follow action CLEAR
+SET DEBUG_SYNC='TEST';
+ERROR 42000: Missing action after synchronization point name 'TEST'
+SET DEBUG_SYNC='p0 TEST p0';
+ERROR 42000: Nothing must follow action TEST
+SET DEBUG_SYNC='p0 RESET';
+ERROR 42000: Illegal or out of order stuff: 'RESET'
+SET DEBUG_SYNC='RESET p0';
+ERROR 42000: Illegal or out of order stuff: 'p0'
+SET DEBUG_SYNC='p0 RESET p0';
+ERROR 42000: Illegal or out of order stuff: 'RESET'
+SET DEBUG_SYNC='p0 SIGNAL ';
+ERROR 42000: Missing signal name after action SIGNAL
+SET DEBUG_SYNC='p0 WAIT_FOR ';
+ERROR 42000: Missing signal name after action WAIT_FOR
+SET DEBUG_SYNC='p0 SIGNAL s1 EXECUTE ';
+ERROR 42000: Missing valid number after EXECUTE
+SET DEBUG_SYNCx='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+ERROR HY000: Unknown system variable 'DEBUG_SYNCx'
+SET DEBUG_SYNC='p0 SIGNAx s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+ERROR 42000: Illegal or out of order stuff: 'SIGNAx'
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOx s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+ERROR 42000: Illegal or out of order stuff: 'WAIT_FOx'
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUx 0 EXECUTE 2 HIT_LIMIT 3';
+ERROR 42000: Illegal or out of order stuff: 'TIMEOUx'
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTx 2 HIT_LIMIT 3';
+ERROR 42000: Illegal or out of order stuff: 'EXECUTx'
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIx 3';
+ERROR 42000: Illegal or out of order stuff: 'HIT_LIMIx'
+SET DEBUG_SYNC='p0 CLEARx';
+ERROR 42000: Illegal or out of order stuff: 'CLEARx'
+SET DEBUG_SYNC='p0 TESTx';
+ERROR 42000: Illegal or out of order stuff: 'TESTx'
+SET DEBUG_SYNC='RESETx';
+ERROR 42000: Missing action after synchronization point name 'RESETx'
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 0x6 EXECUTE 2 HIT_LIMIT 3';
+ERROR 42000: Missing valid number after TIMEOUT
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 6 EXECUTE 0x2 HIT_LIMIT 3';
+ERROR 42000: Missing valid number after EXECUTE
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 7 EXECUTE 2 HIT_LIMIT 0x3';
+ERROR 42000: Missing valid number after HIT_LIMIT
+SET DEBUG_SYNC= 7;
+ERROR 42000: Incorrect argument type to variable 'debug_sync'
+SET GLOBAL DEBUG_SYNC= 'p0 CLEAR';
+ERROR HY000: Variable 'debug_sync' is a SESSION variable and can't be used with SET GLOBAL
+SET @myvar= 'now SIGNAL from_myvar';
+SET DEBUG_SYNC= @myvar;
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 'from_myvar'
+SET DEBUG_SYNC= LEFT('now SIGNAL from_function_cut_here', 24);
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 'from_function'
+SET DEBUG_SYNC= 'now SIGNAL something';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 'something'
+SET DEBUG_SYNC= 'now WAIT_FOR nothing TIMEOUT 0';
+Warnings:
+Warning	####	debug sync point wait timed out
+SET DEBUG_SYNC= 'now SIGNAL nothing';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 'nothing'
+SET DEBUG_SYNC= 'now WAIT_FOR nothing TIMEOUT 0';
+SET DEBUG_SYNC= 'now SIGNAL something EXECUTE 0';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 'nothing'
+SET DEBUG_SYNC= 'now WAIT_FOR anotherthing TIMEOUT 0 EXECUTE 0';
+SET DEBUG_SYNC= 'now HIT_LIMIT 1';
+ERROR HY000: debug sync point hit limit reached
+SET DEBUG_SYNC= 'RESET';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: ''
+SET DEBUG_SYNC= 'p1abcd   SIGNAL s1 EXECUTE 2';
+SET DEBUG_SYNC= 'p2abc    SIGNAL s2 EXECUTE 2';
+SET DEBUG_SYNC= 'p9abcdef SIGNAL s9 EXECUTE 2';
+SET DEBUG_SYNC= 'p4a      SIGNAL s4 EXECUTE 2';
+SET DEBUG_SYNC= 'p5abcde  SIGNAL s5 EXECUTE 2';
+SET DEBUG_SYNC= 'p6ab     SIGNAL s6 EXECUTE 2';
+SET DEBUG_SYNC= 'p7       SIGNAL s7 EXECUTE 2';
+SET DEBUG_SYNC= 'p8abcdef SIGNAL s8 EXECUTE 2';
+SET DEBUG_SYNC= 'p3abcdef SIGNAL s3 EXECUTE 2';
+SET DEBUG_SYNC= 'p4a      TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's4'
+SET DEBUG_SYNC= 'p1abcd   TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's1'
+SET DEBUG_SYNC= 'p7       TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's7'
+SET DEBUG_SYNC= 'p9abcdef TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's9'
+SET DEBUG_SYNC= 'p3abcdef TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's3'
+SET DEBUG_SYNC= 'p1abcd   CLEAR';
+SET DEBUG_SYNC= 'p2abc    CLEAR';
+SET DEBUG_SYNC= 'p5abcde  CLEAR';
+SET DEBUG_SYNC= 'p6ab     CLEAR';
+SET DEBUG_SYNC= 'p8abcdef CLEAR';
+SET DEBUG_SYNC= 'p9abcdef CLEAR';
+SET DEBUG_SYNC= 'p3abcdef CLEAR';
+SET DEBUG_SYNC= 'p4a      CLEAR';
+SET DEBUG_SYNC= 'p7       CLEAR';
+SET DEBUG_SYNC= 'p1abcd   TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's3'
+SET DEBUG_SYNC= 'p7       TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's3'
+SET DEBUG_SYNC= 'p9abcdef TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: 's3'
+SET DEBUG_SYNC= 'RESET';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+Variable_name	Value
+debug_sync	ON - current signal: ''
+CREATE USER mysqltest_1@localhost;
+GRANT SUPER ON *.* TO mysqltest_1@localhost;
+connection con1, mysqltest_1
+SET DEBUG_SYNC= 'RESET';
+connection default
+DROP USER mysqltest_1@localhost;
+CREATE USER mysqltest_2@localhost;
+GRANT ALL ON *.* TO mysqltest_2@localhost;
+REVOKE SUPER ON *.* FROM mysqltest_2@localhost;
+connection con1, mysqltest_2
+SET DEBUG_SYNC= 'RESET';
+ERROR 42000: Access denied; you need the SUPER privilege for this operation
+connection default
+DROP USER mysqltest_2@localhost;
+SET DEBUG_SYNC= 'RESET';
+DROP TABLE IF EXISTS t1;
+CREATE TABLE t1 (c1 INT);
+connection con1
+SET DEBUG_SYNC= 'before_lock_tables_takes_lock
+      SIGNAL opened WAIT_FOR flushed';
+INSERT INTO t1 VALUES(1);
+connection default
+SET DEBUG_SYNC= 'now WAIT_FOR opened';
+SET DEBUG_SYNC= 'after_flush_unlock SIGNAL flushed';
+FLUSH TABLE t1;
+connection con1
+connection default
+DROP TABLE t1;
+SET DEBUG_SYNC= 'RESET';
+DROP TABLE IF EXISTS t1;
+CREATE TABLE t1 (c1 INT);
+LOCK TABLE t1 WRITE;
+connection con1
+SET DEBUG_SYNC= 'wait_for_lock SIGNAL locked EXECUTE 2';
+INSERT INTO t1 VALUES (1);
+connection default
+SET DEBUG_SYNC= 'now WAIT_FOR locked';
+UNLOCK TABLES;
+connection con1
+retrieve INSERT result.
+connection default
+DROP TABLE t1;
+SET DEBUG_SYNC= 'RESET';

=== modified file 'mysql-test/r/delete.result'
--- a/mysql-test/r/delete.result	2007-12-07 14:15:58 +0000
+++ b/mysql-test/r/delete.result	2009-09-28 10:48:52 +0000
@@ -279,3 +279,48 @@ ERROR 42000: Incorrect number of argumen
 DROP TABLE t1;
 DROP FUNCTION f1;
 End of 5.0 tests
+#
+# Bug#46958: Assertion in Diagnostics_area::set_ok_status, trigger, 
+# merge table
+#
+CREATE TABLE t1 ( a INT );
+CREATE TABLE t2 ( a INT );
+CREATE TABLE t3 ( a INT );
+INSERT INTO t1 VALUES (1), (2);
+INSERT INTO t2 VALUES (1), (2);
+INSERT INTO t3 VALUES (1), (2);
+CREATE TRIGGER tr1 BEFORE DELETE ON t2
+FOR EACH ROW INSERT INTO no_such_table VALUES (1);
+DELETE t1, t2, t3 FROM t1, t2, t3;
+ERROR 42S02: Table 'test.no_such_table' doesn't exist
+SELECT * FROM t1;
+a
+SELECT * FROM t2;
+a
+1
+2
+SELECT * FROM t3;
+a
+1
+2
+DROP TABLE t1, t2, t3;
+CREATE TABLE t1 ( a INT );
+CREATE TABLE t2 ( a INT );
+CREATE TABLE t3 ( a INT );
+INSERT INTO t1 VALUES (1), (2);
+INSERT INTO t2 VALUES (1), (2);
+INSERT INTO t3 VALUES (1), (2);
+CREATE TRIGGER tr1 AFTER DELETE ON t2
+FOR EACH ROW INSERT INTO no_such_table VALUES (1);
+DELETE t1, t2, t3 FROM t1, t2, t3;
+ERROR 42S02: Table 'test.no_such_table' doesn't exist
+SELECT * FROM t1;
+a
+SELECT * FROM t2;
+a
+2
+SELECT * FROM t3;
+a
+1
+2
+DROP TABLE t1, t2, t3;

=== modified file 'mysql-test/r/distinct.result'
--- a/mysql-test/r/distinct.result	2009-05-10 16:20:35 +0000
+++ b/mysql-test/r/distinct.result	2009-09-05 20:42:17 +0000
@@ -763,4 +763,34 @@ a	b	d	c
 1	2	0	2
 1	2	0	3
 DROP TABLE t1;
+#
+# Bug #46159: simple query that never returns
+#
+SET @old_max_heap_table_size = @@max_heap_table_size;
+SET @@max_heap_table_size = 16384;
+SET @old_sort_buffer_size = @@sort_buffer_size;
+SET @@sort_buffer_size = 32804;
+CREATE TABLE t1(c1 int, c2 VARCHAR(20));
+INSERT INTO t1 VALUES (1, '1'), (1, '1'), (2, '2'), (3, '1'), (3, '1'), (4, '4');
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+SELECT c1, c2, COUNT(*) FROM t1 GROUP BY c1 LIMIT 4;
+c1	c2	COUNT(*)
+1	1	2
+2	2	1
+3	1	2
+4	4	1
+SELECT DISTINCT c2 FROM t1 GROUP BY c1 HAVING COUNT(*) > 1;
+c2
+1
+5
+DROP TABLE t1;
+SET @@sort_buffer_size = @old_sort_buffer_size;
+SET @@max_heap_table_size = @old_max_heap_table_size;
 End of 5.1 tests

=== modified file 'mysql-test/r/explain.result'
--- a/mysql-test/r/explain.result	2009-06-11 16:21:32 +0000
+++ b/mysql-test/r/explain.result	2009-10-29 23:01:54 +0000
@@ -159,6 +159,14 @@ CREATE TABLE t1 (a INT PRIMARY KEY);
 EXPLAIN EXTENDED SELECT COUNT(a) FROM t1 USE KEY(a);
 ERROR 42000: Key 'a' doesn't exist in table 't1'
 DROP TABLE t1;
+CREATE TABLE t1(a LONGTEXT);
+INSERT INTO t1 VALUES (repeat('a',@@global.max_allowed_packet));
+INSERT INTO t1 VALUES (repeat('b',@@global.max_allowed_packet));
+EXPLAIN SELECT DISTINCT 1 FROM t1,
+(SELECT DISTINCTROW a AS away FROM t1 GROUP BY a WITH ROLLUP) as d1
+WHERE t1.a = d1.a;
+ERROR 42S22: Unknown column 'd1.a' in 'where clause'
+DROP TABLE t1;
 #
 # Bug#37870: Usage of uninitialized value caused failed assertion.
 #
@@ -186,4 +194,20 @@ dt
 2001-01-01 01:01:01
 2001-01-01 01:01:01
 drop tables t1, t2;
+#
+# Bug#48295:
+# explain extended crash with subquery and ONLY_FULL_GROUP_BY sql_mode
+#
+CREATE TABLE t1 (f1 INT);
+SELECT @@session.sql_mode INTO @old_sql_mode;
+SET SESSION sql_mode='ONLY_FULL_GROUP_BY';
+EXPLAIN EXTENDED SELECT 1 FROM t1
+WHERE f1 > ALL( SELECT t.f1 FROM t1,t1 AS t );
+ERROR 42000: Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
+SHOW WARNINGS;
+Level	Code	Message
+Error	1140	Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause
+Note	1003	select 1 AS `1` from `test`.`t1` where <not>(<exists>(...))
+SET SESSION sql_mode=@old_sql_mode;
+DROP TABLE t1;
 End of 5.1 tests.

=== modified file 'mysql-test/r/func_group.result'
--- a/mysql-test/r/func_group.result	2009-04-01 11:10:03 +0000
+++ b/mysql-test/r/func_group.result	2009-10-14 08:46:50 +0000
@@ -1477,3 +1477,47 @@ COUNT(*)
 SET SQL_MODE=default;
 DROP TABLE t1;
 End of 5.0 tests
+#
+# BUG#47280 - strange results from count(*) with order by multiple 
+#             columns without where/group
+# 
+# 
+# Initialize test
+# 
+CREATE TABLE t1 (
+pk INT NOT NULL,
+i INT,
+PRIMARY KEY (pk)
+);
+INSERT INTO t1 VALUES (1,11),(2,12),(3,13);
+#
+# Start test
+# All the following queries shall return 1 record
+#
+
+# Masking all correct values {11...13} for column i in this result. 
+SELECT MAX(pk) as max, i
+FROM t1
+ORDER BY max;
+max	i
+3	#
+
+EXPLAIN
+SELECT MAX(pk) as max, i
+FROM t1
+ORDER BY max;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	NULL	NULL	NULL	NULL	3	Using temporary
+
+# Only 11 is correct for collumn i in this result
+SELECT MAX(pk) as max, i
+FROM t1
+WHERE pk<2
+ORDER BY max;
+max	i
+1	11
+#
+# Cleanup
+#
+DROP TABLE t1;
+End of 5.1 tests

=== modified file 'mysql-test/r/func_in.result'
--- a/mysql-test/r/func_in.result	2009-05-25 08:00:40 +0000
+++ b/mysql-test/r/func_in.result	2009-10-05 05:27:36 +0000
@@ -608,4 +608,146 @@ SELECT SUM( DISTINCT e ) FROM t1 GROUP B
 ((AVG( 1 ), 1 + c, 1 + d), (AVG( 1 ), 2 + c, 2 + d));
 SUM( DISTINCT e )
 DROP TABLE t1;
+#
+# Bug #44139: Table scan when NULL appears in IN clause
+#
+CREATE TABLE t1 (
+c_int INT NOT NULL,
+c_decimal DECIMAL(5,2) NOT NULL,
+c_float FLOAT(5, 2) NOT NULL,
+c_bit BIT(10) NOT NULL,
+c_date DATE NOT NULL, 
+c_datetime DATETIME NOT NULL,
+c_timestamp TIMESTAMP NOT NULL,
+c_time TIME NOT NULL,
+c_year YEAR NOT NULL,
+c_char CHAR(10) NOT NULL,
+INDEX(c_int), INDEX(c_decimal), INDEX(c_float), INDEX(c_bit), INDEX(c_date),
+INDEX(c_datetime), INDEX(c_timestamp), INDEX(c_time), INDEX(c_year),
+INDEX(c_char));
+INSERT INTO t1 (c_int) VALUES (1), (2), (3), (4), (5);
+INSERT INTO t1 (c_int) SELECT 0 FROM t1;
+INSERT INTO t1 (c_int) SELECT 0 FROM t1;
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_int	c_int	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (NULL, 1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_int	c_int	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_int	c_int	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (1, NULL, 2, NULL, 3, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_int	c_int	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_decimal	c_decimal	3	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (NULL, 1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_decimal	c_decimal	3	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_float	c_float	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (NULL, 1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_float	c_float	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_bit	c_bit	2	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (NULL, 1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_bit	c_bit	2	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_date 
+IN ('2009-09-01', '2009-09-02', '2009-09-03');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_date	c_date	3	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_date
+IN (NULL, '2009-09-01', '2009-09-02', '2009-09-03');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_date	c_date	3	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_date IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_date IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_datetime
+IN ('2009-09-01 00:00:01', '2009-09-02 00:00:01', '2009-09-03 00:00:01');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_datetime	c_datetime	8	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_datetime
+IN (NULL, '2009-09-01 00:00:01', '2009-09-02 00:00:01', '2009-09-03 00:00:01');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_datetime	c_datetime	8	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_datetime IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_datetime IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp
+IN ('2009-09-01 00:00:01', '2009-09-01 00:00:02', '2009-09-01 00:00:03');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_timestamp	c_timestamp	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp
+IN (NULL, '2009-09-01 00:00:01', '2009-09-01 00:00:02', '2009-09-01 00:00:03');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_timestamp	c_timestamp	4	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_year	c_year	1	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (NULL, 1, 2, 3);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_year	c_year	1	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_char IN ('1', '2', '3');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_char	c_char	10	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_char IN (NULL, '1', '2', '3');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	c_char	c_char	10	NULL	3	Using where
+EXPLAIN SELECT * FROM t1 WHERE c_char IN (NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+EXPLAIN SELECT * FROM t1 WHERE c_char IN (NULL, NULL);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+DROP TABLE t1;
+#
 End of 5.1 tests

=== modified file 'mysql-test/r/func_str.result'
--- a/mysql-test/r/func_str.result	2009-05-13 18:39:35 +0000
+++ b/mysql-test/r/func_str.result	2009-09-10 10:30:03 +0000
@@ -2534,6 +2534,15 @@ SELECT LOAD_FILE(a) FROM t1;
 LOAD_FILE(a)
 NULL
 DROP TABLE t1;
+CREATE TABLE t1 (f2 VARCHAR(20));
+CREATE TABLE t2 (f2 VARCHAR(20));
+INSERT INTO t1 VALUES ('MIN'),('MAX');
+INSERT INTO t2 VALUES ('LOAD');
+SELECT CONCAT_WS('_', (SELECT t2.f2 FROM t2), t1.f2) AS concat_name FROM t1;
+concat_name
+LOAD_MIN
+LOAD_MAX
+DROP TABLE t1, t2;
 End of 5.0 tests
 drop table if exists t1;
 create table t1(f1 tinyint default null)engine=myisam;

=== modified file 'mysql-test/r/gis-rtree.result'
--- a/mysql-test/r/gis-rtree.result	2009-10-28 07:52:34 +0000
+++ b/mysql-test/r/gis-rtree.result	2009-11-10 15:15:12 +0000
@@ -1037,4 +1037,43 @@ MBRINTERSECTS(b, GEOMFROMTEXT('LINESTRIN
 COUNT(*)
 2
 DROP TABLE t1;
+#
+# Bug #48258: Assertion failed when using a spatial index
+#
+CREATE TABLE t1(a LINESTRING NOT NULL, SPATIAL KEY(a));
+INSERT INTO t1 VALUES
+(GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)')),
+(GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)'));
+EXPLAIN SELECT 1 FROM t1 WHERE a = GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	a	NULL	NULL	NULL	2	Using where
+SELECT 1 FROM t1 WHERE a = GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+1
+1
+1
+EXPLAIN SELECT 1 FROM t1 WHERE a < GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	a	NULL	NULL	NULL	2	Using where
+SELECT 1 FROM t1 WHERE a < GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+1
+EXPLAIN SELECT 1 FROM t1 WHERE a <= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	a	NULL	NULL	NULL	2	Using where
+SELECT 1 FROM t1 WHERE a <= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+1
+1
+1
+EXPLAIN SELECT 1 FROM t1 WHERE a > GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	a	NULL	NULL	NULL	2	Using where
+SELECT 1 FROM t1 WHERE a > GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+1
+EXPLAIN SELECT 1 FROM t1 WHERE a >= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	a	NULL	NULL	NULL	2	Using where
+SELECT 1 FROM t1 WHERE a >= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+1
+1
+1
+DROP TABLE t1;
 End of 5.0 tests.

=== modified file 'mysql-test/r/gis.result'
--- a/mysql-test/r/gis.result	2009-07-10 23:12:13 +0000
+++ b/mysql-test/r/gis.result	2009-10-24 06:57:31 +0000
@@ -972,6 +972,18 @@ select min(`col002`) from t1 union selec
 min(`col002`)
 NULL
 drop table t1;
+#
+# Bug #47780: crash when comparing GIS items from subquery
+#
+CREATE TABLE t1(a INT, b MULTIPOLYGON);
+INSERT INTO t1 VALUES 
+(0,
+GEOMFROMTEXT(
+'multipolygon(((1 2,3 4,5 6,7 8,9 8),(7 6,5 4,3 2,1 2,3 4)))'));
+# must not crash
+SELECT 1 FROM t1 WHERE a <> (SELECT GEOMETRYCOLLECTIONFROMWKB(b) FROM t1);
+1
+DROP TABLE t1;
 End of 5.0 tests
 create table t1 (f1 tinyint(1), f2 char(1), f3 varchar(1), f4 geometry, f5 datetime);
 create view v1 as select * from t1;

=== modified file 'mysql-test/r/grant.result'
--- a/mysql-test/r/grant.result	2009-06-15 15:53:45 +0000
+++ b/mysql-test/r/grant.result	2009-10-27 10:09:36 +0000
@@ -1007,8 +1007,8 @@ DROP TABLE mysqltest1.t2;
 SHOW GRANTS;
 Grants for mysqltest_1@localhost
 GRANT USAGE ON *.* TO 'mysqltest_1'@'localhost'
-GRANT SELECT, INSERT, CREATE, DROP, ALTER ON `mysqltest1`.`t2` TO 'mysqltest_1'@'localhost'
 GRANT SELECT, INSERT, CREATE, DROP, ALTER ON `mysqltest1`.`t1` TO 'mysqltest_1'@'localhost'
+GRANT SELECT, INSERT, CREATE, DROP, ALTER ON `mysqltest1`.`t2` TO 'mysqltest_1'@'localhost'
 RENAME TABLE t1 TO t2;
 RENAME TABLE t2 TO t1;
 ALTER TABLE t1 RENAME TO t2;
@@ -1018,8 +1018,8 @@ REVOKE DROP, INSERT ON mysqltest1.t2 FRO
 SHOW GRANTS;
 Grants for mysqltest_1@localhost
 GRANT USAGE ON *.* TO 'mysqltest_1'@'localhost'
-GRANT SELECT, CREATE, ALTER ON `mysqltest1`.`t2` TO 'mysqltest_1'@'localhost'
 GRANT SELECT, CREATE, ALTER ON `mysqltest1`.`t1` TO 'mysqltest_1'@'localhost'
+GRANT SELECT, CREATE, ALTER ON `mysqltest1`.`t2` TO 'mysqltest_1'@'localhost'
 RENAME TABLE t1 TO t2;
 ERROR 42000: DROP command denied to user 'mysqltest_1'@'localhost' for table 't1'
 ALTER TABLE t1 RENAME TO t2;

=== modified file 'mysql-test/r/grant3.result'
--- a/mysql-test/r/grant3.result	2008-02-13 15:34:12 +0000
+++ b/mysql-test/r/grant3.result	2009-10-20 06:17:57 +0000
@@ -154,4 +154,42 @@ SELECT * FROM mysqltest_1.t1;
 a
 DROP USER 'mysqltest1'@'%';
 DROP DATABASE mysqltest_1;
+#
+# Bug#41597 - After rename of user, there are additional grants
+#             when grants are reapplied.
+#
+CREATE DATABASE temp;
+CREATE TABLE temp.t1(a INT, b VARCHAR(10));
+INSERT INTO temp.t1 VALUES(1, 'name1');
+INSERT INTO temp.t1 VALUES(2, 'name2');
+INSERT INTO temp.t1 VALUES(3, 'name3');
+CREATE USER 'user1'@'%';
+RENAME USER 'user1'@'%' TO 'user2'@'%';
+# Show privileges after rename and BEFORE grant
+SHOW GRANTS FOR 'user2'@'%';
+Grants for user2@%
+GRANT USAGE ON *.* TO 'user2'@'%'
+GRANT SELECT (a), INSERT (b) ON `temp`.`t1` TO 'user2'@'%';
+# Show privileges after rename and grant
+SHOW GRANTS FOR 'user2'@'%';
+Grants for user2@%
+GRANT USAGE ON *.* TO 'user2'@'%'
+GRANT SELECT (a), INSERT (b) ON `temp`.`t1` TO 'user2'@'%'
+# Connect as the renamed user
+SHOW GRANTS;
+Grants for user2@%
+GRANT USAGE ON *.* TO 'user2'@'%'
+GRANT SELECT (a), INSERT (b) ON `temp`.`t1` TO 'user2'@'%'
+SELECT a FROM temp.t1;
+a
+1
+2
+3
+# Check for additional privileges by accessing a
+# non privileged column. We shouldn't be able to 
+# access this column.
+SELECT b FROM temp.t1;
+ERROR 42000: SELECT command denied to user 'user2'@'localhost' for column 'b' in table 't1'
+DROP USER 'user2'@'%';
+DROP DATABASE temp;
 End of 5.0 tests

=== added file 'mysql-test/r/grant_lowercase_fs.result'
--- a/mysql-test/r/grant_lowercase_fs.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/grant_lowercase_fs.result	2009-10-27 08:09:19 +0000
@@ -0,0 +1,16 @@
+create database db1;
+GRANT CREATE ON db1.* to user_1@localhost;
+GRANT SELECT ON db1.* to USER_1@localhost;
+CREATE TABLE t1(f1 int);
+SELECT * FROM t1;
+ERROR 42000: SELECT command denied to user 'user_1'@'localhost' for table 't1'
+SELECT * FROM t1;
+f1
+CREATE TABLE t2(f1 int);
+ERROR 42000: CREATE command denied to user 'USER_1'@'localhost' for table 't2'
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM user_1@localhost;
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM USER_1@localhost;
+DROP USER user_1@localhost;
+DROP USER USER_1@localhost;
+DROP DATABASE db1;
+use test;

=== modified file 'mysql-test/r/group_min_max.result'
--- a/mysql-test/r/group_min_max.result	2009-08-30 07:03:37 +0000
+++ b/mysql-test/r/group_min_max.result	2009-10-09 09:30:40 +0000
@@ -876,10 +876,10 @@ id	select_type	table	type	possible_keys	
 1	SIMPLE	t1	range	NULL	idx_t1_1	163	NULL	17	Using where; Using index for group-by
 explain select a1,a2,b,       max(c) from t1 where (c > 'b1') or (c <= 'g1') group by a1,a2,b;
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
-1	SIMPLE	t1	range	NULL	idx_t1_1	147	NULL	17	Using where; Using index for group-by
+1	SIMPLE	t1	range	NULL	idx_t1_1	163	NULL	17	Using where; Using index for group-by
 explain select a1,a2,b,min(c),max(c) from t1 where (c > 'b1') or (c <= 'g1') group by a1,a2,b;
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
-1	SIMPLE	t1	range	NULL	idx_t1_1	147	NULL	17	Using where; Using index for group-by
+1	SIMPLE	t1	range	NULL	idx_t1_1	163	NULL	17	Using where; Using index for group-by
 explain select a1,a2,b,min(c),max(c) from t1 where (c > 'b111') and (c <= 'g112') group by a1,a2,b;
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	SIMPLE	t1	range	NULL	idx_t1_1	163	NULL	17	Using where; Using index for group-by
@@ -924,7 +924,7 @@ id	select_type	table	type	possible_keys	
 1	SIMPLE	t2	range	NULL	idx_t2_1	163	NULL	#	Using where; Using index for group-by
 explain select a1,a2,b,       max(c) from t2 where (c > 'b1') or (c <= 'g1') group by a1,a2,b;
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
-1	SIMPLE	t2	range	NULL	idx_t2_1	146	NULL	#	Using where; Using index for group-by
+1	SIMPLE	t2	range	NULL	idx_t2_1	163	NULL	#	Using where; Using index for group-by
 explain select a1,a2,b,min(c),max(c) from t2 where (c > 'b1') or (c <= 'g1') group by a1,a2,b;
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	SIMPLE	t2	range	NULL	idx_t2_1	163	NULL	#	Using where; Using index for group-by

=== added file 'mysql-test/r/have_debug_sync.require'
--- a/mysql-test/r/have_debug_sync.require	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/have_debug_sync.require	2009-09-29 15:38:40 +0000
@@ -0,0 +1,2 @@
+debug_sync
+1

=== modified file 'mysql-test/r/information_schema_db.result'
--- a/mysql-test/r/information_schema_db.result	2009-09-07 20:50:10 +0000
+++ b/mysql-test/r/information_schema_db.result	2009-11-10 15:15:12 +0000
@@ -108,7 +108,7 @@ show create view testdb_1.v7;
 View	Create View	character_set_client	collation_connection
 v7	CREATE ALGORITHM=UNDEFINED DEFINER=`no_such_user`@`no_such_host` SQL SECURITY DEFINER VIEW `v7` AS select `testdb_1`.`t2`.`f1` AS `f1` from `t2`	latin1	latin1_swedish_ci
 Warnings:
-Warning	1356	View 'testdb_1.v7' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+Note	1449	The user specified as a definer ('no_such_user'@'no_such_host') does not exist
 show fields from testdb_1.v7;
 Field	Type	Null	Key	Default	Extra
 f1	char(4)	YES		NULL	
@@ -138,7 +138,7 @@ show create view testdb_1.v7;
 View	Create View	character_set_client	collation_connection
 v7	CREATE ALGORITHM=UNDEFINED DEFINER=`no_such_user`@`no_such_host` SQL SECURITY DEFINER VIEW `v7` AS select `testdb_1`.`t2`.`f1` AS `f1` from `t2`	latin1	latin1_swedish_ci
 Warnings:
-Warning	1356	View 'testdb_1.v7' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+Note	1449	The user specified as a definer ('no_such_user'@'no_such_host') does not exist
 revoke insert(f1) on v3 from testdb_2@localhost;
 revoke show view on v5 from testdb_2@localhost;
 use testdb_1;
@@ -156,7 +156,8 @@ ERROR 42000: SELECT command denied to us
 show create view testdb_1.v7;
 ERROR 42000: SELECT command denied to user 'testdb_2'@'localhost' for table 'v7'
 show create view v4;
-ERROR HY000: EXPLAIN/SHOW can not be issued; lacking privileges for underlying table
+View	Create View	character_set_client	collation_connection
+v4	CREATE ALGORITHM=UNDEFINED DEFINER=`testdb_2`@`localhost` SQL SECURITY DEFINER VIEW `v4` AS select `v3`.`f1` AS `f1`,`v3`.`f2` AS `f2` from `testdb_1`.`v3`	latin1	latin1_swedish_ci
 show fields from v4;
 Field	Type	Null	Key	Default	Extra
 f1	char(4)	YES		NULL	

=== modified file 'mysql-test/r/innodb-autoinc.result'
--- a/mysql-test/r/innodb-autoinc.result	2009-06-09 15:08:46 +0000
+++ b/mysql-test/r/innodb-autoinc.result	2009-11-10 15:15:12 +0000
@@ -197,7 +197,7 @@ c1	c2
 5	9
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	100
 auto_increment_offset	10
@@ -230,7 +230,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -269,7 +269,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -282,7 +282,7 @@ SELECT * FROM t1;
 c1
 -1
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	100
 auto_increment_offset	10
@@ -315,7 +315,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -330,7 +330,7 @@ SELECT * FROM t1;
 c1
 1
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	100
 auto_increment_offset	10
@@ -370,7 +370,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -385,7 +385,7 @@ SELECT * FROM t1;
 c1
 1
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	100
 auto_increment_offset	10
@@ -419,7 +419,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -434,7 +434,7 @@ c1
 1
 9223372036854775794
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=2, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	2
 auto_increment_offset	10
@@ -452,7 +452,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -467,7 +467,7 @@ c1
 1
 18446744073709551603
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=2, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	2
 auto_increment_offset	10
@@ -485,7 +485,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -500,7 +500,7 @@ c1
 1
 18446744073709551603
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=5, @@SESSION.AUTO_INCREMENT_OFFSET=7;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	5
 auto_increment_offset	7
@@ -514,7 +514,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -533,7 +533,7 @@ c1
 -9223372036854775806
 1
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=3, @@SESSION.AUTO_INCREMENT_OFFSET=3;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	3
 auto_increment_offset	3
@@ -550,7 +550,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -568,7 +568,7 @@ SET @@SESSION.AUTO_INCREMENT_INCREMENT=1
 Warnings:
 Warning	1292	Truncated incorrect auto_increment_increment value: '1152921504606846976'
 Warning	1292	Truncated incorrect auto_increment_offset value: '1152921504606846976'
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	65535
 auto_increment_offset	65535
@@ -581,7 +581,7 @@ c1
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -867,3 +867,262 @@ INSERT INTO t2 SELECT NULL FROM t1;
 Got one of the listed errors
 DROP TABLE t1;
 DROP TABLE t2;
+SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
+CREATE TABLE t1 (c1 INT PRIMARY KEY AUTO_INCREMENT) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (null);
+INSERT INTO t1 VALUES (null);
+ALTER TABLE t1 CHANGE c1 d1 INT NOT NULL AUTO_INCREMENT;
+SELECT * FROM t1;
+d1
+1
+3
+SELECT * FROM t1;
+d1
+1
+3
+INSERT INTO t1 VALUES(null);
+Got one of the listed errors
+ALTER TABLE t1 AUTO_INCREMENT = 3;
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `d1` int(11) NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (`d1`)
+) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
+INSERT INTO t1 VALUES(null);
+SELECT * FROM t1;
+d1
+1
+3
+4
+DROP TABLE t1;
+SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
+SHOW VARIABLES LIKE "%auto_inc%";
+Variable_name	Value
+auto_increment_increment	1
+auto_increment_offset	1
+CREATE TABLE t1 (c1 TINYINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-127, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` tinyint(4) NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+-127	innodb
+-1	innodb
+1	NULL
+2	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 TINYINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (-127, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+1	NULL
+2	innodb
+3	innodb
+4	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 SMALLINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-32767, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` smallint(6) NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+-32767	innodb
+-1	innodb
+1	NULL
+2	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (-32757, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+1	NULL
+2	innodb
+3	innodb
+4	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 MEDIUMINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-8388607, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` mediumint(9) NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+-8388607	innodb
+-1	innodb
+1	NULL
+2	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 MEDIUMINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (-8388607, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+1	NULL
+2	innodb
+3	innodb
+4	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 INT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-2147483647, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` int(11) NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+-2147483647	innodb
+-1	innodb
+1	NULL
+2	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (-2147483647, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` int(10) unsigned NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+1	NULL
+2	innodb
+3	innodb
+4	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 BIGINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-9223372036854775807, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` bigint(20) NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+-9223372036854775807	innodb
+-1	innodb
+1	NULL
+2	NULL
+DROP TABLE t1;
+CREATE TABLE t1 (c1 BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (-9223372036854775807, 'innodb');
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
+  `c2` varchar(10) DEFAULT NULL,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
+SELECT * FROM t1;
+c1	c2
+1	NULL
+2	innodb
+3	innodb
+4	NULL
+DROP TABLE t1;
+CREATE TABLE T1 (c1 INT AUTO_INCREMENT, c2 INT, PRIMARY KEY(c1)) AUTO_INCREMENT=10 ENGINE=InnoDB;
+CREATE INDEX i1 on T1(c2);
+SHOW CREATE TABLE T1;
+Table	Create Table
+T1	CREATE TABLE `T1` (
+  `c1` int(11) NOT NULL AUTO_INCREMENT,
+  `c2` int(11) DEFAULT NULL,
+  PRIMARY KEY (`c1`),
+  KEY `i1` (`c2`)
+) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1
+INSERT INTO T1 (c2) values (0);
+SELECT * FROM T1;
+c1	c2
+10	0
+DROP TABLE T1;

=== added file 'mysql-test/r/innodb_bug44369.result'
--- a/mysql-test/r/innodb_bug44369.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/innodb_bug44369.result	2009-11-02 14:59:44 +0000
@@ -0,0 +1,14 @@
+create table bug44369 (DB_ROW_ID int) engine=innodb;
+ERROR HY000: Can't create table 'test.bug44369' (errno: -1)
+create table bug44369 (db_row_id int) engine=innodb;
+ERROR HY000: Can't create table 'test.bug44369' (errno: -1)
+show warnings;
+Level	Code	Message
+Warning	1005	Error creating table 'test/bug44369' with column name 'db_row_id'. 'db_row_id' is a reserved name. Please try to re-create the table with a different column name.
+Error	1005	Can't create table 'test.bug44369' (errno: -1)
+create table bug44369 (db_TRX_Id int) engine=innodb;
+ERROR HY000: Can't create table 'test.bug44369' (errno: -1)
+show warnings;
+Level	Code	Message
+Warning	1005	Error creating table 'test/bug44369' with column name 'db_TRX_Id'. 'db_TRX_Id' is a reserved name. Please try to re-create the table with a different column name.
+Error	1005	Can't create table 'test.bug44369' (errno: -1)

=== added file 'mysql-test/r/innodb_bug46000.result'
--- a/mysql-test/r/innodb_bug46000.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/innodb_bug46000.result	2009-11-02 14:59:44 +0000
@@ -0,0 +1,17 @@
+create table bug46000(`id` int,key `GEN_CLUST_INDEX`(`id`))engine=innodb;
+ERROR HY000: Can't create table 'test.bug46000' (errno: -1)
+create table bug46000(`id` int, key `GEN_clust_INDEX`(`id`))engine=innodb;
+ERROR HY000: Can't create table 'test.bug46000' (errno: -1)
+show warnings;
+Level	Code	Message
+Warning	1005	Cannot Create Index with name 'GEN_CLUST_INDEX'. The name is reserved for the system default primary index.
+Error	1005	Can't create table 'test.bug46000' (errno: -1)
+create table bug46000(id int) engine=innodb;
+create index GEN_CLUST_INDEX on bug46000(id);
+ERROR HY000: Can't create table '#sql-temporary' (errno: -1)
+show warnings;
+Level	Code	Message
+Warning	1005	Cannot Create Index with name 'GEN_CLUST_INDEX'. The name is reserved for the system default primary index.
+Error	1005	Can't create table '#sql-temporary' (errno: -1)
+create index idx on bug46000(id);
+drop table bug46000;

=== added file 'mysql-test/r/innodb_bug47777.result'
--- a/mysql-test/r/innodb_bug47777.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/innodb_bug47777.result	2009-11-02 14:41:40 +0000
@@ -0,0 +1,13 @@
+create table bug47777(c2 linestring not null, primary key (c2(1))) engine=innodb;
+insert into bug47777 values (geomfromtext('linestring(1 2,3 4,5 6,7 8,9 10)'));
+select count(*) from bug47777 where c2 =geomfromtext('linestring(1 2,3 4,5 6,7 8,9 10)');
+count(*)
+1
+update bug47777 set c2=GeomFromText('POINT(1 1)');
+select count(*) from bug47777 where c2 =geomfromtext('linestring(1 2,3 4,5 6,7 8,9 10)');
+count(*)
+0
+select count(*) from bug47777 where c2 = GeomFromText('POINT(1 1)');
+count(*)
+1
+drop table bug47777;

=== renamed file 'mysql-test/r/bug40113.result' => 'mysql-test/r/innodb_lock_wait_timeout_1.result'
--- a/mysql-test/r/bug40113.result	2009-07-13 15:11:16 +0000
+++ b/mysql-test/r/innodb_lock_wait_timeout_1.result	2009-11-03 17:45:52 +0000
@@ -26,4 +26,332 @@ SELECT * FROM t1;
 a	b
 1070109	99
 DROP TABLE t2, t1;
-End of 5.0 tests
+# End of 5.0 tests
+#
+# Bug#46539 Various crashes on INSERT IGNORE SELECT + SELECT
+#           FOR UPDATE
+#
+drop table if exists t1;
+create table t1 (a int primary key auto_increment,
+b int, index(b)) engine=innodb;
+insert into t1 (b) values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
+set autocommit=0;
+begin;
+select * from t1 where b=5 for update;
+a	b
+5	5
+insert ignore into t1 (b) select a as b from t1;
+ERROR HY000: Lock wait timeout exceeded; try restarting transaction
+# Cleanup
+#
+commit;
+set autocommit=default;
+drop table t1;
+#
+# Bug#41756 Strange error messages about locks from InnoDB
+#
+drop table if exists t1;
+# In the default transaction isolation mode, and/or with
+# innodb_locks_unsafe_for_binlog=OFF, handler::unlock_row()
+# in InnoDB does nothing.
+# Thus in order to reproduce the condition that led to the
+# warning, one needs to relax isolation by either
+# setting a weaker tx_isolation value, or by turning on
+# the unsafe replication switch.
+# For testing purposes, choose to tweak the isolation level,
+# since it's settable at runtime, unlike
+# innodb_locks_unsafe_for_binlog, which is
+# only a command-line switch.
+#
+set @@session.tx_isolation="read-committed";
+# Prepare data. We need a table with a unique index,
+# for join_read_key to be used. The other column
+# allows to control what passes WHERE clause filter.
+create table t1 (a int primary key, b int) engine=innodb;
+# Let's make sure t1 has sufficient amount of rows
+# to exclude JT_ALL access method when reading it,
+# i.e. make sure that JT_EQ_REF(a) is always preferred.
+insert into t1 values (1,1), (2,null), (3,1), (4,1),
+(5,1), (6,1), (7,1), (8,1), (9,1), (10,1),
+(11,1), (12,1), (13,1), (14,1), (15,1),
+(16,1), (17,1), (18,1), (19,1), (20,1);
+#
+# Demonstrate that for the SELECT statement
+# used later in the test JT_EQ_REF access method is used.
+#
+explain
+select 1 from t1 natural join (select 2 as a, 1 as b union all
+select 2 as a, 2 as b) as t2 for update;
+id	1
+select_type	PRIMARY
+table	<derived2>
+type	ALL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	2
+Extra	
+id	1
+select_type	PRIMARY
+table	t1
+type	eq_ref
+possible_keys	PRIMARY
+key	PRIMARY
+key_len	4
+ref	t2.a
+rows	1
+Extra	Using where
+id	2
+select_type	DERIVED
+table	NULL
+type	NULL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	NULL
+Extra	No tables used
+id	3
+select_type	UNION
+table	NULL
+type	NULL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	NULL
+Extra	No tables used
+id	NULL
+select_type	UNION RESULT
+table	<union2,3>
+type	ALL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	NULL
+Extra	
+#
+# Demonstrate that the reported SELECT statement
+# no longer produces warnings.
+#
+select 1 from t1 natural join (select 2 as a, 1 as b union all
+select 2 as a, 2 as b) as t2 for update;
+1
+commit;
+# 
+# Demonstrate that due to lack of inter-sweep "reset" function,
+# we keep some non-matching records locked, even though we know
+# we could unlock them.
+# To do that, show that if there is only one distinct value
+# for a in t2 (a=2), we will keep record (2,null) in t1 locked.
+# But if we add another value for "a" to t2, say 6,
+# join_read_key cache will be pruned at least once, 
+# and thus record (2, null) in t1 will get unlocked.
+#
+begin;
+select 1 from t1 natural join (select 2 as a, 1 as b union all
+select 2 as a, 2 as b) as t2 for update;
+1
+#
+# Switching to connection con1
+# We should be able to delete all records from t1 except (2, null),
+# since they were not locked.
+begin;
+# Delete in series of 3 records so that full scan
+# is not used and we're not blocked on record (2,null)
+delete from t1 where a in (1,3,4);
+delete from t1 where a in (5,6,7);
+delete from t1 where a in (8,9,10);
+delete from t1 where a in (11,12,13);
+delete from t1 where a in (14,15,16);
+delete from t1 where a in (17,18);
+delete from t1 where a in (19,20);
+# 
+# Record (2, null) is locked. This is actually unnecessary, 
+# because the previous select returned no rows. 
+# Just demonstrate the effect.
+#
+delete from t1;
+ERROR HY000: Lock wait timeout exceeded; try restarting transaction
+rollback;
+#
+# Switching to connection default
+#
+# Show that the original contents of t1 is intact:
+select * from t1;
+a	b
+1	1
+2	NULL
+3	1
+4	1
+5	1
+6	1
+7	1
+8	1
+9	1
+10	1
+11	1
+12	1
+13	1
+14	1
+15	1
+16	1
+17	1
+18	1
+19	1
+20	1
+commit;
+#
+# Have a one more record in t2 to show that 
+# if join_read_key cache is purned, the current
+# row under the cursor is unlocked (provided, this row didn't 
+# match the partial WHERE clause, of course).
+# Sic: the result of this test dependent on the order of retrieval
+# of records --echo # from the derived table, if !
+# We use DELETE to disable the JOIN CACHE. This DELETE modifies no
+# records. It also should leave no InnoDB row locks.
+#
+begin;
+delete t1.* from t1 natural join (select 2 as a, 2 as b union all
+select 0 as a, 0 as b) as t2;
+# Demonstrate that nothing was deleted form t1
+select * from t1;
+a	b
+1	1
+2	NULL
+3	1
+4	1
+5	1
+6	1
+7	1
+8	1
+9	1
+10	1
+11	1
+12	1
+13	1
+14	1
+15	1
+16	1
+17	1
+18	1
+19	1
+20	1
+#
+# Switching to connection con1
+begin;
+# Since there is another distinct record in the derived table
+# the previous matching record in t1 -- (2,null) -- was unlocked.
+delete from t1;
+# We will need the contents of the table again.
+rollback;
+select * from t1;
+a	b
+1	1
+2	NULL
+3	1
+4	1
+5	1
+6	1
+7	1
+8	1
+9	1
+10	1
+11	1
+12	1
+13	1
+14	1
+15	1
+16	1
+17	1
+18	1
+19	1
+20	1
+commit;
+#
+# Switching to connection default
+rollback;
+begin;
+#
+# Before this patch, we could wrongly unlock a record
+# that was cached and later used in a join. Demonstrate that
+# this is no longer the case.
+# Sic: this test is also order-dependent (i.e. the
+# the bug would show up only if the first record in the union
+# is retreived and processed first.
+#
+# Verify that JT_EQ_REF is used.
+explain
+select 1 from t1 natural join (select 3 as a, 2 as b union all
+select 3 as a, 1 as b) as t2 for update;
+id	1
+select_type	PRIMARY
+table	<derived2>
+type	ALL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	2
+Extra	
+id	1
+select_type	PRIMARY
+table	t1
+type	eq_ref
+possible_keys	PRIMARY
+key	PRIMARY
+key_len	4
+ref	t2.a
+rows	1
+Extra	Using where
+id	2
+select_type	DERIVED
+table	NULL
+type	NULL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	NULL
+Extra	No tables used
+id	3
+select_type	UNION
+table	NULL
+type	NULL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	NULL
+Extra	No tables used
+id	NULL
+select_type	UNION RESULT
+table	<union2,3>
+type	ALL
+possible_keys	NULL
+key	NULL
+key_len	NULL
+ref	NULL
+rows	NULL
+Extra	
+# Lock the record.
+select 1 from t1 natural join (select 3 as a, 2 as b union all
+select 3 as a, 1 as b) as t2 for update;
+1
+1
+# Switching to connection con1
+#
+# We should not be able to delete record (3,1) from t1,
+# (previously it was possible).
+#
+delete from t1 where a=3;
+ERROR HY000: Lock wait timeout exceeded; try restarting transaction
+# Switching to connection default
+commit;
+set @@session.tx_isolation=default;
+drop table t1;
+#
+# End of 5.1 tests
+#

=== modified file 'mysql-test/r/innodb_mysql.result'
--- a/mysql-test/r/innodb_mysql.result	2009-09-15 06:08:54 +0000
+++ b/mysql-test/r/innodb_mysql.result	2009-11-10 15:15:12 +0000
@@ -385,9 +385,10 @@ name	dept
 rs5	cs10
 rs5	cs9
 DELETE FROM t1;
+# Masking (#) number in "rows" column of the following EXPLAIN output, as it may vary (bug#47746).
 EXPLAIN SELECT DISTINCT t1.name, t1.dept FROM t1 WHERE t1.name='rs5';
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
-1	SIMPLE	t1	range	name	name	44	NULL	2	Using where; Using index for group-by
+1	SIMPLE	t1	range	name	name	44	NULL	#	Using where; Using index for group-by
 SELECT DISTINCT t1.name, t1.dept FROM t1 WHERE t1.name='rs5';
 name	dept
 DROP TABLE t1;
@@ -2208,4 +2209,46 @@ EXPLAIN SELECT * FROM t1 FORCE INDEX(PRI
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	SIMPLE	t1	index	NULL	PRIMARY	4	NULL	128	Using where
 DROP TABLE t1;
+#
+# Bug #47963: Wrong results when index is used
+#
+CREATE TABLE t1(
+a VARCHAR(5) NOT NULL, 
+b VARCHAR(5) NOT NULL,
+c DATETIME NOT NULL,
+KEY (c) 
+) ENGINE=InnoDB;
+INSERT INTO t1 VALUES('TEST', 'TEST', '2009-10-09 00:00:00');
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00' AND c <= '2009-10-09 00:00:00';
+a	b	c
+TEST	TEST	2009-10-09 00:00:00
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00.0' AND c <= '2009-10-09 00:00:00.0';
+a	b	c
+TEST	TEST	2009-10-09 00:00:00
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00.0' AND c <= '2009-10-09 00:00:00';
+a	b	c
+TEST	TEST	2009-10-09 00:00:00
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00' AND c <= '2009-10-09 00:00:00.0';
+a	b	c
+TEST	TEST	2009-10-09 00:00:00
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00.000' AND c <= '2009-10-09 00:00:00.000';
+a	b	c
+TEST	TEST	2009-10-09 00:00:00
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00.00' AND c <= '2009-10-09 00:00:00.001';
+a	b	c
+TEST	TEST	2009-10-09 00:00:00
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00.001' AND c <= '2009-10-09 00:00:00.00';
+a	b	c
+EXPLAIN SELECT * FROM t1 WHERE a = 'TEST' AND 
+c >= '2009-10-09 00:00:00.001' AND c <= '2009-10-09 00:00:00.00';
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
+DROP TABLE t1;
 End of 5.1 tests

=== modified file 'mysql-test/r/insert_select.result'
--- a/mysql-test/r/insert_select.result	2009-09-07 20:50:10 +0000
+++ b/mysql-test/r/insert_select.result	2009-11-10 15:15:12 +0000
@@ -833,3 +833,17 @@ Table	Op	Msg_type	Msg_text
 test.t2	check	status	OK
 drop table t1,t2;
 End of 5.0 tests
+##################################################################
+#
+# Bug #46075: Assertion failed: 0, file .\protocol.cc, line 416
+#
+CREATE TABLE t1(a INT);
+SET max_heap_table_size = 16384;
+SET @old_myisam_data_pointer_size = @@myisam_data_pointer_size;
+SET GLOBAL myisam_data_pointer_size = 2;
+INSERT INTO t1 VALUES (1), (2), (3), (4), (5);
+call mtr.add_suppression("mysqld: The table '.*#sql.*' is full");
+INSERT IGNORE INTO t1 SELECT t1.a FROM t1,t1 t2,t1 t3,t1 t4,t1 t5,t1 t6,t1 t7;
+SET GLOBAL myisam_data_pointer_size = @old_myisam_data_pointer_size;
+DROP TABLE t1;
+End of 5.1 tests

=== modified file 'mysql-test/r/join.result'
--- a/mysql-test/r/join.result	2008-10-06 12:37:52 +0000
+++ b/mysql-test/r/join.result	2009-10-30 08:03:18 +0000
@@ -1063,4 +1063,68 @@ a	b	c	d
 127	NULL	127	NULL
 128	NULL	128	NULL
 DROP TABLE IF EXISTS t1,t2;
+#
+# Bug #42116: Mysql crash on specific query
+#
+CREATE TABLE t1 (a INT);
+CREATE TABLE t2 (a INT);
+CREATE TABLE t3 (a INT, INDEX (a));
+CREATE TABLE t4 (a INT);
+CREATE TABLE t5 (a INT);
+CREATE TABLE t6 (a INT);
+INSERT INTO t1 VALUES (1), (1), (1);
+INSERT INTO t2 VALUES
+(2), (2), (2), (2), (2), (2), (2), (2), (2), (2);
+INSERT INTO t3 VALUES
+(3), (3), (3), (3), (3), (3), (3), (3), (3), (3);
+EXPLAIN
+SELECT * 
+FROM 
+t1 JOIN t2 ON t1.a = t2.a 
+LEFT JOIN 
+(
+(
+t3 LEFT JOIN t4 ON t3.a = t4.a
+) 
+LEFT JOIN 
+(
+t5 LEFT JOIN t6 ON t5.a = t6.a
+) 
+ON t4.a = t5.a
+) 
+ON t1.a = t3.a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	NULL	NULL	NULL	NULL	3	
+1	SIMPLE	t3	ref	a	a	5	test.t1.a	2	Using index
+1	SIMPLE	t4	ALL	NULL	NULL	NULL	NULL	0	
+1	SIMPLE	t5	ALL	NULL	NULL	NULL	NULL	0	
+1	SIMPLE	t6	ALL	NULL	NULL	NULL	NULL	0	
+1	SIMPLE	t2	ALL	NULL	NULL	NULL	NULL	10	Using where; Using join buffer
+SELECT * 
+FROM 
+t1 JOIN t2 ON t1.a = t2.a 
+LEFT JOIN 
+(
+(
+t3 LEFT JOIN t4 ON t3.a = t4.a
+) 
+LEFT JOIN 
+(
+t5 LEFT JOIN t6 ON t5.a = t6.a
+) 
+ON t4.a = t5.a
+) 
+ON t1.a = t3.a;
+a	a	a	a	a	a
+DROP TABLE t1,t2,t3,t4,t5,t6;
 End of 5.0 tests.
+CREATE TABLE t1 (f1 int);
+CREATE TABLE t2 (f1 int);
+INSERT INTO t2  VALUES (1);
+CREATE VIEW v1 AS SELECT * FROM t2;
+PREPARE stmt FROM 'UPDATE t2 AS A NATURAL JOIN v1 B SET B.f1 = 1';
+EXECUTE stmt;
+EXECUTE stmt;
+DEALLOCATE PREPARE stmt;
+DROP VIEW v1;
+DROP TABLE t1, t2;

=== added file 'mysql-test/r/locale.result'
--- a/mysql-test/r/locale.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/locale.result	2009-10-19 08:44:44 +0000
@@ -0,0 +1,29 @@
+DROP TABLE IF EXISTS t1;
+Start of 5.4 tests
+#
+# Bug#43207 wrong LC_TIME names for romanian locale
+#
+SET NAMES utf8;
+SET lc_time_names=ro_RO;
+SELECT DATE_FORMAT('2001-01-01', '%w %a %W');
+DATE_FORMAT('2001-01-01', '%w %a %W')
+1 Lu Luni
+SELECT DATE_FORMAT('2001-01-02', '%w %a %W');
+DATE_FORMAT('2001-01-02', '%w %a %W')
+2 Ma Mar��i
+SELECT DATE_FORMAT('2001-01-03', '%w %a %W');
+DATE_FORMAT('2001-01-03', '%w %a %W')
+3 Mi Miercuri
+SELECT DATE_FORMAT('2001-01-04', '%w %a %W');
+DATE_FORMAT('2001-01-04', '%w %a %W')
+4 Jo Joi
+SELECT DATE_FORMAT('2001-01-05', '%w %a %W');
+DATE_FORMAT('2001-01-05', '%w %a %W')
+5 Vi Vineri
+SELECT DATE_FORMAT('2001-01-06', '%w %a %W');
+DATE_FORMAT('2001-01-06', '%w %a %W')
+6 S�� S��mb��t��
+SELECT DATE_FORMAT('2001-01-07', '%w %a %W');
+DATE_FORMAT('2001-01-07', '%w %a %W')
+0 Du Duminic��
+End of 5.4 tests

=== modified file 'mysql-test/r/lowercase_fs_off.result'
--- a/mysql-test/r/lowercase_fs_off.result	2006-11-14 18:45:52 +0000
+++ b/mysql-test/r/lowercase_fs_off.result	2009-10-27 08:09:19 +0000
@@ -10,3 +10,48 @@ create database D1;
 ERROR 42000: Access denied for user 'sample'@'localhost' to database 'D1'
 drop user 'sample'@'localhost';
 drop database if exists d1;
+CREATE DATABASE d1;
+USE d1;
+CREATE TABLE T1(f1 INT);
+CREATE TABLE t1(f1 INT);
+GRANT SELECT ON T1 to user_1@localhost;
+select * from t1;
+ERROR 42000: SELECT command denied to user 'user_1'@'localhost' for table 't1'
+select * from T1;
+f1
+GRANT SELECT ON t1 to user_1@localhost;
+select * from information_schema.table_privileges;
+GRANTEE	TABLE_CATALOG	TABLE_SCHEMA	TABLE_NAME	PRIVILEGE_TYPE	IS_GRANTABLE
+'user_1'@'localhost'	NULL	d1	T1	SELECT	NO
+'user_1'@'localhost'	NULL	d1	t1	SELECT	NO
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM user_1@localhost;
+DROP USER user_1@localhost;
+DROP DATABASE d1;
+USE test;
+CREATE DATABASE db1;
+USE db1;
+CREATE PROCEDURE p1() BEGIN END;
+CREATE FUNCTION f1(i INT) RETURNS INT RETURN i+1;
+GRANT USAGE ON db1.* to user_1@localhost;
+GRANT EXECUTE ON PROCEDURE db1.P1 to user_1@localhost;
+GRANT EXECUTE ON FUNCTION db1.f1 to user_1@localhost;
+GRANT UPDATE ON db1.* to USER_1@localhost;
+call p1();
+call P1();
+select f1(1);
+f1(1)
+2
+call p1();
+ERROR 42000: execute command denied to user 'USER_1'@'localhost' for routine 'db1.p1'
+call P1();
+ERROR 42000: execute command denied to user 'USER_1'@'localhost' for routine 'db1.p1'
+select f1(1);
+ERROR 42000: execute command denied to user 'USER_1'@'localhost' for routine 'db1.f1'
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM user_1@localhost;
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM USER_1@localhost;
+DROP FUNCTION f1;
+DROP PROCEDURE p1;
+DROP USER user_1@localhost;
+DROP USER USER_1@localhost;
+DROP DATABASE db1;
+use test;

=== added file 'mysql-test/r/lowercase_mixed_tmpdir_innodb.result'
--- a/mysql-test/r/lowercase_mixed_tmpdir_innodb.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/lowercase_mixed_tmpdir_innodb.result	2009-09-09 09:38:50 +0000
@@ -0,0 +1,6 @@
+drop table if exists t1;
+create table t1 (id int) engine=InnoDB;
+insert into t1 values (1);
+create temporary table t2 engine=InnoDB select * from t1;
+drop temporary table t2;
+drop table t1;

=== modified file 'mysql-test/r/lowercase_table3.result'
--- a/mysql-test/r/lowercase_table3.result	2009-02-13 21:12:59 +0000
+++ b/mysql-test/r/lowercase_table3.result	2009-08-28 14:13:27 +0000
@@ -1,4 +1,4 @@
-call mtr.add_suppression("Cannot find or open table test/BUG29839 from .*");
+call mtr.add_suppression("Cannot find or open table test/BUG29839 from");
 DROP TABLE IF EXISTS t1,T1;
 CREATE TABLE t1 (a INT);
 SELECT * FROM T1;

=== modified file 'mysql-test/r/myisam.result'
--- a/mysql-test/r/myisam.result	2009-09-18 01:04:43 +0000
+++ b/mysql-test/r/myisam.result	2009-11-10 15:15:12 +0000
@@ -2283,4 +2283,50 @@ h+0	d + 0	e	g + 0
 1	1	3	0
 1	1	4	0
 DROP TABLE t1;
+#
+# Test of BUG#35570 CHECKSUM TABLE unreliable if LINESTRING field
+# (same content / differen checksum)
+#
+CREATE TABLE t1 (line LINESTRING NOT NULL) engine=myisam;
+INSERT INTO t1 VALUES (GeomFromText("POINT(0 0)"));
+checksum table t1;
+Table	Checksum
+test.t1	326284887
+CREATE TABLE t2 (line LINESTRING NOT NULL) engine=myisam;
+INSERT INTO t2 VALUES (GeomFromText("POINT(0 0)"));
+checksum table t2;
+Table	Checksum
+test.t2	326284887
+CREATE TABLE t3 select * from t1;
+checksum table t3;
+Table	Checksum
+test.t3	326284887
+drop table t1,t2,t3;
+CREATE TABLE t1(a INT, b CHAR(10), KEY(a), KEY(b));
+INSERT INTO t1 VALUES(1,'0'),(2,'0'),(3,'0'),(4,'0'),(5,'0'),
+(6,'0'),(7,'0');
+INSERT INTO t1 SELECT a+10,b FROM t1;
+INSERT INTO t1 SELECT a+20,b FROM t1;
+INSERT INTO t1 SELECT a+40,b FROM t1;
+INSERT INTO t1 SELECT a+80,b FROM t1;
+INSERT INTO t1 SELECT a+160,b FROM t1;
+INSERT INTO t1 SELECT a+320,b FROM t1;
+INSERT INTO t1 SELECT a+640,b FROM t1;
+INSERT INTO t1 SELECT a+1280,b FROM t1;
+INSERT INTO t1 SELECT a+2560,b FROM t1;
+INSERT INTO t1 SELECT a+5120,b FROM t1;
+SET myisam_sort_buffer_size=4;
+REPAIR TABLE t1;
+Table	Op	Msg_type	Msg_text
+test.t1	repair	error	myisam_sort_buffer_size is too small
+test.t1	repair	warning	Number of rows changed from 0 to 7168
+test.t1	repair	status	OK
+SET myisam_repair_threads=2;
+REPAIR TABLE t1;
+SET myisam_repair_threads=@@global.myisam_repair_threads;
+SET myisam_sort_buffer_size=@@global.myisam_sort_buffer_size;
+CHECK TABLE t1;
+Table	Op	Msg_type	Msg_text
+test.t1	check	status	OK
+DROP TABLE t1;
 End of 5.1 tests

=== modified file 'mysql-test/r/myisam_crash_before_flush_keys.result'
--- a/mysql-test/r/myisam_crash_before_flush_keys.result	2009-04-06 07:01:17 +0000
+++ b/mysql-test/r/myisam_crash_before_flush_keys.result	2009-10-14 11:26:16 +0000
@@ -15,31 +15,13 @@ SET SESSION debug="d,crash_before_flush_
 # Run the crashing query
 FLUSH TABLE t1;
 ERROR HY000: Lost connection to MySQL server during query
-# Run MYISAMCHK tool to check the table t1 and repair
-myisamchk: MyISAM file MYSQLD_DATADIR/test/t1
-myisamchk: warning: 1 client is using or hasn't closed the table properly
-myisamchk: error: Size of indexfile is: 1024            Should be: 3072
-MYISAMCHK: Unknown error 126
-myisamchk: error: Can't read indexpage from filepos: 1024
-MyISAM-table 'MYSQLD_DATADIR/test/t1' is corrupted
-Fix it using switch "-r" or "-o"
 # Write file to make mysql-test-run.pl start the server 
 # Turn on reconnect
 # Call script that will poll the server waiting for
 # it to be back online again
-SHOW CREATE TABLE t1;
-Table	Create Table
-t1	CREATE TABLE `t1` (
-  `a` int(11) NOT NULL DEFAULT '0',
-  `b` int(11) NOT NULL DEFAULT '0',
-  PRIMARY KEY (`a`,`b`),
-  KEY `b` (`b`)
-) ENGINE=MyISAM DEFAULT CHARSET=latin1 DELAY_KEY_WRITE=1
-SELECT * FROM t1 FORCE INDEX (PRIMARY);
-a	b
-1	2
-2	3
-3	4
-4	5
-5	6
+CHECK TABLE t1;
+Table	Op	Msg_type	Msg_text
+test.t1	check	warning	1 client is using or hasn't closed the table properly
+test.t1	check	error	Size of indexfile is: 1024        Should be: 3072
+test.t1	check	error	Corrupt
 DROP TABLE t1;

=== modified file 'mysql-test/r/mysqlbinlog.result'
--- a/mysql-test/r/mysqlbinlog.result	2009-05-08 17:24:15 +0000
+++ b/mysql-test/r/mysqlbinlog.result	2009-09-30 02:31:25 +0000
@@ -44,16 +44,16 @@ SET TIMESTAMP=1000000000/*!*/;
 insert into t2 values ()
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 DELIMITER ;
 # End of log file
@@ -144,16 +144,16 @@ SET TIMESTAMP=1000000000/*!*/;
 insert into t2 values ()
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (word)
 /*!*/;
 DELIMITER ;
 # End of log file
@@ -359,29 +359,29 @@ SET @@session.collation_database=DEFAULT
 create table t1 (a varchar(64) character set utf8)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
 SET @@session.collation_database=7/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
 SET @@session.collation_database=DEFAULT/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-#-#' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
 SET @@session.collation_database=7/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-a-0' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-a-0' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
 SET @@session.collation_database=DEFAULT/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-b-0' INTO  table t1
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-b-0' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
-load data LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-c-0' INTO  table t1 character set koi8r
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/tmp/SQL_LOAD_MB-c-0' INTO TABLE `t1` CHARACTER SET koi8r FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a)
 /*!*/;
 SET TIMESTAMP=1000000000/*!*/;
 drop table t1
@@ -473,5 +473,94 @@ IS NOT NULL
 SET @@global.server_id= 1;
 RESET MASTER;
 FLUSH LOGS;
+RESET MASTER;
+FLUSH LOGS;
+#
+# Test if the 'BEGIN', 'ROLLBACK' and 'COMMIT' are output if the database specified is exist
+/*!40019 SET @@session.max_insert_delayed_threads=0*/;
+/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
+DELIMITER /*!*/;
+ROLLBACK/*!*/;
+use test/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+SET @@session.pseudo_thread_id=999999999/*!*/;
+SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=1, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
+SET @@session.sql_mode=0/*!*/;
+SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
+/*!\C latin1 *//*!*/;
+SET @@session.character_set_client=8,@@session.collation_connection=8,@@session.collation_server=8/*!*/;
+SET @@session.lc_time_names=0/*!*/;
+SET @@session.collation_database=DEFAULT/*!*/;
+create table t1(a int) engine= innodb
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+BEGIN
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+insert into t1 (a) values (1)
+/*!*/;
+COMMIT/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+create table t3(a int) engine= innodb
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+BEGIN
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+insert into t3 (a) values (2)
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+ROLLBACK
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+create table t5(a int) engine= NDB
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+BEGIN
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+insert into t5 (a) values (3)
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+COMMIT
+/*!*/;
+DELIMITER ;
+# End of log file
+ROLLBACK /* added by mysqlbinlog */;
+/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
+#
+# Test if the 'BEGIN', 'ROLLBACK' and 'COMMIT' are output if the database specified is not exist
+/*!40019 SET @@session.max_insert_delayed_threads=0*/;
+/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,COMPLETION_TYPE=0*/;
+DELIMITER /*!*/;
+ROLLBACK/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+SET @@session.pseudo_thread_id=999999999/*!*/;
+SET @@session.foreign_key_checks=1, @@session.sql_auto_is_null=1, @@session.unique_checks=1, @@session.autocommit=1/*!*/;
+SET @@session.sql_mode=0/*!*/;
+SET @@session.auto_increment_increment=1, @@session.auto_increment_offset=1/*!*/;
+/*!\C latin1 *//*!*/;
+SET @@session.character_set_client=8,@@session.collation_connection=8,@@session.collation_server=8/*!*/;
+SET @@session.lc_time_names=0/*!*/;
+SET @@session.collation_database=DEFAULT/*!*/;
+BEGIN
+/*!*/;
+COMMIT/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+BEGIN
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+ROLLBACK
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+BEGIN
+/*!*/;
+SET TIMESTAMP=1253783037/*!*/;
+COMMIT
+/*!*/;
+DELIMITER ;
+# End of log file
+ROLLBACK /* added by mysqlbinlog */;
+/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
 End of 5.0 tests
 End of 5.1 tests

=== modified file 'mysql-test/r/mysqltest.result'
--- a/mysql-test/r/mysqltest.result	2009-05-27 20:54:40 +0000
+++ b/mysql-test/r/mysqltest.result	2009-10-08 09:30:03 +0000
@@ -314,20 +314,10 @@ here is the sourced script
 1 = outer loop variable before dec
 
 0 = outer loop variable after dec
-
-2 = outer loop variable after while
-here is the sourced script
-
-2 = outer loop variable before dec
-
-1 = outer loop variable after dec
-
-1 = outer loop variable after while
+outer=2 ifval=0
+outer=1 ifval=1
 here is the sourced script
-
-1 = outer loop variable before dec
-
-0 = outer loop variable after dec
+ERROR 42S02: Table 'test.nowhere' doesn't exist
 
 In loop
 here is the sourced script
@@ -538,6 +528,10 @@ mysqltest: At line 1: Missing required a
 mysqltest: At line 1: End of file encountered before 'EOF' delimiter was found
 Content for test_file1
 mysqltest: At line 1: File already exist: 'MYSQLTEST_VARDIR/tmp/test_file1.tmp'
+These lines should be repeated,
+if things work as expected
+These lines should be repeated,
+if things work as expected
 Some data
 for cat_file command
 of mysqltest

=== added file 'mysql-test/r/not_true.require'
--- a/mysql-test/r/not_true.require	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/not_true.require	2009-09-25 09:26:49 +0000
@@ -0,0 +1,2 @@
+TRUE
+NULL

=== modified file 'mysql-test/r/olap.result'
--- a/mysql-test/r/olap.result	2007-11-23 08:35:02 +0000
+++ b/mysql-test/r/olap.result	2009-10-30 15:59:06 +0000
@@ -733,4 +733,24 @@ SELECT 1 FROM t1 GROUP BY (DATE(NULL)) W
 1
 1
 DROP TABLE t1;
+#
+# Bug #48131: crash group by with rollup, distinct,
+#             filesort, with temporary tables
+#
+CREATE TABLE t1 (a INT NOT NULL PRIMARY KEY);
+INSERT INTO t1 VALUES (1), (2);
+CREATE TABLE t2 (b INT);
+INSERT INTO t2 VALUES (100);
+SELECT a, b FROM t1, t2 GROUP BY a, b WITH ROLLUP;
+a	b
+1	100
+1	NULL
+2	100
+2	NULL
+NULL	NULL
+SELECT DISTINCT b FROM t1, t2 GROUP BY a, b WITH ROLLUP;
+b
+100
+NULL
+DROP TABLE t1, t2;
 End of 5.0 tests

=== modified file 'mysql-test/r/order_by.result'
--- a/mysql-test/r/order_by.result	2009-08-07 11:51:40 +0000
+++ b/mysql-test/r/order_by.result	2009-10-14 14:30:39 +0000
@@ -1557,3 +1557,34 @@ a
 2001
 1991
 DROP TABLE t1;
+#
+# Bug #43029: FORCE INDEX FOR ORDER BY is ignored when join buffering 
+#   is used
+#
+CREATE TABLE t1 (a INT, b INT, KEY (a));
+INSERT INTO t1 VALUES (0, NULL), (1, NULL), (2, NULL), (3, NULL);
+INSERT INTO t1 SELECT a+4, b FROM t1;
+INSERT INTO t1 SELECT a+8, b FROM t1;
+CREATE TABLE t2 (a INT, b INT);
+INSERT INTO t2 VALUES (0,NULL), (1,NULL), (2,NULL), (3,NULL), (4,NULL);
+INSERT INTO t2 SELECT a+4, b FROM t2;
+# shouldn't have "using filesort"
+EXPLAIN 
+SELECT * FROM t1 FORCE INDEX FOR ORDER BY (a), t2 WHERE t1.a < 2 ORDER BY t1.a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	5	NULL	2	Using where
+1	SIMPLE	t2	ALL	NULL	NULL	NULL	NULL	10	
+# should have "using filesort"
+EXPLAIN 
+SELECT * FROM t1 USE INDEX FOR ORDER BY (a), t2 WHERE t1.a < 2 ORDER BY t1.a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	5	NULL	2	Using where; Using temporary; Using filesort
+1	SIMPLE	t2	ALL	NULL	NULL	NULL	NULL	10	Using join buffer
+# should have "using filesort"
+EXPLAIN 
+SELECT * FROM t1 FORCE INDEX FOR JOIN (a), t2 WHERE t1.a < 2 ORDER BY t1.a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	5	NULL	2	Using where; Using temporary; Using filesort
+1	SIMPLE	t2	ALL	NULL	NULL	NULL	NULL	10	Using join buffer
+DROP TABLE t1, t2;
+End of 5.1 tests

=== modified file 'mysql-test/r/partition.result'
--- a/mysql-test/r/partition.result	2009-10-15 21:38:29 +0000
+++ b/mysql-test/r/partition.result	2009-11-10 15:15:12 +0000
@@ -50,6 +50,21 @@ t1	CREATE TABLE `t1` (
  PARTITION p3 VALUES LESS THAN (733969) ENGINE = MyISAM,
  PARTITION pmax VALUES LESS THAN MAXVALUE ENGINE = MyISAM) */
 DROP TABLE t1;
+create table t1 (a int, b int, key(a))
+partition by list (a)
+( partition p0 values in (1),
+partition p1 values in (2));
+insert into t1 values (1,1),(2,1),(2,2),(2,3);
+show indexes from t1;
+Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_part	Packed	Null	Index_type	Comment
+t1	1	a	1	a	A	NULL	NULL	NULL	YES	BTREE	
+analyze table t1;
+Table	Op	Msg_type	Msg_text
+test.t1	analyze	status	OK
+show indexes from t1;
+Table	Non_unique	Key_name	Seq_in_index	Column_name	Collation	Cardinality	Sub_part	Packed	Null	Index_type	Comment
+t1	1	a	1	a	A	1	NULL	NULL	YES	BTREE	
+drop table t1;
 CREATE TABLE t1 (a INT, FOREIGN KEY (a) REFERENCES t0 (a))
 ENGINE=MyISAM
 PARTITION BY HASH (a);

=== modified file 'mysql-test/r/partition_csv.result'
--- a/mysql-test/r/partition_csv.result	2009-07-31 23:39:26 +0000
+++ b/mysql-test/r/partition_csv.result	2009-09-03 06:38:06 +0000
@@ -1,3 +1,4 @@
+call mtr.add_suppression("Failed to write to mysql.general_log");
 drop table if exists t1;
 create table t1 (a int)
 engine = csv

=== modified file 'mysql-test/r/partition_innodb.result'
--- a/mysql-test/r/partition_innodb.result	2008-11-10 20:13:24 +0000
+++ b/mysql-test/r/partition_innodb.result	2009-09-10 06:54:26 +0000
@@ -1,4 +1,18 @@
 drop table if exists t1;
+create table t1 (a int not null,
+b datetime not null,
+primary key (a,b))
+engine=innodb
+partition by range (to_days(b))
+subpartition by hash (a)
+subpartitions 2
+( partition p0 values less than (to_days('2009-01-01')),
+partition p1 values less than (to_days('2009-02-01')),
+partition p2 values less than (to_days('2009-03-01')),
+partition p3 values less than maxvalue);
+alter table t1 reorganize partition p1,p2 into
+( partition p2 values less than (to_days('2009-03-01')));
+drop table t1;
 CREATE TABLE t1 (id INT PRIMARY KEY, data INT) ENGINE = InnoDB 
 PARTITION BY RANGE(id) ( 
 PARTITION p0 VALUES LESS THAN (5), 
@@ -256,3 +270,7 @@ SUBPARTITION BY KEY (char_column)
 SUBPARTITIONS 2
 (PARTITION p1 VALUES LESS THAN (5) ENGINE = MyISAM) */
 drop table t1;
+CREATE TABLE t1 (a INT) ENGINE=InnoDB
+PARTITION BY list(a) (PARTITION p1 VALUES IN (1));
+CREATE INDEX i1 ON t1 (a);
+DROP TABLE t1;

=== added file 'mysql-test/r/partition_innodb_builtin.result'
--- a/mysql-test/r/partition_innodb_builtin.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/partition_innodb_builtin.result	2009-09-25 09:26:49 +0000
@@ -0,0 +1,39 @@
+SET NAMES utf8;
+CREATE TABLE `t``\""e` (a INT, PRIMARY KEY (a))
+ENGINE=InnoDB
+PARTITION BY RANGE (a)
+SUBPARTITION BY HASH (a)
+(PARTITION `p0``\""e` VALUES LESS THAN (100)
+(SUBPARTITION `sp0``\""e`,
+SUBPARTITION `sp1``\""e`),
+PARTITION `p1``\""e` VALUES LESS THAN (MAXVALUE)
+(SUBPARTITION `sp2``\""e`,
+SUBPARTITION `sp3``\""e`));
+INSERT INTO `t``\""e` VALUES (0), (2), (6), (10), (14), (18), (22);
+START TRANSACTION;
+# con1
+SET NAMES utf8;
+START TRANSACTION;
+# default connection
+UPDATE `t``\""e` SET a = 16 WHERE a = 0;
+# con1
+UPDATE `t``\""e` SET a = 8 WHERE a = 22;
+UPDATE `t``\""e` SET a = 12 WHERE a = 0;
+# default connection
+UPDATE `t``\""e` SET a = 4 WHERE a = 22;
+ERROR 40001: Deadlock found when trying to get lock; try restarting transaction
+# First table reported in 'SHOW ENGINE InnoDB STATUS'
+SHOW ENGINE InnoDB STATUS;
+Type	Name	Status
+InnoDB		index `PRIMARY` of table `test`.`t``\""e` /* Partition `p0``\""e`, Subpartition `sp0``\""e` */
+set @old_sql_mode = @@sql_mode;
+set sql_mode = 'ANSI_QUOTES';
+SHOW ENGINE InnoDB STATUS;
+Type	Name	Status
+InnoDB		index `PRIMARY` of table `test`.`t``\""e` /* Partition `p0``\""e`, Subpartition `sp0``\""e` */
+set @@sql_mode = @old_sql_mode;
+# con1
+ROLLBACK;
+# default connection
+DROP TABLE `t``\""e`;
+SET NAMES DEFAULT;

=== added file 'mysql-test/r/partition_innodb_plugin.result'
--- a/mysql-test/r/partition_innodb_plugin.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/partition_innodb_plugin.result	2009-09-25 09:26:49 +0000
@@ -0,0 +1,50 @@
+SET NAMES utf8;
+CREATE TABLE `t``\""e` (a INT, PRIMARY KEY (a))
+ENGINE=InnoDB
+PARTITION BY RANGE (a)
+SUBPARTITION BY HASH (a)
+(PARTITION `p0``\""e` VALUES LESS THAN (100)
+(SUBPARTITION `sp0``\""e`,
+SUBPARTITION `sp1``\""e`),
+PARTITION `p1``\""e` VALUES LESS THAN (MAXVALUE)
+(SUBPARTITION `sp2``\""e`,
+SUBPARTITION `sp3``\""e`));
+INSERT INTO `t``\""e` VALUES (0), (2), (6), (10), (14), (18), (22);
+START TRANSACTION;
+# con1
+SET NAMES utf8;
+START TRANSACTION;
+# default connection
+UPDATE `t``\""e` SET a = 16 WHERE a = 0;
+# con1
+UPDATE `t``\""e` SET a = 8 WHERE a = 22;
+UPDATE `t``\""e` SET a = 12 WHERE a = 0;
+# default connection
+SELECT lock_table, COUNT(*) FROM INFORMATION_SCHEMA.INNODB_LOCKS
+GROUP BY lock_table;
+lock_table	COUNT(*)
+`test`.`t``\""e` /* Partition `p0``\""e`, Subpartition `sp0``\""e` */	2
+set @old_sql_mode = @@sql_mode;
+set sql_mode = 'ANSI_QUOTES';
+SELECT lock_table, COUNT(*) FROM INFORMATION_SCHEMA.INNODB_LOCKS
+GROUP BY lock_table;
+lock_table	COUNT(*)
+"test"."t`\""""e" /* Partition "p0`\""""e", Subpartition "sp0`\""""e" */	2
+set @@sql_mode = @old_sql_mode;
+UPDATE `t``\""e` SET a = 4 WHERE a = 22;
+ERROR 40001: Deadlock found when trying to get lock; try restarting transaction
+# First table reported in 'SHOW ENGINE InnoDB STATUS'
+SHOW ENGINE InnoDB STATUS;
+Type	Name	Status
+InnoDB		index `PRIMARY` of table `test`.`t``\""e` /* Partition `p0``\""e`, Subpartition `sp0``\""e` */
+set @old_sql_mode = @@sql_mode;
+set sql_mode = 'ANSI_QUOTES';
+SHOW ENGINE InnoDB STATUS;
+Type	Name	Status
+InnoDB		index `PRIMARY` of table `test`.`t``\""e` /* Partition `p0``\""e`, Subpartition `sp0``\""e` */
+set @@sql_mode = @old_sql_mode;
+# con1
+ROLLBACK;
+# default connection
+DROP TABLE `t``\""e`;
+SET NAMES DEFAULT;

=== added file 'mysql-test/r/partition_open_files_limit.result'
--- a/mysql-test/r/partition_open_files_limit.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/partition_open_files_limit.result	2009-10-08 13:36:43 +0000
@@ -0,0 +1,22 @@
+DROP TABLE IF EXISTS `t1`;
+# Bug#46922: crash when adding partitions and open_files_limit is reached
+CREATE TABLE t1 (a INT PRIMARY KEY) 
+ENGINE=MyISAM PARTITION BY KEY () PARTITIONS 1;
+INSERT INTO t1 VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11);
+# if the bug exists, then crash will happen here
+ALTER TABLE t1 ADD PARTITION PARTITIONS 511;
+ERROR HY000: Out of resources when opening file '<partition file>' (Errcode: 24)
+SELECT * FROM t1;
+a
+1
+10
+11
+2
+3
+4
+5
+6
+7
+8
+9
+DROP TABLE t1;

=== modified file 'mysql-test/r/partition_pruning.result'
--- a/mysql-test/r/partition_pruning.result	2009-09-01 12:53:27 +0000
+++ b/mysql-test/r/partition_pruning.result	2009-10-16 20:19:51 +0000
@@ -1272,10 +1272,9 @@ INSERT INTO t1 VALUES (1, '2009-01-01'),
 # test with an invalid date, which lead to item->null_value is set.
 EXPLAIN PARTITIONS SELECT * FROM t1 WHERE b < CAST('2009-04-99' AS DATETIME);
 id	select_type	table	partitions	type	possible_keys	key	key_len	ref	rows	Extra
-1	SIMPLE	t1	p20090401	ALL	NULL	NULL	NULL	NULL	2	Using where
+1	SIMPLE	NULL	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
 Warnings:
 Warning	1292	Incorrect datetime value: '2009-04-99'
-Warning	1292	Incorrect datetime value: '2009-04-99'
 DROP TABLE t1;
 CREATE TABLE t1
 (a INT NOT NULL AUTO_INCREMENT,

=== modified file 'mysql-test/r/ps_grant.result'
--- a/mysql-test/r/ps_grant.result	2006-08-23 13:50:06 +0000
+++ b/mysql-test/r/ps_grant.result	2009-10-27 10:09:36 +0000
@@ -32,19 +32,19 @@ identified by 'looser' ;
 show grants for second_user@localhost ;
 Grants for second_user@localhost
 GRANT USAGE ON *.* TO 'second_user'@'localhost' IDENTIFIED BY PASSWORD '*13843FE600B19A81E32AF50D4A6FED25875FF1F3'
-GRANT SELECT ON `mysqltest`.`t1` TO 'second_user'@'localhost'
 GRANT SELECT ON `mysqltest`.`t9` TO 'second_user'@'localhost'
+GRANT SELECT ON `mysqltest`.`t1` TO 'second_user'@'localhost'
 drop table mysqltest.t9 ;
 show grants for second_user@localhost ;
 Grants for second_user@localhost
 GRANT USAGE ON *.* TO 'second_user'@'localhost' IDENTIFIED BY PASSWORD '*13843FE600B19A81E32AF50D4A6FED25875FF1F3'
-GRANT SELECT ON `mysqltest`.`t1` TO 'second_user'@'localhost'
 GRANT SELECT ON `mysqltest`.`t9` TO 'second_user'@'localhost'
+GRANT SELECT ON `mysqltest`.`t1` TO 'second_user'@'localhost'
 show grants for second_user@localhost ;
 Grants for second_user@localhost
 GRANT USAGE ON *.* TO 'second_user'@'localhost' IDENTIFIED BY PASSWORD '*13843FE600B19A81E32AF50D4A6FED25875FF1F3'
-GRANT SELECT ON `mysqltest`.`t1` TO 'second_user'@'localhost'
 GRANT SELECT ON `mysqltest`.`t9` TO 'second_user'@'localhost'
+GRANT SELECT ON `mysqltest`.`t1` TO 'second_user'@'localhost'
 prepare s_t1 from 'select a as my_col from t1' ;
 execute s_t1 ;
 my_col

=== modified file 'mysql-test/r/query_cache.result'
--- a/mysql-test/r/query_cache.result	2009-02-19 09:01:25 +0000
+++ b/mysql-test/r/query_cache.result	2009-11-10 15:15:12 +0000
@@ -1708,6 +1708,7 @@ Qcache_hits	2
 DROP TABLE t1;
 SET GLOBAL query_cache_size= default;
 End of 5.0 tests
+SET GLOBAL query_cache_size=1024*1024*512;
 CREATE TABLE t1 (a ENUM('rainbow'));
 INSERT INTO t1 VALUES (),(),(),(),();
 SELECT 1 FROM t1 GROUP BY (SELECT 1 FROM t1 ORDER BY AVG(LAST_INSERT_ID()));
@@ -1722,4 +1723,5 @@ SELECT 1 FROM t1 GROUP BY
 1
 1
 DROP TABLE t1;
+SET GLOBAL query_cache_size= default;
 End of 5.1 tests

=== modified file 'mysql-test/r/range.result'
--- a/mysql-test/r/range.result	2008-03-27 02:18:46 +0000
+++ b/mysql-test/r/range.result	2009-11-02 12:24:07 +0000
@@ -1219,3 +1219,388 @@ explain select * from t2 where a=1000 an
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	SIMPLE	t2	ref	a	a	5	const	502	Using where
 drop table t1, t2;
+CREATE TABLE t1( a INT, b INT, KEY( a, b ) );
+CREATE TABLE t2( a INT, b INT, KEY( a, b ) );
+CREATE TABLE t3( a INT, b INT, KEY( a, b ) );
+INSERT INTO t1( a, b ) 
+VALUES (0, 1), (1, 2), (1, 4), (2, 3), (5, 0), (9, 7);
+INSERT INTO t2( a, b ) 
+VALUES ( 1, 1), ( 2, 1), ( 3, 1), ( 4, 1), ( 5, 1),
+( 6, 1), ( 7, 1), ( 8, 1), ( 9, 1), (10, 1), 
+(11, 1), (12, 1), (13, 1), (14, 1), (15, 1),
+(16, 1), (17, 1), (18, 1), (19, 1), (20, 1);
+INSERT INTO t2 SELECT a, 2 FROM t2 WHERE b = 1;
+INSERT INTO t2 SELECT a, 3 FROM t2 WHERE b = 1;
+INSERT INTO t2 SELECT -1, -1 FROM t2;
+INSERT INTO t2 SELECT -1, -1 FROM t2;
+INSERT INTO t2 SELECT -1, -1 FROM t2;
+INSERT INTO t3
+VALUES (1, 0), (2, 0), (3, 0), (4, 0), (5, 0),
+(6, 0), (7, 0), (8, 0), (9, 0), (10, 0);
+INSERT INTO t3 SELECT * FROM t3 WHERE a = 10;
+INSERT INTO t3 SELECT * FROM t3 WHERE a = 10;
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 < a AND b = 3 OR
+3 <= a;
+a	b
+5	0
+9	7
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 < a AND b = 3 OR
+3 <= a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	5	NULL	3	Using where; Using index
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+a	b
+5	0
+9	7
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	5	NULL	4	Using where; Using index
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+a	b
+5	0
+9	7
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	5	NULL	3	Using where; Using index
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+3 <= a;
+a	b
+5	0
+9	7
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+3 <= a;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	5	NULL	3	Using where; Using index
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 1 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+a	b
+1	1
+2	1
+3	1
+4	1
+5	1
+6	1
+7	1
+8	1
+9	1
+10	1
+11	1
+12	1
+13	1
+14	1
+15	1
+15	3
+16	1
+16	3
+17	1
+17	3
+18	1
+18	3
+19	1
+19	3
+20	1
+EXPLAIN
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 1 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t2	range	a	a	10	NULL	50	Using where; Using index
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 2 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+a	b
+1	1
+2	1
+3	1
+4	1
+5	1
+5	2
+6	1
+6	2
+7	1
+7	2
+8	1
+8	2
+9	1
+9	2
+10	1
+11	1
+12	1
+13	1
+14	1
+15	1
+15	3
+16	1
+16	3
+17	1
+17	3
+18	1
+18	3
+19	1
+19	3
+20	1
+EXPLAIN
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 2 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t2	range	a	a	10	NULL	50	Using where; Using index
+SELECT * FROM t3 WHERE
+5 <= a AND a < 10 AND b = 3 OR 
+a < 5 OR
+a < 10;
+a	b
+1	0
+2	0
+3	0
+4	0
+5	0
+6	0
+7	0
+8	0
+9	0
+EXPLAIN
+SELECT * FROM t3 WHERE
+5 <= a AND a < 10 AND b = 3 OR 
+a < 5 OR
+a < 10;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t3	range	a	a	5	NULL	8	Using where; Using index
+DROP TABLE t1, t2, t3;
+#
+# Bug #47123: Endless 100% CPU loop with STRAIGHT_JOIN
+#
+CREATE TABLE t1(a INT, KEY(a));
+INSERT INTO t1 VALUES (1), (NULL);
+SELECT * FROM t1 WHERE a <> NULL and (a <> NULL or a <= NULL);
+a
+DROP TABLE t1;
+#
+# Bug#47925: regression of range optimizer and date comparison in 5.1.39!
+#
+CREATE TABLE t1 ( a DATE,     KEY ( a ) );
+CREATE TABLE t2 ( a DATETIME, KEY ( a ) );
+# Make optimizer choose range scan
+INSERT INTO t1 VALUES ('2009-09-22'), ('2009-09-22'), ('2009-09-22');
+INSERT INTO t1 VALUES ('2009-09-23'), ('2009-09-23'), ('2009-09-23');
+INSERT INTO t2 VALUES ('2009-09-22 12:00:00'), ('2009-09-22 12:00:00'),
+('2009-09-22 12:00:00');
+INSERT INTO t2 VALUES ('2009-09-23 12:00:00'), ('2009-09-23 12:00:00'),
+('2009-09-23 12:00:00');
+# DATE vs DATE
+EXPLAIN
+SELECT * FROM t1 WHERE a >= '2009/09/23';
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+X	X	X	range	a	a	X	X	X	X
+SELECT * FROM t1 WHERE a >= '2009/09/23';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '20090923';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >=  20090923;
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '2009-9-23';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '2009.09.23';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '2009:09:23';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+# DATE vs DATETIME
+EXPLAIN
+SELECT * FROM t2 WHERE a >= '2009/09/23';
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+X	X	X	range	a	a	X	X	X	X
+SELECT * FROM t2 WHERE a >= '2009/09/23';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '2009/09/23';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '20090923';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >=  20090923;
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '2009-9-23';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '2009.09.23';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '2009:09:23';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+# DATETIME vs DATETIME
+EXPLAIN
+SELECT * FROM t2 WHERE a >= '2009/09/23 12:00:00';
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+X	X	X	range	a	a	X	X	X	X
+SELECT * FROM t2 WHERE a >= '2009/09/23 12:00:00';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '20090923120000';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >=  20090923120000;
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '2009-9-23 12:00:00';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '2009.09.23 12:00:00';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+SELECT * FROM t2 WHERE a >= '2009:09:23 12:00:00';
+a
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+2009-09-23 12:00:00
+# DATETIME vs DATE
+EXPLAIN
+SELECT * FROM t1 WHERE a >= '2009/09/23 00:00:00';
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+X	X	X	range	a	a	X	X	X	X
+SELECT * FROM t1 WHERE a >= '2009/09/23 00:00:00';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '2009/09/23 00:00:00';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '20090923000000';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >=  20090923000000;
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '2009-9-23 00:00:00';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '2009.09.23 00:00:00';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+SELECT * FROM t1 WHERE a >= '2009:09:23 00:00:00';
+a
+2009-09-23
+2009-09-23
+2009-09-23
+# Test of the new get_date_from_str implementation
+# Behavior differs slightly between the trunk and mysql-pe.
+# The former may give errors for the truncated values, while the latter
+# gives warnings. The purpose of this test is not to interfere, and only
+# preserve existing behavior.
+SELECT str_to_date('2007-10-00', '%Y-%m-%d') >= '' AND 
+str_to_date('2007-10-00', '%Y-%m-%d') <= '2007/10/20';
+str_to_date('2007-10-00', '%Y-%m-%d') >= '' AND 
+str_to_date('2007-10-00', '%Y-%m-%d') <= '2007/10/20'
+1
+Warnings:
+Warning	1292	Truncated incorrect date value: ''
+SELECT str_to_date('2007-20-00', '%Y-%m-%d') >= '2007/10/20' AND 
+str_to_date('2007-20-00', '%Y-%m-%d') <= '';
+str_to_date('2007-20-00', '%Y-%m-%d') >= '2007/10/20' AND 
+str_to_date('2007-20-00', '%Y-%m-%d') <= ''
+NULL
+Warnings:
+Warning	1292	Truncated incorrect date value: ''
+Error	1411	Incorrect datetime value: '2007-20-00' for function str_to_date
+Error	1411	Incorrect datetime value: '2007-20-00' for function str_to_date
+SELECT str_to_date('2007-10-00', '%Y-%m-%d') BETWEEN '' AND '2007/10/20';
+str_to_date('2007-10-00', '%Y-%m-%d') BETWEEN '' AND '2007/10/20'
+1
+Warnings:
+Warning	1292	Truncated incorrect datetime value: ''
+SELECT str_to_date('2007-20-00', '%Y-%m-%d') BETWEEN '2007/10/20' AND '';
+str_to_date('2007-20-00', '%Y-%m-%d') BETWEEN '2007/10/20' AND ''
+NULL
+Warnings:
+Error	1411	Incorrect datetime value: '2007-20-00' for function str_to_date
+SELECT str_to_date('', '%Y-%m-%d');
+str_to_date('', '%Y-%m-%d')
+0000-00-00
+DROP TABLE t1, t2;
+End of 5.1 tests

=== modified file 'mysql-test/r/select.result'
--- a/mysql-test/r/select.result	2009-09-15 10:46:35 +0000
+++ b/mysql-test/r/select.result	2009-11-10 15:15:12 +0000
@@ -4385,6 +4385,47 @@ id	select_type	table	type	possible_keys	
 Warnings:
 Note	1003	select `test`.`t1`.`a` AS `a`,`test`.`t1`.`b` AS `b` from `test`.`t1` where ((`test`.`t1`.`a` = `test`.`t1`.`b`) and (`test`.`t1`.`a` > 1)) limit 2
 DROP TABLE t1;
+#
+# Bug#47019: Assertion failed: 0, file .\rt_mbr.c, line 138 when 
+# forcing a spatial index
+#
+CREATE TABLE t1(a LINESTRING NOT NULL, SPATIAL KEY(a));
+INSERT INTO t1 VALUES
+(GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)')),
+(GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)'));
+EXPLAIN SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	NULL	NULL	NULL	NULL	2	
+1	SIMPLE	t2	ALL	a	NULL	NULL	NULL	2	
+SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2;
+1
+1
+1
+1
+1
+EXPLAIN SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2 FORCE INDEX(a);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ALL	NULL	NULL	NULL	NULL	2	
+1	SIMPLE	t2	ALL	a	NULL	NULL	NULL	2	
+SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2 FORCE INDEX(a);
+1
+1
+1
+1
+1
+DROP TABLE t1;
+#
+# Bug #48291 : crash with row() operator,select into @var, and 
+#   subquery returning multiple rows
+#
+CREATE TABLE t1(a INT);
+INSERT INTO t1 VALUES (2),(3);
+# Should not crash
+SELECT 1 FROM t1 WHERE a <> 1 AND NOT
+ROW(a,a) <=> ROW((SELECT 1 FROM t1 WHERE 1=2),(SELECT 1 FROM t1))
+INTO @var0;
+ERROR 21000: Subquery returns more than 1 row
+DROP TABLE t1;
 End of 5.0 tests
 create table t1(a INT, KEY (a));
 INSERT INTO t1 VALUES (1),(2),(3),(4),(5);

=== added file 'mysql-test/r/sp-bugs.result'
--- a/mysql-test/r/sp-bugs.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/sp-bugs.result	2009-10-26 09:55:57 +0000
@@ -0,0 +1,47 @@
+#
+# Bug #47412: Valgrind warnings / user can read uninitalized memory
+# using SP variables
+#
+CREATE SCHEMA testdb;
+USE testdb;
+CREATE FUNCTION f2 () RETURNS INTEGER
+BEGIN
+DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
+RETURN f_not_exists () ;
+END|
+CREATE PROCEDURE p3 ( arg1 VARCHAR(32) )
+BEGIN
+CALL p_not_exists ( );
+END|
+# should not return valgrind warnings
+CALL p3 ( f2 () );
+ERROR 42000: PROCEDURE testdb.p_not_exists does not exist
+DROP SCHEMA testdb;
+CREATE SCHEMA testdb;
+USE testdb;
+CREATE FUNCTION f2 () RETURNS INTEGER
+BEGIN
+DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
+RETURN f_not_exists () ;
+END|
+CREATE PROCEDURE p3 ( arg2 INTEGER )
+BEGIN
+CALL p_not_exists ( );
+END|
+# should not return valgrind warnings
+CALL p3 ( f2 () );
+ERROR 42000: PROCEDURE testdb.p_not_exists does not exist
+DROP SCHEMA testdb;
+CREATE SCHEMA testdb;
+USE testdb;
+CREATE FUNCTION f2 () RETURNS INTEGER
+BEGIN
+DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
+RETURN f_not_exists () ;
+END|
+# should not return valgrind warnings
+SELECT f2 ();
+f2 ()
+NULL
+DROP SCHEMA testdb;
+End of 5.1 tests

=== modified file 'mysql-test/r/sp-error.result'
--- a/mysql-test/r/sp-error.result	2009-05-27 15:19:44 +0000
+++ b/mysql-test/r/sp-error.result	2009-10-19 13:55:04 +0000
@@ -1670,3 +1670,19 @@ NULL
 SELECT non_existent (a) FROM t1 WHERE b = 999999;
 ERROR 42000: FUNCTION test.non_existent does not exist
 DROP TABLE t1;
+#
+# Bug #47788: Crash in TABLE_LIST::hide_view_error on UPDATE + VIEW + 
+#   SP + MERGE + ALTER
+#
+CREATE TABLE t1 (pk INT, b INT, KEY (b));
+CREATE ALGORITHM = TEMPTABLE VIEW v1 AS SELECT * FROM t1;
+CREATE PROCEDURE p1 (a int) UPDATE IGNORE v1 SET b = a;
+CALL p1(5);
+ERROR HY000: The target table v1 of the UPDATE is not updatable
+ALTER TABLE t1 CHANGE COLUMN b b2 INT;
+CALL p1(7);
+ERROR HY000: View 'test.v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+DROP PROCEDURE p1;
+DROP VIEW v1;
+DROP TABLE t1;
+End of 5.1 tests

=== modified file 'mysql-test/r/sp.result'
--- a/mysql-test/r/sp.result	2009-06-04 11:53:15 +0000
+++ b/mysql-test/r/sp.result	2009-10-23 13:54:58 +0000
@@ -6963,6 +6963,22 @@ CALL p1();
 CALL p1();
 DROP PROCEDURE p1;
 DROP TABLE t1;
+#
+# Bug #46629: Item_in_subselect::val_int(): Assertion `0' 
+# on subquery inside a SP
+#
+CREATE TABLE t1(a INT);
+CREATE TABLE t2(a INT, b INT PRIMARY KEY);
+CREATE PROCEDURE p1 () 
+BEGIN 
+SELECT a FROM t1 A WHERE A.b IN (SELECT b FROM t2 AS B);
+END|
+CALL p1;
+ERROR 42S22: Unknown column 'A.b' in 'IN/ALL/ANY subquery'
+CALL p1;
+ERROR 42S22: Unknown column 'A.b' in 'IN/ALL/ANY subquery'
+DROP PROCEDURE p1;
+DROP TABLE t1, t2;
 # ------------------------------------------------------------------
 # -- End of 5.1 tests
 # ------------------------------------------------------------------

=== modified file 'mysql-test/r/subselect.result'
--- a/mysql-test/r/subselect.result	2009-10-15 21:38:29 +0000
+++ b/mysql-test/r/subselect.result	2009-11-10 15:15:12 +0000
@@ -75,7 +75,7 @@ SELECT 1 FROM (SELECT 1 as a) b WHERE 1 
 select (SELECT 1 FROM (SELECT 1) a PROCEDURE ANALYSE(1));
 ERROR HY000: Incorrect usage of PROCEDURE and subquery
 SELECT 1 FROM (SELECT 1) a PROCEDURE ANALYSE((SELECT 1));
-ERROR HY000: Incorrect usage of PROCEDURE and subquery
+ERROR HY000: Incorrect parameters to procedure 'ANALYSE'
 SELECT (SELECT 1) as a FROM (SELECT 1) b WHERE (SELECT a) IS NULL;
 ERROR 42S22: Unknown column 'a' in 'field list'
 SELECT (SELECT 1) as a FROM (SELECT 1) b WHERE (SELECT a) IS NOT NULL;
@@ -4403,8 +4403,7 @@ FROM t1 
 WHERE a = 230;
 id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
 1	PRIMARY	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
-2	DEPENDENT SUBQUERY	st1	index	NULL	a	5	NULL	2	Using index
-2	DEPENDENT SUBQUERY	st2	index	b	b	5	NULL	2	Using where; Using index; Using join buffer
+2	DEPENDENT SUBQUERY	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE noticed after reading const tables
 SELECT MAX(b), (SELECT COUNT(*) FROM st1,st2 WHERE st2.b <= t1.b)
 FROM t1 
 WHERE a = 230;
@@ -4561,4 +4560,18 @@ id	g	v	s
 51	50	NULL	l
 61	60	NULL	l
 drop table t1, t2;
+CREATE TABLE t1 (a ENUM('rainbow'));
+INSERT INTO t1 VALUES (),(),(),(),();
+SELECT 1 FROM t1 GROUP BY (SELECT 1 FROM t1 ORDER BY AVG(LAST_INSERT_ID()));
+1
+1
+DROP TABLE t1;
+CREATE TABLE t1 (a LONGBLOB);
+INSERT INTO t1 SET a = 'aaaa';
+INSERT INTO t1 SET a = 'aaaa';
+SELECT 1 FROM t1 GROUP BY
+(SELECT LAST_INSERT_ID() FROM t1 ORDER BY MIN(a) ASC LIMIT 1);
+1
+1
+DROP TABLE t1;
 End of 5.1 tests.

=== modified file 'mysql-test/r/subselect3.result'
--- a/mysql-test/r/subselect3.result	2009-10-15 21:38:29 +0000
+++ b/mysql-test/r/subselect3.result	2009-11-10 15:15:12 +0000
@@ -895,3 +895,72 @@ t1.a < (select t4.a+10                  
 from t4, t5 limit 2));
 ERROR 21000: Subquery returns more than 1 row
 drop table t0, t1, t2, t3, t4, t5;
+# 
+# BUG#48177 - SELECTs with NOT IN subqueries containing NULL 
+#             values return too many records
+# 
+CREATE TABLE t1 (
+i1 int DEFAULT NULL,
+i2 int DEFAULT NULL
+) ;
+INSERT INTO t1 VALUES (1,    NULL);
+INSERT INTO t1 VALUES (2,    3);
+INSERT INTO t1 VALUES (4,    NULL);
+INSERT INTO t1 VALUES (4,    0);
+INSERT INTO t1 VALUES (NULL, NULL);
+CREATE TABLE t2 (
+i1 int DEFAULT NULL,
+i2 int DEFAULT NULL
+) ;
+INSERT INTO t2 VALUES (4, NULL);
+INSERT INTO t2 VALUES (5, 0);
+
+Data in t1
+SELECT i1, i2 FROM t1;
+i1	i2
+1	NULL
+2	3
+4	NULL
+4	0
+NULL	NULL
+
+Data in subquery (should be filtered out)
+SELECT i1, i2 FROM t2 ORDER BY i1;
+i1	i2
+4	NULL
+5	0
+FLUSH STATUS;
+
+SELECT i1, i2
+FROM t1
+WHERE (i1, i2) 
+NOT IN (SELECT i1, i2 FROM t2);
+i1	i2
+1	NULL
+2	3
+
+# Check that the subquery only has to be evaluated once 
+# for all-NULL values even though there are two (NULL,NULL) records
+# Baseline:
+SHOW STATUS LIKE '%Handler_read_rnd_next';
+Variable_name	Value
+Handler_read_rnd_next	17
+
+INSERT INTO t1 VALUES (NULL, NULL);
+FLUSH STATUS;
+
+SELECT i1, i2
+FROM t1
+WHERE (i1, i2) 
+NOT IN (SELECT i1, i2 FROM t2);
+i1	i2
+1	NULL
+2	3
+
+# Handler_read_rnd_next should be one more than baseline 
+# (read record from t1, but do not read from t2)
+SHOW STATUS LIKE '%Handler_read_rnd_next';
+Variable_name	Value
+Handler_read_rnd_next	18
+DROP TABLE t1,t2;
+End of 5.1 tests

=== added file 'mysql-test/r/subselect4.result'
--- a/mysql-test/r/subselect4.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/subselect4.result	2009-09-28 13:48:40 +0000
@@ -0,0 +1,61 @@
+#
+# Bug #46791: Assertion failed:(table->key_read==0),function unknown
+#    function,file sql_base.cc
+#
+CREATE TABLE t1 (a INT, b INT, KEY(a));
+INSERT INTO t1 VALUES (1,1),(2,2);
+CREATE TABLE t2 LIKE t1;
+INSERT INTO t2 VALUES (1,1),(2,2);
+CREATE TABLE t3 LIKE t1;
+# should have 1 impossible where and 2 dependent subqueries
+EXPLAIN
+SELECT 1 FROM t1
+WHERE NOT EXISTS (SELECT 1 FROM t2 WHERE 1 = (SELECT MIN(t2.b) FROM t3))
+ORDER BY count(*);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	PRIMARY	t1	index	NULL	a	5	NULL	2	Using index; Using temporary
+2	DEPENDENT SUBQUERY	t2	ALL	NULL	NULL	NULL	NULL	2	Using where
+3	DEPENDENT SUBQUERY	NULL	NULL	NULL	NULL	NULL	NULL	NULL	no matching row in const table
+# should not crash the next statement
+SELECT 1 FROM t1
+WHERE NOT EXISTS (SELECT 1 FROM t2 WHERE 1 = (SELECT MIN(t2.b) FROM t3))
+ORDER BY count(*);
+1
+1
+# should not crash: the crash is caused by the previous statement
+SELECT 1;
+1
+1
+DROP TABLE t1,t2,t3;
+#
+# Bug #47106: Crash / segfault on adding EXPLAIN to a non-crashing 
+# query
+#
+CREATE TABLE t1 (
+a INT,
+b INT,
+PRIMARY KEY (a),
+KEY b (b)
+);
+INSERT INTO t1 VALUES (1, 1), (2, 1);
+CREATE TABLE t2 LIKE t1;
+INSERT INTO t2 SELECT * FROM t1;
+CREATE TABLE t3 LIKE t1;
+INSERT INTO t3 SELECT * FROM t1;
+# Should not crash.
+# Should have 1 impossible where and 2 dependent subqs.
+EXPLAIN
+SELECT
+(SELECT 1 FROM t1,t2 WHERE t2.b > t3.b)
+FROM t3 WHERE 1 = 0 GROUP BY 1;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	PRIMARY	NULL	NULL	NULL	NULL	NULL	NULL	NULL	Impossible WHERE
+2	DEPENDENT SUBQUERY	t1	index	NULL	PRIMARY	4	NULL	2	Using index
+2	DEPENDENT SUBQUERY	t2	index	b	b	5	NULL	2	Using where; Using index; Using join buffer
+# should return 0 rows
+SELECT
+(SELECT 1 FROM t1,t2 WHERE t2.b > t3.b)
+FROM t3 WHERE 1 = 0 GROUP BY 1;
+(SELECT 1 FROM t1,t2 WHERE t2.b > t3.b)
+DROP TABLE t1,t2,t3;
+End of 5.0 tests.

=== modified file 'mysql-test/r/system_mysql_db.result'
--- a/mysql-test/r/system_mysql_db.result	2009-03-11 20:30:56 +0000
+++ b/mysql-test/r/system_mysql_db.result	2009-10-27 10:09:36 +0000
@@ -161,7 +161,7 @@ procs_priv	CREATE TABLE `procs_priv` (
   `Host` char(60) COLLATE utf8_bin NOT NULL DEFAULT '',
   `Db` char(64) COLLATE utf8_bin NOT NULL DEFAULT '',
   `User` char(16) COLLATE utf8_bin NOT NULL DEFAULT '',
-  `Routine_name` char(64) COLLATE utf8_bin NOT NULL DEFAULT '',
+  `Routine_name` char(64) CHARACTER SET utf8 NOT NULL DEFAULT '',
   `Routine_type` enum('FUNCTION','PROCEDURE') COLLATE utf8_bin NOT NULL,
   `Grantor` char(77) COLLATE utf8_bin NOT NULL DEFAULT '',
   `Proc_priv` set('Execute','Alter Routine','Grant') CHARACTER SET utf8 NOT NULL DEFAULT '',

=== modified file 'mysql-test/r/trigger_notembedded.result'
--- a/mysql-test/r/trigger_notembedded.result	2009-06-25 10:52:50 +0000
+++ b/mysql-test/r/trigger_notembedded.result	2009-09-17 11:33:23 +0000
@@ -180,8 +180,6 @@ NULL	mysqltest_db1	trg5	DELETE	NULL	mysq
 DROP USER mysqltest_dfn@localhost;
 DROP USER mysqltest_inv@localhost;
 DROP DATABASE mysqltest_db1;
-Warnings:
-Warning	1454	No definer attribute for trigger 'mysqltest_db1'.'trg1'. The trigger will be activated under the authorization of the invoker, which may have insufficient privileges. Please recreate the trigger.
 DELETE FROM mysql.user WHERE User LIKE 'mysqltest_%';
 DELETE FROM mysql.db WHERE User LIKE 'mysqltest_%';
 DELETE FROM mysql.tables_priv WHERE User LIKE 'mysqltest_%';

=== modified file 'mysql-test/r/type_bit.result'
--- a/mysql-test/r/type_bit.result	2008-12-09 13:31:22 +0000
+++ b/mysql-test/r/type_bit.result	2009-10-08 15:36:36 +0000
@@ -749,6 +749,16 @@ bin(a1)
 110000111111111
 110001011111111
 drop table t1bit7, t2bit7;
+#
+# Bug42803: Field_bit does not have unsigned_flag field, 
+# can lead to bad memory access
+#
+CREATE TABLE t1 (a BIT(7), b BIT(9), KEY(a, b));
+INSERT INTO t1 VALUES(0, 0), (5, 3), (5, 6), (6, 4), (7, 0);
+EXPLAIN SELECT a+0, b+0 FROM t1 WHERE a > 4 and b < 7 ORDER BY 2;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	range	a	a	2	NULL	4	Using where; Using index; Using filesort
+DROP TABLE t1;
 End of 5.0 tests
 create table t1(a bit(7));
 insert into t1 values(0x40);

=== modified file 'mysql-test/r/type_newdecimal.result'
--- a/mysql-test/r/type_newdecimal.result	2009-08-24 19:47:08 +0000
+++ b/mysql-test/r/type_newdecimal.result	2009-11-02 11:21:39 +0000
@@ -1495,9 +1495,9 @@ CREATE TABLE t1 (a int DEFAULT NULL, b i
 INSERT INTO t1 VALUES (3,30), (1,10), (2,10);
 SELECT a+CAST(1 AS decimal(65,30)) AS aa, SUM(b) FROM t1 GROUP BY aa;
 aa	SUM(b)
-2.00000000000000000000000000000	10
-3.00000000000000000000000000000	10
-4.00000000000000000000000000000	30
+2.000000000000000000000000000000	10
+3.000000000000000000000000000000	10
+4.000000000000000000000000000000	30
 SELECT a+CAST(1 AS decimal(65,31)) AS aa, SUM(b) FROM t1 GROUP BY aa;
 ERROR 42000: Too big scale 31 specified for column '1'. Maximum is 30.
 DROP TABLE t1;
@@ -1521,13 +1521,13 @@ f1
 DROP TABLE t1;
 CREATE TABLE t1 SELECT 123451234512345123451234512345123451234512345.678906789067890678906789067890678906789067890 AS f1;
 Warnings:
-Note	1265	Data truncated for column 'f1' at row 1
+Warning	1264	Out of range value for column 'f1' at row 1
 DESC t1;
 Field	Type	Null	Key	Default	Extra
-f1	decimal(65,20)	NO		0.00000000000000000000	
+f1	decimal(65,30)	NO		0.000000000000000000000000000000	
 SELECT f1 FROM t1;
 f1
-123451234512345123451234512345123451234512345.67890678906789067891
+99999999999999999999999999999999999.999999999999999999999999999999
 DROP TABLE t1;
 select (1.20396873 * 0.89550000 * 0.68000000 * 1.08721696 * 0.99500000 *
 1.01500000 * 1.01500000 * 0.99500000);
@@ -1595,7 +1595,7 @@ Warnings:
 Note	1265	Data truncated for column 'my_col' at row 1
 DESCRIBE t1;
 Field	Type	Null	Key	Default	Extra
-my_col	decimal(32,30)	NO		0.000000000000000000000000000000	
+my_col	decimal(65,30)	NO		0.000000000000000000000000000000	
 SELECT my_col FROM t1;
 my_col
 1.123456789123456789123456789123
@@ -1625,212 +1625,8 @@ Warnings:
 Note	1265	Data truncated for column 'my_col' at row 1
 DESCRIBE t1;
 Field	Type	Null	Key	Default	Extra
-my_col	decimal(30,30)	YES		NULL	
+my_col	decimal(65,30)	YES		NULL	
 SELECT my_col FROM t1;
 my_col
 0.012345687012345687012345687012
 DROP TABLE t1;
-#
-# Bug#45261: Crash, stored procedure + decimal
-#
-DROP TABLE IF EXISTS t1;
-CREATE TABLE t1 SELECT
-/* 81 */ 100000000000000000000000000000000000000000000000000000000000000000000000000000001
-AS c1;
-Warnings:
-Warning	1264	Out of range value for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,0)	NO		0	
-SELECT * FROM t1;
-c1
-99999999999999999999999999999999999999999999999999999999999999999
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 81 */ 100000000000000000000000000000000000000000000000000000000000000000000000000000001.
-AS c1;
-Warnings:
-Warning	1264	Out of range value for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,0)	NO		0	
-SELECT * FROM t1;
-c1
-99999999999999999999999999999999999999999999999999999999999999999
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 81 */ 100000000000000000000000000000000000000000000000000000000000000000000000000000001.1 /* 1 */
-AS c1;
-Warnings:
-Warning	1264	Out of range value for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,0)	NO		0	
-SELECT * FROM t1;
-c1
-99999999999999999999999999999999999999999999999999999999999999999
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 82 */ 1000000000000000000000000000000000000000000000000000000000000000000000000000000001
-AS c1;
-Warnings:
-Error	1292	Truncated incorrect DECIMAL value: ''
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,0)	NO		0	
-SELECT * FROM t1;
-c1
-99999999999999999999999999999999999999999999999999999999999999999
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 40 */ 1000000000000000000000000000000000000001.1000000000000000000000000000000000000001 /* 40 */
-AS c1;
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,25)	NO		0.0000000000000000000000000	
-SELECT * FROM t1;
-c1
-1000000000000000000000000000000000000001.1000000000000000000000000
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 1 */ 1.10000000000000000000000000000000000000000000000000000000000000000000000000000001 /* 80 */
-AS c1;
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(31,30)	NO		0.000000000000000000000000000000	
-SELECT * FROM t1;
-c1
-1.100000000000000000000000000000
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 1 */ 1.100000000000000000000000000000000000000000000000000000000000000000000000000000001 /* 81 */
-AS c1;
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(31,30)	NO		0.000000000000000000000000000000	
-SELECT * FROM t1;
-c1
-1.100000000000000000000000000000
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-.100000000000000000000000000000000000000000000000000000000000000000000000000000001 /* 81 */
-AS c1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(30,30)	NO		0.000000000000000000000000000000	
-SELECT * FROM t1;
-c1
-0.100000000000000000000000000000
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 45 */ 123456789012345678901234567890123456789012345.123456789012345678901234567890123456789012345 /* 45 */
-AS c1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,20)	NO		0.00000000000000000000	
-SELECT * FROM t1;
-c1
-123456789012345678901234567890123456789012345.12345678901234567890
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 65 */ 12345678901234567890123456789012345678901234567890123456789012345.1 /* 1 */
-AS c1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,0)	NO		0	
-SELECT * FROM t1;
-c1
-12345678901234567890123456789012345678901234567890123456789012345
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-/* 66 */ 123456789012345678901234567890123456789012345678901234567890123456.1 /* 1 */
-AS c1;
-Warnings:
-Warning	1264	Out of range value for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,0)	NO		0	
-SELECT * FROM t1;
-c1
-99999999999999999999999999999999999999999999999999999999999999999
-DROP TABLE t1;
-CREATE TABLE t1 SELECT
-.123456789012345678901234567890123456789012345678901234567890123456 /* 66 */
-AS c1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(30,30)	NO		0.000000000000000000000000000000	
-SELECT * FROM t1;
-c1
-0.123456789012345678901234567890
-DROP TABLE t1;
-CREATE TABLE t1 AS SELECT 123.1234567890123456789012345678901 /* 31 */ AS c1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 1
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(33,30)	NO		0.000000000000000000000000000000	
-SELECT * FROM t1;
-c1
-123.123456789012345678901234567890
-DROP TABLE t1;
-CREATE TABLE t1 SELECT 1.1 + CAST(1 AS DECIMAL(65,30)) AS c1;
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,29)	NO		0.00000000000000000000000000000	
-SELECT * FROM t1;
-c1
-2.10000000000000000000000000000
-DROP TABLE t1;
-#
-# Test that the integer and decimal parts are properly calculated.
-#
-CREATE TABLE t1 (a DECIMAL(30,30));
-INSERT INTO t1 VALUES (0.1),(0.2),(0.3);
-CREATE TABLE t2 SELECT MIN(a + 0.0000000000000000000000000000001) AS c1 FROM t1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 3
-DESC t2;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(32,30)	YES		NULL	
-DROP TABLE t1,t2;
-CREATE TABLE t1 (a DECIMAL(30,30));
-INSERT INTO t1 VALUES (0.1),(0.2),(0.3);
-CREATE TABLE t2 SELECT IFNULL(a + 0.0000000000000000000000000000001, NULL) AS c1 FROM t1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 1
-Note	1265	Data truncated for column 'c1' at row 2
-Note	1265	Data truncated for column 'c1' at row 3
-DESC t2;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(32,30)	YES		NULL	
-DROP TABLE t1,t2;
-CREATE TABLE t1 (a DECIMAL(30,30));
-INSERT INTO t1 VALUES (0.1),(0.2),(0.3);
-CREATE TABLE t2 SELECT CASE a WHEN 0.1 THEN 0.0000000000000000000000000000000000000000000000000000000000000000001 END AS c1 FROM t1;
-Warnings:
-Note	1265	Data truncated for column 'c1' at row 1
-DESC t2;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(31,30)	YES		NULL	
-DROP TABLE t1,t2;
-#
-# Test that variables get maximum precision.
-#
-SET @decimal= 1.1;
-CREATE TABLE t1 SELECT @decimal AS c1;
-DESC t1;
-Field	Type	Null	Key	Default	Extra
-c1	decimal(65,30)	YES		NULL	
-SELECT * FROM t1;
-c1
-1.100000000000000000000000000000
-DROP TABLE t1;

=== modified file 'mysql-test/r/udf.result'
--- a/mysql-test/r/udf.result	2009-05-15 12:57:51 +0000
+++ b/mysql-test/r/udf.result	2009-09-07 09:57:22 +0000
@@ -392,4 +392,20 @@ a
 4
 DROP FUNCTION sequence;
 DROP TABLE t1,t2;
+#
+# Bug#46259: 5.0.83 -> 5.1.36, query doesn't work
+#
+CREATE TABLE t1 ( a INT );
+INSERT INTO t1 VALUES (1), (2), (3);
+SELECT IF( a = 1, a, a ) AS `b` FROM t1 ORDER BY field( `b` + 1, 1 );
+b
+1
+2
+3
+SELECT IF( a = 1, a, a ) AS `b` FROM t1 ORDER BY field( `b`, 1 );
+b
+2
+3
+1
+DROP TABLE t1;
 End of 5.0 tests.

=== modified file 'mysql-test/r/update.result'
--- a/mysql-test/r/update.result	2008-11-28 16:36:07 +0000
+++ b/mysql-test/r/update.result	2009-10-23 13:09:14 +0000
@@ -503,3 +503,14 @@ ERROR HY000: Recursive stored functions 
 DROP TABLE t1;
 DROP FUNCTION f1;
 End of 5.0 tests
+#
+# Bug #47919 assert in open_table during ALTER temporary table
+#
+CREATE TABLE t1 (f1 INTEGER AUTO_INCREMENT, PRIMARY KEY (f1));
+CREATE TEMPORARY TABLE t2 LIKE t1;
+INSERT INTO t1 VALUES (1);
+INSERT INTO t2 VALUES (1);
+ALTER TABLE t2 COMMENT = 'ABC';
+UPDATE t2, t1 SET t2.f1 = 2, t1.f1 = 9;
+ALTER TABLE t2 COMMENT = 'DEF';
+DROP TABLE t1, t2;

=== modified file 'mysql-test/r/upgrade.result'
--- a/mysql-test/r/upgrade.result	2009-04-30 12:46:49 +0000
+++ b/mysql-test/r/upgrade.result	2009-08-25 13:56:50 +0000
@@ -108,11 +108,7 @@ a-b-c
 show create view `a-b-c`.v1;
 View	Create View	character_set_client	collation_connection
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v1` AS select `a`.`f1` AS `f1` from (`a-b-c`.`t1` `a` join `information_schema`.`tables` `b`) where (convert(`a`.`f1` using utf8) = `b`.`TABLE_NAME`)	utf8	utf8_general_ci
-Warnings:
-Note	1600	Creation context of view `a-b-c`.`v1' is invalid
 select * from `a-b-c`.v1;
 f1
-Warnings:
-Note	1600	Creation context of view `a-b-c`.`v1' is invalid
 drop database `a-b-c`;
 use test;

=== modified file 'mysql-test/r/view_grant.result'
--- a/mysql-test/r/view_grant.result	2009-08-21 14:41:48 +0000
+++ b/mysql-test/r/view_grant.result	2009-10-16 11:12:21 +0000
@@ -606,7 +606,7 @@ SHOW CREATE VIEW v;
 View	Create View	character_set_client	collation_connection
 v	CREATE ALGORITHM=UNDEFINED DEFINER=`no-such-user`@`localhost` SQL SECURITY DEFINER VIEW `v` AS select `test`.`t1`.`a` AS `a` from `t1`	latin1	latin1_swedish_ci
 Warnings:
-Warning	1356	View 'test.v' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+Note	1449	The user specified as a definer ('no-such-user'@'localhost') does not exist
 SELECT * FROM v;
 ERROR HY000: The user specified as a definer ('no-such-user'@'localhost') does not exist
 DROP VIEW v;
@@ -963,7 +963,7 @@ SHOW CREATE VIEW v1;
 View	Create View	character_set_client	collation_connection
 v1	CREATE ALGORITHM=UNDEFINED DEFINER=`no_such`@`user_1` SQL SECURITY DEFINER VIEW `v1` AS select `test`.`t1`.`i` AS `i` from `t1`	latin1	latin1_swedish_ci
 Warnings:
-Warning	1356	View 'test.v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+Note	1449	The user specified as a definer ('no_such'@'user_1') does not exist
 ALTER ALGORITHM=MERGE VIEW v1 AS SELECT * FROM t1;
 Warnings:
 Note	1449	The user specified as a definer ('no_such'@'user_1') does not exist
@@ -971,7 +971,7 @@ SHOW CREATE VIEW v1;
 View	Create View	character_set_client	collation_connection
 v1	CREATE ALGORITHM=MERGE DEFINER=`no_such`@`user_1` SQL SECURITY DEFINER VIEW `v1` AS select `test`.`t1`.`i` AS `i` from `t1`	latin1	latin1_swedish_ci
 Warnings:
-Warning	1356	View 'test.v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+Note	1449	The user specified as a definer ('no_such'@'user_1') does not exist
 ALTER ALGORITHM=TEMPTABLE DEFINER=no_such@user_2 VIEW v1 AS SELECT * FROM t1;
 Warnings:
 Note	1449	The user specified as a definer ('no_such'@'user_2') does not exist
@@ -979,7 +979,7 @@ SHOW CREATE VIEW v1;
 View	Create View	character_set_client	collation_connection
 v1	CREATE ALGORITHM=TEMPTABLE DEFINER=`no_such`@`user_2` SQL SECURITY DEFINER VIEW `v1` AS select `test`.`t1`.`i` AS `i` from `t1`	latin1	latin1_swedish_ci
 Warnings:
-Warning	1356	View 'test.v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+Note	1449	The user specified as a definer ('no_such'@'user_2') does not exist
 DROP VIEW v1;
 DROP TABLE t1;
 CREATE USER mysqluser1@localhost;
@@ -1044,3 +1044,196 @@ DROP DATABASE mysqltest1;
 DROP VIEW test.v3;
 DROP USER mysqluser1@localhost;
 USE test;
+#
+# Bug#35996: SELECT + SHOW VIEW should be enough to display view 
+# definition
+#
+CREATE USER mysqluser1@localhost;
+CREATE DATABASE mysqltest1;
+CREATE DATABASE mysqltest2;
+GRANT USAGE, SELECT, CREATE VIEW, SHOW VIEW 
+ON mysqltest2.* TO mysqluser1@localhost;
+USE mysqltest1;
+CREATE TABLE t1( a INT );
+CREATE TABLE t2( a INT, b INT );
+CREATE FUNCTION f1() RETURNS INT RETURN 1;
+CREATE VIEW v1 AS SELECT 1 AS a;
+CREATE VIEW v2 AS SELECT 1 AS a, 2 AS b;
+GRANT SELECT        ON TABLE    t1 TO mysqluser1@localhost;
+GRANT SELECT (a, b) ON TABLE    t2 TO mysqluser1@localhost;
+GRANT EXECUTE       ON FUNCTION f1 TO mysqluser1@localhost;
+GRANT SELECT        ON TABLE    v1 TO mysqluser1@localhost;
+GRANT SELECT (a, b) ON TABLE    v2 TO mysqluser1@localhost;
+CREATE VIEW v_t1 AS SELECT * FROM t1;
+CREATE VIEW v_t2 AS SELECT * FROM t2;
+CREATE VIEW v_f1 AS SELECT f1() AS a;
+CREATE VIEW v_v1 AS SELECT * FROM v1;
+CREATE VIEW v_v2 AS SELECT * FROM v2;
+GRANT SELECT, SHOW VIEW ON v_t1 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_t2 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_f1 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_v1 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_v2 TO mysqluser1@localhost;
+CREATE VIEW v_mysqluser1_t1 AS SELECT * FROM mysqltest1.t1;
+CREATE VIEW v_mysqluser1_t2 AS SELECT * FROM mysqltest1.t2;
+CREATE VIEW v_mysqluser1_f1 AS SELECT mysqltest1.f1() AS a;
+CREATE VIEW v_mysqluser1_v1 AS SELECT * FROM mysqltest1.v1;
+CREATE VIEW v_mysqluser1_v2 AS SELECT * FROM mysqltest1.v2;
+SHOW CREATE VIEW mysqltest1.v_t1;
+View	Create View	character_set_client	collation_connection
+v_t1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_t1` AS select `mysqltest1`.`t1`.`a` AS `a` from `mysqltest1`.`t1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_t2;
+View	Create View	character_set_client	collation_connection
+v_t2	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_t2` AS select `mysqltest1`.`t2`.`a` AS `a`,`mysqltest1`.`t2`.`b` AS `b` from `mysqltest1`.`t2`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_f1;
+View	Create View	character_set_client	collation_connection
+v_f1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_f1` AS select `f1`() AS `a`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_v1;
+View	Create View	character_set_client	collation_connection
+v_v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_v1` AS select `v1`.`a` AS `a` from `mysqltest1`.`v1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_v2;
+View	Create View	character_set_client	collation_connection
+v_v2	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_v2` AS select `v2`.`a` AS `a`,`v2`.`b` AS `b` from `mysqltest1`.`v2`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_t1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_t1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_t1` AS select `mysqltest1`.`t1`.`a` AS `a` from `mysqltest1`.`t1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_t2;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_t2	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_t2` AS select `mysqltest1`.`t2`.`a` AS `a`,`mysqltest1`.`t2`.`b` AS `b` from `mysqltest1`.`t2`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_f1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_f1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_f1` AS select `mysqltest1`.`f1`() AS `a`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_v1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_v1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_v1` AS select `v1`.`a` AS `a` from `mysqltest1`.`v1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_v2;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_v2	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_v2` AS select `v2`.`a` AS `a`,`v2`.`b` AS `b` from `mysqltest1`.`v2`	latin1	latin1_swedish_ci
+REVOKE SELECT     ON TABLE    t1 FROM mysqluser1@localhost;
+REVOKE SELECT (a) ON TABLE    t2 FROM mysqluser1@localhost;
+REVOKE EXECUTE    ON FUNCTION f1 FROM mysqluser1@localhost;
+REVOKE SELECT     ON TABLE    v1 FROM mysqluser1@localhost;
+SHOW CREATE VIEW mysqltest1.v_t1;
+View	Create View	character_set_client	collation_connection
+v_t1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_t1` AS select `mysqltest1`.`t1`.`a` AS `a` from `mysqltest1`.`t1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_t2;
+View	Create View	character_set_client	collation_connection
+v_t2	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_t2` AS select `mysqltest1`.`t2`.`a` AS `a`,`mysqltest1`.`t2`.`b` AS `b` from `mysqltest1`.`t2`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_f1;
+View	Create View	character_set_client	collation_connection
+v_f1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_f1` AS select `f1`() AS `a`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_v1;
+View	Create View	character_set_client	collation_connection
+v_v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_v1` AS select `v1`.`a` AS `a` from `mysqltest1`.`v1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW mysqltest1.v_v2;
+View	Create View	character_set_client	collation_connection
+v_v2	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_v2` AS select `v2`.`a` AS `a`,`v2`.`b` AS `b` from `mysqltest1`.`v2`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_t1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_t1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_t1` AS select `mysqltest1`.`t1`.`a` AS `a` from `mysqltest1`.`t1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_t2;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_t2	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_t2` AS select `mysqltest1`.`t2`.`a` AS `a`,`mysqltest1`.`t2`.`b` AS `b` from `mysqltest1`.`t2`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_f1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_f1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_f1` AS select `mysqltest1`.`f1`() AS `a`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_v1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_v1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_v1` AS select `v1`.`a` AS `a` from `mysqltest1`.`v1`	latin1	latin1_swedish_ci
+SHOW CREATE VIEW v_mysqluser1_v2;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_v2	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_v2` AS select `v2`.`a` AS `a`,`v2`.`b` AS `b` from `mysqltest1`.`v2`	latin1	latin1_swedish_ci
+# Testing the case when the views reference missing objects.
+# Obviously, there are no privileges to check for, so we
+# need only each object type once.
+DROP TABLE t1;
+DROP FUNCTION f1;
+DROP VIEW v1;
+SHOW CREATE VIEW mysqltest1.v_t1;
+View	Create View	character_set_client	collation_connection
+v_t1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_t1` AS select `mysqltest1`.`t1`.`a` AS `a` from `mysqltest1`.`t1`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest1.v_t1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+SHOW CREATE VIEW mysqltest1.v_f1;
+View	Create View	character_set_client	collation_connection
+v_f1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_f1` AS select `f1`() AS `a`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest1.v_f1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+SHOW CREATE VIEW mysqltest1.v_v1;
+View	Create View	character_set_client	collation_connection
+v_v1	CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `mysqltest1`.`v_v1` AS select `v1`.`a` AS `a` from `mysqltest1`.`v1`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest1.v_v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+SHOW CREATE VIEW v_mysqluser1_t1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_t1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_t1` AS select `mysqltest1`.`t1`.`a` AS `a` from `mysqltest1`.`t1`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest2.v_mysqluser1_t1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+SHOW CREATE VIEW v_mysqluser1_f1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_f1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_f1` AS select `mysqltest1`.`f1`() AS `a`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest2.v_mysqluser1_f1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+SHOW CREATE VIEW v_mysqluser1_v1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_v1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_v1` AS select `v1`.`a` AS `a` from `mysqltest1`.`v1`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest2.v_mysqluser1_v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+REVOKE SHOW VIEW ON v_t1 FROM mysqluser1@localhost;
+REVOKE SHOW VIEW ON v_f1 FROM mysqluser1@localhost;
+REVOKE SHOW VIEW ON v_v1 FROM mysqluser1@localhost;
+SHOW CREATE VIEW mysqltest1.v_t1;
+ERROR 42000: SHOW VIEW command denied to user 'mysqluser1'@'localhost' for table 'v_t1'
+SHOW CREATE VIEW mysqltest1.v_f1;
+ERROR 42000: SHOW VIEW command denied to user 'mysqluser1'@'localhost' for table 'v_f1'
+SHOW CREATE VIEW mysqltest1.v_v1;
+ERROR 42000: SHOW VIEW command denied to user 'mysqluser1'@'localhost' for table 'v_v1'
+SHOW CREATE VIEW v_mysqluser1_t1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_t1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_t1` AS select `mysqltest1`.`t1`.`a` AS `a` from `mysqltest1`.`t1`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest2.v_mysqluser1_t1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+SHOW CREATE VIEW v_mysqluser1_f1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_f1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_f1` AS select `mysqltest1`.`f1`() AS `a`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest2.v_mysqluser1_f1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+SHOW CREATE VIEW v_mysqluser1_v1;
+View	Create View	character_set_client	collation_connection
+v_mysqluser1_v1	CREATE ALGORITHM=UNDEFINED DEFINER=`mysqluser1`@`localhost` SQL SECURITY DEFINER VIEW `v_mysqluser1_v1` AS select `v1`.`a` AS `a` from `mysqltest1`.`v1`	latin1	latin1_swedish_ci
+Warnings:
+Warning	1356	View 'mysqltest2.v_mysqluser1_v1' references invalid table(s) or column(s) or function(s) or definer/invoker of view lack rights to use them
+DROP USER mysqluser1@localhost;
+DROP DATABASE mysqltest1;
+DROP DATABASE mysqltest2;
+USE test;
+CREATE TABLE t1( a INT );
+CREATE DEFINER = no_such_user@no_such_host VIEW v1 AS SELECT * FROM t1;
+Warnings:
+Note	1449	The user specified as a definer ('no_such_user'@'no_such_host') does not exist
+SHOW CREATE VIEW v1;
+View	Create View	character_set_client	collation_connection
+v1	CREATE ALGORITHM=UNDEFINED DEFINER=`no_such_user`@`no_such_host` SQL SECURITY DEFINER VIEW `v1` AS select `test`.`t1`.`a` AS `a` from `t1`	latin1	latin1_swedish_ci
+Warnings:
+Note	1449	The user specified as a definer ('no_such_user'@'no_such_host') does not exist
+DROP TABLE t1;
+DROP VIEW v1;
+#
+# Bug #46019: ERROR 1356 When selecting from within another 
+#  view that has Group By
+#
+CREATE DATABASE mysqltest1;
+USE mysqltest1;
+CREATE TABLE t1 (a INT);
+CREATE SQL SECURITY INVOKER VIEW v1 AS SELECT a FROM t1 GROUP BY a;
+CREATE SQL SECURITY INVOKER VIEW v2 AS SELECT a FROM v1;
+CREATE USER mysqluser1;
+GRANT SELECT ON TABLE t1 TO mysqluser1;
+GRANT SELECT, SHOW VIEW ON TABLE v1 TO mysqluser1;
+GRANT SELECT, SHOW VIEW ON TABLE v2 TO mysqluser1;
+SELECT a FROM v1;
+a
+SELECT a FROM v2;
+a
+DROP USER mysqluser1;
+DROP DATABASE mysqltest1;

=== modified file 'mysql-test/r/warnings.result'
--- a/mysql-test/r/warnings.result	2009-07-06 06:55:53 +0000
+++ b/mysql-test/r/warnings.result	2009-09-10 08:49:49 +0000
@@ -313,4 +313,9 @@ ERROR 22001: Data too long for column 'c
 insert into t2 values(@q);
 ERROR 22001: Data too long for column 'c_tinyblob' at row 1
 drop table t1, t2;
+DROP TABLE t1;
+ERROR 42S02: Unknown table 't1'
+SHOW ERRORS;
+Level	Code	Message
+Error	1051	Unknown table 't1'
 End of 5.0 tests

=== modified file 'mysql-test/r/windows.result'
--- a/mysql-test/r/windows.result	2009-02-12 09:52:01 +0000
+++ b/mysql-test/r/windows.result	2009-09-22 11:22:07 +0000
@@ -53,3 +53,10 @@ ERROR HY000: No paths allowed for shared
 execute abc;
 ERROR HY000: No paths allowed for shared library
 deallocate prepare abc;
+#
+# Bug#45498: Socket variable not available on Windows
+#
+SELECT VARIABLE_NAME FROM INFORMATION_SCHEMA.GLOBAL_VARIABLES
+WHERE VARIABLE_NAME = 'socket';
+VARIABLE_NAME
+SOCKET

=== modified file 'mysql-test/r/xa.result'
--- a/mysql-test/r/xa.result	2009-06-25 15:25:23 +0000
+++ b/mysql-test/r/xa.result	2009-10-28 15:39:08 +0000
@@ -89,3 +89,28 @@ xa start 'a';
 xa end 'a';
 xa prepare 'a';
 xa commit 'a';
+CREATE TABLE t1(a INT, KEY(a)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES(1),(2);
+BEGIN;
+UPDATE t1 SET a=3 WHERE a=1;
+BEGIN;
+UPDATE t1 SET a=4 WHERE a=2;
+UPDATE t1 SET a=5 WHERE a=2;
+UPDATE t1 SET a=5 WHERE a=1;
+ERROR 40001: Deadlock found when trying to get lock; try restarting transaction
+ROLLBACK;
+ROLLBACK;
+BEGIN;
+UPDATE t1 SET a=3 WHERE a=1;
+XA START 'xid1';
+UPDATE t1 SET a=4 WHERE a=2;
+UPDATE t1 SET a=5 WHERE a=2;
+UPDATE t1 SET a=5 WHERE a=1;
+ERROR 40001: Deadlock found when trying to get lock; try restarting transaction
+XA END 'xid1';
+ERROR XA102: XA_RBDEADLOCK: Transaction branch was rolled back: deadlock was detected
+XA ROLLBACK 'xid1';
+XA START 'xid1';
+XA END 'xid1';
+XA ROLLBACK 'xid1';
+DROP TABLE t1;

=== modified file 'mysql-test/std_data/Index.xml'
--- a/mysql-test/std_data/Index.xml	2007-06-07 12:55:55 +0000
+++ b/mysql-test/std_data/Index.xml	2009-10-12 07:43:15 +0000
@@ -68,4 +68,17 @@
 
   </charset>
 
+  <charset name="latin1">
+    <family>Western</family>
+    <description>cp1252 West European</description>
+    <alias>csisolatin1</alias>
+    <alias>iso-8859-1</alias>
+    <alias>iso-ir-100</alias>
+    <alias>iso_8859-1</alias>
+    <alias>iso_8859-1:1987</alias>
+    <alias>l1</alias>
+    <alias>latin1</alias>
+    <collation name="latin1_test" id="99" order="test"/>
+  </charset>
+
 </charsets>

=== added file 'mysql-test/std_data/binlog_transaction.000001'
Files a/mysql-test/std_data/binlog_transaction.000001	1970-01-01 00:00:00 +0000 and b/mysql-test/std_data/binlog_transaction.000001	2009-09-30 02:01:52 +0000 differ

=== added file 'mysql-test/std_data/latin1.xml'
--- a/mysql-test/std_data/latin1.xml	1970-01-01 00:00:00 +0000
+++ b/mysql-test/std_data/latin1.xml	2009-10-12 09:55:59 +0000
@@ -0,0 +1,135 @@
+<?xml version='1.0' encoding="utf-8"?>
+
+<charsets>
+
+<copyright>
+  Copyright (C) 2009 Sun Microsystems, Inc
+
+  This program is free software; you can redistribute it and/or modify
+  it under the terms of the GNU General Public License as published by
+  the Free Software Foundation; version 2 of the License.
+
+  This program is distributed in the hope that it will be useful,
+  but WITHOUT ANY WARRANTY; without even the implied warranty of
+  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+  GNU General Public License for more details.
+
+  You should have received a copy of the GNU General Public License
+  along with this program; if not, write to the Free Software
+  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+</copyright>
+
+<charset name="latin1">
+
+<ctype>
+<map>
+ 00
+ 20 20 20 20 20 20 20 20 20 28 28 28 28 28 20 20
+ 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20 20
+ 48 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
+ 84 84 84 84 84 84 84 84 84 84 10 10 10 10 10 10
+ 10 81 81 81 81 81 81 01 01 01 01 01 01 01 01 01
+ 01 01 01 01 01 01 01 01 01 01 01 10 10 10 10 10
+ 10 82 82 82 82 82 82 02 02 02 02 02 02 02 02 02
+ 02 02 02 02 02 02 02 02 02 02 02 10 10 10 10 20
+ 10 00 10 02 10 10 10 10 10 10 01 10 01 00 01 00
+ 00 10 10 10 10 10 10 10 10 10 02 10 02 00 02 01
+ 48 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
+ 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10 10
+ 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01
+ 01 01 01 01 01 01 01 10 01 01 01 01 01 01 01 02
+ 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02 02
+ 02 02 02 02 02 02 02 10 02 02 02 02 02 02 02 02
+</map>
+</ctype>
+
+
+<lower>
+<map>
+ 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
+ 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
+ 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
+ 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
+ 40 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F
+ 70 71 72 73 74 75 76 77 78 79 7A 5B 5C 5D 5E 5F
+ 60 61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F
+ 70 71 72 73 74 75 76 77 78 79 7A 7B 7C 7D 7E 7F
+ 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F
+ 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F
+ A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF
+ B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF
+ E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF
+ F0 F1 F2 F3 F4 F5 F6 D7 F8 F9 FA FB FC FD FE DF
+ E0 E1 E2 E3 E4 E5 E6 E7 E8 E9 EA EB EC ED EE EF
+ F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 FA FB FC FD FE FF
+</map>
+</lower>
+
+
+<upper>
+<map>
+ 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F
+ 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F
+ 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F
+ 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 3E 3F
+ 40 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
+ 50 51 52 53 54 55 56 57 58 59 5A 5B 5C 5D 5E 5F
+ 60 41 42 43 44 45 46 47 48 49 4A 4B 4C 4D 4E 4F
+ 50 51 52 53 54 55 56 57 58 59 5A 7B 7C 7D 7E 7F
+ 80 81 82 83 84 85 86 87 88 89 8A 8B 8C 8D 8E 8F
+ 90 91 92 93 94 95 96 97 98 99 9A 9B 9C 9D 9E 9F
+ A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 AA AB AC AD AE AF
+ B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 BA BB BC BD BE BF
+ C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF
+ D0 D1 D2 D3 D4 D5 D6 D7 D8 D9 DA DB DC DD DE DF
+ C0 C1 C2 C3 C4 C5 C6 C7 C8 C9 CA CB CC CD CE CF
+ D0 D1 D2 D3 D4 D5 D6 F7 D8 D9 DA DB DC DD DE FF
+</map>
+</upper>
+
+
+<unicode>
+<map>
+ 0000 0001 0002 0003 0004 0005 0006 0007 0008 0009 000A 000B 000C 000D 000E 000F
+ 0010 0011 0012 0013 0014 0015 0016 0017 0018 0019 001A 001B 001C 001D 001E 001F
+ 0020 0021 0022 0023 0024 0025 0026 0027 0028 0029 002A 002B 002C 002D 002E 002F
+ 0030 0031 0032 0033 0034 0035 0036 0037 0038 0039 003A 003B 003C 003D 003E 003F
+ 0040 0041 0042 0043 0044 0045 0046 0047 0048 0049 004A 004B 004C 004D 004E 004F
+ 0050 0051 0052 0053 0054 0055 0056 0057 0058 0059 005A 005B 005C 005D 005E 005F
+ 0060 0061 0062 0063 0064 0065 0066 0067 0068 0069 006A 006B 006C 006D 006E 006F
+ 0070 0071 0072 0073 0074 0075 0076 0077 0078 0079 007A 007B 007C 007D 007E 007F
+ 20AC 0081 201A 0192 201E 2026 2020 2021 02C6 2030 0160 2039 0152 008D 017D 008F
+ 0090 2018 2019 201C 201D 2022 2013 2014 02DC 2122 0161 203A 0153 009D 017E 0178
+ 00A0 00A1 00A2 00A3 00A4 00A5 00A6 00A7 00A8 00A9 00AA 00AB 00AC 00AD 00AE 00AF
+ 00B0 00B1 00B2 00B3 00B4 00B5 00B6 00B7 00B8 00B9 00BA 00BB 00BC 00BD 00BE 00BF
+ 00C0 00C1 00C2 00C3 00C4 00C5 00C6 00C7 00C8 00C9 00CA 00CB 00CC 00CD 00CE 00CF
+ 00D0 00D1 00D2 00D3 00D4 00D5 00D6 00D7 00D8 00D9 00DA 00DB 00DC 00DD 00DE 00DF
+ 00E0 00E1 00E2 00E3 00E4 00E5 00E6 00E7 00E8 00E9 00EA 00EB 00EC 00ED 00EE 00EF
+ 00F0 00F1 00F2 00F3 00F4 00F5 00F6 00F7 00F8 00F9 00FA 00FB 00FC 00FD 00FE 00FF
+</map>
+</unicode>
+
+<collation name="latin1_test">
+<map>
+ 00 01 02 03 37 2D 2E 2F 16 05 25 0B 0C 0D 0E 0F
+ 10 11 12 13 3C 3D 32 26 18 19 3F 27 1C 1D 1E 1F
+ 40 4F 7F 7B 5B 6C 50 7D 4D 5D 5C 4E 6B 60 4B 61
+ F0 F1 F2 F3 F4 F5 F6 F7 F8 F9 7A 5E 4C 7E 6E 6F
+ 7C C1 C2 C3 C4 C5 C6 C7 C8 C9 D1 D2 D3 D4 D5 D6
+ D7 D8 D9 E2 E3 E4 E5 E6 E7 E8 E9 4A E0 5A 5F 6D
+ 79 81 82 83 84 85 86 87 88 89 91 92 93 94 95 96
+ 97 98 99 A2 A3 A4 A5 A6 A7 A8 A9 C0 6A D0 A1 07
+ 20 21 22 23 24 15 06 17 28 29 2A 2B 2C 09 0A 1B
+ 30 31 1A 33 34 35 36 08 38 39 3A 3B 04 14 3E E1
+ 41 42 43 44 45 46 47 48 49 51 52 53 54 55 56 57
+ 58 59 62 63 64 65 66 67 68 69 70 71 72 73 74 75
+ 76 77 78 80 8A 8B 8C 8D 8E 8F 90 9A 9B 9C 9D 9E
+ 9F A0 AA AB AC AD AE AF B0 B1 B2 B3 B4 B5 B6 B7
+ B8 B9 BA BB BC BD BE BF CA CB CC CD CE CF DA DB
+ DC DD DE DF EA EB EC ED EE EF FA FB FC FD FE FF
+</map>
+</collation>
+
+</charset>
+
+</charsets>

=== added file 'mysql-test/suite/binlog/r/binlog_delete_and_flush_index.result'
--- a/mysql-test/suite/binlog/r/binlog_delete_and_flush_index.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/r/binlog_delete_and_flush_index.result	2009-10-20 08:39:40 +0000
@@ -0,0 +1,50 @@
+RESET MASTER;
+CREATE TABLE t1 (a int);
+### assertion: index file contains regular entries
+SET @index=LOAD_FILE('MYSQLTEST_VARDIR/mysqld.1/data//master-bin.index');
+SELECT @index;
+@index
+master-bin.000001
+
+### assertion: show original binlogs
+show binary logs;
+Log_name	File_size
+master-bin.000001	#
+### assertion: binlog contents from regular entries
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a int)
+FLUSH LOGS;
+### assertion: index file contains renamed binlog and the new one
+SET @index=LOAD_FILE('MYSQLTEST_VARDIR/mysqld.1/data//master-bin.index');
+SELECT @index;
+@index
+master-bin-b34582.000001
+master-bin.000002
+
+### assertion: original binlog content still exists, despite we
+###            renamed and changed the index file 
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin-b34582.000001	#	Query	#	#	use `test`; CREATE TABLE t1 (a int)
+### assertion: user changed binlog index shows correct entries
+show binary logs;
+Log_name	File_size
+master-bin-b34582.000001	#
+master-bin.000002	#
+DROP TABLE t1;
+### assertion: purging binlogs up to binlog created after instrumenting index file should work
+PURGE BINARY LOGS TO 'master-bin.000002';
+### assertion: show binary logs should only contain latest binlog
+show binary logs;
+Log_name	File_size
+master-bin.000002	#
+### assertion: assert that binlog files were indeed purged (using file_exists calls)
+### assertion: assert that not purged binlog file exists
+### assertion: show index file contents and these should match show binary logs issued above
+SET @index=LOAD_FILE('MYSQLTEST_VARDIR/mysqld.1/data//master-bin.index');
+SELECT @index;
+@index
+master-bin.000002
+
+RESET MASTER;

=== modified file 'mysql-test/suite/binlog/r/binlog_killed_simulate.result'
--- a/mysql-test/suite/binlog/r/binlog_killed_simulate.result	2008-08-15 02:31:04 +0000
+++ b/mysql-test/suite/binlog/r/binlog_killed_simulate.result	2009-09-28 12:41:10 +0000
@@ -19,7 +19,7 @@ ERROR 70100: Query execution was interru
 show binlog events from <binlog_start>;
 Log_name	Pos	Event_type	Server_id	End_log_pos	Info
 master-bin.000001	#	Begin_load_query	#	#	;file_id=#;block_len=#
-master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../../std_data/rpl_loaddata.dat' into table t2 /* will be "killed" in the middle */ ;file_id=#
+master-bin.000001	#	Execute_load_query	#	#	use `test`; LOAD DATA INFILE '../../std_data/rpl_loaddata.dat' INTO TABLE `t2` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a, b) ;file_id=#
 select
 (@a:=load_file("MYSQLTEST_VARDIR/tmp/binlog_killed_bug27571.binlog"))
 is not null;

=== added file 'mysql-test/suite/binlog/r/binlog_mixed_failure_mixing_engines.result'
--- a/mysql-test/suite/binlog/r/binlog_mixed_failure_mixing_engines.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/r/binlog_mixed_failure_mixing_engines.result	2009-10-06 00:54:00 +0000
@@ -0,0 +1,406 @@
+###################################################################################
+#                                   CONFIGURATION
+###################################################################################
+CREATE TABLE nt_1 (a text, b int PRIMARY KEY) ENGINE = MyISAM;
+CREATE TABLE nt_2 (a text, b int PRIMARY KEY) ENGINE = MyISAM;
+CREATE TABLE tt_1 (a text, b int PRIMARY KEY) ENGINE = Innodb;
+CREATE TABLE tt_2 (a text, b int PRIMARY KEY) ENGINE = Innodb;
+CREATE TRIGGER tr_i_tt_1_to_nt_1 BEFORE INSERT ON tt_1 FOR EACH ROW
+BEGIN
+INSERT INTO nt_1 VALUES (NEW.a, NEW.b);
+END|
+CREATE TRIGGER tr_i_nt_2_to_tt_2 BEFORE INSERT ON nt_2 FOR EACH ROW
+BEGIN
+INSERT INTO tt_2 VALUES (NEW.a, NEW.b);
+END|
+###################################################################################
+#                             CHECK HISTORY IN BINLOG
+###################################################################################
+
+
+
+*** "B M* T C" with error in M* generates in the binlog the "B M* R B T C" entries
+
+INSERT INTO nt_1 VALUES ("new text 1", 1);
+BEGIN;
+INSERT INTO tt_1 VALUES (USER(), 2), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 3", 3);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO nt_1 VALUES ("new text 1", 1)
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 3", 3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+INSERT INTO tt_2 VALUES ("new text 4", 4);
+BEGIN;
+INSERT INTO nt_2 VALUES (USER(), 5), (USER(), 4);
+ERROR 23000: Duplicate entry '4' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 6", 6);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 4", 4)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 6", 6)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B M M* T C" with error in M* generates in the binlog the "B M M* T C" entries
+
+INSERT INTO nt_1 VALUES ("new text 10", 10);
+BEGIN;
+INSERT INTO tt_1 VALUES ("new text 7", 7), ("new text 8", 8);
+INSERT INTO tt_1 VALUES (USER(), 9), (USER(), 10);
+ERROR 23000: Duplicate entry '10' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 11", 11);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO nt_1 VALUES ("new text 10", 10)
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_1 VALUES ("new text 7", 7), ("new text 8", 8)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 11", 11)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+INSERT INTO tt_2 VALUES ("new text 15", 15);
+BEGIN;
+INSERT INTO nt_2 VALUES ("new text 12", 12), ("new text 13", 13);
+INSERT INTO nt_2 VALUES (USER(), 14), (USER(), 15);
+ERROR 23000: Duplicate entry '15' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 16", 16);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 15", 15)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO nt_2 VALUES ("new text 12", 12), ("new text 13", 13)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 16", 16)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B M* M* T C" with error in M* generates in the binlog the "B M* R B M* R B T C" entries
+
+INSERT INTO nt_1 VALUES ("new text 18", 18);
+INSERT INTO nt_1 VALUES ("new text 20", 20);
+BEGIN;
+INSERT INTO tt_1 VALUES (USER(), 17), (USER(), 18);
+ERROR 23000: Duplicate entry '18' for key 'PRIMARY'
+INSERT INTO tt_1 VALUES (USER(), 19), (USER(), 20);
+ERROR 23000: Duplicate entry '20' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 21", 21);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO nt_1 VALUES ("new text 18", 18)
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO nt_1 VALUES ("new text 20", 20)
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 21", 21)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+INSERT INTO tt_2 VALUES ("new text 23", 23);
+INSERT INTO tt_2 VALUES ("new text 25", 25);
+BEGIN;
+INSERT INTO nt_2 VALUES (USER(), 22), (USER(), 23);
+ERROR 23000: Duplicate entry '23' for key 'PRIMARY'
+INSERT INTO nt_2 VALUES (USER(), 24), (USER(), 25);
+ERROR 23000: Duplicate entry '25' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 26", 26);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 23", 23)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 25", 25)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 26", 26)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B T INSERT M...SELECT* C" with an error in INSERT M...SELECT* generates
+*** in the binlog the following entries: "Nothing".
+*** There is a bug in that will be fixed after WL#2687. Please, check BUG#47175 for further details.
+
+TRUNCATE TABLE nt_2;
+TRUNCATE TABLE tt_2;
+INSERT INTO tt_2 VALUES ("new text 7", 7);
+BEGIN;
+INSERT INTO tt_2 VALUES ("new text 27", 27);
+INSERT INTO nt_2(a, b) SELECT USER(), b FROM nt_1;
+ERROR 23000: Duplicate entry '7' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 28", 28);
+ROLLBACK;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE nt_2
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE tt_2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 7", 7)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B INSERT M..SELECT* C" with an error in INSERT M...SELECT* generates
+*** in the binlog the following entries: "B INSERT M..SELECT* R".
+
+TRUNCATE TABLE nt_2;
+TRUNCATE TABLE tt_2;
+INSERT INTO tt_2 VALUES ("new text 7", 7);
+BEGIN;
+INSERT INTO nt_2(a, b) SELECT USER(), b FROM nt_1;
+ERROR 23000: Duplicate entry '7' for key 'PRIMARY'
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE nt_2
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE tt_2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO tt_2 VALUES ("new text 7", 7)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	#	ROLLBACK
+
+
+
+*** "B N N T C" generates in the binlog the "B N C B N C B T C" entries
+
+TRUNCATE TABLE nt_1;
+TRUNCATE TABLE tt_2;
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 1);
+INSERT INTO nt_1 VALUES (USER(), 2);
+INSERT INTO tt_2 VALUES (USER(), 3);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE nt_1
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE tt_2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B N N T R" generates in the binlog the "B N C B N C B T R" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 4);
+INSERT INTO nt_1 VALUES (USER(), 5);
+INSERT INTO tt_2 VALUES (USER(), 6);
+ROLLBACK;
+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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+
+
+
+*** "B N* N* T C" with error in N* generates in the binlog the "B N R B N R B T C" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 7), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO nt_1 VALUES (USER(), 8), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES (USER(), 9);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B N* N* T R" with error in N* generates in the binlog the "B N R B N R B T R" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 10), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO nt_1 VALUES (USER(), 11), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES (USER(), 12);
+ROLLBACK;
+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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+
+
+
+*** "B N N T N T C" generates in the binlog the "B N C B N C B T N T C" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 13);
+INSERT INTO nt_1 VALUES (USER(), 14);
+INSERT INTO tt_2 VALUES (USER(), 15);
+INSERT INTO nt_1 VALUES (USER(), 16);
+INSERT INTO tt_2 VALUES (USER(), 17);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B N N T N T R" generates in the binlog the "B N C B N C B T N T R" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 18);
+INSERT INTO nt_1 VALUES (USER(), 19);
+INSERT INTO tt_2 VALUES (USER(), 20);
+INSERT INTO nt_1 VALUES (USER(), 21);
+INSERT INTO tt_2 VALUES (USER(), 22);
+ROLLBACK;
+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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+###################################################################################
+#                                        CLEAN
+###################################################################################
+DROP TABLE tt_1;
+DROP TABLE tt_2;
+DROP TABLE nt_1;
+DROP TABLE nt_2;

=== modified file 'mysql-test/suite/binlog/r/binlog_row_binlog.result'
--- a/mysql-test/suite/binlog/r/binlog_row_binlog.result	2009-07-14 15:07:29 +0000
+++ b/mysql-test/suite/binlog/r/binlog_row_binlog.result	2009-10-14 15:46:45 +0000
@@ -1309,3 +1309,27 @@ INSERT INTO test.t1 VALUES (1), (2);
 CREATE TABLE test.t2 SELECT * FROM test.t1;
 USE test;
 DROP TABLES t1, t2;
+RESET MASTER;
+CREATE TABLE t1 (a INT PRIMARY KEY);
+BINLOG '
+3u9kSA8KAAAAZgAAAGoAAAABAAQANS4xLjM1LW1hcmlhLWJldGExLWRlYnVnLWxvZwAAAAAAAAAA
+AAAAAAAAAAAAAAAAAADe72RIEzgNAAgAEgAEBAQEEgAAUwAEGggAAAAICAgC
+';
+INSERT INTO t1 VALUES (1);
+BINLOG '
+3u9kSBMUAAAAKQAAAJEBAAAAABoAAAAAAAAABHRlc3QAAnQxAAEDAAA=
+3u9kSBcUAAAAIgAAALMBAAAQABoAAAAAAAEAAf/+AgAAAA==
+';
+SHOW BINLOG EVENTS;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+#	#	Format_desc	1	#	Server ver: #, Binlog ver: #
+#	#	Query	1	#	use `test`; CREATE TABLE t1 (a INT PRIMARY KEY)
+#	#	Query	1	#	BEGIN
+#	#	Table_map	1	#	table_id: # (test.t1)
+#	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+#	#	Query	1	#	COMMIT
+#	#	Query	1	#	BEGIN
+#	#	Table_map	1	#	table_id: # (test.t1)
+#	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+#	#	Query	1	#	COMMIT
+DROP TABLE t1;

=== modified file 'mysql-test/suite/binlog/r/binlog_row_drop_tmp_tbl.result'
--- a/mysql-test/suite/binlog/r/binlog_row_drop_tmp_tbl.result	2007-06-27 12:28:02 +0000
+++ b/mysql-test/suite/binlog/r/binlog_row_drop_tmp_tbl.result	2009-11-03 10:20:08 +0000
@@ -1,17 +1,32 @@
-drop database if exists `drop-temp+table-test`;
-reset master;
-create database `drop-temp+table-test`;
-use `drop-temp+table-test`;
-create temporary table shortn1 (a int);
-create temporary table `table:name` (a int);
-create temporary table shortn2 (a int);
-select get_lock("a",10);
-get_lock("a",10)
+DROP DATABASE IF EXISTS `drop-temp+table-test`;
+RESET MASTER;
+CREATE DATABASE `drop-temp+table-test`;
+USE `drop-temp+table-test`;
+CREATE TEMPORARY TABLE shortn1 (a INT);
+CREATE TEMPORARY TABLE `table:name` (a INT);
+CREATE TEMPORARY TABLE shortn2 (a INT);
+CREATE TEMPORARY TABLE tmp(c1 int);
+CREATE TEMPORARY TABLE tmp1(c1 int);
+CREATE TEMPORARY TABLE tmp2(c1 int);
+CREATE TEMPORARY TABLE tmp3(c1 int);
+CREATE TABLE t(c1 int);
+DROP TEMPORARY TABLE IF EXISTS tmp;
+DROP TEMPORARY TABLE IF EXISTS tmp;
+DROP TEMPORARY TABLE IF EXISTS tmp, tmp1;
+DROP TEMPORARY TABLE tmp3;
+DROP TABLE IF EXISTS tmp2, t;
+DROP TABLE IF EXISTS tmp2, t;
+SELECT GET_LOCK("a",10);
+GET_LOCK("a",10)
 1
-select get_lock("a",10);
-get_lock("a",10)
+USE test;
+SELECT GET_LOCK("a",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	#	#	create database `drop-temp+table-test`
-drop database `drop-temp+table-test`;
+master-bin.000001	#	Query	#	#	CREATE DATABASE `drop-temp+table-test`
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; CREATE TABLE t(c1 int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TABLE IF EXISTS `t` /* generated by server */
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TABLE IF EXISTS tmp2, t
+DROP DATABASE `drop-temp+table-test`;

=== added file 'mysql-test/suite/binlog/r/binlog_row_failure_mixing_engines.result'
--- a/mysql-test/suite/binlog/r/binlog_row_failure_mixing_engines.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/r/binlog_row_failure_mixing_engines.result	2009-10-06 00:54:00 +0000
@@ -0,0 +1,440 @@
+###################################################################################
+#                                   CONFIGURATION
+###################################################################################
+CREATE TABLE nt_1 (a text, b int PRIMARY KEY) ENGINE = MyISAM;
+CREATE TABLE nt_2 (a text, b int PRIMARY KEY) ENGINE = MyISAM;
+CREATE TABLE tt_1 (a text, b int PRIMARY KEY) ENGINE = Innodb;
+CREATE TABLE tt_2 (a text, b int PRIMARY KEY) ENGINE = Innodb;
+CREATE TRIGGER tr_i_tt_1_to_nt_1 BEFORE INSERT ON tt_1 FOR EACH ROW
+BEGIN
+INSERT INTO nt_1 VALUES (NEW.a, NEW.b);
+END|
+CREATE TRIGGER tr_i_nt_2_to_tt_2 BEFORE INSERT ON nt_2 FOR EACH ROW
+BEGIN
+INSERT INTO tt_2 VALUES (NEW.a, NEW.b);
+END|
+###################################################################################
+#                             CHECK HISTORY IN BINLOG
+###################################################################################
+
+
+
+*** "B M* T C" with error in M* generates in the binlog the "B M* R B T C" entries
+
+INSERT INTO nt_1 VALUES ("new text 1", 1);
+BEGIN;
+INSERT INTO tt_1 VALUES (USER(), 2), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 3", 3);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+INSERT INTO tt_2 VALUES ("new text 4", 4);
+BEGIN;
+INSERT INTO nt_2 VALUES (USER(), 5), (USER(), 4);
+ERROR 23000: Duplicate entry '4' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 6", 6);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B M M* T C" with error in M* generates in the binlog the "B M M* T C" entries
+
+INSERT INTO nt_1 VALUES ("new text 10", 10);
+BEGIN;
+INSERT INTO tt_1 VALUES ("new text 7", 7), ("new text 8", 8);
+INSERT INTO tt_1 VALUES (USER(), 9), (USER(), 10);
+ERROR 23000: Duplicate entry '10' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 11", 11);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+INSERT INTO tt_2 VALUES ("new text 15", 15);
+BEGIN;
+INSERT INTO nt_2 VALUES ("new text 12", 12), ("new text 13", 13);
+INSERT INTO nt_2 VALUES (USER(), 14), (USER(), 15);
+ERROR 23000: Duplicate entry '15' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 16", 16);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B M* M* T C" with error in M* generates in the binlog the "B M* R B M* R B T C" entries
+
+INSERT INTO nt_1 VALUES ("new text 18", 18);
+INSERT INTO nt_1 VALUES ("new text 20", 20);
+BEGIN;
+INSERT INTO tt_1 VALUES (USER(), 17), (USER(), 18);
+ERROR 23000: Duplicate entry '18' for key 'PRIMARY'
+INSERT INTO tt_1 VALUES (USER(), 19), (USER(), 20);
+ERROR 23000: Duplicate entry '20' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 21", 21);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+INSERT INTO tt_2 VALUES ("new text 23", 23);
+INSERT INTO tt_2 VALUES ("new text 25", 25);
+BEGIN;
+INSERT INTO nt_2 VALUES (USER(), 22), (USER(), 23);
+ERROR 23000: Duplicate entry '23' for key 'PRIMARY'
+INSERT INTO nt_2 VALUES (USER(), 24), (USER(), 25);
+ERROR 23000: Duplicate entry '25' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 26", 26);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B T INSERT M...SELECT* C" with an error in INSERT M...SELECT* generates
+*** in the binlog the following entries: "Nothing".
+*** There is a bug in that will be fixed after WL#2687. Please, check BUG#47175 for further details.
+
+TRUNCATE TABLE nt_2;
+TRUNCATE TABLE tt_2;
+INSERT INTO tt_2 VALUES ("new text 7", 7);
+BEGIN;
+INSERT INTO tt_2 VALUES ("new text 27", 27);
+INSERT INTO nt_2(a, b) SELECT USER(), b FROM nt_1;
+ERROR 23000: Duplicate entry '7' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES ("new text 28", 28);
+ROLLBACK;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE nt_2
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE tt_2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B INSERT M..SELECT* C" with an error in INSERT M...SELECT* generates
+*** in the binlog the following entries: "B INSERT M..SELECT* R".
+
+TRUNCATE TABLE nt_2;
+TRUNCATE TABLE tt_2;
+INSERT INTO tt_2 VALUES ("new text 7", 7);
+BEGIN;
+INSERT INTO nt_2(a, b) SELECT USER(), b FROM nt_1;
+ERROR 23000: Duplicate entry '7' for key 'PRIMARY'
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE nt_2
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE tt_2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	#	ROLLBACK
+
+
+
+*** "B N N T C" generates in the binlog the "B N C B N C B T C" entries
+
+TRUNCATE TABLE nt_1;
+TRUNCATE TABLE tt_2;
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 1);
+INSERT INTO nt_1 VALUES (USER(), 2);
+INSERT INTO tt_2 VALUES (USER(), 3);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE nt_1
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; TRUNCATE TABLE tt_2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B N N T R" generates in the binlog the "B N C B N C B T R" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 4);
+INSERT INTO nt_1 VALUES (USER(), 5);
+INSERT INTO tt_2 VALUES (USER(), 6);
+ROLLBACK;
+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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+
+
+
+*** "B N* N* T C" with error in N* generates in the binlog the "B N R B N R B T C" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 7), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO nt_1 VALUES (USER(), 8), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES (USER(), 9);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B N* N* T R" with error in N* generates in the binlog the "B N R B N R B T R" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 10), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO nt_1 VALUES (USER(), 11), (USER(), 1);
+ERROR 23000: Duplicate entry '1' for key 'PRIMARY'
+INSERT INTO tt_2 VALUES (USER(), 12);
+ROLLBACK;
+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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+
+
+
+*** "B N N T N T C" generates in the binlog the "B N C B N C B T N T C" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 13);
+INSERT INTO nt_1 VALUES (USER(), 14);
+INSERT INTO tt_2 VALUES (USER(), 15);
+INSERT INTO nt_1 VALUES (USER(), 16);
+INSERT INTO tt_2 VALUES (USER(), 17);
+COMMIT;
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+
+
+
+*** "B N N T N T R" generates in the binlog the "B N C B N C B T N T R" entries
+
+BEGIN;
+INSERT INTO nt_1 VALUES (USER(), 18);
+INSERT INTO nt_1 VALUES (USER(), 19);
+INSERT INTO tt_2 VALUES (USER(), 20);
+INSERT INTO nt_1 VALUES (USER(), 21);
+INSERT INTO tt_2 VALUES (USER(), 22);
+ROLLBACK;
+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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.nt_1)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.tt_2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	ROLLBACK
+###################################################################################
+#                                        CLEAN
+###################################################################################
+DROP TABLE tt_1;
+DROP TABLE tt_2;
+DROP TABLE nt_1;
+DROP TABLE nt_2;

=== modified file 'mysql-test/suite/binlog/r/binlog_row_mix_innodb_myisam.result'
--- a/mysql-test/suite/binlog/r/binlog_row_mix_innodb_myisam.result	2009-08-26 23:13:03 +0000
+++ b/mysql-test/suite/binlog/r/binlog_row_mix_innodb_myisam.result	2009-10-06 10:25:36 +0000
@@ -133,6 +133,10 @@ master-bin.000001	#	Query	#	#	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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
 insert into t1 values(11);
 commit;
 show binlog events from <binlog_start>;
@@ -144,6 +148,8 @@ master-bin.000001	#	Xid	#	#	COMMIT /* XI
 master-bin.000001	#	Query	#	#	BEGIN
 master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
 master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	COMMIT
+master-bin.000001	#	Query	#	#	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 */
@@ -272,6 +278,10 @@ master-bin.000001	#	Query	#	#	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	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+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,t2
 master-bin.000001	#	Query	#	#	use `test`; create table t0 (n int)
 master-bin.000001	#	Query	#	#	BEGIN
@@ -372,7 +382,7 @@ master-bin.000001	#	Query	#	#	use `test`
 master-bin.000001	#	Query	#	#	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	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	COMMIT
 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	#	#	BEGIN
@@ -390,9 +400,11 @@ master-bin.000001	#	Query	#	#	use `test`
 master-bin.000001	#	Query	#	#	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	#	#	COMMIT
+master-bin.000001	#	Query	#	#	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	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	COMMIT
 master-bin.000001	#	Query	#	#	BEGIN
 master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
 master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
@@ -400,7 +412,7 @@ master-bin.000001	#	Query	#	#	COMMIT
 master-bin.000001	#	Query	#	#	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	#	#	ROLLBACK
+master-bin.000001	#	Query	#	#	COMMIT
 master-bin.000001	#	Query	#	#	use `test`; TRUNCATE table t2
 master-bin.000001	#	Query	#	#	BEGIN
 master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
@@ -917,7 +929,7 @@ master-bin.000001	#	User var	#	#	@`b`=_l
 master-bin.000001	#	Begin_load_query	#	#	;file_id=#;block_len=#
 master-bin.000001	#	Intvar	#	#	INSERT_ID=10
 master-bin.000001	#	User var	#	#	@`b`=_latin1 0x3135 COLLATE latin1_swedish_ci
-master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../../std_data/rpl_loaddata.dat' into table t4 (a, @b) set b= @b + bug27417(2) ;file_id=#
+master-bin.000001	#	Execute_load_query	#	#	use `test`; LOAD DATA INFILE '../../std_data/rpl_loaddata.dat' INTO TABLE `t4` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a, @b) SET b=((@b) + `bug27417`(2)) ;file_id=#
 master-bin.000001	#	Query	#	#	ROLLBACK
 drop trigger trg_del_t2;
 drop table t1,t2,t3,t4,t5;

=== added file 'mysql-test/suite/binlog/r/binlog_row_mysqlbinlog_verbose.result'
--- a/mysql-test/suite/binlog/r/binlog_row_mysqlbinlog_verbose.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/r/binlog_row_mysqlbinlog_verbose.result	2009-10-14 13:25:11 +0000
@@ -0,0 +1,161 @@
+Verbose statements from : write-partial-row.binlog
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+stmt
+### INSERT INTO mysql.ndb_apply_status
+### SET
+###   @1=1
+###   @2=25769803786
+###   @3=''
+###   @4=0
+###   @5=0
+### INSERT INTO test.ba
+### SET
+###   @1=3
+###   @2=3
+###   @3=3
+### INSERT INTO test.ba
+### SET
+###   @1=1
+###   @2=1
+###   @3=1
+### INSERT INTO test.ba
+### SET
+###   @1=2
+###   @2=2
+###   @3=2
+### INSERT INTO test.ba
+### SET
+###   @1=4
+###   @2=4
+###   @3=4
+### INSERT INTO test.ba
+### SET
+###   @1=4
+###   @3=40
+### DELETE FROM test.ba
+### WHERE
+###   @1=2
+drop table raw_binlog_rows;
+Verbose statements from : write-full-row.binlog
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+stmt
+### INSERT INTO mysql.ndb_apply_status
+### SET
+###   @1=2
+###   @2=25769803786
+###   @3=''
+###   @4=0
+###   @5=0
+### INSERT INTO test.ba
+### SET
+###   @1=3
+###   @2=3
+###   @3=3
+### INSERT INTO test.ba
+### SET
+###   @1=1
+###   @2=1
+###   @3=1
+### INSERT INTO test.ba
+### SET
+###   @1=2
+###   @2=2
+###   @3=2
+### INSERT INTO test.ba
+### SET
+###   @1=4
+###   @2=4
+###   @3=4
+### INSERT INTO test.ba
+### SET
+###   @1=4
+###   @2=4
+###   @3=40
+### DELETE FROM test.ba
+### WHERE
+###   @1=2
+drop table raw_binlog_rows;
+Verbose statements from : update-partial-row.binlog
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+stmt
+### INSERT INTO mysql.ndb_apply_status
+### SET
+###   @1=3
+###   @2=25769803786
+###   @3=''
+###   @4=0
+###   @5=0
+### INSERT INTO test.ba
+### SET
+###   @1=3
+###   @2=3
+###   @3=3
+### INSERT INTO test.ba
+### SET
+###   @1=1
+###   @2=1
+###   @3=1
+### INSERT INTO test.ba
+### SET
+###   @1=2
+###   @2=2
+###   @3=2
+### INSERT INTO test.ba
+### SET
+###   @1=4
+###   @2=4
+###   @3=4
+### UPDATE test.ba
+### WHERE
+###   @1=4
+###   @3=4
+### SET
+###   @1=4
+###   @3=40
+### DELETE FROM test.ba
+### WHERE
+###   @1=2
+drop table raw_binlog_rows;
+Verbose statements from : update-full-row.binlog
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+stmt
+### INSERT INTO mysql.ndb_apply_status
+### SET
+###   @1=4
+###   @2=25769803786
+###   @3=''
+###   @4=0
+###   @5=0
+### INSERT INTO test.ba
+### SET
+###   @1=3
+###   @2=3
+###   @3=3
+### INSERT INTO test.ba
+### SET
+###   @1=1
+###   @2=1
+###   @3=1
+### INSERT INTO test.ba
+### SET
+###   @1=2
+###   @2=2
+###   @3=2
+### INSERT INTO test.ba
+### SET
+###   @1=4
+###   @2=4
+###   @3=4
+### UPDATE test.ba
+### WHERE
+###   @1=4
+###   @2=4
+###   @3=4
+### SET
+###   @1=4
+###   @2=4
+###   @3=40
+### DELETE FROM test.ba
+### WHERE
+###   @1=2
+drop table raw_binlog_rows;

=== modified file 'mysql-test/suite/binlog/r/binlog_stm_binlog.result'
--- a/mysql-test/suite/binlog/r/binlog_stm_binlog.result	2009-07-15 10:25:44 +0000
+++ b/mysql-test/suite/binlog/r/binlog_stm_binlog.result	2009-10-14 15:46:45 +0000
@@ -784,3 +784,24 @@ INSERT INTO test.t1 VALUES (1), (2);
 CREATE TABLE test.t2 SELECT * FROM test.t1;
 USE test;
 DROP TABLES t1, t2;
+RESET MASTER;
+CREATE TABLE t1 (a INT PRIMARY KEY);
+BINLOG '
+3u9kSA8KAAAAZgAAAGoAAAABAAQANS4xLjM1LW1hcmlhLWJldGExLWRlYnVnLWxvZwAAAAAAAAAA
+AAAAAAAAAAAAAAAAAADe72RIEzgNAAgAEgAEBAQEEgAAUwAEGggAAAAICAgC
+';
+INSERT INTO t1 VALUES (1);
+BINLOG '
+3u9kSBMUAAAAKQAAAJEBAAAAABoAAAAAAAAABHRlc3QAAnQxAAEDAAA=
+3u9kSBcUAAAAIgAAALMBAAAQABoAAAAAAAEAAf/+AgAAAA==
+';
+SHOW BINLOG EVENTS;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+#	#	Format_desc	1	#	Server ver: #, Binlog ver: #
+#	#	Query	1	#	use `test`; CREATE TABLE t1 (a INT PRIMARY KEY)
+#	#	Query	1	#	use `test`; INSERT INTO t1 VALUES (1)
+#	#	Query	1	#	BEGIN
+#	#	Table_map	1	#	table_id: # (test.t1)
+#	#	Write_rows	1	#	table_id: # flags: STMT_END_F
+#	#	Query	1	#	COMMIT
+DROP TABLE t1;

=== modified file 'mysql-test/suite/binlog/r/binlog_stm_blackhole.result'
--- a/mysql-test/suite/binlog/r/binlog_stm_blackhole.result	2009-05-31 05:44:41 +0000
+++ b/mysql-test/suite/binlog/r/binlog_stm_blackhole.result	2009-09-28 12:41:10 +0000
@@ -127,7 +127,7 @@ master-bin.000001	#	Query	#	#	COMMIT
 master-bin.000001	#	Query	#	#	use `test`; create table t2 (a varchar(200)) engine=blackhole
 master-bin.000001	#	Query	#	#	BEGIN
 master-bin.000001	#	Begin_load_query	#	#	;file_id=#;block_len=581
-master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../../std_data/words.dat' into table t2 ;file_id=#
+master-bin.000001	#	Execute_load_query	#	#	use `test`; LOAD DATA INFILE '../../std_data/words.dat' INTO TABLE `t2` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a) ;file_id=#
 master-bin.000001	#	Query	#	#	COMMIT
 master-bin.000001	#	Query	#	#	use `test`; alter table t1 add b int
 master-bin.000001	#	Query	#	#	use `test`; alter table t1 drop b

=== added file 'mysql-test/suite/binlog/r/binlog_stm_do_db.result'
--- a/mysql-test/suite/binlog/r/binlog_stm_do_db.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/r/binlog_stm_do_db.result	2009-09-24 14:52:52 +0000
@@ -0,0 +1,42 @@
+SET @old_isolation_level= @@session.tx_isolation;
+SET @@session.tx_isolation= 'READ-COMMITTED';
+CREATE DATABASE b42829;
+use b42829;
+CREATE TABLE t1 (x int, y int) engine=InnoDB;
+CREATE TABLE t2 (x int, y int) engine=InnoDB;
+CREATE DATABASE b42829_filtered;
+use b42829_filtered;
+CREATE TABLE t1 (x int, y int) engine=InnoDB;
+CREATE TABLE t2 (x int, y int) engine=InnoDB;
+SET @@session.sql_log_bin= 0;
+INSERT INTO b42829_filtered.t1 VALUES (100,100);
+INSERT INTO b42829.t1 VALUES (100,100);
+SET @@session.sql_log_bin= 1;
+### assertion: the inserts will not raise log error because
+###            binlog-do-db is filtering used database
+INSERT INTO t2 VALUES (1,2), (1,3), (1,4);
+INSERT INTO t1 SELECT * FROM t2;
+### assertion: assert that despite updating a not filtered
+###            database this wont trigger an error as the
+###            used database is the filtered one.
+UPDATE b42829_filtered.t1 ft1, b42829.t1 nft1 SET ft1.x=1, nft1.x=2;
+use b42829;
+### assertion: the statements *will* raise log error because
+###            binlog-do-db is not filtering  used database 
+BEGIN;
+INSERT INTO t2 VALUES (1,2), (1,3), (1,4);
+ERROR HY000: Binary logging not possible. Message: Transaction level 'READ-COMMITTED' in InnoDB is not safe for binlog mode 'STATEMENT'
+UPDATE b42829_filtered.t1 ft1, b42829.t1 nft1 SET ft1.x=1, nft1.x=2;
+ERROR HY000: Binary logging not possible. Message: Transaction level 'READ-COMMITTED' in InnoDB is not safe for binlog mode 'STATEMENT'
+INSERT INTO t1 SELECT * FROM t2;
+ERROR HY000: Binary logging not possible. Message: Transaction level 'READ-COMMITTED' in InnoDB is not safe for binlog mode 'STATEMENT'
+COMMIT;
+### assertion: filtered events did not make into the binlog
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	CREATE DATABASE b42829
+master-bin.000001	#	Query	#	#	use `b42829`; CREATE TABLE t1 (x int, y int) engine=InnoDB
+master-bin.000001	#	Query	#	#	use `b42829`; CREATE TABLE t2 (x int, y int) engine=InnoDB
+DROP DATABASE b42829;
+DROP DATABASE b42829_filtered;
+SET @@session.tx_isolation= @old_isolation_level;

=== modified file 'mysql-test/suite/binlog/r/binlog_stm_drop_tmp_tbl.result'
--- a/mysql-test/suite/binlog/r/binlog_stm_drop_tmp_tbl.result	2009-08-28 09:45:57 +0000
+++ b/mysql-test/suite/binlog/r/binlog_stm_drop_tmp_tbl.result	2009-11-03 10:20:08 +0000
@@ -1,21 +1,44 @@
-drop database if exists `drop-temp+table-test`;
-reset master;
-create database `drop-temp+table-test`;
-use `drop-temp+table-test`;
-create temporary table shortn1 (a int);
-create temporary table `table:name` (a int);
-create temporary table shortn2 (a int);
-select get_lock("a",10);
-get_lock("a",10)
+DROP DATABASE IF EXISTS `drop-temp+table-test`;
+RESET MASTER;
+CREATE DATABASE `drop-temp+table-test`;
+USE `drop-temp+table-test`;
+CREATE TEMPORARY TABLE shortn1 (a INT);
+CREATE TEMPORARY TABLE `table:name` (a INT);
+CREATE TEMPORARY TABLE shortn2 (a INT);
+CREATE TEMPORARY TABLE tmp(c1 int);
+CREATE TEMPORARY TABLE tmp1(c1 int);
+CREATE TEMPORARY TABLE tmp2(c1 int);
+CREATE TEMPORARY TABLE tmp3(c1 int);
+CREATE TABLE t(c1 int);
+DROP TEMPORARY TABLE IF EXISTS tmp;
+DROP TEMPORARY TABLE IF EXISTS tmp;
+DROP TEMPORARY TABLE IF EXISTS tmp, tmp1;
+DROP TEMPORARY TABLE tmp3;
+DROP TABLE IF EXISTS tmp2, t;
+DROP TABLE IF EXISTS tmp2, t;
+SELECT GET_LOCK("a",10);
+GET_LOCK("a",10)
 1
-select get_lock("a",10);
-get_lock("a",10)
+USE test;
+SELECT GET_LOCK("a",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	#	#	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	#	#	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`; CREATE TEMPORARY TABLE tmp(c1 int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; CREATE TEMPORARY TABLE tmp1(c1 int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; CREATE TEMPORARY TABLE tmp2(c1 int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; CREATE TEMPORARY TABLE tmp3(c1 int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; CREATE TABLE t(c1 int)
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TEMPORARY TABLE IF EXISTS tmp
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TEMPORARY TABLE IF EXISTS tmp
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TEMPORARY TABLE IF EXISTS tmp, tmp1
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TEMPORARY TABLE tmp3
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TABLE IF EXISTS tmp2, t
+master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP TABLE IF EXISTS tmp2, t
 master-bin.000001	#	Query	#	#	use `drop-temp+table-test`; DROP /*!40005 TEMPORARY */ TABLE IF EXISTS `shortn2`,`table:name`,`shortn1`
-drop database `drop-temp+table-test`;
+DROP DATABASE `drop-temp+table-test`;

=== modified file 'mysql-test/suite/binlog/r/binlog_stm_mix_innodb_myisam.result'
--- a/mysql-test/suite/binlog/r/binlog_stm_mix_innodb_myisam.result	2009-08-28 09:45:57 +0000
+++ b/mysql-test/suite/binlog/r/binlog_stm_mix_innodb_myisam.result	2009-09-28 12:41:10 +0000
@@ -625,7 +625,7 @@ master-bin.000001	#	Query	#	#	BEGIN
 master-bin.000001	#	Intvar	#	#	INSERT_ID=10
 master-bin.000001	#	Begin_load_query	#	#	;file_id=#;block_len=#
 master-bin.000001	#	Intvar	#	#	INSERT_ID=10
-master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../../std_data/rpl_loaddata.dat' into table t4 (a, @b) set b= @b + bug27417(2) ;file_id=#
+master-bin.000001	#	Execute_load_query	#	#	use `test`; LOAD DATA INFILE '../../std_data/rpl_loaddata.dat' INTO TABLE `t4` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a, @b) SET b=((@b) + `bug27417`(2)) ;file_id=#
 master-bin.000001	#	Query	#	#	ROLLBACK
 /* the output must denote there is the query */;
 drop trigger trg_del_t2;
@@ -863,7 +863,7 @@ master-bin.000001	#	User var	#	#	@`b`=_l
 master-bin.000001	#	Begin_load_query	#	#	;file_id=#;block_len=#
 master-bin.000001	#	Intvar	#	#	INSERT_ID=10
 master-bin.000001	#	User var	#	#	@`b`=_latin1 0x3135 COLLATE latin1_swedish_ci
-master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../../std_data/rpl_loaddata.dat' into table t4 (a, @b) set b= @b + bug27417(2) ;file_id=#
+master-bin.000001	#	Execute_load_query	#	#	use `test`; LOAD DATA INFILE '../../std_data/rpl_loaddata.dat' INTO TABLE `t4` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a, @b) SET b=((@b) + `bug27417`(2)) ;file_id=#
 master-bin.000001	#	Query	#	#	ROLLBACK
 drop trigger trg_del_t2;
 drop table t1,t2,t3,t4,t5;

=== added file 'mysql-test/suite/binlog/std_data/update-full-row.binlog'
Files a/mysql-test/suite/binlog/std_data/update-full-row.binlog	1970-01-01 00:00:00 +0000 and b/mysql-test/suite/binlog/std_data/update-full-row.binlog	2009-10-09 08:54:48 +0000 differ

=== added file 'mysql-test/suite/binlog/std_data/update-partial-row.binlog'
Files a/mysql-test/suite/binlog/std_data/update-partial-row.binlog	1970-01-01 00:00:00 +0000 and b/mysql-test/suite/binlog/std_data/update-partial-row.binlog	2009-10-09 08:54:48 +0000 differ

=== added file 'mysql-test/suite/binlog/std_data/write-full-row.binlog'
Files a/mysql-test/suite/binlog/std_data/write-full-row.binlog	1970-01-01 00:00:00 +0000 and b/mysql-test/suite/binlog/std_data/write-full-row.binlog	2009-10-09 08:54:48 +0000 differ

=== added file 'mysql-test/suite/binlog/std_data/write-partial-row.binlog'
Files a/mysql-test/suite/binlog/std_data/write-partial-row.binlog	1970-01-01 00:00:00 +0000 and b/mysql-test/suite/binlog/std_data/write-partial-row.binlog	2009-10-09 08:54:48 +0000 differ

=== added file 'mysql-test/suite/binlog/t/binlog_delete_and_flush_index.test'
--- a/mysql-test/suite/binlog/t/binlog_delete_and_flush_index.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/t/binlog_delete_and_flush_index.test	2009-10-20 08:39:40 +0000
@@ -0,0 +1,114 @@
+# BUG#34582: FLUSH LOGS does not close and reopen the binlog index
+# file
+#
+# WHAT
+# ==== 
+#
+# We want to test that FLUSH LOGS closes and reopens binlog index
+# file.
+#
+# HOW
+# === 
+#
+#  PREPARE:
+#   1. create some binlog events
+#   2. show index content, binlog events and binlog contents 
+#      for mysql-bin.000001
+#   3. copy the mysql-bin.000001 to mysql-bin-b34582.000001
+#   4. change the index file so that mysql-bin.000001 is replaced 
+#      with mysql-bin-b34582.000001
+#   5. FLUSH the logs so that new index is closed and reopened
+#
+#  ASSERTIONS:
+#   1. index file contents shows mysql-bin-b34582.000001 and 
+#      mysql-bin.000002
+#   1. show binary logs shows current index entries
+#   2. binlog contents for mysql-bin-b34582.000001 are displayed
+#   3. Purge binlogs up to the latest one succeeds
+#   4. SHOW BINARY LOGS presents the latest one only after purging
+#   5. Purged binlogs files don't exist in the filesystem
+#   6. Not purged binlog file exists in the filesystem
+#
+#  CLEAN UP:
+#   1. RESET MASTER
+#
+
+-- source include/have_log_bin.inc
+
+RESET MASTER;
+
+-- let $datadir= `SELECT @@datadir`
+-- let $index=$datadir/master-bin.index
+-- chmod 0644 $index
+
+# action: issue one command so that binlog gets some event
+CREATE TABLE t1 (a int);
+
+-- echo ### assertion: index file contains regular entries
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- eval SET @index=LOAD_FILE('$index')
+-- replace_regex /\.[\\\/]master/master/
+SELECT @index;
+
+--echo ### assertion: show original binlogs
+-- source include/show_binary_logs.inc
+
+--echo ### assertion: binlog contents from regular entries
+-- source include/show_binlog_events.inc
+
+# action: copy binlogs to other names and change entries in index file
+-- copy_file $datadir/master-bin.000001 $datadir/master-bin-b34582.000001
+let INDEX_FILE=$index;
+perl;
+$file= $ENV{'INDEX_FILE'};
+open(FILE, ">$file") || die "Unable to open $file.";
+truncate(FILE,0);
+close ($file);
+EOF
+
+-- append_file $index 
+master-bin-b34582.000001
+EOF
+
+# action: should cause rotation, and creation of new binlogs
+FLUSH LOGS;
+
+# file is not used anymore - remove it (mysql closed on flush logs).
+-- remove_file $datadir/master-bin.000001
+
+-- echo ### assertion: index file contains renamed binlog and the new one
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- eval SET @index=LOAD_FILE('$index')
+-- replace_regex /\.[\\\/]master/master/
+SELECT @index;
+
+-- echo ### assertion: original binlog content still exists, despite we
+-- echo ###            renamed and changed the index file 
+-- source include/show_binlog_events.inc
+
+-- echo ### assertion: user changed binlog index shows correct entries
+-- source include/show_binary_logs.inc
+
+DROP TABLE t1;
+
+-- echo ### assertion: purging binlogs up to binlog created after instrumenting index file should work
+-- let $current_binlog= query_get_value(SHOW MASTER STATUS, File, 1)
+-- eval PURGE BINARY LOGS TO '$current_binlog'
+
+-- echo ### assertion: show binary logs should only contain latest binlog
+-- source include/show_binary_logs.inc
+
+-- echo ### assertion: assert that binlog files were indeed purged (using file_exists calls)
+-- error 1
+-- file_exists $datadir/master-bin-b34852.000001
+
+-- echo ### assertion: assert that not purged binlog file exists
+-- file_exists $datadir/$current_binlog
+
+-- echo ### assertion: show index file contents and these should match show binary logs issued above
+-- replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+-- eval SET @index=LOAD_FILE('$index')
+-- replace_regex /\.[\\\/]master/master/
+SELECT @index;
+
+RESET MASTER;

=== added file 'mysql-test/suite/binlog/t/binlog_mixed_failure_mixing_engines.test'
--- a/mysql-test/suite/binlog/t/binlog_mixed_failure_mixing_engines.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/t/binlog_mixed_failure_mixing_engines.test	2009-10-06 00:38:58 +0000
@@ -0,0 +1,4 @@
+--source include/have_binlog_format_mixed.inc
+--source include/have_innodb.inc
+
+--source extra/binlog_tests/binlog_failure_mixing_engines.test

=== added file 'mysql-test/suite/binlog/t/binlog_row_failure_mixing_engines.test'
--- a/mysql-test/suite/binlog/t/binlog_row_failure_mixing_engines.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/t/binlog_row_failure_mixing_engines.test	2009-10-06 00:38:58 +0000
@@ -0,0 +1,4 @@
+--source include/have_binlog_format_row.inc
+--source include/have_innodb.inc
+
+--source extra/binlog_tests/binlog_failure_mixing_engines.test

=== modified file 'mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_db_filter.test'
--- a/mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_db_filter.test	2009-06-07 22:28:08 +0000
+++ b/mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_db_filter.test	2009-09-30 02:31:25 +0000
@@ -112,17 +112,22 @@ while($i)
   # remove unecessary files
   -- remove_file $outfile.1
   -- remove_file $outfile.2
-
+  
+  #
+  # The two tests are canceled since we introduced the patch of bug#46998,  
+  # which will make mydsqlbinlog output the 'BEGIN', 'COMMIT' and 'ROLLBACK' 
+  # in regardless of database filtering
+  #
   # assertion: events for database test are filtered
-  if (`SELECT INSTR(@b42941_output.1, 'test')`)
-  {
-    -- echo **** ERROR **** Database name 'test' FOUND in mysqlbinlog output ($flags $outfile.1).
-  }
-
-  if (`SELECT INSTR(@b42941_output.2, 'test')`)
-  {
-    -- echo **** ERROR **** Database name 'test' FOUND in mysqlbinlog output ($flags $outfile.2).
-  }
+  #if (`SELECT INSTR(@b42941_output.1, 'test')`)
+  #{
+    #-- echo **** ERROR **** Database name 'test' FOUND in mysqlbinlog output ($flags $outfile.1).
+  #}
+
+  #if (`SELECT INSTR(@b42941_output.2, 'test')`)
+  #{
+    #-- echo **** ERROR **** Database name 'test' FOUND in mysqlbinlog output ($flags $outfile.2).
+  #}
 
   # assertion: events for database b42941 are not filtered
   if (!`SELECT INSTR(@b42941_output.1, 'b42941')`)

=== added file 'mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_verbose.test'
--- a/mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_verbose.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/t/binlog_row_mysqlbinlog_verbose.test	2009-10-14 13:25:11 +0000
@@ -0,0 +1,86 @@
+########################################################
+# Test mysqlbinlog command with Ndb produced Binlog
+# variants
+#
+# WHAT
+# ====
+#  This test aims to check that the mysqlbinlog --verbose
+#  command can output binlogs in 4 format variants, currently
+#  used by Ndb
+#
+#  1) Updates logged as write_row events
+#     Only primary key and updated columns included in the 
+#     event
+#  2) Updates logged as write_row_events
+#     All columns included in the event
+#  3) Updates logged as update_row events
+#     Only primary key and updated columns included in the
+#     event
+#  4) Updates logged as update_row events
+#     All columns included in the event
+#
+# Format variant (1) is the Ndb default.
+# Bug#47323 resulted in binlogs generated in format (1) 
+# being incorrectly parsed by the mysqlbinlog --verbose
+# option
+#
+# HOW
+# ===
+#  Row-based binlog files in each format have been 
+#  captured from an Ndb cluster
+#  These are output using the mysqlbinlog --verbose
+#  tool and the output is checked.
+#
+########################################################
+
+# We require binlog_format_row as we're independent of binlog format
+# and there's no point running the same test 3 times
+-- source include/have_binlog_format_row.inc
+
+--disable_query_log
+--let $binlog_file=write-partial-row.binlog
+--exec $MYSQL_BINLOG --verbose suite/binlog/std_data/$binlog_file > $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+create table raw_binlog_rows (txt varchar(1000));
+--eval load data local infile '$MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql' into table raw_binlog_rows columns terminated by '\n';
+--remove_file $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+--enable_query_log
+--echo Verbose statements from : $binlog_file
+# Output --verbose lines, with extra Windows CR's trimmed
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+drop table raw_binlog_rows;
+
+--disable_query_log
+--let $binlog_file=write-full-row.binlog
+--exec $MYSQL_BINLOG --verbose suite/binlog/std_data/$binlog_file > $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+create table raw_binlog_rows (txt varchar(1000));
+--eval load data local infile '$MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql' into table raw_binlog_rows columns terminated by '\n';
+--remove_file $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+--enable_query_log
+--echo Verbose statements from : $binlog_file
+# Output --verbose lines, with extra Windows CR's trimmed
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+drop table raw_binlog_rows;
+
+--disable_query_log
+--let $binlog_file=update-partial-row.binlog
+--exec $MYSQL_BINLOG --verbose suite/binlog/std_data/$binlog_file > $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+create table raw_binlog_rows (txt varchar(1000));
+--eval load data local infile '$MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql' into table raw_binlog_rows columns terminated by '\n';
+--remove_file $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+--enable_query_log
+--echo Verbose statements from : $binlog_file
+# Output --verbose lines, with extra Windows CR's trimmed
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+drop table raw_binlog_rows;
+
+--disable_query_log
+--let $binlog_file=update-full-row.binlog
+--exec $MYSQL_BINLOG --verbose suite/binlog/std_data/$binlog_file > $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+create table raw_binlog_rows (txt varchar(1000));
+--eval load data local infile '$MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql' into table raw_binlog_rows columns terminated by '\n';
+--remove_file $MYSQLTEST_VARDIR/tmp/mysqlbinlog_verbose.sql
+--enable_query_log
+--echo Verbose statements from : $binlog_file
+# Output --verbose lines, with extra Windows CR's trimmed
+select replace(txt,'\r', '') as stmt from raw_binlog_rows where txt like '###%';
+drop table raw_binlog_rows;

=== added file 'mysql-test/suite/binlog/t/binlog_stm_do_db-master.opt'
--- a/mysql-test/suite/binlog/t/binlog_stm_do_db-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/t/binlog_stm_do_db-master.opt	2009-09-24 14:52:52 +0000
@@ -0,0 +1 @@
+--binlog-do-db=b42829

=== added file 'mysql-test/suite/binlog/t/binlog_stm_do_db.test'
--- a/mysql-test/suite/binlog/t/binlog_stm_do_db.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/binlog/t/binlog_stm_do_db.test	2009-09-24 14:52:52 +0000
@@ -0,0 +1,90 @@
+# BUG#42829: binlogging enabled for all schemas regardless of
+# binlog-db-db / binlog-ignore-db
+#
+# WHAT
+# ====
+#
+#  We want to test whether filtered events from binlog will cause
+#  raising an error mentioning that statement is unable to be logged or
+#  not, when:
+#
+#   1. isolation level READ-COMMITTED; AND
+#
+#   2. using InnoDB engine; AND
+#
+#   3. using SBL (in which case InnoDB will only allow RBL).
+#
+# HOW
+# ===
+#
+#  The test is implemented as follows:
+#
+#     i) set tx_isolation to read-committed.
+#
+#    ii) create two databases (one filtered other not - using
+#        binlog-do-db)
+#
+#   iii) Create statements that are to be filtered on filtered db
+#
+#       - At this point, before fix, an error would be raised
+#
+#    iv) do the same thing for not the filtered database and check
+#        that events throw an error:
+#
+#      - Error: ER_BINLOG_STMT_MODE_AND_ROW_ENGINE
+#
+
+-- source include/have_log_bin.inc
+-- source include/have_innodb.inc
+-- source include/have_binlog_format_statement.inc
+
+SET @old_isolation_level= @@session.tx_isolation;
+SET @@session.tx_isolation= 'READ-COMMITTED';
+
+-- let $engine= InnoDB
+-- let $filtered= b42829_filtered
+-- let $not_filtered= b42829
+
+-- eval CREATE DATABASE $not_filtered
+-- eval use $not_filtered
+-- eval CREATE TABLE t1 (x int, y int) engine=$engine
+-- eval CREATE TABLE t2 (x int, y int) engine=$engine
+
+-- eval CREATE DATABASE $filtered
+-- eval use $filtered
+-- eval CREATE TABLE t1 (x int, y int) engine=$engine
+-- eval CREATE TABLE t2 (x int, y int) engine=$engine
+
+SET @@session.sql_log_bin= 0;
+-- eval INSERT INTO $filtered.t1 VALUES (100,100)
+-- eval INSERT INTO $not_filtered.t1 VALUES (100,100)
+SET @@session.sql_log_bin= 1;
+
+-- echo ### assertion: the inserts will not raise log error because
+-- echo ###            binlog-do-db is filtering used database
+INSERT INTO t2 VALUES (1,2), (1,3), (1,4);
+INSERT INTO t1 SELECT * FROM t2;
+
+-- echo ### assertion: assert that despite updating a not filtered
+-- echo ###            database this wont trigger an error as the
+-- echo ###            used database is the filtered one.
+-- eval UPDATE $filtered.t1 ft1, $not_filtered.t1 nft1 SET ft1.x=1, nft1.x=2
+
+-- eval use $not_filtered
+-- echo ### assertion: the statements *will* raise log error because
+-- echo ###            binlog-do-db is not filtering  used database 
+BEGIN;
+-- error ER_BINLOG_LOGGING_IMPOSSIBLE
+INSERT INTO t2 VALUES (1,2), (1,3), (1,4);
+-- error ER_BINLOG_LOGGING_IMPOSSIBLE
+-- eval UPDATE $filtered.t1 ft1, $not_filtered.t1 nft1 SET ft1.x=1, nft1.x=2
+-- error ER_BINLOG_LOGGING_IMPOSSIBLE
+INSERT INTO t1 SELECT * FROM t2;
+COMMIT;
+
+-- echo ### assertion: filtered events did not make into the binlog
+source include/show_binlog_events.inc;
+
+-- eval DROP DATABASE $not_filtered
+-- eval DROP DATABASE $filtered
+SET @@session.tx_isolation= @old_isolation_level;

=== modified file 'mysql-test/suite/binlog/t/binlog_stm_unsafe_warning.test'
--- a/mysql-test/suite/binlog/t/binlog_stm_unsafe_warning.test	2009-07-31 13:00:35 +0000
+++ b/mysql-test/suite/binlog/t/binlog_stm_unsafe_warning.test	2009-10-08 12:00:43 +0000
@@ -94,15 +94,24 @@ DROP TABLE t1;
 
 SET GLOBAL log_warnings = @old_log_warnings;
 
-let LOG_ERROR= `SELECT @@GLOBAL.log_error`;
+let $log_error_= `SELECT @@GLOBAL.log_error`;
+if(!`select LENGTH('$log_error_')`)
+{
+  # MySQL Server on windows is started with --console and thus
+  # does not know the location of its .err log, use default location
+  let $log_error_ = $MYSQLTEST_VARDIR/log/mysqld.1.err;
+}
+# Assign env variable LOG_ERROR
+let LOG_ERROR=$log_error_;
 
 --echo # Count the number of times the "Unsafe" message was printed
 --echo # to the error log.
 
 perl;
-  $log_error= $ENV{'LOG_ERROR'};
+  use strict;
+  my $log_error= $ENV{'LOG_ERROR'} or die "LOG_ERROR not set";
   open(FILE, "$log_error") or die("Unable to open $log_error: $!\n");
-  $count = () = grep(/Bug#46265/g,<FILE>);
+  my $count = () = grep(/Bug#46265/g,<FILE>);
   print "Occurrences: $count\n";
   close(FILE);
 EOF

=== added file 'mysql-test/suite/federated/federated_debug-master.opt'
--- a/mysql-test/suite/federated/federated_debug-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/federated/federated_debug-master.opt	2009-09-30 22:25:06 +0000
@@ -0,0 +1 @@
+--loose-debug=d,simulate_detached_thread_refresh

=== added file 'mysql-test/suite/federated/federated_debug.result'
--- a/mysql-test/suite/federated/federated_debug.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/federated/federated_debug.result	2009-09-30 22:25:06 +0000
@@ -0,0 +1,28 @@
+CREATE DATABASE federated;
+CREATE DATABASE federated;
+#
+# Bug#47525: MySQL crashed (Federated)
+#
+# Switch to slave
+CREATE TABLE t1(a INT);
+INSERT INTO t1 VALUES (1);
+# Switch to master
+CREATE TABLE t1(a INT) ENGINE=FEDERATED
+CONNECTION='mysql://root@127.0.0.1:SLAVE_PORT/test/t1';
+SELECT * FROM t1;
+a
+1
+# Start a asynchronous reload
+# Wait for tables to be closed
+# Ensure that the server didn't crash
+SELECT * FROM t1;
+a
+1
+# Drop tables on master and slave
+DROP TABLE t1;
+DROP TABLE t1;
+# Federated cleanup
+DROP TABLE IF EXISTS federated.t1;
+DROP DATABASE federated;
+DROP TABLE IF EXISTS federated.t1;
+DROP DATABASE federated;

=== added file 'mysql-test/suite/federated/federated_debug.test'
--- a/mysql-test/suite/federated/federated_debug.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/federated/federated_debug.test	2009-09-30 22:25:06 +0000
@@ -0,0 +1,39 @@
+--source include/have_debug.inc
+--source federated.inc
+
+--echo #
+--echo # Bug#47525: MySQL crashed (Federated)
+--echo #
+
+connection slave;
+--echo # Switch to slave
+CREATE TABLE t1(a INT);
+INSERT INTO t1 VALUES (1);
+
+connection master;
+--echo # Switch to master
+--replace_result $SLAVE_MYPORT SLAVE_PORT
+eval CREATE TABLE t1(a INT) ENGINE=FEDERATED
+  CONNECTION='mysql://root@127.0.0.1:$SLAVE_MYPORT/test/t1';
+
+SELECT * FROM t1;
+
+--echo # Start a asynchronous reload
+--exec $MYSQLADMIN --no-defaults -S $MASTER_MYSOCK -P $MASTER_MYPORT  -u root --password= refresh 2>&1
+
+--echo # Wait for tables to be closed
+let $show_statement= SHOW STATUS LIKE 'Open_tables';
+let $field= Value;
+let $condition= = '0';
+--source include/wait_show_condition.inc
+
+--echo # Ensure that the server didn't crash
+SELECT * FROM t1;
+--echo # Drop tables on master and slave
+DROP TABLE t1;
+connection slave;
+DROP TABLE t1;
+
+connection default;
+--echo # Federated cleanup
+source federated_cleanup.inc;

=== modified file 'mysql-test/suite/federated/my.cnf'
--- a/mysql-test/suite/federated/my.cnf	2007-12-12 17:19:24 +0000
+++ b/mysql-test/suite/federated/my.cnf	2009-09-30 22:25:06 +0000
@@ -9,4 +9,7 @@ log-bin=                 master-bin
 
 [ENV]
 MASTER_MYPORT=           @mysqld.1.port
+MASTER_MYSOCK=           @mysqld.1.socket
+
 SLAVE_MYPORT=            @mysqld.2.port
+SLAVE_MYSOCK=            @mysqld.2.socket

=== modified file 'mysql-test/suite/funcs_1/r/is_columns_mysql.result'
--- a/mysql-test/suite/funcs_1/r/is_columns_mysql.result	2009-03-13 09:16:32 +0000
+++ b/mysql-test/suite/funcs_1/r/is_columns_mysql.result	2009-10-28 09:23:02 +0000
@@ -130,7 +130,7 @@ NULL	mysql	procs_priv	Db	2		NO	char	64	1
 NULL	mysql	procs_priv	Grantor	6		NO	char	77	231	NULL	NULL	utf8	utf8_bin	char(77)	MUL		select,insert,update,references	
 NULL	mysql	procs_priv	Host	1		NO	char	60	180	NULL	NULL	utf8	utf8_bin	char(60)	PRI		select,insert,update,references	
 NULL	mysql	procs_priv	Proc_priv	7		NO	set	27	81	NULL	NULL	utf8	utf8_general_ci	set('Execute','Alter Routine','Grant')			select,insert,update,references	
-NULL	mysql	procs_priv	Routine_name	4		NO	char	64	192	NULL	NULL	utf8	utf8_bin	char(64)	PRI		select,insert,update,references	
+NULL	mysql	procs_priv	Routine_name	4		NO	char	64	192	NULL	NULL	utf8	utf8_general_ci	char(64)	PRI		select,insert,update,references	
 NULL	mysql	procs_priv	Routine_type	5	NULL	NO	enum	9	27	NULL	NULL	utf8	utf8_bin	enum('FUNCTION','PROCEDURE')	PRI		select,insert,update,references	
 NULL	mysql	procs_priv	Timestamp	8	CURRENT_TIMESTAMP	NO	timestamp	NULL	NULL	NULL	NULL	NULL	NULL	timestamp		on update CURRENT_TIMESTAMP	select,insert,update,references	
 NULL	mysql	procs_priv	User	3		NO	char	16	48	NULL	NULL	utf8	utf8_bin	char(16)	PRI		select,insert,update,references	
@@ -411,7 +411,7 @@ NULL	mysql	proc	modified	timestamp	NULL	
 3.0000	mysql	procs_priv	Host	char	60	180	utf8	utf8_bin	char(60)
 3.0000	mysql	procs_priv	Db	char	64	192	utf8	utf8_bin	char(64)
 3.0000	mysql	procs_priv	User	char	16	48	utf8	utf8_bin	char(16)
-3.0000	mysql	procs_priv	Routine_name	char	64	192	utf8	utf8_bin	char(64)
+3.0000	mysql	procs_priv	Routine_name	char	64	192	utf8	utf8_general_ci	char(64)
 3.0000	mysql	procs_priv	Routine_type	enum	9	27	utf8	utf8_bin	enum('FUNCTION','PROCEDURE')
 3.0000	mysql	procs_priv	Grantor	char	77	231	utf8	utf8_bin	char(77)
 3.0000	mysql	procs_priv	Proc_priv	set	27	81	utf8	utf8_general_ci	set('Execute','Alter Routine','Grant')

=== modified file 'mysql-test/suite/funcs_1/r/is_statistics.result'
--- a/mysql-test/suite/funcs_1/r/is_statistics.result	2008-03-07 19:18:14 +0000
+++ b/mysql-test/suite/funcs_1/r/is_statistics.result	2009-10-28 09:23:02 +0000
@@ -166,8 +166,8 @@ NULL	db_datadict_2	t4	0	db_datadict_2	PR
 SHOW GRANTS FOR 'testuser1'@'localhost';
 Grants for testuser1@localhost
 GRANT USAGE ON *.* TO 'testuser1'@'localhost'
-GRANT SELECT (f5, f1) ON `db_datadict_2`.`t3` TO 'testuser1'@'localhost'
 GRANT SELECT ON `db_datadict`.`t1` TO 'testuser1'@'localhost' WITH GRANT OPTION
+GRANT SELECT (f5, f1) ON `db_datadict_2`.`t3` TO 'testuser1'@'localhost'
 SHOW GRANTS FOR 'testuser2'@'localhost';
 Grants for testuser2@localhost
 GRANT USAGE ON *.* TO 'testuser2'@'localhost'
@@ -185,8 +185,8 @@ NULL	db_datadict_2	t3	0	db_datadict_2	PR
 SHOW GRANTS FOR 'testuser1'@'localhost';
 Grants for testuser1@localhost
 GRANT USAGE ON *.* TO 'testuser1'@'localhost'
-GRANT SELECT (f5, f1) ON `db_datadict_2`.`t3` TO 'testuser1'@'localhost'
 GRANT SELECT ON `db_datadict`.`t1` TO 'testuser1'@'localhost' WITH GRANT OPTION
+GRANT SELECT (f5, f1) ON `db_datadict_2`.`t3` TO 'testuser1'@'localhost'
 SHOW GRANTS FOR 'testuser2'@'localhost';
 ERROR 42000: Access denied for user 'testuser1'@'localhost' to database 'mysql'
 # Switch to connection testuser2

=== added file 'mysql-test/suite/innodb/r/innodb-consistent.result'
--- a/mysql-test/suite/innodb/r/innodb-consistent.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/r/innodb-consistent.result	2009-10-09 13:37:47 +0000
@@ -0,0 +1,35 @@
+drop table if exists t1;
+set session transaction isolation level read committed;
+create table t1(a int not null) engine=innodb DEFAULT CHARSET=latin1;
+create table t2 like t1;
+insert into t2 values (1),(2),(3),(4),(5),(6),(7);
+set autocommit=0;
+begin;
+replace into t1 select * from t2;
+set session transaction isolation level read committed;
+set autocommit=0;
+delete from t2 where a=5;
+commit;
+delete from t2;
+commit;
+commit;
+begin;
+insert into t1 select * from t2;
+set session transaction isolation level read committed;
+set autocommit=0;
+delete from t2 where a=5;
+commit;
+delete from t2;
+commit;
+commit;
+select * from t1;
+a
+1
+2
+3
+4
+5
+6
+7
+drop table t1;
+drop table t2;

=== modified file 'mysql-test/suite/innodb/r/innodb-zip.result'
--- a/mysql-test/suite/innodb/r/innodb-zip.result	2009-06-10 13:51:20 +0000
+++ b/mysql-test/suite/innodb/r/innodb-zip.result	2009-11-03 10:21:39 +0000
@@ -141,7 +141,7 @@ drop table t1;
 CREATE TABLE t1(c TEXT, PRIMARY KEY (c(440)))
 ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=1 CHARSET=ASCII;
 ERROR 42000: Row size too large. The maximum row size for the used table type, not counting BLOBs, is 8126. You have to change some columns to TEXT or BLOBs
-CREATE TABLE t1(c TEXT, PRIMARY KEY (c(439)))
+CREATE TABLE t1(c TEXT, PRIMARY KEY (c(438)))
 ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=1 CHARSET=ASCII;
 INSERT INTO t1 VALUES(REPEAT('A',512)),(REPEAT('B',512));
 DROP TABLE t1;
@@ -196,15 +196,15 @@ drop table t1;
 set innodb_strict_mode = on;
 create table t1 (id int primary key) engine = innodb key_block_size = 0;
 ERROR HY000: Can't create table 'test.t1' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: invalid KEY_BLOCK_SIZE = 0. Valid values are [1, 2, 4, 8, 16]
+Warning	1478	InnoDB: invalid KEY_BLOCK_SIZE = 0. Valid values are [1, 2, 4, 8, 16]
 Error	1005	Can't create table 'test.t1' (errno: 1478)
 create table t2 (id int primary key) engine = innodb key_block_size = 9;
 ERROR HY000: Can't create table 'test.t2' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
+Warning	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
 Error	1005	Can't create table 'test.t2' (errno: 1478)
 create table t3 (id int primary key) engine = innodb key_block_size = 1;
 create table t4 (id int primary key) engine = innodb key_block_size = 2;
@@ -233,30 +233,30 @@ key_block_size = 8 row_format = compress
 create table t2 (id int primary key) engine = innodb
 key_block_size = 8 row_format = redundant;
 ERROR HY000: Can't create table 'test.t2' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: cannot specify ROW_FORMAT = REDUNDANT with KEY_BLOCK_SIZE.
+Warning	1478	InnoDB: cannot specify ROW_FORMAT = REDUNDANT with KEY_BLOCK_SIZE.
 Error	1005	Can't create table 'test.t2' (errno: 1478)
 create table t3 (id int primary key) engine = innodb
 key_block_size = 8 row_format = compact;
 ERROR HY000: Can't create table 'test.t3' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: cannot specify ROW_FORMAT = COMPACT with KEY_BLOCK_SIZE.
+Warning	1478	InnoDB: cannot specify ROW_FORMAT = COMPACT with KEY_BLOCK_SIZE.
 Error	1005	Can't create table 'test.t3' (errno: 1478)
 create table t4 (id int primary key) engine = innodb
 key_block_size = 8 row_format = dynamic;
 ERROR HY000: Can't create table 'test.t4' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: cannot specify ROW_FORMAT = DYNAMIC with KEY_BLOCK_SIZE.
+Warning	1478	InnoDB: cannot specify ROW_FORMAT = DYNAMIC with KEY_BLOCK_SIZE.
 Error	1005	Can't create table 'test.t4' (errno: 1478)
 create table t5 (id int primary key) engine = innodb
 key_block_size = 8 row_format = default;
 ERROR HY000: Can't create table 'test.t5' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: cannot specify ROW_FORMAT = COMPACT with KEY_BLOCK_SIZE.
+Warning	1478	InnoDB: cannot specify ROW_FORMAT = COMPACT with KEY_BLOCK_SIZE.
 Error	1005	Can't create table 'test.t5' (errno: 1478)
 SELECT table_schema, table_name, row_format
 FROM information_schema.tables WHERE engine='innodb';
@@ -266,26 +266,26 @@ drop table t1;
 create table t1 (id int primary key) engine = innodb
 key_block_size = 9 row_format = redundant;
 ERROR HY000: Can't create table 'test.t1' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
-Error	1478	InnoDB: cannot specify ROW_FORMAT = REDUNDANT with KEY_BLOCK_SIZE.
+Warning	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
+Warning	1478	InnoDB: cannot specify ROW_FORMAT = REDUNDANT with KEY_BLOCK_SIZE.
 Error	1005	Can't create table 'test.t1' (errno: 1478)
 create table t2 (id int primary key) engine = innodb
 key_block_size = 9 row_format = compact;
 ERROR HY000: Can't create table 'test.t2' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
-Error	1478	InnoDB: cannot specify ROW_FORMAT = COMPACT with KEY_BLOCK_SIZE.
+Warning	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
+Warning	1478	InnoDB: cannot specify ROW_FORMAT = COMPACT with KEY_BLOCK_SIZE.
 Error	1005	Can't create table 'test.t2' (errno: 1478)
 create table t2 (id int primary key) engine = innodb
 key_block_size = 9 row_format = dynamic;
 ERROR HY000: Can't create table 'test.t2' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
-Error	1478	InnoDB: cannot specify ROW_FORMAT = DYNAMIC with KEY_BLOCK_SIZE.
+Warning	1478	InnoDB: invalid KEY_BLOCK_SIZE = 9. Valid values are [1, 2, 4, 8, 16]
+Warning	1478	InnoDB: cannot specify ROW_FORMAT = DYNAMIC with KEY_BLOCK_SIZE.
 Error	1005	Can't create table 'test.t2' (errno: 1478)
 SELECT table_schema, table_name, row_format
 FROM information_schema.tables WHERE engine='innodb';
@@ -293,45 +293,45 @@ table_schema	table_name	row_format
 set global innodb_file_per_table = off;
 create table t1 (id int primary key) engine = innodb key_block_size = 1;
 ERROR HY000: Can't create table 'test.t1' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
 Error	1005	Can't create table 'test.t1' (errno: 1478)
 create table t2 (id int primary key) engine = innodb key_block_size = 2;
 ERROR HY000: Can't create table 'test.t2' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
 Error	1005	Can't create table 'test.t2' (errno: 1478)
 create table t3 (id int primary key) engine = innodb key_block_size = 4;
 ERROR HY000: Can't create table 'test.t3' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
 Error	1005	Can't create table 'test.t3' (errno: 1478)
 create table t4 (id int primary key) engine = innodb key_block_size = 8;
 ERROR HY000: Can't create table 'test.t4' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
 Error	1005	Can't create table 'test.t4' (errno: 1478)
 create table t5 (id int primary key) engine = innodb key_block_size = 16;
 ERROR HY000: Can't create table 'test.t5' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_per_table.
 Error	1005	Can't create table 'test.t5' (errno: 1478)
 create table t6 (id int primary key) engine = innodb row_format = compressed;
 ERROR HY000: Can't create table 'test.t6' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: ROW_FORMAT=COMPRESSED requires innodb_file_per_table.
+Warning	1478	InnoDB: ROW_FORMAT=COMPRESSED requires innodb_file_per_table.
 Error	1005	Can't create table 'test.t6' (errno: 1478)
 create table t7 (id int primary key) engine = innodb row_format = dynamic;
 ERROR HY000: Can't create table 'test.t7' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: ROW_FORMAT=DYNAMIC requires innodb_file_per_table.
+Warning	1478	InnoDB: ROW_FORMAT=DYNAMIC requires innodb_file_per_table.
 Error	1005	Can't create table 'test.t7' (errno: 1478)
 create table t8 (id int primary key) engine = innodb row_format = compact;
 create table t9 (id int primary key) engine = innodb row_format = redundant;
@@ -345,45 +345,45 @@ set global innodb_file_per_table = on;
 set global innodb_file_format = `0`;
 create table t1 (id int primary key) engine = innodb key_block_size = 1;
 ERROR HY000: Can't create table 'test.t1' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
 Error	1005	Can't create table 'test.t1' (errno: 1478)
 create table t2 (id int primary key) engine = innodb key_block_size = 2;
 ERROR HY000: Can't create table 'test.t2' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
 Error	1005	Can't create table 'test.t2' (errno: 1478)
 create table t3 (id int primary key) engine = innodb key_block_size = 4;
 ERROR HY000: Can't create table 'test.t3' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
 Error	1005	Can't create table 'test.t3' (errno: 1478)
 create table t4 (id int primary key) engine = innodb key_block_size = 8;
 ERROR HY000: Can't create table 'test.t4' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
 Error	1005	Can't create table 'test.t4' (errno: 1478)
 create table t5 (id int primary key) engine = innodb key_block_size = 16;
 ERROR HY000: Can't create table 'test.t5' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
+Warning	1478	InnoDB: KEY_BLOCK_SIZE requires innodb_file_format > Antelope.
 Error	1005	Can't create table 'test.t5' (errno: 1478)
 create table t6 (id int primary key) engine = innodb row_format = compressed;
 ERROR HY000: Can't create table 'test.t6' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: ROW_FORMAT=COMPRESSED requires innodb_file_format > Antelope.
+Warning	1478	InnoDB: ROW_FORMAT=COMPRESSED requires innodb_file_format > Antelope.
 Error	1005	Can't create table 'test.t6' (errno: 1478)
 create table t7 (id int primary key) engine = innodb row_format = dynamic;
 ERROR HY000: Can't create table 'test.t7' (errno: 1478)
-show errors;
+show warnings;
 Level	Code	Message
-Error	1478	InnoDB: ROW_FORMAT=DYNAMIC requires innodb_file_format > Antelope.
+Warning	1478	InnoDB: ROW_FORMAT=DYNAMIC requires innodb_file_format > Antelope.
 Error	1005	Can't create table 'test.t7' (errno: 1478)
 create table t8 (id int primary key) engine = innodb row_format = compact;
 create table t9 (id int primary key) engine = innodb row_format = redundant;

=== added file 'mysql-test/suite/innodb/r/innodb_bug44571.result'
--- a/mysql-test/suite/innodb/r/innodb_bug44571.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/r/innodb_bug44571.result	2009-10-08 11:28:37 +0000
@@ -0,0 +1,9 @@
+CREATE TABLE bug44571 (foo INT) ENGINE=InnoDB;
+ALTER TABLE bug44571 CHANGE foo bar INT;
+ALTER TABLE bug44571 ADD INDEX bug44571b (foo);
+ERROR 42000: Key column 'foo' doesn't exist in table
+ALTER TABLE bug44571 ADD INDEX bug44571b (bar);
+ERROR HY000: Incorrect key file for table 'bug44571'; try to repair it
+CREATE INDEX bug44571b ON bug44571 (bar);
+ERROR HY000: Incorrect key file for table 'bug44571'; try to repair it
+DROP TABLE bug44571;

=== modified file 'mysql-test/suite/innodb/r/innodb_file_format.result'
--- a/mysql-test/suite/innodb/r/innodb_file_format.result	2009-07-30 12:42:56 +0000
+++ b/mysql-test/suite/innodb/r/innodb_file_format.result	2009-09-02 16:58:17 +0000
@@ -1,3 +1,4 @@
+call mtr.add_suppression("InnoDB: invalid innodb_file_format_check value");
 select @@innodb_file_format;
 @@innodb_file_format
 Antelope

=== added file 'mysql-test/suite/innodb/t/innodb-consistent-master.opt'
--- a/mysql-test/suite/innodb/t/innodb-consistent-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/t/innodb-consistent-master.opt	2009-10-09 13:37:47 +0000
@@ -0,0 +1 @@
+--innodb_lock_wait_timeout=2

=== added file 'mysql-test/suite/innodb/t/innodb-consistent.test'
--- a/mysql-test/suite/innodb/t/innodb-consistent.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/t/innodb-consistent.test	2009-10-09 13:37:47 +0000
@@ -0,0 +1,59 @@
+-- source include/not_embedded.inc
+-- source include/have_innodb.inc
+-- source suite/innodb/include/have_innodb_plugin.inc
+
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+
+# REPLACE INTO ... SELECT and INSERT INTO ... SELECT should do
+# a consistent read of the source table.
+
+connect (a,localhost,root,,);
+connect (b,localhost,root,,);
+connection a;
+set session transaction isolation level read committed;
+create table t1(a int not null) engine=innodb DEFAULT CHARSET=latin1;
+create table t2 like t1;
+insert into t2 values (1),(2),(3),(4),(5),(6),(7);
+set autocommit=0;
+
+# REPLACE INTO ... SELECT case
+begin;
+# this should not result in any locks on t2.
+replace into t1 select * from t2;
+
+connection b;
+set session transaction isolation level read committed;
+set autocommit=0;
+# should not cuase a lock wait.
+delete from t2 where a=5;
+commit;
+delete from t2;
+commit;
+connection a;
+commit;
+
+# INSERT INTO ... SELECT case
+begin;
+# this should not result in any locks on t2.
+insert into t1 select * from t2;
+
+connection b;
+set session transaction isolation level read committed;
+set autocommit=0;
+# should not cuase a lock wait.
+delete from t2 where a=5;
+commit;
+delete from t2;
+commit;
+connection a;
+commit;
+
+select * from t1;
+drop table t1;
+drop table t2;
+
+connection default;
+disconnect a;
+disconnect b;

=== modified file 'mysql-test/suite/innodb/t/innodb-zip.test'
--- a/mysql-test/suite/innodb/t/innodb-zip.test	2009-06-24 17:18:58 +0000
+++ b/mysql-test/suite/innodb/t/innodb-zip.test	2009-11-03 10:20:18 +0000
@@ -106,7 +106,7 @@ drop table t1;
 --error ER_TOO_BIG_ROWSIZE
 CREATE TABLE t1(c TEXT, PRIMARY KEY (c(440)))
 ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=1 CHARSET=ASCII;
-CREATE TABLE t1(c TEXT, PRIMARY KEY (c(439)))
+CREATE TABLE t1(c TEXT, PRIMARY KEY (c(438)))
 ENGINE=InnoDB ROW_FORMAT=COMPRESSED KEY_BLOCK_SIZE=1 CHARSET=ASCII;
 INSERT INTO t1 VALUES(REPEAT('A',512)),(REPEAT('B',512));
 DROP TABLE t1;
@@ -175,11 +175,11 @@ set innodb_strict_mode = on;
 
 --error ER_CANT_CREATE_TABLE
 create table t1 (id int primary key) engine = innodb key_block_size = 0;
-show errors;
+show warnings;
 
 --error ER_CANT_CREATE_TABLE
 create table t2 (id int primary key) engine = innodb key_block_size = 9;
-show errors;
+show warnings;
 
 
 create table t3 (id int primary key) engine = innodb key_block_size = 1;
@@ -205,22 +205,22 @@ key_block_size = 8 row_format = compress
 --error ER_CANT_CREATE_TABLE
 create table t2 (id int primary key) engine = innodb
 key_block_size = 8 row_format = redundant;
-show errors;
+show warnings;
 
 --error ER_CANT_CREATE_TABLE
 create table t3 (id int primary key) engine = innodb
 key_block_size = 8 row_format = compact;
-show errors;
+show warnings;
 
 --error ER_CANT_CREATE_TABLE
 create table t4 (id int primary key) engine = innodb
 key_block_size = 8 row_format = dynamic;
-show errors;
+show warnings;
 
 --error ER_CANT_CREATE_TABLE
 create table t5 (id int primary key) engine = innodb
 key_block_size = 8 row_format = default;
-show errors;
+show warnings;
 
 SELECT table_schema, table_name, row_format
 FROM information_schema.tables WHERE engine='innodb';
@@ -230,17 +230,17 @@ drop table t1;
 --error ER_CANT_CREATE_TABLE
 create table t1 (id int primary key) engine = innodb
 key_block_size = 9 row_format = redundant;
-show errors;
+show warnings;
 
 --error ER_CANT_CREATE_TABLE
 create table t2 (id int primary key) engine = innodb
 key_block_size = 9 row_format = compact;
-show errors;
+show warnings;
 
 --error ER_CANT_CREATE_TABLE
 create table t2 (id int primary key) engine = innodb
 key_block_size = 9 row_format = dynamic;
-show errors;
+show warnings;
 
 SELECT table_schema, table_name, row_format
 FROM information_schema.tables WHERE engine='innodb';
@@ -250,25 +250,25 @@ set global innodb_file_per_table = off;
 
 --error ER_CANT_CREATE_TABLE
 create table t1 (id int primary key) engine = innodb key_block_size = 1;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t2 (id int primary key) engine = innodb key_block_size = 2;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t3 (id int primary key) engine = innodb key_block_size = 4;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t4 (id int primary key) engine = innodb key_block_size = 8;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t5 (id int primary key) engine = innodb key_block_size = 16;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t6 (id int primary key) engine = innodb row_format = compressed;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t7 (id int primary key) engine = innodb row_format = dynamic;
-show errors;
+show warnings;
 create table t8 (id int primary key) engine = innodb row_format = compact;
 create table t9 (id int primary key) engine = innodb row_format = redundant;
 
@@ -282,25 +282,25 @@ set global innodb_file_format = `0`; 
 
 --error ER_CANT_CREATE_TABLE
 create table t1 (id int primary key) engine = innodb key_block_size = 1;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t2 (id int primary key) engine = innodb key_block_size = 2;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t3 (id int primary key) engine = innodb key_block_size = 4;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t4 (id int primary key) engine = innodb key_block_size = 8;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t5 (id int primary key) engine = innodb key_block_size = 16;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t6 (id int primary key) engine = innodb row_format = compressed;
-show errors;
+show warnings;
 --error ER_CANT_CREATE_TABLE
 create table t7 (id int primary key) engine = innodb row_format = dynamic;
-show errors;
+show warnings;
 create table t8 (id int primary key) engine = innodb row_format = compact;
 create table t9 (id int primary key) engine = innodb row_format = redundant;
 

=== added file 'mysql-test/suite/innodb/t/innodb_bug44571.test'
--- a/mysql-test/suite/innodb/t/innodb_bug44571.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/t/innodb_bug44571.test	2009-10-08 11:28:37 +0000
@@ -0,0 +1,18 @@
+#
+# Bug#44571 InnoDB Plugin crashes on ADD INDEX
+# http://bugs.mysql.com/44571
+#
+-- source include/have_innodb.inc
+-- source suite/innodb/include/have_innodb_plugin.inc
+
+CREATE TABLE bug44571 (foo INT) ENGINE=InnoDB;
+ALTER TABLE bug44571 CHANGE foo bar INT;
+-- error ER_KEY_COLUMN_DOES_NOT_EXITS
+ALTER TABLE bug44571 ADD INDEX bug44571b (foo);
+# The following will fail, because the CHANGE foo bar was
+# not communicated to InnoDB.
+--error ER_NOT_KEYFILE
+ALTER TABLE bug44571 ADD INDEX bug44571b (bar);
+--error ER_NOT_KEYFILE
+CREATE INDEX bug44571b ON bug44571 (bar);
+DROP TABLE bug44571;

=== modified file 'mysql-test/suite/innodb/t/innodb_file_format.test'
--- a/mysql-test/suite/innodb/t/innodb_file_format.test	2009-07-30 12:42:56 +0000
+++ b/mysql-test/suite/innodb/t/innodb_file_format.test	2009-09-02 16:58:17 +0000
@@ -1,6 +1,8 @@
 -- source include/have_innodb.inc
 -- source suite/innodb/include/have_innodb_plugin.inc
 
+call mtr.add_suppression("InnoDB: invalid innodb_file_format_check value");
+
 let $format=`select @@innodb_file_format`;
 let $innodb_file_format_check_orig=`select @@innodb_file_format_check`;
 

=== modified file 'mysql-test/suite/innodb/t/innodb_information_schema.test'
--- a/mysql-test/suite/innodb/t/innodb_information_schema.test	2009-06-24 17:18:58 +0000
+++ b/mysql-test/suite/innodb/t/innodb_information_schema.test	2009-11-03 10:04:18 +0000
@@ -110,14 +110,18 @@ SELECT * FROM ```t'\"_str` WHERE c1 = '3
 -- send
 SELECT * FROM ```t'\"_str` WHERE c1 = '4' FOR UPDATE;
 
-# Give time to the above 2 queries to execute before continuing.
-# Without this sleep it sometimes happens that the SELECT from innodb_locks
-# executes before some of them, resulting in less than expected number
-# of rows being selected from innodb_locks.
--- sleep 0.1
-
 -- enable_result_log
 -- connection con_verify_innodb_locks
+# Wait for the above queries to execute before continuing.
+# Without this, it sometimes happens that the SELECT from innodb_locks
+# executes before some of them, resulting in less than expected number
+# of rows being selected from innodb_locks. If there is a bug and there
+# are no 14 rows in innodb_locks then this test will fail with timeout.
+let $count = 14;
+let $table = INFORMATION_SCHEMA.INNODB_LOCKS;
+-- source include/wait_until_rows_count.inc
+# the above enables the query log, re-disable it
+-- disable_query_log
 SELECT lock_mode, lock_type, lock_table, lock_index, lock_rec, lock_data
 FROM INFORMATION_SCHEMA.INNODB_LOCKS ORDER BY lock_data;
 

=== modified file 'mysql-test/suite/parts/inc/partition_auto_increment.inc'
--- a/mysql-test/suite/parts/inc/partition_auto_increment.inc	2009-02-18 21:35:28 +0000
+++ b/mysql-test/suite/parts/inc/partition_auto_increment.inc	2009-09-04 03:57:11 +0000
@@ -623,3 +623,195 @@ SHOW CREATE TABLE t1;
 SELECT * FROM t1 ORDER BY c1;
 DROP TABLE t1;
 
+if (!$skip_negative_auto_inc)
+{
+--echo #############################################################################
+--echo # Bug #45823 - Assertion failure in file row/row0mysql.c line 1386
+--echo # Bug #43988 - AUTO_INCREMENT errors with partitioned InnoDB tables in 5.1.31
+--echo ##############################################################################
+
+--echo # Inserting negative autoincrement values into a partition table (partitions >= 4)
+
+eval CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 4;
+
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Reading from a partition table (partitions >= 2 ) after inserting a negative
+--echo # value into the auto increment column
+
+
+eval CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 2;
+
+INSERT INTO t VALUES (-2,-20);
+INSERT INTO t(c2) VALUES (30);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Inserting negative auto increment value into a partition table (partitions >= 2)
+--echo # auto increment value > 2.
+
+eval CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 2;
+
+INSERT INTO t VALUES (-4,-20);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Inserting -1 into autoincrement column of a partition table (partition >= 4)
+
+eval CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 4;
+
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+INSERT INTO t(c2) VALUES (30);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Deleting from an auto increment table after inserting negative values
+
+eval CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 4; 
+
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t VALUES (-3,-20);
+INSERT INTO t(c2) VALUES (40);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+if (!$skip_delete)
+{ 
+DELETE FROM t WHERE c1 > 1;
+}
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Inserting a positive value that exceeds maximum allowed value for an
+--echo # Auto Increment column (positive maximum)
+
+eval CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 4;
+
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+
+--error ER_DUP_ENTRY
+INSERT INTO t VALUES (128,50);
+--error ER_DUP_ENTRY 
+INSERT INTO t VALUES (129,60);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Inserting a negative value that goes below minimum allowed value for an
+--echo # Auto Increment column (negative minimum)
+
+eval CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 4;
+
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-127,30);
+INSERT INTO t VALUES (-128,40);
+
+--error ER_DUP_ENTRY
+INSERT INTO t VALUES (-129,50);
+--error ER_DUP_ENTRY
+INSERT INTO t VALUES (-130,60);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Updating the partition table with a negative Auto Increment value
+
+eval CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 4;
+
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+if (!$skip_update)
+{ 
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+}
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+INSERT INTO t(c2) VALUES (40);
+INSERT INTO t(c2) VALUES (50);
+
+if (!$skip_update)
+{ 
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+}
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo # Updating the partition table with a value that crosses the upper limits
+--echo # on both the positive and the negative side.
+
+eval CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+  c2 INT) ENGINE=$engine PARTITION BY HASH(c1) PARTITIONS 4;
+
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+if (!$skip_update)
+{ 
+UPDATE t SET c1 = 130 where c1 = 127;
+}
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+if (!$skip_update)
+{ 
+UPDATE t SET c1 = -140 where c1 = 126;
+}
+
+SELECT * FROM t ORDER BY c1 ASC;
+
+DROP TABLE t;
+
+--echo ##############################################################################
+}

=== modified file 'mysql-test/suite/parts/r/partition_auto_increment_innodb.result'
--- a/mysql-test/suite/parts/r/partition_auto_increment_innodb.result	2009-02-05 17:47:24 +0000
+++ b/mysql-test/suite/parts/r/partition_auto_increment_innodb.result	2009-09-04 03:57:11 +0000
@@ -825,3 +825,194 @@ c1
 4
 5
 DROP TABLE t1;
+#############################################################################
+# Bug #45823 - Assertion failure in file row/row0mysql.c line 1386
+# Bug #43988 - AUTO_INCREMENT errors with partitioned InnoDB tables in 5.1.31
+##############################################################################
+# Inserting negative autoincrement values into a partition table (partitions >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DROP TABLE t;
+# Reading from a partition table (partitions >= 2 ) after inserting a negative
+# value into the auto increment column
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-2,-20);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-2	-20
+1	30
+DROP TABLE t;
+# Inserting negative auto increment value into a partition table (partitions >= 2)
+# auto increment value > 2.
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-4,-20);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-4	-20
+1	30
+2	40
+DROP TABLE t;
+# Inserting -1 into autoincrement column of a partition table (partition >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+DROP TABLE t;
+# Deleting from an auto increment table after inserting negative values
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t VALUES (-3,-20);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DELETE FROM t WHERE c1 > 1;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+DROP TABLE t;
+# Inserting a positive value that exceeds maximum allowed value for an
+# Auto Increment column (positive maximum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+INSERT INTO t VALUES (128,50);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+INSERT INTO t VALUES (129,60);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+DROP TABLE t;
+# Inserting a negative value that goes below minimum allowed value for an
+# Auto Increment column (negative minimum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-127,30);
+INSERT INTO t VALUES (-128,40);
+INSERT INTO t VALUES (-129,50);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+INSERT INTO t VALUES (-130,60);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	40
+-127	30
+1	10
+2	20
+DROP TABLE t;
+# Updating the partition table with a negative Auto Increment value
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+INSERT INTO t(c2) VALUES (40);
+INSERT INTO t(c2) VALUES (50);
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+4	40
+5	50
+DROP TABLE t;
+# Updating the partition table with a value that crosses the upper limits
+# on both the positive and the negative side.
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='InnoDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = 130 where c1 = 127;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = -140 where c1 = 126;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	30
+1	10
+2	20
+127	40
+DROP TABLE t;
+##############################################################################

=== modified file 'mysql-test/suite/parts/r/partition_auto_increment_maria.result'
--- a/mysql-test/suite/parts/r/partition_auto_increment_maria.result	2009-04-01 10:06:41 +0000
+++ b/mysql-test/suite/parts/r/partition_auto_increment_maria.result	2009-11-10 15:15:12 +0000
@@ -870,3 +870,194 @@ c1
 4
 5
 DROP TABLE t1;
+#############################################################################
+# Bug #45823 - Assertion failure in file row/row0mysql.c line 1386
+# Bug #43988 - AUTO_INCREMENT errors with partitioned InnoDB tables in 5.1.31
+##############################################################################
+# Inserting negative autoincrement values into a partition table (partitions >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DROP TABLE t;
+# Reading from a partition table (partitions >= 2 ) after inserting a negative
+# value into the auto increment column
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-2,-20);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-2	-20
+1	30
+DROP TABLE t;
+# Inserting negative auto increment value into a partition table (partitions >= 2)
+# auto increment value > 2.
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-4,-20);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-4	-20
+1	30
+2	40
+DROP TABLE t;
+# Inserting -1 into autoincrement column of a partition table (partition >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+DROP TABLE t;
+# Deleting from an auto increment table after inserting negative values
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t VALUES (-3,-20);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DELETE FROM t WHERE c1 > 1;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+DROP TABLE t;
+# Inserting a positive value that exceeds maximum allowed value for an
+# Auto Increment column (positive maximum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+INSERT INTO t VALUES (128,50);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+INSERT INTO t VALUES (129,60);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+DROP TABLE t;
+# Inserting a negative value that goes below minimum allowed value for an
+# Auto Increment column (negative minimum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-127,30);
+INSERT INTO t VALUES (-128,40);
+INSERT INTO t VALUES (-129,50);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+INSERT INTO t VALUES (-130,60);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	40
+-127	30
+1	10
+2	20
+DROP TABLE t;
+# Updating the partition table with a negative Auto Increment value
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+INSERT INTO t(c2) VALUES (40);
+INSERT INTO t(c2) VALUES (50);
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+4	40
+5	50
+DROP TABLE t;
+# Updating the partition table with a value that crosses the upper limits
+# on both the positive and the negative side.
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MARIA' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = 130 where c1 = 127;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = -140 where c1 = 126;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	30
+1	10
+2	20
+127	40
+DROP TABLE t;
+##############################################################################

=== modified file 'mysql-test/suite/parts/r/partition_auto_increment_memory.result'
--- a/mysql-test/suite/parts/r/partition_auto_increment_memory.result	2009-07-08 12:11:34 +0000
+++ b/mysql-test/suite/parts/r/partition_auto_increment_memory.result	2009-09-04 03:57:11 +0000
@@ -851,3 +851,194 @@ c1
 4
 5
 DROP TABLE t1;
+#############################################################################
+# Bug #45823 - Assertion failure in file row/row0mysql.c line 1386
+# Bug #43988 - AUTO_INCREMENT errors with partitioned InnoDB tables in 5.1.31
+##############################################################################
+# Inserting negative autoincrement values into a partition table (partitions >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DROP TABLE t;
+# Reading from a partition table (partitions >= 2 ) after inserting a negative
+# value into the auto increment column
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-2,-20);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-2	-20
+1	30
+DROP TABLE t;
+# Inserting negative auto increment value into a partition table (partitions >= 2)
+# auto increment value > 2.
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-4,-20);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-4	-20
+1	30
+2	40
+DROP TABLE t;
+# Inserting -1 into autoincrement column of a partition table (partition >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+DROP TABLE t;
+# Deleting from an auto increment table after inserting negative values
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t VALUES (-3,-20);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DELETE FROM t WHERE c1 > 1;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+DROP TABLE t;
+# Inserting a positive value that exceeds maximum allowed value for an
+# Auto Increment column (positive maximum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+INSERT INTO t VALUES (128,50);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+INSERT INTO t VALUES (129,60);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+DROP TABLE t;
+# Inserting a negative value that goes below minimum allowed value for an
+# Auto Increment column (negative minimum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-127,30);
+INSERT INTO t VALUES (-128,40);
+INSERT INTO t VALUES (-129,50);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+INSERT INTO t VALUES (-130,60);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	40
+-127	30
+1	10
+2	20
+DROP TABLE t;
+# Updating the partition table with a negative Auto Increment value
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+INSERT INTO t(c2) VALUES (40);
+INSERT INTO t(c2) VALUES (50);
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+4	40
+5	50
+DROP TABLE t;
+# Updating the partition table with a value that crosses the upper limits
+# on both the positive and the negative side.
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='Memory' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = 130 where c1 = 127;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = -140 where c1 = 126;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	30
+1	10
+2	20
+127	40
+DROP TABLE t;
+##############################################################################

=== modified file 'mysql-test/suite/parts/r/partition_auto_increment_myisam.result'
--- a/mysql-test/suite/parts/r/partition_auto_increment_myisam.result	2009-07-08 12:11:34 +0000
+++ b/mysql-test/suite/parts/r/partition_auto_increment_myisam.result	2009-09-04 03:57:11 +0000
@@ -870,3 +870,194 @@ c1
 4
 5
 DROP TABLE t1;
+#############################################################################
+# Bug #45823 - Assertion failure in file row/row0mysql.c line 1386
+# Bug #43988 - AUTO_INCREMENT errors with partitioned InnoDB tables in 5.1.31
+##############################################################################
+# Inserting negative autoincrement values into a partition table (partitions >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DROP TABLE t;
+# Reading from a partition table (partitions >= 2 ) after inserting a negative
+# value into the auto increment column
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-2,-20);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-2	-20
+1	30
+DROP TABLE t;
+# Inserting negative auto increment value into a partition table (partitions >= 2)
+# auto increment value > 2.
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-4,-20);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-4	-20
+1	30
+2	40
+DROP TABLE t;
+# Inserting -1 into autoincrement column of a partition table (partition >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+DROP TABLE t;
+# Deleting from an auto increment table after inserting negative values
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t VALUES (-3,-20);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DELETE FROM t WHERE c1 > 1;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+DROP TABLE t;
+# Inserting a positive value that exceeds maximum allowed value for an
+# Auto Increment column (positive maximum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+INSERT INTO t VALUES (128,50);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+INSERT INTO t VALUES (129,60);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+DROP TABLE t;
+# Inserting a negative value that goes below minimum allowed value for an
+# Auto Increment column (negative minimum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-127,30);
+INSERT INTO t VALUES (-128,40);
+INSERT INTO t VALUES (-129,50);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+INSERT INTO t VALUES (-130,60);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	40
+-127	30
+1	10
+2	20
+DROP TABLE t;
+# Updating the partition table with a negative Auto Increment value
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+INSERT INTO t(c2) VALUES (40);
+INSERT INTO t(c2) VALUES (50);
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+4	40
+5	50
+DROP TABLE t;
+# Updating the partition table with a value that crosses the upper limits
+# on both the positive and the negative side.
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='MyISAM' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = 130 where c1 = 127;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = -140 where c1 = 126;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	30
+1	10
+2	20
+127	40
+DROP TABLE t;
+##############################################################################

=== modified file 'mysql-test/suite/parts/r/partition_auto_increment_ndb.result'
--- a/mysql-test/suite/parts/r/partition_auto_increment_ndb.result	2009-02-18 21:35:28 +0000
+++ b/mysql-test/suite/parts/r/partition_auto_increment_ndb.result	2009-09-04 03:57:11 +0000
@@ -846,3 +846,194 @@ c1
 4
 5
 DROP TABLE t1;
+#############################################################################
+# Bug #45823 - Assertion failure in file row/row0mysql.c line 1386
+# Bug #43988 - AUTO_INCREMENT errors with partitioned InnoDB tables in 5.1.31
+##############################################################################
+# Inserting negative autoincrement values into a partition table (partitions >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DROP TABLE t;
+# Reading from a partition table (partitions >= 2 ) after inserting a negative
+# value into the auto increment column
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-2,-20);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-2	-20
+1	30
+DROP TABLE t;
+# Inserting negative auto increment value into a partition table (partitions >= 2)
+# auto increment value > 2.
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 2;
+INSERT INTO t VALUES (-4,-20);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-4	-20
+1	30
+2	40
+DROP TABLE t;
+# Inserting -1 into autoincrement column of a partition table (partition >= 4)
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+DROP TABLE t;
+# Deleting from an auto increment table after inserting negative values
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+INSERT INTO t VALUES (-3,-20);
+INSERT INTO t(c2) VALUES (40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+2	20
+3	30
+4	40
+DELETE FROM t WHERE c1 > 1;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-3	-20
+-1	-10
+1	10
+DROP TABLE t;
+# Inserting a positive value that exceeds maximum allowed value for an
+# Auto Increment column (positive maximum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+INSERT INTO t VALUES (128,50);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+INSERT INTO t VALUES (129,60);
+ERROR 23000: Duplicate entry '127' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+DROP TABLE t;
+# Inserting a negative value that goes below minimum allowed value for an
+# Auto Increment column (negative minimum)
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-127,30);
+INSERT INTO t VALUES (-128,40);
+INSERT INTO t VALUES (-129,50);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+INSERT INTO t VALUES (-130,60);
+ERROR 23000: Duplicate entry '-128' for key 'PRIMARY'
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	40
+-127	30
+1	10
+2	20
+DROP TABLE t;
+# Updating the partition table with a negative Auto Increment value
+CREATE TABLE t (c1 INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (-1,-10);
+INSERT INTO t(c2) VALUES (30);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-1	-10
+1	10
+2	20
+3	30
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+INSERT INTO t(c2) VALUES (40);
+INSERT INTO t(c2) VALUES (50);
+UPDATE t SET c1 = -6 WHERE c1 = 2;
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-6	20
+-1	-10
+1	10
+3	30
+4	40
+5	50
+DROP TABLE t;
+# Updating the partition table with a value that crosses the upper limits
+# on both the positive and the negative side.
+CREATE TABLE t (c1 TINYINT NOT NULL AUTO_INCREMENT, PRIMARY KEY(c1),
+c2 INT) ENGINE='NDB' PARTITION BY HASH(c1) PARTITIONS 4;
+INSERT INTO t(c2) VALUES (10);
+INSERT INTO t(c2) VALUES (20);
+INSERT INTO t VALUES (126,30);
+INSERT INTO t VALUES (127,40);
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = 130 where c1 = 127;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+1	10
+2	20
+126	30
+127	40
+UPDATE t SET c1 = -140 where c1 = 126;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+SELECT * FROM t ORDER BY c1 ASC;
+c1	c2
+-128	30
+1	10
+2	20
+127	40
+DROP TABLE t;
+##############################################################################

=== modified file 'mysql-test/suite/parts/r/partition_recover_myisam.result'
--- a/mysql-test/suite/parts/r/partition_recover_myisam.result	2008-08-19 09:44:22 +0000
+++ b/mysql-test/suite/parts/r/partition_recover_myisam.result	2009-08-29 21:29:47 +0000
@@ -1,3 +1,5 @@
+call mtr.add_suppression("./test/t1_will_crash");
+call mtr.add_suppression("Got an error from unknown thread, ha_myisam.cc");
 CREATE TABLE t1_will_crash (a INT, KEY (a)) ENGINE=MyISAM;
 INSERT INTO t1_will_crash VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11);
 FLUSH TABLES;

=== modified file 'mysql-test/suite/parts/t/partition_auto_increment_archive.test'
--- a/mysql-test/suite/parts/t/partition_auto_increment_archive.test	2008-09-08 13:30:01 +0000
+++ b/mysql-test/suite/parts/t/partition_auto_increment_archive.test	2009-09-04 03:57:11 +0000
@@ -30,6 +30,9 @@ let $skip_delete= 1;
 let $skip_truncate= 1;
 let $skip_update= 1;
 let $only_ai_pk= 1;
+# Bug#45823 Assertion failure in file row/row0mysql.c line 1386
+# Archive does not handle negative autoincrement values correctly
+let $skip_negative_auto_inc= 1;
 
 ##### Storage engine to be tested
 let $engine= 'Archive';

=== modified file 'mysql-test/suite/parts/t/partition_auto_increment_blackhole.test'
--- a/mysql-test/suite/parts/t/partition_auto_increment_blackhole.test	2008-09-08 13:30:01 +0000
+++ b/mysql-test/suite/parts/t/partition_auto_increment_blackhole.test	2009-09-04 03:57:11 +0000
@@ -25,6 +25,9 @@
 #------------------------------------------------------------------------------#
 # Engine specific settings and requirements
 --source include/have_blackhole.inc
+# Bug#45823 Assertion failure in file row/row0mysql.c line 1386
+# Blackhole does not handle negative autoincrement values correctly
+let $skip_negative_auto_inc= 1;
 
 ##### Storage engine to be tested
 let $engine= 'Blackhole';

=== modified file 'mysql-test/suite/parts/t/partition_recover_myisam.test'
--- a/mysql-test/suite/parts/t/partition_recover_myisam.test	2009-10-09 08:09:24 +0000
+++ b/mysql-test/suite/parts/t/partition_recover_myisam.test	2009-11-10 15:15:12 +0000
@@ -1,4 +1,8 @@
 # test the auto-recover (--myisam-recover) of partitioned myisam tables
+
+call mtr.add_suppression("./test/t1_will_crash");
+call mtr.add_suppression("Got an error from unknown thread, ha_myisam.cc");
+
 --source include/have_partition.inc
 --disable_warnings
 --disable_query_log

=== modified file 'mysql-test/suite/rpl/r/rpl_auto_increment.result'
--- a/mysql-test/suite/rpl/r/rpl_auto_increment.result	2009-04-08 16:55:26 +0000
+++ b/mysql-test/suite/rpl/r/rpl_auto_increment.result	2009-11-10 15:15:12 +0000
@@ -244,3 +244,71 @@ t1	CREATE TABLE `t1` (
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
 drop table t1;
+stop slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+reset master;
+reset slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+start slave;
+DROP TABLE IF EXISTS t1;
+DROP TABLE IF EXISTS t2;
+CREATE TABLE t1 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY) ENGINE=innodb;
+CREATE TABLE t2 (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY) ENGINE=myisam;
+SET SQL_MODE='';
+INSERT INTO t1 VALUES(NULL);
+INSERT INTO t2 VALUES(NULL);
+SELECT * FROM t1;
+id
+1
+SELECT * FROM t2;
+id
+1
+INSERT INTO t1 VALUES();
+INSERT INTO t2 VALUES();
+SELECT * FROM t1;
+id
+1
+2
+SELECT * FROM t2;
+id
+1
+2
+INSERT INTO t1 VALUES(0);
+INSERT INTO t2 VALUES(0);
+SELECT * FROM t1;
+id
+1
+2
+3
+SELECT * FROM t2;
+id
+1
+2
+3
+SET SQL_MODE=NO_AUTO_VALUE_ON_ZERO;
+INSERT INTO t1 VALUES(0);
+INSERT INTO t2 VALUES(0);
+SELECT * FROM t1;
+id
+0
+1
+2
+3
+SELECT * FROM t2;
+id
+0
+1
+2
+3
+INSERT INTO t1 VALUES(4);
+INSERT INTO t2 VALUES(4);
+FLUSH LOGS;
+Comparing tables master:test.t1 and slave:test.t1
+Comparing tables master:test.t2 and slave:test.t2
+DROP TABLE t1;
+DROP TABLE t2;
+Comparing tables master:test.t1 and slave:test.t1
+Comparing tables master:test.t2 and slave:test.t2
+DROP TABLE t1;
+DROP TABLE t2;
+SET SQL_MODE='';

=== added file 'mysql-test/suite/rpl/r/rpl_auto_increment_update_failure.result'
--- a/mysql-test/suite/rpl/r/rpl_auto_increment_update_failure.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_auto_increment_update_failure.result	2009-09-30 23:19:36 +0000
@@ -0,0 +1,1041 @@
+stop slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+reset master;
+reset slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+start slave;
+# Test case1: INVOKES A TRIGGER with after insert action
+create table t1(a int, b int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr1 after insert on t1 for each row insert into t2(a) values(6);
+create table t3(a int, b int) engine=innodb;
+create table t4(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t5(a int) engine=innodb;
+create trigger tr2 after insert on t3 for each row begin
+insert into t4(a) values(f1_insert_triggered());
+insert into t4(a) values(f1_insert_triggered());
+insert into t5(a) values(8);
+end |
+create table t6(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_insert_triggered() RETURNS INTEGER
+BEGIN
+INSERT INTO t6(a) values(2),(3);
+RETURN 1;
+END//
+begin;
+insert into t1(a,b) values(1,1),(2,1);
+insert into t3(a,b) values(1,1),(2,1);
+update t1 set a = a + 5 where b = 1;
+update t3 set a = a + 5 where b = 1;
+delete from t1 where b = 1;
+delete from t3 where b = 1;
+insert into t2(a) values(3);
+insert into t4(a) values(3);
+commit;
+insert into t1(a,b) values(4,2);
+insert into t3(a,b) values(4,2);
+update t1 set a = a + 5 where b = 2;
+update t3 set a = a + 5 where b = 2;
+delete from t1 where b = 2;
+delete from t3 where b = 2;
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; insert into t4(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	#	use `test`; update t1 set a = a + 5 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t1 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'INVOKES A TRIGGER with after insert action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t4 and slave:test.t4
+Comparing tables master:test.t6 and slave:test.t6
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+DROP TABLE t5;
+DROP TABLE t6;
+DROP FUNCTION f1_insert_triggered;
+# Test case2: INVOKES A TRIGGER with before insert action
+create table t1(a int, b int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr1 before insert on t1 for each row insert into t2(a) values(6);
+create table t3(a int, b int) engine=innodb;
+create table t4(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t5(a int) engine=innodb;
+create trigger tr2 before insert on t3 for each row begin
+insert into t4(a) values(f1_insert_triggered());
+insert into t4(a) values(f1_insert_triggered());
+insert into t5(a) values(8);
+end |
+create table t6(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_insert_triggered() RETURNS INTEGER
+BEGIN
+INSERT INTO t6(a) values(2),(3);
+RETURN 1;
+END//
+begin;
+insert into t1(a,b) values(1,1),(2,1);
+insert into t3(a,b) values(1,1),(2,1);
+update t1 set a = a + 5 where b = 1;
+update t3 set a = a + 5 where b = 1;
+delete from t1 where b = 1;
+delete from t3 where b = 1;
+insert into t2(a) values(3);
+insert into t4(a) values(3);
+commit;
+insert into t1(a,b) values(4,2);
+insert into t3(a,b) values(4,2);
+update t1 set a = a + 5 where b = 2;
+update t3 set a = a + 5 where b = 2;
+delete from t1 where b = 2;
+delete from t3 where b = 2;
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; insert into t4(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	#	use `test`; update t1 set a = a + 5 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t1 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'INVOKES A TRIGGER with before insert action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t4 and slave:test.t4
+Comparing tables master:test.t6 and slave:test.t6
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+DROP TABLE t5;
+DROP TABLE t6;
+DROP FUNCTION f1_insert_triggered;
+# Test case3: INVOKES A TRIGGER with after update action
+create table t1(a int, b int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr1 after update on t1 for each row insert into t2(a) values(6);
+create table t3(a int, b int) engine=innodb;
+create table t4(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t5(a int) engine=innodb;
+create trigger tr2 after update on t3 for each row begin
+insert into t4(a) values(f1_insert_triggered());
+insert into t4(a) values(f1_insert_triggered());
+insert into t5(a) values(8);
+end |
+create table t6(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_insert_triggered() RETURNS INTEGER
+BEGIN
+INSERT INTO t6(a) values(2),(3);
+RETURN 1;
+END//
+begin;
+insert into t1(a,b) values(1,1),(2,1);
+insert into t3(a,b) values(1,1),(2,1);
+update t1 set a = a + 5 where b = 1;
+update t3 set a = a + 5 where b = 1;
+delete from t1 where b = 1;
+delete from t3 where b = 1;
+insert into t2(a) values(3);
+insert into t4(a) values(3);
+commit;
+insert into t1(a,b) values(4,2);
+insert into t3(a,b) values(4,2);
+update t1 set a = a + 5 where b = 2;
+update t3 set a = a + 5 where b = 2;
+delete from t1 where b = 2;
+delete from t3 where b = 2;
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; insert into t4(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(1,1),(2,1)
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(1,1),(2,1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	#	use `test`; delete from t1 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'INVOKES A TRIGGER with after update action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t4 and slave:test.t4
+Comparing tables master:test.t6 and slave:test.t6
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+DROP TABLE t5;
+DROP TABLE t6;
+DROP FUNCTION f1_insert_triggered;
+# Test case4: INVOKES A TRIGGER with before update action
+create table t1(a int, b int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr1 before update on t1 for each row insert into t2(a) values(6);
+create table t3(a int, b int) engine=innodb;
+create table t4(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t5(a int) engine=innodb;
+create trigger tr2 before update on t3 for each row begin
+insert into t4(a) values(f1_insert_triggered());
+insert into t4(a) values(f1_insert_triggered());
+insert into t5(a) values(8);
+end |
+create table t6(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_insert_triggered() RETURNS INTEGER
+BEGIN
+INSERT INTO t6(a) values(2),(3);
+RETURN 1;
+END//
+begin;
+insert into t1(a,b) values(1,1),(2,1);
+insert into t3(a,b) values(1,1),(2,1);
+update t1 set a = a + 5 where b = 1;
+update t3 set a = a + 5 where b = 1;
+delete from t1 where b = 1;
+delete from t3 where b = 1;
+insert into t2(a) values(3);
+insert into t4(a) values(3);
+commit;
+insert into t1(a,b) values(4,2);
+insert into t3(a,b) values(4,2);
+update t1 set a = a + 5 where b = 2;
+update t3 set a = a + 5 where b = 2;
+delete from t1 where b = 2;
+delete from t3 where b = 2;
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; insert into t4(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(1,1),(2,1)
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(1,1),(2,1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 1
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Update_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t1 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; delete from t3 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'INVOKES A TRIGGER with before update action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t4 and slave:test.t4
+Comparing tables master:test.t6 and slave:test.t6
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+DROP TABLE t5;
+DROP TABLE t6;
+DROP FUNCTION f1_insert_triggered;
+# Test case5: INVOKES A TRIGGER with after delete action
+create table t1(a int, b int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr1 after delete on t1 for each row insert into t2(a) values(6);
+create table t3(a int, b int) engine=innodb;
+create table t4(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t5(a int) engine=innodb;
+create trigger tr2 after delete on t3 for each row begin
+insert into t4(a) values(f1_insert_triggered());
+insert into t4(a) values(f1_insert_triggered());
+insert into t5(a) values(8);
+end |
+create table t6(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_insert_triggered() RETURNS INTEGER
+BEGIN
+INSERT INTO t6(a) values(2),(3);
+RETURN 1;
+END//
+begin;
+insert into t1(a,b) values(1,1),(2,1);
+insert into t3(a,b) values(1,1),(2,1);
+update t1 set a = a + 5 where b = 1;
+update t3 set a = a + 5 where b = 1;
+delete from t1 where b = 1;
+delete from t3 where b = 1;
+insert into t2(a) values(3);
+insert into t4(a) values(3);
+commit;
+insert into t1(a,b) values(4,2);
+insert into t3(a,b) values(4,2);
+update t1 set a = a + 5 where b = 2;
+update t3 set a = a + 5 where b = 2;
+delete from t1 where b = 2;
+delete from t3 where b = 2;
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; insert into t4(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(1,1),(2,1)
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(1,1),(2,1)
+master-bin.000001	#	Query	#	#	use `test`; update t1 set a = a + 5 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 1
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t1 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'INVOKES A TRIGGER with after delete action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t4 and slave:test.t4
+Comparing tables master:test.t6 and slave:test.t6
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+DROP TABLE t5;
+DROP TABLE t6;
+DROP FUNCTION f1_insert_triggered;
+# Test case6: INVOKES A TRIGGER with before delete action
+create table t1(a int, b int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr1 before delete on t1 for each row insert into t2(a) values(6);
+create table t3(a int, b int) engine=innodb;
+create table t4(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t5(a int) engine=innodb;
+create trigger tr2 before delete on t3 for each row begin
+insert into t4(a) values(f1_insert_triggered());
+insert into t4(a) values(f1_insert_triggered());
+insert into t5(a) values(8);
+end |
+create table t6(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_insert_triggered() RETURNS INTEGER
+BEGIN
+INSERT INTO t6(a) values(2),(3);
+RETURN 1;
+END//
+begin;
+insert into t1(a,b) values(1,1),(2,1);
+insert into t3(a,b) values(1,1),(2,1);
+update t1 set a = a + 5 where b = 1;
+update t3 set a = a + 5 where b = 1;
+delete from t1 where b = 1;
+delete from t3 where b = 1;
+insert into t2(a) values(3);
+insert into t4(a) values(3);
+commit;
+insert into t1(a,b) values(4,2);
+insert into t3(a,b) values(4,2);
+update t1 set a = a + 5 where b = 2;
+update t3 set a = a + 5 where b = 2;
+delete from t1 where b = 2;
+delete from t3 where b = 2;
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; insert into t4(a) values(3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(1,1),(2,1)
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(1,1),(2,1)
+master-bin.000001	#	Query	#	#	use `test`; update t1 set a = a + 5 where b = 1
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 1
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; insert into t3(a,b) values(4,2)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t1 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Query	#	#	use `test`; update t3 set a = a + 5 where b = 2
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t5)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t4)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t6)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Delete_rows	#	#	table_id: # flags: STMT_END_F
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'INVOKES A TRIGGER with before delete action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t4 and slave:test.t4
+Comparing tables master:test.t6 and slave:test.t6
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+DROP TABLE t5;
+DROP TABLE t6;
+DROP FUNCTION f1_insert_triggered;
+# Test case7: CALLS A FUNCTION which INVOKES A TRIGGER with after insert action
+create table t1(a int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t3(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_two_inserts_trigger() RETURNS INTEGER
+BEGIN
+INSERT INTO t2(a) values(2),(3);
+INSERT INTO t2(a) values(2),(3);
+RETURN 1;
+END |
+create trigger tr11 after insert on t2 for each row begin
+insert into t3(a) values(new.a);
+insert into t3(a) values(new.a);
+end |
+begin;
+insert into t1(a) values(f1_two_inserts_trigger());
+insert into t2(a) values(4),(5);
+commit;
+insert into t1(a) values(f1_two_inserts_trigger());
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'CALLS A FUNCTION which INVOKES A TRIGGER with after insert action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t3 and slave:test.t3
+drop table t1;
+drop table t2;
+drop table t3;
+drop function f1_two_inserts_trigger;
+# Test case8: CALLS A FUNCTION which INVOKES A TRIGGER with before insert action
+create table t1(a int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create table t3(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_two_inserts_trigger() RETURNS INTEGER
+BEGIN
+INSERT INTO t2(a) values(2),(3);
+INSERT INTO t2(a) values(2),(3);
+RETURN 1;
+END |
+create trigger tr11 before insert on t2 for each row begin
+insert into t3(a) values(new.a);
+insert into t3(a) values(new.a);
+end |
+begin;
+insert into t1(a) values(f1_two_inserts_trigger());
+insert into t2(a) values(4),(5);
+commit;
+insert into t1(a) values(f1_two_inserts_trigger());
+# To verify if insert/update in an autoinc column causes statement to be logged in row format
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t1)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t2)
+master-bin.000001	#	Table_map	#	#	table_id: # (test.t3)
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+master-bin.000001	#	Write_rows	#	#	table_id: #
+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	#	Xid	#	#	COMMIT /* XID */
+commit;
+#Test if the results are consistent on master and slave
+#for 'CALLS A FUNCTION which INVOKES A TRIGGER with before insert action'
+Comparing tables master:test.t2 and slave:test.t2
+Comparing tables master:test.t3 and slave:test.t3
+drop table t1;
+drop table t2;
+drop table t3;
+drop function f1_two_inserts_trigger;
+# Test case9: INSERT DATA INTO VIEW WHICH INVOKES TRIGGERS with after insert action
+CREATE TABLE t1(i1 int not null auto_increment, c1 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t2(i1 int not null auto_increment, c2 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t3(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr16 after insert on t1 for each row insert into t3(a) values(new.c1);
+create trigger tr17 after insert on t2 for each row insert into t3(a) values(new.c2);
+begin;
+INSERT INTO t1(c1) VALUES (11), (12);
+INSERT INTO t2(c2) VALUES (13), (14);
+CREATE VIEW v16 AS SELECT c1, c2 FROM t1, t2;
+INSERT INTO v16(c1) VALUES (15),(16);
+INSERT INTO v16(c2) VALUES (17),(18);
+INSERT INTO v16(c1) VALUES (19),(20);
+INSERT INTO v16(c2) VALUES (21),(22);
+INSERT INTO v16(c1) VALUES (23), (24);
+INSERT INTO v16(c1) VALUES (25), (26);
+commit;
+#Test if the results are consistent on master and slave
+#for 'INSERT DATA INTO VIEW WHICH INVOKES TRIGGERS'
+Comparing tables master:test.t3 and slave:test.t3
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP VIEW  v16;
+# Test case10: INSERT DATA INTO VIEW WHICH INVOKES TRIGGERS with before insert action
+CREATE TABLE t1(i1 int not null auto_increment, c1 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t2(i1 int not null auto_increment, c2 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t3(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+create trigger tr16 before insert on t1 for each row insert into t3(a) values(new.c1);
+create trigger tr17 before insert on t2 for each row insert into t3(a) values(new.c2);
+begin;
+INSERT INTO t1(c1) VALUES (11), (12);
+INSERT INTO t2(c2) VALUES (13), (14);
+CREATE VIEW v16 AS SELECT c1, c2 FROM t1, t2;
+INSERT INTO v16(c1) VALUES (15),(16);
+INSERT INTO v16(c2) VALUES (17),(18);
+INSERT INTO v16(c1) VALUES (19),(20);
+INSERT INTO v16(c2) VALUES (21),(22);
+INSERT INTO v16(c1) VALUES (23), (24);
+INSERT INTO v16(c1) VALUES (25), (26);
+commit;
+#Test if the results are consistent on master and slave
+#for 'INSERT DATA INTO VIEW WHICH INVOKES TRIGGERS'
+Comparing tables master:test.t3 and slave:test.t3
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP VIEW  v16;
+# Test case11: INVOKES A FUNCTION TO INSERT TWO OR MORE VALUES INTO A TABLE WITH AUTOINC COLUMN
+create table t1(a int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_two_inserts() RETURNS INTEGER
+BEGIN
+INSERT INTO t2(a) values(2);
+INSERT INTO t2(a) values(2);
+RETURN 1;
+END//
+begin;
+insert into t1(a) values(f1_two_inserts());
+insert into t2(a) values(4),(5);
+commit;
+insert into t1(a) values(f1_two_inserts());
+commit;
+#Test result for INVOKES A FUNCTION TO INSERT TWO OR MORE VALUES on master
+select * from t2 ORDER BY i1;
+i1	a
+1	2
+2	2
+3	4
+4	5
+5	2
+6	2
+#Test result for INVOKES A FUNCTION TO INSERT TWO OR MORE VALUES on slave
+select * from t2 ORDER BY i1;
+i1	a
+1	2
+2	2
+3	4
+4	5
+5	2
+6	2
+drop table t1;
+drop table t2;
+drop function f1_two_inserts;
+# Test case12: INVOKES A FUNCTION TO UPDATE TWO OR MORE VALUES OF A TABLE WITH AUTOINC COLUMN
+create table t1(a int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, b int, primary key(i1)) engine=innodb;
+CREATE FUNCTION f1_two_updates() RETURNS INTEGER
+BEGIN
+update t2 set a = a + 5 where b = 1;
+update t2 set a = a + 5 where b = 2;
+update t2 set a = a + 5 where b = 3;
+update t2 set a = a + 5 where b = 4;
+RETURN 1;
+END//
+insert into t2(a,b) values(1,1);
+insert into t2(a,b) values(2,2);
+insert into t2(a,b) values(3,3);
+insert into t2(a,b) values(4,4);
+insert into t1(a) values(f1_two_updates());
+begin;
+insert into t1(a) values(f1_two_updates());
+commit;
+#Test result for INVOKES A FUNCTION TO UPDATE TWO OR MORE VALUES on master
+select * from t2 ORDER BY i1;
+i1	a	b
+1	11	1
+2	12	2
+3	13	3
+4	14	4
+#Test result for INVOKES A FUNCTION TO UPDATE TWO OR MORE VALUES on slave
+select * from t2 ORDER BY i1;
+i1	a	b
+1	11	1
+2	12	2
+3	13	3
+4	14	4
+drop table t1;
+drop table t2;
+drop function f1_two_updates;
+# Test case13: UPDATE MORE THAN ONE TABLES ON TOP-STATEMENT
+create table t1(i1 int not null auto_increment, a int, b int, primary key(i1)) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, b int, primary key(i1)) engine=innodb;
+begin;
+insert into t1(a,b) values(1,1),(2,2);
+insert into t2(a,b) values(1,1),(2,2);
+update t1,t2 set t1.a=t1.a+5, t2.a=t2.a+5 where t1.b=t2.b;
+insert into t1(a,b) values(3,3);
+insert into t2(a,b) values(3,3);
+commit;
+# To verify if it works fine when these statements are not be marked as unsafe
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=1
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(1,1),(2,2)
+master-bin.000001	#	Intvar	#	#	INSERT_ID=1
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a,b) values(1,1),(2,2)
+master-bin.000001	#	Query	#	#	use `test`; update t1,t2 set t1.a=t1.a+5, t2.a=t2.a+5 where t1.b=t2.b
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t1(a,b) values(3,3)
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; insert into t2(a,b) values(3,3)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+#Test if the results are consistent on master and slave
+#for 'UPDATE MORE THAN ONE TABLES ON TOP-STATEMENT'
+Comparing tables master:test.t1 and slave:test.t1
+Comparing tables master:test.t2 and slave:test.t2
+drop table t1;
+drop table t2;
+# Test case14: INSERT DATA INTO VIEW WHICH INVOLVED MORE THAN ONE TABLES
+CREATE TABLE t1(i1 int not null auto_increment, c1 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t2(i1 int not null auto_increment, c2 INT, primary key(i1)) engine=innodb;
+begin;
+INSERT INTO t1(c1) VALUES (11), (12);
+INSERT INTO t2(c2) VALUES (13), (14);
+CREATE VIEW v15 AS SELECT c1, c2 FROM t1, t2;
+INSERT INTO v15(c1) VALUES (15),(16);
+INSERT INTO v15(c2) VALUES (17),(18);
+INSERT INTO v15(c1) VALUES (19),(20);
+INSERT INTO v15(c2) VALUES (21),(22);
+INSERT INTO v15(c1) VALUES (23), (24);
+INSERT INTO v15(c2) VALUES (25), (26);
+commit;
+# To verify if it works fine when these statements are not be marked as unsafe
+show binlog events from <binlog_start>;
+Log_name	Pos	Event_type	Server_id	End_log_pos	Info
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=1
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t1(c1) VALUES (11), (12)
+master-bin.000001	#	Intvar	#	#	INSERT_ID=1
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO t2(c2) VALUES (13), (14)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	use `test`; CREATE ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v15` AS SELECT c1, c2 FROM t1, t2
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO v15(c1) VALUES (15),(16)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=3
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO v15(c2) VALUES (17),(18)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO v15(c1) VALUES (19),(20)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=5
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO v15(c2) VALUES (21),(22)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=7
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO v15(c1) VALUES (23), (24)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+master-bin.000001	#	Query	#	#	BEGIN
+master-bin.000001	#	Intvar	#	#	INSERT_ID=7
+master-bin.000001	#	Query	#	#	use `test`; INSERT INTO v15(c2) VALUES (25), (26)
+master-bin.000001	#	Xid	#	#	COMMIT /* XID */
+#Test if the results are consistent on master and slave
+#for 'INSERT DATA INTO VIEW WHICH INVOLVED MORE THAN ONE TABLES'
+Comparing tables master:test.t1 and slave:test.t1
+Comparing tables master:test.t2 and slave:test.t2
+drop table t1;
+drop table t2;
+drop view  v15;

=== modified file 'mysql-test/suite/rpl/r/rpl_bug33931.result'
--- a/mysql-test/suite/rpl/r/rpl_bug33931.result	2009-02-11 11:56:25 +0000
+++ b/mysql-test/suite/rpl/r/rpl_bug33931.result	2009-08-28 14:13:27 +0000
@@ -1,5 +1,5 @@
 reset master;
-call mtr.add_suppression("Failed during slave thread initialization");
+call mtr.add_suppression("Failed during slave I/O thread initialization");
 stop slave;
 reset slave;
 SET GLOBAL debug="d,simulate_io_slave_error_on_init,simulate_sql_slave_error_on_init";

=== modified file 'mysql-test/suite/rpl/r/rpl_do_grant.result'
--- a/mysql-test/suite/rpl/r/rpl_do_grant.result	2009-03-18 13:48:23 +0000
+++ b/mysql-test/suite/rpl/r/rpl_do_grant.result	2009-09-01 11:38:17 +0000
@@ -166,4 +166,7 @@ DROP FUNCTION upgrade_del_func;
 DROP FUNCTION upgrade_alter_func;
 DROP DATABASE bug42217_db;
 DROP USER 'create_rout_db'@'localhost';
+call mtr.add_suppression("Slave: Operation DROP USER failed for 'create_rout_db'@'localhost' Error_code: 1396");
+USE mtr;
+call mtr.add_suppression("Slave: Operation DROP USER failed for 'create_rout_db'@'localhost' Error_code: 1396");
 "End of test"

=== modified file 'mysql-test/suite/rpl/r/rpl_extraCol_innodb.result'
--- a/mysql-test/suite/rpl/r/rpl_extraCol_innodb.result	2008-11-04 07:43:21 +0000
+++ b/mysql-test/suite/rpl/r/rpl_extraCol_innodb.result	2009-08-28 14:13:27 +0000
@@ -4,6 +4,7 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+call mtr.add_suppression("Slave: Unknown table 't6' Error_code: 1051");
 **** Diff Table Def Start ****
 *** On Slave ***
 STOP SLAVE;

=== modified file 'mysql-test/suite/rpl/r/rpl_extraCol_myisam.result'
--- a/mysql-test/suite/rpl/r/rpl_extraCol_myisam.result	2008-11-04 07:43:21 +0000
+++ b/mysql-test/suite/rpl/r/rpl_extraCol_myisam.result	2009-08-28 14:13:27 +0000
@@ -4,6 +4,7 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+call mtr.add_suppression("Slave: Unknown table 't6' Error_code: 1051");
 **** Diff Table Def Start ****
 *** On Slave ***
 STOP SLAVE;

=== modified file 'mysql-test/suite/rpl/r/rpl_get_master_version_and_clock.result'
--- a/mysql-test/suite/rpl/r/rpl_get_master_version_and_clock.result	2009-09-18 19:02:57 +0000
+++ b/mysql-test/suite/rpl/r/rpl_get_master_version_and_clock.result	2009-11-10 15:15:12 +0000
@@ -4,6 +4,10 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+call mtr.add_suppression("Get master clock failed with error: ");
+call mtr.add_suppression("Get master SERVER_ID failed with error: ");
+call mtr.add_suppression("Slave I/O: Master command COM_REGISTER_SLAVE failed: failed registering on master, reconnecting to try again");
+call mtr.add_suppression("Fatal error: The slave I/O thread stops because master and slave have equal MySQL server ids; .*");
 SELECT IS_FREE_LOCK("debug_lock.before_get_UNIX_TIMESTAMP");
 IS_FREE_LOCK("debug_lock.before_get_UNIX_TIMESTAMP")
 1

=== modified file 'mysql-test/suite/rpl/r/rpl_idempotency.result'
--- a/mysql-test/suite/rpl/r/rpl_idempotency.result	2009-04-05 12:03:04 +0000
+++ b/mysql-test/suite/rpl/r/rpl_idempotency.result	2009-08-25 13:56:50 +0000
@@ -4,7 +4,8 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
-call mtr.add_suppression("Slave: Can\'t find record in \'t1\' Error_code: 1032");
+call mtr.add_suppression("Slave: Can't find record in 't.' Error_code: 1032");
+call mtr.add_suppression("Slave: Cannot delete or update a parent row: a foreign key constraint fails .* Error_code: 1451");
 call mtr.add_suppression("Slave: Cannot add or update a child row: a foreign key constraint fails .* Error_code: 1452");
 SET @old_slave_exec_mode= @@global.slave_exec_mode;
 CREATE TABLE t1 (a INT PRIMARY KEY);

=== modified file 'mysql-test/suite/rpl/r/rpl_init_slave_errors.result'
--- a/mysql-test/suite/rpl/r/rpl_init_slave_errors.result	2009-04-06 00:22:34 +0000
+++ b/mysql-test/suite/rpl/r/rpl_init_slave_errors.result	2009-08-28 14:13:27 +0000
@@ -9,6 +9,7 @@ reset slave;
 SET GLOBAL debug= "d,simulate_io_slave_error_on_init,simulate_sql_slave_error_on_init";
 start slave;
 Reporting the following error: Failed during slave thread initialization
+call mtr.add_suppression("Failed during slave I/O thread initialization");
 SET GLOBAL debug= "";
 stop slave;
 reset slave;

=== modified file 'mysql-test/suite/rpl/r/rpl_innodb_mixed_dml.result'
--- a/mysql-test/suite/rpl/r/rpl_innodb_mixed_dml.result	2009-08-29 08:52:22 +0000
+++ b/mysql-test/suite/rpl/r/rpl_innodb_mixed_dml.result	2009-09-28 12:41:10 +0000
@@ -885,7 +885,7 @@ master-bin.000001	#	Query	1	#	use `test_
 master-bin.000001	#	Xid	1	#	#
 master-bin.000001	#	Query	1	#	BEGIN
 master-bin.000001	#	Begin_load_query	1	#	;file_id=#;block_len=#
-master-bin.000001	#	Execute_load_query	1	#	use `test_rpl`; LOAD DATA INFILE 'MYSQLTEST_VARDIR/std_data/rpl_mixed.dat' INTO TABLE t1 FIELDS TERMINATED BY '|' ;file_id=#
+master-bin.000001	#	Execute_load_query	1	#	use `test_rpl`; LOAD DATA INFILE 'MYSQLTEST_VARDIR/std_data/rpl_mixed.dat' INTO TABLE `t1` FIELDS TERMINATED BY '|' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (a, b) ;file_id=#
 master-bin.000001	#	Xid	1	#	#
 master-bin.000001	#	Query	1	#	BEGIN
 master-bin.000001	#	Query	1	#	use `test_rpl`; DELETE FROM t1

=== modified file 'mysql-test/suite/rpl/r/rpl_loaddata.result'
--- a/mysql-test/suite/rpl/r/rpl_loaddata.result	2008-11-13 19:19:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_loaddata.result	2009-10-27 15:15:53 +0000
@@ -36,7 +36,7 @@ set global sql_slave_skip_counter=1;
 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	Master_SSL_Verify_Server_Cert	Last_IO_Errno	Last_IO_Error	Last_SQL_Errno	Last_SQL_Error
-#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	1797	#	#	master-bin.000001	Yes	Yes				#			0		0	1797	#	None		0	No						#	No	0		0	
+#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	2009	#	#	master-bin.000001	Yes	Yes				#			0		0	2009	#	None		0	No						#	No	0		0	
 set sql_log_bin=0;
 delete from t1;
 set sql_log_bin=1;
@@ -46,7 +46,7 @@ change master to master_user='test';
 change master to master_user='root';
 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	Master_SSL_Verify_Server_Cert	Last_IO_Errno	Last_IO_Error	Last_SQL_Errno	Last_SQL_Error
-#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	1832	#	#	master-bin.000001	No	No				#			0		0	1832	#	None		0	No						#	No	0		0	
+#	127.0.0.1	root	MASTER_PORT	1	master-bin.000001	2044	#	#	master-bin.000001	No	No				#			0		0	2044	#	None		0	No						#	No	0		0	
 set global sql_slave_skip_counter=1;
 start slave;
 set sql_log_bin=0;
@@ -86,3 +86,32 @@ CREATE TABLE t1 (word CHAR(20) NOT NULL 
 LOAD DATA INFILE "../../std_data/words.dat" INTO TABLE t1;
 ERROR 23000: Duplicate entry 'Aarhus' for key 'PRIMARY'
 DROP TABLE IF EXISTS t1;
+stop slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+reset master;
+reset slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+start slave;
+drop database if exists b48297_db1;
+drop database if exists b42897_db2;
+create database b48297_db1;
+create database b42897_db2;
+use b48297_db1;
+CREATE TABLE t1 (c1 VARCHAR(256)) engine=MyISAM;;
+use b42897_db2;
+### assertion: works with cross-referenced database
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE b48297_db1.t1;
+use b48297_db1;
+### assertion: works with fully qualified name on current database
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE b48297_db1.t1;
+### assertion: works without fully qualified name on current database
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE t1;
+### create connection without default database
+### connect (conn2,localhost,root,,*NO-ONE*);
+### assertion: works without stating the default database
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/std_data/loaddata5.dat' INTO TABLE b48297_db1.t1;
+### disconnect and switch back to master connection
+use b48297_db1;
+Comparing tables master:b48297_db1.t1 and slave:b48297_db1.t1
+DROP DATABASE b48297_db1;
+DROP DATABASE b42897_db2;

=== modified file 'mysql-test/suite/rpl/r/rpl_loaddata_fatal.result'
--- a/mysql-test/suite/rpl/r/rpl_loaddata_fatal.result	2007-12-12 17:19:24 +0000
+++ b/mysql-test/suite/rpl/r/rpl_loaddata_fatal.result	2009-09-28 12:41:10 +0000
@@ -53,7 +53,7 @@ Master_User	root
 Master_Port	MASTER_PORT
 Connect_Retry	1
 Master_Log_File	master-bin.000001
-Read_Master_Log_Pos	465
+Read_Master_Log_Pos	556
 Relay_Log_File	#
 Relay_Log_Pos	#
 Relay_Master_Log_File	master-bin.000001

=== modified file 'mysql-test/suite/rpl/r/rpl_loaddata_map.result'
--- a/mysql-test/suite/rpl/r/rpl_loaddata_map.result	2008-07-18 11:34:19 +0000
+++ b/mysql-test/suite/rpl/r/rpl_loaddata_map.result	2009-09-28 12:41:10 +0000
@@ -20,7 +20,7 @@ master-bin.000001	#	Query	#	#	use `test`
 master-bin.000001	#	Begin_load_query	#	#	;file_id=#;block_len=#
 master-bin.000001	#	Append_block	#	#	;file_id=#;block_len=#
 master-bin.000001	#	Append_block	#	#	;file_id=#;block_len=#
-master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile 'MYSQLTEST_VARDIR/tmp/bug30435_5k.txt' into table t2 ;file_id=#
+master-bin.000001	#	Execute_load_query	#	#	use `test`; LOAD DATA INFILE 'MYSQLTEST_VARDIR/tmp/bug30435_5k.txt' INTO TABLE `t2` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' (id) ;file_id=#
 ==== Verify results on slave ====
 [on slave]
 select count(*) from t2 /* 5 000 */;

=== modified file 'mysql-test/suite/rpl/r/rpl_loaddatalocal.result'
--- a/mysql-test/suite/rpl/r/rpl_loaddatalocal.result	2009-03-16 08:21:29 +0000
+++ b/mysql-test/suite/rpl/r/rpl_loaddatalocal.result	2009-09-28 12:41:10 +0000
@@ -54,3 +54,31 @@ a
 [on master]
 DROP TABLE t1;
 [on slave]
+
+Bug #43746:
+"return wrong query string when parse 'load data infile' sql statement"
+
+[master]
+SELECT @@SESSION.sql_mode INTO @old_mode;
+SET sql_mode='ignore_space';
+CREATE TABLE t1(a int);
+INSERT INTO t1 VALUES (1), (2), (3), (4);
+SELECT * INTO OUTFILE 'MYSQLD_DATADIR/bug43746.sql' FROM t1;
+TRUNCATE TABLE t1;
+LOAD DATA LOCAL INFILE 'MYSQLD_DATADIR/bug43746.sql' INTO TABLE t1;
+LOAD/* look mum, with comments in weird places! */DATA/* oh hai */LOCAL INFILE 'MYSQLD_DATADIR/bug43746.sql'/* we are */INTO/* from the internets */TABLE t1;
+LOAD DATA/*!10000 LOCAL */INFILE 'MYSQLD_DATADIR/bug43746.sql' INTO TABLE t1;
+LOAD DATA LOCAL INFILE 'MYSQLD_DATADIR/bug43746.sql' /*!10000 INTO */ TABLE t1;
+LOAD DATA LOCAL INFILE 'MYSQLD_DATADIR/bug43746.sql' /*!10000 INTO TABLE */ t1;
+LOAD DATA /*!10000 LOCAL INFILE 'MYSQLD_DATADIR/bug43746.sql' INTO TABLE */ t1;
+LOAD DATA/*!10000 LOCAL */INFILE 'MYSQLD_DATADIR/bug43746.sql'/*!10000 INTO*/TABLE t1;
+LOAD DATA/*!10000 LOCAL */INFILE 'MYSQLD_DATADIR/bug43746.sql'/* empty */INTO TABLE t1;
+LOAD DATA/*!10000 LOCAL */INFILE 'MYSQLD_DATADIR/bug43746.sql' INTO/* empty */TABLE t1;
+LOAD/*!99999 special comments that do not expand */DATA/*!99999 code from the future */LOCAL INFILE 'MYSQLD_DATADIR/bug43746.sql'/*!99999 have flux capacitor */INTO/*!99999 will travel */TABLE t1;
+SET sql_mode='PIPES_AS_CONCAT,ANSI_QUOTES,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER';
+LOAD DATA LOCAL INFILE 'MYSQLD_DATADIR/bug43746.sql' INTO TABLE t1;
+[slave]
+[master]
+DROP TABLE t1;
+SET SESSION sql_mode=@old_mode;
+[slave]

=== modified file 'mysql-test/suite/rpl/r/rpl_log_pos.result'
--- a/mysql-test/suite/rpl/r/rpl_log_pos.result	2008-07-10 16:09:39 +0000
+++ b/mysql-test/suite/rpl/r/rpl_log_pos.result	2009-09-24 13:19:06 +0000
@@ -4,6 +4,7 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+call mtr.add_suppression ("Slave I/O: Got fatal error 1236 from master when reading data from binary");
 show master status;
 File	Position	Binlog_Do_DB	Binlog_Ignore_DB
 master-bin.000001	#	<Binlog_Do_DB>	<Binlog_Ignore_DB>

=== added file 'mysql-test/suite/rpl/r/rpl_mysql_upgrade.result'
--- a/mysql-test/suite/rpl/r/rpl_mysql_upgrade.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_mysql_upgrade.result	2009-09-28 06:24:19 +0000
@@ -0,0 +1,13 @@
+stop slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+reset master;
+reset slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+start slave;
+DROP DATABASE IF EXISTS `#mysql50#mysqltest-1`;
+CREATE DATABASE `#mysql50#mysqltest-1`;
+Master position is not changed
+STOP SLAVE SQL_THREAD;
+Master position has been changed
+DROP DATABASE `mysqltest-1`;
+DROP DATABASE `#mysql50#mysqltest-1`;

=== modified file 'mysql-test/suite/rpl/r/rpl_packet.result'
--- a/mysql-test/suite/rpl/r/rpl_packet.result	2009-01-23 12:22:05 +0000
+++ b/mysql-test/suite/rpl/r/rpl_packet.result	2009-09-24 13:19:06 +0000
@@ -4,6 +4,8 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+call mtr.add_suppression("Slave I/O: Got a packet bigger than 'max_allowed_packet' bytes, Error_code: 1153");
+call mtr.add_suppression("Slave I/O: Got fatal error 1236 from master when reading data from binary log:");
 drop database if exists DB_NAME_OF_MAX_LENGTH_AKA_NAME_LEN_64_BYTES_____________________;
 create database DB_NAME_OF_MAX_LENGTH_AKA_NAME_LEN_64_BYTES_____________________;
 SET @@global.max_allowed_packet=1024;
@@ -32,6 +34,21 @@ include/start_slave.inc
 CREATE TABLE `t1` (`f1` LONGTEXT) ENGINE=MyISAM;
 INSERT INTO `t1`(`f1`) VALUES ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa2048');
 Slave_IO_Running = No (expect No)
+SELECT "Got a packet bigger than 'max_allowed_packet' bytes" AS Last_IO_Error;
+Last_IO_Error
+Got a packet bigger than 'max_allowed_packet' bytes
+stop slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+reset master;
+reset slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+start slave;
+CREATE TABLE t1 (f1 int PRIMARY KEY, f2 LONGTEXT, f3 LONGTEXT) ENGINE=MyISAM;
+INSERT INTO t1(f1, f2, f3) VALUES(1, REPEAT('a', @@global.max_allowed_packet), REPEAT('b', @@global.max_allowed_packet));
+Slave_IO_Running = No (expect No)
+SELECT "Got fatal error 1236 from master when reading data from binary log: 'log event entry exceeded max_allowed_packet; Increase max_allowed_packet on master'" AS Last_IO_Error;
+Last_IO_Error
+Got fatal error 1236 from master when reading data from binary log: 'log event entry exceeded max_allowed_packet; Increase max_allowed_packet on master'
 ==== clean up ====
 DROP TABLE t1;
 SET @@global.max_allowed_packet= 1024;

=== modified file 'mysql-test/suite/rpl/r/rpl_row_create_table.result'
--- a/mysql-test/suite/rpl/r/rpl_row_create_table.result	2009-05-31 05:44:41 +0000
+++ b/mysql-test/suite/rpl/r/rpl_row_create_table.result	2009-10-06 00:54:00 +0000
@@ -176,7 +176,7 @@ Log_name	Pos	Event_type	Server_id	End_lo
 #	106	Query	#	174	BEGIN
 #	174	Table_map	#	216	table_id: # (test.t7)
 #	216	Write_rows	#	272	table_id: # flags: STMT_END_F
-#	272	Query	#	343	ROLLBACK
+#	272	Query	#	341	COMMIT
 SELECT * FROM t7 ORDER BY a,b;
 a	b
 1	2
@@ -327,7 +327,7 @@ Log_name	Pos	Event_type	Server_id	End_lo
 #	1329	Query	#	1397	BEGIN
 #	1397	Table_map	#	1438	table_id: # (test.t1)
 #	1438	Write_rows	#	1482	table_id: # flags: STMT_END_F
-#	1482	Query	#	1553	ROLLBACK
+#	1482	Query	#	1551	COMMIT
 SHOW TABLES;
 Tables_in_test
 t1

=== added file 'mysql-test/suite/rpl/r/rpl_row_disabled_slave_key.result'
--- a/mysql-test/suite/rpl/r/rpl_row_disabled_slave_key.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_row_disabled_slave_key.result	2009-09-27 21:02:47 +0000
@@ -0,0 +1,26 @@
+stop slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+reset master;
+reset slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+start slave;
+SET SQL_LOG_BIN=0;
+CREATE TABLE t (a int, b int, c int, key(b));
+SET SQL_LOG_BIN=1;
+CREATE TABLE t (a int, b int, c int);
+INSERT INTO t VALUES (1,2,4);
+INSERT INTO t VALUES (4,3,4);
+DELETE FROM t;
+DROP TABLE t;
+stop slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+reset master;
+reset slave;
+drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
+start slave;
+CREATE TABLE t (a int, b int, c int, key(b));
+ALTER TABLE t DISABLE KEYS;
+INSERT INTO t VALUES (1,2,4);
+INSERT INTO t VALUES (4,3,4);
+DELETE FROM t;
+DROP TABLE t;

=== modified file 'mysql-test/suite/rpl/r/rpl_row_sp006_InnoDB.result'
--- a/mysql-test/suite/rpl/r/rpl_row_sp006_InnoDB.result	2007-06-27 12:28:02 +0000
+++ b/mysql-test/suite/rpl/r/rpl_row_sp006_InnoDB.result	2009-09-04 01:33:45 +0000
@@ -4,21 +4,20 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
-create database if not exists mysqltest1;
-DROP PROCEDURE IF EXISTS mysqltest1.p1;
-DROP PROCEDURE IF EXISTS mysqltest1.p2;
-DROP TABLE IF EXISTS mysqltest1.t2;
-DROP TABLE IF EXISTS mysqltest1.t1;
-CREATE TABLE IF NOT EXISTS mysqltest1.t1(name CHAR(16), birth DATE,PRIMARY KEY(name))ENGINE=InnoDB;
-CREATE TABLE IF NOT EXISTS mysqltest1.t2(name CHAR(16), age INT ,PRIMARY KEY(name))ENGINE=InnoDB;
-CREATE PROCEDURE mysqltest1.p1()
+DROP TABLE IF EXISTS t1;
+DROP TABLE IF EXISTS t2;
+DROP PROCEDURE IF EXISTS p1;
+DROP PROCEDURE IF EXISTS p2;
+CREATE TABLE IF NOT EXISTS t1(name CHAR(16), birth DATE,PRIMARY KEY(name))ENGINE=InnoDB;
+CREATE TABLE IF NOT EXISTS t2(name CHAR(16), age INT ,PRIMARY KEY(name))ENGINE=InnoDB;
+CREATE PROCEDURE p1()
 BEGIN
 DECLARE done INT DEFAULT 0;
 DECLARE spa CHAR(16);
 DECLARE spb INT;
 DECLARE cur1 CURSOR FOR SELECT name, 
 (YEAR(CURDATE())-YEAR(birth))-(RIGHT(CURDATE(),5)<RIGHT(birth,5)) 
-FROM mysqltest1.t1;
+FROM t1;
 DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
 OPEN cur1;
 SET AUTOCOMMIT=0;
@@ -26,21 +25,20 @@ REPEAT
 FETCH cur1 INTO spa, spb;
 IF NOT done THEN
 START TRANSACTION;
-INSERT INTO mysqltest1.t2 VALUES (spa,spb);
+INSERT INTO t2 VALUES (spa,spb);
 COMMIT;
 END IF;
 UNTIL done END REPEAT;
 SET AUTOCOMMIT=1;
 CLOSE cur1;
 END|
-CREATE PROCEDURE mysqltest1.p2()
+CREATE PROCEDURE p2()
 BEGIN
-INSERT INTO mysqltest1.t1 VALUES ('MySQL','1993-02-04'),('ROCKS', '1990-08-27'),('Texas', '1999-03-30'),('kyle','2005-1-1');
+INSERT INTO t1 VALUES ('MySQL','1993-02-04'),('ROCKS', '1990-08-27'),('Texas', '1999-03-30'),('kyle','2005-1-1');
 END|
-CALL mysqltest1.p2();
-CALL mysqltest1.p1();
-DROP PROCEDURE IF EXISTS mysqltest1.p1;
-DROP PROCEDURE IF EXISTS mysqltest1.p2;
-DROP TABLE IF EXISTS mysqltest1.t1;
-DROP TABLE IF EXISTS mysqltest1.t2;
-DROP DATABASE mysqltest1;
+CALL p2();
+CALL p1();
+DROP TABLE t1;
+DROP TABLE t2;
+DROP PROCEDURE p1;
+DROP PROCEDURE p2;

=== modified file 'mysql-test/suite/rpl/r/rpl_slave_load_remove_tmpfile.result'
--- a/mysql-test/suite/rpl/r/rpl_slave_load_remove_tmpfile.result	2009-03-23 01:07:25 +0000
+++ b/mysql-test/suite/rpl/r/rpl_slave_load_remove_tmpfile.result	2009-09-01 11:38:17 +0000
@@ -51,3 +51,4 @@ Last_SQL_Errno	9
 Last_SQL_Error	Error in Begin_load_query event: write to '../../tmp/SQL_LOAD.data' failed
 drop table t1;
 drop table t1;
+call mtr.add_suppression("Slave: Error writing file 'UNKNOWN' .Errcode: 9. Error_code: 3");

=== modified file 'mysql-test/suite/rpl/r/rpl_stm_log.result'
--- a/mysql-test/suite/rpl/r/rpl_stm_log.result	2009-03-16 08:21:29 +0000
+++ b/mysql-test/suite/rpl/r/rpl_stm_log.result	2009-09-28 12:41:10 +0000
@@ -25,7 +25,7 @@ master-bin.000001	#	Query	1	#	use `test`
 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/words.dat' into table t1 ignore 1 lines ;file_id=1
+master-bin.000001	#	Execute_load_query	1	#	use `test`; LOAD DATA INFILE '../../std_data/words.dat' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' IGNORE 1 LINES  (word) ;file_id=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
@@ -193,7 +193,7 @@ master-bin.000001	#	Query	#	#	use `test`
 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=#;block_len=#
-master-bin.000001	#	Execute_load_query	#	#	use `test`; load data infile '../../std_data/words.dat' into table t1 ignore 1 lines ;file_id=#
+master-bin.000001	#	Execute_load_query	#	#	use `test`; LOAD DATA INFILE '../../std_data/words.dat' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' IGNORE 1 LINES  (word) ;file_id=#
 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
@@ -218,7 +218,7 @@ slave-bin.000001	#	Query	1	#	use `test`;
 slave-bin.000001	#	Query	1	#	use `test`; drop table t1
 slave-bin.000001	#	Query	1	#	use `test`; create table t1 (word char(20) not null)ENGINE=MyISAM
 slave-bin.000001	#	Begin_load_query	1	#	;file_id=1;block_len=581
-slave-bin.000001	#	Execute_load_query	1	#	use `test`; load data INFILE '../../tmp/SQL_LOAD-2-1-1.data' INTO  table t1 ignore 1 lines ;file_id=1
+slave-bin.000001	#	Execute_load_query	1	#	use `test`; LOAD DATA INFILE '../../tmp/SQL_LOAD-2-1-1.data' INTO TABLE `t1` FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\\' LINES TERMINATED BY '\n' IGNORE 1 LINES  (word) ;file_id=1
 slave-bin.000001	#	Query	1	#	use `test`; create table t3 (a int)ENGINE=MyISAM
 slave-bin.000001	#	Rotate	2	#	slave-bin.000002;pos=4
 show binlog events in 'slave-bin.000002' from 4;

=== modified file 'mysql-test/suite/rpl/t/disabled.def'
--- a/mysql-test/suite/rpl/t/disabled.def	2009-07-06 22:20:17 +0000
+++ b/mysql-test/suite/rpl/t/disabled.def	2009-09-27 10:12:58 +0000
@@ -10,6 +10,3 @@
 #
 ##############################################################################
 
-rpl_cross_version      : Bug#42311 2009-03-27 joro rpl_cross_version fails on macosx
-rpl_init_slave         : Bug#44920 2009-07006 pcrews MTR2 is not processing master.opt input properly on Windows.  *Must be done this way due to the nature of the bug*
-

=== added file 'mysql-test/suite/rpl/t/rpl_auto_increment_update_failure.test'
--- a/mysql-test/suite/rpl/t/rpl_auto_increment_update_failure.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_auto_increment_update_failure.test	2009-09-30 23:19:36 +0000
@@ -0,0 +1,214 @@
+#
+# Bug45677
+# This test verifies the following two properties:
+# P1) insert/update in an autoinc column causes statement to 
+#     be logged in row format if binlog_format=mixed.
+# P2) if binlog_format=mixed, and a trigger or function contains 
+#     two or more inserts/updates in a table that has an autoinc 
+#     column, then the slave should not go out of sync, even if 
+#     there are concurrent transactions.
+# 
+# Property (P1) is tested by executing an insert and an update on 
+# a table that has an autoinc column, and verifying that these 
+# statements result in row events in the binlog.
+# Property (P2) is tested by setting up the test scenario and 
+# verifying that the tables are identical on master and slave.
+#
+
+source include/have_binlog_format_mixed.inc;
+source include/have_innodb.inc;
+source include/master-slave.inc;
+
+--echo # Test case1: INVOKES A TRIGGER with after insert action
+let $trigger_action = after insert;
+source extra/rpl_tests/rpl_auto_increment_invoke_trigger.test;
+
+--echo # Test case2: INVOKES A TRIGGER with before insert action
+let $trigger_action = before insert;
+source extra/rpl_tests/rpl_auto_increment_invoke_trigger.test;
+
+--echo # Test case3: INVOKES A TRIGGER with after update action
+let $trigger_action = after update;
+source extra/rpl_tests/rpl_auto_increment_invoke_trigger.test;
+
+--echo # Test case4: INVOKES A TRIGGER with before update action
+let $trigger_action = before update;
+source extra/rpl_tests/rpl_auto_increment_invoke_trigger.test;
+
+--echo # Test case5: INVOKES A TRIGGER with after delete action
+let $trigger_action = after delete;
+source extra/rpl_tests/rpl_auto_increment_invoke_trigger.test;
+
+--echo # Test case6: INVOKES A TRIGGER with before delete action
+let $trigger_action = before delete;
+source extra/rpl_tests/rpl_auto_increment_invoke_trigger.test;
+
+--echo # Test case7: CALLS A FUNCTION which INVOKES A TRIGGER with after insert action
+let $insert_action = after insert;
+source extra/rpl_tests/rpl_autoinc_func_invokes_trigger.test;
+
+--echo # Test case8: CALLS A FUNCTION which INVOKES A TRIGGER with before insert action
+let $insert_action = before insert;
+source extra/rpl_tests/rpl_autoinc_func_invokes_trigger.test;
+
+--echo # Test case9: INSERT DATA INTO VIEW WHICH INVOKES TRIGGERS with after insert action
+let $insert_action = after insert;
+source extra/rpl_tests/rpl_auto_increment_insert_view.test;
+
+--echo # Test case10: INSERT DATA INTO VIEW WHICH INVOKES TRIGGERS with before insert action
+let $insert_action = before insert;
+source extra/rpl_tests/rpl_auto_increment_insert_view.test;
+
+--echo # Test case11: INVOKES A FUNCTION TO INSERT TWO OR MORE VALUES INTO A TABLE WITH AUTOINC COLUMN
+connection master;
+create table t1(a int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, primary key(i1)) engine=innodb;
+delimiter //;
+CREATE FUNCTION f1_two_inserts() RETURNS INTEGER
+BEGIN
+   INSERT INTO t2(a) values(2);
+   INSERT INTO t2(a) values(2);
+   RETURN 1;
+END//
+delimiter ;//
+begin;
+insert into t1(a) values(f1_two_inserts());
+
+connection master1;
+#The default autocommit is set to 1, so the statement is auto committed
+insert into t2(a) values(4),(5);
+
+connection master;
+commit;
+insert into t1(a) values(f1_two_inserts());
+commit;
+
+connection master;
+--echo #Test result for INVOKES A FUNCTION TO INSERT TWO OR MORE VALUES on master
+select * from t2 ORDER BY i1;
+
+sync_slave_with_master;
+connection slave;
+--echo #Test result for INVOKES A FUNCTION TO INSERT TWO OR MORE VALUES on slave
+select * from t2 ORDER BY i1;
+
+connection master;
+drop table t1;
+drop table t2;
+drop function f1_two_inserts;
+sync_slave_with_master;
+
+--echo # Test case12: INVOKES A FUNCTION TO UPDATE TWO OR MORE VALUES OF A TABLE WITH AUTOINC COLUMN
+connection master;
+create table t1(a int) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, b int, primary key(i1)) engine=innodb;
+delimiter //;
+CREATE FUNCTION f1_two_updates() RETURNS INTEGER
+BEGIN
+   update t2 set a = a + 5 where b = 1;
+   update t2 set a = a + 5 where b = 2;
+   update t2 set a = a + 5 where b = 3;
+   update t2 set a = a + 5 where b = 4;
+   RETURN 1;
+END//
+delimiter ;//
+
+connection master1;
+#The default autocommit is set to 1, so the statement is auto committed
+insert into t2(a,b) values(1,1);
+insert into t2(a,b) values(2,2);
+insert into t2(a,b) values(3,3);
+insert into t2(a,b) values(4,4);
+insert into t1(a) values(f1_two_updates());
+
+connection master;
+begin;
+insert into t1(a) values(f1_two_updates());
+commit;
+
+connection master;
+--echo #Test result for INVOKES A FUNCTION TO UPDATE TWO OR MORE VALUES on master
+select * from t2 ORDER BY i1;
+
+sync_slave_with_master;
+connection slave;
+--echo #Test result for INVOKES A FUNCTION TO UPDATE TWO OR MORE VALUES on slave
+select * from t2 ORDER BY i1;
+
+connection master;
+drop table t1;
+drop table t2;
+drop function f1_two_updates;
+sync_slave_with_master;
+
+--echo # Test case13: UPDATE MORE THAN ONE TABLES ON TOP-STATEMENT
+connection master;
+create table t1(i1 int not null auto_increment, a int, b int, primary key(i1)) engine=innodb;
+create table t2(i1 int not null auto_increment, a int, b int, primary key(i1)) engine=innodb;
+begin;
+let $binlog_start= query_get_value(SHOW MASTER STATUS, Position, 1);
+insert into t1(a,b) values(1,1),(2,2);
+insert into t2(a,b) values(1,1),(2,2);
+update t1,t2 set t1.a=t1.a+5, t2.a=t2.a+5 where t1.b=t2.b;
+insert into t1(a,b) values(3,3);
+insert into t2(a,b) values(3,3);
+commit;
+--echo # To verify if it works fine when these statements are not be marked as unsafe
+source include/show_binlog_events.inc;
+
+sync_slave_with_master;
+--echo #Test if the results are consistent on master and slave
+--echo #for 'UPDATE MORE THAN ONE TABLES ON TOP-STATEMENT'
+let $diff_table_1=master:test.t1;
+let $diff_table_2=slave:test.t1;
+source include/diff_tables.inc;
+let $diff_table_1=master:test.t2;
+let $diff_table_2=slave:test.t2;
+source include/diff_tables.inc;
+
+connection master;
+drop table t1;
+drop table t2;
+sync_slave_with_master;
+
+--echo # Test case14: INSERT DATA INTO VIEW WHICH INVOLVED MORE THAN ONE TABLES
+connection master;
+CREATE TABLE t1(i1 int not null auto_increment, c1 INT, primary key(i1)) engine=innodb;
+CREATE TABLE t2(i1 int not null auto_increment, c2 INT, primary key(i1)) engine=innodb;
+let $binlog_start= query_get_value(SHOW MASTER STATUS, Position, 1);
+begin;
+INSERT INTO t1(c1) VALUES (11), (12);
+INSERT INTO t2(c2) VALUES (13), (14);
+
+CREATE VIEW v15 AS SELECT c1, c2 FROM t1, t2;
+
+INSERT INTO v15(c1) VALUES (15),(16);
+INSERT INTO v15(c2) VALUES (17),(18);
+
+connection master1;
+INSERT INTO v15(c1) VALUES (19),(20);
+INSERT INTO v15(c2) VALUES (21),(22);
+
+connection master;
+INSERT INTO v15(c1) VALUES (23), (24);
+INSERT INTO v15(c2) VALUES (25), (26);
+commit;
+--echo # To verify if it works fine when these statements are not be marked as unsafe
+source include/show_binlog_events.inc;
+
+sync_slave_with_master;
+--echo #Test if the results are consistent on master and slave
+--echo #for 'INSERT DATA INTO VIEW WHICH INVOLVED MORE THAN ONE TABLES'
+let $diff_table_1=master:test.t1;
+let $diff_table_2=slave:test.t1;
+source include/diff_tables.inc;
+let $diff_table_1=master:test.t2;
+let $diff_table_2=slave:test.t2;
+source include/diff_tables.inc;
+
+connection master;
+drop table t1;
+drop table t2;
+drop view  v15;
+sync_slave_with_master;
+

=== modified file 'mysql-test/suite/rpl/t/rpl_bug33931.test'
--- a/mysql-test/suite/rpl/t/rpl_bug33931.test	2009-02-11 11:56:25 +0000
+++ b/mysql-test/suite/rpl/t/rpl_bug33931.test	2009-08-28 14:13:27 +0000
@@ -15,7 +15,7 @@ reset master;
 connection slave;
 
 # Add suppression for expected warnings in slaves error log
-call mtr.add_suppression("Failed during slave thread initialization");
+call mtr.add_suppression("Failed during slave I/O thread initialization");
 
 --disable_warnings
 stop slave;

=== modified file 'mysql-test/suite/rpl/t/rpl_do_grant.test'
--- a/mysql-test/suite/rpl/t/rpl_do_grant.test	2009-09-20 03:02:26 +0000
+++ b/mysql-test/suite/rpl/t/rpl_do_grant.test	2009-11-10 15:15:12 +0000
@@ -210,5 +210,10 @@ DROP FUNCTION upgrade_del_func;
 DROP FUNCTION upgrade_alter_func;
 DROP DATABASE bug42217_db;
 DROP USER 'create_rout_db'@'localhost';
- 
+
+call mtr.add_suppression("Slave: Operation DROP USER failed for 'create_rout_db'@'localhost' Error_code: 1396");
+connection slave;
+USE mtr;
+call mtr.add_suppression("Slave: Operation DROP USER failed for 'create_rout_db'@'localhost' Error_code: 1396");
+
 --echo "End of test"

=== modified file 'mysql-test/suite/rpl/t/rpl_drop_temp.test'
--- a/mysql-test/suite/rpl/t/rpl_drop_temp.test	2009-08-28 09:45:57 +0000
+++ b/mysql-test/suite/rpl/t/rpl_drop_temp.test	2009-09-13 20:52:14 +0000
@@ -23,6 +23,8 @@ disconnect con_temp;
 --source include/wait_until_disconnected.inc
 
 connection master;
+-- let $wait_binlog_event= DROP
+-- source include/wait_for_binlog_event.inc
 sync_slave_with_master;
 
 connection slave;

=== modified file 'mysql-test/suite/rpl/t/rpl_err_ignoredtable.test'
--- a/mysql-test/suite/rpl/t/rpl_err_ignoredtable.test	2009-02-05 09:49:32 +0000
+++ b/mysql-test/suite/rpl/t/rpl_err_ignoredtable.test	2009-10-20 18:00:07 +0000
@@ -50,7 +50,7 @@ kill @id;
 drop table t2,t3;
 insert into t4 values (3),(4);
 connection master;
---error 0,1053,2013
+--error 0,1317,2013
 reap;
 connection master1;
 save_master_pos;

=== added file 'mysql-test/suite/rpl/t/rpl_get_master_version_and_clock-slave.opt'
--- a/mysql-test/suite/rpl/t/rpl_get_master_version_and_clock-slave.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_get_master_version_and_clock-slave.opt	2009-10-29 02:26:59 +0000
@@ -0,0 +1 @@
+--master-retry-count=60

=== modified file 'mysql-test/suite/rpl/t/rpl_get_master_version_and_clock.test'
--- a/mysql-test/suite/rpl/t/rpl_get_master_version_and_clock.test	2009-07-17 05:07:43 +0000
+++ b/mysql-test/suite/rpl/t/rpl_get_master_version_and_clock.test	2009-10-29 02:26:59 +0000
@@ -16,6 +16,10 @@
 
 source include/master-slave.inc;
 source include/have_debug.inc;
+call mtr.add_suppression("Get master clock failed with error: ");
+call mtr.add_suppression("Get master SERVER_ID failed with error: ");
+call mtr.add_suppression("Slave I/O: Master command COM_REGISTER_SLAVE failed: failed registering on master, reconnecting to try again");
+call mtr.add_suppression("Fatal error: The slave I/O thread stops because master and slave have equal MySQL server ids; .*");
 #Test case 1: Try to get the value of the UNIX_TIMESTAMP from master under network disconnection
 connection slave;
 let $debug_saved= `select @@global.debug`;

=== modified file 'mysql-test/suite/rpl/t/rpl_idempotency.test'
--- a/mysql-test/suite/rpl/t/rpl_idempotency.test	2009-04-05 12:03:04 +0000
+++ b/mysql-test/suite/rpl/t/rpl_idempotency.test	2009-08-25 13:56:50 +0000
@@ -8,7 +8,8 @@ connection slave;
 source include/have_innodb.inc;
 
 # Add suppression for expected warning(s) in slaves error log
-call mtr.add_suppression("Slave: Can\'t find record in \'t1\' Error_code: 1032");
+call mtr.add_suppression("Slave: Can't find record in 't.' Error_code: 1032");
+call mtr.add_suppression("Slave: Cannot delete or update a parent row: a foreign key constraint fails .* Error_code: 1451");
 call mtr.add_suppression("Slave: Cannot add or update a child row: a foreign key constraint fails .* Error_code: 1452");
 
 SET @old_slave_exec_mode= @@global.slave_exec_mode;

=== modified file 'mysql-test/suite/rpl/t/rpl_init_slave_errors.test'
--- a/mysql-test/suite/rpl/t/rpl_init_slave_errors.test	2009-04-06 00:22:34 +0000
+++ b/mysql-test/suite/rpl/t/rpl_init_slave_errors.test	2009-08-28 14:13:27 +0000
@@ -57,6 +57,7 @@ source include/wait_for_slave_to_stop.in
 
 let $error= query_get_value(SHOW SLAVE STATUS, Last_Error, 1);
 echo Reporting the following error: $error;
+call mtr.add_suppression("Failed during slave I/O thread initialization");
 
 SET GLOBAL debug= "";
 

=== modified file 'mysql-test/suite/rpl/t/rpl_loaddatalocal.test'
--- a/mysql-test/suite/rpl/t/rpl_loaddatalocal.test	2009-03-16 08:21:29 +0000
+++ b/mysql-test/suite/rpl/t/rpl_loaddatalocal.test	2009-09-28 12:41:10 +0000
@@ -98,3 +98,73 @@ DROP TABLE t1;
 --echo [on slave]
 sync_slave_with_master;
 
+--echo
+--echo Bug #43746:
+--echo "return wrong query string when parse 'load data infile' sql statement"
+--echo
+
+--echo [master]
+connection master;
+let $MYSQLD_DATADIR= `select @@datadir`;
+SELECT @@SESSION.sql_mode INTO @old_mode;
+
+SET sql_mode='ignore_space';
+
+CREATE TABLE t1(a int);
+INSERT INTO t1 VALUES (1), (2), (3), (4);
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval SELECT * INTO OUTFILE '$MYSQLD_DATADIR/bug43746.sql' FROM t1;
+TRUNCATE TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA LOCAL INFILE '$MYSQLD_DATADIR/bug43746.sql' INTO TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD/* look mum, with comments in weird places! */DATA/* oh hai */LOCAL INFILE '$MYSQLD_DATADIR/bug43746.sql'/* we are */INTO/* from the internets */TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA/*!10000 LOCAL */INFILE '$MYSQLD_DATADIR/bug43746.sql' INTO TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA LOCAL INFILE '$MYSQLD_DATADIR/bug43746.sql' /*!10000 INTO */ TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA LOCAL INFILE '$MYSQLD_DATADIR/bug43746.sql' /*!10000 INTO TABLE */ t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA /*!10000 LOCAL INFILE '$MYSQLD_DATADIR/bug43746.sql' INTO TABLE */ t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA/*!10000 LOCAL */INFILE '$MYSQLD_DATADIR/bug43746.sql'/*!10000 INTO*/TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA/*!10000 LOCAL */INFILE '$MYSQLD_DATADIR/bug43746.sql'/* empty */INTO TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA/*!10000 LOCAL */INFILE '$MYSQLD_DATADIR/bug43746.sql' INTO/* empty */TABLE t1;
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD/*!99999 special comments that do not expand */DATA/*!99999 code from the future */LOCAL INFILE '$MYSQLD_DATADIR/bug43746.sql'/*!99999 have flux capacitor */INTO/*!99999 will travel */TABLE t1;
+
+SET sql_mode='PIPES_AS_CONCAT,ANSI_QUOTES,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,STRICT_TRANS_TABLES,STRICT_ALL_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,TRADITIONAL,NO_AUTO_CREATE_USER';
+
+--replace_result $MYSQLD_DATADIR MYSQLD_DATADIR
+eval LOAD DATA LOCAL INFILE '$MYSQLD_DATADIR/bug43746.sql' INTO TABLE t1;
+
+--echo [slave]
+sync_slave_with_master;
+
+# cleanup
+
+--remove_file $MYSQLD_DATADIR/bug43746.sql
+
+--echo [master]
+connection master;
+DROP TABLE t1;
+SET SESSION sql_mode=@old_mode;
+
+--echo [slave]
+sync_slave_with_master;
+
+connection master;

=== modified file 'mysql-test/suite/rpl/t/rpl_log_pos.test'
--- a/mysql-test/suite/rpl/t/rpl_log_pos.test	2008-07-10 16:09:39 +0000
+++ b/mysql-test/suite/rpl/t/rpl_log_pos.test	2009-09-24 13:19:06 +0000
@@ -11,6 +11,7 @@
 # Passes with rbr no problem, removed statement include [jbm]
 
 source include/master-slave.inc;
+call mtr.add_suppression ("Slave I/O: Got fatal error 1236 from master when reading data from binary");
 source include/show_master_status.inc;
 sync_slave_with_master;
 source include/stop_slave.inc;

=== added file 'mysql-test/suite/rpl/t/rpl_mysql_upgrade.test'
--- a/mysql-test/suite/rpl/t/rpl_mysql_upgrade.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_mysql_upgrade.test	2009-09-28 06:24:19 +0000
@@ -0,0 +1,56 @@
+#############################################################################
+# BUG#43579 mysql_upgrade tries to alter log tables on replicated database
+# Master and slave should be upgraded separately.  All statements executed by
+# mysql_upgrade will not be binlogged. --write-binlog and --skip-write-binlog
+# options are added into mysql_upgrade. These options control whether sql
+# statements are binlogged or not. 
+#############################################################################
+--source include/master-slave.inc
+
+# Only run test if "mysql_upgrade" is found
+--source include/have_mysql_upgrade.inc
+
+connection master;
+--disable_warnings
+DROP DATABASE IF EXISTS `#mysql50#mysqltest-1`;
+CREATE DATABASE `#mysql50#mysqltest-1`;
+--enable_warnings
+sync_slave_with_master;
+
+connection master;
+let $before_position= query_get_value(SHOW MASTER STATUS, Position, 1);
+
+#With '--force' option, mysql_upgrade always executes all sql statements for upgrading.
+#--skip-write-binlog option disables binlog.
+--exec $MYSQL_UPGRADE --skip-write-binlog --skip-verbose --force --user=root > $MYSQLTEST_VARDIR/log/mysql_upgrade.log 2>&1
+sync_slave_with_master;
+
+connection master;
+let $after_position= query_get_value(SHOW MASTER STATUS, Position, 1);
+
+if (`SELECT '$before_position'='$after_position'`)
+{
+  echo Master position is not changed;
+}
+
+#Some log events of the mysql_upgrade's will cause errors on slave.
+connection slave;
+STOP SLAVE SQL_THREAD;
+source include/wait_for_slave_sql_to_stop.inc;
+
+connection master;
+#With '--force' option, mysql_upgrade always executes all sql statements for upgrading.
+--exec $MYSQL_UPGRADE --skip-verbose --force --user=root > $MYSQLTEST_VARDIR/log/mysql_upgrade.log 2>&1
+
+connection master;
+let $after_file= query_get_value(SHOW MASTER STATUS, File, 1);
+let $after_position= query_get_value(SHOW MASTER STATUS, Position, 1);
+
+if (!`SELECT '$before_position'='$after_position'`)
+{
+  echo Master position has been changed;
+}
+
+DROP DATABASE `mysqltest-1`;
+connection slave;
+DROP DATABASE `#mysql50#mysqltest-1`;

=== modified file 'mysql-test/suite/rpl/t/rpl_packet.test'
--- a/mysql-test/suite/rpl/t/rpl_packet.test	2009-01-23 12:22:05 +0000
+++ b/mysql-test/suite/rpl/t/rpl_packet.test	2009-09-24 13:19:06 +0000
@@ -5,6 +5,9 @@
 
 # max-out size db name 
 source include/master-slave.inc;
+source include/have_binlog_format_row.inc;
+call mtr.add_suppression("Slave I/O: Got a packet bigger than 'max_allowed_packet' bytes, Error_code: 1153");
+call mtr.add_suppression("Slave I/O: Got fatal error 1236 from master when reading data from binary log:");
 
 let $db= DB_NAME_OF_MAX_LENGTH_AKA_NAME_LEN_64_BYTES_____________________;
 disable_warnings;
@@ -86,6 +89,35 @@ connection slave;
 --source include/wait_for_slave_io_to_stop.inc
 let $slave_io_running= query_get_value(SHOW SLAVE STATUS, Slave_IO_Running, 1);
 --echo Slave_IO_Running = $slave_io_running (expect No)
+#
+# Bug#42914: The slave I/O thread must stop after trying to read the above
+# event, However there is no Last_IO_Error report.
+#
+let $last_io_error= query_get_value(SHOW SLAVE STATUS, Last_IO_Error, 1);
+eval SELECT "$last_io_error" AS Last_IO_Error;
+
+#
+# Bug#42914: On the master, if a binary log event is larger than
+# max_allowed_packet, the error message ER_MASTER_FATAL_ERROR_READING_BINLOG
+# is sent to a slave when it requests a dump from the master, thus leading the
+# I/O thread to stop. However, there is no Last_IO_Error reported.
+#
+source include/master-slave-reset.inc;
+connection master;
+CREATE TABLE t1 (f1 int PRIMARY KEY, f2 LONGTEXT, f3 LONGTEXT) ENGINE=MyISAM;
+sync_slave_with_master;
+
+connection master;
+INSERT INTO t1(f1, f2, f3) VALUES(1, REPEAT('a', @@global.max_allowed_packet), REPEAT('b', @@global.max_allowed_packet));
+
+connection slave;
+# The slave I/O thread must stop after receiving
+# ER_MASTER_FATAL_ERROR_READING_BINLOG error message from master.
+--source include/wait_for_slave_io_to_stop.inc
+let $slave_io_running= query_get_value(SHOW SLAVE STATUS, Slave_IO_Running, 1);
+--echo Slave_IO_Running = $slave_io_running (expect No)
+let $last_io_error= query_get_value(SHOW SLAVE STATUS, Last_IO_Error, 1);
+eval SELECT "$last_io_error" AS Last_IO_Error;
 
 --echo ==== clean up ====
 connection master;

=== added file 'mysql-test/suite/rpl/t/rpl_row_disabled_slave_key.test'
--- a/mysql-test/suite/rpl/t/rpl_row_disabled_slave_key.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_row_disabled_slave_key.test	2009-09-27 21:02:47 +0000
@@ -0,0 +1,73 @@
+# BUG#47312: RBR: Disabling key on slave breaks replication:
+# HA_ERR_WRONG_INDEX
+#
+# Description
+# ===========
+#   
+#   This test case checks whether disabling a key on a slave breaks
+#   replication or not.
+#   
+#   Case #1, shows that while not using ALTER TABLE... DISABLE KEYS and
+#   the slave has no key defined while the master has one, replication
+#   won't break.
+#
+#   Case #2, shows that before patch for BUG#47312, if defining key on
+#   slave table, and later disable it, replication would break. This
+#   has been fixed.
+# 
+
+-- source include/master-slave.inc
+-- source include/have_binlog_format_row.inc
+
+#
+# Case #1: master has key, but slave has not. 
+#          Replication does not break.
+# 
+
+SET SQL_LOG_BIN=0;
+CREATE TABLE t (a int, b int, c int, key(b));
+SET SQL_LOG_BIN=1;
+
+-- connection slave
+
+CREATE TABLE t (a int, b int, c int);
+
+-- connection master
+
+INSERT INTO t VALUES (1,2,4);
+INSERT INTO t VALUES (4,3,4);
+DELETE FROM t;
+
+-- sync_slave_with_master
+
+-- connection master
+DROP TABLE t;
+
+-- sync_slave_with_master
+
+#
+# Case #2: master has key, slave also has one, 
+#          but it gets disabled sometime.
+#          Replication does not break anymore.
+# 
+-- source include/master-slave-reset.inc
+-- connection master
+
+CREATE TABLE t (a int, b int, c int, key(b));
+
+-- sync_slave_with_master
+
+ALTER TABLE t DISABLE KEYS;
+
+-- connection master
+
+INSERT INTO t VALUES (1,2,4);
+INSERT INTO t VALUES (4,3,4);
+DELETE FROM t;
+
+-- sync_slave_with_master
+
+-- connection master
+DROP TABLE t;
+
+-- sync_slave_with_master

=== modified file 'mysql-test/suite/rpl/t/rpl_slave_load_remove_tmpfile.test'
--- a/mysql-test/suite/rpl/t/rpl_slave_load_remove_tmpfile.test	2009-03-23 01:07:25 +0000
+++ b/mysql-test/suite/rpl/t/rpl_slave_load_remove_tmpfile.test	2009-09-01 11:38:17 +0000
@@ -7,6 +7,7 @@
 #    1 - Creates a table and populates it through "LOAD DATA INFILE".
 #    2 - Catches error.
 ##########################################################################
+
 --source include/have_binlog_format_mixed_or_statement.inc
 --source include/have_innodb.inc
 --source include/have_debug.inc
@@ -47,3 +48,5 @@ drop table t1;
 connection slave;
 
 drop table t1;
+
+call mtr.add_suppression("Slave: Error writing file 'UNKNOWN' .Errcode: 9. Error_code: 3");

=== modified file 'mysql-test/suite/rpl_ndb/r/rpl_ndb_circular_simplex.result'
--- a/mysql-test/suite/rpl_ndb/r/rpl_ndb_circular_simplex.result	2008-03-14 20:06:01 +0000
+++ b/mysql-test/suite/rpl_ndb/r/rpl_ndb_circular_simplex.result	2009-09-27 22:03:05 +0000
@@ -102,3 +102,4 @@ Last_IO_Errno	#
 Last_IO_Error	#
 Last_SQL_Errno	0
 Last_SQL_Error	
+DROP TABLE t1;

=== modified file 'mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result'
--- a/mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result	2008-11-04 07:43:21 +0000
+++ b/mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result	2009-08-29 08:30:59 +0000
@@ -4,6 +4,7 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
+call mtr.add_suppression("Slave: Unknown table 't6' Error_code: 1051");
 **** Diff Table Def Start ****
 *** On Slave ***
 STOP SLAVE;

=== modified file 'mysql-test/suite/rpl_ndb/r/rpl_ndb_sp006.result'
--- a/mysql-test/suite/rpl_ndb/r/rpl_ndb_sp006.result	2007-06-27 12:28:02 +0000
+++ b/mysql-test/suite/rpl_ndb/r/rpl_ndb_sp006.result	2009-09-07 05:01:03 +0000
@@ -4,21 +4,20 @@ reset master;
 reset slave;
 drop table if exists t1,t2,t3,t4,t5,t6,t7,t8,t9;
 start slave;
-create database if not exists mysqltest1;
-DROP PROCEDURE IF EXISTS mysqltest1.p1;
-DROP PROCEDURE IF EXISTS mysqltest1.p2;
-DROP TABLE IF EXISTS mysqltest1.t2;
-DROP TABLE IF EXISTS mysqltest1.t1;
-CREATE TABLE IF NOT EXISTS mysqltest1.t1(name CHAR(16), birth DATE,PRIMARY KEY(name))ENGINE=NDBCLUSTER;
-CREATE TABLE IF NOT EXISTS mysqltest1.t2(name CHAR(16), age INT ,PRIMARY KEY(name))ENGINE=NDBCLUSTER;
-CREATE PROCEDURE mysqltest1.p1()
+DROP TABLE IF EXISTS t1;
+DROP TABLE IF EXISTS t2;
+DROP PROCEDURE IF EXISTS p1;
+DROP PROCEDURE IF EXISTS p2;
+CREATE TABLE IF NOT EXISTS t1(name CHAR(16), birth DATE,PRIMARY KEY(name))ENGINE=NDBCLUSTER;
+CREATE TABLE IF NOT EXISTS t2(name CHAR(16), age INT ,PRIMARY KEY(name))ENGINE=NDBCLUSTER;
+CREATE PROCEDURE p1()
 BEGIN
 DECLARE done INT DEFAULT 0;
 DECLARE spa CHAR(16);
 DECLARE spb INT;
 DECLARE cur1 CURSOR FOR SELECT name, 
 (YEAR(CURDATE())-YEAR(birth))-(RIGHT(CURDATE(),5)<RIGHT(birth,5)) 
-FROM mysqltest1.t1;
+FROM t1;
 DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
 OPEN cur1;
 SET AUTOCOMMIT=0;
@@ -26,21 +25,20 @@ REPEAT
 FETCH cur1 INTO spa, spb;
 IF NOT done THEN
 START TRANSACTION;
-INSERT INTO mysqltest1.t2 VALUES (spa,spb);
+INSERT INTO t2 VALUES (spa,spb);
 COMMIT;
 END IF;
 UNTIL done END REPEAT;
 SET AUTOCOMMIT=1;
 CLOSE cur1;
 END|
-CREATE PROCEDURE mysqltest1.p2()
+CREATE PROCEDURE p2()
 BEGIN
-INSERT INTO mysqltest1.t1 VALUES ('MySQL','1993-02-04'),('ROCKS', '1990-08-27'),('Texas', '1999-03-30'),('kyle','2005-1-1');
+INSERT INTO t1 VALUES ('MySQL','1993-02-04'),('ROCKS', '1990-08-27'),('Texas', '1999-03-30'),('kyle','2005-1-1');
 END|
-CALL mysqltest1.p2();
-CALL mysqltest1.p1();
-DROP PROCEDURE IF EXISTS mysqltest1.p1;
-DROP PROCEDURE IF EXISTS mysqltest1.p2;
-DROP TABLE IF EXISTS mysqltest1.t1;
-DROP TABLE IF EXISTS mysqltest1.t2;
-DROP DATABASE mysqltest1;
+CALL p2();
+CALL p1();
+DROP TABLE t1;
+DROP TABLE t2;
+DROP PROCEDURE p1;
+DROP PROCEDURE p2;

=== modified file 'mysql-test/suite/rpl_ndb/t/rpl_ndb_circular.test'
--- a/mysql-test/suite/rpl_ndb/t/rpl_ndb_circular.test	2008-03-14 14:42:27 +0000
+++ b/mysql-test/suite/rpl_ndb/t/rpl_ndb_circular.test	2009-09-27 22:03:05 +0000
@@ -58,3 +58,4 @@ STOP SLAVE;
 # cleanup
 --connection master
 DROP TABLE t1;
+-- sync_slave_with_master

=== modified file 'mysql-test/suite/rpl_ndb/t/rpl_ndb_circular_simplex.test'
--- a/mysql-test/suite/rpl_ndb/t/rpl_ndb_circular_simplex.test	2008-03-14 20:06:01 +0000
+++ b/mysql-test/suite/rpl_ndb/t/rpl_ndb_circular_simplex.test	2009-09-27 22:03:05 +0000
@@ -78,3 +78,7 @@ SELECT * FROM t1 ORDER BY a;
 --replace_result $MASTER_MYPORT MASTER_PORT
 --replace_column 1 # 7 # 8 # 9 # 22 # 23 # 33 # 35 # 36 #
 query_vertical SHOW SLAVE STATUS;
+
+-- connection master
+DROP TABLE t1;
+-- sync_slave_with_master

=== modified file 'mysql-test/t/almost_full.test'
--- a/mysql-test/t/almost_full.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/almost_full.test	2009-11-10 15:15:12 +0000
@@ -2,6 +2,8 @@
 # Some special cases with empty tables
 #
 
+call mtr.add_suppression("The table 't1' is full");
+
 --disable_warnings
 drop table if exists t1;
 --enable_warnings

=== modified file 'mysql-test/t/alter_table.test'
--- a/mysql-test/t/alter_table.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/alter_table.test	2009-11-10 15:15:12 +0000
@@ -1027,5 +1027,65 @@ INSERT INTO t1 (a) VALUES (11);
 SELECT * FROM t1 ORDER BY a;
 DROP TABLE t1;
 SET @@sql_mode=@save_sql_mode;
+--echo #
+--echo # Bug#45567: Fast ALTER TABLE broken for enum and set
+--echo #
+
+--disable_warnings
+DROP TABLE IF EXISTS t1;
+--enable_warnings
+
+CREATE TABLE t1 (a ENUM('a1','a2'));
+INSERT INTO t1 VALUES ('a1'),('a2');
+--enable_info
+--echo # No copy: No modification
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2');
+--echo # No copy: Add new enumeration to the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','a3');
+--echo # Copy: Modify and add new to the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','xx','a5');
+--echo # Copy: Remove from the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','xx');
+--echo # Copy: Add new enumeration
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','a0','xx');
+--echo # No copy: Add new enumerations to the end
+ALTER TABLE t1 MODIFY COLUMN a ENUM('a1','a2','a0','xx','a5','a6');
+--disable_info
+DROP TABLE t1;
+
+CREATE TABLE t1 (a SET('a1','a2'));
+INSERT INTO t1 VALUES ('a1'),('a2');
+--enable_info
+--echo # No copy: No modification
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2');
+--echo # No copy: Add new to the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a3');
+--echo # Copy: Modify and add new to the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','xx','a5');
+--echo # Copy: Remove from the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','xx');
+--echo # Copy: Add new member
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a0','xx');
+--echo # No copy: Add new to the end
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a0','xx','a5','a6');
+--echo # Copy: Numerical incrase (pack lenght)
+ALTER TABLE t1 MODIFY COLUMN a SET('a1','a2','a0','xx','a5','a6','a7','a8','a9','a10');
+--disable_info
+DROP TABLE t1;
+
+#
+# Bug#43508: Renaming timestamp or date column triggers table copy
+#
+
+CREATE TABLE t1 (f1 TIMESTAMP NULL DEFAULT NULL,
+                 f2 INT(11) DEFAULT NULL) ENGINE=MYISAM DEFAULT CHARSET=utf8;
+
+INSERT INTO t1 VALUES (NULL, NULL), ("2009-10-09 11:46:19", 2);
+
+--echo this should affect no rows as there is no real change
+--enable_info
+ALTER TABLE t1 CHANGE COLUMN f1 f1_no_real_change TIMESTAMP NULL DEFAULT NULL;
+--disable_info
+DROP TABLE t1;
 
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/analyse.test'
--- a/mysql-test/t/analyse.test	2009-08-27 10:22:19 +0000
+++ b/mysql-test/t/analyse.test	2009-10-30 09:56:32 +0000
@@ -10,37 +10,14 @@ insert into t1 values (1,2,"","Y","2002-
 select count(*) from t1 procedure analyse();
 select * from t1 procedure analyse();
 select * from t1 procedure analyse(2);
+--error ER_WRONG_USAGE
 create table t2 select * from t1 procedure analyse();
-select * from t2;
-drop table t1,t2;
+drop table t1;
 
 --error ER_WRONG_USAGE
 EXPLAIN SELECT 1 FROM (SELECT 1) a PROCEDURE ANALYSE();
 
 #
-# Test with impossible where
-#
-create table t1 (a int not null);
-create table t2 select * from t1 where 0=1 procedure analyse();
-show create table t2;
-select * from t1 where 0=1 procedure analyse();
-insert into t1 values(1);
-drop table t2;
-create table t2 select * from t1 where 0=1 procedure analyse();
-show create table t2;
-select * from t2;
-insert into t2 select * from t1 procedure analyse();
-select * from t2;
-insert into t1 values(2);
-drop table t2;
-create table t2 select * from t1 where 0=1 procedure analyse();
-show create table t2;
-select * from t2;
-insert into t2 select * from t1 procedure analyse();
-select * from t2;
-drop table t1,t2;
-
-#
 # Bug#2813 - analyse does not quote string values in enums from string
 #
 
@@ -113,3 +90,46 @@ SELECT * FROM (SELECT * FROM t1) d PROCE
 DROP TABLE t1;
 
 --echo End of 4.1 tests
+
+--echo #
+--echo # Bug #48293: crash with procedure analyse, view with > 10 columns, 
+--echo #  having clause...
+--echo #
+
+CREATE TABLE t1(a INT, b INT, c INT, d INT, e INT,
+                f INT, g INT, h INT, i INT, j INT,k INT);
+INSERT INTO t1 VALUES (),();
+
+CREATE ALGORITHM=TEMPTABLE VIEW v1 AS SELECT * FROM t1;
+--echo #should have a derived table
+EXPLAIN SELECT * FROM v1;
+--echo #should not crash
+--error ER_WRONG_USAGE
+SELECT * FROM v1 PROCEDURE analyse();
+--echo #should not crash
+--error ER_WRONG_USAGE
+SELECT * FROM t1 a, v1, t1 b PROCEDURE analyse();
+--echo #should not crash
+--error ER_WRONG_USAGE
+SELECT * FROM (SELECT * FROM t1 having a > 1) x PROCEDURE analyse();
+--echo #should not crash
+--error ER_WRONG_USAGE
+SELECT * FROM t1 a, (SELECT * FROM t1 having a > 1) x, t1 b PROCEDURE analyse();
+--echo #should not crash
+--error ER_ORDER_WITH_PROC
+SELECT 1 FROM t1 group by a having a > 1 order by 1 PROCEDURE analyse();
+
+DROP VIEW v1;
+DROP TABLE t1;
+
+CREATE TABLE t1(a INT);
+INSERT INTO t1 VALUES (1),(2);
+
+--echo # should not crash
+--error ER_WRONG_USAGE
+CREATE TABLE t2 SELECT 1 FROM t1, t1 t3 GROUP BY t3.a PROCEDURE ANALYSE();
+
+DROP TABLE t1;
+
+
+--echo End of 5.0 tests

=== modified file 'mysql-test/t/archive.test'
--- a/mysql-test/t/archive.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/archive.test	2009-11-10 15:15:12 +0000
@@ -1601,3 +1601,27 @@ INSERT INTO t1 VALUES (NULL, NULL),(NULL
 FLUSH TABLE t1;
 SELECT * FROM t1 ORDER BY a;
 DROP TABLE t1;
+
+#
+# BUG#29203 - archive tables have weird values in show table status
+#
+CREATE TABLE t1(a INT, b BLOB) ENGINE=archive;
+SELECT DATA_LENGTH, AVG_ROW_LENGTH FROM
+  INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='t1' AND TABLE_SCHEMA='test';
+INSERT INTO t1 VALUES(1, 'sampleblob1'),(2, 'sampleblob2');
+SELECT DATA_LENGTH, AVG_ROW_LENGTH FROM
+  INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='t1' AND TABLE_SCHEMA='test';
+DROP TABLE t1;
+
+#
+# BUG#46961 - archive engine loses rows during self joining select!
+#
+SET @save_join_buffer_size= @@join_buffer_size;
+SET @@join_buffer_size= 8228;
+CREATE TABLE t1(a CHAR(255)) ENGINE=archive;
+INSERT INTO t1 VALUES('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'),
+                     ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'),
+                     ('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa');
+SELECT COUNT(t1.a) FROM t1, t1 a, t1 b, t1 c, t1 d, t1 e;
+DROP TABLE t1;
+SET @@join_buffer_size= @save_join_buffer_size;

=== modified file 'mysql-test/t/bug46080.test'
--- a/mysql-test/t/bug46080.test	2009-07-13 11:17:14 +0000
+++ b/mysql-test/t/bug46080.test	2009-09-03 06:38:06 +0000
@@ -3,6 +3,9 @@
 --echo #  sort_buffer_size cannot allocate
 --echo #
 
+call mtr.add_suppression("Out of memory at line .*, 'my_alloc.c'");
+call mtr.add_suppression("needed .* byte .*k., memory in use: .* bytes .*k");
+
 CREATE TABLE t1(a CHAR(255));
 INSERT INTO t1 VALUES ('a');
 

=== added file 'mysql-test/t/bug46760-master.opt'
--- a/mysql-test/t/bug46760-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/bug46760-master.opt	2009-09-18 13:01:18 +0000
@@ -0,0 +1,2 @@
+--innodb-lock-wait-timeout=2
+--innodb-file-per-table

=== added file 'mysql-test/t/bug46760.test'
--- a/mysql-test/t/bug46760.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/bug46760.test	2009-09-18 13:01:18 +0000
@@ -0,0 +1,38 @@
+-- source include/have_innodb.inc
+
+--echo #
+--echo # Bug#46760: Fast ALTER TABLE no longer works for InnoDB
+--echo #
+
+CREATE TABLE t1 (a INT) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1);
+
+--echo # By using --enable_info and verifying that number of affected
+--echo # rows is 0 we check that this ALTER TABLE is really carried
+--echo # out as "fast/online" operation, i.e. without full-blown data
+--echo # copying.
+--echo #
+--echo # I.e. info for the below statement should normally look like:
+--echo #
+--echo # affected rows: 0
+--echo # info: Records: 0  Duplicates: 0  Warnings: 0
+
+--enable_info
+ALTER TABLE t1 ALTER COLUMN a SET DEFAULT 10;
+--disable_info
+SHOW CREATE TABLE t1;
+
+DROP TABLE t1;
+
+--echo #
+--echo # MySQL Bug#39200: optimize table does not recognize 
+--echo # ROW_FORMAT=COMPRESSED
+--echo #
+
+CREATE TABLE t1 (a INT) ROW_FORMAT=compressed;
+SHOW CREATE TABLE t1;
+OPTIMIZE TABLE t1;
+SHOW CREATE TABLE t1;
+DROP TABLE t1;
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/create.test'
--- a/mysql-test/t/create.test	2009-09-07 20:50:10 +0000
+++ b/mysql-test/t/create.test	2009-11-10 15:15:12 +0000
@@ -1198,6 +1198,23 @@ CREATE TABLE IF NOT EXISTS t2 (a INTEGER
 
 DROP TABLE t1, t2;
 
+--echo #
+--echo # BUG#46384 - mysqld segfault when trying to create table with same 
+--echo #             name as existing view
+--echo #
+
+CREATE TABLE t1 (a INT);
+CREATE TABLE t2 (a INT);
+
+INSERT INTO t1 VALUES (1),(2),(3);
+INSERT INTO t2 VALUES (1),(2),(3);
+
+CREATE VIEW v1 AS SELECT t1.a FROM t1, t2;
+--error ER_TABLE_EXISTS_ERROR
+CREATE TABLE v1 AS SELECT * FROM t1;
+
+DROP VIEW v1;
+DROP TABLE t1,t2;
 
 --echo End of 5.0 tests
 

=== modified file 'mysql-test/t/ctype_ldml.test'
--- a/mysql-test/t/ctype_ldml.test	2009-06-04 09:35:29 +0000
+++ b/mysql-test/t/ctype_ldml.test	2009-10-19 13:23:53 +0000
@@ -38,6 +38,14 @@ SELECT * FROM t1 WHERE col1=col2 ORDER B
 DROP TABLE t1;
 
 --echo #
+--echo # Bug#45645 Mysql server close all connection and restart using lower function
+--echo #
+CREATE TABLE t1 (a VARCHAR(10)) CHARACTER SET utf8 COLLATE utf8_test_ci;
+INSERT INTO t1 (a) VALUES ('hello!');
+SELECT * FROM t1 WHERE LOWER(a)=LOWER('N');
+DROP TABLE t1;
+
+--echo #
 --echo # Bug#43827 Server closes connections and restarts
 --echo #
 # Crash happened with a user-defined utf8 collation,
@@ -86,3 +94,8 @@ select hex(c1) as h, c1 from t1 order by
 select group_concat(hex(c1) order by hex(c1)) from t1 group by c1;
 select group_concat(c1 order by hex(c1) SEPARATOR '') from t1 group by c1;
 drop table t1;
+
+--echo Bug#46448 trailing spaces are not ignored when user collation maps space != 0x20
+set names latin1;
+show collation like 'latin1_test';
+select "foo" = "foo " collate latin1_test;

=== added file 'mysql-test/t/debug_sync.test'
--- a/mysql-test/t/debug_sync.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/debug_sync.test	2009-09-29 15:38:40 +0000
@@ -0,0 +1,420 @@
+###################### t/debug_sync.test ###############################
+#                                                                      #
+# Testing of the Debug Sync Facility.                                  #
+#                                                                      #
+# There is important documentation within sql/debug_sync.cc            #
+#                                                                      #
+# Used objects in this test case:                                      #
+# p0 - synchronization point 0. Non-existent dummy sync point.         #
+# s1 - signal 1.                                                       #
+# s2 - signal 2.                                                       #
+#                                                                      #
+# Creation:                                                            #
+# 2008-02-18 istruewing                                                #
+#                                                                      #
+########################################################################
+
+#
+# We need the Debug Sync Facility.
+#
+--source include/have_debug_sync.inc
+
+#
+# We are checking privileges, which the embedded server cannot do.
+#
+--source include/not_embedded.inc
+
+#
+# Preparative cleanup.
+#
+--disable_warnings
+SET DEBUG_SYNC= 'RESET';
+DROP TABLE IF EXISTS t1;
+--enable_warnings
+
+#
+# Show the special system variable.
+# It shows ON or OFF depending on the command line option --debug-sync.
+# The test case assumes it is ON (command line option present).
+#
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+
+#
+# Syntax. Valid forms.
+#
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6           HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2           EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2           EXECUTE 2';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2                     HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2';
+SET DEBUG_SYNC='p0 SIGNAL s1                       EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1                       EXECUTE 2';
+SET DEBUG_SYNC='p0 SIGNAL s1                                 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 SIGNAL s1';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6 EXECUTE 2';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6           HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2 TIMEOUT 6';
+SET DEBUG_SYNC='p0           WAIT_FOR s2           EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2           EXECUTE 2';
+SET DEBUG_SYNC='p0           WAIT_FOR s2                     HIT_LIMIT 3';
+SET DEBUG_SYNC='p0           WAIT_FOR s2';
+SET DEBUG_SYNC='p0                                           HIT_LIMIT 3';
+SET DEBUG_SYNC='p0 CLEAR';
+SET DEBUG_SYNC='p0 TEST';
+SET DEBUG_SYNC='RESET';
+
+#
+# Syntax. Valid forms. Lower case.
+#
+set debug_sync='p0 signal s1 wait_for s2 timeout 6 execute 2 hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2 timeout 6 execute 2';
+set debug_sync='p0 signal s1 wait_for s2 timeout 6           hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2 timeout 6';
+set debug_sync='p0 signal s1 wait_for s2           execute 2 hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2           execute 2';
+set debug_sync='p0 signal s1 wait_for s2                     hit_limit 3';
+set debug_sync='p0 signal s1 wait_for s2';
+set debug_sync='p0 signal s1                       execute 2 hit_limit 3';
+set debug_sync='p0 signal s1                       execute 2';
+set debug_sync='p0 signal s1                                 hit_limit 3';
+set debug_sync='p0 signal s1';
+set debug_sync='p0           wait_for s2 timeout 6 execute 2 hit_limit 3';
+set debug_sync='p0           wait_for s2 timeout 6 execute 2';
+set debug_sync='p0           wait_for s2 timeout 6           hit_limit 3';
+set debug_sync='p0           wait_for s2 timeout 6';
+set debug_sync='p0           wait_for s2           execute 2 hit_limit 3';
+set debug_sync='p0           wait_for s2           execute 2';
+set debug_sync='p0           wait_for s2                     hit_limit 3';
+set debug_sync='p0           wait_for s2';
+set debug_sync='p0                                           hit_limit 3';
+set debug_sync='p0 clear';
+set debug_sync='p0 test';
+set debug_sync='reset';
+
+#
+# Syntax. Valid forms. Line wrap, leading, mid, trailing space.
+#
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6
+                EXECUTE 2 HIT_LIMIT 3';
+SET DEBUG_SYNC='   p0 SIGNAL s1 WAIT_FOR s2';
+SET DEBUG_SYNC='p0    SIGNAL    s1    WAIT_FOR    s2';
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2   ';
+SET DEBUG_SYNC='   p0 SIGNAL s1 WAIT_FOR s2   ';
+SET DEBUG_SYNC='   p0    SIGNAL    s1    WAIT_FOR    s2   ';
+
+#
+# Syntax. Invalid forms.
+#
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC=' ';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0                                          EXECUTE 2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0                                TIMEOUT 6 EXECUTE 2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0                                TIMEOUT 6';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1           EXECUTE 2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1 TIMEOUT 6 EXECUTE 2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 SIGNAL s1 TIMEOUT 6';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 6 SIGNAL s1 EXECUTE 2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 6 SIGNAL s1';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 TIMEOUT 6 WAIT_FOR s2 EXECUTE 2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 TIMEOUT 6 WAIT_FOR s2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0                  SIGNAL s1 TIMEOUT 6 EXECUTE 2';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0                  SIGNAL s1 TIMEOUT 6';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 EXECUTE 2 SIGNAL s1 TIMEOUT 6';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 TIMEOUT 6 SIGNAL s1';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 EXECUTE 2 TIMEOUT 6 SIGNAL s1';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 CLEAR HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='CLEAR';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 CLEAR p0';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='TEST';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 TEST p0';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 RESET';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='RESET p0';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 RESET p0';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 SIGNAL ';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR ';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 SIGNAL s1 EXECUTE ';
+
+#
+# Syntax. Invalid keywords used.
+#
+--error ER_UNKNOWN_SYSTEM_VARIABLE
+SET DEBUG_SYNCx='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 SIGNAx s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOx s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUx 0 EXECUTE 2 HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTx 2 HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 SIGNAL s1 WAIT_FOR s2 TIMEOUT 6 EXECUTE 2 HIT_LIMIx 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 CLEARx';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 TESTx';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='RESETx';
+
+#
+# Syntax. Invalid numbers. Decimal only.
+#
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 0x6 EXECUTE 2 HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 6 EXECUTE 0x2 HIT_LIMIT 3';
+--error ER_PARSE_ERROR
+SET DEBUG_SYNC='p0 WAIT_FOR s2 TIMEOUT 7 EXECUTE 2 HIT_LIMIT 0x3';
+
+#
+# Syntax. Invalid value type.
+#
+--error ER_WRONG_TYPE_FOR_VAR
+SET DEBUG_SYNC= 7;
+
+#
+# Syntax. DEBUG_SYNC is a SESSION-only variable.
+#
+--error ER_LOCAL_VARIABLE
+SET GLOBAL DEBUG_SYNC= 'p0 CLEAR';
+
+#
+# Syntax. The variable value does not need to be a string literal.
+#
+SET @myvar= 'now SIGNAL from_myvar';
+SET DEBUG_SYNC= @myvar;
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+#
+SET DEBUG_SYNC= LEFT('now SIGNAL from_function_cut_here', 24);
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+
+#
+# Functional tests.
+#
+# NOTE: There is the special synchronization point 'now'. It is placed
+#       immediately after setting of the DEBUG_SYNC variable.
+#       So it is executed before the SET statement ends.
+#
+# NOTE: There is only one global signal (say "signal post" or "flag mast").
+#       A SIGNAL action writes its signal into it ("sets a flag").
+#       The signal persists until explicitly overwritten.
+#       To avoid confusion for later tests, it is recommended to clear
+#       the signal by signalling "empty" ("setting the 'empty' flag"):
+#       SET DEBUG_SYNC= 'now SIGNAL empty';
+#       Preferably you can reset the whole facility with:
+#       SET DEBUG_SYNC= 'RESET';
+#       The signal is then '' (really empty) which connot be done otherwise.
+#
+
+#
+# Time out immediately. This gives just a warning.
+#
+SET DEBUG_SYNC= 'now SIGNAL something';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+# Suppress warning number
+--replace_column 2 ####
+SET DEBUG_SYNC= 'now WAIT_FOR nothing TIMEOUT 0';
+#
+# If signal is present already, TIMEOUT 0 does not give a warning.
+#
+SET DEBUG_SYNC= 'now SIGNAL nothing';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'now WAIT_FOR nothing TIMEOUT 0';
+
+#
+# EXECUTE 0 is effectively a no-op.
+#
+SET DEBUG_SYNC= 'now SIGNAL something EXECUTE 0';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'now WAIT_FOR anotherthing TIMEOUT 0 EXECUTE 0';
+
+#
+# Run into HIT_LIMIT. This gives an error.
+#
+--error ER_DEBUG_SYNC_HIT_LIMIT
+SET DEBUG_SYNC= 'now HIT_LIMIT 1';
+
+#
+# Many actions. Watch the array growing and shrinking in the debug trace:
+# egrep 'query:|debug_sync_action:' mysql-test/var/log/master.trace
+#
+SET DEBUG_SYNC= 'RESET';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'p1abcd   SIGNAL s1 EXECUTE 2';
+SET DEBUG_SYNC= 'p2abc    SIGNAL s2 EXECUTE 2';
+SET DEBUG_SYNC= 'p9abcdef SIGNAL s9 EXECUTE 2';
+SET DEBUG_SYNC= 'p4a      SIGNAL s4 EXECUTE 2';
+SET DEBUG_SYNC= 'p5abcde  SIGNAL s5 EXECUTE 2';
+SET DEBUG_SYNC= 'p6ab     SIGNAL s6 EXECUTE 2';
+SET DEBUG_SYNC= 'p7       SIGNAL s7 EXECUTE 2';
+SET DEBUG_SYNC= 'p8abcdef SIGNAL s8 EXECUTE 2';
+SET DEBUG_SYNC= 'p3abcdef SIGNAL s3 EXECUTE 2';
+#
+# Execute some actions to show they exist. Each sets a distinct signal.
+#
+SET DEBUG_SYNC= 'p4a      TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'p1abcd   TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'p7       TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'p9abcdef TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'p3abcdef TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+#
+# Clear the actions.
+#
+SET DEBUG_SYNC= 'p1abcd   CLEAR';
+SET DEBUG_SYNC= 'p2abc    CLEAR';
+SET DEBUG_SYNC= 'p5abcde  CLEAR';
+SET DEBUG_SYNC= 'p6ab     CLEAR';
+SET DEBUG_SYNC= 'p8abcdef CLEAR';
+SET DEBUG_SYNC= 'p9abcdef CLEAR';
+SET DEBUG_SYNC= 'p3abcdef CLEAR';
+SET DEBUG_SYNC= 'p4a      CLEAR';
+SET DEBUG_SYNC= 'p7       CLEAR';
+#
+# Execute some actions to show they have gone.
+#
+SET DEBUG_SYNC= 'p1abcd   TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'p7       TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+SET DEBUG_SYNC= 'p9abcdef TEST';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+#
+# Now cleanup. Actions are clear already, but signal needs to be cleared.
+#
+SET DEBUG_SYNC= 'RESET';
+SHOW VARIABLES LIKE 'DEBUG_SYNC';
+
+#
+# Facility requires SUPER privilege.
+#
+CREATE USER mysqltest_1@localhost;
+GRANT SUPER ON *.* TO mysqltest_1@localhost;
+--echo connection con1, mysqltest_1
+connect (con1,localhost,mysqltest_1,,);
+SET DEBUG_SYNC= 'RESET';
+disconnect con1;
+--echo connection default
+connection default;
+DROP USER mysqltest_1@localhost;
+#
+CREATE USER mysqltest_2@localhost;
+GRANT ALL ON *.* TO mysqltest_2@localhost;
+REVOKE SUPER ON *.* FROM mysqltest_2@localhost;
+--echo connection con1, mysqltest_2
+connect (con1,localhost,mysqltest_2,,);
+--error ER_SPECIFIC_ACCESS_DENIED_ERROR
+SET DEBUG_SYNC= 'RESET';
+disconnect con1;
+--echo connection default
+connection default;
+DROP USER mysqltest_2@localhost;
+
+#
+# Example 1.
+#
+# Preparative cleanup.
+--disable_warnings
+SET DEBUG_SYNC= 'RESET';
+DROP TABLE IF EXISTS t1;
+--enable_warnings
+#
+# Test.
+CREATE TABLE t1 (c1 INT);
+    --echo connection con1
+    connect (con1,localhost,root,,);
+    SET DEBUG_SYNC= 'before_lock_tables_takes_lock
+      SIGNAL opened WAIT_FOR flushed';
+    send INSERT INTO t1 VALUES(1);
+--echo connection default
+connection default;
+SET DEBUG_SYNC= 'now WAIT_FOR opened';
+SET DEBUG_SYNC= 'after_flush_unlock SIGNAL flushed';
+FLUSH TABLE t1;
+    --echo connection con1
+    connection con1;
+    reap;
+    disconnect con1;
+--echo connection default
+connection default;
+DROP TABLE t1;
+
+#
+# Example 2.
+#
+# Preparative cleanup.
+--disable_warnings
+SET DEBUG_SYNC= 'RESET';
+DROP TABLE IF EXISTS t1;
+--enable_warnings
+#
+# Test.
+CREATE TABLE t1 (c1 INT);
+LOCK TABLE t1 WRITE;
+    --echo connection con1
+    connect (con1,localhost,root,,);
+    # Retain action after use. First used by general_log.
+    SET DEBUG_SYNC= 'wait_for_lock SIGNAL locked EXECUTE 2';
+    send INSERT INTO t1 VALUES (1);
+--echo connection default
+connection default;
+# Wait until INSERT waits for lock.
+SET DEBUG_SYNC= 'now WAIT_FOR locked';
+# let INSERT continue.
+UNLOCK TABLES;
+    --echo connection con1
+    connection con1;
+    --echo retrieve INSERT result.
+    reap;
+    disconnect con1;
+--echo connection default
+connection default;
+DROP TABLE t1;
+
+#
+# Cleanup after test case.
+# Otherwise signal would contain 'flushed' here,
+# which could confuse the next test.
+#
+SET DEBUG_SYNC= 'RESET';
+

=== modified file 'mysql-test/t/delete.test'
--- a/mysql-test/t/delete.test	2007-12-07 14:15:58 +0000
+++ b/mysql-test/t/delete.test	2009-09-28 10:48:52 +0000
@@ -292,3 +292,47 @@ DROP TABLE t1;
 DROP FUNCTION f1;
 
 --echo End of 5.0 tests
+
+--echo #
+--echo # Bug#46958: Assertion in Diagnostics_area::set_ok_status, trigger, 
+--echo # merge table
+--echo #
+CREATE TABLE t1 ( a INT );
+CREATE TABLE t2 ( a INT );
+CREATE TABLE t3 ( a INT );
+
+INSERT INTO t1 VALUES (1), (2);
+INSERT INTO t2 VALUES (1), (2);
+INSERT INTO t3 VALUES (1), (2);
+
+CREATE TRIGGER tr1 BEFORE DELETE ON t2
+FOR EACH ROW INSERT INTO no_such_table VALUES (1);
+
+--error ER_NO_SUCH_TABLE
+DELETE t1, t2, t3 FROM t1, t2, t3;
+
+SELECT * FROM t1;
+SELECT * FROM t2;
+SELECT * FROM t3;
+
+DROP TABLE t1, t2, t3;
+
+CREATE TABLE t1 ( a INT );
+CREATE TABLE t2 ( a INT );
+CREATE TABLE t3 ( a INT );
+
+INSERT INTO t1 VALUES (1), (2);
+INSERT INTO t2 VALUES (1), (2);
+INSERT INTO t3 VALUES (1), (2);
+
+CREATE TRIGGER tr1 AFTER DELETE ON t2
+FOR EACH ROW INSERT INTO no_such_table VALUES (1);
+
+--error ER_NO_SUCH_TABLE
+DELETE t1, t2, t3 FROM t1, t2, t3;
+
+SELECT * FROM t1;
+SELECT * FROM t2;
+SELECT * FROM t3;
+
+DROP TABLE t1, t2, t3;

=== modified file 'mysql-test/t/disabled.def'
--- a/mysql-test/t/disabled.def	2009-09-07 20:50:10 +0000
+++ b/mysql-test/t/disabled.def	2009-11-10 15:15:12 +0000
@@ -10,7 +10,8 @@
 #
 ##############################################################################
 kill                     : Bug#37780 2008-12-03 HHunger need some changes to be robust enough for pushbuild.
-innodb_bug39438          : Bug#42383 2009-01-28 lsoares "This fails in embedded and on windows.  Note that this test is not run on windows and on embedded in PB for main trees currently"
 query_cache_28249        : Bug#43861 2009-03-25 main.query_cache_28249 fails sporadically
-init_connect             : Bug#44920 2009-07-06 pcrews MTR not processing master.opt input properly on Windows.  *Must be done this way due to the nature of the bug*
-
+partition_innodb_builtin : Bug#32430 2009-09-25 mattiasj Waiting for push of Innodb changes
+partition_innodb_plugin  : Bug#32430 2009-09-25 mattiasj Waiting for push of Innodb changes
+innodb-autoinc           : Bug#48482 2009-11-02 svoj innodb-autoinc.test fails with results difference
+rpl_killed_ddl           : Bug#45520: rpl_killed_ddl fails sporadically in pb2

=== modified file 'mysql-test/t/distinct.test'
--- a/mysql-test/t/distinct.test	2008-10-29 17:38:18 +0000
+++ b/mysql-test/t/distinct.test	2009-09-05 20:42:17 +0000
@@ -573,4 +573,44 @@ SELECT DISTINCT a, b, d, c FROM t1;
 
 DROP TABLE t1;
 
+--echo #
+--echo # Bug #46159: simple query that never returns
+--echo #
+
+# Set max_heap_table_size to the minimum value so that GROUP BY table in the
+# SELECT query below gets converted to MyISAM
+SET @old_max_heap_table_size = @@max_heap_table_size;
+SET @@max_heap_table_size = 16384;
+
+# Set sort_buffer_size to the mininum value so that remove_duplicates() calls
+# remove_dup_with_compare()
+SET @old_sort_buffer_size = @@sort_buffer_size;
+SET @@sort_buffer_size = 32804;
+
+CREATE TABLE t1(c1 int, c2 VARCHAR(20));
+INSERT INTO t1 VALUES (1, '1'), (1, '1'), (2, '2'), (3, '1'), (3, '1'), (4, '4');
+# Now we just need to pad the table with random data so we have enough unique
+# values to force conversion of the GROUP BY table to MyISAM
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+INSERT INTO t1 SELECT 5 + 10000 * RAND(), '5' FROM t1;
+
+# First rows of the GROUP BY table that will be processed by 
+# remove_dup_with_compare()
+SELECT c1, c2, COUNT(*) FROM t1 GROUP BY c1 LIMIT 4;
+
+# The actual test case
+SELECT DISTINCT c2 FROM t1 GROUP BY c1 HAVING COUNT(*) > 1;
+
+# Cleanup
+
+DROP TABLE t1;
+SET @@sort_buffer_size = @old_sort_buffer_size;
+SET @@max_heap_table_size = @old_max_heap_table_size;
+
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/explain.test'
--- a/mysql-test/t/explain.test	2009-06-11 16:21:32 +0000
+++ b/mysql-test/t/explain.test	2009-10-29 23:01:54 +0000
@@ -135,6 +135,17 @@ EXPLAIN EXTENDED SELECT COUNT(a) FROM t1
 
 DROP TABLE t1;
 
+#
+# Bug#45989 memory leak after explain encounters an error in the query
+#
+CREATE TABLE t1(a LONGTEXT);
+INSERT INTO t1 VALUES (repeat('a',@@global.max_allowed_packet));
+INSERT INTO t1 VALUES (repeat('b',@@global.max_allowed_packet));
+--error ER_BAD_FIELD_ERROR
+EXPLAIN SELECT DISTINCT 1 FROM t1,
+        (SELECT DISTINCTROW a AS away FROM t1 GROUP BY a WITH ROLLUP) as d1
+         WHERE t1.a = d1.a;
+DROP TABLE t1;
 
 # End of 5.0 tests.
 
@@ -156,4 +167,24 @@ flush tables;
 SELECT OUTR.dt FROM t1 AS OUTR WHERE OUTR.dt IN ( SELECT INNR.dt FROM t2 AS INNR WHERE OUTR.t < '2005-11-13 7:41:31' );
 drop tables t1, t2;
 
+--echo #
+--echo # Bug#48295:
+--echo # explain extended crash with subquery and ONLY_FULL_GROUP_BY sql_mode
+--echo #
+
+CREATE TABLE t1 (f1 INT);
+
+SELECT @@session.sql_mode INTO @old_sql_mode;
+SET SESSION sql_mode='ONLY_FULL_GROUP_BY';
+
+# EXPLAIN EXTENDED (with subselect). used to crash. should give NOTICE.
+--error ER_MIX_OF_GROUP_FUNC_AND_FIELDS
+EXPLAIN EXTENDED SELECT 1 FROM t1
+                          WHERE f1 > ALL( SELECT t.f1 FROM t1,t1 AS t );
+SHOW WARNINGS;
+
+SET SESSION sql_mode=@old_sql_mode;
+
+DROP TABLE t1;
+
 --echo End of 5.1 tests.

=== modified file 'mysql-test/t/flush_read_lock_kill.test'
--- a/mysql-test/t/flush_read_lock_kill.test	2009-03-06 14:56:17 +0000
+++ b/mysql-test/t/flush_read_lock_kill.test	2009-10-20 18:00:07 +0000
@@ -57,7 +57,7 @@ connection con1;
 # debug build running without our --debug=make_global..., will be
 # error 0 (no error). The only important thing to test is that on
 # debug builds with our --debug=make_global... we don't hang forever.
---error 0,1053,2013
+--error 0,1317,2013
 reap;
 
 connection con2;

=== modified file 'mysql-test/t/func_group.test'
--- a/mysql-test/t/func_group.test	2009-04-01 11:10:03 +0000
+++ b/mysql-test/t/func_group.test	2009-10-14 08:46:50 +0000
@@ -1006,3 +1006,51 @@ DROP TABLE t1;
 
 ###
 --echo End of 5.0 tests
+
+--echo #
+--echo # BUG#47280 - strange results from count(*) with order by multiple 
+--echo #             columns without where/group
+--echo # 
+
+--echo # 
+--echo # Initialize test
+--echo # 
+
+CREATE TABLE t1 (
+  pk INT NOT NULL,
+  i INT,
+  PRIMARY KEY (pk)
+);
+INSERT INTO t1 VALUES (1,11),(2,12),(3,13);
+
+--echo #
+--echo # Start test
+--echo # All the following queries shall return 1 record
+--echo #
+
+--echo
+--echo # Masking all correct values {11...13} for column i in this result. 
+--replace_column 2 #
+SELECT MAX(pk) as max, i
+FROM t1
+ORDER BY max;
+
+--echo
+EXPLAIN
+SELECT MAX(pk) as max, i
+FROM t1
+ORDER BY max;
+
+--echo
+--echo # Only 11 is correct for collumn i in this result
+SELECT MAX(pk) as max, i
+FROM t1
+WHERE pk<2
+ORDER BY max;
+
+--echo #
+--echo # Cleanup
+--echo #
+DROP TABLE t1;
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/func_in.test'
--- a/mysql-test/t/func_in.test	2009-05-25 08:00:40 +0000
+++ b/mysql-test/t/func_in.test	2009-10-05 05:27:36 +0000
@@ -456,4 +456,89 @@ SELECT SUM( DISTINCT e ) FROM t1 GROUP B
   ((AVG( 1 ), 1 + c, 1 + d), (AVG( 1 ), 2 + c, 2 + d));
 DROP TABLE t1;
 
+--echo #
+--echo # Bug #44139: Table scan when NULL appears in IN clause
+--echo #
+
+--disable_warnings
+
+CREATE TABLE t1 (
+  c_int INT NOT NULL,
+  c_decimal DECIMAL(5,2) NOT NULL,
+  c_float FLOAT(5, 2) NOT NULL,
+  c_bit BIT(10) NOT NULL,
+  c_date DATE NOT NULL, 
+  c_datetime DATETIME NOT NULL,
+  c_timestamp TIMESTAMP NOT NULL,
+  c_time TIME NOT NULL,
+  c_year YEAR NOT NULL,
+  c_char CHAR(10) NOT NULL,
+  INDEX(c_int), INDEX(c_decimal), INDEX(c_float), INDEX(c_bit), INDEX(c_date),
+  INDEX(c_datetime), INDEX(c_timestamp), INDEX(c_time), INDEX(c_year),
+  INDEX(c_char));
+
+INSERT INTO t1 (c_int) VALUES (1), (2), (3), (4), (5);
+INSERT INTO t1 (c_int) SELECT 0 FROM t1;
+INSERT INTO t1 (c_int) SELECT 0 FROM t1;
+
+--enable_warnings
+
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (NULL, 1, 2, 3);
+
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (1, NULL, 2, NULL, 3, NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_int IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (NULL, 1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_decimal IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (NULL, 1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_float IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (NULL, 1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_bit IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_date 
+  IN ('2009-09-01', '2009-09-02', '2009-09-03');
+EXPLAIN SELECT * FROM t1 WHERE c_date
+  IN (NULL, '2009-09-01', '2009-09-02', '2009-09-03');
+EXPLAIN SELECT * FROM t1 WHERE c_date IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_date IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_datetime
+  IN ('2009-09-01 00:00:01', '2009-09-02 00:00:01', '2009-09-03 00:00:01');
+EXPLAIN SELECT * FROM t1 WHERE c_datetime
+  IN (NULL, '2009-09-01 00:00:01', '2009-09-02 00:00:01', '2009-09-03 00:00:01');
+EXPLAIN SELECT * FROM t1 WHERE c_datetime IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_datetime IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp
+  IN ('2009-09-01 00:00:01', '2009-09-01 00:00:02', '2009-09-01 00:00:03');
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp
+  IN (NULL, '2009-09-01 00:00:01', '2009-09-01 00:00:02', '2009-09-01 00:00:03');
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_timestamp IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (NULL, 1, 2, 3);
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_year IN (NULL, NULL);
+
+EXPLAIN SELECT * FROM t1 WHERE c_char IN ('1', '2', '3');
+EXPLAIN SELECT * FROM t1 WHERE c_char IN (NULL, '1', '2', '3');
+EXPLAIN SELECT * FROM t1 WHERE c_char IN (NULL);
+EXPLAIN SELECT * FROM t1 WHERE c_char IN (NULL, NULL);
+
+DROP TABLE t1;
+
+--echo #
+
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/func_str.test'
--- a/mysql-test/t/func_str.test	2009-05-13 18:39:35 +0000
+++ b/mysql-test/t/func_str.test	2009-09-10 10:30:03 +0000
@@ -1291,6 +1291,19 @@ INSERT INTO t1 VALUES ('aaaaaaaa');
 SELECT LOAD_FILE(a) FROM t1;
 DROP TABLE t1;
 
+#
+# Bug#46815 CONCAT_WS returning wrong data
+#
+CREATE TABLE t1 (f2 VARCHAR(20));
+CREATE TABLE t2 (f2 VARCHAR(20));
+
+INSERT INTO t1 VALUES ('MIN'),('MAX');
+INSERT INTO t2 VALUES ('LOAD');
+
+SELECT CONCAT_WS('_', (SELECT t2.f2 FROM t2), t1.f2) AS concat_name FROM t1;
+
+DROP TABLE t1, t2;
+
 
 --echo End of 5.0 tests
 

=== modified file 'mysql-test/t/gis-rtree.test'
--- a/mysql-test/t/gis-rtree.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/gis-rtree.test	2009-11-10 15:15:12 +0000
@@ -893,4 +893,25 @@ SELECT COUNT(*) FROM t1 IGNORE INDEX (b)
 
 DROP TABLE t1;
 
+
+--echo #
+--echo # Bug #48258: Assertion failed when using a spatial index
+--echo #
+CREATE TABLE t1(a LINESTRING NOT NULL, SPATIAL KEY(a));
+INSERT INTO t1 VALUES
+  (GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)')),
+  (GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)'));
+EXPLAIN SELECT 1 FROM t1 WHERE a = GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+SELECT 1 FROM t1 WHERE a = GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+EXPLAIN SELECT 1 FROM t1 WHERE a < GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+SELECT 1 FROM t1 WHERE a < GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+EXPLAIN SELECT 1 FROM t1 WHERE a <= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+SELECT 1 FROM t1 WHERE a <= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+EXPLAIN SELECT 1 FROM t1 WHERE a > GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+SELECT 1 FROM t1 WHERE a > GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+EXPLAIN SELECT 1 FROM t1 WHERE a >= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+SELECT 1 FROM t1 WHERE a >= GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)');
+DROP TABLE t1;
+
+
 --echo End of 5.0 tests.

=== modified file 'mysql-test/t/gis.test'
--- a/mysql-test/t/gis.test	2009-07-10 23:12:13 +0000
+++ b/mysql-test/t/gis.test	2009-10-24 06:57:31 +0000
@@ -655,6 +655,22 @@ insert into t1 values (),(),();
 select min(`col002`) from t1 union select `col002` from t1;
 drop table t1;
 
+--echo #
+--echo # Bug #47780: crash when comparing GIS items from subquery
+--echo #
+
+CREATE TABLE t1(a INT, b MULTIPOLYGON);
+INSERT INTO t1 VALUES 
+  (0,
+   GEOMFROMTEXT(
+    'multipolygon(((1 2,3 4,5 6,7 8,9 8),(7 6,5 4,3 2,1 2,3 4)))'));
+
+--echo # must not crash
+SELECT 1 FROM t1 WHERE a <> (SELECT GEOMETRYCOLLECTIONFROMWKB(b) FROM t1);
+
+DROP TABLE t1;
+
+
 --echo End of 5.0 tests
 
 

=== modified file 'mysql-test/t/grant3.test'
--- a/mysql-test/t/grant3.test	2009-02-02 21:20:25 +0000
+++ b/mysql-test/t/grant3.test	2009-10-20 06:17:57 +0000
@@ -163,6 +163,41 @@ connection default;
 DROP USER 'mysqltest1'@'%';
 DROP DATABASE mysqltest_1;
 
+--echo #
+--echo # Bug#41597 - After rename of user, there are additional grants
+--echo #             when grants are reapplied.
+--echo #
+
+CREATE DATABASE temp;
+CREATE TABLE temp.t1(a INT, b VARCHAR(10));
+INSERT INTO temp.t1 VALUES(1, 'name1');
+INSERT INTO temp.t1 VALUES(2, 'name2');
+INSERT INTO temp.t1 VALUES(3, 'name3');
+
+
+CREATE USER 'user1'@'%';
+RENAME USER 'user1'@'%' TO 'user2'@'%';
+--echo # Show privileges after rename and BEFORE grant
+SHOW GRANTS FOR 'user2'@'%';
+GRANT SELECT (a), INSERT (b) ON `temp`.`t1` TO 'user2'@'%';
+--echo # Show privileges after rename and grant
+SHOW GRANTS FOR 'user2'@'%';
+
+--echo # Connect as the renamed user
+connect (conn1, localhost, user2,,);
+connection conn1;
+SHOW GRANTS;
+SELECT a FROM temp.t1;
+--echo # Check for additional privileges by accessing a
+--echo # non privileged column. We shouldn't be able to 
+--echo # access this column.
+--error ER_COLUMNACCESS_DENIED_ERROR 
+SELECT b FROM temp.t1;
+disconnect conn1;
+
+connection default;
+DROP USER 'user2'@'%';
+DROP DATABASE temp;
 
 --echo End of 5.0 tests
 

=== added file 'mysql-test/t/grant_lowercase_fs.test'
--- a/mysql-test/t/grant_lowercase_fs.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/grant_lowercase_fs.test	2009-10-27 08:09:19 +0000
@@ -0,0 +1,30 @@
+-- source include/have_case_insensitive_fs.inc
+-- source include/not_embedded.inc
+
+
+#
+# Bug#41049 does syntax "grant" case insensitive?
+#
+create database db1;
+GRANT CREATE ON db1.* to user_1@localhost;
+GRANT SELECT ON db1.* to USER_1@localhost;
+
+connect (con1,localhost,user_1,,db1);
+CREATE TABLE t1(f1 int);
+--error 1142
+SELECT * FROM t1;
+connect (con2,localhost,USER_1,,db1);
+SELECT * FROM t1;
+--error 1142
+CREATE TABLE t2(f1 int);
+
+connection default;
+disconnect con1;
+disconnect con2;
+
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM user_1@localhost;
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM USER_1@localhost;
+DROP USER user_1@localhost;
+DROP USER USER_1@localhost;
+DROP DATABASE db1;
+use test;

=== modified file 'mysql-test/t/information_schema_db.test'
--- a/mysql-test/t/information_schema_db.test	2009-09-07 20:50:10 +0000
+++ b/mysql-test/t/information_schema_db.test	2009-11-10 15:15:12 +0000
@@ -181,7 +181,6 @@ show fields from testdb_1.v7;
 --error ER_TABLEACCESS_DENIED_ERROR
 show create view testdb_1.v7;
 
---error ER_VIEW_NO_EXPLAIN
 show create view v4;
 #--error ER_VIEW_NO_EXPLAIN
 show fields from v4;

=== modified file 'mysql-test/t/innodb-autoinc.test'
--- a/mysql-test/t/innodb-autoinc.test	2009-06-09 15:08:46 +0000
+++ b/mysql-test/t/innodb-autoinc.test	2009-11-10 15:15:12 +0000
@@ -156,7 +156,7 @@ DROP TABLE t1;
 #
 # Test changes to AUTOINC next value calculation
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 INT AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 INSERT INTO t1 VALUES (NULL),(5),(NULL);
@@ -173,7 +173,7 @@ DROP TABLE t1;
 # Reset the AUTOINC session variables
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 INT AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 INSERT INTO t1 VALUES(0);
@@ -193,13 +193,13 @@ DROP TABLE t1;
 # Reset the AUTOINC session variables
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 INT AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 INSERT INTO t1 VALUES(-1);
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 INSERT INTO t1 VALUES (-2), (NULL),(2),(NULL);
 INSERT INTO t1 VALUES (250),(NULL);
 SELECT * FROM t1;
@@ -214,13 +214,13 @@ DROP TABLE t1;
 # Reset the AUTOINC session variables
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 INT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 INSERT INTO t1 VALUES(-1);
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 INSERT INTO t1 VALUES (-2);
 INSERT INTO t1 VALUES (NULL);
 INSERT INTO t1 VALUES (2);
@@ -240,13 +240,13 @@ DROP TABLE t1;
 # Reset the AUTOINC session variables
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 INT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 INSERT INTO t1 VALUES(-1);
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=100, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 INSERT INTO t1 VALUES (-2),(NULL),(2),(NULL);
 INSERT INTO t1 VALUES (250),(NULL);
 SELECT * FROM t1;
@@ -262,7 +262,7 @@ DROP TABLE t1;
 # Check for overflow handling when increment is > 1
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 BIGINT AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 # TODO: Fix the autoinc init code
@@ -271,7 +271,7 @@ INSERT INTO t1 VALUES(NULL);
 INSERT INTO t1 VALUES (9223372036854775794); #-- 2^63 - 14
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=2, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 # This should just fit
 INSERT INTO t1 VALUES (NULL),(NULL),(NULL),(NULL),(NULL),(NULL);
 SELECT * FROM t1;
@@ -281,7 +281,7 @@ DROP TABLE t1;
 # Check for overflow handling when increment and offser are > 1
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 BIGINT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 # TODO: Fix the autoinc init code
@@ -290,7 +290,7 @@ INSERT INTO t1 VALUES(NULL);
 INSERT INTO t1 VALUES (18446744073709551603); #-- 2^64 - 13
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=2, @@SESSION.AUTO_INCREMENT_OFFSET=10;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 # This should fail because of overflow but it doesn't, it seems to be
 # a MySQL server bug. It wraps around to 0 for the last value.
 # See MySQL Bug# 39828
@@ -313,7 +313,7 @@ DROP TABLE t1;
 # Check for overflow handling when increment and offset are odd numbers
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 BIGINT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 # TODO: Fix the autoinc init code
@@ -322,7 +322,7 @@ INSERT INTO t1 VALUES(NULL);
 INSERT INTO t1 VALUES (18446744073709551603); #-- 2^64 - 13
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=5, @@SESSION.AUTO_INCREMENT_OFFSET=7;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 # This should fail because of overflow but it doesn't. It fails with
 # a duplicate entry message because of a MySQL server bug, it wraps
 # around.  See MySQL Bug# 39828, once MySQL fix the bug we can replace
@@ -344,7 +344,7 @@ DROP TABLE t1;
 # and check for large -ve numbers
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 BIGINT AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 # TODO: Fix the autoinc init code
@@ -355,7 +355,7 @@ INSERT INTO t1 VALUES(-92233720368547758
 INSERT INTO t1 VALUES(-9223372036854775808); #-- -2^63
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=3, @@SESSION.AUTO_INCREMENT_OFFSET=3;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 INSERT INTO t1 VALUES (NULL),(NULL), (NULL);
 SELECT * FROM t1;
 DROP TABLE t1;
@@ -364,7 +364,7 @@ DROP TABLE t1;
 # large numbers 2^60
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 BIGINT UNSIGNED AUTO_INCREMENT, PRIMARY KEY(c1)) ENGINE=InnoDB;
 # TODO: Fix the autoinc init code
@@ -373,7 +373,7 @@ INSERT INTO t1 VALUES(NULL);
 INSERT INTO t1 VALUES (18446744073709551610); #-- 2^64 - 2
 SELECT * FROM t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1152921504606846976, @@SESSION.AUTO_INCREMENT_OFFSET=1152921504606846976;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 # This should fail because of overflow but it doesn't. It wraps around
 # and the autoinc values look bogus too.
 # See MySQL Bug# 39828, once MySQL fix the bug we can enable the error
@@ -396,7 +396,7 @@ DROP TABLE t1;
 #
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
 SET @@INSERT_ID=1;
-SHOW VARIABLES LIKE "auto_inc%";
+SHOW VARIABLES LIKE "%auto_inc%";
 CREATE TABLE t1 (c1 DOUBLE NOT NULL AUTO_INCREMENT, c2 INT, PRIMARY KEY (c1)) ENGINE=InnoDB;
 INSERT INTO t1 VALUES(NULL, 1);
 INSERT INTO t1 VALUES(NULL, 2);
@@ -478,3 +478,145 @@ INSERT INTO t2 SELECT c1 FROM t1;
 INSERT INTO t2 SELECT NULL FROM t1;
 DROP TABLE t1;
 DROP TABLE t2;
+#
+# 44030: Error: (1500) Couldn't read the MAX(ID) autoinc value from
+# the index (PRIMARY)
+# This test requires a restart of the server
+SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
+CREATE TABLE t1 (c1 INT PRIMARY KEY AUTO_INCREMENT) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (null);
+INSERT INTO t1 VALUES (null);
+ALTER TABLE t1 CHANGE c1 d1 INT NOT NULL AUTO_INCREMENT;
+SELECT * FROM t1;
+# Restart the server
+-- source include/restart_mysqld.inc
+# The MySQL and InnoDB data dictionaries should now be out of sync.
+# The select should print message to the error log
+SELECT * FROM t1;
+# MySQL have made a change (http://lists.mysql.com/commits/75268) that no
+# longer results in the two data dictionaries being out of sync. If they
+# revert their changes then this check for ER_AUTOINC_READ_FAILED will need
+# to be enabled.
+-- error ER_AUTOINC_READ_FAILED,1467
+INSERT INTO t1 VALUES(null);
+ALTER TABLE t1 AUTO_INCREMENT = 3;
+SHOW CREATE TABLE t1;
+INSERT INTO t1 VALUES(null);
+SELECT * FROM t1;
+DROP TABLE t1;
+
+# If the user has specified negative values for an AUTOINC column then
+# InnoDB should ignore those values when setting the table's max value.
+SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
+SHOW VARIABLES LIKE "%auto_inc%";
+# TINYINT
+CREATE TABLE t1 (c1 TINYINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-127, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+
+CREATE TABLE t1 (c1 TINYINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-127, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+#
+# SMALLINT
+#
+CREATE TABLE t1 (c1 SMALLINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-32767, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+
+CREATE TABLE t1 (c1 SMALLINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-32757, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+#
+# MEDIUMINT
+#
+CREATE TABLE t1 (c1 MEDIUMINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-8388607, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+
+CREATE TABLE t1 (c1 MEDIUMINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-8388607, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+#
+# INT
+#
+CREATE TABLE t1 (c1 INT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-2147483647, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+
+CREATE TABLE t1 (c1 INT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-2147483647, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+#
+# BIGINT
+#
+CREATE TABLE t1 (c1 BIGINT PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-9223372036854775807, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+
+CREATE TABLE t1 (c1 BIGINT UNSIGNED PRIMARY KEY AUTO_INCREMENT, c2 VARCHAR(10)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES (1, NULL);
+INSERT INTO t1 VALUES (-1, 'innodb');
+INSERT INTO t1 VALUES (-9223372036854775807, 'innodb');
+INSERT INTO t1 VALUES (NULL, NULL);
+SHOW CREATE TABLE t1;
+SELECT * FROM t1;
+DROP TABLE t1;
+#
+# End negative number check
+
+##
+# 47125: auto_increment start value is ignored if an index is created
+# and engine=innodb
+#
+CREATE TABLE T1 (c1 INT AUTO_INCREMENT, c2 INT, PRIMARY KEY(c1)) AUTO_INCREMENT=10 ENGINE=InnoDB;
+CREATE INDEX i1 on T1(c2);
+SHOW CREATE TABLE T1;
+INSERT INTO T1 (c2) values (0);
+SELECT * FROM T1;
+DROP TABLE T1;

=== modified file 'mysql-test/t/innodb_bug39438.test'
--- a/mysql-test/t/innodb_bug39438.test	2008-12-14 20:31:13 +0000
+++ b/mysql-test/t/innodb_bug39438.test	2009-11-03 08:46:04 +0000
@@ -9,6 +9,10 @@
 
 -- source include/have_innodb.inc
 
+--disable_query_log
+call mtr.add_suppression("InnoDB: Error: table 'test/bug39438'");
+--enable_query_log
+
 SET storage_engine=InnoDB;
 
 # we care only that the following SQL commands do not crash the server

=== added file 'mysql-test/t/innodb_bug44369.test'
--- a/mysql-test/t/innodb_bug44369.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/innodb_bug44369.test	2009-11-02 14:59:44 +0000
@@ -0,0 +1,21 @@
+# This is the test for bug 44369. We should
+# block table creation with columns match
+# some innodb internal reserved key words,
+# both case sensitively and insensitely.
+
+--source include/have_innodb.inc
+
+# This create table operation should fail.
+--error ER_CANT_CREATE_TABLE
+create table bug44369 (DB_ROW_ID int) engine=innodb;
+
+# This create should fail as well
+--error ER_CANT_CREATE_TABLE
+create table bug44369 (db_row_id int) engine=innodb;
+
+show warnings;
+
+--error ER_CANT_CREATE_TABLE
+create table bug44369 (db_TRX_Id int) engine=innodb;
+
+show warnings;

=== added file 'mysql-test/t/innodb_bug46000.test'
--- a/mysql-test/t/innodb_bug46000.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/innodb_bug46000.test	2009-11-02 14:59:44 +0000
@@ -0,0 +1,34 @@
+# This is the test for bug 46000. We shall
+# block any index creation with the name of
+# "GEN_CLUST_INDEX", which is the reserved
+# name for innodb default primary index.
+
+--source include/have_innodb.inc
+
+# This 'create table' operation should fail because of
+# using the reserve name as its index name.
+--error ER_CANT_CREATE_TABLE
+create table bug46000(`id` int,key `GEN_CLUST_INDEX`(`id`))engine=innodb;
+
+# Mixed upper/lower case of the reserved key words
+--error ER_CANT_CREATE_TABLE
+create table bug46000(`id` int, key `GEN_clust_INDEX`(`id`))engine=innodb;
+
+show warnings;
+
+create table bug46000(id int) engine=innodb;
+
+# This 'create index' operation should fail.
+--replace_regex /'[^']*test.#sql-[0-9a-f_]*'/'#sql-temporary'/
+--error ER_CANT_CREATE_TABLE
+create index GEN_CLUST_INDEX on bug46000(id);
+
+--replace_regex /'[^']*test.#sql-[0-9a-f_]*'/'#sql-temporary'/
+show warnings;
+
+# This 'create index' operation should succeed, no
+# temp table left from last failed create index
+# operation.
+create index idx on bug46000(id);
+
+drop table bug46000;

=== added file 'mysql-test/t/innodb_bug47777.test'
--- a/mysql-test/t/innodb_bug47777.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/innodb_bug47777.test	2009-11-02 14:41:40 +0000
@@ -0,0 +1,24 @@
+# This is the test for bug 47777. GEOMETRY
+# data is treated as BLOB data in innodb.
+# Consequently, its key value generation/storing
+# should follow the process for the BLOB
+# datatype as well.
+
+--source include/have_innodb.inc
+
+create table bug47777(c2 linestring not null, primary key (c2(1))) engine=innodb;
+
+insert into bug47777 values (geomfromtext('linestring(1 2,3 4,5 6,7 8,9 10)'));
+
+# Verify correct row get inserted.
+select count(*) from bug47777 where c2 =geomfromtext('linestring(1 2,3 4,5 6,7 8,9 10)');
+
+# Update table bug47777 should be successful.
+update bug47777 set c2=GeomFromText('POINT(1 1)');
+
+# Verify the row get updated successfully. The original
+# c2 value should be changed to GeomFromText('POINT(1 1)').
+select count(*) from bug47777 where c2 =geomfromtext('linestring(1 2,3 4,5 6,7 8,9 10)');
+select count(*) from bug47777 where c2 = GeomFromText('POINT(1 1)');
+
+drop table bug47777;

=== renamed file 'mysql-test/t/bug40113-master.opt' => 'mysql-test/t/innodb_lock_wait_timeout_1-master.opt'
=== renamed file 'mysql-test/t/bug40113.test' => 'mysql-test/t/innodb_lock_wait_timeout_1.test'
--- a/mysql-test/t/bug40113.test	2009-07-13 15:11:16 +0000
+++ b/mysql-test/t/innodb_lock_wait_timeout_1.test	2009-11-03 17:45:52 +0000
@@ -43,4 +43,188 @@ DISCONNECT addconroot;
 
 DROP TABLE t2, t1;
 
---echo End of 5.0 tests
+--echo # End of 5.0 tests
+
+--echo #
+--echo # Bug#46539 Various crashes on INSERT IGNORE SELECT + SELECT
+--echo #           FOR UPDATE
+--echo #
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+create table t1 (a int primary key auto_increment,
+                 b int, index(b)) engine=innodb;
+insert into t1 (b) values (1), (2), (3), (4), (5), (6), (7), (8), (9), (10);
+set autocommit=0;
+begin;
+select * from t1 where b=5 for update;
+connect (con1, localhost, root,,);
+connection con1;
+--error ER_LOCK_WAIT_TIMEOUT
+insert ignore into t1 (b) select a as b from t1;
+connection default;
+--echo # Cleanup
+--echo #
+disconnect con1;
+commit;
+set autocommit=default;
+drop table t1;
+
+--echo #
+--echo # Bug#41756 Strange error messages about locks from InnoDB
+--echo #
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+--echo # In the default transaction isolation mode, and/or with
+--echo # innodb_locks_unsafe_for_binlog=OFF, handler::unlock_row()
+--echo # in InnoDB does nothing.
+--echo # Thus in order to reproduce the condition that led to the
+--echo # warning, one needs to relax isolation by either
+--echo # setting a weaker tx_isolation value, or by turning on
+--echo # the unsafe replication switch.
+--echo # For testing purposes, choose to tweak the isolation level,
+--echo # since it's settable at runtime, unlike
+--echo # innodb_locks_unsafe_for_binlog, which is
+--echo # only a command-line switch.
+--echo #
+set @@session.tx_isolation="read-committed";
+
+--echo # Prepare data. We need a table with a unique index,
+--echo # for join_read_key to be used. The other column
+--echo # allows to control what passes WHERE clause filter.
+create table t1 (a int primary key, b int) engine=innodb;
+--echo # Let's make sure t1 has sufficient amount of rows
+--echo # to exclude JT_ALL access method when reading it,
+--echo # i.e. make sure that JT_EQ_REF(a) is always preferred.
+insert into t1 values (1,1), (2,null), (3,1), (4,1),
+                      (5,1), (6,1), (7,1), (8,1), (9,1), (10,1),
+                      (11,1), (12,1), (13,1), (14,1), (15,1),
+                      (16,1), (17,1), (18,1), (19,1), (20,1);
+--echo #
+--echo # Demonstrate that for the SELECT statement
+--echo # used later in the test JT_EQ_REF access method is used.
+--echo #
+--vertical_results
+explain
+select 1 from t1 natural join (select 2 as a, 1 as b union all
+                               select 2 as a, 2 as b) as t2 for update;
+--horizontal_results
+--echo #
+--echo # Demonstrate that the reported SELECT statement
+--echo # no longer produces warnings.
+--echo #
+select 1 from t1 natural join (select 2 as a, 1 as b union all
+                               select 2 as a, 2 as b) as t2 for update;
+commit;
+--echo # 
+--echo # Demonstrate that due to lack of inter-sweep "reset" function,
+--echo # we keep some non-matching records locked, even though we know
+--echo # we could unlock them.
+--echo # To do that, show that if there is only one distinct value
+--echo # for a in t2 (a=2), we will keep record (2,null) in t1 locked.
+--echo # But if we add another value for "a" to t2, say 6,
+--echo # join_read_key cache will be pruned at least once, 
+--echo # and thus record (2, null) in t1 will get unlocked.
+--echo #
+begin;
+select 1 from t1 natural join (select 2 as a, 1 as b union all
+                               select 2 as a, 2 as b) as t2 for update;
+connect (con1,localhost,root,,);
+--echo #
+--echo # Switching to connection con1
+connection con1;
+--echo # We should be able to delete all records from t1 except (2, null),
+--echo # since they were not locked.
+begin;
+--echo # Delete in series of 3 records so that full scan
+--echo # is not used and we're not blocked on record (2,null)
+delete from t1 where a in (1,3,4);
+delete from t1 where a in (5,6,7);
+delete from t1 where a in (8,9,10);
+delete from t1 where a in (11,12,13);
+delete from t1 where a in (14,15,16);
+delete from t1 where a in (17,18);
+delete from t1 where a in (19,20);
+--echo # 
+--echo # Record (2, null) is locked. This is actually unnecessary, 
+--echo # because the previous select returned no rows. 
+--echo # Just demonstrate the effect.
+--echo #
+--error ER_LOCK_WAIT_TIMEOUT
+delete from t1;
+rollback;
+--echo #
+--echo # Switching to connection default
+connection default;
+--echo #
+--echo # Show that the original contents of t1 is intact:
+select * from t1;
+commit;
+--echo #
+--echo # Have a one more record in t2 to show that 
+--echo # if join_read_key cache is purned, the current
+--echo # row under the cursor is unlocked (provided, this row didn't 
+--echo # match the partial WHERE clause, of course).
+--echo # Sic: the result of this test dependent on the order of retrieval
+--echo # of records --echo # from the derived table, if !
+--echo # We use DELETE to disable the JOIN CACHE. This DELETE modifies no
+--echo # records. It also should leave no InnoDB row locks.
+--echo #
+begin;
+delete t1.* from t1 natural join (select 2 as a, 2 as b union all
+                                  select 0 as a, 0 as b) as t2;
+--echo # Demonstrate that nothing was deleted form t1
+select * from t1;
+--echo #
+--echo # Switching to connection con1
+connection con1;
+begin;
+--echo # Since there is another distinct record in the derived table
+--echo # the previous matching record in t1 -- (2,null) -- was unlocked.
+delete from t1;
+--echo # We will need the contents of the table again.
+rollback;
+select * from t1;
+commit;
+--echo #
+--echo # Switching to connection default
+connection default;
+rollback;
+begin;
+--echo #
+--echo # Before this patch, we could wrongly unlock a record
+--echo # that was cached and later used in a join. Demonstrate that
+--echo # this is no longer the case.
+--echo # Sic: this test is also order-dependent (i.e. the
+--echo # the bug would show up only if the first record in the union
+--echo # is retreived and processed first.
+--echo #
+--echo # Verify that JT_EQ_REF is used.
+--vertical_results
+explain
+select 1 from t1 natural join (select 3 as a, 2 as b union all
+                               select 3 as a, 1 as b) as t2 for update;
+--horizontal_results
+--echo # Lock the record.
+select 1 from t1 natural join (select 3 as a, 2 as b union all
+                               select 3 as a, 1 as b) as t2 for update;
+--echo # Switching to connection con1
+connection con1;
+--echo #
+--echo # We should not be able to delete record (3,1) from t1,
+--echo # (previously it was possible).
+--echo #
+--error ER_LOCK_WAIT_TIMEOUT
+delete from t1 where a=3;
+--echo # Switching to connection default
+connection default;
+commit;
+
+disconnect con1;
+set @@session.tx_isolation=default;
+drop table t1;
+
+--echo #
+--echo # End of 5.1 tests
+--echo #

=== modified file 'mysql-test/t/innodb_mysql.test'
--- a/mysql-test/t/innodb_mysql.test	2009-09-07 20:50:10 +0000
+++ b/mysql-test/t/innodb_mysql.test	2009-11-10 15:15:12 +0000
@@ -463,4 +463,33 @@ EXPLAIN SELECT * FROM t1 FORCE INDEX(PRI
 
 DROP TABLE t1;
 
+--echo #
+--echo # Bug #47963: Wrong results when index is used
+--echo #
+CREATE TABLE t1(
+  a VARCHAR(5) NOT NULL, 
+  b VARCHAR(5) NOT NULL,
+  c DATETIME NOT NULL,
+  KEY (c) 
+) ENGINE=InnoDB;
+INSERT INTO t1 VALUES('TEST', 'TEST', '2009-10-09 00:00:00');
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00' AND c <= '2009-10-09 00:00:00';
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00.0' AND c <= '2009-10-09 00:00:00.0';
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00.0' AND c <= '2009-10-09 00:00:00';
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00' AND c <= '2009-10-09 00:00:00.0';
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00.000' AND c <= '2009-10-09 00:00:00.000';
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00.00' AND c <= '2009-10-09 00:00:00.001';
+SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00.001' AND c <= '2009-10-09 00:00:00.00';
+EXPLAIN SELECT * FROM t1 WHERE a = 'TEST' AND 
+  c >= '2009-10-09 00:00:00.001' AND c <= '2009-10-09 00:00:00.00';
+DROP TABLE t1;
+
+
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/insert_select.test'
--- a/mysql-test/t/insert_select.test	2009-09-07 20:50:10 +0000
+++ b/mysql-test/t/insert_select.test	2009-11-10 15:15:12 +0000
@@ -392,4 +392,32 @@ insert into t1 values(1),(2),(3);
 create table t2 (key(f1)) engine=myisam select sql_buffer_result f1 from t1;
 check table t2 extended;
 drop table t1,t2;
+
 --echo End of 5.0 tests
+
+# The following is not relevant for MariaDB as we are using Maria for
+# tmp tables.
+
+--echo ##################################################################
+--echo #
+--echo # Bug #46075: Assertion failed: 0, file .\protocol.cc, line 416
+--echo #
+
+CREATE TABLE t1(a INT);
+# To force MyISAM temp. table in the following INSERT ... SELECT.
+SET max_heap_table_size = 16384;
+# To overflow the temp. table.
+SET @old_myisam_data_pointer_size = @@myisam_data_pointer_size;
+SET GLOBAL myisam_data_pointer_size = 2;
+
+INSERT INTO t1 VALUES (1), (2), (3), (4), (5);
+
+call mtr.add_suppression("mysqld: The table '.*#sql.*' is full");
+--error 0,ER_RECORD_FILE_FULL,ER_RECORD_FILE_FULL
+INSERT IGNORE INTO t1 SELECT t1.a FROM t1,t1 t2,t1 t3,t1 t4,t1 t5,t1 t6,t1 t7;
+
+# Cleanup
+SET GLOBAL myisam_data_pointer_size = @old_myisam_data_pointer_size;
+DROP TABLE t1;
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/join.test'
--- a/mysql-test/t/join.test	2008-10-06 12:37:52 +0000
+++ b/mysql-test/t/join.test	2009-10-30 08:03:18 +0000
@@ -729,4 +729,78 @@ SELECT * FROM t1 JOIN t2 ON b=c ORDER BY
 SELECT * FROM t1 JOIN t2 ON a=c ORDER BY a;
 
 DROP TABLE IF EXISTS t1,t2;
+
+
+--echo #
+--echo # Bug #42116: Mysql crash on specific query
+--echo #
+CREATE TABLE t1 (a INT);
+CREATE TABLE t2 (a INT);
+CREATE TABLE t3 (a INT, INDEX (a));
+CREATE TABLE t4 (a INT);
+CREATE TABLE t5 (a INT);
+CREATE TABLE t6 (a INT);
+
+INSERT INTO t1 VALUES (1), (1), (1);
+
+INSERT INTO t2 VALUES
+(2), (2), (2), (2), (2), (2), (2), (2), (2), (2);
+
+INSERT INTO t3 VALUES
+(3), (3), (3), (3), (3), (3), (3), (3), (3), (3);
+
+EXPLAIN
+SELECT * 
+FROM 
+  t1 JOIN t2 ON t1.a = t2.a 
+  LEFT JOIN 
+  (
+   (
+    t3 LEFT JOIN t4 ON t3.a = t4.a
+   ) 
+   LEFT JOIN 
+   (
+     t5 LEFT JOIN t6 ON t5.a = t6.a
+   ) 
+   ON t4.a = t5.a
+  ) 
+  ON t1.a = t3.a;
+
+SELECT * 
+FROM 
+  t1 JOIN t2 ON t1.a = t2.a 
+  LEFT JOIN 
+  (
+   (
+    t3 LEFT JOIN t4 ON t3.a = t4.a
+   ) 
+   LEFT JOIN 
+   (
+     t5 LEFT JOIN t6 ON t5.a = t6.a
+   ) 
+   ON t4.a = t5.a
+  ) 
+  ON t1.a = t3.a;
+
+DROP TABLE t1,t2,t3,t4,t5,t6;
+
 --echo End of 5.0 tests.
+
+
+#
+# Bug#47150 Assertion in Field_long::val_int() on MERGE + TRIGGER + multi-table UPDATE
+#
+CREATE TABLE t1 (f1 int);
+
+CREATE TABLE t2 (f1 int);
+INSERT INTO t2  VALUES (1);
+CREATE VIEW v1 AS SELECT * FROM t2;
+
+PREPARE stmt FROM 'UPDATE t2 AS A NATURAL JOIN v1 B SET B.f1 = 1';
+EXECUTE stmt;
+EXECUTE stmt;
+
+DEALLOCATE PREPARE stmt;
+
+DROP VIEW v1;
+DROP TABLE t1, t2;

=== modified file 'mysql-test/t/kill.test'
--- a/mysql-test/t/kill.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/kill.test	2009-11-10 15:15:12 +0000
@@ -99,7 +99,7 @@ select ((@id := kill_id) - kill_id) from
 kill @id;
 
 connection conn1;
--- error 1053,2013
+-- error 1317,2013
 reap;
 
 connection default;

=== added file 'mysql-test/t/locale.test'
--- a/mysql-test/t/locale.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/locale.test	2009-10-19 08:44:44 +0000
@@ -0,0 +1,18 @@
+--disable_warnings
+DROP TABLE IF EXISTS t1;
+--enable_warnings
+
+--echo Start of 5.4 tests
+--echo #
+--echo # Bug#43207 wrong LC_TIME names for romanian locale
+--echo #
+SET NAMES utf8;
+SET lc_time_names=ro_RO;
+SELECT DATE_FORMAT('2001-01-01', '%w %a %W');
+SELECT DATE_FORMAT('2001-01-02', '%w %a %W');
+SELECT DATE_FORMAT('2001-01-03', '%w %a %W');
+SELECT DATE_FORMAT('2001-01-04', '%w %a %W');
+SELECT DATE_FORMAT('2001-01-05', '%w %a %W');
+SELECT DATE_FORMAT('2001-01-06', '%w %a %W');
+SELECT DATE_FORMAT('2001-01-07', '%w %a %W');
+--echo End of 5.4 tests

=== modified file 'mysql-test/t/lowercase_fs_off.test'
--- a/mysql-test/t/lowercase_fs_off.test	2009-05-15 10:15:56 +0000
+++ b/mysql-test/t/lowercase_fs_off.test	2009-10-27 10:09:36 +0000
@@ -29,3 +29,65 @@ disconnect master;
 connection default;
 
 # End of 4.1 tests
+
+#
+# Bug#41049 does syntax "grant" case insensitive?
+#
+CREATE DATABASE d1;
+USE d1;
+CREATE TABLE T1(f1 INT);
+CREATE TABLE t1(f1 INT);
+GRANT SELECT ON T1 to user_1@localhost;
+
+connect (con1,localhost,user_1,,d1);
+--error ER_TABLEACCESS_DENIED_ERROR
+select * from t1;
+select * from T1;
+connection default;
+GRANT SELECT ON t1 to user_1@localhost;
+connection con1;
+select * from information_schema.table_privileges;
+connection default;
+disconnect con1;
+
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM user_1@localhost;
+DROP USER user_1@localhost;
+DROP DATABASE d1;
+USE test;
+
+CREATE DATABASE db1;
+USE db1;
+CREATE PROCEDURE p1() BEGIN END;
+CREATE FUNCTION f1(i INT) RETURNS INT RETURN i+1;
+
+GRANT USAGE ON db1.* to user_1@localhost;
+GRANT EXECUTE ON PROCEDURE db1.P1 to user_1@localhost;
+GRANT EXECUTE ON FUNCTION db1.f1 to user_1@localhost;
+GRANT UPDATE ON db1.* to USER_1@localhost;
+
+connect (con1,localhost,user_1,,db1);
+call p1();
+call P1();
+select f1(1);
+connect (con2,localhost,USER_1,,db1);
+--error ER_PROCACCESS_DENIED_ERROR
+call p1();
+--error ER_PROCACCESS_DENIED_ERROR
+call P1();
+--error ER_PROCACCESS_DENIED_ERROR
+select f1(1);
+
+connection default;
+disconnect con1;
+disconnect con2;
+
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM user_1@localhost;
+REVOKE ALL PRIVILEGES, GRANT OPTION FROM USER_1@localhost;
+DROP FUNCTION f1;
+DROP PROCEDURE p1;
+DROP USER user_1@localhost;
+DROP USER USER_1@localhost;
+DROP DATABASE db1;
+use test;
+
+# End of 5.0 tests

=== added file 'mysql-test/t/lowercase_mixed_tmpdir_innodb-master.opt'
--- a/mysql-test/t/lowercase_mixed_tmpdir_innodb-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/lowercase_mixed_tmpdir_innodb-master.opt	2009-09-09 09:38:50 +0000
@@ -0,0 +1,2 @@
+--lower-case-table-names=2
+--tmpdir=$MYSQLTEST_VARDIR/tmp/MixedCase

=== added file 'mysql-test/t/lowercase_mixed_tmpdir_innodb-master.sh'
--- a/mysql-test/t/lowercase_mixed_tmpdir_innodb-master.sh	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/lowercase_mixed_tmpdir_innodb-master.sh	2009-09-09 09:38:50 +0000
@@ -0,0 +1,6 @@
+# This test requires a non-lowercase tmpdir directory on a case-sensitive
+# filesystem.
+
+d="$MYSQLTEST_VARDIR/tmp/MixedCase"
+test -d "$d" || mkdir "$d"
+rm -f "$d"/*

=== added file 'mysql-test/t/lowercase_mixed_tmpdir_innodb.test'
--- a/mysql-test/t/lowercase_mixed_tmpdir_innodb.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/lowercase_mixed_tmpdir_innodb.test	2009-09-09 09:38:50 +0000
@@ -0,0 +1,12 @@
+--source include/have_lowercase2.inc
+--source include/have_innodb.inc
+
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+
+create table t1 (id int) engine=InnoDB;
+insert into t1 values (1);
+create temporary table t2 engine=InnoDB select * from t1;
+drop temporary table t2;
+drop table t1;

=== modified file 'mysql-test/t/lowercase_table3.test'
--- a/mysql-test/t/lowercase_table3.test	2009-02-13 21:12:59 +0000
+++ b/mysql-test/t/lowercase_table3.test	2009-08-28 14:13:27 +0000
@@ -9,7 +9,7 @@
 --source include/have_case_insensitive_file_system.inc
 --source include/not_windows.inc
 
-call mtr.add_suppression("Cannot find or open table test/BUG29839 from .*");
+call mtr.add_suppression("Cannot find or open table test/BUG29839 from");
 
 --disable_warnings
 DROP TABLE IF EXISTS t1,T1;

=== modified file 'mysql-test/t/myisam-system.test'
--- a/mysql-test/t/myisam-system.test	2007-12-12 17:19:24 +0000
+++ b/mysql-test/t/myisam-system.test	2009-09-17 11:33:23 +0000
@@ -12,11 +12,11 @@ let $MYSQLD_DATADIR= `select @@datadir`;
 drop table if exists t1;
 create table t1 (a int) engine=myisam;
 --remove_file $MYSQLD_DATADIR/test/t1.MYI
---error 1051,6
+--error ER_BAD_TABLE_ERROR,6
 drop table t1;
 create table t1 (a int) engine=myisam;
 --remove_file $MYSQLD_DATADIR/test/t1.MYD
---error 1105,6,29
+--error ER_BAD_TABLE_ERROR,6,29
 drop table t1;
---error 1051
+--error ER_BAD_TABLE_ERROR
 drop table t1;

=== modified file 'mysql-test/t/myisam.test'
--- a/mysql-test/t/myisam.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/myisam.test	2009-11-10 15:15:12 +0000
@@ -1549,4 +1549,50 @@ SELECT h+0, d + 0, e, g + 0 FROM t1;
 
 DROP TABLE t1;
 
+--echo #
+--echo # Test of BUG#35570 CHECKSUM TABLE unreliable if LINESTRING field
+--echo # (same content / differen checksum)
+--echo #
+
+CREATE TABLE t1 (line LINESTRING NOT NULL) engine=myisam;
+INSERT INTO t1 VALUES (GeomFromText("POINT(0 0)"));
+checksum table t1;
+CREATE TABLE t2 (line LINESTRING NOT NULL) engine=myisam;
+INSERT INTO t2 VALUES (GeomFromText("POINT(0 0)"));
+checksum table t2;
+CREATE TABLE t3 select * from t1;
+checksum table t3;
+drop table t1,t2,t3;
+
+
+#
+# BUG#47073 - valgrind errs, corruption,failed repair of partition,
+#             low myisam_sort_buffer_size
+#
+CREATE TABLE t1(a INT, b CHAR(10), KEY(a), KEY(b));
+INSERT INTO t1 VALUES(1,'0'),(2,'0'),(3,'0'),(4,'0'),(5,'0'),
+                     (6,'0'),(7,'0');
+INSERT INTO t1 SELECT a+10,b FROM t1;
+INSERT INTO t1 SELECT a+20,b FROM t1;
+INSERT INTO t1 SELECT a+40,b FROM t1;
+INSERT INTO t1 SELECT a+80,b FROM t1;
+INSERT INTO t1 SELECT a+160,b FROM t1;
+INSERT INTO t1 SELECT a+320,b FROM t1;
+INSERT INTO t1 SELECT a+640,b FROM t1;
+INSERT INTO t1 SELECT a+1280,b FROM t1;
+INSERT INTO t1 SELECT a+2560,b FROM t1;
+INSERT INTO t1 SELECT a+5120,b FROM t1;
+SET myisam_sort_buffer_size=4;
+REPAIR TABLE t1;
+
+SET myisam_repair_threads=2;
+# May report different values depending on threads activity.
+--disable_result_log
+REPAIR TABLE t1;
+--enable_result_log
+SET myisam_repair_threads=@@global.myisam_repair_threads;
+SET myisam_sort_buffer_size=@@global.myisam_sort_buffer_size;
+CHECK TABLE t1;
+DROP TABLE t1;
+
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/myisam_crash_before_flush_keys.test'
--- a/mysql-test/t/myisam_crash_before_flush_keys.test	2009-04-06 07:01:17 +0000
+++ b/mysql-test/t/myisam_crash_before_flush_keys.test	2009-10-14 11:26:16 +0000
@@ -26,12 +26,6 @@ SET SESSION debug="d,crash_before_flush_
 --error 2013
 FLUSH TABLE t1;
 
---echo # Run MYISAMCHK tool to check the table t1 and repair
---replace_result $MYISAMCHK MYISAMCHK  $MYSQLD_DATADIR  MYSQLD_DATADIR
---error 255
---exec $MYISAMCHK -cs $MYSQLD_DATADIR/test/t1 2>&1
---exec $MYISAMCHK -rs $MYSQLD_DATADIR/test/t1
-
 --echo # Write file to make mysql-test-run.pl start the server 
 --exec echo "restart" > $MYSQLTEST_VARDIR/tmp/mysqld.1.expect
 
@@ -42,8 +36,6 @@ FLUSH TABLE t1;
 --echo # it to be back online again
 --source include/wait_until_connected_again.inc
 
-SHOW CREATE TABLE t1;
-
-SELECT * FROM t1 FORCE INDEX (PRIMARY);
-
+# Must report that the table wasn't closed properly
+CHECK TABLE t1;
 DROP TABLE t1;

=== modified file 'mysql-test/t/mysqlbinlog.test'
--- a/mysql-test/t/mysqlbinlog.test	2009-05-08 17:24:15 +0000
+++ b/mysql-test/t/mysqlbinlog.test	2009-09-30 02:31:25 +0000
@@ -71,7 +71,8 @@ select "--- --position --" as "";
 --enable_query_log
 --replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
 --replace_regex /SQL_LOAD_MB-[0-9]-[0-9]/SQL_LOAD_MB-#-#/
---exec $MYSQL_BINLOG --short-form --local-load=$MYSQLTEST_VARDIR/tmp/ --position=239 $MYSQLD_DATADIR/master-bin.000002
+--exec $MYSQL_BINLOG --short-form --local-load=$MYSQLTEST_VARDIR/tmp/ --position=330 $MYSQLD_DATADIR/master-bin.000002
+
 
 # These are tests for remote binlog.
 # They should return the same as previous test.
@@ -107,7 +108,7 @@ select "--- --position --" as "";
 --enable_query_log
 --replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
 --replace_regex /SQL_LOAD_MB-[0-9]-[0-9]/SQL_LOAD_MB-#-#/
---exec $MYSQL_BINLOG --short-form --local-load=$MYSQLTEST_VARDIR/tmp/ --read-from-remote-server --position=239 --user=root --host=127.0.0.1 --port=$MASTER_MYPORT master-bin.000002
+--exec $MYSQL_BINLOG --short-form --local-load=$MYSQLTEST_VARDIR/tmp/ --read-from-remote-server --position=330 --user=root --host=127.0.0.1 --port=$MASTER_MYPORT master-bin.000002
 
 # Bug#7853 mysqlbinlog does not accept input from stdin
 --disable_query_log
@@ -377,6 +378,68 @@ FLUSH LOGS;
 # We do not need the results, just make sure that mysqlbinlog does not crash
 --exec $MYSQL_BINLOG --hexdump --read-from-remote-server --user=root --host=127.0.0.1 --port=$MASTER_MYPORT  master-bin.000001 >/dev/null
 
+#
+# #46998
+# This test verifies if the 'BEGIN', 'COMMIT' and 'ROLLBACK' are output 
+# in regardless of database filtering
+#
+
+RESET MASTER;
+FLUSH LOGS;
+
+# The following three test cases were wrtten into binlog_transaction.000001
+# Test case1: Test if the 'BEGIN' and 'COMMIT' are output for the 'test' database 
+# in transaction1 base on innodb engine tables
+# use test;
+# create table t1(a int) engine= innodb;
+# use mysql;
+# create table t2(a int) engine= innodb;
+# Transaction1 begin
+# begin;
+# use test;
+# insert into t1 (a) values (1);
+# use mysql;
+# insert into t2 (a) values (1);
+# commit;
+# Transaction1 end
+
+# Test case2: Test if the 'BEGIN' and 'ROLLBACK' are output for the 'test' database 
+# in transaction2 base on innodb and myisam engine tables
+# use test;
+# create table t3(a int) engine= innodb;
+# use mysql;
+# create table t4(a int) engine= myisam;
+# Transaction2 begin
+# begin;
+# use test;
+# insert into t3 (a) values (2);
+# use mysql;
+# insert into t4 (a) values (2);
+# rollback;
+# Transaction2 end
+
+# Test case3: Test if the 'BEGIN' and 'COMMIT' are output for the 'test' database 
+# in transaction3 base on NDB engine tables
+# use test;
+# create table t5(a int) engine= NDB;
+# use mysql;
+# create table t6(a int) engine= NDB;
+# Transaction3 begin
+# begin;
+# use test;
+# insert into t5 (a) values (3);
+# use mysql;
+# insert into t6 (a) values (3);
+# commit;
+# Transaction3 end
+
+--echo #
+--echo # Test if the 'BEGIN', 'ROLLBACK' and 'COMMIT' are output if the database specified is exist
+--exec $MYSQL_BINLOG --database=test --short-form $MYSQLTEST_VARDIR/std_data/binlog_transaction.000001
+--echo #
+--echo # Test if the 'BEGIN', 'ROLLBACK' and 'COMMIT' are output if the database specified is not exist
+--exec $MYSQL_BINLOG --database=not_exist --short-form $MYSQLTEST_VARDIR/std_data/binlog_transaction.000001
+
 --echo End of 5.0 tests
 
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/mysqltest.test'
--- a/mysql-test/t/mysqltest.test	2009-05-27 20:54:40 +0000
+++ b/mysql-test/t/mysqltest.test	2009-10-08 09:30:03 +0000
@@ -853,16 +853,21 @@ while ($outer)
   eval SELECT '$outer = outer loop variable after dec' AS "";
 }
 
+# Test source in an if in a while which is false on 1st iteration
+# Also test --error in same context
 let $outer= 2; # Number of outer loops
+let $ifval= 0; # false 1st time
 while ($outer)
 {
-  eval SELECT '$outer = outer loop variable after while' AS "";
+  echo outer=$outer ifval=$ifval;
 
-  echo here is the sourced script;
-
-  eval SELECT '$outer = outer loop variable before dec' AS "";
+  if ($ifval) {
+    --source $MYSQLTEST_VARDIR/tmp/sourced.inc
+    --error ER_NO_SUCH_TABLE
+    SELECT * from nowhere;
+  }
   dec $outer;
-  eval SELECT '$outer = outer loop variable after dec' AS "";
+  inc $ifval;
 }
 
 
@@ -1663,6 +1668,20 @@ EOF
 
 remove_file $MYSQLTEST_VARDIR/tmp/test_file1.tmp;
 
+# Test append_file within while
+let $outer= 2; # Number of outer loops
+while ($outer)
+{
+  append_file $MYSQLTEST_VARDIR/tmp/app_while.tmp;
+These lines should be repeated,
+if things work as expected
+EOF
+  dec $outer;
+}
+
+cat_file $MYSQLTEST_VARDIR/tmp/app_while.tmp;
+remove_file $MYSQLTEST_VARDIR/tmp/app_while.tmp;
+
 # ----------------------------------------------------------------------------
 # test for cat_file
 # ----------------------------------------------------------------------------
@@ -1710,10 +1729,6 @@ EOF
 --diff_files $MYSQLTEST_VARDIR/tmp/diff1.tmp $MYSQLTEST_VARDIR/tmp/diff2.tmp
 --diff_files $MYSQLTEST_VARDIR/tmp/diff2.tmp $MYSQLTEST_VARDIR/tmp/diff1.tmp
 
-# Write the below commands to a intermediary file and execute them with
-# mysqltest in --exec, since the output will vary depending on what "diff"
-# is available it is sent to /dev/null
---write_file $MYSQLTEST_VARDIR/tmp/diff.test
 # Compare files that differ in size
 --error 2
 --diff_files $MYSQLTEST_VARDIR/tmp/diff1.tmp $MYSQLTEST_VARDIR/tmp/diff3.tmp
@@ -1725,13 +1740,6 @@ EOF
 --diff_files $MYSQLTEST_VARDIR/tmp/diff1.tmp $MYSQLTEST_VARDIR/tmp/diff4.tmp
 --error 1
 --diff_files $MYSQLTEST_VARDIR/tmp/diff4.tmp $MYSQLTEST_VARDIR/tmp/diff1.tmp
-exit;
-EOF
-
-# Execute the above diffs, and send their output to /dev/null - only
-# interesting to see that it returns correct error codes
---exec $MYSQL_TEST < $MYSQLTEST_VARDIR/tmp/diff.test > /dev/null 2>&1
-
 
 # Compare equal files, again...
 --diff_files $MYSQLTEST_VARDIR/tmp/diff1.tmp $MYSQLTEST_VARDIR/tmp/diff2.tmp
@@ -1740,7 +1748,6 @@ EOF
 --remove_file $MYSQLTEST_VARDIR/tmp/diff2.tmp
 --remove_file $MYSQLTEST_VARDIR/tmp/diff3.tmp
 --remove_file $MYSQLTEST_VARDIR/tmp/diff4.tmp
---remove_file $MYSQLTEST_VARDIR/tmp/diff.test
 
 
 # ----------------------------------------------------------------------------

=== modified file 'mysql-test/t/named_pipe.test'
--- a/mysql-test/t/named_pipe.test	2007-09-24 10:42:44 +0000
+++ b/mysql-test/t/named_pipe.test	2009-11-03 00:19:37 +0000
@@ -9,6 +9,11 @@ if (`SELECT '$nmp' != 'ON'`){
   skip No named pipe support;
 }
 
+# Connect using named pipe for testing
+connect(pipe_con,localhost,root,,,,,PIPE);
+
 # Source select test case
 -- source include/common-tests.inc
 
+connection default;
+disconnect pipe_con;

=== modified file 'mysql-test/t/not_partition.test'
--- a/mysql-test/t/not_partition.test	2009-01-08 14:16:44 +0000
+++ b/mysql-test/t/not_partition.test	2009-09-02 21:29:11 +0000
@@ -15,7 +15,7 @@ let $MYSQLD_DATADIR= `SELECT @@datadir`;
 # Bug#39893: Crash if select on a partitioned table,
 #            when partitioning is disabled
 FLUSH TABLES;
---copy_file $MYSQLTEST_VARDIR/std_data_ln/parts/t1.frm $MYSQLD_DATADIR/test/t1.frm
+--copy_file $MYSQLTEST_VARDIR/std_data/parts/t1.frm $MYSQLD_DATADIR/test/t1.frm
 SELECT * FROM t1;
 TRUNCATE TABLE t1;
 ANALYZE TABLE t1;

=== modified file 'mysql-test/t/olap.test'
--- a/mysql-test/t/olap.test	2007-11-21 16:53:44 +0000
+++ b/mysql-test/t/olap.test	2009-10-30 15:54:53 +0000
@@ -375,4 +375,19 @@ INSERT INTO t1 VALUES(0);
 SELECT 1 FROM t1 GROUP BY (DATE(NULL)) WITH ROLLUP;
 DROP TABLE t1;
 
+--echo #
+--echo # Bug #48131: crash group by with rollup, distinct,
+--echo #             filesort, with temporary tables
+--echo #
+
+CREATE TABLE t1 (a INT NOT NULL PRIMARY KEY);
+INSERT INTO t1 VALUES (1), (2);
+CREATE TABLE t2 (b INT);
+INSERT INTO t2 VALUES (100);
+
+SELECT a, b FROM t1, t2 GROUP BY a, b WITH ROLLUP;
+SELECT DISTINCT b FROM t1, t2 GROUP BY a, b WITH ROLLUP;
+
+DROP TABLE t1, t2;
+
 --echo End of 5.0 tests

=== modified file 'mysql-test/t/order_by.test'
--- a/mysql-test/t/order_by.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/order_by.test	2009-11-10 15:15:12 +0000
@@ -1404,3 +1404,35 @@ SELECT DISTINCT a FROM t1 WHERE b = 1 OR
 SELECT DISTINCT a FROM t1 WHERE b = 1 ORDER BY c DESC LIMIT 0, 9;
 
 DROP TABLE t1;
+
+--echo #
+--echo # Bug #43029: FORCE INDEX FOR ORDER BY is ignored when join buffering 
+--echo #   is used
+--echo #
+
+CREATE TABLE t1 (a INT, b INT, KEY (a));
+
+INSERT INTO t1 VALUES (0, NULL), (1, NULL), (2, NULL), (3, NULL);
+INSERT INTO t1 SELECT a+4, b FROM t1;
+INSERT INTO t1 SELECT a+8, b FROM t1;
+
+CREATE TABLE t2 (a INT, b INT);
+
+INSERT INTO t2 VALUES (0,NULL), (1,NULL), (2,NULL), (3,NULL), (4,NULL);
+INSERT INTO t2 SELECT a+4, b FROM t2;
+
+--echo # shouldn't have "using filesort"
+EXPLAIN 
+SELECT * FROM t1 FORCE INDEX FOR ORDER BY (a), t2 WHERE t1.a < 2 ORDER BY t1.a;
+
+--echo # should have "using filesort"
+EXPLAIN 
+SELECT * FROM t1 USE INDEX FOR ORDER BY (a), t2 WHERE t1.a < 2 ORDER BY t1.a;
+
+--echo # should have "using filesort"
+EXPLAIN 
+SELECT * FROM t1 FORCE INDEX FOR JOIN (a), t2 WHERE t1.a < 2 ORDER BY t1.a;
+
+DROP TABLE t1, t2;
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/partition.test'
--- a/mysql-test/t/partition.test	2009-11-06 17:22:32 +0000
+++ b/mysql-test/t/partition.test	2009-11-10 15:15:12 +0000
@@ -62,6 +62,19 @@ SHOW CREATE TABLE t1;
 DROP TABLE t1;
 
 #
+# Bug#44059: rec_per_key on empty partition gives weird optimiser results
+#
+create table t1 (a int, b int, key(a))
+partition by list (a)
+( partition p0 values in (1),
+  partition p1 values in (2));
+insert into t1 values (1,1),(2,1),(2,2),(2,3);
+show indexes from t1;
+analyze table t1;
+show indexes from t1;
+drop table t1;
+
+#
 # Bug#36001: Partitions: spelling and using some error messages
 #
 --error ER_FOREIGN_KEY_ON_PARTITIONED

=== modified file 'mysql-test/t/partition_csv.test'
--- a/mysql-test/t/partition_csv.test	2009-07-31 23:39:26 +0000
+++ b/mysql-test/t/partition_csv.test	2009-09-03 06:38:06 +0000
@@ -10,6 +10,8 @@
 --source include/have_partition.inc
 --source include/have_csv.inc
 
+call mtr.add_suppression("Failed to write to mysql.general_log");
+
 #
 # Bug#19307: Partitions: csv delete failure
 #            = CSV engine crashes

=== modified file 'mysql-test/t/partition_innodb.test'
--- a/mysql-test/t/partition_innodb.test	2009-06-09 15:08:46 +0000
+++ b/mysql-test/t/partition_innodb.test	2009-11-10 15:15:12 +0000
@@ -6,6 +6,23 @@ drop table if exists t1;
 --enable_warnings
 
 #
+# Bug#47029: Crash when reorganize partition with subpartition
+#
+create table t1 (a int not null,
+                 b datetime not null,
+                 primary key (a,b))
+engine=innodb
+partition by range (to_days(b))
+subpartition by hash (a)
+subpartitions 2
+( partition p0 values less than (to_days('2009-01-01')),
+  partition p1 values less than (to_days('2009-02-01')),
+  partition p2 values less than (to_days('2009-03-01')),
+  partition p3 values less than maxvalue);
+alter table t1 reorganize partition p1,p2 into
+( partition p2 values less than (to_days('2009-03-01')));
+drop table t1;
+#
 # Bug#40595: Non-matching rows not released with READ-COMMITTED on tables
 #            with partitions
 CREATE TABLE t1 (id INT PRIMARY KEY, data INT) ENGINE = InnoDB 
@@ -270,3 +287,15 @@ PARTITION BY RANGE (int_column)
   (PARTITION p1 VALUES LESS THAN (5));
 show create table t1;
 drop table t1;
+
+#
+# BUG#46483 - drop table of partitioned table may leave extraneous file
+# Note: was only repeatable with InnoDB plugin
+#
+CREATE TABLE t1 (a INT) ENGINE=InnoDB
+  PARTITION BY list(a) (PARTITION p1 VALUES IN (1));
+CREATE INDEX i1 ON t1 (a);
+DROP TABLE t1;
+let $MYSQLD_DATADIR= `SELECT @@datadir`;
+# Before the fix it should show extra file like #sql-2405_2.par
+--list_files $MYSQLD_DATADIR/test/ *

=== added file 'mysql-test/t/partition_innodb_builtin.test'
--- a/mysql-test/t/partition_innodb_builtin.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/partition_innodb_builtin.test	2009-09-25 09:26:49 +0000
@@ -0,0 +1,67 @@
+--source include/have_partition.inc
+--source include/have_innodb.inc
+--source include/have_not_innodb_plugin.inc
+
+#
+# Bug#32430 - show engine innodb status causes errors
+#
+SET NAMES utf8;
+CREATE TABLE `t``\""e` (a INT, PRIMARY KEY (a))
+ENGINE=InnoDB
+PARTITION BY RANGE (a)
+SUBPARTITION BY HASH (a)
+(PARTITION `p0``\""e` VALUES LESS THAN (100)
+ (SUBPARTITION `sp0``\""e`,
+  SUBPARTITION `sp1``\""e`),
+ PARTITION `p1``\""e` VALUES LESS THAN (MAXVALUE)
+ (SUBPARTITION `sp2``\""e`,
+  SUBPARTITION `sp3``\""e`));
+INSERT INTO `t``\""e` VALUES (0), (2), (6), (10), (14), (18), (22);
+START TRANSACTION;
+--echo # con1
+connect(con1,localhost,root,,);
+SET NAMES utf8;
+START TRANSACTION;
+--echo # default connection
+connection default;
+UPDATE `t``\""e` SET a = 16 WHERE a = 0;
+--echo # con1
+connection con1;
+UPDATE `t``\""e` SET a = 8 WHERE a = 22;
+let $id_1= `SELECT CONNECTION_ID()`;
+SEND;
+UPDATE `t``\""e` SET a = 12 WHERE a = 0;
+--echo # default connection
+connection default;
+let $wait_timeout= 2;
+let $wait_condition= SELECT 1 FROM INFORMATION_SCHEMA.PROCESSLIST
+WHERE ID = $id_1 AND STATE = 'Searching rows for update';
+--source include/wait_condition.inc
+#--echo # tested wait condition $wait_condition_reps times
+--error ER_LOCK_DEADLOCK
+UPDATE `t``\""e` SET a = 4 WHERE a = 22;
+--echo # First table reported in 'SHOW ENGINE InnoDB STATUS'
+# RECORD LOCKS space id 0 page no 50 n bits 80 index `PRIMARY` in \
+# Database `test`, Table `t1`, Partition `p0`, Subpartition `sp0` \
+# trx id 0 775
+# NOTE: replace_regex is very slow on match copy/past '(.*)' regex's
+# on big texts, removing a lot of text before + after makes it much faster.
+#/.*in (.*) trx.*/\1/
+--replace_regex /.*RECORD LOCKS space id [0-9]* page no [0-9]* n bits [0-9]* // / trx id .*// /.*index .* in //
+SHOW ENGINE InnoDB STATUS;
+set @old_sql_mode = @@sql_mode;
+set sql_mode = 'ANSI_QUOTES';
+# INNODB_LOCKS only exists in innodb_plugin
+#SELECT * FROM INFORMATION_SCHEMA.INNODB_LOCKS;
+--replace_regex /.*RECORD LOCKS space id [0-9]* page no [0-9]* n bits [0-9]* // / trx id .*// /.*index .* in //
+SHOW ENGINE InnoDB STATUS;
+set @@sql_mode = @old_sql_mode;
+--echo # con1
+connection con1;
+REAP;
+ROLLBACK;
+disconnect con1;
+--echo # default connection
+connection default;
+DROP TABLE `t``\""e`;
+SET NAMES DEFAULT;

=== added file 'mysql-test/t/partition_innodb_plugin.test'
--- a/mysql-test/t/partition_innodb_plugin.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/partition_innodb_plugin.test	2009-09-25 09:26:49 +0000
@@ -0,0 +1,75 @@
+--source include/have_partition.inc
+--source include/have_innodb.inc
+--source suite/innodb/include/have_innodb_plugin.inc
+
+#
+# Bug#32430 - show engine innodb status causes errors
+#
+SET NAMES utf8;
+CREATE TABLE `t``\""e` (a INT, PRIMARY KEY (a))
+ENGINE=InnoDB
+PARTITION BY RANGE (a)
+SUBPARTITION BY HASH (a)
+(PARTITION `p0``\""e` VALUES LESS THAN (100)
+ (SUBPARTITION `sp0``\""e`,
+  SUBPARTITION `sp1``\""e`),
+ PARTITION `p1``\""e` VALUES LESS THAN (MAXVALUE)
+ (SUBPARTITION `sp2``\""e`,
+  SUBPARTITION `sp3``\""e`));
+INSERT INTO `t``\""e` VALUES (0), (2), (6), (10), (14), (18), (22);
+START TRANSACTION;
+--echo # con1
+connect(con1,localhost,root,,);
+SET NAMES utf8;
+START TRANSACTION;
+--echo # default connection
+connection default;
+UPDATE `t``\""e` SET a = 16 WHERE a = 0;
+--echo # con1
+connection con1;
+UPDATE `t``\""e` SET a = 8 WHERE a = 22;
+let $id_1= `SELECT CONNECTION_ID()`;
+SEND;
+UPDATE `t``\""e` SET a = 12 WHERE a = 0;
+--echo # default connection
+connection default;
+let $wait_timeout= 2;
+let $wait_condition= SELECT 1 FROM INFORMATION_SCHEMA.PROCESSLIST
+WHERE ID = $id_1 AND STATE = 'Searching rows for update';
+--source include/wait_condition.inc
+#--echo # tested wait condition $wait_condition_reps times
+# INNODB_LOCKS only exists in innodb_plugin
+--sorted_result
+SELECT lock_table, COUNT(*) FROM INFORMATION_SCHEMA.INNODB_LOCKS
+GROUP BY lock_table;
+set @old_sql_mode = @@sql_mode;
+set sql_mode = 'ANSI_QUOTES';
+--sorted_result
+SELECT lock_table, COUNT(*) FROM INFORMATION_SCHEMA.INNODB_LOCKS
+GROUP BY lock_table;
+set @@sql_mode = @old_sql_mode;
+--error ER_LOCK_DEADLOCK
+UPDATE `t``\""e` SET a = 4 WHERE a = 22;
+--echo # First table reported in 'SHOW ENGINE InnoDB STATUS'
+# RECORD LOCKS space id 0 page no 50 n bits 80 index `PRIMARY` in \
+# Database `test`, Table `t1`, Partition `p0`, Subpartition `sp0` \
+# trx id 0 775
+# NOTE: replace_regex is very slow on match copy/past '(.*)' regex's
+# on big texts, removing a lot of text before + after makes it much faster.
+#/.*in (.*) trx.*/\1/
+--replace_regex /.*RECORD LOCKS space id [0-9]* page no [0-9]* n bits [0-9]* // / trx id .*// /.*index .* in //
+SHOW ENGINE InnoDB STATUS;
+set @old_sql_mode = @@sql_mode;
+set sql_mode = 'ANSI_QUOTES';
+--replace_regex /.*RECORD LOCKS space id [0-9]* page no [0-9]* n bits [0-9]* // / trx id .*// /.*index .* in //
+SHOW ENGINE InnoDB STATUS;
+set @@sql_mode = @old_sql_mode;
+--echo # con1
+connection con1;
+REAP;
+ROLLBACK;
+disconnect con1;
+--echo # default connection
+connection default;
+DROP TABLE `t``\""e`;
+SET NAMES DEFAULT;

=== added file 'mysql-test/t/partition_open_files_limit-master.opt'
--- a/mysql-test/t/partition_open_files_limit-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/partition_open_files_limit-master.opt	2009-10-08 13:36:43 +0000
@@ -0,0 +1 @@
+--open-files-limit=5 --max_connections=2 --table_open_cache=1

=== added file 'mysql-test/t/partition_open_files_limit.test'
--- a/mysql-test/t/partition_open_files_limit.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/partition_open_files_limit.test	2009-10-09 14:12:01 +0000
@@ -0,0 +1,26 @@
+--source include/have_partition.inc
+
+--disable_warnings
+DROP TABLE IF EXISTS `t1`;
+--enable_warnings
+
+# On some platforms the lowest possible open_files_limit is too high...
+let $max_open_files_limit= `SELECT @@open_files_limit > 511`;
+if ($max_open_files_limit)
+{
+  skip Need open_files_limit to be lower than 512;
+}
+
+#
+--echo # Bug#46922: crash when adding partitions and open_files_limit is reached
+#
+CREATE TABLE t1 (a INT PRIMARY KEY) 
+ENGINE=MyISAM PARTITION BY KEY () PARTITIONS 1;
+INSERT INTO t1 VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10), (11);
+--echo # if the bug exists, then crash will happen here
+--replace_regex /file '.*'/file '<partition file>'/
+--error 23
+ALTER TABLE t1 ADD PARTITION PARTITIONS 511;
+--sorted_result
+SELECT * FROM t1;
+DROP TABLE t1;

=== modified file 'mysql-test/t/plugin.test'
--- a/mysql-test/t/plugin.test	2009-06-10 08:59:49 +0000
+++ b/mysql-test/t/plugin.test	2009-10-08 08:39:15 +0000
@@ -1,3 +1,4 @@
+--source include/not_windows_embedded.inc
 --source include/have_example_plugin.inc
 
 CREATE TABLE t1(a int) ENGINE=EXAMPLE;

=== modified file 'mysql-test/t/plugin_load.test'
--- a/mysql-test/t/plugin_load.test	2008-01-26 00:05:15 +0000
+++ b/mysql-test/t/plugin_load.test	2009-10-08 08:39:15 +0000
@@ -1,3 +1,4 @@
+--source include/not_windows_embedded.inc
 --source include/have_example_plugin.inc
 
 SELECT @@global.example_enum_var = 'e2';

=== modified file 'mysql-test/t/ps_not_windows.test'
--- a/mysql-test/t/ps_not_windows.test	2009-05-22 17:53:25 +0000
+++ b/mysql-test/t/ps_not_windows.test	2009-11-10 15:15:12 +0000
@@ -2,7 +2,7 @@
 --source include/not_embedded.inc
 # Non-windows specific ps tests.
 --source include/not_windows.inc
-# Requires ability to install plugins.
+# requires dynamic loading
 --source include/have_dynamic_loading.inc
 
 #

=== modified file 'mysql-test/t/query_cache.test'
--- a/mysql-test/t/query_cache.test	2009-02-19 09:01:25 +0000
+++ b/mysql-test/t/query_cache.test	2009-11-10 15:15:12 +0000
@@ -1294,7 +1294,7 @@ SET GLOBAL query_cache_size= default;
 # Bug #31157: Crash when select+order by the avg of some field within the
 # group by
 #
-
+SET GLOBAL query_cache_size=1024*1024*512;
 CREATE TABLE t1 (a ENUM('rainbow'));
 INSERT INTO t1 VALUES (),(),(),(),();
 SELECT 1 FROM t1 GROUP BY (SELECT 1 FROM t1 ORDER BY AVG(LAST_INSERT_ID()));
@@ -1305,6 +1305,7 @@ INSERT INTO t1 SET a = 'aaaa';
 SELECT 1 FROM t1 GROUP BY
   (SELECT LAST_INSERT_ID() FROM t1 ORDER BY MIN(a) ASC LIMIT 1);
 DROP TABLE t1;
+SET GLOBAL query_cache_size= default;
 
 --echo End of 5.1 tests
 

=== modified file 'mysql-test/t/range.test'
--- a/mysql-test/t/range.test	2008-03-27 02:18:46 +0000
+++ b/mysql-test/t/range.test	2009-11-02 12:24:07 +0000
@@ -1046,3 +1046,218 @@ explain select * from t2 where a=1000 an
 
 drop table t1, t2;
 
+#
+# Bug#42846: wrong result returned for range scan when using covering index
+#
+CREATE TABLE t1( a INT, b INT, KEY( a, b ) );
+
+CREATE TABLE t2( a INT, b INT, KEY( a, b ) );
+
+CREATE TABLE t3( a INT, b INT, KEY( a, b ) );
+
+INSERT INTO t1( a, b ) 
+VALUES (0, 1), (1, 2), (1, 4), (2, 3), (5, 0), (9, 7);
+
+INSERT INTO t2( a, b ) 
+VALUES ( 1, 1), ( 2, 1), ( 3, 1), ( 4, 1), ( 5, 1),
+       ( 6, 1), ( 7, 1), ( 8, 1), ( 9, 1), (10, 1), 
+       (11, 1), (12, 1), (13, 1), (14, 1), (15, 1),
+       (16, 1), (17, 1), (18, 1), (19, 1), (20, 1);
+
+INSERT INTO t2 SELECT a, 2 FROM t2 WHERE b = 1;
+INSERT INTO t2 SELECT a, 3 FROM t2 WHERE b = 1;
+
+# To make range scan compelling to the optimizer
+INSERT INTO t2 SELECT -1, -1 FROM t2;
+INSERT INTO t2 SELECT -1, -1 FROM t2;
+INSERT INTO t2 SELECT -1, -1 FROM t2;
+
+INSERT INTO t3
+VALUES (1, 0), (2, 0), (3, 0), (4, 0), (5, 0),
+       (6, 0), (7, 0), (8, 0), (9, 0), (10, 0);
+
+# To make range scan compelling to the optimizer
+INSERT INTO t3 SELECT * FROM t3 WHERE a = 10;
+INSERT INTO t3 SELECT * FROM t3 WHERE a = 10;
+
+
+#
+# Problem#1 Test queries. Will give missing results unless Problem#1 is fixed.
+# With one exception, they are independent of Problem#2.
+#
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 < a AND b = 3 OR
+3 <= a;
+
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 < a AND b = 3 OR
+3 <= a;
+
+# Query below: Tests both Problem#1 and Problem#2 (EXPLAIN differs as well)
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a < 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+5 <= a AND b = 3 OR
+3 <= a;
+
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+3 <= a;
+
+EXPLAIN
+SELECT * FROM t1 WHERE
+3 <= a AND a <= 5 OR 
+3 <= a;
+
+#
+# Problem#2 Test queries. 
+# These queries will give missing results if Problem#1 is fixed.
+# But Problem#1 also hides this bug.
+#
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 1 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+
+EXPLAIN
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 1 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 2 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+
+EXPLAIN
+SELECT * FROM t2 WHERE
+5 <= a AND a < 10 AND b = 2 OR
+15 <= a AND a < 20 AND b = 3
+OR
+1 <= a AND b = 1;
+
+SELECT * FROM t3 WHERE
+5 <= a AND a < 10 AND b = 3 OR 
+a < 5 OR
+a < 10;
+
+EXPLAIN
+SELECT * FROM t3 WHERE
+5 <= a AND a < 10 AND b = 3 OR 
+a < 5 OR
+a < 10;
+
+DROP TABLE t1, t2, t3;
+
+--echo #
+--echo # Bug #47123: Endless 100% CPU loop with STRAIGHT_JOIN
+--echo #
+
+CREATE TABLE t1(a INT, KEY(a));
+INSERT INTO t1 VALUES (1), (NULL);
+SELECT * FROM t1 WHERE a <> NULL and (a <> NULL or a <= NULL);
+DROP TABLE t1;
+
+--echo #
+--echo # Bug#47925: regression of range optimizer and date comparison in 5.1.39!
+--echo #
+CREATE TABLE t1 ( a DATE,     KEY ( a ) );
+CREATE TABLE t2 ( a DATETIME, KEY ( a ) );
+
+--echo # Make optimizer choose range scan
+INSERT INTO t1 VALUES ('2009-09-22'), ('2009-09-22'), ('2009-09-22');
+INSERT INTO t1 VALUES ('2009-09-23'), ('2009-09-23'), ('2009-09-23');
+
+INSERT INTO t2 VALUES ('2009-09-22 12:00:00'), ('2009-09-22 12:00:00'),
+                      ('2009-09-22 12:00:00');
+INSERT INTO t2 VALUES ('2009-09-23 12:00:00'), ('2009-09-23 12:00:00'),
+                      ('2009-09-23 12:00:00');
+
+--echo # DATE vs DATE
+--replace_column 1 X 2 X 3 X 7 X 8 X 9 X 10 X
+EXPLAIN
+SELECT * FROM t1 WHERE a >= '2009/09/23';
+SELECT * FROM t1 WHERE a >= '2009/09/23';
+SELECT * FROM t1 WHERE a >= '20090923';
+SELECT * FROM t1 WHERE a >=  20090923;
+SELECT * FROM t1 WHERE a >= '2009-9-23';
+SELECT * FROM t1 WHERE a >= '2009.09.23';
+SELECT * FROM t1 WHERE a >= '2009:09:23';
+
+--echo # DATE vs DATETIME
+--replace_column 1 X 2 X 3 X 7 X 8 X 9 X 10 X
+EXPLAIN
+SELECT * FROM t2 WHERE a >= '2009/09/23';
+SELECT * FROM t2 WHERE a >= '2009/09/23';
+SELECT * FROM t2 WHERE a >= '2009/09/23';
+SELECT * FROM t2 WHERE a >= '20090923';
+SELECT * FROM t2 WHERE a >=  20090923;
+SELECT * FROM t2 WHERE a >= '2009-9-23';
+SELECT * FROM t2 WHERE a >= '2009.09.23';
+SELECT * FROM t2 WHERE a >= '2009:09:23';
+
+--echo # DATETIME vs DATETIME
+--replace_column 1 X 2 X 3 X 7 X 8 X 9 X 10 X
+EXPLAIN
+SELECT * FROM t2 WHERE a >= '2009/09/23 12:00:00';
+SELECT * FROM t2 WHERE a >= '2009/09/23 12:00:00';
+SELECT * FROM t2 WHERE a >= '20090923120000';
+SELECT * FROM t2 WHERE a >=  20090923120000;
+SELECT * FROM t2 WHERE a >= '2009-9-23 12:00:00';
+SELECT * FROM t2 WHERE a >= '2009.09.23 12:00:00';
+SELECT * FROM t2 WHERE a >= '2009:09:23 12:00:00';
+
+--echo # DATETIME vs DATE
+--replace_column 1 X 2 X 3 X 7 X 8 X 9 X 10 X
+EXPLAIN
+SELECT * FROM t1 WHERE a >= '2009/09/23 00:00:00';
+SELECT * FROM t1 WHERE a >= '2009/09/23 00:00:00';
+SELECT * FROM t1 WHERE a >= '2009/09/23 00:00:00';
+SELECT * FROM t1 WHERE a >= '20090923000000';
+SELECT * FROM t1 WHERE a >=  20090923000000;
+SELECT * FROM t1 WHERE a >= '2009-9-23 00:00:00';
+SELECT * FROM t1 WHERE a >= '2009.09.23 00:00:00';
+SELECT * FROM t1 WHERE a >= '2009:09:23 00:00:00';
+
+--echo # Test of the new get_date_from_str implementation
+--echo # Behavior differs slightly between the trunk and mysql-pe.
+--echo # The former may give errors for the truncated values, while the latter
+--echo # gives warnings. The purpose of this test is not to interfere, and only
+--echo # preserve existing behavior.
+SELECT str_to_date('2007-10-00', '%Y-%m-%d') >= '' AND 
+       str_to_date('2007-10-00', '%Y-%m-%d') <= '2007/10/20';
+
+SELECT str_to_date('2007-20-00', '%Y-%m-%d') >= '2007/10/20' AND 
+       str_to_date('2007-20-00', '%Y-%m-%d') <= '';
+
+SELECT str_to_date('2007-10-00', '%Y-%m-%d') BETWEEN '' AND '2007/10/20';
+SELECT str_to_date('2007-20-00', '%Y-%m-%d') BETWEEN '2007/10/20' AND '';
+
+SELECT str_to_date('', '%Y-%m-%d');
+
+DROP TABLE t1, t2;
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/select.test'
--- a/mysql-test/t/select.test	2009-06-26 19:57:42 +0000
+++ b/mysql-test/t/select.test	2009-10-30 14:13:13 +0000
@@ -3739,7 +3739,40 @@ EXPLAIN EXTENDED SELECT a, b FROM t1 WHE
 EXPLAIN EXTENDED SELECT a, b FROM t1 WHERE a > 1 AND b = a LIMIT 2;
 
 DROP TABLE t1;
+
+
+--echo #
+--echo # Bug#47019: Assertion failed: 0, file .\rt_mbr.c, line 138 when 
+--echo # forcing a spatial index
+--echo #
+CREATE TABLE t1(a LINESTRING NOT NULL, SPATIAL KEY(a));
+INSERT INTO t1 VALUES
+  (GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)')),
+  (GEOMFROMTEXT('LINESTRING(-1 -1, 1 -1, -1 -1, -1 1, 1 1)'));
+EXPLAIN SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2;
+SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2;
+EXPLAIN SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2 FORCE INDEX(a);
+SELECT 1 FROM t1 NATURAL LEFT JOIN t1 AS t2 FORCE INDEX(a);
+DROP TABLE t1;
+
+
+--echo #
+--echo # Bug #48291 : crash with row() operator,select into @var, and 
+--echo #   subquery returning multiple rows
+--echo #
+
+CREATE TABLE t1(a INT);
+INSERT INTO t1 VALUES (2),(3);
+
+--echo # Should not crash
+--error ER_SUBQUERY_NO_1_ROW
+SELECT 1 FROM t1 WHERE a <> 1 AND NOT
+ROW(a,a) <=> ROW((SELECT 1 FROM t1 WHERE 1=2),(SELECT 1 FROM t1))
+INTO @var0;
+
+DROP TABLE t1;
  
+
 --echo End of 5.0 tests
 
 #

=== added file 'mysql-test/t/sp-bugs.test'
--- a/mysql-test/t/sp-bugs.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/sp-bugs.test	2009-10-26 09:55:57 +0000
@@ -0,0 +1,61 @@
+# Test file for stored procedure bugfixes
+
+--echo #
+--echo # Bug #47412: Valgrind warnings / user can read uninitalized memory
+--echo # using SP variables
+--echo #
+
+CREATE SCHEMA testdb;
+USE testdb;
+DELIMITER |;
+CREATE FUNCTION f2 () RETURNS INTEGER
+BEGIN
+   DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
+   RETURN f_not_exists () ;
+END|
+CREATE PROCEDURE p3 ( arg1 VARCHAR(32) )
+BEGIN
+   CALL p_not_exists ( );
+END|
+DELIMITER ;|
+--echo # should not return valgrind warnings
+--error ER_SP_DOES_NOT_EXIST
+CALL p3 ( f2 () );
+
+DROP SCHEMA testdb;
+
+CREATE SCHEMA testdb;
+USE testdb;
+DELIMITER |;
+CREATE FUNCTION f2 () RETURNS INTEGER
+BEGIN
+   DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
+   RETURN f_not_exists () ;
+END|
+CREATE PROCEDURE p3 ( arg2 INTEGER )
+BEGIN
+   CALL p_not_exists ( );
+END|
+DELIMITER ;|
+--echo # should not return valgrind warnings
+--error ER_SP_DOES_NOT_EXIST
+CALL p3 ( f2 () );
+
+DROP SCHEMA testdb;
+
+CREATE SCHEMA testdb;
+USE testdb;
+DELIMITER |;
+CREATE FUNCTION f2 () RETURNS INTEGER
+BEGIN
+   DECLARE CONTINUE HANDLER FOR SQLSTATE '42000' SET @aux = 1;
+   RETURN f_not_exists () ;
+END|
+DELIMITER ;|
+--echo # should not return valgrind warnings
+SELECT f2 ();
+
+DROP SCHEMA testdb;
+
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/sp-error.test'
--- a/mysql-test/t/sp-error.test	2009-05-27 15:19:44 +0000
+++ b/mysql-test/t/sp-error.test	2009-10-19 13:55:04 +0000
@@ -2448,3 +2448,27 @@ SELECT AVG (a) FROM t1 WHERE b = 999999;
 --error ER_SP_DOES_NOT_EXIST
 SELECT non_existent (a) FROM t1 WHERE b = 999999;
 DROP TABLE t1;
+
+--echo #
+--echo # Bug #47788: Crash in TABLE_LIST::hide_view_error on UPDATE + VIEW + 
+--echo #   SP + MERGE + ALTER
+--echo #
+
+CREATE TABLE t1 (pk INT, b INT, KEY (b));
+CREATE ALGORITHM = TEMPTABLE VIEW v1 AS SELECT * FROM t1;
+
+CREATE PROCEDURE p1 (a int) UPDATE IGNORE v1 SET b = a; 
+
+--error ER_NON_UPDATABLE_TABLE
+CALL p1(5);
+
+ALTER TABLE t1 CHANGE COLUMN b b2 INT;
+
+--error ER_VIEW_INVALID
+CALL p1(7);
+
+DROP PROCEDURE p1;
+DROP VIEW v1;
+DROP TABLE t1;
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/sp.test'
--- a/mysql-test/t/sp.test	2009-06-04 11:53:15 +0000
+++ b/mysql-test/t/sp.test	2009-10-23 13:54:58 +0000
@@ -8242,6 +8242,28 @@ while ($tab_count)
 DROP PROCEDURE p1;
 DROP TABLE t1;
 
+
+--echo #
+--echo # Bug #46629: Item_in_subselect::val_int(): Assertion `0' 
+--echo # on subquery inside a SP
+--echo #
+CREATE TABLE t1(a INT);
+CREATE TABLE t2(a INT, b INT PRIMARY KEY);
+
+DELIMITER |;
+CREATE PROCEDURE p1 () 
+BEGIN 
+  SELECT a FROM t1 A WHERE A.b IN (SELECT b FROM t2 AS B);
+END|
+DELIMITER ;|
+--error ER_BAD_FIELD_ERROR
+CALL p1;
+--error ER_BAD_FIELD_ERROR
+CALL p1;
+DROP PROCEDURE p1;
+DROP TABLE t1, t2;
+
+
 --echo # ------------------------------------------------------------------
 --echo # -- End of 5.1 tests
 --echo # ------------------------------------------------------------------

=== added file 'mysql-test/t/status-master.opt'
--- a/mysql-test/t/status-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/status-master.opt	2009-08-27 13:17:09 +0000
@@ -0,0 +1 @@
+--log-output=table,file

=== modified file 'mysql-test/t/subselect.test'
--- a/mysql-test/t/subselect.test	2009-11-06 17:22:32 +0000
+++ b/mysql-test/t/subselect.test	2009-11-10 15:15:12 +0000
@@ -30,7 +30,7 @@ SELECT 1 IN (SELECT 1);
 SELECT 1 FROM (SELECT 1 as a) b WHERE 1 IN (SELECT (SELECT a));
 -- error ER_WRONG_USAGE
 select (SELECT 1 FROM (SELECT 1) a PROCEDURE ANALYSE(1));
--- error ER_WRONG_USAGE
+-- error ER_WRONG_PARAMETERS_TO_PROCEDURE
 SELECT 1 FROM (SELECT 1) a PROCEDURE ANALYSE((SELECT 1));
 -- error ER_BAD_FIELD_ERROR
 SELECT (SELECT 1) as a FROM (SELECT 1) b WHERE (SELECT a) IS NULL;
@@ -3554,4 +3554,19 @@ where v in(select v
            where t1.g=t2.g) is unknown;
 drop table t1, t2;
 
+#
+# Bug #31157: Crash when select+order by the avg of some field within the
+# group by
+#
+CREATE TABLE t1 (a ENUM('rainbow'));
+INSERT INTO t1 VALUES (),(),(),(),();
+SELECT 1 FROM t1 GROUP BY (SELECT 1 FROM t1 ORDER BY AVG(LAST_INSERT_ID()));
+DROP TABLE t1;
+CREATE TABLE t1 (a LONGBLOB);
+INSERT INTO t1 SET a = 'aaaa';
+INSERT INTO t1 SET a = 'aaaa';
+SELECT 1 FROM t1 GROUP BY
+  (SELECT LAST_INSERT_ID() FROM t1 ORDER BY MIN(a) ASC LIMIT 1);
+DROP TABLE t1;
+
 --echo End of 5.1 tests.

=== modified file 'mysql-test/t/subselect3.test'
--- a/mysql-test/t/subselect3.test	2009-10-15 21:38:29 +0000
+++ b/mysql-test/t/subselect3.test	2009-11-10 15:15:12 +0000
@@ -730,3 +730,69 @@ where
                                   from t4, t5 limit 2));
 
 drop table t0, t1, t2, t3, t4, t5;
+
+--echo # 
+--echo # BUG#48177 - SELECTs with NOT IN subqueries containing NULL 
+--echo #             values return too many records
+--echo # 
+
+CREATE TABLE t1 (
+  i1 int DEFAULT NULL,
+  i2 int DEFAULT NULL
+) ;
+
+INSERT INTO t1 VALUES (1,    NULL);
+INSERT INTO t1 VALUES (2,    3);
+INSERT INTO t1 VALUES (4,    NULL);
+INSERT INTO t1 VALUES (4,    0);
+INSERT INTO t1 VALUES (NULL, NULL);
+
+CREATE TABLE t2 (
+  i1 int DEFAULT NULL,
+  i2 int DEFAULT NULL
+) ;
+
+INSERT INTO t2 VALUES (4, NULL);
+INSERT INTO t2 VALUES (5, 0);
+
+--echo 
+--echo Data in t1
+SELECT i1, i2 FROM t1;
+
+--echo 
+--echo Data in subquery (should be filtered out)
+SELECT i1, i2 FROM t2 ORDER BY i1;
+
+FLUSH STATUS;
+
+--echo 
+SELECT i1, i2
+FROM t1
+WHERE (i1, i2) 
+      NOT IN (SELECT i1, i2 FROM t2);
+
+--echo 
+--echo # Check that the subquery only has to be evaluated once 
+--echo # for all-NULL values even though there are two (NULL,NULL) records
+--echo # Baseline:
+SHOW STATUS LIKE '%Handler_read_rnd_next';
+
+--echo 
+INSERT INTO t1 VALUES (NULL, NULL); 
+FLUSH STATUS;
+
+--echo 
+SELECT i1, i2
+FROM t1
+WHERE (i1, i2) 
+      NOT IN (SELECT i1, i2 FROM t2);
+
+--echo 
+--echo # Handler_read_rnd_next should be one more than baseline 
+--echo # (read record from t1, but do not read from t2)
+SHOW STATUS LIKE '%Handler_read_rnd_next';
+
+
+DROP TABLE t1,t2;
+
+--echo End of 5.1 tests

=== added file 'mysql-test/t/subselect4.test'
--- a/mysql-test/t/subselect4.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/subselect4.test	2009-09-18 09:34:08 +0000
@@ -0,0 +1,64 @@
+# General purpose bug fix tests go here : subselect.test too large
+
+
+--echo #
+--echo # Bug #46791: Assertion failed:(table->key_read==0),function unknown
+--echo #    function,file sql_base.cc
+--echo #
+
+CREATE TABLE t1 (a INT, b INT, KEY(a));
+INSERT INTO t1 VALUES (1,1),(2,2);
+CREATE TABLE t2 LIKE t1;
+INSERT INTO t2 VALUES (1,1),(2,2);
+CREATE TABLE t3 LIKE t1;
+
+--echo # should have 1 impossible where and 2 dependent subqueries
+EXPLAIN
+SELECT 1 FROM t1
+WHERE NOT EXISTS (SELECT 1 FROM t2 WHERE 1 = (SELECT MIN(t2.b) FROM t3))
+ORDER BY count(*);
+
+--echo # should not crash the next statement
+SELECT 1 FROM t1
+WHERE NOT EXISTS (SELECT 1 FROM t2 WHERE 1 = (SELECT MIN(t2.b) FROM t3))
+ORDER BY count(*);
+
+--echo # should not crash: the crash is caused by the previous statement
+SELECT 1;
+
+DROP TABLE t1,t2,t3;
+
+--echo #
+--echo # Bug #47106: Crash / segfault on adding EXPLAIN to a non-crashing 
+--echo # query
+--echo #
+
+CREATE TABLE t1 (
+  a INT,
+  b INT,
+  PRIMARY KEY (a),
+  KEY b (b)
+);
+INSERT INTO t1 VALUES (1, 1), (2, 1);
+
+CREATE TABLE t2 LIKE t1;
+INSERT INTO t2 SELECT * FROM t1;
+
+CREATE TABLE t3 LIKE t1;
+INSERT INTO t3 SELECT * FROM t1;
+
+--echo # Should not crash.
+--echo # Should have 1 impossible where and 2 dependent subqs.
+EXPLAIN
+SELECT
+  (SELECT 1 FROM t1,t2 WHERE t2.b > t3.b)
+FROM t3 WHERE 1 = 0 GROUP BY 1;
+
+--echo # should return 0 rows
+SELECT
+  (SELECT 1 FROM t1,t2 WHERE t2.b > t3.b)
+FROM t3 WHERE 1 = 0 GROUP BY 1;
+
+DROP TABLE t1,t2,t3;
+
+--echo End of 5.0 tests.

=== modified file 'mysql-test/t/type_bit.test'
--- a/mysql-test/t/type_bit.test	2008-12-09 13:31:22 +0000
+++ b/mysql-test/t/type_bit.test	2009-10-08 15:36:36 +0000
@@ -397,6 +397,17 @@ insert into t2bit7 values (b'11001101111
 select bin(a1) from t1bit7, t2bit7 where t1bit7.a1=t2bit7.b1; 
 drop table t1bit7, t2bit7; 
 
+
+--echo #
+--echo # Bug42803: Field_bit does not have unsigned_flag field, 
+--echo # can lead to bad memory access
+--echo #
+CREATE TABLE t1 (a BIT(7), b BIT(9), KEY(a, b));
+INSERT INTO t1 VALUES(0, 0), (5, 3), (5, 6), (6, 4), (7, 0);
+EXPLAIN SELECT a+0, b+0 FROM t1 WHERE a > 4 and b < 7 ORDER BY 2;
+DROP TABLE t1;
+
+
 --echo End of 5.0 tests
 
 #

=== modified file 'mysql-test/t/type_newdecimal.test'
--- a/mysql-test/t/type_newdecimal.test	2009-08-24 19:47:08 +0000
+++ b/mysql-test/t/type_newdecimal.test	2009-11-02 11:21:39 +0000
@@ -1286,137 +1286,3 @@ CREATE TABLE t1 SELECT 1 % .123456789123
 DESCRIBE t1;
 SELECT my_col FROM t1;
 DROP TABLE t1;
-
---echo #
---echo # Bug#45261: Crash, stored procedure + decimal
---echo #
-
---disable_warnings
-DROP TABLE IF EXISTS t1;
---enable_warnings
-
-CREATE TABLE t1 SELECT
-  /* 81 */ 100000000000000000000000000000000000000000000000000000000000000000000000000000001
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 81 */ 100000000000000000000000000000000000000000000000000000000000000000000000000000001.
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 81 */ 100000000000000000000000000000000000000000000000000000000000000000000000000000001.1 /* 1 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 82 */ 1000000000000000000000000000000000000000000000000000000000000000000000000000000001
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 40 */ 1000000000000000000000000000000000000001.1000000000000000000000000000000000000001 /* 40 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 1 */ 1.10000000000000000000000000000000000000000000000000000000000000000000000000000001 /* 80 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 1 */ 1.100000000000000000000000000000000000000000000000000000000000000000000000000000001 /* 81 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  .100000000000000000000000000000000000000000000000000000000000000000000000000000001 /* 81 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 45 */ 123456789012345678901234567890123456789012345.123456789012345678901234567890123456789012345 /* 45 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 65 */ 12345678901234567890123456789012345678901234567890123456789012345.1 /* 1 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  /* 66 */ 123456789012345678901234567890123456789012345678901234567890123456.1 /* 1 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT
-  .123456789012345678901234567890123456789012345678901234567890123456 /* 66 */
-  AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 AS SELECT 123.1234567890123456789012345678901 /* 31 */ AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
-CREATE TABLE t1 SELECT 1.1 + CAST(1 AS DECIMAL(65,30)) AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;
-
---echo #
---echo # Test that the integer and decimal parts are properly calculated.
---echo #
-
-CREATE TABLE t1 (a DECIMAL(30,30));
-INSERT INTO t1 VALUES (0.1),(0.2),(0.3);
-CREATE TABLE t2 SELECT MIN(a + 0.0000000000000000000000000000001) AS c1 FROM t1;
-DESC t2;
-DROP TABLE t1,t2;
-
-CREATE TABLE t1 (a DECIMAL(30,30));
-INSERT INTO t1 VALUES (0.1),(0.2),(0.3);
-CREATE TABLE t2 SELECT IFNULL(a + 0.0000000000000000000000000000001, NULL) AS c1 FROM t1;
-DESC t2;
-DROP TABLE t1,t2;
-
-CREATE TABLE t1 (a DECIMAL(30,30));
-INSERT INTO t1 VALUES (0.1),(0.2),(0.3);
-CREATE TABLE t2 SELECT CASE a WHEN 0.1 THEN 0.0000000000000000000000000000000000000000000000000000000000000000001 END AS c1 FROM t1;
-DESC t2;
-DROP TABLE t1,t2;
-
---echo #
---echo # Test that variables get maximum precision.
---echo #
-
-SET @decimal= 1.1;
-CREATE TABLE t1 SELECT @decimal AS c1;
-DESC t1;
-SELECT * FROM t1;
-DROP TABLE t1;

=== modified file 'mysql-test/t/udf.test'
--- a/mysql-test/t/udf.test	2007-11-27 15:19:51 +0000
+++ b/mysql-test/t/udf.test	2009-09-07 09:57:22 +0000
@@ -436,4 +436,16 @@ SELECT * FROM t2 WHERE a = sequence();
 DROP FUNCTION sequence;
 DROP TABLE t1,t2;
 
+--echo #
+--echo # Bug#46259: 5.0.83 -> 5.1.36, query doesn't work
+--echo #
+CREATE TABLE t1 ( a INT );
+
+INSERT INTO t1 VALUES (1), (2), (3);
+
+SELECT IF( a = 1, a, a ) AS `b` FROM t1 ORDER BY field( `b` + 1, 1 );
+SELECT IF( a = 1, a, a ) AS `b` FROM t1 ORDER BY field( `b`, 1 );
+
+DROP TABLE t1;
+
 --echo End of 5.0 tests.

=== modified file 'mysql-test/t/update.test'
--- a/mysql-test/t/update.test	2008-11-28 16:36:07 +0000
+++ b/mysql-test/t/update.test	2009-10-23 13:09:14 +0000
@@ -452,3 +452,18 @@ DROP TABLE t1;
 DROP FUNCTION f1;
 
 --echo End of 5.0 tests
+
+--echo #
+--echo # Bug #47919 assert in open_table during ALTER temporary table
+--echo #
+
+CREATE TABLE t1 (f1 INTEGER AUTO_INCREMENT, PRIMARY KEY (f1));
+CREATE TEMPORARY TABLE t2 LIKE t1;
+INSERT INTO t1 VALUES (1);
+INSERT INTO t2 VALUES (1);
+
+ALTER TABLE t2 COMMENT = 'ABC';
+UPDATE t2, t1 SET t2.f1 = 2, t1.f1 = 9;
+ALTER TABLE t2 COMMENT = 'DEF';
+
+DROP TABLE t1, t2;

=== modified file 'mysql-test/t/upgrade.test'
--- a/mysql-test/t/upgrade.test	2009-04-30 12:46:49 +0000
+++ b/mysql-test/t/upgrade.test	2009-08-25 13:56:50 +0000
@@ -124,6 +124,8 @@ with_check_option=0
 timestamp=2009-04-10 11:53:37
 create-version=1
 source=select f1 from `a-b-c`.t1 a, information_schema.tables b\nwhere a.f1 = b.table_name
+client_cs_name=utf8
+connection_cl_name=utf8_general_ci
 EOF
 
 show databases like '%a-b-c%';

=== modified file 'mysql-test/t/view_grant.test'
--- a/mysql-test/t/view_grant.test	2009-08-21 14:41:48 +0000
+++ b/mysql-test/t/view_grant.test	2009-10-16 11:12:21 +0000
@@ -1382,6 +1382,153 @@ DROP VIEW test.v3;
 DROP USER mysqluser1@localhost;
 USE test;
 
+--echo #
+--echo # Bug#35996: SELECT + SHOW VIEW should be enough to display view 
+--echo # definition
+--echo #
+-- source include/not_embedded.inc
+CREATE USER mysqluser1@localhost;
+CREATE DATABASE mysqltest1;
+CREATE DATABASE mysqltest2;
+GRANT USAGE, SELECT, CREATE VIEW, SHOW VIEW 
+ON mysqltest2.* TO mysqluser1@localhost;
+
+USE mysqltest1;
+
+CREATE TABLE t1( a INT );
+CREATE TABLE t2( a INT, b INT );
+CREATE FUNCTION f1() RETURNS INT RETURN 1;
+CREATE VIEW v1 AS SELECT 1 AS a;
+CREATE VIEW v2 AS SELECT 1 AS a, 2 AS b;
+
+GRANT SELECT        ON TABLE    t1 TO mysqluser1@localhost;
+GRANT SELECT (a, b) ON TABLE    t2 TO mysqluser1@localhost;
+GRANT EXECUTE       ON FUNCTION f1 TO mysqluser1@localhost;
+GRANT SELECT        ON TABLE    v1 TO mysqluser1@localhost;
+GRANT SELECT (a, b) ON TABLE    v2 TO mysqluser1@localhost;
+
+CREATE VIEW v_t1 AS SELECT * FROM t1;
+CREATE VIEW v_t2 AS SELECT * FROM t2;
+CREATE VIEW v_f1 AS SELECT f1() AS a;
+CREATE VIEW v_v1 AS SELECT * FROM v1;
+CREATE VIEW v_v2 AS SELECT * FROM v2;
+
+GRANT SELECT, SHOW VIEW ON v_t1 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_t2 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_f1 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_v1 TO mysqluser1@localhost;
+GRANT SELECT, SHOW VIEW ON v_v2 TO mysqluser1@localhost;
+
+--connect (connection1, localhost, mysqluser1,, mysqltest2)
+CREATE VIEW v_mysqluser1_t1 AS SELECT * FROM mysqltest1.t1;
+CREATE VIEW v_mysqluser1_t2 AS SELECT * FROM mysqltest1.t2;
+CREATE VIEW v_mysqluser1_f1 AS SELECT mysqltest1.f1() AS a;
+CREATE VIEW v_mysqluser1_v1 AS SELECT * FROM mysqltest1.v1;
+CREATE VIEW v_mysqluser1_v2 AS SELECT * FROM mysqltest1.v2;
+
+SHOW CREATE VIEW mysqltest1.v_t1;
+SHOW CREATE VIEW mysqltest1.v_t2;
+SHOW CREATE VIEW mysqltest1.v_f1;
+SHOW CREATE VIEW mysqltest1.v_v1;
+SHOW CREATE VIEW mysqltest1.v_v2;
+
+SHOW CREATE VIEW v_mysqluser1_t1;
+SHOW CREATE VIEW v_mysqluser1_t2;
+SHOW CREATE VIEW v_mysqluser1_f1;
+SHOW CREATE VIEW v_mysqluser1_v1;
+SHOW CREATE VIEW v_mysqluser1_v2;
+
+--connection default
+REVOKE SELECT     ON TABLE    t1 FROM mysqluser1@localhost;
+REVOKE SELECT (a) ON TABLE    t2 FROM mysqluser1@localhost;
+REVOKE EXECUTE    ON FUNCTION f1 FROM mysqluser1@localhost;
+REVOKE SELECT     ON TABLE    v1 FROM mysqluser1@localhost;
+
+--connection connection1
+SHOW CREATE VIEW mysqltest1.v_t1;
+SHOW CREATE VIEW mysqltest1.v_t2;
+SHOW CREATE VIEW mysqltest1.v_f1;
+SHOW CREATE VIEW mysqltest1.v_v1;
+SHOW CREATE VIEW mysqltest1.v_v2;
+
+SHOW CREATE VIEW v_mysqluser1_t1;
+SHOW CREATE VIEW v_mysqluser1_t2;
+SHOW CREATE VIEW v_mysqluser1_f1;
+SHOW CREATE VIEW v_mysqluser1_v1;
+SHOW CREATE VIEW v_mysqluser1_v2;
+
+--connection default
+--echo # Testing the case when the views reference missing objects.
+--echo # Obviously, there are no privileges to check for, so we
+--echo # need only each object type once.
+DROP TABLE t1;
+DROP FUNCTION f1;
+DROP VIEW v1;
+
+--connection connection1
+SHOW CREATE VIEW mysqltest1.v_t1;
+SHOW CREATE VIEW mysqltest1.v_f1;
+SHOW CREATE VIEW mysqltest1.v_v1;
+
+SHOW CREATE VIEW v_mysqluser1_t1;
+SHOW CREATE VIEW v_mysqluser1_f1;
+SHOW CREATE VIEW v_mysqluser1_v1;
+
+--connection default
+REVOKE SHOW VIEW ON v_t1 FROM mysqluser1@localhost;
+REVOKE SHOW VIEW ON v_f1 FROM mysqluser1@localhost;
+REVOKE SHOW VIEW ON v_v1 FROM mysqluser1@localhost;
+
+--connection connection1
+--error ER_TABLEACCESS_DENIED_ERROR
+SHOW CREATE VIEW mysqltest1.v_t1;
+--error ER_TABLEACCESS_DENIED_ERROR
+SHOW CREATE VIEW mysqltest1.v_f1;
+--error ER_TABLEACCESS_DENIED_ERROR
+SHOW CREATE VIEW mysqltest1.v_v1;
+SHOW CREATE VIEW v_mysqluser1_t1;
+SHOW CREATE VIEW v_mysqluser1_f1;
+SHOW CREATE VIEW v_mysqluser1_v1;
+
+--disconnect connection1
+--connection default
+DROP USER mysqluser1@localhost;
+DROP DATABASE mysqltest1;
+DROP DATABASE mysqltest2;
+USE test;
+
+CREATE TABLE t1( a INT );
+CREATE DEFINER = no_such_user@no_such_host VIEW v1 AS SELECT * FROM t1;
+SHOW CREATE VIEW v1;
+DROP TABLE t1;
+DROP VIEW v1;
+
 # Wait till we reached the initial number of concurrent sessions
 --source include/wait_until_count_sessions.inc
 
+--echo #
+--echo # Bug #46019: ERROR 1356 When selecting from within another 
+--echo #  view that has Group By
+--echo #
+CREATE DATABASE mysqltest1;
+USE mysqltest1;
+
+CREATE TABLE t1 (a INT);
+
+CREATE SQL SECURITY INVOKER VIEW v1 AS SELECT a FROM t1 GROUP BY a;
+CREATE SQL SECURITY INVOKER VIEW v2 AS SELECT a FROM v1;
+
+CREATE USER mysqluser1;
+
+GRANT SELECT ON TABLE t1 TO mysqluser1;
+GRANT SELECT, SHOW VIEW ON TABLE v1 TO mysqluser1;
+GRANT SELECT, SHOW VIEW ON TABLE v2 TO mysqluser1;
+
+--connect (mysqluser1, localhost, mysqluser1,,mysqltest1)
+SELECT a FROM v1;
+SELECT a FROM v2;
+
+--connection default
+--disconnect mysqluser1
+DROP USER mysqluser1;
+DROP DATABASE mysqltest1;

=== modified file 'mysql-test/t/warnings.test'
--- a/mysql-test/t/warnings.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/warnings.test	2009-11-10 15:15:12 +0000
@@ -227,4 +227,11 @@ insert into t2 values(@q);
 
 drop table t1, t2;
 
+#
+# Bug#42364 SHOW ERRORS returns empty resultset after dropping non existent table
+#
+--error ER_BAD_TABLE_ERROR
+DROP TABLE t1;
+SHOW ERRORS;
+
 --echo End of 5.0 tests

=== modified file 'mysql-test/t/windows.test'
--- a/mysql-test/t/windows.test	2009-02-12 09:52:01 +0000
+++ b/mysql-test/t/windows.test	2009-09-22 11:22:07 +0000
@@ -92,3 +92,9 @@ execute abc;
 execute abc;
 deallocate prepare abc;
 
+--echo #
+--echo # Bug#45498: Socket variable not available on Windows
+--echo #
+
+SELECT VARIABLE_NAME FROM INFORMATION_SCHEMA.GLOBAL_VARIABLES
+  WHERE VARIABLE_NAME = 'socket';

=== modified file 'mysql-test/t/xa.test'
--- a/mysql-test/t/xa.test	2009-06-25 15:25:23 +0000
+++ b/mysql-test/t/xa.test	2009-10-28 15:39:08 +0000
@@ -149,6 +149,68 @@ xa end 'a';
 xa prepare 'a';
 xa commit 'a';
 
+#
+# BUG#43171 - Assertion failed: thd->transaction.xid_state.xid.is_null()
+#
+CREATE TABLE t1(a INT, KEY(a)) ENGINE=InnoDB;
+INSERT INTO t1 VALUES(1),(2);
+connect(con1,localhost,root,,);
+
+# Part 1: Prepare to test XA START after regular transaction deadlock
+BEGIN;
+UPDATE t1 SET a=3 WHERE a=1;
+
+connection default;
+BEGIN;
+UPDATE t1 SET a=4 WHERE a=2;
+
+connection con1;
+let $conn_id= `SELECT CONNECTION_ID()`;
+SEND UPDATE t1 SET a=5 WHERE a=2;
+
+connection default;
+let $wait_timeout= 2;
+let $wait_condition= SELECT 1 FROM INFORMATION_SCHEMA.PROCESSLIST
+WHERE ID=$conn_id AND STATE='Searching rows for update';
+--source include/wait_condition.inc
+
+--error ER_LOCK_DEADLOCK
+UPDATE t1 SET a=5 WHERE a=1;
+ROLLBACK;
+
+# Part 2: Prepare to test XA START after XA transaction deadlock
+connection con1;
+REAP;
+ROLLBACK;
+BEGIN;
+UPDATE t1 SET a=3 WHERE a=1;
+
+connection default;
+XA START 'xid1';
+UPDATE t1 SET a=4 WHERE a=2;
+
+connection con1;
+SEND UPDATE t1 SET a=5 WHERE a=2;
+
+connection default;
+let $wait_timeout= 2;
+let $wait_condition= SELECT 1 FROM INFORMATION_SCHEMA.PROCESSLIST
+WHERE ID=$conn_id AND STATE='Searching rows for update';
+--source include/wait_condition.inc
+
+--error ER_LOCK_DEADLOCK
+UPDATE t1 SET a=5 WHERE a=1;
+--error ER_XA_RBDEADLOCK
+XA END 'xid1';
+XA ROLLBACK 'xid1';
+
+XA START 'xid1';
+XA END 'xid1';
+XA ROLLBACK 'xid1';
+
+disconnect con1;
+DROP TABLE t1;
+
 # Wait till all disconnects are completed
 --source include/wait_until_count_sessions.inc
 

=== modified file 'mysql-test/valgrind.supp'
--- a/mysql-test/valgrind.supp	2009-10-30 18:50:56 +0000
+++ b/mysql-test/valgrind.supp	2009-11-10 15:15:12 +0000
@@ -1,4 +1,3 @@
-#
 # Suppress some common (not fatal) errors in system libraries found by valgrind
 #
 
@@ -894,3 +893,101 @@
    obj: /lib64/libnss_dns-*so)
    fun: gethostbyaddr_r
 }
+
+# suppressions for glibc 2.6.1 64 bit
+
+{
+   Mem loss within nptl_pthread_exit_hack_handler 6
+   Memcheck:Leak
+   fun:malloc
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   fun:__libc_dlopen_mode
+   fun:pthread_cancel_init
+   fun:_Unwind_ForcedUnwind
+   fun:__pthread_unwind
+   fun:pthread_exit
+   fun:nptl_pthread_exit_hack_handler
+}
+
+{
+   Mem loss within nptl_pthread_exit_hack_handler 7
+   Memcheck:Leak
+   fun:malloc
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   fun:__libc_dlopen_mode
+   fun:pthread_cancel_init
+   fun:_Unwind_ForcedUnwind
+   fun:__pthread_unwind
+   fun:pthread_exit
+   fun:nptl_pthread_exit_hack_handler
+   fun:start_thread
+   fun:clone
+}
+
+{
+   Mem loss within nptl_pthread_exit_hack_handler 8
+   Memcheck:Leak
+   fun:calloc
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   fun:__libc_dlopen_mode
+   fun:pthread_cancel_init
+   fun:_Unwind_ForcedUnwind
+   fun:__pthread_unwind
+   fun:pthread_exit
+   fun:nptl_pthread_exit_hack_handler
+   fun:start_thread
+   fun:clone
+}
+
+{
+   Mem loss within nptl_pthread_exit_hack_handler 8
+   Memcheck:Leak
+   fun:calloc
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   obj:*/ld-*.so
+   obj:*/libc-*.so
+   fun:__libc_dlopen_mode
+   fun:pthread_cancel_init
+   fun:_Unwind_ForcedUnwind
+   fun:__pthread_unwind
+   fun:pthread_exit
+   fun:nptl_pthread_exit_hack_handler
+}
+
+#
+# Pthread doesn't free all thread specific memory before program exists
+#
+{
+   pthread allocate_tls memory loss in 2.6.1.
+   Memcheck:Leak 
+   fun:calloc
+   obj:*/ld-*.so
+   fun:_dl_allocate_tls
+   fun:pthread_create*
+}

=== modified file 'mysys/CMakeLists.txt'
--- a/mysys/CMakeLists.txt	2008-10-10 15:28:41 +0000
+++ b/mysys/CMakeLists.txt	2009-11-10 15:15:12 +0000
@@ -29,7 +29,7 @@ SET(MYSYS_SOURCES  array.c charset-def.c
 				errors.c hash.c list.c md5.c mf_brkhant.c mf_cache.c mf_dirname.c mf_fn_ext.c
 				mf_format.c mf_getdate.c mf_iocache.c mf_iocache2.c mf_keycache.c my_safehash.c
 				mf_keycaches.c mf_loadpath.c mf_pack.c mf_path.c mf_qsort.c mf_qsort2.c
-				mf_radix.c mf_same.c mf_sort.c mf_soundex.c mf_strip.c mf_arr_appstr.c mf_tempdir.c
+				mf_radix.c mf_same.c mf_sort.c mf_soundex.c mf_arr_appstr.c mf_tempdir.c
 				mf_tempfile.c mf_unixpath.c mf_wcomp.c mf_wfile.c mulalloc.c my_access.c
 				my_aes.c my_alarm.c my_alloc.c my_append.c my_bit.c my_bitmap.c my_chmod.c my_chsize.c
 				my_clock.c my_compress.c my_conio.c my_copy.c my_crc32.c my_create.c my_delete.c

=== modified file 'mysys/Makefile.am'
--- a/mysys/Makefile.am	2009-09-07 20:50:10 +0000
+++ b/mysys/Makefile.am	2009-11-10 15:15:12 +0000
@@ -1,4 +1,4 @@
-# Copyright (C) 2000-2006 MySQL AB
+# Copyright (C) 2000-2006 MySQL AB, 2009 Sun Microsystems, Inc.
 # 
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -20,32 +20,32 @@ INCLUDES =		@ZLIB_INCLUDES@ -I$(top_buil
 			-I$(top_srcdir)/include -I$(srcdir)
 pkglib_LIBRARIES =	libmysys.a
 LDADD =			libmysys.a $(top_builddir)/strings/libmystrings.a $(top_builddir)/dbug/libdbug.a
-noinst_HEADERS =	mysys_priv.h my_static.h my_handler_errors.h my_safehash.h
+noinst_HEADERS =	mysys_priv.h my_static.h my_handler_errors.h \
+			my_safehash.h
 libmysys_a_SOURCES =    my_init.c my_getwd.c mf_getdate.c my_mmap.c \
 			mf_path.c mf_loadpath.c my_file.c \
 			my_open.c my_create.c my_dup.c my_seek.c my_read.c \
 			my_pread.c my_write.c my_getpagesize.c \
-			my_safehash.c \
-			mf_keycache.c mf_keycaches.c my_crc32.c \
+			my_crc32.c \
 			mf_iocache.c mf_iocache2.c mf_cache.c mf_tempfile.c \
 			mf_tempdir.c my_lock.c mf_brkhant.c my_alarm.c \
 			my_malloc.c my_realloc.c my_once.c mulalloc.c \
 			my_alloc.c safemalloc.c my_new.cc \
-			my_vle.c my_atomic.c lf_hash.c \
-			lf_dynarray.c lf_alloc-pin.c \
+			my_vle.c my_atomic.c \
+			my_safehash.c lf_hash.c lf_dynarray.c lf_alloc-pin.c \
+			my_rnd.c my_uuid.c my_chmod.c \
 			my_fopen.c my_fstream.c my_getsystime.c \
-			my_rnd.c my_uuid.c \
 			my_error.c errors.c my_div.c my_messnc.c \
 			mf_format.c mf_same.c mf_dirname.c mf_fn_ext.c \
 			my_symlink.c my_symlink2.c \
-			mf_pack.c mf_unixpath.c mf_strip.c mf_arr_appstr.c \
+			mf_pack.c mf_unixpath.c mf_arr_appstr.c \
 			mf_wcomp.c mf_wfile.c my_gethwaddr.c \
 			mf_qsort.c mf_qsort2.c mf_sort.c \
 			ptr_cmp.c mf_radix.c queues.c my_getncpus.c \
 			tree.c trie.c list.c hash.c array.c string.c typelib.c \
 			my_copy.c my_append.c my_lib.c \
 			my_delete.c my_rename.c my_redel.c \
-			my_chsize.c my_chmod.c my_clock.c \
+			my_chsize.c my_clock.c \
 			my_quick.c my_lockmem.c my_static.c \
 			my_sync.c my_getopt.c my_mkdir.c \
 			default_modify.c default.c \
@@ -57,12 +57,19 @@ libmysys_a_SOURCES =    my_init.c my_get
 			my_memmem.c stacktrace.c \
 			my_windac.c my_access.c base64.c my_libwrap.c \
 		        wqueue.c
-if THREAD
-libmysys_a_SOURCES+=	thr_alarm.c thr_lock.c my_pthread.c my_thr_init.c \
-			thr_mutex.c thr_rwlock.c waiting_threads.c
+
+if NEED_THREAD
+# mf_keycache is used only in the server, so it is safe to leave the file
+# out of the non-threaded library.
+# In fact, it will currently not compile without thread support.
+libmysys_a_SOURCES +=   mf_keycache.c mf_keycaches.c
 endif
-EXTRA_DIST =		CMakeLists.txt mf_soundex.c \
+
+EXTRA_DIST =		thr_alarm.c thr_lock.c my_pthread.c my_thr_init.c \
+			thr_mutex.c thr_rwlock.c waiting_threads.c \
+			CMakeLists.txt mf_soundex.c \
 			my_conio.c my_wincond.c my_winthread.c
+libmysys_a_LIBADD =	@THREAD_LOBJECTS@
 # test_dir_DEPENDENCIES=	$(LIBRARIES)
 # testhash_DEPENDENCIES=	$(LIBRARIES)
 # test_charset_DEPENDENCIES=	$(LIBRARIES)
@@ -76,6 +83,8 @@ DEFS =			-DDEFAULT_BASEDIR=\"$(prefix)\"
 			-DDEFAULT_SYSCONFDIR="\"$(sysconfdir)\"" \
                         @DEFS@
 
+libmysys_a_DEPENDENCIES= @THREAD_LOBJECTS@
+
 # I hope this always does the right thing. Otherwise this is only test programs
 FLAGS=$(DEFS) $(INCLUDES) $(CPPFLAGS) $(CFLAGS) @NOINST_LDFLAGS@
 

=== modified file 'mysys/hash.c'
--- a/mysys/hash.c	2009-09-07 20:50:10 +0000
+++ b/mysys/hash.c	2009-11-10 15:15:12 +0000
@@ -338,13 +338,8 @@ my_bool my_hash_insert(HASH *info, const
 {
   int flag;
   size_t idx,halfbuff,hash_nr,first_index;
-  uchar *ptr_to_rec,*ptr_to_rec2;
-  HASH_LINK *data,*empty,*gpos,*gpos2,*pos;
-
-  LINT_INIT(gpos);
-  LINT_INIT(gpos2);
-  LINT_INIT(ptr_to_rec);
-  LINT_INIT(ptr_to_rec2);
+  uchar *UNINIT_VAR(ptr_to_rec),*UNINIT_VAR(ptr_to_rec2);
+  HASH_LINK *data,*empty,*UNINIT_VAR(gpos),*UNINIT_VAR(gpos2),*pos;
 
   if (info->flags & HASH_UNIQUE)
   {

=== modified file 'mysys/mf_keycache.c'
--- a/mysys/mf_keycache.c	2009-09-07 20:50:10 +0000
+++ b/mysys/mf_keycache.c	2009-11-10 15:15:12 +0000
@@ -13,7 +13,8 @@
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
 
-/*
+/**
+  @file
   These functions handle keyblock cacheing for ISAM and MyISAM tables.
 
   One cache can handle many files.
@@ -36,7 +37,9 @@
   blocks_unused is the sum of never used blocks in the pool and of currently
   free blocks. blocks_used is the number of blocks fetched from the pool and
   as such gives the maximum number of in-use blocks at any time.
+*/
 
+/*
   Key Cache Locking
   =================
 
@@ -368,8 +371,8 @@ static inline uint next_power(uint value
 */
 
 int init_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
-		   size_t use_mem, uint division_limit,
-		   uint age_threshold)
+                   size_t use_mem, uint division_limit,
+                   uint age_threshold)
 {
   ulong blocks, hash_links;
   size_t length;
@@ -560,8 +563,8 @@ err:
 */
 
 int resize_key_cache(KEY_CACHE *keycache, uint key_cache_block_size,
-		     size_t use_mem, uint division_limit,
-		     uint age_threshold)
+                     size_t use_mem, uint division_limit,
+                     uint age_threshold)
 {
   int blocks;
   DBUG_ENTER("resize_key_cache");
@@ -760,6 +763,13 @@ void end_key_cache(KEY_CACHE *keycache, 
                         (ulong) keycache->global_cache_r_requests,
                         (ulong) keycache->global_cache_read));
 
+  /*
+    Reset these values to be able to detect a disabled key cache.
+    See Bug#44068 (RESTORE can disable the MyISAM Key Cache).
+  */
+  keycache->blocks_used= 0;
+  keycache->blocks_unused= 0;
+
   if (cleanup)
   {
     pthread_mutex_destroy(&keycache->cache_lock);
@@ -1343,7 +1353,11 @@ static void unreg_request(KEY_CACHE *key
   DBUG_ASSERT(block->prev_changed && *block->prev_changed == block);
   DBUG_ASSERT(!block->next_used);
   DBUG_ASSERT(!block->prev_used);
-  if (! --block->requests)
+  /*
+    Unregister the request, but do not link erroneous blocks into the
+    LRU ring.
+  */
+  if (!--block->requests && !(block->status & BLOCK_ERROR))
   {
     my_bool hot;
     if (block->hits_left)
@@ -1425,8 +1439,7 @@ static void wait_for_readers(KEY_CACHE *
 #ifdef THREAD
   struct st_my_thread_var *thread= my_thread_var;
   DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
-  DBUG_ASSERT(!(block->status & (BLOCK_ERROR | BLOCK_IN_FLUSH |
-                                 BLOCK_CHANGED)));
+  DBUG_ASSERT(!(block->status & (BLOCK_IN_FLUSH | BLOCK_CHANGED)));
   DBUG_ASSERT(block->hash_link);
   DBUG_ASSERT(block->hash_link->block == block);
   /* Linked in file_blocks or changed_blocks hash. */
@@ -1716,6 +1729,7 @@ restart:
       - block assigned but not yet read from file (invalid data).
   */
 
+#ifdef THREAD
   if (keycache->in_resize)
   {
     /* This is a request during a resize operation */
@@ -1957,6 +1971,9 @@ restart:
     }
     DBUG_RETURN(0);
   }
+#else /* THREAD */
+  DBUG_ASSERT(!keycache->in_resize);
+#endif
 
   if (page_status == PAGE_READ &&
       (block->status & (BLOCK_IN_EVICTION | BLOCK_IN_SWITCH |
@@ -2210,9 +2227,9 @@ restart:
                 thread might change the block->hash_link value
               */
               error= my_pwrite(block->hash_link->file,
-                               block->buffer+block->offset,
+                               block->buffer + block->offset,
                                block->length - block->offset,
-                               block->hash_link->diskpos+ block->offset,
+                               block->hash_link->diskpos + block->offset,
                                MYF(MY_NABP | MY_WAIT_IF_FULL));
               keycache_pthread_mutex_lock(&keycache->cache_lock);
 
@@ -2536,7 +2553,6 @@ uchar *key_cache_read(KEY_CACHE *keycach
     reg1 BLOCK_LINK *block;
     uint read_length;
     uint offset;
-    uint status;
     int page_st;
 
     /*
@@ -2571,9 +2587,11 @@ uchar *key_cache_read(KEY_CACHE *keycach
     do
     {
       /* Cache could be disabled in a later iteration. */
-      
       if (!keycache->can_be_used)
-	goto no_key_cache;
+      {
+        KEYCACHE_DBUG_PRINT("key_cache_read", ("keycache cannot be used"));
+        goto no_key_cache;
+      }
       /* Start reading at the beginning of the cache block. */
       filepos-= offset;
       /* Do not read beyond the end of the cache block. */
@@ -2634,7 +2652,7 @@ uchar *key_cache_read(KEY_CACHE *keycach
       }
 
       /* block status may have added BLOCK_ERROR in the above 'if'. */
-      if (!((status= block->status) & BLOCK_ERROR))
+      if (!(block->status & BLOCK_ERROR))
       {
 #ifndef THREAD
         if (! return_buffer)
@@ -2660,14 +2678,22 @@ uchar *key_cache_read(KEY_CACHE *keycach
 
       remove_reader(block);
 
-      /*
-         Link the block into the LRU ring if it's the last submitted
-         request for the block. This enables eviction for the block.
-           */
-      unreg_request(keycache, block, 1);
+      /* Error injection for coverage testing. */
+      DBUG_EXECUTE_IF("key_cache_read_block_error",
+                      block->status|= BLOCK_ERROR;);
 
-      if (status & BLOCK_ERROR)
+      /* Do not link erroneous blocks into the LRU ring, but free them. */
+      if (!(block->status & BLOCK_ERROR))
+      {
+        /*
+          Link the block into the LRU ring if it's the last submitted
+          request for the block. This enables eviction for the block.
+        */
+        unreg_request(keycache, block, 1);
+      }
+      else
       {
+        free_block(keycache, block);
         error= 1;
         break;
       }
@@ -2677,7 +2703,7 @@ uchar *key_cache_read(KEY_CACHE *keycach
       if (return_buffer)
 	DBUG_RETURN(block->buffer);
 #endif
-  next_block:
+    next_block:
       buff+= read_length;
       filepos+= read_length+offset;
       offset= 0;
@@ -2685,6 +2711,7 @@ uchar *key_cache_read(KEY_CACHE *keycach
     } while ((length-= read_length));
     goto end;
   }
+  KEYCACHE_DBUG_PRINT("key_cache_read", ("keycache not initialized"));
 
 no_key_cache:
   /* Key cache is not used */
@@ -2705,6 +2732,7 @@ end:
     dec_counter_for_resize_op(keycache);
     keycache_pthread_mutex_unlock(&keycache->cache_lock);
   }
+  DBUG_PRINT("exit", ("error: %d", error ));
   DBUG_RETURN(error ? (uchar*) 0 : start);
 }
 
@@ -2913,19 +2941,27 @@ int key_cache_insert(KEY_CACHE *keycache
         DBUG_ASSERT(block->status & (BLOCK_READ | BLOCK_IN_USE));
       } /* end of if (!(block->status & BLOCK_ERROR)) */
 
-
       remove_reader(block);
 
-      /*
-         Link the block into the LRU ring if it's the last submitted
-         request for the block. This enables eviction for the block.
-      */
-      unreg_request(keycache, block, 1);
-
-      error= (block->status & BLOCK_ERROR);
+      /* Error injection for coverage testing. */
+      DBUG_EXECUTE_IF("key_cache_insert_block_error",
+                      block->status|= BLOCK_ERROR; errno=EIO;);
 
-      if (error)
+      /* Do not link erroneous blocks into the LRU ring, but free them. */
+      if (!(block->status & BLOCK_ERROR))
+      {
+        /*
+          Link the block into the LRU ring if it's the last submitted
+          request for the block. This enables eviction for the block.
+        */
+        unreg_request(keycache, block, 1);
+      }
+      else
+      {
+        free_block(keycache, block);
+        error= 1;
         break;
+      }
 
       buff+= read_length;
       filepos+= read_length+offset;
@@ -3206,14 +3242,24 @@ int key_cache_write(KEY_CACHE *keycache,
       */
       remove_reader(block);
 
-      /*
-         Link the block into the LRU ring if it's the last submitted
-         request for the block. This enables eviction for the block.
-      */
-      unreg_request(keycache, block, 1);
+      /* Error injection for coverage testing. */
+      DBUG_EXECUTE_IF("key_cache_write_block_error",
+                      block->status|= BLOCK_ERROR;);
 
-      if (block->status & BLOCK_ERROR)
+      /* Do not link erroneous blocks into the LRU ring, but free them. */
+      if (!(block->status & BLOCK_ERROR))
+      {
+        /*
+          Link the block into the LRU ring if it's the last submitted
+          request for the block. This enables eviction for the block.
+        */
+        unreg_request(keycache, block, 1);
+      }
+      else
       {
+        /* Pretend a "clean" block to avoid complications. */
+        block->status&= ~(BLOCK_CHANGED);
+        free_block(keycache, block);
         error= 1;
         break;
       }
@@ -3288,8 +3334,9 @@ static void free_block(KEY_CACHE *keycac
 {
   KEYCACHE_THREAD_TRACE("free block");
   KEYCACHE_DBUG_PRINT("free_block",
-                      ("block %u to be freed, hash_link %p",
-                       BLOCK_NUMBER(block), block->hash_link));
+                      ("block %u to be freed, hash_link %p  status: %u",
+                       BLOCK_NUMBER(block), block->hash_link,
+                       block->status));
   /*
     Assert that the block is not free already. And that it is in a clean
     state. Note that the block might just be assigned to a hash_link and
@@ -3371,10 +3418,14 @@ static void free_block(KEY_CACHE *keycac
   if (block->status & BLOCK_IN_EVICTION)
     return;
 
-  /* Here the block must be in the LRU ring. Unlink it again. */
-  DBUG_ASSERT(block->next_used && block->prev_used &&
-              *block->prev_used == block);
-  unlink_block(keycache, block);
+  /* Error blocks are not put into the LRU ring. */
+  if (!(block->status & BLOCK_ERROR))
+  {
+    /* Here the block must be in the LRU ring. Unlink it again. */
+    DBUG_ASSERT(block->next_used && block->prev_used &&
+                *block->prev_used == block);
+    unlink_block(keycache, block);
+  }
   if (block->temperature == BLOCK_WARM)
     keycache->warm_blocks--;
   block->temperature= BLOCK_COLD;
@@ -3463,8 +3514,7 @@ static int flush_cached_blocks(KEY_CACHE
                   (BLOCK_READ | BLOCK_IN_FLUSH | BLOCK_CHANGED | BLOCK_IN_USE));
       block->status|= BLOCK_IN_FLUSHWRITE;
       keycache_pthread_mutex_unlock(&keycache->cache_lock);
-      error= my_pwrite(file,
-                       block->buffer+block->offset,
+      error= my_pwrite(file, block->buffer+block->offset,
                        block->length - block->offset,
                        block->hash_link->diskpos+ block->offset,
                        MYF(MY_NABP | MY_WAIT_IF_FULL));
@@ -3491,7 +3541,6 @@ static int flush_cached_blocks(KEY_CACHE
         right queue anyway.
       */
       link_to_file_list(keycache, block, file, 1);
-
     }
     block->status&= ~BLOCK_IN_FLUSH;
     /*
@@ -3527,7 +3576,7 @@ static int flush_cached_blocks(KEY_CACHE
 
 
 /*
-  flush all key blocks for a file to disk, but don't do any mutex locks.
+  Flush all key blocks for a file to disk, but don't do any mutex locks.
 
   SYNOPSIS
     flush_key_blocks_int()
@@ -3693,7 +3742,6 @@ restart:
             {
               /* It's a temporary file */
               DBUG_ASSERT(!(block->status & BLOCK_REASSIGNED));
-
               /*
                 free_block() must not be called with BLOCK_CHANGED. Note
                 that we must not change the BLOCK_CHANGED flag outside of
@@ -4404,8 +4452,8 @@ static void keycache_debug_print(const c
   va_start(args,fmt);
   if (keycache_debug_log)
   {
-    VOID(vfprintf(keycache_debug_log, fmt, args));
-    VOID(fputc('\n',keycache_debug_log));
+    (void) vfprintf(keycache_debug_log, fmt, args);
+    (void) fputc('\n',keycache_debug_log);
   }
   va_end(args);
 }

=== removed file 'mysys/mf_strip.c'
--- a/mysys/mf_strip.c	2007-05-10 09:59:39 +0000
+++ b/mysys/mf_strip.c	1970-01-01 00:00:00 +0000
@@ -1,45 +0,0 @@
-/* Copyright (C) 2000 MySQL AB
-
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; version 2 of the License.
-
-   This program is distributed in the hope that it will be useful,
-   but WITHOUT ANY WARRANTY; without even the implied warranty of
-   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-   GNU General Public License for more details.
-
-   You should have received a copy of the GNU General Public License
-   along with this program; if not, write to the Free Software
-   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
-
-/* T|mmer en str{ng p{ slut_space */
-
-#include "mysys_priv.h"
-
-/*
-	strip_sp(char * str)
-	Strips end-space from string and returns new length.
-*/
-
-size_t strip_sp(register char * str)
-{
-  reg2 char * found;
-  reg3 char * start;
-
-  start=found=str;
-
-  while (*str)
-  {
-    if (*str != ' ')
-    {
-      while (*++str && *str != ' ') {};
-      if (!*str)
-	return (size_t) (str-start);	/* Return stringlength */
-    }
-    found=str;
-    while (*++str == ' ') {};
-  }
-  *found= '\0';				/* Stripp at first space */
-  return (size_t) (found-start);
-} /* strip_sp */

=== modified file 'mysys/my_copy.c'
--- a/mysys/my_copy.c	2009-11-06 17:22:32 +0000
+++ b/mysys/my_copy.c	2009-11-10 15:15:12 +0000
@@ -89,6 +89,13 @@ int my_copy(const char *from, const char
 	goto err;
     }
 
+    /* sync the destination file */
+    if (MyFlags & MY_SYNC)
+    {
+      if (my_sync(to_file, MyFlags))
+        goto err;
+    }
+
     if (my_close(from_file,MyFlags) | my_close(to_file,MyFlags))
       DBUG_RETURN(-1);				/* Error on close */
 

=== modified file 'mysys/my_getopt.c'
--- a/mysys/my_getopt.c	2009-10-15 21:38:29 +0000
+++ b/mysys/my_getopt.c	2009-11-10 15:15:12 +0000
@@ -1017,10 +1017,12 @@ static void init_one_value(const struct 
   case GET_LL:
     *((longlong*) variable)= (longlong) getopt_ll_limit_value((longlong) value, option, NULL);
     break;
-  case GET_ULL: /* Fall through */
-  case GET_SET:
+  case GET_ULL:
     *((ulonglong*) variable)= (ulonglong) getopt_ull_limit_value((ulonglong) value, option, NULL);
     break;
+  case GET_SET:
+    *((ulonglong*) variable)= (ulonglong) value;
+    break;
   case GET_DOUBLE:
     *((double*) variable)=  (double) value;
     break;

=== modified file 'mysys/my_largepage.c'
--- a/mysys/my_largepage.c	2007-10-02 07:32:33 +0000
+++ b/mysys/my_largepage.c	2009-09-18 07:19:02 +0000
@@ -121,7 +121,7 @@ uchar* my_large_malloc_int(size_t size, 
   DBUG_ENTER("my_large_malloc_int");
 
   /* Align block size to my_large_page_size */
-  size = ((size - 1) & ~(my_large_page_size - 1)) + my_large_page_size;
+  size= MY_ALIGN(size, (size_t) my_large_page_size);
   
   shmid = shmget(IPC_PRIVATE, size, SHM_HUGETLB | SHM_R | SHM_W);
   if (shmid < 0)

=== modified file 'mysys/my_static.c'
--- a/mysys/my_static.c	2009-04-25 10:05:32 +0000
+++ b/mysys/my_static.c	2009-11-10 15:15:12 +0000
@@ -104,6 +104,13 @@ static const char *proc_info_dummy(void 
 /* this is to be able to call set_thd_proc_info from the C code */
 const char *(*proc_info_hook)(void *, const char *, const char *, const char *,
                               const unsigned int)= proc_info_dummy;
+#if defined(ENABLED_DEBUG_SYNC)
+/**
+  Global pointer to be set if callback function is defined
+  (e.g. in mysqld). See sql/debug_sync.cc.
+*/
+void (*debug_sync_C_callback_ptr)(const char *, size_t);
+#endif /* defined(ENABLED_DEBUG_SYNC) */
 
 #ifdef __WIN__
 /* from my_getsystime.c */

=== modified file 'mysys/my_thr_init.c'
--- a/mysys/my_thr_init.c	2009-02-19 09:01:25 +0000
+++ b/mysys/my_thr_init.c	2009-11-10 15:15:12 +0000
@@ -134,10 +134,11 @@ my_bool my_thread_global_init(void)
     pthread_attr_t  dummy_thread_attr;
 
     pthread_attr_init(&dummy_thread_attr);
-    pthread_attr_setdetachstate(&dummy_thread_attr, PTHREAD_CREATE_DETACHED);
+    pthread_attr_setdetachstate(&dummy_thread_attr, PTHREAD_CREATE_JOINABLE);
 
-    pthread_create(&dummy_thread,&dummy_thread_attr,
-                   nptl_pthread_exit_hack_handler, NULL);
+    if (pthread_create(&dummy_thread,&dummy_thread_attr,
+                       nptl_pthread_exit_hack_handler, NULL) == 0)
+      (void)pthread_join(dummy_thread, NULL);
   }
 #endif /* TARGET_OS_LINUX */
 

=== modified file 'mysys/my_wincond.c'
--- a/mysys/my_wincond.c	2009-03-22 12:16:09 +0000
+++ b/mysys/my_wincond.c	2009-11-10 15:15:12 +0000
@@ -121,7 +121,6 @@ int pthread_cond_timedwait(pthread_cond_
   LeaveCriticalSection(&cond->lock_waiting);
 
   LeaveCriticalSection(mutex);
-
   result= WaitForMultipleObjects(2, cond->events, FALSE, timeout);
   
   EnterCriticalSection(&cond->lock_waiting);

=== modified file 'mysys/thr_lock.c'
--- a/mysys/thr_lock.c	2009-04-25 09:04:38 +0000
+++ b/mysys/thr_lock.c	2009-11-10 15:15:12 +0000
@@ -420,6 +420,28 @@ wait_for_lock(struct st_lock_list *wait,
   my_bool can_deadlock= test(data->owner->info->n_cursors);
   DBUG_ENTER("wait_for_lock");
 
+  /*
+    One can use this to signal when a thread is going to wait for a lock.
+    See debug_sync.cc.
+
+    Beware of waiting for a signal here. The lock has aquired its mutex.
+    While waiting on a signal here, the locking thread could not aquire
+    the mutex to release the lock. One could lock up the table
+    completely.
+
+    In detail it works so: When thr_lock() tries to acquire a table
+    lock, it locks the lock->mutex, checks if it can have the lock, and
+    if not, it calls wait_for_lock(). Here it unlocks the table lock
+    while waiting on a condition. The sync point is located before this
+    wait for condition. If we have a waiting action here, we hold the
+    the table locks mutex all the time. Any attempt to look at the table
+    lock by another thread blocks it immediately on lock->mutex. This
+    can easily become an unexpected and unobvious blockage. So be
+    warned: Do not request a WAIT_FOR action for the 'wait_for_lock'
+    sync point unless you really know what you do.
+  */
+  DEBUG_SYNC_C("wait_for_lock");
+
   if (!in_wait_list)
   {
     (*wait->last)=data;				/* Wait for lock */

=== modified file 'mysys/typelib.c'
--- a/mysys/typelib.c	2009-10-15 21:38:29 +0000
+++ b/mysys/typelib.c	2009-11-10 15:15:12 +0000
@@ -190,7 +190,10 @@ my_ulonglong find_typeset(char *x, TYPEL
   {
     (*err)++;
     i= x;
-    while (*x && *x != field_separator) x++;
+    while (*x && *x != field_separator)
+      x++;
+    if (x[0] && x[1])                            // skip separator if found
+      x++;
     if ((find= find_type(i, lib, 2 | 8) - 1) < 0)
       DBUG_RETURN(0);
     result|= (ULL(1) << find);

=== modified file 'regex/CMakeLists.txt'
--- a/regex/CMakeLists.txt	2008-05-22 22:25:21 +0000
+++ b/regex/CMakeLists.txt	2009-10-09 07:53:29 +0000
@@ -18,7 +18,7 @@ SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS
 
 INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)
 
-SET(REGEX_SOURCES debug.c regcomp.c regerror.c regexec.c regfree.c reginit.c split.c)
+SET(REGEX_SOURCES regcomp.c regerror.c regexec.c regfree.c reginit.c)
 
 IF(NOT SOURCE_SUBLIBS)
   ADD_LIBRARY(regex ${REGEX_SOURCES})

=== modified file 'scripts/make_win_bin_dist'
--- a/scripts/make_win_bin_dist	2009-10-15 21:52:31 +0000
+++ b/scripts/make_win_bin_dist	2009-11-10 15:15:12 +0000
@@ -350,6 +350,7 @@ fi
 
 mkdir $DESTDIR/mysql-test
 cp mysql-test/mysql-test-run.pl $DESTDIR/mysql-test/
+cp mysql-test/mysql-stress-test.pl $DESTDIR/mysql-test/
 cp mysql-test/README $DESTDIR/mysql-test/
 cp -R mysql-test/{t,r,include,suite,std_data,lib} $DESTDIR/mysql-test/
 

=== modified file 'scripts/mysql_system_tables.sql'
--- a/scripts/mysql_system_tables.sql	2009-05-15 12:57:51 +0000
+++ b/scripts/mysql_system_tables.sql	2009-10-27 10:09:36 +0000
@@ -62,7 +62,7 @@ CREATE TABLE IF NOT EXISTS time_zone_lea
 
 CREATE TABLE IF NOT EXISTS proc (db char(64) collate utf8_bin DEFAULT '' NOT NULL, name char(64) DEFAULT '' NOT NULL, type enum('FUNCTION','PROCEDURE') NOT NULL, specific_name char(64) DEFAULT '' NOT NULL, language enum('SQL') DEFAULT 'SQL' NOT NULL, sql_data_access enum( 'CONTAINS_SQL', 'NO_SQL', 'READS_SQL_DATA', 'MODIFIES_SQL_DATA') DEFAULT 'CONTAINS_SQL' NOT NULL, is_deterministic enum('YES','NO') DEFAULT 'NO' NOT NULL, security_type enum('INVOKER','DEFINER') DEFAULT 'DEFINER' NOT NULL, param_list blob NOT NULL, returns longblob DEFAULT '' NOT NULL, body longblob NOT NULL, definer char(77) collate utf8_bin DEFAULT '' NOT NULL, created timestamp, modified timestamp, sql_mode set( 'REAL_AS_FLOAT', 'PIPES_AS_CONCAT', 'ANSI_QUOTES', 'IGNORE_SPACE', 'NOT_USED', 'ONLY_FULL_GROUP_BY', 'NO_UNSIGNED_SUBTRACTION', 'NO_DIR_IN_CREATE', 'POSTGRESQL', 'ORACLE', 'MSSQL', 'DB2', 'MAXDB', 'NO_KEY_OPTIONS', 'NO_TABLE_OPTIONS', 'NO_FIELD_OPTIONS', 'MYSQL323', 'MYSQL40', 'ANSI', 'NO_AUTO_VALUE_ON_ZERO', 'NO_BACKSLASH_ESCAPES', 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'NO_ZERO_IN_DATE', 'NO_ZERO_DATE', 'INVALID_DATES', 'ERROR_FOR_DIVISION_BY_ZERO', 'TRADITIONAL', 'NO_AUTO_CREATE_USER', 'HIGH_NOT_PRECEDENCE', 'NO_ENGINE_SUBSTITUTION', 'PAD_CHAR_TO_FULL_LENGTH') DEFAULT '' NOT NULL, comment char(64) collate utf8_bin DEFAULT '' NOT NULL, character_set_client char(32) collate utf8_bin, collation_connection char(32) collate utf8_bin, db_collation char(32) collate utf8_bin, body_utf8 longblob, PRIMARY KEY (db,name,type)) engine=MyISAM character set utf8 comment='Stored Procedures';
 
-CREATE TABLE IF NOT EXISTS procs_priv ( Host char(60) binary DEFAULT '' NOT NULL, Db char(64) binary DEFAULT '' NOT NULL, User char(16) binary DEFAULT '' NOT NULL, Routine_name char(64) binary DEFAULT '' NOT NULL, Routine_type enum('FUNCTION','PROCEDURE') NOT NULL, Grantor char(77) DEFAULT '' NOT NULL, Proc_priv set('Execute','Alter Routine','Grant') COLLATE utf8_general_ci DEFAULT '' NOT NULL, Timestamp timestamp(14), PRIMARY KEY (Host,Db,User,Routine_name,Routine_type), KEY Grantor (Grantor) ) engine=MyISAM CHARACTER SET utf8 COLLATE utf8_bin   comment='Procedure privileges';
+CREATE TABLE IF NOT EXISTS procs_priv ( Host char(60) binary DEFAULT '' NOT NULL, Db char(64) binary DEFAULT '' NOT NULL, User char(16) binary DEFAULT '' NOT NULL, Routine_name char(64) COLLATE utf8_general_ci DEFAULT '' NOT NULL, Routine_type enum('FUNCTION','PROCEDURE') NOT NULL, Grantor char(77) DEFAULT '' NOT NULL, Proc_priv set('Execute','Alter Routine','Grant') COLLATE utf8_general_ci DEFAULT '' NOT NULL, Timestamp timestamp(14), PRIMARY KEY (Host,Db,User,Routine_name,Routine_type), KEY Grantor (Grantor) ) engine=MyISAM CHARACTER SET utf8 COLLATE utf8_bin   comment='Procedure privileges';
 
 -- Create general_log if CSV is enabled.
 

=== modified file 'scripts/mysql_system_tables_fix.sql'
--- a/scripts/mysql_system_tables_fix.sql	2009-03-11 20:30:56 +0000
+++ b/scripts/mysql_system_tables_fix.sql	2009-10-27 10:09:36 +0000
@@ -337,6 +337,10 @@ ALTER TABLE procs_priv
   MODIFY Proc_priv set('Execute','Alter Routine','Grant')
     COLLATE utf8_general_ci DEFAULT '' NOT NULL;
 
+ALTER IGNORE TABLE procs_priv
+  MODIFY Routine_name char(64)
+    COLLATE utf8_general_ci DEFAULT '' NOT NULL;
+
 ALTER TABLE procs_priv
   ADD Routine_type enum('FUNCTION','PROCEDURE')
     COLLATE utf8_general_ci NOT NULL AFTER Routine_name;

=== modified file 'sql-common/client.c'
--- a/sql-common/client.c	2009-10-15 21:38:29 +0000
+++ b/sql-common/client.c	2009-11-10 15:15:12 +0000
@@ -389,7 +389,7 @@ HANDLE create_named_pipe(MYSQL *mysql, u
 			    0,
 			    NULL,
 			    OPEN_EXISTING,
-			    0,
+			    FILE_FLAG_OVERLAPPED,
 			    NULL )) != INVALID_HANDLE_VALUE)
       break;
     if (GetLastError() != ERROR_PIPE_BUSY)
@@ -623,7 +623,7 @@ HANDLE create_shared_memory(MYSQL *mysql
 err2:
   if (error_allow == 0)
   {
-    net->vio= vio_new_win32shared_memory(net,handle_file_map,handle_map,
+    net->vio= vio_new_win32shared_memory(handle_file_map,handle_map,
                                          event_server_wrote,
                                          event_server_read,event_client_wrote,
                                          event_client_read,event_conn_closed);
@@ -2033,7 +2033,7 @@ CLI_MYSQL_REAL_CONNECT(MYSQL *mysql,cons
     }
     else
     {
-      net->vio=vio_new_win32pipe(hPipe);
+      net->vio= vio_new_win32pipe(hPipe);
       my_snprintf(host_info=buff, sizeof(buff)-1,
                   ER(CR_NAMEDPIPE_CONNECTION), unix_socket);
     }

=== modified file 'sql-common/my_time.c'
--- a/sql-common/my_time.c	2009-09-01 11:04:56 +0000
+++ b/sql-common/my_time.c	2009-09-17 15:25:52 +0000
@@ -165,7 +165,7 @@ str_to_datetime(const char *str, uint le
   uint add_hours= 0, start_loop;
   ulong not_zero_date, allow_space;
   my_bool is_internal_format;
-  const char *pos, *last_field_pos;
+  const char *pos, *UNINIT_VAR(last_field_pos);
   const char *end=str+length;
   const uchar *format_position;
   my_bool found_delimitier= 0, found_space= 0;
@@ -174,7 +174,6 @@ str_to_datetime(const char *str, uint le
   DBUG_PRINT("ENTER",("str: %.*s",length,str));
 
   LINT_INIT(field_length);
-  LINT_INIT(last_field_pos);
 
   *was_cut= 0;
 

=== modified file 'sql/CMakeLists.txt'
--- a/sql/CMakeLists.txt	2009-09-15 10:46:35 +0000
+++ b/sql/CMakeLists.txt	2009-11-10 15:15:12 +0000
@@ -65,6 +65,7 @@ SET (SQL_SOURCE
                sql_error.cc sql_handler.cc sql_help.cc sql_insert.cc sql_lex.cc 
                sql_list.cc sql_load.cc sql_manager.cc sql_map.cc sql_parse.cc 
                sql_partition.cc sql_plugin.cc sql_prepare.cc sql_rename.cc 
+               debug_sync.cc debug_sync.h
                sql_repl.cc sql_select.cc sql_show.cc sql_state.c sql_string.cc 
                sql_table.cc sql_test.cc sql_trigger.cc sql_udf.cc sql_union.cc
                sql_update.cc sql_view.cc strfunc.cc table.cc thr_malloc.cc 

=== modified file 'sql/Makefile.am'
--- a/sql/Makefile.am	2009-09-15 10:46:35 +0000
+++ b/sql/Makefile.am	2009-11-10 15:15:12 +0000
@@ -59,6 +59,7 @@ noinst_HEADERS =	item.h item_func.h item
 			ha_ndbcluster.h ha_ndbcluster_cond.h \
 			ha_ndbcluster_binlog.h ha_ndbcluster_tables.h \
 			ha_partition.h rpl_constants.h \
+			debug_sync.h \
 			opt_range.h protocol.h rpl_tblmap.h rpl_utility.h \
 			rpl_reporting.h \
 			log.h log_slow.h sql_show.h rpl_rli.h rpl_mi.h \
@@ -103,6 +104,7 @@ mysqld_SOURCES =	sql_lex.cc sql_handler.
 			discover.cc time.cc opt_range.cc opt_sum.cc \
 		   	records.cc filesort.cc handler.cc \
 		        ha_partition.cc \
+			debug_sync.cc \
 			sql_db.cc sql_table.cc sql_rename.cc sql_crypt.cc \
 			sql_load.cc mf_iocache.cc field_conv.cc sql_show.cc \
 			sql_udf.cc sql_analyse.cc sql_analyse.h sql_cache.cc \

=== added file 'sql/debug_sync.cc'
--- a/sql/debug_sync.cc	1970-01-01 00:00:00 +0000
+++ b/sql/debug_sync.cc	2009-10-04 09:53:02 +0000
@@ -0,0 +1,1906 @@
+/* Copyright (C) 2008 MySQL AB, 2008 - 2009 Sun Microsystems, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; version 2 of the License.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
+
+/**
+  == Debug Sync Facility ==
+
+  The Debug Sync Facility allows placement of synchronization points in
+  the server code by using the DEBUG_SYNC macro:
+
+      open_tables(...)
+
+      DEBUG_SYNC(thd, "after_open_tables");
+
+      lock_tables(...)
+
+  When activated, a sync point can
+
+    - Emit a signal and/or
+    - Wait for a signal
+
+  Nomenclature:
+
+    - signal:             A value of a global variable that persists
+                          until overwritten by a new signal. The global
+                          variable can also be seen as a "signal post"
+                          or "flag mast". Then the signal is what is
+                          attached to the "signal post" or "flag mast".
+
+    - emit a signal:      Assign the value (the signal) to the global
+                          variable ("set a flag") and broadcast a
+                          global condition to wake those waiting for
+                          a signal.
+
+    - wait for a signal:  Loop over waiting for the global condition until
+                          the global value matches the wait-for signal.
+
+  By default, all sync points are inactive. They do nothing (except to
+  burn a couple of CPU cycles for checking if they are active).
+
+  A sync point becomes active when an action is requested for it.
+  To do so, put a line like this in the test case file:
+
+      SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed';
+
+  This activates the sync point 'after_open_tables'. It requests it to
+  emit the signal 'opened' and wait for another thread to emit the signal
+  'flushed' when the thread's execution runs through the sync point.
+
+  For every sync point there can be one action per thread only. Every
+  thread can request multiple actions, but only one per sync point. In
+  other words, a thread can activate multiple sync points.
+
+  Here is an example how to activate and use the sync points:
+
+      --connection conn1
+      SET DEBUG_SYNC= 'after_open_tables SIGNAL opened WAIT_FOR flushed';
+      send INSERT INTO t1 VALUES(1);
+          --connection conn2
+          SET DEBUG_SYNC= 'now WAIT_FOR opened';
+          SET DEBUG_SYNC= 'after_abort_locks SIGNAL flushed';
+          FLUSH TABLE t1;
+
+  When conn1 runs through the INSERT statement, it hits the sync point
+  'after_open_tables'. It notices that it is active and executes its
+  action. It emits the signal 'opened' and waits for another thread to
+  emit the signal 'flushed'.
+
+  conn2 waits immediately at the special sync point 'now' for another
+  thread to emit the 'opened' signal.
+
+  A signal remains in effect until it is overwritten. If conn1 signals
+  'opened' before conn2 reaches 'now', conn2 will still find the 'opened'
+  signal. It does not wait in this case.
+
+  When conn2 reaches 'after_abort_locks', it signals 'flushed', which lets
+  conn1 awake.
+
+  Normally the activation of a sync point is cleared when it has been
+  executed. Sometimes it is necessary to keep the sync point active for
+  another execution. You can add an execute count to the action:
+
+      SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 3';
+
+  This sets the signal point's activation counter to 3. Each execution
+  decrements the counter. After the third execution the sync point
+  becomes inactive.
+
+  One of the primary goals of this facility is to eliminate sleeps from
+  the test suite. In most cases it should be possible to rewrite test
+  cases so that they do not need to sleep. (But this facility cannot
+  synchronize multiple processes.) However, to support test development,
+  and as a last resort, sync point waiting times out. There is a default
+  timeout, but it can be overridden:
+
+      SET DEBUG_SYNC= 'name WAIT_FOR sig TIMEOUT 10 EXECUTE 2';
+
+  TIMEOUT 0 is special: If the signal is not present, the wait times out
+  immediately.
+
+  When a wait timed out (even on TIMEOUT 0), a warning is generated so
+  that it shows up in the test result.
+
+  You can throw an error message and kill the query when a synchronization
+  point is hit a certain number of times:
+
+      SET DEBUG_SYNC= 'name HIT_LIMIT 3';
+
+  Or combine it with signal and/or wait:
+
+      SET DEBUG_SYNC= 'name SIGNAL sig EXECUTE 2 HIT_LIMIT 3';
+
+  Here the first two hits emit the signal, the third hit returns the error
+  message and kills the query.
+
+  For cases where you are not sure that an action is taken and thus
+  cleared in any case, you can force to clear (deactivate) a sync point:
+
+      SET DEBUG_SYNC= 'name CLEAR';
+
+  If you want to clear all actions and clear the global signal, use:
+
+      SET DEBUG_SYNC= 'RESET';
+
+  This is the only way to reset the global signal to an empty string.
+
+  For testing of the facility itself you can execute a sync point just
+  as if it had been hit:
+
+      SET DEBUG_SYNC= 'name TEST';
+
+
+  === Formal Syntax ===
+
+  The string to "assign" to the DEBUG_SYNC variable can contain:
+
+      {RESET |
+       <sync point name> TEST |
+       <sync point name> CLEAR |
+       <sync point name> {{SIGNAL <signal name> |
+                           WAIT_FOR <signal name> [TIMEOUT <seconds>]}
+                          [EXECUTE <count>] &| HIT_LIMIT <count>}
+
+  Here '&|' means 'and/or'. This means that one of the sections
+  separated by '&|' must be present or both of them.
+
+
+  === Activation/Deactivation ===
+
+  The facility is an optional part of the MySQL server.
+  It is enabled in a debug server by default.
+
+      ./configure --enable-debug-sync
+
+  The Debug Sync Facility, when compiled in, is disabled by default. It
+  can be enabled by a mysqld command line option:
+
+      --debug-sync-timeout[=default_wait_timeout_value_in_seconds]
+
+  'default_wait_timeout_value_in_seconds' is the default timeout for the
+  WAIT_FOR action. If set to zero, the facility stays disabled.
+
+  The facility is enabled by default in the test suite, but can be
+  disabled with:
+
+      mysql-test-run.pl ... --debug-sync-timeout=0 ...
+
+  Likewise the default wait timeout can be set:
+
+      mysql-test-run.pl ... --debug-sync-timeout=10 ...
+
+  The command line option influences the readable value of the system
+  variable 'debug_sync'.
+
+  * If the facility is not compiled in, the system variable does not exist.
+
+  * If --debug-sync-timeout=0 the value of the variable reads as "OFF".
+
+  * Otherwise the value reads as "ON - current signal: " followed by the
+    current signal string, which can be empty.
+
+  The readable variable value is the same, regardless if read as global
+  or session value.
+
+  Setting the 'debug-sync' system variable requires 'SUPER' privilege.
+  You can never read back the string that you assigned to the variable,
+  unless you assign the value that the variable does already have. But
+  that would give a parse error. A syntactically correct string is
+  parsed into a debug sync action and stored apart from the variable value.
+
+
+  === Implementation ===
+
+  Pseudo code for a sync point:
+
+      #define DEBUG_SYNC(thd, sync_point_name)
+                if (unlikely(opt_debug_sync_timeout))
+                  debug_sync(thd, STRING_WITH_LEN(sync_point_name))
+
+  The sync point performs a binary search in a sorted array of actions
+  for this thread.
+
+  The SET DEBUG_SYNC statement adds a requested action to the array or
+  overwrites an existing action for the same sync point. When it adds a
+  new action, the array is sorted again.
+
+
+  === A typical synchronization pattern ===
+
+  There are quite a few places in MySQL, where we use a synchronization
+  pattern like this:
+
+  pthread_mutex_lock(&mutex);
+  thd->enter_cond(&condition_variable, &mutex, new_message);
+  #if defined(ENABLE_DEBUG_SYNC)
+  if (!thd->killed && !end_of_wait_condition)
+     DEBUG_SYNC(thd, "sync_point_name");
+  #endif
+  while (!thd->killed && !end_of_wait_condition)
+    pthread_cond_wait(&condition_variable, &mutex);
+  thd->exit_cond(old_message);
+
+  Here some explanations:
+
+  thd->enter_cond() is used to register the condition variable and the
+  mutex in thd->mysys_var. This is done to allow the thread to be
+  interrupted (killed) from its sleep. Another thread can find the
+  condition variable to signal and mutex to use for synchronization in
+  this thread's THD::mysys_var.
+
+  thd->enter_cond() requires the mutex to be acquired in advance.
+
+  thd->exit_cond() unregisters the condition variable and mutex and
+  releases the mutex.
+
+  If you want to have a Debug Sync point with the wait, please place it
+  behind enter_cond(). Only then you can safely decide, if the wait will
+  be taken. Also you will have THD::proc_info correct when the sync
+  point emits a signal. DEBUG_SYNC sets its own proc_info, but restores
+  the previous one before releasing its internal mutex. As soon as
+  another thread sees the signal, it does also see the proc_info from
+  before entering the sync point. In this case it will be "new_message",
+  which is associated with the wait that is to be synchronized.
+
+  In the example above, the wait condition is repeated before the sync
+  point. This is done to skip the sync point, if no wait takes place.
+  The sync point is before the loop (not inside the loop) to have it hit
+  once only. It is possible that the condition variable is signaled
+  multiple times without the wait condition to be true.
+
+  A bit off-topic: At some places, the loop is taken around the whole
+  synchronization pattern:
+
+  while (!thd->killed && !end_of_wait_condition)
+  {
+    pthread_mutex_lock(&mutex);
+    thd->enter_cond(&condition_variable, &mutex, new_message);
+    if (!thd->killed [&& !end_of_wait_condition])
+    {
+      [DEBUG_SYNC(thd, "sync_point_name");]
+      pthread_cond_wait(&condition_variable, &mutex);
+    }
+    thd->exit_cond(old_message);
+  }
+
+  Note that it is important to repeat the test for thd->killed after
+  enter_cond(). Otherwise the killing thread may kill this thread after
+  it tested thd->killed in the loop condition and before it registered
+  the condition variable and mutex in enter_cond(). In this case, the
+  killing thread does not know that this thread is going to wait on a
+  condition variable. It would just set THD::killed. But if we would not
+  test it again, we would go asleep though we are killed. If the killing
+  thread would kill us when we are after the second test, but still
+  before sleeping, we hold the mutex, which is registered in mysys_var.
+  The killing thread would try to acquire the mutex before signaling
+  the condition variable. Since the mutex is only released implicitly in
+  pthread_cond_wait(), the signaling happens at the right place. We
+  have a safe synchronization.
+
+  === Co-work with the DBUG facility ===
+
+  When running the MySQL test suite with the --debug command line
+  option, the Debug Sync Facility writes trace messages to the DBUG
+  trace. The following shell commands proved very useful in extracting
+  relevant information:
+
+  egrep 'query:|debug_sync_exec:' mysql-test/var/log/mysqld.1.trace
+
+  It shows all executed SQL statements and all actions executed by
+  synchronization points.
+
+  Sometimes it is also useful to see, which synchronization points have
+  been run through (hit) with or without executing actions. Then add
+  "|debug_sync_point:" to the egrep pattern.
+
+  === Further reading ===
+
+  For a discussion of other methods to synchronize threads see
+  http://forge.mysql.com/wiki/MySQL_Internals_Test_Synchronization
+
+  For complete syntax tests, functional tests, and examples see the test
+  case debug_sync.test.
+
+  See also worklog entry WL#4259 - Test Synchronization Facility
+*/
+
+#include "debug_sync.h"
+
+#if defined(ENABLED_DEBUG_SYNC)
+
+/*
+  Due to weaknesses in our include files, we need to include
+  mysql_priv.h here. To have THD declared, we need to include
+  sql_class.h. This includes log_event.h, which in turn requires
+  declarations from mysql_priv.h (e.g. OPTION_AUTO_IS_NULL).
+  mysql_priv.h includes almost everything, so is sufficient here.
+*/
+#include "mysql_priv.h"
+
+/*
+  Action to perform at a synchronization point.
+  NOTE: This structure is moved around in memory by realloc(), qsort(),
+        and memmove(). Do not add objects with non-trivial constuctors
+        or destructors, which might prevent moving of this structure
+        with these functions.
+*/
+struct st_debug_sync_action
+{
+  ulong         activation_count;       /* max(hit_limit, execute) */
+  ulong         hit_limit;              /* hits before kill query */
+  ulong         execute;                /* executes before self-clear */
+  ulong         timeout;                /* wait_for timeout */
+  String        signal;                 /* signal to emit */
+  String        wait_for;               /* signal to wait for */
+  String        sync_point;             /* sync point name */
+  bool          need_sort;              /* if new action, array needs sort */
+};
+
+/* Debug sync control. Referenced by THD. */
+struct st_debug_sync_control
+{
+  st_debug_sync_action  *ds_action;             /* array of actions */
+  uint                  ds_active;              /* # active actions */
+  uint                  ds_allocated;           /* # allocated actions */
+  ulonglong             dsp_hits;               /* statistics */
+  ulonglong             dsp_executed;           /* statistics */
+  ulonglong             dsp_max_active;         /* statistics */
+  /*
+    thd->proc_info points at unsynchronized memory.
+    It must not go away as long as the thread exists.
+  */
+  char                  ds_proc_info[80];       /* proc_info string */
+};
+
+
+/**
+  Definitions for the debug sync facility.
+  1. Global string variable to hold a "signal" ("signal post", "flag mast").
+  2. Global condition variable for signaling and waiting.
+  3. Global mutex to synchronize access to the above.
+*/
+struct st_debug_sync_globals
+{
+  String                ds_signal;              /* signal variable */
+  pthread_cond_t        ds_cond;                /* condition variable */
+  pthread_mutex_t       ds_mutex;               /* mutex variable */
+  ulonglong             dsp_hits;               /* statistics */
+  ulonglong             dsp_executed;           /* statistics */
+  ulonglong             dsp_max_active;         /* statistics */
+};
+static st_debug_sync_globals debug_sync_global; /* All globals in one object */
+
+/**
+  Callback pointer for C files.
+*/
+extern "C" void (*debug_sync_C_callback_ptr)(const char *, size_t);
+
+
+/**
+  Callback for debug sync, to be used by C files. See thr_lock.c for example.
+
+  @description
+
+    We cannot place a sync point directly in C files (like those in mysys or
+    certain storage engines written mostly in C like MyISAM or Maria). Because
+    they are C code and do not include mysql_priv.h. So they do not know the
+    macro DEBUG_SYNC(thd, sync_point_name). The macro needs a 'thd' argument.
+    Hence it cannot be used in files outside of the sql/ directory.
+
+    The workaround is to call back simple functions like this one from
+    non-sql/ files.
+
+    We want to allow modules like thr_lock to be used without sql/ and
+    especially without Debug Sync. So we cannot just do a simple call
+    of the callback function. Instead we provide a global pointer in
+    the other file, which is to be set to the callback by Debug Sync.
+    If the pointer is not set, no call back will be done. If Debug
+    Sync sets the pointer to a callback function like this one, it will
+    be called. That way thr_lock.c does not have an undefined reference
+    to Debug Sync and can be used without it. Debug Sync, in contrast,
+    has an undefined reference to that pointer and thus requires
+    thr_lock to be linked too. But this is not a problem as it is part
+    of the MySQL server anyway.
+
+  @note
+    The callback pointer in C files is set only if debug sync is
+    initialized. And this is done only if opt_debug_sync_timeout is set.
+*/
+
+static void debug_sync_C_callback(const char *sync_point_name,
+                                  size_t name_len)
+{
+  if (unlikely(opt_debug_sync_timeout))                            
+    debug_sync(current_thd, sync_point_name, name_len);   
+}
+
+
+/**
+  Initialize the debug sync facility at server start.
+
+  @return status
+    @retval     0       ok
+    @retval     != 0    error
+*/
+
+int debug_sync_init(void)
+{
+  DBUG_ENTER("debug_sync_init");
+
+  if (opt_debug_sync_timeout)
+  {
+    int rc;
+
+    /* Initialize the global variables. */
+    debug_sync_global.ds_signal.length(0);
+    if ((rc= pthread_cond_init(&debug_sync_global.ds_cond, NULL)) ||
+        (rc= pthread_mutex_init(&debug_sync_global.ds_mutex,
+                                MY_MUTEX_INIT_FAST)))
+      DBUG_RETURN(rc); /* purecov: inspected */
+
+    /* Set the call back pointer in C files. */
+    debug_sync_C_callback_ptr= debug_sync_C_callback;
+  }
+
+  DBUG_RETURN(0);
+}
+
+
+/**
+  End the debug sync facility.
+
+  @description
+    This is called at server shutdown or after a thread initialization error.
+*/
+
+void debug_sync_end(void)
+{
+  DBUG_ENTER("debug_sync_end");
+
+  /* End the facility only if it had been initialized. */
+  if (debug_sync_C_callback_ptr)
+  {
+    /* Clear the call back pointer in C files. */
+    debug_sync_C_callback_ptr= NULL;
+
+    /* Destroy the global variables. */
+    debug_sync_global.ds_signal.free();
+    (void) pthread_cond_destroy(&debug_sync_global.ds_cond);
+    (void) pthread_mutex_destroy(&debug_sync_global.ds_mutex);
+
+    /* Print statistics. */
+    {
+      char llbuff[22];
+      sql_print_information("Debug sync points hit:                   %22s",
+                            llstr(debug_sync_global.dsp_hits, llbuff));
+      sql_print_information("Debug sync points executed:              %22s",
+                            llstr(debug_sync_global.dsp_executed, llbuff));
+      sql_print_information("Debug sync points max active per thread: %22s",
+                            llstr(debug_sync_global.dsp_max_active, llbuff));
+    }
+  }
+
+  DBUG_VOID_RETURN;
+}
+
+
+/* purecov: begin tested */
+
+/**
+  Disable the facility after lack of memory if no error can be returned.
+
+  @note
+    Do not end the facility here because the global variables can
+    be in use by other threads.
+*/
+
+static void debug_sync_emergency_disable(void)
+{
+  DBUG_ENTER("debug_sync_emergency_disable");
+
+  opt_debug_sync_timeout= 0;
+
+  DBUG_PRINT("debug_sync",
+             ("Debug Sync Facility disabled due to lack of memory."));
+  sql_print_error("Debug Sync Facility disabled due to lack of memory.");
+
+  DBUG_VOID_RETURN;
+}
+
+/* purecov: end */
+
+
+/**
+  Initialize the debug sync facility at thread start.
+
+  @param[in]    thd             thread handle
+*/
+
+void debug_sync_init_thread(THD *thd)
+{
+  DBUG_ENTER("debug_sync_init_thread");
+  DBUG_ASSERT(thd);
+
+  if (opt_debug_sync_timeout)
+  {
+    thd->debug_sync_control= (st_debug_sync_control*)
+      my_malloc(sizeof(st_debug_sync_control), MYF(MY_WME | MY_ZEROFILL));
+    if (!thd->debug_sync_control)
+    {
+      /*
+        Error is reported by my_malloc().
+        We must disable the facility. We have no way to return an error.
+      */
+      debug_sync_emergency_disable(); /* purecov: tested */
+    }
+  }
+
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  End the debug sync facility at thread end.
+
+  @param[in]    thd             thread handle
+*/
+
+void debug_sync_end_thread(THD *thd)
+{
+  DBUG_ENTER("debug_sync_end_thread");
+  DBUG_ASSERT(thd);
+
+  if (thd->debug_sync_control)
+  {
+    st_debug_sync_control *ds_control= thd->debug_sync_control;
+
+    /*
+      This synchronization point can be used to synchronize on thread end.
+      This is the latest point in a THD's life, where this can be done.
+    */
+    DEBUG_SYNC(thd, "thread_end");
+
+    if (ds_control->ds_action)
+    {
+      st_debug_sync_action *action= ds_control->ds_action;
+      st_debug_sync_action *action_end= action + ds_control->ds_allocated;
+      for (; action < action_end; action++)
+      {
+        action->signal.free();
+        action->wait_for.free();
+        action->sync_point.free();
+      }
+      my_free(ds_control->ds_action, MYF(0));
+    }
+
+    /* Statistics. */
+    pthread_mutex_lock(&debug_sync_global.ds_mutex);
+    debug_sync_global.dsp_hits+=           ds_control->dsp_hits;
+    debug_sync_global.dsp_executed+=       ds_control->dsp_executed;
+    if (debug_sync_global.dsp_max_active < ds_control->dsp_max_active)
+      debug_sync_global.dsp_max_active=    ds_control->dsp_max_active;
+    pthread_mutex_unlock(&debug_sync_global.ds_mutex);
+
+    my_free(ds_control, MYF(0));
+    thd->debug_sync_control= NULL;
+  }
+
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Move a string by length.
+
+  @param[out]   to              buffer for the resulting string
+  @param[in]    to_end          end of buffer
+  @param[in]    from            source string
+  @param[in]    length          number of bytes to copy
+
+  @return       pointer to end of copied string
+*/
+
+static char *debug_sync_bmove_len(char *to, char *to_end,
+                                  const char *from, size_t length)
+{
+  DBUG_ASSERT(to);
+  DBUG_ASSERT(to_end);
+  DBUG_ASSERT(!length || from);
+  set_if_smaller(length, (size_t) (to_end - to));
+  memcpy(to, from, length);
+  return (to + length);
+}
+
+
+#if !defined(DBUG_OFF)
+
+/**
+  Create a string that describes an action.
+
+  @param[out]   result          buffer for the resulting string
+  @param[in]    size            size of result buffer
+  @param[in]    action          action to describe
+*/
+
+static void debug_sync_action_string(char *result, uint size,
+                                     st_debug_sync_action *action)
+{
+  char  *wtxt= result;
+  char  *wend= wtxt + size - 1; /* Allow emergency '\0'. */
+  DBUG_ASSERT(result);
+  DBUG_ASSERT(action);
+
+  /* If an execute count is present, signal or wait_for are needed too. */
+  DBUG_ASSERT(!action->execute ||
+              action->signal.length() || action->wait_for.length());
+
+  if (action->execute)
+  {
+    if (action->signal.length())
+    {
+      wtxt= debug_sync_bmove_len(wtxt, wend, STRING_WITH_LEN("SIGNAL "));
+      wtxt= debug_sync_bmove_len(wtxt, wend, action->signal.ptr(),
+                                 action->signal.length());
+    }
+    if (action->wait_for.length())
+    {
+      if ((wtxt == result) && (wtxt < wend))
+        *(wtxt++)= ' ';
+      wtxt= debug_sync_bmove_len(wtxt, wend, STRING_WITH_LEN(" WAIT_FOR "));
+      wtxt= debug_sync_bmove_len(wtxt, wend, action->wait_for.ptr(),
+                                 action->wait_for.length());
+
+      if (action->timeout != opt_debug_sync_timeout)
+      {
+        wtxt+= my_snprintf(wtxt, wend - wtxt, " TIMEOUT %lu", action->timeout);
+      }
+    }
+    if (action->execute != 1)
+    {
+      wtxt+= my_snprintf(wtxt, wend - wtxt, " EXECUTE %lu", action->execute);
+    }
+  }
+  if (action->hit_limit)
+  {
+    wtxt+= my_snprintf(wtxt, wend - wtxt, "%sHIT_LIMIT %lu",
+                       (wtxt == result) ? "" : " ", action->hit_limit);
+  }
+
+  /*
+    If (wtxt == wend) string may not be terminated.
+    There is one byte left for an emergency termination.
+  */
+  *wtxt= '\0';
+}
+
+
+/**
+  Print actions.
+
+  @param[in]    thd             thread handle
+*/
+
+static void debug_sync_print_actions(THD *thd)
+{
+  st_debug_sync_control *ds_control= thd->debug_sync_control;
+  uint                  idx;
+  DBUG_ENTER("debug_sync_print_actions");
+  DBUG_ASSERT(thd);
+
+  if (!ds_control)
+    DBUG_VOID_RETURN;
+
+  for (idx= 0; idx < ds_control->ds_active; idx++)
+  {
+    const char *dsp_name= ds_control->ds_action[idx].sync_point.c_ptr();
+    char action_string[256];
+
+    debug_sync_action_string(action_string, sizeof(action_string),
+                             ds_control->ds_action + idx);
+    DBUG_PRINT("debug_sync_list", ("%s %s", dsp_name, action_string));
+  }
+
+  DBUG_VOID_RETURN;
+}
+
+#endif /* !defined(DBUG_OFF) */
+
+
+/**
+  Compare two actions by sync point name length, string.
+
+  @param[in]    arg1            reference to action1
+  @param[in]    arg2            reference to action2
+
+  @return       difference
+    @retval     == 0            length1/string1 is same as length2/string2
+    @retval     < 0             length1/string1 is smaller
+    @retval     > 0             length1/string1 is bigger
+*/
+
+static int debug_sync_qsort_cmp(const void* arg1, const void* arg2)
+{
+  st_debug_sync_action *action1= (st_debug_sync_action*) arg1;
+  st_debug_sync_action *action2= (st_debug_sync_action*) arg2;
+  int diff;
+  DBUG_ASSERT(action1);
+  DBUG_ASSERT(action2);
+
+  if (!(diff= action1->sync_point.length() - action2->sync_point.length()))
+    diff= memcmp(action1->sync_point.ptr(), action2->sync_point.ptr(),
+                 action1->sync_point.length());
+
+  return diff;
+}
+
+
+/**
+  Find a debug sync action.
+
+  @param[in]    actionarr       array of debug sync actions
+  @param[in]    quantity        number of actions in array
+  @param[in]    dsp_name        name of debug sync point to find
+  @param[in]    name_len        length of name of debug sync point
+
+  @return       action
+    @retval     != NULL         found sync point in array
+    @retval     NULL            not found
+
+  @description
+    Binary search. Array needs to be sorted by length, sync point name.
+*/
+
+static st_debug_sync_action *debug_sync_find(st_debug_sync_action *actionarr,
+                                             int quantity,
+                                             const char *dsp_name,
+                                             uint name_len)
+{
+  st_debug_sync_action  *action;
+  int                   low ;
+  int                   high ;
+  int                   mid ;
+  int                   diff ;
+  DBUG_ASSERT(actionarr);
+  DBUG_ASSERT(dsp_name);
+  DBUG_ASSERT(name_len);
+
+  low= 0;
+  high= quantity;
+
+  while (low < high)
+  {
+    mid= (low + high) / 2;
+    action= actionarr + mid;
+    if (!(diff= name_len - action->sync_point.length()) &&
+        !(diff= memcmp(dsp_name, action->sync_point.ptr(), name_len)))
+      return action;
+    if (diff > 0)
+      low= mid + 1;
+    else
+      high= mid - 1;
+  }
+
+  if (low < quantity)
+  {
+    action= actionarr + low;
+    if ((name_len == action->sync_point.length()) &&
+        !memcmp(dsp_name, action->sync_point.ptr(), name_len))
+      return action;
+  }
+
+  return NULL;
+}
+
+
+/**
+  Reset the debug sync facility.
+
+  @param[in]    thd             thread handle
+
+  @description
+    Remove all actions of this thread.
+    Clear the global signal.
+*/
+
+static void debug_sync_reset(THD *thd)
+{
+  st_debug_sync_control *ds_control= thd->debug_sync_control;
+  DBUG_ENTER("debug_sync_reset");
+  DBUG_ASSERT(thd);
+  DBUG_ASSERT(ds_control);
+
+  /* Remove all actions of this thread. */
+  ds_control->ds_active= 0;
+
+  /* Clear the global signal. */
+  pthread_mutex_lock(&debug_sync_global.ds_mutex);
+  debug_sync_global.ds_signal.length(0);
+  pthread_mutex_unlock(&debug_sync_global.ds_mutex);
+
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Remove a debug sync action.
+
+  @param[in]    ds_control      control object
+  @param[in]    action          action to be removed
+
+  @description
+    Removing an action mainly means to decrement the ds_active counter.
+    But if the action is between other active action in the array, then
+    the array needs to be shrinked. The active actions above the one to
+    be removed have to be moved down by one slot.
+*/
+
+static void debug_sync_remove_action(st_debug_sync_control *ds_control,
+                                     st_debug_sync_action *action)
+{
+  uint dsp_idx= action - ds_control->ds_action;
+  DBUG_ENTER("debug_sync_remove_action");
+  DBUG_ASSERT(ds_control);
+  DBUG_ASSERT(ds_control == current_thd->debug_sync_control);
+  DBUG_ASSERT(action);
+  DBUG_ASSERT(dsp_idx < ds_control->ds_active);
+
+  /* Decrement the number of currently active actions. */
+  ds_control->ds_active--;
+
+  /*
+    If this was not the last active action in the array, we need to
+    shift remaining active actions down to keep the array gap-free.
+    Otherwise binary search might fail or take longer than necessary at
+    least. Also new actions are always put to the end of the array.
+  */
+  if (ds_control->ds_active > dsp_idx)
+  {
+    /*
+      Do not make save_action an object of class st_debug_sync_action.
+      Its destructor would tamper with the String pointers.
+    */
+    uchar save_action[sizeof(st_debug_sync_action)];
+
+    /*
+      Copy the to-be-removed action object to temporary storage before
+      the shift copies the string pointers over. Do not use assignment
+      because it would use assignment operator methods for the Strings.
+      This would copy the strings. The shift below overwrite the string
+      pointers without freeing them first. By using memmove() we save
+      the pointers, which are overwritten by the shift.
+    */
+    memmove(save_action, action, sizeof(st_debug_sync_action));
+
+    /* Move actions down. */
+    memmove(ds_control->ds_action + dsp_idx,
+            ds_control->ds_action + dsp_idx + 1,
+            (ds_control->ds_active - dsp_idx) *
+            sizeof(st_debug_sync_action));
+
+    /*
+      Copy back the saved action object to the now free array slot. This
+      replaces the double references of String pointers that have been
+      produced by the shift. Again do not use an assignment operator to
+      avoid string allocation/copy.
+    */
+    memmove(ds_control->ds_action + ds_control->ds_active, save_action,
+            sizeof(st_debug_sync_action));
+  }
+
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Get a debug sync action.
+
+  @param[in]    thd             thread handle
+  @param[in]    dsp_name        debug sync point name
+  @param[in]    name_len        length of sync point name
+
+  @return       action
+    @retval     != NULL         ok
+    @retval     NULL            error
+
+  @description
+    Find the debug sync action for a debug sync point or make a new one.
+*/
+
+static st_debug_sync_action *debug_sync_get_action(THD *thd,
+                                                   const char *dsp_name,
+                                                   uint name_len)
+{
+  st_debug_sync_control *ds_control= thd->debug_sync_control;
+  st_debug_sync_action  *action;
+  DBUG_ENTER("debug_sync_get_action");
+  DBUG_ASSERT(thd);
+  DBUG_ASSERT(dsp_name);
+  DBUG_ASSERT(name_len);
+  DBUG_ASSERT(ds_control);
+  DBUG_PRINT("debug_sync", ("sync_point: '%.*s'", (int) name_len, dsp_name));
+  DBUG_PRINT("debug_sync", ("active: %u  allocated: %u",
+                            ds_control->ds_active, ds_control->ds_allocated));
+
+  /* There cannot be more active actions than allocated. */
+  DBUG_ASSERT(ds_control->ds_active <= ds_control->ds_allocated);
+  /* If there are active actions, the action array must be present. */
+  DBUG_ASSERT(!ds_control->ds_active || ds_control->ds_action);
+
+  /* Try to reuse existing action if there is one for this sync point. */
+  if (ds_control->ds_active &&
+      (action= debug_sync_find(ds_control->ds_action, ds_control->ds_active,
+                               dsp_name, name_len)))
+  {
+    /* Reuse an already active sync point action. */
+    DBUG_ASSERT((uint)(action - ds_control->ds_action) < ds_control->ds_active);
+    DBUG_PRINT("debug_sync", ("reuse action idx: %ld",
+                              (long) (action - ds_control->ds_action)));
+  }
+  else
+  {
+    /* Create a new action. */
+    int dsp_idx= ds_control->ds_active++;
+    set_if_bigger(ds_control->dsp_max_active, ds_control->ds_active);
+    if (ds_control->ds_active > ds_control->ds_allocated)
+    {
+      uint new_alloc= ds_control->ds_active + 3;
+      void *new_action= my_realloc(ds_control->ds_action,
+                                   new_alloc * sizeof(st_debug_sync_action),
+                                   MYF(MY_WME | MY_ALLOW_ZERO_PTR));
+      if (!new_action)
+      {
+        /* Error is reported by my_malloc(). */
+        goto err; /* purecov: tested */
+      }
+      ds_control->ds_action= (st_debug_sync_action*) new_action;
+      ds_control->ds_allocated= new_alloc;
+      /* Clear memory as we do not run string constructors here. */
+      bzero((uchar*) (ds_control->ds_action + dsp_idx),
+            (new_alloc - dsp_idx) * sizeof(st_debug_sync_action));
+    }
+    DBUG_PRINT("debug_sync", ("added action idx: %u", dsp_idx));
+    action= ds_control->ds_action + dsp_idx;
+    if (action->sync_point.copy(dsp_name, name_len, system_charset_info))
+    {
+      /* Error is reported by my_malloc(). */
+      goto err; /* purecov: tested */
+    }
+    action->need_sort= TRUE;
+  }
+  DBUG_ASSERT(action >= ds_control->ds_action);
+  DBUG_ASSERT(action < ds_control->ds_action + ds_control->ds_active);
+  DBUG_PRINT("debug_sync", ("action: 0x%lx  array: 0x%lx  count: %u",
+                            (long) action, (long) ds_control->ds_action,
+                            ds_control->ds_active));
+
+  DBUG_RETURN(action);
+
+  /* purecov: begin tested */
+ err:
+  DBUG_RETURN(NULL);
+  /* purecov: end */
+}
+
+
+/**
+  Set a debug sync action.
+
+  @param[in]    thd             thread handle
+  @param[in]    action          synchronization action
+
+  @return       status
+    @retval     FALSE           ok
+    @retval     TRUE            error
+
+  @description
+    This is called from the debug sync parser. It arms the action for
+    the requested sync point. If the action parsed into an empty action,
+    it is removed instead.
+
+    Setting an action for a sync point means to make the sync point
+    active. When it is hit it will execute this action.
+
+    Before parsing, we "get" an action object. This is placed at the
+    end of the thread's action array unless the requested sync point
+    has an action already.
+
+    Then the parser fills the action object from the request string.
+
+    Finally the action is "set" for the sync point. If it was parsed
+    to be empty, it is removed from the array. If it did belong to a
+    sync point before, the sync point becomes inactive. If the action
+    became non-empty and it did not belong to a sync point before (it
+    was added at the end of the action array), the action array needs
+    to be sorted by sync point.
+
+    If the sync point name is "now", it is executed immediately.
+*/
+
+static bool debug_sync_set_action(THD *thd, st_debug_sync_action *action)
+{
+  st_debug_sync_control *ds_control= thd->debug_sync_control;
+  bool is_dsp_now= FALSE;
+  DBUG_ENTER("debug_sync_set_action");
+  DBUG_ASSERT(thd);
+  DBUG_ASSERT(action);
+  DBUG_ASSERT(ds_control);
+
+  action->activation_count= max(action->hit_limit, action->execute);
+  if (!action->activation_count)
+  {
+    debug_sync_remove_action(ds_control, action);
+    DBUG_PRINT("debug_sync", ("action cleared"));
+  }
+  else
+  {
+    const char *dsp_name= action->sync_point.c_ptr();
+    DBUG_EXECUTE("debug_sync", {
+        /* Functions as DBUG_PRINT args can change keyword and line nr. */
+        const char *sig_emit= action->signal.c_ptr();
+        const char *sig_wait= action->wait_for.c_ptr();
+        DBUG_PRINT("debug_sync",
+                   ("sync_point: '%s'  activation_count: %lu  hit_limit: %lu  "
+                    "execute: %lu  timeout: %lu  signal: '%s'  wait_for: '%s'",
+                    dsp_name, action->activation_count,
+                    action->hit_limit, action->execute, action->timeout,
+                    sig_emit, sig_wait));});
+
+    /* Check this before sorting the array. action may move. */
+    is_dsp_now= !my_strcasecmp(system_charset_info, dsp_name, "now");
+
+    if (action->need_sort)
+    {
+      action->need_sort= FALSE;
+      /* Sort actions by (name_len, name). */
+      my_qsort(ds_control->ds_action, ds_control->ds_active,
+               sizeof(st_debug_sync_action), debug_sync_qsort_cmp);
+    }
+  }
+  DBUG_EXECUTE("debug_sync_list", debug_sync_print_actions(thd););
+
+  /* Execute the special sync point 'now' if activated above. */
+  if (is_dsp_now)
+  {
+    DEBUG_SYNC(thd, "now");
+    /*
+      If HIT_LIMIT for sync point "now" was 1, the execution of the sync
+      point decremented it to 0. In this case the following happened:
+
+      - an error message was reported with my_error() and
+      - the statement was killed with thd->killed= THD::KILL_QUERY.
+
+      If a statement reports an error, it must not call send_ok().
+      The calling functions will not call send_ok(), if we return TRUE
+      from this function.
+
+      thd->killed is also set if the wait is interrupted from a
+      KILL or KILL QUERY statement. In this case, no error is reported
+      and shall not be reported as a result of SET DEBUG_SYNC.
+      Hence, we check for the first condition above.
+    */
+    if (thd->is_error())
+      DBUG_RETURN(TRUE);
+  }
+
+  DBUG_RETURN(FALSE);
+}
+
+
+/**
+  Extract a token from a string.
+
+  @param[out]     token_p         returns start of token
+  @param[out]     token_length_p  returns length of token
+  @param[in,out]  ptr             current string pointer, adds '\0' terminators
+
+  @return       string pointer or NULL
+    @retval     != NULL         ptr behind token terminator or at string end
+    @retval     NULL            no token found in remainder of string
+
+  @note
+    This function assumes that the string is in system_charset_info,
+    that this charset is single byte for ASCII NUL ('\0'), that no
+    character except of ASCII NUL ('\0') contains a byte with value 0,
+    and that ASCII NUL ('\0') is used as the string terminator.
+
+    This function needs to return tokens that are terminated with ASCII
+    NUL ('\0'). The tokens are used in my_strcasecmp(). Unfortunately
+    there is no my_strncasecmp().
+
+    To return the last token without copying it, we require the input
+    string to be nul terminated.
+
+  @description
+    This function skips space characters at string begin.
+
+    It returns a pointer to the first non-space character in *token_p.
+
+    If no non-space character is found before the string terminator
+    ASCII NUL ('\0'), the function returns NULL. *token_p and
+    *token_length_p remain unchanged in this case (they are not set).
+
+    The function takes a space character or an ASCII NUL ('\0') as a
+    terminator of the token. The space character could be multi-byte.
+
+    It returns the length of the token in bytes, excluding the
+    terminator, in *token_length_p.
+
+    If the terminator of the token is ASCII NUL ('\0'), it returns a
+    pointer to the terminator (string end).
+
+    If the terminator is a space character, it replaces the the first
+    byte of the terminator character by ASCII NUL ('\0'), skips the (now
+    corrupted) terminator character, and skips all following space
+    characters. It returns a pointer to the next non-space character or
+    to the string terminator ASCII NUL ('\0').
+*/
+
+static char *debug_sync_token(char **token_p, uint *token_length_p, char *ptr)
+{
+  DBUG_ASSERT(token_p);
+  DBUG_ASSERT(token_length_p);
+  DBUG_ASSERT(ptr);
+
+  /* Skip leading space */
+  while (my_isspace(system_charset_info, *ptr))
+    ptr+= my_mbcharlen(system_charset_info, (uchar) *ptr);
+
+  if (!*ptr)
+  {
+    ptr= NULL;
+    goto end;
+  }
+
+  /* Get token start. */
+  *token_p= ptr;
+
+  /* Find token end. */
+  while (*ptr && !my_isspace(system_charset_info, *ptr))
+    ptr+= my_mbcharlen(system_charset_info, (uchar) *ptr);
+
+  /* Get token length. */
+  *token_length_p= ptr - *token_p;
+
+  /* If necessary, terminate token. */
+  if (*ptr)
+  {
+    /* Get terminator character length. */
+    uint mbspacelen= my_mbcharlen(system_charset_info, (uchar) *ptr);
+
+    /* Terminate token. */
+    *ptr= '\0';
+
+    /* Skip the terminator. */
+    ptr+= mbspacelen;
+
+    /* Skip trailing space */
+    while (my_isspace(system_charset_info, *ptr))
+      ptr+= my_mbcharlen(system_charset_info, (uchar) *ptr);
+  }
+
+ end:
+  return ptr;
+}
+
+
+/**
+  Extract a number from a string.
+
+  @param[out]   number_p        returns number
+  @param[in]    actstrptr       current pointer in action string
+
+  @return       string pointer or NULL
+    @retval     != NULL         ptr behind token terminator or at string end
+    @retval     NULL            no token found or token is not valid number
+
+  @note
+    The same assumptions about charset apply as for debug_sync_token().
+
+  @description
+    This function fetches a token from the string and converts it
+    into a number.
+
+    If there is no token left in the string, or the token is not a valid
+    decimal number, NULL is returned. The result in *number_p is
+    undefined in this case.
+*/
+
+static char *debug_sync_number(ulong *number_p, char *actstrptr)
+{
+  char                  *ptr;
+  char                  *ept;
+  char                  *token;
+  uint                  token_length;
+  DBUG_ASSERT(number_p);
+  DBUG_ASSERT(actstrptr);
+
+  /* Get token from string. */
+  if (!(ptr= debug_sync_token(&token, &token_length, actstrptr)))
+    goto end;
+
+  *number_p= strtoul(token, &ept, 10);
+  if (*ept)
+    ptr= NULL;
+
+ end:
+  return ptr;
+}
+
+
+/**
+  Evaluate a debug sync action string.
+
+  @param[in]        thd             thread handle
+  @param[in,out]    action_str      action string to receive '\0' terminators
+
+  @return           status
+    @retval         FALSE           ok
+    @retval         TRUE            error
+
+  @description
+    This is called when the DEBUG_SYNC system variable is set.
+    Parse action string, build a debug sync action, activate it.
+
+    Before parsing, we "get" an action object. This is placed at the
+    end of the thread's action array unless the requested sync point
+    has an action already.
+
+    Then the parser fills the action object from the request string.
+
+    Finally the action is "set" for the sync point. This means that the
+    sync point becomes active or inactive, depending on the action
+    values.
+
+  @note
+    The input string needs to be ASCII NUL ('\0') terminated. We split
+    nul-terminated tokens in it without copy.
+
+  @see the function comment of debug_sync_token() for more constraints
+    for the string.
+*/
+
+static bool debug_sync_eval_action(THD *thd, char *action_str)
+{
+  st_debug_sync_action  *action= NULL;
+  const char            *errmsg;
+  char                  *ptr;
+  char                  *token;
+  uint                  token_length= 0;
+  DBUG_ENTER("debug_sync_eval_action");
+  DBUG_ASSERT(thd);
+  DBUG_ASSERT(action_str);
+
+  /*
+    Get debug sync point name. Or a special command.
+  */
+  if (!(ptr= debug_sync_token(&token, &token_length, action_str)))
+  {
+    errmsg= "Missing synchronization point name";
+    goto err;
+  }
+
+  /*
+    If there is a second token, the first one is the sync point name.
+  */
+  if (*ptr)
+  {
+    /* Get an action object to collect the requested action parameters. */
+    action= debug_sync_get_action(thd, token, token_length);
+    if (!action)
+    {
+      /* Error message is sent. */
+      DBUG_RETURN(TRUE); /* purecov: tested */
+    }
+  }
+
+  /*
+    Get kind of action to be taken at sync point.
+  */
+  if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+  {
+    /* No action present. Try special commands. Token unchanged. */
+
+    /*
+      Try RESET.
+    */
+    if (!my_strcasecmp(system_charset_info, token, "RESET"))
+    {
+      /* It is RESET. Reset all actions and global signal. */
+      debug_sync_reset(thd);
+      goto end;
+    }
+
+    /* Token unchanged. It still contains sync point name. */
+    errmsg= "Missing action after synchronization point name '%.*s'";
+    goto err;
+  }
+
+  /*
+    Check for pseudo actions first. Start with actions that work on
+    an existing action.
+  */
+  DBUG_ASSERT(action);
+
+  /*
+    Try TEST.
+  */
+  if (!my_strcasecmp(system_charset_info, token, "TEST"))
+  {
+    /* It is TEST. Nothing must follow it. */
+    if (*ptr)
+    {
+      errmsg= "Nothing must follow action TEST";
+      goto err;
+    }
+
+    /* Execute sync point. */
+    debug_sync(thd, action->sync_point.ptr(), action->sync_point.length());
+    /* Fix statistics. This was not a real hit of the sync point. */
+    thd->debug_sync_control->dsp_hits--;
+    goto end;
+  }
+
+  /*
+    Now check for actions that define a new action.
+    Initialize action. Do not use bzero(). Strings may have malloced.
+  */
+  action->activation_count= 0;
+  action->hit_limit= 0;
+  action->execute= 0;
+  action->timeout= 0;
+  action->signal.length(0);
+  action->wait_for.length(0);
+
+  /*
+    Try CLEAR.
+  */
+  if (!my_strcasecmp(system_charset_info, token, "CLEAR"))
+  {
+    /* It is CLEAR. Nothing must follow it. */
+    if (*ptr)
+    {
+      errmsg= "Nothing must follow action CLEAR";
+      goto err;
+    }
+
+    /* Set (clear/remove) action. */
+    goto set_action;
+  }
+
+  /*
+    Now check for real sync point actions.
+  */
+
+  /*
+    Try SIGNAL.
+  */
+  if (!my_strcasecmp(system_charset_info, token, "SIGNAL"))
+  {
+    /* It is SIGNAL. Signal name must follow. */
+    if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+    {
+      errmsg= "Missing signal name after action SIGNAL";
+      goto err;
+    }
+    if (action->signal.copy(token, token_length, system_charset_info))
+    {
+      /* Error is reported by my_malloc(). */
+      /* purecov: begin tested */
+      errmsg= NULL;
+      goto err;
+      /* purecov: end */
+    }
+
+    /* Set default for EXECUTE option. */
+    action->execute= 1;
+
+    /* Get next token. If none follows, set action. */
+    if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+      goto set_action;
+  }
+
+  /*
+    Try WAIT_FOR.
+  */
+  if (!my_strcasecmp(system_charset_info, token, "WAIT_FOR"))
+  {
+    /* It is WAIT_FOR. Wait_for signal name must follow. */
+    if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+    {
+      errmsg= "Missing signal name after action WAIT_FOR";
+      goto err;
+    }
+    if (action->wait_for.copy(token, token_length, system_charset_info))
+    {
+      /* Error is reported by my_malloc(). */
+      /* purecov: begin tested */
+      errmsg= NULL;
+      goto err;
+      /* purecov: end */
+    }
+
+    /* Set default for EXECUTE and TIMEOUT options. */
+    action->execute= 1;
+    action->timeout= opt_debug_sync_timeout;
+
+    /* Get next token. If none follows, set action. */
+    if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+      goto set_action;
+
+    /*
+      Try TIMEOUT.
+    */
+    if (!my_strcasecmp(system_charset_info, token, "TIMEOUT"))
+    {
+      /* It is TIMEOUT. Number must follow. */
+      if (!(ptr= debug_sync_number(&action->timeout, ptr)))
+      {
+        errmsg= "Missing valid number after TIMEOUT";
+        goto err;
+      }
+
+      /* Get next token. If none follows, set action. */
+      if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+        goto set_action;
+    }
+  }
+
+  /*
+    Try EXECUTE.
+  */
+  if (!my_strcasecmp(system_charset_info, token, "EXECUTE"))
+  {
+    /*
+      EXECUTE requires either SIGNAL and/or WAIT_FOR to be present.
+      In this case action->execute has been preset to 1.
+    */
+    if (!action->execute)
+    {
+      errmsg= "Missing action before EXECUTE";
+      goto err;
+    }
+
+    /* Number must follow. */
+    if (!(ptr= debug_sync_number(&action->execute, ptr)))
+    {
+      errmsg= "Missing valid number after EXECUTE";
+      goto err;
+    }
+
+    /* Get next token. If none follows, set action. */
+    if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+      goto set_action;
+  }
+
+  /*
+    Try HIT_LIMIT.
+  */
+  if (!my_strcasecmp(system_charset_info, token, "HIT_LIMIT"))
+  {
+    /* Number must follow. */
+    if (!(ptr= debug_sync_number(&action->hit_limit, ptr)))
+    {
+      errmsg= "Missing valid number after HIT_LIMIT";
+      goto err;
+    }
+
+    /* Get next token. If none follows, set action. */
+    if (!(ptr= debug_sync_token(&token, &token_length, ptr)))
+      goto set_action;
+  }
+
+  errmsg= "Illegal or out of order stuff: '%.*s'";
+
+ err:
+  if (errmsg)
+  {
+    /*
+      NOTE: errmsg must either have %.*s or none % at all.
+      It can be NULL if an error message is already reported
+      (e.g. by my_malloc()).
+    */
+    set_if_smaller(token_length, 64); /* Limit error message length. */
+    my_printf_error(ER_PARSE_ERROR, errmsg, MYF(0), token_length, token);
+  }
+  if (action)
+    debug_sync_remove_action(thd->debug_sync_control, action);
+  DBUG_RETURN(TRUE);
+
+ set_action:
+  DBUG_RETURN(debug_sync_set_action(thd, action));
+
+ end:
+  DBUG_RETURN(FALSE);
+}
+
+
+/**
+  Check if the system variable 'debug_sync' can be set.
+
+  @param[in]    thd             thread handle
+  @param[in]    var             set variable request
+
+  @return       status
+    @retval     FALSE           ok, variable can be set
+    @retval     TRUE            error, variable cannot be set
+*/
+
+bool sys_var_debug_sync::check(THD *thd, set_var *var)
+{
+  DBUG_ENTER("sys_var_debug_sync::check");
+  DBUG_ASSERT(thd);
+  DBUG_ASSERT(var);
+
+  /*
+    Variable can be set for the session only.
+
+    This could be changed later. Then we need to have a global array of
+    actions in addition to the thread local ones. SET GLOBAL would
+    manage the global array, SET [SESSION] the local array. A sync point
+    would need to look for a local and a global action. Setting and
+    executing of global actions need to be protected by a mutex.
+
+    The purpose of global actions could be to allow synchronizing with
+    connectionless threads that cannot execute SET statements.
+  */
+  if (var->type == OPT_GLOBAL)
+  {
+    my_error(ER_LOCAL_VARIABLE, MYF(0), name);
+    DBUG_RETURN(TRUE);
+  }
+
+  /*
+    Do not check for disabled facility. Test result should not
+    unnecessarily differ from enabled facility.
+  */
+
+  /*
+    Facility requires SUPER privilege. Sync points could be inside
+    global mutexes (e.g. LOCK_open). Waiting there forever would
+    stall the whole server.
+  */
+  DBUG_RETURN(check_global_access(thd, SUPER_ACL));
+}
+
+
+/**
+  Set the system variable 'debug_sync'.
+
+  @param[in]    thd             thread handle
+  @param[in]    var             set variable request
+
+  @return       status
+    @retval     FALSE           ok, variable is set
+    @retval     TRUE            error, variable could not be set
+
+  @note
+    "Setting" of the system variable 'debug_sync' does not mean to
+    assign a value to it as usual. Instead a debug sync action is parsed
+    from the input string and stored apart from the variable value.
+
+  @note
+    For efficiency reasons, the action string parser places '\0'
+    terminators in the string. So we need to take a copy here.
+*/
+
+bool sys_var_debug_sync::update(THD *thd, set_var *var)
+{
+  char   *val_str;
+  String *val_ptr;
+  String val_buf;
+  DBUG_ENTER("sys_var_debug_sync::update");
+  DBUG_ASSERT(thd);
+
+  /*
+    Depending on the value type (string literal, user variable, ...)
+    val_buf receives a copy of the value or not. But we always need
+    a copy. So we take a copy, if it is not done by val_str().
+    If val_str() puts a copy into val_buf, then it returns &val_buf,
+    otherwise it returns a pointer to the string object that we need
+    to copy.
+  */
+  val_ptr= var ? var->value->val_str(&val_buf) : &val_buf;
+  if (val_ptr != &val_buf)
+  {
+    val_buf.copy(*val_ptr);
+  }
+  val_str= val_buf.c_ptr();
+  DBUG_PRINT("debug_sync", ("set action: '%s'", val_str));
+
+  /*
+    debug_sync_eval_action() places '\0' in the string, which itself
+    must be '\0' terminated.
+  */
+  DBUG_RETURN(opt_debug_sync_timeout ?
+              debug_sync_eval_action(thd, val_str) :
+              FALSE);
+}
+
+
+/**
+  Retrieve the value of the system variable 'debug_sync'.
+
+  @param[in]    thd             thread handle
+  @param[in]    type            variable type, unused
+  @param[in]    base            variable base, unused
+
+  @return       string
+    @retval     != NULL         ok, string pointer
+    @retval     NULL            memory allocation error
+
+  @note
+    The value of the system variable 'debug_sync' reflects if
+    the facility is enabled ("ON") or disabled (default, "OFF").
+
+    When "ON", the current signal is added.
+*/
+
+uchar *sys_var_debug_sync::value_ptr(THD *thd,
+                                     enum_var_type type __attribute__((unused)),
+                                     LEX_STRING *base __attribute__((unused)))
+{
+  char *value;
+  DBUG_ENTER("sys_var_debug_sync::value_ptr");
+  DBUG_ASSERT(thd);
+
+  if (opt_debug_sync_timeout)
+  {
+    static char on[]= "ON - current signal: '"; 
+
+    // Ensure exclusive access to debug_sync_global.ds_signal
+    pthread_mutex_lock(&debug_sync_global.ds_mutex);
+
+    size_t lgt= (sizeof(on) /* includes '\0' */ +
+                 debug_sync_global.ds_signal.length() + 1 /* for '\'' */);
+    char *vend;
+    char *vptr;
+
+    if ((value= (char*) alloc_root(thd->mem_root, lgt)))
+    {
+      vend= value + lgt - 1; /* reserve space for '\0'. */
+      vptr= debug_sync_bmove_len(value, vend, STRING_WITH_LEN(on));
+      vptr= debug_sync_bmove_len(vptr, vend, debug_sync_global.ds_signal.ptr(),
+                                 debug_sync_global.ds_signal.length());
+      if (vptr < vend)
+        *(vptr++)= '\'';
+      *vptr= '\0'; /* We have one byte reserved for the worst case. */
+    }
+    pthread_mutex_unlock(&debug_sync_global.ds_mutex);
+  }
+  else
+  {
+    /* purecov: begin tested */
+    value= strmake_root(thd->mem_root, STRING_WITH_LEN("OFF"));
+    /* purecov: end */
+  }
+
+  DBUG_RETURN((uchar*) value);
+}
+
+
+/**
+  Execute requested action at a synchronization point.
+
+  @param[in]    thd                 thread handle
+  @param[in]    action              action to be executed
+
+  @note
+    This is to be called only if activation count > 0.
+*/
+
+static void debug_sync_execute(THD *thd, st_debug_sync_action *action)
+{
+  IF_DBUG(const char *dsp_name= action->sync_point.c_ptr());
+  IF_DBUG(const char *sig_emit= action->signal.c_ptr());
+  IF_DBUG(const char *sig_wait= action->wait_for.c_ptr());
+  DBUG_ENTER("debug_sync_execute");
+  DBUG_ASSERT(thd);
+  DBUG_ASSERT(action);
+  DBUG_PRINT("debug_sync",
+             ("sync_point: '%s'  activation_count: %lu  hit_limit: %lu  "
+              "execute: %lu  timeout: %lu  signal: '%s'  wait_for: '%s'",
+              dsp_name, action->activation_count, action->hit_limit,
+              action->execute, action->timeout, sig_emit, sig_wait));
+
+  DBUG_ASSERT(action->activation_count);
+  action->activation_count--;
+
+  if (action->execute)
+  {
+    const char  *old_proc_info;
+
+    action->execute--;
+
+    /*
+      If we will be going to wait, set proc_info for the PROCESSLIST table.
+      Do this before emitting the signal, so other threads can see it
+      if they awake before we enter_cond() below.
+    */
+    if (action->wait_for.length())
+    {
+      st_debug_sync_control *ds_control= thd->debug_sync_control;
+      strxnmov(ds_control->ds_proc_info, sizeof(ds_control->ds_proc_info)-1,
+               "debug sync point: ", action->sync_point.c_ptr(), NullS);
+      old_proc_info= thd->proc_info;
+      thd_proc_info(thd, ds_control->ds_proc_info);
+    }
+
+    /*
+      Take mutex to ensure that only one thread access
+      debug_sync_global.ds_signal at a time.  Need to take mutex for
+      read access too, to create a memory barrier in order to avoid that
+      threads just reads an old cached version of the signal.
+    */
+    pthread_mutex_lock(&debug_sync_global.ds_mutex);
+
+    if (action->signal.length())
+    {
+      /* Copy the signal to the global variable. */
+      if (debug_sync_global.ds_signal.copy(action->signal))
+      {
+        /*
+          Error is reported by my_malloc().
+          We must disable the facility. We have no way to return an error.
+        */
+        debug_sync_emergency_disable(); /* purecov: tested */
+      }
+      /* Wake threads waiting in a sync point. */
+      pthread_cond_broadcast(&debug_sync_global.ds_cond);
+      DBUG_PRINT("debug_sync_exec", ("signal '%s'  at: '%s'",
+                                     sig_emit, dsp_name));
+    } /* end if (action->signal.length()) */
+
+    if (action->wait_for.length())
+    {
+      pthread_mutex_t *old_mutex;
+      pthread_cond_t  *old_cond;
+      int             error= 0;
+      struct timespec abstime;
+
+      /*
+        We don't use enter_cond()/exit_cond(). They do not save old
+        mutex and cond. This would prohibit the use of DEBUG_SYNC
+        between other places of enter_cond() and exit_cond().
+      */
+      old_mutex= thd->mysys_var->current_mutex;
+      old_cond= thd->mysys_var->current_cond;
+      thd->mysys_var->current_mutex= &debug_sync_global.ds_mutex;
+      thd->mysys_var->current_cond= &debug_sync_global.ds_cond;
+
+      set_timespec(abstime, action->timeout);
+      DBUG_EXECUTE("debug_sync_exec", {
+          /* Functions as DBUG_PRINT args can change keyword and line nr. */
+          const char *sig_glob= debug_sync_global.ds_signal.c_ptr();
+          DBUG_PRINT("debug_sync_exec",
+                     ("wait for '%s'  at: '%s'  curr: '%s'",
+                      sig_wait, dsp_name, sig_glob));});
+
+      /*
+        Wait until global signal string matches the wait_for string.
+        Interrupt when thread or query is killed or facility disabled.
+        The facility can become disabled when some thread cannot get
+        the required dynamic memory allocated.
+      */
+      while (stringcmp(&debug_sync_global.ds_signal, &action->wait_for) &&
+             !thd->killed && opt_debug_sync_timeout)
+      {
+        error= pthread_cond_timedwait(&debug_sync_global.ds_cond,
+                                      &debug_sync_global.ds_mutex,
+                                      &abstime);
+        DBUG_EXECUTE("debug_sync", {
+            /* Functions as DBUG_PRINT args can change keyword and line nr. */
+            const char *sig_glob= debug_sync_global.ds_signal.c_ptr();
+            DBUG_PRINT("debug_sync",
+                       ("awoke from %s  global: %s  error: %d",
+                        sig_wait, sig_glob, error));});
+        if (error == ETIMEDOUT || error == ETIME)
+        {
+          push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+                       ER_DEBUG_SYNC_TIMEOUT, ER(ER_DEBUG_SYNC_TIMEOUT));
+          break;
+        }
+        error= 0;
+      }
+      DBUG_EXECUTE("debug_sync_exec",
+                   if (thd->killed)
+                     DBUG_PRINT("debug_sync_exec",
+                                ("killed %d from '%s'  at: '%s'",
+                                 thd->killed, sig_wait, dsp_name));
+                   else
+                     DBUG_PRINT("debug_sync_exec",
+                                ("%s from '%s'  at: '%s'",
+                                 error ? "timeout" : "resume",
+                                 sig_wait, dsp_name)););
+
+      /*
+        We don't use enter_cond()/exit_cond(). They do not save old
+        mutex and cond. This would prohibit the use of DEBUG_SYNC
+        between other places of enter_cond() and exit_cond(). The
+        protected mutex must always unlocked _before_ mysys_var->mutex
+        is locked. (See comment in THD::exit_cond().)
+      */
+      pthread_mutex_unlock(&debug_sync_global.ds_mutex);
+      pthread_mutex_lock(&thd->mysys_var->mutex);
+      thd->mysys_var->current_mutex= old_mutex;
+      thd->mysys_var->current_cond= old_cond;
+      thd_proc_info(thd, old_proc_info);
+      pthread_mutex_unlock(&thd->mysys_var->mutex);
+
+    }
+    else
+    {
+      /* In case we don't wait, we just release the mutex. */
+      pthread_mutex_unlock(&debug_sync_global.ds_mutex);
+    } /* end if (action->wait_for.length()) */
+
+  } /* end if (action->execute) */
+
+  /* hit_limit is zero for infinite. Don't decrement unconditionally. */
+  if (action->hit_limit)
+  {
+    if (!--action->hit_limit)
+    {
+      thd->killed= THD::KILL_QUERY;
+      my_error(ER_DEBUG_SYNC_HIT_LIMIT, MYF(0));
+    }
+    DBUG_PRINT("debug_sync_exec", ("hit_limit: %lu  at: '%s'",
+                                   action->hit_limit, dsp_name));
+  }
+
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Execute requested action at a synchronization point.
+
+  @param[in]     thd                thread handle
+  @param[in]     sync_point_name    name of synchronization point
+  @param[in]     name_len           length of sync point name
+*/
+
+void debug_sync(THD *thd, const char *sync_point_name, size_t name_len)
+{
+  st_debug_sync_control *ds_control= thd->debug_sync_control;
+  st_debug_sync_action  *action;
+  DBUG_ENTER("debug_sync");
+  DBUG_ASSERT(thd);
+  DBUG_ASSERT(sync_point_name);
+  DBUG_ASSERT(name_len);
+  DBUG_ASSERT(ds_control);
+  DBUG_PRINT("debug_sync_point", ("hit: '%s'", sync_point_name));
+
+  /* Statistics. */
+  ds_control->dsp_hits++;
+
+  if (ds_control->ds_active &&
+      (action= debug_sync_find(ds_control->ds_action, ds_control->ds_active,
+                               sync_point_name, name_len)) &&
+      action->activation_count)
+  {
+    /* Sync point is active (action exists). */
+    debug_sync_execute(thd, action);
+
+    /* Statistics. */
+    ds_control->dsp_executed++;
+
+    /* If action became inactive, remove it to shrink the search array. */
+    if (!action->activation_count)
+      debug_sync_remove_action(ds_control, action);
+  }
+
+  DBUG_VOID_RETURN;
+}
+
+#endif /* defined(ENABLED_DEBUG_SYNC) */

=== added file 'sql/debug_sync.h'
--- a/sql/debug_sync.h	1970-01-01 00:00:00 +0000
+++ b/sql/debug_sync.h	2009-09-29 15:38:40 +0000
@@ -0,0 +1,60 @@
+#ifndef DEBUG_SYNC_INCLUDED
+#define DEBUG_SYNC_INCLUDED
+
+/* Copyright (C) 2008 Sun Microsystems, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; version 2 of the License.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */
+
+/**
+  @file
+
+  Declarations for the Debug Sync Facility. See debug_sync.cc for details.
+*/
+
+#ifdef USE_PRAGMA_INTERFACE
+#pragma interface                      /* gcc class implementation */
+#endif
+
+#include <my_global.h>
+
+class THD;
+
+#if defined(ENABLED_DEBUG_SYNC)
+
+/* Macro to be put in the code at synchronization points. */
+#define DEBUG_SYNC(_thd_, _sync_point_name_)                            \
+          do { if (unlikely(opt_debug_sync_timeout))                    \
+               debug_sync(_thd_, STRING_WITH_LEN(_sync_point_name_));   \
+             } while (0)
+
+/* Command line option --debug-sync-timeout. See mysqld.cc. */
+extern uint opt_debug_sync_timeout;
+
+/* Default WAIT_FOR timeout if command line option is given without argument. */
+#define DEBUG_SYNC_DEFAULT_WAIT_TIMEOUT 300
+
+/* Debug Sync prototypes. See debug_sync.cc. */
+extern int  debug_sync_init(void);
+extern void debug_sync_end(void);
+extern void debug_sync_init_thread(THD *thd);
+extern void debug_sync_end_thread(THD *thd);
+extern void debug_sync(THD *thd, const char *sync_point_name, size_t name_len);
+
+#else /* defined(ENABLED_DEBUG_SYNC) */
+
+#define DEBUG_SYNC(_thd_, _sync_point_name_)    /* disabled DEBUG_SYNC */
+
+#endif /* defined(ENABLED_DEBUG_SYNC) */
+
+#endif /* DEBUG_SYNC_INCLUDED */

=== modified file 'sql/event_data_objects.cc'
--- a/sql/event_data_objects.cc	2009-09-15 10:46:35 +0000
+++ b/sql/event_data_objects.cc	2009-11-10 15:15:12 +0000
@@ -1432,7 +1432,7 @@ Event_job_data::execute(THD *thd, bool d
   thd->set_query(sp_sql.c_ptr_safe(), sp_sql.length());
 
   {
-    Parser_state parser_state(thd, thd->query, thd->query_length);
+    Parser_state parser_state(thd, thd->query(), thd->query_length());
     lex_start(thd);
 
     if (parse_sql(thd, & parser_state, creation_ctx))

=== modified file 'sql/events.cc'
--- a/sql/events.cc	2009-10-15 21:38:29 +0000
+++ b/sql/events.cc	2009-11-10 15:15:12 +0000
@@ -464,7 +464,7 @@ Events::create_event(THD *thd, Event_par
     if (!dropped)
     {
       /* Binlog the create event. */
-      DBUG_ASSERT(thd->query && thd->query_length);
+      DBUG_ASSERT(thd->query() && thd->query_length());
       String log_query;
       if (create_query_string(thd, &log_query))
       {
@@ -594,8 +594,8 @@ Events::update_event(THD *thd, Event_par
         event_queue->update_event(thd, parse_data->dbname, parse_data->name,
                                   new_element);
       /* Binlog the alter event. */
-      DBUG_ASSERT(thd->query && thd->query_length);
-      write_bin_log(thd, TRUE, thd->query, thd->query_length);
+      DBUG_ASSERT(thd->query() && thd->query_length());
+      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
     }
   }
   pthread_mutex_unlock(&LOCK_event_metadata);
@@ -669,8 +669,8 @@ Events::drop_event(THD *thd, LEX_STRING 
     if (event_queue)
       event_queue->drop_event(thd, dbname, name);
     /* Binlog the drop event. */
-    DBUG_ASSERT(thd->query && thd->query_length);
-    write_bin_log(thd, TRUE, thd->query, thd->query_length);
+    DBUG_ASSERT(thd->query() && thd->query_length());
+    write_bin_log(thd, TRUE, thd->query(), thd->query_length());
   }
   pthread_mutex_unlock(&LOCK_event_metadata);
   DBUG_RETURN(ret);

=== modified file 'sql/field.cc'
--- a/sql/field.cc	2009-10-15 21:38:29 +0000
+++ b/sql/field.cc	2009-11-10 15:15:12 +0000
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
+/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -2481,97 +2481,12 @@ Field_new_decimal::Field_new_decimal(uin
 {
   precision= my_decimal_length_to_precision(len_arg, dec_arg, unsigned_arg);
   set_if_smaller(precision, DECIMAL_MAX_PRECISION);
-  DBUG_ASSERT(precision >= dec);
   DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION) &&
               (dec <= DECIMAL_MAX_SCALE));
   bin_size= my_decimal_get_binary_size(precision, dec);
 }
 
 
-/**
-  Create a field to hold a decimal value from an item.
-
-  @remark The MySQL DECIMAL data type has a characteristic that needs to be
-          taken into account when deducing the type from a Item_decimal.
-
-  But first, let's briefly recap what is the new MySQL DECIMAL type:
-
-  The declaration syntax for a decimal is DECIMAL(M,D), where:
-
-  * M is the maximum number of digits (the precision).
-    It has a range of 1 to 65.
-  * D is the number of digits to the right of the decimal separator (the scale).
-    It has a range of 0 to 30 and must be no larger than M.
-
-  D and M are used to determine the storage requirements for the integer
-  and fractional parts of each value. The integer part is to the left of
-  the decimal separator and to the right is the fractional part. Hence:
-
-  M is the number of digits for the integer and fractional part.
-  D is the number of digits for the fractional part.
-
-  Consequently, M - D is the number of digits for the integer part. For
-  example, a DECIMAL(20,10) column has ten digits on either side of
-  the decimal separator.
-
-  The characteristic that needs to be taken into account is that the
-  backing type for Item_decimal is a my_decimal that has a higher
-  precision (DECIMAL_MAX_POSSIBLE_PRECISION, see my_decimal.h) than
-  DECIMAL.
-
-  Drawing a comparison between my_decimal and DECIMAL:
-
-  * M has a range of 1 to 81.
-  * D has a range of 0 to 81.
-
-  There can be a difference in range if the decimal contains a integer
-  part. This is because the fractional part must always be on a group
-  boundary, leaving at least one group for the integer part. Since each
-  group is 9 (DIG_PER_DEC1) digits and there are 9 (DECIMAL_BUFF_LENGTH)
-  groups, the fractional part is limited to 72 digits if there is at
-  least one digit in the integral part.
-
-  Although the backing type for a DECIMAL is also my_decimal, every
-  time a my_decimal is stored in a DECIMAL field, the precision and
-  scale are explicitly capped at 65 (DECIMAL_MAX_PRECISION) and 30
-  (DECIMAL_MAX_SCALE) digits, following my_decimal truncation procedure
-  (FIX_INTG_FRAC_ERROR).
-*/
-
-Field_new_decimal *
-Field_new_decimal::new_decimal_field(const Item *item)
-{
-  uint32 len;
-  uint intg= item->decimal_int_part(), scale= item->decimals;
-
-  DBUG_ASSERT(item->decimal_precision() >= item->decimals);
-
-  /*
-    Employ a procedure along the lines of the my_decimal truncation process:
-    - If the integer part is equal to or bigger than the maximum precision:
-      Truncate integer part to fit and the fractional becomes zero.
-    - Otherwise:
-      Truncate fractional part to fit.
-  */
-  if (intg >= DECIMAL_MAX_PRECISION)
-  {
-    intg= DECIMAL_MAX_PRECISION;
-    scale= 0;
-  }
-  else
-  {
-    uint room= min(DECIMAL_MAX_PRECISION - intg, DECIMAL_MAX_SCALE);
-    if (scale > room)
-      scale= room;
-  }
-
-  len= my_decimal_precision_to_length(intg + scale, scale, item->unsigned_flag);
-
-  return new Field_new_decimal(len, item->maybe_null, item->name, scale,
-                               item->unsigned_flag);
-}
-
-
 int Field_new_decimal::reset(void)
 {
   store_value(&decimal_zero);
@@ -6555,20 +6470,9 @@ uint Field::is_equal(Create_field *new_f
 }
 
 
-/* If one of the fields is binary and the other one isn't return 1 else 0 */
-
-bool Field_str::compare_str_field_flags(Create_field *new_field, uint32 flag_arg)
-{
-  return (((new_field->flags & (BINCMP_FLAG | BINARY_FLAG)) &&
-          !(flag_arg & (BINCMP_FLAG | BINARY_FLAG))) ||
-         (!(new_field->flags & (BINCMP_FLAG | BINARY_FLAG)) &&
-          (flag_arg & (BINCMP_FLAG | BINARY_FLAG))));
-}
-
-
 uint Field_str::is_equal(Create_field *new_field)
 {
-  if (compare_str_field_flags(new_field, flags))
+  if (field_flags_are_binary() != new_field->field_flags_are_binary())
     return 0;
 
   return ((new_field->sql_type == real_type()) &&
@@ -8334,7 +8238,7 @@ uint Field_blob::max_packed_col_length(u
 
 uint Field_blob::is_equal(Create_field *new_field)
 {
-  if (compare_str_field_flags(new_field, flags))
+  if (field_flags_are_binary() != new_field->field_flags_are_binary())
     return 0;
 
   return ((new_field->sql_type == get_blob_type_from_length(max_data_length()))
@@ -8838,38 +8742,81 @@ bool Field::eq_def(Field *field)
 
 
 /**
+  Compare the first t1::count type names.
+
+  @return TRUE if the type names of t1 match those of t2. FALSE otherwise.
+*/
+
+static bool compare_type_names(CHARSET_INFO *charset, TYPELIB *t1, TYPELIB *t2)
+{
+  for (uint i= 0; i < t1->count; i++)
+    if (my_strnncoll(charset,
+                     (const uchar*) t1->type_names[i],
+                     t1->type_lengths[i],
+                     (const uchar*) t2->type_names[i],
+                     t2->type_lengths[i]))
+      return FALSE;
+  return TRUE;
+}
+
+/**
   @return
   returns 1 if the fields are equally defined
 */
 
 bool Field_enum::eq_def(Field *field)
 {
+  TYPELIB *values;
+
   if (!Field::eq_def(field))
-    return 0;
-  return compare_enum_values(((Field_enum*) field)->typelib);
-}
+    return FALSE;
 
+  values= ((Field_enum*) field)->typelib;
 
-bool Field_enum::compare_enum_values(TYPELIB *values)
-{
+  /* Definition must be strictly equal. */
   if (typelib->count != values->count)
     return FALSE;
-  for (uint i= 0; i < typelib->count; i++)
-    if (my_strnncoll(field_charset,
-                     (const uchar*) typelib->type_names[i],
-                     typelib->type_lengths[i],
-                     (const uchar*) values->type_names[i],
-                     values->type_lengths[i]))
-      return FALSE;
-  return TRUE;
+
+  return compare_type_names(field_charset, typelib, values);
 }
 
 
+/**
+  Check whether two fields can be considered 'equal' for table
+  alteration purposes. Fields are equal if they retain the same
+  pack length and if new members are added to the end of the list.
+
+  @return IS_EQUAL_YES if fields are compatible.
+          IS_EQUAL_NO otherwise.
+*/
+
 uint Field_enum::is_equal(Create_field *new_field)
 {
-  if (!Field_str::is_equal(new_field))
-    return 0;
-  return compare_enum_values(new_field->interval);
+  TYPELIB *values= new_field->interval;
+
+  /*
+    The fields are compatible if they have the same flags,
+    type, charset and have the same underlying length.
+  */
+  if (new_field->field_flags_are_binary() != field_flags_are_binary() ||
+      new_field->sql_type != real_type() ||
+      new_field->charset != field_charset ||
+      new_field->pack_length != pack_length())
+    return IS_EQUAL_NO;
+
+  /*
+    Changing the definition of an ENUM or SET column by adding a new
+    enumeration or set members to the end of the list of valid member
+    values only alters table metadata and not table data.
+  */
+  if (typelib->count > values->count)
+    return IS_EQUAL_NO;
+
+  /* Check whether there are modification before the end. */
+  if (! compare_type_names(field_charset, typelib, new_field->interval))
+    return IS_EQUAL_NO;
+
+  return IS_EQUAL_YES;
 }
 
 
@@ -9622,7 +9569,7 @@ bool Create_field::init(THD *thd, char *
     }
 
     if (length == 0)
-      fld_length= 0; /* purecov: inspected */
+      fld_length= NULL; /* purecov: inspected */
   }
 
   sign_len= fld_type_modifier & UNSIGNED_FLAG ? 0 : 1;
@@ -9774,8 +9721,7 @@ bool Create_field::init(THD *thd, char *
   case MYSQL_TYPE_TIMESTAMP:
     if (fld_length == NULL)
     {
-      /* Compressed date YYYYMMDDHHMMSS */
-      length= MAX_DATETIME_COMPRESSED_WIDTH;
+      length= MAX_DATETIME_WIDTH;
     }
     else if (length != MAX_DATETIME_WIDTH)
     {
@@ -9839,7 +9785,7 @@ bool Create_field::init(THD *thd, char *
     sql_type= MYSQL_TYPE_NEWDATE;
     /* fall trough */
   case MYSQL_TYPE_NEWDATE:
-    length= 10;
+    length= MAX_DATE_WIDTH;
     break;
   case MYSQL_TYPE_TIME:
     length= 10;
@@ -9920,6 +9866,17 @@ bool Create_field::init(THD *thd, char *
     DBUG_RETURN(TRUE);
   }
 
+  switch (fld_type) {
+  case MYSQL_TYPE_DATE:
+  case MYSQL_TYPE_NEWDATE:
+  case MYSQL_TYPE_TIME:
+  case MYSQL_TYPE_DATETIME:
+  case MYSQL_TYPE_TIMESTAMP:
+    charset= &my_charset_bin;
+    flags|= BINCMP_FLAG;
+  default: break;
+  }
+
   DBUG_RETURN(FALSE); /* success */
 }
 

=== modified file 'sql/field.h'
--- a/sql/field.h	2009-10-15 21:38:29 +0000
+++ b/sql/field.h	2009-11-10 15:15:12 +0000
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
+/* Copyright 2000-2008 MySQL AB, 2008, 2009 Sun Microsystems, Inc.
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
@@ -472,6 +472,13 @@ public:
   /* maximum possible display length */
   virtual uint32 max_display_length()= 0;
 
+  /**
+    Whether a field being created is compatible with a existing one.
+
+    Used by the ALTER TABLE code to evaluate whether the new definition
+    of a table is compatible with the old definition so that it can
+    determine if data needs to be copied over (table data change).
+  */
   virtual uint is_equal(Create_field *new_field);
   /* convert decimal to longlong with overflow check */
   longlong convert_decimal2longlong(const my_decimal *val, bool unsigned_flag,
@@ -603,15 +610,17 @@ protected:
     handle_int64(to, from, low_byte_first_from, table->s->db_low_byte_first);
     return from + sizeof(int64);
   }
+
+  bool field_flags_are_binary()
+  {
+    return (flags & (BINCMP_FLAG | BINARY_FLAG)) != 0;
+  }
+
 };
 
 
 class Field_num :public Field {
 public:
-  /**
-     The scale of the Field's value, i.e. the number of digits to the right
-     of the decimal point.
-  */
   const uint8 dec;
   bool zerofill,unsigned_flag;	// Purify cannot handle bit fields
   Field_num(uchar *ptr_arg,uint32 len_arg, uchar *null_ptr_arg,
@@ -662,7 +671,6 @@ public:
   friend class Create_field;
   my_decimal *val_decimal(my_decimal *);
   virtual bool str_needs_quotes() { return TRUE; }
-  bool compare_str_field_flags(Create_field *new_field, uint32 flags);
   uint is_equal(Create_field *new_field);
 };
 
@@ -770,11 +778,6 @@ public:
   Field_new_decimal(uint32 len_arg, bool maybe_null_arg,
                     const char *field_name_arg, uint8 dec_arg,
                     bool unsigned_arg);
-  /*
-    Create a field to hold a decimal value from an item.
-    Truncates the precision and/or scale if necessary.
-  */
-  static Field_new_decimal *new_decimal_field(const Item *item);
   enum_field_types type() const { return MYSQL_TYPE_NEWDECIMAL;}
   enum ha_base_keytype key_type() const { return HA_KEYTYPE_BINARY; }
   Item_result result_type () const { return DECIMAL_RESULT; }
@@ -1277,12 +1280,12 @@ public:
   Field_date(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
 	     enum utype unireg_check_arg, const char *field_name_arg,
 	     CHARSET_INFO *cs)
-    :Field_str(ptr_arg, 10, null_ptr_arg, null_bit_arg,
+    :Field_str(ptr_arg, MAX_DATE_WIDTH, null_ptr_arg, null_bit_arg,
 	       unireg_check_arg, field_name_arg, cs)
     {}
   Field_date(bool maybe_null_arg, const char *field_name_arg,
              CHARSET_INFO *cs)
-    :Field_str((uchar*) 0,10, maybe_null_arg ? (uchar*) "": 0,0,
+    :Field_str((uchar*) 0, MAX_DATE_WIDTH, maybe_null_arg ? (uchar*) "": 0,0,
 	       NONE, field_name_arg, cs) {}
   enum_field_types type() const { return MYSQL_TYPE_DATE;}
   enum ha_base_keytype key_type() const { return HA_KEYTYPE_ULONG_INT; }
@@ -1392,12 +1395,12 @@ public:
   Field_datetime(uchar *ptr_arg, uchar *null_ptr_arg, uchar null_bit_arg,
 		 enum utype unireg_check_arg, const char *field_name_arg,
 		 CHARSET_INFO *cs)
-    :Field_str(ptr_arg, 19, null_ptr_arg, null_bit_arg,
+    :Field_str(ptr_arg, MAX_DATETIME_WIDTH, null_ptr_arg, null_bit_arg,
 	       unireg_check_arg, field_name_arg, cs)
     {}
   Field_datetime(bool maybe_null_arg, const char *field_name_arg,
 		 CHARSET_INFO *cs)
-    :Field_str((uchar*) 0,19, maybe_null_arg ? (uchar*) "": 0,0,
+    :Field_str((uchar*) 0, MAX_DATETIME_WIDTH, maybe_null_arg ? (uchar*) "": 0,0,
 	       NONE, field_name_arg, cs) {}
   enum_field_types type() const { return MYSQL_TYPE_DATETIME;}
 #ifdef HAVE_LONG_LONG
@@ -1862,7 +1865,6 @@ public:
   CHARSET_INFO *sort_charset(void) const { return &my_charset_bin; }
 private:
   int do_save_field_metadata(uchar *first_byte);
-  bool compare_enum_values(TYPELIB *values);
   uint is_equal(Create_field *new_field);
 };
 
@@ -2070,6 +2072,11 @@ public:
             Item *on_update_value, LEX_STRING *comment, char *change,
             List<String> *interval_list, CHARSET_INFO *cs,
             uint uint_geom_type);
+
+  bool field_flags_are_binary()
+  {
+    return (flags & (BINCMP_FLAG | BINARY_FLAG)) != 0;
+  }
 };
 
 

=== modified file 'sql/ha_ndbcluster.cc'
--- a/sql/ha_ndbcluster.cc	2009-09-07 20:50:10 +0000
+++ b/sql/ha_ndbcluster.cc	2009-11-10 15:15:12 +0000
@@ -5527,7 +5527,7 @@ int ha_ndbcluster::create(const char *na
       if (share && !do_event_op)
         share->flags|= NSF_NO_BINLOG;
       ndbcluster_log_schema_op(thd, share,
-                               thd->query, thd->query_length,
+                               thd->query(), thd->query_length(),
                                share->db, share->table_name,
                                m_table->getObjectId(),
                                m_table->getObjectVersion(),
@@ -5969,7 +5969,8 @@ int ha_ndbcluster::rename_table(const ch
     */
     if (!is_old_table_tmpfile)
       ndbcluster_log_schema_op(current_thd, share,
-                               current_thd->query, current_thd->query_length,
+                               current_thd->query(),
+                               current_thd->query_length(),
                                old_dbname, m_tabname,
                                ndb_table_id, ndb_table_version,
                                SOT_RENAME_TABLE,
@@ -6164,7 +6165,7 @@ retry_temporary_error1:
       current_thd->lex->sql_command != SQLCOM_TRUNCATE)
   {
     ndbcluster_log_schema_op(thd, share,
-                             thd->query, thd->query_length,
+                             thd->query(), thd->query_length(),
                              share->db, share->table_name,
                              ndb_table_id, ndb_table_version,
                              SOT_DROP_TABLE, 0, 0, 1);
@@ -6887,7 +6888,7 @@ static void ndbcluster_drop_database(han
   THD *thd= current_thd;
   ha_ndbcluster::set_dbname(path, db);
   ndbcluster_log_schema_op(thd, 0,
-                           thd->query, thd->query_length,
+                           thd->query(), thd->query_length(),
                            db, "", 0, 0, SOT_DROP_DB, 0, 0, 0);
 #endif
   DBUG_VOID_RETURN;
@@ -9429,9 +9430,11 @@ ndb_util_thread_fail:
   pthread_cond_signal(&COND_ndb_util_ready);
   pthread_mutex_unlock(&LOCK_ndb_util_thread);
   DBUG_PRINT("exit", ("ndb_util_thread"));
+
+  DBUG_LEAVE;                               // Must match DBUG_ENTER()
   my_thread_end();
   pthread_exit(0);
-  DBUG_RETURN(NULL);
+  return NULL;                              // Avoid compiler warnings
 }
 
 /*
@@ -10254,13 +10257,13 @@ int ndbcluster_alter_tablespace(handlert
 #ifdef HAVE_NDB_BINLOG
   if (is_tablespace)
     ndbcluster_log_schema_op(thd, 0,
-                             thd->query, thd->query_length,
+                             thd->query(), thd->query_length(),
                              "", alter_info->tablespace_name,
                              0, 0,
                              SOT_TABLESPACE, 0, 0, 0);
   else
     ndbcluster_log_schema_op(thd, 0,
-                             thd->query, thd->query_length,
+                             thd->query(), thd->query_length(),
                              "", alter_info->logfile_group_name,
                              0, 0,
                              SOT_LOGFILE_GROUP, 0, 0, 0);

=== modified file 'sql/ha_ndbcluster_binlog.cc'
--- a/sql/ha_ndbcluster_binlog.cc	2009-09-07 20:50:10 +0000
+++ b/sql/ha_ndbcluster_binlog.cc	2009-11-10 15:15:12 +0000
@@ -241,8 +241,8 @@ static void dbug_print_table(const char 
 static void run_query(THD *thd, char *buf, char *end,
                       const int *no_print_error, my_bool disable_binlog)
 {
-  ulong save_thd_query_length= thd->query_length;
-  char *save_thd_query= thd->query;
+  ulong save_thd_query_length= thd->query_length();
+  char *save_thd_query= thd->query();
   ulong save_thread_id= thd->variables.pseudo_thread_id;
   struct system_status_var save_thd_status_var= thd->status_var;
   THD_TRANS save_thd_transaction_all= thd->transaction.all;
@@ -259,12 +259,12 @@ static void run_query(THD *thd, char *bu
   if (disable_binlog)
     thd->options&= ~OPTION_BIN_LOG;
     
-  DBUG_PRINT("query", ("%s", thd->query));
+  DBUG_PRINT("query", ("%s", thd->query()));
 
   DBUG_ASSERT(!thd->in_sub_stmt);
   DBUG_ASSERT(!thd->prelocked_mode);
 
-  mysql_parse(thd, thd->query, thd->query_length, &found_semicolon);
+  mysql_parse(thd, thd->query(), thd->query_length(), &found_semicolon);
 
   if (no_print_error && thd->is_slave_error)
   {
@@ -3665,9 +3665,11 @@ pthread_handler_t ndb_binlog_thread_func
     ndb_binlog_thread_running= -1;
     pthread_mutex_unlock(&injector_mutex);
     pthread_cond_signal(&injector_cond);
+
+    DBUG_LEAVE;                               // Must match DBUG_ENTER()
     my_thread_end();
     pthread_exit(0);
-    DBUG_RETURN(NULL);
+    return NULL;                              // Avoid compiler warnings
   }
   lex_start(thd);
 
@@ -4378,10 +4380,11 @@ err:
   (void) pthread_cond_signal(&injector_cond);
 
   DBUG_PRINT("exit", ("ndb_binlog_thread"));
-  my_thread_end();
 
+  DBUG_LEAVE;                               // Must match DBUG_ENTER()
+  my_thread_end();
   pthread_exit(0);
-  DBUG_RETURN(NULL);
+  return NULL;                              // Avoid compiler warnings
 }
 
 bool

=== modified file 'sql/ha_partition.cc'
--- a/sql/ha_partition.cc	2009-11-06 17:22:32 +0000
+++ b/sql/ha_partition.cc	2009-11-10 15:15:12 +0000
@@ -239,6 +239,7 @@ void ha_partition::init_handler_variable
   m_curr_key_info[0]= NULL;
   m_curr_key_info[1]= NULL;
   is_clone= FALSE,
+  m_part_func_monotonicity_info= NON_MONOTONIC;
   auto_increment_lock= FALSE;
   auto_increment_safe_stmt_log_lock= FALSE;
   /*
@@ -705,6 +706,7 @@ int ha_partition::rename_partitions(cons
       if (m_is_sub_partitioned)
       {
         List_iterator<partition_element> sub_it(part_elem->subpartitions);
+        j= 0;
         do
         {
           sub_elem= sub_it++;
@@ -1278,10 +1280,10 @@ void ha_partition::cleanup_new_partition
     m_file= m_added_file;
     m_added_file= NULL;
 
+    external_lock(ha_thd(), F_UNLCK);
     /* delete_table also needed, a bit more complex */
     close();
 
-    m_added_file= m_file;
     m_file= save_m_file;
   }
   DBUG_VOID_RETURN;
@@ -2464,11 +2466,18 @@ int ha_partition::open(const char *name,
     }
   }
 
+  /* Initialize the bitmap we use to minimize ha_start_bulk_insert calls */
+  if (bitmap_init(&m_bulk_insert_started, NULL, m_tot_parts + 1, FALSE))
+    DBUG_RETURN(1);
+  bitmap_clear_all(&m_bulk_insert_started);
   /* Initialize the bitmap we use to determine what partitions are used */
   if (!is_clone)
   {
     if (bitmap_init(&(m_part_info->used_partitions), NULL, m_tot_parts, TRUE))
+    {
+      bitmap_free(&m_bulk_insert_started);
       DBUG_RETURN(1);
+    }
     bitmap_set_all(&(m_part_info->used_partitions));
   }
 
@@ -2552,12 +2561,18 @@ int ha_partition::open(const char *name,
     calling open on all individual handlers.
   */
   m_handler_status= handler_opened;
+  if (m_part_info->part_expr)
+    m_part_func_monotonicity_info=
+                            m_part_info->part_expr->get_monotonicity_info();
+  else if (m_part_info->list_of_part_fields)
+    m_part_func_monotonicity_info= MONOTONIC_STRICT_INCREASING;
   info(HA_STATUS_VARIABLE | HA_STATUS_CONST);
   DBUG_RETURN(0);
 
 err_handler:
   while (file-- != m_file)
     (*file)->close();
+  bitmap_free(&m_bulk_insert_started);
   if (!is_clone)
     bitmap_free(&(m_part_info->used_partitions));
 
@@ -2605,6 +2620,7 @@ int ha_partition::close(void)
 
   DBUG_ASSERT(table->s == table_share);
   delete_queue(&m_queue);
+  bitmap_free(&m_bulk_insert_started);
   if (!is_clone)
     bitmap_free(&(m_part_info->used_partitions));
   file= m_file;
@@ -3021,10 +3037,12 @@ int ha_partition::write_row(uchar * buf)
   }
   m_last_part= part_id;
   DBUG_PRINT("info", ("Insert in partition %d", part_id));
+  start_part_bulk_insert(thd, part_id);
+
   tmp_disable_binlog(thd); /* Do not replicate the low-level changes. */
   error= m_file[part_id]->ha_write_row(buf);
   if (have_auto_increment && !table->s->next_number_keypart)
-    set_auto_increment_if_higher(table->next_number_field->val_int());
+    set_auto_increment_if_higher(table->next_number_field);
   reenable_binlog(thd);
 exit:
   table->timestamp_field_type= orig_timestamp_type;
@@ -3083,6 +3101,7 @@ int ha_partition::update_row(const uchar
   }
 
   m_last_part= new_part_id;
+  start_part_bulk_insert(thd, new_part_id);
   if (new_part_id == old_part_id)
   {
     DBUG_PRINT("info", ("Update in partition %d", new_part_id));
@@ -3128,7 +3147,7 @@ exit:
     HA_DATA_PARTITION *ha_data= (HA_DATA_PARTITION*) table_share->ha_data;
     if (!ha_data->auto_inc_initialized)
       info(HA_STATUS_AUTO);
-    set_auto_increment_if_higher(table->found_next_number_field->val_int());
+    set_auto_increment_if_higher(table->found_next_number_field);
   }
   table->timestamp_field_type= orig_timestamp_type;
   DBUG_RETURN(error);
@@ -3247,23 +3266,112 @@ int ha_partition::delete_all_rows()
   DESCRIPTION
     rows == 0 means we will probably insert many rows
 */
-
 void ha_partition::start_bulk_insert(ha_rows rows)
 {
-  handler **file;
   DBUG_ENTER("ha_partition::start_bulk_insert");
 
-  rows= rows ? rows/m_tot_parts + 1 : 0;
-  file= m_file;
-  do
-  {
-    (*file)->ha_start_bulk_insert(rows);
-  } while (*(++file));
+  m_bulk_inserted_rows= 0;
+  bitmap_clear_all(&m_bulk_insert_started);
+  /* use the last bit for marking if bulk_insert_started was called */
+  bitmap_set_bit(&m_bulk_insert_started, m_tot_parts);
   DBUG_VOID_RETURN;
 }
 
 
 /*
+  Check if start_bulk_insert has been called for this partition,
+  if not, call it and mark it called
+*/
+void ha_partition::start_part_bulk_insert(THD *thd, uint part_id)
+{
+  long old_buffer_size;
+  if (!bitmap_is_set(&m_bulk_insert_started, part_id) &&
+      bitmap_is_set(&m_bulk_insert_started, m_tot_parts))
+  {
+    old_buffer_size= thd->variables.read_buff_size;
+    /* Update read_buffer_size for this partition */
+    thd->variables.read_buff_size= estimate_read_buffer_size(old_buffer_size);
+    m_file[part_id]->ha_start_bulk_insert(guess_bulk_insert_rows());
+    bitmap_set_bit(&m_bulk_insert_started, part_id);
+    thd->variables.read_buff_size= old_buffer_size;
+  }
+  m_bulk_inserted_rows++;
+}
+
+/*
+  Estimate the read buffer size for each partition.
+  SYNOPSIS
+    ha_partition::estimate_read_buffer_size()
+    original_size  read buffer size originally set for the server
+  RETURN VALUE
+    estimated buffer size.
+  DESCRIPTION
+    If the estimated number of rows to insert is less than 10 (but not 0)
+    the new buffer size is same as original buffer size.
+    In case of first partition of when partition function is monotonic 
+    new buffer size is same as the original buffer size.
+    For rest of the partition total buffer of 10*original_size is divided 
+    equally if number of partition is more than 10 other wise each partition
+    will be allowed to use original buffer size.
+*/
+long ha_partition::estimate_read_buffer_size(long original_size)
+{
+  /*
+    If number of rows to insert is less than 10, but not 0,
+    return original buffer size.
+  */
+  if (estimation_rows_to_insert && (estimation_rows_to_insert < 10))
+    return (original_size);
+  /*
+    If first insert/partition and monotonic partition function,
+    allow using buffer size originally set.
+   */
+  if (!m_bulk_inserted_rows &&
+      m_part_func_monotonicity_info != NON_MONOTONIC &&
+      m_tot_parts > 1)
+    return original_size;
+  /*
+    Allow total buffer used in all partition to go up to 10*read_buffer_size.
+    11*read_buffer_size in case of monotonic partition function.
+  */
+
+  if (m_tot_parts < 10)
+      return original_size;
+  return (original_size * 10 / m_tot_parts);
+}
+
+/*
+  Try to predict the number of inserts into this partition.
+
+  If less than 10 rows (including 0 which means Unknown)
+    just give that as a guess
+  If monotonic partitioning function was used
+    guess that 50 % of the inserts goes to the first partition
+  For all other cases, guess on equal distribution between the partitions
+*/ 
+ha_rows ha_partition::guess_bulk_insert_rows()
+{
+  DBUG_ENTER("guess_bulk_insert_rows");
+
+  if (estimation_rows_to_insert < 10)
+    DBUG_RETURN(estimation_rows_to_insert);
+
+  /* If first insert/partition and monotonic partition function, guess 50%.  */
+  if (!m_bulk_inserted_rows && 
+      m_part_func_monotonicity_info != NON_MONOTONIC &&
+      m_tot_parts > 1)
+    DBUG_RETURN(estimation_rows_to_insert / 2);
+
+  /* Else guess on equal distribution (+1 is to avoid returning 0/Unknown) */
+  if (m_bulk_inserted_rows < estimation_rows_to_insert)
+    DBUG_RETURN(((estimation_rows_to_insert - m_bulk_inserted_rows)
+                / m_tot_parts) + 1);
+  /* The estimation was wrong, must say 'Unknown' */
+  DBUG_RETURN(0);
+}
+
+
+/*
   Finish a large batch of insert rows
 
   SYNOPSIS
@@ -3273,21 +3381,29 @@ void ha_partition::start_bulk_insert(ha_
   RETURN VALUE
     >0                      Error code
     0                       Success
+
+  Note: end_bulk_insert can be called without start_bulk_insert
+        being called, see bug��44108.
+
 */
 
 int ha_partition::end_bulk_insert(bool abort)
 {
   int error= 0;
-  handler **file;
+  uint i;
   DBUG_ENTER("ha_partition::end_bulk_insert");
 
-  file= m_file;
-  do
+  if (!bitmap_is_set(&m_bulk_insert_started, m_tot_parts))
+    DBUG_RETURN(error);
+
+  for (i= 0; i < m_tot_parts; i++)
   {
     int tmp;
-    if ((tmp= (*file)->ha_end_bulk_insert(abort)))
+    if (bitmap_is_set(&m_bulk_insert_started, i) &&
+        (tmp= m_file[i]->ha_end_bulk_insert(abort)))
       error= tmp;
-  } while (*(++file));
+  }
+  bitmap_clear_all(&m_bulk_insert_started);
   DBUG_RETURN(error);
 }
 
@@ -4896,8 +5012,9 @@ int ha_partition::info(uint flag)
       If the handler doesn't support statistics, it should set all of the
       above to 0.
 
-      We will allow the first handler to set the rec_per_key and use
-      this as an estimate on the total table.
+      We first scans through all partitions to get the one holding most rows.
+      We will then allow the handler with the most rows to set
+      the rec_per_key and use this as an estimate on the total table.
 
       max_data_file_length:     Maximum data file length
       We ignore it, is only used in
@@ -4909,14 +5026,33 @@ int ha_partition::info(uint flag)
       ref_length:               We set this to the value calculated
       and stored in local object
       create_time:              Creation time of table
-      Set by first handler
 
-      So we calculate these constants by using the variables on the first
-      handler.
+      So we calculate these constants by using the variables from the
+      handler with most rows.
     */
-    handler *file;
+    handler *file, **file_array;
+    ulonglong max_records= 0;
+    uint32 i= 0;
+    uint32 handler_instance= 0;
+
+    file_array= m_file;
+    do
+    {
+      file= *file_array;
+      /* Get variables if not already done */
+      if (!(flag & HA_STATUS_VARIABLE) ||
+          !bitmap_is_set(&(m_part_info->used_partitions),
+                         (file_array - m_file)))
+        file->info(HA_STATUS_VARIABLE);
+      if (file->stats.records > max_records)
+      {
+        max_records= file->stats.records;
+        handler_instance= i;
+      }
+      i++;
+    } while (*(++file_array));
 
-    file= m_file[0];
+    file= m_file[handler_instance];
     file->info(HA_STATUS_CONST);
     stats.create_time= file->stats.create_time;
     ref_length= m_ref_length;

=== modified file 'sql/ha_partition.h'
--- a/sql/ha_partition.h	2009-02-19 09:01:25 +0000
+++ b/sql/ha_partition.h	2009-11-10 15:15:12 +0000
@@ -176,6 +176,11 @@ private:
     This to ensure it will work with statement based replication.
   */
   bool auto_increment_safe_stmt_log_lock;
+  /** For optimizing ha_start_bulk_insert calls */
+  MY_BITMAP m_bulk_insert_started;
+  ha_rows   m_bulk_inserted_rows;
+  /** used for prediction of start_bulk_insert rows */
+  enum_monotonicity_info m_part_func_monotonicity_info;
 public:
   handler *clone(MEM_ROOT *mem_root);
   virtual void set_part_info(partition_info *part_info)
@@ -353,7 +358,6 @@ public:
     Bulk inserts are supported if all underlying handlers support it.
     start_bulk_insert and end_bulk_insert is called before and after a
     number of calls to write_row.
-    Not yet though.
   */
   virtual int write_row(uchar * buf);
   virtual int update_row(const uchar * old_data, uchar * new_data);
@@ -361,6 +365,11 @@ public:
   virtual int delete_all_rows(void);
   virtual void start_bulk_insert(ha_rows rows);
   virtual int end_bulk_insert(bool);
+private:
+  ha_rows guess_bulk_insert_rows();
+  void start_part_bulk_insert(THD *thd, uint part_id);
+  long estimate_read_buffer_size(long original_size);
+public:
 
   virtual bool is_fatal_error(int error, uint flags)
   {
@@ -764,10 +773,10 @@ public:
     if (m_handler_status < handler_initialized ||
         m_handler_status >= handler_closed)
       DBUG_RETURN(PARTITION_ENABLED_TABLE_FLAGS);
-    else
-      DBUG_RETURN((m_file[0]->ha_table_flags() &
-                   ~(PARTITION_DISABLED_TABLE_FLAGS)) |
-                  (PARTITION_ENABLED_TABLE_FLAGS));
+
+    DBUG_RETURN((m_file[0]->ha_table_flags() &
+                 ~(PARTITION_DISABLED_TABLE_FLAGS)) |
+                (PARTITION_ENABLED_TABLE_FLAGS));
   }
 
   /*
@@ -936,9 +945,11 @@ private:
       auto_increment_lock= FALSE;
     }
   }
-  virtual void set_auto_increment_if_higher(const ulonglong nr)
+  virtual void set_auto_increment_if_higher(Field *field)
   {
     HA_DATA_PARTITION *ha_data= (HA_DATA_PARTITION*) table_share->ha_data;
+    ulonglong nr= (((Field_num*) field)->unsigned_flag ||
+                   field->val_int() > 0) ? field->val_int() : 0;
     lock_auto_increment();
     DBUG_ASSERT(ha_data->auto_inc_initialized == TRUE);
     /* must check when the mutex is taken */

=== modified file 'sql/handler.cc'
--- a/sql/handler.cc	2009-09-09 21:06:57 +0000
+++ b/sql/handler.cc	2009-11-10 15:15:12 +0000
@@ -1316,7 +1316,8 @@ int ha_rollback_trans(THD *thd, bool all
     }
     trans->ha_list= 0;
     trans->no_2pc=0;
-    if (is_real_trans && thd->transaction_rollback_request)
+    if (is_real_trans && thd->transaction_rollback_request &&
+        thd->transaction.xid_state.xa_state != XA_NOTR)
       thd->transaction.xid_state.rm_error= thd->main_da.sql_errno();
     if (all)
       thd->variables.tx_isolation=thd->session_tx_isolation;
@@ -1890,12 +1891,42 @@ bool ha_flush_logs(handlerton *db_type)
   return FALSE;
 }
 
+
+/**
+  @brief make canonical filename
+
+  @param[in]  file     table handler
+  @param[in]  path     original path
+  @param[out] tmp_path buffer for canonized path
+
+  @details Lower case db name and table name path parts for
+           non file based tables when lower_case_table_names
+           is 2 (store as is, compare in lower case).
+           Filesystem path prefix (mysql_data_home or tmpdir)
+           is left intact.
+
+  @note tmp_path may be left intact if no conversion was
+        performed.
+
+  @retval canonized path
+
+  @todo This may be done more efficiently when table path
+        gets built. Convert this function to something like
+        ASSERT_CANONICAL_FILENAME.
+*/
 const char *get_canonical_filename(handler *file, const char *path,
                                    char *tmp_path)
 {
+  uint i;
   if (lower_case_table_names != 2 || (file->ha_table_flags() & HA_FILE_BASED))
     return path;
 
+  for (i= 0; i <= mysql_tmpdir_list.max; i++)
+  {
+    if (is_prefix(path, mysql_tmpdir_list.list[i]))
+      return path;
+  }
+
   /* Ensure that table handler get path in lower case */
   if (tmp_path != path)
     strmov(tmp_path, path);
@@ -3479,14 +3510,10 @@ int handler::index_next_same(uchar *buf,
   if (!(error=index_next(buf)))
   {
     my_ptrdiff_t ptrdiff= buf - table->record[0];
-    uchar *save_record_0;
-    KEY *key_info;
-    KEY_PART_INFO *key_part;
-    KEY_PART_INFO *key_part_end;
-    LINT_INIT(save_record_0);
-    LINT_INIT(key_info);
-    LINT_INIT(key_part);
-    LINT_INIT(key_part_end);
+    uchar *UNINIT_VAR(save_record_0);
+    KEY *UNINIT_VAR(key_info);
+    KEY_PART_INFO *UNINIT_VAR(key_part);
+    KEY_PART_INFO *UNINIT_VAR(key_part_end);
 
     /*
       key_cmp_if_same() compares table->record[0] against 'key'.

=== modified file 'sql/handler.h'
--- a/sql/handler.h	2009-10-15 21:38:29 +0000
+++ b/sql/handler.h	2009-11-10 15:15:12 +0000
@@ -398,7 +398,6 @@ struct xid_t {
   my_xid get_my_xid()
   {
     return gtrid_length == MYSQL_XID_GTRID_LEN && bqual_length == 0 &&
-           !memcmp(data+MYSQL_XID_PREFIX_LEN, &server_id, sizeof(server_id)) &&
            !memcmp(data, MYSQL_XID_PREFIX, MYSQL_XID_PREFIX_LEN) ?
            quick_get_my_xid() : 0;
   }
@@ -920,6 +919,15 @@ typedef struct st_ha_create_information
   ulong key_block_size;
   SQL_LIST merge_list;
   handlerton *db_type;
+  /**
+    Row type of the table definition.
+
+    Defaults to ROW_TYPE_DEFAULT for all non-ALTER statements.
+    For ALTER TABLE defaults to ROW_TYPE_NOT_USED (means "keep the current").
+
+    Can be changed either explicitly by the parser.
+    If nothing speficied inherits the value of the original table (if present).
+  */
   enum row_type row_type;
   uint null_bits;                       /* NULL bits at start of record */
   uint options;				/* OR of HA_CREATE_ options */

=== modified file 'sql/item.cc'
--- a/sql/item.cc	2009-10-15 21:38:29 +0000
+++ b/sql/item.cc	2009-11-10 15:15:12 +0000
@@ -433,26 +433,17 @@ Item::Item(THD *thd, Item *item):
 }
 
 
-/**
-  Decimal precision of the item.
-
-  @remark The precision must not be capped as it can be used in conjunction
-          with Item::decimals to determine the size of the integer part when
-          constructing a decimal data type.
-
-  @see Item::decimal_int_part()
-  @see Item::decimals
-*/
-
 uint Item::decimal_precision() const
 {
-  uint precision= max_length;
   Item_result restype= result_type();
 
   if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
-    precision= my_decimal_length_to_precision(max_length, decimals, unsigned_flag);
-
-  return precision;
+  {
+    uint prec= 
+      my_decimal_length_to_precision(max_length, decimals, unsigned_flag);
+    return min(prec, DECIMAL_MAX_PRECISION);
+  }
+  return min(max_length, DECIMAL_MAX_PRECISION);
 }
 
 
@@ -4917,7 +4908,9 @@ Field *Item::tmp_table_field_from_field_
   switch (field_type()) {
   case MYSQL_TYPE_DECIMAL:
   case MYSQL_TYPE_NEWDECIMAL:
-    field= Field_new_decimal::new_decimal_field(this);
+    field= new Field_new_decimal((uchar*) 0, max_length, null_ptr, 0,
+                                 Field::NONE, name, decimals, 0,
+                                 unsigned_flag);
     break;
   case MYSQL_TYPE_TINY:
     field= new Field_tiny((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
@@ -6340,9 +6333,26 @@ bool Item_direct_view_ref::fix_fields(TH
   /* view fild reference must be defined */
   DBUG_ASSERT(*ref);
   /* (*ref)->check_cols() will be made in Item_direct_ref::fix_fields */
-  if (!(*ref)->fixed &&
-      ((*ref)->fix_fields(thd, ref)))
+  if ((*ref)->fixed)
+  {
+    Item *ref_item= (*ref)->real_item();
+    if (ref_item->type() == Item::FIELD_ITEM)
+    {
+      /*
+        In some cases we need to update table read set(see bug#47150).
+        If ref item is FIELD_ITEM and fixed then field and table
+        have proper values. So we can use them for update.
+      */
+      Field *fld= ((Item_field*) ref_item)->field;
+      DBUG_ASSERT(fld && fld->table);
+      if (thd->mark_used_columns == MARK_COLUMNS_READ)
+        bitmap_set_bit(fld->table->read_set, fld->field_index);
+    }
+  }
+  else if (!(*ref)->fixed &&
+           ((*ref)->fix_fields(thd, ref)))
     return TRUE;
+
   return Item_direct_ref::fix_fields(thd, reference);
 }
 
@@ -6858,52 +6868,61 @@ void resolve_const_item(THD *thd, Item *
 }
 
 /**
-  Compare the value stored in field, with the original item.
+  Compare the value stored in field with the expression from the query.
 
-  @param field   field which the item is converted and stored in
-  @param item    original item
+  @param field   Field which the Item is stored in after conversion
+  @param item    Original expression from query
 
-  @return Return an integer greater than, equal to, or less than 0 if
-          the value stored in the field is greater than,  equal to,
-          or less than the original item
+  @return Returns an integer greater than, equal to, or less than 0 if
+          the value stored in the field is greater than, equal to,
+          or less than the original Item. A 0 may also be returned if 
+          out of memory.          
 
   @note We only use this on the range optimizer/partition pruning,
         because in some cases we can't store the value in the field
         without some precision/character loss.
 */
 
-int stored_field_cmp_to_item(Field *field, Item *item)
+int stored_field_cmp_to_item(THD *thd, Field *field, Item *item)
 {
-
   Item_result res_type=item_cmp_type(field->result_type(),
 				     item->result_type());
   if (res_type == STRING_RESULT)
   {
     char item_buff[MAX_FIELD_WIDTH];
     char field_buff[MAX_FIELD_WIDTH];
-    String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin),*item_result;
+    
+    String item_tmp(item_buff,sizeof(item_buff),&my_charset_bin);
     String field_tmp(field_buff,sizeof(field_buff),&my_charset_bin);
-    enum_field_types field_type;
-    item_result=item->val_str(&item_tmp);
+    String *item_result= item->val_str(&item_tmp);
+    /*
+      Some implementations of Item::val_str(String*) actually modify
+      the field Item::null_value, hence we can't check it earlier.
+    */
     if (item->null_value)
       return 0;
-    field->val_str(&field_tmp);
+    String *field_result= field->val_str(&field_tmp);
 
-    /*
-      If comparing DATE with DATETIME, append the time-part to the DATE.
-      So that the strings are equally formatted.
-      A DATE converted to string is 10 characters, and a DATETIME converted
-      to string is 19 characters.
-    */
-    field_type= field->type();
-    if (field_type == MYSQL_TYPE_DATE &&
-        item_result->length() == 19)
-      field_tmp.append(" 00:00:00");
-    else if (field_type == MYSQL_TYPE_DATETIME &&
-             item_result->length() == 10)
-      item_result->append(" 00:00:00");
+    enum_field_types field_type= field->type();
+
+    if (field_type == MYSQL_TYPE_DATE || field_type == MYSQL_TYPE_DATETIME)
+    {
+      enum_mysql_timestamp_type type= MYSQL_TIMESTAMP_ERROR;
 
-    return stringcmp(&field_tmp,item_result);
+      if (field_type == MYSQL_TYPE_DATE)
+        type= MYSQL_TIMESTAMP_DATE;
+
+      if (field_type == MYSQL_TYPE_DATETIME)
+        type= MYSQL_TIMESTAMP_DATETIME;
+        
+      const char *field_name= field->field_name;
+      MYSQL_TIME field_time, item_time;
+      get_mysql_time_from_str(thd, field_result, type, field_name, &field_time);
+      get_mysql_time_from_str(thd, item_result, type, field_name,  &item_time);
+
+      return my_time_compare(&field_time, &item_time);
+    }
+    return stringcmp(field_result, item_result);
   }
   if (res_type == INT_RESULT)
     return 0;					// Both are of type int

=== modified file 'sql/item.h'
--- a/sql/item.h	2009-10-15 21:38:29 +0000
+++ b/sql/item.h	2009-11-10 15:15:12 +0000
@@ -766,10 +766,9 @@ public:
   virtual cond_result eq_cmp_result() const { return COND_OK; }
   inline uint float_length(uint decimals_par) const
   { return decimals != NOT_FIXED_DEC ? (DBL_DIG+2+decimals_par) : DBL_DIG+8;}
-  /** Returns the uncapped decimal precision of this item. */
   virtual uint decimal_precision() const;
   inline int decimal_int_part() const
-  { return decimal_precision() - decimals; }
+  { return my_decimal_int_part(decimal_precision(), decimals); }
   /* 
     Returns true if this is constant (during query execution, i.e. its value
     will not change until next fix_fields) and its value is known.
@@ -3160,4 +3159,4 @@ void mark_select_range_as_dependent(THD 
 extern Cached_item *new_Cached_item(THD *thd, Item *item);
 extern Item_result item_cmp_type(Item_result a,Item_result b);
 extern void resolve_const_item(THD *thd, Item **ref, Item *cmp_item);
-extern int stored_field_cmp_to_item(Field *field, Item *item);
+extern int stored_field_cmp_to_item(THD *thd, Field *field, Item *item);

=== modified file 'sql/item_cmpfunc.cc'
--- a/sql/item_cmpfunc.cc	2009-10-15 21:38:29 +0000
+++ b/sql/item_cmpfunc.cc	2009-11-10 15:15:12 +0000
@@ -189,6 +189,7 @@ enum_field_types agg_field_type(Item **i
     collect_cmp_types()
       items             Array of items to collect types from
       nitems            Number of items in the array
+      skip_nulls        Don't collect types of NULL items if TRUE
 
   DESCRIPTION
     This function collects different result types for comparison of the first
@@ -199,7 +200,7 @@ enum_field_types agg_field_type(Item **i
     Bitmap of collected types - otherwise
 */
 
-static uint collect_cmp_types(Item **items, uint nitems)
+static uint collect_cmp_types(Item **items, uint nitems, bool skip_nulls= FALSE)
 {
   uint i;
   uint found_types;
@@ -208,6 +209,8 @@ static uint collect_cmp_types(Item **ite
   found_types= 0;
   for (i= 1; i < nitems ; i++)
   {
+    if (skip_nulls && items[i]->type() == Item::NULL_ITEM)
+      continue; // Skip NULL constant items
     if ((left_result == ROW_RESULT || 
          items[i]->result_type() == ROW_RESULT) &&
         cmp_row_type(items[0], items[i]))
@@ -215,6 +218,12 @@ static uint collect_cmp_types(Item **ite
     found_types|= 1<< (uint)item_cmp_type(left_result,
                                            items[i]->result_type());
   }
+  /*
+   Even if all right-hand items are NULLs and we are skipping them all, we need
+   at least one type bit in the found_type bitmask.
+  */
+  if (skip_nulls && !found_types)
+    found_types= 1 << (uint)left_result;
   return found_types;
 }
 
@@ -627,56 +636,51 @@ int Arg_comparator::set_compare_func(Ite
   return 0;
 }
 
-
 /**
-  @brief Convert date provided in a string to the int representation.
+  Parse date provided in a string to a MYSQL_TIME.
 
-  @param[in]   thd        thread handle
-  @param[in]   str        a string to convert
-  @param[in]   warn_type  type of the timestamp for issuing the warning
-  @param[in]   warn_name  field name for issuing the warning
-  @param[out]  error_arg  could not extract a DATE or DATETIME
-
-  @details Convert date provided in the string str to the int
-    representation.  If the string contains wrong date or doesn't
-    contain it at all then a warning is issued.  The warn_type and
-    the warn_name arguments are used as the name and the type of the
-    field when issuing the warning.  If any input was discarded
-    (trailing or non-timestampy characters), was_cut will be non-zero.
-    was_type will return the type str_to_datetime() could correctly
-    extract.
-
-  @return
-    converted value. 0 on error and on zero-dates -- check 'failure'
+  @param[in]   thd        Thread handle
+  @param[in]   str        A string to convert
+  @param[in]   warn_type  Type of the timestamp for issuing the warning
+  @param[in]   warn_name  Field name for issuing the warning
+  @param[out]  l_time     The MYSQL_TIME objects is initialized.
+
+  Parses a date provided in the string str into a MYSQL_TIME object. If the
+  string contains an incorrect date or doesn't correspond to a date at all
+  then a warning is issued. The warn_type and the warn_name arguments are used
+  as the name and the type of the field when issuing the warning. If any input
+  was discarded (trailing or non-timestamp-y characters), return value will be
+  TRUE.
+
+  @return Status flag
+  @retval FALSE Success.
+  @retval True Indicates failure.
 */
 
-static ulonglong
-get_date_from_str(THD *thd, String *str, timestamp_type warn_type,
-                  char *warn_name, bool *error_arg)
+bool get_mysql_time_from_str(THD *thd, String *str, timestamp_type warn_type, 
+                             const char *warn_name, MYSQL_TIME *l_time)
 {
-  ulonglong value= 0;
+  bool value;
   int error;
-  MYSQL_TIME l_time;
-  enum_mysql_timestamp_type ret;
+  enum_mysql_timestamp_type timestamp_type;
 
-  ret= str_to_datetime(str->ptr(), str->length(), &l_time,
-                       (TIME_FUZZY_DATE | MODE_INVALID_DATES |
-                        (thd->variables.sql_mode &
-                         (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE))),
-                       &error);
+  timestamp_type= 
+    str_to_datetime(str->ptr(), str->length(), l_time,
+                    (TIME_FUZZY_DATE | MODE_INVALID_DATES |
+                     (thd->variables.sql_mode &
+                      (MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE))),
+                    &error);
 
-  if (ret == MYSQL_TIMESTAMP_DATETIME || ret == MYSQL_TIMESTAMP_DATE)
-  {
+  if (timestamp_type == MYSQL_TIMESTAMP_DATETIME || 
+      timestamp_type == MYSQL_TIMESTAMP_DATE)
     /*
       Do not return yet, we may still want to throw a "trailing garbage"
       warning.
     */
-    *error_arg= FALSE;
-    value= TIME_to_ulonglong_datetime(&l_time);
-  }
+    value= FALSE;
   else
   {
-    *error_arg= TRUE;
+    value= TRUE;
     error= 1;                                   /* force warning */
   }
 
@@ -689,6 +693,37 @@ get_date_from_str(THD *thd, String *str,
 }
 
 
+/**
+  @brief Convert date provided in a string to the int representation.
+
+  @param[in]   thd        thread handle
+  @param[in]   str        a string to convert
+  @param[in]   warn_type  type of the timestamp for issuing the warning
+  @param[in]   warn_name  field name for issuing the warning
+  @param[out]  error_arg  could not extract a DATE or DATETIME
+
+  @details Convert date provided in the string str to the int
+    representation.  If the string contains wrong date or doesn't
+    contain it at all then a warning is issued.  The warn_type and
+    the warn_name arguments are used as the name and the type of the
+    field when issuing the warning.
+
+  @return
+    converted value. 0 on error and on zero-dates -- check 'failure'
+*/
+static ulonglong get_date_from_str(THD *thd, String *str, 
+                                   timestamp_type warn_type, 
+                                   const char *warn_name, bool *error_arg)
+{
+  MYSQL_TIME l_time;
+  *error_arg= get_mysql_time_from_str(thd, str, warn_type, warn_name, &l_time);
+
+  if (*error_arg)
+    return 0;
+  return TIME_to_ulonglong_datetime(&l_time);
+}
+
+
 /*
   Check whether compare_datetime() can be used to compare items.
 
@@ -1549,61 +1584,73 @@ longlong Item_in_optimizer::val_int()
   
   if (cache->null_value)
   {
+    /*
+      We're evaluating 
+      "<outer_value_list> [NOT] IN (SELECT <inner_value_list>...)" 
+      where one or more of the outer values is NULL. 
+    */
     if (((Item_in_subselect*)args[1])->is_top_level_item())
     {
       /*
-        We're evaluating "NULL IN (SELECT ...)". The result can be NULL or
-        FALSE, and we can return one instead of another. Just return NULL.
+        We're evaluating a top level item, e.g. 
+	"<outer_value_list> IN (SELECT <inner_value_list>...)",
+	and in this case a NULL value in the outer_value_list means
+        that the result shall be NULL/FALSE (makes no difference for
+        top level items). The cached value is NULL, so just return
+        NULL.
       */
       null_value= 1;
     }
     else
     {
-      if (!((Item_in_subselect*)args[1])->is_correlated &&
-          result_for_null_param != UNKNOWN)
+      /*
+	We're evaluating an item where a NULL value in either the
+        outer or inner value list does not automatically mean that we
+        can return NULL/FALSE. An example of such a query is
+        "<outer_value_list> NOT IN (SELECT <inner_value_list>...)" 
+        The result when there is at least one NULL value is: NULL if the
+        SELECT evaluated over the non-NULL values produces at least
+        one row, FALSE otherwise
+      */
+      Item_in_subselect *item_subs=(Item_in_subselect*)args[1]; 
+      bool all_left_cols_null= true;
+      const uint ncols= cache->cols();
+
+      /*
+        Turn off the predicates that are based on column compares for
+        which the left part is currently NULL
+      */
+      for (uint i= 0; i < ncols; i++)
       {
-        /* Use cached value from previous execution */
-        null_value= result_for_null_param;
+        if (cache->element_index(i)->null_value)
+          item_subs->set_cond_guard_var(i, FALSE);
+        else 
+          all_left_cols_null= false;
       }
-      else
+
+      if (!((Item_in_subselect*)args[1])->is_correlated && 
+          all_left_cols_null && result_for_null_param != UNKNOWN)
       {
-        /*
-          We're evaluating "NULL IN (SELECT ...)". The result is:
-             FALSE if SELECT produces an empty set, or
-             NULL  otherwise.
-          We disable the predicates we've pushed down into subselect, run the
-          subselect and see if it has produced any rows.
+        /* 
+           This is a non-correlated subquery, all values in the outer
+           value list are NULL, and we have already evaluated the
+           subquery for all NULL values: Return the same result we
+           did last time without evaluating the subquery.
         */
-        Item_in_subselect *item_subs=(Item_in_subselect*)args[1]; 
-        if (cache->cols() == 1)
-        {
-          item_subs->set_cond_guard_var(0, FALSE);
-          (void) args[1]->val_bool_result();
-          result_for_null_param= null_value= !item_subs->engine->no_rows();
-          item_subs->set_cond_guard_var(0, TRUE);
-        }
-        else
-        {
-          uint i;
-          uint ncols= cache->cols();
-          /*
-            Turn off the predicates that are based on column compares for
-            which the left part is currently NULL
-          */
-          for (i= 0; i < ncols; i++)
-          {
-            if (cache->element_index(i)->null_value)
-              item_subs->set_cond_guard_var(i, FALSE);
-          }
-          
-          (void) args[1]->val_bool_result();
-          result_for_null_param= null_value= !item_subs->engine->no_rows();
-          
-          /* Turn all predicates back on */
-          for (i= 0; i < ncols; i++)
-            item_subs->set_cond_guard_var(i, TRUE);
-        }
+        null_value= result_for_null_param;
+      } 
+      else 
+      {
+        /* The subquery has to be evaluated */
+        (void) args[1]->val_bool_result();
+        null_value= !item_subs->engine->no_rows();
+        if (all_left_cols_null)
+          result_for_null_param= null_value;
       }
+
+      /* Turn all predicates back on */
+      for (uint i= 0; i < ncols; i++)
+        item_subs->set_cond_guard_var(i, TRUE);
     }
     return 0;
   }
@@ -2181,7 +2228,7 @@ uint Item_func_ifnull::decimal_precision
   int arg1_int_part= args[1]->decimal_int_part();
   int max_int_part= max(arg0_int_part, arg1_int_part);
   int precision= max_int_part + decimals;
-  return precision;
+  return min(precision, DECIMAL_MAX_PRECISION);
 }
 
 
@@ -2365,7 +2412,7 @@ uint Item_func_if::decimal_precision() c
   int arg1_prec= args[1]->decimal_int_part();
   int arg2_prec= args[2]->decimal_int_part();
   int precision=max(arg1_prec,arg2_prec) + decimals;
-  return precision;
+  return min(precision, DECIMAL_MAX_PRECISION);
 }
 
 
@@ -2782,7 +2829,7 @@ uint Item_func_case::decimal_precision()
 
   if (else_expr_num != -1) 
     set_if_bigger(max_int_part, args[else_expr_num]->decimal_int_part());
-  return max_int_part + decimals;
+  return min(max_int_part + decimals, DECIMAL_MAX_PRECISION);
 }
 
 
@@ -3523,7 +3570,7 @@ void Item_func_in::fix_length_and_dec()
   uint type_cnt= 0, i;
   Item_result cmp_type= STRING_RESULT;
   left_result_type= args[0]->result_type();
-  if (!(found_types= collect_cmp_types(args, arg_count)))
+  if (!(found_types= collect_cmp_types(args, arg_count, true)))
     return;
   
   for (arg= args + 1, arg_end= args + arg_count; arg != arg_end ; arg++)
@@ -3701,9 +3748,11 @@ void Item_func_in::fix_length_and_dec()
       uint j=0;
       for (uint i=1 ; i < arg_count ; i++)
       {
-	array->set(j,args[i]);
 	if (!args[i]->null_value)			// Skip NULL values
+        {
+          array->set(j,args[i]);
 	  j++;
+        }
 	else
 	  have_null= 1;
       }

=== modified file 'sql/item_cmpfunc.h'
--- a/sql/item_cmpfunc.h	2009-08-20 15:51:02 +0000
+++ b/sql/item_cmpfunc.h	2009-11-10 15:15:12 +0000
@@ -1722,3 +1722,6 @@ inline Item *and_conds(Item *a, Item *b)
 }
 
 Item *and_expressions(Item *a, Item *b, Item **org_item);
+
+bool get_mysql_time_from_str(THD *thd, String *str, timestamp_type warn_type, 
+                             const char *warn_name, MYSQL_TIME *l_time);

=== modified file 'sql/item_func.cc'
--- a/sql/item_func.cc	2009-10-15 21:38:29 +0000
+++ b/sql/item_func.cc	2009-11-10 15:15:12 +0000
@@ -435,8 +435,7 @@ bool Item_func::eq(const Item *item, boo
 
 Field *Item_func::tmp_table_field(TABLE *table)
 {
-  Field *field;
-  LINT_INIT(field);
+  Field *field= NULL;
 
   switch (result_type()) {
   case INT_RESULT:
@@ -451,8 +450,45 @@ Field *Item_func::tmp_table_field(TABLE 
   case STRING_RESULT:
     return make_string_field(table);
   case DECIMAL_RESULT:
-    field= Field_new_decimal::new_decimal_field(this);
+  {
+    uint8 dec= decimals;
+    uint8 intg= decimal_precision() - dec;
+    uint32 len= max_length;
+
+    /*
+      Trying to put too many digits overall in a DECIMAL(prec,dec)
+      will always throw a warning. We must limit dec to
+      DECIMAL_MAX_SCALE however to prevent an assert() later.
+    */
+
+    if (dec > 0)
+    {
+      int overflow;
+
+      dec= min(dec, DECIMAL_MAX_SCALE);
+
+      /*
+        If the value still overflows the field with the corrected dec,
+        we'll throw out decimals rather than integers. This is still
+        bad and of course throws a truncation warning.
+      */
+
+      const int required_length=
+        my_decimal_precision_to_length(intg + dec, dec,
+                                                     unsigned_flag);
+
+      overflow= required_length - len;
+
+      if (overflow > 0)
+        dec= max(0, dec - overflow);            // too long, discard fract
+      else
+        /* Corrected value fits. */
+        len= required_length;
+    }
+
+    field= new Field_new_decimal(len, maybe_null, name, dec, unsigned_flag);
     break;
+  }
   case ROW_RESULT:
   default:
     // This case should never be chosen
@@ -4239,9 +4275,8 @@ void Item_func_set_user_var::save_item_r
 bool
 Item_func_set_user_var::update()
 {
-  bool res;
+  bool res= 0;
   DBUG_ENTER("Item_func_set_user_var::update");
-  LINT_INIT(res);
 
   switch (cached_result_type) {
   case REAL_RESULT:
@@ -4744,19 +4779,6 @@ void Item_func_get_user_var::fix_length_
 }
 
 
-uint Item_func_get_user_var::decimal_precision() const
-{
-  uint precision= max_length;
-  Item_result restype= result_type();
-
-  /* Default to maximum as the precision is unknown a priori. */
-  if ((restype == DECIMAL_RESULT) || (restype == INT_RESULT))
-    precision= DECIMAL_MAX_PRECISION;
-
-  return precision;
-}
-
-
 bool Item_func_get_user_var::const_item() const
 {
   return (!var_entry || current_thd->query_id != var_entry->update_query_id);

=== modified file 'sql/item_func.h'
--- a/sql/item_func.h	2009-10-15 21:38:29 +0000
+++ b/sql/item_func.h	2009-11-10 15:15:12 +0000
@@ -1393,7 +1393,6 @@ public:
   table_map used_tables() const
   { return const_item() ? 0 : RAND_TABLE_BIT; }
   bool eq(const Item *item, bool binary_cmp) const;
-  uint decimal_precision() const;
 private:
   bool set_value(THD *thd, sp_rcontext *ctx, Item **it);
 

=== modified file 'sql/item_geofunc.cc'
--- a/sql/item_geofunc.cc	2009-07-10 23:12:13 +0000
+++ b/sql/item_geofunc.cc	2009-10-24 06:57:31 +0000
@@ -84,7 +84,9 @@ String *Item_func_geometry_from_wkb::val
 
   if (args[0]->field_type() == MYSQL_TYPE_GEOMETRY)
   {
-    return args[0]->val_str(str);
+    String *str_ret= args[0]->val_str(str);
+    null_value= args[0]->null_value;
+    return str_ret;
   }
 
   wkb= args[0]->val_str(&arg_val);
@@ -94,7 +96,10 @@ String *Item_func_geometry_from_wkb::val
 
   str->set_charset(&my_charset_bin);
   if (str->reserve(SRID_SIZE, 512))
-    return 0;
+  {
+    null_value= TRUE;                           /* purecov: inspected */
+    return 0;                                   /* purecov: inspected */
+  }
   str->length(0);
   str->q_append(srid);
   if ((null_value= 

=== modified file 'sql/item_strfunc.cc'
--- a/sql/item_strfunc.cc	2009-09-07 20:50:10 +0000
+++ b/sql/item_strfunc.cc	2009-11-10 15:15:12 +0000
@@ -632,6 +632,7 @@ String *Item_func_concat_ws::val_str(Str
   String tmp_sep_str(tmp_str_buff, sizeof(tmp_str_buff),default_charset_info),
          *sep_str, *res, *res2,*use_as_buff;
   uint i;
+  bool is_const= 0;
 
   null_value=0;
   if (!(sep_str= args[0]->val_str(&tmp_sep_str)))
@@ -645,7 +646,11 @@ String *Item_func_concat_ws::val_str(Str
   // If not, return the empty string
   for (i=1; i < arg_count; i++)
     if ((res= args[i]->val_str(str)))
+    {
+      is_const= args[i]->const_item() || !args[i]->used_tables();
       break;
+    }
+
   if (i ==  arg_count)
     return &my_empty_string;
 
@@ -663,7 +668,7 @@ String *Item_func_concat_ws::val_str(Str
 			  current_thd->variables.max_allowed_packet);
       goto null;
     }
-    if (res->alloced_length() >=
+    if (!is_const && res->alloced_length() >=
 	res->length() + sep_str->length() + res2->length())
     {						// Use old buffer
       res->append(*sep_str);			// res->length() > 0 always

=== modified file 'sql/item_subselect.cc'
--- a/sql/item_subselect.cc	2009-09-15 10:46:35 +0000
+++ b/sql/item_subselect.cc	2009-11-10 15:15:12 +0000
@@ -159,17 +159,14 @@ bool Item_subselect::fix_fields(THD *thd
     return TRUE;
   
   in_fix_fields++;
-  res= engine->prepare();
 
-  // all transformation is done (used by prepared statements)
-  changed= 1;
-
-  if (!res)
+  if (!(res= engine->prepare()))
   {
+    // all transformation is done (used by prepared statements)
+    changed= 1;
+
     if (substitution)
     {
-      int ret= 0;
-
       // did we changed top item of WHERE condition
       if (unit->outer_select()->where == (*ref))
 	unit->outer_select()->where= substitution; // correct WHERE for PS
@@ -183,22 +180,20 @@ bool Item_subselect::fix_fields(THD *thd
       substitution= 0;
       thd->where= "checking transformed subquery";
       if (!(*ref)->fixed)
-	ret= (*ref)->fix_fields(thd, ref);
-      thd->where= save_where;
-      in_fix_fields--;
-      return ret;
+	res= (*ref)->fix_fields(thd, ref);
+      goto end;
     }
     // Is it one field subselect?
     if (engine->cols() > max_columns)
     {
       my_error(ER_OPERAND_COLUMNS, MYF(0), 1);
-      in_fix_fields--;
-      return TRUE;
+      res= 1;
+      goto end;
     }
     fix_length_and_dec();
   }
   else
-    goto err;
+    goto end;
   
   if ((uncacheable= engine->uncacheable()))
   {
@@ -208,7 +203,7 @@ bool Item_subselect::fix_fields(THD *thd
   }
   fixed= 1;
 
-err:
+end:
   in_fix_fields--;
   thd->where= save_where;
   return res;
@@ -339,9 +334,14 @@ void Item_subselect::update_used_tables(
 
 void Item_subselect::print(String *str, enum_query_type query_type)
 {
-  str->append('(');
-  engine->print(str, query_type);
-  str->append(')');
+  if (engine)
+  {
+    str->append('(');
+    engine->print(str, query_type);
+    str->append(')');
+  }
+  else
+    str->append("(...)");
 }
 
 
@@ -1977,6 +1977,7 @@ int subselect_single_select_engine::exec
               tab->read_record.record= tab->table->record[0];
               tab->read_record.thd= join->thd;
               tab->read_record.ref_length= tab->table->file->ref_length;
+              tab->read_record.unlock_row= rr_unlock_row;
               *(last_changed_tab++)= tab;
               break;
             }

=== modified file 'sql/item_sum.cc'
--- a/sql/item_sum.cc	2009-10-15 21:38:29 +0000
+++ b/sql/item_sum.cc	2009-11-10 15:15:12 +0000
@@ -517,7 +517,8 @@ Field *Item_sum::create_tmp_field(bool g
                                name, table->s, collation.collation);
     break;
   case DECIMAL_RESULT:
-    field= Field_new_decimal::new_decimal_field(this);
+    field= new Field_new_decimal(max_length, maybe_null, name,
+                                 decimals, unsigned_flag);
     break;
   case ROW_RESULT:
   default:

=== modified file 'sql/item_timefunc.cc'
--- a/sql/item_timefunc.cc	2009-10-15 21:38:29 +0000
+++ b/sql/item_timefunc.cc	2009-11-10 15:15:12 +0000
@@ -278,9 +278,9 @@ static bool extract_date_time(DATE_TIME_
   int  strict_week_number_year= -1;
   int frac_part;
   bool usa_time= 0;
-  bool sunday_first_n_first_week_non_iso;
-  bool strict_week_number;
-  bool strict_week_number_year_type;
+  bool UNINIT_VAR(sunday_first_n_first_week_non_iso);
+  bool UNINIT_VAR(strict_week_number);
+  bool UNINIT_VAR(strict_week_number_year_type);
   const char *val_begin= val;
   const char *val_end= val + length;
   const char *ptr= format->format.str;
@@ -1350,15 +1350,11 @@ bool get_interval_value(Item *args,inter
 			       String *str_value, INTERVAL *interval)
 {
   ulonglong array[5];
-  longlong value;
-  const char *str;
-  size_t length;
+  longlong UNINIT_VAR(value);
+  const char *UNINIT_VAR(str);
+  size_t UNINIT_VAR(length);
   CHARSET_INFO *cs=str_value->charset();
 
-  LINT_INIT(value);
-  LINT_INIT(str);
-  LINT_INIT(length);
-
   bzero((char*) interval,sizeof(*interval));
   if ((int) int_type <= INTERVAL_MICROSECOND)
   {

=== modified file 'sql/item_xmlfunc.cc'
--- a/sql/item_xmlfunc.cc	2009-09-07 20:50:10 +0000
+++ b/sql/item_xmlfunc.cc	2009-11-10 15:15:12 +0000
@@ -1354,8 +1354,7 @@ my_xpath_lex_scan(MY_XPATH *xpath,
                   MY_XPATH_LEX *lex, const char *beg, const char *end)
 {
   int ch, ctype, length;
-  for ( ; beg < end && *beg == ' ' ; beg++) // skip leading spaces
-    ;
+  for ( ; beg < end && *beg == ' ' ; beg++) ; // skip leading spaces
   lex->beg= beg;
   
   if (beg >= end)
@@ -1424,8 +1423,7 @@ my_xpath_lex_scan(MY_XPATH *xpath,
 
   if (my_xdigit(ch)) // a sequence of digits
   {
-    for ( ; beg < end && my_xdigit(*beg) ; beg++)
-      ;
+    for ( ; beg < end && my_xdigit(*beg) ; beg++) ;
     lex->end= beg;
     lex->term= MY_XPATH_LEX_DIGITS;
     return;
@@ -1433,8 +1431,7 @@ my_xpath_lex_scan(MY_XPATH *xpath,
 
   if (ch == '"' || ch == '\'')  // a string: either '...' or "..."
   {
-    for ( ; beg < end && *beg != ch ; beg++)
-      ;
+    for ( ; beg < end && *beg != ch ; beg++) ;
     if (beg < end)
     {
       lex->end= beg+1;

=== modified file 'sql/log.cc'
--- a/sql/log.cc	2009-11-06 17:22:32 +0000
+++ b/sql/log.cc	2009-11-10 15:15:12 +0000
@@ -153,7 +153,7 @@ private:
 class binlog_trx_data {
 public:
   binlog_trx_data()
-    : at_least_one_stmt(0), incident(FALSE), m_pending(0),
+    : at_least_one_stmt_committed(0), incident(FALSE), m_pending(0),
     before_stmt_pos(MY_OFF_T_UNDEF)
   {
     trans_log.end_of_file= max_binlog_cache_size;
@@ -182,7 +182,10 @@ public:
   {
     DBUG_PRINT("info", ("truncating to position %lu", (ulong) pos));
     DBUG_PRINT("info", ("before_stmt_pos=%lu", (ulong) pos));
-    delete pending();
+    if (pending())
+    {
+      delete pending();
+    }
     set_pending(0);
     reinit_io_cache(&trans_log, WRITE_CACHE, pos, 0, 0);
     trans_log.end_of_file= max_binlog_cache_size;
@@ -192,12 +195,12 @@ public:
     /*
       The only valid positions that can be truncated to are at the
       beginning of a statement. We are relying on this fact to be able
-      to set the at_least_one_stmt flag correctly. In other word, if
+      to set the at_least_one_stmt_committed flag correctly. In other word, if
       we are truncating to the beginning of the transaction cache,
       there will be no statements in the cache, otherwhise, we will
       have at least one statement in the transaction cache.
      */
-    at_least_one_stmt= (pos > 0);
+    at_least_one_stmt_committed= (pos > 0);
   }
 
   /*
@@ -239,7 +242,7 @@ public:
     Boolean that is true if there is at least one statement in the
     transaction cache.
   */
-  bool at_least_one_stmt;
+  bool at_least_one_stmt_committed;
   bool incident;
 
 private:
@@ -1035,14 +1038,10 @@ bool LOGGER::general_log_write(THD *thd,
   Log_event_handler **current_handler= general_log_handler_list;
   char user_host_buff[MAX_USER_HOST_SIZE + 1];
   Security_context *sctx= thd->security_ctx;
-  ulong id;
   uint user_host_len= 0;
   time_t current_time;
 
-  if (thd)
-    id= thd->thread_id;                 /* Normal thread */
-  else
-    id= 0;                              /* Log from connect handler */
+  DBUG_ASSERT(thd);
 
   lock_shared();
   if (!opt_log)
@@ -1061,7 +1060,7 @@ bool LOGGER::general_log_write(THD *thd,
   while (*current_handler)
     error|= (*current_handler++)->
       log_general(thd, current_time, user_host_buff,
-                  user_host_len, id,
+                  user_host_len, thd->thread_id,
                   command_name[(uint) command].str,
                   command_name[(uint) command].length,
                   query, query_length,
@@ -1287,7 +1286,7 @@ static bool stmt_has_updated_trans_table
 {
   Ha_trx_info *ha_info;
 
-  for (ha_info= thd->transaction.stmt.ha_list; ha_info; ha_info= ha_info->next())
+  for (ha_info= thd->transaction.stmt.ha_list; ha_info && ha_info->is_started(); ha_info= ha_info->next())
   {
     if (ha_info->is_trx_read_write() && ha_info->ht() != binlog_hton)
       return (TRUE);
@@ -1535,9 +1534,9 @@ static int binlog_commit(handlerton *hto
   /*
     We commit the transaction if:
 
-     - We are not in a transaction and committing a statement, or
+    - We are not in a transaction and committing a statement, or
 
-     - We are in a transaction and a full transaction is committed
+    - We are in a transaction and a full transaction is committed
 
     Otherwise, we accumulate the statement
   */
@@ -1550,21 +1549,18 @@ static int binlog_commit(handlerton *hto
               YESNO(in_transaction),
               YESNO(thd->transaction.all.modified_non_trans_table),
               YESNO(thd->transaction.stmt.modified_non_trans_table)));
-  if (thd->options & OPTION_BIN_LOG)
-  {
-    if (!in_transaction || all)
-    {
-      Query_log_event qev(thd, STRING_WITH_LEN("COMMIT"), TRUE, TRUE, 0);
-      error= binlog_end_trans(thd, trx_data, &qev, all);
-      goto end;
-    }
-  }
-  else
+
+  if (!in_transaction || all ||
+      (!all && !trx_data->at_least_one_stmt_committed &&
+       !stmt_has_updated_trans_table(thd) &&
+       thd->transaction.stmt.modified_non_trans_table))
   {
-    trx_data->reset();
+    Query_log_event qev(thd, STRING_WITH_LEN("COMMIT"), TRUE, TRUE, 0);
+    error= binlog_end_trans(thd, trx_data, &qev, all);
   }
 
-end:
+  trx_data->at_least_one_stmt_committed = my_b_tell(&trx_data->trans_log) > 0;
+
   if (!all)
     trx_data->before_stmt_pos = MY_OFF_T_UNDEF; // part of the stmt commit
   DBUG_RETURN(error);
@@ -1630,15 +1626,18 @@ static int binlog_rollback(handlerton *h
   {
    /*
       We flush the cache with a rollback, wrapped in a beging/rollback if:
-        . aborting a transcation that modified a non-transactional table or;
+        . aborting a transaction that modified a non-transactional table;
         . aborting a statement that modified both transactional and
-          non-transctional tables but which is not in the boundaries of any
-          transaction;
+          non-transactional tables but which is not in the boundaries of any
+          transaction or there was no early change;
         . the OPTION_KEEP_LOG is activate.
     */
     if ((all && thd->transaction.all.modified_non_trans_table) ||
         (!all && thd->transaction.stmt.modified_non_trans_table &&
          !(thd->options & (OPTION_BEGIN | OPTION_NOT_AUTOCOMMIT))) ||
+        (!all && thd->transaction.stmt.modified_non_trans_table &&
+         !trx_data->at_least_one_stmt_committed &&
+         thd->current_stmt_binlog_row_based) ||
         ((thd->options & OPTION_KEEP_LOG)))
     {
       Query_log_event qev(thd, STRING_WITH_LEN("ROLLBACK"), TRUE, TRUE, 0);
@@ -1730,7 +1729,7 @@ static int binlog_savepoint_set(handlert
   int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED);
   int const error=
     thd->binlog_query(THD::STMT_QUERY_TYPE,
-                      thd->query, thd->query_length, TRUE, FALSE, errcode);
+                      thd->query(), thd->query_length(), TRUE, FALSE, errcode);
   DBUG_RETURN(error);
 }
 
@@ -1749,7 +1748,7 @@ static int binlog_savepoint_rollback(han
     int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED);
     int error=
       thd->binlog_query(THD::STMT_QUERY_TYPE,
-                        thd->query, thd->query_length, TRUE, FALSE, errcode);
+                        thd->query(), thd->query_length(), TRUE, FALSE, errcode);
     DBUG_RETURN(error);
   }
   binlog_trans_log_truncate(thd, *(my_off_t*)sv);
@@ -3641,7 +3640,7 @@ void MYSQL_BIN_LOG::new_file_impl(bool n
   }
   old_name=name;
   name=0;				// Don't free name
-  close(LOG_CLOSE_TO_BE_OPENED);
+  close(LOG_CLOSE_TO_BE_OPENED | LOG_CLOSE_INDEX);
 
   /*
      Note that at this point, log_state != LOG_CLOSED (important for is_open()).
@@ -3656,8 +3655,10 @@ void MYSQL_BIN_LOG::new_file_impl(bool n
      trigger temp tables deletion on slaves.
   */
 
-  open(old_name, log_type, new_name_ptr,
-       io_cache_type, no_auto_events, max_size, 1);
+  /* reopen index binlog file, BUG#34582 */
+  if (!open_index_file(index_file_name, 0))
+    open(old_name, log_type, new_name_ptr, 
+         io_cache_type, no_auto_events, max_size, 1);
   my_free(old_name,MYF(0));
 
 end:
@@ -4096,8 +4097,8 @@ bool MYSQL_BIN_LOG::write(Log_event *eve
       binlog_[wild_]{do|ignore}_table?" (WL#1049)"
     */
     const char *local_db= event_info->get_db();
-    if ((thd && !(thd->options & OPTION_BIN_LOG)) ||
-	(!binlog_filter->db_ok(local_db)))
+    if ((!(thd->options & OPTION_BIN_LOG)) ||
+        (!binlog_filter->db_ok(local_db)))
     {
       VOID(pthread_mutex_unlock(&LOCK_log));
       DBUG_RETURN(0);

=== modified file 'sql/log_event.cc'
--- a/sql/log_event.cc	2009-10-15 21:38:29 +0000
+++ b/sql/log_event.cc	2009-11-10 15:15:12 +0000
@@ -1851,6 +1851,7 @@ Rows_log_event::print_verbose_one_row(IO
 {
   const uchar *value0= value;
   const uchar *null_bits= value;
+  uint null_bit_index= 0;
   char typestr[64]= "";
   
   value+= (m_width + 7) / 8;
@@ -1859,7 +1860,8 @@ Rows_log_event::print_verbose_one_row(IO
   
   for (size_t i= 0; i < td->size(); i ++)
   {
-    int is_null= (null_bits[i / 8] >> (i % 8))  & 0x01;
+    int is_null= (null_bits[null_bit_index / 8] 
+                  >> (null_bit_index % 8))  & 0x01;
 
     if (bitmap_is_set(cols_bitmap, i) == 0)
       continue;
@@ -1896,6 +1898,8 @@ Rows_log_event::print_verbose_one_row(IO
     }
     
     my_b_printf(file, "\n");
+    
+    null_bit_index++;
   }
   return value - value0;
 }
@@ -3038,7 +3042,7 @@ int Query_log_event::do_apply_event(Rela
     thd->query_id = next_query_id();
     VOID(pthread_mutex_unlock(&LOCK_thread_count));
     thd->variables.pseudo_thread_id= thread_id;		// for temp tables
-    DBUG_PRINT("query",("%s",thd->query));
+    DBUG_PRINT("query",("%s", thd->query()));
 
     if (ignored_error_code((expected_error= error_code)) ||
 	!unexpected_error_code(expected_error))
@@ -3132,7 +3136,7 @@ int Query_log_event::do_apply_event(Rela
       
       /* Execute the query (note that we bypass dispatch_command()) */
       const char* found_semicolon= NULL;
-      mysql_parse(thd, thd->query, thd->query_length, &found_semicolon);
+      mysql_parse(thd, thd->query(), thd->query_length(), &found_semicolon);
       log_slow_statement(thd);
     }
     else
@@ -3144,7 +3148,7 @@ int Query_log_event::do_apply_event(Rela
         we exit gracefully; otherwise we warn about the bad error and tell DBA
         to check/fix it.
       */
-      if (mysql_test_parse_for_slave(thd, thd->query, thd->query_length))
+      if (mysql_test_parse_for_slave(thd, thd->query(), thd->query_length()))
         clear_all_errors(thd, const_cast<Relay_log_info*>(rli)); /* Can ignore query */
       else
       {
@@ -3154,7 +3158,7 @@ Query partially completed on the master 
 and was aborted. There is a chance that your master is inconsistent at this \
 point. If you are sure that your master is ok, run this query manually on the \
 slave and then restart the slave with SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1; \
-START SLAVE; . Query: '%s'", expected_error, thd->query);
+START SLAVE; . Query: '%s'", expected_error, thd->query());
         thd->is_slave_error= 1;
       }
       goto end;
@@ -3162,7 +3166,7 @@ START SLAVE; . Query: '%s'", expected_er
 
     /* If the query was not ignored, it is printed to the general log */
     if (!thd->is_error() || thd->main_da.sql_errno() != ER_SLAVE_IGNORED_TABLE)
-      general_log_write(thd, COM_QUERY, thd->query, thd->query_length);
+      general_log_write(thd, COM_QUERY, thd->query(), thd->query_length());
 
 compare_errors:
 
@@ -3854,6 +3858,7 @@ bool Format_description_log_event::write
 #if defined(HAVE_REPLICATION) && !defined(MYSQL_CLIENT)
 int Format_description_log_event::do_apply_event(Relay_log_info const *rli)
 {
+  int ret= 0;
   DBUG_ENTER("Format_description_log_event::do_apply_event");
 
 #ifdef USING_TRANSACTIONS
@@ -3895,17 +3900,21 @@ int Format_description_log_event::do_app
       0, then 96, then jump to first really asked event (which is
       >96). So this is ok.
     */
-    DBUG_RETURN(Start_log_event_v3::do_apply_event(rli));
+    ret= Start_log_event_v3::do_apply_event(rli);
   }
-  DBUG_RETURN(0);
+
+  if (!ret)
+  {
+    /* Save the information describing this binlog */
+    delete rli->relay_log.description_event_for_exec;
+    const_cast<Relay_log_info *>(rli)->relay_log.description_event_for_exec= this;
+  }
+
+  DBUG_RETURN(ret);
 }
 
 int Format_description_log_event::do_update_pos(Relay_log_info *rli)
 {
-  /* save the information describing this binlog */
-  delete rli->relay_log.description_event_for_exec;
-  rli->relay_log.description_event_for_exec= this;
-
   if (server_id == (uint32) ::server_id)
   {
     /*
@@ -4009,7 +4018,7 @@ uint Load_log_event::get_query_buffer_le
 }
 
 
-void Load_log_event::print_query(bool need_db, char *buf,
+void Load_log_event::print_query(bool need_db, const char *cs, char *buf,
                                  char **end, char **fn_start, char **fn_end)
 {
   char *pos= buf;
@@ -4033,9 +4042,9 @@ void Load_log_event::print_query(bool ne
   pos= strmov(pos+fname_len, "' ");
 
   if (sql_ex.opt_flags & REPLACE_FLAG)
-    pos= strmov(pos, " REPLACE ");
+    pos= strmov(pos, "REPLACE ");
   else if (sql_ex.opt_flags & IGNORE_FLAG)
-    pos= strmov(pos, " IGNORE ");
+    pos= strmov(pos, "IGNORE ");
 
   pos= strmov(pos ,"INTO");
 
@@ -4046,8 +4055,16 @@ void Load_log_event::print_query(bool ne
   memcpy(pos, table_name, table_name_len);
   pos+= table_name_len;
 
-  /* We have to create all optinal fields as the default is not empty */
-  pos= strmov(pos, "` FIELDS TERMINATED BY ");
+  if (cs != NULL)
+  {
+    pos= strmov(pos ,"` CHARACTER SET ");
+    pos= strmov(pos ,  cs);
+  }
+  else
+    pos= strmov(pos, "`");
+
+  /* We have to create all optional fields as the default is not empty */
+  pos= strmov(pos, " FIELDS TERMINATED BY ");
   pos= pretty_print_str(pos, sql_ex.field_term, sql_ex.field_term_len);
   if (sql_ex.opt_flags & OPT_ENCLOSED_FLAG)
     pos= strmov(pos, " OPTIONALLY ");
@@ -4101,7 +4118,7 @@ void Load_log_event::pack_info(Protocol 
 
   if (!(buf= (char*) my_malloc(get_query_buffer_length(), MYF(MY_WME))))
     return;
-  print_query(TRUE, buf, &end, 0, 0);
+  print_query(TRUE, NULL, buf, &end, 0, 0);
   protocol->store(buf, end-buf, &my_charset_bin);
   my_free(buf, MYF(0));
 }
@@ -4366,9 +4383,9 @@ void Load_log_event::print(FILE* file_ar
   my_b_printf(&cache, "INFILE '%-*s' ", fname_len, fname);
 
   if (sql_ex.opt_flags & REPLACE_FLAG)
-    my_b_printf(&cache," REPLACE ");
+    my_b_printf(&cache,"REPLACE ");
   else if (sql_ex.opt_flags & IGNORE_FLAG)
-    my_b_printf(&cache," IGNORE ");
+    my_b_printf(&cache,"IGNORE ");
   
   my_b_printf(&cache, "INTO TABLE `%s`", table_name);
   my_b_printf(&cache, " FIELDS TERMINATED BY ");
@@ -4480,8 +4497,8 @@ int Load_log_event::do_apply_event(NET* 
   new_db.length= db_len;
   new_db.str= (char *) rpl_filter->get_rewrite_db(db, &new_db.length);
   thd->set_db(new_db.str, new_db.length);
-  DBUG_ASSERT(thd->query == 0);
-  thd->query_length= 0;                         // Should not be needed
+  DBUG_ASSERT(thd->query() == 0);
+  thd->set_query_inner(NULL, 0);               // Should not be needed
   thd->is_slave_error= 0;
   clear_all_errors(thd, const_cast<Relay_log_info*>(rli));
 
@@ -4576,8 +4593,7 @@ int Load_log_event::do_apply_event(NET* 
         goto error;
       }
 
-      print_query(FALSE, load_data_query, &end, (char **)&thd->lex->fname_start,
-                  (char **)&thd->lex->fname_end);
+      print_query(FALSE, NULL, load_data_query, &end, NULL, NULL);
       *end= 0;
       thd->set_query(load_data_query, (uint) (end - load_data_query));
 
@@ -6734,7 +6750,7 @@ void Execute_load_query_log_event::print
     my_b_printf(&cache, "\'");
     if (dup_handling == LOAD_DUP_REPLACE)
       my_b_printf(&cache, " REPLACE");
-    my_b_printf(&cache, " INTO ");
+    my_b_printf(&cache, " INTO");
     my_b_write(&cache, (uchar*) query + fn_pos_end, q_len-fn_pos_end);
     my_b_printf(&cache, "\n%s\n", print_event_info->delimiter);
   }
@@ -7497,6 +7513,7 @@ int Rows_log_event::do_apply_event(Relay
     thd->reset_current_stmt_binlog_row_based();
     const_cast<Relay_log_info*>(rli)->cleanup_context(thd, error);
     thd->is_slave_error= 1;
+    DBUG_RETURN(error);
   }
   /*
     This code would ideally be placed in do_update_pos() instead, but
@@ -7525,6 +7542,14 @@ int Rows_log_event::do_apply_event(Relay
     const_cast<Relay_log_info*>(rli)->last_event_start_time= my_time(0);
   }
 
+  if (get_flags(STMT_END_F))
+    if ((error= rows_event_stmt_cleanup(rli, thd)))
+      rli->report(ERROR_LEVEL, error,
+                  "Error in %s event: commit of row events failed, "
+                  "table `%s`.`%s`",
+                  get_type_str(), m_table->s->db.str,
+                  m_table->s->table_name.str);
+
   DBUG_RETURN(error);
 }
 
@@ -7623,33 +7648,19 @@ Rows_log_event::do_update_pos(Relay_log_
 
   if (get_flags(STMT_END_F))
   {
-    if ((error= rows_event_stmt_cleanup(rli, thd)) == 0)
-    {
-      /*
-        Indicate that a statement is finished.
-        Step the group log position if we are not in a transaction,
-        otherwise increase the event log position.
-      */
-      rli->stmt_done(log_pos, when);
-
-      /*
-        Clear any errors pushed in thd->net.last_err* if for example "no key
-        found" (as this is allowed). This is a safety measure; apparently
-        those errors (e.g. when executing a Delete_rows_log_event of a
-        non-existing row, like in rpl_row_mystery22.test,
-        thd->net.last_error = "Can't find record in 't1'" and last_errno=1032)
-        do not become visible. We still prefer to wipe them out.
-      */
-      thd->clear_error();
-    }
-    else
-    {
-      rli->report(ERROR_LEVEL, error,
-                  "Error in %s event: commit of row events failed, "
-                  "table `%s`.`%s`",
-                  get_type_str(), m_table->s->db.str,
-                  m_table->s->table_name.str);
-    }
+    /*
+      Indicate that a statement is finished.
+      Step the group log position if we are not in a transaction,
+      otherwise increase the event log position.
+    */
+    rli->stmt_done(log_pos, when);
+    /*
+      Clear any errors in thd->net.last_err*. It is not known if this is
+      needed or not. It is believed that any errors that may exist in
+      thd->net.last_err* are allowed. Examples of errors are "key not
+      found", which is produced in the test case rpl_row_conflicts.test
+    */
+    thd->clear_error();
   }
   else
   {
@@ -8314,6 +8325,16 @@ Write_rows_log_event::do_before_row_oper
   
   /* Honor next number column if present */
   m_table->next_number_field= m_table->found_next_number_field;
+  /*
+   * Fixed Bug#45999, In RBR, Store engine of Slave auto-generates new
+   * sequence numbers for auto_increment fields if the values of them are 0.
+   * If generateing a sequence number is decided by the values of
+   * table->auto_increment_field_not_null and SQL_MODE(if includes
+   * MODE_NO_AUTO_VALUE_ON_ZERO) in update_auto_increment function.
+   * SQL_MODE of slave sql thread is always consistency with master's.
+   * In RBR, auto_increment fields never are NULL.
+   */
+  m_table->auto_increment_field_not_null= TRUE;
   return error;
 }
 
@@ -8323,6 +8344,7 @@ Write_rows_log_event::do_after_row_opera
 {
   int local_error= 0;
   m_table->next_number_field=0;
+  m_table->auto_increment_field_not_null= FALSE;
   if (bit_is_set(slave_exec_mode, SLAVE_EXEC_MODE_IDEMPOTENT) == 1 ||
       m_table->s->db_type()->db_type == DB_TYPE_NDBCLUSTER)
   {
@@ -8826,11 +8848,11 @@ int Rows_log_event::find_row(const Relay
    */ 
   store_record(table,record[1]);    
 
-  if (table->s->keys > 0)
+  if (table->s->keys > 0 && table->s->keys_in_use.is_set(0))
   {
     DBUG_PRINT("info",("locating record using primary key (index_read)"));
 
-    /* We have a key: search the table using the index */
+    /* The 0th key is active: search the table using the index */
     if (!table->file->inited && (error= table->file->ha_index_init(0, FALSE)))
     {
       DBUG_PRINT("info",("ha_index_init returns error %d",error));

=== modified file 'sql/log_event.h'
--- a/sql/log_event.h	2009-09-07 20:50:10 +0000
+++ b/sql/log_event.h	2009-11-10 15:15:12 +0000
@@ -1960,15 +1960,15 @@ private:
 class Load_log_event: public Log_event
 {
 private:
-  uint get_query_buffer_length();
-  void print_query(bool need_db, char *buf, char **end,
-                   char **fn_start, char **fn_end);
 protected:
   int copy_log_event(const char *buf, ulong event_len,
                      int body_offset,
                      const Format_description_log_event* description_event);
 
 public:
+  uint get_query_buffer_length();
+  void print_query(bool need_db, const char *cs, char *buf, char **end,
+                   char **fn_start, char **fn_end);
   ulong thread_id;
   ulong slave_proxy_id;
   uint32 table_name_len;

=== modified file 'sql/log_event_old.cc'
--- a/sql/log_event_old.cc	2009-05-19 09:28:05 +0000
+++ b/sql/log_event_old.cc	2009-11-10 15:15:12 +0000
@@ -1814,33 +1814,6 @@ int Old_rows_log_event::do_apply_event(R
     const_cast<Relay_log_info*>(rli)->last_event_start_time= my_time(0);
   }
 
-  DBUG_RETURN(0);
-}
-
-
-Log_event::enum_skip_reason
-Old_rows_log_event::do_shall_skip(Relay_log_info *rli)
-{
-  /*
-    If the slave skip counter is 1 and this event does not end a
-    statement, then we should not start executing on the next event.
-    Otherwise, we defer the decision to the normal skipping logic.
-  */
-  if (rli->slave_skip_counter == 1 && !get_flags(STMT_END_F))
-    return Log_event::EVENT_SKIP_IGNORE;
-  else
-    return Log_event::do_shall_skip(rli);
-}
-
-int
-Old_rows_log_event::do_update_pos(Relay_log_info *rli)
-{
-  DBUG_ENTER("Old_rows_log_event::do_update_pos");
-  int error= 0;
-
-  DBUG_PRINT("info", ("flags: %s",
-                      get_flags(STMT_END_F) ? "STMT_END_F " : ""));
-
   if (get_flags(STMT_END_F))
   {
     /*
@@ -1869,7 +1842,12 @@ Old_rows_log_event::do_update_pos(Relay_
       are involved, commit the transaction and flush the pending event to the
       binlog.
     */
-    error= ha_autocommit_or_rollback(thd, 0);
+    if ((error= ha_autocommit_or_rollback(thd, 0)))
+      rli->report(ERROR_LEVEL, error,
+                  "Error in %s event: commit of row events failed, "
+                  "table `%s`.`%s`",
+                  get_type_str(), m_table->s->db.str,
+                  m_table->s->table_name.str);
 
     /*
       Now what if this is not a transactional engine? we still need to
@@ -1882,33 +1860,51 @@ Old_rows_log_event::do_update_pos(Relay_
     */
 
     thd->reset_current_stmt_binlog_row_based();
-    rli->cleanup_context(thd, 0);
-    if (error == 0)
-    {
-      /*
-        Indicate that a statement is finished.
-        Step the group log position if we are not in a transaction,
-        otherwise increase the event log position.
-       */
-      rli->stmt_done(log_pos, when);
+    const_cast<Relay_log_info*>(rli)->cleanup_context(thd, 0);
+  }
 
-      /*
-        Clear any errors pushed in thd->net.client_last_err* if for
-        example "no key found" (as this is allowed). This is a safety
-        measure; apparently those errors (e.g. when executing a
-        Delete_rows_log_event_old of a non-existing row, like in
-        rpl_row_mystery22.test, thd->net.last_error = "Can't
-        find record in 't1'" and last_errno=1032) do not become
-        visible. We still prefer to wipe them out.
-      */
-      thd->clear_error();
-    }
-    else
-      rli->report(ERROR_LEVEL, error,
-                  "Error in %s event: commit of row events failed, "
-                  "table `%s`.`%s`",
-                  get_type_str(), m_table->s->db.str,
-                  m_table->s->table_name.str);
+  DBUG_RETURN(error);
+}
+
+
+Log_event::enum_skip_reason
+Old_rows_log_event::do_shall_skip(Relay_log_info *rli)
+{
+  /*
+    If the slave skip counter is 1 and this event does not end a
+    statement, then we should not start executing on the next event.
+    Otherwise, we defer the decision to the normal skipping logic.
+  */
+  if (rli->slave_skip_counter == 1 && !get_flags(STMT_END_F))
+    return Log_event::EVENT_SKIP_IGNORE;
+  else
+    return Log_event::do_shall_skip(rli);
+}
+
+int
+Old_rows_log_event::do_update_pos(Relay_log_info *rli)
+{
+  DBUG_ENTER("Old_rows_log_event::do_update_pos");
+  int error= 0;
+
+  DBUG_PRINT("info", ("flags: %s",
+                      get_flags(STMT_END_F) ? "STMT_END_F " : ""));
+
+  if (get_flags(STMT_END_F))
+  {
+    /*
+      Indicate that a statement is finished.
+      Step the group log position if we are not in a transaction,
+      otherwise increase the event log position.
+     */
+    rli->stmt_done(log_pos, when);
+    /*
+      Clear any errors in thd->net.last_err*. It is not known if this is
+      needed or not. It is believed that any errors that may exist in
+      thd->net.last_err* are allowed. Examples of errors are "key not
+      found", which is produced in the test case rpl_row_conflicts.test
+    */
+    thd->clear_error();
   }
   else
   {

=== modified file 'sql/my_decimal.h'
--- a/sql/my_decimal.h	2009-10-15 21:38:29 +0000
+++ b/sql/my_decimal.h	2009-11-10 15:15:12 +0000
@@ -48,12 +48,10 @@ C_MODE_END
   digits * number of decimal digits in one our big digit - number of decimal
   digits in one our big digit decreased by 1 (because we always put decimal
   point on the border of our big digits))
-
-  This value is 65 due to historical reasons partly due to it being used
-  as the maximum allowed precision and not the actual maximum precision.
 */
 #define DECIMAL_MAX_PRECISION (DECIMAL_MAX_POSSIBLE_PRECISION - 8*2)
 #define DECIMAL_MAX_SCALE 30
+#define DECIMAL_NOT_SPECIFIED 31
 
 /**
   maximum length of string representation (number of maximum decimal
@@ -77,6 +75,12 @@ inline uint my_decimal_size(uint precisi
 }
 
 
+inline int my_decimal_int_part(uint precision, uint decimals)
+{
+  return precision - ((decimals == DECIMAL_NOT_SPECIFIED) ? 0 : decimals);
+}
+
+
 /**
   my_decimal class limits 'decimal_t' type to what we need in MySQL.
 
@@ -180,7 +184,7 @@ inline uint my_decimal_length_to_precisi
 }
 
 inline uint32 my_decimal_precision_to_length_no_truncation(uint precision,
-                                                           uint scale,
+                                                           uint8 scale,
                                                            bool unsigned_flag)
 {
   /*
@@ -192,7 +196,7 @@ inline uint32 my_decimal_precision_to_le
                   (unsigned_flag || !precision ? 0 : 1));
 }
 
-inline uint32 my_decimal_precision_to_length(uint precision, uint scale,
+inline uint32 my_decimal_precision_to_length(uint precision, uint8 scale,
                                              bool unsigned_flag)
 {
   /*

=== modified file 'sql/mysql_priv.h'
--- a/sql/mysql_priv.h	2009-10-15 21:52:31 +0000
+++ b/sql/mysql_priv.h	2009-11-10 15:15:12 +0000
@@ -2303,10 +2303,9 @@ enum enum_explain_filename_mode
 {
   EXPLAIN_ALL_VERBOSE= 0,
   EXPLAIN_PARTITIONS_VERBOSE,
-  EXPLAIN_PARTITIONS_AS_COMMENT,
-  EXPLAIN_PARTITIONS_AS_COMMENT_NO_QUOTING
+  EXPLAIN_PARTITIONS_AS_COMMENT
 };
-uint explain_filename(const char *from, char *to, uint to_length,
+uint explain_filename(THD* thd, const char *from, char *to, uint to_length,
                       enum_explain_filename_mode explain_mode);
 uint filename_to_tablename(const char *from, char *to, uint to_length);
 uint tablename_to_filename(const char *from, char *to, uint to_length);
@@ -2460,6 +2459,7 @@ inline void setup_table_map(TABLE *table
   table->tablenr= tablenr;
   table->map= (table_map) 1 << tablenr;
   table->force_index= table_list->force_index;
+  table->force_index_order= table->force_index_group= 0;
   table->covering_keys= table->s->keys_for_keyread;
   table->merge_keys.clear_all();
 }

=== modified file 'sql/mysqld.cc'
--- a/sql/mysqld.cc	2009-10-31 19:22:50 +0000
+++ b/sql/mysqld.cc	2009-11-10 15:15:12 +0000
@@ -28,6 +28,7 @@
 #include "mysys_err.h"
 #include "events.h"
 #include <waiting_threads.h>
+#include "debug_sync.h"
 
 #include "../storage/myisam/ha_myisam.h"
 
@@ -497,6 +498,9 @@ my_bool lower_case_file_system= 0;
 my_bool opt_large_pages= 0;
 my_bool opt_myisam_use_mmap= 0;
 uint    opt_large_page_size= 0;
+#if defined(ENABLED_DEBUG_SYNC)
+uint    opt_debug_sync_timeout= 0;
+#endif /* defined(ENABLED_DEBUG_SYNC) */
 my_bool opt_old_style_user_limits= 0, trust_function_creators= 0;
 /*
   True if there is at least one per-hour limit for some user, so we should
@@ -1136,13 +1140,13 @@ void kill_mysql(void)
 
 #if defined(__NETWARE__)
 extern "C" void kill_server(int sig_ptr)
-#define RETURN_FROM_KILL_SERVER DBUG_VOID_RETURN
+#define RETURN_FROM_KILL_SERVER return
 #elif !defined(__WIN__)
 static void *kill_server(void *sig_ptr)
-#define RETURN_FROM_KILL_SERVER DBUG_RETURN(0)
+#define RETURN_FROM_KILL_SERVER return 0
 #else
 static void __cdecl kill_server(int sig_ptr)
-#define RETURN_FROM_KILL_SERVER DBUG_VOID_RETURN
+#define RETURN_FROM_KILL_SERVER return
 #endif
 {
   DBUG_ENTER("kill_server");
@@ -1150,7 +1154,10 @@ static void __cdecl kill_server(int sig_
   int sig=(int) (long) sig_ptr;			// This is passed a int
   // if there is a signal during the kill in progress, ignore the other
   if (kill_in_progress)				// Safety
+  {
+    DBUG_LEAVE;
     RETURN_FROM_KILL_SERVER;
+  }
   kill_in_progress=TRUE;
   abort_loop=1;					// This should be set
   if (sig != 0) // 0 is not a valid signal number
@@ -1185,12 +1192,19 @@ static void __cdecl kill_server(int sig_
     pthread_join(select_thread, NULL);		// wait for main thread
 #endif /* __NETWARE__ */
 
+  DBUG_LEAVE;                                   // Must match DBUG_ENTER()
   my_thread_end();
   pthread_exit(0);
   /* purecov: end */
 
-#endif /* EMBEDDED_LIBRARY */
+  RETURN_FROM_KILL_SERVER;                      // Avoid compiler warnings
+
+#else /* EMBEDDED_LIBRARY*/
+
+  DBUG_LEAVE;
   RETURN_FROM_KILL_SERVER;
+
+#endif /* EMBEDDED_LIBRARY */
 }
 
 
@@ -1354,6 +1368,10 @@ void clean_up(bool print_message)
 #ifdef USE_REGEX
   my_regex_end();
 #endif
+#if defined(ENABLED_DEBUG_SYNC)
+  /* End the debug sync facility. See debug_sync.cc. */
+  debug_sync_end();
+#endif /* defined(ENABLED_DEBUG_SYNC) */
 
 #if !defined(EMBEDDED_LIBRARY)
   if (!opt_bootstrap)
@@ -1777,7 +1795,7 @@ static void network_init(void)
     saPipeSecurity.lpSecurityDescriptor = &sdPipeDescriptor;
     saPipeSecurity.bInheritHandle = FALSE;
     if ((hPipe= CreateNamedPipe(pipe_name,
-				PIPE_ACCESS_DUPLEX,
+				PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
 				PIPE_TYPE_BYTE |
 				PIPE_READMODE_BYTE |
 				PIPE_WAIT,
@@ -2012,8 +2030,9 @@ bool one_thread_per_connection_end(THD *
   my_thread_end();
   (void) pthread_cond_broadcast(&COND_thread_count);
 
+  DBUG_LEAVE;                                   // Must match DBUG_ENTER()
   pthread_exit(0);
-  DBUG_RETURN(0);                               // Impossible
+  return 0;                                     // Avoid compiler warnings
 }
 
 
@@ -2580,7 +2599,7 @@ terribly wrong...\n");  
     }
     fprintf(stderr, "Trying to get some variables.\n\
 Some pointers may be invalid and cause the dump to abort...\n");
-    my_safe_print_str("thd->query", thd->query, 1024);
+    my_safe_print_str("thd->query", thd->query(), 1024);
     fprintf(stderr, "thd->thread_id=%lu\n", (ulong) thd->thread_id);
     fprintf(stderr, "thd->killed=%s\n", kreason);
   }
@@ -2837,7 +2856,9 @@ pthread_handler_t signal_hand(void *arg 
       DBUG_PRINT("quit",("signal_handler: calling my_thread_end()"));
       my_thread_end();
       signal_thread_in_use= 0;
+      DBUG_LEAVE;                               // Must match DBUG_ENTER()
       pthread_exit(0);				// Safety
+      return 0;                                 // Avoid compiler warnings
     }
     switch (sig) {
     case SIGTERM:
@@ -3557,6 +3578,12 @@ static int init_common_variables(const c
   sys_var_slow_log_path.value= my_strdup(s, MYF(0));
   sys_var_slow_log_path.value_length= strlen(s);
 
+#if defined(ENABLED_DEBUG_SYNC)
+  /* Initialize the debug sync facility. See debug_sync.cc. */
+  if (debug_sync_init())
+    return 1; /* purecov: tested */
+#endif /* defined(ENABLED_DEBUG_SYNC) */
+
 #if (ENABLE_TEMP_POOL)
   if (use_temp_pool && bitmap_init(&temp_pool,0,1024,1))
     return 1;
@@ -4909,10 +4936,10 @@ static bool read_init_file(char *file_na
   DBUG_ENTER("read_init_file");
   DBUG_PRINT("enter",("name: %s",file_name));
   if (!(file=my_fopen(file_name,O_RDONLY,MYF(MY_WME))))
-    DBUG_RETURN(1);
+    DBUG_RETURN(TRUE);
   bootstrap(file);
   (void) my_fclose(file,MYF(MY_WME));
-  DBUG_RETURN(0);
+  DBUG_RETURN(FALSE);
 }
 
 
@@ -4966,7 +4993,7 @@ void create_thread_to_handle_connection(
                               handle_one_connection,
                               (void*) thd)))
     {
-      /* purify: begin inspected */
+      /* purecov: begin inspected */
       DBUG_PRINT("error",
                  ("Can't create thread to handle request (error %d)",
                   error));
@@ -5324,17 +5351,26 @@ pthread_handler_t handle_connections_soc
 pthread_handler_t handle_connections_namedpipes(void *arg)
 {
   HANDLE hConnectedPipe;
-  BOOL fConnected;
+  OVERLAPPED connectOverlapped = {0};
   THD *thd;
   my_thread_init();
   DBUG_ENTER("handle_connections_namedpipes");
-  (void) my_pthread_getprio(pthread_self());		// For debugging
+  connectOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
 
   DBUG_PRINT("general",("Waiting for named pipe connections."));
   while (!abort_loop)
   {
     /* wait for named pipe connection */
-    fConnected = ConnectNamedPipe(hPipe, NULL);
+    BOOL fConnected= ConnectNamedPipe(hPipe, &connectOverlapped);
+    if (!fConnected && (GetLastError() == ERROR_IO_PENDING))
+    {
+        /*
+          ERROR_IO_PENDING says async IO has started but not yet finished.
+          GetOverlappedResult will wait for completion.
+        */
+        DWORD bytes;
+        fConnected= GetOverlappedResult(hPipe, &connectOverlapped,&bytes, TRUE);
+    }
     if (abort_loop)
       break;
     if (!fConnected)
@@ -5343,7 +5379,7 @@ pthread_handler_t handle_connections_nam
     {
       CloseHandle(hPipe);
       if ((hPipe= CreateNamedPipe(pipe_name,
-                                  PIPE_ACCESS_DUPLEX,
+                                  PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
                                   PIPE_TYPE_BYTE |
                                   PIPE_READMODE_BYTE |
                                   PIPE_WAIT,
@@ -5363,7 +5399,7 @@ pthread_handler_t handle_connections_nam
     hConnectedPipe = hPipe;
     /* create new pipe for new connection */
     if ((hPipe = CreateNamedPipe(pipe_name,
-				 PIPE_ACCESS_DUPLEX,
+				 PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
 				 PIPE_TYPE_BYTE |
 				 PIPE_READMODE_BYTE |
 				 PIPE_WAIT,
@@ -5385,7 +5421,7 @@ pthread_handler_t handle_connections_nam
       CloseHandle(hConnectedPipe);
       continue;
     }
-    if (!(thd->net.vio = vio_new_win32pipe(hConnectedPipe)) ||
+    if (!(thd->net.vio= vio_new_win32pipe(hConnectedPipe)) ||
 	my_net_init(&thd->net, thd->net.vio))
     {
       close_connection(thd, ER_OUT_OF_RESOURCES, 1);
@@ -5396,7 +5432,7 @@ pthread_handler_t handle_connections_nam
     thd->security_ctx->host= my_strdup(my_localhost, MYF(0));
     create_new_thread(thd);
   }
-
+  CloseHandle(connectOverlapped.hEvent);
   decrement_handler_count();
   DBUG_RETURN(0);
 }
@@ -5573,8 +5609,7 @@ pthread_handler_t handle_connections_sha
       errmsg= "Could not set client to read mode";
       goto errorconn;
     }
-    if (!(thd->net.vio= vio_new_win32shared_memory(&thd->net,
-                                                   handle_client_file_map,
+    if (!(thd->net.vio= vio_new_win32shared_memory(handle_client_file_map,
                                                    handle_client_map,
                                                    event_client_wrote,
                                                    event_client_read,
@@ -5814,6 +5849,9 @@ enum options_mysqld
   OPT_LOG_SLOW_SLAVE_STATEMENTS,
   OPT_DEBUG_CRC, OPT_DEBUG_ON, OPT_OLD_MODE,
   OPT_TEST_IGNORE_WRONG_OPTIONS, 
+#if defined(ENABLED_DEBUG_SYNC)
+  OPT_DEBUG_SYNC_TIMEOUT,
+#endif /* defined(ENABLED_DEBUG_SYNC) */
   OPT_SLAVE_EXEC_MODE,
   OPT_DEADLOCK_SEARCH_DEPTH_SHORT,
   OPT_DEADLOCK_SEARCH_DEPTH_LONG,
@@ -6634,6 +6672,14 @@ log and this option does nothing anymore
    "Decision to use in heuristic recover process. Possible values are COMMIT or ROLLBACK.",
    (uchar**) &opt_tc_heuristic_recover, (uchar**) &opt_tc_heuristic_recover,
    0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
+#if defined(ENABLED_DEBUG_SYNC)
+  {"debug-sync-timeout", OPT_DEBUG_SYNC_TIMEOUT,
+   "Enable the debug sync facility "
+   "and optionally specify a default wait timeout in seconds. "
+   "A zero value keeps the facility disabled.",
+   (uchar**) &opt_debug_sync_timeout, 0,
+   0, GET_UINT, OPT_ARG, 0, 0, UINT_MAX, 0, 0, 0},
+#endif /* defined(ENABLED_DEBUG_SYNC) */
   {"temp-pool", OPT_TEMP_POOL,
 #if (ENABLE_TEMP_POOL)
    "Using this option will cause most temporary files created to use a small set of names, rather than a unique name for each new file.",
@@ -7846,6 +7892,9 @@ static int mysql_init_variables(void)
   bzero((uchar*) &mysql_tmpdir_list, sizeof(mysql_tmpdir_list));
   bzero((char *) &global_status_var, sizeof(global_status_var));
   opt_large_pages= 0;
+#if defined(ENABLED_DEBUG_SYNC)
+  opt_debug_sync_timeout= 0;
+#endif /* defined(ENABLED_DEBUG_SYNC) */
   key_map_full.set_all();
 
   /* Character sets */
@@ -8658,6 +8707,22 @@ mysqld_get_one_option(int optid,
     /* Used for testing options */
     opt_ignore_wrong_options= 1;
     break;
+#if defined(ENABLED_DEBUG_SYNC)
+  case OPT_DEBUG_SYNC_TIMEOUT:
+    /*
+      Debug Sync Facility. See debug_sync.cc.
+      Default timeout for WAIT_FOR action.
+      Default value is zero (facility disabled).
+      If option is given without an argument, supply a non-zero value.
+    */
+    if (!argument)
+    {
+      /* purecov: begin tested */
+      opt_debug_sync_timeout= DEBUG_SYNC_DEFAULT_WAIT_TIMEOUT;
+      /* purecov: end */
+    }
+    break;
+#endif /* defined(ENABLED_DEBUG_SYNC) */
   }
   return 0;
 }

=== modified file 'sql/opt_range.cc'
--- a/sql/opt_range.cc	2009-10-15 21:38:29 +0000
+++ b/sql/opt_range.cc	2009-11-10 15:15:12 +0000
@@ -5710,6 +5710,27 @@ get_mm_leaf(RANGE_OPT_PARAM *param, COND
       !(conf_func->compare_collation()->state & MY_CS_BINSORT))
     goto end;
 
+  if (key_part->image_type == Field::itMBR)
+  {
+    switch (type) {
+    case Item_func::SP_EQUALS_FUNC:
+    case Item_func::SP_DISJOINT_FUNC:
+    case Item_func::SP_INTERSECTS_FUNC:
+    case Item_func::SP_TOUCHES_FUNC:
+    case Item_func::SP_CROSSES_FUNC:
+    case Item_func::SP_WITHIN_FUNC:
+    case Item_func::SP_CONTAINS_FUNC:
+    case Item_func::SP_OVERLAPS_FUNC:
+      break;
+    default:
+      /* 
+        We cannot involve spatial indexes for queries that
+        don't use MBREQUALS(), MBRDISJOINT(), etc. functions.
+      */
+      goto end;
+    }
+  }
+
   if (param->using_real_indexes)
     optimize_range= field->optimize_range(param->real_keynr[key_part->key],
                                           key_part->part);
@@ -5877,6 +5898,7 @@ get_mm_leaf(RANGE_OPT_PARAM *param, COND
       if (type == Item_func::LT_FUNC && (value->val_int() > 0))
         type = Item_func::LE_FUNC;
       else if (type == Item_func::GT_FUNC &&
+               (field->type() != FIELD_TYPE_BIT) &&
                !((Field_num*)field)->unsigned_flag &&
                !((Item_int*)value)->unsigned_flag &&
                (value->val_int() < 0))
@@ -5891,6 +5913,17 @@ get_mm_leaf(RANGE_OPT_PARAM *param, COND
     goto end;
   }
   field->table->in_use->variables.sql_mode= orig_sql_mode;
+
+  /*
+    Any sargable predicate except "<=>" involving NULL as a constant is always
+    FALSE
+  */
+  if (type != Item_func::EQUAL_FUNC && field->is_real_null())
+  {
+    tree= &null_element;
+    goto end;
+  }
+  
   str= (uchar*) alloc_root(alloc, key_part->store_length+1);
   if (!str)
     goto end;
@@ -5914,7 +5947,9 @@ get_mm_leaf(RANGE_OPT_PARAM *param, COND
    */
   if (field->result_type() == INT_RESULT &&
       value->result_type() == INT_RESULT &&
-      ((Field_num*)field)->unsigned_flag && !((Item_int*)value)->unsigned_flag)
+      ((field->type() == FIELD_TYPE_BIT || 
+       ((Field_num *) field)->unsigned_flag) && 
+       !((Item_int*) value)->unsigned_flag))
   {
     longlong item_val= value->val_int();
     if (item_val < 0)
@@ -5934,7 +5969,7 @@ get_mm_leaf(RANGE_OPT_PARAM *param, COND
 
   switch (type) {
   case Item_func::LT_FUNC:
-    if (stored_field_cmp_to_item(field,value) == 0)
+    if (stored_field_cmp_to_item(param->thd, field, value) == 0)
       tree->max_flag=NEAR_MAX;
     /* fall through */
   case Item_func::LE_FUNC:
@@ -5949,14 +5984,14 @@ get_mm_leaf(RANGE_OPT_PARAM *param, COND
   case Item_func::GT_FUNC:
     /* Don't use open ranges for partial key_segments */
     if ((!(key_part->flag & HA_PART_KEY_SEG)) &&
-        (stored_field_cmp_to_item(field, value) <= 0))
+        (stored_field_cmp_to_item(param->thd, field, value) <= 0))
       tree->min_flag=NEAR_MIN;
     tree->max_flag= NO_MAX_RANGE;
     break;
   case Item_func::GE_FUNC:
     /* Don't use open ranges for partial key_segments */
     if ((!(key_part->flag & HA_PART_KEY_SEG)) &&
-        (stored_field_cmp_to_item(field,value) < 0))
+        (stored_field_cmp_to_item(param->thd, field, value) < 0))
       tree->min_flag= NEAR_MIN;
     tree->max_flag=NO_MAX_RANGE;
     break;
@@ -6510,6 +6545,63 @@ get_range(SEL_ARG **e1,SEL_ARG **e2,SEL_
 }
 
 
+/**
+   Combine two range expression under a common OR. On a logical level, the
+   transformation is key_or( expr1, expr2 ) => expr1 OR expr2.
+
+   Both expressions are assumed to be in the SEL_ARG format. In a logic sense,
+   theformat is reminiscent of DNF, since an expression such as the following
+
+   ( 1 < kp1 < 10 AND p1 ) OR ( 10 <= kp2 < 20 AND p2 )
+
+   where there is a key consisting of keyparts ( kp1, kp2, ..., kpn ) and p1
+   and p2 are valid SEL_ARG expressions over keyparts kp2 ... kpn, is a valid
+   SEL_ARG condition. The disjuncts appear ordered by the minimum endpoint of
+   the first range and ranges must not overlap. It follows that they are also
+   ordered by maximum endpoints. Thus
+
+   ( 1 < kp1 <= 2 AND ( kp2 = 2 OR kp2 = 3 ) ) OR kp1 = 3
+
+   Is a a valid SER_ARG expression for a key of at least 2 keyparts.
+   
+   For simplicity, we will assume that expr2 is a single range predicate,
+   i.e. on the form ( a < x < b AND ... ). It is easy to generalize to a
+   disjunction of several predicates by subsequently call key_or for each
+   disjunct.
+
+   The algorithm iterates over each disjunct of expr1, and for each disjunct
+   where the first keypart's range overlaps with the first keypart's range in
+   expr2:
+   
+   If the predicates are equal for the rest of the keyparts, or if there are
+   no more, the range in expr2 has its endpoints copied in, and the SEL_ARG
+   node in expr2 is deallocated. If more ranges became connected in expr1, the
+   surplus is also dealocated. If they differ, two ranges are created.
+   
+   - The range leading up to the overlap. Empty if endpoints are equal.
+
+   - The overlapping sub-range. May be the entire range if they are equal.
+
+   Finally, there may be one more range if expr2's first keypart's range has a
+   greater maximum endpoint than the last range in expr1.
+
+   For the overlapping sub-range, we recursively call key_or. Thus in order to
+   compute key_or of
+
+     (1) ( 1 < kp1 < 10 AND 1 < kp2 < 10 ) 
+
+     (2) ( 2 < kp1 < 20 AND 4 < kp2 < 20 )
+
+   We create the ranges 1 < kp <= 2, 2 < kp1 < 10, 10 <= kp1 < 20. For the
+   first one, we simply hook on the condition for the second keypart from (1)
+   : 1 < kp2 < 10. For the second range 2 < kp1 < 10, key_or( 1 < kp2 < 10, 4
+   < kp2 < 20 ) is called, yielding 1 < kp2 < 20. For the last range, we reuse
+   the range 4 < kp2 < 20 from (2) for the second keypart. The result is thus
+   
+   ( 1  <  kp1 <= 2 AND 1 < kp2 < 10 ) OR
+   ( 2  <  kp1 < 10 AND 1 < kp2 < 20 ) OR
+   ( 10 <= kp1 < 20 AND 4 < kp2 < 20 )
+*/
 static SEL_ARG *
 key_or(RANGE_OPT_PARAM *param, SEL_ARG *key1,SEL_ARG *key2)
 {
@@ -6661,7 +6753,21 @@ key_or(RANGE_OPT_PARAM *param, SEL_ARG *
 	  key1=key1->tree_delete(save);
 	}
         last->copy_min(tmp);
-	if (last->copy_min(key2) || last->copy_max(key2))
+        bool full_range= last->copy_min(key2);
+        if (!full_range)
+        {
+          if (last->next && key2->cmp_max_to_min(last->next) >= 0)
+          {
+            last->max_value= last->next->min_value;
+            if (last->next->min_flag & NEAR_MIN)
+              last->max_flag&= ~NEAR_MAX;
+            else
+              last->max_flag|= NEAR_MAX;
+          }
+          else
+            full_range= last->copy_max(key2);
+        }
+	if (full_range)
 	{					// Full range
 	  key1->free_tree();
 	  for (; key2 ; key2=key2->next)
@@ -6671,8 +6777,6 @@ key_or(RANGE_OPT_PARAM *param, SEL_ARG *
 	  return 0;
 	}
       }
-      key2=key2->next;
-      continue;
     }
 
     if (cmp >= 0 && tmp->cmp_min_to_min(key2) < 0)

=== modified file 'sql/opt_sum.cc'
--- a/sql/opt_sum.cc	2009-09-07 20:50:10 +0000
+++ b/sql/opt_sum.cc	2009-11-10 15:15:12 +0000
@@ -97,7 +97,8 @@ static ulonglong get_exact_record_count(
 
   @note
     This function is only called for queries with sum functions and no
-    GROUP BY part.
+    GROUP BY part. This means that the result set shall contain a single
+    row only
 
   @retval
     0                    no errors

=== modified file 'sql/partition_info.cc'
--- a/sql/partition_info.cc	2009-02-19 09:01:25 +0000
+++ b/sql/partition_info.cc	2009-11-10 15:15:12 +0000
@@ -483,10 +483,8 @@ static bool check_engine_condition(parti
   {
     DBUG_RETURN(TRUE);
   }
-  else
-  {
-    DBUG_RETURN(FALSE);
-  }
+
+  DBUG_RETURN(FALSE);
 }
 
 

=== modified file 'sql/records.cc'
--- a/sql/records.cc	2009-05-06 12:03:24 +0000
+++ b/sql/records.cc	2009-11-10 15:15:12 +0000
@@ -57,10 +57,12 @@ void init_read_record_idx(READ_RECORD *i
 {
   empty_record(table);
   bzero((char*) info,sizeof(*info));
+  info->thd= thd;
   info->table= table;
   info->file=  table->file;
   info->record= table->record[0];
   info->print_error= print_error;
+  info->unlock_row= rr_unlock_row;
 
   table->status=0;			/* And it's always found */
   if (!table->file->inited)
@@ -186,6 +188,7 @@ void init_read_record(READ_RECORD *info,
   }
   info->select=select;
   info->print_error=print_error;
+  info->unlock_row= rr_unlock_row;
   info->ignore_not_found_rows= 0;
   table->status=0;			/* And it's always found */
 
@@ -292,6 +295,12 @@ void end_read_record(READ_RECORD *info)
 
 static int rr_handle_error(READ_RECORD *info, int error)
 {
+  if (info->thd->killed)
+  {
+    info->thd->send_kill_message();
+    return 1;
+  }
+
   if (error == HA_ERR_END_OF_FILE)
     error= -1;
   else
@@ -312,12 +321,7 @@ static int rr_quick(READ_RECORD *info)
   int tmp;
   while ((tmp= info->select->quick->get_next()))
   {
-    if (info->thd->killed)
-    {
-      my_error(ER_SERVER_SHUTDOWN, MYF(0));
-      return 1;
-    }
-    if (tmp != HA_ERR_RECORD_DELETED)
+    if (info->thd->killed || (tmp != HA_ERR_RECORD_DELETED))
     {
       tmp= rr_handle_error(info, tmp);
       break;
@@ -380,16 +384,11 @@ int rr_sequential(READ_RECORD *info)
   int tmp;
   while ((tmp=info->file->rnd_next(info->record)))
   {
-    if (info->thd->killed)
-    {
-      info->thd->send_kill_message();
-      return 1;
-    }
     /*
       rnd_next can return RECORD_DELETED for MyISAM when one thread is
       reading and another deleting without locks.
     */
-    if (tmp != HA_ERR_RECORD_DELETED)
+    if (info->thd->killed || (tmp != HA_ERR_RECORD_DELETED))
     {
       tmp= rr_handle_error(info, tmp);
       break;

=== modified file 'sql/repl_failsafe.cc'
--- a/sql/repl_failsafe.cc	2009-05-15 12:57:51 +0000
+++ b/sql/repl_failsafe.cc	2009-09-23 13:10:23 +0000
@@ -638,9 +638,11 @@ err:
   if (recovery_captain)
     mysql_close(recovery_captain);
   delete thd;
+
+  DBUG_LEAVE;                                   // Must match DBUG_ENTER()
   my_thread_end();
   pthread_exit(0);
-  DBUG_RETURN(0);
+  return 0;                                     // Avoid compiler warnings
 }
 #endif
 

=== modified file 'sql/rpl_filter.cc'
--- a/sql/rpl_filter.cc	2009-09-07 20:50:10 +0000
+++ b/sql/rpl_filter.cc	2009-11-10 15:15:12 +0000
@@ -155,8 +155,10 @@ Rpl_filter::db_ok(const char* db)
     and db was not selected, do not replicate.
   */
   if (!db)
+  {
+    DBUG_PRINT("exit", ("Don't replicate"));
     DBUG_RETURN(0);
-
+  }
   if (!do_db.is_empty()) // if the do's are not empty
   {
     I_List_iterator<i_string> it(do_db);
@@ -167,6 +169,7 @@ Rpl_filter::db_ok(const char* db)
       if (!strcmp(tmp->ptr, db))
 	DBUG_RETURN(1); // match
     }
+    DBUG_PRINT("exit", ("Don't replicate"));
     DBUG_RETURN(0);
   }
   else // there are some elements in the don't, otherwise we cannot get here
@@ -177,7 +180,10 @@ Rpl_filter::db_ok(const char* db)
     while ((tmp=it++))
     {
       if (!strcmp(tmp->ptr, db))
+      {
+        DBUG_PRINT("exit", ("Don't replicate"));
 	DBUG_RETURN(0); // match
+      }
     }
     DBUG_RETURN(1);
   }

=== modified file 'sql/set_var.cc'
--- a/sql/set_var.cc	2009-10-26 11:35:42 +0000
+++ b/sql/set_var.cc	2009-11-10 15:15:12 +0000
@@ -553,11 +553,11 @@ static sys_var_const    sys_skip_network
 static sys_var_const    sys_skip_show_database(&vars, "skip_show_database",
                                             OPT_GLOBAL, SHOW_BOOL,
                                             (uchar*) &opt_skip_show_db);
-#ifdef HAVE_SYS_UN_H
+
 static sys_var_const    sys_socket(&vars, "socket",
                                    OPT_GLOBAL, SHOW_CHAR_PTR,
                                    (uchar*) &mysqld_unix_port);
-#endif
+
 #ifdef HAVE_THR_SETCONCURRENCY
 /* purecov: begin tested */
 static sys_var_const    sys_thread_concurrency(&vars, "thread_concurrency",
@@ -649,6 +649,12 @@ static sys_var_long_ptr	sys_table_cache_
 					     &table_cache_size);
 static sys_var_long_ptr	sys_table_lock_wait_timeout(&vars, "table_lock_wait_timeout",
                                                     &table_lock_wait_timeout);
+
+#if defined(ENABLED_DEBUG_SYNC)
+/* Debug Sync Facility. Implemented in debug_sync.cc. */
+static sys_var_debug_sync sys_debug_sync(&vars, "debug_sync");
+#endif /* defined(ENABLED_DEBUG_SYNC) */
+
 static sys_var_long_ptr	sys_thread_cache_size(&vars, "thread_cache_size",
 					      &thread_cache_size);
 #if HAVE_POOL_OF_THREADS == 1
@@ -3446,8 +3452,7 @@ int set_var_init()
   uint count= 0;
   DBUG_ENTER("set_var_init");
   
-  for (sys_var *var=vars.first; var; var= var->next, count++)
-    ;
+  for (sys_var *var=vars.first; var; var= var->next, count++) ;
 
   if (hash_init(&system_variable_hash, system_charset_info, count, 0,
                 0, (hash_get_key) get_sys_var_length, 0, HASH_UNIQUE))
@@ -4255,6 +4260,7 @@ end_with_read_lock:
 }
 
 
+#ifndef DBUG_OFF
 /* even session variable here requires SUPER, because of -#o,file */
 bool sys_var_thd_dbug::check(THD *thd, set_var *var)
 {
@@ -4302,6 +4308,8 @@ uchar *sys_var_thd_dbug::value_ptr(THD *
   }
   return (uchar*) thd->strdup(buf);
 }
+#endif /* DBUG_OFF */
+
 
 #ifdef HAVE_EVENT_SCHEDULER
 bool sys_var_event_scheduler::check(THD *thd, set_var *var)

=== modified file 'sql/set_var.h'
--- a/sql/set_var.h	2009-09-15 10:46:35 +0000
+++ b/sql/set_var.h	2009-11-10 15:15:12 +0000
@@ -634,6 +634,7 @@ public:
   uchar *value_ptr(THD *thd, enum_var_type type, LEX_STRING *base);
 };
 
+#ifndef DBUG_OFF
 class sys_var_thd_dbug :public sys_var_thd
 {
 public:
@@ -647,8 +648,23 @@ public:
   void set_default(THD *thd, enum_var_type type) { DBUG_POP(); }
   uchar *value_ptr(THD *thd, enum_var_type type, LEX_STRING *b);
 };
+#endif /* DBUG_OFF */
 
-
+#if defined(ENABLED_DEBUG_SYNC)
+/* Debug Sync Facility. Implemented in debug_sync.cc. */
+class sys_var_debug_sync :public sys_var_thd
+{
+public:
+  sys_var_debug_sync(sys_var_chain *chain, const char *name_arg)
+    :sys_var_thd(name_arg)
+  { chain_sys_var(chain); }
+  bool check(THD *thd, set_var *var);
+  bool update(THD *thd, set_var *var);
+  SHOW_TYPE show_type() { return SHOW_CHAR; }
+  bool check_update_type(Item_result type) { return type != STRING_RESULT; }
+  uchar *value_ptr(THD *thd, enum_var_type type, LEX_STRING *base);
+};
+#endif /* defined(ENABLED_DEBUG_SYNC) */
 
 /* some variables that require special handling */
 

=== modified file 'sql/share/errmsg.txt'
--- a/sql/share/errmsg.txt	2009-10-15 21:38:29 +0000
+++ b/sql/share/errmsg.txt	2009-11-10 15:15:12 +0000
@@ -4702,7 +4702,7 @@ ER_NOT_SUPPORTED_YET 42000 
         swe "Denna version av MySQL kan �nnu inte utf�ra '%s'"
 ER_MASTER_FATAL_ERROR_READING_BINLOG  
         nla "Kreeg fatale fout %d: '%-.128s' van master tijdens lezen van data uit binaire log"
-        eng "Got fatal error %d: '%-.128s' from master when reading data from binary log"
+        eng "Got fatal error %d from master when reading data from binary log: '%-.128s'"
         ger "Schwerer Fehler %d: '%-.128s vom Master beim Lesen des bin�ren Logs"
         ita "Errore fatale %d: '%-.128s' dal master leggendo i dati dal log binario"
         por "Obteve fatal erro %d: '%-.128s' do master quando lendo dados do binary log"
@@ -6206,3 +6206,10 @@ ER_TOO_MANY_CONCURRENT_TRXS
 
 WARN_NON_ASCII_SEPARATOR_NOT_IMPLEMENTED
   eng "Non-ASCII separator arguments are not fully supported"
+
+ER_DEBUG_SYNC_TIMEOUT
+  eng "debug sync point wait timed out"
+  ger "Debug Sync Point Wartezeit �berschritten"
+ER_DEBUG_SYNC_HIT_LIMIT
+  eng "debug sync point hit limit reached"
+  ger "Debug Sync Point Hit Limit erreicht"

=== modified file 'sql/slave.cc'
--- a/sql/slave.cc	2009-11-06 17:22:32 +0000
+++ b/sql/slave.cc	2009-11-10 15:15:12 +0000
@@ -1238,7 +1238,8 @@ static int create_table_from_dump(THD* t
   thd->db = (char*)db;
   DBUG_ASSERT(thd->db != 0);
   thd->db_length= strlen(thd->db);
-  mysql_parse(thd, thd->query, packet_len, &found_semicolon); // run create table
+  /* run create table */
+  mysql_parse(thd, thd->query(), packet_len, &found_semicolon);
   thd->db = save_db;            // leave things the way the were before
   thd->db_length= save_db_length;
   thd->options = save_options;
@@ -2033,8 +2034,7 @@ static int has_temporary_error(THD *thd)
   @retval 2 No error calling ev->apply_event(), but error calling
   ev->update_pos().
 */
-int apply_event_and_update_pos(Log_event* ev, THD* thd, Relay_log_info* rli,
-                               bool skip)
+int apply_event_and_update_pos(Log_event* ev, THD* thd, Relay_log_info* rli)
 {
   int exec_res= 0;
 
@@ -2079,37 +2079,33 @@ int apply_event_and_update_pos(Log_event
     ev->when= my_time(0);
   ev->thd = thd; // because up to this point, ev->thd == 0
 
-  if (skip)
-  {
-    int reason= ev->shall_skip(rli);
-    if (reason == Log_event::EVENT_SKIP_COUNT)
-      --rli->slave_skip_counter;
-    pthread_mutex_unlock(&rli->data_lock);
-    if (reason == Log_event::EVENT_SKIP_NOT)
-      exec_res= ev->apply_event(rli);
+  int reason= ev->shall_skip(rli);
+  if (reason == Log_event::EVENT_SKIP_COUNT)
+    --rli->slave_skip_counter;
+  pthread_mutex_unlock(&rli->data_lock);
+  if (reason == Log_event::EVENT_SKIP_NOT)
+    exec_res= ev->apply_event(rli);
+
 #ifndef DBUG_OFF
-    /*
-      This only prints information to the debug trace.
+  /*
+    This only prints information to the debug trace.
 
-      TODO: Print an informational message to the error log?
-    */
-    static const char *const explain[] = {
-      // EVENT_SKIP_NOT,
-      "not skipped",
-      // EVENT_SKIP_IGNORE,
-      "skipped because event should be ignored",
-      // EVENT_SKIP_COUNT
-      "skipped because event skip counter was non-zero"
-    };
-    DBUG_PRINT("info", ("OPTION_BEGIN: %d; IN_STMT: %d",
-                        thd->options & OPTION_BEGIN ? 1 : 0,
-                        rli->get_flag(Relay_log_info::IN_STMT)));
-    DBUG_PRINT("skip_event", ("%s event was %s",
-                              ev->get_type_str(), explain[reason]));
+    TODO: Print an informational message to the error log?
+  */
+  static const char *const explain[] = {
+    // EVENT_SKIP_NOT,
+    "not skipped",
+    // EVENT_SKIP_IGNORE,
+    "skipped because event should be ignored",
+    // EVENT_SKIP_COUNT
+    "skipped because event skip counter was non-zero"
+  };
+  DBUG_PRINT("info", ("OPTION_BEGIN: %d; IN_STMT: %d",
+                      thd->options & OPTION_BEGIN ? 1 : 0,
+                      rli->get_flag(Relay_log_info::IN_STMT)));
+  DBUG_PRINT("skip_event", ("%s event was %s",
+                            ev->get_type_str(), explain[reason]));
 #endif
-  }
-  else
-    exec_res= ev->apply_event(rli);
 
   DBUG_PRINT("info", ("apply_event error = %d", exec_res));
   if (exec_res == 0)
@@ -2229,7 +2225,7 @@ static int exec_relay_log_event(THD* thd
       delete ev;
       DBUG_RETURN(1);
     }
-    exec_res= apply_event_and_update_pos(ev, thd, rli, TRUE);
+    exec_res= apply_event_and_update_pos(ev, thd, rli);
 
     /*
       Format_description_log_event should not be deleted because it will be
@@ -2629,15 +2625,19 @@ Log entry on master is longer than max_a
 slave. If the entry is correct, restart the server with a higher value of \
 max_allowed_packet",
                           thd->variables.max_allowed_packet);
+          mi->report(ERROR_LEVEL, ER_NET_PACKET_TOO_LARGE,
+                     "%s", ER(ER_NET_PACKET_TOO_LARGE));
           goto err;
         case ER_MASTER_FATAL_ERROR_READING_BINLOG:
-          sql_print_error(ER(mysql_error_number), mysql_error_number,
-                          mysql_error(mysql));
+          mi->report(ERROR_LEVEL, ER_MASTER_FATAL_ERROR_READING_BINLOG,
+                     ER(ER_MASTER_FATAL_ERROR_READING_BINLOG),
+                     mysql_error_number, mysql_error(mysql));
           goto err;
-        case EE_OUTOFMEMORY:
-        case ER_OUTOFMEMORY:
+        case ER_OUT_OF_RESOURCES:
           sql_print_error("\
 Stopping slave I/O thread due to out-of-memory error from master");
+          mi->report(ERROR_LEVEL, ER_OUT_OF_RESOURCES,
+                     "%s", ER(ER_OUT_OF_RESOURCES));
           goto err;
         }
         if (try_to_reconnect(thd, mysql, mi, &retry_count, suppress_warnings,
@@ -2746,9 +2746,11 @@ err:
   pthread_cond_broadcast(&mi->stop_cond);       // tell the world we are done
   DBUG_EXECUTE_IF("simulate_slave_delay_at_terminate_bug38694", sleep(5););
   pthread_mutex_unlock(&mi->run_lock);
+
+  DBUG_LEAVE;                                   // Must match DBUG_ENTER()
   my_thread_end();
   pthread_exit(0);
-  DBUG_RETURN(0);                               // Can't return anything here
+  return 0;                                     // Avoid compiler warnings
 }
 
 /*
@@ -3104,10 +3106,11 @@ the slave SQL thread with \"SLAVE START\
   pthread_cond_broadcast(&rli->stop_cond);
   DBUG_EXECUTE_IF("simulate_slave_delay_at_terminate_bug38694", sleep(5););
   pthread_mutex_unlock(&rli->run_lock);  // tell the world we are done
-  
+
+  DBUG_LEAVE;                                   // Must match DBUG_ENTER()
   my_thread_end();
   pthread_exit(0);
-  DBUG_RETURN(0);                               // Can't return anything here
+  return 0;                                     // Avoid compiler warnings
 }
 
 
@@ -3705,7 +3708,7 @@ extern "C" void slave_io_thread_detach_v
 {
 #ifdef SIGNAL_WITH_VIO_CLOSE
   THD *thd= current_thd;
-  if (thd->slave_thread)
+  if (thd && thd->slave_thread)
     thd->clear_active_vio();
 #endif
 }

=== modified file 'sql/slave.h'
--- a/sql/slave.h	2009-09-15 01:04:15 +0000
+++ b/sql/slave.h	2009-11-10 15:15:12 +0000
@@ -191,8 +191,7 @@ int purge_relay_logs(Relay_log_info* rli
 void set_slave_thread_options(THD* thd);
 void set_slave_thread_default_charset(THD *thd, Relay_log_info const *rli);
 void rotate_relay_log(Master_info* mi);
-int apply_event_and_update_pos(Log_event* ev, THD* thd, Relay_log_info* rli,
-                               bool skip);
+int apply_event_and_update_pos(Log_event* ev, THD* thd, Relay_log_info* rli);
 
 pthread_handler_t handle_slave_io(void *arg);
 pthread_handler_t handle_slave_sql(void *arg);

=== modified file 'sql/sp.cc'
--- a/sql/sp.cc	2009-07-28 22:39:58 +0000
+++ b/sql/sp.cc	2009-10-16 10:29:42 +0000
@@ -997,7 +997,7 @@ sp_drop_routine(THD *thd, int type, sp_n
 
   if (ret == SP_OK)
   {
-    write_bin_log(thd, TRUE, thd->query, thd->query_length);
+    write_bin_log(thd, TRUE, thd->query(), thd->query_length());
     sp_cache_invalidate();
   }
 
@@ -1067,7 +1067,7 @@ sp_update_routine(THD *thd, int type, sp
 
   if (ret == SP_OK)
   {
-    write_bin_log(thd, TRUE, thd->query, thd->query_length);
+    write_bin_log(thd, TRUE, thd->query(), thd->query_length());
     sp_cache_invalidate();
   }
 

=== modified file 'sql/sp_head.cc'
--- a/sql/sp_head.cc	2009-09-15 10:46:35 +0000
+++ b/sql/sp_head.cc	2009-11-10 15:15:12 +0000
@@ -334,16 +334,18 @@ bool
 sp_eval_expr(THD *thd, Field *result_field, Item **expr_item_ptr)
 {
   Item *expr_item;
+  enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
+  bool save_abort_on_warning= thd->abort_on_warning;
+  bool save_stmt_modified_non_trans_table= 
+    thd->transaction.stmt.modified_non_trans_table;
 
   DBUG_ENTER("sp_eval_expr");
 
   if (!*expr_item_ptr)
-    DBUG_RETURN(TRUE);
+    goto error;
 
   if (!(expr_item= sp_prepare_func_item(thd, expr_item_ptr)))
-    DBUG_RETURN(TRUE);
-
-  bool err_status= FALSE;
+    goto error;
 
   /*
     Set THD flags to emit warnings/errors in case of overflow/type errors
@@ -352,10 +354,6 @@ sp_eval_expr(THD *thd, Field *result_fie
     Save original values and restore them after save.
   */
   
-  enum_check_fields save_count_cuted_fields= thd->count_cuted_fields;
-  bool save_abort_on_warning= thd->abort_on_warning;
-  bool save_stmt_modified_non_trans_table= thd->transaction.stmt.modified_non_trans_table;
-
   thd->count_cuted_fields= CHECK_FIELD_ERROR_FOR_NULL;
   thd->abort_on_warning=
     thd->variables.sql_mode &
@@ -370,13 +368,18 @@ sp_eval_expr(THD *thd, Field *result_fie
   thd->abort_on_warning= save_abort_on_warning;
   thd->transaction.stmt.modified_non_trans_table= save_stmt_modified_non_trans_table;
 
-  if (thd->is_error())
-  {
-    /* Return error status if something went wrong. */
-    err_status= TRUE;
-  }
+  if (!thd->is_error())
+    DBUG_RETURN(FALSE);
 
-  DBUG_RETURN(err_status);
+error:
+  /*
+    In case of error during evaluation, leave the result field set to NULL.
+    Sic: we can't do it in the beginning of the function because the 
+    result field might be needed for its own re-evaluation, e.g. case of 
+    set x = x + 1;
+  */
+  result_field->set_null();
+  DBUG_RETURN (TRUE);
 }
 
 
@@ -2824,8 +2827,8 @@ sp_instr_stmt::execute(THD *thd, uint *n
   DBUG_ENTER("sp_instr_stmt::execute");
   DBUG_PRINT("info", ("command: %d", m_lex_keeper.sql_command()));
 
-  query= thd->query;
-  query_length= thd->query_length;
+  query= thd->query();
+  query_length= thd->query_length();
 #if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
   /* This s-p instr is profilable and will be captured. */
   thd->profiling.set_query_source(m_query.str, m_query.length);
@@ -2838,10 +2841,11 @@ sp_instr_stmt::execute(THD *thd, uint *n
       queries with SP vars can't be cached)
     */
     if (unlikely((thd->options & OPTION_LOG_OFF)==0))
-      general_log_write(thd, COM_QUERY, thd->query, thd->query_length);
+      general_log_write(thd, COM_QUERY, thd->query(), thd->query_length());
 
     if (query_cache_send_result_to_client(thd,
-					  thd->query, thd->query_length) <= 0)
+          thd->query(), 
+          thd->query_length()) <= 0)
     {
       res= m_lex_keeper.reset_lex_and_exec_core(thd, nextp, FALSE, this);
 

=== modified file 'sql/sql_acl.cc'
--- a/sql/sql_acl.cc	2009-10-15 21:38:29 +0000
+++ b/sql/sql_acl.cc	2009-11-10 15:15:12 +0000
@@ -263,8 +263,7 @@ my_bool acl_init(bool dont_read_acl_tabl
   acl_cache= new hash_filo(ACL_CACHE_SIZE, 0, 0,
                            (hash_get_key) acl_entry_get_key,
                            (hash_free_key) free,
-                           lower_case_file_system ?
-                           system_charset_info : &my_charset_bin);
+                           &my_charset_utf8_bin);
   if (dont_read_acl_tables)
   {
     DBUG_RETURN(0); /* purecov: tested */
@@ -2252,10 +2251,13 @@ public:
   ulong sort;
   size_t key_length;
   GRANT_NAME(const char *h, const char *d,const char *u,
-             const char *t, ulong p);
-  GRANT_NAME (TABLE *form);
+             const char *t, ulong p, bool is_routine);
+  GRANT_NAME (TABLE *form, bool is_routine);
   virtual ~GRANT_NAME() {};
   virtual bool ok() { return privs != 0; }
+  void set_user_details(const char *h, const char *d,
+                        const char *u, const char *t,
+                        bool is_routine);
 };
 
 
@@ -2273,38 +2275,48 @@ public:
 };
 
 
-
-GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
-                       const char *t, ulong p)
-  :privs(p)
+void GRANT_NAME::set_user_details(const char *h, const char *d,
+                                  const char *u, const char *t,
+                                  bool is_routine)
 {
   /* Host given by user */
   update_hostname(&host, strdup_root(&memex, h));
-  db =   strdup_root(&memex,d);
+  if (db != d)
+  {
+    db= strdup_root(&memex, d);
+    if (lower_case_table_names)
+      my_casedn_str(files_charset_info, db);
+  }
   user = strdup_root(&memex,u);
   sort=  get_sort(3,host.hostname,db,user);
-  tname= strdup_root(&memex,t);
-  if (lower_case_table_names)
+  if (tname != t)
   {
-    my_casedn_str(files_charset_info, db);
-    my_casedn_str(files_charset_info, tname);
+    tname= strdup_root(&memex, t);
+    if (lower_case_table_names || is_routine)
+      my_casedn_str(files_charset_info, tname);
   }
   key_length= strlen(d) + strlen(u)+ strlen(t)+3;
   hash_key=   (char*) alloc_root(&memex,key_length);
   strmov(strmov(strmov(hash_key,user)+1,db)+1,tname);
 }
 
+GRANT_NAME::GRANT_NAME(const char *h, const char *d,const char *u,
+                       const char *t, ulong p, bool is_routine)
+  :db(0), tname(0), privs(p)
+{
+  set_user_details(h, d, u, t, is_routine);
+}
 
 GRANT_TABLE::GRANT_TABLE(const char *h, const char *d,const char *u,
                 	 const char *t, ulong p, ulong c)
-  :GRANT_NAME(h,d,u,t,p), cols(c)
+  :GRANT_NAME(h,d,u,t,p, FALSE), cols(c)
 {
   (void) hash_init2(&hash_columns,4,system_charset_info,
                    0,0,0, (hash_get_key) get_key_column,0,0);
 }
 
 
-GRANT_NAME::GRANT_NAME(TABLE *form)
+GRANT_NAME::GRANT_NAME(TABLE *form, bool is_routine)
 {
   update_hostname(&host, get_field(&memex, form->field[0]));
   db=    get_field(&memex,form->field[1]);
@@ -2322,6 +2334,9 @@ GRANT_NAME::GRANT_NAME(TABLE *form)
   if (lower_case_table_names)
   {
     my_casedn_str(files_charset_info, db);
+  }
+  if (lower_case_table_names || is_routine)
+  {
     my_casedn_str(files_charset_info, tname);
   }
   key_length= (strlen(db) + strlen(user) + strlen(tname) + 3);
@@ -2333,7 +2348,7 @@ GRANT_NAME::GRANT_NAME(TABLE *form)
 
 
 GRANT_TABLE::GRANT_TABLE(TABLE *form, TABLE *col_privs)
-  :GRANT_NAME(form)
+  :GRANT_NAME(form, FALSE)
 {
   uchar key[MAX_KEY_LENGTH];
 
@@ -3185,7 +3200,7 @@ int mysql_table_grant(THD *thd, TABLE_LI
 
   if (!result) /* success */
   {
-    write_bin_log(thd, TRUE, thd->query, thd->query_length);
+    write_bin_log(thd, TRUE, thd->query(), thd->query_length());
   }
 
   rw_unlock(&LOCK_grant);
@@ -3328,7 +3343,7 @@ bool mysql_routine_grant(THD *thd, TABLE
       }
       grant_name= new GRANT_NAME(Str->host.str, db_name,
 				 Str->user.str, table_name,
-				 rights);
+				 rights, TRUE);
       if (!grant_name)
       {
         result= TRUE;
@@ -3350,7 +3365,7 @@ bool mysql_routine_grant(THD *thd, TABLE
 
   if (write_to_binlog)
   {
-    write_bin_log(thd, TRUE, thd->query, thd->query_length);
+    write_bin_log(thd, TRUE, thd->query(), thd->query_length());
   }
 
   rw_unlock(&LOCK_grant);
@@ -3462,7 +3477,7 @@ bool mysql_grant(THD *thd, const char *d
 
   if (!result)
   {
-    write_bin_log(thd, TRUE, thd->query, thd->query_length);
+    write_bin_log(thd, TRUE, thd->query(), thd->query_length());
   }
 
   rw_unlock(&LOCK_grant);
@@ -3539,10 +3554,10 @@ static my_bool grant_load_procs_priv(TAB
   MEM_ROOT **save_mem_root_ptr= my_pthread_getspecific_ptr(MEM_ROOT**,
                                                            THR_MALLOC);
   DBUG_ENTER("grant_load_procs_priv");
-  (void) hash_init(&proc_priv_hash,system_charset_info,
+  (void) hash_init(&proc_priv_hash, &my_charset_utf8_bin,
                    0,0,0, (hash_get_key) get_grant_table,
                    0,0);
-  (void) hash_init(&func_priv_hash,system_charset_info,
+  (void) hash_init(&func_priv_hash, &my_charset_utf8_bin,
                    0,0,0, (hash_get_key) get_grant_table,
                    0,0);
   p_table->file->ha_index_init(0, 1);
@@ -3556,7 +3571,7 @@ static my_bool grant_load_procs_priv(TAB
     {
       GRANT_NAME *mem_check;
       HASH *hash;
-      if (!(mem_check=new (memex_ptr) GRANT_NAME(p_table)))
+      if (!(mem_check=new (memex_ptr) GRANT_NAME(p_table, TRUE)))
       {
         /* This could only happen if we are out memory */
         goto end_unlock;
@@ -3640,7 +3655,7 @@ static my_bool grant_load(THD *thd, TABL
 
   thd->variables.sql_mode&= ~MODE_PAD_CHAR_TO_FULL_LENGTH;
 
-  (void) hash_init(&column_priv_hash,system_charset_info,
+  (void) hash_init(&column_priv_hash, &my_charset_utf8_bin,
                    0,0,0, (hash_get_key) get_grant_table,
                    (hash_free_key) free_grant_table,0);
 
@@ -4073,8 +4088,7 @@ bool check_column_grant_in_table_ref(THD
     db_name= table_ref->view_db.str;
     table_name= table_ref->view_name.str;
     if (table_ref->belong_to_view && 
-        (thd->lex->sql_command == SQLCOM_SHOW_FIELDS ||
-         thd->lex->sql_command == SQLCOM_SHOW_CREATE))
+        thd->lex->sql_command == SQLCOM_SHOW_FIELDS)
     {
       view_privs= get_column_grant(thd, grant, db_name, table_name, name);
       if (view_privs & VIEW_ANY_ACL)
@@ -5438,9 +5452,21 @@ static int handle_grant_struct(uint stru
 
       case 2:
       case 3:
-        grant_name->user= strdup_root(&mem, user_to->user.str);
-        update_hostname(&grant_name->host,
-                        strdup_root(&mem, user_to->host.str));
+        /* 
+          Update the grant structure with the new user name and
+          host name
+        */
+        grant_name->set_user_details(user_to->host.str, grant_name->db,
+                                     user_to->user.str, grant_name->tname,
+                                     TRUE);
+
+        /*
+          Since username is part of the hash key, when the user name
+          is renamed, the hash key is changed. Update the hash to
+          ensure that the position matches the new hash key value
+        */
+        hash_update(&column_priv_hash, (uchar*) grant_name,
+                    (uchar*) grant_name->hash_key, grant_name->key_length);
 	break;
       }
     }
@@ -5663,7 +5689,7 @@ bool mysql_create_user(THD *thd, List <L
     my_error(ER_CANNOT_USER, MYF(0), "CREATE USER", wrong_users.c_ptr_safe());
 
   if (some_users_created)
-    write_bin_log(thd, FALSE, thd->query, thd->query_length);
+    write_bin_log(thd, FALSE, thd->query(), thd->query_length());
 
   rw_unlock(&LOCK_grant);
   close_thread_tables(thd);
@@ -5736,7 +5762,7 @@ bool mysql_drop_user(THD *thd, List <LEX
     my_error(ER_CANNOT_USER, MYF(0), "DROP USER", wrong_users.c_ptr_safe());
 
   if (some_users_deleted)
-    write_bin_log(thd, FALSE, thd->query, thd->query_length);
+    write_bin_log(thd, FALSE, thd->query(), thd->query_length());
 
   rw_unlock(&LOCK_grant);
   close_thread_tables(thd);
@@ -5821,7 +5847,7 @@ bool mysql_rename_user(THD *thd, List <L
     my_error(ER_CANNOT_USER, MYF(0), "RENAME USER", wrong_users.c_ptr_safe());
   
   if (some_users_renamed && mysql_bin_log.is_open())
-    write_bin_log(thd, FALSE, thd->query, thd->query_length);
+    write_bin_log(thd, FALSE, thd->query(), thd->query_length());
 
   rw_unlock(&LOCK_grant);
   close_thread_tables(thd);
@@ -6003,7 +6029,7 @@ bool mysql_revoke_all(THD *thd,  List <L
 
   VOID(pthread_mutex_unlock(&acl_cache->lock));
 
-  write_bin_log(thd, FALSE, thd->query, thd->query_length);
+  write_bin_log(thd, FALSE, thd->query(), thd->query_length());
 
   rw_unlock(&LOCK_grant);
   close_thread_tables(thd);
@@ -6117,7 +6143,7 @@ bool sp_revoke_privileges(THD *thd, cons
     for (counter= 0, revoked= 0 ; counter < hash->records ; )
     {
       GRANT_NAME *grant_proc= (GRANT_NAME*) hash_element(hash, counter);
-      if (!my_strcasecmp(system_charset_info, grant_proc->db, sp_db) &&
+      if (!my_strcasecmp(&my_charset_utf8_bin, grant_proc->db, sp_db) &&
 	  !my_strcasecmp(system_charset_info, grant_proc->tname, sp_name))
       {
         LEX_USER lex_user;

=== modified file 'sql/sql_base.cc'
--- a/sql/sql_base.cc	2009-10-15 21:38:29 +0000
+++ b/sql/sql_base.cc	2009-11-10 15:15:12 +0000
@@ -17,6 +17,7 @@
 /* Basic functions needed by many modules */
 
 #include "mysql_priv.h"
+#include "debug_sync.h"
 #include "sql_select.h"
 #include "sp_head.h"
 #include "sp.h"
@@ -24,6 +25,7 @@
 #include <m_ctype.h>
 #include <my_dir.h>
 #include <hash.h>
+#include "rpl_filter.h"
 #ifdef  __WIN__
 #include <io.h>
 #endif
@@ -106,7 +108,7 @@ static bool open_new_frm(THD *thd, TABLE
 static void close_old_data_files(THD *thd, TABLE *table, bool morph_locks,
                                  bool send_refresh);
 static bool
-has_two_write_locked_tables_with_auto_increment(TABLE_LIST *tables);
+has_write_table_with_auto_increment(TABLE_LIST *tables);
 
 
 extern "C" uchar *table_cache_key(const uchar *record, size_t *length,
@@ -950,6 +952,7 @@ bool close_cached_tables(THD *thd, TABLE
 
     close_old_data_files(thd,thd->open_tables,1,1);
     mysql_ha_flush(thd);
+    DEBUG_SYNC(thd, "after_flush_unlock");
 
     bool found=1;
     /* Wait until all threads has closed all the tables we had locked */
@@ -1545,6 +1548,7 @@ void close_temporary_tables(THD *thd)
                             s_query.length() - 1 /* to remove trailing ',' */,
                             0, FALSE, 0);
       qinfo.db= db.ptr();
+      qinfo.db_len= db.length();
       thd->variables.character_set_client= cs_save;
       mysql_bin_log.write(&qinfo);
       thd->variables.pseudo_thread_id= save_pseudo_thread_id;
@@ -2306,7 +2310,8 @@ bool reopen_name_locked_table(THD* thd, 
   table->tablenr=thd->current_tablenr++;
   table->used_fields=0;
   table->const_table=0;
-  table->null_row= table->maybe_null= table->force_index= 0;
+  table->null_row= table->maybe_null= 0;
+  table->force_index= table->force_index_order= table->force_index_group= 0;
   table->status=STATUS_NO_RECORD;
   DBUG_RETURN(FALSE);
 }
@@ -2964,7 +2969,8 @@ TABLE *open_table(THD *thd, TABLE_LIST *
   table->tablenr=thd->current_tablenr++;
   table->used_fields=0;
   table->const_table=0;
-  table->null_row= table->maybe_null= table->force_index= 0;
+  table->null_row= table->maybe_null= 0;
+  table->force_index= table->force_index_order= table->force_index_group= 0;
   table->status=STATUS_NO_RECORD;
   table->insert_values= 0;
   table->fulltext_searched= 0;
@@ -5112,7 +5118,16 @@ static void mark_real_tables_as_free_for
 
 int decide_logging_format(THD *thd, TABLE_LIST *tables)
 {
-  if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG))
+  /*
+    In SBR mode, we are only proceeding if we are binlogging this
+    statement, ie, the filtering rules won't later filter this out.
+
+    This check here is needed to prevent some spurious error to be
+    raised in some cases (See BUG#42829).
+   */
+  if (mysql_bin_log.is_open() && (thd->options & OPTION_BIN_LOG) &&
+      (thd->variables.binlog_format != BINLOG_FORMAT_STMT ||
+       binlog_filter->db_ok(thd->db)))
   {
     /*
       Compute the starting vectors for the computations by creating a
@@ -5295,18 +5310,22 @@ int lock_tables(THD *thd, TABLE_LIST *ta
       thd->in_lock_tables=1;
       thd->options|= OPTION_TABLE_LOCK;
       /*
-        If we have >= 2 different tables to update with auto_inc columns,
-        statement-based binlogging won't work. We can solve this problem in
-        mixed mode by switching to row-based binlogging:
-      */
-      if (thd->variables.binlog_format == BINLOG_FORMAT_MIXED &&
-          has_two_write_locked_tables_with_auto_increment(tables))
+        A query that modifies autoinc column in sub-statement can make the 
+        master and slave inconsistent.
+        We can solve these problems in mixed mode by switching to binlogging 
+        if at least one updated table is used by sub-statement
+      */
+      /* The BINLOG_FORMAT_MIXED judgement is saved for suppressing 
+         warnings, but it will be removed by fixing bug#45827 */
+      if (thd->variables.binlog_format == BINLOG_FORMAT_MIXED && tables && 
+          has_write_table_with_auto_increment(thd->lex->first_not_own_table()))
       {
         thd->lex->set_stmt_unsafe();
-        thd->set_current_stmt_binlog_row_based_if_mixed();
       }
     }
 
+    DEBUG_SYNC(thd, "before_lock_tables_takes_lock");
+
     if (! (thd->lock= mysql_lock_tables(thd, start, (uint) (ptr - start),
                                         lock_flag, need_reopen)))
     {
@@ -8830,47 +8849,31 @@ void mysql_wait_completed_table(ALTER_PA
 
 
 /*
-  Tells if two (or more) tables have auto_increment columns and we want to
-  lock those tables with a write lock.
+  Check if one (or more) write tables have auto_increment columns.
 
-  SYNOPSIS
-    has_two_write_locked_tables_with_auto_increment
-      tables        Table list
+  @param[in] tables Table list
+
+  @retval 0 if at least one write tables has an auto_increment column
+  @retval 1 otherwise
 
   NOTES:
     Call this function only when you have established the list of all tables
     which you'll want to update (including stored functions, triggers, views
     inside your statement).
-
-  RETURN
-    0  No
-    1  Yes
 */
 
 static bool
-has_two_write_locked_tables_with_auto_increment(TABLE_LIST *tables)
+has_write_table_with_auto_increment(TABLE_LIST *tables)
 {
-  char *first_table_name= NULL, *first_db;
-  LINT_INIT(first_db);
-
   for (TABLE_LIST *table= tables; table; table= table->next_global)
   {
     /* we must do preliminary checks as table->table may be NULL */
     if (!table->placeholder() &&
         table->table->found_next_number_field &&
         (table->lock_type >= TL_WRITE_ALLOW_WRITE))
-    {
-      if (first_table_name == NULL)
-      {
-        first_table_name= table->table_name;
-        first_db= table->db;
-        DBUG_ASSERT(first_db);
-      }
-      else if (strcmp(first_db, table->db) ||
-               strcmp(first_table_name, table->table_name))
-        return 1;
-    }
+      return 1;
   }
+
   return 0;
 }
 

=== modified file 'sql/sql_binlog.cc'
--- a/sql/sql_binlog.cc	2009-05-06 12:03:24 +0000
+++ b/sql/sql_binlog.cc	2009-11-10 15:15:12 +0000
@@ -56,17 +56,20 @@ void mysql_client_binlog_statement(THD* 
     Format_description_event.
   */
   my_bool have_fd_event= TRUE;
-  if (!thd->rli_fake)
+  int err;
+  Relay_log_info *rli;
+  rli= thd->rli_fake;
+  if (!rli)
   {
-    thd->rli_fake= new Relay_log_info;
+    rli= thd->rli_fake= new Relay_log_info;
 #ifdef HAVE_valgrind
-    thd->rli_fake->is_fake= TRUE;
+    rli->is_fake= TRUE;
 #endif
     have_fd_event= FALSE;
   }
-  if (thd->rli_fake && !thd->rli_fake->relay_log.description_event_for_exec)
+  if (rli && !rli->relay_log.description_event_for_exec)
   {
-    thd->rli_fake->relay_log.description_event_for_exec=
+    rli->relay_log.description_event_for_exec=
       new Format_description_log_event(4);
     have_fd_event= FALSE;
   }
@@ -78,16 +81,16 @@ void mysql_client_binlog_statement(THD* 
   /*
     Out of memory check
   */
-  if (!(thd->rli_fake &&
-        thd->rli_fake->relay_log.description_event_for_exec &&
+  if (!(rli &&
+        rli->relay_log.description_event_for_exec &&
         buf))
   {
     my_error(ER_OUTOFMEMORY, MYF(0), 1);  /* needed 1 bytes */
     goto end;
   }
 
-  thd->rli_fake->sql_thd= thd;
-  thd->rli_fake->no_storage= TRUE;
+  rli->sql_thd= thd;
+  rli->no_storage= TRUE;
 
   for (char const *strptr= thd->lex->comment.str ;
        strptr < thd->lex->comment.str + thd->lex->comment.length ; )
@@ -170,8 +173,7 @@ void mysql_client_binlog_statement(THD* 
       }
 
       ev= Log_event::read_log_event(bufptr, event_len, &error,
-                                    thd->rli_fake->relay_log.
-                                      description_event_for_exec);
+                                    rli->relay_log.description_event_for_exec);
 
       DBUG_PRINT("info",("binlog base64 err=%s", error));
       if (!ev)
@@ -209,18 +211,10 @@ void mysql_client_binlog_statement(THD* 
         reporting.
       */
 #if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
-      if (apply_event_and_update_pos(ev, thd, thd->rli_fake, FALSE))
-      {
-        delete ev;
-        /*
-          TODO: Maybe a better error message since the BINLOG statement
-          now contains several events.
-        */
-        my_error(ER_UNKNOWN_ERROR, MYF(0), "Error executing BINLOG statement");
-        goto end;
-      }
+      err= ev->apply_event(rli);
+#else
+      err= 0;
 #endif
-
       /*
         Format_description_log_event should not be deleted because it
         will be used to read info about the relay log's format; it
@@ -228,8 +222,17 @@ void mysql_client_binlog_statement(THD* 
         i.e. when this thread terminates.
       */
       if (ev->get_type_code() != FORMAT_DESCRIPTION_EVENT)
-        delete ev;
+        delete ev; 
       ev= 0;
+      if (err)
+      {
+        /*
+          TODO: Maybe a better error message since the BINLOG statement
+          now contains several events.
+        */
+        my_error(ER_UNKNOWN_ERROR, MYF(0), "Error executing BINLOG statement");
+        goto end;
+      }
     }
   }
 
@@ -238,7 +241,7 @@ void mysql_client_binlog_statement(THD* 
   my_ok(thd);
 
 end:
-  thd->rli_fake->clear_tables_to_lock();
+  rli->clear_tables_to_lock();
   my_free(buf, MYF(MY_ALLOW_ZERO_PTR));
   DBUG_VOID_RETURN;
 }

=== modified file 'sql/sql_cache.cc'
--- a/sql/sql_cache.cc	2009-10-26 11:35:42 +0000
+++ b/sql/sql_cache.cc	2009-11-10 15:15:12 +0000
@@ -1119,8 +1119,8 @@ void Query_cache::store_query(THD *thd, 
     DBUG_VOID_RETURN;
   uint8 tables_type= 0;
 
-  if ((local_tables= is_cacheable(thd, thd->query_length,
-				  thd->query, thd->lex, tables_used,
+  if ((local_tables= is_cacheable(thd, thd->query_length(),
+				  thd->query(), thd->lex, tables_used,
 				  &tables_type)))
   {
     NET *net= &thd->net;
@@ -1210,7 +1210,8 @@ def_week_frmt: %lu, in_trans: %d, autoco
     /* Key is query + database + flag */
     if (thd->db_length)
     {
-      memcpy(thd->query+thd->query_length+1, thd->db, thd->db_length);
+      memcpy(thd->query() + thd->query_length() + 1, thd->db, 
+        thd->db_length);
       DBUG_PRINT("qcache", ("database: %s  length: %u",
 			    thd->db, (unsigned) thd->db_length)); 
     }
@@ -1218,24 +1219,24 @@ def_week_frmt: %lu, in_trans: %d, autoco
     {
       DBUG_PRINT("qcache", ("No active database"));
     }
-    tot_length= thd->query_length + thd->db_length + 1 +
+    tot_length= thd->query_length() + thd->db_length + 1 +
       QUERY_CACHE_FLAGS_SIZE;
     /*
       We should only copy structure (don't use it location directly)
       because of alignment issue
     */
-    memcpy((void *)(thd->query + (tot_length - QUERY_CACHE_FLAGS_SIZE)),
+    memcpy((void*) (thd->query() + (tot_length - QUERY_CACHE_FLAGS_SIZE)),
 	   &flags, QUERY_CACHE_FLAGS_SIZE);
 
     /* Check if another thread is processing the same query? */
     Query_cache_block *competitor = (Query_cache_block *)
-      hash_search(&queries, (uchar*) thd->query, tot_length);
+      hash_search(&queries, (uchar*) thd->query(), tot_length);
     DBUG_PRINT("qcache", ("competitor 0x%lx", (ulong) competitor));
     if (competitor == 0)
     {
       /* Query is not in cache and no one is working with it; Store it */
       Query_cache_block *query_block;
-      query_block= write_block_data(tot_length, (uchar*) thd->query,
+      query_block= write_block_data(tot_length, (uchar*) thd->query(),
 				    ALIGN_SIZE(sizeof(Query_cache_query)),
 				    Query_cache_block::QUERY, local_tables);
       if (query_block != 0)

=== modified file 'sql/sql_class.cc'
--- a/sql/sql_class.cc	2009-09-15 10:46:35 +0000
+++ b/sql/sql_class.cc	2009-11-10 15:15:12 +0000
@@ -42,6 +42,7 @@
 
 #include "sp_rcontext.h"
 #include "sp_cache.h"
+#include "debug_sync.h"
 
 /*
   The following is used to initialise Table_ident with a internal
@@ -378,14 +379,14 @@ char *thd_security_context(THD *thd, cha
     str.append(proc_info);
   }
 
-  if (thd->query)
+  if (thd->query())
   {
     if (max_query_len < 1)
-      len= thd->query_length;
+      len= thd->query_length();
     else
-      len= min(thd->query_length, max_query_len);
+      len= min(thd->query_length(), max_query_len);
     str.append('\n');
-    str.append(thd->query, len);
+    str.append(thd->query(), len);
   }
   if (str.c_ptr_safe() == buffer)
     return buffer;
@@ -402,6 +403,31 @@ char *thd_security_context(THD *thd, cha
   return buffer;
 }
 
+
+/**
+  Implementation of Drop_table_error_handler::handle_error().
+  The reason in having this implementation is to silence technical low-level
+  warnings during DROP TABLE operation. Currently we don't want to expose
+  the following warnings during DROP TABLE:
+    - Some of table files are missed or invalid (the table is going to be
+      deleted anyway, so why bother that something was missed);
+    - A trigger associated with the table does not have DEFINER (One of the
+      MySQL specifics now is that triggers are loaded for the table being
+      dropped. So, we may have a warning that trigger does not have DEFINER
+      attribute during DROP TABLE operation).
+
+  @return TRUE if the condition is handled.
+*/
+bool Drop_table_error_handler::handle_error(uint sql_errno,
+                                            const char *message,
+                                            MYSQL_ERROR::enum_warning_level level,
+                                            THD *thd)
+{
+  return ((sql_errno == EE_DELETE && my_errno == ENOENT) ||
+          sql_errno == ER_TRG_NO_DEFINER);
+}
+
+
 /**
   Clear this diagnostics area. 
 
@@ -564,6 +590,9 @@ THD::THD()
    derived_tables_processing(FALSE),
    spcont(NULL),
    m_parser_state(NULL)
+#if defined(ENABLED_DEBUG_SYNC)
+   , debug_sync_control(0)
+#endif /* defined(ENABLED_DEBUG_SYNC) */
 {
   ulong tmp;
 
@@ -702,17 +731,13 @@ void THD::push_internal_handler(Internal
 bool THD::handle_error(uint sql_errno, const char *message,
                        MYSQL_ERROR::enum_warning_level level)
 {
-  if (!m_internal_handler)
-    return FALSE;
-
   for (Internal_error_handler *error_handler= m_internal_handler;
        error_handler;
        error_handler= m_internal_handler->m_prev_internal_handler)
   {
     if (error_handler->handle_error(sql_errno, message, level, this))
-    return TRUE;
+      return TRUE;
   }
-
   return FALSE;
 }
 
@@ -818,6 +843,11 @@ void THD::init(void)
   reset_current_stmt_binlog_row_based();
   bzero((char *) &status_var, sizeof(status_var));
   sql_log_bin_toplevel= options & OPTION_BIN_LOG;
+
+#if defined(ENABLED_DEBUG_SYNC)
+  /* Initialize the Debug Sync Facility. See debug_sync.cc. */
+  debug_sync_init_thread(this);
+#endif /* defined(ENABLED_DEBUG_SYNC) */
 }
 
 
@@ -898,6 +928,12 @@ void THD::cleanup(void)
     close_thread_tables(this);
   }
   wt_thd_destroy(&transaction.wt);
+
+#if defined(ENABLED_DEBUG_SYNC)
+  /* End the Debug Sync Facility. See debug_sync.cc. */
+  debug_sync_end_thread(this);
+#endif /* defined(ENABLED_DEBUG_SYNC) */
+
   mysql_ha_cleanup(this);
   delete_dynamic(&user_var_events);
   hash_free(&user_vars);
@@ -2449,12 +2485,12 @@ Statement::Statement(LEX *lex_arg, MEM_R
   id(id_arg),
   mark_used_columns(MARK_COLUMNS_READ),
   lex(lex_arg),
-  query(0),
-  query_length(0),
   cursor(0),
   db(NULL),
   db_length(0)
 {
+  query_string.length= 0;
+  query_string.str= NULL;
   name.str= NULL;
 }
 
@@ -2470,8 +2506,7 @@ void Statement::set_statement(Statement 
   id=             stmt->id;
   mark_used_columns=   stmt->mark_used_columns;
   lex=            stmt->lex;
-  query=          stmt->query;
-  query_length=   stmt->query_length;
+  query_string=   stmt->query_string;
   cursor=         stmt->cursor;
 }
 
@@ -2495,6 +2530,15 @@ void Statement::restore_backup_statement
 }
 
 
+/** Assign a new value to thd->query.  */
+
+void Statement::set_query_inner(char *query_arg, uint32 query_length_arg)
+{
+  query_string.str= query_arg;
+  query_string.length= query_length_arg;
+}
+
+
 void THD::end_statement()
 {
   /* Cleanup SQL processing state to reuse this statement in next query. */
@@ -2730,9 +2774,11 @@ bool select_dumpvar::send_data(List<Item
     else
     {
       Item_func_set_user_var *suv= new Item_func_set_user_var(mv->s, item);
-      suv->fix_fields(thd, 0);
+      if (suv->fix_fields(thd, 0))
+        DBUG_RETURN (1);
       suv->save_item_result(item);
-      suv->update();
+      if (suv->update())
+        DBUG_RETURN (1);
     }
   }
   DBUG_RETURN(thd->is_error());
@@ -3008,9 +3054,24 @@ extern "C" struct charset_info_st *thd_c
   return(thd->charset());
 }
 
+/**
+  OBSOLETE : there's no way to ensure the string is null terminated.
+  Use thd_query_string instead()
+*/
 extern "C" char **thd_query(MYSQL_THD thd)
 {
-  return(&thd->query);
+  return(&thd->query_string.str);
+}
+
+/**
+  Get the current query string for the thread.
+
+  @param The MySQL internal thread pointer
+  @return query string and length. May be non-null-terminated.
+*/
+extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd)
+{
+  return(&thd->query_string);
 }
 
 extern "C" int thd_slave_thread(const MYSQL_THD thd)
@@ -3035,6 +3096,11 @@ extern "C" void thd_mark_transaction_to_
 {
   mark_transaction_to_rollback(thd, all);
 }
+
+extern "C" bool thd_binlog_filter_ok(const MYSQL_THD thd)
+{
+  return binlog_filter->db_ok(thd->db);
+}
 #endif // INNODB_COMPATIBILITY_HOOKS */
 
 /****************************************************************************
@@ -3191,8 +3257,7 @@ void THD::set_statement(Statement *stmt)
 void THD::set_query(char *query_arg, uint32 query_length_arg)
 {
   pthread_mutex_lock(&LOCK_thd_data);
-  query= query_arg;
-  query_length= query_length_arg;
+  set_query_inner(query_arg, query_length_arg);
   pthread_mutex_unlock(&LOCK_thd_data);
 }
 
@@ -3210,6 +3275,16 @@ void mark_transaction_to_rollback(THD *t
   {
     thd->is_fatal_sub_stmt_error= TRUE;
     thd->transaction_rollback_request= all;
+    /*
+      Aborted transactions can not be IGNOREd.
+      Switch off the IGNORE flag for the current
+      SELECT_LEX. This should allow my_error()
+      to report the error and abort the execution
+      flow, even in presence
+      of IGNORE clause.
+    */
+    if (thd->lex->current_select)
+      thd->lex->current_select->no_error= FALSE;
   }
 }
 /***************************************************************************

=== modified file 'sql/sql_class.h'
--- a/sql/sql_class.h	2009-09-15 10:46:35 +0000
+++ b/sql/sql_class.h	2009-11-10 15:15:12 +0000
@@ -95,6 +95,8 @@ extern char internal_table_name[2];
 extern char empty_c_string[1];
 extern MYSQL_PLUGIN_IMPORT const char **errmesg;
 
+extern bool volatile shutdown_in_progress;
+
 #define TC_LOG_PAGE_SIZE   8192
 #define TC_LOG_MIN_SIZE    (3*TC_LOG_PAGE_SIZE)
 
@@ -652,10 +654,13 @@ public:
     This printing is needed at least in SHOW PROCESSLIST and SHOW
     ENGINE INNODB STATUS.
   */
-  char *query;
-  uint32 query_length;                          // current query length
+  LEX_STRING query_string;
   Server_side_cursor *cursor;
 
+  inline char *query() { return query_string.str; }
+  inline uint32 query_length() { return query_string.length; }
+  void set_query_inner(char *query_arg, uint32 query_length_arg);
+
   /**
     Name of the current (default) database.
 
@@ -1103,6 +1108,31 @@ public:
 
 
 /**
+  This class is an internal error handler implementation for 
+  DROP TABLE statements. The thing is that there may be warnings during
+  execution of these statements, which should not be exposed to the user.
+  This class is intended to silence such warnings.
+*/
+
+class Drop_table_error_handler : public Internal_error_handler
+{
+public:
+  Drop_table_error_handler(Internal_error_handler *err_handler)
+    :m_err_handler(err_handler)
+  { }
+
+public:
+  bool handle_error(uint sql_errno,
+                    const char *message,
+                    MYSQL_ERROR::enum_warning_level level,
+                    THD *thd);
+
+private:
+  Internal_error_handler *m_err_handler;
+};
+
+
+/**
   Stores status of the currently executed statement.
   Cleared at the beginning of the statement, and then
   can hold either OK, ERROR, or EOF status.
@@ -1888,6 +1918,11 @@ public:
   partition_info *work_part_info;
 #endif
 
+#if defined(ENABLED_DEBUG_SYNC)
+  /* Debug Sync facility. See debug_sync.cc. */
+  struct st_debug_sync_control *debug_sync_control;
+#endif /* defined(ENABLED_DEBUG_SYNC) */
+
   THD();
   ~THD();
 
@@ -2124,7 +2159,11 @@ public:
   {
     int err= killed_errno();
     if (err)
+    {
+      if ((err == KILL_CONNECTION) && !shutdown_in_progress)
+        err = KILL_QUERY;
       my_message(err, ER(err), MYF(0));
+    }
   }
   /* return TRUE if we will abort query if we make a warning now */
   inline bool really_abort_on_warning()
@@ -2641,7 +2680,32 @@ public:
   ENGINE_COLUMNDEF *recinfo, *start_recinfo;
   KEY *keyinfo;
   ha_rows end_write_records;
-  uint	field_count,sum_func_count,func_count;
+  /**
+    Number of normal fields in the query, including those referred to
+    from aggregate functions. Hence, "SELECT `field1`,
+    SUM(`field2`) from t1" sets this counter to 2.
+
+    @see count_field_types
+  */
+  uint	field_count; 
+  /**
+    Number of fields in the query that have functions. Includes both
+    aggregate functions (e.g., SUM) and non-aggregates (e.g., RAND).
+    Also counts functions referred to from aggregate functions, i.e.,
+    "SELECT SUM(RAND())" sets this counter to 2.
+
+    @see count_field_types
+  */
+  uint  func_count;  
+  /**
+    Number of fields in the query that have aggregate functions. Note
+    that the optimizer may choose to optimize away these fields by
+    replacing them with constants, in which case sum_func_count will
+    need to be updated.
+
+    @see opt_sum_query, count_field_types
+  */
+  uint  sum_func_count;   
   uint  hidden_field_count;
   uint	group_parts,group_length,group_null_parts;
   uint	quick_group;
@@ -2906,7 +2970,8 @@ public:
   bool send_data(List<Item> &items);
   bool initialize_tables (JOIN *join);
   void send_error(uint errcode,const char *err);
-  int  do_deletes();
+  int do_deletes();
+  int do_table_deletes(TABLE *table, bool ignore);
   bool send_eof();
   virtual void abort();
 };

=== modified file 'sql/sql_db.cc'
--- a/sql/sql_db.cc	2009-10-15 21:38:29 +0000
+++ b/sql/sql_db.cc	2009-11-10 15:15:12 +0000
@@ -703,7 +703,7 @@ not_silent:
     char *query;
     uint query_length;
 
-    if (!thd->query)				// Only in replication
+    if (!thd->query())                          // Only in replication
     {
       query= 	     tmp_query;
       query_length= (uint) (strxmov(tmp_query,"create database `",
@@ -711,8 +711,8 @@ not_silent:
     }
     else
     {
-      query= 	    thd->query;
-      query_length= thd->query_length;
+      query=        thd->query();
+      query_length= thd->query_length();
     }
 
     ha_binlog_log_query(thd, 0, LOGCOM_CREATE_DB,
@@ -805,13 +805,13 @@ bool mysql_alter_db(THD *thd, const char
   }
 
   ha_binlog_log_query(thd, 0, LOGCOM_ALTER_DB,
-                      thd->query, thd->query_length,
+                      thd->query(), thd->query_length(),
                       db, "");
 
   if (mysql_bin_log.is_open())
   {
     int errcode= query_error_code(thd, TRUE);
-    Query_log_event qinfo(thd, thd->query, thd->query_length, 0,
+    Query_log_event qinfo(thd, thd->query(), thd->query_length(), 0,
 			  /* suppress_use */ TRUE, errcode);
 
     /*
@@ -907,6 +907,9 @@ bool mysql_rm_db(THD *thd,char *db,bool 
     remove_db_from_cache(db);
     pthread_mutex_unlock(&LOCK_open);
 
+    Drop_table_error_handler err_handler(thd->get_internal_handler());
+    thd->push_internal_handler(&err_handler);
+
     error= -1;
     /*
       We temporarily disable the binary log while dropping the objects
@@ -939,12 +942,13 @@ bool mysql_rm_db(THD *thd,char *db,bool 
       error = 0;
       reenable_binlog(thd);
     }
+    thd->pop_internal_handler();
   }
   if (!silent && deleted>=0)
   {
     const char *query;
     ulong query_length;
-    if (!thd->query)
+    if (!thd->query())
     {
       /* The client used the old obsolete mysql_drop_db() call */
       query= path;
@@ -953,8 +957,8 @@ bool mysql_rm_db(THD *thd,char *db,bool 
     }
     else
     {
-      query =thd->query;
-      query_length= thd->query_length;
+      query= thd->query();
+      query_length= thd->query_length();
     }
     if (mysql_bin_log.is_open())
     {
@@ -1444,7 +1448,7 @@ static inline bool
 cmp_db_names(const char *db1_name,
              const char *db2_name)
 {
-  return ((!db1_name && !db2_name) || /* db1 is NULL and db2 is NULL */
+  return ((!db1_name && !db2_name) ||
           (db1_name && db2_name &&
            my_strcasecmp(system_charset_info, db1_name, db2_name) == 0));
 }
@@ -1956,7 +1960,7 @@ bool mysql_upgrade_db(THD *thd, LEX_STRI
   if (mysql_bin_log.is_open())
   {
     int errcode= query_error_code(thd, TRUE);
-    Query_log_event qinfo(thd, thd->query, thd->query_length,
+    Query_log_event qinfo(thd, thd->query(), thd->query_length(),
                           0, TRUE, errcode);
     thd->clear_error();
     mysql_bin_log.write(&qinfo);

=== modified file 'sql/sql_delete.cc'
--- a/sql/sql_delete.cc	2009-10-15 21:38:29 +0000
+++ b/sql/sql_delete.cc	2009-11-10 15:15:12 +0000
@@ -413,7 +413,7 @@ cleanup:
         therefore be treated as a DDL.
       */
       int log_result= thd->binlog_query(query_type,
-                                        thd->query, thd->query_length,
+                                        thd->query(), thd->query_length(),
                                         is_trans, FALSE, errcode);
 
       if (log_result)
@@ -850,7 +850,7 @@ void multi_delete::abort()
     {
       int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED);
       thd->binlog_query(THD::ROW_QUERY_TYPE,
-                        thd->query, thd->query_length,
+                        thd->query(), thd->query_length(),
                         transactional_tables, FALSE, errcode);
     }
     thd->transaction.all.modified_non_trans_table= true;
@@ -860,22 +860,19 @@ void multi_delete::abort()
 
 
 
-/*
+/**
   Do delete from other tables.
-  Returns values:
-	0 ok
-	1 error
+
+  @retval 0 ok
+  @retval 1 error
+
+  @todo Is there any reason not use the normal nested-loops join? If not, and
+  there is no documentation supporting it, this method and callee should be
+  removed and there should be hooks within normal execution.
 */
 
 int multi_delete::do_deletes()
 {
-  int local_error= 0, counter= 0, tmp_error;
-  bool will_batch;
-  /*
-    If the IGNORE option is used all non fatal errors will be translated
-    to warnings and we should not break the row-by-row iteration
-  */
-  bool ignore= thd->lex->current_select->no_error;
   DBUG_ENTER("do_deletes");
   DBUG_ASSERT(do_delete);
 
@@ -886,79 +883,108 @@ int multi_delete::do_deletes()
   table_being_deleted= (delete_while_scanning ? delete_tables->next_local :
                         delete_tables);
  
-  for (; table_being_deleted;
+  for (uint counter= 0; table_being_deleted;
        table_being_deleted= table_being_deleted->next_local, counter++)
   { 
-    ha_rows last_deleted= deleted;
     TABLE *table = table_being_deleted->table;
     if (tempfiles[counter]->get(table))
+      DBUG_RETURN(1);
+
+    int local_error= 
+      do_table_deletes(table, thd->lex->current_select->no_error);
+
+    if (thd->killed && !local_error)
+      DBUG_RETURN(1);
+
+    if (local_error == -1)				// End of file
+      local_error = 0;
+
+    if (local_error)
+      DBUG_RETURN(local_error);
+  }
+  DBUG_RETURN(0);
+}
+
+
+/**
+   Implements the inner loop of nested-loops join within multi-DELETE
+   execution.
+
+   @param table The table from which to delete.
+
+   @param ignore If used, all non fatal errors will be translated
+   to warnings and we should not break the row-by-row iteration.
+
+   @return Status code
+
+   @retval  0 All ok.
+   @retval  1 Triggers or handler reported error.
+   @retval -1 End of file from handler.
+*/
+int multi_delete::do_table_deletes(TABLE *table, bool ignore)
+{
+  int local_error= 0;
+  READ_RECORD info;
+  ha_rows last_deleted= deleted;
+  DBUG_ENTER("do_deletes_for_table");
+  init_read_record(&info, thd, table, NULL, 0, 1, FALSE);
+  /*
+    Ignore any rows not found in reference tables as they may already have
+    been deleted by foreign key handling
+  */
+  info.ignore_not_found_rows= 1;
+  bool will_batch= !table->file->start_bulk_delete();
+  while (!(local_error= info.read_record(&info)) && !thd->killed)
+  {
+    if (table->triggers &&
+        table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
+                                          TRG_ACTION_BEFORE, FALSE))
     {
-      local_error=1;
+      local_error= 1;
       break;
     }
-
-    READ_RECORD	info;
-    init_read_record(&info, thd, table, NULL, 0, 1, FALSE);
+      
+    local_error= table->file->ha_delete_row(table->record[0]);
+    if (local_error && !ignore)
+    {
+      table->file->print_error(local_error, MYF(0));
+      break;
+    }
+      
     /*
-      Ignore any rows not found in reference tables as they may already have
-      been deleted by foreign key handling
+      Increase the reported number of deleted rows only if no error occurred
+      during ha_delete_row.
+      Also, don't execute the AFTER trigger if the row operation failed.
     */
-    info.ignore_not_found_rows= 1;
-    will_batch= !table->file->start_bulk_delete();
-    while (!(local_error=info.read_record(&info)) && !thd->killed)
+    if (!local_error)
     {
+      deleted++;
       if (table->triggers &&
           table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
-                                            TRG_ACTION_BEFORE, FALSE))
+                                            TRG_ACTION_AFTER, FALSE))
       {
         local_error= 1;
         break;
       }
-
-      local_error= table->file->ha_delete_row(table->record[0]);
-      if (local_error && !ignore)
-      {
-        table->file->print_error(local_error,MYF(0));
-        break;
-      }
-
-      /*
-        Increase the reported number of deleted rows only if no error occurred
-        during ha_delete_row.
-        Also, don't execute the AFTER trigger if the row operation failed.
-      */
-      if (!local_error)
-      {
-        deleted++;
-        if (table->triggers &&
-            table->triggers->process_triggers(thd, TRG_EVENT_DELETE,
-                                              TRG_ACTION_AFTER, FALSE))
-        {
-          local_error= 1;
-          break;
-        }
-      }
     }
-    if (will_batch && (tmp_error= table->file->end_bulk_delete()))
+  }
+  if (will_batch)
+  {
+    int tmp_error= table->file->end_bulk_delete();
+    if (tmp_error && !local_error)
     {
-      if (!local_error)
-      {
-        local_error= tmp_error;
-        table->file->print_error(local_error,MYF(0));
-      }
+      local_error= tmp_error;
+      table->file->print_error(local_error, MYF(0));
     }
-    if (last_deleted != deleted && !table->file->has_transactions())
-      thd->transaction.stmt.modified_non_trans_table= TRUE;
-    end_read_record(&info);
-    if (thd->killed && !local_error)
-      local_error= 1;
-    if (local_error == -1)				// End of file
-      local_error = 0;
   }
+  if (last_deleted != deleted && !table->file->has_transactions())
+    thd->transaction.stmt.modified_non_trans_table= TRUE;
+
+  end_read_record(&info);
+
   DBUG_RETURN(local_error);
 }
 
-
 /*
   Send ok to the client
 
@@ -998,7 +1024,7 @@ bool multi_delete::send_eof()
       else
         errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
       if (thd->binlog_query(THD::ROW_QUERY_TYPE,
-                            thd->query, thd->query_length,
+                            thd->query(), thd->query_length(),
                             transactional_tables, FALSE, errcode) &&
           !normal_tables)
       {
@@ -1144,7 +1170,7 @@ end:
         TRUNCATE must always be statement-based binlogged (not row-based) so
         we don't test current_stmt_binlog_row_based.
       */
-      write_bin_log(thd, TRUE, thd->query, thd->query_length);
+      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
       my_ok(thd);		// This should return record count
     }
     VOID(pthread_mutex_lock(&LOCK_open));

=== modified file 'sql/sql_handler.cc'
--- a/sql/sql_handler.cc	2009-07-15 23:23:57 +0000
+++ b/sql/sql_handler.cc	2009-09-17 15:25:52 +0000
@@ -422,16 +422,13 @@ bool mysql_ha_read(THD *thd, TABLE_LIST 
   String	buffer(buff, sizeof(buff), system_charset_info);
   int           error, keyno= -1;
   uint          num_rows;
-  uchar		*key;
-  uint		key_len;
+  uchar		*UNINIT_VAR(key);
+  uint		UNINIT_VAR(key_len);
   bool          need_reopen;
   DBUG_ENTER("mysql_ha_read");
   DBUG_PRINT("enter",("'%s'.'%s' as '%s'",
                       tables->db, tables->table_name, tables->alias));
 
-  LINT_INIT(key);
-  LINT_INIT(key_len);
-
   thd->lex->select_lex.context.resolve_in_table_list_only(tables);
   list.push_front(new Item_field(&thd->lex->select_lex.context,
                                  NULL, NULL, "*"));

=== modified file 'sql/sql_insert.cc'
--- a/sql/sql_insert.cc	2009-11-07 10:34:19 +0000
+++ b/sql/sql_insert.cc	2009-11-10 15:15:12 +0000
@@ -589,7 +589,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *t
   Name_resolution_context *context;
   Name_resolution_context_state ctx_state;
 #ifndef EMBEDDED_LIBRARY
-  char *query= thd->query;
+  char *query= thd->query();
   /*
     log_on is about delayed inserts only.
     By default, both logs are enabled (this won't cause problems if the server
@@ -826,7 +826,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *t
 #ifndef EMBEDDED_LIBRARY
     if (lock_type == TL_WRITE_DELAYED)
     {
-      LEX_STRING const st_query = { query, thd->query_length };
+      LEX_STRING const st_query = { query, thd->query_length() };
       error=write_delayed(thd, table, duplic, st_query, ignore, log_on);
       query=0;
     }
@@ -919,7 +919,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *t
 	*/
 	DBUG_ASSERT(thd->killed != THD::KILL_BAD_DATA || error > 0);
 	if (thd->binlog_query(THD::ROW_QUERY_TYPE,
-			      thd->query, thd->query_length,
+                              thd->query(), thd->query_length(),
 			      transactional_table, FALSE,
 			      errcode))
         {
@@ -1791,7 +1791,7 @@ public:
     pthread_cond_destroy(&cond);
     pthread_cond_destroy(&cond_client);
     thd.unlink();				// Must be unlinked under lock
-    x_free(thd.query);
+    x_free(thd.query());
     thd.security_ctx->user= thd.security_ctx->host=0;
     thread_count--;
     delayed_insert_threads--;
@@ -1937,7 +1937,7 @@ bool delayed_get_table(THD *thd, TABLE_L
       pthread_mutex_unlock(&LOCK_thread_count);
       di->thd.set_db(table_list->db, (uint) strlen(table_list->db));
       di->thd.set_query(my_strdup(table_list->table_name, MYF(MY_WME)), 0);
-      if (di->thd.db == NULL || di->thd.query == NULL)
+      if (di->thd.db == NULL || di->thd.query() == NULL)
       {
         /* The error is reported */
 	delete di;
@@ -1946,7 +1946,7 @@ bool delayed_get_table(THD *thd, TABLE_L
       }
       di->table_list= *table_list;			// Needed to open table
       /* Replace volatile strings with local copies */
-      di->table_list.alias= di->table_list.table_name= di->thd.query;
+      di->table_list.alias= di->table_list.table_name= di->thd.query();
       di->table_list.db= di->thd.db;
       di->lock();
       pthread_mutex_lock(&di->mutex);
@@ -2302,44 +2302,9 @@ void kill_delayed_threads(void)
 }
 
 
-/*
- * Create a new delayed insert thread
-*/
-
-pthread_handler_t handle_delayed_insert(void *arg)
+static void handle_delayed_insert_impl(THD *thd, Delayed_insert *di)
 {
-  Delayed_insert *di=(Delayed_insert*) arg;
-  THD *thd= &di->thd;
-
-  pthread_detach_this_thread();
-  /* Add thread to THD list so that's it's visible in 'show processlist' */
-  pthread_mutex_lock(&LOCK_thread_count);
-  thd->thread_id= thd->variables.pseudo_thread_id= thread_id++;
-  thd->set_current_time();
-  threads.append(thd);
-  thd->killed=abort_loop ? THD::KILL_CONNECTION : THD::NOT_KILLED;
-  pthread_mutex_unlock(&LOCK_thread_count);
-
-  /*
-    Wait until the client runs into pthread_cond_wait(),
-    where we free it after the table is opened and di linked in the list.
-    If we did not wait here, the client might detect the opened table
-    before it is linked to the list. It would release LOCK_delayed_create
-    and allow another thread to create another handler for the same table,
-    since it does not find one in the list.
-  */
-  pthread_mutex_lock(&di->mutex);
-#if !defined( __WIN__) /* Win32 calls this in pthread_create */
-  if (my_thread_init())
-  {
-    /* Can't use my_error since store_globals has not yet been called */
-    thd->main_da.set_error_status(thd, ER_OUT_OF_RESOURCES,
-                                  ER(ER_OUT_OF_RESOURCES));
-    goto end;
-  }
-#endif
-
-  DBUG_ENTER("handle_delayed_insert");
+  DBUG_ENTER("handle_delayed_insert_impl");
   thd->thread_stack= (char*) &thd;
   if (init_thr_lock() || thd->store_globals())
   {
@@ -2528,6 +2493,49 @@ err:
    */
   ha_autocommit_or_rollback(thd, 1);
 
+  DBUG_VOID_RETURN;
+}
+
+
+/*
+ * Create a new delayed insert thread
+*/
+
+pthread_handler_t handle_delayed_insert(void *arg)
+{
+  Delayed_insert *di=(Delayed_insert*) arg;
+  THD *thd= &di->thd;
+
+  pthread_detach_this_thread();
+  /* Add thread to THD list so that's it's visible in 'show processlist' */
+  pthread_mutex_lock(&LOCK_thread_count);
+  thd->thread_id= thd->variables.pseudo_thread_id= thread_id++;
+  thd->set_current_time();
+  threads.append(thd);
+  thd->killed=abort_loop ? THD::KILL_CONNECTION : THD::NOT_KILLED;
+  pthread_mutex_unlock(&LOCK_thread_count);
+
+  /*
+    Wait until the client runs into pthread_cond_wait(),
+    where we free it after the table is opened and di linked in the list.
+    If we did not wait here, the client might detect the opened table
+    before it is linked to the list. It would release LOCK_delayed_create
+    and allow another thread to create another handler for the same table,
+    since it does not find one in the list.
+  */
+  pthread_mutex_lock(&di->mutex);
+#if !defined( __WIN__) /* Win32 calls this in pthread_create */
+  if (my_thread_init())
+  {
+    /* Can't use my_error since store_globals has not yet been called */
+    thd->main_da.set_error_status(thd, ER_OUT_OF_RESOURCES,
+                                  ER(ER_OUT_OF_RESOURCES));
+    goto end;
+  }
+#endif
+
+  handle_delayed_insert_impl(thd, di);
+
 #ifndef __WIN__
 end:
 #endif
@@ -2552,7 +2560,8 @@ end:
 
   my_thread_end();
   pthread_exit(0);
-  DBUG_RETURN(0);
+
+  return 0;
 }
 
 
@@ -3269,7 +3278,7 @@ bool select_insert::send_eof()
     else
       errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
     thd->binlog_query(THD::ROW_QUERY_TYPE,
-                      thd->query, thd->query_length,
+                      thd->query(), thd->query_length(),
                       trans_table, FALSE, errcode);
   }
   table->file->ha_release_auto_increment();
@@ -3339,7 +3348,8 @@ void select_insert::abort() {
         if (mysql_bin_log.is_open())
         {
           int errcode= query_error_code(thd, thd->killed == THD::NOT_KILLED);
-          thd->binlog_query(THD::ROW_QUERY_TYPE, thd->query, thd->query_length,
+          thd->binlog_query(THD::ROW_QUERY_TYPE, thd->query(),
+                            thd->query_length(),
                             transactional_table, FALSE, errcode);
         }
         if (!thd->current_stmt_binlog_row_based && !can_rollback_data())
@@ -3633,7 +3643,7 @@ select_create::prepare(List<Item> &value
   DBUG_EXECUTE_IF("sleep_create_select_before_check_if_exists", my_sleep(6000000););
 
   if (!(create_info->options & HA_LEX_CREATE_TMP_TABLE) &&
-      create_table->table->db_stat)
+      (create_table->table && create_table->table->db_stat))
   {
     /* Table already exists and was open at open_and_lock_tables() stage. */
     if (create_info->options & HA_LEX_CREATE_IF_NOT_EXISTS)

=== modified file 'sql/sql_lex.h'
--- a/sql/sql_lex.h	2009-09-15 10:46:35 +0000
+++ b/sql/sql_lex.h	2009-11-10 15:15:12 +0000
@@ -1735,13 +1735,6 @@ typedef struct st_lex : public Query_tab
 
   const char *stmt_definition_end;
 
-  /*
-    Pointers to part of LOAD DATA statement that should be rewritten
-    during replication ("LOCAL 'filename' REPLACE INTO" part).
-  */
-  const char *fname_start;
-  const char *fname_end;
-  
   /**
     During name resolution search only in the table list given by 
     Name_resolution_context::first_name_resolution_table and

=== modified file 'sql/sql_load.cc'
--- a/sql/sql_load.cc	2009-09-07 20:50:10 +0000
+++ b/sql/sql_load.cc	2009-11-10 15:15:12 +0000
@@ -83,10 +83,13 @@ static int read_sep_field(THD *thd, COPY
 			  String &enclosed, ulong skip_lines,
 			  bool ignore_check_option_errors);
 #ifndef EMBEDDED_LIBRARY
-static bool write_execute_load_query_log_event(THD *thd,
-					       bool duplicates, bool ignore,
-					       bool transactional_table,
-                                               int errcode);
+static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex,
+                                               const char* db_arg, /* table's database */
+                                               const char* table_name_arg,
+                                               enum enum_duplicates duplicates,
+                                               bool ignore,
+                                               bool transactional_table,
+                                               int errocode);
 #endif /* EMBEDDED_LIBRARY */
 
 /*
@@ -497,8 +500,11 @@ int mysql_load(THD *thd,sql_exchange *ex
           int errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
           
 	  if (thd->transaction.stmt.modified_non_trans_table)
-	    write_execute_load_query_log_event(thd, handle_duplicates,
-					       ignore, transactional_table,
+            write_execute_load_query_log_event(thd, ex,
+                                               table_list->db, 
+                                               table_list->table_name,
+                                               handle_duplicates, ignore,
+                                               transactional_table,
                                                errcode);
 	  else
 	  {
@@ -542,8 +548,11 @@ int mysql_load(THD *thd,sql_exchange *ex
       if (lf_info.wrote_create_file)
       {
         int errcode= query_error_code(thd, killed_status == THD::NOT_KILLED);
-        write_execute_load_query_log_event(thd, handle_duplicates, ignore,
-                                           transactional_table, errcode);
+        write_execute_load_query_log_event(thd, ex,
+                                           table_list->db, table_list->table_name,
+                                           handle_duplicates, ignore,
+                                           transactional_table,
+                                           errcode);
       }
     }
   }
@@ -564,15 +573,113 @@ err:
 #ifndef EMBEDDED_LIBRARY
 
 /* Not a very useful function; just to avoid duplication of code */
-static bool write_execute_load_query_log_event(THD *thd,
-					       bool duplicates, bool ignore,
-					       bool transactional_table,
+static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex,
+                                               const char* db_arg,  /* table's database */
+                                               const char* table_name_arg,
+                                               enum enum_duplicates duplicates,
+                                               bool ignore,
+                                               bool transactional_table,
                                                int errcode)
 {
+  char                *load_data_query,
+                      *end,
+                      *fname_start,
+                      *fname_end,
+                      *p= NULL;
+  size_t               pl= 0;
+  List<Item>           fv;
+  Item                *item, *val;
+  String               pfield, pfields;
+  int                  n;
+  const char          *tbl= table_name_arg;
+  const char          *tdb= (thd->db != NULL ? thd->db : db_arg);
+  String              string_buf;
+
+  if (!thd->db || strcmp(db_arg, thd->db)) 
+  {
+    /*
+      If used database differs from table's database, 
+      prefix table name with database name so that it 
+      becomes a FQ name.
+     */
+    string_buf.set_charset(system_charset_info);
+    string_buf.append(db_arg);
+    string_buf.append("`");
+    string_buf.append(".");
+    string_buf.append("`");
+    string_buf.append(table_name_arg);
+    tbl= string_buf.c_ptr_safe();
+  }
+
+  Load_log_event       lle(thd, ex, tdb, tbl, fv, duplicates,
+                           ignore, transactional_table);
+
+  /*
+    force in a LOCAL if there was one in the original.
+  */
+  if (thd->lex->local_file)
+    lle.set_fname_outside_temp_buf(ex->file_name, strlen(ex->file_name));
+
+  /*
+    prepare fields-list and SET if needed; print_query won't do that for us.
+  */
+  if (!thd->lex->field_list.is_empty())
+  {
+    List_iterator<Item>  li(thd->lex->field_list);
+
+    pfields.append(" (");
+    n= 0;
+
+    while ((item= li++))
+    {
+      if (n++)
+        pfields.append(", ");
+      if (item->name)
+        pfields.append(item->name);
+      else
+        item->print(&pfields, QT_ORDINARY);
+    }
+    pfields.append(")");
+  }
+
+  if (!thd->lex->update_list.is_empty())
+  {
+    List_iterator<Item> lu(thd->lex->update_list);
+    List_iterator<Item> lv(thd->lex->value_list);
+
+    pfields.append(" SET ");
+    n= 0;
+
+    while ((item= lu++))
+    {
+      val= lv++;
+      if (n++)
+        pfields.append(", ");
+      pfields.append(item->name);
+      pfields.append("=");
+      val->print(&pfields, QT_ORDINARY);
+    }
+  }
+
+  p= pfields.c_ptr_safe();
+  pl= strlen(p);
+
+  if (!(load_data_query= (char *)thd->alloc(lle.get_query_buffer_length() + 1 + pl)))
+    return TRUE;
+
+  lle.print_query(FALSE, (const char *) ex->cs?ex->cs->csname:NULL,
+                  load_data_query, &end,
+                  (char **)&fname_start, (char **)&fname_end);
+
+  strcpy(end, p);
+  end += pl;
+
+  thd->set_query_inner(load_data_query, end - load_data_query);
+
   Execute_load_query_log_event
-    e(thd, thd->query, thd->query_length,
-      (uint) ((char*)thd->lex->fname_start - (char*)thd->query),
-      (uint) ((char*)thd->lex->fname_end - (char*)thd->query),
+    e(thd, thd->query(), thd->query_length(),
+      (uint) ((char*) fname_start - (char*) thd->query() - 1),
+      (uint) ((char*) fname_end - (char*) thd->query()),
       (duplicates == DUP_REPLACE) ? LOAD_DUP_REPLACE :
       (ignore ? LOAD_DUP_IGNORE : LOAD_DUP_ERROR),
       transactional_table, FALSE, errcode);

=== modified file 'sql/sql_locale.cc'
--- a/sql/sql_locale.cc	2008-12-23 14:21:01 +0000
+++ b/sql/sql_locale.cc	2009-10-19 08:41:52 +0000
@@ -1309,9 +1309,9 @@ static const char *my_locale_month_names
 static const char *my_locale_ab_month_names_ro_RO[13] = 
  {"ian","feb","mar","apr","mai","iun","iul","aug","sep","oct","nov","dec", NullS };
 static const char *my_locale_day_names_ro_RO[8] = 
- {"Luni","Mar��i","Miercuri","Joi","Vineri","S��mb��t��","Duminic��", NullS };
+ {"Luni","Mar��i","Miercuri","Joi","Vineri","S��mb��t��","Duminic��", NullS };
 static const char *my_locale_ab_day_names_ro_RO[8] = 
- {"Lu","Ma","Mi","Jo","Vi","S��","Du", NullS };
+ {"Lu","Ma","Mi","Jo","Vi","S��","Du", NullS };
 static TYPELIB my_locale_typelib_month_names_ro_RO = 
  { array_elements(my_locale_month_names_ro_RO)-1, "", my_locale_month_names_ro_RO, NULL };
 static TYPELIB my_locale_typelib_ab_month_names_ro_RO = 

=== modified file 'sql/sql_parse.cc'
--- a/sql/sql_parse.cc	2009-11-06 17:22:32 +0000
+++ b/sql/sql_parse.cc	2009-11-10 15:15:12 +0000
@@ -126,6 +126,14 @@ static bool xa_trans_rolled_back(XID_STA
 */
 static bool xa_trans_rollback(THD *thd)
 {
+  /*
+    Resource Manager error is meaningless at this point, as we perform
+    explicit rollback request by user. We must reset rm_error before
+    calling ha_rollback(), so thd->transaction.xid structure gets reset
+    by ha_rollback()/THD::transaction::cleanup().
+  */
+  thd->transaction.xid_state.rm_error= 0;
+
   bool status= test(ha_rollback(thd));
 
   thd->options&= ~(ulong) OPTION_BEGIN;
@@ -133,7 +141,6 @@ static bool xa_trans_rollback(THD *thd)
   thd->server_status&= ~SERVER_STATUS_IN_TRANS;
   xid_cache_delete(&thd->transaction.xid_state);
   thd->transaction.xid_state.xa_state= XA_NOTR;
-  thd->transaction.xid_state.rm_error= 0;
 
   return status;
 }
@@ -415,29 +422,12 @@ void execute_init_command(THD *thd, sys_
 }
 
 
-/**
-  Execute commands from bootstrap_file.
-
-  Used when creating the initial grant tables.
-*/
-
-pthread_handler_t handle_bootstrap(void *arg)
+static void handle_bootstrap_impl(THD *thd)
 {
-  THD *thd=(THD*) arg;
   FILE *file=bootstrap_file;
   char *buff;
   const char* found_semicolon= NULL;
 
-  /* The following must be called before DBUG_ENTER */
-  thd->thread_stack= (char*) &thd;
-  if (my_thread_init() || thd->store_globals())
-  {
-#ifndef EMBEDDED_LIBRARY
-    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
-#endif
-    thd->fatal_error();
-    goto end;
-  }
   DBUG_ENTER("handle_bootstrap");
 
 #ifndef EMBEDDED_LIBRARY
@@ -505,10 +495,10 @@ pthread_handler_t handle_bootstrap(void 
                                       thd->db_length + 1 +
                                       QUERY_CACHE_FLAGS_SIZE);
     thd->set_query(query, length);
-    DBUG_PRINT("query",("%-.4096s",thd->query));
+    DBUG_PRINT("query",("%-.4096s", thd->query()));
 #if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
     thd->profiling.start_new_query();
-    thd->profiling.set_query_source(thd->query, length);
+    thd->profiling.set_query_source(thd->query(), length);
 #endif
 
     /*
@@ -517,7 +507,7 @@ pthread_handler_t handle_bootstrap(void 
     */
     thd->query_id=next_query_id();
     thd->set_time();
-    mysql_parse(thd, thd->query, length, & found_semicolon);
+    mysql_parse(thd, thd->query(), length, & found_semicolon);
     close_thread_tables(thd);			// Free tables
 
     bootstrap_error= thd->is_error();
@@ -536,6 +526,33 @@ pthread_handler_t handle_bootstrap(void 
 #endif
   }
 
+  DBUG_VOID_RETURN;
+}
+
+
+/**
+  Execute commands from bootstrap_file.
+
+  Used when creating the initial grant tables.
+*/
+
+pthread_handler_t handle_bootstrap(void *arg)
+{
+  THD *thd=(THD*) arg;
+
+  /* The following must be called before DBUG_ENTER */
+  thd->thread_stack= (char*) &thd;
+  if (my_thread_init() || thd->store_globals())
+  {
+#ifndef EMBEDDED_LIBRARY
+    close_connection(thd, ER_OUT_OF_RESOURCES, 1);
+#endif
+    thd->fatal_error();
+    goto end;
+  }
+
+  handle_bootstrap_impl(thd);
+
 end:
   net_end(&thd->net);
   thd->cleanup();
@@ -550,7 +567,8 @@ end:
   my_thread_end();
   pthread_exit(0);
 #endif
-  DBUG_RETURN(0);
+
+  return 0;
 }
 
 
@@ -1211,20 +1229,20 @@ bool dispatch_command(enum enum_server_c
   {
     if (alloc_query(thd, packet, packet_length))
       break;					// fatal error is set
-    char *packet_end= thd->query + thd->query_length;
+    char *packet_end= thd->query() + thd->query_length();
     /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */
     const char* end_of_stmt= NULL;
 
-    general_log_write(thd, command, thd->query, thd->query_length);
-    DBUG_PRINT("query",("%-.4096s",thd->query));
+    general_log_write(thd, command, thd->query(), thd->query_length());
+    DBUG_PRINT("query",("%-.4096s",thd->query()));
 #if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
-    thd->profiling.set_query_source(thd->query, thd->query_length);
+    thd->profiling.set_query_source(thd->query(), thd->query_length());
 #endif
 
     if (!(specialflag & SPECIAL_NO_PRIOR))
       my_pthread_setprio(pthread_self(),QUERY_PRIOR);
 
-    mysql_parse(thd, thd->query, thd->query_length, &end_of_stmt);
+    mysql_parse(thd, thd->query(), thd->query_length(), &end_of_stmt);
 
     while (!thd->killed && (end_of_stmt != NULL) && ! thd->is_error())
     {
@@ -1436,7 +1454,28 @@ bool dispatch_command(enum enum_server_c
     if (check_global_access(thd,RELOAD_ACL))
       break;
     general_log_print(thd, command, NullS);
-    if (!reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used))
+#ifndef DBUG_OFF
+    bool debug_simulate= FALSE;
+    DBUG_EXECUTE_IF("simulate_detached_thread_refresh", debug_simulate= TRUE;);
+    if (debug_simulate)
+    {
+      /*
+        Simulate a reload without a attached thread session.
+        Provides a environment similar to that of when the
+        server receives a SIGHUP signal and reloads caches
+        and flushes tables.
+      */
+      bool res;
+      my_pthread_setspecific_ptr(THR_THD, NULL);
+      res= reload_acl_and_cache(NULL, options | REFRESH_FAST,
+                                NULL, &not_used);
+      my_pthread_setspecific_ptr(THR_THD, thd);
+      if (!res)
+        my_ok(thd);
+      break;
+    }
+#endif
+    if (!reload_acl_and_cache(thd, options, NULL, &not_used))
       my_ok(thd);
     break;
   }
@@ -1672,7 +1711,8 @@ void log_slow_statement(THD *thd)
     {
       thd_proc_info(thd, "logging slow query");
       thd->status_var.long_query_count++;
-      slow_log_print(thd, thd->query, thd->query_length, end_utime_of_query);
+      slow_log_print(thd, thd->query(), thd->query_length(), 
+                     end_utime_of_query);
     }
   }
   DBUG_VOID_RETURN;
@@ -2990,7 +3030,7 @@ end_with_restore_list:
       /*
         Presumably, REPAIR and binlog writing doesn't require synchronization
       */
-      write_bin_log(thd, TRUE, thd->query, thd->query_length);
+      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
     }
     select_lex->table_list.first= (uchar*) first_table;
     lex->query_tables=all_tables;
@@ -3024,7 +3064,7 @@ end_with_restore_list:
       /*
         Presumably, ANALYZE and binlog writing doesn't require synchronization
       */
-      write_bin_log(thd, TRUE, thd->query, thd->query_length);
+      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
     }
     select_lex->table_list.first= (uchar*) first_table;
     lex->query_tables=all_tables;
@@ -3048,7 +3088,7 @@ end_with_restore_list:
       /*
         Presumably, OPTIMIZE and binlog writing doesn't require synchronization
       */
-      write_bin_log(thd, TRUE, thd->query, thd->query_length);
+      write_bin_log(thd, TRUE, thd->query(), thd->query_length());
     }
     select_lex->table_list.first= (uchar*) first_table;
     lex->query_tables=all_tables;
@@ -4000,7 +4040,7 @@ end_with_restore_list:
       */
       if (!lex->no_write_to_binlog && write_to_binlog)
       {
-        write_bin_log(thd, FALSE, thd->query, thd->query_length);
+        write_bin_log(thd, FALSE, thd->query(), thd->query_length());
       }
       my_ok(thd);
     } 
@@ -4577,7 +4617,7 @@ create_sp_error:
       case SP_KEY_NOT_FOUND:
 	if (lex->drop_if_exists)
 	{
-          write_bin_log(thd, TRUE, thd->query, thd->query_length);
+          write_bin_log(thd, TRUE, thd->query(), thd->query_length());
 	  push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
 			      ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST),
 			      SP_COM_STRING(lex), lex->spname->m_name.str);
@@ -5107,8 +5147,6 @@ bool check_single_table_access(THD *thd,
   /* Show only 1 table for check_grant */
   if (!(all_tables->belong_to_view &&
         (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) &&
-      !(all_tables->view &&
-        all_tables->effective_algorithm == VIEW_ALGORITHM_TMPTABLE) &&
       check_grant(thd, privilege, all_tables, 0, 1, no_errors))
     goto deny;
 
@@ -5970,9 +6008,10 @@ void mysql_parse(THD *thd, const char *i
             PROCESSLIST.
             Note that we don't need LOCK_thread_count to modify query_length.
           */
-          if (*found_semicolon &&
-              (thd->query_length= (ulong)(*found_semicolon - thd->query)))
-            thd->query_length--;
+          if (*found_semicolon && (ulong) (*found_semicolon - thd->query()))
+            thd->set_query_inner(thd->query(),
+                                 (uint32) (*found_semicolon -
+                                           thd->query() - 1));
           /* Actually execute the query */
           if (*found_semicolon)
           {
@@ -6278,6 +6317,7 @@ TABLE_LIST *st_select_lex::add_table_to_
   ptr->table_name_length=table->table.length;
   ptr->lock_type=   lock_type;
   ptr->updating=    test(table_options & TL_OPTION_UPDATING);
+  /* TODO: remove TL_OPTION_FORCE_INDEX as it looks like it's not used */
   ptr->force_index= test(table_options & TL_OPTION_FORCE_INDEX);
   ptr->ignore_leaves= test(table_options & TL_OPTION_IGNORE_LEAVES);
   ptr->derived=	    table->sel;

=== modified file 'sql/sql_partition.cc'
--- a/sql/sql_partition.cc	2009-10-15 21:38:29 +0000
+++ b/sql/sql_partition.cc	2009-11-10 15:15:12 +0000
@@ -4077,7 +4077,7 @@ static int fast_end_partition(THD *thd, 
 
   if ((!is_empty) && (!written_bin_log) &&
       (!thd->lex->no_write_to_binlog))
-    write_bin_log(thd, FALSE, thd->query, thd->query_length);
+    write_bin_log(thd, FALSE, thd->query(), thd->query_length());
 
   my_snprintf(tmp_name, sizeof(tmp_name), ER(ER_INSERT_INFO),
               (ulong) (copied + deleted),
@@ -6235,7 +6235,7 @@ uint fast_alter_partition_table(THD *thd
         ERROR_INJECT_CRASH("crash_drop_partition_5") ||
         ((!thd->lex->no_write_to_binlog) &&
          (write_bin_log(thd, FALSE,
-                        thd->query, thd->query_length), FALSE)) ||
+                        thd->query(), thd->query_length()), FALSE)) ||
         ERROR_INJECT_CRASH("crash_drop_partition_6") ||
         ((frm_install= TRUE), FALSE) ||
         mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
@@ -6302,7 +6302,7 @@ uint fast_alter_partition_table(THD *thd
         ERROR_INJECT_CRASH("crash_add_partition_5") ||
         ((!thd->lex->no_write_to_binlog) &&
          (write_bin_log(thd, FALSE,
-                        thd->query, thd->query_length), FALSE)) ||
+                        thd->query(), thd->query_length()), FALSE)) ||
         ERROR_INJECT_CRASH("crash_add_partition_6") ||
         write_log_rename_frm(lpt) ||
         (not_completed= FALSE) ||
@@ -6392,7 +6392,7 @@ uint fast_alter_partition_table(THD *thd
         ERROR_INJECT_CRASH("crash_change_partition_6") ||
         ((!thd->lex->no_write_to_binlog) &&
          (write_bin_log(thd, FALSE,
-                        thd->query, thd->query_length), FALSE)) ||
+                        thd->query(), thd->query_length()), FALSE)) ||
         ERROR_INJECT_CRASH("crash_change_partition_7") ||
         mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
         ERROR_INJECT_CRASH("crash_change_partition_8") ||
@@ -7209,4 +7209,3 @@ void create_subpartition_name(char *out,
             "#SP#", transl_subpart_name, "#REN#", NullS);
 }
 #endif
-

=== modified file 'sql/sql_plugin.cc'
--- a/sql/sql_plugin.cc	2009-10-29 00:04:56 +0000
+++ b/sql/sql_plugin.cc	2009-11-10 15:15:12 +0000
@@ -1536,7 +1536,7 @@ error:
 
 void plugin_shutdown(void)
 {
-  uint i, count= plugin_array.elements, free_slots= 0;
+  uint i, count= plugin_array.elements;
   struct st_plugin_int **plugins, *plugin;
   struct st_plugin_dl **dl;
   DBUG_ENTER("plugin_shutdown");
@@ -1557,18 +1557,13 @@ void plugin_shutdown(void)
     while (reap_needed && (count= plugin_array.elements))
     {
       reap_plugins();
-      for (i= free_slots= 0; i < count; i++)
+      for (i= 0; i < count; i++)
       {
         plugin= *dynamic_element(&plugin_array, i, struct st_plugin_int **);
-        switch (plugin->state) {
-        case PLUGIN_IS_READY:
+        if (plugin->state == PLUGIN_IS_READY)
+        {
           plugin->state= PLUGIN_IS_DELETED;
           reap_needed= true;
-          break;
-        case PLUGIN_IS_FREED:
-        case PLUGIN_IS_UNINITIALIZED:
-          free_slots++;
-          break;
         }
       }
       if (!reap_needed)
@@ -1581,9 +1576,6 @@ void plugin_shutdown(void)
       }
     }
 
-    if (count > free_slots && global_system_variables.log_warnings > 1)
-      sql_print_warning("Forcing shutdown of %d plugins", count - free_slots);
-
     plugins= (struct st_plugin_int **) my_alloca(sizeof(void*) * (count+1));
 
     /*
@@ -1605,8 +1597,8 @@ void plugin_shutdown(void)
       if (!(plugins[i]->state & (PLUGIN_IS_UNINITIALIZED | PLUGIN_IS_FREED |
                                  PLUGIN_IS_DISABLED)))
       {
-        sql_print_information("Plugin '%s' will be forced to shutdown",
-                              plugins[i]->name.str);
+        sql_print_warning("Plugin '%s' will be forced to shutdown",
+                          plugins[i]->name.str);
         /*
           We are forcing deinit on plugins so we don't want to do a ref_count
           check until we have processed all the plugins.
@@ -2090,7 +2082,7 @@ static int check_func_set(THD *thd, stru
   const char *strvalue= "NULL", *str;
   TYPELIB *typelib;
   ulonglong result;
-  uint error_len;
+  uint error_len= 0;                            // init as only set on error
   bool not_used;
   int length;
 
@@ -2689,7 +2681,9 @@ uchar* sys_var_pluginvar::value_ptr(THD 
     {
       if (!(value & mask))
         continue;
-      str.append(typelib->type_names[i], typelib->type_lengths[i]);
+      str.append(typelib->type_names[i], typelib->type_lengths
+                                       ? typelib->type_lengths[i]
+                                       : strlen(typelib->type_names[i]));
       str.append(',');
     }
 

=== modified file 'sql/sql_prepare.cc'
--- a/sql/sql_prepare.cc	2009-10-15 21:38:29 +0000
+++ b/sql/sql_prepare.cc	2009-11-10 15:15:12 +0000
@@ -752,7 +752,7 @@ static bool insert_params_with_log(Prepa
   const String *res;
   DBUG_ENTER("insert_params_with_log");
 
-  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
+  if (query->copy(stmt->query(), stmt->query_length(), default_charset_info))
     DBUG_RETURN(1);
 
   for (Item_param **it= begin; it < end; ++it)
@@ -914,7 +914,7 @@ static bool emb_insert_params_with_log(P
 
   DBUG_ENTER("emb_insert_params_with_log");
 
-  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
+  if (query->copy(stmt->query(), stmt->query_length(), default_charset_info))
     DBUG_RETURN(1);
 
   for (; it < end; ++it, ++client_param)
@@ -1065,7 +1065,7 @@ static bool insert_params_from_vars_with
 
   DBUG_ENTER("insert_params_from_vars");
 
-  if (query->copy(stmt->query, stmt->query_length, default_charset_info))
+  if (query->copy(stmt->query(), stmt->query_length(), default_charset_info))
     DBUG_RETURN(1);
 
   for (Item_param **it= begin; it < end; ++it)
@@ -2346,6 +2346,9 @@ void reinit_stmt_before_use(THD *thd, LE
       /* Fix ORDER list */
       for (order= (ORDER *)sl->order_list.first; order; order= order->next)
         order->item= &order->item_ptr;
+
+      /* clear the no_error flag for INSERT/UPDATE IGNORE */
+      sl->no_error= FALSE;
     }
     {
       SELECT_LEX_UNIT *unit= sl->master_unit();
@@ -2461,9 +2464,9 @@ void mysqld_stmt_execute(THD *thd, char 
   }
 
 #if defined(ENABLED_PROFILING) && defined(COMMUNITY_SERVER)
-  thd->profiling.set_query_source(stmt->query, stmt->query_length);
+  thd->profiling.set_query_source(stmt->query(), stmt->query_length());
 #endif
-  DBUG_PRINT("exec_query", ("%s", stmt->query));
+  DBUG_PRINT("exec_query", ("%s", stmt->query()));
   DBUG_PRINT("info",("stmt: 0x%lx", (long) stmt));
 
   sp_cache_flush_obsolete(&thd->sp_proc_cache);
@@ -3032,7 +3035,7 @@ bool Prepared_statement::prepare(const c
   old_stmt_arena= thd->stmt_arena;
   thd->stmt_arena= this;
 
-  Parser_state parser_state(thd, thd->query, thd->query_length);
+  Parser_state parser_state(thd, thd->query(), thd->query_length());
   parser_state.m_lip.stmt_prepare_mode= TRUE;
   lex_start(thd);
 
@@ -3121,7 +3124,7 @@ bool Prepared_statement::prepare(const c
       the general log.
     */
     if (thd->spcont == NULL)
-      general_log_write(thd, COM_STMT_PREPARE, query, query_length);
+      general_log_write(thd, COM_STMT_PREPARE, query(), query_length());
   }
   DBUG_RETURN(error);
 }
@@ -3312,7 +3315,7 @@ Prepared_statement::reprepare()
     return TRUE;
 
   error= ((name.str && copy.set_name(&name)) ||
-          copy.prepare(query, query_length) ||
+          copy.prepare(query(), query_length()) ||
           validate_metadata(&copy));
 
   if (cur_db_changed)
@@ -3550,8 +3553,7 @@ bool Prepared_statement::execute(String 
     to point at it even after we restore from backup. This is ok, as
     expanded query was allocated in thd->mem_root.
   */
-  stmt_backup.query= thd->query;
-  stmt_backup.query_length= thd->query_length;
+  stmt_backup.set_query_inner(thd->query(), thd->query_length());
 
   /*
     At first execution of prepared statement we may perform logical
@@ -3576,8 +3578,8 @@ bool Prepared_statement::execute(String 
       Note that multi-statements cannot exist here (they are not supported in
       prepared statements).
     */
-    if (query_cache_send_result_to_client(thd, thd->query,
-                                          thd->query_length) <= 0)
+    if (query_cache_send_result_to_client(thd, thd->query(),
+                                          thd->query_length()) <= 0)
     {
       error= mysql_execute_command(thd);
     }
@@ -3622,7 +3624,7 @@ bool Prepared_statement::execute(String 
     the general log.
   */
   if (error == 0 && thd->spcont == NULL)
-    general_log_write(thd, COM_STMT_EXECUTE, thd->query, thd->query_length);
+    general_log_write(thd, COM_STMT_EXECUTE, thd->query(), thd->query_length());
 
 error:
   flags&= ~ (uint) IS_IN_USE;

=== modified file 'sql/sql_rename.cc'
--- a/sql/sql_rename.cc	2009-06-19 08:24:43 +0000
+++ b/sql/sql_rename.cc	2009-10-16 10:29:42 +0000
@@ -177,7 +177,7 @@ bool mysql_rename_tables(THD *thd, TABLE
   /* Lets hope this doesn't fail as the result will be messy */ 
   if (!silent && !error)
   {
-    write_bin_log(thd, TRUE, thd->query, thd->query_length);
+    write_bin_log(thd, TRUE, thd->query(), thd->query_length());
     my_ok(thd);
   }
 

=== modified file 'sql/sql_repl.cc'
--- a/sql/sql_repl.cc	2009-09-07 20:50:10 +0000
+++ b/sql/sql_repl.cc	2009-11-10 15:15:12 +0000
@@ -623,7 +623,7 @@ impossible position";
       */
       {
 	log.error=0;
-	bool read_packet = 0, fatal_error = 0;
+	bool read_packet = 0;
 
 #ifndef DBUG_OFF
 	if (max_binlog_dump_events && !left_events--)
@@ -645,7 +645,7 @@ impossible position";
 	*/
 
 	pthread_mutex_lock(log_lock);
-	switch (Log_event::read_log_event(&log, packet, (pthread_mutex_t*)0)) {
+	switch (error= Log_event::read_log_event(&log, packet, (pthread_mutex_t*) 0)) {
 	case 0:
 	  /* we read successfully, so we'll need to send it to the slave */
 	  pthread_mutex_unlock(log_lock);
@@ -671,8 +671,8 @@ impossible position";
 
 	default:
 	  pthread_mutex_unlock(log_lock);
-	  fatal_error = 1;
-	  break;
+          test_for_non_eof_log_read_errors(error, &errmsg);
+          goto err;
 	}
 
 	if (read_packet)
@@ -701,12 +701,6 @@ impossible position";
 	  */
 	}
 
-	if (fatal_error)
-	{
-	  errmsg = "error reading log entry";
-          my_errno= ER_MASTER_FATAL_ERROR_READING_BINLOG;
-	  goto err;
-	}
 	log.error=0;
       }
     }

=== modified file 'sql/sql_select.cc'
--- a/sql/sql_select.cc	2009-11-06 17:22:32 +0000
+++ b/sql/sql_select.cc	2009-11-10 15:15:12 +0000
@@ -159,6 +159,7 @@ static int join_read_const_table(JOIN_TA
 static int join_read_system(JOIN_TAB *tab);
 static int join_read_const(JOIN_TAB *tab);
 static int join_read_key(JOIN_TAB *tab);
+static void join_read_key_unlock_row(st_join_table *tab);
 static int join_read_always_key(JOIN_TAB *tab);
 static int join_read_last_key(JOIN_TAB *tab);
 static int join_no_more_records(READ_RECORD *info);
@@ -643,6 +644,18 @@ JOIN::prepare(Item ***rref_pointer_array
                  MYF(0));                       /* purecov: inspected */
       goto err;					/* purecov: inspected */
     }
+    if (thd->lex->derived_tables)
+    {
+      my_error(ER_WRONG_USAGE, MYF(0), "PROCEDURE", 
+               thd->lex->derived_tables & DERIVED_VIEW ?
+               "view" : "subquery"); 
+      goto err;
+    }
+    if (thd->lex->sql_command != SQLCOM_SELECT)
+    {
+      my_error(ER_WRONG_USAGE, MYF(0), "PROCEDURE", "non-SELECT");
+      goto err;
+    }
   }
 
   if (!procedure && result && result->prepare(fields_list, unit_arg))
@@ -654,8 +667,11 @@ JOIN::prepare(Item ***rref_pointer_array
   this->group= group_list != 0;
   unit= unit_arg;
 
+  if (tmp_table_param.sum_func_count && !group_list)
+    implicit_grouping= TRUE;
+
 #ifdef RESTRICTED_GROUP
-  if (sum_func_count && !group_list && (func_count || field_count))
+  if (implicit_grouping)
   {
     my_message(ER_WRONG_SUM_SELECT,ER(ER_WRONG_SUM_SELECT),MYF(0));
     goto err;
@@ -891,15 +907,23 @@ JOIN::optimize()
   }
 #endif
 
-  /* Optimize count(*), min() and max() */
-  if (tables_list && tmp_table_param.sum_func_count && ! group_list)
+  /* 
+     Try to optimize count(*), min() and max() to const fields if
+     there is implicit grouping (aggregate functions but no
+     group_list). In this case, the result set shall only contain one
+     row. 
+  */
+  if (tables_list && implicit_grouping)
   {
     int res;
     /*
       opt_sum_query() returns HA_ERR_KEY_NOT_FOUND if no rows match
       to the WHERE conditions,
-      or 1 if all items were resolved,
+      or 1 if all items were resolved (optimized away),
       or 0, or an error number HA_ERR_...
+
+      If all items were resolved by opt_sum_query, there is no need to
+      open any tables.
     */
     if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
     {
@@ -968,6 +992,12 @@ JOIN::optimize()
     DBUG_RETURN(1);
   }
 
+  if (select_lex->olap == ROLLUP_TYPE && rollup_process_const_fields())
+  {
+    DBUG_PRINT("error", ("Error: rollup_process_fields() failed"));
+    DBUG_RETURN(1);
+  }
+
   /* Remove distinct if only const tables */
   select_distinct= select_distinct && (const_tables != tables);
   thd_proc_info(thd, "preparing");
@@ -1098,7 +1128,7 @@ JOIN::optimize()
        join_tab[const_tables].select->quick->get_type() != 
        QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX))
   {
-    if (group_list &&
+    if (group_list && rollup.state == ROLLUP::STATE_NONE &&
        list_contains_unique_index(join_tab[const_tables].table,
                                  find_field_in_order_list,
                                  (void *) group_list))
@@ -1142,7 +1172,8 @@ JOIN::optimize()
     if (! hidden_group_fields && rollup.state == ROLLUP::STATE_NONE)
       select_distinct=0;
   }
-  else if (select_distinct && tables - const_tables == 1)
+  else if (select_distinct && tables - const_tables == 1 &&
+           rollup.state == ROLLUP::STATE_NONE)
   {
     /*
       We are only using one table. In this case we change DISTINCT to a
@@ -1241,13 +1272,22 @@ JOIN::optimize()
       (!group_list && tmp_table_param.sum_func_count))
     order=0;
 
-  // Can't use sort on head table if using row cache
+  // Can't use sort on head table if using join buffering
   if (full_join)
   {
-    if (group_list)
-      simple_group=0;
-    if (order)
-      simple_order=0;
+    TABLE *stable= (sort_by_table == (TABLE *) 1 ? 
+      join_tab[const_tables].table : sort_by_table);
+    /* 
+      FORCE INDEX FOR ORDER BY can be used to prevent join buffering when
+      sorting on the first table.
+    */
+    if (!stable || !stable->force_index_order)
+    {
+      if (group_list)
+        simple_group= 0;
+      if (order)
+        simple_order= 0;
+    }
   }
 
   /*
@@ -1533,12 +1573,8 @@ JOIN::optimize()
       }
     }
 
-    /* 
-      If this join belongs to an uncacheable subquery save 
-      the original join 
-    */
-    if (select_lex->uncacheable && !is_top_level_join() &&
-        init_save_join_tab())
+    /* If this join belongs to an uncacheable query save the original join */
+    if (select_lex->uncacheable && init_save_join_tab())
       DBUG_RETURN(-1);                         /* purecov: inspected */
   }
 
@@ -2039,7 +2075,8 @@ JOIN::exec()
     count_field_types(select_lex, &curr_join->tmp_table_param, 
                       *curr_all_fields, 0);
   
-  if (curr_join->group || curr_join->tmp_table_param.sum_func_count ||
+  if (curr_join->group || curr_join->implicit_grouping ||
+      curr_join->tmp_table_param.sum_func_count ||
       (procedure && (procedure->flags & PROC_GROUP)))
   {
     if (make_group_fields(this, curr_join))
@@ -2274,7 +2311,7 @@ JOIN::destroy()
 	tab->cleanup();
     }
     tmp_join->tmp_join= 0;
-    tmp_table_param.copy_field=0;
+    tmp_table_param.copy_field= 0;
     DBUG_RETURN(tmp_join->destroy());
   }
   cond_equal= 0;
@@ -3379,12 +3416,12 @@ add_key_equal_fields(KEY_FIELD **key_fie
      @retval FALSE  it's something else
 */
 
-inline static bool
+static bool
 is_local_field (Item *field)
 {
-  field= field->real_item();
-  return field->type() == Item::FIELD_ITEM && 
-    !((Item_field *)field)->depended_from;
+  return field->real_item()->type() == Item::FIELD_ITEM
+    && !(field->used_tables() & OUTER_REF_TABLE_BIT)
+    && !((Item_field *)field->real_item())->depended_from;
 }
 
 
@@ -3629,7 +3666,7 @@ add_key_part(DYNAMIC_ARRAY *keyuse_array
     {
       if (!(form->keys_in_use_for_query.is_set(key)))
 	continue;
-      if (form->key_info[key].flags & HA_FULLTEXT)
+      if (form->key_info[key].flags & (HA_FULLTEXT | HA_SPATIAL))
 	continue;    // ToDo: ft-keys in non-ft queries.   SerG
 
       uint key_parts= (uint) form->key_info[key].key_parts;
@@ -5677,7 +5714,9 @@ static bool create_ref_for_key(JOIN *joi
   }
   j->ref.key_buff2=j->ref.key_buff+ALIGN_SIZE(length);
   j->ref.key_err=1;
+  j->ref.has_record= FALSE;
   j->ref.null_rejecting= 0;
+  j->ref.use_count= 0;
   keyuse=org_keyuse;
 
   store_key **ref_key= j->ref.key_copy;
@@ -6511,6 +6550,20 @@ make_join_select(JOIN *join,SQL_SELECT *
   DBUG_RETURN(0);
 }
 
+
+/**
+  The default implementation of unlock-row method of READ_RECORD,
+  used in all access methods.
+*/
+
+void rr_unlock_row(st_join_table *tab)
+{
+  READ_RECORD *info= &tab->read_record;
+  info->file->unlock_row();
+}
+
+
+
 static void
 make_join_readinfo(JOIN *join, ulonglong options)
 {
@@ -6526,6 +6579,7 @@ make_join_readinfo(JOIN *join, ulonglong
     TABLE *table=tab->table;
     tab->read_record.table= table;
     tab->read_record.file=table->file;
+    tab->read_record.unlock_row= rr_unlock_row;
     tab->next_select=sub_select;		/* normal select */
 
     /*
@@ -6571,6 +6625,7 @@ make_join_readinfo(JOIN *join, ulonglong
       delete tab->quick;
       tab->quick=0;
       tab->read_first_record= join_read_key;
+      tab->read_record.unlock_row= join_read_key_unlock_row;
       tab->read_record.read_record= join_no_more_records;
       if (table->covering_keys.is_set(tab->ref.key) &&
 	  !table->no_keyread)
@@ -9046,7 +9101,10 @@ static void restore_prev_nj_state(JOIN_T
       join->cur_embedding_map&= ~last_emb->nested_join->nj_map;
     else if (last_emb->nested_join->n_tables-1 ==
              last_emb->nested_join->counter) 
+    {
       join->cur_embedding_map|= last_emb->nested_join->nj_map;
+      break;
+    }
     else
       break;
     last_emb= last_emb->embedding;
@@ -9493,8 +9551,47 @@ static Field *create_tmp_field_from_item
     new_field->set_derivation(item->collation.derivation);
     break;
   case DECIMAL_RESULT:
-    new_field= Field_new_decimal::new_decimal_field(item);
+  {
+    uint8 dec= item->decimals;
+    uint8 intg= ((Item_decimal *) item)->decimal_precision() - dec;
+    uint32 len= item->max_length;
+
+    /*
+      Trying to put too many digits overall in a DECIMAL(prec,dec)
+      will always throw a warning. We must limit dec to
+      DECIMAL_MAX_SCALE however to prevent an assert() later.
+    */
+
+    if (dec > 0)
+    {
+      signed int overflow;
+
+      dec= min(dec, DECIMAL_MAX_SCALE);
+
+      /*
+        If the value still overflows the field with the corrected dec,
+        we'll throw out decimals rather than integers. This is still
+        bad and of course throws a truncation warning.
+        +1: for decimal point
+      */
+
+      const int required_length=
+        my_decimal_precision_to_length(intg + dec, dec,
+                                                     item->unsigned_flag);
+
+      overflow= required_length - len;
+
+      if (overflow > 0)
+        dec= max(0, dec - overflow);            // too long, discard fract
+      else
+        /* Corrected value fits. */
+        len= required_length;
+    }
+
+    new_field= new Field_new_decimal(len, maybe_null, item->name,
+                                     dec, item->unsigned_flag);
     break;
+  }
   case ROW_RESULT:
   default:
     // This case should never be choosen
@@ -10303,6 +10400,7 @@ create_tmp_table(THD *thd,TMP_TABLE_PARA
     for (; cur_group ; cur_group= cur_group->next, key_part_info++)
     {
       Field *field=(*cur_group->item)->get_tmp_table_field();
+      DBUG_ASSERT(field->table == table);
       bool maybe_null=(*cur_group->item)->maybe_null;
       key_part_info->null_bit=0;
       key_part_info->field=  field;
@@ -11062,6 +11160,12 @@ Next_select_func setup_end_select_func(J
   }
   else
   {
+    /* 
+       Choose method for presenting result to user. Use end_send_group
+       if the query requires grouping (has a GROUP BY clause and/or one or
+       more aggregate functions). Use end_send if the query should not
+       be grouped.
+     */
     if ((join->sort_and_group ||
          (join->procedure && join->procedure->flags & PROC_GROUP)) &&
         !tmp_tbl->precomputed_group_by)
@@ -11430,6 +11534,7 @@ evaluate_join_record(JOIN *join, JOIN_TA
   bool not_used_in_distinct=join_tab->not_used_in_distinct;
   ha_rows found_records=join->found_records;
   COND *select_cond= join_tab->select_cond;
+  bool select_cond_result= TRUE;
 
   if (error > 0 || (join->thd->is_error()))     // Fatal error
     return NESTED_LOOP_ERROR;
@@ -11441,7 +11546,17 @@ evaluate_join_record(JOIN *join, JOIN_TA
     return NESTED_LOOP_KILLED;               /* purecov: inspected */
   }
   DBUG_PRINT("info", ("select cond 0x%lx", (ulong)select_cond));
-  if (!select_cond || select_cond->val_int())
+
+  if (select_cond)
+  {
+    select_cond_result= test(select_cond->val_int());
+
+    /* check for errors evaluating the condition */
+    if (join->thd->is_error())
+      return NESTED_LOOP_ERROR;
+  }
+
+  if (!select_cond || select_cond_result)
   {
     /*
       There is no select condition or the attached pushed down
@@ -11525,7 +11640,7 @@ evaluate_join_record(JOIN *join, JOIN_TA
         return NESTED_LOOP_NO_MORE_ROWS;
     }
     else
-      join_tab->read_record.file->unlock_row();
+      join_tab->read_record.unlock_row(join_tab);
   }
   else
   {
@@ -11535,7 +11650,7 @@ evaluate_join_record(JOIN *join, JOIN_TA
     */
     join->examined_rows++;
     join->thd->row_count++;
-    join_tab->read_record.file->unlock_row();
+    join_tab->read_record.unlock_row(join_tab);
   }
   return NESTED_LOOP_OK;
 }
@@ -11915,18 +12030,55 @@ join_read_key(JOIN_TAB *tab)
       table->status=STATUS_NOT_FOUND;
       return -1;
     }
+    /*
+      Moving away from the current record. Unlock the row
+      in the handler if it did not match the partial WHERE.
+    */
+    if (tab->ref.has_record && tab->ref.use_count == 0)
+    {
+      tab->read_record.file->unlock_row();
+      tab->ref.has_record= FALSE;
+    }
     error=table->file->index_read_map(table->record[0],