← Back to team overview

maria-developers team mailing list archive

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

 

#At lp:maria based on revid:psergey@xxxxxxxxxxxx-20091227165146-ij7tcujhkaubuizu

 2779 Michael Widenius	2010-01-15 [merge]
      Autmatic merge with my 5.1 tree
      removed:
        mysql-test/r/have_big5.require
        mysql-test/r/have_cp1250_ch.require
        mysql-test/r/have_cp1251.require
        mysql-test/r/have_cp866.require
        mysql-test/r/have_cp932.require
        mysql-test/r/have_eucjpms.require
        mysql-test/r/have_euckr.require
        mysql-test/r/have_gb2312.require
        mysql-test/r/have_gbk.require
        mysql-test/r/have_koi8r.require
        mysql-test/r/have_latin2_ch.require
        mysql-test/r/have_sjis.require
        mysql-test/r/have_tis620.require
        mysql-test/r/have_ucs2.require
        mysql-test/r/have_ujis.require
        mysql-test/r/have_utf8.require
      added:
        BUILD/compile-bintar
        BUILD/util.sh
        mysql-test/extra/rpl_tests/rpl_not_null.test
        mysql-test/include/have_collation.inc
        mysql-test/r/bug47671.result
        mysql-test/r/create-uca.result
        mysql-test/r/innodb_utf8.result
        mysql-test/r/udf_query_cache.result
        mysql-test/std_data/bug47012.ARM
        mysql-test/std_data/bug47012.ARZ
        mysql-test/std_data/bug47012.frm
        mysql-test/suite/innodb/r/innodb_bug46676.result
        mysql-test/suite/innodb/r/innodb_bug47167.result
        mysql-test/suite/innodb/t/innodb_bug46676.test
        mysql-test/suite/innodb/t/innodb_bug47167.test
        mysql-test/suite/rpl/r/rpl_loaddata_symlink.result
        mysql-test/suite/rpl/r/rpl_nondeterministic_functions.result
        mysql-test/suite/rpl/r/rpl_not_null_innodb.result
        mysql-test/suite/rpl/r/rpl_not_null_myisam.result
        mysql-test/suite/rpl/r/rpl_row_trunc_temp.result
        mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.opt
        mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.sh
        mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.opt
        mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.sh
        mysql-test/suite/rpl/t/rpl_loaddata_symlink.test
        mysql-test/suite/rpl/t/rpl_nondeterministic_functions.test
        mysql-test/suite/rpl/t/rpl_not_null_innodb.test
        mysql-test/suite/rpl/t/rpl_not_null_myisam.test
        mysql-test/suite/rpl/t/rpl_row_trunc_temp.test
        mysql-test/t/bug47671-master.opt
        mysql-test/t/bug47671.test
        mysql-test/t/create-uca.test
        mysql-test/t/innodb_utf8.test
        mysql-test/t/udf_query_cache-master.opt
        mysql-test/t/udf_query_cache.test
      renamed:
        mysql-test/suite/pbxt/t/load_unique_error1.inc => mysql-test/std_data/pbxt_load_unique_error1.inc
      modified:
        .bzrignore
        BUILD/Makefile.am
        BUILD/SETUP.sh
        BUILD/compile-solaris-amd64-debug-forte*
        BUILD/compile-solaris-x86-32*
        BUILD/compile-solaris-x86-32-debug*
        BUILD/compile-solaris-x86-32-debug-forte*
        BUILD/compile-solaris-x86-forte-32*
        Makefile.am
        client/mysql.cc
        client/mysqlbinlog.cc
        client/mysqltest.cc
        config/ac-macros/plugins.m4
        configure.in
        extra/comp_err.c
        extra/libevent/evbuffer.c
        extra/libevent/select.c
        include/my_pthread.h
        include/mysql.h
        include/mysql.h.pp
        include/violite.h
        libmysql/libmysql.c
        libmysql/libmysql.def
        libmysqld/libmysqld.def
        mysql-test/collections/default.experimental
        mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test
        mysql-test/extra/rpl_tests/rpl_row_tabledefs.test
        mysql-test/extra/rpl_tests/rpl_stm_000001.test
        mysql-test/include/have_big5.inc
        mysql-test/include/have_cp1250_ch.inc
        mysql-test/include/have_cp1251.inc
        mysql-test/include/have_cp866.inc
        mysql-test/include/have_cp932.inc
        mysql-test/include/have_eucjpms.inc
        mysql-test/include/have_euckr.inc
        mysql-test/include/have_gb2312.inc
        mysql-test/include/have_gbk.inc
        mysql-test/include/have_koi8r.inc
        mysql-test/include/have_latin2_ch.inc
        mysql-test/include/have_sjis.inc
        mysql-test/include/have_tis620.inc
        mysql-test/include/have_ucs2.inc
        mysql-test/include/have_ujis.inc
        mysql-test/include/have_utf8.inc
        mysql-test/include/mtr_warnings.sql
        mysql-test/lib/mtr_cases.pm
        mysql-test/mysql-test-run.pl
        mysql-test/r/archive.result
        mysql-test/r/create.result
        mysql-test/r/ctype_utf8.result
        mysql-test/r/delayed.result
        mysql-test/r/delete.result
        mysql-test/r/fulltext.result
        mysql-test/r/func_group.result
        mysql-test/r/func_misc.result
        mysql-test/r/grant2.result
        mysql-test/r/group_min_max.result
        mysql-test/r/innodb-autoinc.result
        mysql-test/r/innodb.result
        mysql-test/r/innodb_lock_wait_timeout_1.result
        mysql-test/r/innodb_mysql.result
        mysql-test/r/mysql.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/query_cache.result
        mysql-test/r/query_cache_notembedded.result
        mysql-test/r/range.result
        mysql-test/r/select.result
        mysql-test/r/show_check.result
        mysql-test/r/sp-destruct.result
        mysql-test/r/sp-security.result
        mysql-test/r/sp.result
        mysql-test/r/sp_notembedded.result
        mysql-test/r/trigger.result
        mysql-test/r/trigger_notembedded.result
        mysql-test/r/type_newdecimal.result
        mysql-test/r/type_year.result
        mysql-test/r/udf.result
        mysql-test/r/variables.result
        mysql-test/suite/binlog/r/binlog_stm_mix_innodb_myisam.result
        mysql-test/suite/binlog/r/binlog_stm_row.result
        mysql-test/suite/binlog/r/binlog_unsafe.result
        mysql-test/suite/binlog/t/binlog_killed.test
        mysql-test/suite/binlog/t/binlog_stm_mix_innodb_myisam.test
        mysql-test/suite/binlog/t/binlog_stm_row.test
        mysql-test/suite/binlog/t/binlog_unsafe.test
        mysql-test/suite/funcs_1/datadict/processlist_val.inc
        mysql-test/suite/innodb/r/innodb-index.result
        mysql-test/suite/innodb/t/innodb-consistent-master.opt
        mysql-test/suite/innodb/t/innodb-index.test
        mysql-test/suite/maria/t/maria2-master.opt
        mysql-test/suite/parts/t/partition_alter1_2_innodb.test
        mysql-test/suite/parts/t/partition_alter2_1_innodb.test
        mysql-test/suite/parts/t/partition_alter2_2_innodb.test
        mysql-test/suite/parts/t/partition_alter4_innodb.test
        mysql-test/suite/pbxt/r/lock_multi.result
        mysql-test/suite/pbxt/r/pbxt_bugs.result
        mysql-test/suite/pbxt/t/lock_multi.test
        mysql-test/suite/pbxt/t/pbxt_bugs.test
        mysql-test/suite/pbxt/t/pbxt_locking.test
        mysql-test/suite/pbxt/t/pbxt_transactions.test
        mysql-test/suite/pbxt/t/ps_1general.test
        mysql-test/suite/rpl/r/rpl_err_ignoredtable.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_lock.result
        mysql-test/suite/rpl/r/rpl_row_create_table.result
        mysql-test/suite/rpl/r/rpl_row_tabledefs_2myisam.result
        mysql-test/suite/rpl/r/rpl_row_tabledefs_3innodb.result
        mysql-test/suite/rpl/r/rpl_stm_000001.result
        mysql-test/suite/rpl/r/rpl_temporary.result
        mysql-test/suite/rpl/r/rpl_trigger.result
        mysql-test/suite/rpl/t/disabled.def
        mysql-test/suite/rpl/t/rpl_err_ignoredtable.test
        mysql-test/suite/rpl/t/rpl_get_lock.test
        mysql-test/suite/rpl/t/rpl_ignore_table.test
        mysql-test/suite/rpl/t/rpl_row_create_table.test
        mysql-test/suite/rpl/t/rpl_temporary.test
        mysql-test/suite/rpl/t/rpl_trigger.test
        mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result
        mysql-test/t/archive.test
        mysql-test/t/create.test
        mysql-test/t/ctype_utf8.test
        mysql-test/t/ddl_i18n_koi8r.test
        mysql-test/t/ddl_i18n_utf8.test
        mysql-test/t/delayed.test
        mysql-test/t/delete.test
        mysql-test/t/disabled.def
        mysql-test/t/fulltext.test
        mysql-test/t/fulltext2.test
        mysql-test/t/func_group.test
        mysql-test/t/func_misc.test
        mysql-test/t/grant2.test
        mysql-test/t/group_min_max.test
        mysql-test/t/innodb-autoinc.test
        mysql-test/t/innodb.test
        mysql-test/t/innodb_lock_wait_timeout_1.test
        mysql-test/t/innodb_mysql.test
        mysql-test/t/mysql.test
        mysql-test/t/mysqltest.test
        mysql-test/t/olap.test
        mysql-test/t/order_by.test
        mysql-test/t/partition.test
        mysql-test/t/query_cache.test
        mysql-test/t/query_cache_notembedded.test
        mysql-test/t/query_cache_ps_no_prot.test
        mysql-test/t/query_cache_ps_ps_prot.test
        mysql-test/t/range.test
        mysql-test/t/select.test
        mysql-test/t/show_check.test
        mysql-test/t/sp-destruct.test
        mysql-test/t/sp-security.test
        mysql-test/t/sp.test
        mysql-test/t/sp_notembedded.test
        mysql-test/t/trigger.test
        mysql-test/t/trigger_notembedded.test
        mysql-test/t/type_newdecimal.test
        mysql-test/t/type_year.test
        mysql-test/t/udf.test
        mysql-test/t/variables.test
        mysys/my_getopt.c
        mysys/my_sync.c
        mysys/my_uuid.c
        scripts/make_win_bin_dist
        scripts/mysql_secure_installation.pl.in
        scripts/mysql_secure_installation.sh
        scripts/mysqlbug.sh
        sql/event_db_repository.cc
        sql/field.cc
        sql/field.h
        sql/ha_ndbcluster.cc
        sql/handler.h
        sql/item.cc
        sql/item.h
        sql/item_cmpfunc.cc
        sql/item_cmpfunc.h
        sql/item_create.cc
        sql/item_func.cc
        sql/item_func.h
        sql/item_geofunc.cc
        sql/item_strfunc.cc
        sql/item_subselect.cc
        sql/item_subselect.h
        sql/item_sum.cc
        sql/item_sum.h
        sql/item_timefunc.cc
        sql/item_xmlfunc.cc
        sql/log.cc
        sql/log_event.cc
        sql/log_event.h
        sql/mysqld.cc
        sql/opt_range.cc
        sql/repl_failsafe.cc
        sql/rpl_record.cc
        sql/rpl_record.h
        sql/rpl_rli.cc
        sql/rpl_tblmap.cc
        sql/set_var.cc
        sql/sp.cc
        sql/sp.h
        sql/sp_cache.cc
        sql/sp_head.cc
        sql/sp_head.h
        sql/sp_rcontext.cc
        sql/sql_acl.cc
        sql/sql_acl.h
        sql/sql_base.cc
        sql/sql_cache.cc
        sql/sql_cache.h
        sql/sql_class.cc
        sql/sql_delete.cc
        sql/sql_insert.cc
        sql/sql_load.cc
        sql/sql_parse.cc
        sql/sql_partition.cc
        sql/sql_plugin.cc
        sql/sql_select.cc
        sql/sql_show.cc
        sql/sql_table.cc
        sql/sql_yacc.yy
        sql/table.cc
        sql/table.h
        storage/archive/CMakeLists.txt*
        storage/archive/azio.c
        storage/archive/azlib.h
        storage/archive/ha_archive.cc
        storage/federated/CMakeLists.txt*
        storage/innobase/btr/btr0btr.c
        storage/innobase/data/data0type.c
        storage/innobase/handler/ha_innodb.cc
        storage/innobase/include/ha_prototypes.h
        storage/innobase/include/mach0data.h
        storage/innobase/include/mach0data.ic
        storage/innobase/include/os0file.h
        storage/innobase/include/trx0trx.h
        storage/innobase/lock/lock0lock.c
        storage/innobase/os/os0file.c
        storage/innobase/row/row0sel.c
        storage/innobase/trx/trx0trx.c
        storage/innobase/ut/ut0ut.c
        storage/innodb_plugin/CMakeLists.txt
        storage/innodb_plugin/ChangeLog
        storage/innodb_plugin/btr/btr0btr.c
        storage/innodb_plugin/btr/btr0sea.c
        storage/innodb_plugin/buf/buf0buf.c
        storage/innodb_plugin/data/data0type.c
        storage/innodb_plugin/dict/dict0dict.c
        storage/innodb_plugin/fil/fil0fil.c
        storage/innodb_plugin/handler/ha_innodb.cc
        storage/innodb_plugin/handler/ha_innodb.h
        storage/innodb_plugin/handler/handler0alter.cc
        storage/innodb_plugin/ibuf/ibuf0ibuf.c
        storage/innodb_plugin/include/btr0sea.h
        storage/innodb_plugin/include/db0err.h
        storage/innodb_plugin/include/dict0dict.h
        storage/innodb_plugin/include/fil0fil.h
        storage/innodb_plugin/include/ha_prototypes.h
        storage/innodb_plugin/include/ibuf0ibuf.h
        storage/innodb_plugin/include/lock0lock.h
        storage/innodb_plugin/include/log0log.h
        storage/innodb_plugin/include/log0recv.h
        storage/innodb_plugin/include/mem0mem.h
        storage/innodb_plugin/include/mem0pool.h
        storage/innodb_plugin/include/os0file.h
        storage/innodb_plugin/include/pars0pars.h
        storage/innodb_plugin/include/srv0srv.h
        storage/innodb_plugin/include/thr0loc.h
        storage/innodb_plugin/include/trx0i_s.h
        storage/innodb_plugin/include/trx0purge.h
        storage/innodb_plugin/include/trx0rseg.h
        storage/innodb_plugin/include/trx0sys.h
        storage/innodb_plugin/include/trx0trx.h
        storage/innodb_plugin/include/trx0undo.h
        storage/innodb_plugin/include/univ.i
        storage/innodb_plugin/include/usr0sess.h
        storage/innodb_plugin/lock/lock0lock.c
        storage/innodb_plugin/log/log0log.c
        storage/innodb_plugin/log/log0recv.c
        storage/innodb_plugin/mem/mem0dbg.c
        storage/innodb_plugin/mem/mem0pool.c
        storage/innodb_plugin/os/os0file.c
        storage/innodb_plugin/os/os0sync.c
        storage/innodb_plugin/os/os0thread.c
        storage/innodb_plugin/pars/lexyy.c
        storage/innodb_plugin/pars/pars0lex.l
        storage/innodb_plugin/que/que0que.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/sync0arr.c
        storage/innodb_plugin/sync/sync0sync.c
        storage/innodb_plugin/thr/thr0loc.c
        storage/innodb_plugin/trx/trx0i_s.c
        storage/innodb_plugin/trx/trx0purge.c
        storage/innodb_plugin/trx/trx0rseg.c
        storage/innodb_plugin/trx/trx0sys.c
        storage/innodb_plugin/trx/trx0trx.c
        storage/innodb_plugin/trx/trx0undo.c
        storage/innodb_plugin/usr/usr0sess.c
        storage/innodb_plugin/ut/ut0mem.c
        storage/maria/ma_blockrec.c
        storage/maria/ma_check.c
        storage/maria/ma_create.c
        storage/maria/ma_loghandler.c
        storage/maria/ma_test3.c
        storage/myisam/ft_boolean_search.c
        storage/myisam/mi_check.c
        storage/myisam/mi_create.c
        storage/myisam/mi_test3.c
        storage/ndb/plug.in
        storage/pbxt/ChangeLog
        storage/pbxt/plug.in
        storage/pbxt/src/Makefile.am
        storage/pbxt/src/discover_xt.cc
        storage/pbxt/src/ha_pbxt.cc
        storage/pbxt/src/restart_xt.cc
        storage/pbxt/src/strutil_xt.cc
        storage/pbxt/src/table_xt.cc
        storage/pbxt/src/thread_xt.cc
        storage/pbxt/src/thread_xt.h
        storage/pbxt/src/trace_xt.cc
        storage/xtradb/handler/ha_innodb.cc
        storage/xtradb/srv/srv0srv.c
        support-files/compiler_warnings.supp
        tests/mysql_client_test.c
        vio/vio.c
        vio/viosocket.c

=== modified file '.bzrignore'
--- a/.bzrignore	2009-12-03 11:34:11 +0000
+++ b/.bzrignore	2009-12-22 13:50:20 +0000
@@ -666,6 +666,9 @@ libmysqld/time.cc
 libmysqld/tztime.cc
 libmysqld/uniques.cc
 libmysqld/unireg.cc
+libmysqld/discover_xt.cc
+libmysqld/ha_pbxt.cc
+libmysqld/myxt_xt.cc
 libmysqltest/*.ds?
 libmysqltest/*.vcproj
 libmysqltest/mytest.c

=== modified file 'BUILD/Makefile.am'
--- a/BUILD/Makefile.am	2009-08-29 19:04:46 +0000
+++ b/BUILD/Makefile.am	2010-01-07 13:03:54 +0000
@@ -34,6 +34,7 @@ EXTRA_DIST =		FINISH.sh \
 			compile-amd64-max \
 			compile-amd64-max-sci \
 			compile-amd64-valgrind-max \
+			compile-bintar \
 			compile-darwin-mwcc \
 			compile-dist \
 			compile-hpux11-parisc2-aCC \
@@ -80,7 +81,8 @@ EXTRA_DIST =		FINISH.sh \
 			compile-solaris-x86-32 \
 			compile-solaris-x86-32-debug \
 			compile-solaris-x86-32-debug-forte \
-			compile-solaris-x86-forte-32
+			compile-solaris-x86-forte-32 \
+			util.sh
 
 # Don't update the files from bitkeeper
 %::SCCS/s.%

=== modified file 'BUILD/SETUP.sh'
--- a/BUILD/SETUP.sh	2009-12-06 17:34:54 +0000
+++ b/BUILD/SETUP.sh	2010-01-07 12:02:18 +0000
@@ -86,15 +86,9 @@ set -e
 # 
 path=`dirname $0`
 . "$path/check-cpu"
+. "$path/util.sh"
 
-export AM_MAKEFLAGS
-# Default to a parallel build, but only if AM_MAKEFLAGS is not set.
-# (So buildbots can easily disable this behaviour if required.)
-if test -z "$AM_MAKEFLAGS"
-then
-  AM_MAKEFLAGS="-j 6"
-fi
-
+get_make_parallel_flag
 
 # SSL library to use.--with-ssl will select our bundled yaSSL
 # implementation of SSL. To use openSSl you will nee too point out

=== added file 'BUILD/compile-bintar'
--- a/BUILD/compile-bintar	1970-01-01 00:00:00 +0000
+++ b/BUILD/compile-bintar	2010-01-07 12:02:18 +0000
@@ -0,0 +1,81 @@
+#!/bin/bash
+#
+# MariaDB SQL server.
+# Copyright (C) 2010 Kristian Nielsen and 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
+# 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.
+
+
+# This script's purpose is to build the binary tarball packages for MariaDB
+# (currently only on Linux systems).
+#
+# Thus BUILD/compile-bintar from the appropriate source tarball will reproduce
+# such a release, provided the build environment (gcc version etc.) matches
+# (use scripts/make_binary_distribution after running this script to actually
+# create the binary tarball package).
+#
+# Note that packages are built from source tarballs not bzr checkouts.
+# Therefore, this script assumes autotools have already been run.
+#
+# We link libc dynamically, otherwise we get lots of problems loading
+# .so files at runtime (either system stuff like NSS, or server
+# plugins).
+#
+# We link libgcc statically (and avoid linking libstdc++ at all by
+# CXX=gcc), to avoid reduce nasty library version dependencies.
+
+test -f Makefile && make distclean
+
+path=`dirname $0`
+. $path/util.sh
+
+SYSTEM_TYPE="$(uname -o)"
+MACHINE_TYPE="$(uname -m)"
+
+# We cannot have a slash '/' in tarfile name.
+SYSTEM_TYPE="$(echo ${SYSTEM_TYPE} | sed -e 's/GNU\///')"
+
+# Get correct options for architecture into CPUOPT.
+get_cpuopt
+# Get correct -j option into AM_MAKEFLAGS
+get_make_parallel_flag
+
+# Use gcc rather than g++ to avoid linking libstdc++.so (which we don't need).
+COMP="gcc -static-libgcc"
+FLAGS="-O2 -fno-omit-frame-pointer -g -pipe -Wall $CPUOPT"
+
+# Don't press on in case of error.
+set -e
+
+CC="$COMP" CXX="$COMP" CFLAGS="$FLAGS" CXXFLAGS="$FLAGS" \
+	./configure \
+	--prefix=/usr/local/mysql \
+	--exec-prefix=/usr/local/mysql \
+	--libexecdir=/usr/local/mysql/bin \
+	--localstatedir=/usr/local/mysql/data \
+	\
+	--with-comment="(MariaDB - http://mariadb.com/)" \
+	--with-system-type="${SYSTEM_TYPE}" \
+	--with-machine-type="${MACHINE_TYPE}" \
+	\
+	--enable-shared --enable-static \
+	--with-client-ldflags=-static --with-mysqld-ldflags=-static \
+	--enable-thread-safe-client --enable-local-infile --with-big-tables \
+	--without-docs --with-extra-charsets=all \
+	--with-libwrap --with-ssl --with-readline --with-libevent --with-zlib-dir=bundled \
+	--with-partition --with-embedded-server \
+	--with-plugins=max-no-ndb \
+	--without-plugin-innodb_plugin
+
+make $AM_MAKEFLAGS

=== modified file 'BUILD/compile-solaris-amd64-debug-forte' (properties changed: -x to +x)
=== modified file 'BUILD/compile-solaris-x86-32' (properties changed: -x to +x)
=== modified file 'BUILD/compile-solaris-x86-32-debug' (properties changed: -x to +x)
=== modified file 'BUILD/compile-solaris-x86-32-debug-forte' (properties changed: -x to +x)
=== modified file 'BUILD/compile-solaris-x86-forte-32' (properties changed: -x to +x)
=== added file 'BUILD/util.sh'
--- a/BUILD/util.sh	1970-01-01 00:00:00 +0000
+++ b/BUILD/util.sh	2010-01-07 12:02:18 +0000
@@ -0,0 +1,40 @@
+# MariaDB SQL server.
+# Copyright (C) 2010 Kristian Nielsen and 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
+# 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.
+
+# Setting cpu options.
+get_cpuopt () {
+	case "$(gcc -dumpmachine)" in
+          x86_64-*)
+                # gcc barfs on -march=... on x64
+                CPUOPT="-m64 -mtune=generic"
+                ;;
+          *)
+                # we'd use i586 to not trip up mobile/lowpower devices
+                CPUOPT="-m32 -march=i586 -mtune=generic"
+                ;;
+	esac
+	return 0
+}
+
+# Default to a parallel build, but only if AM_MAKEFLAGS is not set.
+# (So buildbots can easily disable this behaviour if required.)
+get_make_parallel_flag () {
+        if test -z "$AM_MAKEFLAGS"
+        then
+                AM_MAKEFLAGS="-j 6"
+        fi
+	return 0
+}

=== modified file 'Makefile.am'
--- a/Makefile.am	2009-12-03 11:19:05 +0000
+++ b/Makefile.am	2010-01-15 15:27:55 +0000
@@ -208,10 +208,6 @@ 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 $(MTR_EXTRA_OPTIONS) --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 \

=== modified file 'client/mysql.cc'
--- a/client/mysql.cc	2009-12-03 11:34:11 +0000
+++ b/client/mysql.cc	2010-01-15 15:27:55 +0000
@@ -4356,7 +4356,7 @@ com_status(String *buffer __attribute__(
     Don't remove "limit 1",
     it is protection againts SQL_SELECT_LIMIT=0
   */
-  if (mysql_store_result_for_lazy(&result))
+  if (!mysql_store_result_for_lazy(&result))
   {
     MYSQL_ROW cur=mysql_fetch_row(result);
     if (cur)
@@ -4401,7 +4401,7 @@ com_status(String *buffer __attribute__(
     if (mysql_errno(&mysql) == CR_SERVER_GONE_ERROR)
       return 0;
   }
-  if (mysql_store_result_for_lazy(&result))
+  if (!mysql_store_result_for_lazy(&result))
   {
     MYSQL_ROW cur=mysql_fetch_row(result);
     if (cur)
@@ -4496,9 +4496,7 @@ server_version_string(MYSQL *con)
     */
 
     if (server_version == NULL)
-    {
-      server_version= strdup(mysql_get_server_info(con));
-    }
+      server_version= my_strdup(mysql_get_server_info(con), MYF(MY_WME));
   }
 
   return server_version ? server_version : "";

=== modified file 'client/mysqlbinlog.cc'
--- a/client/mysqlbinlog.cc	2009-12-03 11:19:05 +0000
+++ b/client/mysqlbinlog.cc	2010-01-09 09:04:51 +0000
@@ -1378,6 +1378,10 @@ static int parse_args(int *argc, char***
 */
 static Exit_status safe_connect()
 {
+  /* Close and old connections to MySQL */
+  if (mysql)
+    mysql_close(mysql);
+
   mysql= mysql_init(NULL);
 
   if (!mysql)

=== modified file 'client/mysqltest.cc'
--- a/client/mysqltest.cc	2009-12-03 11:19:05 +0000
+++ b/client/mysqltest.cc	2010-01-15 15:27:55 +0000
@@ -1267,6 +1267,7 @@ void abort_not_supported_test(const char
   DBUG_ENTER("abort_not_supported_test");
 
   /* Print include filestack */
+  fflush(stdout);
   fprintf(stderr, "The test '%s' is not supported by this installation\n",
           file_stack->file_name);
   fprintf(stderr, "Detected in file %s at line %d\n",
@@ -8098,7 +8099,10 @@ int main(int argc, char **argv)
         abort_flag= 1;
         break;
       case Q_SKIP:
-        abort_not_supported_test("%s", command->first_argument);
+        /* Eval the query, thus replacing all environment variables */
+        dynstr_set(&ds_res, 0);
+        do_eval(&ds_res, command->first_argument, command->end, FALSE);
+        abort_not_supported_test("%s",ds_res.str);
         break;
 
       case Q_RESULT:

=== modified file 'config/ac-macros/plugins.m4'
--- a/config/ac-macros/plugins.m4	2009-04-25 10:05:32 +0000
+++ b/config/ac-macros/plugins.m4	2009-12-22 10:33:20 +0000
@@ -267,7 +267,6 @@ dnl   we have to recompile these modules
 dnl   to compile server parts with the different #defines
 dnl   Normally it happens when we compile the embedded server
 dnl   Thus one should mark such files in his handler using this macro
-dnl    (currently only one such a file per plugin is supported)
 dnl
 dnl ---------------------------------------------------------------------------
 
@@ -463,11 +462,13 @@ dnl Although this is "pretty", it breaks
       mysql_plugin_defs="$mysql_plugin_defs, [builtin_]$2[_plugin]"
       [with_plugin_]$2=yes
       AC_MSG_RESULT([yes])
-      m4_ifdef([$11],[
-       condition_dependent_plugin_modules="$condition_dependent_plugin_modules m4_bregexp($11, [[^/]+$], [\&])"
-       condition_dependent_plugin_objects="$condition_dependent_plugin_objects m4_bregexp($11, [[^/]+\.], [\&o])"
-       condition_dependent_plugin_links="$condition_dependent_plugin_links $6/$11"
-       condition_dependent_plugin_includes="$condition_dependent_plugin_includes -I[\$(top_srcdir)]/$6/m4_bregexp($11, [^.+[/$]], [\&])"
+      m4_ifdef([$11], [
+        m4_foreach([plugin], [$11], [
+           condition_dependent_plugin_modules="$condition_dependent_plugin_modules m4_bregexp(plugin, [[^/]+$], [\&])"
+           condition_dependent_plugin_objects="$condition_dependent_plugin_objects m4_bregexp(plugin, [[^/]+\.], [\&o])"
+           condition_dependent_plugin_links="$condition_dependent_plugin_links $6/plugin"
+           condition_dependent_plugin_includes="$condition_dependent_plugin_includes -I[\$(top_srcdir)]/$6/m4_bregexp(plugin, [^.+[/$]], [\&])"
+        ])
       ])
     fi
   fi

=== modified file 'configure.in'
--- a/configure.in	2009-12-03 11:34:11 +0000
+++ b/configure.in	2010-01-15 15:27:55 +0000
@@ -9,15 +9,16 @@ AC_CANONICAL_SYSTEM
 # remember to also update version.c in ndb
 #
 # When changing major version number please also check switch statement
-# in mysqlbinlog.cc / check_master_version().
-#
-# When merging new MySQL releases, update the version number to match the
-# MySQL version number.
-#
-# Note: the following line must be parseable by win/configure.js:GetVersion()
-AM_INIT_AUTOMAKE(mysql, 5.1.41-MariaDB-beta)
+# in mysqlbinlog::check_master_version().
+AM_INIT_AUTOMAKE(mysql, 5.1.42-MariaDB-rc)
 AM_CONFIG_HEADER([include/config.h:config.h.in])
 
+# Request support for automake silent-rules if available.
+# Default to verbose output. One can use the configure-time
+# option --enable-silent-rules or make V=0 to activate
+# silent rules.
+m4_ifdef([AM_SILENT_RULES], [AM_SILENT_RULES([no])])
+
 PROTOCOL_VERSION=10
 DOT_FRM_VERSION=6
 # See the libtool docs for information on how to do shared lib versions.

=== modified file 'extra/comp_err.c'
--- a/extra/comp_err.c	2009-02-13 16:41:47 +0000
+++ b/extra/comp_err.c	2009-11-20 10:11:31 +0000
@@ -660,7 +660,7 @@ static ha_checksum checksum_format_speci
       case 'u':
       case 'x':
       case 's':
-        chksum= my_checksum(chksum, start, (uint) (p - start));
+        chksum= my_checksum(chksum, start, (uint) (p + 1 - start));
         start= 0; /* Not in format specifier anymore */
         break;
 
@@ -1030,8 +1030,10 @@ static char *parse_text_line(char *pos)
 {
   int i, nr;
   char *row= pos;
+  size_t len;
   DBUG_ENTER("parse_text_line");
 
+  len= strlen (pos);
   while (*pos)
   {
     if (*pos == '\\')
@@ -1039,11 +1041,11 @@ static char *parse_text_line(char *pos)
       switch (*++pos) {
       case '\\':
       case '"':
-	VOID(strmov(pos - 1, pos));
+	VOID(memmove (pos - 1, pos, len - (row - pos)));
 	break;
       case 'n':
 	pos[-1]= '\n';
-	VOID(strmov(pos, pos + 1));
+	VOID(memmove (pos, pos + 1, len - (row - pos)));
 	break;
       default:
 	if (*pos >= '0' && *pos < '8')
@@ -1053,10 +1055,10 @@ static char *parse_text_line(char *pos)
 	    nr= nr * 8 + (*(pos++) - '0');
 	  pos -= i;
 	  pos[-1]= nr;
-	  VOID(strmov(pos, pos + i));
+	  VOID(memmove (pos, pos + i, len - (row - pos)));
 	}
 	else if (*pos)
-	  VOID(strmov(pos - 1, pos));		/* Remove '\' */
+	  VOID(memmove (pos - 1, pos, len - (row - pos)));		/* Remove '\' */
       }
     }
     else

=== modified file 'extra/libevent/evbuffer.c'
--- a/extra/libevent/evbuffer.c	2009-03-12 22:27:35 +0000
+++ b/extra/libevent/evbuffer.c	2010-01-07 13:00:06 +0000
@@ -25,12 +25,12 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include <sys/types.h>
-
 #ifdef HAVE_CONFIG_H
 #include "config.h"
 #endif
 
+#include <sys/types.h>
+
 #ifdef HAVE_SYS_TIME_H
 #include <sys/time.h>
 #endif

=== modified file 'extra/libevent/select.c'
--- a/extra/libevent/select.c	2009-03-12 22:27:35 +0000
+++ b/extra/libevent/select.c	2010-01-06 21:27:53 +0000
@@ -266,7 +266,7 @@ select_add(void *arg, struct event *ev)
 	 * of the fd_sets for select(2)
 	 */
 	if (sop->event_fds < ev->ev_fd) {
-		int fdsz = sop->event_fdsz;
+		unsigned int fdsz = sop->event_fdsz;
 
 		if (fdsz < sizeof(fd_mask))
 			fdsz = sizeof(fd_mask);
@@ -275,7 +275,7 @@ select_add(void *arg, struct event *ev)
 		    (howmany(ev->ev_fd + 1, NFDBITS) * sizeof(fd_mask)))
 			fdsz *= 2;
 
-		if (fdsz != sop->event_fdsz) {
+		if (fdsz != (unsigned int) sop->event_fdsz) {
 			if (select_resize(sop, fdsz)) {
 				check_selectop(sop);
 				return (-1);

=== modified file 'include/my_pthread.h'
--- a/include/my_pthread.h	2009-06-30 12:01:29 +0000
+++ b/include/my_pthread.h	2010-01-14 16:51:00 +0000
@@ -543,9 +543,9 @@ void safe_mutex_free_deadlock_data(safe_
 #else
 #define my_pthread_mutex_init(A,B,C,D) pthread_mutex_init((A),(B))
 #define my_pthread_mutex_lock(A,B) pthread_mutex_lock(A)
-#define safe_mutex_assert_owner(mp)
-#define safe_mutex_assert_not_owner(mp)
-#define safe_mutex_free_deadlock_data(mp)
+#define safe_mutex_assert_owner(mp)    do {} while(0)
+#define safe_mutex_assert_not_owner(mp) do {} while(0)
+#define safe_mutex_free_deadlock_data(mp) do {} while(0)
 #endif /* SAFE_MUTEX */
 
 #if defined(MY_PTHREAD_FASTMUTEX) && !defined(SAFE_MUTEX)

=== modified file 'include/mysql.h'
--- a/include/mysql.h	2009-12-03 11:19:05 +0000
+++ b/include/mysql.h	2010-01-15 15:27:55 +0000
@@ -558,16 +558,6 @@ 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-12-03 11:19:05 +0000
+++ b/include/mysql.h.pp	2010-01-15 15:27:55 +0000
@@ -518,16 +518,6 @@ 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-12-03 11:19:05 +0000
+++ b/include/violite.h	2010-01-15 15:27:55 +0000
@@ -225,8 +225,8 @@ struct st_vio
 #endif /* HAVE_SMEM */
 #ifdef _WIN32
   OVERLAPPED pipe_overlapped;
-  DWORD read_timeout_millis;
-  DWORD write_timeout_millis;
+  DWORD read_timeout_ms;
+  DWORD write_timeout_ms;
 #endif
 };
 #endif /* vio_violite_h_ */

=== modified file 'libmysql/libmysql.c'
--- a/libmysql/libmysql.c	2009-12-03 11:34:11 +0000
+++ b/libmysql/libmysql.c	2010-01-15 15:27:55 +0000
@@ -1642,20 +1642,6 @@ 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-12-03 11:19:05 +0000
+++ b/libmysql/libmysql.def	2010-01-15 15:27:55 +0000
@@ -78,7 +78,6 @@ 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/libmysqld.def'
--- a/libmysqld/libmysqld.def	2009-12-03 11:19:05 +0000
+++ b/libmysqld/libmysqld.def	2010-01-15 15:27:55 +0000
@@ -50,7 +50,6 @@ 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/default.experimental'
--- a/mysql-test/collections/default.experimental	2009-10-26 12:33:03 +0000
+++ b/mysql-test/collections/default.experimental	2009-12-02 09:47:49 +0000
@@ -13,15 +13,13 @@ funcs_1.ndb*
 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_cross_version*                   # Bug#48340 2009-12-01 Daogang rpl_cross_version: Found warnings/errors in server log file!
+rpl.rpl_get_master_version_and_clock*    # Bug #49191 2009-12-01 Daogang rpl_get_master_version_and_clock failed on PB2: COM_REGISTER_SLAVE failed
 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

=== modified file 'mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test'
--- a/mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test	2009-08-28 14:13:27 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_extraSlave_Col.test	2009-10-22 00:21:50 +0000
@@ -407,37 +407,57 @@ sync_slave_with_master;
 ###########################################
 # Bug#22234, Bug#23907 Extra Slave Col is not 
 # erroring on extra col with no default values.
-########################################################
+###############################################################
+# Error reaction is up to sql_mode of the slave sql (bug#38173)
 #--echo *** Create t9 on slave  ***
-STOP SLAVE;
-RESET SLAVE;
-eval CREATE TABLE t9 (a INT KEY, b BLOB, c CHAR(5),
-                      d TIMESTAMP,
-                      e INT NOT NULL) ENGINE=$engine_type;
-
---echo *** Create t9 on Master ***
-connection master;
-eval CREATE TABLE t9 (a INT PRIMARY KEY, b BLOB, c CHAR(5)
+# Please, check BUG#47741 to see why you are not testing NDB.
+if (`SELECT $engine_type != 'NDB'`)
+{
+  STOP SLAVE;
+  RESET SLAVE;
+  eval CREATE TABLE t9 (a INT KEY, b BLOB, c CHAR(5),
+                        d TIMESTAMP,
+                        e INT NOT NULL,
+                        f text not null,
+                        g text,
+                        h blob not null,
+                        i blob) ENGINE=$engine_type;
+
+  --echo *** Create t9 on Master ***
+  connection master;
+  eval CREATE TABLE t9 (a INT PRIMARY KEY, b BLOB, c CHAR(5)
                        ) ENGINE=$engine_type;
-RESET MASTER;
+  RESET MASTER;
+
+  --echo *** Start Slave ***
+  connection slave;
+  START SLAVE;
+
+  --echo *** Master Data Insert ***
+  connection master;
+  set @b1 = 'b1b1b1b1';
+
+  set @b1 = concat(@b1,@b1);
+  INSERT INTO t9 () VALUES(1,@b1,'Kyle'),(2,@b1,'JOE'),(3,@b1,'QA');
+
+  # the test would stop slave if @@sql_mode for the sql thread
+  # was set to strict. Otherwise, as with this tests setup, 
+  # the implicit defaults will be inserted into fields even though
+  # they are declared without DEFAULT clause.
+
+  sync_slave_with_master;
+  select * from t9;
+
+  # todo: fix Bug #43992 slave sql thread can't tune own sql_mode ...
+  # and add/restore waiting for stop test
 
---echo *** Start Slave ***
-connection slave;
-START SLAVE;
-
---echo *** Master Data Insert ***
-connection master;
-set @b1 = 'b1b1b1b1';
-set @b1 = concat(@b1,@b1);
-INSERT INTO t9 () VALUES(1,@b1,'Kyle'),(2,@b1,'JOE'),(3,@b1,'QA');
-
-connection slave;
---source include/wait_for_slave_sql_to_stop.inc
---replace_result $MASTER_MYPORT MASTER_PORT
---replace_column 1 # 4 # 7 # 8 # 9 # 16 # 22 # 23 # 33 # 35 # 36 #
---query_vertical SHOW SLAVE STATUS
-SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
-START SLAVE;
+  #--source include/wait_for_slave_sql_to_stop.inc
+  #--replace_result $MASTER_MYPORT MASTER_PORT
+  #--replace_column 1 # 4 # 7 # 8 # 9 # 16 # 22 # 23 # 33 # 35 # 36 #
+  #--query_vertical SHOW SLAVE STATUS
+  #SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
+  #START SLAVE;
+}
 
 #--echo *** Drop t9  ***
 #connection master;

=== added file 'mysql-test/extra/rpl_tests/rpl_not_null.test'
--- a/mysql-test/extra/rpl_tests/rpl_not_null.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_not_null.test	2009-10-22 00:19:52 +0000
@@ -0,0 +1,364 @@
+#################################################################################
+# This test checks if the replication between "null" fields to either "null"
+# fields or "not null" fields works properly. In the first case, the execution
+# should work fine. In the second case, it may fail according to the sql_mode
+# being used.
+#
+# The test is devided in three main parts:
+#
+# 1 - NULL --> NULL (no failures)
+# 2 - NULL --> NOT NULL ( sql-mode  = STRICT and failures)
+# 3 - NULL --> NOT NULL ( sql-mode != STRICT and no failures)
+#
+#################################################################################
+connection master;
+
+SET SQL_LOG_BIN= 0;
+eval CREATE TABLE t1(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+eval CREATE TABLE t2(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+eval CREATE TABLE t3(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+eval CREATE TABLE t4(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+SET SQL_LOG_BIN= 1;
+
+connection slave;
+
+eval CREATE TABLE t1(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+eval CREATE TABLE t2(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+eval CREATE TABLE t3(`a` INT, `b` DATE DEFAULT '0000-00-00',
+`c` INT DEFAULT 500, 
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+eval CREATE TABLE t4(`a` INT, `b` DATE DEFAULT '0000-00-00',
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+--echo ************* EXECUTION WITH INSERTS *************
+connection master;
+INSERT INTO t1(a,b,c) VALUES (1, null, 1);
+INSERT INTO t1(a,b,c) VALUES (2,'1111-11-11', 2);
+INSERT INTO t1(a,b) VALUES (3, null);
+INSERT INTO t1(a,c) VALUES (4, 4);
+INSERT INTO t1(a) VALUES (5);
+
+INSERT INTO t2(a,b) VALUES (1, null);
+INSERT INTO t2(a,b) VALUES (2,'1111-11-11');
+INSERT INTO t2(a) VALUES (3);
+
+INSERT INTO t3(a,b) VALUES (1, null);
+INSERT INTO t3(a,b) VALUES (2,'1111-11-11');
+INSERT INTO t3(a) VALUES (3);
+
+INSERT INTO t4(a,b,c) VALUES (1, null, 1);
+INSERT INTO t4(a,b,c) VALUES (2,'1111-11-11', 2);
+INSERT INTO t4(a,b) VALUES (3, null);
+INSERT INTO t4(a,c) VALUES (4, 4);
+INSERT INTO t4(a) VALUES (5);
+
+--echo ************* SHOWING THE RESULT SETS WITH INSERTS *************
+sync_slave_with_master;
+
+--echo TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+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;
+
+--echo TABLES t2 and t3 must be different.
+connection master;
+SELECT * FROM t3 ORDER BY a;
+connection slave;
+SELECT * FROM t3 ORDER BY a;
+connection master;
+SELECT * FROM t4 ORDER BY a;
+connection slave;
+SELECT * FROM t4 ORDER BY a;
+
+--echo ************* EXECUTION WITH UPDATES and REPLACES *************
+connection master;
+DELETE FROM t1;
+INSERT INTO t1(a,b,c) VALUES (1,'1111-11-11', 1);
+REPLACE INTO t1(a,b,c) VALUES (2,'1111-11-11', 2);
+UPDATE t1 set b= NULL, c= 300 where a= 1;
+REPLACE INTO t1(a,b,c) VALUES (2, NULL, 300);
+
+--echo ************* SHOWING THE RESULT SETS WITH UPDATES and REPLACES *************
+sync_slave_with_master;
+
+--echo TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+let $diff_table_1=master:test.t1;
+let $diff_table_2=slave:test.t1;
+source include/diff_tables.inc;
+
+--echo ************* CLEANING *************
+connection master;
+
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+
+sync_slave_with_master;
+  
+connection master;
+
+SET SQL_LOG_BIN= 0;
+eval CREATE TABLE t1 (`a` INT, `b` BIT DEFAULT NULL, `c` BIT DEFAULT NULL, 
+PRIMARY KEY (`a`)) ENGINE= $engine;
+SET SQL_LOG_BIN= 1;
+
+connection slave;
+
+eval CREATE TABLE t1 (`a` INT, `b` BIT DEFAULT b'01', `c` BIT DEFAULT NULL,
+PRIMARY KEY (`a`)) ENGINE= $engine;
+
+--echo ************* EXECUTION WITH INSERTS *************
+connection master;
+INSERT INTO t1(a,b,c) VALUES (1, null, b'01');
+INSERT INTO t1(a,b,c) VALUES (2,b'00', b'01');
+INSERT INTO t1(a,b) VALUES (3, null);
+INSERT INTO t1(a,c) VALUES (4, b'01');
+INSERT INTO t1(a) VALUES (5);
+
+--echo ************* SHOWING THE RESULT SETS WITH INSERTS *************
+--echo TABLES t1 and t2 must be different.
+sync_slave_with_master;
+connection master;
+SELECT a,b+0,c+0 FROM t1 ORDER BY a;
+connection slave;
+SELECT a,b+0,c+0 FROM t1 ORDER BY a;
+
+--echo ************* EXECUTION WITH UPDATES and REPLACES *************
+connection master;
+DELETE FROM t1;
+INSERT INTO t1(a,b,c) VALUES (1,b'00', b'01');
+REPLACE INTO t1(a,b,c) VALUES (2,b'00',b'01');
+UPDATE t1 set b= NULL, c= b'00' where a= 1;
+REPLACE INTO t1(a,b,c) VALUES (2, NULL, b'00');
+
+--echo ************* SHOWING THE RESULT SETS WITH UPDATES and REPLACES *************
+--echo TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+sync_slave_with_master;
+let $diff_table_1=master:test.t1;
+let $diff_table_2=slave:test.t1;
+source include/diff_tables.inc;
+ 
+connection master;
+
+DROP TABLE t1;
+
+sync_slave_with_master;
+  
+--echo ################################################################################
+--echo #                       NULL ---> NOT NULL (STRICT MODE)
+--echo #                    UNCOMMENT THIS AFTER FIXING BUG#43992
+--echo ################################################################################
+#connection slave;
+#SET GLOBAL sql_mode="TRADITIONAL";
+#
+#STOP SLAVE;
+#--source include/wait_for_slave_to_stop.inc
+#START SLAVE;
+#--source include/wait_for_slave_to_start.inc
+#
+#let $y=0;
+#while (`select $y < 6`)
+#{
+#  connection master;
+#
+#  SET SQL_LOG_BIN= 0;
+#  eval CREATE TABLE t1(`a` INT NOT NULL, `b` INT,
+#  PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+#  eval CREATE TABLE t2(`a` INT NOT NULL, `b` INT,
+#  PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+#  eval CREATE TABLE t3(`a` INT NOT NULL, `b` INT,
+#  PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+#  SET SQL_LOG_BIN= 1;
+#  
+#  connection slave;
+#  
+#  eval CREATE TABLE t1(`a` INT NOT NULL, `b` INT NOT NULL, 
+#  `c` INT NOT NULL,
+#  PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+#  eval CREATE TABLE t2(`a` INT NOT NULL, `b` INT NOT NULL,
+#  `c` INT, 
+#  PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+#  eval CREATE TABLE t3(`a` INT NOT NULL, `b` INT NOT NULL,
+#  `c` INT DEFAULT 500, 
+#  PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+#  
+#  if (`select $y=0`)
+#  {
+#    --echo ************* EXECUTION WITH INSERTS *************
+#    connection master;
+#    INSERT INTO t1(a) VALUES (1);
+#  }
+#  
+#  if (`select $y=1`)
+#  {
+#    --echo ************* EXECUTION WITH INSERTS *************
+#    connection master;
+#    INSERT INTO t1(a, b) VALUES (1, NULL);
+#  }
+#  
+#  if (`select $y=2`)
+#  {
+#    --echo ************* EXECUTION WITH UPDATES *************
+#    connection master;
+#    INSERT INTO t3(a, b) VALUES (1, 1);
+#    INSERT INTO t3(a, b) VALUES (2, 1);
+#    UPDATE t3 SET b = NULL where a= 1;
+#  }
+#  
+#  if (`select $y=3`)
+#  {
+#    --echo ************* EXECUTION WITH INSERTS/REPLACES *************
+#    connection master;
+#    REPLACE INTO t3(a, b) VALUES (1, null);
+#  }
+#   
+#  if (`select $y=4`)
+#  {
+#    --echo ************* EXECUTION WITH UPDATES/REPLACES *************
+#    connection master;
+#    INSERT INTO t3(a, b) VALUES (1, 1);
+#    REPLACE INTO t3(a, b) VALUES (1, null);
+#  }
+#   
+#  if (`select $y=5`)
+#  {
+#    --echo ************* EXECUTION WITH MULTI-ROW INSERTS *************
+#    connection master;
+#
+#    SET SQL_LOG_BIN= 0;
+#    INSERT INTO t2(a, b) VALUES (1, 1);
+#    INSERT INTO t2(a, b) VALUES (2, 1);
+#    INSERT INTO t2(a, b) VALUES (3, null);
+#    INSERT INTO t2(a, b) VALUES (4, 1);
+#    INSERT INTO t2(a, b) VALUES (5, 1);
+#    SET SQL_LOG_BIN= 1;
+#
+#    INSERT INTO t2 SELECT a + 10, b from t2;
+#    --echo The statement below is just executed to stop processing
+#    INSERT INTO t1(a) VALUES (1);
+#  }
+#  
+#  --echo ************* SHOWING THE RESULT SETS *************
+#  connection slave;
+#  --source include/wait_for_slave_sql_to_stop.inc
+#  connection master;
+#  SELECT * FROM t1 ORDER BY a;
+#  connection slave;
+#  SELECT * FROM t1 ORDER BY a;
+#  connection master;
+#  SELECT * FROM t2 ORDER BY a;
+#  connection slave;
+#  SELECT * FROM t2 ORDER BY a;
+#  connection master;
+#  SELECT * FROM t3 ORDER BY a;
+#  connection slave;
+#  SELECT * FROM t3 ORDER BY a;
+#  --source include/reset_master_and_slave.inc
+#  
+#  connection master;
+#  
+#  DROP TABLE t1;
+#  DROP TABLE t2;
+#  DROP TABLE t3;
+#  
+#  sync_slave_with_master;
+#
+#  inc $y;
+#}
+#connection slave;
+#SET GLOBAL sql_mode="";
+#
+#STOP SLAVE;
+#source include/wait_for_slave_to_stop.inc;
+#START SLAVE;
+#--source include/wait_for_slave_to_start.inc
+
+--echo ################################################################################
+--echo #                       NULL ---> NOT NULL (NON-STRICT MODE)
+--echo ################################################################################
+connection master;
+
+SET SQL_LOG_BIN= 0;
+eval CREATE TABLE t1(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+eval CREATE TABLE t2(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+eval CREATE TABLE t3(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+SET SQL_LOG_BIN= 1;
+
+connection slave;
+
+eval CREATE TABLE t1(`a` INT NOT NULL, `b` INT NOT NULL, 
+`c` INT NOT NULL,
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+eval CREATE TABLE t2(`a` INT NOT NULL, `b` INT NOT NULL,
+`c` INT, 
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+eval CREATE TABLE t3(`a` INT NOT NULL, `b` INT NOT NULL,
+`c` INT DEFAULT 500, 
+PRIMARY KEY(`a`)) ENGINE=$engine DEFAULT CHARSET=LATIN1;
+
+--echo ************* EXECUTION WITH INSERTS *************
+connection master;
+INSERT INTO t1(a) VALUES (1);
+INSERT INTO t1(a, b) VALUES (2, NULL);
+INSERT INTO t1(a, b) VALUES (3, 1);
+
+INSERT INTO t2(a) VALUES (1);
+INSERT INTO t2(a, b) VALUES (2, NULL);
+INSERT INTO t2(a, b) VALUES (3, 1);
+
+INSERT INTO t3(a) VALUES (1);
+INSERT INTO t3(a, b) VALUES (2, NULL);
+INSERT INTO t3(a, b) VALUES (3, 1);
+INSERT INTO t3(a, b) VALUES (4, 1);
+REPLACE INTO t3(a, b) VALUES (5, null);
+
+REPLACE INTO t3(a, b) VALUES (3, null);
+UPDATE t3 SET b = NULL where a = 4;
+
+--echo ************* SHOWING THE RESULT SETS *************
+connection master;
+sync_slave_with_master;
+
+connection master;
+SELECT * FROM t1 ORDER BY a;
+connection slave;
+SELECT * FROM t1 ORDER BY a;
+connection master;
+SELECT * FROM t2 ORDER BY a;
+connection slave;
+SELECT * FROM t2 ORDER BY a;
+connection master;
+SELECT * FROM t3 ORDER BY a;
+connection slave;
+SELECT * FROM t3 ORDER BY a;
+
+connection master;
+
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+
+sync_slave_with_master;

=== modified file 'mysql-test/extra/rpl_tests/rpl_row_tabledefs.test'
--- a/mysql-test/extra/rpl_tests/rpl_row_tabledefs.test	2008-03-14 20:02:52 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_row_tabledefs.test	2009-10-22 00:10:42 +0000
@@ -111,21 +111,18 @@ SELECT a,b,x FROM t1_int ORDER BY a;
 SELECT a,b,HEX(x),HEX(y),HEX(z) FROM t1_bit ORDER BY a;
 SELECT a,b,x FROM t1_char ORDER BY a;
 
-# Each of these inserts should generate an error and stop the slave
-
 connection master;
 INSERT INTO t9 VALUES (2);
 sync_slave_with_master;
 # Now slave is guaranteed to be running
 connection master;
 INSERT INTO t1_nodef VALUES (1,2);
-connection slave;
---source include/wait_for_slave_sql_to_stop.inc
---replace_result $MASTER_MYPORT MASTER_PORT
---replace_column 1 # 4 # 7 # 8 # 9 # 20 <Last_Error> 22 # 23 # 33 # 35 <Last_IO_Errno> 36 <Last_IO_Error> 38 <Last_SQL_Error>
---query_vertical SHOW SLAVE STATUS
-SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
-START SLAVE;
+
+# Last insert on wider slave table succeeds while slave sql sql_mode permits.
+# The previous version of the above test expected slave sql to stop.
+# bug#38173 relaxed conditions to stop only with the strict mode.
+sync_slave_with_master;
+select count(*) from t1_nodef;
 
 #
 # Replicating to tables with fewer columns at the end works as of WL#3228

=== modified file 'mysql-test/extra/rpl_tests/rpl_stm_000001.test'
--- a/mysql-test/extra/rpl_tests/rpl_stm_000001.test	2009-10-20 18:00:07 +0000
+++ b/mysql-test/extra/rpl_tests/rpl_stm_000001.test	2009-11-18 14:50:31 +0000
@@ -1,6 +1,11 @@
--- source include/have_binlog_format_mixed_or_statement.inc
+# Requires binlog_format=statement format since query involving
+# get_lock() is logged in row format if binlog_format=mixed or row.
+-- source include/have_binlog_format_statement.inc
 -- source include/master-slave.inc
 
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
+
+# Load some data into t1
 create table t1 (word char(20) not null);
 load data infile '../../std_data/words.dat' into table t1;
 --replace_result $MYSQL_TEST_DIR MYSQL_TEST_DIR
@@ -10,9 +15,7 @@ select * from t1 limit 10;
 #
 # Test slave with wrong password
 #
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 stop slave;
 connection master;
 set password for root@"localhost" = password('foo');
@@ -29,16 +32,12 @@ sleep 2;
 
 create table t3(n int);
 insert into t3 values(1),(2);
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 select * from t3;
 select sum(length(word)) from t1;
 connection master;
 drop table t1,t3;
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 
 # Test if the slave SQL thread can be more than 16K behind the slave
 # I/O thread (> IO_SIZE)
@@ -77,12 +76,13 @@ unlock tables;
 connection master;
 create table t2(id int);
 insert into t2 values(connection_id());
-save_master_pos;
 
 connection master1;
 # Avoid generating result
 create temporary table t3(n int);
+--disable_warnings
 insert into t3 select get_lock('crash_lock%20C', 1) from t2;
+--enable_warnings
 
 connection master;
 send update t1 set n = n + get_lock('crash_lock%20C', 2);
@@ -93,8 +93,11 @@ kill @id;
 # We don't drop t3 as this is a temporary table
 drop table t2;
 connection master;
+# The get_lock function causes warning for unsafe statement.
+--disable_warnings
 --error 1317,2013
 reap;
+--enable_warnings
 connection slave;
 # The SQL slave thread should now have stopped because the query was killed on
 # the master (so it has a non-zero error code in the binlog).
@@ -117,16 +120,12 @@ insert into mysql.user (Host, User, Pass
 select select_priv,user from mysql.user where user = _binary'blafasel2';
 update mysql.user set Select_priv = "Y" where User= _binary"blafasel2";
 select select_priv,user from mysql.user where user = _binary'blafasel2';
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 select n from t1;
 select select_priv,user from mysql.user where user = _binary'blafasel2';
 connection master1;
 drop table t1;
 delete from mysql.user where user="blafasel2";
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 
 # End of 4.1 tests

=== modified file 'mysql-test/include/have_big5.inc'
--- a/mysql-test/include/have_big5.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_big5.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_big5.require
-disable_query_log;
-show collation like 'big5_chinese_ci';
-enable_query_log;
+let collation=big5_chinese_ci;
+--source include/have_collation.inc

=== added file 'mysql-test/include/have_collation.inc'
--- a/mysql-test/include/have_collation.inc	1970-01-01 00:00:00 +0000
+++ b/mysql-test/include/have_collation.inc	2009-12-27 13:54:41 +0000
@@ -0,0 +1,3 @@
+if (!`SELECT count(*) AS 'true' FROM information_schema.collations WHERE collation_name LIKE '$collation'`) {
+   skip Test needs character set '$collation';
+}

=== modified file 'mysql-test/include/have_cp1250_ch.inc'
--- a/mysql-test/include/have_cp1250_ch.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_cp1250_ch.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_cp1250_ch.require
-disable_query_log;
-show collation like 'cp1250_czech_cs';
-enable_query_log;
+let collation=cp1250_czech_cs;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_cp1251.inc'
--- a/mysql-test/include/have_cp1251.inc	2007-06-28 17:34:54 +0000
+++ b/mysql-test/include/have_cp1251.inc	2009-12-27 13:54:41 +0000
@@ -1,7 +1,2 @@
---require r/have_cp1251.require
-
---disable_query_log
-
-SHOW COLLATION LIKE 'cp1251_general_ci';
-
---enable_query_log
+let collation=cp1251_general_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_cp866.inc'
--- a/mysql-test/include/have_cp866.inc	2007-06-28 17:34:54 +0000
+++ b/mysql-test/include/have_cp866.inc	2009-12-27 13:54:41 +0000
@@ -1,7 +1,2 @@
---require r/have_cp866.require
-
---disable_query_log
-
-SHOW COLLATION LIKE 'cp866_general_ci';
-
---enable_query_log
+let collation=cp866_general_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_cp932.inc'
--- a/mysql-test/include/have_cp932.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_cp932.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_cp932.require
-disable_query_log;
-show collation like 'cp932_japanese_ci';
-enable_query_log;
+let collation=cp932_japanese_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_eucjpms.inc'
--- a/mysql-test/include/have_eucjpms.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_eucjpms.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_eucjpms.require
-disable_query_log;
-show collation like 'eucjpms_japanese_ci';
-enable_query_log;
+let collation=eucjpms_japanese_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_euckr.inc'
--- a/mysql-test/include/have_euckr.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_euckr.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_euckr.require
-disable_query_log;
-show collation like 'euckr_korean_ci';
-enable_query_log;
+let collation=euckr_korean_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_gb2312.inc'
--- a/mysql-test/include/have_gb2312.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_gb2312.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_gb2312.require
-disable_query_log;
-show collation like 'gb2312_chinese_ci';
-enable_query_log;
+let collation=gb2312_chinese_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_gbk.inc'
--- a/mysql-test/include/have_gbk.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_gbk.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_gbk.require
-disable_query_log;
-show collation like 'gbk_chinese_ci';
-enable_query_log;
+let collation=gbk_chinese_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_koi8r.inc'
--- a/mysql-test/include/have_koi8r.inc	2007-06-28 17:34:54 +0000
+++ b/mysql-test/include/have_koi8r.inc	2009-12-27 13:54:41 +0000
@@ -1,7 +1,2 @@
---require r/have_koi8r.require
-
---disable_query_log
-
-SHOW COLLATION LIKE 'koi8r_general_ci';
-
---enable_query_log
+let collation=koi8r_general_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_latin2_ch.inc'
--- a/mysql-test/include/have_latin2_ch.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_latin2_ch.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_latin2_ch.require
-disable_query_log;
-show collation like 'latin2_czech_cs';
-enable_query_log;
+let collation=latin2_czech_cs;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_sjis.inc'
--- a/mysql-test/include/have_sjis.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_sjis.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_sjis.require
-disable_query_log;
-show collation like 'sjis_japanese_ci';
-enable_query_log;
+let collation=sjis_japanese_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_tis620.inc'
--- a/mysql-test/include/have_tis620.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_tis620.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_tis620.require
-disable_query_log;
-show collation like 'tis620_thai_ci';
-enable_query_log;
+let collation=tis620_thai_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_ucs2.inc'
--- a/mysql-test/include/have_ucs2.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_ucs2.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_ucs2.require
-disable_query_log;
-show collation like 'ucs2_general_ci';
-enable_query_log;
+let collation=ucs2_general_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_ujis.inc'
--- a/mysql-test/include/have_ujis.inc	2008-07-04 16:41:27 +0000
+++ b/mysql-test/include/have_ujis.inc	2009-12-27 13:54:41 +0000
@@ -1,4 +1,2 @@
--- require r/have_ujis.require
-disable_query_log;
-show collation like 'ujis_japanese_ci';
-enable_query_log;
+let collation=ujis_japanese_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/have_utf8.inc'
--- a/mysql-test/include/have_utf8.inc	2007-06-28 17:34:54 +0000
+++ b/mysql-test/include/have_utf8.inc	2009-12-27 13:54:41 +0000
@@ -1,7 +1,2 @@
---require r/have_utf8.require
-
---disable_query_log
-
-SHOW COLLATION LIKE 'utf8_general_ci';
-
---enable_query_log
+let collation=utf8_general_ci;
+--source include/have_collation.inc

=== modified file 'mysql-test/include/mtr_warnings.sql'
--- a/mysql-test/include/mtr_warnings.sql	2009-12-03 11:19:05 +0000
+++ b/mysql-test/include/mtr_warnings.sql	2010-01-15 15:27:55 +0000
@@ -175,6 +175,8 @@ INSERT INTO global_suppressions VALUES
  ("Can't find file: '.\\\\test\\\\\\?{8}.frm'"),
  ("Slave: Unknown table 't1' Error_code: 1051"),
 
+ /* Maria storage engine dependent tests */
+
  /* maria-recovery.test has warning about missing log file */
  ("File '.*maria_log.000.*' not found \\(Errcode: 2\\)"),
  /* and about marked-corrupted table */
@@ -184,6 +186,14 @@ INSERT INTO global_suppressions VALUES
  ("Table '..mysqltest.t_corrupted2' is marked as crashed and should be"),
  ("Incorrect key file for table '..mysqltest.t_corrupted2.MAI'"),
 
+ /*
+   Transient network failures that cause warnings on reconnect.
+   BUG#47743 and BUG#47983.
+ */
+ ("Slave I/O: Get master SERVER_ID failed with error:.*"),
+ ("Slave I/O: Get master clock failed with error:.*"),
+ ("Slave I/O: Get master COLLATION_SERVER failed with error:.*"),
+ ("Slave I/O: Get master TIME_ZONE failed with error:.*"),
 
  ("THE_LAST_SUPPRESSION")||
 

=== modified file 'mysql-test/lib/mtr_cases.pm'
--- a/mysql-test/lib/mtr_cases.pm	2009-12-06 17:34:54 +0000
+++ b/mysql-test/lib/mtr_cases.pm	2010-01-15 15:27:55 +0000
@@ -524,6 +524,10 @@ sub collect_one_suite
       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');
+      # Fails with innodb plugin
+      next if ($test->{'name'} eq 'main.innodb-autoinc');
+      # Fails with innodb plugin: r6185 Testcases changes not included
+      next if ($test->{'name'} eq 'main.innodb_bug44369');
       # Copy test options
       my $new_test= My::Test->new();
       while (my ($key, $value) = each(%$test))

=== modified file 'mysql-test/mysql-test-run.pl'
--- a/mysql-test/mysql-test-run.pl	2009-12-06 17:34:54 +0000
+++ b/mysql-test/mysql-test-run.pl	2010-01-06 21:27:53 +0000
@@ -126,7 +126,7 @@ my $path_config_file;           # The ge
 # executables will be used by the test suite.
 our $opt_vs_config = $ENV{'MTR_VS_CONFIG'};
 
-my $DEFAULT_SUITES= "main,binlog,federated,rpl,innodb,maria,parts";
+my $DEFAULT_SUITES= "main,binlog,federated,rpl,maria,parts";
 my $opt_suites;
 
 our $opt_verbose= 0;  # Verbose output, enable with --verbose
@@ -301,6 +301,9 @@ sub main {
     }
   }
 
+  # Check for plugin availability so we know whether to skip tests or not.
+  detect_plugins();
+
   mtr_report("Collecting tests...");
   my $tests= collect_test_cases($opt_suites, \@opt_cases);
 
@@ -1877,6 +1880,37 @@ sub have_maria_support () {
 }
 
 
+# Detect plugin presense and set environment variables appropriately.
+# This needs to be done early, so we can know whether to skip tests.
+sub detect_plugins {
+  # --------------------------------------------------------------------------
+  # Add the path where mysqld will find ha_example.so
+  # --------------------------------------------------------------------------
+  if ($mysql_version_id >= 50100) {
+    my $plugin_filename;
+    if (IS_WINDOWS)
+    {
+       $plugin_filename = "ha_example.dll";
+    }
+    else 
+    {
+       $plugin_filename = "ha_example.so";
+    }
+    my $lib_example_plugin=
+      mtr_file_exists(vs_config_dirs('storage/example',$plugin_filename),
+		      "$basedir/storage/example/.libs/".$plugin_filename,
+                      "$basedir/lib/mariadb/plugin/".$plugin_filename,
+                      "$basedir/lib/mysql/plugin/".$plugin_filename);
+    $ENV{'EXAMPLE_PLUGIN'}=
+      ($lib_example_plugin ? basename($lib_example_plugin) : "");
+    $ENV{'EXAMPLE_PLUGIN_OPT'}= "--plugin-dir=".
+      ($lib_example_plugin ? dirname($lib_example_plugin) : "");
+
+    $ENV{'HA_EXAMPLE_SO'}="'".$plugin_filename."'";
+    $ENV{'EXAMPLE_PLUGIN_LOAD'}="--plugin_load=EXAMPLE=".$plugin_filename;
+  }
+}
+
 #
 # Set environment to be used by childs of this process for
 # things that are constant during the whole lifetime of mysql-test-run
@@ -1935,33 +1969,6 @@ sub environment_setup {
   $ENV{'UDF_EXAMPLE_LIB_OPT'}= "--plugin-dir=".
     ($lib_udf_example ? dirname($lib_udf_example) : "");
 
-  # --------------------------------------------------------------------------
-  # Add the path where mysqld will find ha_example.so
-  # --------------------------------------------------------------------------
-  if ($mysql_version_id >= 50100) {
-    my $plugin_filename;
-    if (IS_WINDOWS)
-    {
-       $plugin_filename = "ha_example.dll";
-    }
-    else 
-    {
-       $plugin_filename = "ha_example.so";
-    }
-    my $lib_example_plugin=
-      mtr_file_exists(vs_config_dirs('storage/example',$plugin_filename),
-		      "$basedir/storage/example/.libs/".$plugin_filename,
-                      "$basedir/lib/mariadb/plugin/".$plugin_filename,
-                      "$basedir/lib/mysql/plugin/".$plugin_filename);
-    $ENV{'EXAMPLE_PLUGIN'}=
-      ($lib_example_plugin ? basename($lib_example_plugin) : "");
-    $ENV{'EXAMPLE_PLUGIN_OPT'}= "--plugin-dir=".
-      ($lib_example_plugin ? dirname($lib_example_plugin) : "");
-
-    $ENV{'HA_EXAMPLE_SO'}="'".$plugin_filename."'";
-    $ENV{'EXAMPLE_PLUGIN_LOAD'}="--plugin_load=EXAMPLE=".$plugin_filename;
-  }
-
   # ----------------------------------------------------
   # Add the path where mysqld will find mypluglib.so
   # ----------------------------------------------------
@@ -4003,6 +4010,7 @@ sub extract_warning_lines ($) {
      qr/Slave I\/O: error reconnecting to master '.*' - retry-time: [1-3]  retries/,
      qr/Error reading packet/,
      qr/Slave: Can't drop database.* database doesn't exist/,
+     qr/Slave: Operation DROP USER failed for 'create_rout_db'/,
     );
 
   my $matched_lines= [];

=== modified file 'mysql-test/r/archive.result'
--- a/mysql-test/r/archive.result	2009-09-10 06:58:13 +0000
+++ b/mysql-test/r/archive.result	2009-11-11 08:03:29 +0000
@@ -12717,3 +12717,14 @@ COUNT(t1.a)
 729
 DROP TABLE t1;
 SET @@join_buffer_size= @save_join_buffer_size;
+SHOW CREATE TABLE t1;
+ERROR HY000: Table upgrade required. Please do "REPAIR TABLE `t1`" or dump/reload to fix it!
+SELECT * FROM t1;
+ERROR HY000: Table upgrade required. Please do "REPAIR TABLE `t1`" or dump/reload to fix it!
+INSERT INTO t1 (col1, col2) VALUES (1, "value");
+ERROR HY000: Table upgrade required. Please do "REPAIR TABLE `t1`" or dump/reload to fix it!
+REPAIR TABLE t1;
+Table	Op	Msg_type	Msg_text
+test.t1	repair	Error	Table upgrade required. Please do "REPAIR TABLE `t1`" or dump/reload to fix it!
+test.t1	repair	error	Corrupt
+DROP TABLE t1;

=== added file 'mysql-test/r/bug47671.result'
--- a/mysql-test/r/bug47671.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/bug47671.result	2010-01-15 15:27:55 +0000
@@ -0,0 +1,14 @@
+#
+# Bug#47671 - wrong character-set after upgrade from 5.1.34 to 5.1.39
+#
+# Extract only charset information from 'status' command output using regex
+--------------
+
+Server:			MariaDB
+Server characterset:	utf8
+Db     characterset:	utf8
+Client characterset:	utf8
+Conn.  characterset:	utf8
+
+--------------
+

=== added file 'mysql-test/r/create-uca.result'
--- a/mysql-test/r/create-uca.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/create-uca.result	2009-12-27 13:54:41 +0000
@@ -0,0 +1,31 @@
+drop table if exists t1,t2;
+CREATE TABLE t1(
+c1 INT DEFAULT 12 COMMENT 'column1',
+c2 INT NULL COMMENT 'column2',
+c3 INT NOT NULL COMMENT 'column3',
+c4 VARCHAR(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
+c5 VARCHAR(255) COLLATE utf8_unicode_ci NULL DEFAULT 'b',
+c6 VARCHAR(255))
+COLLATE latin1_bin;
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` int(11) DEFAULT '12' COMMENT 'column1',
+  `c2` int(11) DEFAULT NULL COMMENT 'column2',
+  `c3` int(11) NOT NULL COMMENT 'column3',
+  `c4` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
+  `c5` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'b',
+  `c6` varchar(255) COLLATE latin1_bin DEFAULT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_bin
+CREATE TABLE t2 AS SELECT * FROM t1;
+SHOW CREATE TABLE t2;
+Table	Create Table
+t2	CREATE TABLE `t2` (
+  `c1` int(11) DEFAULT '12' COMMENT 'column1',
+  `c2` int(11) DEFAULT NULL COMMENT 'column2',
+  `c3` int(11) NOT NULL COMMENT 'column3',
+  `c4` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
+  `c5` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'b',
+  `c6` varchar(255) CHARACTER SET latin1 COLLATE latin1_bin DEFAULT NULL
+) ENGINE=MyISAM DEFAULT CHARSET=latin1
+DROP TABLE t1,t2;

=== modified file 'mysql-test/r/create.result'
--- a/mysql-test/r/create.result	2009-12-03 11:19:05 +0000
+++ b/mysql-test/r/create.result	2009-12-27 13:54:41 +0000
@@ -1793,52 +1793,6 @@ t1	CREATE TABLE `t1` (
 drop table t1;
 
 # --
-# -- Bug#21380: DEFAULT definition not always transfered by CREATE
-# -- TABLE/SELECT to the new table.
-# --
-
-DROP TABLE IF EXISTS t1;
-DROP TABLE IF EXISTS t2;
-
-CREATE TABLE t1(
-c1 INT DEFAULT 12 COMMENT 'column1',
-c2 INT NULL COMMENT 'column2',
-c3 INT NOT NULL COMMENT 'column3',
-c4 VARCHAR(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
-c5 VARCHAR(255) COLLATE utf8_unicode_ci NULL DEFAULT 'b',
-c6 VARCHAR(255))
-COLLATE latin1_bin;
-
-SHOW CREATE TABLE t1;
-Table	Create Table
-t1	CREATE TABLE `t1` (
-  `c1` int(11) DEFAULT '12' COMMENT 'column1',
-  `c2` int(11) DEFAULT NULL COMMENT 'column2',
-  `c3` int(11) NOT NULL COMMENT 'column3',
-  `c4` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
-  `c5` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'b',
-  `c6` varchar(255) COLLATE latin1_bin DEFAULT NULL
-) ENGINE=MyISAM DEFAULT CHARSET=latin1 COLLATE=latin1_bin
-
-CREATE TABLE t2 AS SELECT * FROM t1;
-
-SHOW CREATE TABLE t2;
-Table	Create Table
-t2	CREATE TABLE `t2` (
-  `c1` int(11) DEFAULT '12' COMMENT 'column1',
-  `c2` int(11) DEFAULT NULL COMMENT 'column2',
-  `c3` int(11) NOT NULL COMMENT 'column3',
-  `c4` varchar(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
-  `c5` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT 'b',
-  `c6` varchar(255) CHARACTER SET latin1 COLLATE latin1_bin DEFAULT NULL
-) ENGINE=MyISAM DEFAULT CHARSET=latin1
-
-DROP TABLE t2;
-DROP TABLE t1;
-
-# -- End of test case for Bug#21380.
-
-# --
 # -- Bug#18834: ALTER TABLE ADD INDEX on table with two timestamp fields
 # --
 

=== modified file 'mysql-test/r/ctype_utf8.result'
--- a/mysql-test/r/ctype_utf8.result	2009-01-26 21:19:13 +0000
+++ b/mysql-test/r/ctype_utf8.result	2010-01-04 12:35:54 +0000
@@ -1,3 +1,5 @@
+drop table if exists t1,t2,t3,t4;
+drop database if exists mysqltest;
 drop table if exists t1,t2;
 set names utf8;
 select left(_utf8 0xD0B0D0B1D0B2,1);

=== modified file 'mysql-test/r/delayed.result'
--- a/mysql-test/r/delayed.result	2009-03-11 15:32:42 +0000
+++ b/mysql-test/r/delayed.result	2010-01-15 15:27:55 +0000
@@ -314,4 +314,16 @@ a	b
 2	2
 drop table t1;
 set global low_priority_updates = @old_delayed_updates;
+#
+# Bug #47682 strange behaviour of INSERT DELAYED
+#
+DROP TABLE IF EXISTS t1, t2;
+CREATE TABLE t1 (f1 integer);
+CREATE TABLE t2 (f1 integer);
+FLUSH TABLES WITH READ LOCK;
+LOCK TABLES t1 READ;
+INSERT DELAYED INTO t2 VALUES (1);
+Got one of the listed errors
+UNLOCK TABLES;
+DROP TABLE t1, t2;
 End of 5.1 tests

=== modified file 'mysql-test/r/delete.result'
--- a/mysql-test/r/delete.result	2009-09-28 10:48:52 +0000
+++ b/mysql-test/r/delete.result	2009-11-18 09:32:03 +0000
@@ -324,3 +324,16 @@ a
 1
 2
 DROP TABLE t1, t2, t3;
+#
+# Bug #46425 crash in Diagnostics_area::set_ok_status, 
+#            empty statement, DELETE IGNORE
+#
+CREATE table t1 (i INTEGER);
+INSERT INTO t1 VALUES (1);
+CREATE TRIGGER tr1 AFTER DELETE ON t1 FOR EACH ROW 
+BEGIN 
+INSERT INTO t1 SELECT * FROM t1 AS A;
+END |
+DELETE IGNORE FROM t1;
+ERROR HY000: Can't update table 't1' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.
+DROP TABLE t1;

=== modified file 'mysql-test/r/fulltext.result'
--- a/mysql-test/r/fulltext.result	2009-09-07 20:50:10 +0000
+++ b/mysql-test/r/fulltext.result	2010-01-15 15:27:55 +0000
@@ -559,3 +559,42 @@ EXECUTE s;
 MATCH (col) AGAINST('findme')
 DEALLOCATE PREPARE s;
 DROP TABLE t1;
+#
+# Bug #47930: MATCH IN BOOLEAN MODE returns too many results 
+#  inside subquery
+#
+CREATE TABLE t1 (a int);
+INSERT INTO t1 VALUES (1), (2);
+CREATE TABLE t2 (a int, b2 char(10), FULLTEXT KEY b2 (b2));
+INSERT INTO t2 VALUES (1,'Scargill');
+CREATE TABLE t3 (a int, b int);
+INSERT INTO t3 VALUES (1,1), (2,1);
+# t2 should use full text index
+EXPLAIN
+SELECT count(*) FROM t1 WHERE 
+not exists(
+SELECT 1 FROM t2, t3
+WHERE t3.a=t1.a AND MATCH(b2) AGAINST('scargill' IN BOOLEAN MODE)
+);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	PRIMARY	t1	ALL	NULL	NULL	NULL	NULL	2	Using where
+2	DEPENDENT SUBQUERY	t2	fulltext	b2	b2	0		1	Using where
+2	DEPENDENT SUBQUERY	t3	ALL	NULL	NULL	NULL	NULL	2	Using where
+# should return 0
+SELECT count(*) FROM t1 WHERE 
+not exists(
+SELECT 1 FROM t2, t3
+WHERE t3.a=t1.a AND MATCH(b2) AGAINST('scargill' IN BOOLEAN MODE)
+);
+count(*)
+0
+# should return 0
+SELECT count(*) FROM t1 WHERE 
+not exists(
+SELECT 1 FROM t2 IGNORE INDEX (b2), t3
+WHERE t3.a=t1.a AND MATCH(b2) AGAINST('scargill' IN BOOLEAN MODE)
+);
+count(*)
+0
+DROP TABLE t1,t2,t3;
+End of 5.1 tests

=== modified file 'mysql-test/r/func_group.result'
--- a/mysql-test/r/func_group.result	2009-10-14 08:46:50 +0000
+++ b/mysql-test/r/func_group.result	2009-11-24 15:26:13 +0000
@@ -885,7 +885,7 @@ cast(sum(distinct df) as signed)
 3
 select cast(min(df) as signed) from t1;
 cast(min(df) as signed)
-0
+1
 select 1e8 * sum(distinct df) from t1;
 1e8 * sum(distinct df)
 330000000
@@ -1520,4 +1520,197 @@ max	i
 # Cleanup
 #
 DROP TABLE t1;
+#
+# Bug#43668: Wrong comparison and MIN/MAX for YEAR(2)
+#
+create table t1 (f1 year(2), f2 year(4), f3 date, f4 datetime);
+insert into t1 values
+(98,1998,19980101,"1998-01-01 00:00:00"),
+(00,2000,20000101,"2000-01-01 00:00:01"),
+(02,2002,20020101,"2002-01-01 23:59:59"),
+(60,2060,20600101,"2060-01-01 11:11:11"),
+(70,1970,19700101,"1970-11-11 22:22:22"),
+(NULL,NULL,NULL,NULL);
+select min(f1),max(f1) from t1;
+min(f1)	max(f1)
+70	60
+select min(f2),max(f2) from t1;
+min(f2)	max(f2)
+1970	2060
+select min(f3),max(f3) from t1;
+min(f3)	max(f3)
+1970-01-01	2060-01-01
+select min(f4),max(f4) from t1;
+min(f4)	max(f4)
+1970-11-11 22:22:22	2060-01-01 11:11:11
+select a.f1 as a, b.f1 as b, a.f1 > b.f1 as gt,
+a.f1 < b.f1 as lt, a.f1<=>b.f1 as eq
+from t1 a, t1 b;
+a	b	gt	lt	eq
+98	98	0	0	1
+00	98	1	0	0
+02	98	1	0	0
+60	98	1	0	0
+70	98	0	1	0
+NULL	98	NULL	NULL	0
+98	00	0	1	0
+00	00	0	0	1
+02	00	1	0	0
+60	00	1	0	0
+70	00	0	1	0
+NULL	00	NULL	NULL	0
+98	02	0	1	0
+00	02	0	1	0
+02	02	0	0	1
+60	02	1	0	0
+70	02	0	1	0
+NULL	02	NULL	NULL	0
+98	60	0	1	0
+00	60	0	1	0
+02	60	0	1	0
+60	60	0	0	1
+70	60	0	1	0
+NULL	60	NULL	NULL	0
+98	70	1	0	0
+00	70	1	0	0
+02	70	1	0	0
+60	70	1	0	0
+70	70	0	0	1
+NULL	70	NULL	NULL	0
+98	NULL	NULL	NULL	0
+00	NULL	NULL	NULL	0
+02	NULL	NULL	NULL	0
+60	NULL	NULL	NULL	0
+70	NULL	NULL	NULL	0
+NULL	NULL	NULL	NULL	1
+select a.f1 as a, b.f2 as b, a.f1 > b.f2 as gt,
+a.f1 < b.f2 as lt, a.f1<=>b.f2 as eq
+from t1 a, t1 b;
+a	b	gt	lt	eq
+98	1998	0	0	1
+00	1998	1	0	0
+02	1998	1	0	0
+60	1998	1	0	0
+70	1998	0	1	0
+NULL	1998	NULL	NULL	0
+98	2000	0	1	0
+00	2000	0	0	1
+02	2000	1	0	0
+60	2000	1	0	0
+70	2000	0	1	0
+NULL	2000	NULL	NULL	0
+98	2002	0	1	0
+00	2002	0	1	0
+02	2002	0	0	1
+60	2002	1	0	0
+70	2002	0	1	0
+NULL	2002	NULL	NULL	0
+98	2060	0	1	0
+00	2060	0	1	0
+02	2060	0	1	0
+60	2060	0	0	1
+70	2060	0	1	0
+NULL	2060	NULL	NULL	0
+98	1970	1	0	0
+00	1970	1	0	0
+02	1970	1	0	0
+60	1970	1	0	0
+70	1970	0	0	1
+NULL	1970	NULL	NULL	0
+98	NULL	NULL	NULL	0
+00	NULL	NULL	NULL	0
+02	NULL	NULL	NULL	0
+60	NULL	NULL	NULL	0
+70	NULL	NULL	NULL	0
+NULL	NULL	NULL	NULL	1
+select a.f1 as a, b.f3 as b, a.f1 > b.f3 as gt,
+a.f1 < b.f3 as lt, a.f1<=>b.f3 as eq
+from t1 a, t1 b;
+a	b	gt	lt	eq
+98	1998-01-01	0	1	0
+00	1998-01-01	1	0	0
+02	1998-01-01	1	0	0
+60	1998-01-01	1	0	0
+70	1998-01-01	0	1	0
+NULL	1998-01-01	NULL	NULL	0
+98	2000-01-01	0	1	0
+00	2000-01-01	0	1	0
+02	2000-01-01	1	0	0
+60	2000-01-01	1	0	0
+70	2000-01-01	0	1	0
+NULL	2000-01-01	NULL	NULL	0
+98	2002-01-01	0	1	0
+00	2002-01-01	0	1	0
+02	2002-01-01	0	1	0
+60	2002-01-01	1	0	0
+70	2002-01-01	0	1	0
+NULL	2002-01-01	NULL	NULL	0
+98	2060-01-01	0	1	0
+00	2060-01-01	0	1	0
+02	2060-01-01	0	1	0
+60	2060-01-01	0	1	0
+70	2060-01-01	0	1	0
+NULL	2060-01-01	NULL	NULL	0
+98	1970-01-01	1	0	0
+00	1970-01-01	1	0	0
+02	1970-01-01	1	0	0
+60	1970-01-01	1	0	0
+70	1970-01-01	0	1	0
+NULL	1970-01-01	NULL	NULL	0
+98	NULL	NULL	NULL	0
+00	NULL	NULL	NULL	0
+02	NULL	NULL	NULL	0
+60	NULL	NULL	NULL	0
+70	NULL	NULL	NULL	0
+NULL	NULL	NULL	NULL	1
+select a.f1 as a, b.f4 as b, a.f1 > b.f4 as gt,
+a.f1 < b.f4 as lt, a.f1<=>b.f4 as eq
+from t1 a, t1 b;
+a	b	gt	lt	eq
+98	1998-01-01 00:00:00	0	1	0
+00	1998-01-01 00:00:00	1	0	0
+02	1998-01-01 00:00:00	1	0	0
+60	1998-01-01 00:00:00	1	0	0
+70	1998-01-01 00:00:00	0	1	0
+NULL	1998-01-01 00:00:00	NULL	NULL	0
+98	2000-01-01 00:00:01	0	1	0
+00	2000-01-01 00:00:01	0	1	0
+02	2000-01-01 00:00:01	1	0	0
+60	2000-01-01 00:00:01	1	0	0
+70	2000-01-01 00:00:01	0	1	0
+NULL	2000-01-01 00:00:01	NULL	NULL	0
+98	2002-01-01 23:59:59	0	1	0
+00	2002-01-01 23:59:59	0	1	0
+02	2002-01-01 23:59:59	0	1	0
+60	2002-01-01 23:59:59	1	0	0
+70	2002-01-01 23:59:59	0	1	0
+NULL	2002-01-01 23:59:59	NULL	NULL	0
+98	2060-01-01 11:11:11	0	1	0
+00	2060-01-01 11:11:11	0	1	0
+02	2060-01-01 11:11:11	0	1	0
+60	2060-01-01 11:11:11	0	1	0
+70	2060-01-01 11:11:11	0	1	0
+NULL	2060-01-01 11:11:11	NULL	NULL	0
+98	1970-11-11 22:22:22	1	0	0
+00	1970-11-11 22:22:22	1	0	0
+02	1970-11-11 22:22:22	1	0	0
+60	1970-11-11 22:22:22	1	0	0
+70	1970-11-11 22:22:22	0	1	0
+NULL	1970-11-11 22:22:22	NULL	NULL	0
+98	NULL	NULL	NULL	0
+00	NULL	NULL	NULL	0
+02	NULL	NULL	NULL	0
+60	NULL	NULL	NULL	0
+70	NULL	NULL	NULL	0
+NULL	NULL	NULL	NULL	1
+select *, f1 = f2 from t1;
+f1	f2	f3	f4	f1 = f2
+98	1998	1998-01-01	1998-01-01 00:00:00	1
+00	2000	2000-01-01	2000-01-01 00:00:01	1
+02	2002	2002-01-01	2002-01-01 23:59:59	1
+60	2060	2060-01-01	2060-01-01 11:11:11	1
+70	1970	1970-01-01	1970-11-11 22:22:22	1
+NULL	NULL	NULL	NULL	NULL
+drop table t1;
+#
 End of 5.1 tests

=== modified file 'mysql-test/r/func_misc.result'
--- a/mysql-test/r/func_misc.result	2009-10-28 07:52:34 +0000
+++ b/mysql-test/r/func_misc.result	2010-01-11 13:15:28 +0000
@@ -104,95 +104,6 @@ t1	CREATE TABLE `t1` (
   `length(uuid())` int(10) NOT NULL DEFAULT '0'
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1
 drop table t1;
-#------------------------------------------------------------------------
-# Tests for Bug#6760 and Bug#12689
-SET @row_count = 4;
-SET @sleep_time_per_result_row = 1;
-SET @max_acceptable_delay = 2;
-SET @@global.query_cache_size = 1024 * 64;
-DROP TEMPORARY TABLE IF EXISTS t_history;
-DROP TABLE IF EXISTS t1;
-CREATE TEMPORARY TABLE t_history (attempt SMALLINT,
-start_ts DATETIME, end_ts DATETIME,
-start_cached INTEGER, end_cached INTEGER);
-CREATE TABLE t1 (f1 BIGINT);
-INSERT INTO t_history
-SET attempt = 4 - 4 + 1, start_ts = NOW(),
-start_cached = 0;
-SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
-f1	SLEEP(@sleep_time_per_result_row)
-1	0
-1	0
-1	0
-1	0
-UPDATE t_history SET end_ts = NOW()
-WHERE attempt = 4 - 4 + 1;
-UPDATE t_history SET end_cached = 0
-WHERE attempt = 4 - 4 + 1;
-INSERT INTO t_history
-SET attempt = 4 - 3 + 1, start_ts = NOW(),
-start_cached = 0;
-SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
-f1	SLEEP(@sleep_time_per_result_row)
-1	0
-1	0
-1	0
-1	0
-UPDATE t_history SET end_ts = NOW()
-WHERE attempt = 4 - 3 + 1;
-UPDATE t_history SET end_cached = 0
-WHERE attempt = 4 - 3 + 1;
-INSERT INTO t_history
-SET attempt = 4 - 2 + 1, start_ts = NOW(),
-start_cached = 0;
-SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
-f1	SLEEP(@sleep_time_per_result_row)
-1	0
-1	0
-1	0
-1	0
-UPDATE t_history SET end_ts = NOW()
-WHERE attempt = 4 - 2 + 1;
-UPDATE t_history SET end_cached = 0
-WHERE attempt = 4 - 2 + 1;
-INSERT INTO t_history
-SET attempt = 4 - 1 + 1, start_ts = NOW(),
-start_cached = 0;
-SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
-f1	SLEEP(@sleep_time_per_result_row)
-1	0
-1	0
-1	0
-1	0
-UPDATE t_history SET end_ts = NOW()
-WHERE attempt = 4 - 1 + 1;
-UPDATE t_history SET end_cached = 0
-WHERE attempt = 4 - 1 + 1;
-# Test 1: Does the query with SLEEP need a reasonable time?
-SELECT COUNT(*) >= 4 - 1 INTO @aux1 FROM t_history
-WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
-BETWEEN 0 AND @max_acceptable_delay;
-SELECT @aux1 AS "Expect 1";
-Expect 1
-1
-# Test 2: Does the query with SLEEP need a reasonable time even in case
-#         of the non first execution?
-SELECT COUNT(*) >= 4 - 1 - 1 INTO @aux2 FROM t_history
-WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
-BETWEEN 0 AND @max_acceptable_delay
-AND attempt > 1;
-SELECT @aux2 AS "Expect 1";
-Expect 1
-1
-# Test 3: The query with SLEEP must be not cached.
-SELECT COUNT(*) = 4 INTO @aux3 FROM t_history
-WHERE end_cached = start_cached;
-SELECT @aux3 AS "Expect 1";
-Expect 1
-1
-DROP TABLE t1;
-DROP TEMPORARY TABLE t_history;
-SET @@global.query_cache_size = default;
 create table t1 select INET_ATON('255.255.0.1') as `a`;
 show create table t1;
 Table	Create Table

=== modified file 'mysql-test/r/grant2.result'
--- a/mysql-test/r/grant2.result	2009-02-27 08:03:47 +0000
+++ b/mysql-test/r/grant2.result	2009-10-30 05:06:10 +0000
@@ -443,3 +443,30 @@ DROP TABLE db1.t1, db1.t2;
 DROP USER mysqltest1@localhost;
 DROP DATABASE db1;
 End of 5.0 tests
+USE mysql;
+SELECT LEFT(CURRENT_USER(),INSTR(CURRENT_USER(),'@')-1) INTO @u;
+SELECT MID(CURRENT_USER(),INSTR(CURRENT_USER(),'@')+1)  INTO @h;
+SELECT password FROM user WHERE user=@u AND host=@h INTO @pwd;
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+user	host	password	insert_priv
+root	localhost		Y
+UPDATE user SET insert_priv='N' WHERE user=@u AND host=@h;
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+user	host	password	insert_priv
+root	localhost		N
+GRANT INSERT ON *.* TO CURRENT_USER();
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+user	host	password	insert_priv
+root	localhost		Y
+UPDATE user SET insert_priv='N' WHERE user=@u AND host=@h;
+GRANT INSERT ON *.* TO CURRENT_USER() IDENTIFIED BY 'keksdose';
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+user	host	password	insert_priv
+root	localhost	*0BB7188CF0DE9B403BA66E9DD810D82652D002EB	Y
+UPDATE user SET password=@pwd WHERE user=@u AND host=@h;
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+user	host	password	insert_priv
+root	localhost		Y
+FLUSH PRIVILEGES;
+USE test;
+End of 5.1 tests

=== modified file 'mysql-test/r/group_min_max.result'
--- a/mysql-test/r/group_min_max.result	2009-10-09 09:30:40 +0000
+++ b/mysql-test/r/group_min_max.result	2009-11-23 10:04:17 +0000
@@ -2501,6 +2501,17 @@ SELECT a, MAX(b) FROM t WHERE b > 0 AND
 a	MAX(b)
 2	1
 DROP TABLE t;
+#
+# Bug #48472: Loose index scan inappropriately chosen for some WHERE
+#             conditions
+# 
+CREATE TABLE t (a INT, b INT, INDEX (a,b));
+INSERT INTO t VALUES (2,0), (2,0), (2,1), (2,1);
+INSERT INTO t SELECT * FROM t;
+SELECT a, MAX(b) FROM t WHERE 0=b+0 GROUP BY a;
+a	MAX(b)
+2	0
+DROP TABLE t;
 End of 5.0 tests
 #
 # Bug #46607: Assertion failed: (cond_type == Item::FUNC_ITEM) results in

=== removed file 'mysql-test/r/have_big5.require'
--- a/mysql-test/r/have_big5.require	2003-12-24 12:59:48 +0000
+++ b/mysql-test/r/have_big5.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-big5_chinese_ci	big5	1	Yes	Yes	1

=== removed file 'mysql-test/r/have_cp1250_ch.require'
--- a/mysql-test/r/have_cp1250_ch.require	2005-03-03 10:15:37 +0000
+++ b/mysql-test/r/have_cp1250_ch.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-cp1250_czech_cs	cp1250	34		Yes	2

=== removed file 'mysql-test/r/have_cp1251.require'
--- a/mysql-test/r/have_cp1251.require	2007-06-28 17:34:54 +0000
+++ b/mysql-test/r/have_cp1251.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-cp1251_general_ci	cp1251	51	Yes		0

=== removed file 'mysql-test/r/have_cp866.require'
--- a/mysql-test/r/have_cp866.require	2007-06-28 17:34:54 +0000
+++ b/mysql-test/r/have_cp866.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-cp866_general_ci	cp866	36	Yes		0

=== removed file 'mysql-test/r/have_cp932.require'
--- a/mysql-test/r/have_cp932.require	2005-02-01 10:37:51 +0000
+++ b/mysql-test/r/have_cp932.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-cp932_japanese_ci	cp932	95	Yes	Yes	1

=== removed file 'mysql-test/r/have_eucjpms.require'
--- a/mysql-test/r/have_eucjpms.require	2005-02-01 10:37:51 +0000
+++ b/mysql-test/r/have_eucjpms.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-eucjpms_japanese_ci	eucjpms	97	Yes	Yes	1

=== removed file 'mysql-test/r/have_euckr.require'
--- a/mysql-test/r/have_euckr.require	2005-12-09 12:37:58 +0000
+++ b/mysql-test/r/have_euckr.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-euckr_korean_ci	euckr	19	Yes	Yes	1

=== removed file 'mysql-test/r/have_gb2312.require'
--- a/mysql-test/r/have_gb2312.require	2005-12-09 12:37:58 +0000
+++ b/mysql-test/r/have_gb2312.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-gb2312_chinese_ci	gb2312	24	Yes	Yes	1

=== removed file 'mysql-test/r/have_gbk.require'
--- a/mysql-test/r/have_gbk.require	2005-07-22 16:06:02 +0000
+++ b/mysql-test/r/have_gbk.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-gbk_chinese_ci	gbk	28	Yes	Yes	1

=== removed file 'mysql-test/r/have_koi8r.require'
--- a/mysql-test/r/have_koi8r.require	2007-06-28 17:34:54 +0000
+++ b/mysql-test/r/have_koi8r.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-koi8r_general_ci	koi8r	7	Yes		0

=== removed file 'mysql-test/r/have_latin2_ch.require'
--- a/mysql-test/r/have_latin2_ch.require	2006-03-20 12:28:25 +0000
+++ b/mysql-test/r/have_latin2_ch.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-latin2_czech_cs	latin2	2		Yes	4

=== removed file 'mysql-test/r/have_sjis.require'
--- a/mysql-test/r/have_sjis.require	2004-03-25 10:29:56 +0000
+++ b/mysql-test/r/have_sjis.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-sjis_japanese_ci	sjis	13	Yes	Yes	1

=== removed file 'mysql-test/r/have_tis620.require'
--- a/mysql-test/r/have_tis620.require	2003-12-25 16:11:01 +0000
+++ b/mysql-test/r/have_tis620.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-tis620_thai_ci	tis620	18	Yes	Yes	4

=== removed file 'mysql-test/r/have_ucs2.require'
--- a/mysql-test/r/have_ucs2.require	2003-06-02 12:19:06 +0000
+++ b/mysql-test/r/have_ucs2.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-ucs2_general_ci	ucs2	35	Yes	Yes	1

=== removed file 'mysql-test/r/have_ujis.require'
--- a/mysql-test/r/have_ujis.require	2003-09-19 10:18:19 +0000
+++ b/mysql-test/r/have_ujis.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-ujis_japanese_ci	ujis	12	Yes	Yes	1

=== removed file 'mysql-test/r/have_utf8.require'
--- a/mysql-test/r/have_utf8.require	2007-06-28 17:34:54 +0000
+++ b/mysql-test/r/have_utf8.require	1970-01-01 00:00:00 +0000
@@ -1,2 +0,0 @@
-Collation	Charset	Id	Default	Compiled	Sortlen
-utf8_general_ci	utf8	33	Yes	Yes	1

=== modified file 'mysql-test/r/innodb-autoinc.result'
--- a/mysql-test/r/innodb-autoinc.result	2009-12-03 11:34:11 +0000
+++ b/mysql-test/r/innodb-autoinc.result	2010-01-15 15:27:55 +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
@@ -897,7 +897,7 @@ d1
 4
 DROP TABLE t1;
 SET @@SESSION.AUTO_INCREMENT_INCREMENT=1, @@SESSION.AUTO_INCREMENT_OFFSET=1;
-SHOW VARIABLES LIKE "%auto_inc%";
+SHOW VARIABLES LIKE "auto_inc%";
 Variable_name	Value
 auto_increment_increment	1
 auto_increment_offset	1
@@ -1126,3 +1126,61 @@ SELECT * FROM T1;
 c1	c2
 10	0
 DROP TABLE T1;
+CREATE TABLE T1(C1 DOUBLE AUTO_INCREMENT KEY, C2 CHAR(10)) ENGINE=InnoDB;
+INSERT INTO T1(C1, C2) VALUES (1, 'innodb'), (3, 'innodb');
+INSERT INTO T1(C2) VALUES ('innodb');
+SHOW CREATE TABLE T1;
+Table	Create Table
+T1	CREATE TABLE `T1` (
+  `C1` double NOT NULL AUTO_INCREMENT,
+  `C2` char(10) DEFAULT NULL,
+  PRIMARY KEY (`C1`)
+) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
+DROP TABLE T1;
+CREATE TABLE T1(C1 FLOAT AUTO_INCREMENT KEY, C2 CHAR(10)) ENGINE=InnoDB;
+INSERT INTO T1(C1, C2) VALUES (1, 'innodb'), (3, 'innodb');
+INSERT INTO T1(C2) VALUES ('innodb');
+SHOW CREATE TABLE T1;
+Table	Create Table
+T1	CREATE TABLE `T1` (
+  `C1` float NOT NULL AUTO_INCREMENT,
+  `C2` char(10) DEFAULT NULL,
+  PRIMARY KEY (`C1`)
+) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
+DROP TABLE T1;
+CREATE TABLE t1 (c1 INT AUTO_INCREMENT PRIMARY KEY) ENGINE=InnoDB;
+INSERT INTO t1 SET c1 = 1;
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` int(11) NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
+INSERT INTO t1 SET c1 = 2;
+INSERT INTO t1 SET c1 = -1;
+SELECT * FROM t1;
+c1
+-1
+1
+2
+INSERT INTO t1 SET c1 = -1;
+Got one of the listed errors
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` int(11) NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
+REPLACE INTO t1 VALUES (-1);
+SELECT * FROM t1;
+c1
+-1
+1
+2
+SHOW CREATE TABLE t1;
+Table	Create Table
+t1	CREATE TABLE `t1` (
+  `c1` int(11) NOT NULL AUTO_INCREMENT,
+  PRIMARY KEY (`c1`)
+) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
+DROP TABLE t1;

=== modified file 'mysql-test/r/innodb.result'
--- a/mysql-test/r/innodb.result	2009-11-13 21:26:08 +0000
+++ b/mysql-test/r/innodb.result	2009-12-27 13:54:41 +0000
@@ -3160,15 +3160,6 @@ ALTER TABLE t2 MODIFY a INT NOT NULL;
 ERROR HY000: Error on rename of '#sql-temporary' to './test/t2' (errno: 150)
 DELETE FROM t1;
 DROP TABLE t2,t1;
-CREATE TABLE t1 (a VARCHAR(5) COLLATE utf8_unicode_ci PRIMARY KEY)
-ENGINE=InnoDB;
-INSERT INTO t1 VALUES (0xEFBCA4EFBCA4EFBCA4);
-DELETE FROM t1;
-INSERT INTO t1 VALUES ('DDD');
-SELECT * FROM t1;
-a
-DDD
-DROP TABLE t1;
 CREATE TABLE t1 (id int PRIMARY KEY AUTO_INCREMENT) ENGINE=InnoDB
 AUTO_INCREMENT=42;
 INSERT INTO t1 VALUES (0),(347),(0);

=== modified file 'mysql-test/r/innodb_lock_wait_timeout_1.result'
--- a/mysql-test/r/innodb_lock_wait_timeout_1.result	2009-11-03 17:45:52 +0000
+++ b/mysql-test/r/innodb_lock_wait_timeout_1.result	2009-11-12 11:43:33 +0000
@@ -48,6 +48,24 @@ commit;
 set autocommit=default;
 drop table t1;
 #
+# Bug #37183 insert ignore into .. select ... hangs 
+#            after deadlock was encountered
+#
+create table t1(id int primary key,v int)engine=innodb;
+insert into t1 values (1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7);
+create table t2 like t1;
+begin;
+update t1 set v=id*2 where id=1;
+begin;
+update t1 set v=id*2 where id=2;
+update t1 set v=id*2 where id=2;
+ERROR HY000: Lock wait timeout exceeded; try restarting transaction
+insert ignore into t2 select * from t1 where id=1;
+ERROR HY000: Lock wait timeout exceeded; try restarting transaction
+rollback;
+rollback;
+drop table t1, t2;
+#
 # Bug#41756 Strange error messages about locks from InnoDB
 #
 drop table if exists t1;

=== modified file 'mysql-test/r/innodb_mysql.result'
--- a/mysql-test/r/innodb_mysql.result	2009-12-03 11:19:05 +0000
+++ b/mysql-test/r/innodb_mysql.result	2010-01-15 15:27:55 +0000
@@ -2251,4 +2251,26 @@ c >= '2009-10-09 00:00:00.001' AND c <=
 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;
+#
+# Bug #46175: NULL read_view and consistent read assertion
+#
+CREATE TABLE t1(a CHAR(13),KEY(a)) ENGINE=innodb;
+CREATE TABLE t2(b DATETIME,KEY(b)) ENGINE=innodb;
+INSERT INTO t1 VALUES (),();
+INSERT INTO t2 VALUES (),();
+CREATE OR REPLACE VIEW v1 AS SELECT 1 FROM t2 
+WHERE b =(SELECT a FROM t1 LIMIT 1);
+CREATE PROCEDURE p1(num INT)
+BEGIN
+DECLARE i INT DEFAULT 0;
+REPEAT
+SHOW CREATE VIEW v1;
+SET i:=i+1;
+UNTIL i>num END REPEAT;
+END|
+# Should not crash
+# Should not crash
+DROP PROCEDURE p1;
+DROP VIEW v1;
+DROP TABLE t1,t2;
 End of 5.1 tests

=== added file 'mysql-test/r/innodb_utf8.result'
--- a/mysql-test/r/innodb_utf8.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/innodb_utf8.result	2009-12-27 13:54:41 +0000
@@ -0,0 +1,10 @@
+drop table if exists t1;
+CREATE TABLE t1 (a VARCHAR(5) COLLATE utf8_unicode_ci PRIMARY KEY)
+ENGINE=InnoDB;
+INSERT INTO t1 VALUES (0xEFBCA4EFBCA4EFBCA4);
+DELETE FROM t1;
+INSERT INTO t1 VALUES ('DDD');
+SELECT * FROM t1;
+a
+DDD
+DROP TABLE t1;

=== modified file 'mysql-test/r/mysql.result'
--- a/mysql-test/r/mysql.result	2009-07-31 23:43:46 +0000
+++ b/mysql-test/r/mysql.result	2009-11-27 14:41:45 +0000
@@ -229,5 +229,4 @@ a:  b
   </row>
 </resultset>
 drop table t1;
-
-End of tests
+End of 5.0 tests

=== modified file 'mysql-test/r/mysqltest.result'
--- a/mysql-test/r/mysqltest.result	2009-10-08 09:30:03 +0000
+++ b/mysql-test/r/mysqltest.result	2010-01-11 13:15:28 +0000
@@ -1,3 +1,4 @@
+SET GLOBAL max_connections = 1000;
 select 0 as "before_use_test" ;
 before_use_test
 0

=== modified file 'mysql-test/r/olap.result'
--- a/mysql-test/r/olap.result	2009-10-30 15:59:06 +0000
+++ b/mysql-test/r/olap.result	2009-12-08 09:26:11 +0000
@@ -753,4 +753,16 @@ b
 100
 NULL
 DROP TABLE t1, t2;
+#
+# Bug #48475: DISTINCT is ignored with GROUP BY WITH ROLLUP
+#             and only const tables
+CREATE TABLE t1 (a INT);
+CREATE TABLE t2 (b INT);
+INSERT INTO t1 VALUES (1);
+INSERT INTO t2 VALUES (1);
+SELECT DISTINCT b FROM t1, t2 GROUP BY a, b WITH ROLLUP;
+b
+1
+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-10-14 14:30:39 +0000
+++ b/mysql-test/r/order_by.result	2009-11-10 08:58:43 +0000
@@ -1444,6 +1444,27 @@ FROM t3;
 2
 NULL
 DROP TABLE t1, t2, t3;
+#
+# Bug #42760: Select doesn't return desired results when we have null
+# values
+#
+CREATE TABLE t1 (
+a INT,
+c INT,
+UNIQUE KEY a_c (a,c),
+KEY (a));
+INSERT INTO t1 VALUES (1, 10), (2, NULL);
+# Must use ref-or-null on the a_c index
+EXPLAIN
+SELECT 1 AS col FROM t1 WHERE a=2 AND (c=10 OR c IS NULL) ORDER BY c;
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+1	SIMPLE	t1	ref_or_null	a_c,a	a_c	10	const,const	1	Using where
+# Must return 1 row
+SELECT 1 AS col FROM t1 WHERE a=2 AND (c=10 OR c IS NULL) ORDER BY c;
+col
+1
+DROP TABLE t1;
+End of 5.0 tests
 CREATE TABLE t2 (a varchar(32), b int(11), c float, d double, 
 UNIQUE KEY a (a,b,c), KEY b (b), KEY c (c));
 CREATE TABLE t1 (a varchar(32), b char(3), UNIQUE KEY a (a,b), KEY b (b));

=== modified file 'mysql-test/r/partition.result'
--- a/mysql-test/r/partition.result	2009-12-03 11:19:05 +0000
+++ b/mysql-test/r/partition.result	2010-01-15 15:27:55 +0000
@@ -1,4 +1,10 @@
 drop table if exists t1, t2;
+CREATE TABLE t1 (a INT, b INT)
+PARTITION BY LIST (a)
+SUBPARTITION BY HASH (b)
+(PARTITION p1 VALUES IN (1));
+ALTER TABLE t1 ADD COLUMN c INT;
+DROP TABLE t1;
 CREATE TABLE t1 (
 a int NOT NULL,
 b int NOT NULL);
@@ -50,6 +56,13 @@ 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 NOT NULL, b varchar(5) NOT NULL)
+default charset=utf8
+partition by list (a)
+subpartition by key (b)
+(partition p0 values in (1),
+partition p1 values in (2));
+drop table t1;
 create table t1 (a int, b int, key(a))
 partition by list (a)
 ( partition p0 values in (1),
@@ -2045,10 +2058,15 @@ DROP TABLE t1;
 #
 # Bug #45807: crash accessing partitioned table and sql_mode 
 #   contains ONLY_FULL_GROUP_BY
+# Bug#46923: select count(*) from partitioned table fails with
+# ONLY_FULL_GROUP_BY
 #
 SET SESSION SQL_MODE='ONLY_FULL_GROUP_BY';
 CREATE TABLE t1(id INT,KEY(id)) ENGINE=MYISAM 
 PARTITION BY HASH(id) PARTITIONS 2;
+SELECT COUNT(*) FROM t1;
+COUNT(*)
+0
 DROP TABLE t1;
 SET SESSION SQL_MODE=DEFAULT;
 #

=== modified file 'mysql-test/r/query_cache.result'
--- a/mysql-test/r/query_cache.result	2009-12-03 11:19:05 +0000
+++ b/mysql-test/r/query_cache.result	2010-01-11 13:15:28 +0000
@@ -1302,6 +1302,15 @@ drop procedure f3;
 drop procedure f4;
 drop table t1;
 set GLOBAL query_cache_size=0;
+set GLOBAL query_cache_size=100000;
+set SESSION query_cache_size=10000;
+ERROR HY000: Variable 'query_cache_size' is a GLOBAL variable and should be set with SET GLOBAL
+set global query_cache_limit=100;
+set global query_cache_size=100;
+set global query_cache_type=demand;
+set GLOBAL query_cache_type=default;
+set GLOBAL query_cache_limit=default;
+set GLOBAL query_cache_size=default;
 End of 4.1 tests
 SET GLOBAL query_cache_size=102400;
 create table t1(a int);
@@ -1707,6 +1716,95 @@ Variable_name	Value
 Qcache_hits	2
 DROP TABLE t1;
 SET GLOBAL query_cache_size= default;
+#------------------------------------------------------------------------
+# Tests for Bug#6760 and Bug#12689
+SET @row_count = 4;
+SET @sleep_time_per_result_row = 1;
+SET @max_acceptable_delay = 2;
+SET @@global.query_cache_size = 1024 * 64;
+DROP TEMPORARY TABLE IF EXISTS t_history;
+DROP TABLE IF EXISTS t1;
+CREATE TEMPORARY TABLE t_history (attempt SMALLINT,
+start_ts DATETIME, end_ts DATETIME,
+start_cached INTEGER, end_cached INTEGER);
+CREATE TABLE t1 (f1 BIGINT);
+INSERT INTO t_history
+SET attempt = 4 - 4 + 1, start_ts = NOW(),
+start_cached = 0;
+SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
+f1	SLEEP(@sleep_time_per_result_row)
+1	0
+1	0
+1	0
+1	0
+UPDATE t_history SET end_ts = NOW()
+WHERE attempt = 4 - 4 + 1;
+UPDATE t_history SET end_cached = 0
+WHERE attempt = 4 - 4 + 1;
+INSERT INTO t_history
+SET attempt = 4 - 3 + 1, start_ts = NOW(),
+start_cached = 0;
+SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
+f1	SLEEP(@sleep_time_per_result_row)
+1	0
+1	0
+1	0
+1	0
+UPDATE t_history SET end_ts = NOW()
+WHERE attempt = 4 - 3 + 1;
+UPDATE t_history SET end_cached = 0
+WHERE attempt = 4 - 3 + 1;
+INSERT INTO t_history
+SET attempt = 4 - 2 + 1, start_ts = NOW(),
+start_cached = 0;
+SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
+f1	SLEEP(@sleep_time_per_result_row)
+1	0
+1	0
+1	0
+1	0
+UPDATE t_history SET end_ts = NOW()
+WHERE attempt = 4 - 2 + 1;
+UPDATE t_history SET end_cached = 0
+WHERE attempt = 4 - 2 + 1;
+INSERT INTO t_history
+SET attempt = 4 - 1 + 1, start_ts = NOW(),
+start_cached = 0;
+SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
+f1	SLEEP(@sleep_time_per_result_row)
+1	0
+1	0
+1	0
+1	0
+UPDATE t_history SET end_ts = NOW()
+WHERE attempt = 4 - 1 + 1;
+UPDATE t_history SET end_cached = 0
+WHERE attempt = 4 - 1 + 1;
+# Test 1: Does the query with SLEEP need a reasonable time?
+SELECT COUNT(*) >= 4 - 1 INTO @aux1 FROM t_history
+WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
+BETWEEN 0 AND @max_acceptable_delay;
+SELECT @aux1 AS "Expect 1";
+Expect 1
+1
+# Test 2: Does the query with SLEEP need a reasonable time even in case
+#         of the non first execution?
+SELECT COUNT(*) >= 4 - 1 - 1 INTO @aux2 FROM t_history
+WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
+BETWEEN 0 AND @max_acceptable_delay
+AND attempt > 1;
+SELECT @aux2 AS "Expect 1";
+Expect 1
+1
+# Test 3: The query with SLEEP must be not cached.
+SELECT COUNT(*) = 4 INTO @aux3 FROM t_history
+WHERE end_cached = start_cached;
+SELECT @aux3 AS "Expect 1";
+Expect 1
+1
+DROP TABLE t1;
+DROP TEMPORARY TABLE t_history;
+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'));

=== modified file 'mysql-test/r/query_cache_notembedded.result'
--- a/mysql-test/r/query_cache_notembedded.result	2009-02-13 19:32:24 +0000
+++ b/mysql-test/r/query_cache_notembedded.result	2010-01-11 13:15:28 +0000
@@ -382,3 +382,55 @@ set GLOBAL query_cache_type=default;
 set GLOBAL query_cache_limit=default;
 set GLOBAL query_cache_min_res_unit=default;
 set GLOBAL query_cache_size=default;
+drop table if exists t1|
+create table t1 (
+id   char(16) not null default '',
+data int not null
+)|
+drop procedure if exists bug3583|
+drop procedure if exists bug3583|
+create procedure bug3583()
+begin
+declare c int;
+select * from t1;
+select count(*) into c from t1;
+select c;
+end|
+insert into t1 values ("x", 3), ("y", 5)|
+set @x = @@query_cache_size|
+set global query_cache_size = 10*1024*1024|
+flush status|
+flush query cache|
+show status like 'Qcache_hits'|
+Variable_name	Value
+Qcache_hits	0
+call bug3583()|
+id	data
+x	3
+y	5
+c
+2
+show status like 'Qcache_hits'|
+Variable_name	Value
+Qcache_hits	0
+call bug3583()|
+id	data
+x	3
+y	5
+c
+2
+call bug3583()|
+id	data
+x	3
+y	5
+c
+2
+show status like 'Qcache_hits'|
+Variable_name	Value
+Qcache_hits	2
+set global query_cache_size = @x|
+flush status|
+flush query cache|
+delete from t1|
+drop procedure bug3583|
+drop table t1|

=== modified file 'mysql-test/r/range.result'
--- a/mysql-test/r/range.result	2009-11-02 12:24:07 +0000
+++ b/mysql-test/r/range.result	2009-12-08 09:26:11 +0000
@@ -1603,4 +1603,54 @@ SELECT str_to_date('', '%Y-%m-%d');
 str_to_date('', '%Y-%m-%d')
 0000-00-00
 DROP TABLE t1, t2;
+#
+# Bug#48459: valgrind errors with query using 'Range checked for each 
+# record'
+#
+CREATE TABLE t1 (
+a INT,
+b CHAR(2),
+c INT,
+d INT,
+KEY ( c ),
+KEY ( d, a, b ( 2 ) ),
+KEY ( b ( 1 ) )
+);
+INSERT INTO t1 VALUES ( NULL, 'a', 1, 2 ), ( NULL, 'a', 1, 2 ),
+( 1,    'a', 1, 2 ), ( 1,    'a', 1, 2 );
+CREATE TABLE t2 (
+a INT,
+c INT,
+e INT,
+KEY ( e )
+);
+INSERT INTO t2 VALUES ( 1, 1, NULL ), ( 1, 1, NULL );
+# Should not give Valgrind warnings
+SELECT 1
+FROM t1, t2
+WHERE t1.d <> '1' AND t1.b > '1'
+AND t1.a = t2.a AND t1.c = t2.c;
+1
+1
+1
+1
+1
+DROP TABLE t1, t2;
+#
+# Bug #48665: sql-bench's insert test fails due to wrong result
+#
+CREATE TABLE t1 (a INT, b INT, PRIMARY KEY (a));
+INSERT INTO t1 VALUES (0,0), (1,1);
+EXPLAIN 
+SELECT * FROM t1 FORCE INDEX (PRIMARY) 
+WHERE (a>=1 AND a<=2) OR (a>=4 AND a<=5) OR (a>=0 AND a <=10);
+id	select_type	table	type	possible_keys	key	key_len	ref	rows	Extra
+@	@	@	range	@	@	@	@	@	@
+# Should return 2 rows
+SELECT * FROM t1 FORCE INDEX (PRIMARY) 
+WHERE (a>=1 AND a<=2) OR (a>=4 AND a<=5) OR (a>=0 AND a <=10);
+a	b
+0	0
+1	1
+DROP TABLE t1;
 End of 5.1 tests

=== modified file 'mysql-test/r/select.result'
--- a/mysql-test/r/select.result	2009-12-03 11:19:05 +0000
+++ b/mysql-test/r/select.result	2010-01-15 15:27:55 +0000
@@ -4426,6 +4426,20 @@ ROW(a,a) <=> ROW((SELECT 1 FROM t1 WHERE
 INTO @var0;
 ERROR 21000: Subquery returns more than 1 row
 DROP TABLE t1;
+#
+# Bug #48458: simple query tries to allocate enormous amount of
+#   memory
+#
+CREATE TABLE t1(a INT NOT NULL, b YEAR);
+INSERT INTO t1 VALUES ();
+Warnings:
+Warning	1364	Field 'a' doesn't have a default value
+CREATE TABLE t2(c INT);
+# Should not err out because of out-of-memory
+SELECT 1 FROM t2 JOIN t1 ON 1=1
+WHERE a != '1' AND NOT a >= b OR NOT ROW(b,a )<> ROW(a,a);
+1
+DROP TABLE t1,t2;
 End of 5.0 tests
 create table t1(a INT, KEY (a));
 INSERT INTO t1 VALUES (1),(2),(3),(4),(5);
@@ -4576,4 +4590,47 @@ field2
 15:13:38
 drop table A,AA,B,BB;
 #end of test for bug#45266
+# 
+# BUG#48052: Valgrind warning - uninitialized value in init_read_record()
+# 
+CREATE TABLE t1 (
+pk int(11) NOT NULL,
+i int(11) DEFAULT NULL,
+v varchar(1) DEFAULT NULL,
+PRIMARY KEY (pk)
+);
+INSERT INTO t1 VALUES (2,7,'m');
+INSERT INTO t1 VALUES (3,9,'m');
+SELECT  v
+FROM t1
+WHERE NOT pk > 0  
+HAVING v <= 't' 
+ORDER BY pk;
+v
+DROP TABLE t1;
+#
+# Bug#49489 Uninitialized cache led to a wrong result.
+#
+CREATE TABLE t1(c1 DOUBLE(5,4));
+INSERT INTO t1 VALUES (9.1234);
+SELECT * FROM t1 WHERE c1 < 9.12345;
+c1
+9.1234
+DROP TABLE t1;
+# End of test for bug#49489.
+#
+# Bug #49517: Inconsistent behavior while using 
+# NULLable BIGINT and INT columns in comparison
+#
+CREATE TABLE t1(a BIGINT UNSIGNED NOT NULL, b BIGINT NULL, c INT NULL);
+INSERT INTO t1 VALUES(105, NULL, NULL);
+SELECT * FROM t1 WHERE b < 102;
+a	b	c
+SELECT * FROM t1 WHERE c < 102;
+a	b	c
+SELECT * FROM t1 WHERE 102 < b;
+a	b	c
+SELECT * FROM t1 WHERE 102 < c;
+a	b	c
+DROP TABLE t1;
 End of 5.1 tests

=== modified file 'mysql-test/r/show_check.result'
--- a/mysql-test/r/show_check.result	2009-03-06 14:56:17 +0000
+++ b/mysql-test/r/show_check.result	2009-12-15 09:03:24 +0000
@@ -1454,4 +1454,10 @@ GRANT PROCESS ON *.* TO test_u@localhost
 SHOW ENGINE MYISAM MUTEX;
 SHOW ENGINE MYISAM STATUS;
 DROP USER test_u@localhost;
+#
+# Bug #48985: show create table crashes if previous access to the table
+#    was killed
+#
+SHOW CREATE TABLE non_existent;
+ERROR 70100: Query execution was interrupted
 End of 5.1 tests

=== modified file 'mysql-test/r/sp-destruct.result'
--- a/mysql-test/r/sp-destruct.result	2008-04-08 14:51:26 +0000
+++ b/mysql-test/r/sp-destruct.result	2009-11-21 11:18:21 +0000
@@ -1,3 +1,4 @@
+call mtr.add_suppression("Column count of mysql.proc is wrong. Expected 20, found 19. The table is probably corrupted");
 use test;
 drop procedure if exists bug14233;
 drop function if exists bug14233;
@@ -11,11 +12,13 @@ create table t1 (id int);
 create trigger t1_ai after insert on t1 for each row call bug14233();
 alter table mysql.proc drop type;
 call bug14233();
-ERROR HY000: Failed to load routine test.bug14233. The table mysql.proc is missing, corrupt, or contains bad data (internal code -5)
+ERROR HY000: Column count of mysql.proc is wrong. Expected 20, found 19. The table is probably corrupted
 create view v1 as select bug14233_f();
-ERROR HY000: Failed to load routine test.bug14233_f. The table mysql.proc is missing, corrupt, or contains bad data (internal code -5)
+ERROR HY000: Column count of mysql.proc is wrong. Expected 20, found 19. The table is probably corrupted
 insert into t1 values (0);
-ERROR HY000: Failed to load routine test.bug14233. The table mysql.proc is missing, corrupt, or contains bad data (internal code -5)
+ERROR HY000: Column count of mysql.proc is wrong. Expected 20, found 19. The table is probably corrupted
+show procedure status;
+ERROR HY000: Column count of mysql.proc is wrong. Expected 20, found 19. The table is probably corrupted
 flush table mysql.proc;
 call bug14233();
 ERROR HY000: Incorrect information in file: './mysql/proc.frm'
@@ -88,3 +91,28 @@ show procedure status where db=DATABASE(
 Db	Name	Type	Definer	Modified	Created	Security_type	Comment	character_set_client	collation_connection	Database Collation
 show function status where db=DATABASE();
 Db	Name	Type	Definer	Modified	Created	Security_type	Comment	character_set_client	collation_connection	Database Collation
+DROP TABLE IF EXISTS proc_backup;
+DROP PROCEDURE IF EXISTS p1;
+# Backup the proc table
+RENAME TABLE mysql.proc TO proc_backup;
+CREATE TABLE mysql.proc LIKE proc_backup;
+FLUSH TABLE mysql.proc;
+# Test with a valid table.
+CREATE PROCEDURE p1()
+SET @foo = 10;
+CALL p1();
+SHOW PROCEDURE STATUS;
+Db	Name	Type	Definer	Modified	Created	Security_type	Comment	character_set_client	collation_connection	Database Collation
+test	p1	PROCEDURE	root@localhost	0000-00-00 00:00:00	0000-00-00 00:00:00	DEFINER		latin1	latin1_swedish_ci	latin1_swedish_ci
+# Modify a field of the table.
+ALTER TABLE mysql.proc MODIFY comment CHAR (32);
+CREATE PROCEDURE p2()
+SET @foo = 10;
+ERROR HY000: Cannot load from mysql.proc. The table is probably corrupted
+# Procedure loaded from the cache
+CALL p1();
+SHOW PROCEDURE STATUS;
+ERROR HY000: Cannot load from mysql.proc. The table is probably corrupted
+DROP TABLE mysql.proc;
+RENAME TABLE proc_backup TO mysql.proc;
+FLUSH TABLE mysql.proc;

=== modified file 'mysql-test/r/sp-security.result'
--- a/mysql-test/r/sp-security.result	2009-03-06 14:56:17 +0000
+++ b/mysql-test/r/sp-security.result	2009-11-27 16:10:28 +0000
@@ -510,4 +510,60 @@ DROP USER mysqltest_u1@localhost;
 DROP PROCEDURE p_suid;
 DROP FUNCTION f_suid;
 DROP TABLE t1;
+#
+# Bug #48872 : Privileges for stored functions ignored if function name 
+#  is mixed case
+#
+CREATE DATABASE B48872;
+USE B48872;
+CREATE TABLE `TestTab` (id INT);
+INSERT INTO `TestTab` VALUES (1),(2);
+CREATE FUNCTION `f_Test`() RETURNS INT RETURN 123;
+CREATE FUNCTION `f_Test_denied`() RETURNS INT RETURN 123;
+CREATE USER 'tester';
+CREATE USER 'Tester';
+GRANT SELECT ON TABLE `TestTab` TO 'tester';
+GRANT EXECUTE ON FUNCTION `f_Test` TO 'tester';
+GRANT EXECUTE ON FUNCTION `f_Test_denied` TO 'Tester';
+SELECT f_Test();
+f_Test()
+123
+SELECT * FROM TestTab;
+id
+1
+2
+SELECT * FROM TestTab;
+id
+1
+2
+SELECT `f_Test`();
+`f_Test`()
+123
+SELECT `F_TEST`();
+`F_TEST`()
+123
+SELECT f_Test();
+f_Test()
+123
+SELECT F_TEST();
+F_TEST()
+123
+SELECT * FROM TestTab;
+SELECT `f_Test`();
+SELECT `F_TEST`();
+SELECT f_Test();
+SELECT F_TEST();
+SELECT `f_Test_denied`();
+`f_Test_denied`()
+123
+SELECT `F_TEST_DENIED`();
+`F_TEST_DENIED`()
+123
+DROP TABLE `TestTab`;
+DROP FUNCTION `f_Test`;
+DROP FUNCTION `f_Test_denied`;
+USE test;
+DROP USER 'tester';
+DROP USER 'Tester';
+DROP DATABASE B48872;
 End of 5.0 tests.

=== modified file 'mysql-test/r/sp.result'
--- a/mysql-test/r/sp.result	2009-10-23 13:54:58 +0000
+++ b/mysql-test/r/sp.result	2009-11-13 01:03:26 +0000
@@ -6979,6 +6979,64 @@ CALL p1;
 ERROR 42S22: Unknown column 'A.b' in 'IN/ALL/ANY subquery'
 DROP PROCEDURE p1;
 DROP TABLE t1, t2;
+#
+# Bug#47627: SET @@{global.session}.local_variable in stored routine causes crash
+# Bug#48626: Crash or lost connection using SET for declared variables with @@
+#
+DROP PROCEDURE IF EXISTS p1;
+DROP PROCEDURE IF EXISTS p2;
+DROP PROCEDURE IF EXISTS p3;
+CREATE PROCEDURE p1()
+BEGIN
+DECLARE v INT DEFAULT 0;
+SET @@SESSION.v= 10;
+END//
+ERROR HY000: Unknown system variable 'v'
+CREATE PROCEDURE p2()
+BEGIN
+DECLARE v INT DEFAULT 0;
+SET v= 10;
+END//
+call p2()//
+CREATE PROCEDURE p3()
+BEGIN
+DECLARE v INT DEFAULT 0;
+SELECT @@SESSION.v;
+END//
+ERROR HY000: Unknown system variable 'v'
+CREATE PROCEDURE p4()
+BEGIN
+DECLARE v INT DEFAULT 0;
+SET @@GLOBAL.v= 10;
+END//
+ERROR HY000: Unknown system variable 'v'
+CREATE PROCEDURE p5()
+BEGIN
+DECLARE init_connect INT DEFAULT 0;
+SET init_connect= 10;
+SET @@GLOBAL.init_connect= 'SELECT 1';
+SET @@SESSION.IDENTITY= 1;
+SELECT @@SESSION.IDENTITY;
+SELECT @@GLOBAL.init_connect;
+SELECT init_connect;
+END//
+CREATE PROCEDURE p6()
+BEGIN
+DECLARE v INT DEFAULT 0;
+SET @@v= 0;
+END//
+ERROR HY000: Unknown system variable 'v'
+SET @old_init_connect= @@GLOBAL.init_connect;
+CALL p5();
+@@SESSION.IDENTITY
+1
+@@GLOBAL.init_connect
+SELECT 1
+init_connect
+10
+SET @@GLOBAL.init_connect= @old_init_connect;
+DROP PROCEDURE p2;
+DROP PROCEDURE p5;
 # ------------------------------------------------------------------
 # -- End of 5.1 tests
 # ------------------------------------------------------------------

=== modified file 'mysql-test/r/sp_notembedded.result'
--- a/mysql-test/r/sp_notembedded.result	2009-10-13 18:21:42 +0000
+++ b/mysql-test/r/sp_notembedded.result	2010-01-11 13:15:28 +0000
@@ -25,58 +25,6 @@ call bug4902_2()|
 show warnings|
 Level	Code	Message
 drop procedure bug4902_2|
-drop table if exists t1|
-create table t1 (
-id   char(16) not null default '',
-data int not null
-)|
-drop procedure if exists bug3583|
-drop procedure if exists bug3583|
-create procedure bug3583()
-begin
-declare c int;
-select * from t1;
-select count(*) into c from t1;
-select c;
-end|
-insert into t1 values ("x", 3), ("y", 5)|
-set @x = @@query_cache_size|
-set global query_cache_size = 10*1024*1024|
-flush status|
-flush query cache|
-show status like 'Qcache_hits'|
-Variable_name	Value
-Qcache_hits	0
-call bug3583()|
-id	data
-x	3
-y	5
-c
-2
-show status like 'Qcache_hits'|
-Variable_name	Value
-Qcache_hits	0
-call bug3583()|
-id	data
-x	3
-y	5
-c
-2
-call bug3583()|
-id	data
-x	3
-y	5
-c
-2
-show status like 'Qcache_hits'|
-Variable_name	Value
-Qcache_hits	2
-set global query_cache_size = @x|
-flush status|
-flush query cache|
-delete from t1|
-drop procedure bug3583|
-drop table t1|
 drop procedure if exists bug6807|
 create procedure bug6807()
 begin

=== modified file 'mysql-test/r/trigger.result'
--- a/mysql-test/r/trigger.result	2009-06-22 12:51:33 +0000
+++ b/mysql-test/r/trigger.result	2010-01-12 08:19:48 +0000
@@ -1448,33 +1448,6 @@ isave
 1
 2
 drop table t1, t2, t3;
-CREATE TABLE t1 (id INTEGER);
-CREATE TABLE t2 (id INTEGER);
-INSERT INTO t2 VALUES (1),(2);
-CREATE TRIGGER t1_test AFTER INSERT ON t1 FOR EACH ROW 
-INSERT INTO t2 VALUES (new.id);
-SELECT GET_LOCK('B26162',120);
-GET_LOCK('B26162',120)
-1
-SELECT 'rl_acquirer', GET_LOCK('B26162',120), id FROM t2 WHERE id = 1;
-SET SESSION LOW_PRIORITY_UPDATES=1;
-SET GLOBAL LOW_PRIORITY_UPDATES=1;
-INSERT INTO t1 VALUES (5);
-SELECT 'rl_contender', id FROM t2 WHERE id > 1;
-SELECT RELEASE_LOCK('B26162');
-RELEASE_LOCK('B26162')
-1
-rl_acquirer	GET_LOCK('B26162',120)	id
-rl_acquirer	1	1
-SELECT RELEASE_LOCK('B26162');
-RELEASE_LOCK('B26162')
-1
-rl_contender	id
-rl_contender	2
-DROP TRIGGER t1_test;
-DROP TABLE t1,t2;
-SET SESSION LOW_PRIORITY_UPDATES=DEFAULT;
-SET GLOBAL LOW_PRIORITY_UPDATES=DEFAULT;
 
 Bug#28502 Triggers that update another innodb table will block
 on X lock unnecessarily

=== modified file 'mysql-test/r/trigger_notembedded.result'
--- a/mysql-test/r/trigger_notembedded.result	2009-09-17 11:33:23 +0000
+++ b/mysql-test/r/trigger_notembedded.result	2010-01-12 08:19:48 +0000
@@ -445,6 +445,33 @@ DROP TABLE t2;
 DROP TABLE t1;
 DROP DATABASE mysqltest_db1;
 USE test;
+CREATE TABLE t1 (id INTEGER);
+CREATE TABLE t2 (id INTEGER);
+INSERT INTO t2 VALUES (1),(2);
+CREATE TRIGGER t1_test AFTER INSERT ON t1 FOR EACH ROW 
+INSERT INTO t2 VALUES (new.id);
+SELECT GET_LOCK('B26162',120);
+GET_LOCK('B26162',120)
+1
+SELECT 'rl_acquirer', GET_LOCK('B26162',120), id FROM t2 WHERE id = 1;
+SET SESSION LOW_PRIORITY_UPDATES=1;
+SET GLOBAL LOW_PRIORITY_UPDATES=1;
+INSERT INTO t1 VALUES (5);
+SELECT 'rl_contender', id FROM t2 WHERE id > 1;
+SELECT RELEASE_LOCK('B26162');
+RELEASE_LOCK('B26162')
+1
+rl_acquirer	GET_LOCK('B26162',120)	id
+rl_acquirer	1	1
+SELECT RELEASE_LOCK('B26162');
+RELEASE_LOCK('B26162')
+1
+rl_contender	id
+rl_contender	2
+DROP TRIGGER t1_test;
+DROP TABLE t1,t2;
+SET SESSION LOW_PRIORITY_UPDATES=DEFAULT;
+SET GLOBAL LOW_PRIORITY_UPDATES=DEFAULT;
 End of 5.0 tests.
 drop table if exists t1;
 create table t1 (i int);

=== modified file 'mysql-test/r/type_newdecimal.result'
--- a/mysql-test/r/type_newdecimal.result	2009-11-02 11:21:39 +0000
+++ b/mysql-test/r/type_newdecimal.result	2009-12-08 09:26:11 +0000
@@ -1630,3 +1630,287 @@ 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;
+Warnings:
+Warning	1264	Out of range value for column 'c1' at row 1
+DESC t1;
+Field	Type	Null	Key	Default	Extra
+c1	decimal(65,30)	NO		0.000000000000000000000000000000	
+SELECT * FROM t1;
+c1
+99999999999999999999999999999999999.999999999999999999999999999999
+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:
+Warning	1264	Out of range value for column 'c1' at row 1
+DESC t1;
+Field	Type	Null	Key	Default	Extra
+c1	decimal(65,30)	NO		0.000000000000000000000000000000	
+SELECT * FROM t1;
+c1
+99999999999999999999999999999999999.999999999999999999999999999999
+DROP TABLE t1;
+CREATE TABLE t1 SELECT
+/* 65 */ 12345678901234567890123456789012345678901234567890123456789012345.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,1)	NO		0.0	
+SELECT * FROM t1;
+c1
+9999999999999999999999999999999999999999999999999999999999999999.9
+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,1)	NO		0.0	
+SELECT * FROM t1;
+c1
+9999999999999999999999999999999999999999999999999999999999999999.9
+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,30)	NO		0.000000000000000000000000000000	
+SELECT * FROM t1;
+c1
+2.100000000000000000000000000000
+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(34,0)	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(65,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;
+#
+# Bug #45261 : Crash, stored procedure + decimal
+# Original test by the reporter.
+#
+# should not crash
+CREATE TABLE t1 
+SELECT .123456789012345678901234567890123456789012345678901234567890123456 AS a;
+Warnings:
+Note	1265	Data truncated for column 'a' at row 1
+DROP TABLE t1;
+CREATE PROCEDURE test_proc()
+BEGIN
+# The las non critical CUSER definition is:
+# DECLARE mycursor CURSOR FOR SELECT 1 % 
+# .12345678912345678912345678912345678912345678912345678912345678912 AS my_col;
+DECLARE mycursor CURSOR FOR 
+SELECT 1 % 
+.123456789123456789123456789123456789123456789123456789123456789123456789123456789 
+AS my_col;
+OPEN mycursor;
+CLOSE mycursor;
+END|
+# should not crash
+CALL test_proc();
+DROP PROCEDURE test_proc;
+#
+# Bug #48370  Absolutely wrong calculations with GROUP BY and 
+# decimal fields when using IF
+#
+CREATE TABLE currencies (id int, rate decimal(16,4), 
+PRIMARY KEY (id), KEY (rate));
+INSERT INTO currencies VALUES (11,0.7028);
+INSERT INTO currencies VALUES (1,1);
+CREATE TABLE payments (
+id int,
+supplier_id int,
+status int,
+currency_id int,
+vat decimal(7,4),
+PRIMARY KEY (id),
+KEY currency_id (currency_id),
+KEY supplier_id (supplier_id)
+);
+INSERT INTO payments (id,status,vat,supplier_id,currency_id) VALUES
+(3001,2,0.0000,344,11), (1,2,0.0000,1,1);
+CREATE TABLE sub_tasks (
+id int,
+currency_id int,
+price decimal(16,4),
+discount decimal(10,4),
+payment_id int,
+PRIMARY KEY (id),
+KEY currency_id (currency_id),
+KEY payment_id (payment_id)
+) ;
+INSERT INTO sub_tasks (id, price, discount, payment_id, currency_id) VALUES
+(52, 12.60, 0, 3001, 11), (56, 14.58, 0, 3001, 11);
+# should return 1 and the same values in col 2 and 3
+select STRAIGHT_JOIN
+(1 + PAY.vat) AS mult,
+SUM(ROUND((SUB.price - ROUND(ROUND(SUB.price, 2) * SUB.discount, 2)) * 
+CUR.rate / CUR.rate, 2)
+) v_net_with_discount,
+SUM(ROUND((SUB.price - ROUND(ROUND(SUB.price, 2) * SUB.discount, 1)) *
+CUR.rate / CUR.rate , 2) 
+* (1 + PAY.vat)
+) v_total
+from
+currencies CUR, payments PAY, sub_tasks SUB
+where
+SUB.payment_id = PAY.id and
+PAY.currency_id = CUR.id and
+PAY.id > 2
+group by PAY.id + 1;
+mult	v_net_with_discount	v_total
+1.0000	27.18	27.180000
+DROP TABLE currencies, payments, sub_tasks;
+End of 5.1 tests

=== modified file 'mysql-test/r/type_year.result'
--- a/mysql-test/r/type_year.result	2007-03-29 04:08:30 +0000
+++ b/mysql-test/r/type_year.result	2009-12-15 08:37:10 +0000
@@ -46,3 +46,267 @@ a
 2001
 drop table t1;
 End of 5.0 tests
+#
+# Bug #49480: WHERE using YEAR columns returns unexpected results
+#
+CREATE TABLE t2(yy YEAR(2), c2 CHAR(4));
+CREATE TABLE t4(yyyy YEAR(4), c4 CHAR(4));
+INSERT INTO t2 (c2) VALUES (NULL),(1970),(1999),(2000),(2001),(2069);
+INSERT INTO t4 (c4) SELECT c2 FROM t2;
+UPDATE t2 SET yy = c2;
+UPDATE t4 SET yyyy = c4;
+SELECT * FROM t2;
+yy	c2
+NULL	NULL
+70	1970
+99	1999
+00	2000
+01	2001
+69	2069
+SELECT * FROM t4;
+yyyy	c4
+NULL	NULL
+1970	1970
+1999	1999
+2000	2000
+2001	2001
+2069	2069
+# Comparison of YEAR(2) with YEAR(4)
+SELECT * FROM t2, t4 WHERE yy = yyyy;
+yy	c2	yyyy	c4
+70	1970	1970	1970
+99	1999	1999	1999
+00	2000	2000	2000
+01	2001	2001	2001
+69	2069	2069	2069
+SELECT * FROM t2, t4 WHERE yy <=> yyyy;
+yy	c2	yyyy	c4
+NULL	NULL	NULL	NULL
+70	1970	1970	1970
+99	1999	1999	1999
+00	2000	2000	2000
+01	2001	2001	2001
+69	2069	2069	2069
+SELECT * FROM t2, t4 WHERE yy < yyyy;
+yy	c2	yyyy	c4
+70	1970	1999	1999
+70	1970	2000	2000
+99	1999	2000	2000
+70	1970	2001	2001
+99	1999	2001	2001
+00	2000	2001	2001
+70	1970	2069	2069
+99	1999	2069	2069
+00	2000	2069	2069
+01	2001	2069	2069
+SELECT * FROM t2, t4 WHERE yy > yyyy;
+yy	c2	yyyy	c4
+99	1999	1970	1970
+00	2000	1970	1970
+01	2001	1970	1970
+69	2069	1970	1970
+00	2000	1999	1999
+01	2001	1999	1999
+69	2069	1999	1999
+01	2001	2000	2000
+69	2069	2000	2000
+69	2069	2001	2001
+# Comparison of YEAR(2) with YEAR(2)
+SELECT * FROM t2 a, t2 b WHERE a.yy = b.yy;
+yy	c2	yy	c2
+70	1970	70	1970
+99	1999	99	1999
+00	2000	00	2000
+01	2001	01	2001
+69	2069	69	2069
+SELECT * FROM t2 a, t2 b WHERE a.yy <=> b.yy;
+yy	c2	yy	c2
+NULL	NULL	NULL	NULL
+70	1970	70	1970
+99	1999	99	1999
+00	2000	00	2000
+01	2001	01	2001
+69	2069	69	2069
+SELECT * FROM t2 a, t2 b WHERE a.yy < b.yy;
+yy	c2	yy	c2
+70	1970	99	1999
+70	1970	00	2000
+99	1999	00	2000
+70	1970	01	2001
+99	1999	01	2001
+00	2000	01	2001
+70	1970	69	2069
+99	1999	69	2069
+00	2000	69	2069
+01	2001	69	2069
+# Comparison of YEAR(4) with YEAR(4)
+SELECT * FROM t4 a, t4 b WHERE a.yyyy = b.yyyy;
+yyyy	c4	yyyy	c4
+1970	1970	1970	1970
+1999	1999	1999	1999
+2000	2000	2000	2000
+2001	2001	2001	2001
+2069	2069	2069	2069
+SELECT * FROM t4 a, t4 b WHERE a.yyyy <=> b.yyyy;
+yyyy	c4	yyyy	c4
+NULL	NULL	NULL	NULL
+1970	1970	1970	1970
+1999	1999	1999	1999
+2000	2000	2000	2000
+2001	2001	2001	2001
+2069	2069	2069	2069
+SELECT * FROM t4 a, t4 b WHERE a.yyyy < b.yyyy;
+yyyy	c4	yyyy	c4
+1970	1970	1999	1999
+1970	1970	2000	2000
+1999	1999	2000	2000
+1970	1970	2001	2001
+1999	1999	2001	2001
+2000	2000	2001	2001
+1970	1970	2069	2069
+1999	1999	2069	2069
+2000	2000	2069	2069
+2001	2001	2069	2069
+# Comparison with constants:
+SELECT * FROM t2 WHERE yy = NULL;
+yy	c2
+SELECT * FROM t4 WHERE yyyy = NULL;
+yyyy	c4
+SELECT * FROM t2 WHERE yy <=> NULL;
+yy	c2
+NULL	NULL
+SELECT * FROM t4 WHERE yyyy <=> NULL;
+yyyy	c4
+NULL	NULL
+SELECT * FROM t2 WHERE yy < NULL;
+yy	c2
+SELECT * FROM t2 WHERE yy > NULL;
+yy	c2
+SELECT * FROM t2 WHERE yy = NOW();
+yy	c2
+SELECT * FROM t4 WHERE yyyy = NOW();
+yyyy	c4
+SELECT * FROM t2 WHERE yy = 99;
+yy	c2
+99	1999
+SELECT * FROM t2 WHERE 99 = yy;
+yy	c2
+99	1999
+SELECT * FROM t4 WHERE yyyy = 99;
+yyyy	c4
+1999	1999
+SELECT * FROM t2 WHERE yy = 'test';
+yy	c2
+00	2000
+Warnings:
+Warning	1292	Truncated incorrect DOUBLE value: 'test'
+SELECT * FROM t4 WHERE yyyy = 'test';
+yyyy	c4
+Warnings:
+Warning	1292	Truncated incorrect DOUBLE value: 'test'
+SELECT * FROM t2 WHERE yy = '1999';
+yy	c2
+99	1999
+SELECT * FROM t4 WHERE yyyy = '1999';
+yyyy	c4
+1999	1999
+SELECT * FROM t2 WHERE yy = 1999;
+yy	c2
+99	1999
+SELECT * FROM t4 WHERE yyyy = 1999;
+yyyy	c4
+1999	1999
+SELECT * FROM t2 WHERE yy = 1999.1;
+yy	c2
+99	1999
+SELECT * FROM t4 WHERE yyyy = 1999.1;
+yyyy	c4
+1999	1999
+SELECT * FROM t2 WHERE yy = 1998.9;
+yy	c2
+99	1999
+SELECT * FROM t4 WHERE yyyy = 1998.9;
+yyyy	c4
+1999	1999
+# Coverage tests for YEAR with zero/2000 constants:
+SELECT * FROM t2 WHERE yy = 0;
+yy	c2
+00	2000
+SELECT * FROM t2 WHERE yy = '0';
+yy	c2
+00	2000
+SELECT * FROM t2 WHERE yy = '0000';
+yy	c2
+00	2000
+SELECT * FROM t2 WHERE yy = '2000';
+yy	c2
+00	2000
+SELECT * FROM t2 WHERE yy = 2000;
+yy	c2
+00	2000
+SELECT * FROM t4 WHERE yyyy = 0;
+yyyy	c4
+SELECT * FROM t4 WHERE yyyy = '0';
+yyyy	c4
+2000	2000
+SELECT * FROM t4 WHERE yyyy = '0000';
+yyyy	c4
+SELECT * FROM t4 WHERE yyyy = '2000';
+yyyy	c4
+2000	2000
+SELECT * FROM t4 WHERE yyyy = 2000;
+yyyy	c4
+2000	2000
+# Comparison with constants those are out of YEAR range
+# (coverage test for backward compatibility)
+SELECT COUNT(yy) FROM t2;
+COUNT(yy)
+5
+SELECT COUNT(yyyy) FROM t4;
+COUNT(yyyy)
+5
+SELECT COUNT(*) FROM t2 WHERE yy = -1;
+COUNT(*)
+0
+SELECT COUNT(*) FROM t4 WHERE yyyy > -1;
+COUNT(*)
+5
+SELECT COUNT(*) FROM t2 WHERE yy > -1000000000000000000;
+COUNT(*)
+5
+SELECT COUNT(*) FROM t4 WHERE yyyy > -1000000000000000000;
+COUNT(*)
+5
+SELECT COUNT(*) FROM t2 WHERE yy < 2156;
+COUNT(*)
+5
+SELECT COUNT(*) FROM t4 WHERE yyyy < 2156;
+COUNT(*)
+5
+SELECT COUNT(*) FROM t2 WHERE yy < 1000000000000000000;
+COUNT(*)
+5
+SELECT COUNT(*) FROM t4 WHERE yyyy < 1000000000000000000;
+COUNT(*)
+5
+SELECT * FROM t2 WHERE yy < 123;
+yy	c2
+70	1970
+99	1999
+00	2000
+01	2001
+69	2069
+SELECT * FROM t2 WHERE yy > 123;
+yy	c2
+SELECT * FROM t4 WHERE yyyy < 123;
+yyyy	c4
+SELECT * FROM t4 WHERE yyyy > 123;
+yyyy	c4
+1970	1970
+1999	1999
+2000	2000
+2001	2001
+2069	2069
+DROP TABLE t2, t4;
+#
+End of 5.1 tests

=== modified file 'mysql-test/r/udf.result'
--- a/mysql-test/r/udf.result	2009-09-07 09:57:22 +0000
+++ b/mysql-test/r/udf.result	2010-01-11 13:15:28 +0000
@@ -311,29 +311,6 @@ drop function f3;
 drop function metaphon;
 drop function myfunc_double;
 drop function myfunc_int;
-CREATE FUNCTION metaphon RETURNS STRING SONAME "UDF_EXAMPLE_LIB";
-create table t1 (a char);
-set GLOBAL query_cache_size=1355776;
-reset query cache;
-select metaphon('MySQL') from t1;
-metaphon('MySQL')
-show status like "Qcache_hits";
-Variable_name	Value
-Qcache_hits	0
-show status like "Qcache_queries_in_cache";
-Variable_name	Value
-Qcache_queries_in_cache	0
-select metaphon('MySQL') from t1;
-metaphon('MySQL')
-show status like "Qcache_hits";
-Variable_name	Value
-Qcache_hits	0
-show status like "Qcache_queries_in_cache";
-Variable_name	Value
-Qcache_queries_in_cache	0
-drop table t1;
-drop function metaphon;
-set GLOBAL query_cache_size=default;
 DROP DATABASE IF EXISTS mysqltest;
 CREATE DATABASE mysqltest;
 USE mysqltest;

=== added file 'mysql-test/r/udf_query_cache.result'
--- a/mysql-test/r/udf_query_cache.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/r/udf_query_cache.result	2010-01-11 13:15:28 +0000
@@ -0,0 +1,24 @@
+drop table if exists t1;
+CREATE FUNCTION metaphon RETURNS STRING SONAME "UDF_EXAMPLE_LIB";
+create table t1 (a char);
+set GLOBAL query_cache_size=1355776;
+reset query cache;
+select metaphon('MySQL') from t1;
+metaphon('MySQL')
+show status like "Qcache_hits";
+Variable_name	Value
+Qcache_hits	0
+show status like "Qcache_queries_in_cache";
+Variable_name	Value
+Qcache_queries_in_cache	0
+select metaphon('MySQL') from t1;
+metaphon('MySQL')
+show status like "Qcache_hits";
+Variable_name	Value
+Qcache_hits	0
+show status like "Qcache_queries_in_cache";
+Variable_name	Value
+Qcache_queries_in_cache	0
+drop table t1;
+drop function metaphon;
+set GLOBAL query_cache_size=default;

=== modified file 'mysql-test/r/variables.result'
--- a/mysql-test/r/variables.result	2009-09-15 10:46:35 +0000
+++ b/mysql-test/r/variables.result	2010-01-11 13:15:28 +0000
@@ -19,8 +19,6 @@ set @my_myisam_max_sort_file_size =@@glo
 set @my_net_buffer_length         =@@global.net_buffer_length;
 set @my_net_write_timeout         =@@global.net_write_timeout;
 set @my_net_read_timeout          =@@global.net_read_timeout;
-set @my_query_cache_limit         =@@global.query_cache_limit;
-set @my_query_cache_type          =@@global.query_cache_type;
 set @my_rpl_recovery_rank         =@@global.rpl_recovery_rank;
 set @my_server_id                 =@@global.server_id;
 set @my_slow_launch_time          =@@global.slow_launch_time;
@@ -215,7 +213,6 @@ storage_engine	MRG_MYISAM
 select * from information_schema.global_variables where variable_name like 'storage_engine';
 VARIABLE_NAME	VARIABLE_VALUE
 STORAGE_ENGINE	MRG_MYISAM
-set GLOBAL query_cache_size=100000;
 set GLOBAL myisam_max_sort_file_size=2000000;
 show global variables like 'myisam_max_sort_file_size';
 Variable_name	Value
@@ -423,8 +420,6 @@ ERROR 42000: Variable 'big_tables' can't
 show local variables like 'storage_engine';
 Variable_name	Value
 storage_engine	MEMORY
-set SESSION query_cache_size=10000;
-ERROR HY000: Variable 'query_cache_size' is a GLOBAL variable and should be set with SET GLOBAL
 set GLOBAL storage_engine=DEFAULT;
 ERROR 42000: Variable 'storage_engine' doesn't have a default value
 set character_set_client=UNKNOWN_CHARACTER_SET;
@@ -529,9 +524,6 @@ Warnings:
 Warning	1292	Truncated incorrect net_buffer_length value: '100'
 set net_read_timeout=100;
 set net_write_timeout=100;
-set global query_cache_limit=100;
-set global query_cache_size=100;
-set global query_cache_type=demand;
 set read_buffer_size=100;
 Warnings:
 Warning	1292	Truncated incorrect read_buffer_size value: '100'
@@ -1047,8 +1039,6 @@ set global myisam_max_sort_file_size =@m
 set global net_buffer_length         =@my_net_buffer_length;
 set global net_write_timeout         =@my_net_write_timeout;
 set global net_read_timeout          =@my_net_read_timeout;
-set global query_cache_limit         =@my_query_cache_limit;
-set global query_cache_type          =@my_query_cache_type;
 set global rpl_recovery_rank         =@my_rpl_recovery_rank;
 set global server_id                 =@my_server_id;
 set global slow_launch_time          =@my_slow_launch_time;

=== added file 'mysql-test/std_data/bug47012.ARM'
Files a/mysql-test/std_data/bug47012.ARM	1970-01-01 00:00:00 +0000 and b/mysql-test/std_data/bug47012.ARM	2009-11-11 08:03:29 +0000 differ

=== added file 'mysql-test/std_data/bug47012.ARZ'
Files a/mysql-test/std_data/bug47012.ARZ	1970-01-01 00:00:00 +0000 and b/mysql-test/std_data/bug47012.ARZ	2009-11-11 08:03:29 +0000 differ

=== added file 'mysql-test/std_data/bug47012.frm'
Files a/mysql-test/std_data/bug47012.frm	1970-01-01 00:00:00 +0000 and b/mysql-test/std_data/bug47012.frm	2009-11-11 08:03:29 +0000 differ

=== renamed file 'mysql-test/suite/pbxt/t/load_unique_error1.inc' => 'mysql-test/std_data/pbxt_load_unique_error1.inc'
=== 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-09-28 12:41:10 +0000
+++ b/mysql-test/suite/binlog/r/binlog_stm_mix_innodb_myisam.result	2009-11-18 14:50:31 +0000
@@ -1,3 +1,4 @@
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
 drop table if exists t1, t2;
 create table t1 (a int) engine=innodb;
 create table t2 (a int) engine=myisam;
@@ -224,6 +225,8 @@ create table t0 (n int);
 insert t0 select * from t1;
 set autocommit=1;
 insert into t0 select GET_LOCK("lock1",null);
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
 set autocommit=0;
 create table t2 (n int) engine=innodb;
 insert into t2 values (3);

=== modified file 'mysql-test/suite/binlog/r/binlog_stm_row.result'
--- a/mysql-test/suite/binlog/r/binlog_stm_row.result	2009-09-07 20:50:10 +0000
+++ b/mysql-test/suite/binlog/r/binlog_stm_row.result	2010-01-15 15:27:55 +0000
@@ -1,3 +1,4 @@
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
 DROP TABLE IF EXISTS t1;
 DROP TABLE IF EXISTS t2;
 set @saved_global_binlog_format = @@global.binlog_format;
@@ -29,6 +30,8 @@ SELECT RELEASE_LOCK('Bug#34306');
 RELEASE_LOCK('Bug#34306')
 1
 # con2
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
 SELECT RELEASE_LOCK('Bug#34306');
 RELEASE_LOCK('Bug#34306')
 1

=== modified file 'mysql-test/suite/binlog/r/binlog_unsafe.result'
--- a/mysql-test/suite/binlog/r/binlog_unsafe.result	2009-09-07 20:50:10 +0000
+++ b/mysql-test/suite/binlog/r/binlog_unsafe.result	2010-01-15 15:27:55 +0000
@@ -327,4 +327,86 @@ Warnings:
 Note	1592	Statement may not be safe to log in statement format.
 DROP TABLE t1, t2;
 SET @@SESSION.SQL_MODE = @save_sql_mode;
+CREATE TABLE t1 (a VARCHAR(1000));
+INSERT INTO t1 VALUES (CURRENT_USER());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (FOUND_ROWS());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (GET_LOCK('tmp', 1));
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (IS_FREE_LOCK('tmp'));
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (IS_USED_LOCK('tmp'));
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (LOAD_FILE('../../std_data/words2.dat'));
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (MASTER_POS_WAIT('dummy arg', 4711, 1));
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (RELEASE_LOCK('tmp'));
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (ROW_COUNT());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (SESSION_USER());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (SLEEP(1));
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (SYSDATE());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (SYSTEM_USER());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (USER());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (UUID());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (UUID_SHORT());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+INSERT INTO t1 VALUES (VERSION());
+Warnings:
+Note	1592	Statement may not be safe to log in statement format.
+DELETE FROM t1;
+SET TIMESTAMP=1000000;
+INSERT INTO t1 VALUES
+(CURDATE()),
+(CURRENT_DATE()),
+(CURRENT_TIME()),
+(CURRENT_TIMESTAMP()),
+(CURTIME()),
+(LOCALTIME()),
+(LOCALTIMESTAMP()),
+(NOW()),
+(UNIX_TIMESTAMP()),
+(UTC_DATE()),
+(UTC_TIME()),
+(UTC_TIMESTAMP());
+SELECT * FROM t1;
+a
+1970-01-12
+1970-01-12
+16:46:40
+1970-01-12 16:46:40
+16:46:40
+1970-01-12 16:46:40
+1970-01-12 16:46:40
+1970-01-12 16:46:40
+1000000
+1970-01-12
+13:46:40
+1970-01-12 13:46:40
+DROP TABLE t1;
 "End of tests"

=== modified file 'mysql-test/suite/binlog/t/binlog_killed.test'
--- a/mysql-test/suite/binlog/t/binlog_killed.test	2008-10-23 19:27:09 +0000
+++ b/mysql-test/suite/binlog/t/binlog_killed.test	2009-11-18 14:50:31 +0000
@@ -1,5 +1,5 @@
 -- source include/have_innodb.inc
--- source include/have_binlog_format_mixed_or_statement.inc
+-- source include/have_binlog_format_statement.inc
 
 # You cannot use `KILL' with the Embedded MySQL Server library,
 # because the embedded server merely runs inside the threads of the host

=== modified file 'mysql-test/suite/binlog/t/binlog_stm_mix_innodb_myisam.test'
--- a/mysql-test/suite/binlog/t/binlog_stm_mix_innodb_myisam.test	2008-02-28 11:21:44 +0000
+++ b/mysql-test/suite/binlog/t/binlog_stm_mix_innodb_myisam.test	2009-11-18 14:50:31 +0000
@@ -2,6 +2,9 @@
 # For both statement and row based bin logs 9/19/2005 [jbm]
 
 -- source include/have_binlog_format_statement.inc
+
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
+
 -- source extra/binlog_tests/mix_innodb_myisam_binlog.test
 
 set @@session.binlog_format=statement;

=== modified file 'mysql-test/suite/binlog/t/binlog_stm_row.test'
--- a/mysql-test/suite/binlog/t/binlog_stm_row.test	2009-02-19 09:01:25 +0000
+++ b/mysql-test/suite/binlog/t/binlog_stm_row.test	2010-01-15 15:27:55 +0000
@@ -1,5 +1,8 @@
 --source include/have_log_bin.inc
---source include/have_binlog_format_row_or_statement.inc
+# Test sets its own binlog_format, so we restrict it to run only once
+--source include/have_binlog_format_row.inc
+
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
 
 # Get rid of previous tests binlog
 --disable_query_log

=== modified file 'mysql-test/suite/binlog/t/binlog_unsafe.test'
--- a/mysql-test/suite/binlog/t/binlog_unsafe.test	2009-09-07 20:50:10 +0000
+++ b/mysql-test/suite/binlog/t/binlog_unsafe.test	2010-01-15 15:27:55 +0000
@@ -388,4 +388,56 @@ DELETE FROM t1 LIMIT 1;
 
 DROP TABLE t1, t2;
 SET @@SESSION.SQL_MODE = @save_sql_mode;
+
+#
+# BUG#47995: Mark user functions as unsafe
+#
+# Test that the system functions that are supposed to be marked unsafe
+# generate a warning.  Each INSERT statement below should generate a
+# warning.
+#
+
+CREATE TABLE t1 (a VARCHAR(1000));
+INSERT INTO t1 VALUES (CURRENT_USER());       #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (FOUND_ROWS());         #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (GET_LOCK('tmp', 1));
+INSERT INTO t1 VALUES (IS_FREE_LOCK('tmp'));
+INSERT INTO t1 VALUES (IS_USED_LOCK('tmp'));
+INSERT INTO t1 VALUES (LOAD_FILE('../../std_data/words2.dat')); #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (MASTER_POS_WAIT('dummy arg', 4711, 1));
+INSERT INTO t1 VALUES (RELEASE_LOCK('tmp'));
+INSERT INTO t1 VALUES (ROW_COUNT());          #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (SESSION_USER());       #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (SLEEP(1));
+INSERT INTO t1 VALUES (SYSDATE());
+INSERT INTO t1 VALUES (SYSTEM_USER());        #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (USER());               #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (UUID());               #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (UUID_SHORT());         #marked unsafe before BUG#47995
+INSERT INTO t1 VALUES (VERSION());
+DELETE FROM t1;
+
+# Since we replicate the TIMESTAMP variable, functions affected by the
+# TIMESTAMP variable are safe to replicate.  So we check that the
+# following following functions depend on the TIMESTAMP variable and
+# don't generate a warning.
+
+SET TIMESTAMP=1000000;
+INSERT INTO t1 VALUES
+  (CURDATE()),
+  (CURRENT_DATE()),
+  (CURRENT_TIME()),
+  (CURRENT_TIMESTAMP()),
+  (CURTIME()),
+  (LOCALTIME()),
+  (LOCALTIMESTAMP()),
+  (NOW()),
+  (UNIX_TIMESTAMP()),
+  (UTC_DATE()),
+  (UTC_TIME()),
+  (UTC_TIMESTAMP());
+SELECT * FROM t1;
+
+DROP TABLE t1;
+
 --echo "End of tests"

=== modified file 'mysql-test/suite/funcs_1/datadict/processlist_val.inc'
--- a/mysql-test/suite/funcs_1/datadict/processlist_val.inc	2009-10-10 09:59:06 +0000
+++ b/mysql-test/suite/funcs_1/datadict/processlist_val.inc	2010-01-11 13:15:28 +0000
@@ -238,7 +238,7 @@ echo
 # Poll till all connections of 'test_user' are in a state with COMMAND = 'Sleep'
 ;
 let $wait_condition= SELECT COUNT(*) = 2 FROM INFORMATION_SCHEMA.PROCESSLIST
-        WHERE USER = 'test_user' AND COMMAND = 'Sleep';
+        WHERE USER = 'test_user' AND COMMAND = 'Sleep' AND STATE = '';
 --source include/wait_condition.inc
 echo
 # ----- switch to connection con2 (user = test_user) -----

=== modified file 'mysql-test/suite/innodb/r/innodb-index.result'
--- a/mysql-test/suite/innodb/r/innodb-index.result	2009-06-10 13:51:20 +0000
+++ b/mysql-test/suite/innodb/r/innodb-index.result	2009-11-30 12:49:13 +0000
@@ -968,6 +968,7 @@ create index t1u on t1 (u(1));
 drop table t1;
 set global innodb_file_per_table=0;
 set global innodb_file_format=Antelope;
+set global innodb_file_format_check=Antelope;
 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
 CREATE TABLE t1(

=== added file 'mysql-test/suite/innodb/r/innodb_bug46676.result'
--- a/mysql-test/suite/innodb/r/innodb_bug46676.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/r/innodb_bug46676.result	2009-11-30 12:24:54 +0000
@@ -0,0 +1,9 @@
+SET foreign_key_checks=0;
+CREATE TABLE t1 (id int, foreign key (id) references t2(id)) ENGINE=INNODB;
+CREATE TABLE t2 (id int, foreign key (id) references t1(id)) ENGINE=INNODB;
+SET foreign_key_checks=1;
+SELECT COUNT(*) FROM information_schema.key_column_usage WHERE REFERENCED_TABLE_NAME in ('t1', 't2');
+COUNT(*)
+2
+SET foreign_key_checks=0;
+DROP TABLE t1, t2;

=== added file 'mysql-test/suite/innodb/r/innodb_bug47167.result'
--- a/mysql-test/suite/innodb/r/innodb_bug47167.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/r/innodb_bug47167.result	2009-11-30 11:56:21 +0000
@@ -0,0 +1,24 @@
+set @old_innodb_file_format_check=@@innodb_file_format_check;
+select @old_innodb_file_format_check;
+@old_innodb_file_format_check
+Antelope
+set global innodb_file_format_check = Barracuda;
+select @@innodb_file_format_check;
+@@innodb_file_format_check
+Barracuda
+set global innodb_file_format_check = DEFAULT;
+select @@innodb_file_format_check;
+@@innodb_file_format_check
+Barracuda
+set global innodb_file_format_check = @old_innodb_file_format_check;
+select @@innodb_file_format_check;
+@@innodb_file_format_check
+Antelope
+set global innodb_file_format_check = cheetah;
+ERROR HY000: Incorrect arguments to SET
+set global innodb_file_format_check = Bear;
+ERROR HY000: Incorrect arguments to SET
+set global innodb_file_format_check = on;
+ERROR HY000: Incorrect arguments to SET
+set global innodb_file_format_check = off;
+ERROR HY000: Incorrect arguments to SET

=== modified file 'mysql-test/suite/innodb/t/innodb-consistent-master.opt'
--- a/mysql-test/suite/innodb/t/innodb-consistent-master.opt	2009-10-09 13:37:47 +0000
+++ b/mysql-test/suite/innodb/t/innodb-consistent-master.opt	2009-11-30 12:49:13 +0000
@@ -1 +1 @@
---innodb_lock_wait_timeout=2
+--loose-innodb_lock_wait_timeout=2

=== modified file 'mysql-test/suite/innodb/t/innodb-index.test'
--- a/mysql-test/suite/innodb/t/innodb-index.test	2009-06-11 12:57:44 +0000
+++ b/mysql-test/suite/innodb/t/innodb-index.test	2009-11-30 12:49:13 +0000
@@ -1,5 +1,7 @@
 -- source include/have_innodb.inc
 
+let $innodb_file_format_check_orig=`select @@innodb_file_format_check`;
+
 create table t1(a int not null, b int, c char(10) not null, d varchar(20)) engine = innodb;
 insert into t1 values (5,5,'oo','oo'),(4,4,'tr','tr'),(3,4,'ad','ad'),(2,3,'ak','ak');
 commit;
@@ -398,6 +400,7 @@ create index t1u on t1 (u(1));
 drop table t1;
 eval set global innodb_file_per_table=$per_table;
 eval set global innodb_file_format=$format;
+eval set global innodb_file_format_check=$format;
 
 #
 # Test to check whether CREATE INDEX handles implicit foreign key
@@ -532,3 +535,10 @@ disconnect a;
 disconnect b;
 
 DROP TABLE t1;
+
+#
+# restore environment to the state it was before this test execution
+#
+
+-- disable_query_log
+eval SET GLOBAL innodb_file_format_check=$innodb_file_format_check_orig;

=== added file 'mysql-test/suite/innodb/t/innodb_bug46676.test'
--- a/mysql-test/suite/innodb/t/innodb_bug46676.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/t/innodb_bug46676.test	2009-11-30 12:24:54 +0000
@@ -0,0 +1,16 @@
+# This is the test for bug 46676: mysqld got exception 0xc0000005
+# It is reproducible with InnoDB plugin 1.0.4 + MySQL 5.1.37.
+# But no longer reproducible after MySQL 5.1.38 (with plugin 1.0.5).
+
+--source include/have_innodb.inc
+
+SET foreign_key_checks=0;
+CREATE TABLE t1 (id int, foreign key (id) references t2(id)) ENGINE=INNODB;
+CREATE TABLE t2 (id int, foreign key (id) references t1(id)) ENGINE=INNODB;
+SET foreign_key_checks=1;
+
+# Server crashes
+SELECT COUNT(*) FROM information_schema.key_column_usage WHERE REFERENCED_TABLE_NAME in ('t1', 't2');
+
+SET foreign_key_checks=0;
+DROP TABLE t1, t2;

=== added file 'mysql-test/suite/innodb/t/innodb_bug47167.test'
--- a/mysql-test/suite/innodb/t/innodb_bug47167.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/innodb/t/innodb_bug47167.test	2009-11-30 11:56:21 +0000
@@ -0,0 +1,46 @@
+# This is the unit test for bug *47167.
+# It tests setting the global variable
+# "innodb_file_format_check" with a
+# user-Defined Variable.
+
+--source include/have_innodb.inc
+-- source suite/innodb/include/have_innodb_plugin.inc
+
+# Save the value (Antelope) in 'innodb_file_format_check' to
+# 'old_innodb_file_format_check'
+set @old_innodb_file_format_check=@@innodb_file_format_check;
+
+# @old_innodb_file_format_check shall have the value of 'Antelope'
+select @old_innodb_file_format_check;
+
+# Reset the value in 'innodb_file_format_check' to 'Barracuda'
+set global innodb_file_format_check = Barracuda;
+
+select @@innodb_file_format_check;
+
+# Set 'innodb_file_format_check' to its default value, which
+# is the latest file format supported in the current release.
+set global innodb_file_format_check = DEFAULT;
+
+select @@innodb_file_format_check;
+
+# Put the saved value back to 'innodb_file_format_check'
+set global innodb_file_format_check = @old_innodb_file_format_check;
+
+# Check whether 'innodb_file_format_check' get its original value.
+select @@innodb_file_format_check;
+
+# Following are negative tests, all should fail.
+--disable_warnings
+--error ER_WRONG_ARGUMENTS
+set global innodb_file_format_check = cheetah;
+
+--error ER_WRONG_ARGUMENTS
+set global innodb_file_format_check = Bear;
+
+--error ER_WRONG_ARGUMENTS
+set global innodb_file_format_check = on;
+
+--error ER_WRONG_ARGUMENTS
+set global innodb_file_format_check = off;
+--enable_warnings

=== modified file 'mysql-test/suite/maria/t/maria2-master.opt'
--- a/mysql-test/suite/maria/t/maria2-master.opt	2009-02-15 10:58:34 +0000
+++ b/mysql-test/suite/maria/t/maria2-master.opt	2010-01-15 15:27:55 +0000
@@ -1,2 +1 @@
---secure-file-priv=""
-
+--secure-file-priv="../../std_data"

=== modified file 'mysql-test/suite/parts/t/partition_alter1_2_innodb.test'
--- a/mysql-test/suite/parts/t/partition_alter1_2_innodb.test	2009-10-09 13:08:09 +0000
+++ b/mysql-test/suite/parts/t/partition_alter1_2_innodb.test	2010-01-15 15:27:55 +0000
@@ -28,6 +28,8 @@
 #------------------------------------------------------------------------------#
 # General not engine specific settings and requirements
 
+--source include/big_test.inc
+
 ##### Options, for debugging support #####
 let $debug= 0;
 let $with_partitioning= 1;

=== modified file 'mysql-test/suite/parts/t/partition_alter2_1_innodb.test'
--- a/mysql-test/suite/parts/t/partition_alter2_1_innodb.test	2009-10-09 13:08:09 +0000
+++ b/mysql-test/suite/parts/t/partition_alter2_1_innodb.test	2010-01-15 15:27:55 +0000
@@ -22,6 +22,8 @@
 # any of the variables.
 #
 
+--source include/big_test.inc
+
 #------------------------------------------------------------------------------#
 # General not engine specific settings and requirements
 

=== modified file 'mysql-test/suite/parts/t/partition_alter2_2_innodb.test'
--- a/mysql-test/suite/parts/t/partition_alter2_2_innodb.test	2009-10-09 13:08:09 +0000
+++ b/mysql-test/suite/parts/t/partition_alter2_2_innodb.test	2010-01-15 15:27:55 +0000
@@ -22,6 +22,8 @@
 # any of the variables.
 #
 
+--source include/big_test.inc
+
 #------------------------------------------------------------------------------#
 # General not engine specific settings and requirements
 

=== modified file 'mysql-test/suite/parts/t/partition_alter4_innodb.test'
--- a/mysql-test/suite/parts/t/partition_alter4_innodb.test	2009-10-09 13:08:09 +0000
+++ b/mysql-test/suite/parts/t/partition_alter4_innodb.test	2010-01-15 15:27:55 +0000
@@ -22,6 +22,8 @@
 # any of the variables.
 #
 
+--source include/big_test.inc
+
 #------------------------------------------------------------------------------#
 # General not engine specific settings and requirements
 

=== modified file 'mysql-test/suite/pbxt/r/lock_multi.result'
--- a/mysql-test/suite/pbxt/r/lock_multi.result	2009-04-02 10:03:14 +0000
+++ b/mysql-test/suite/pbxt/r/lock_multi.result	2010-01-06 21:27:53 +0000
@@ -1,22 +1,4 @@
 drop table if exists t1,t2;
-create table t1(n int);
-insert into t1 values (1);
-lock tables t1 write;
-update low_priority t1 set n = 4;
-select n from t1;
-unlock tables;
-n
-1
-drop table t1;
-create table t1(n int);
-insert into t1 values (1);
-lock tables t1 read;
-update low_priority t1 set n = 4;
-select n from t1;
-unlock tables;
-n
-1
-drop table t1;
 create table t1 (a int, b int);
 create table t2 (c int, d int);
 insert into t1 values(1,1);
@@ -43,6 +25,7 @@ insert t1 select * from t2;
 drop table t2;
 ERROR 42S02: Table 'test.t2' doesn't exist
 drop table t1;
+End of 4.1 tests
 create table t1(a int);
 lock tables t1 write;
 show columns from t1;
@@ -50,10 +33,10 @@ Field	Type	Null	Key	Default	Extra
 a	int(11)	YES		NULL	
 unlock tables;
 drop table t1;
-use mysql;
+USE mysql;
 LOCK TABLES columns_priv WRITE, db WRITE, host WRITE, user WRITE;
 FLUSH TABLES;
-use mysql;
+USE mysql;
 SELECT user.Select_priv FROM user, db WHERE user.user = db.user LIMIT 1;
 OPTIMIZE TABLES columns_priv, db, host, user;
 Table	Op	Msg_type	Msg_text
@@ -63,7 +46,8 @@ mysql.host	optimize	status	OK
 mysql.user	optimize	status	OK
 UNLOCK TABLES;
 Select_priv
-use test;
+N
+USE test;
 use test;
 CREATE TABLE t1 (c1 int);
 LOCK TABLE t1 WRITE;
@@ -90,7 +74,115 @@ DROP DATABASE mysqltest_1;
 ERROR HY000: Can't drop database 'mysqltest_1'; database doesn't exist
 create table t1 (f1 int(12) unsigned not null auto_increment, primary key(f1)) engine=innodb;
 lock tables t1 write;
-alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; //
-alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; //
+alter table t1 auto_increment=0;
+alter table t1 auto_increment=0;
+unlock tables;
+drop table t1;
+create table t1 (a int);
+create table t2 like t1;
+# con1
+lock tables t1 write;
+# con2
+flush tables with read lock;
+# con5
+# global read lock is taken
+# con3
+select * from t2 for update;
+# waiting for release of read lock
+# con4
+# would hang and later cause a deadlock
+flush tables t2;
+# clean up
+unlock tables;
+unlock tables;
+a
+drop table t1,t2;
+#
+# Lightweight version:
+# Ensure that the wait for a GRL is done before opening tables.
+#
+create table t1 (a int);
+create table t2 like t1;
+#
+# UPDATE
+#
+# default
+flush tables with read lock;
+# con1
+update t2 set a = 1;
+# default
+# statement is waiting for release of read lock
+# con2
+flush table t2;
+# default
+unlock tables;
+# con1
+#
+# LOCK TABLES .. WRITE
+#
+# default
+flush tables with read lock;
+# con1
+lock tables t2 write;
+# default
+# statement is waiting for release of read lock
+# con2
+flush table t2;
+# default
+unlock tables;
+# con1
+unlock tables;
+drop table t1,t2;
+End of 5.0 tests
+create table t1 (i int);
+lock table t1 read;
+update t1 set i= 10;
+select * from t1;
+Timeout in wait_condition.inc for select count(*) = 1 from information_schema.processlist
+where state = "Locked" and info = "select * from t1"
+kill query ID;
+i
+ERROR 70100: Query execution was interrupted
+unlock tables;
+drop table t1;
+drop table if exists t1;
+create table t1 (i int);
+connection: default
+lock tables t1 write;
+connection: flush
+flush tables with read lock;;
+connection: default
+alter table t1 add column j int;
+connection: insert
+insert into t1 values (1,2);;
+connection: default
+unlock tables;
+connection: flush
+select * from t1;
+i	j
+unlock tables;
+select * from t1;
+i	j
+1	2
+drop table t1;
+drop table if exists t1;
+create table t1 (i int);
+connection: default
+lock tables t1 write;
+connection: flush
+flush tables with read lock;;
+connection: default
+flush tables;
+unlock tables;
+drop table t1;
+drop table if exists t1,t2;
+create table t1 (a int);
+flush status;
+lock tables t1 read;
+insert into t1 values(1);;
 unlock tables;
 drop table t1;
+select @tlwa < @tlwb;
+@tlwa < @tlwb
+1
+End of 5.1 tests

=== modified file 'mysql-test/suite/pbxt/r/pbxt_bugs.result'
--- a/mysql-test/suite/pbxt/r/pbxt_bugs.result	2009-08-17 15:57:58 +0000
+++ b/mysql-test/suite/pbxt/r/pbxt_bugs.result	2009-12-22 10:33:20 +0000
@@ -1212,7 +1212,7 @@ c1
 2147483647
 DROP TABLE IF EXISTS t1;
 CREATE TABLE t1 (c1 INTEGER NOT NULL PRIMARY KEY, c2 VARCHAR(255));
-LOAD DATA LOCAL INFILE 'suite/pbxt/t/load_unique_error1.inc' REPLACE INTO TABLE t1 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (@c1,c2) SET c1 = @c1 % 2;
+LOAD DATA LOCAL INFILE 'MYSQLTEST_VARDIR/std_data/pbxt_load_unique_error1.inc' REPLACE INTO TABLE t1 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (@c1,c2) SET c1 = @c1 % 2;
 SELECT * FROM t1 ORDER BY c1;
 c1	c2
 0	opq

=== modified file 'mysql-test/suite/pbxt/t/lock_multi.test'
--- a/mysql-test/suite/pbxt/t/lock_multi.test	2009-04-02 10:03:14 +0000
+++ b/mysql-test/suite/pbxt/t/lock_multi.test	2010-01-06 21:27:53 +0000
@@ -1,4 +1,8 @@
 -- source include/not_embedded.inc
+
+# Save the initial number of concurrent sessions
+--source include/count_sessions.inc
+
 --disable_warnings
 drop table if exists t1,t2;
 --enable_warnings
@@ -9,42 +13,6 @@ connect (locker,localhost,root,,);
 connect (reader,localhost,root,,);
 connect (writer,localhost,root,,);
 
-connection locker;
-create table t1(n int);
-insert into t1 values (1);
-lock tables t1 write;
-connection writer;
-send update low_priority t1 set n = 4;
-connection reader;
---sleep 2
-send select n from t1;
-connection locker;
---sleep 2
-unlock tables;
-connection writer;
-reap;
-connection reader;
-reap;
-drop table t1;
-
-connection locker;
-create table t1(n int);
-insert into t1 values (1);
-lock tables t1 read;
-connection writer;
-send update low_priority t1 set n = 4;
-connection reader;
---sleep 2
-send select n from t1;
-connection locker;
---sleep 2
-unlock tables;
-connection writer;
-reap;
-connection reader;
-reap;
-drop table t1;
-
 #
 # Test problem when using locks with multi-updates
 # It should not block when multi-update is reading on a read-locked table
@@ -58,32 +26,33 @@ insert into t1 values(2,2);
 insert into t2 values(1,2);
 lock table t1 read;
 connection writer;
---sleep 2
-send update t1,t2 set c=a where b=d;
+update t1,t2 set c=a where b=d;
 connection reader;
---sleep 2
 select c from t2;
-connection writer;
-reap;
 connection locker;
 drop table t1;
 drop table t2;
 
 #
-# Test problem when using locks on many tables and droping a table that
+# Test problem when using locks on many tables and dropping a table that
 # is to-be-locked by another thread
 #
-
+#
 connection locker;
 create table t1 (a int);
 create table t2 (a int);
 lock table t1 write, t2 write;
 connection reader;
-send insert t1 select * from t2;
+send
+insert t1 select * from t2;
 connection locker;
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Locked" and info = "insert t1 select * from t2";
+--source include/wait_condition.inc
 drop table t2;
 connection reader;
---error 1146
+--error ER_NO_SUCH_TABLE
 reap;
 connection locker;
 drop table t1;
@@ -97,20 +66,26 @@ create table t1 (a int);
 create table t2 (a int);
 lock table t1 write, t2 write, t1 as t1_2 write, t2 as t2_2 write;
 connection reader;
-send insert t1 select * from t2;
+send
+insert t1 select * from t2;
 connection locker;
+# Sleep a bit till the insert of connection reader is in work and hangs
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Locked" and info = "insert t1 select * from t2";
+--source include/wait_condition.inc
 drop table t2;
 connection reader;
---error 1146
+--error ER_NO_SUCH_TABLE
 reap;
 connection locker;
 drop table t1;
 
 
-# End of 4.1 tests
+--echo End of 4.1 tests
 
 #
-# BUG#9998 - MySQL client hangs on USE "database"
+# Bug#9998 MySQL client hangs on USE "database"
 #
 create table t1(a int);
 lock tables t1 write;
@@ -121,21 +96,30 @@ unlock tables;
 drop table t1;
 
 #
-# Bug#16986 - Deadlock condition with MyISAM tables
+# Bug#16986 Deadlock condition with MyISAM tables
 #
+
+# Need a matching user in mysql.user for multi-table select
+--source include/add_anonymous_users.inc
+
 connection locker;
-use mysql;
+USE mysql;
 LOCK TABLES columns_priv WRITE, db WRITE, host WRITE, user WRITE;
 FLUSH TABLES;
---sleep 1
 #
 connection reader;
-use mysql;
-#NOTE:  This must be a multi-table select, otherwise the deadlock will not occur
-send SELECT user.Select_priv FROM user, db WHERE user.user = db.user LIMIT 1;
---sleep 1
+USE mysql;
+# Note:  This must be a multi-table select, otherwise the deadlock will not occur
+send
+SELECT user.Select_priv FROM user, db WHERE user.user = db.user LIMIT 1;
 #
 connection locker;
+# Sleep a bit till the select of connection reader is in work and hangs
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Waiting for table" and info =
+  "SELECT user.Select_priv FROM user, db WHERE user.user = db.user LIMIT 1";
+--source include/wait_condition.inc
 # Make test case independent from earlier grants.
 --replace_result "Table is already up to date" "OK"
 OPTIMIZE TABLES columns_priv, db, host, user;
@@ -143,7 +127,7 @@ UNLOCK TABLES;
 #
 connection reader;
 reap;
-use test;
+USE test;
 #
 connection locker;
 use test;
@@ -158,11 +142,16 @@ LOCK TABLE t1 WRITE;
 #
 # This waits until t1 is unlocked.
 connection locker;
-send FLUSH TABLES WITH READ LOCK;
---sleep 1
+send
+FLUSH TABLES WITH READ LOCK;
 #
-# This must not block.
 connection writer;
+# Sleep a bit till the flush of connection locker is in work and hangs
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Flushing tables" and info = "FLUSH TABLES WITH READ LOCK";
+--source include/wait_condition.inc
+# This must not block.
 CREATE TABLE t2 (c1 int);
 UNLOCK TABLES;
 #
@@ -182,12 +171,17 @@ LOCK TABLE t1 WRITE;
 #
 # This waits until t1 is unlocked.
 connection locker;
-send FLUSH TABLES WITH READ LOCK;
---sleep 1
+send
+FLUSH TABLES WITH READ LOCK;
 #
 # This must not block.
 connection writer;
---error 1100
+# Sleep a bit till the flush of connection locker is in work and hangs
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Flushing tables" and info = "FLUSH TABLES WITH READ LOCK";
+--source include/wait_condition.inc
+--error ER_TABLE_NOT_LOCKED
 CREATE TABLE t2 AS SELECT * FROM t1;
 UNLOCK TABLES;
 #
@@ -199,8 +193,10 @@ UNLOCK TABLES;
 connection default;
 DROP TABLE t1;
 
+--source include/delete_anonymous_users.inc
+
 #
-# Bug#19815 - CREATE/RENAME/DROP DATABASE can deadlock on a global read lock
+# Bug#19815 CREATE/RENAME/DROP DATABASE can deadlock on a global read lock
 #
 connect (con1,localhost,root,,);
 connect (con2,localhost,root,,);
@@ -212,12 +208,18 @@ FLUSH TABLES WITH READ LOCK;
 # With bug in place: acquire LOCK_mysql_create_table and
 # wait in wait_if_global_read_lock().
 connection con2;
-send DROP DATABASE mysqltest_1;
---sleep 1
+send
+DROP DATABASE mysqltest_1;
 #
 # With bug in place: try to acquire LOCK_mysql_create_table...
 # When fixed: Reject dropping db because of the read lock.
 connection con1;
+# Wait a bit so that the session con2 is in state "Waiting for release of readlock"
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Waiting for release of readlock"
+  and info = "DROP DATABASE mysqltest_1";
+--source include/wait_condition.inc
 --error ER_CANT_UPDATE_WITH_READLOCK
 DROP DATABASE mysqltest_1;
 UNLOCK TABLES;
@@ -234,7 +236,7 @@ disconnect con2;
 DROP DATABASE mysqltest_1;
 
 #
-# Bug #17264: MySQL Server freeze
+# Bug#17264 MySQL Server freeze
 #
 connection locker;
 # Disable warnings to allow test to run also without InnoDB
@@ -243,17 +245,22 @@ create table t1 (f1 int(12) unsigned not
 --enable_warnings
 lock tables t1 write;
 connection writer;
---sleep 2
-delimiter //;
-send alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; //
-delimiter ;//
-connection reader;
---sleep 2
-delimiter //;
-send alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; alter table t1 auto_increment=0; //
-delimiter ;//
-connection locker;
---sleep 2
+send
+alter table t1 auto_increment=0;
+connection reader;
+# Wait till connection writer is blocked
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Locked" and info = "alter table t1 auto_increment=0";
+--source include/wait_condition.inc
+send
+alter table t1 auto_increment=0;
+connection locker;
+# Wait till connection reader is blocked
+let $wait_condition=
+  select count(*) = 2 from information_schema.processlist
+  where state = "Locked" and info = "alter table t1 auto_increment=0";
+--source include/wait_condition.inc
 unlock tables;
 connection writer;
 reap;
@@ -262,8 +269,310 @@ reap;
 connection locker;
 drop table t1;
 
+#
+# Bug#43230: SELECT ... FOR UPDATE can hang with FLUSH TABLES WITH READ LOCK indefinitely
+#
+
+connect (con1,localhost,root,,);
+connect (con2,localhost,root,,);
+connect (con3,localhost,root,,);
+connect (con4,localhost,root,,);
+connect (con5,localhost,root,,);
+
+create table t1 (a int);
+create table t2 like t1;
+
+connection con1;
+--echo # con1
+lock tables t1 write;
+connection con2;
+--echo # con2
+send flush tables with read lock;
+connection con5;
+--echo # con5
+let $show_statement= SHOW PROCESSLIST;
+let $field= State;
+let $condition= = 'Flushing tables';
+--source include/wait_show_condition.inc
+--echo # global read lock is taken
+connection con3;
+--echo # con3
+send select * from t2 for update;
+connection con5;
+let $show_statement= SHOW PROCESSLIST;
+let $field= State;
+let $condition= = 'Waiting for release of readlock';
+--source include/wait_show_condition.inc
+--echo # waiting for release of read lock
+connection con4;
+--echo # con4
+--echo # would hang and later cause a deadlock
+flush tables t2;
+connection con1;
+--echo # clean up
+unlock tables;
+connection con2;
+--reap
+unlock tables;
+connection con3;
+--reap
+connection default;
+disconnect con5;
+disconnect con4;
+disconnect con3;
+disconnect con2;
+disconnect con1;
+
+drop table t1,t2;
+
+--echo #
+--echo # Lightweight version:
+--echo # Ensure that the wait for a GRL is done before opening tables.
+--echo #
+
+connect (con1,localhost,root,,);
+connect (con2,localhost,root,,);
+
+create table t1 (a int);
+create table t2 like t1;
+
+--echo #
+--echo # UPDATE
+--echo #
+
+connection default;
+--echo # default
+flush tables with read lock;
+connection con1;
+--echo # con1
+send update t2 set a = 1;
+connection default;
+--echo # default
+let $show_statement= SHOW PROCESSLIST;
+let $field= State;
+let $condition= = 'Waiting for release of readlock';
+--source include/wait_show_condition.inc
+--echo # statement is waiting for release of read lock
+connection con2;
+--echo # con2
+flush table t2;
+connection default;
+--echo # default
+unlock tables;
+connection con1;
+--echo # con1
+--reap
+
+--echo #
+--echo # LOCK TABLES .. WRITE
+--echo #
+
+connection default;
+--echo # default
+flush tables with read lock;
+connection con1;
+--echo # con1
+send lock tables t2 write;
+connection default;
+--echo # default
+let $show_statement= SHOW PROCESSLIST;
+let $field= State;
+let $condition= = 'Waiting for release of readlock';
+--source include/wait_show_condition.inc
+--echo # statement is waiting for release of read lock
+connection con2;
+--echo # con2
+flush table t2;
+connection default;
+--echo # default
+unlock tables;
+connection con1;
+--echo # con1
+--reap
+unlock tables;
+
+connection default;
+disconnect con2;
+disconnect con1;
+
+drop table t1,t2;
+
+
+--echo End of 5.0 tests
+
+
+#
+# Bug#21281 Pending write lock is incorrectly removed when its
+#           statement being KILLed
+#
+create table t1 (i int);
+connection locker;
+lock table t1 read;
+connection writer;
+send
+update t1 set i= 10;
+connection reader;
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Locked" and info = "update t1 set i= 10";
+--source include/wait_condition.inc
+send
+select * from t1;
+connection default;
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Locked" and info = "select * from t1";
+--source include/wait_condition.inc
+let $ID= `select id from information_schema.processlist where state = "Locked" and info = "update t1 set i= 10"`;
+--replace_result $ID ID
+eval kill query $ID;
+connection reader;
+--reap
+connection writer;
+--error ER_QUERY_INTERRUPTED
+--reap
+connection locker;
+unlock tables;
+connection default;
+drop table t1;
+
+# Disconnect sessions used in many subtests above
+disconnect locker;
+disconnect reader;
+disconnect writer;
+
+#
+# Bug#32395 Alter table under a impending global read lock causes a server crash
+#
+
+#
+# Test ALTER TABLE under LOCK TABLES and FLUSH TABLES WITH READ LOCK
+#
+
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+create table t1 (i int);
+connect (flush,localhost,root,,test,,);
+connection default;
+--echo connection: default
+lock tables t1 write;
+connection flush;
+--echo connection: flush
+--send flush tables with read lock;
+connection default;
+--echo connection: default
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Flushing tables";
+--source include/wait_condition.inc
+alter table t1 add column j int;
+connect (insert,localhost,root,,test,,);
+connection insert;
+--echo connection: insert
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Flushing tables";
+--source include/wait_condition.inc
+--send insert into t1 values (1,2);
+--echo connection: default
+connection default;
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Waiting for release of readlock";
+--source include/wait_condition.inc
+unlock tables;
+connection flush;
+--echo connection: flush
+--reap
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Waiting for release of readlock";
+--source include/wait_condition.inc
+select * from t1;
+unlock tables;
+connection insert;
+--reap
+connection default;
+let $wait_condition=
+  select count(*) = 1 from t1;
+--source include/wait_condition.inc
+select * from t1;
+drop table t1;
+disconnect flush;
+disconnect insert;
+
+#
+# Test that FLUSH TABLES under LOCK TABLES protects write locked tables
+# from a impending FLUSH TABLES WITH READ LOCK
+#
+
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+create table t1 (i int);
+connect (flush,localhost,root,,test,,);
+connection default;
+--echo connection: default
+lock tables t1 write;
+connection flush;
+--echo connection: flush
+--send flush tables with read lock;
+connection default;
+--echo connection: default
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Flushing tables";
+--source include/wait_condition.inc
+flush tables;
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Flushing tables";
+--source include/wait_condition.inc
+unlock tables;
+let $wait_condition=
+  select count(*) = 0 from information_schema.processlist
+  where state = "Flushing tables";
+--source include/wait_condition.inc
+connection flush;
+--reap
+connection default;
+disconnect flush;
+drop table t1;
+
+#
+# Bug#30331 Table_locks_waited shows inaccurate values
+#
+
+--disable_warnings
+drop table if exists t1,t2;
+--enable_warnings
+create table t1 (a int);
+flush status;
+lock tables t1 read;
+let $tlwa= `show status like 'Table_locks_waited'`;
+connect (waiter,localhost,root,,);
+connection waiter;
+--send insert into t1 values(1);
+connection default;
+let $wait_condition=
+  select count(*) = 1 from information_schema.processlist
+  where state = "Locked" and info = "insert into t1 values(1)";
+--source include/wait_condition.inc
+let $tlwb= `show status like 'Table_locks_waited'`;
+unlock tables;
+drop table t1;
+disconnect waiter;
+connection default;
 --disable_query_log
+eval SET @tlwa= SUBSTRING_INDEX('$tlwa', '	', -1);
+eval SET @tlwb= SUBSTRING_INDEX('$tlwb', '	', -1);
 drop database pbxt;
 --enable_query_log
-# End of 5.0 tests
+select @tlwa < @tlwb;
+
+--echo End of 5.1 tests
+
+# Wait till all disconnects are completed
+--source include/wait_until_count_sessions.inc
 

=== modified file 'mysql-test/suite/pbxt/t/pbxt_bugs.test'
--- a/mysql-test/suite/pbxt/t/pbxt_bugs.test	2009-08-17 15:57:58 +0000
+++ b/mysql-test/suite/pbxt/t/pbxt_bugs.test	2009-12-22 10:33:20 +0000
@@ -921,7 +921,8 @@ SELECT c1 FROM t2;
 DROP TABLE IF EXISTS t1;
 --enable_warnings
 CREATE TABLE t1 (c1 INTEGER NOT NULL PRIMARY KEY, c2 VARCHAR(255));
-LOAD DATA LOCAL INFILE 'suite/pbxt/t/load_unique_error1.inc' REPLACE INTO TABLE t1 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (@c1,c2) SET c1 = @c1 % 2;
+--replace_result $MYSQLTEST_VARDIR MYSQLTEST_VARDIR
+eval LOAD DATA LOCAL INFILE '$MYSQLTEST_VARDIR/std_data/pbxt_load_unique_error1.inc' REPLACE INTO TABLE t1 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (@c1,c2) SET c1 = @c1 % 2;
 --sorted_result
 SELECT * FROM t1 ORDER BY c1;
 DROP TABLE t1;

=== modified file 'mysql-test/suite/pbxt/t/pbxt_locking.test'
--- a/mysql-test/suite/pbxt/t/pbxt_locking.test	2009-04-02 10:03:14 +0000
+++ b/mysql-test/suite/pbxt/t/pbxt_locking.test	2009-12-22 10:33:20 +0000
@@ -1,6 +1,9 @@
 # This test covers various aspects of PBXT locking mechanism, including
 # internal permanent/temporary row locking and MySQL locking
 
+# SHOW PROCESSLIST has hardcoded "Writing to net" as state.
+-- source include/not_embedded.inc
+
 # TEST: select for update test
  
 drop table if exists t1;

=== modified file 'mysql-test/suite/pbxt/t/pbxt_transactions.test'
--- a/mysql-test/suite/pbxt/t/pbxt_transactions.test	2009-04-02 10:03:14 +0000
+++ b/mysql-test/suite/pbxt/t/pbxt_transactions.test	2009-12-22 10:33:20 +0000
@@ -1,3 +1,6 @@
+# We cannot run mysqldump against embedded server.
+-- source include/not_embedded.inc
+
 --disable_warnings
 drop table if exists t1, t2, t3;
 --enable_warnings

=== modified file 'mysql-test/suite/pbxt/t/ps_1general.test'
--- a/mysql-test/suite/pbxt/t/ps_1general.test	2009-04-02 10:03:14 +0000
+++ b/mysql-test/suite/pbxt/t/ps_1general.test	2009-12-22 10:33:20 +0000
@@ -582,7 +582,7 @@ prepare stmt1 from ' rename table t5 to
 create table t5 (a int) ;
 # rename must fail, t7 does not exist
 # Clean up the filename here because embedded server reports whole path
---replace_result $MYSQLTEST_VARDIR . master-data/ '' t7.frm t7
+--replace_result $MYSQLTEST_VARDIR . mysqld.1/data/ '' t7.frm t7
 --error 1017
 execute stmt1 ;
 create table t7 (a int) ;

=== modified file 'mysql-test/suite/rpl/r/rpl_err_ignoredtable.result'
--- a/mysql-test/suite/rpl/r/rpl_err_ignoredtable.result	2007-06-27 12:28:02 +0000
+++ b/mysql-test/suite/rpl/r/rpl_err_ignoredtable.result	2009-11-18 14:50:31 +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("Statement may not be safe to log in statement format.");
 create table t1 (a int primary key);
 create table t4 (a int primary key);
 insert into t1 values (1),(1);

=== modified file 'mysql-test/suite/rpl/r/rpl_extraCol_innodb.result'
--- a/mysql-test/suite/rpl/r/rpl_extraCol_innodb.result	2009-08-28 14:13:27 +0000
+++ b/mysql-test/suite/rpl/r/rpl_extraCol_innodb.result	2009-10-22 00:10:42 +0000
@@ -404,7 +404,11 @@ STOP SLAVE;
 RESET SLAVE;
 CREATE TABLE t9 (a INT KEY, b BLOB, c CHAR(5),
 d TIMESTAMP,
-e INT NOT NULL) ENGINE='InnoDB';
+e INT NOT NULL,
+f text not null,
+g text,
+h blob not null,
+i blob) ENGINE='InnoDB';
 *** Create t9 on Master ***
 CREATE TABLE t9 (a INT PRIMARY KEY, b BLOB, c CHAR(5)
 ) ENGINE='InnoDB';
@@ -415,47 +419,11 @@ START SLAVE;
 set @b1 = 'b1b1b1b1';
 set @b1 = concat(@b1,@b1);
 INSERT INTO t9 () VALUES(1,@b1,'Kyle'),(2,@b1,'JOE'),(3,@b1,'QA');
-SHOW SLAVE STATUS;
-Slave_IO_State	#
-Master_Host	127.0.0.1
-Master_User	root
-Master_Port	#
-Connect_Retry	1
-Master_Log_File	master-bin.000001
-Read_Master_Log_Pos	#
-Relay_Log_File	#
-Relay_Log_Pos	#
-Relay_Master_Log_File	master-bin.000001
-Slave_IO_Running	Yes
-Slave_SQL_Running	No
-Replicate_Do_DB	
-Replicate_Ignore_DB	
-Replicate_Do_Table	
-Replicate_Ignore_Table	#
-Replicate_Wild_Do_Table	
-Replicate_Wild_Ignore_Table	
-Last_Errno	1364
-Last_Error	Could not execute Write_rows event on table test.t9; Field 'e' doesn't have a default value, Error_code: 1364; handler error HA_ERR_ROWS_EVENT_APPLY; the event's master log master-bin.000001, end_log_pos 330
-Skip_Counter	0
-Exec_Master_Log_Pos	#
-Relay_Log_Space	#
-Until_Condition	None
-Until_Log_File	
-Until_Log_Pos	0
-Master_SSL_Allowed	No
-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	No
-Last_IO_Errno	#
-Last_IO_Error	#
-Last_SQL_Errno	1364
-Last_SQL_Error	Could not execute Write_rows event on table test.t9; Field 'e' doesn't have a default value, Error_code: 1364; handler error HA_ERR_ROWS_EVENT_APPLY; the event's master log master-bin.000001, end_log_pos 330
-SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
-START SLAVE;
+select * from t9;
+a	b	c	d	e	f	g	h	i
+1	b1b1b1b1b1b1b1b1	Kyle	0000-00-00 00:00:00	0		NULL		NULL
+2	b1b1b1b1b1b1b1b1	JOE	0000-00-00 00:00:00	0		NULL		NULL
+3	b1b1b1b1b1b1b1b1	QA	0000-00-00 00:00:00	0		NULL		NULL
 *** Create t10 on slave  ***
 STOP SLAVE;
 RESET SLAVE;

=== modified file 'mysql-test/suite/rpl/r/rpl_extraCol_myisam.result'
--- a/mysql-test/suite/rpl/r/rpl_extraCol_myisam.result	2009-08-28 14:13:27 +0000
+++ b/mysql-test/suite/rpl/r/rpl_extraCol_myisam.result	2009-10-22 00:10:42 +0000
@@ -404,7 +404,11 @@ STOP SLAVE;
 RESET SLAVE;
 CREATE TABLE t9 (a INT KEY, b BLOB, c CHAR(5),
 d TIMESTAMP,
-e INT NOT NULL) ENGINE='MyISAM';
+e INT NOT NULL,
+f text not null,
+g text,
+h blob not null,
+i blob) ENGINE='MyISAM';
 *** Create t9 on Master ***
 CREATE TABLE t9 (a INT PRIMARY KEY, b BLOB, c CHAR(5)
 ) ENGINE='MyISAM';
@@ -415,47 +419,11 @@ START SLAVE;
 set @b1 = 'b1b1b1b1';
 set @b1 = concat(@b1,@b1);
 INSERT INTO t9 () VALUES(1,@b1,'Kyle'),(2,@b1,'JOE'),(3,@b1,'QA');
-SHOW SLAVE STATUS;
-Slave_IO_State	#
-Master_Host	127.0.0.1
-Master_User	root
-Master_Port	#
-Connect_Retry	1
-Master_Log_File	master-bin.000001
-Read_Master_Log_Pos	#
-Relay_Log_File	#
-Relay_Log_Pos	#
-Relay_Master_Log_File	master-bin.000001
-Slave_IO_Running	Yes
-Slave_SQL_Running	No
-Replicate_Do_DB	
-Replicate_Ignore_DB	
-Replicate_Do_Table	
-Replicate_Ignore_Table	#
-Replicate_Wild_Do_Table	
-Replicate_Wild_Ignore_Table	
-Last_Errno	1364
-Last_Error	Could not execute Write_rows event on table test.t9; Field 'e' doesn't have a default value, Error_code: 1364; handler error HA_ERR_ROWS_EVENT_APPLY; the event's master log master-bin.000001, end_log_pos 330
-Skip_Counter	0
-Exec_Master_Log_Pos	#
-Relay_Log_Space	#
-Until_Condition	None
-Until_Log_File	
-Until_Log_Pos	0
-Master_SSL_Allowed	No
-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	No
-Last_IO_Errno	#
-Last_IO_Error	#
-Last_SQL_Errno	1364
-Last_SQL_Error	Could not execute Write_rows event on table test.t9; Field 'e' doesn't have a default value, Error_code: 1364; handler error HA_ERR_ROWS_EVENT_APPLY; the event's master log master-bin.000001, end_log_pos 330
-SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
-START SLAVE;
+select * from t9;
+a	b	c	d	e	f	g	h	i
+1	b1b1b1b1b1b1b1b1	Kyle	0000-00-00 00:00:00	0		NULL		NULL
+2	b1b1b1b1b1b1b1b1	JOE	0000-00-00 00:00:00	0		NULL		NULL
+3	b1b1b1b1b1b1b1b1	QA	0000-00-00 00:00:00	0		NULL		NULL
 *** Create t10 on slave  ***
 STOP SLAVE;
 RESET SLAVE;

=== modified file 'mysql-test/suite/rpl/r/rpl_get_lock.result'
--- a/mysql-test/suite/rpl/r/rpl_get_lock.result	2008-02-12 19:09:16 +0000
+++ b/mysql-test/suite/rpl/r/rpl_get_lock.result	2009-11-18 14:50:31 +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("Statement may not be safe to log in statement format.");
 create table t1(n int);
 insert into t1 values(get_lock("lock",2));
 select get_lock("lock",2);

=== added file 'mysql-test/suite/rpl/r/rpl_loaddata_symlink.result'
--- a/mysql-test/suite/rpl/r/rpl_loaddata_symlink.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_loaddata_symlink.result	2009-11-28 04:43:16 +0000
@@ -0,0 +1,17 @@
+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(a int not null auto_increment, b int, primary key(a) );
+load data infile '../../std_data/rpl_loaddata.dat' into table t1;
+select * from t1;
+a	b
+1	10
+2	15
+select * from t1;
+a	b
+1	10
+2	15
+drop table t1;

=== added file 'mysql-test/suite/rpl/r/rpl_nondeterministic_functions.result'
--- a/mysql-test/suite/rpl/r/rpl_nondeterministic_functions.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_nondeterministic_functions.result	2009-11-18 14:50:31 +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;
+CREATE TABLE t1 (a VARCHAR(1000));
+INSERT INTO t1 VALUES (CONNECTION_ID());
+INSERT INTO t1 VALUES (CONNECTION_ID());
+INSERT INTO t1 VALUES
+(CURDATE()),
+(CURRENT_DATE()),
+(CURRENT_TIME()),
+(CURRENT_TIMESTAMP()),
+(CURTIME()),
+(LOCALTIME()),
+(LOCALTIMESTAMP()),
+(NOW()),
+(UNIX_TIMESTAMP()),
+(UTC_DATE()),
+(UTC_TIME()),
+(UTC_TIMESTAMP());
+INSERT INTO t1 VALUES (RAND());
+INSERT INTO t1 VALUES (LAST_INSERT_ID());
+Comparing tables master:test.t1 and slave:test.t1
+DROP TABLE t1;

=== added file 'mysql-test/suite/rpl/r/rpl_not_null_innodb.result'
--- a/mysql-test/suite/rpl/r/rpl_not_null_innodb.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_not_null_innodb.result	2009-10-22 00:19:52 +0000
@@ -0,0 +1,202 @@
+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 t1(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t4(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+SET SQL_LOG_BIN= 1;
+CREATE TABLE t1(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT, `b` DATE DEFAULT '0000-00-00',
+`c` INT DEFAULT 500, 
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t4(`a` INT, `b` DATE DEFAULT '0000-00-00',
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+************* EXECUTION WITH INSERTS *************
+INSERT INTO t1(a,b,c) VALUES (1, null, 1);
+INSERT INTO t1(a,b,c) VALUES (2,'1111-11-11', 2);
+INSERT INTO t1(a,b) VALUES (3, null);
+INSERT INTO t1(a,c) VALUES (4, 4);
+INSERT INTO t1(a) VALUES (5);
+INSERT INTO t2(a,b) VALUES (1, null);
+INSERT INTO t2(a,b) VALUES (2,'1111-11-11');
+INSERT INTO t2(a) VALUES (3);
+INSERT INTO t3(a,b) VALUES (1, null);
+INSERT INTO t3(a,b) VALUES (2,'1111-11-11');
+INSERT INTO t3(a) VALUES (3);
+INSERT INTO t4(a,b,c) VALUES (1, null, 1);
+INSERT INTO t4(a,b,c) VALUES (2,'1111-11-11', 2);
+INSERT INTO t4(a,b) VALUES (3, null);
+INSERT INTO t4(a,c) VALUES (4, 4);
+INSERT INTO t4(a) VALUES (5);
+************* SHOWING THE RESULT SETS WITH INSERTS *************
+TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+Comparing tables master:test.t1 and slave:test.t1
+Comparing tables master:test.t2 and slave:test.t2
+TABLES t2 and t3 must be different.
+SELECT * FROM t3 ORDER BY a;
+a	b
+1	NULL
+2	1111-11-11
+3	NULL
+SELECT * FROM t3 ORDER BY a;
+a	b	c
+1	NULL	500
+2	1111-11-11	500
+3	NULL	500
+SELECT * FROM t4 ORDER BY a;
+a	b	c
+1	NULL	1
+2	1111-11-11	2
+3	NULL	NULL
+4	NULL	4
+5	NULL	NULL
+SELECT * FROM t4 ORDER BY a;
+a	b
+1	NULL
+2	1111-11-11
+3	NULL
+4	NULL
+5	NULL
+************* EXECUTION WITH UPDATES and REPLACES *************
+DELETE FROM t1;
+INSERT INTO t1(a,b,c) VALUES (1,'1111-11-11', 1);
+REPLACE INTO t1(a,b,c) VALUES (2,'1111-11-11', 2);
+UPDATE t1 set b= NULL, c= 300 where a= 1;
+REPLACE INTO t1(a,b,c) VALUES (2, NULL, 300);
+************* SHOWING THE RESULT SETS WITH UPDATES and REPLACES *************
+TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+Comparing tables master:test.t1 and slave:test.t1
+************* CLEANING *************
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+SET SQL_LOG_BIN= 0;
+CREATE TABLE t1 (`a` INT, `b` BIT DEFAULT NULL, `c` BIT DEFAULT NULL, 
+PRIMARY KEY (`a`)) ENGINE= Innodb;
+SET SQL_LOG_BIN= 1;
+CREATE TABLE t1 (`a` INT, `b` BIT DEFAULT b'01', `c` BIT DEFAULT NULL,
+PRIMARY KEY (`a`)) ENGINE= Innodb;
+************* EXECUTION WITH INSERTS *************
+INSERT INTO t1(a,b,c) VALUES (1, null, b'01');
+INSERT INTO t1(a,b,c) VALUES (2,b'00', b'01');
+INSERT INTO t1(a,b) VALUES (3, null);
+INSERT INTO t1(a,c) VALUES (4, b'01');
+INSERT INTO t1(a) VALUES (5);
+************* SHOWING THE RESULT SETS WITH INSERTS *************
+TABLES t1 and t2 must be different.
+SELECT a,b+0,c+0 FROM t1 ORDER BY a;
+a	b+0	c+0
+1	NULL	1
+2	0	1
+3	NULL	NULL
+4	NULL	1
+5	NULL	NULL
+SELECT a,b+0,c+0 FROM t1 ORDER BY a;
+a	b+0	c+0
+1	NULL	1
+2	0	1
+3	NULL	NULL
+4	NULL	1
+5	NULL	NULL
+************* EXECUTION WITH UPDATES and REPLACES *************
+DELETE FROM t1;
+INSERT INTO t1(a,b,c) VALUES (1,b'00', b'01');
+REPLACE INTO t1(a,b,c) VALUES (2,b'00',b'01');
+UPDATE t1 set b= NULL, c= b'00' where a= 1;
+REPLACE INTO t1(a,b,c) VALUES (2, NULL, b'00');
+************* SHOWING THE RESULT SETS WITH UPDATES and REPLACES *************
+TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+Comparing tables master:test.t1 and slave:test.t1
+DROP TABLE t1;
+################################################################################
+#                       NULL ---> NOT NULL (STRICT MODE)
+#                    UNCOMMENT THIS AFTER FIXING BUG#43992
+################################################################################
+################################################################################
+#                       NULL ---> NOT NULL (NON-STRICT MODE)
+################################################################################
+SET SQL_LOG_BIN= 0;
+CREATE TABLE t1(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+SET SQL_LOG_BIN= 1;
+CREATE TABLE t1(`a` INT NOT NULL, `b` INT NOT NULL, 
+`c` INT NOT NULL,
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT NOT NULL, `b` INT NOT NULL,
+`c` INT, 
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT NOT NULL, `b` INT NOT NULL,
+`c` INT DEFAULT 500, 
+PRIMARY KEY(`a`)) ENGINE=Innodb DEFAULT CHARSET=LATIN1;
+************* EXECUTION WITH INSERTS *************
+INSERT INTO t1(a) VALUES (1);
+INSERT INTO t1(a, b) VALUES (2, NULL);
+INSERT INTO t1(a, b) VALUES (3, 1);
+INSERT INTO t2(a) VALUES (1);
+INSERT INTO t2(a, b) VALUES (2, NULL);
+INSERT INTO t2(a, b) VALUES (3, 1);
+INSERT INTO t3(a) VALUES (1);
+INSERT INTO t3(a, b) VALUES (2, NULL);
+INSERT INTO t3(a, b) VALUES (3, 1);
+INSERT INTO t3(a, b) VALUES (4, 1);
+REPLACE INTO t3(a, b) VALUES (5, null);
+REPLACE INTO t3(a, b) VALUES (3, null);
+UPDATE t3 SET b = NULL where a = 4;
+************* SHOWING THE RESULT SETS *************
+SELECT * FROM t1 ORDER BY a;
+a	b
+1	NULL
+2	NULL
+3	1
+SELECT * FROM t1 ORDER BY a;
+a	b	c
+1	0	0
+2	0	0
+3	1	0
+SELECT * FROM t2 ORDER BY a;
+a	b
+1	NULL
+2	NULL
+3	1
+SELECT * FROM t2 ORDER BY a;
+a	b	c
+1	0	NULL
+2	0	NULL
+3	1	NULL
+SELECT * FROM t3 ORDER BY a;
+a	b
+1	NULL
+2	NULL
+3	NULL
+4	NULL
+5	NULL
+SELECT * FROM t3 ORDER BY a;
+a	b	c
+1	0	500
+2	0	500
+3	0	500
+4	0	500
+5	0	500
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;

=== added file 'mysql-test/suite/rpl/r/rpl_not_null_myisam.result'
--- a/mysql-test/suite/rpl/r/rpl_not_null_myisam.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_not_null_myisam.result	2009-10-22 00:19:52 +0000
@@ -0,0 +1,202 @@
+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 t1(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t4(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+SET SQL_LOG_BIN= 1;
+CREATE TABLE t1(`a` INT, `b` DATE DEFAULT NULL,
+`c` INT DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT, `b` DATE DEFAULT NULL,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT, `b` DATE DEFAULT '0000-00-00',
+`c` INT DEFAULT 500, 
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t4(`a` INT, `b` DATE DEFAULT '0000-00-00',
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+************* EXECUTION WITH INSERTS *************
+INSERT INTO t1(a,b,c) VALUES (1, null, 1);
+INSERT INTO t1(a,b,c) VALUES (2,'1111-11-11', 2);
+INSERT INTO t1(a,b) VALUES (3, null);
+INSERT INTO t1(a,c) VALUES (4, 4);
+INSERT INTO t1(a) VALUES (5);
+INSERT INTO t2(a,b) VALUES (1, null);
+INSERT INTO t2(a,b) VALUES (2,'1111-11-11');
+INSERT INTO t2(a) VALUES (3);
+INSERT INTO t3(a,b) VALUES (1, null);
+INSERT INTO t3(a,b) VALUES (2,'1111-11-11');
+INSERT INTO t3(a) VALUES (3);
+INSERT INTO t4(a,b,c) VALUES (1, null, 1);
+INSERT INTO t4(a,b,c) VALUES (2,'1111-11-11', 2);
+INSERT INTO t4(a,b) VALUES (3, null);
+INSERT INTO t4(a,c) VALUES (4, 4);
+INSERT INTO t4(a) VALUES (5);
+************* SHOWING THE RESULT SETS WITH INSERTS *************
+TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+Comparing tables master:test.t1 and slave:test.t1
+Comparing tables master:test.t2 and slave:test.t2
+TABLES t2 and t3 must be different.
+SELECT * FROM t3 ORDER BY a;
+a	b
+1	NULL
+2	1111-11-11
+3	NULL
+SELECT * FROM t3 ORDER BY a;
+a	b	c
+1	NULL	500
+2	1111-11-11	500
+3	NULL	500
+SELECT * FROM t4 ORDER BY a;
+a	b	c
+1	NULL	1
+2	1111-11-11	2
+3	NULL	NULL
+4	NULL	4
+5	NULL	NULL
+SELECT * FROM t4 ORDER BY a;
+a	b
+1	NULL
+2	1111-11-11
+3	NULL
+4	NULL
+5	NULL
+************* EXECUTION WITH UPDATES and REPLACES *************
+DELETE FROM t1;
+INSERT INTO t1(a,b,c) VALUES (1,'1111-11-11', 1);
+REPLACE INTO t1(a,b,c) VALUES (2,'1111-11-11', 2);
+UPDATE t1 set b= NULL, c= 300 where a= 1;
+REPLACE INTO t1(a,b,c) VALUES (2, NULL, 300);
+************* SHOWING THE RESULT SETS WITH UPDATES and REPLACES *************
+TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+Comparing tables master:test.t1 and slave:test.t1
+************* CLEANING *************
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;
+DROP TABLE t4;
+SET SQL_LOG_BIN= 0;
+CREATE TABLE t1 (`a` INT, `b` BIT DEFAULT NULL, `c` BIT DEFAULT NULL, 
+PRIMARY KEY (`a`)) ENGINE= MyISAM;
+SET SQL_LOG_BIN= 1;
+CREATE TABLE t1 (`a` INT, `b` BIT DEFAULT b'01', `c` BIT DEFAULT NULL,
+PRIMARY KEY (`a`)) ENGINE= MyISAM;
+************* EXECUTION WITH INSERTS *************
+INSERT INTO t1(a,b,c) VALUES (1, null, b'01');
+INSERT INTO t1(a,b,c) VALUES (2,b'00', b'01');
+INSERT INTO t1(a,b) VALUES (3, null);
+INSERT INTO t1(a,c) VALUES (4, b'01');
+INSERT INTO t1(a) VALUES (5);
+************* SHOWING THE RESULT SETS WITH INSERTS *************
+TABLES t1 and t2 must be different.
+SELECT a,b+0,c+0 FROM t1 ORDER BY a;
+a	b+0	c+0
+1	NULL	1
+2	0	1
+3	NULL	NULL
+4	NULL	1
+5	NULL	NULL
+SELECT a,b+0,c+0 FROM t1 ORDER BY a;
+a	b+0	c+0
+1	NULL	1
+2	0	1
+3	NULL	NULL
+4	NULL	1
+5	NULL	NULL
+************* EXECUTION WITH UPDATES and REPLACES *************
+DELETE FROM t1;
+INSERT INTO t1(a,b,c) VALUES (1,b'00', b'01');
+REPLACE INTO t1(a,b,c) VALUES (2,b'00',b'01');
+UPDATE t1 set b= NULL, c= b'00' where a= 1;
+REPLACE INTO t1(a,b,c) VALUES (2, NULL, b'00');
+************* SHOWING THE RESULT SETS WITH UPDATES and REPLACES *************
+TABLES t1 and t2 must be equal otherwise an error will be thrown. 
+Comparing tables master:test.t1 and slave:test.t1
+DROP TABLE t1;
+################################################################################
+#                       NULL ---> NOT NULL (STRICT MODE)
+#                    UNCOMMENT THIS AFTER FIXING BUG#43992
+################################################################################
+################################################################################
+#                       NULL ---> NOT NULL (NON-STRICT MODE)
+################################################################################
+SET SQL_LOG_BIN= 0;
+CREATE TABLE t1(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT NOT NULL, `b` INT,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+SET SQL_LOG_BIN= 1;
+CREATE TABLE t1(`a` INT NOT NULL, `b` INT NOT NULL, 
+`c` INT NOT NULL,
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t2(`a` INT NOT NULL, `b` INT NOT NULL,
+`c` INT, 
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+CREATE TABLE t3(`a` INT NOT NULL, `b` INT NOT NULL,
+`c` INT DEFAULT 500, 
+PRIMARY KEY(`a`)) ENGINE=MyISAM DEFAULT CHARSET=LATIN1;
+************* EXECUTION WITH INSERTS *************
+INSERT INTO t1(a) VALUES (1);
+INSERT INTO t1(a, b) VALUES (2, NULL);
+INSERT INTO t1(a, b) VALUES (3, 1);
+INSERT INTO t2(a) VALUES (1);
+INSERT INTO t2(a, b) VALUES (2, NULL);
+INSERT INTO t2(a, b) VALUES (3, 1);
+INSERT INTO t3(a) VALUES (1);
+INSERT INTO t3(a, b) VALUES (2, NULL);
+INSERT INTO t3(a, b) VALUES (3, 1);
+INSERT INTO t3(a, b) VALUES (4, 1);
+REPLACE INTO t3(a, b) VALUES (5, null);
+REPLACE INTO t3(a, b) VALUES (3, null);
+UPDATE t3 SET b = NULL where a = 4;
+************* SHOWING THE RESULT SETS *************
+SELECT * FROM t1 ORDER BY a;
+a	b
+1	NULL
+2	NULL
+3	1
+SELECT * FROM t1 ORDER BY a;
+a	b	c
+1	0	0
+2	0	0
+3	1	0
+SELECT * FROM t2 ORDER BY a;
+a	b
+1	NULL
+2	NULL
+3	1
+SELECT * FROM t2 ORDER BY a;
+a	b	c
+1	0	NULL
+2	0	NULL
+3	1	NULL
+SELECT * FROM t3 ORDER BY a;
+a	b
+1	NULL
+2	NULL
+3	NULL
+4	NULL
+5	NULL
+SELECT * FROM t3 ORDER BY a;
+a	b	c
+1	0	500
+2	0	500
+3	0	500
+4	0	500
+5	0	500
+DROP TABLE t1;
+DROP TABLE t2;
+DROP TABLE t3;

=== modified file 'mysql-test/suite/rpl/r/rpl_row_create_table.result'
--- a/mysql-test/suite/rpl/r/rpl_row_create_table.result	2009-10-06 00:54:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_row_create_table.result	2009-11-27 13:34:39 +0000
@@ -476,4 +476,30 @@ master-bin.000001	#	Table_map	#	#	table_
 master-bin.000001	#	Write_rows	#	#	table_id: # flags: STMT_END_F
 master-bin.000001	#	Query	#	#	COMMIT
 DROP DATABASE mysqltest1;
+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 TEMPORARY TABLE t7(c1 INT);
+CREATE TABLE t5(c1 INT);
+CREATE TABLE t4(c1 INT);
+CREATE VIEW bug48506_t1 AS SELECT 1;
+CREATE VIEW bug48506_t2 AS SELECT * FROM t4;
+CREATE VIEW bug48506_t3 AS SELECT t5.c1 AS A, t4.c1 AS B FROM t5, t4;
+CREATE TABLE bug48506_t4(c1 INT);
+DROP VIEW bug48506_t1, bug48506_t2, bug48506_t3;
+DROP TABLE bug48506_t4;
+CREATE TABLE IF NOT EXISTS bug48506_t1 LIKE t7;
+CREATE TABLE IF NOT EXISTS bug48506_t2 LIKE t7;
+CREATE TABLE IF NOT EXISTS bug48506_t3 LIKE t7;
+CREATE TABLE IF NOT EXISTS bug48506_t4 LIKE t7;
+SHOW TABLES LIKE 'bug48506%';
+Tables_in_test (bug48506%)
+bug48506_t4
+DROP VIEW IF EXISTS bug48506_t1, bug48506_t2, bug48506_t3;
+DROP TEMPORARY TABLES t7;
+DROP TABLES t4, t5;
+DROP TABLES IF EXISTS bug48506_t4;
 end of the tests

=== modified file 'mysql-test/suite/rpl/r/rpl_row_tabledefs_2myisam.result'
--- a/mysql-test/suite/rpl/r/rpl_row_tabledefs_2myisam.result	2008-03-14 20:02:52 +0000
+++ b/mysql-test/suite/rpl/r/rpl_row_tabledefs_2myisam.result	2009-10-22 00:10:42 +0000
@@ -105,47 +105,9 @@ a	b	x
 2	10	Foo is a bar
 INSERT INTO t9 VALUES (2);
 INSERT INTO t1_nodef VALUES (1,2);
-SHOW SLAVE STATUS;
-Slave_IO_State	#
-Master_Host	127.0.0.1
-Master_User	root
-Master_Port	#
-Connect_Retry	1
-Master_Log_File	master-bin.000001
-Read_Master_Log_Pos	#
-Relay_Log_File	#
-Relay_Log_Pos	#
-Relay_Master_Log_File	master-bin.000001
-Slave_IO_Running	Yes
-Slave_SQL_Running	No
-Replicate_Do_DB	
-Replicate_Ignore_DB	
-Replicate_Do_Table	
-Replicate_Ignore_Table	
-Replicate_Wild_Do_Table	
-Replicate_Wild_Ignore_Table	
-Last_Errno	1364
-Last_Error	<Last_Error>
-Skip_Counter	0
-Exec_Master_Log_Pos	#
-Relay_Log_Space	#
-Until_Condition	None
-Until_Log_File	
-Until_Log_Pos	0
-Master_SSL_Allowed	No
-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	No
-Last_IO_Errno	<Last_IO_Errno>
-Last_IO_Error	<Last_IO_Error>
-Last_SQL_Errno	1364
-Last_SQL_Error	<Last_SQL_Error>
-SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
-START SLAVE;
+select count(*) from t1_nodef;
+count(*)
+1
 INSERT INTO t9 VALUES (2);
 **** On Master ****
 INSERT INTO t2 VALUES (2,4);

=== modified file 'mysql-test/suite/rpl/r/rpl_row_tabledefs_3innodb.result'
--- a/mysql-test/suite/rpl/r/rpl_row_tabledefs_3innodb.result	2008-03-14 20:02:52 +0000
+++ b/mysql-test/suite/rpl/r/rpl_row_tabledefs_3innodb.result	2009-10-22 00:10:42 +0000
@@ -105,47 +105,9 @@ a	b	x
 2	10	Foo is a bar
 INSERT INTO t9 VALUES (2);
 INSERT INTO t1_nodef VALUES (1,2);
-SHOW SLAVE STATUS;
-Slave_IO_State	#
-Master_Host	127.0.0.1
-Master_User	root
-Master_Port	#
-Connect_Retry	1
-Master_Log_File	master-bin.000001
-Read_Master_Log_Pos	#
-Relay_Log_File	#
-Relay_Log_Pos	#
-Relay_Master_Log_File	master-bin.000001
-Slave_IO_Running	Yes
-Slave_SQL_Running	No
-Replicate_Do_DB	
-Replicate_Ignore_DB	
-Replicate_Do_Table	
-Replicate_Ignore_Table	
-Replicate_Wild_Do_Table	
-Replicate_Wild_Ignore_Table	
-Last_Errno	1364
-Last_Error	<Last_Error>
-Skip_Counter	0
-Exec_Master_Log_Pos	#
-Relay_Log_Space	#
-Until_Condition	None
-Until_Log_File	
-Until_Log_Pos	0
-Master_SSL_Allowed	No
-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	No
-Last_IO_Errno	<Last_IO_Errno>
-Last_IO_Error	<Last_IO_Error>
-Last_SQL_Errno	1364
-Last_SQL_Error	<Last_SQL_Error>
-SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
-START SLAVE;
+select count(*) from t1_nodef;
+count(*)
+1
 INSERT INTO t9 VALUES (2);
 **** On Master ****
 INSERT INTO t2 VALUES (2,4);

=== added file 'mysql-test/suite/rpl/r/rpl_row_trunc_temp.result'
--- a/mysql-test/suite/rpl/r/rpl_row_trunc_temp.result	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/r/rpl_row_trunc_temp.result	2009-11-22 05:10:33 +0000
@@ -0,0 +1,29 @@
+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 TEMPORARY TABLE t1(c1 INTEGER);
+CREATE TABLE t2(c1 INTEGER);
+CREATE TABLE t1(c1 INTEGER);
+INSERT INTO t1 VALUES(1), (2);
+INSERT INTO t2 VALUES(1), (2);
+SELECT * FROM t1;
+c1
+1
+2
+SELECT * FROM t2;
+c1
+1
+2
+TRUNCATE t1;
+TRUNCATE t2;
+SELECT * FROM t1;
+c1
+1
+2
+SELECT * FROM t2;
+c1
+DROP TABLE t1;
+DROP TABLE t2;

=== modified file 'mysql-test/suite/rpl/r/rpl_stm_000001.result'
--- a/mysql-test/suite/rpl/r/rpl_stm_000001.result	2007-12-12 17:19:24 +0000
+++ b/mysql-test/suite/rpl/r/rpl_stm_000001.result	2009-11-18 14:50:31 +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("Statement may not be safe to log in statement format.");
 create table t1 (word char(20) not null);
 load data infile '../../std_data/words.dat' into table t1;
 load data local infile 'MYSQL_TEST_DIR/std_data/words.dat' into table t1;

=== modified file 'mysql-test/suite/rpl/r/rpl_temporary.result'
--- a/mysql-test/suite/rpl/r/rpl_temporary.result	2009-05-22 23:29:41 +0000
+++ b/mysql-test/suite/rpl/r/rpl_temporary.result	2010-01-11 13:15:28 +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 \'user\' Error_code: 1032");
+SET sql_log_bin = 0;
+SET sql_log_bin = 1;
 reset master;
 DROP TABLE IF EXISTS t1;
 CREATE TEMPORARY TABLE t1 (a char(1));
@@ -127,6 +128,8 @@ select * from t1;
 a
 1
 drop table t1;
+SET sql_log_bin = 0;
+SET sql_log_bin = 1;
 -- Bug#43748
 -- make a user on the slave that can list but not kill system threads.
 FLUSH PRIVILEGES;

=== modified file 'mysql-test/suite/rpl/r/rpl_trigger.result'
--- a/mysql-test/suite/rpl/r/rpl_trigger.result	2009-08-03 09:47:45 +0000
+++ b/mysql-test/suite/rpl/r/rpl_trigger.result	2009-11-18 14:50:31 +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("Statement may not be safe to log in statement format.");
 DROP TABLE IF EXISTS t1;
 DROP TABLE IF EXISTS t2;
 DROP TABLE IF EXISTS t3;

=== modified file 'mysql-test/suite/rpl/t/disabled.def'
--- a/mysql-test/suite/rpl/t/disabled.def	2009-09-27 10:12:58 +0000
+++ b/mysql-test/suite/rpl/t/disabled.def	2009-12-01 09:21:15 +0000
@@ -10,3 +10,4 @@
 #
 ##############################################################################
 
+rpl_row_create_table    : Bug#45576 2009-12-01 joro rpl_row_create_table fails on PB2

=== modified file 'mysql-test/suite/rpl/t/rpl_err_ignoredtable.test'
--- a/mysql-test/suite/rpl/t/rpl_err_ignoredtable.test	2009-10-20 18:00:07 +0000
+++ b/mysql-test/suite/rpl/t/rpl_err_ignoredtable.test	2009-11-18 14:50:31 +0000
@@ -7,6 +7,8 @@
 
 -- source include/master-slave.inc
 
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
+
 connection master;
 create table t1 (a int primary key);
 create table t4 (a int primary key);
@@ -14,19 +16,15 @@ create table t4 (a int primary key);
 --error 1022, ER_DUP_ENTRY
 insert into t1 values (1),(1);
 insert into t4 values (1),(2);
-save_master_pos;
-connection slave;
 # as the t1 table is ignored on the slave, the slave should be able to sync
-sync_with_master;
+sync_slave_with_master;
 # check that the table has been ignored, because otherwise the test is nonsense
 show tables like 't1';
 show tables like 't4';
 SELECT * FROM test.t4 ORDER BY a;
 connection master;
 drop table t1;
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 
 # Now test that even critical errors (connection killed)
 # are ignored if rules allow it.
@@ -50,18 +48,17 @@ kill @id;
 drop table t2,t3;
 insert into t4 values (3),(4);
 connection master;
+# The get_lock function causes warning for unsafe statement.
+--disable_warnings
 --error 0,1317,2013
 reap;
+--enable_warnings
 connection master1;
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 SELECT * FROM test.t4 ORDER BY a;
 
 connection master1;
 DROP TABLE test.t4;
-save_master_pos;
-connection slave;
-sync_with_master;
+sync_slave_with_master;
 # End of 4.1 tests
 # Adding comment for force manual merge 5.0 -> wl1012. delete me if needed

=== modified file 'mysql-test/suite/rpl/t/rpl_get_lock.test'
--- a/mysql-test/suite/rpl/t/rpl_get_lock.test	2007-06-27 12:28:02 +0000
+++ b/mysql-test/suite/rpl/t/rpl_get_lock.test	2009-11-18 14:50:31 +0000
@@ -1,7 +1,12 @@
 source include/master-slave.inc;
 
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
+
 create table t1(n int);
+# Use of get_lock gives a warning for unsafeness if binlog_format=statement
+--disable_warnings
 insert into t1 values(get_lock("lock",2));
+--enable_warnings
 dirty_close master;
 connection master1;
 select get_lock("lock",2);

=== modified file 'mysql-test/suite/rpl/t/rpl_ignore_table.test'
--- a/mysql-test/suite/rpl/t/rpl_ignore_table.test	2008-11-13 19:19:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_ignore_table.test	2009-12-27 13:54:41 +0000
@@ -1,4 +1,6 @@
 source include/master-slave.inc;
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
 
 #
 # BUG#16487

=== added file 'mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.opt'
--- a/mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.opt	2009-11-28 04:43:16 +0000
@@ -0,0 +1 @@
+--secure-file-priv=$MYSQLTEST_VARDIR/std_data_master_link

=== added file 'mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.sh'
--- a/mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.sh	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_loaddata_symlink-master.sh	2009-11-28 04:43:16 +0000
@@ -0,0 +1 @@
+ln -s $MYSQLTEST_VARDIR/std_data $MYSQLTEST_VARDIR/std_data_master_link

=== added file 'mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.opt'
--- a/mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.opt	2009-11-28 04:43:16 +0000
@@ -0,0 +1 @@
+--slave-load-tmpdir=$MYSQLTEST_VARDIR/std_data_slave_link

=== added file 'mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.sh'
--- a/mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.sh	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_loaddata_symlink-slave.sh	2009-11-28 04:43:16 +0000
@@ -0,0 +1 @@
+ln -s $MYSQLTEST_VARDIR/std_data $MYSQLTEST_VARDIR/std_data_slave_link

=== added file 'mysql-test/suite/rpl/t/rpl_loaddata_symlink.test'
--- a/mysql-test/suite/rpl/t/rpl_loaddata_symlink.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_loaddata_symlink.test	2009-11-28 04:43:16 +0000
@@ -0,0 +1,20 @@
+#
+# BUG#43913
+# This test verifies if loading data infile will work fine 
+# if the path of the load data file is a symbolic link.
+#
+--source include/master-slave.inc
+--source include/have_binlog_format_statement.inc
+
+create table t1(a int not null auto_increment, b int, primary key(a) );
+load data infile '../../std_data/rpl_loaddata.dat' into table t1;
+select * from t1;
+
+sync_slave_with_master;
+connection slave;
+select * from t1;
+
+connection master;
+drop table t1;
+sync_slave_with_master;
+

=== added file 'mysql-test/suite/rpl/t/rpl_nondeterministic_functions.test'
--- a/mysql-test/suite/rpl/t/rpl_nondeterministic_functions.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_nondeterministic_functions.test	2009-11-18 14:50:31 +0000
@@ -0,0 +1,53 @@
+# ==== Purpose ====
+#
+# Test that nondeterministic system functions are correctly replicated.
+#
+# (Some functions are only correctly replicated if binlog_format=MIXED
+# or ROW.  See binlog_unsafe.test for a test that those variables are
+# indeed unsafe.)
+#
+# ==== Implementation ====
+#
+# We insert the values of each unsafe function into a table. Then we
+# replicate and check that the table is identical on slave.
+#
+# ==== Related bugs ====
+#
+# BUG#47995
+
+--source include/master-slave.inc
+
+CREATE TABLE t1 (a VARCHAR(1000));
+
+# We replicate the connection_id in the query_log_event
+INSERT INTO t1 VALUES (CONNECTION_ID());
+--connection master1
+INSERT INTO t1 VALUES (CONNECTION_ID());
+
+# We replicate the TIMESTAMP variable, so the following functions that
+# are affected by the TIMESTAMP variable should be safe to replicate.
+INSERT INTO t1 VALUES
+  (CURDATE()),
+  (CURRENT_DATE()),
+  (CURRENT_TIME()),
+  (CURRENT_TIMESTAMP()),
+  (CURTIME()),
+  (LOCALTIME()),
+  (LOCALTIMESTAMP()),
+  (NOW()),
+  (UNIX_TIMESTAMP()),
+  (UTC_DATE()),
+  (UTC_TIME()),
+  (UTC_TIMESTAMP());
+
+# We replicate the random seed in a rand_log_event
+INSERT INTO t1 VALUES (RAND());
+# We replicate the last_insert_id in an intvar_log_event
+INSERT INTO t1 VALUES (LAST_INSERT_ID());
+
+--sync_slave_with_master
+--let $diff_table_1= master:test.t1
+--let $diff_table_2= slave:test.t1
+--source include/diff_tables.inc
+
+DROP TABLE t1;

=== added file 'mysql-test/suite/rpl/t/rpl_not_null_innodb.test'
--- a/mysql-test/suite/rpl/t/rpl_not_null_innodb.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_not_null_innodb.test	2009-10-22 00:15:45 +0000
@@ -0,0 +1,19 @@
+#################################################################################
+# This test checks if the replication between "null" fields to either "null"
+# fields or "not null" fields works properly. In the first case, the execution
+# should work fine. In the second case, it may fail according to the sql_mode
+# being used.
+#
+# The test is devided in three main parts:
+#
+# 1 - NULL --> NULL (no failures)
+# 2 - NULL --> NOT NULL ( sql-mode  = STRICT and failures)
+# 3 - NULL --> NOT NULL ( sql-mode != STRICT and no failures)
+#
+#################################################################################
+--source include/master-slave.inc
+--source include/have_innodb.inc
+--source include/have_binlog_format_row.inc
+
+let $engine=Innodb;
+--source extra/rpl_tests/rpl_not_null.test

=== added file 'mysql-test/suite/rpl/t/rpl_not_null_myisam.test'
--- a/mysql-test/suite/rpl/t/rpl_not_null_myisam.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_not_null_myisam.test	2009-10-22 00:15:45 +0000
@@ -0,0 +1,18 @@
+#################################################################################
+# This test checks if the replication between "null" fields to either "null"
+# fields or "not null" fields works properly. In the first case, the execution
+# should work fine. In the second case, it may fail according to the sql_mode
+# being used.
+#
+# The test is devided in three main parts:
+#
+# 1 - NULL --> NULL (no failures)
+# 2 - NULL --> NOT NULL ( sql-mode  = STRICT and failures)
+# 3 - NULL --> NOT NULL ( sql-mode != STRICT and no failures)
+#
+#################################################################################
+--source include/master-slave.inc
+--source include/have_binlog_format_row.inc
+
+let $engine=MyISAM;
+--source extra/rpl_tests/rpl_not_null.test

=== modified file 'mysql-test/suite/rpl/t/rpl_row_create_table.test'
--- a/mysql-test/suite/rpl/t/rpl_row_create_table.test	2009-01-23 12:22:05 +0000
+++ b/mysql-test/suite/rpl/t/rpl_row_create_table.test	2009-11-27 13:34:39 +0000
@@ -292,4 +292,40 @@ connection master;
 DROP DATABASE mysqltest1;
 sync_slave_with_master;
 
+#
+# BUG#48506: crash in CREATE TABLE <existing_view> IF NOT EXISTS LIKE
+# <tmp_tbl> with RBL
+#
+
+source include/master-slave-reset.inc;
+
+connection master;
+CREATE TEMPORARY TABLE t7(c1 INT);
+CREATE TABLE t5(c1 INT);
+CREATE TABLE t4(c1 INT);
+CREATE VIEW bug48506_t1 AS SELECT 1;
+CREATE VIEW bug48506_t2 AS SELECT * FROM t4;
+CREATE VIEW bug48506_t3 AS SELECT t5.c1 AS A, t4.c1 AS B FROM t5, t4;
+CREATE TABLE bug48506_t4(c1 INT);
+--disable_warnings
+sync_slave_with_master;
+DROP VIEW bug48506_t1, bug48506_t2, bug48506_t3;
+DROP TABLE bug48506_t4;
+
+connection master;
+CREATE TABLE IF NOT EXISTS bug48506_t1 LIKE t7;
+CREATE TABLE IF NOT EXISTS bug48506_t2 LIKE t7;
+CREATE TABLE IF NOT EXISTS bug48506_t3 LIKE t7;
+CREATE TABLE IF NOT EXISTS bug48506_t4 LIKE t7;
+--enable_warnings
+sync_slave_with_master;
+
+SHOW TABLES LIKE 'bug48506%';
+
+connection master;
+DROP VIEW IF EXISTS bug48506_t1, bug48506_t2, bug48506_t3;
+DROP TEMPORARY TABLES t7;
+DROP TABLES t4, t5;
+DROP TABLES IF EXISTS bug48506_t4;
+source include/master-slave-end.inc;
 --echo end of the tests

=== added file 'mysql-test/suite/rpl/t/rpl_row_trunc_temp.test'
--- a/mysql-test/suite/rpl/t/rpl_row_trunc_temp.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/suite/rpl/t/rpl_row_trunc_temp.test	2009-11-22 05:10:33 +0000
@@ -0,0 +1,35 @@
+#
+# Bug#48350 truncate temporary table crashes replication 
+#
+# All statements operating on temporary tables should not be binlogged in RBR.
+# However, before fix of bug#48350, 'TRUNCATE ...' statement on a temporary
+# table was binlogged in RBR.
+#
+
+--source include/master-slave.inc
+--source include/have_binlog_format_row.inc
+
+#This statement is not binlogged in RBR.
+CREATE TEMPORARY TABLE t1(c1 INTEGER);
+CREATE TABLE t2(c1 INTEGER);
+sync_slave_with_master;
+
+CREATE TABLE t1(c1 INTEGER);
+INSERT INTO t1 VALUES(1), (2);
+INSERT INTO t2 VALUES(1), (2);
+SELECT * FROM t1;
+SELECT * FROM t2;
+
+connection master;
+TRUNCATE t1;
+TRUNCATE t2;
+sync_slave_with_master;
+# t1 will have nothing, if 'TRUNCATE t1' has been replicate from master to
+# slave.
+SELECT * FROM t1;
+SELECT * FROM t2;
+
+DROP TABLE t1;
+connection master;
+DROP TABLE t2;
+--source include/master-slave-end.inc

=== modified file 'mysql-test/suite/rpl/t/rpl_temporary.test'
--- a/mysql-test/suite/rpl/t/rpl_temporary.test	2009-05-22 23:29:41 +0000
+++ b/mysql-test/suite/rpl/t/rpl_temporary.test	2010-01-11 13:15:28 +0000
@@ -1,7 +1,10 @@
+-- source include/master-slave.inc
+
 # Test need anonymous user when connection are made as "zedjzlcsjhd"
+# But we only need it on the master, not the slave.
+SET sql_log_bin = 0;
 source include/add_anonymous_users.inc;
-
--- source include/master-slave.inc
+SET sql_log_bin = 1;
 
 # Clean up old slave's binlogs.
 # The slave is started with --log-slave-updates
@@ -17,9 +20,6 @@ source include/add_anonymous_users.inc;
 save_master_pos;
 connection slave;
 
-# Add suppression for expected warning(s) in slaves error log
-call mtr.add_suppression("Slave: Can\'t find record in \'user\' Error_code: 1032");
-
 sync_with_master;
 reset master;
 
@@ -291,7 +291,9 @@ drop table t1;
 --remove_file $MYSQLTEST_VARDIR/tmp/bug14157.sql
 
 # Delete the anonymous users
+SET sql_log_bin = 0;
 source include/delete_anonymous_users.inc;
+SET sql_log_bin = 1;
 
 
 

=== modified file 'mysql-test/suite/rpl/t/rpl_trigger.test'
--- a/mysql-test/suite/rpl/t/rpl_trigger.test	2009-08-03 15:01:06 +0000
+++ b/mysql-test/suite/rpl/t/rpl_trigger.test	2009-11-18 14:50:31 +0000
@@ -5,6 +5,8 @@
 --source include/have_binlog_format_mixed_or_statement.inc 
 --source include/master-slave.inc
 
+CALL mtr.add_suppression("Statement may not be safe to log in statement format.");
+
 --disable_warnings
 DROP TABLE IF EXISTS t1;
 DROP TABLE IF EXISTS t2;
@@ -89,7 +91,11 @@ end
 |
 
 delimiter ;|
+# The trigger causes a warning for unsafe statement when
+# binlog_format=statement since it uses get_lock.
+--disable_warnings
 insert into t1 set a = now();
+--enable_warnings
 select a=b && a=c from t1;
 let $time=`select a from t1`;
 
@@ -135,7 +141,11 @@ disconnect con2;
 truncate table t1;
 drop trigger t1_first;
 
+# The trigger causes a warning for unsafe statement when
+# binlog_format=statement since it uses get_lock.
+--disable_warnings
 insert into t1 values ("2003-03-03","2003-03-03","2003-03-03"),(bug12480(),bug12480(),bug12480()),(now(),now(),now());
+--enable_warnings
 select a=b && a=c from t1;
 
 drop function bug12480;

=== modified file 'mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result'
--- a/mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result	2009-08-29 08:30:59 +0000
+++ b/mysql-test/suite/rpl_ndb/r/rpl_ndb_extraCol.result	2009-10-22 00:21:50 +0000
@@ -400,62 +400,6 @@ set @b1 = concat(@b1,@b1);
 INSERT INTO t8 () VALUES(1,@b1,'Kyle'),(2,@b1,'JOE'),(3,@b1,'QA');
 *** Drop t8  ***
 DROP TABLE t8;
-STOP SLAVE;
-RESET SLAVE;
-CREATE TABLE t9 (a INT KEY, b BLOB, c CHAR(5),
-d TIMESTAMP,
-e INT NOT NULL) ENGINE='NDB';
-*** Create t9 on Master ***
-CREATE TABLE t9 (a INT PRIMARY KEY, b BLOB, c CHAR(5)
-) ENGINE='NDB';
-RESET MASTER;
-*** Start Slave ***
-START SLAVE;
-*** Master Data Insert ***
-set @b1 = 'b1b1b1b1';
-set @b1 = concat(@b1,@b1);
-INSERT INTO t9 () VALUES(1,@b1,'Kyle'),(2,@b1,'JOE'),(3,@b1,'QA');
-SHOW SLAVE STATUS;
-Slave_IO_State	#
-Master_Host	127.0.0.1
-Master_User	root
-Master_Port	#
-Connect_Retry	1
-Master_Log_File	master-bin.000001
-Read_Master_Log_Pos	#
-Relay_Log_File	#
-Relay_Log_Pos	#
-Relay_Master_Log_File	master-bin.000001
-Slave_IO_Running	Yes
-Slave_SQL_Running	No
-Replicate_Do_DB	
-Replicate_Ignore_DB	
-Replicate_Do_Table	
-Replicate_Ignore_Table	#
-Replicate_Wild_Do_Table	
-Replicate_Wild_Ignore_Table	
-Last_Errno	1364
-Last_Error	Could not execute Write_rows event on table test.t9; Field 'e' doesn't have a default value, Error_code: 1364; handler error HA_ERR_ROWS_EVENT_APPLY; the event's master log master-bin.000001, end_log_pos 447
-Skip_Counter	0
-Exec_Master_Log_Pos	#
-Relay_Log_Space	#
-Until_Condition	None
-Until_Log_File	
-Until_Log_Pos	0
-Master_SSL_Allowed	No
-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	No
-Last_IO_Errno	#
-Last_IO_Error	#
-Last_SQL_Errno	1364
-Last_SQL_Error	Could not execute Write_rows event on table test.t9; Field 'e' doesn't have a default value, Error_code: 1364; handler error HA_ERR_ROWS_EVENT_APPLY; the event's master log master-bin.000001, end_log_pos 447
-SET GLOBAL SQL_SLAVE_SKIP_COUNTER=2;
-START SLAVE;
 *** Create t10 on slave  ***
 STOP SLAVE;
 RESET SLAVE;

=== modified file 'mysql-test/t/archive.test'
--- a/mysql-test/t/archive.test	2009-12-03 11:19:05 +0000
+++ b/mysql-test/t/archive.test	2010-01-15 15:27:55 +0000
@@ -1625,3 +1625,24 @@ INSERT INTO t1 VALUES('aaaaaaaaaaaaaaaaa
 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;
+
+#
+# BUG#47012 archive tables are not upgradeable, and server crashes on any access
+#
+let $MYSQLD_DATADIR= `SELECT @@datadir`;
+copy_file std_data/bug47012.frm $MYSQLD_DATADIR/test/t1.frm;
+copy_file std_data/bug47012.ARZ $MYSQLD_DATADIR/test/t1.ARZ;
+copy_file std_data/bug47012.ARM $MYSQLD_DATADIR/test/t1.ARM;
+
+--error ER_TABLE_NEEDS_UPGRADE
+SHOW CREATE TABLE t1;
+
+--error ER_TABLE_NEEDS_UPGRADE
+SELECT * FROM t1;
+
+--error ER_TABLE_NEEDS_UPGRADE
+INSERT INTO t1 (col1, col2) VALUES (1, "value");
+
+REPAIR TABLE t1;
+DROP TABLE t1;
+remove_file $MYSQLD_DATADIR/test/t1.ARM;

=== added file 'mysql-test/t/bug47671-master.opt'
--- a/mysql-test/t/bug47671-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/bug47671-master.opt	2009-11-25 06:55:49 +0000
@@ -0,0 +1 @@
+--default-character-set=utf8 --skip-character-set-client-handshake

=== added file 'mysql-test/t/bug47671.test'
--- a/mysql-test/t/bug47671.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/bug47671.test	2009-11-30 05:24:26 +0000
@@ -0,0 +1,9 @@
+# Embedded server doesn't support external clients
+--source include/not_embedded.inc
+
+--echo #
+--echo # Bug#47671 - wrong character-set after upgrade from 5.1.34 to 5.1.39
+--echo #
+--echo # Extract only charset information from 'status' command output using regex
+--replace_regex /.*mysql.*// /Connection.*// /Current.*//  /SSL.*// /Using.*// /Server version.*// /Protocol.*// /UNIX.*// /Uptime.*// /Threads.*// /TCP.*//
+--exec $MYSQL -e "status";

=== added file 'mysql-test/t/create-uca.test'
--- a/mysql-test/t/create-uca.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/create-uca.test	2009-12-27 13:54:41 +0000
@@ -0,0 +1,26 @@
+# Prerequisites
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
+
+# Initial cleanup
+--disable_warnings
+drop table if exists t1,t2;
+--enable_warnings
+
+#
+# Bug#21380: DEFAULT definition not always transfered by CREATE
+# TABLE/SELECT to the new table.
+#
+
+CREATE TABLE t1(
+  c1 INT DEFAULT 12 COMMENT 'column1',
+  c2 INT NULL COMMENT 'column2',
+  c3 INT NOT NULL COMMENT 'column3',
+  c4 VARCHAR(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
+  c5 VARCHAR(255) COLLATE utf8_unicode_ci NULL DEFAULT 'b',
+  c6 VARCHAR(255))
+  COLLATE latin1_bin;
+SHOW CREATE TABLE t1;
+CREATE TABLE t2 AS SELECT * FROM t1;
+SHOW CREATE TABLE t2;
+DROP TABLE t1,t2;

=== modified file 'mysql-test/t/create.test'
--- a/mysql-test/t/create.test	2009-12-03 11:19:05 +0000
+++ b/mysql-test/t/create.test	2009-12-27 13:54:41 +0000
@@ -1400,52 +1400,6 @@ drop table t1;
 
 --echo
 --echo # --
---echo # -- Bug#21380: DEFAULT definition not always transfered by CREATE
---echo # -- TABLE/SELECT to the new table.
---echo # --
---echo
-
-
---disable_warnings
-DROP TABLE IF EXISTS t1;
-DROP TABLE IF EXISTS t2;
---enable_warnings
-
---echo
-
-CREATE TABLE t1(
-  c1 INT DEFAULT 12 COMMENT 'column1',
-  c2 INT NULL COMMENT 'column2',
-  c3 INT NOT NULL COMMENT 'column3',
-  c4 VARCHAR(255) CHARACTER SET utf8 NOT NULL DEFAULT 'a',
-  c5 VARCHAR(255) COLLATE utf8_unicode_ci NULL DEFAULT 'b',
-  c6 VARCHAR(255))
-  COLLATE latin1_bin;
-
---echo
-
-SHOW CREATE TABLE t1;
-
---echo
-
-CREATE TABLE t2 AS SELECT * FROM t1;
-
---echo
-
-SHOW CREATE TABLE t2;
-
---echo
-
-DROP TABLE t2;
-DROP TABLE t1;
-
---echo
---echo # -- End of test case for Bug#21380.
-
-###########################################################################
-
---echo
---echo # --
 --echo # -- Bug#18834: ALTER TABLE ADD INDEX on table with two timestamp fields
 --echo # --
 --echo

=== modified file 'mysql-test/t/ctype_utf8.test'
--- a/mysql-test/t/ctype_utf8.test	2009-01-26 21:19:13 +0000
+++ b/mysql-test/t/ctype_utf8.test	2009-12-27 13:54:41 +0000
@@ -2,6 +2,15 @@
 # Tests with the utf8 character set
 #
 
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
+
+--disable_warnings
+drop table if exists t1,t2,t3,t4;
+drop database if exists mysqltest;
+--enable_warnings
+
+
 --disable_warnings
 drop table if exists t1,t2;
 --enable_warnings

=== modified file 'mysql-test/t/ddl_i18n_koi8r.test'
--- a/mysql-test/t/ddl_i18n_koi8r.test	2009-05-15 10:15:56 +0000
+++ b/mysql-test/t/ddl_i18n_koi8r.test	2009-12-27 13:54:41 +0000
@@ -36,6 +36,8 @@
 --source include/have_cp866.inc
 --source include/have_cp1251.inc
 --source include/have_koi8r.inc
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
 
 ###########################################################################
 

=== modified file 'mysql-test/t/ddl_i18n_utf8.test'
--- a/mysql-test/t/ddl_i18n_utf8.test	2009-05-15 10:15:56 +0000
+++ b/mysql-test/t/ddl_i18n_utf8.test	2009-12-27 13:54:41 +0000
@@ -36,6 +36,8 @@
 --source include/have_cp866.inc
 --source include/have_cp1251.inc
 --source include/have_koi8r.inc
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
 
 ###########################################################################
 

=== modified file 'mysql-test/t/delayed.test'
--- a/mysql-test/t/delayed.test	2009-03-11 15:32:42 +0000
+++ b/mysql-test/t/delayed.test	2010-01-15 15:27:55 +0000
@@ -341,4 +341,28 @@ drop table t1;
 
 set global low_priority_updates = @old_delayed_updates;
 
+
+--echo #
+--echo # Bug #47682 strange behaviour of INSERT DELAYED
+--echo #
+
+--disable_warnings
+DROP TABLE IF EXISTS t1, t2;
+--enable_warnings
+
+CREATE TABLE t1 (f1 integer);
+CREATE TABLE t2 (f1 integer);
+
+FLUSH TABLES WITH READ LOCK;
+LOCK TABLES t1 READ;
+
+# ER_CANT_UPDATE_WITH_READLOCK with normal execution
+# ER_TABLE_NOT_LOCKED when executed as prepared statement
+--error ER_CANT_UPDATE_WITH_READLOCK, ER_TABLE_NOT_LOCKED
+INSERT DELAYED INTO t2 VALUES (1);
+
+UNLOCK TABLES;
+DROP TABLE t1, t2;
+
+
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/delete.test'
--- a/mysql-test/t/delete.test	2009-09-28 10:48:52 +0000
+++ b/mysql-test/t/delete.test	2009-11-18 09:32:03 +0000
@@ -336,3 +336,25 @@ SELECT * FROM t2;
 SELECT * FROM t3;
 
 DROP TABLE t1, t2, t3;
+
+--echo #
+--echo # Bug #46425 crash in Diagnostics_area::set_ok_status, 
+--echo #            empty statement, DELETE IGNORE
+--echo #
+
+CREATE table t1 (i INTEGER);
+
+INSERT INTO t1 VALUES (1);
+
+--delimiter |
+
+CREATE TRIGGER tr1 AFTER DELETE ON t1 FOR EACH ROW 
+BEGIN 
+  INSERT INTO t1 SELECT * FROM t1 AS A;
+END |
+
+--delimiter ;
+--error ER_CANT_UPDATE_USED_TABLE_IN_SF_OR_TRG
+DELETE IGNORE FROM t1;
+
+DROP TABLE t1;
\ No newline at end of file

=== modified file 'mysql-test/t/disabled.def'
--- a/mysql-test/t/disabled.def	2009-12-03 11:19:05 +0000
+++ b/mysql-test/t/disabled.def	2010-01-15 15:27:55 +0000
@@ -11,7 +11,5 @@
 ##############################################################################
 kill                     : Bug#37780 2008-12-03 HHunger need some changes to be robust enough for pushbuild.
 query_cache_28249        : Bug#43861 2009-03-25 main.query_cache_28249 fails sporadically
-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
+innodb-autoinc           : Bug#49267 2009-12-02 test fails on windows because of different case mode

=== modified file 'mysql-test/t/fulltext.test'
--- a/mysql-test/t/fulltext.test	2009-09-07 20:50:10 +0000
+++ b/mysql-test/t/fulltext.test	2010-01-15 15:27:55 +0000
@@ -2,6 +2,9 @@
 # Test of fulltext index
 #
 
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
+
 --disable_warnings
 drop table if exists t1,t2,t3;
 --enable_warnings
@@ -493,3 +496,44 @@ PREPARE s FROM
 EXECUTE s;
 DEALLOCATE PREPARE s;
 DROP TABLE t1;
+
+--echo #
+--echo # Bug #47930: MATCH IN BOOLEAN MODE returns too many results 
+--echo #  inside subquery
+--echo #
+
+CREATE TABLE t1 (a int);
+INSERT INTO t1 VALUES (1), (2);
+
+CREATE TABLE t2 (a int, b2 char(10), FULLTEXT KEY b2 (b2));
+INSERT INTO t2 VALUES (1,'Scargill');
+
+CREATE TABLE t3 (a int, b int);
+INSERT INTO t3 VALUES (1,1), (2,1);
+
+--echo # t2 should use full text index
+EXPLAIN
+SELECT count(*) FROM t1 WHERE 
+  not exists(
+   SELECT 1 FROM t2, t3
+   WHERE t3.a=t1.a AND MATCH(b2) AGAINST('scargill' IN BOOLEAN MODE)
+  );
+
+--echo # should return 0
+SELECT count(*) FROM t1 WHERE 
+  not exists(
+   SELECT 1 FROM t2, t3
+   WHERE t3.a=t1.a AND MATCH(b2) AGAINST('scargill' IN BOOLEAN MODE)
+  );
+
+--echo # should return 0
+SELECT count(*) FROM t1 WHERE 
+  not exists(
+   SELECT 1 FROM t2 IGNORE INDEX (b2), t3
+   WHERE t3.a=t1.a AND MATCH(b2) AGAINST('scargill' IN BOOLEAN MODE)
+  );
+
+DROP TABLE t1,t2,t3;
+
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/fulltext2.test'
--- a/mysql-test/t/fulltext2.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/fulltext2.test	2009-12-27 13:54:41 +0000
@@ -2,6 +2,9 @@
 # test of new fulltext search features
 #
 
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
+
 #
 # two-level tree
 #

=== modified file 'mysql-test/t/func_group.test'
--- a/mysql-test/t/func_group.test	2009-10-14 08:46:50 +0000
+++ b/mysql-test/t/func_group.test	2009-11-24 15:26:13 +0000
@@ -1053,4 +1053,35 @@ ORDER BY max;
 --echo #
 DROP TABLE t1;
 
+--echo #
+--echo # Bug#43668: Wrong comparison and MIN/MAX for YEAR(2)
+--echo #
+create table t1 (f1 year(2), f2 year(4), f3 date, f4 datetime);
+insert into t1 values
+  (98,1998,19980101,"1998-01-01 00:00:00"),
+  (00,2000,20000101,"2000-01-01 00:00:01"),
+  (02,2002,20020101,"2002-01-01 23:59:59"),
+  (60,2060,20600101,"2060-01-01 11:11:11"),
+  (70,1970,19700101,"1970-11-11 22:22:22"),
+  (NULL,NULL,NULL,NULL);
+select min(f1),max(f1) from t1;
+select min(f2),max(f2) from t1;
+select min(f3),max(f3) from t1;
+select min(f4),max(f4) from t1;
+select a.f1 as a, b.f1 as b, a.f1 > b.f1 as gt,
+       a.f1 < b.f1 as lt, a.f1<=>b.f1 as eq
+from t1 a, t1 b;
+select a.f1 as a, b.f2 as b, a.f1 > b.f2 as gt,
+       a.f1 < b.f2 as lt, a.f1<=>b.f2 as eq
+from t1 a, t1 b;
+select a.f1 as a, b.f3 as b, a.f1 > b.f3 as gt,
+       a.f1 < b.f3 as lt, a.f1<=>b.f3 as eq
+from t1 a, t1 b;
+select a.f1 as a, b.f4 as b, a.f1 > b.f4 as gt,
+       a.f1 < b.f4 as lt, a.f1<=>b.f4 as eq
+from t1 a, t1 b;
+select *, f1 = f2 from t1;
+drop table t1;
+--echo #
 --echo End of 5.1 tests
+

=== modified file 'mysql-test/t/func_misc.test'
--- a/mysql-test/t/func_misc.test	2009-10-28 07:52:34 +0000
+++ b/mysql-test/t/func_misc.test	2010-01-11 13:15:28 +0000
@@ -103,198 +103,6 @@ show create table t1;
 drop table t1;
 
 #
-# Bug#6760: Add SLEEP() function (feature request)
-#
-#   Logics of original test:
-#   Reveal that a query with SLEEP does not need less time than estimated.
-#
-# Bug#12689: SLEEP() gets incorrectly cached/optimized-away
-#
-#   Description from bug report (slightly modified)
-#
-#   Bug 1 (happened all time):
-#      SELECT * FROM t1 WHERE SLEEP(1) will only result in a sleep of 1
-#      second, regardless of the number of rows in t1.
-#   Bug 2 (happened all time):
-#      Such a query will also get cached by the query cache, but should not.
-#
-# Notes (mleich, 2008-05)
-# =======================
-#
-# Experiments around
-#    Bug#36345 Test 'func_misc' fails on RHAS3 x86_64
-# showed that the tests for both bugs could produce in case of parallel
-# artificial system time (like via ntpd)
-# - decreases false alarm
-# - increases false success
-#
-# We try here to circumvent these issues by reimplementation of the tests
-# and sophisticated scripting, although the cause of the problems is a massive
-# error within the setup of the testing environment.
-# Tests relying on or checking derivates of the system time must never meet
-# parallel manipulations of system time.
-#
-# Results of experiments with/without manipulation of system time,
-# information_schema.processlist content, high load on testing box
-# ----------------------------------------------------------------
-# Definition: Predicted_cumulative_sleep_time =
-#                #_of_result_rows * sleep_time_per_result_row
-#
-# 1. Total (real sleep time) ~= predicted_cumulative_sleep_time !!
-# 2. The state of a session within the PROCESSLIST changes to 'User sleep'
-#    if the sessions runs a statement containing the sleep function and the
-#    processing of the statement is just within the phase where the sleep
-#    is done. (*)
-# 3. NOW() and processlist.time behave "synchronous" to system time and
-#    show also the "jumps" caused by system time manipulations. (*)
-# 4. processlist.time is unsigned, the "next" value below 0 is ~ 4G (*)
-# 5. Current processlist.time ~= current real sleep time if the system time
-#    was not manipulated. (*)
-# 6. High system load can cause delays of <= 2 seconds.
-# 7. Thanks to Davi for excellent hints and ideas.
-#
-#    (*)
-#    - information_schema.processlist is not available before MySQL 5.1.
-#    - Observation of processlist content requires a
-#      - "worker" session sending the query with "send" and pulling results
-#        with "reap"
-#      - session observing the processlist parallel to the worker session
-#      "send" and "reap" do not work in case of an embedded server.
-#    Conclusion: Tests based on processlist have too many restrictions.
-#
-# Solutions for subtests based on TIMEDIFF of values filled via NOW()
-# -------------------------------------------------------------------
-# Run the following sequence three times
-#    1. SELECT <start_time>
-#    2. Query with SLEEP
-#    3. SELECT <end_time>
-# If TIMEDIFF(<end_time>,<start_time>) is at least two times within a
-# reasonable range assume that we did not met errors we were looking for.
-#
-# It is extreme unlikely that we have two system time changes within the
-# < 30 seconds runtime. Even if the unlikely happens, there are so
-# frequent runs of this test on this or another testing box which will
-# catch the problem.
-#
-
---echo #------------------------------------------------------------------------
---echo # Tests for Bug#6760 and Bug#12689
-# Number of rows within the intended result set.
-SET @row_count = 4;
-# Parameter within SLEEP function
-SET @sleep_time_per_result_row = 1;
-# Maximum acceptable delay caused by high load on testing box
-SET @max_acceptable_delay = 2;
-# TIMEDIFF = time for query with sleep (mostly the time caused by SLEEP)
-#            + time for delays caused by high load on testing box
-# Ensure that at least a reasonable fraction of TIMEDIFF belongs to the SLEEP
-# by appropriate setting of variables.
-# Ensure that any "judging" has a base of minimum three attempts.
-# (Test 2 uses all attempts except the first one.)
-if (!` SELECT (@sleep_time_per_result_row * @row_count - @max_acceptable_delay >
-              @sleep_time_per_result_row) AND (@row_count - 1 >= 3)`)
-{
-   --echo # Have to abort because of error in plausibility check
-   --echo ######################################################
-   --vertical_results
-   SELECT @sleep_time_per_result_row * @row_count - @max_acceptable_delay >
-               @sleep_time_per_result_row AS must_be_1,
-               @row_count - 1 >= 3 AS must_be_also_1,
-               @sleep_time_per_result_row, @row_count, @max_acceptable_delay;
-   exit;
-}
-SET @@global.query_cache_size = 1024 * 64;
---disable_warnings
-DROP TEMPORARY TABLE IF EXISTS t_history;
-DROP TABLE IF EXISTS t1;
---enable_warnings
-CREATE TEMPORARY TABLE t_history (attempt SMALLINT,
-start_ts DATETIME, end_ts DATETIME,
-start_cached INTEGER, end_cached INTEGER);
-CREATE TABLE t1 (f1 BIGINT);
-let $num = `SELECT @row_count`;
---disable_query_log
-begin;
-while ($num)
-{
-   INSERT INTO t1 VALUES (1);
-   dec $num;
-}
-commit;
---enable_query_log
-
-let $loops = 4;
-let $num = $loops;
-while ($num)
-{
-   let $Qcache_queries_in_cache =
-       query_get_value(SHOW STATUS LIKE 'Qcache_queries_in_cache', Value, 1);
-   eval
-   INSERT INTO t_history
-   SET attempt = $loops - $num + 1, start_ts = NOW(),
-       start_cached = $Qcache_queries_in_cache;
-   SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
-   #
-   # Do not determine Qcache_queries_in_cache before updating end_ts. The SHOW
-   # might cost too much time on an overloaded box.
-   eval
-   UPDATE t_history SET end_ts = NOW()
-   WHERE attempt = $loops - $num + 1;
-   let $Qcache_queries_in_cache =
-          query_get_value(SHOW STATUS LIKE 'Qcache_queries_in_cache', Value, 1);
-   eval
-   UPDATE t_history SET end_cached = $Qcache_queries_in_cache
-   WHERE attempt = $loops - $num + 1;
-   # DEBUG eval SELECT * FROM t_history WHERE attempt = $loops - $num + 1;
-   dec $num;
-}
-
-# 1. The majority of queries with SLEEP must need a reasonable time
-#    -> SLEEP has an impact on runtime
-#       = Replacement for original Bug#6760 test
-#    -> total runtime is clear more needed than for one result row needed
-#       = Replacement for one of the original Bug#12689 tests
---echo # Test 1: Does the query with SLEEP need a reasonable time?
-eval SELECT COUNT(*) >= $loops - 1 INTO @aux1 FROM t_history
-WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
-      BETWEEN 0 AND @max_acceptable_delay;
-SELECT @aux1 AS "Expect 1";
-#
-# 2. The majority of queries (the first one must be ignored) with SLEEP must
-#    need a reasonable time
-#    -> If we assume that the result of a cached query will be sent back
-#       immediate, without any sleep, than the query with SLEEP cannot be cached
-#       (current and intended behaviour for queries with SLEEP).
-#    -> It could be also not excluded that the query was cached but the server
-#       honoured somehow the SLEEP. Such a behaviour would be also acceptable.
-#    = Replacement for one of the original Bug#12689 tests
---echo # Test 2: Does the query with SLEEP need a reasonable time even in case
---echo #         of the non first execution?
-eval SELECT COUNT(*) >= $loops - 1 - 1 INTO @aux2 FROM t_history
-WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
-      BETWEEN 0 AND @max_acceptable_delay
-      AND attempt > 1;
-SELECT @aux2 AS "Expect 1";
-#
-# 3. The query with SLEEP should be not cached.
-#    -> SHOW STATUS Qcache_queries_in_cache must be not incremented after
-#       the execution of the query with SLEEP
---echo # Test 3: The query with SLEEP must be not cached.
-eval SELECT COUNT(*) = $loops INTO @aux3 FROM t_history
-WHERE end_cached = start_cached;
-SELECT @aux3 AS "Expect 1";
-#
-# Dump the content of t_history if one of the tests failed.
-if (`SELECT @aux1 + @aux2 + @aux3 <> 3`)
-{
-   --echo # Some tests failed, dumping the content of t_history
-   SELECT * FROM t_history;
-}
-DROP TABLE t1;
-DROP TEMPORARY TABLE t_history;
-SET @@global.query_cache_size = default;
-
-#
 # Bug #21466: INET_ATON() returns signed, not unsigned
 #
 

=== modified file 'mysql-test/t/grant2.test'
--- a/mysql-test/t/grant2.test	2009-02-27 08:03:47 +0000
+++ b/mysql-test/t/grant2.test	2009-10-30 05:06:10 +0000
@@ -632,5 +632,40 @@ DROP DATABASE db1;
 
 --echo End of 5.0 tests
 
+#
+# Bug #48319: Server crashes on "GRANT/REVOKE ... TO CURRENT_USER"
+#
+
+# work out who we are.
+USE mysql;
+SELECT LEFT(CURRENT_USER(),INSTR(CURRENT_USER(),'@')-1) INTO @u;
+SELECT MID(CURRENT_USER(),INSTR(CURRENT_USER(),'@')+1)  INTO @h;
+SELECT password FROM user WHERE user=@u AND host=@h INTO @pwd;
+
+# show current privs.
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+
+# toggle INSERT
+UPDATE user SET insert_priv='N' WHERE user=@u AND host=@h;
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+
+# show that GRANT ... TO CURRENT_USER() no longer crashes
+GRANT INSERT ON *.* TO CURRENT_USER();
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+UPDATE user SET insert_priv='N' WHERE user=@u AND host=@h;
+
+# show that GRANT ... TO CURRENT_USER() IDENTIFIED BY ... works now
+GRANT INSERT ON *.* TO CURRENT_USER() IDENTIFIED BY 'keksdose';
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+
+UPDATE user SET password=@pwd WHERE user=@u AND host=@h;
+SELECT user,host,password,insert_priv FROM user WHERE user=@u AND host=@h;
+
+FLUSH PRIVILEGES;
+
+USE test;
+
+--echo End of 5.1 tests
+
 # Wait till we reached the initial number of concurrent sessions
 --source include/wait_until_count_sessions.inc

=== modified file 'mysql-test/t/group_min_max.test'
--- a/mysql-test/t/group_min_max.test	2009-08-30 07:03:37 +0000
+++ b/mysql-test/t/group_min_max.test	2009-11-23 10:04:17 +0000
@@ -1016,6 +1016,18 @@ SELECT a, MAX(b) FROM t WHERE b > 0 AND
 
 DROP TABLE t;
 
+--echo #
+--echo # Bug #48472: Loose index scan inappropriately chosen for some WHERE
+--echo #             conditions
+--echo # 
+
+CREATE TABLE t (a INT, b INT, INDEX (a,b));
+INSERT INTO t VALUES (2,0), (2,0), (2,1), (2,1);
+INSERT INTO t SELECT * FROM t;                                   
+
+SELECT a, MAX(b) FROM t WHERE 0=b+0 GROUP BY a;
+
+DROP TABLE t;
 
 --echo End of 5.0 tests
 

=== modified file 'mysql-test/t/innodb-autoinc.test'
--- a/mysql-test/t/innodb-autoinc.test	2009-12-03 11:34:11 +0000
+++ b/mysql-test/t/innodb-autoinc.test	2010-01-15 15:27:55 +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);
@@ -508,7 +508,7 @@ 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%";
+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);
@@ -620,3 +620,38 @@ SHOW CREATE TABLE T1;
 INSERT INTO T1 (c2) values (0);
 SELECT * FROM T1;
 DROP TABLE T1;
+
+##
+# 49032: Use the correct function to read the AUTOINC column value
+#
+CREATE TABLE T1(C1 DOUBLE AUTO_INCREMENT KEY, C2 CHAR(10)) ENGINE=InnoDB;
+INSERT INTO T1(C1, C2) VALUES (1, 'innodb'), (3, 'innodb');
+# Restart the server
+-- source include/restart_mysqld.inc
+INSERT INTO T1(C2) VALUES ('innodb');
+SHOW CREATE TABLE T1;
+DROP TABLE T1;
+CREATE TABLE T1(C1 FLOAT AUTO_INCREMENT KEY, C2 CHAR(10)) ENGINE=InnoDB;
+INSERT INTO T1(C1, C2) VALUES (1, 'innodb'), (3, 'innodb');
+# Restart the server
+-- source include/restart_mysqld.inc
+INSERT INTO T1(C2) VALUES ('innodb');
+SHOW CREATE TABLE T1;
+DROP TABLE T1;
+
+##
+# 47720: REPLACE INTO Autoincrement column with negative values
+#
+CREATE TABLE t1 (c1 INT AUTO_INCREMENT PRIMARY KEY) ENGINE=InnoDB;
+INSERT INTO t1 SET c1 = 1;
+SHOW CREATE TABLE t1;
+INSERT INTO t1 SET c1 = 2;
+INSERT INTO t1 SET c1 = -1;
+SELECT * FROM t1;
+-- error ER_DUP_ENTRY,1062
+INSERT INTO t1 SET c1 = -1;
+SHOW CREATE TABLE t1;
+REPLACE INTO t1 VALUES (-1);
+SELECT * FROM t1;
+SHOW CREATE TABLE t1;
+DROP TABLE t1;

=== modified file 'mysql-test/t/innodb.test'
--- a/mysql-test/t/innodb.test	2009-11-13 21:26:08 +0000
+++ b/mysql-test/t/innodb.test	2009-12-27 13:54:41 +0000
@@ -2353,18 +2353,6 @@ DELETE FROM t1;
 DROP TABLE t2,t1;
 
 #
-# Bug #26835: table corruption after delete+insert
-#
-
-CREATE TABLE t1 (a VARCHAR(5) COLLATE utf8_unicode_ci PRIMARY KEY)
-ENGINE=InnoDB;
-INSERT INTO t1 VALUES (0xEFBCA4EFBCA4EFBCA4);
-DELETE FROM t1;
-INSERT INTO t1 VALUES ('DDD');
-SELECT * FROM t1;
-DROP TABLE t1;
-
-#
 # Bug #23313 (AUTO_INCREMENT=# not reported back for InnoDB tables)
 # Bug #21404 (AUTO_INCREMENT value reset when Adding FKEY (or ALTER?))
 #

=== modified file 'mysql-test/t/innodb_lock_wait_timeout_1.test'
--- a/mysql-test/t/innodb_lock_wait_timeout_1.test	2009-11-03 17:45:52 +0000
+++ b/mysql-test/t/innodb_lock_wait_timeout_1.test	2009-11-12 11:43:33 +0000
@@ -71,6 +71,40 @@ set autocommit=default;
 drop table t1;
 
 --echo #
+--echo # Bug #37183 insert ignore into .. select ... hangs 
+--echo #            after deadlock was encountered
+--echo #
+connect (con1,localhost,root,,);
+create table t1(id int primary key,v int)engine=innodb;
+insert into t1 values (1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7);
+create table t2 like t1;
+
+--connection con1
+begin;
+update t1 set v=id*2 where id=1;
+
+--connection default
+begin;
+update t1 set v=id*2 where id=2;
+
+--connection con1
+--error 1205
+update t1 set v=id*2 where id=2;
+
+--connection default
+--error 1205
+insert ignore into t2 select * from t1 where id=1; 
+rollback;
+
+--connection con1
+rollback;
+
+--connection default
+disconnect con1;
+drop table t1, t2;
+
+
+--echo #
 --echo # Bug#41756 Strange error messages about locks from InnoDB
 --echo #
 --disable_warnings

=== modified file 'mysql-test/t/innodb_mysql.test'
--- a/mysql-test/t/innodb_mysql.test	2009-12-03 11:19:05 +0000
+++ b/mysql-test/t/innodb_mysql.test	2010-01-15 15:27:55 +0000
@@ -491,5 +491,51 @@ EXPLAIN SELECT * FROM t1 WHERE a = 'TEST
   c >= '2009-10-09 00:00:00.001' AND c <= '2009-10-09 00:00:00.00';
 DROP TABLE t1;
 
+--echo #
+--echo # Bug #46175: NULL read_view and consistent read assertion
+--echo #
+
+CREATE TABLE t1(a CHAR(13),KEY(a)) ENGINE=innodb;
+CREATE TABLE t2(b DATETIME,KEY(b)) ENGINE=innodb;
+INSERT INTO t1 VALUES (),();
+INSERT INTO t2 VALUES (),();
+CREATE OR REPLACE VIEW v1 AS SELECT 1 FROM t2 
+  WHERE b =(SELECT a FROM t1 LIMIT 1);
+
+--disable_query_log
+--disable_result_log
+CONNECT (con1, localhost, root,,);
+--enable_query_log
+--enable_result_log
+CONNECTION default;
+
+DELIMITER |;
+CREATE PROCEDURE p1(num INT)
+BEGIN
+  DECLARE i INT DEFAULT 0;
+  REPEAT
+    SHOW CREATE VIEW v1;
+    SET i:=i+1;
+  UNTIL i>num END REPEAT;
+END|
+DELIMITER ;|
+
+--echo # Should not crash
+--disable_query_log
+--disable_result_log
+--send CALL p1(1000)
+CONNECTION con1;
+--echo # Should not crash
+CALL p1(1000);
+
+CONNECTION default;
+--reap
+--enable_query_log
+--enable_result_log
+
+DISCONNECT con1;
+DROP PROCEDURE p1;
+DROP VIEW v1;
+DROP TABLE t1,t2;
 
 --echo End of 5.1 tests

=== added file 'mysql-test/t/innodb_utf8.test'
--- a/mysql-test/t/innodb_utf8.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/innodb_utf8.test	2009-12-27 13:54:41 +0000
@@ -0,0 +1,24 @@
+#
+# Tests for innodb that requires not default character sets
+#
+
+--source include/have_innodb.inc
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
+
+# Setup
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+
+#
+# Bug #26835: table corruption after delete+insert
+#
+
+CREATE TABLE t1 (a VARCHAR(5) COLLATE utf8_unicode_ci PRIMARY KEY)
+ENGINE=InnoDB;
+INSERT INTO t1 VALUES (0xEFBCA4EFBCA4EFBCA4);
+DELETE FROM t1;
+INSERT INTO t1 VALUES ('DDD');
+SELECT * FROM t1;
+DROP TABLE t1;

=== modified file 'mysql-test/t/mysql.test'
--- a/mysql-test/t/mysql.test	2009-10-05 13:22:23 +0000
+++ b/mysql-test/t/mysql.test	2010-01-15 15:27:55 +0000
@@ -386,10 +386,16 @@ drop tables t1, t2;
 #
 # Bug #27884: mysql --html does not quote HTML special characters in output
 # 
---exec $MYSQL --html test -e "select '< & >' as '<'"
+--write_file $MYSQLTEST_VARDIR/tmp/bug27884.sql
+SELECT '< & >' AS `<`;
+EOF
+--exec $MYSQL --html test < $MYSQLTEST_VARDIR/tmp/bug27884.sql
+
+remove_file $MYSQLTEST_VARDIR/tmp/bug27884.sql;
+
 
 #
-# Bug #27884: mysql client + null byte
+# Bug #28203: mysql client + null byte
 # 
 create table t1 (a char(5));
 insert into t1 values ('\0b\0');
@@ -402,5 +408,5 @@ insert into t1 values ('\0b\0');
 --exec $MYSQL --xml test -e "select a from t1"
 drop table t1;
 
---echo
---echo End of tests
+
+--echo End of 5.0 tests

=== modified file 'mysql-test/t/mysqltest.test'
--- a/mysql-test/t/mysqltest.test	2009-10-08 09:30:03 +0000
+++ b/mysql-test/t/mysqltest.test	2010-01-11 13:15:28 +0000
@@ -9,6 +9,14 @@
 # Save the initial number of concurrent sessions
 --source include/count_sessions.inc
 
+# Some tests below connect/disconnect rapidly in a loop. This causes a race
+# where mysqld may not have time to register the previous disconnects before
+# new connects, and eventually we run out of connections. So we need to
+# increase the maximum.
+let $saved_max_connections = `SELECT @@global.max_connections`;
+SET GLOBAL max_connections = 1000;
+
+
 # ============================================================================
 #
 # Test of mysqltest itself
@@ -2319,3 +2327,7 @@ disconnect $y;
 connection default;
 # Wait till we reached the initial number of concurrent sessions
 --source include/wait_until_count_sessions.inc
+
+--disable_query_log
+--eval SET GLOBAL max_connections = $saved_max_connections
+--enable_query_log

=== modified file 'mysql-test/t/olap.test'
--- a/mysql-test/t/olap.test	2009-10-30 15:54:53 +0000
+++ b/mysql-test/t/olap.test	2009-12-08 09:26:11 +0000
@@ -390,4 +390,17 @@ SELECT DISTINCT b FROM t1, t2 GROUP BY a
 
 DROP TABLE t1, t2;
 
+--echo #
+--echo # Bug #48475: DISTINCT is ignored with GROUP BY WITH ROLLUP
+--echo #             and only const tables
+
+CREATE TABLE t1 (a INT);
+CREATE TABLE t2 (b INT);
+INSERT INTO t1 VALUES (1);
+INSERT INTO t2 VALUES (1);
+
+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-12-03 11:19:05 +0000
+++ b/mysql-test/t/order_by.test	2010-01-15 15:27:55 +0000
@@ -869,6 +869,31 @@ SELECT
 DROP TABLE t1, t2, t3;
 
 
+--echo #
+--echo # Bug #42760: Select doesn't return desired results when we have null
+--echo # values
+--echo #
+
+CREATE TABLE t1 (
+  a INT,
+  c INT,
+  UNIQUE KEY a_c (a,c),
+  KEY (a));
+
+INSERT INTO t1 VALUES (1, 10), (2, NULL);
+
+--echo # Must use ref-or-null on the a_c index
+EXPLAIN
+SELECT 1 AS col FROM t1 WHERE a=2 AND (c=10 OR c IS NULL) ORDER BY c;
+--echo # Must return 1 row
+SELECT 1 AS col FROM t1 WHERE a=2 AND (c=10 OR c IS NULL) ORDER BY c;
+
+DROP TABLE t1;
+
+
+--echo End of 5.0 tests
+
+
 #
 # Bug #35206: select query result different if the key is indexed or not
 #

=== modified file 'mysql-test/t/partition.test'
--- a/mysql-test/t/partition.test	2009-12-03 11:19:05 +0000
+++ b/mysql-test/t/partition.test	2010-01-15 15:27:55 +0000
@@ -15,6 +15,15 @@ drop table if exists t1, t2;
 --enable_warnings
 
 #
+# Bug#48276: can't add column if subpartition exists
+CREATE TABLE t1 (a INT, b INT)
+PARTITION BY LIST (a)
+SUBPARTITION BY HASH (b)
+(PARTITION p1 VALUES IN (1));
+ALTER TABLE t1 ADD COLUMN c INT;
+DROP TABLE t1;
+
+#
 # Bug#46639: 1030 (HY000): Got error 124 from storage engine on
 # INSERT ... SELECT ...
 CREATE TABLE t1 (
@@ -62,6 +71,17 @@ SHOW CREATE TABLE t1;
 DROP TABLE t1;
 
 #
+# Bug#45904: Error when CHARSET=utf8 and subpartitioning
+#
+create table t1 (a int NOT NULL, b varchar(5) NOT NULL)
+default charset=utf8
+partition by list (a)
+subpartition by key (b)
+(partition p0 values in (1),
+ partition p1 values in (2));
+drop table t1;
+
+#
 # Bug#44059: rec_per_key on empty partition gives weird optimiser results
 #
 create table t1 (a int, b int, key(a))
@@ -2035,11 +2055,14 @@ DROP TABLE t1;
 --echo #
 --echo # Bug #45807: crash accessing partitioned table and sql_mode 
 --echo #   contains ONLY_FULL_GROUP_BY
+--echo # Bug#46923: select count(*) from partitioned table fails with
+--echo # ONLY_FULL_GROUP_BY
 --echo #
 
 SET SESSION SQL_MODE='ONLY_FULL_GROUP_BY';
 CREATE TABLE t1(id INT,KEY(id)) ENGINE=MYISAM 
   PARTITION BY HASH(id) PARTITIONS 2;
+SELECT COUNT(*) FROM t1;
 DROP TABLE t1;
 SET SESSION SQL_MODE=DEFAULT;
 

=== modified file 'mysql-test/t/query_cache.test'
--- a/mysql-test/t/query_cache.test	2009-12-03 11:19:05 +0000
+++ b/mysql-test/t/query_cache.test	2010-01-11 13:15:28 +0000
@@ -882,6 +882,19 @@ drop procedure f4;
 drop table t1;
 set GLOBAL query_cache_size=0;
 
+# Tests moved from main.variables due to needing query cache in server.
+set GLOBAL query_cache_size=100000;
+--error ER_GLOBAL_VARIABLE
+set SESSION query_cache_size=10000;
+set global query_cache_limit=100;
+set global query_cache_size=100;
+set global query_cache_type=demand;
+
+set GLOBAL query_cache_type=default;
+set GLOBAL query_cache_limit=default;
+set GLOBAL query_cache_size=default;
+
+
 --echo End of 4.1 tests
 
 #
@@ -1288,6 +1301,198 @@ SHOW STATUS LIKE "Qcache_hits";
 DROP TABLE t1;
 SET GLOBAL query_cache_size= default;
 
+#
+# Bug#6760: Add SLEEP() function (feature request)
+#
+#   Logics of original test:
+#   Reveal that a query with SLEEP does not need less time than estimated.
+#
+# Bug#12689: SLEEP() gets incorrectly cached/optimized-away
+#
+#   Description from bug report (slightly modified)
+#
+#   Bug 1 (happened all time):
+#      SELECT * FROM t1 WHERE SLEEP(1) will only result in a sleep of 1
+#      second, regardless of the number of rows in t1.
+#   Bug 2 (happened all time):
+#      Such a query will also get cached by the query cache, but should not.
+#
+# Notes (mleich, 2008-05)
+# =======================
+#
+# Experiments around
+#    Bug#36345 Test 'func_misc' fails on RHAS3 x86_64
+# showed that the tests for both bugs could produce in case of parallel
+# artificial system time (like via ntpd)
+# - decreases false alarm
+# - increases false success
+#
+# We try here to circumvent these issues by reimplementation of the tests
+# and sophisticated scripting, although the cause of the problems is a massive
+# error within the setup of the testing environment.
+# Tests relying on or checking derivates of the system time must never meet
+# parallel manipulations of system time.
+#
+# Results of experiments with/without manipulation of system time,
+# information_schema.processlist content, high load on testing box
+# ----------------------------------------------------------------
+# Definition: Predicted_cumulative_sleep_time =
+#                #_of_result_rows * sleep_time_per_result_row
+#
+# 1. Total (real sleep time) ~= predicted_cumulative_sleep_time !!
+# 2. The state of a session within the PROCESSLIST changes to 'User sleep'
+#    if the sessions runs a statement containing the sleep function and the
+#    processing of the statement is just within the phase where the sleep
+#    is done. (*)
+# 3. NOW() and processlist.time behave "synchronous" to system time and
+#    show also the "jumps" caused by system time manipulations. (*)
+# 4. processlist.time is unsigned, the "next" value below 0 is ~ 4G (*)
+# 5. Current processlist.time ~= current real sleep time if the system time
+#    was not manipulated. (*)
+# 6. High system load can cause delays of <= 2 seconds.
+# 7. Thanks to Davi for excellent hints and ideas.
+#
+#    (*)
+#    - information_schema.processlist is not available before MySQL 5.1.
+#    - Observation of processlist content requires a
+#      - "worker" session sending the query with "send" and pulling results
+#        with "reap"
+#      - session observing the processlist parallel to the worker session
+#      "send" and "reap" do not work in case of an embedded server.
+#    Conclusion: Tests based on processlist have too many restrictions.
+#
+# Solutions for subtests based on TIMEDIFF of values filled via NOW()
+# -------------------------------------------------------------------
+# Run the following sequence three times
+#    1. SELECT <start_time>
+#    2. Query with SLEEP
+#    3. SELECT <end_time>
+# If TIMEDIFF(<end_time>,<start_time>) is at least two times within a
+# reasonable range assume that we did not met errors we were looking for.
+#
+# It is extreme unlikely that we have two system time changes within the
+# < 30 seconds runtime. Even if the unlikely happens, there are so
+# frequent runs of this test on this or another testing box which will
+# catch the problem.
+#
+
+--echo #------------------------------------------------------------------------
+--echo # Tests for Bug#6760 and Bug#12689
+# Number of rows within the intended result set.
+SET @row_count = 4;
+# Parameter within SLEEP function
+SET @sleep_time_per_result_row = 1;
+# Maximum acceptable delay caused by high load on testing box
+SET @max_acceptable_delay = 2;
+# TIMEDIFF = time for query with sleep (mostly the time caused by SLEEP)
+#            + time for delays caused by high load on testing box
+# Ensure that at least a reasonable fraction of TIMEDIFF belongs to the SLEEP
+# by appropriate setting of variables.
+# Ensure that any "judging" has a base of minimum three attempts.
+# (Test 2 uses all attempts except the first one.)
+if (!` SELECT (@sleep_time_per_result_row * @row_count - @max_acceptable_delay >
+              @sleep_time_per_result_row) AND (@row_count - 1 >= 3)`)
+{
+   --echo # Have to abort because of error in plausibility check
+   --echo ######################################################
+   --vertical_results
+   SELECT @sleep_time_per_result_row * @row_count - @max_acceptable_delay >
+               @sleep_time_per_result_row AS must_be_1,
+               @row_count - 1 >= 3 AS must_be_also_1,
+               @sleep_time_per_result_row, @row_count, @max_acceptable_delay;
+   exit;
+}
+SET @@global.query_cache_size = 1024 * 64;
+--disable_warnings
+DROP TEMPORARY TABLE IF EXISTS t_history;
+DROP TABLE IF EXISTS t1;
+--enable_warnings
+CREATE TEMPORARY TABLE t_history (attempt SMALLINT,
+start_ts DATETIME, end_ts DATETIME,
+start_cached INTEGER, end_cached INTEGER);
+CREATE TABLE t1 (f1 BIGINT);
+let $num = `SELECT @row_count`;
+--disable_query_log
+begin;
+while ($num)
+{
+   INSERT INTO t1 VALUES (1);
+   dec $num;
+}
+commit;
+--enable_query_log
+
+let $loops = 4;
+let $num = $loops;
+while ($num)
+{
+   let $Qcache_queries_in_cache =
+       query_get_value(SHOW STATUS LIKE 'Qcache_queries_in_cache', Value, 1);
+   eval
+   INSERT INTO t_history
+   SET attempt = $loops - $num + 1, start_ts = NOW(),
+       start_cached = $Qcache_queries_in_cache;
+   SELECT *, SLEEP(@sleep_time_per_result_row) FROM t1;
+   #
+   # Do not determine Qcache_queries_in_cache before updating end_ts. The SHOW
+   # might cost too much time on an overloaded box.
+   eval
+   UPDATE t_history SET end_ts = NOW()
+   WHERE attempt = $loops - $num + 1;
+   let $Qcache_queries_in_cache =
+          query_get_value(SHOW STATUS LIKE 'Qcache_queries_in_cache', Value, 1);
+   eval
+   UPDATE t_history SET end_cached = $Qcache_queries_in_cache
+   WHERE attempt = $loops - $num + 1;
+   # DEBUG eval SELECT * FROM t_history WHERE attempt = $loops - $num + 1;
+   dec $num;
+}
+
+# 1. The majority of queries with SLEEP must need a reasonable time
+#    -> SLEEP has an impact on runtime
+#       = Replacement for original Bug#6760 test
+#    -> total runtime is clear more needed than for one result row needed
+#       = Replacement for one of the original Bug#12689 tests
+--echo # Test 1: Does the query with SLEEP need a reasonable time?
+eval SELECT COUNT(*) >= $loops - 1 INTO @aux1 FROM t_history
+WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
+      BETWEEN 0 AND @max_acceptable_delay;
+SELECT @aux1 AS "Expect 1";
+#
+# 2. The majority of queries (the first one must be ignored) with SLEEP must
+#    need a reasonable time
+#    -> If we assume that the result of a cached query will be sent back
+#       immediate, without any sleep, than the query with SLEEP cannot be cached
+#       (current and intended behaviour for queries with SLEEP).
+#    -> It could be also not excluded that the query was cached but the server
+#       honoured somehow the SLEEP. Such a behaviour would be also acceptable.
+#    = Replacement for one of the original Bug#12689 tests
+--echo # Test 2: Does the query with SLEEP need a reasonable time even in case
+--echo #         of the non first execution?
+eval SELECT COUNT(*) >= $loops - 1 - 1 INTO @aux2 FROM t_history
+WHERE TIMEDIFF(end_ts,start_ts) - @sleep_time_per_result_row * @row_count
+      BETWEEN 0 AND @max_acceptable_delay
+      AND attempt > 1;
+SELECT @aux2 AS "Expect 1";
+#
+# 3. The query with SLEEP should be not cached.
+#    -> SHOW STATUS Qcache_queries_in_cache must be not incremented after
+#       the execution of the query with SLEEP
+--echo # Test 3: The query with SLEEP must be not cached.
+eval SELECT COUNT(*) = $loops INTO @aux3 FROM t_history
+WHERE end_cached = start_cached;
+SELECT @aux3 AS "Expect 1";
+#
+# Dump the content of t_history if one of the tests failed.
+if (`SELECT @aux1 + @aux2 + @aux3 <> 3`)
+{
+   --echo # Some tests failed, dumping the content of t_history
+   SELECT * FROM t_history;
+}
+DROP TABLE t1;
+DROP TEMPORARY TABLE t_history;
+SET @@global.query_cache_size = default;
+
 --echo End of 5.0 tests
 
 #

=== modified file 'mysql-test/t/query_cache_notembedded.test'
--- a/mysql-test/t/query_cache_notembedded.test	2009-04-25 09:04:38 +0000
+++ b/mysql-test/t/query_cache_notembedded.test	2010-01-11 13:15:28 +0000
@@ -274,5 +274,52 @@ set GLOBAL query_cache_limit=default;
 set GLOBAL query_cache_min_res_unit=default;
 set GLOBAL query_cache_size=default;
 
+#
+# Bug#3583 query cache doesn't work for stored procedures
+#
+delimiter |;
+--disable_warnings
+drop table if exists t1|
+--enable_warnings
+create table t1 (
+    id   char(16) not null default '',
+    data int not null
+)|
+--disable_warnings
+drop procedure if exists bug3583|
+--enable_warnings
+--disable_warnings
+drop procedure if exists bug3583|
+--enable_warnings
+create procedure bug3583()
+begin
+  declare c int;
+
+  select * from t1;
+  select count(*) into c from t1;
+  select c;
+end|
+
+insert into t1 values ("x", 3), ("y", 5)|
+set @x = @@query_cache_size|
+set global query_cache_size = 10*1024*1024|
+
+flush status|
+flush query cache|
+show status like 'Qcache_hits'|
+call bug3583()|
+show status like 'Qcache_hits'|
+call bug3583()|
+call bug3583()|
+show status like 'Qcache_hits'|
+
+set global query_cache_size = @x|
+flush status|
+flush query cache|
+delete from t1|
+drop procedure bug3583|
+drop table t1|
+delimiter ;|
+
 # Wait till we reached the initial number of concurrent sessions
 --source include/wait_until_count_sessions.inc

=== modified file 'mysql-test/t/query_cache_ps_no_prot.test'
--- a/mysql-test/t/query_cache_ps_no_prot.test	2007-05-24 20:13:49 +0000
+++ b/mysql-test/t/query_cache_ps_no_prot.test	2009-12-27 13:54:41 +0000
@@ -11,8 +11,9 @@
 
 # We cannot run on embedded server because we use multiple sessions.
 --source include/not_embedded.inc
-
 --source include/have_query_cache.inc
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
 
 # The file with expected results fits only to a run without
 # ps-protocol/sp-protocol/cursor-protocol/view-protocol.

=== modified file 'mysql-test/t/query_cache_ps_ps_prot.test'
--- a/mysql-test/t/query_cache_ps_ps_prot.test	2007-05-24 20:13:49 +0000
+++ b/mysql-test/t/query_cache_ps_ps_prot.test	2009-12-27 13:54:41 +0000
@@ -11,8 +11,9 @@
 
 # We cannot run on embedded server because we use multiple sessions.
 --source include/not_embedded.inc
-
 --source include/have_query_cache.inc
+let collation=utf8_unicode_ci;
+--source include/have_collation.inc
 
 # The file with expected results fits only to a run with "--ps-protocol".
 if (`SELECT $SP_PROTOCOL + $CURSOR_PROTOCOL + $VIEW_PROTOCOL > 0

=== modified file 'mysql-test/t/range.test'
--- a/mysql-test/t/range.test	2009-11-02 12:24:07 +0000
+++ b/mysql-test/t/range.test	2009-12-08 09:26:11 +0000
@@ -1260,4 +1260,57 @@ SELECT str_to_date('', '%Y-%m-%d');
 
 DROP TABLE t1, t2;
 
+--echo #
+--echo # Bug#48459: valgrind errors with query using 'Range checked for each 
+--echo # record'
+--echo #
+CREATE TABLE t1 (
+  a INT,
+  b CHAR(2),
+  c INT,
+  d INT,
+  KEY ( c ),
+  KEY ( d, a, b ( 2 ) ),
+  KEY ( b ( 1 ) )
+);
+
+INSERT INTO t1 VALUES ( NULL, 'a', 1, 2 ), ( NULL, 'a', 1, 2 ),
+                      ( 1,    'a', 1, 2 ), ( 1,    'a', 1, 2 );
+
+CREATE TABLE t2 (
+  a INT,
+  c INT,
+  e INT,
+  KEY ( e )
+);
+
+INSERT INTO t2 VALUES ( 1, 1, NULL ), ( 1, 1, NULL );
+
+--echo # Should not give Valgrind warnings
+SELECT 1
+FROM t1, t2
+WHERE t1.d <> '1' AND t1.b > '1'
+AND t1.a = t2.a AND t1.c = t2.c;
+
+DROP TABLE t1, t2;
+
+--echo #
+--echo # Bug #48665: sql-bench's insert test fails due to wrong result
+--echo #
+
+CREATE TABLE t1 (a INT, b INT, PRIMARY KEY (a));
+
+INSERT INTO t1 VALUES (0,0), (1,1);
+
+--replace_column 1 @ 2 @ 3 @ 5 @ 6 @ 7 @ 8 @ 9 @ 10 @
+EXPLAIN 
+SELECT * FROM t1 FORCE INDEX (PRIMARY) 
+ WHERE (a>=1 AND a<=2) OR (a>=4 AND a<=5) OR (a>=0 AND a <=10);
+
+--echo # Should return 2 rows
+SELECT * FROM t1 FORCE INDEX (PRIMARY) 
+ WHERE (a>=1 AND a<=2) OR (a>=4 AND a<=5) OR (a>=0 AND a <=10);
+
+DROP TABLE t1;
+
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/select.test'
--- a/mysql-test/t/select.test	2009-10-30 14:13:13 +0000
+++ b/mysql-test/t/select.test	2009-12-15 17:08:21 +0000
@@ -3772,6 +3772,19 @@ INTO @var0;
 
 DROP TABLE t1;
  
+--echo #
+--echo # Bug #48458: simple query tries to allocate enormous amount of
+--echo #   memory
+--echo #
+
+CREATE TABLE t1(a INT NOT NULL, b YEAR);
+INSERT INTO t1 VALUES ();
+CREATE TABLE t2(c INT);
+--echo # Should not err out because of out-of-memory
+SELECT 1 FROM t2 JOIN t1 ON 1=1
+  WHERE a != '1' AND NOT a >= b OR NOT ROW(b,a )<> ROW(a,a);
+DROP TABLE t1,t2;
+
 
 --echo End of 5.0 tests
 
@@ -3918,4 +3931,60 @@ SELECT table1 .`time_key` field2  FROM B
 
 drop table A,AA,B,BB;
 --echo #end of test for bug#45266
+
+--echo # 
+--echo # BUG#48052: Valgrind warning - uninitialized value in init_read_record()
+--echo # 
+
+# Needed in 6.0 codebase
+#--echo # Disable Index condition pushdown
+#--replace_column 1 #
+#SELECT @old_icp:=@@engine_condition_pushdown;
+#SET SESSION engine_condition_pushdown = 'OFF';
+
+CREATE TABLE t1 (
+  pk int(11) NOT NULL,
+  i int(11) DEFAULT NULL,
+  v varchar(1) DEFAULT NULL,
+  PRIMARY KEY (pk)
+);
+
+INSERT INTO t1 VALUES (2,7,'m');
+INSERT INTO t1 VALUES (3,9,'m');
+
+SELECT  v
+FROM t1
+WHERE NOT pk > 0  
+HAVING v <= 't' 
+ORDER BY pk;
+
+# Needed in 6.0 codebase
+#--echo # Restore old value for Index condition pushdown
+#SET SESSION engine_condition_pushdown=@old_icp;
+
+DROP TABLE t1;
+
+--echo #
+--echo # Bug#49489 Uninitialized cache led to a wrong result.
+--echo #
+CREATE TABLE t1(c1 DOUBLE(5,4));
+INSERT INTO t1 VALUES (9.1234);
+SELECT * FROM t1 WHERE c1 < 9.12345;
+DROP TABLE t1;
+--echo # End of test for bug#49489.
+
+
+--echo #
+--echo # Bug #49517: Inconsistent behavior while using 
+--echo # NULLable BIGINT and INT columns in comparison
+--echo #
+CREATE TABLE t1(a BIGINT UNSIGNED NOT NULL, b BIGINT NULL, c INT NULL);
+INSERT INTO t1 VALUES(105, NULL, NULL);
+SELECT * FROM t1 WHERE b < 102;
+SELECT * FROM t1 WHERE c < 102;
+SELECT * FROM t1 WHERE 102 < b;
+SELECT * FROM t1 WHERE 102 < c;
+DROP TABLE t1;
+
+
 --echo End of 5.1 tests

=== modified file 'mysql-test/t/show_check.test'
--- a/mysql-test/t/show_check.test	2009-03-06 14:56:17 +0000
+++ b/mysql-test/t/show_check.test	2009-12-15 09:03:24 +0000
@@ -1207,6 +1207,28 @@ connection default;
 DROP USER test_u@localhost;
 
 
+--echo #
+--echo # Bug #48985: show create table crashes if previous access to the table
+--echo #    was killed
+--echo #
+
+connect(con1,localhost,root,,);
+CONNECTION con1;
+LET $ID= `SELECT connection_id()`;
+
+CONNECTION default;
+--disable_query_log
+eval KILL QUERY $ID;
+--enable_query_log
+
+CONNECTION con1;
+--error ER_QUERY_INTERRUPTED
+SHOW CREATE TABLE non_existent;
+
+CONNECTION default;
+DISCONNECT con1;
+
+
 --echo End of 5.1 tests
 
 # Wait till all disconnects are completed

=== modified file 'mysql-test/t/sp-destruct.test'
--- a/mysql-test/t/sp-destruct.test	2008-04-08 14:51:26 +0000
+++ b/mysql-test/t/sp-destruct.test	2009-11-21 11:18:21 +0000
@@ -12,6 +12,9 @@
 # mysqltest should be fixed to allow REPLACE_RESULT in error message
 -- source include/not_embedded.inc
 
+# Supress warnings written to the log file
+call mtr.add_suppression("Column count of mysql.proc is wrong. Expected 20, found 19. The table is probably corrupted");
+
 # Backup proc table
 let $MYSQLD_DATADIR= `select @@datadir`;
 --copy_file $MYSQLD_DATADIR/mysql/proc.frm $MYSQLTEST_VARDIR/tmp/proc.frm
@@ -38,15 +41,14 @@ create trigger t1_ai after insert on t1
 
 # Unsupported tampering with the mysql.proc definition
 alter table mysql.proc drop type;
---replace_result $MYSQL_TEST_DIR .
---error ER_SP_PROC_TABLE_CORRUPT
+--error ER_COL_COUNT_DOESNT_MATCH_CORRUPTED
 call bug14233();
---replace_result $MYSQL_TEST_DIR .
---error ER_SP_PROC_TABLE_CORRUPT
+--error ER_COL_COUNT_DOESNT_MATCH_CORRUPTED
 create view v1 as select bug14233_f();
---replace_result $MYSQL_TEST_DIR .
---error ER_SP_PROC_TABLE_CORRUPT
+--error ER_COL_COUNT_DOESNT_MATCH_CORRUPTED
 insert into t1 values (0);
+--error ER_COL_COUNT_DOESNT_MATCH_CORRUPTED
+show procedure status;
 
 flush table mysql.proc;
 
@@ -155,3 +157,43 @@ drop procedure bug14233_3;
 # Assert: These should show nothing.
 show procedure status where db=DATABASE();
 show function status where db=DATABASE();
+
+#
+# Bug#41726 upgrade from 5.0 to 5.1.30 crashes if you didn't run mysql_upgrade
+#
+
+
+--disable_warnings
+DROP TABLE IF EXISTS proc_backup;
+DROP PROCEDURE IF EXISTS p1;
+--enable_warnings
+
+--echo # Backup the proc table
+
+RENAME TABLE mysql.proc TO proc_backup;
+CREATE TABLE mysql.proc LIKE proc_backup;
+FLUSH TABLE mysql.proc;
+
+--echo # Test with a valid table.
+
+CREATE PROCEDURE p1()
+  SET @foo = 10;
+CALL p1();
+--replace_column 5 '0000-00-00 00:00:00' 6 '0000-00-00 00:00:00'
+SHOW PROCEDURE STATUS;
+
+--echo # Modify a field of the table.
+
+ALTER TABLE mysql.proc MODIFY comment CHAR (32);
+
+--error ER_CANNOT_LOAD_FROM_TABLE
+CREATE PROCEDURE p2()
+  SET @foo = 10;
+--echo # Procedure loaded from the cache
+CALL p1();
+--error ER_CANNOT_LOAD_FROM_TABLE
+SHOW PROCEDURE STATUS;
+
+DROP TABLE mysql.proc;
+RENAME TABLE proc_backup TO mysql.proc;
+FLUSH TABLE mysql.proc;

=== modified file 'mysql-test/t/sp-security.test'
--- a/mysql-test/t/sp-security.test	2009-03-06 14:56:17 +0000
+++ b/mysql-test/t/sp-security.test	2009-11-27 16:10:28 +0000
@@ -865,6 +865,65 @@ DROP PROCEDURE p_suid;
 DROP FUNCTION f_suid;
 DROP TABLE t1;
 
+--echo #
+--echo # Bug #48872 : Privileges for stored functions ignored if function name 
+--echo #  is mixed case
+--echo #
+
+CREATE DATABASE B48872;
+USE B48872;
+CREATE TABLE `TestTab` (id INT);
+INSERT INTO `TestTab` VALUES (1),(2);
+CREATE FUNCTION `f_Test`() RETURNS INT RETURN 123;
+CREATE FUNCTION `f_Test_denied`() RETURNS INT RETURN 123;
+CREATE USER 'tester';
+CREATE USER 'Tester';
+GRANT SELECT ON TABLE `TestTab` TO 'tester';
+GRANT EXECUTE ON FUNCTION `f_Test` TO 'tester';
+GRANT EXECUTE ON FUNCTION `f_Test_denied` TO 'Tester';
+
+SELECT f_Test();
+SELECT * FROM TestTab;
+
+CONNECT (con_tester,localhost,tester,,B48872);
+CONNECT (con_tester_denied,localhost,Tester,,B48872);
+CONNECTION con_tester;
+
+SELECT * FROM TestTab;
+SELECT `f_Test`();
+SELECT `F_TEST`();
+SELECT f_Test();
+SELECT F_TEST();
+
+CONNECTION con_tester_denied;
+
+--disable_result_log
+--error ER_TABLEACCESS_DENIED_ERROR
+SELECT * FROM TestTab;
+--error ER_PROCACCESS_DENIED_ERROR
+SELECT `f_Test`();
+--error ER_PROCACCESS_DENIED_ERROR
+SELECT `F_TEST`();
+--error ER_PROCACCESS_DENIED_ERROR
+SELECT f_Test();
+--error ER_PROCACCESS_DENIED_ERROR
+SELECT F_TEST();
+--enable_result_log
+SELECT `f_Test_denied`();
+SELECT `F_TEST_DENIED`();
+
+CONNECTION default;
+DISCONNECT con_tester;
+DISCONNECT con_tester_denied;
+DROP TABLE `TestTab`;
+DROP FUNCTION `f_Test`;
+DROP FUNCTION `f_Test_denied`;
+
+USE test;
+DROP USER 'tester';
+DROP USER 'Tester';
+DROP DATABASE B48872;
+
 --echo End of 5.0 tests.
 
 # Wait till all disconnects are completed

=== modified file 'mysql-test/t/sp.test'
--- a/mysql-test/t/sp.test	2009-10-23 13:54:58 +0000
+++ b/mysql-test/t/sp.test	2009-11-13 01:03:26 +0000
@@ -8263,6 +8263,73 @@ CALL p1;
 DROP PROCEDURE p1;
 DROP TABLE t1, t2;
 
+--echo #
+--echo # Bug#47627: SET @@{global.session}.local_variable in stored routine causes crash
+--echo # Bug#48626: Crash or lost connection using SET for declared variables with @@
+--echo #
+
+--disable_warnings
+DROP PROCEDURE IF EXISTS p1;
+DROP PROCEDURE IF EXISTS p2;
+DROP PROCEDURE IF EXISTS p3;
+--enable_warnings
+
+delimiter //;
+
+--error ER_UNKNOWN_SYSTEM_VARIABLE
+CREATE PROCEDURE p1()
+BEGIN
+  DECLARE v INT DEFAULT 0;
+  SET @@SESSION.v= 10;
+END//
+
+CREATE PROCEDURE p2()
+BEGIN
+  DECLARE v INT DEFAULT 0;
+  SET v= 10;
+END//
+call p2()//
+
+--error ER_UNKNOWN_SYSTEM_VARIABLE
+CREATE PROCEDURE p3()
+BEGIN
+  DECLARE v INT DEFAULT 0;
+  SELECT @@SESSION.v;
+END//
+
+--error ER_UNKNOWN_SYSTEM_VARIABLE
+CREATE PROCEDURE p4()
+BEGIN
+  DECLARE v INT DEFAULT 0;
+  SET @@GLOBAL.v= 10;
+END//
+
+CREATE PROCEDURE p5()
+BEGIN
+  DECLARE init_connect INT DEFAULT 0;
+  SET init_connect= 10;
+  SET @@GLOBAL.init_connect= 'SELECT 1';
+  SET @@SESSION.IDENTITY= 1;
+  SELECT @@SESSION.IDENTITY;
+  SELECT @@GLOBAL.init_connect;
+  SELECT init_connect;
+END//
+
+--error ER_UNKNOWN_SYSTEM_VARIABLE
+CREATE PROCEDURE p6()
+BEGIN
+  DECLARE v INT DEFAULT 0;
+  SET @@v= 0;
+END//
+
+delimiter ;//
+
+SET @old_init_connect= @@GLOBAL.init_connect;
+CALL p5();
+SET @@GLOBAL.init_connect= @old_init_connect;
+
+DROP PROCEDURE p2;
+DROP PROCEDURE p5;
 
 --echo # ------------------------------------------------------------------
 --echo # -- End of 5.1 tests

=== modified file 'mysql-test/t/sp_notembedded.test'
--- a/mysql-test/t/sp_notembedded.test	2009-10-13 18:21:42 +0000
+++ b/mysql-test/t/sp_notembedded.test	2010-01-11 13:15:28 +0000
@@ -56,52 +56,6 @@ show warnings|
 drop procedure bug4902_2|
 
 #
-# Bug#3583 query cache doesn't work for stored procedures
-#
---disable_warnings
-drop table if exists t1|
---enable_warnings
-create table t1 (
-    id   char(16) not null default '',
-    data int not null
-)|
---disable_warnings
-drop procedure if exists bug3583|
---enable_warnings
---disable_warnings
-drop procedure if exists bug3583|
---enable_warnings
-create procedure bug3583()
-begin
-  declare c int;
-
-  select * from t1;
-  select count(*) into c from t1;
-  select c;
-end|
-
-insert into t1 values ("x", 3), ("y", 5)|
-set @x = @@query_cache_size|
-set global query_cache_size = 10*1024*1024|
-
-flush status|
-flush query cache|
-show status like 'Qcache_hits'|
-call bug3583()|
-show status like 'Qcache_hits'|
-call bug3583()|
-call bug3583()|
-show status like 'Qcache_hits'|
-
-set global query_cache_size = @x|
-flush status|
-flush query cache|
-delete from t1|
-drop procedure bug3583|
-drop table t1|
-
-
-#
 # Bug#6807 Stored procedure crash if CREATE PROCEDURE ... KILL QUERY
 #
 --disable_warnings

=== modified file 'mysql-test/t/trigger.test'
--- a/mysql-test/t/trigger.test	2009-06-22 12:51:33 +0000
+++ b/mysql-test/t/trigger.test	2010-01-12 08:19:48 +0000
@@ -1767,68 +1767,6 @@ drop table t1, t2, t3;
 disconnect addconroot1;
 disconnect addconroot2;
 disconnect addconwithoutdb;
-#
-# Bug #26162: Trigger DML ignores low_priority_updates setting
-#
-CREATE TABLE t1 (id INTEGER);
-CREATE TABLE t2 (id INTEGER);
-
-INSERT INTO t2 VALUES (1),(2);
-
-# trigger that produces the high priority insert, but should be low, adding
-# LOW_PRIORITY fixes this
-CREATE TRIGGER t1_test AFTER INSERT ON t1 FOR EACH ROW 
-  INSERT INTO t2 VALUES (new.id);
-
-CONNECT (rl_holder,    localhost, root,,);
-CONNECT (rl_acquirer,  localhost, root,,);
-CONNECT (wl_acquirer,  localhost, root,,);
-CONNECT (rl_contender, localhost, root,,);
-
-CONNECTION rl_holder;
-SELECT GET_LOCK('B26162',120);
-
-CONNECTION rl_acquirer;
---send
-SELECT 'rl_acquirer', GET_LOCK('B26162',120), id FROM t2 WHERE id = 1;
-
-CONNECTION wl_acquirer;
-SET SESSION LOW_PRIORITY_UPDATES=1;
-SET GLOBAL LOW_PRIORITY_UPDATES=1;
-#need to wait for rl_acquirer to lock on the B26162 lock 
-sleep 2;
---send
-INSERT INTO t1 VALUES (5);
-
-CONNECTION rl_contender;
-# must not "see" the row inserted by the INSERT (as it must run before the
-# INSERT)
---send
-SELECT 'rl_contender', id FROM t2 WHERE id > 1;
-
-CONNECTION rl_holder;
-#need to wait for wl_acquirer and rl_contender to lock on t2 
-sleep 2;
-SELECT RELEASE_LOCK('B26162');
-
-CONNECTION rl_acquirer;
---reap
-SELECT RELEASE_LOCK('B26162');
-CONNECTION wl_acquirer;
---reap
-CONNECTION rl_contender;
---reap
-
-CONNECTION default;
-DISCONNECT rl_acquirer;
-DISCONNECT wl_acquirer;
-DISCONNECT rl_contender;
-DISCONNECT rl_holder;
-
-DROP TRIGGER t1_test;
-DROP TABLE t1,t2;
-SET SESSION LOW_PRIORITY_UPDATES=DEFAULT;
-SET GLOBAL LOW_PRIORITY_UPDATES=DEFAULT;
 --echo
 --echo Bug#28502 Triggers that update another innodb table will block
 --echo on X lock unnecessarily

=== modified file 'mysql-test/t/trigger_notembedded.test'
--- a/mysql-test/t/trigger_notembedded.test	2009-06-25 10:52:50 +0000
+++ b/mysql-test/t/trigger_notembedded.test	2010-01-12 08:19:48 +0000
@@ -875,6 +875,79 @@ DROP TABLE t1;
 DROP DATABASE mysqltest_db1;
 USE test;
 
+#
+# Bug #26162: Trigger DML ignores low_priority_updates setting
+#
+CREATE TABLE t1 (id INTEGER);
+CREATE TABLE t2 (id INTEGER);
+
+INSERT INTO t2 VALUES (1),(2);
+
+# trigger that produces the high priority insert, but should be low, adding
+# LOW_PRIORITY fixes this
+CREATE TRIGGER t1_test AFTER INSERT ON t1 FOR EACH ROW 
+  INSERT INTO t2 VALUES (new.id);
+
+CONNECT (rl_holder,    localhost, root,,);
+CONNECT (rl_acquirer,  localhost, root,,);
+CONNECT (wl_acquirer,  localhost, root,,);
+CONNECT (rl_contender, localhost, root,,);
+
+CONNECTION rl_holder;
+SELECT GET_LOCK('B26162',120);
+
+CONNECTION rl_acquirer;
+let $rl_acquirer_thread_id = `SELECT @@pseudo_thread_id`;
+--send
+SELECT 'rl_acquirer', GET_LOCK('B26162',120), id FROM t2 WHERE id = 1;
+
+CONNECTION wl_acquirer;
+let $wl_acquirer_thread_id = `SELECT @@pseudo_thread_id`;
+SET SESSION LOW_PRIORITY_UPDATES=1;
+SET GLOBAL LOW_PRIORITY_UPDATES=1;
+#need to wait for rl_acquirer to lock on the B26162 lock 
+let $wait_condition=
+  SELECT STATE = 'User lock' FROM INFORMATION_SCHEMA.PROCESSLIST
+   WHERE ID = $rl_acquirer_thread_id;
+--source include/wait_condition.inc
+--send
+INSERT INTO t1 VALUES (5);
+
+CONNECTION rl_contender;
+# Wait until wl_acquirer is waiting for the read lock on t2 to be released.
+let $wait_condition=
+  SELECT STATE = 'Locked' FROM INFORMATION_SCHEMA.PROCESSLIST
+   WHERE ID = $wl_acquirer_thread_id;
+--source include/wait_condition.inc
+# must not "see" the row inserted by the INSERT (as it must run before the
+# INSERT)
+--send
+SELECT 'rl_contender', id FROM t2 WHERE id > 1;
+
+CONNECTION rl_holder;
+#need to wait for wl_acquirer and rl_contender to lock on t2 
+sleep 2;
+SELECT RELEASE_LOCK('B26162');
+
+CONNECTION rl_acquirer;
+--reap
+SELECT RELEASE_LOCK('B26162');
+CONNECTION wl_acquirer;
+--reap
+CONNECTION rl_contender;
+--reap
+
+CONNECTION default;
+DISCONNECT rl_acquirer;
+DISCONNECT wl_acquirer;
+DISCONNECT rl_contender;
+DISCONNECT rl_holder;
+
+DROP TRIGGER t1_test;
+DROP TABLE t1,t2;
+SET SESSION LOW_PRIORITY_UPDATES=DEFAULT;
+SET GLOBAL LOW_PRIORITY_UPDATES=DEFAULT;
+
 --echo End of 5.0 tests.
 
 #

=== modified file 'mysql-test/t/type_newdecimal.test'
--- a/mysql-test/t/type_newdecimal.test	2009-11-02 11:21:39 +0000
+++ b/mysql-test/t/type_newdecimal.test	2009-12-08 09:26:11 +0000
@@ -1286,3 +1286,229 @@ 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;
+
+--echo #
+--echo # Bug #45261 : Crash, stored procedure + decimal
+--echo # Original test by the reporter.
+--echo #
+
+--echo # should not crash
+CREATE TABLE t1 
+SELECT .123456789012345678901234567890123456789012345678901234567890123456 AS a;
+DROP TABLE t1;
+
+delimiter |;
+CREATE PROCEDURE test_proc()
+BEGIN
+  # The las non critical CUSER definition is:
+  # DECLARE mycursor CURSOR FOR SELECT 1 % 
+  # .12345678912345678912345678912345678912345678912345678912345678912 AS my_col;
+  DECLARE mycursor CURSOR FOR 
+SELECT 1 % 
+.123456789123456789123456789123456789123456789123456789123456789123456789123456789 
+  AS my_col;
+
+  OPEN mycursor;
+  CLOSE mycursor;
+END|
+delimiter ;|
+--echo # should not crash
+CALL test_proc();
+DROP PROCEDURE test_proc;
+
+--echo #
+--echo # Bug #48370  Absolutely wrong calculations with GROUP BY and 
+--echo # decimal fields when using IF
+--echo #
+
+CREATE TABLE currencies (id int, rate decimal(16,4), 
+  PRIMARY KEY (id), KEY (rate));
+
+INSERT INTO currencies VALUES (11,0.7028);
+INSERT INTO currencies VALUES (1,1);
+
+CREATE TABLE payments (
+  id int,
+  supplier_id int,
+  status int,
+  currency_id int,
+  vat decimal(7,4),
+  PRIMARY KEY (id),
+  KEY currency_id (currency_id),
+  KEY supplier_id (supplier_id)
+);
+
+INSERT INTO payments (id,status,vat,supplier_id,currency_id) VALUES
+(3001,2,0.0000,344,11), (1,2,0.0000,1,1);
+
+CREATE TABLE sub_tasks (
+  id int,
+  currency_id int,
+  price decimal(16,4),
+  discount decimal(10,4),
+  payment_id int,
+  PRIMARY KEY (id),
+  KEY currency_id (currency_id),
+  KEY payment_id (payment_id)
+) ;
+
+INSERT INTO sub_tasks (id, price, discount, payment_id, currency_id) VALUES
+(52, 12.60, 0, 3001, 11), (56, 14.58, 0, 3001, 11);
+
+--echo # should return 1 and the same values in col 2 and 3
+select STRAIGHT_JOIN
+  (1 + PAY.vat) AS mult,
+  SUM(ROUND((SUB.price - ROUND(ROUND(SUB.price, 2) * SUB.discount, 2)) * 
+            CUR.rate / CUR.rate, 2)
+  ) v_net_with_discount,
+
+  SUM(ROUND((SUB.price - ROUND(ROUND(SUB.price, 2) * SUB.discount, 1)) *
+            CUR.rate / CUR.rate , 2) 
+      * (1 + PAY.vat)
+  ) v_total
+from
+   currencies CUR, payments PAY, sub_tasks SUB
+where
+  SUB.payment_id = PAY.id and
+  PAY.currency_id = CUR.id and
+  PAY.id > 2
+group by PAY.id + 1;
+
+DROP TABLE currencies, payments, sub_tasks;
+
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/type_year.test'
--- a/mysql-test/t/type_year.test	2007-03-29 04:08:30 +0000
+++ b/mysql-test/t/type_year.test	2009-12-15 08:37:10 +0000
@@ -30,3 +30,109 @@ select * from t1;
 drop table t1;
 
 --echo End of 5.0 tests
+
+--echo #
+--echo # Bug #49480: WHERE using YEAR columns returns unexpected results
+--echo #
+
+CREATE TABLE t2(yy YEAR(2), c2 CHAR(4));
+CREATE TABLE t4(yyyy YEAR(4), c4 CHAR(4));
+
+INSERT INTO t2 (c2) VALUES (NULL),(1970),(1999),(2000),(2001),(2069);
+INSERT INTO t4 (c4) SELECT c2 FROM t2;
+UPDATE t2 SET yy = c2;
+UPDATE t4 SET yyyy = c4;
+
+SELECT * FROM t2;
+SELECT * FROM t4;
+
+--echo # Comparison of YEAR(2) with YEAR(4)
+
+SELECT * FROM t2, t4 WHERE yy = yyyy;
+SELECT * FROM t2, t4 WHERE yy <=> yyyy;
+SELECT * FROM t2, t4 WHERE yy < yyyy;
+SELECT * FROM t2, t4 WHERE yy > yyyy;
+
+--echo # Comparison of YEAR(2) with YEAR(2)
+
+SELECT * FROM t2 a, t2 b WHERE a.yy = b.yy;
+SELECT * FROM t2 a, t2 b WHERE a.yy <=> b.yy;
+SELECT * FROM t2 a, t2 b WHERE a.yy < b.yy;
+
+--echo # Comparison of YEAR(4) with YEAR(4)
+
+SELECT * FROM t4 a, t4 b WHERE a.yyyy = b.yyyy;
+SELECT * FROM t4 a, t4 b WHERE a.yyyy <=> b.yyyy;
+SELECT * FROM t4 a, t4 b WHERE a.yyyy < b.yyyy;
+
+--echo # Comparison with constants:
+
+SELECT * FROM t2 WHERE yy = NULL;
+SELECT * FROM t4 WHERE yyyy = NULL;
+SELECT * FROM t2 WHERE yy <=> NULL;
+SELECT * FROM t4 WHERE yyyy <=> NULL;
+SELECT * FROM t2 WHERE yy < NULL;
+SELECT * FROM t2 WHERE yy > NULL;
+
+SELECT * FROM t2 WHERE yy = NOW();
+SELECT * FROM t4 WHERE yyyy = NOW();
+
+SELECT * FROM t2 WHERE yy = 99;
+SELECT * FROM t2 WHERE 99 = yy;
+SELECT * FROM t4 WHERE yyyy = 99;
+
+SELECT * FROM t2 WHERE yy = 'test';
+SELECT * FROM t4 WHERE yyyy = 'test';
+
+SELECT * FROM t2 WHERE yy = '1999';
+SELECT * FROM t4 WHERE yyyy = '1999';
+
+SELECT * FROM t2 WHERE yy = 1999;
+SELECT * FROM t4 WHERE yyyy = 1999;
+
+SELECT * FROM t2 WHERE yy = 1999.1;
+SELECT * FROM t4 WHERE yyyy = 1999.1;
+
+SELECT * FROM t2 WHERE yy = 1998.9;
+SELECT * FROM t4 WHERE yyyy = 1998.9;
+
+--echo # Coverage tests for YEAR with zero/2000 constants:
+
+SELECT * FROM t2 WHERE yy = 0;
+SELECT * FROM t2 WHERE yy = '0';
+SELECT * FROM t2 WHERE yy = '0000';
+SELECT * FROM t2 WHERE yy = '2000';
+SELECT * FROM t2 WHERE yy = 2000;
+
+SELECT * FROM t4 WHERE yyyy = 0;
+SELECT * FROM t4 WHERE yyyy = '0';
+SELECT * FROM t4 WHERE yyyy = '0000';
+SELECT * FROM t4 WHERE yyyy = '2000';
+SELECT * FROM t4 WHERE yyyy = 2000;
+
+--echo # Comparison with constants those are out of YEAR range
+--echo # (coverage test for backward compatibility)
+
+SELECT COUNT(yy) FROM t2;
+SELECT COUNT(yyyy) FROM t4;
+
+SELECT COUNT(*) FROM t2 WHERE yy = -1;
+SELECT COUNT(*) FROM t4 WHERE yyyy > -1;
+SELECT COUNT(*) FROM t2 WHERE yy > -1000000000000000000;
+SELECT COUNT(*) FROM t4 WHERE yyyy > -1000000000000000000;
+
+SELECT COUNT(*) FROM t2 WHERE yy < 2156;
+SELECT COUNT(*) FROM t4 WHERE yyyy < 2156;
+SELECT COUNT(*) FROM t2 WHERE yy < 1000000000000000000;
+SELECT COUNT(*) FROM t4 WHERE yyyy < 1000000000000000000;
+
+SELECT * FROM t2 WHERE yy < 123;
+SELECT * FROM t2 WHERE yy > 123;
+SELECT * FROM t4 WHERE yyyy < 123;
+SELECT * FROM t4 WHERE yyyy > 123;
+
+DROP TABLE t2, t4;
+
+--echo #
+
+--echo End of 5.1 tests

=== modified file 'mysql-test/t/udf.test'
--- a/mysql-test/t/udf.test	2009-09-07 09:57:22 +0000
+++ b/mysql-test/t/udf.test	2010-01-11 13:15:28 +0000
@@ -342,29 +342,6 @@ drop function myfunc_double;
 drop function myfunc_int;
 
 #
-# Bug #28921: Queries containing UDF functions are cached
-#
-
---replace_result $UDF_EXAMPLE_LIB UDF_EXAMPLE_LIB
-eval CREATE FUNCTION metaphon RETURNS STRING SONAME "$UDF_EXAMPLE_LIB";
-create table t1 (a char);
-
-set GLOBAL query_cache_size=1355776;
-reset query cache;
-
-select metaphon('MySQL') from t1;
-show status like "Qcache_hits";
-show status like "Qcache_queries_in_cache";
-
-select metaphon('MySQL') from t1;
-show status like "Qcache_hits";
-show status like "Qcache_queries_in_cache";
-
-drop table t1;
-drop function metaphon;
-set GLOBAL query_cache_size=default;
-
-#
 # Bug#28318  CREATE FUNCTION (UDF) requires a schema
 #
 

=== added file 'mysql-test/t/udf_query_cache-master.opt'
--- a/mysql-test/t/udf_query_cache-master.opt	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/udf_query_cache-master.opt	2010-01-11 13:15:28 +0000
@@ -0,0 +1 @@
+$UDF_EXAMPLE_LIB_OPT

=== added file 'mysql-test/t/udf_query_cache.test'
--- a/mysql-test/t/udf_query_cache.test	1970-01-01 00:00:00 +0000
+++ b/mysql-test/t/udf_query_cache.test	2010-01-11 13:15:28 +0000
@@ -0,0 +1,35 @@
+--source include/have_udf.inc
+--source include/have_query_cache.inc
+#
+# To run this tests the "sql/udf_example.c" need to be compiled into
+# udf_example.so and LD_LIBRARY_PATH should be setup to point out where
+# the library are.
+#
+
+--disable_warnings
+drop table if exists t1;
+--enable_warnings
+
+#
+# Bug #28921: Queries containing UDF functions are cached
+#
+
+--replace_result $UDF_EXAMPLE_LIB UDF_EXAMPLE_LIB
+eval CREATE FUNCTION metaphon RETURNS STRING SONAME "$UDF_EXAMPLE_LIB";
+create table t1 (a char);
+
+set GLOBAL query_cache_size=1355776;
+reset query cache;
+
+select metaphon('MySQL') from t1;
+show status like "Qcache_hits";
+show status like "Qcache_queries_in_cache";
+
+select metaphon('MySQL') from t1;
+show status like "Qcache_hits";
+show status like "Qcache_queries_in_cache";
+
+drop table t1;
+drop function metaphon;
+set GLOBAL query_cache_size=default;
+

=== modified file 'mysql-test/t/variables.test'
--- a/mysql-test/t/variables.test	2009-09-07 20:50:10 +0000
+++ b/mysql-test/t/variables.test	2010-01-11 13:15:28 +0000
@@ -28,8 +28,6 @@ set @my_myisam_max_sort_file_size =@@glo
 set @my_net_buffer_length         =@@global.net_buffer_length;
 set @my_net_write_timeout         =@@global.net_write_timeout;
 set @my_net_read_timeout          =@@global.net_read_timeout;
-set @my_query_cache_limit         =@@global.query_cache_limit;
-set @my_query_cache_type          =@@global.query_cache_type;
 set @my_rpl_recovery_rank         =@@global.rpl_recovery_rank;
 set @my_server_id                 =@@global.server_id;
 set @my_slow_launch_time          =@@global.slow_launch_time;
@@ -138,7 +136,6 @@ show local variables like 'storage_engin
 select * from information_schema.session_variables where variable_name like 'storage_engine';
 show global variables like 'storage_engine';
 select * from information_schema.global_variables where variable_name like 'storage_engine';
-set GLOBAL query_cache_size=100000;
 
 set GLOBAL myisam_max_sort_file_size=2000000;
 show global variables like 'myisam_max_sort_file_size';
@@ -255,8 +252,6 @@ set storage_engine=UNKNOWN_TABLE_TYPE;
 --error ER_WRONG_VALUE_FOR_VAR
 set storage_engine=MERGE, big_tables=2;
 show local variables like 'storage_engine';
---error ER_GLOBAL_VARIABLE
-set SESSION query_cache_size=10000;
 --error ER_NO_DEFAULT
 set GLOBAL storage_engine=DEFAULT;
 --error ER_UNKNOWN_CHARACTER_SET
@@ -334,9 +329,6 @@ set myisam_sort_buffer_size=100;
 set global net_buffer_length=100;
 set net_read_timeout=100;
 set net_write_timeout=100;
-set global query_cache_limit=100;
-set global query_cache_size=100;
-set global query_cache_type=demand;
 set read_buffer_size=100;
 set read_rnd_buffer_size=100;
 set global rpl_recovery_rank=100;
@@ -822,8 +814,6 @@ set global myisam_max_sort_file_size =@m
 set global net_buffer_length         =@my_net_buffer_length;
 set global net_write_timeout         =@my_net_write_timeout;
 set global net_read_timeout          =@my_net_read_timeout;
-set global query_cache_limit         =@my_query_cache_limit;
-set global query_cache_type          =@my_query_cache_type;
 set global rpl_recovery_rank         =@my_rpl_recovery_rank;
 set global server_id                 =@my_server_id;
 set global slow_launch_time          =@my_slow_launch_time;

=== modified file 'mysys/my_getopt.c'
--- a/mysys/my_getopt.c	2009-12-03 11:19:05 +0000
+++ b/mysys/my_getopt.c	2010-01-15 15:27:55 +0000
@@ -414,17 +414,11 @@ invalid value '%s'",
                    (optp->var_type & GET_TYPE_MASK) == GET_ENUM))
 	{
 	  if (optend == disabled_my_option)
-            if ((optp->var_type & GET_TYPE_MASK) == GET_BOOL)
-              *((my_bool*) value)= (my_bool) 0;
-            else
-              *((ulong*) value)= (ulong) 0;
+            init_one_value(optp, value, 0);
 	  else
 	  {
 	    if (!optend) /* No argument -> enable option */
-              if ((optp->var_type & GET_TYPE_MASK) == GET_BOOL)
-                *((my_bool*) value)= (my_bool) 1;
-              else
-                *((ulong*) value)= (ulong) 1;
+                init_one_value(optp, value, 1);
             else
               argument= optend;
 	  }

=== modified file 'mysys/my_sync.c'
--- a/mysys/my_sync.c	2008-04-28 16:24:05 +0000
+++ b/mysys/my_sync.c	2010-01-15 15:27:55 +0000
@@ -100,14 +100,15 @@ static const char cur_dir_name[]= {FN_CU
   RETURN
     0 if ok, !=0 if error
 */
-int my_sync_dir(const char *dir_name, myf my_flags)
+int my_sync_dir(const char *dir_name __attribute__((unused)),
+                myf my_flags __attribute__((unused)))
 {
 #ifdef NEED_EXPLICIT_SYNC_DIR
-  DBUG_ENTER("my_sync_dir");
-  DBUG_PRINT("my",("Dir: '%s'  my_flags: %d", dir_name, my_flags));
   File dir_fd;
   int res= 0;
   const char *correct_dir_name;
+  DBUG_ENTER("my_sync_dir");
+  DBUG_PRINT("my",("Dir: '%s'  my_flags: %d", dir_name, my_flags));
   /* Sometimes the path does not contain an explicit directory */
   correct_dir_name= (dir_name[0] == 0) ? cur_dir_name : dir_name;
   /*
@@ -141,7 +142,8 @@ int my_sync_dir(const char *dir_name, my
   RETURN
     0 if ok, !=0 if error
 */
-int my_sync_dir_by_file(const char *file_name, myf my_flags)
+int my_sync_dir_by_file(const char *file_name __attribute__((unused)),
+                        myf my_flags __attribute__((unused)))
 {
 #ifdef NEED_EXPLICIT_SYNC_DIR
   char dir_name[FN_REFLEN];

=== modified file 'mysys/my_uuid.c'
--- a/mysys/my_uuid.c	2009-02-01 12:02:29 +0000
+++ b/mysys/my_uuid.c	2010-01-04 18:31:26 +0000
@@ -108,7 +108,7 @@ void my_uuid_init(ulong seed1, ulong see
     */
     /* purecov: begin inspected */
     my_rnd_init(&uuid_rand, (ulong) (seed2+ now/2), (ulong) (now+rand()));
-    for (i=0; i < sizeof(mac); i++)
+    for (i=0; i < array_elements(uuid_suffix) -2 ; i++)
       mac[i]= (uchar)(my_rnd(&uuid_rand)*255);
     /* purecov: end */
   }

=== modified file 'scripts/make_win_bin_dist'
--- a/scripts/make_win_bin_dist	2009-12-03 11:19:05 +0000
+++ b/scripts/make_win_bin_dist	2010-01-15 15:27:55 +0000
@@ -352,7 +352,7 @@ 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/
+cp -R mysql-test/{t,r,include,suite,std_data,lib,collections} $DESTDIR/mysql-test/
 
 rm -rf $DESTDIR/mysql-test/lib/My/SafeProcess/my_safe_kill.{dir,vcproj}
 rm -rf $DESTDIR/mysql-test/lib/My/SafeProcess/my_safe_process.{dir,vcproj}

=== modified file 'scripts/mysql_secure_installation.pl.in'
--- a/scripts/mysql_secure_installation.pl.in	2007-12-28 21:58:54 +0000
+++ b/scripts/mysql_secure_installation.pl.in	2009-11-03 21:34:01 +0000
@@ -17,16 +17,41 @@
 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 use Fcntl;
+use File::Spec;
+use if $^O eq 'MSWin32', 'Term::ReadKey' => qw/ReadMode/;
 use strict;
 
 my $config  = ".my.cnf.$$";
 my $command = ".mysql.$$";
 my $hadpass = 0;
+my $mysql;  # How to call the mysql client
+my $rootpass = "";
 
-# FIXME
-# trap "interrupt" 2
 
-my $rootpass = "";
+$SIG{QUIT} = $SIG{INT} = sub {
+  print "\nAborting!\n\n";
+  echo_on();
+  cleanup();
+  exit 1;
+};
+
+
+END {
+  # Remove temporary files, even if exiting via die(), etc.
+  cleanup();
+}
+
+
+sub read_without_echo {
+  my ($prompt) = @_;
+  print $prompt;
+  echo_off();
+  my $answer = <STDIN>;
+  echo_on();
+  print "\n";
+  chomp($answer);
+  return $answer;
+}
 
 sub echo_on {
   if ($^O eq 'MSWin32') {
@@ -55,6 +80,25 @@ sub write_file {
 }
 
 sub prepare {
+  # Locate the mysql client; look in current directory first, then
+  # in path
+  our $SAVEERR;   # Suppress Perl warning message
+  open SAVEERR, ">& STDERR";
+  close STDERR;
+  for my $m (File::Spec->catfile('bin', 'mysql'), 'mysql') {
+    # mysql --version should always work
+    qx($m --no-defaults --version);
+    next unless $? == 0;
+
+    $mysql = $m;
+    last;
+  }
+  open STDERR, ">& SAVEERR";
+
+  die "Can't find a 'mysql' client in PATH or ./bin\n"
+    unless $mysql;
+
+  # Create safe files to avoid leaking info to other users
   foreach my $file ( $config, $command ) {
     next if -f $file;                   # Already exists
     local *FILE;
@@ -64,30 +108,50 @@ sub prepare {
   }
 }
 
+# Simple escape mechanism (\-escape any ' and \), suitable for two contexts:
+# - single-quoted SQL strings
+# - single-quoted option values on the right hand side of = in my.cnf
+#
+# These two contexts don't handle escapes identically.  SQL strings allow
+# quoting any character (\C => C, for any C), but my.cnf parsing allows
+# quoting only \, ' or ".  For example, password='a\b' quotes a 3-character
+# string in my.cnf, but a 2-character string in SQL.
+#
+# This simple escape works correctly in both places.
+sub basic_single_escape {
+  my ($str) = @_;
+  # Inside a character class, \ is not special; this escapes both \ and '
+  $str =~ s/([\'])/\\$1/g;
+  return $str;
+}
+
 sub do_query {
   my $query   = shift;
   write_file($command, $query);
-  system("mysql --defaults-file=$config < $command");
-  return $?;
+  my $rv = system("$mysql --defaults-file=$config < $command");
+  # system() returns -1 if exec fails (e.g., command not found, etc.); die
+  # in this case because nothing is going to work
+  die "Failed to execute mysql client '$mysql'\n" if $rv == -1;
+  # Return true if query executed OK, or false if there was some problem
+  # (for example, SQL error or wrong password)
+  return ($rv == 0 ? 1 : undef);
 }
 
 sub make_config {
   my $password = shift;
 
+  my $esc_pass = basic_single_escape($rootpass);
   write_file($config,
              "# mysql_secure_installation config file",
              "[mysql]",
              "user=root",
-             "password=$rootpass");
+             "password='$esc_pass'");
 }
 
 sub get_root_password {
-  my $status = 1;
-  while ( $status == 1 ) {
-    echo_off();
-    print "Enter current password for root (enter for none): ";
-    my $password = <STDIN>;
-    echo_on();
+  my $attempts = 3;
+  for (;;) {
+    my $password = read_without_echo("Enter current password for root (enter for none): ");
     if ( $password ) {
       $hadpass = 1;
     } else {
@@ -95,64 +159,56 @@ sub get_root_password {
     }
     $rootpass = $password;
     make_config($rootpass);
-    do_query("");
-    $status = $?;
+    last if do_query("");
+
+    die "Unable to connect to the server as root user, giving up.\n"
+      if --$attempts == 0;
   }
   print "OK, successfully used password, moving on...\n\n";
 }
 
 sub set_root_password {
-  echo_off();
-  print "New password: ";
-  my $password1 = <STDIN>;
-  print "\nRe-enter new password: ";
-  my $password2 = <STDIN>;
-  print "\n";
-  echo_on();
-
-  if ( $password1 eq $password2 ) {
-    print "Sorry, passwords do not match.\n\n";
-    return 1;
-  }
+  my $password1;
+  for (;;) {
+    $password1 = read_without_echo("New password: ");
+
+    if ( !$password1 ) {
+      print "Sorry, you can't use an empty password here.\n\n";
+      next;
+    }
 
-  if ( !$password1 ) {
-    print "Sorry, you can't use an empty password here.\n\n";
-    return 1;
-  }
+    my $password2 = read_without_echo("Re-enter new password: ");
 
-  do_query("UPDATE mysql.user SET Password=PASSWORD('$password1') WHERE User='root';");
-  if ( $? == 0 ) {
-    print "Password updated successfully!\n";
-    print "Reloading privilege tables..\n";
-    if ( !reload_privilege_tables() ) {
-      exit 1;
+    if ( $password1 ne $password2 ) {
+      print "Sorry, passwords do not match.\n\n";
+      next;
     }
-    print "\n";
-    $rootpass = $password1;
-    make_config($rootpass);
-  } else {
-    print "Password update failed!\n";
-    exit 1;
+
+    last;
   }
 
-  return 0;
+  my $esc_pass = basic_single_escape($password1);
+  do_query("UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';")
+    or die "Password update failed!\n";
+
+  print "Password updated successfully!\n";
+  print "Reloading privilege tables..\n";
+  reload_privilege_tables()
+    or die "Can not continue.\n";
+
+  print "\n";
+  $rootpass = $password1;
+  make_config($rootpass);
 }
 
 sub remove_anonymous_users {
-  do_query("DELETE FROM mysql.user WHERE User='';");
-  if ( $? == 0 ) {
-    print " ... Success!\n";
-  } else {
-    print " ... Failed!\n";
-    exit 1;
-  }
-
-  return 0;
+  do_query("DELETE FROM mysql.user WHERE User='';")
+    or die print " ... Failed!\n";
+  print " ... Success!\n";
 }
 
 sub remove_remote_root {
-  do_query("DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';");
-  if ( $? == 0 ) {
+  if (do_query("DELETE FROM mysql.user WHERE User='root' AND Host!='localhost';")) {
     print " ... Success!\n";
   } else {
     print " ... Failed!\n";
@@ -161,44 +217,31 @@ sub remove_remote_root {
 
 sub remove_test_database {
   print " - Dropping test database...\n";
-  do_query("DROP DATABASE test;");
-  if ( $? == 0 ) {
+  if (do_query("DROP DATABASE test;")) {
     print " ... Success!\n";
   } else {
     print " ... Failed!  Not critical, keep moving...\n";
   }
 
   print " - Removing privileges on test database...\n";
-  do_query("DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'");
-  if ( $? == 0 ) {
+  if (do_query("DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'")) {
     print " ... Success!\n";
   } else {
     print " ... Failed!  Not critical, keep moving...\n";
   }
-
-  return 0;
 }
 
 sub reload_privilege_tables {
-  do_query("FLUSH PRIVILEGES;");
-  if ( $? == 0 ) {
+  if (do_query("FLUSH PRIVILEGES;")) {
     print " ... Success!\n";
-    return 0;
+    return 1;
   } else {
     print " ... Failed!\n";
-    return 1;
+    return undef;
   }
 }
 
-sub interrupt {
-  print "\nAborting!\n\n";
-  cleanup();
-  echo_on();
-  exit 1;
-}
-
 sub cleanup {
-  print "Cleaning up...\n";
   unlink($config,$command);
 }
 
@@ -242,11 +285,7 @@ my $reply = <STDIN>;
 if ( $reply =~ /n/i ) {
   print " ... skipping.\n";
 } else {
-  my $status = 1;
-  while ( $status == 1 ) {
-    set_root_password();
-    $status = $?;
-  }
+  set_root_password();
 }
 print "\n";
 
@@ -334,8 +373,6 @@ if ( $reply =~ /n/i ) {
 }
 print "\n";
 
-cleanup();
-
 print <<HERE;
 
 

=== modified file 'scripts/mysql_secure_installation.sh'
--- a/scripts/mysql_secure_installation.sh	2009-10-23 16:48:54 +0000
+++ b/scripts/mysql_secure_installation.sh	2010-01-15 15:27:55 +0000
@@ -189,16 +189,39 @@ prepare() {
 }
 
 do_query() {
-    echo $1 >$command
+    echo "$1" >$command
+    #sed 's,^,> ,' < $command  # Debugging
     $bindir/mysql --defaults-file=$config <$command
     return $?
 }
 
+# Simple escape mechanism (\-escape any ' and \), suitable for two contexts:
+# - single-quoted SQL strings
+# - single-quoted option values on the right hand side of = in my.cnf
+#
+# These two contexts don't handle escapes identically.  SQL strings allow
+# quoting any character (\C => C, for any C), but my.cnf parsing allows
+# quoting only \, ' or ".  For example, password='a\b' quotes a 3-character
+# string in my.cnf, but a 2-character string in SQL.
+#
+# This simple escape works correctly in both places.
+basic_single_escape () {
+    # The quoting on this sed command is a bit complex.  Single-quoted strings
+    # don't allow *any* escape mechanism, so they cannot contain a single
+    # quote.  The string sed gets (as argv[1]) is:  s/\(['\]\)/\\\1/g
+    #
+    # Inside a character class, \ and ' are not special, so the ['\] character
+    # class is balanced and contains two characters.
+    echo "$1" | sed 's/\(['"'"'\]\)/\\\1/g'
+}
+
 make_config() {
     echo "# mysql_secure_installation config file" >$config
     echo "[mysql]" >>$config
     echo "user=root" >>$config
-    echo "password=$rootpass" >>$config
+    esc_pass=`basic_single_escape "$rootpass"`
+    echo "password='$esc_pass'" >>$config
+    #sed 's,^,> ,' < $config  # Debugging
 }
 
 get_root_password() {
@@ -245,13 +268,12 @@ set_root_password() {
 	return 1
     fi
 
-    do_query "UPDATE mysql.user SET Password=PASSWORD('$password1') WHERE User='root';"
+    esc_pass=`basic_single_escape "$password1"`
+    do_query "UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';"
     if [ $? -eq 0 ]; then
 	echo "Password updated successfully!"
 	echo "Reloading privilege tables.."
-	if ! reload_privilege_tables; then
-	    exit 1
-	fi
+	reload_privilege_tables || exit 1
 	echo
 	rootpass=$password1
 	make_config

=== modified file 'scripts/mysqlbug.sh'
--- a/scripts/mysqlbug.sh	2007-10-19 17:06:30 +0000
+++ b/scripts/mysqlbug.sh	2009-12-27 13:54:41 +0000
@@ -21,7 +21,7 @@ echo "Finding system information for a M
 
 VERSION="@VERSION@@MYSQL_SERVER_SUFFIX@"
 COMPILATION_COMMENT="@COMPILATION_COMMENT@"
-BUGmysql="mysql@xxxxxxxxxxxxxxx"
+BUGmysql="maria-developers@xxxxxxxxxxxxxxxxxxx"
 # This is set by configure
 COMP_CALL_INFO="CC='@SAVE_CC@'  CFLAGS='@SAVE_CFLAGS@'  CXX='@SAVE_CXX@'  CXXFLAGS='@SAVE_CXXFLAGS@'  LDFLAGS='@SAVE_LDFLAGS@'  ASFLAGS='@SAVE_ASFLAGS@'"
 COMP_RUN_INFO="CC='@CC@'  CFLAGS='@CFLAGS@'  CXX='@CXX@'  CXXFLAGS='@CXXFLAGS@'  LDFLAGS='@LDFLAGS@'  ASFLAGS='@ASFLAGS@'"

=== modified file 'sql/event_db_repository.cc'
--- a/sql/event_db_repository.cc	2009-12-03 11:19:05 +0000
+++ b/sql/event_db_repository.cc	2010-01-15 15:27:55 +0000
@@ -26,7 +26,7 @@
 */
 
 static
-const TABLE_FIELD_W_TYPE event_table_fields[ET_FIELD_COUNT] =
+const TABLE_FIELD_TYPE event_table_fields[ET_FIELD_COUNT] =
 {
   {
     { C_STRING_WITH_LEN("db") },
@@ -151,6 +151,24 @@ const TABLE_FIELD_W_TYPE event_table_fie
   }
 };
 
+static const TABLE_FIELD_DEF
+  event_table_def= {ET_FIELD_COUNT, event_table_fields};
+
+class Event_db_intact : public Table_check_intact
+{
+protected:
+  void report_error(uint, const char *fmt, ...)
+  {
+    va_list args;
+    va_start(args, fmt);
+    error_log_print(ERROR_LEVEL, fmt, args);
+    va_end(args);
+  }
+};
+
+/** In case of an error, a message is printed to the error log. */
+static Event_db_intact table_intact;
+
 
 /**
   Puts some data common to CREATE and ALTER EVENT into a row.
@@ -1117,10 +1135,8 @@ Event_db_repository::check_system_tables
   }
   else
   {
-    if (table_check_intact(tables.table, MYSQL_DB_FIELD_COUNT,
-                           mysql_db_table_fields))
+    if (table_intact.check(tables.table, &mysql_db_table_def))
       ret= 1;
-    /* in case of an error, the message is printed inside table_check_intact */
 
     close_thread_tables(thd);
   }
@@ -1154,9 +1170,8 @@ Event_db_repository::check_system_tables
   }
   else
   {
-    if (table_check_intact(tables.table, ET_FIELD_COUNT, event_table_fields))
+    if (table_intact.check(tables.table, &event_table_def))
       ret= 1;
-    /* in case of an error, the message is printed inside table_check_intact */
     close_thread_tables(thd);
   }
 

=== modified file 'sql/field.cc'
--- a/sql/field.cc	2009-12-03 11:19:05 +0000
+++ b/sql/field.cc	2010-01-15 15:27:55 +0000
@@ -2487,6 +2487,50 @@ Field_new_decimal::Field_new_decimal(uin
 }
 
 
+Field *Field_new_decimal::create_from_item (Item *item)
+{
+  uint8 dec= item->decimals;
+  uint8 intg= item->decimal_precision() - dec;
+  uint32 len= item->max_length;
+
+  DBUG_ASSERT (item->result_type() == DECIMAL_RESULT);
+
+  /*
+    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;
+  }
+  return new Field_new_decimal(len, item->maybe_null, item->name,
+                               dec, item->unsigned_flag);
+}
+
+
 int Field_new_decimal::reset(void)
 {
   store_value(&decimal_zero);

=== modified file 'sql/field.h'
--- a/sql/field.h	2009-12-03 11:19:05 +0000
+++ b/sql/field.h	2010-01-15 15:27:55 +0000
@@ -807,6 +807,7 @@ public:
   uint is_equal(Create_field *new_field);
   virtual const uchar *unpack(uchar* to, const uchar *from,
                               uint param_data, bool low_byte_first);
+  static Field *create_from_item (Item *);
 };
 
 

=== modified file 'sql/ha_ndbcluster.cc'
--- a/sql/ha_ndbcluster.cc	2009-12-03 11:19:05 +0000
+++ b/sql/ha_ndbcluster.cc	2010-01-06 21:27:53 +0000
@@ -10565,4 +10565,6 @@ mysql_declare_plugin(ndbcluster)
 }
 mysql_declare_plugin_end;
 
+#else
+int Sun_ar_require_a_symbol_here= 0;
 #endif

=== modified file 'sql/handler.h'
--- a/sql/handler.h	2009-12-03 11:19:05 +0000
+++ b/sql/handler.h	2010-01-14 16:51:00 +0000
@@ -278,6 +278,11 @@ enum legacy_db_type
   DB_TYPE_FIRST_DYNAMIC=42,
   DB_TYPE_DEFAULT=127 // Must be last
 };
+/*
+  Better name for DB_TYPE_UNKNOWN. Should be used for engines that do not have
+  a hard-coded type value here.
+ */
+#define DB_TYPE_AUTOASSIGN DB_TYPE_UNKNOWN
 
 enum row_type { ROW_TYPE_NOT_USED=-1, ROW_TYPE_DEFAULT, ROW_TYPE_FIXED,
 		ROW_TYPE_DYNAMIC, ROW_TYPE_COMPRESSED,
@@ -886,9 +891,9 @@ typedef struct {
   ulonglong delete_length;
   ha_rows records;
   ulong mean_rec_length;
-  ulong create_time;
-  ulong check_time;
-  ulong update_time;
+  time_t create_time;
+  time_t check_time;
+  time_t update_time;
   ulonglong check_sum;
 } PARTITION_INFO;
 
@@ -1055,9 +1060,9 @@ public:
   ha_rows records;
   ha_rows deleted;			/* Deleted records */
   ulong mean_rec_length;		/* physical reclength */
-  ulong create_time;			/* When table was created */
-  ulong check_time;
-  ulong update_time;
+  time_t create_time;			/* When table was created */
+  time_t check_time;
+  time_t update_time;
   uint block_size;			/* index block size */
 
   ha_statistics():

=== modified file 'sql/item.cc'
--- a/sql/item.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item.cc	2010-01-15 15:27:55 +0000
@@ -4908,9 +4908,7 @@ Field *Item::tmp_table_field_from_field_
   switch (field_type()) {
   case MYSQL_TYPE_DECIMAL:
   case MYSQL_TYPE_NEWDECIMAL:
-    field= new Field_new_decimal((uchar*) 0, max_length, null_ptr, 0,
-                                 Field::NONE, name, decimals, 0,
-                                 unsigned_flag);
+    field= Field_new_decimal::create_from_item(this);
     break;
   case MYSQL_TYPE_TINY:
     field= new Field_tiny((uchar*) 0, max_length, null_ptr, 0, Field::NONE,
@@ -6949,9 +6947,24 @@ int stored_field_cmp_to_item(THD *thd, F
 
 Item_cache* Item_cache::get_cache(const Item *item)
 {
-  switch (item->result_type()) {
+  return get_cache(item, item->result_type());
+}
+
+
+/**
+  Get a cache item of given type.
+
+  @param item         value to be cached
+  @param type         required type of cache
+
+  @return cache item
+*/
+
+Item_cache* Item_cache::get_cache(const Item *item, const Item_result type)
+{
+  switch (type) {
   case INT_RESULT:
-    return new Item_cache_int();
+    return new Item_cache_int(item->field_type());
   case REAL_RESULT:
     return new Item_cache_real();
   case DECIMAL_RESULT:
@@ -6967,6 +6980,13 @@ Item_cache* Item_cache::get_cache(const
   }
 }
 
+void Item_cache::store(Item *item)
+{
+  example= item;
+  if (!item)
+    null_value= TRUE;
+  value_cached= FALSE;
+}
 
 void Item_cache::print(String *str, enum_query_type query_type)
 {
@@ -6978,17 +6998,22 @@ void Item_cache::print(String *str, enum
   str->append(')');
 }
 
-
-void Item_cache_int::store(Item *item)
+bool  Item_cache_int::cache_value()
 {
-  value= item->val_int_result();
-  null_value= item->null_value;
-  unsigned_flag= item->unsigned_flag;
+  if (!example)
+    return FALSE;
+  value_cached= TRUE;
+  value= example->val_int_result();
+  null_value= example->null_value;
+  unsigned_flag= example->unsigned_flag;
+  return TRUE;
 }
 
 
 void Item_cache_int::store(Item *item, longlong val_arg)
 {
+  /* An explicit values is given, save it. */
+  value_cached= TRUE;
   value= val_arg;
   null_value= item->null_value;
   unsigned_flag= item->unsigned_flag;
@@ -6998,6 +7023,8 @@ void Item_cache_int::store(Item *item, l
 String *Item_cache_int::val_str(String *str)
 {
   DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return NULL;
   str->set(value, default_charset());
   return str;
 }
@@ -7006,21 +7033,52 @@ String *Item_cache_int::val_str(String *
 my_decimal *Item_cache_int::val_decimal(my_decimal *decimal_val)
 {
   DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return NULL;
   int2my_decimal(E_DEC_FATAL_ERROR, value, unsigned_flag, decimal_val);
   return decimal_val;
 }
 
+double Item_cache_int::val_real()
+{
+  DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return 0.0;
+  return (double) value;
+}
 
-void Item_cache_real::store(Item *item)
+longlong Item_cache_int::val_int()
 {
-  value= item->val_result();
-  null_value= item->null_value;
+  DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return 0;
+  return value;
 }
 
+bool Item_cache_real::cache_value()
+{
+  if (!example)
+    return FALSE;
+  value_cached= TRUE;
+  value= example->val_result();
+  null_value= example->null_value;
+  return TRUE;
+}
+
+
+double Item_cache_real::val_real()
+{
+  DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return 0.0;
+  return value;
+}
 
 longlong Item_cache_real::val_int()
 {
   DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return 0;
   return (longlong) rint(value);
 }
 
@@ -7028,6 +7086,8 @@ longlong Item_cache_real::val_int()
 String* Item_cache_real::val_str(String *str)
 {
   DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return NULL;
   str->set_real(value, decimals, default_charset());
   return str;
 }
@@ -7036,22 +7096,30 @@ String* Item_cache_real::val_str(String
 my_decimal *Item_cache_real::val_decimal(my_decimal *decimal_val)
 {
   DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return NULL;
   double2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
   return decimal_val;
 }
 
 
-void Item_cache_decimal::store(Item *item)
+bool Item_cache_decimal::cache_value()
 {
-  my_decimal *val= item->val_decimal_result(&decimal_value);
-  if (!(null_value= item->null_value) && val != &decimal_value)
+  if (!example)
+    return FALSE;
+  value_cached= TRUE;
+  my_decimal *val= example->val_decimal_result(&decimal_value);
+  if (!(null_value= example->null_value) && val != &decimal_value)
     my_decimal2decimal(val, &decimal_value);
+  return TRUE;
 }
 
 double Item_cache_decimal::val_real()
 {
   DBUG_ASSERT(fixed);
   double res;
+  if (!value_cached && !cache_value())
+    return NULL;
   my_decimal2double(E_DEC_FATAL_ERROR, &decimal_value, &res);
   return res;
 }
@@ -7060,6 +7128,8 @@ longlong Item_cache_decimal::val_int()
 {
   DBUG_ASSERT(fixed);
   longlong res;
+  if (!value_cached && !cache_value())
+    return 0;
   my_decimal2int(E_DEC_FATAL_ERROR, &decimal_value, unsigned_flag, &res);
   return res;
 }
@@ -7067,6 +7137,8 @@ longlong Item_cache_decimal::val_int()
 String* Item_cache_decimal::val_str(String *str)
 {
   DBUG_ASSERT(fixed);
+  if (!value_cached && !cache_value())
+    return NULL;
   my_decimal_round(E_DEC_FATAL_ERROR, &decimal_value, decimals, FALSE,
                    &decimal_value);
   my_decimal2string(E_DEC_FATAL_ERROR, &decimal_value, 0, 0, 0, str);
@@ -7076,15 +7148,20 @@ String* Item_cache_decimal::val_str(Stri
 my_decimal *Item_cache_decimal::val_decimal(my_decimal *val)
 {
   DBUG_ASSERT(fixed);
+  if (!value_cached && !cache_value())
+    return NULL;
   return &decimal_value;
 }
 
 
-void Item_cache_str::store(Item *item)
+bool Item_cache_str::cache_value()
 {
-  value_buff.set(buffer, sizeof(buffer), item->collation.collation);
-  value= item->str_result(&value_buff);
-  if ((null_value= item->null_value))
+  if (!example)
+    return FALSE;
+  value_cached= TRUE;
+  value_buff.set(buffer, sizeof(buffer), example->collation.collation);
+  value= example->str_result(&value_buff);
+  if ((null_value= example->null_value))
     value= 0;
   else if (value != &value_buff)
   {
@@ -7099,6 +7176,7 @@ void Item_cache_str::store(Item *item)
     value_buff.copy(*value);
     value= &value_buff;
   }
+  return TRUE;
 }
 
 double Item_cache_str::val_real()
@@ -7106,6 +7184,8 @@ double Item_cache_str::val_real()
   DBUG_ASSERT(fixed == 1);
   int err_not_used;
   char *end_not_used;
+  if (!value_cached && !cache_value())
+    return 0.0;
   if (value)
     return my_strntod(value->charset(), (char*) value->ptr(),
 		      value->length(), &end_not_used, &err_not_used);
@@ -7117,6 +7197,8 @@ longlong Item_cache_str::val_int()
 {
   DBUG_ASSERT(fixed == 1);
   int err;
+  if (!value_cached && !cache_value())
+    return 0;
   if (value)
     return my_strntoll(value->charset(), value->ptr(),
 		       value->length(), 10, (char**) 0, &err);
@@ -7124,9 +7206,21 @@ longlong Item_cache_str::val_int()
     return (longlong)0;
 }
 
+
+String* Item_cache_str::val_str(String *str)
+{
+  DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return 0;
+  return value;
+}
+
+
 my_decimal *Item_cache_str::val_decimal(my_decimal *decimal_val)
 {
   DBUG_ASSERT(fixed == 1);
+  if (!value_cached && !cache_value())
+    return NULL;
   if (value)
     string2my_decimal(E_DEC_FATAL_ERROR, value, decimal_val);
   else
@@ -7137,6 +7231,8 @@ my_decimal *Item_cache_str::val_decimal(
 
 int Item_cache_str::save_in_field(Field *field, bool no_conversions)
 {
+  if (!value_cached && !cache_value())
+    return 0;
   int res= Item_cache::save_in_field(field, no_conversions);
   return (is_varbinary && field->type() == MYSQL_TYPE_STRING &&
           value->length() < field->field_length) ? 1 : res;
@@ -7171,13 +7267,30 @@ bool Item_cache_row::setup(Item * item)
 
 void Item_cache_row::store(Item * item)
 {
+  example= item;
+  if (!item)
+  {
+    null_value= TRUE;
+    return;
+  }
+  for (uint i= 0; i < item_count; i++)
+    values[i]->store(item->element_index(i));
+}
+
+
+bool Item_cache_row::cache_value()
+{
+  if (!example)
+    return FALSE;
+  value_cached= TRUE;
   null_value= 0;
-  item->bring_value();
+  example->bring_value();
   for (uint i= 0; i < item_count; i++)
   {
-    values[i]->store(item->element_index(i));
+    values[i]->cache_value();
     null_value|= values[i]->null_value;
   }
+  return TRUE;
 }
 
 

=== modified file 'sql/item.h'
--- a/sql/item.h	2009-12-03 11:19:05 +0000
+++ b/sql/item.h	2010-01-15 15:27:55 +0000
@@ -1053,7 +1053,11 @@ class sp_head;
 
 class Item_basic_constant :public Item
 {
+  table_map used_table_map;
 public:
+  Item_basic_constant(): Item(), used_table_map(0) {};
+  void set_used_tables(table_map map) { used_table_map= map; }
+  table_map used_tables() const { return used_table_map; }
   /* to prevent drop fixed flag (no need parent cleanup call) */
   void cleanup()
   {
@@ -1065,7 +1069,6 @@ public:
     if (orig_name)
       name= orig_name;
   }
-  Item_basic_constant() {}                      /* Remove gcc warning */
 };
 
 
@@ -2165,6 +2168,23 @@ public:
     save_in_field(result_field, no_conversions);
   }
   void cleanup();
+  /*
+    This method is used for debug purposes to print the name of an
+    item to the debug log. The second use of this method is as
+    a helper function of print() and error messages, where it is
+    applicable. To suit both goals it should return a meaningful,
+    distinguishable and sintactically correct string. This method
+    should not be used for runtime type identification, use enum
+    {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
+    instead.
+    Added here, to the parent class of both Item_func and Item_sum_func.
+
+    NOTE: for Items inherited from Item_sum, func_name() return part of
+    function name till first argument (including '(') to make difference in
+    names for functions with 'distinct' clause and without 'distinct' and
+    also to make printing of items inherited from Item_sum uniform.
+  */
+  virtual const char *func_name() const= 0;
 };
 
 
@@ -2924,15 +2944,25 @@ protected:
   */  
   Field *cached_field;
   enum enum_field_types cached_field_type;
-public:
-  Item_cache(): 
-    example(0), used_table_map(0), cached_field(0), cached_field_type(MYSQL_TYPE_STRING) 
+  /*
+    TRUE <=> cache holds value of the last stored item (i.e actual value).
+    store() stores item to be cached and sets this flag to FALSE.
+    On the first call of val_xxx function if this flag is set to FALSE the 
+    cache_value() will be called to actually cache value of saved item.
+    cache_value() will set this flag to TRUE.
+  */
+  bool value_cached;
+public:
+  Item_cache():
+    example(0), used_table_map(0), cached_field(0), cached_field_type(MYSQL_TYPE_STRING),
+    value_cached(0)
   {
     fixed= 1; 
     null_value= 1;
   }
   Item_cache(enum_field_types field_type_arg):
-    example(0), used_table_map(0), cached_field(0), cached_field_type(field_type_arg)
+    example(0), used_table_map(0), cached_field(0), cached_field_type(field_type_arg),
+    value_cached(0)
   {
     fixed= 1;
     null_value= 1;
@@ -2952,10 +2982,10 @@ public:
       cached_field= ((Item_field *)item)->field;
     return 0;
   };
-  virtual void store(Item *)= 0;
   enum Type type() const { return CACHE_ITEM; }
   enum_field_types field_type() const { return cached_field_type; }
   static Item_cache* get_cache(const Item *item);
+  static Item_cache* get_cache(const Item* item, const Item_result type);
   table_map used_tables() const { return used_table_map; }
   virtual void keep_array() {}
   virtual void print(String *str, enum_query_type query_type);
@@ -2967,6 +2997,8 @@ public:
   {
     return this == item;
   }
+  virtual void store(Item *item);
+  virtual bool cache_value()= 0;
 };
 
 
@@ -2975,18 +3007,19 @@ class Item_cache_int: public Item_cache
 protected:
   longlong value;
 public:
-  Item_cache_int(): Item_cache(), value(0) {}
+  Item_cache_int(): Item_cache(),
+    value(0) {}
   Item_cache_int(enum_field_types field_type_arg):
     Item_cache(field_type_arg), value(0) {}
 
-  void store(Item *item);
   void store(Item *item, longlong val_arg);
-  double val_real() { DBUG_ASSERT(fixed == 1); return (double) value; }
-  longlong val_int() { DBUG_ASSERT(fixed == 1); return value; }
+  double val_real();
+  longlong val_int();
   String* val_str(String *str);
   my_decimal *val_decimal(my_decimal *);
   enum Item_result result_type() const { return INT_RESULT; }
   bool result_as_longlong() { return TRUE; }
+  bool cache_value();
 };
 
 
@@ -2994,14 +3027,15 @@ class Item_cache_real: public Item_cache
 {
   double value;
 public:
-  Item_cache_real(): Item_cache(), value(0) {}
+  Item_cache_real(): Item_cache(),
+    value(0) {}
 
-  void store(Item *item);
-  double val_real() { DBUG_ASSERT(fixed == 1); return value; }
+  double val_real();
   longlong val_int();
   String* val_str(String *str);
   my_decimal *val_decimal(my_decimal *);
   enum Item_result result_type() const { return REAL_RESULT; }
+  bool cache_value();
 };
 
 
@@ -3012,12 +3046,12 @@ protected:
 public:
   Item_cache_decimal(): Item_cache() {}
 
-  void store(Item *item);
   double val_real();
   longlong val_int();
   String* val_str(String *str);
   my_decimal *val_decimal(my_decimal *);
   enum Item_result result_type() const { return DECIMAL_RESULT; }
+  bool cache_value();
 };
 
 
@@ -3035,14 +3069,14 @@ public:
                    MYSQL_TYPE_VARCHAR &&
                  !((const Item_field *) item)->field->has_charset())
   {}
-  void store(Item *item);
   double val_real();
   longlong val_int();
-  String* val_str(String *) { DBUG_ASSERT(fixed == 1); return value; }
+  String* val_str(String *);
   my_decimal *val_decimal(my_decimal *);
   enum Item_result result_type() const { return STRING_RESULT; }
   CHARSET_INFO *charset() const { return value->charset(); };
   int save_in_field(Field *field, bool no_conversions);
+  bool cache_value();
 };
 
 class Item_cache_row: public Item_cache
@@ -3052,7 +3086,8 @@ class Item_cache_row: public Item_cache
   bool save_array;
 public:
   Item_cache_row()
-    :Item_cache(), values(0), item_count(2), save_array(0) {}
+    :Item_cache(), values(0), item_count(2),
+    save_array(0) {}
   
   /*
     'allocate' used only in row transformer, to preallocate space for row 
@@ -3110,6 +3145,7 @@ public:
       values= 0;
     DBUG_VOID_RETURN;
   }
+  bool cache_value();
 };
 
 

=== modified file 'sql/item_cmpfunc.cc'
--- a/sql/item_cmpfunc.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item_cmpfunc.cc	2010-01-15 15:27:55 +0000
@@ -30,6 +30,9 @@
 #include "sql_select.h"
 
 static bool convert_constant_item(THD *, Item_field *, Item **);
+static longlong
+get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
+               Item *warn_item, bool *is_null);
 
 static Item_result item_store_type(Item_result a, Item *item,
                                    my_bool unsigned_flag)
@@ -533,11 +536,12 @@ void Item_bool_func2::fix_length_and_dec
 }
 
 
-int Arg_comparator::set_compare_func(Item_bool_func2 *item, Item_result type)
+int Arg_comparator::set_compare_func(Item_result_field *item, Item_result type)
 {
   owner= item;
   func= comparator_matrix[type]
-                         [test(owner->functype() == Item_func::EQUAL_FUNC)];
+                         [is_owner_equal_func()];
+
   switch (type) {
   case ROW_RESULT:
   {
@@ -557,7 +561,8 @@ int Arg_comparator::set_compare_func(Ite
 	my_error(ER_OPERAND_COLUMNS, MYF(0), (*a)->element_index(i)->cols());
 	return 1;
       }
-      if (comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i)))
+      if (comparators[i].set_cmp_func(owner, (*a)->addr(i), (*b)->addr(i),
+                                      set_null))
         return 1;
     }
     break;
@@ -571,7 +576,8 @@ int Arg_comparator::set_compare_func(Ite
     if (cmp_collation.set((*a)->collation, (*b)->collation) || 
 	cmp_collation.derivation == DERIVATION_NONE)
     {
-      my_coll_agg_error((*a)->collation, (*b)->collation, owner->func_name());
+      my_coll_agg_error((*a)->collation, (*b)->collation,
+                        owner->func_name());
       return 1;
     }
     if (cmp_collation.collation == &my_charset_bin)
@@ -785,15 +791,21 @@ Arg_comparator::can_compare_as_dates(Ite
 
   if (cmp_type != CMP_DATE_DFLT)
   {
+    THD *thd= current_thd;
     /*
       Do not cache GET_USER_VAR() function as its const_item() may return TRUE
       for the current thread but it still may change during the execution.
+      Don't use cache while in the context analysis mode only (i.e. for 
+      EXPLAIN/CREATE VIEW and similar queries). Cache is useless in such 
+      cases and can cause problems. For example evaluating subqueries can 
+      confuse storage engines since in context analysis mode tables 
+      aren't locked.
     */
-    if (cmp_type != CMP_DATE_WITH_DATE && str_arg->const_item() &&
+    if (!thd->is_context_analysis_only() &&
+        cmp_type != CMP_DATE_WITH_DATE && str_arg->const_item() &&
         (str_arg->type() != Item::FUNC_ITEM ||
         ((Item_func*)str_arg)->functype() != Item_func::GUSERVAR_FUNC))
     {
-      THD *thd= current_thd;
       ulonglong value;
       bool error;
       String tmp, *str_val= 0;
@@ -875,18 +887,20 @@ get_time_value(THD *thd, Item ***item_ar
 }
 
 
-int Arg_comparator::set_cmp_func(Item_bool_func2 *owner_arg,
+int Arg_comparator::set_cmp_func(Item_result_field *owner_arg,
                                         Item **a1, Item **a2,
                                         Item_result type)
 {
   ulonglong const_value= (ulonglong)-1;
+  thd= current_thd;
+  owner= owner_arg;
+  set_null= set_null && owner_arg;
   a= a1;
   b= a2;
+  thd= current_thd;
 
   if (can_compare_as_dates(*a, *b, &const_value))
   {
-    thd= current_thd;
-    owner= owner_arg;
     a_type= (*a)->field_type();
     b_type= (*b)->field_type();
     a_cache= 0;
@@ -894,6 +908,10 @@ int Arg_comparator::set_cmp_func(Item_bo
 
     if (const_value != (ulonglong)-1)
     {
+      /*
+        cache_converted_constant can't be used here because it can't
+        correctly convert a DATETIME value from string to int representation.
+      */
       Item_cache_int *cache= new Item_cache_int();
       /* Mark the cache as non-const to prevent re-caching. */
       cache->set_used_tables(1);
@@ -910,22 +928,22 @@ int Arg_comparator::set_cmp_func(Item_bo
         b= (Item **)&b_cache;
       }
     }
-    is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC);
+    is_nulls_eq= is_owner_equal_func();
     func= &Arg_comparator::compare_datetime;
-    get_value_func= &get_datetime_value;
+    get_value_a_func= &get_datetime_value;
+    get_value_b_func= &get_datetime_value;
     return 0;
   }
   else if (type == STRING_RESULT && (*a)->field_type() == MYSQL_TYPE_TIME &&
            (*b)->field_type() == MYSQL_TYPE_TIME)
   {
     /* Compare TIME values as integers. */
-    thd= current_thd;
-    owner= owner_arg;
     a_cache= 0;
     b_cache= 0;
-    is_nulls_eq= test(owner && owner->functype() == Item_func::EQUAL_FUNC);
+    is_nulls_eq= is_owner_equal_func();
     func= &Arg_comparator::compare_datetime;
-    get_value_func= &get_time_value;
+    get_value_a_func= &get_time_value;
+    get_value_b_func= &get_time_value;
     return 0;
   }
   else if (type == STRING_RESULT &&
@@ -934,20 +952,97 @@ int Arg_comparator::set_cmp_func(Item_bo
   {
     DTCollation coll;
     coll.set((*a)->collation.collation);
-    if (agg_item_set_converter(coll, owner_arg->func_name(),
+    if (agg_item_set_converter(coll, owner->func_name(),
                                b, 1, MY_COLL_CMP_CONV, 1))
       return 1;
   }
+  else if (try_year_cmp_func(type))
+    return 0;
 
+  a= cache_converted_constant(thd, a, &a_cache, type);
+  b= cache_converted_constant(thd, b, &b_cache, type);
   return set_compare_func(owner_arg, type);
 }
 
 
-void Arg_comparator::set_datetime_cmp_func(Item **a1, Item **b1)
+/*
+  Helper function to call from Arg_comparator::set_cmp_func()
+*/
+
+bool Arg_comparator::try_year_cmp_func(Item_result type)
+{
+  if (type == ROW_RESULT)
+    return FALSE;
+
+  bool a_is_year= (*a)->field_type() == MYSQL_TYPE_YEAR;
+  bool b_is_year= (*b)->field_type() == MYSQL_TYPE_YEAR;
+
+  if (!a_is_year && !b_is_year)
+    return FALSE;
+
+  if (a_is_year && b_is_year)
+  {
+    get_value_a_func= &get_year_value;
+    get_value_b_func= &get_year_value;
+  }
+  else if (a_is_year && (*b)->is_datetime())
+  {
+    get_value_a_func= &get_year_value;
+    get_value_b_func= &get_datetime_value;
+  }
+  else if (b_is_year && (*a)->is_datetime())
+  {
+    get_value_b_func= &get_year_value;
+    get_value_a_func= &get_datetime_value;
+  }
+  else
+    return FALSE;
+
+  is_nulls_eq= is_owner_equal_func();
+  func= &Arg_comparator::compare_datetime;
+
+  return TRUE;
+}
+
+/**
+  Convert and cache a constant.
+
+  @param value      [in]  An item to cache
+  @param cache_item [out] Placeholder for the cache item
+  @param type       [in]  Comparison type
+
+  @details
+    When given item is a constant and its type differs from comparison type
+    then cache its value to avoid type conversion of this constant on each
+    evaluation. In this case the value is cached and the reference to the cache
+    is returned.
+    Original value is returned otherwise.
+
+  @return cache item or original value.
+*/
+
+Item** Arg_comparator::cache_converted_constant(THD *thd, Item **value,
+                                                Item **cache_item,
+                                                Item_result type)
+{
+  /* Don't need cache if doing context analysis only. */
+  if (!thd->is_context_analysis_only() &&
+      (*value)->const_item() && type != (*value)->result_type())
+  {
+    Item_cache *cache= Item_cache::get_cache(*value, type);
+    cache->setup(*value);
+    *cache_item= cache;
+    return cache_item;
+  }
+  return value;
+}
+
+
+void Arg_comparator::set_datetime_cmp_func(Item_result_field *owner_arg,
+                                           Item **a1, Item **b1)
 {
   thd= current_thd;
-  /* A caller will handle null values by itself. */
-  owner= NULL;
+  owner= owner_arg;
   a= a1;
   b= b1;
   a_type= (*a)->field_type();
@@ -956,7 +1051,8 @@ void Arg_comparator::set_datetime_cmp_fu
   b_cache= 0;
   is_nulls_eq= FALSE;
   func= &Arg_comparator::compare_datetime;
-  get_value_func= &get_datetime_value;
+  get_value_a_func= &get_datetime_value;
+  get_value_b_func= &get_datetime_value;
 }
 
 
@@ -1056,6 +1152,56 @@ get_datetime_value(THD *thd, Item ***ite
   return value;
 }
 
+
+/*
+  Retrieves YEAR value of 19XX-00-00 00:00:00 form from given item.
+
+  SYNOPSIS
+    get_year_value()
+    thd                 thread handle
+    item_arg   [in/out] item to retrieve YEAR value from
+    cache_arg  [in/out] pointer to place to store the caching item to
+    warn_item  [in]     item for issuing the conversion warning
+    is_null    [out]    TRUE <=> the item_arg is null
+
+  DESCRIPTION
+    Retrieves the YEAR value of 19XX form from given item for comparison by the
+    compare_datetime() function.
+    Converts year to DATETIME of form YYYY-00-00 00:00:00 for the compatibility
+    with the get_datetime_value function result.
+
+  RETURN
+    obtained value
+*/
+
+static longlong
+get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
+               Item *warn_item, bool *is_null)
+{
+  longlong value= 0;
+  Item *item= **item_arg;
+
+  value= item->val_int();
+  *is_null= item->null_value;
+  if (*is_null)
+    return ~(ulonglong) 0;
+
+  /*
+    Coerce value to the 19XX form in order to correctly compare
+    YEAR(2) & YEAR(4) types.
+  */
+  if (value < 70)
+    value+= 100;
+  if (value <= 1900)
+    value+= 1900;
+
+  /* Convert year to DATETIME of form YYYY-00-00 00:00:00 (YYYY0000000000). */
+  value*= 10000000000LL;
+
+  return value;
+}
+
+
 /*
   Compare items values as dates.
 
@@ -1088,25 +1234,25 @@ int Arg_comparator::compare_datetime()
   longlong a_value, b_value;
 
   /* Get DATE/DATETIME/TIME value of the 'a' item. */
-  a_value= (*get_value_func)(thd, &a, &a_cache, *b, &a_is_null);
+  a_value= (*get_value_a_func)(thd, &a, &a_cache, *b, &a_is_null);
   if (!is_nulls_eq && a_is_null)
   {
-    if (owner)
+    if (set_null)
       owner->null_value= 1;
     return -1;
   }
 
   /* Get DATE/DATETIME/TIME value of the 'b' item. */
-  b_value= (*get_value_func)(thd, &b, &b_cache, *a, &b_is_null);
+  b_value= (*get_value_b_func)(thd, &b, &b_cache, *a, &b_is_null);
   if (a_is_null || b_is_null)
   {
-    if (owner)
+    if (set_null)
       owner->null_value= is_nulls_eq ? 0 : 1;
     return is_nulls_eq ? (a_is_null == b_is_null) : -1;
   }
 
   /* Here we have two not-NULL values. */
-  if (owner)
+  if (set_null)
     owner->null_value= 0;
 
   /* Compare values. */
@@ -1119,15 +1265,17 @@ int Arg_comparator::compare_datetime()
 int Arg_comparator::compare_string()
 {
   String *res1,*res2;
-  if ((res1= (*a)->val_str(&owner->tmp_value1)))
+  if ((res1= (*a)->val_str(&value1)))
   {
-    if ((res2= (*b)->val_str(&owner->tmp_value2)))
+    if ((res2= (*b)->val_str(&value2)))
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       return sortcmp(res1,res2,cmp_collation.collation);
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1146,18 +1294,20 @@ int Arg_comparator::compare_string()
 int Arg_comparator::compare_binary_string()
 {
   String *res1,*res2;
-  if ((res1= (*a)->val_str(&owner->tmp_value1)))
+  if ((res1= (*a)->val_str(&value1)))
   {
-    if ((res2= (*b)->val_str(&owner->tmp_value2)))
+    if ((res2= (*b)->val_str(&value2)))
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       uint res1_length= res1->length();
       uint res2_length= res2->length();
       int cmp= memcmp(res1->ptr(), res2->ptr(), min(res1_length,res2_length));
       return cmp ? cmp : (int) (res1_length - res2_length);
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1170,8 +1320,8 @@ int Arg_comparator::compare_binary_strin
 int Arg_comparator::compare_e_string()
 {
   String *res1,*res2;
-  res1= (*a)->val_str(&owner->tmp_value1);
-  res2= (*b)->val_str(&owner->tmp_value2);
+  res1= (*a)->val_str(&value1);
+  res2= (*b)->val_str(&value2);
   if (!res1 || !res2)
     return test(res1 == res2);
   return test(sortcmp(res1, res2, cmp_collation.collation) == 0);
@@ -1181,8 +1331,8 @@ int Arg_comparator::compare_e_string()
 int Arg_comparator::compare_e_binary_string()
 {
   String *res1,*res2;
-  res1= (*a)->val_str(&owner->tmp_value1);
-  res2= (*b)->val_str(&owner->tmp_value2);
+  res1= (*a)->val_str(&value1);
+  res2= (*b)->val_str(&value2);
   if (!res1 || !res2)
     return test(res1 == res2);
   return test(stringcmp(res1, res2) == 0);
@@ -1203,13 +1353,15 @@ int Arg_comparator::compare_real()
     val2= (*b)->val_real();
     if (!(*b)->null_value)
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       if (val1 < val2)	return -1;
       if (val1 == val2) return 0;
       return 1;
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1223,11 +1375,13 @@ int Arg_comparator::compare_decimal()
     my_decimal *val2= (*b)->val_decimal(&value2);
     if (!(*b)->null_value)
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       return my_decimal_cmp(val1, val2);
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1265,7 +1419,8 @@ int Arg_comparator::compare_real_fixed()
     val2= (*b)->val_real();
     if (!(*b)->null_value)
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       if (val1 == val2 || fabs(val1 - val2) < precision)
         return 0;
       if (val1 < val2)
@@ -1273,7 +1428,8 @@ int Arg_comparator::compare_real_fixed()
       return 1;
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1296,13 +1452,15 @@ int Arg_comparator::compare_int_signed()
     longlong val2= (*b)->val_int();
     if (!(*b)->null_value)
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       if (val1 < val2)	return -1;
       if (val1 == val2)   return 0;
       return 1;
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1319,13 +1477,15 @@ int Arg_comparator::compare_int_unsigned
     ulonglong val2= (*b)->val_int();
     if (!(*b)->null_value)
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       if (val1 < val2)	return -1;
       if (val1 == val2)   return 0;
       return 1;
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1342,7 +1502,8 @@ int Arg_comparator::compare_int_signed_u
     ulonglong uval2= (ulonglong)(*b)->val_int();
     if (!(*b)->null_value)
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       if (sval1 < 0 || (ulonglong)sval1 < uval2)
         return -1;
       if ((ulonglong)sval1 == uval2)
@@ -1350,7 +1511,8 @@ int Arg_comparator::compare_int_signed_u
       return 1;
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1367,7 +1529,8 @@ int Arg_comparator::compare_int_unsigned
     longlong sval2= (*b)->val_int();
     if (!(*b)->null_value)
     {
-      owner->null_value= 0;
+      if (set_null)
+        owner->null_value= 0;
       if (sval2 < 0)
         return 1;
       if (uval1 < (ulonglong)sval2)
@@ -1377,7 +1540,8 @@ int Arg_comparator::compare_int_unsigned
       return 1;
     }
   }
-  owner->null_value= 1;
+  if (set_null)
+    owner->null_value= 1;
   return -1;
 }
 
@@ -1413,10 +1577,11 @@ int Arg_comparator::compare_row()
   for (uint i= 0; i<n; i++)
   {
     res= comparators[i].compare();
-    if (owner->null_value)
+    /* Aggregate functions don't need special null handling. */
+    if (owner->null_value && owner->type() == Item::FUNC_ITEM)
     {
       // NULL was compared
-      switch (owner->functype()) {
+      switch (((Item_func*)owner)->functype()) {
       case Item_func::NE_FUNC:
         break; // NE never aborts on NULL even if abort_on_null is set
       case Item_func::LT_FUNC:
@@ -1425,7 +1590,7 @@ int Arg_comparator::compare_row()
       case Item_func::GE_FUNC:
         return -1; // <, <=, > and >= always fail on NULL
       default: // EQ_FUNC
-        if (owner->abort_on_null)
+        if (((Item_bool_func2*)owner)->abort_on_null)
           return -1; // We do not need correct NULL returning
       }
       was_null= 1;
@@ -1581,6 +1746,7 @@ longlong Item_in_optimizer::val_int()
   bool tmp;
   DBUG_ASSERT(fixed == 1);
   cache->store(args[0]);
+  cache->cache_value();
   
   if (cache->null_value)
   {
@@ -1748,8 +1914,8 @@ longlong Item_func_lt::val_int()
 longlong Item_func_strcmp::val_int()
 {
   DBUG_ASSERT(fixed == 1);
-  String *a=args[0]->val_str(&tmp_value1);
-  String *b=args[1]->val_str(&tmp_value2);
+  String *a=args[0]->val_str(&cmp.value1);
+  String *b=args[1]->val_str(&cmp.value2);
   if (!a || !b)
   {
     null_value=1;
@@ -2032,8 +2198,8 @@ void Item_func_between::fix_length_and_d
 
   if (compare_as_dates)
   {
-    ge_cmp.set_datetime_cmp_func(args, args + 1);
-    le_cmp.set_datetime_cmp_func(args, args + 2);
+    ge_cmp.set_datetime_cmp_func(this, args, args + 1);
+    le_cmp.set_datetime_cmp_func(this, args, args + 2);
   }
   else if (time_items_found == 3)
   {
@@ -4370,13 +4536,13 @@ void Item_func_isnotnull::print(String *
 longlong Item_func_like::val_int()
 {
   DBUG_ASSERT(fixed == 1);
-  String* res = args[0]->val_str(&tmp_value1);
+  String* res = args[0]->val_str(&cmp.value1);
   if (args[0]->null_value)
   {
     null_value=1;
     return 0;
   }
-  String* res2 = args[1]->val_str(&tmp_value2);
+  String* res2 = args[1]->val_str(&cmp.value2);
   if (args[1]->null_value)
   {
     null_value=1;
@@ -4400,7 +4566,7 @@ Item_func::optimize_type Item_func_like:
 {
   if (args[1]->const_item())
   {
-    String* res2= args[1]->val_str((String *)&tmp_value2);
+    String* res2= args[1]->val_str((String *)&cmp.value2);
 
     if (!res2)
       return OPTIMIZE_NONE;
@@ -4431,7 +4597,7 @@ bool Item_func_like::fix_fields(THD *thd
   if (escape_item->const_item())
   {
     /* If we are on execution stage */
-    String *escape_str= escape_item->val_str(&tmp_value1);
+    String *escape_str= escape_item->val_str(&cmp.value1);
     if (escape_str)
     {
       if (escape_used_in_parsing && (
@@ -4486,7 +4652,7 @@ bool Item_func_like::fix_fields(THD *thd
     if (args[1]->const_item() && !use_strnxfrm(collation.collation) &&
        !(specialflag & SPECIAL_NO_NEW_FUNC))
     {
-      String* res2 = args[1]->val_str(&tmp_value2);
+      String* res2 = args[1]->val_str(&cmp.value2);
       if (!res2)
         return FALSE;				// Null argument
       

=== modified file 'sql/item_cmpfunc.h'
--- a/sql/item_cmpfunc.h	2009-12-03 11:19:05 +0000
+++ b/sql/item_cmpfunc.h	2010-01-15 15:27:55 +0000
@@ -32,7 +32,7 @@ class Arg_comparator: public Sql_alloc
 {
   Item **a, **b;
   arg_cmp_func func;
-  Item_bool_func2 *owner;
+  Item_result_field *owner;
   Arg_comparator *comparators;   // used only for compare_row()
   double precision;
   /* Fields used in DATE/DATETIME comparison. */
@@ -40,30 +40,40 @@ class Arg_comparator: public Sql_alloc
   enum_field_types a_type, b_type; // Types of a and b items
   Item *a_cache, *b_cache;         // Cached values of a and b items
   bool is_nulls_eq;                // TRUE <=> compare for the EQUAL_FUNC
+  bool set_null;                   // TRUE <=> set owner->null_value
+                                   //   when one of arguments is NULL.
   enum enum_date_cmp_type { CMP_DATE_DFLT= 0, CMP_DATE_WITH_DATE,
                             CMP_DATE_WITH_STR, CMP_STR_WITH_DATE };
-  longlong (*get_value_func)(THD *thd, Item ***item_arg, Item **cache_arg,
-                             Item *warn_item, bool *is_null);
+  longlong (*get_value_a_func)(THD *thd, Item ***item_arg, Item **cache_arg,
+                               Item *warn_item, bool *is_null);
+  longlong (*get_value_b_func)(THD *thd, Item ***item_arg, Item **cache_arg,
+                               Item *warn_item, bool *is_null);
+  bool try_year_cmp_func(Item_result type);
 public:
   DTCollation cmp_collation;
+  /* Allow owner function to use string buffers. */
+  String value1, value2;
 
-  Arg_comparator(): thd(0), a_cache(0), b_cache(0) {};
+  Arg_comparator(): thd(0), a_cache(0), b_cache(0), set_null(TRUE),
+    get_value_a_func(0), get_value_b_func(0) {};
   Arg_comparator(Item **a1, Item **a2): a(a1), b(a2), thd(0),
-    a_cache(0), b_cache(0) {};
+    a_cache(0), b_cache(0), set_null(TRUE),
+    get_value_a_func(0), get_value_b_func(0) {};
 
-  int set_compare_func(Item_bool_func2 *owner, Item_result type);
-  inline int set_compare_func(Item_bool_func2 *owner_arg)
+  int set_compare_func(Item_result_field *owner, Item_result type);
+  inline int set_compare_func(Item_result_field *owner_arg)
   {
     return set_compare_func(owner_arg, item_cmp_type((*a)->result_type(),
                                                      (*b)->result_type()));
   }
-  int set_cmp_func(Item_bool_func2 *owner_arg,
+  int set_cmp_func(Item_result_field *owner_arg,
 			  Item **a1, Item **a2,
 			  Item_result type);
 
-  inline int set_cmp_func(Item_bool_func2 *owner_arg,
-			  Item **a1, Item **a2)
+  inline int set_cmp_func(Item_result_field *owner_arg,
+			  Item **a1, Item **a2, bool set_null_arg)
   {
+    set_null= set_null_arg;
     return set_cmp_func(owner_arg, a1, a2,
                         item_cmp_type((*a1)->result_type(),
                                       (*a2)->result_type()));
@@ -93,8 +103,15 @@ public:
   static enum enum_date_cmp_type can_compare_as_dates(Item *a, Item *b,
                                                       ulonglong *const_val_arg);
 
-  void set_datetime_cmp_func(Item **a1, Item **b1);
+  Item** cache_converted_constant(THD *thd, Item **value, Item **cache,
+                                  Item_result type);
+  void set_datetime_cmp_func(Item_result_field *owner_arg, Item **a1, Item **b1);
   static arg_cmp_func comparator_matrix [5][2];
+  inline bool is_owner_equal_func()
+  {
+    return (owner->type() == Item::FUNC_ITEM &&
+           ((Item_func*)owner)->functype() == Item_func::EQUAL_FUNC);
+  }
 
   friend class Item_func;
 };
@@ -324,7 +341,6 @@ class Item_bool_func2 :public Item_int_f
 {						/* Bool with 2 string args */
 protected:
   Arg_comparator cmp;
-  String tmp_value1,tmp_value2;
   bool abort_on_null;
 
 public:
@@ -333,7 +349,7 @@ public:
   void fix_length_and_dec();
   void set_cmp_func()
   {
-    cmp.set_cmp_func(this, tmp_arg, tmp_arg+1);
+    cmp.set_cmp_func(this, tmp_arg, tmp_arg+1, TRUE);
   }
   optimize_type select_optimize() const { return OPTIMIZE_OP; }
   virtual enum Functype rev_functype() const { return UNKNOWN_FUNC; }

=== modified file 'sql/item_create.cc'
--- a/sql/item_create.cc	2009-10-15 21:38:29 +0000
+++ b/sql/item_create.cc	2010-01-15 15:27:55 +0000
@@ -3524,6 +3524,7 @@ Create_func_get_lock Create_func_get_loc
 Item*
 Create_func_get_lock::create(THD *thd, Item *arg1, Item *arg2)
 {
+  thd->lex->set_stmt_unsafe();
   thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
   return new (thd->mem_root) Item_func_get_lock(arg1, arg2);
 }
@@ -3635,6 +3636,7 @@ Create_func_is_free_lock Create_func_is_
 Item*
 Create_func_is_free_lock::create(THD *thd, Item *arg1)
 {
+  thd->lex->set_stmt_unsafe();
   thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
   return new (thd->mem_root) Item_func_is_free_lock(arg1);
 }
@@ -3645,6 +3647,7 @@ Create_func_is_used_lock Create_func_is_
 Item*
 Create_func_is_used_lock::create(THD *thd, Item *arg1)
 {
+  thd->lex->set_stmt_unsafe();
   thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
   return new (thd->mem_root) Item_func_is_used_lock(arg1);
 }
@@ -3961,6 +3964,8 @@ Create_func_master_pos_wait::create_nati
   Item *func= NULL;
   int arg_count= 0;
 
+  thd->lex->set_stmt_unsafe();
+
   if (item_list != NULL)
     arg_count= item_list->elements;
 
@@ -4203,6 +4208,7 @@ Create_func_release_lock Create_func_rel
 Item*
 Create_func_release_lock::create(THD *thd, Item *arg1)
 {
+  thd->lex->set_stmt_unsafe();
   thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
   return new (thd->mem_root) Item_func_release_lock(arg1);
 }
@@ -4325,6 +4331,7 @@ Create_func_sleep Create_func_sleep::s_s
 Item*
 Create_func_sleep::create(THD *thd, Item *arg1)
 {
+  thd->lex->set_stmt_unsafe();
   thd->lex->uncacheable(UNCACHEABLE_SIDEEFFECT);
   return new (thd->mem_root) Item_func_sleep(arg1);
 }
@@ -4591,6 +4598,7 @@ Create_func_version Create_func_version:
 Item*
 Create_func_version::create(THD *thd)
 {
+  thd->lex->set_stmt_unsafe();
   return new (thd->mem_root) Item_static_string_func("version()",
                                                      server_version,
                                                      (uint) strlen(server_version),

=== modified file 'sql/item_func.cc'
--- a/sql/item_func.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item_func.cc	2010-01-15 15:27:55 +0000
@@ -450,45 +450,8 @@ Field *Item_func::tmp_table_field(TABLE
   case STRING_RESULT:
     return make_string_field(table);
   case DECIMAL_RESULT:
-  {
-    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);
+    field= Field_new_decimal::create_from_item(this);
     break;
-  }
   case ROW_RESULT:
   default:
     // This case should never be chosen

=== modified file 'sql/item_func.h'
--- a/sql/item_func.h	2009-12-03 11:19:05 +0000
+++ b/sql/item_func.h	2010-01-15 15:27:55 +0000
@@ -124,17 +124,6 @@ public:
   virtual optimize_type select_optimize() const { return OPTIMIZE_NONE; }
   virtual bool have_rev_func() const { return 0; }
   virtual Item *key_item() const { return args[0]; }
-  /*
-    This method is used for debug purposes to print the name of an
-    item to the debug log. The second use of this method is as
-    a helper function of print(), where it is applicable.
-    To suit both goals it should return a meaningful,
-    distinguishable and sintactically correct string.  This method
-    should not be used for runtime type identification, use enum
-    {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
-    instead.
-  */
-  virtual const char *func_name() const= 0;
   virtual bool const_item() const { return const_item_cache; }
   inline Item **arguments() const { return args; }
   void set_arguments(List<Item> &list);

=== modified file 'sql/item_geofunc.cc'
--- a/sql/item_geofunc.cc	2009-10-24 06:57:31 +0000
+++ b/sql/item_geofunc.cc	2009-12-08 09:26:11 +0000
@@ -511,8 +511,8 @@ err:
 longlong Item_func_spatial_rel::val_int()
 {
   DBUG_ASSERT(fixed == 1);
-  String *res1= args[0]->val_str(&tmp_value1);
-  String *res2= args[1]->val_str(&tmp_value2);
+  String *res1= args[0]->val_str(&cmp.value1);
+  String *res2= args[1]->val_str(&cmp.value2);
   Geometry_buffer buffer1, buffer2;
   Geometry *g1, *g2;
   MBR mbr1, mbr2;

=== modified file 'sql/item_strfunc.cc'
--- a/sql/item_strfunc.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item_strfunc.cc	2010-01-15 15:27:55 +0000
@@ -1828,8 +1828,9 @@ String *Item_func_database::val_str(Stri
 
 
 /**
-  @todo
-  make USER() replicate properly (currently it is replicated to "")
+  @note USER() is replicated correctly if binlog_format=ROW or (as of
+  BUG#28086) binlog_format=MIXED, but is incorrectly replicated to ''
+  if binlog_format=STATEMENT.
 */
 bool Item_func_user::init(const char *user, const char *host)
 {

=== modified file 'sql/item_subselect.cc'
--- a/sql/item_subselect.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item_subselect.cc	2010-01-15 15:27:55 +0000
@@ -503,6 +503,7 @@ Item_singlerow_subselect::select_transfo
 void Item_singlerow_subselect::store(uint i, Item *item)
 {
   row[i]->store(item);
+  row[i]->cache_value();
 }
 
 enum Item_result Item_singlerow_subselect::result_type() const
@@ -1854,6 +1855,7 @@ void subselect_engine::set_row(List<Item
     if (!(row[i]= Item_cache::get_cache(sel_item)))
       return;
     row[i]->setup(sel_item);
+    row[i]->store(sel_item);
   }
   if (item_list.elements > 1)
     res_type= ROW_RESULT;

=== modified file 'sql/item_subselect.h'
--- a/sql/item_subselect.h	2009-08-31 20:02:09 +0000
+++ b/sql/item_subselect.h	2010-01-15 15:27:55 +0000
@@ -142,6 +142,7 @@ public:
     @return the SELECT_LEX structure associated with this Item
   */
   st_select_lex* get_select_lex();
+  const char *func_name() const { DBUG_ASSERT(0); return "subselect"; }
 
   friend class select_subselect;
   friend class Item_in_optimizer;

=== modified file 'sql/item_sum.cc'
--- a/sql/item_sum.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item_sum.cc	2010-01-15 15:27:55 +0000
@@ -517,8 +517,7 @@ Field *Item_sum::create_tmp_field(bool g
                                name, table->s, collation.collation);
     break;
   case DECIMAL_RESULT:
-    field= new Field_new_decimal(max_length, maybe_null, name,
-                                 decimals, unsigned_flag);
+    field= Field_new_decimal::create_from_item(this);
     break;
   case ROW_RESULT:
   default:
@@ -610,35 +609,6 @@ Item_sum_num::fix_fields(THD *thd, Item
 }
 
 
-Item_sum_hybrid::Item_sum_hybrid(THD *thd, Item_sum_hybrid *item)
-  :Item_sum(thd, item), value(item->value), hybrid_type(item->hybrid_type),
-  hybrid_field_type(item->hybrid_field_type), cmp_sign(item->cmp_sign),
-  was_values(item->was_values)
-{
-  /* copy results from old value */
-  switch (hybrid_type) {
-  case INT_RESULT:
-    sum_int= item->sum_int;
-    break;
-  case DECIMAL_RESULT:
-    my_decimal2decimal(&item->sum_dec, &sum_dec);
-    break;
-  case REAL_RESULT:
-    sum= item->sum;
-    break;
-  case STRING_RESULT:
-    /*
-      This can happen with ROLLUP. Note that the value is already
-      copied at function call.
-    */
-    break;
-  case ROW_RESULT:
-  default:
-    DBUG_ASSERT(0);
-  }
-  collation.set(item->collation);
-}
-
 bool
 Item_sum_hybrid::fix_fields(THD *thd, Item **ref)
 {
@@ -658,15 +628,12 @@ Item_sum_hybrid::fix_fields(THD *thd, It
   switch (hybrid_type= item->result_type()) {
   case INT_RESULT:
     max_length= 20;
-    sum_int= 0;
     break;
   case DECIMAL_RESULT:
     max_length= item->max_length;
-    my_decimal_set_zero(&sum_dec);
     break;
   case REAL_RESULT:
     max_length= float_length(decimals);
-    sum= 0.0;
     break;
   case STRING_RESULT:
     max_length= item->max_length;
@@ -675,10 +642,10 @@ Item_sum_hybrid::fix_fields(THD *thd, It
   default:
     DBUG_ASSERT(0);
   };
+  setup(args[0], NULL);
   /* MIN/MAX can return NULL for empty set indepedent of the used column */
   maybe_null= 1;
   unsigned_flag=item->unsigned_flag;
-  collation.set(item->collation);
   result_field=0;
   null_value=1;
   fix_length_and_dec();
@@ -696,6 +663,30 @@ Item_sum_hybrid::fix_fields(THD *thd, It
   return FALSE;
 }
 
+
+/**
+  MIN/MAX function setup.
+
+  @param item       argument of MIN/MAX function
+  @param value_arg  calculated value of MIN/MAX function
+
+  @details
+    Setup cache/comparator of MIN/MAX functions. When called by the
+    copy_or_same function value_arg parameter contains calculated value
+    of the original MIN/MAX object and it is saved in this object's cache.
+*/
+
+void Item_sum_hybrid::setup(Item *item, Item *value_arg)
+{
+  value= Item_cache::get_cache(item);
+  value->setup(item);
+  value->store(value_arg);
+  cmp= new Arg_comparator();
+  cmp->set_cmp_func(this, args, (Item**)&value, FALSE);
+  collation.set(item->collation);
+}
+
+
 Field *Item_sum_hybrid::create_tmp_field(bool group, TABLE *table,
 					 uint convert_blob_length)
 {
@@ -1265,8 +1256,7 @@ Field *Item_sum_avg::create_tmp_field(bo
                             0, name, &my_charset_bin);
   }
   else if (hybrid_type == DECIMAL_RESULT)
-    field= new Field_new_decimal(max_length, maybe_null, name,
-                                 decimals, unsigned_flag);
+    field= Field_new_decimal::create_from_item(this);
   else
     field= new Field_double(max_length, maybe_null, name, decimals, TRUE);
   if (field)
@@ -1587,19 +1577,7 @@ void Item_sum_variance::update_field()
 
 void Item_sum_hybrid::clear()
 {
-  switch (hybrid_type) {
-  case INT_RESULT:
-    sum_int= 0;
-    break;
-  case DECIMAL_RESULT:
-    my_decimal_set_zero(&sum_dec);
-    break;
-  case REAL_RESULT:
-    sum= 0.0;
-    break;
-  default:
-    value.length(0);
-  }
+  value->null_value= 1;
   null_value= 1;
 }
 
@@ -1608,30 +1586,7 @@ double Item_sum_hybrid::val_real()
   DBUG_ASSERT(fixed == 1);
   if (null_value)
     return 0.0;
-  switch (hybrid_type) {
-  case STRING_RESULT:
-  {
-    char *end_not_used;
-    int err_not_used;
-    String *res;  res=val_str(&str_value);
-    return (res ? my_strntod(res->charset(), (char*) res->ptr(), res->length(),
-			     &end_not_used, &err_not_used) : 0.0);
-  }
-  case INT_RESULT:
-    if (unsigned_flag)
-      return ulonglong2double(sum_int);
-    return (double) sum_int;
-  case DECIMAL_RESULT:
-    my_decimal2double(E_DEC_FATAL_ERROR, &sum_dec, &sum);
-    return sum;
-  case REAL_RESULT:
-    return sum;
-  case ROW_RESULT:
-  default:
-    // This case should never be choosen
-    DBUG_ASSERT(0);
-    return 0;
-  }
+  return value->val_real();
 }
 
 longlong Item_sum_hybrid::val_int()
@@ -1639,18 +1594,7 @@ longlong Item_sum_hybrid::val_int()
   DBUG_ASSERT(fixed == 1);
   if (null_value)
     return 0;
-  switch (hybrid_type) {
-  case INT_RESULT:
-    return sum_int;
-  case DECIMAL_RESULT:
-  {
-    longlong result;
-    my_decimal2int(E_DEC_FATAL_ERROR, &sum_dec, unsigned_flag, &result);
-    return sum_int;
-  }
-  default:
-    return (longlong) rint(Item_sum_hybrid::val_real());
-  }
+  return value->val_int();
 }
 
 
@@ -1659,26 +1603,7 @@ my_decimal *Item_sum_hybrid::val_decimal
   DBUG_ASSERT(fixed == 1);
   if (null_value)
     return 0;
-  switch (hybrid_type) {
-  case STRING_RESULT:
-    string2my_decimal(E_DEC_FATAL_ERROR, &value, val);
-    break;
-  case REAL_RESULT:
-    double2my_decimal(E_DEC_FATAL_ERROR, sum, val);
-    break;
-  case DECIMAL_RESULT:
-    val= &sum_dec;
-    break;
-  case INT_RESULT:
-    int2my_decimal(E_DEC_FATAL_ERROR, sum_int, unsigned_flag, val);
-    break;
-  case ROW_RESULT:
-  default:
-    // This case should never be choosen
-    DBUG_ASSERT(0);
-    break;
-  }
-  return val;					// Keep compiler happy
+  return value->val_decimal(val);
 }
 
 
@@ -1688,25 +1613,7 @@ Item_sum_hybrid::val_str(String *str)
   DBUG_ASSERT(fixed == 1);
   if (null_value)
     return 0;
-  switch (hybrid_type) {
-  case STRING_RESULT:
-    return &value;
-  case REAL_RESULT:
-    str->set_real(sum,decimals, &my_charset_bin);
-    break;
-  case DECIMAL_RESULT:
-    my_decimal2string(E_DEC_FATAL_ERROR, &sum_dec, 0, 0, 0, str);
-    return str;
-  case INT_RESULT:
-    str->set_int(sum_int, unsigned_flag, &my_charset_bin);
-    break;
-  case ROW_RESULT:
-  default:
-    // This case should never be choosen
-    DBUG_ASSERT(0);
-    break;
-  }
-  return str;					// Keep compiler happy
+  return value->val_str(str);
 }
 
 
@@ -1715,7 +1622,9 @@ void Item_sum_hybrid::cleanup()
   DBUG_ENTER("Item_sum_hybrid::cleanup");
   Item_sum::cleanup();
   forced_const= FALSE;
-
+  if (cmp)
+    delete cmp;
+  cmp= 0;
   /*
     by default it is TRUE to avoid TRUE reporting by
     Item_func_not_all/Item_func_nop_all if this item was never called.
@@ -1736,63 +1645,22 @@ void Item_sum_hybrid::no_rows_in_result(
 
 Item *Item_sum_min::copy_or_same(THD* thd)
 {
-  return new (thd->mem_root) Item_sum_min(thd, this);
+  Item_sum_min *item= new (thd->mem_root) Item_sum_min(thd, this);
+  item->setup(args[0], value);
+  return item;
 }
 
 
 bool Item_sum_min::add()
 {
-  switch (hybrid_type) {
-  case STRING_RESULT:
+  /* args[0] < value */
+  int res= cmp->compare();
+  if (!args[0]->null_value &&
+      (null_value || res < 0))
   {
-    String *result=args[0]->val_str(&tmp_value);
-    if (!args[0]->null_value &&
-	(null_value || sortcmp(&value,result,collation.collation) > 0))
-    {
-      value.copy(*result);
-      null_value=0;
-    }
-  }
-  break;
-  case INT_RESULT:
-  {
-    longlong nr=args[0]->val_int();
-    if (!args[0]->null_value && (null_value ||
-				 (unsigned_flag && 
-				  (ulonglong) nr < (ulonglong) sum_int) ||
-				 (!unsigned_flag && nr < sum_int)))
-    {
-      sum_int=nr;
-      null_value=0;
-    }
-  }
-  break;
-  case DECIMAL_RESULT:
-  {
-    my_decimal value_buff, *val= args[0]->val_decimal(&value_buff);
-    if (!args[0]->null_value &&
-        (null_value || (my_decimal_cmp(&sum_dec, val) > 0)))
-    {
-      my_decimal2decimal(val, &sum_dec);
-      null_value= 0;
-    }
-  }
-  break;
-  case REAL_RESULT:
-  {
-    double nr= args[0]->val_real();
-    if (!args[0]->null_value && (null_value || nr < sum))
-    {
-      sum=nr;
-      null_value=0;
-    }
-  }
-  break;
-  case ROW_RESULT:
-  default:
-    // This case should never be choosen
-    DBUG_ASSERT(0);
-    break;
+    value->store(args[0]);
+    value->cache_value();
+    null_value= 0;
   }
   return 0;
 }
@@ -1800,63 +1668,22 @@ bool Item_sum_min::add()
 
 Item *Item_sum_max::copy_or_same(THD* thd)
 {
-  return new (thd->mem_root) Item_sum_max(thd, this);
+  Item_sum_max *item= new (thd->mem_root) Item_sum_max(thd, this);
+  item->setup(args[0], value);
+  return item;
 }
 
 
 bool Item_sum_max::add()
 {
-  switch (hybrid_type) {
-  case STRING_RESULT:
+  /* args[0] > value */
+  int res= cmp->compare();
+  if (!args[0]->null_value &&
+      (null_value || res > 0))
   {
-    String *result=args[0]->val_str(&tmp_value);
-    if (!args[0]->null_value &&
-	(null_value || sortcmp(&value,result,collation.collation) < 0))
-    {
-      value.copy(*result);
-      null_value=0;
-    }
-  }
-  break;
-  case INT_RESULT:
-  {
-    longlong nr=args[0]->val_int();
-    if (!args[0]->null_value && (null_value ||
-				 (unsigned_flag && 
-				  (ulonglong) nr > (ulonglong) sum_int) ||
-				 (!unsigned_flag && nr > sum_int)))
-    {
-      sum_int=nr;
-      null_value=0;
-    }
-  }
-  break;
-  case DECIMAL_RESULT:
-  {
-    my_decimal value_buff, *val= args[0]->val_decimal(&value_buff);
-    if (!args[0]->null_value &&
-        (null_value || (my_decimal_cmp(val, &sum_dec) > 0)))
-    {
-      my_decimal2decimal(val, &sum_dec);
-      null_value= 0;
-    }
-  }
-  break;
-  case REAL_RESULT:
-  {
-    double nr= args[0]->val_real();
-    if (!args[0]->null_value && (null_value || nr > sum))
-    {
-      sum=nr;
-      null_value=0;
-    }
-  }
-  break;
-  case ROW_RESULT:
-  default:
-    // This case should never be choosen
-    DBUG_ASSERT(0);
-    break;
+    value->store(args[0]);
+    value->cache_value();
+    null_value= 0;
   }
   return 0;
 }
@@ -2221,14 +2048,15 @@ void Item_sum_hybrid::update_field()
 void
 Item_sum_hybrid::min_max_update_str_field()
 {
-  String *res_str=args[0]->val_str(&value);
+  DBUG_ASSERT(cmp);
+  String *res_str=args[0]->val_str(&cmp->value1);
 
   if (!args[0]->null_value)
   {
-    result_field->val_str(&tmp_value);
+    result_field->val_str(&cmp->value2);
 
     if (result_field->is_null() ||
-	(cmp_sign * sortcmp(res_str,&tmp_value,collation.collation)) < 0)
+	(cmp_sign * sortcmp(res_str,&cmp->value2,collation.collation)) < 0)
       result_field->store(res_str->ptr(),res_str->length(),res_str->charset());
     result_field->set_notnull();
   }

=== modified file 'sql/item_sum.h'
--- a/sql/item_sum.h	2009-09-15 10:46:35 +0000
+++ b/sql/item_sum.h	2010-01-15 15:27:55 +0000
@@ -329,22 +329,6 @@ public:
   virtual void update_field()=0;
   virtual bool keep_field_type(void) const { return 0; }
   virtual void fix_length_and_dec() { maybe_null=1; null_value=1; }
-  /*
-    This method is used for debug purposes to print the name of an
-    item to the debug log. The second use of this method is as
-    a helper function of print(), where it is applicable.
-    To suit both goals it should return a meaningful,
-    distinguishable and sintactically correct string.  This method
-    should not be used for runtime type identification, use enum
-    {Sum}Functype and Item_func::functype()/Item_sum::sum_func()
-    instead.
-
-    NOTE: for Items inherited from Item_sum, func_name() return part of
-    function name till first argument (including '(') to make difference in
-    names for functions with 'distinct' clause and without 'distinct' and
-    also to make printing of items inherited from Item_sum uniform.
-  */
-  virtual const char *func_name() const= 0;
   virtual Item *result_item(Field *field)
     { return new Item_field(field); }
   /*
@@ -679,6 +663,7 @@ public:
   }
   void fix_length_and_dec() {}
   enum Item_result result_type () const { return hybrid_type; }
+  const char *func_name() const { DBUG_ASSERT(0); return "avg_field"; }
 };
 
 
@@ -747,6 +732,7 @@ public:
   }
   void fix_length_and_dec() {}
   enum Item_result result_type () const { return hybrid_type; }
+  const char *func_name() const { DBUG_ASSERT(0); return "variance_field"; }
 };
 
 
@@ -822,6 +808,7 @@ public:
   my_decimal *val_decimal(my_decimal *);
   enum Item_result result_type () const { return REAL_RESULT; }
   enum_field_types field_type() const { return MYSQL_TYPE_DOUBLE;}
+  const char *func_name() const { DBUG_ASSERT(0); return "std_field"; }
 };
 
 /*
@@ -847,14 +834,13 @@ class Item_sum_std :public Item_sum_vari
 };
 
 // This class is a string or number function depending on num_func
-
+class Arg_comparator;
+class Item_cache;
 class Item_sum_hybrid :public Item_sum
 {
 protected:
-  String value,tmp_value;
-  double sum;
-  longlong sum_int;
-  my_decimal sum_dec;
+  Item_cache *value;
+  Arg_comparator *cmp;
   Item_result hybrid_type;
   enum_field_types hybrid_field_type;
   int cmp_sign;
@@ -862,12 +848,17 @@ protected:
 
   public:
   Item_sum_hybrid(Item *item_par,int sign)
-    :Item_sum(item_par), sum(0.0), sum_int(0),
+    :Item_sum(item_par), value(0), cmp(0),
     hybrid_type(INT_RESULT), hybrid_field_type(MYSQL_TYPE_LONGLONG),
     cmp_sign(sign), was_values(TRUE)
   { collation.set(&my_charset_bin); }
-  Item_sum_hybrid(THD *thd, Item_sum_hybrid *item);
+  Item_sum_hybrid(THD *thd, Item_sum_hybrid *item)
+    :Item_sum(thd, item), value(item->value), hybrid_type(item->hybrid_type),
+    hybrid_field_type(item->hybrid_field_type), cmp_sign(item->cmp_sign),
+    was_values(item->was_values)
+  { }
   bool fix_fields(THD *, Item **);
+  void setup(Item *item, Item *value_arg);
   void clear();
   double val_real();
   longlong val_int();

=== modified file 'sql/item_timefunc.cc'
--- a/sql/item_timefunc.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item_timefunc.cc	2010-01-15 15:27:55 +0000
@@ -391,7 +391,7 @@ static bool extract_date_time(DATE_TIME_
 	if (tmp - val > 6)
 	  tmp= (char*) val + 6;
 	l_time->second_part= (int) my_strtoll10(val, &tmp, &error);
-	frac_part= 6 - (uint) (tmp - val);
+	frac_part= 6 - (int) (tmp - val);
 	if (frac_part > 0)
 	  l_time->second_part*= (ulong) log_10_int[frac_part];
 	val= tmp;
@@ -882,9 +882,9 @@ static bool get_interval_info(const char
       value= value*LL(10) + (longlong) (*str - '0');
     if (transform_msec && i == count - 1) // microseconds always last
     {
-      long msec_length= 6 - (uint) (str - start);
+      int msec_length= 6 - (int)(str - start);
       if (msec_length > 0)
-	value*= (long) log_10_int[msec_length];
+        value*= (long)log_10_int[msec_length];
     }
     values[i]= value;
     while (str != end && !my_isdigit(cs,*str))

=== modified file 'sql/item_xmlfunc.cc'
--- a/sql/item_xmlfunc.cc	2009-12-03 11:19:05 +0000
+++ b/sql/item_xmlfunc.cc	2010-01-15 15:27:55 +0000
@@ -941,14 +941,16 @@ static Item *create_comparator(MY_XPATH
      in a loop through all of the nodes in the node set.
     */
 
-    Item *fake= new Item_string("", 0, xpath->cs);
+    Item_string *fake= new Item_string("", 0, xpath->cs);
+    /* Don't cache fake because its value will be changed during comparison.*/
+    fake->set_used_tables(RAND_TABLE_BIT);
     Item_nodeset_func *nodeset;
     Item *scalar, *comp;
     if (a->type() == Item::XPATH_NODESET)
     {
       nodeset= (Item_nodeset_func*) a;
       scalar= b;
-      comp= eq_func(oper, fake, scalar);
+      comp= eq_func(oper, (Item*)fake, scalar);
     }
     else
     {

=== modified file 'sql/log.cc'
--- a/sql/log.cc	2009-12-03 11:19:05 +0000
+++ b/sql/log.cc	2010-01-15 15:27:55 +0000
@@ -5154,8 +5154,8 @@ int TC_LOG_MMAP::open(const char *opt_na
     pthread_mutex_init(&pg->lock, MY_MUTEX_INIT_FAST);
     pthread_cond_init (&pg->cond, 0);
     pg->start=(my_xid *)(data + i*tc_log_page_size);
-    pg->end=(my_xid *)(pg->start + tc_log_page_size);
     pg->size=pg->free=tc_log_page_size/sizeof(my_xid);
+    pg->end=pg->start + pg->size;
   }
   pages[0].size=pages[0].free=
                 (tc_log_page_size-TC_LOG_HEADER_SIZE)/sizeof(my_xid);
@@ -5691,9 +5691,8 @@ int TC_LOG_BINLOG::recover(IO_CACHE *log
       Xid_log_event *xev=(Xid_log_event *)ev;
       uchar *x= (uchar *) memdup_root(&mem_root, (uchar*) &xev->xid,
                                       sizeof(xev->xid));
-      if (! x)
+      if (!x || my_hash_insert(&xids, x))
         goto err2;
-      my_hash_insert(&xids, x);
     }
     delete ev;
   }

=== modified file 'sql/log_event.cc'
--- a/sql/log_event.cc	2009-12-03 11:34:11 +0000
+++ b/sql/log_event.cc	2010-01-15 15:27:55 +0000
@@ -8453,13 +8453,17 @@ Rows_log_event::write_row(const Relay_lo
   auto_afree_ptr<char> key(NULL);
 
   /* fill table->record[0] with default values */
-
+  bool abort_on_warnings= (rli->sql_thd->variables.sql_mode &
+                           (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES));
   if ((error= prepare_record(table, m_width,
-                             TRUE /* check if columns have def. values */)))
+                             table->file->ht->db_type != DB_TYPE_NDBCLUSTER,
+                             abort_on_warnings, m_curr_row == m_rows_buf)))
     DBUG_RETURN(error);
   
   /* unpack row into table->record[0] */
-  error= unpack_current_row(rli); // TODO: how to handle errors?
+  if ((error= unpack_current_row(rli, abort_on_warnings)))
+    DBUG_RETURN(error);
+
   if (m_curr_row == m_rows_buf)
   {
     /* this is the first row to be inserted, we estimate the rows with
@@ -9256,8 +9260,12 @@ Update_rows_log_event::do_exec_row(const
 
   store_record(m_table,record[1]);
 
+  bool abort_on_warnings= (rli->sql_thd->variables.sql_mode &
+                           (MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES));
   m_curr_row= m_curr_row_end;
-  error= unpack_current_row(rli); // this also updates m_curr_row_end
+  /* this also updates m_curr_row_end */
+  if ((error= unpack_current_row(rli, abort_on_warnings)))
+    return error;
 
   /*
     Now we have the right row to update.  The old row (the one we're

=== modified file 'sql/log_event.h'
--- a/sql/log_event.h	2009-12-03 11:19:05 +0000
+++ b/sql/log_event.h	2010-01-15 15:27:55 +0000
@@ -3541,12 +3541,16 @@ protected:
   int write_row(const Relay_log_info *const, const bool);
 
   // Unpack the current row into m_table->record[0]
-  int unpack_current_row(const Relay_log_info *const rli)
+  int unpack_current_row(const Relay_log_info *const rli,
+                         const bool abort_on_warning= TRUE)
   { 
     DBUG_ASSERT(m_table);
+
+    bool first_row= (m_curr_row == m_rows_buf);
     ASSERT_OR_RETURN_ERROR(m_curr_row < m_rows_end, HA_ERR_CORRUPT_EVENT);
     int const result= ::unpack_row(rli, m_table, m_width, m_curr_row, &m_cols,
-                                   &m_curr_row_end, &m_master_reclength);
+                                   &m_curr_row_end, &m_master_reclength,
+                                   abort_on_warning, first_row);
     if (m_curr_row_end > m_rows_end)
       my_error(ER_SLAVE_CORRUPT_EVENT, MYF(0));
     ASSERT_OR_RETURN_ERROR(m_curr_row_end <= m_rows_end, HA_ERR_CORRUPT_EVENT);

=== modified file 'sql/mysqld.cc'
--- a/sql/mysqld.cc	2009-12-04 15:12:22 +0000
+++ b/sql/mysqld.cc	2010-01-15 15:27:55 +0000
@@ -4005,6 +4005,27 @@ server.");
 
   if (opt_bin_log)
   {
+    /* Reports an error and aborts, if the --log-bin's path 
+       is a directory.*/
+    if (opt_bin_logname && 
+        opt_bin_logname[strlen(opt_bin_logname) - 1] == FN_LIBCHAR)
+    {
+      sql_print_error("Path '%s' is a directory name, please specify \
+a file name for --log-bin option", opt_bin_logname);
+      unireg_abort(1);
+    }
+
+    /* Reports an error and aborts, if the --log-bin-index's path 
+       is a directory.*/
+    if (opt_binlog_index_name && 
+        opt_binlog_index_name[strlen(opt_binlog_index_name) - 1] 
+        == FN_LIBCHAR)
+    {
+      sql_print_error("Path '%s' is a directory name, please specify \
+a file name for --log-bin-index option", opt_binlog_index_name);
+      unireg_abort(1);
+    }
+
     char buf[FN_REFLEN];
     const char *ln;
     ln= mysql_bin_log.generate_name(opt_bin_logname, "-bin", 1, buf);
@@ -5355,12 +5376,16 @@ pthread_handler_t handle_connections_soc
 pthread_handler_t handle_connections_namedpipes(void *arg)
 {
   HANDLE hConnectedPipe;
-  OVERLAPPED connectOverlapped = {0};
+  OVERLAPPED connectOverlapped= {0};
   THD *thd;
   my_thread_init();
   DBUG_ENTER("handle_connections_namedpipes");
-  connectOverlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
-
+  connectOverlapped.hEvent= CreateEvent(NULL, TRUE, FALSE, NULL);
+  if (!connectOverlapped.hEvent)
+  {
+    sql_print_error("Can't create event, last error=%u", GetLastError());
+    unireg_abort(1);
+  }
   DBUG_PRINT("general",("Waiting for named pipe connections."));
   while (!abort_loop)
   {
@@ -5383,7 +5408,8 @@ pthread_handler_t handle_connections_nam
     {
       CloseHandle(hPipe);
       if ((hPipe= CreateNamedPipe(pipe_name,
-                                  PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
+                                  PIPE_ACCESS_DUPLEX |
+                                  FILE_FLAG_OVERLAPPED,
                                   PIPE_TYPE_BYTE |
                                   PIPE_READMODE_BYTE |
                                   PIPE_WAIT,
@@ -5403,7 +5429,8 @@ pthread_handler_t handle_connections_nam
     hConnectedPipe = hPipe;
     /* create new pipe for new connection */
     if ((hPipe = CreateNamedPipe(pipe_name,
-				 PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
+                 PIPE_ACCESS_DUPLEX |
+                 FILE_FLAG_OVERLAPPED,
 				 PIPE_TYPE_BYTE |
 				 PIPE_READMODE_BYTE |
 				 PIPE_WAIT,
@@ -8974,14 +9001,8 @@ static int fix_paths(void)
     pos[0]= FN_LIBCHAR;
     pos[1]= 0;
   }
-  convert_dirname(mysql_real_data_home,mysql_real_data_home,NullS);
-  my_realpath(mysql_unpacked_real_data_home, mysql_real_data_home, MYF(0));
-  mysql_unpacked_real_data_home_len= strlen(mysql_unpacked_real_data_home);
-  if (mysql_unpacked_real_data_home[mysql_unpacked_real_data_home_len-1] == FN_LIBCHAR)
-    --mysql_unpacked_real_data_home_len;
-
-
   convert_dirname(language,language,NullS);
+  convert_dirname(mysql_real_data_home,mysql_real_data_home,NullS);
   (void) my_load_path(mysql_home,mysql_home,""); // Resolve current dir
   (void) my_load_path(mysql_real_data_home,mysql_real_data_home,mysql_home);
   (void) my_load_path(pidfile_name,pidfile_name,mysql_real_data_home);
@@ -8989,6 +9010,12 @@ static int fix_paths(void)
                                       get_relative_path(PLUGINDIR), mysql_home);
   opt_plugin_dir_ptr= opt_plugin_dir;
 
+  my_realpath(mysql_unpacked_real_data_home, mysql_real_data_home, MYF(0));
+  mysql_unpacked_real_data_home_len= 
+    (int) strlen(mysql_unpacked_real_data_home);
+  if (mysql_unpacked_real_data_home[mysql_unpacked_real_data_home_len-1] == FN_LIBCHAR)
+    --mysql_unpacked_real_data_home_len;
+
   char *sharedir=get_relative_path(SHAREDIR);
   if (test_if_hard_path(sharedir))
     strmake(buff,sharedir,sizeof(buff)-1);		/* purecov: tested */
@@ -9019,8 +9046,8 @@ static int fix_paths(void)
   /*
     Convert the secure-file-priv option to system format, allowing
     a quick strcmp to check if read or write is in an allowed dir
-   */
-  if (opt_secure_file_priv)
+  */
+  if (opt_secure_file_priv && opt_secure_file_priv[0])
   {
     convert_dirname(buff, opt_secure_file_priv, NullS);
     my_free(opt_secure_file_priv, MYF(0));

=== modified file 'sql/opt_range.cc'
--- a/sql/opt_range.cc	2009-12-03 11:19:05 +0000
+++ b/sql/opt_range.cc	2010-01-15 15:27:55 +0000
@@ -446,9 +446,9 @@ public:
                                   range_key, *range_key_flag);
     *range_key_flag|= key_tree->min_flag;
     if (key_tree->next_key_part &&
+	key_tree->next_key_part->type == SEL_ARG::KEY_RANGE &&
 	key_tree->next_key_part->part == key_tree->part+1 &&
-	!(*range_key_flag & (NO_MIN_RANGE | NEAR_MIN)) &&
-	key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
+	!(*range_key_flag & (NO_MIN_RANGE | NEAR_MIN)))
       res+= key_tree->next_key_part->store_min_key(key, range_key,
                                                    range_key_flag);
     return res;
@@ -462,9 +462,9 @@ public:
                                  range_key, *range_key_flag);
     (*range_key_flag)|= key_tree->max_flag;
     if (key_tree->next_key_part &&
+	key_tree->next_key_part->type == SEL_ARG::KEY_RANGE &&
 	key_tree->next_key_part->part == key_tree->part+1 &&
-	!(*range_key_flag & (NO_MAX_RANGE | NEAR_MAX)) &&
-	key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
+	!(*range_key_flag & (NO_MAX_RANGE | NEAR_MAX)))
       res+= key_tree->next_key_part->store_max_key(key, range_key,
                                                    range_key_flag);
     return res;
@@ -1700,6 +1700,7 @@ SEL_ARG *SEL_ARG::clone(RANGE_OPT_PARAM
     tmp->prev= *next_arg;			// Link into next/prev chain
     (*next_arg)->next=tmp;
     (*next_arg)= tmp;
+    tmp->part= this->part;
   }
   else
   {
@@ -6672,6 +6673,7 @@ key_or(RANGE_OPT_PARAM *param, SEL_ARG *
     else if ((cmp=tmp->cmp_max_to_min(key2)) < 0)
     {						// Found tmp.max < key2.min
       SEL_ARG *next=tmp->next;
+      /* key1 on the left of key2 non-overlapping */
       if (cmp == -2 && eq_tree(tmp->next_key_part,key2->next_key_part))
       {
 	// Join near ranges like tmp.max < 0 and key2.min >= 0
@@ -6700,6 +6702,7 @@ key_or(RANGE_OPT_PARAM *param, SEL_ARG *
       int tmp_cmp;
       if ((tmp_cmp=tmp->cmp_min_to_max(key2)) > 0) // if tmp.min > key2.max
       {
+        /* tmp is on the right of key2 non-overlapping */
 	if (tmp_cmp == 2 && eq_tree(tmp->next_key_part,key2->next_key_part))
 	{					// ranges are connected
 	  tmp->copy_min_to_min(key2);
@@ -6734,25 +6737,52 @@ key_or(RANGE_OPT_PARAM *param, SEL_ARG *
       }
     }
 
-    // tmp.max >= key2.min && tmp.min <= key.max  (overlapping ranges)
+    /* 
+      tmp.min >= key2.min && tmp.min <= key.max  (overlapping ranges)
+      key2.min <= tmp.min <= key2.max 
+    */  
     if (eq_tree(tmp->next_key_part,key2->next_key_part))
     {
       if (tmp->is_same(key2))
       {
+        /* 
+          Found exact match of key2 inside key1. 
+          Use the relevant range in key1.
+        */
 	tmp->merge_flags(key2);			// Copy maybe flags
 	key2->increment_use_count(-1);		// Free not used tree
       }
       else
       {
 	SEL_ARG *last=tmp;
+        SEL_ARG *first=tmp;
+        /* 
+          Find the last range in tmp that overlaps key2 and has the same 
+          condition on the rest of the keyparts.
+        */
 	while (last->next && last->next->cmp_min_to_max(key2) <= 0 &&
 	       eq_tree(last->next->next_key_part,key2->next_key_part))
 	{
+          /*
+            We've found the last overlapping key1 range in last.
+            This means that the ranges between (and including) the 
+            first overlapping range (tmp) and the last overlapping range
+            (last) are fully nested into the current range of key2 
+            and can safely be discarded. We just need the minimum endpoint
+            of the first overlapping range (tmp) so we can compare it with
+            the minimum endpoint of the enclosing key2 range.
+          */
 	  SEL_ARG *save=last;
 	  last=last->next;
 	  key1=key1->tree_delete(save);
 	}
-        last->copy_min(tmp);
+        /*
+          The tmp range (the first overlapping range) could have been discarded
+          by the previous loop. We should re-direct tmp to the new united range 
+          that's taking its place.
+        */
+        tmp= last;
+        last->copy_min(first);
         bool full_range= last->copy_min(key2);
         if (!full_range)
         {
@@ -7262,27 +7292,25 @@ int test_rb_tree(SEL_ARG *element,SEL_AR
 }
 
 
-/*
-  Count how many times SEL_ARG graph "root" refers to its part "key"
+/**
+  Count how many times SEL_ARG graph "root" refers to its part "key" via
+  transitive closure.
   
-  SYNOPSIS
-    count_key_part_usage()
-      root  An RB-Root node in a SEL_ARG graph.
-      key   Another RB-Root node in that SEL_ARG graph.
+  @param root  An RB-Root node in a SEL_ARG graph.
+  @param key   Another RB-Root node in that SEL_ARG graph.
 
-  DESCRIPTION
-    The passed "root" node may refer to "key" node via root->next_key_part,
-    root->next->n
+  The passed "root" node may refer to "key" node via root->next_key_part,
+  root->next->n
 
-    This function counts how many times the node "key" is referred (via
-    SEL_ARG::next_key_part) by 
-     - intervals of RB-tree pointed by "root", 
-     - intervals of RB-trees that are pointed by SEL_ARG::next_key_part from 
-       intervals of RB-tree pointed by "root",
-     - and so on.
+  This function counts how many times the node "key" is referred (via
+  SEL_ARG::next_key_part) by 
+  - intervals of RB-tree pointed by "root", 
+  - intervals of RB-trees that are pointed by SEL_ARG::next_key_part from 
+  intervals of RB-tree pointed by "root",
+  - and so on.
     
-    Here is an example (horizontal links represent next_key_part pointers, 
-    vertical links - next/prev prev pointers):  
+  Here is an example (horizontal links represent next_key_part pointers, 
+  vertical links - next/prev prev pointers):  
     
          +----+               $
          |root|-----------------+
@@ -7302,8 +7330,8 @@ int test_rb_tree(SEL_ARG *element,SEL_AR
           ...     +---+       $    |
                   |   |------------+
                   +---+       $
-  RETURN 
-    Number of links to "key" from nodes reachable from "root".
+  @return 
+  Number of links to "key" from nodes reachable from "root".
 */
 
 static ulong count_key_part_usage(SEL_ARG *root, SEL_ARG *key)
@@ -7558,8 +7586,8 @@ check_quick_keys(PARAM *param, uint idx,
     param->first_null_comp= key_tree->part+1;
 
   if (key_tree->next_key_part &&
-      key_tree->next_key_part->part == key_tree->part+1 &&
-      key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
+      key_tree->next_key_part->type == SEL_ARG::KEY_RANGE &&
+      key_tree->next_key_part->part == key_tree->part+1)
   {						// const key as prefix
     if (min_key_length == max_key_length &&
 	!memcmp(min_key, max_key, (uint) (tmp_max_key - max_key)) &&
@@ -7840,8 +7868,8 @@ get_quick_keys(PARAM *param,QUICK_RANGE_
                                  &tmp_max_key,max_key_flag);
 
   if (key_tree->next_key_part &&
-      key_tree->next_key_part->part == key_tree->part+1 &&
-      key_tree->next_key_part->type == SEL_ARG::KEY_RANGE)
+      key_tree->next_key_part->type == SEL_ARG::KEY_RANGE &&
+      key_tree->next_key_part->part == key_tree->part+1)
   {						  // const key as prefix
     if ((tmp_min_key - min_key) == (tmp_max_key - max_key) &&
          memcmp(min_key, max_key, (uint)(tmp_max_key - max_key))==0 &&
@@ -9823,7 +9851,11 @@ check_group_min_max_predicates(COND *con
     }
     else if (cur_arg->const_item())
     {
-      DBUG_RETURN(TRUE);
+      /*
+        For predicates of the form "const OP expr" we also have to check 'expr'
+        to make a decision.
+      */
+      continue;
     }
     else
       DBUG_RETURN(FALSE);

=== modified file 'sql/repl_failsafe.cc'
--- a/sql/repl_failsafe.cc	2009-09-23 13:10:23 +0000
+++ b/sql/repl_failsafe.cc	2009-11-20 15:18:01 +0000
@@ -559,7 +559,12 @@ HOSTS";
 	goto err;
       }
       si->server_id = log_server_id;
-      my_hash_insert(&slave_list, (uchar*)si);
+      if (my_hash_insert(&slave_list, (uchar*)si))
+      {
+        error= "the slave is out of memory";
+        pthread_mutex_unlock(&LOCK_slave_list);
+        goto err;
+      }
     }
     strmake(si->host, row[1], sizeof(si->host)-1);
     si->port = atoi(row[port_ind]);

=== modified file 'sql/rpl_record.cc'
--- a/sql/rpl_record.cc	2009-03-05 19:54:53 +0000
+++ b/sql/rpl_record.cc	2009-10-22 00:15:45 +0000
@@ -180,7 +180,8 @@ int
 unpack_row(Relay_log_info const *rli,
            TABLE *table, uint const colcnt,
            uchar const *const row_data, MY_BITMAP const *cols,
-           uchar const **const row_end, ulong *const master_reclength)
+           uchar const **const row_end, ulong *const master_reclength,
+           const bool abort_on_warning, const bool first_row)
 {
   DBUG_ENTER("unpack_row");
   DBUG_ASSERT(row_data);
@@ -224,8 +225,35 @@ unpack_row(Relay_log_info const *rli,
       /* Field...::unpack() cannot return 0 */
       DBUG_ASSERT(pack_ptr != NULL);
 
-      if ((null_bits & null_mask) && f->maybe_null())
-        f->set_null();
+      if (null_bits & null_mask)
+      {
+        if (f->maybe_null())
+        {
+          DBUG_PRINT("debug", ("Was NULL; null mask: 0x%x; null bits: 0x%x",
+                               null_mask, null_bits));
+          f->set_null();
+        }
+        else
+        {
+          MYSQL_ERROR::enum_warning_level error_type=
+            MYSQL_ERROR::WARN_LEVEL_NOTE;
+          if (abort_on_warning && (table->file->has_transactions() ||
+                                   first_row))
+          {
+            error = HA_ERR_ROWS_EVENT_APPLY;
+            error_type= MYSQL_ERROR::WARN_LEVEL_ERROR;
+          }
+          else
+          {
+            f->set_default();
+            error_type= MYSQL_ERROR::WARN_LEVEL_WARN;
+          }
+          push_warning_printf(current_thd, error_type,
+                              ER_BAD_NULL_ERROR,
+                              ER(ER_BAD_NULL_ERROR),
+                              f->field_name);
+        }
+      }
       else
       {
         f->set_notnull();
@@ -305,13 +333,17 @@ unpack_row(Relay_log_info const *rli,
   @param table  Table whose record[0] buffer is prepared. 
   @param skip   Number of columns for which default/nullable check 
                 should be skipped.
-  @param check  Indicates if errors should be raised when checking 
-                default/nullable field properties.
+  @param check  Specifies if lack of default error needs checking.
+  @param abort_on_warning
+                Controls how to react on lack of a field's default.
+                The parameter mimics the master side one for
+                @c check_that_all_fields_are_given_values.
                 
   @returns 0 on success or a handler level error code
  */ 
 int prepare_record(TABLE *const table, 
-                   const uint skip, const bool check)
+                   const uint skip, const bool check,
+                   const bool abort_on_warning, const bool first_row)
 {
   DBUG_ENTER("prepare_record");
 
@@ -326,17 +358,37 @@ int prepare_record(TABLE *const table,
   if (skip >= table->s->fields || !check)
     DBUG_RETURN(0);
 
-  /* Checking if exists default/nullable fields in the default values. */
-
-  for (Field **field_ptr= table->field+skip ; *field_ptr ; ++field_ptr)
+  /*
+    For fields the extra fields on the slave, we check if they have a default.
+    The check follows the same rules as the INSERT query without specifying an
+    explicit value for a field not having the explicit default 
+    (@c check_that_all_fields_are_given_values()).
+  */
+  for (Field **field_ptr= table->field+skip; *field_ptr; ++field_ptr)
   {
     uint32 const mask= NOT_NULL_FLAG | NO_DEFAULT_VALUE_FLAG;
     Field *const f= *field_ptr;
-
-    if (((f->flags & mask) == mask))
+    if ((f->flags &  NO_DEFAULT_VALUE_FLAG) &&
+        (f->real_type() != MYSQL_TYPE_ENUM))
     {
-      my_error(ER_NO_DEFAULT_FOR_FIELD, MYF(0), f->field_name);
-      error = HA_ERR_ROWS_EVENT_APPLY;
+
+      MYSQL_ERROR::enum_warning_level error_type=
+        MYSQL_ERROR::WARN_LEVEL_NOTE;
+      if (abort_on_warning && (table->file->has_transactions() ||
+                               first_row))
+      {
+        error= HA_ERR_ROWS_EVENT_APPLY;
+        error_type= MYSQL_ERROR::WARN_LEVEL_ERROR;
+      }
+      else
+      {
+        f->set_default();
+        error_type= MYSQL_ERROR::WARN_LEVEL_WARN;
+      }
+      push_warning_printf(current_thd, error_type,
+                          ER_NO_DEFAULT_FOR_FIELD,
+                          ER(ER_NO_DEFAULT_FOR_FIELD),
+                          f->field_name);
     }
   }
 

=== modified file 'sql/rpl_record.h'
--- a/sql/rpl_record.h	2008-01-31 12:54:03 +0000
+++ b/sql/rpl_record.h	2009-10-22 00:15:45 +0000
@@ -27,10 +27,13 @@ size_t pack_row(TABLE* table, MY_BITMAP
 int unpack_row(Relay_log_info const *rli,
                TABLE *table, uint const colcnt,
                uchar const *const row_data, MY_BITMAP const *cols,
-               uchar const **const row_end, ulong *const master_reclength);
+               uchar const **const row_end, ulong *const master_reclength,
+               const bool abort_on_warning= TRUE, const bool first_row= TRUE);
 
 // Fill table's record[0] with default values.
-int prepare_record(TABLE *const, const uint =0, const bool =FALSE);
+int prepare_record(TABLE *const table, const uint skip, const bool check,
+                   const bool abort_on_warning= TRUE,
+                   const bool first_row= TRUE);
 #endif
 
 #endif

=== modified file 'sql/rpl_rli.cc'
--- a/sql/rpl_rli.cc	2009-12-03 11:19:05 +0000
+++ b/sql/rpl_rli.cc	2010-01-15 15:27:55 +0000
@@ -100,7 +100,8 @@ int init_relay_log_info(Relay_log_info*
   rli->tables_to_lock_count= 0;
 
   char pattern[FN_REFLEN];
-  if (fn_format(pattern, PREFIX_SQL_LOAD, slave_load_tmpdir, "",
+  (void) my_realpath(pattern, slave_load_tmpdir, 0);
+  if (fn_format(pattern, PREFIX_SQL_LOAD, pattern, "",
             MY_SAFE_PATH | MY_RETURN_REAL_PATH) == NullS)
   {
     pthread_mutex_unlock(&rli->data_lock);
@@ -127,6 +128,29 @@ int init_relay_log_info(Relay_log_info*
     rli->relay_log.max_size (and mysql_bin_log.max_size).
   */
   {
+    /* Reports an error and returns, if the --relay-log's path 
+       is a directory.*/
+    if (opt_relay_logname && 
+        opt_relay_logname[strlen(opt_relay_logname) - 1] == FN_LIBCHAR)
+    {
+      pthread_mutex_unlock(&rli->data_lock);
+      sql_print_error("Path '%s' is a directory name, please specify \
+a file name for --relay-log option", opt_relay_logname);
+      DBUG_RETURN(1);
+    }
+
+    /* Reports an error and returns, if the --relay-log-index's path 
+       is a directory.*/
+    if (opt_relaylog_index_name && 
+        opt_relaylog_index_name[strlen(opt_relaylog_index_name) - 1] 
+        == FN_LIBCHAR)
+    {
+      pthread_mutex_unlock(&rli->data_lock);
+      sql_print_error("Path '%s' is a directory name, please specify \
+a file name for --relay-log-index option", opt_relaylog_index_name);
+      DBUG_RETURN(1);
+    }
+
     char buf[FN_REFLEN];
     const char *ln;
     static bool name_warning_sent= 0;

=== modified file 'sql/rpl_tblmap.cc'
--- a/sql/rpl_tblmap.cc	2008-08-20 14:06:31 +0000
+++ b/sql/rpl_tblmap.cc	2009-11-20 15:18:01 +0000
@@ -119,7 +119,13 @@ int table_mapping::set_table(ulong table
   }
   e->table_id= table_id;
   e->table= table;
-  my_hash_insert(&m_table_ids,(uchar *)e);
+  if (my_hash_insert(&m_table_ids,(uchar *)e))
+  {
+    /* we add this entry to the chain of free (free for use) entries */
+    e->next= m_free;
+    m_free= e;
+    DBUG_RETURN(ERR_MEMORY_ALLOCATION);
+  }
 
   DBUG_PRINT("info", ("tid %lu -> table 0x%lx (%s)", 
 		      table_id, (long) e->table,

=== modified file 'sql/set_var.cc'
--- a/sql/set_var.cc	2009-12-03 11:19:05 +0000
+++ b/sql/set_var.cc	2010-01-14 16:32:41 +0000
@@ -58,6 +58,9 @@
 #include <my_getopt.h>
 #include <thr_alarm.h>
 #include <myisam.h>
+#ifdef WITH_MARIA_STORAGE_ENGINE
+#include <maria.h>
+#endif
 #include <my_dir.h>
 #include <waiting_threads.h>
 #include "events.h"

=== modified file 'sql/sp.cc'
--- a/sql/sp.cc	2009-10-16 10:29:42 +0000
+++ b/sql/sp.cc	2009-11-21 11:18:21 +0000
@@ -70,6 +70,122 @@ enum
   MYSQL_PROC_FIELD_COUNT
 };
 
+static const
+TABLE_FIELD_TYPE proc_table_fields[MYSQL_PROC_FIELD_COUNT] =
+{
+  {
+    { C_STRING_WITH_LEN("db") },
+    { C_STRING_WITH_LEN("char(64)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("name") },
+    { C_STRING_WITH_LEN("char(64)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("type") },
+    { C_STRING_WITH_LEN("enum('FUNCTION','PROCEDURE')") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("specific_name") },
+    { C_STRING_WITH_LEN("char(64)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("language") },
+    { C_STRING_WITH_LEN("enum('SQL')") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("sql_data_access") },
+    { C_STRING_WITH_LEN("enum('CONTAINS_SQL','NO_SQL','READS_SQL_DATA','MODIFIES_SQL_DATA')") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("is_deterministic") },
+    { C_STRING_WITH_LEN("enum('YES','NO')") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("security_type") },
+    { C_STRING_WITH_LEN("enum('INVOKER','DEFINER')") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("param_list") },
+    { C_STRING_WITH_LEN("blob") },
+    { NULL, 0 }
+  },
+
+  {
+    { C_STRING_WITH_LEN("returns") },
+    { C_STRING_WITH_LEN("longblob") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("body") },
+    { C_STRING_WITH_LEN("longblob") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("definer") },
+    { C_STRING_WITH_LEN("char(77)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("created") },
+    { C_STRING_WITH_LEN("timestamp") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("modified") },
+    { C_STRING_WITH_LEN("timestamp") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("sql_mode") },
+    { C_STRING_WITH_LEN("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')") },
+    { NULL, 0 }
+  },
+  {
+    { C_STRING_WITH_LEN("comment") },
+    { C_STRING_WITH_LEN("char(64)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("character_set_client") },
+    { C_STRING_WITH_LEN("char(32)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("collation_connection") },
+    { C_STRING_WITH_LEN("char(32)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("db_collation") },
+    { C_STRING_WITH_LEN("char(32)") },
+    { C_STRING_WITH_LEN("utf8") }
+  },
+  {
+    { C_STRING_WITH_LEN("body_utf8") },
+    { C_STRING_WITH_LEN("longblob") },
+    { NULL, 0 }
+  }
+};
+
+static const TABLE_FIELD_DEF
+  proc_table_def= {MYSQL_PROC_FIELD_COUNT, proc_table_fields};
+
 /*************************************************************************/
 
 /**
@@ -247,6 +363,50 @@ Stored_routine_creation_ctx::load_from_d
 
 /*************************************************************************/
 
+class Proc_table_intact : public Table_check_intact
+{
+private:
+  bool m_print_once;
+
+public:
+  Proc_table_intact() : m_print_once(TRUE) {}
+
+protected:
+  void report_error(uint code, const char *fmt, ...);
+};
+
+
+/**
+  Report failure to validate the mysql.proc table definition.
+  Print a message to the error log only once.
+*/
+
+void Proc_table_intact::report_error(uint code, const char *fmt, ...)
+{
+  va_list args;
+  char buf[512];
+
+  va_start(args, fmt);
+  my_vsnprintf(buf, sizeof(buf), fmt, args);
+  va_end(args);
+
+  if (code)
+    my_message(code, buf, MYF(0));
+  else
+    my_error(ER_CANNOT_LOAD_FROM_TABLE, MYF(0), "proc");
+
+  if (m_print_once)
+  {
+    m_print_once= FALSE;
+    sql_print_error("%s", buf);
+  }
+};
+
+
+/** Single instance used to control printing to the error log. */
+static Proc_table_intact proc_table_intact;
+
+
 /**
   Open the mysql.proc table for read.
 
@@ -266,15 +426,17 @@ TABLE *open_proc_table_for_read(THD *thd
   DBUG_ENTER("open_proc_table_for_read");
 
   TABLE_LIST table;
-  bzero((char*) &table, sizeof(table));
-  table.db= (char*) "mysql";
-  table.table_name= table.alias= (char*)"proc";
-  table.lock_type= TL_READ;
+  table.init_one_table("mysql", "proc", TL_READ);
+
+  if (open_system_tables_for_read(thd, &table, backup))
+    DBUG_RETURN(NULL);
 
-  if (!open_system_tables_for_read(thd, &table, backup))
+  if (!proc_table_intact.check(table.table, &proc_table_def))
     DBUG_RETURN(table.table);
-  else
-    DBUG_RETURN(0);
+
+  close_system_tables(thd, backup);
+
+  DBUG_RETURN(NULL);
 }
 
 
@@ -296,13 +458,19 @@ static TABLE *open_proc_table_for_update
 {
   DBUG_ENTER("open_proc_table_for_update");
 
-  TABLE_LIST table;
-  bzero((char*) &table, sizeof(table));
-  table.db= (char*) "mysql";
-  table.table_name= table.alias= (char*)"proc";
-  table.lock_type= TL_WRITE;
+  TABLE *table;
+  TABLE_LIST table_list;
+  table_list.init_one_table("mysql", "proc", TL_WRITE);
+
+  if (!(table= open_system_table_for_update(thd, &table_list)))
+    DBUG_RETURN(NULL);
+
+  if (!proc_table_intact.check(table, &proc_table_def))
+    DBUG_RETURN(table);
+
+  close_thread_tables(thd);
 
-  DBUG_RETURN(open_system_table_for_update(thd, &table));
+  DBUG_RETURN(NULL);
 }
 
 
@@ -1506,7 +1674,8 @@ static bool add_used_routine(LEX *lex, Q
     rn->key.length= key->length;
     rn->key.str= (char *)rn + sizeof(Sroutine_hash_entry);
     memcpy(rn->key.str, key->str, key->length + 1);
-    my_hash_insert(&lex->sroutines, (uchar *)rn);
+    if (my_hash_insert(&lex->sroutines, (uchar *)rn))
+      return FALSE;
     lex->sroutines_list.link_in_list((uchar *)rn, (uchar **)&rn->next);
     rn->belong_to_view= belong_to_view;
     return TRUE;
@@ -1584,16 +1753,24 @@ void sp_remove_not_own_routines(LEX *lex
     dependant on time of life of elements from source hash. It also
     won't touch lists linking elements in source and destination
     hashes.
+
+  @returns
+    @return TRUE Failure
+    @return FALSE Success
 */
 
-void sp_update_sp_used_routines(HASH *dst, HASH *src)
+bool sp_update_sp_used_routines(HASH *dst, HASH *src)
 {
   for (uint i=0 ; i < src->records ; i++)
   {
     Sroutine_hash_entry *rt= (Sroutine_hash_entry *)hash_element(src, i);
     if (!hash_search(dst, (uchar *)rt->key.str, rt->key.length))
-      my_hash_insert(dst, (uchar *)rt);
+    {
+      if (my_hash_insert(dst, (uchar *)rt))
+        return TRUE;
+    }
   }
+  return FALSE;
 }
 
 

=== modified file 'sql/sp.h'
--- a/sql/sp.h	2009-07-28 17:44:38 +0000
+++ b/sql/sp.h	2009-11-20 15:18:01 +0000
@@ -69,7 +69,7 @@ void sp_get_prelocking_info(THD *thd, bo
 void sp_add_used_routine(LEX *lex, Query_arena *arena,
                          sp_name *rt, char rt_type);
 void sp_remove_not_own_routines(LEX *lex);
-void sp_update_sp_used_routines(HASH *dst, HASH *src);
+bool sp_update_sp_used_routines(HASH *dst, HASH *src);
 int sp_cache_routines_and_add_tables(THD *thd, LEX *lex,
                                      bool first_no_prelock);
 int sp_cache_routines_and_add_tables_for_view(THD *thd, LEX *lex,

=== modified file 'sql/sp_cache.cc'
--- a/sql/sp_cache.cc	2008-12-02 22:02:52 +0000
+++ b/sql/sp_cache.cc	2010-01-15 15:27:55 +0000
@@ -36,10 +36,16 @@ public:
   sp_cache();
   ~sp_cache();
 
-  inline void insert(sp_head *sp)
+  /**
+   Inserts a sp_head object into a hash table.
+
+   @returns Success status
+     @return TRUE Failure
+     @return FALSE Success
+  */
+  inline bool insert(sp_head *sp)
   {
-    /* TODO: why don't we check return value? */
-    my_hash_insert(&m_hashtable, (const uchar *)sp);
+    return my_hash_insert(&m_hashtable, (const uchar *)sp);
   }
 
   inline sp_head *lookup(char *name, uint namelen)

=== modified file 'sql/sp_head.cc'
--- a/sql/sp_head.cc	2009-12-03 11:34:11 +0000
+++ b/sql/sp_head.cc	2010-01-15 15:27:55 +0000
@@ -2090,8 +2090,18 @@ sp_head::reset_lex(THD *thd)
   DBUG_RETURN(FALSE);
 }
 
-/// Restore lex during parsing, after we have parsed a sub statement.
-void
+
+/**
+  Restore lex during parsing, after we have parsed a sub statement.
+
+  @param thd Thread handle
+
+  @return
+    @retval TRUE failure
+    @retval FALSE success
+*/
+
+bool
 sp_head::restore_lex(THD *thd)
 {
   DBUG_ENTER("sp_head::restore_lex");
@@ -2102,7 +2112,7 @@ sp_head::restore_lex(THD *thd)
 
   oldlex= (LEX *)m_lex.pop();
   if (! oldlex)
-    return;			// Nothing to restore
+    DBUG_RETURN(FALSE);			// Nothing to restore
 
   oldlex->trg_table_fields.push_back(&sublex->trg_table_fields);
 
@@ -2118,7 +2128,8 @@ sp_head::restore_lex(THD *thd)
     Add routines which are used by statement to respective set for
     this routine.
   */
-  sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines);
+  if (sp_update_sp_used_routines(&m_sroutines, &sublex->sroutines))
+    DBUG_RETURN(TRUE);
   /*
     Merge tables used by this statement (but not by its functions or
     procedures) to multiset of tables used by this routine.
@@ -2130,7 +2141,7 @@ sp_head::restore_lex(THD *thd)
     delete sublex;
   }
   thd->lex= oldlex;
-  DBUG_VOID_RETURN;
+  DBUG_RETURN(FALSE);
 }
 
 /**
@@ -3867,7 +3878,8 @@ sp_head::merge_table_list(THD *thd, TABL
         tab->lock_type= table->lock_type;
         tab->lock_count= tab->query_lock_count= 1;
         tab->trg_event_map= table->trg_event_map;
-	my_hash_insert(&m_sptabs, (uchar *)tab);
+	if (my_hash_insert(&m_sptabs, (uchar *)tab))
+          return FALSE;
       }
     }
   return TRUE;

=== modified file 'sql/sp_head.h'
--- a/sql/sp_head.h	2009-04-29 02:59:10 +0000
+++ b/sql/sp_head.h	2009-11-20 15:18:01 +0000
@@ -340,7 +340,7 @@ public:
 
     @todo Conflicting comment in sp_head.cc
   */
-  void
+  bool
   restore_lex(THD *thd);
 
   /// Put the instruction on the backpatch list, associated with the label.

=== modified file 'sql/sp_rcontext.cc'
--- a/sql/sp_rcontext.cc	2008-01-23 22:36:57 +0000
+++ b/sql/sp_rcontext.cc	2009-11-06 19:34:25 +0000
@@ -617,7 +617,7 @@ sp_rcontext::set_case_expr(THD *thd, int
   }
 
   m_case_expr_holders[case_expr_id]->store(case_expr_item);
-
+  m_case_expr_holders[case_expr_id]->cache_value();
   return FALSE;
 }
 

=== modified file 'sql/sql_acl.cc'
--- a/sql/sql_acl.cc	2009-12-03 11:19:05 +0000
+++ b/sql/sql_acl.cc	2010-01-15 15:27:55 +0000
@@ -31,9 +31,8 @@
 #include "sp_head.h"
 #include "sp.h"
 
-time_t mysql_db_table_last_check= 0L;
-
-TABLE_FIELD_W_TYPE mysql_db_table_fields[MYSQL_DB_FIELD_COUNT] = {
+static const
+TABLE_FIELD_TYPE mysql_db_table_fields[MYSQL_DB_FIELD_COUNT] = {
   {
     { C_STRING_WITH_LEN("Host") },            
     { C_STRING_WITH_LEN("char(60)") },
@@ -146,6 +145,8 @@ TABLE_FIELD_W_TYPE mysql_db_table_fields
   }
 };
 
+const TABLE_FIELD_DEF
+  mysql_db_table_def= {MYSQL_DB_FIELD_COUNT, mysql_db_table_fields};
 
 #ifndef NO_EMBEDDED_ACCESS_CHECKS
 
@@ -2405,7 +2406,12 @@ GRANT_TABLE::GRANT_TABLE(TABLE *form, TA
         privs = cols = 0;			/* purecov: deadcode */
         return;				/* purecov: deadcode */
       }
-      my_hash_insert(&hash_columns, (uchar *) mem_check);
+      if (my_hash_insert(&hash_columns, (uchar *) mem_check))
+      {
+        /* Invalidate this entry */
+        privs= cols= 0;
+        return;
+      }
     } while (!col_privs->file->index_next(col_privs->record[0]) &&
              !key_cmp_if_same(col_privs,key,0,key_prefix_len));
     col_privs->file->ha_index_end();
@@ -2439,14 +2445,17 @@ static GRANT_NAME *name_hash_search(HASH
                                     const char *host,const char* ip,
                                     const char *db,
                                     const char *user, const char *tname,
-                                    bool exact)
+                                    bool exact, bool name_tolower)
 {
-  char helping [NAME_LEN*2+USERNAME_LENGTH+3];
+  char helping [NAME_LEN*2+USERNAME_LENGTH+3], *name_ptr;
   uint len;
   GRANT_NAME *grant_name,*found=0;
   HASH_SEARCH_STATE state;
 
-  len  = (uint) (strmov(strmov(strmov(helping,user)+1,db)+1,tname)-helping)+ 1;
+  name_ptr= strmov(strmov(helping, user) + 1, db) + 1;
+  len  = (uint) (strmov(name_ptr, tname) - helping) + 1;
+  if (name_tolower)
+    my_casedn_str(files_charset_info, name_ptr);
   for (grant_name= (GRANT_NAME*) hash_first(name_hash, (uchar*) helping,
                                             len, &state);
        grant_name ;
@@ -2479,7 +2488,7 @@ routine_hash_search(const char *host, co
 {
   return (GRANT_TABLE*)
     name_hash_search(proc ? &proc_priv_hash : &func_priv_hash,
-		     host, ip, db, user, tname, exact);
+		     host, ip, db, user, tname, exact, TRUE);
 }
 
 
@@ -2488,7 +2497,7 @@ table_hash_search(const char *host, cons
 		  const char *user, const char *tname, bool exact)
 {
   return (GRANT_TABLE*) name_hash_search(&column_priv_hash, host, ip, db,
-					 user, tname, exact);
+					 user, tname, exact, FALSE);
 }
 
 
@@ -2610,7 +2619,11 @@ static int replace_column_table(GRANT_TA
 	goto end;				/* purecov: inspected */
       }
       grant_column= new GRANT_COLUMN(column->column,privileges);
-      my_hash_insert(&g_t->hash_columns,(uchar*) grant_column);
+      if (my_hash_insert(&g_t->hash_columns,(uchar*) grant_column))
+      {
+        result= -1;
+        goto end;
+      }
     }
   }
 
@@ -3135,12 +3148,12 @@ int mysql_table_grant(THD *thd, TABLE_LI
 				     Str->user.str, table_name,
 				     rights,
 				     column_priv);
-      if (!grant_table)				// end of memory
+      if (!grant_table ||
+        my_hash_insert(&column_priv_hash,(uchar*) grant_table))
       {
 	result= TRUE;				/* purecov: deadcode */
 	continue;				/* purecov: deadcode */
       }
-      my_hash_insert(&column_priv_hash,(uchar*) grant_table);
     }
 
     /* If revoke_grant, calculate the new column privilege for tables_priv */
@@ -3344,12 +3357,13 @@ bool mysql_routine_grant(THD *thd, TABLE
       grant_name= new GRANT_NAME(Str->host.str, db_name,
 				 Str->user.str, table_name,
 				 rights, TRUE);
-      if (!grant_name)
+      if (!grant_name ||
+        my_hash_insert(is_proc ?
+                       &proc_priv_hash : &func_priv_hash,(uchar*) grant_name))
       {
         result= TRUE;
 	continue;
       }
-      my_hash_insert(is_proc ? &proc_priv_hash : &func_priv_hash,(uchar*) grant_name);
     }
 
     if (replace_routine_table(thd, grant_name, tables[1].table, *Str,
@@ -3452,6 +3466,13 @@ bool mysql_grant(THD *thd, const char *d
       result= TRUE;
       continue;
     }
+    /*
+      No User, but a password?
+      They did GRANT ... TO CURRENT_USER() IDENTIFIED BY ... !
+      Get the current user, and shallow-copy the new password to them!
+    */
+    if (!tmp_Str->user.str && tmp_Str->password.str)
+      Str->password= tmp_Str->password;
     if (replace_user_table(thd, tables[0].table, *Str,
                            (!db ? rights : 0), revoke_grant, create_new_users,
                            test(thd->variables.sql_mode &

=== modified file 'sql/sql_acl.h'
--- a/sql/sql_acl.h	2009-05-29 13:37:54 +0000
+++ b/sql/sql_acl.h	2009-11-21 11:18:21 +0000
@@ -159,8 +159,7 @@ enum mysql_db_table_field
   MYSQL_DB_FIELD_COUNT
 };
 
-extern TABLE_FIELD_W_TYPE mysql_db_table_fields[];
-extern time_t mysql_db_table_last_check;
+extern const TABLE_FIELD_DEF mysql_db_table_def;
 
 /* Classes */
 

=== modified file 'sql/sql_base.cc'
--- a/sql/sql_base.cc	2009-12-04 15:12:22 +0000
+++ b/sql/sql_base.cc	2010-01-15 15:27:55 +0000
@@ -2938,7 +2938,12 @@ TABLE *open_table(THD *thd, TABLE_LIST *
     DBUG_PRINT("info", ("inserting table '%s'.'%s' 0x%lx into the cache",
                         table->s->db.str, table->s->table_name.str,
                         (long) table));
-    VOID(my_hash_insert(&open_cache,(uchar*) table));
+    if (my_hash_insert(&open_cache,(uchar*) table))
+    {
+      my_free(table, MYF(0));
+      VOID(pthread_mutex_unlock(&LOCK_open));
+      DBUG_RETURN(NULL);
+    }
   }
 
   check_unused();				// Debugging call

=== modified file 'sql/sql_cache.cc'
--- a/sql/sql_cache.cc	2009-12-03 11:19:05 +0000
+++ b/sql/sql_cache.cc	2010-01-15 15:27:55 +0000
@@ -421,12 +421,16 @@ TYPELIB query_cache_type_typelib=
   effect by another thread. This enables a quick path in execution to skip waits
   when the outcome is known.
 
+  @param use_timeout TRUE if the lock can abort because of a timeout.
+
+  @note use_timeout is optional and default value is FALSE.
+
   @return
    @retval FALSE An exclusive lock was taken
    @retval TRUE The locking attempt failed
 */
 
-bool Query_cache::try_lock(void)
+bool Query_cache::try_lock(bool use_timeout)
 {
   bool interrupt= FALSE;
   DBUG_ENTER("Query_cache::try_lock");
@@ -456,7 +460,26 @@ bool Query_cache::try_lock(void)
     else
     {
       DBUG_ASSERT(m_cache_lock_status == Query_cache::LOCKED);
-      pthread_cond_wait(&COND_cache_status_changed, &structure_guard_mutex);
+      /*
+        To prevent send_result_to_client() and query_cache_insert() from
+        blocking execution for too long a timeout is put on the lock.
+      */
+      if (use_timeout)
+      {
+        struct timespec waittime;
+        set_timespec_nsec(waittime,(ulong)(50000000L));  /* Wait for 50 msec */
+        int res= pthread_cond_timedwait(&COND_cache_status_changed,
+                                        &structure_guard_mutex,&waittime);
+        if (res == ETIMEDOUT)
+        {
+          interrupt= TRUE;
+          break;
+        }
+      }
+      else
+      {
+        pthread_cond_wait(&COND_cache_status_changed, &structure_guard_mutex);
+      }
     }
   }
   pthread_mutex_unlock(&structure_guard_mutex);
@@ -1190,8 +1213,14 @@ def_week_frmt: %lu, in_trans: %d, autoco
       A table- or a full flush operation can potentially take a long time to
       finish. We choose not to wait for them and skip caching statements
       instead.
+
+      In case the wait time can't be determined there is an upper limit which
+      causes try_lock() to abort with a time out.
+
+      The 'TRUE' parameter indicate that the lock is allowed to timeout
+
     */
-    if (try_lock())
+    if (try_lock(TRUE))
       DBUG_VOID_RETURN;
     if (query_cache_size == 0)
     {
@@ -1306,8 +1335,8 @@ end:
   to the user.
 
   RESULTS
-        1	Query was not cached.
-	0	The query was cached and user was sent the result.
+        0	Query was not cached.
+	1	The query was cached and user was sent the result.
 	-1	The query was cached but we didn't have rights to use it.
 		No error is sent to the client yet.
 
@@ -1388,8 +1417,10 @@ Query_cache::send_result_to_client(THD *
     Try to obtain an exclusive lock on the query cache. If the cache is
     disabled or if a full cache flush is in progress, the attempt to
     get the lock is aborted.
+
+    The 'TRUE' parameter indicate that the lock is allowed to timeout
   */
-  if (try_lock())
+  if (try_lock(TRUE))
     goto err;
 
   if (query_cache_size == 0)

=== modified file 'sql/sql_cache.h'
--- a/sql/sql_cache.h	2009-06-16 08:34:47 +0000
+++ b/sql/sql_cache.h	2009-11-20 12:49:06 +0000
@@ -485,7 +485,7 @@ protected:
 			const char *name);
   my_bool in_blocks(Query_cache_block * point);
 
-  bool try_lock(void);
+  bool try_lock(bool use_timeout= FALSE);
   void lock(void);
   void lock_and_suspend(void);
   void unlock(void);

=== modified file 'sql/sql_class.cc'
--- a/sql/sql_class.cc	2009-12-04 15:12:22 +0000
+++ b/sql/sql_class.cc	2010-01-15 15:27:55 +0000
@@ -379,6 +379,8 @@ char *thd_security_context(THD *thd, cha
     str.append(proc_info);
   }
 
+  pthread_mutex_lock(&thd->LOCK_thd_data);
+
   if (thd->query())
   {
     if (max_query_len < 1)
@@ -388,6 +390,9 @@ char *thd_security_context(THD *thd, cha
     str.append('\n');
     str.append(thd->query(), len);
   }
+
+  pthread_mutex_unlock(&thd->LOCK_thd_data);
+
   if (str.c_ptr_safe() == buffer)
     return buffer;
 

=== modified file 'sql/sql_delete.cc'
--- a/sql/sql_delete.cc	2009-12-03 11:34:11 +0000
+++ b/sql/sql_delete.cc	2010-01-15 15:27:55 +0000
@@ -426,7 +426,8 @@ cleanup:
   }
   DBUG_ASSERT(transactional_table || !deleted || thd->transaction.stmt.modified_non_trans_table);
   free_underlaid_joins(thd, select_lex);
-  if (error < 0 || (thd->lex->ignore && !thd->is_fatal_error))
+  if (error < 0 || 
+      (thd->lex->ignore && !thd->is_error() && !thd->is_fatal_error))
   {
     /*
       If a TRUNCATE TABLE was issued, the number of rows should be reported as
@@ -1089,6 +1090,7 @@ bool mysql_truncate(THD *thd, TABLE_LIST
   TABLE *table;
   bool error;
   uint path_length;
+  bool is_temporary_table= false;
   DBUG_ENTER("mysql_truncate");
 
   bzero((char*) &create_info,sizeof(create_info));
@@ -1101,6 +1103,8 @@ bool mysql_truncate(THD *thd, TABLE_LIST
   {
     TABLE_SHARE *share= table->s;
     handlerton *table_type= share->db_type();
+    is_temporary_table= true;
+
     if (!ha_check_storage_engine_flag(table_type, HTON_CAN_RECREATE))
       goto trunc_by_del;
 
@@ -1166,11 +1170,9 @@ end:
   {
     if (!error)
     {
-      /*
-        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());
+      /* In RBR, the statement is not binlogged if the table is temporary. */
+      if (!is_temporary_table || !thd->current_stmt_binlog_row_based)
+        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_insert.cc'
--- a/sql/sql_insert.cc	2009-12-04 15:12:22 +0000
+++ b/sql/sql_insert.cc	2010-01-15 15:27:55 +0000
@@ -521,6 +521,22 @@ bool open_and_lock_for_insert_delayed(TH
   DBUG_ENTER("open_and_lock_for_insert_delayed");
 
 #ifndef EMBEDDED_LIBRARY
+  if (thd->locked_tables && thd->global_read_lock)
+  {
+    /*
+      If this connection has the global read lock, the handler thread
+      will not be able to lock the table. It will wait for the global
+      read lock to go away, but this will never happen since the
+      connection thread will be stuck waiting for the handler thread
+      to open and lock the table.
+      If we are not in locked tables mode, INSERT will seek protection
+      against the global read lock (and fail), thus we will only get
+      to this point in locked tables mode.
+    */
+    my_error(ER_CANT_UPDATE_WITH_READLOCK, MYF(0));
+    DBUG_RETURN(TRUE);
+  }
+
   if (delayed_get_table(thd, table_list))
     DBUG_RETURN(TRUE);
 

=== modified file 'sql/sql_load.cc'
--- a/sql/sql_load.cc	2009-12-03 11:19:05 +0000
+++ b/sql/sql_load.cc	2010-01-15 15:27:55 +0000
@@ -304,7 +304,8 @@ int mysql_load(THD *thd,sql_exchange *ex
     else
     {
       (void) fn_format(name, ex->file_name, mysql_real_data_home, "",
-		       MY_RELATIVE_PATH | MY_UNPACK_FILENAME);
+                       MY_RELATIVE_PATH | MY_UNPACK_FILENAME |
+                       MY_RETURN_REAL_PATH);
 #if !defined(__WIN__) && ! defined(__NETWARE__)
       MY_STAT stat_info;
       if (!my_stat(name,&stat_info,MYF(MY_WME)))
@@ -347,12 +348,16 @@ int mysql_load(THD *thd,sql_exchange *ex
         DBUG_ASSERT(FALSE); 
 #endif
       }
-      else if (opt_secure_file_priv &&
-               strncmp(opt_secure_file_priv, name, strlen(opt_secure_file_priv)))
+      else if (opt_secure_file_priv)
       {
-        /* Read only allowed from within dir specified by secure_file_priv */
-        my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
-        DBUG_RETURN(TRUE);
+        char secure_file_real_path[FN_REFLEN];
+        (void) my_realpath(secure_file_real_path, opt_secure_file_priv, 0);
+        if (strncmp(secure_file_real_path, name, strlen(secure_file_real_path)))
+        {
+          /* Read only allowed from within dir specified by secure_file_priv */
+          my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
+          DBUG_RETURN(TRUE);
+        }
       }
 
     }

=== modified file 'sql/sql_parse.cc'
--- a/sql/sql_parse.cc	2009-12-03 11:34:11 +0000
+++ b/sql/sql_parse.cc	2010-01-15 15:27:55 +0000
@@ -7632,6 +7632,9 @@ void get_default_definer(THD *thd, LEX_U
 
   definer->host.str= (char *) sctx->priv_host;
   definer->host.length= strlen(definer->host.str);
+
+  definer->password.str= NULL;
+  definer->password.length= 0;
 }
 
 
@@ -7683,6 +7686,8 @@ LEX_USER *create_definer(THD *thd, LEX_S
 
   definer->user= *user_name;
   definer->host= *host_name;
+  definer->password.str= NULL;
+  definer->password.length= 0;
 
   return definer;
 }

=== modified file 'sql/sql_partition.cc'
--- a/sql/sql_partition.cc	2009-12-03 11:19:05 +0000
+++ b/sql/sql_partition.cc	2010-01-15 15:27:55 +0000
@@ -196,26 +196,27 @@ bool partition_default_handling(TABLE *t
 {
   DBUG_ENTER("partition_default_handling");
 
-  if (part_info->use_default_no_partitions)
+  if (!is_create_table_ind)
   {
-    if (!is_create_table_ind &&
-        table->file->get_no_parts(normalized_path, &part_info->no_parts))
+    if (part_info->use_default_no_partitions)
     {
-      DBUG_RETURN(TRUE);
+      if (table->file->get_no_parts(normalized_path, &part_info->no_parts))
+      {
+        DBUG_RETURN(TRUE);
+      }
     }
-  }
-  else if (part_info->is_sub_partitioned() &&
-           part_info->use_default_no_subpartitions)
-  {
-    uint no_parts;
-    if (!is_create_table_ind &&
-        (table->file->get_no_parts(normalized_path, &no_parts)))
+    else if (part_info->is_sub_partitioned() &&
+             part_info->use_default_no_subpartitions)
     {
-      DBUG_RETURN(TRUE);
+      uint no_parts;
+      if (table->file->get_no_parts(normalized_path, &no_parts))
+      {
+        DBUG_RETURN(TRUE);
+      }
+      DBUG_ASSERT(part_info->no_parts > 0);
+      DBUG_ASSERT((no_parts % part_info->no_parts) == 0);
+      part_info->no_subparts= no_parts / part_info->no_parts;
     }
-    DBUG_ASSERT(part_info->no_parts > 0);
-    part_info->no_subparts= no_parts / part_info->no_parts;
-    DBUG_ASSERT((no_parts % part_info->no_parts) == 0);
   }
   part_info->set_up_defaults_for_partitioning(table->file,
                                               (ulonglong)0, (uint)0);
@@ -905,6 +906,8 @@ bool fix_fields_part_func(THD *thd, Item
   char* db_name;
   char db_name_string[FN_REFLEN];
   bool save_use_only_table_context;
+  uint8 saved_full_group_by_flag;
+  nesting_map saved_allow_sum_func;
   DBUG_ENTER("fix_fields_part_func");
 
   if (part_info->fixed)
@@ -974,9 +977,19 @@ bool fix_fields_part_func(THD *thd, Item
   save_use_only_table_context= thd->lex->use_only_table_context;
   thd->lex->use_only_table_context= TRUE;
   thd->lex->current_select->cur_pos_in_select_list= UNDEF_POS;
+  saved_full_group_by_flag= thd->lex->current_select->full_group_by_flag;
+  saved_allow_sum_func= thd->lex->allow_sum_func;
+  thd->lex->allow_sum_func= 0;
   
   error= func_expr->fix_fields(thd, (Item**)&func_expr);
 
+  /*
+    Restore full_group_by_flag and allow_sum_func,
+    fix_fields should not affect mysql_select later, see Bug#46923.
+  */
+  thd->lex->current_select->full_group_by_flag= saved_full_group_by_flag;
+  thd->lex->allow_sum_func= saved_allow_sum_func;
+
   thd->lex->use_only_table_context= save_use_only_table_context;
 
   context->table_list= save_table_list;
@@ -1679,7 +1692,7 @@ bool fix_partition_func(THD *thd, TABLE
   if (((part_info->part_type != HASH_PARTITION ||
       part_info->list_of_part_fields == FALSE) &&
       check_part_func_fields(part_info->part_field_array, TRUE)) ||
-      (part_info->list_of_part_fields == FALSE &&
+      (part_info->list_of_subpart_fields == FALSE &&
        part_info->is_sub_partitioned() &&
        check_part_func_fields(part_info->subpart_field_array, TRUE)))
   {

=== modified file 'sql/sql_plugin.cc'
--- a/sql/sql_plugin.cc	2009-12-03 11:19:05 +0000
+++ b/sql/sql_plugin.cc	2009-12-22 10:33:20 +0000
@@ -1168,22 +1168,7 @@ int plugin_init(int *argc, char **argv,
           !my_strnncoll(&my_charset_latin1, (const uchar*) plugin->name,
                         6, (const uchar*) "InnoDB", 6))
         continue;
-#ifdef EMBEDDED_LIBRARY
-      /*
-        MariaDB: disable PBXT in embedded server. We do this for two reasons
-         - PBXT currently doesn't work in embedded server (see 
-         https://bugs.launchpad.net/maria/+bug/439889)
-         - Embedded server is supposed to be "leaner" and our current
-           understanding of that is "without PBXT". At the same time, we want
-           regular server to be with PBXT, and since we don't support compiling
-           embedded server with different options than the regular server,
-           the only way was to disable PBXT from here.
-      */
-      if (!my_strnncoll(&my_charset_latin1, (const uchar*) plugin->name,
-                        4, (const uchar*) "PBXT", 4))
-        continue;
 
-#endif
       bzero(&tmp, sizeof(tmp));
       tmp.plugin= plugin;
       tmp.name.str= (char *)plugin->name;

=== modified file 'sql/sql_select.cc'
--- a/sql/sql_select.cc	2009-12-03 11:34:11 +0000
+++ b/sql/sql_select.cc	2010-01-15 15:27:55 +0000
@@ -992,14 +992,20 @@ JOIN::optimize()
     DBUG_RETURN(1);
   }
 
-  if (select_lex->olap == ROLLUP_TYPE && rollup_process_const_fields())
+  if (rollup.state != ROLLUP::STATE_NONE)
   {
-    DBUG_PRINT("error", ("Error: rollup_process_fields() failed"));
-    DBUG_RETURN(1);
+    if (rollup_process_const_fields())
+    {
+      DBUG_PRINT("error", ("Error: rollup_process_fields() failed"));
+      DBUG_RETURN(1);
+    }
+  }
+  else
+  {
+    /* Remove distinct if only const tables */
+    select_distinct= select_distinct && (const_tables != tables);
   }
 
-  /* Remove distinct if only const tables */
-  select_distinct= select_distinct && (const_tables != tables);
   thd_proc_info(thd, "preparing");
   if (result->initialize_tables(this))
   {
@@ -1298,11 +1304,14 @@ JOIN::optimize()
     - We are using an ORDER BY or GROUP BY on fields not in the first table
     - We are using different ORDER BY and GROUP BY orders
     - The user wants us to buffer the result.
+    When the WITH ROLLUP modifier is present, we cannot skip temporary table
+    creation for the DISTINCT clause just because there are only const tables.
   */
-  need_tmp= (const_tables != tables &&
+  need_tmp= ((const_tables != tables &&
 	     ((select_distinct || !simple_order || !simple_group) ||
 	      (group_list && order) ||
-	      test(select_options & OPTION_BUFFER_RESULT)));
+	      test(select_options & OPTION_BUFFER_RESULT))) ||
+             (rollup.state != ROLLUP::STATE_NONE && select_distinct));
 
   // No cache for MATCH
   make_join_readinfo(this,
@@ -2144,17 +2153,13 @@ JOIN::exec()
 	    DBUG_VOID_RETURN;
 	if (!curr_table->select->cond)
 	  curr_table->select->cond= sort_table_cond;
-	else					// This should never happen
+	else
 	{
 	  if (!(curr_table->select->cond=
 		new Item_cond_and(curr_table->select->cond,
 				  sort_table_cond)))
 	    DBUG_VOID_RETURN;
-	  /*
-	    Item_cond_and do not need fix_fields for execution, its parameters
-	    are fixed or do not need fix_fields, too
-	  */
-	  curr_table->select->cond->quick_fix_field();
+	  curr_table->select->cond->fix_fields(thd, 0);
 	}
 	curr_table->select_cond= curr_table->select->cond;
 	curr_table->select_cond->top_level_item();
@@ -6565,6 +6570,56 @@ void rr_unlock_row(st_join_table *tab)
 
 
 
+/**
+  Pick the appropriate access method functions
+
+  Sets the functions for the selected table access method
+
+  @param      tab               Table reference to put access method
+*/
+
+static void
+pick_table_access_method(JOIN_TAB *tab)
+{
+  switch (tab->type) 
+  {
+  case JT_REF:
+    tab->read_first_record= join_read_always_key;
+    tab->read_record.read_record= join_read_next_same;
+    break;
+
+  case JT_REF_OR_NULL:
+    tab->read_first_record= join_read_always_key_or_null;
+    tab->read_record.read_record= join_read_next_same_or_null;
+    break;
+
+  case JT_CONST:
+    tab->read_first_record= join_read_const;
+    tab->read_record.read_record= join_no_more_records;
+    break;
+
+  case JT_EQ_REF:
+    tab->read_first_record= join_read_key;
+    tab->read_record.read_record= join_no_more_records;
+    break;
+
+  case JT_FT:
+    tab->read_first_record= join_ft_read_first;
+    tab->read_record.read_record= join_ft_read_next;
+    break;
+
+  case JT_SYSTEM:
+    tab->read_first_record= join_read_system;
+    tab->read_record.read_record= join_no_more_records;
+    break;
+
+  /* keep gcc happy */  
+  default:
+    break;  
+  }
+}
+
+
 static void
 make_join_readinfo(JOIN *join, ulonglong options)
 {
@@ -6599,45 +6654,15 @@ make_join_readinfo(JOIN *join, ulonglong
 
     tab->sorted= sorted;
     sorted= 0;                                  // only first must be sorted
+    table->status=STATUS_NO_RECORD;
+    pick_table_access_method (tab);
+
     switch (tab->type) {
-    case JT_SYSTEM:				// Only happens with left join
-      table->status=STATUS_NO_RECORD;
-      tab->read_first_record= join_read_system;
-      tab->read_record.read_record= join_no_more_records;
-      break;
-    case JT_CONST:				// Only happens with left join
-      table->status=STATUS_NO_RECORD;
-      tab->read_first_record= join_read_const;
-      tab->read_record.read_record= join_no_more_records;
-      if (table->covering_keys.is_set(tab->ref.key) &&
-          !table->no_keyread)
-      {
-        table->key_read=1;
-        table->file->extra(HA_EXTRA_KEYREAD);
-      }
-      break;
     case JT_EQ_REF:
-      table->status=STATUS_NO_RECORD;
-      if (tab->select)
-      {
-	delete tab->select->quick;
-	tab->select->quick=0;
-      }
-      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)
-      {
-	table->key_read=1;
-	table->file->extra(HA_EXTRA_KEYREAD);
-      }
-      break;
+      /* fall through */
     case JT_REF_OR_NULL:
     case JT_REF:
-      table->status=STATUS_NO_RECORD;
       if (tab->select)
       {
 	delete tab->select->quick;
@@ -6645,34 +6670,20 @@ make_join_readinfo(JOIN *join, ulonglong
       }
       delete tab->quick;
       tab->quick=0;
+      /* fall through */
+    case JT_CONST:				// Only happens with left join
       if (table->covering_keys.is_set(tab->ref.key) &&
 	  !table->no_keyread)
       {
 	table->key_read=1;
 	table->file->extra(HA_EXTRA_KEYREAD);
       }
-      if (tab->type == JT_REF)
-      {
-	tab->read_first_record= join_read_always_key;
-	tab->read_record.read_record= join_read_next_same;
-      }
-      else
-      {
-	tab->read_first_record= join_read_always_key_or_null;
-	tab->read_record.read_record= join_read_next_same_or_null;
-      }
-      break;
-    case JT_FT:
-      table->status=STATUS_NO_RECORD;
-      tab->read_first_record= join_ft_read_first;
-      tab->read_record.read_record= join_ft_read_next;
       break;
     case JT_ALL:
       /*
 	If previous table use cache
         If the incoming data set is already sorted don't use cache.
       */
-      table->status=STATUS_NO_RECORD;
       if (i != join->const_tables && !(options & SELECT_NO_JOIN_CACHE) &&
           tab->use_quick != 2 && !tab->first_inner && !ordered_set)
       {
@@ -6758,6 +6769,9 @@ make_join_readinfo(JOIN *join, ulonglong
 	}
       }
       break;
+    case JT_FT:
+    case JT_SYSTEM: 
+      break;
     default:
       DBUG_PRINT("error",("Table type %d found",tab->type)); /* purecov: deadcode */
       break;					/* purecov: deadcode */
@@ -7909,12 +7923,12 @@ static COND *build_equal_items_for_cond(
         {
           item_equal->fix_length_and_dec();
           item_equal->update_used_tables();
+          set_if_bigger(thd->lex->current_select->max_equal_elems,
+                        item_equal->members());  
+          return item_equal;
 	}
-        else
-          item_equal= (Item_equal *) eq_list.pop();
-        set_if_bigger(thd->lex->current_select->max_equal_elems,
-                      item_equal->members());  
-        return item_equal;
+
+        return eq_list.pop();
       }
       else
       {
@@ -9552,47 +9566,8 @@ static Field *create_tmp_field_from_item
     new_field->set_derivation(item->collation.derivation);
     break;
   case DECIMAL_RESULT:
-  {
-    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);
+    new_field= Field_new_decimal::create_from_item(item);
     break;
-  }
   case ROW_RESULT:
   default:
     // This case should never be choosen
@@ -13496,6 +13471,8 @@ test_if_skip_sort_order(JOIN_TAB *tab,OR
           if (create_ref_for_key(tab->join, tab, keyuse, 
                                  tab->join->const_table_map))
             DBUG_RETURN(0);
+
+          pick_table_access_method(tab);
 	}
 	else
 	{
@@ -14305,7 +14282,10 @@ static int remove_dup_with_hash_index(TH
 	goto err;
     }
     else
-      (void) my_hash_insert(&hash, org_key_pos);
+    {
+      if (my_hash_insert(&hash, org_key_pos))
+        goto err;
+    }
     key_pos+=extra_length;
   }
   my_free((char*) key_buffer,MYF(0));

=== modified file 'sql/sql_show.cc'
--- a/sql/sql_show.cc	2009-12-03 11:34:11 +0000
+++ b/sql/sql_show.cc	2010-01-15 15:27:55 +0000
@@ -721,7 +721,7 @@ mysqld_show_create(THD *thd, TABLE_LIST
     thd->push_internal_handler(&view_error_suppressor);
     bool error= open_normal_and_derived_tables(thd, table_list, 0);
     thd->pop_internal_handler();
-    if (error && thd->main_da.is_error())
+    if (error && (thd->killed || thd->main_da.is_error()))
       DBUG_RETURN(TRUE);
   }
 

=== modified file 'sql/sql_table.cc'
--- a/sql/sql_table.cc	2009-12-03 11:19:05 +0000
+++ b/sql/sql_table.cc	2010-01-15 15:27:55 +0000
@@ -5428,12 +5428,20 @@ binlog:
         }
         VOID(pthread_mutex_unlock(&LOCK_open));
 
-        IF_DBUG(int result=)
-          store_create_info(thd, table, &query,
-                            create_info, FALSE /* show_database */);
+       /*
+         The condition avoids a crash as described in BUG#48506. Other
+         binlogging problems related to CREATE TABLE IF NOT EXISTS LIKE
+         when the existing object is a view will be solved by BUG 47442.
+       */
+        if (!table->view)
+        {
+          IF_DBUG(int result=)
+            store_create_info(thd, table, &query,
+                              create_info, FALSE /* show_database */);
 
-        DBUG_ASSERT(result == 0); // store_create_info() always return 0
-        write_bin_log(thd, TRUE, query.ptr(), query.length());
+          DBUG_ASSERT(result == 0); // store_create_info() always return 0
+          write_bin_log(thd, TRUE, query.ptr(), query.length());
+        }
       }
       else                                      // Case 1
         write_bin_log(thd, TRUE, thd->query(), thd->query_length());

=== modified file 'sql/sql_yacc.yy'
--- a/sql/sql_yacc.yy	2009-12-03 11:19:05 +0000
+++ b/sql/sql_yacc.yy	2010-01-15 15:27:55 +0000
@@ -389,6 +389,138 @@ void case_stmt_action_end_case(LEX *lex,
   lex->sphead->do_cont_backpatch();
 }
 
+
+static bool
+find_sys_var_null_base(THD *thd, struct sys_var_with_base *tmp)
+{
+  tmp->var= find_sys_var(thd, tmp->base_name.str, tmp->base_name.length);
+
+  if (tmp->var == NULL)
+    my_error(ER_UNKNOWN_SYSTEM_VARIABLE, MYF(0), tmp->base_name.str);
+  else
+    tmp->base_name= null_lex_str;
+
+  return thd->is_error();
+}
+
+
+/**
+  Helper action for a SET statement.
+  Used to push a system variable into the assignment list.
+
+  @param thd      the current thread
+  @param tmp      the system variable with base name
+  @param var_type the scope of the variable
+  @param val      the value being assigned to the variable
+
+  @return TRUE if error, FALSE otherwise.
+*/
+
+static bool
+set_system_variable(THD *thd, struct sys_var_with_base *tmp,
+                    enum enum_var_type var_type, Item *val)
+{
+  set_var *var;
+  LEX *lex= thd->lex;
+
+  /* No AUTOCOMMIT from a stored function or trigger. */
+  if (lex->spcont && tmp->var == &sys_autocommit)
+    lex->sphead->m_flags|= sp_head::HAS_SET_AUTOCOMMIT_STMT;
+
+  if (! (var= new set_var(var_type, tmp->var, &tmp->base_name, val)))
+    return TRUE;
+
+  return lex->var_list.push_back(var);
+}
+
+
+/**
+  Helper action for a SET statement.
+  Used to push a SP local variable into the assignment list.
+
+  @param thd      the current thread
+  @param var_type the SP local variable
+  @param val      the value being assigned to the variable
+
+  @return TRUE if error, FALSE otherwise.
+*/
+
+static bool
+set_local_variable(THD *thd, sp_variable_t *spv, Item *val)
+{
+  Item *it;
+  LEX *lex= thd->lex;
+  sp_instr_set *sp_set;
+
+  if (val)
+    it= val;
+  else if (spv->dflt)
+    it= spv->dflt;
+  else
+  {
+    it= new (thd->mem_root) Item_null();
+    if (it == NULL)
+      return TRUE;
+  }
+
+  sp_set= new sp_instr_set(lex->sphead->instructions(), lex->spcont,
+                           spv->offset, it, spv->type, lex, TRUE);
+
+  return (sp_set == NULL || lex->sphead->add_instr(sp_set));
+}
+
+
+/**
+  Helper action for a SET statement.
+  Used to SET a field of NEW row.
+
+  @param thd      the current thread
+  @param name     the field name
+  @param val      the value being assigned to the row
+
+  @return TRUE if error, FALSE otherwise.
+*/
+
+static bool
+set_trigger_new_row(THD *thd, LEX_STRING *name, Item *val)
+{
+  LEX *lex= thd->lex;
+  Item_trigger_field *trg_fld;
+  sp_instr_set_trigger_field *sp_fld;
+
+  /* QQ: Shouldn't this be field's default value ? */
+  if (! val)
+    val= new Item_null();
+
+  DBUG_ASSERT(lex->trg_chistics.action_time == TRG_ACTION_BEFORE &&
+              (lex->trg_chistics.event == TRG_EVENT_INSERT ||
+               lex->trg_chistics.event == TRG_EVENT_UPDATE));
+
+  trg_fld= new (thd->mem_root)
+            Item_trigger_field(lex->current_context(),
+                               Item_trigger_field::NEW_ROW,
+                               name->str, UPDATE_ACL, FALSE);
+
+  if (trg_fld == NULL)
+    return TRUE;
+
+  sp_fld= new sp_instr_set_trigger_field(lex->sphead->instructions(),
+                                         lex->spcont, trg_fld, val, lex);
+
+  if (sp_fld == NULL)
+    return TRUE;
+
+  /*
+    Let us add this item to list of all Item_trigger_field
+    objects in trigger.
+  */
+  lex->trg_table_fields.link_in_list((uchar *) trg_fld,
+                                     (uchar **) &trg_fld->next_trg_field);
+
+  return lex->sphead->add_instr(sp_fld);
+}
+
+
 /**
   Helper to resolve the SQL:2003 Syntax exception 1) in <in predicate>.
   See SQL:2003, Part 2, section 8.4 <in predicate>, Note 184, page 383.
@@ -2335,8 +2467,8 @@ sp_decl:
             }
 
             pctx->declare_var_boundary(0);
-            lex->sphead->restore_lex(YYTHD);
-
+            if (lex->sphead->restore_lex(YYTHD))
+              MYSQL_YYABORT;
             $$.vars= $2;
             $$.conds= $$.hndlrs= $$.curs= 0;
           }
@@ -2446,7 +2578,8 @@ sp_cursor_stmt:
             }
             lex->sp_lex_in_use= TRUE;
             $$= lex;
-            lex->sphead->restore_lex(YYTHD);
+            if (lex->sphead->restore_lex(YYTHD))
+              MYSQL_YYABORT;
           }
         ;
 
@@ -2665,7 +2798,8 @@ sp_proc_stmt_statement:
                     sp->add_instr(i))
                 MYSQL_YYABORT;
             }
-            sp->restore_lex(thd);
+            if (sp->restore_lex(thd))
+              MYSQL_YYABORT;
           }
         ;
 
@@ -2693,7 +2827,8 @@ sp_proc_stmt_return:
                 MYSQL_YYABORT;
               sp->m_flags|= sp_head::HAS_RETURN;
             }
-            sp->restore_lex(YYTHD);
+            if (sp->restore_lex(YYTHD))
+              MYSQL_YYABORT;
           }
         ;
 
@@ -2933,7 +3068,8 @@ sp_if:
                 sp->add_cont_backpatch(i) ||
                 sp->add_instr(i))
               MYSQL_YYABORT;
-            sp->restore_lex(YYTHD);
+            if (sp->restore_lex(YYTHD))
+              MYSQL_YYABORT;
           }
           sp_proc_stmts1
           {
@@ -2979,7 +3115,9 @@ simple_case_stmt:
             if (case_stmt_action_expr(lex, $3))
               MYSQL_YYABORT;
 
-            lex->sphead->restore_lex(YYTHD); /* For expr $3 */
+            /* For expr $3 */
+            if (lex->sphead->restore_lex(YYTHD))
+              MYSQL_YYABORT;
           }
           simple_when_clause_list
           else_clause_opt
@@ -3029,7 +3167,9 @@ simple_when_clause:
             LEX *lex= Lex;
             if (case_stmt_action_when(lex, $3, true))
               MYSQL_YYABORT;
-            lex->sphead->restore_lex(YYTHD); /* For expr $3 */
+            /* For expr $3 */
+            if (lex->sphead->restore_lex(YYTHD))
+              MYSQL_YYABORT;
           }
           THEN_SYM
           sp_proc_stmts1
@@ -3050,7 +3190,9 @@ searched_when_clause:
             LEX *lex= Lex;
             if (case_stmt_action_when(lex, $3, false))
               MYSQL_YYABORT;
-            lex->sphead->restore_lex(YYTHD); /* For expr $3 */
+            /* For expr $3 */
+            if (lex->sphead->restore_lex(YYTHD))
+              MYSQL_YYABORT;
           }
           THEN_SYM
           sp_proc_stmts1
@@ -3227,7 +3369,8 @@ sp_unlabeled_control:
                 sp->new_cont_backpatch(i) ||
                 sp->add_instr(i))
               MYSQL_YYABORT;
-            sp->restore_lex(YYTHD);
+            if (sp->restore_lex(YYTHD))
+              MYSQL_YYABORT;
           }
           sp_proc_stmts1 END WHILE_SYM
           {
@@ -3253,7 +3396,8 @@ sp_unlabeled_control:
             if (i == NULL ||
                 lex->sphead->add_instr(i))
               MYSQL_YYABORT;
-            lex->sphead->restore_lex(YYTHD);
+            if (lex->sphead->restore_lex(YYTHD))
+              MYSQL_YYABORT;
             /* We can shortcut the cont_backpatch here */
             i->m_cont_dest= ip+1;
           }
@@ -7539,6 +7683,14 @@ function_call_nonkeyword:
           }
         | SYSDATE optional_braces
           {
+            /*
+              Unlike other time-related functions, SYSDATE() is
+              replication-unsafe because it is not affected by the
+              TIMESTAMP variable.  It is unsafe even if
+              sysdate_is_now=1, because the slave may have
+              sysdate_is_now=0.
+            */
+            Lex->set_stmt_unsafe();
             if (global_system_variables.sysdate_is_now == 0)
               $$= new (YYTHD->mem_root) Item_func_sysdate_local();
             else
@@ -11791,7 +11943,8 @@ option_type_value:
                 if (sp->add_instr(i))
                   MYSQL_YYABORT;
               }
-              lex->sphead->restore_lex(thd);
+              if (lex->sphead->restore_lex(thd))
+                MYSQL_YYABORT;
             }
           }
         ;
@@ -11831,98 +11984,42 @@ sys_option_value:
           option_type internal_variable_name equal set_expr_or_default
           {
             THD *thd= YYTHD;
-            LEX *lex=Lex;
+            LEX *lex= Lex;
+            LEX_STRING *name= &$2.base_name;
 
             if ($2.var == trg_new_row_fake_var)
             {
               /* We are in trigger and assigning value to field of new row */
-              Item *it;
-              Item_trigger_field *trg_fld;
-              sp_instr_set_trigger_field *sp_fld;
-              LINT_INIT(sp_fld);
               if ($1)
               {
                 my_parse_error(ER(ER_SYNTAX_ERROR));
                 MYSQL_YYABORT;
               }
-              if ($4)
-                it= $4;
-              else
-              {
-                /* QQ: Shouldn't this be field's default value ? */
-                it= new Item_null();
-              }
-
-              DBUG_ASSERT(lex->trg_chistics.action_time == TRG_ACTION_BEFORE &&
-                          (lex->trg_chistics.event == TRG_EVENT_INSERT ||
-                           lex->trg_chistics.event == TRG_EVENT_UPDATE));
-
-              trg_fld= new (thd->mem_root)
-                         Item_trigger_field(Lex->current_context(),
-                                            Item_trigger_field::NEW_ROW,
-                                            $2.base_name.str,
-                                            UPDATE_ACL, FALSE);
-              if (trg_fld == NULL)
-                MYSQL_YYABORT;
-
-              sp_fld= new sp_instr_set_trigger_field(lex->sphead->
-                                                     instructions(),
-                                                     lex->spcont,
-                                                     trg_fld,
-                                                     it, lex);
-              if (sp_fld == NULL)
-                MYSQL_YYABORT;
-
-              /*
-                Let us add this item to list of all Item_trigger_field
-                objects in trigger.
-              */
-              lex->trg_table_fields.link_in_list((uchar *)trg_fld,
-                                                 (uchar **) &trg_fld->
-                                                   next_trg_field);
-
-              if (lex->sphead->add_instr(sp_fld))
+              if (set_trigger_new_row(YYTHD, name, $4))
                 MYSQL_YYABORT;
             }
             else if ($2.var)
-            { /* System variable */
+            {
               if ($1)
                 lex->option_type= $1;
-              set_var *var= new set_var(lex->option_type, $2.var,
-                                        &$2.base_name, $4);
-              if (var == NULL)
+
+              /* It is a system variable. */
+              if (set_system_variable(thd, &$2, lex->option_type, $4))
                 MYSQL_YYABORT;
-              lex->var_list.push_back(var);
             }
             else
             {
-              /* An SP local variable */
-              sp_pcontext *ctx= lex->spcont;
-              sp_variable_t *spv;
-              sp_instr_set *sp_set;
-              Item *it;
+              sp_pcontext *spc= lex->spcont;
+              sp_variable_t *spv= spc->find_variable(name);
+
               if ($1)
               {
                 my_parse_error(ER(ER_SYNTAX_ERROR));
                 MYSQL_YYABORT;
               }
 
-              spv= ctx->find_variable(&$2.base_name);
-
-              if ($4)
-                it= $4;
-              else if (spv->dflt)
-                it= spv->dflt;
-              else
-              {
-                it= new (thd->mem_root) Item_null();
-                if (it == NULL)
-                  MYSQL_YYABORT;
-              }
-              sp_set= new sp_instr_set(lex->sphead->instructions(), ctx,
-                                       spv->offset, it, spv->type, lex, TRUE);
-              if (sp_set == NULL ||
-                  lex->sphead->add_instr(sp_set))
+              /* It is a local variable. */
+              if (set_local_variable(thd, spv, $4))
                 MYSQL_YYABORT;
             }
           }
@@ -11958,11 +12055,16 @@ option_value:
           }
         | '@' '@' opt_var_ident_type internal_variable_name equal set_expr_or_default
           {
-            LEX *lex=Lex;
-            set_var *var= new set_var($3, $4.var, &$4.base_name, $6);
-            if (var == NULL)
+            THD *thd= YYTHD;
+            struct sys_var_with_base tmp= $4;
+            /* Lookup if necessary: must be a system variable. */
+            if (tmp.var == NULL)
+            {
+              if (find_sys_var_null_base(thd, &tmp))
+                MYSQL_YYABORT;
+            }
+            if (set_system_variable(thd, &tmp, $3, $6))
               MYSQL_YYABORT;
-            lex->var_list.push_back(var);
           }
         | charset old_or_new_charset_name_or_default
           {
@@ -12055,31 +12157,26 @@ internal_variable_name:
           ident
           {
             THD *thd= YYTHD;
-            LEX *lex= thd->lex;
-            sp_pcontext *spc= lex->spcont;
+            sp_pcontext *spc= thd->lex->spcont;
             sp_variable_t *spv;
 
-            /* We have to lookup here since local vars can shadow sysvars */
+            /* Best effort lookup for system variable. */
             if (!spc || !(spv = spc->find_variable(&$1)))
             {
+              struct sys_var_with_base tmp= {NULL, $1};
+
               /* Not an SP local variable */
-              sys_var *tmp=find_sys_var(thd, $1.str, $1.length);
-              if (!tmp)
+              if (find_sys_var_null_base(thd, &tmp))
                 MYSQL_YYABORT;
-              $$.var= tmp;
-              $$.base_name= null_lex_str;
-              if (spc && tmp == &sys_autocommit)
-              {
-                /*
-                  We don't allow setting AUTOCOMMIT from a stored function
-                  or trigger.
-                */
-                lex->sphead->m_flags|= sp_head::HAS_SET_AUTOCOMMIT_STMT;
-              }
+
+              $$= tmp;
             }
             else
             {
-              /* An SP local variable */
+              /*
+                Possibly an SP local variable (or a shadowed sysvar).
+                Will depend on the context of the SET statement.
+              */
               $$.var= NULL;
               $$.base_name= $1;
             }

=== modified file 'sql/table.cc'
--- a/sql/table.cc	2009-12-03 11:34:11 +0000
+++ b/sql/table.cc	2010-01-15 15:27:55 +0000
@@ -1316,8 +1316,16 @@ static int open_binary_frm(THD *thd, TAB
       share->timestamp_field_offset= i;
 
     if (use_hash)
-      (void) my_hash_insert(&share->name_hash,
-                            (uchar*) field_ptr); // never fail
+      if (my_hash_insert(&share->name_hash, (uchar*) field_ptr) )
+      {
+        /*
+          Set return code 8 here to indicate that an error has
+          occurred but that the error message already has been
+          sent (OOM).
+        */
+        error= 8; 
+        goto err;
+      }
   }
   *field_ptr=0;					// End marker
 
@@ -2804,34 +2812,38 @@ bool check_column_name(const char *name)
                   and such errors never reach the user.
 */
 
-my_bool
-table_check_intact(TABLE *table, const uint table_f_count,
-                   const TABLE_FIELD_W_TYPE *table_def)
+bool
+Table_check_intact::check(TABLE *table, const TABLE_FIELD_DEF *table_def)
 {
   uint i;
   my_bool error= FALSE;
-  my_bool fields_diff_count;
+  const TABLE_FIELD_TYPE *field_def= table_def->field;
   DBUG_ENTER("table_check_intact");
   DBUG_PRINT("info",("table: %s  expected_count: %d",
-                     table->alias, table_f_count));
+                     table->alias, table_def->count));
 
-  fields_diff_count= (table->s->fields != table_f_count);
-  if (fields_diff_count)
+  /* Whether the table definition has already been validated. */
+  if (table->s->table_field_def_cache == table_def)
+    DBUG_RETURN(FALSE);
+
+  if (table->s->fields != table_def->count)
   {
     DBUG_PRINT("info", ("Column count has changed, checking the definition"));
 
     /* previous MySQL version */
     if (MYSQL_VERSION_ID > table->s->mysql_version)
     {
-      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
-                      table->alias, table_f_count, table->s->fields,
-                      table->s->mysql_version, MYSQL_VERSION_ID);
+      report_error(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE,
+                   ER(ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE),
+                   table->alias, table_def->count, table->s->fields,
+                   table->s->mysql_version, MYSQL_VERSION_ID);
       DBUG_RETURN(TRUE);
     }
     else if (MYSQL_VERSION_ID == table->s->mysql_version)
     {
-      sql_print_error(ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), table->alias,
-                      table_f_count, table->s->fields);
+      report_error(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED,
+                   ER(ER_COL_COUNT_DOESNT_MATCH_CORRUPTED), table->alias,
+                   table_def->count, table->s->fields);
       DBUG_RETURN(TRUE);
     }
     /*
@@ -2843,7 +2855,7 @@ table_check_intact(TABLE *table, const u
     */
   }
   char buffer[STRING_BUFFER_USUAL_SIZE];
-  for (i=0 ; i < table_f_count; i++, table_def++)
+  for (i=0 ; i < table_def->count; i++, field_def++)
   {
     String sql_type(buffer, sizeof(buffer), system_charset_info);
     sql_type.length(0);
@@ -2851,18 +2863,18 @@ table_check_intact(TABLE *table, const u
     {
       Field *field= table->field[i];
 
-      if (strncmp(field->field_name, table_def->name.str,
-                  table_def->name.length))
+      if (strncmp(field->field_name, field_def->name.str,
+                  field_def->name.length))
       {
         /*
           Name changes are not fatal, we use ordinal numbers to access columns.
           Still this can be a sign of a tampered table, output an error
           to the error log.
         */
-        sql_print_error("Incorrect definition of table %s.%s: "
-                        "expected column '%s' at position %d, found '%s'.",
-                        table->s->db.str, table->alias, table_def->name.str, i,
-                        field->field_name);
+        report_error(0, "Incorrect definition of table %s.%s: "
+                     "expected column '%s' at position %d, found '%s'.",
+                     table->s->db.str, table->alias, field_def->name.str, i,
+                     field->field_name);
       }
       field->sql_type(sql_type);
       /*
@@ -2882,47 +2894,51 @@ table_check_intact(TABLE *table, const u
         the new table definition is backward compatible with the
         original one.
        */
-      if (strncmp(sql_type.c_ptr_safe(), table_def->type.str,
-                  table_def->type.length - 1))
+      if (strncmp(sql_type.c_ptr_safe(), field_def->type.str,
+                  field_def->type.length - 1))
       {
-        sql_print_error("Incorrect definition of table %s.%s: "
-                        "expected column '%s' at position %d to have type "
-                        "%s, found type %s.", table->s->db.str, table->alias,
-                        table_def->name.str, i, table_def->type.str,
-                        sql_type.c_ptr_safe());
+        report_error(0, "Incorrect definition of table %s.%s: "
+                     "expected column '%s' at position %d to have type "
+                     "%s, found type %s.", table->s->db.str, table->alias,
+                     field_def->name.str, i, field_def->type.str,
+                     sql_type.c_ptr_safe());
         error= TRUE;
       }
-      else if (table_def->cset.str && !field->has_charset())
+      else if (field_def->cset.str && !field->has_charset())
       {
-        sql_print_error("Incorrect definition of table %s.%s: "
-                        "expected the type of column '%s' at position %d "
-                        "to have character set '%s' but the type has no "
-                        "character set.", table->s->db.str, table->alias,
-                        table_def->name.str, i, table_def->cset.str);
+        report_error(0, "Incorrect definition of table %s.%s: "
+                     "expected the type of column '%s' at position %d "
+                     "to have character set '%s' but the type has no "
+                     "character set.", table->s->db.str, table->alias,
+                     field_def->name.str, i, field_def->cset.str);
         error= TRUE;
       }
-      else if (table_def->cset.str &&
-               strcmp(field->charset()->csname, table_def->cset.str))
+      else if (field_def->cset.str &&
+               strcmp(field->charset()->csname, field_def->cset.str))
       {
-        sql_print_error("Incorrect definition of table %s.%s: "
-                        "expected the type of column '%s' at position %d "
-                        "to have character set '%s' but found "
-                        "character set '%s'.", table->s->db.str, table->alias,
-                        table_def->name.str, i, table_def->cset.str,
-                        field->charset()->csname);
+        report_error(0, "Incorrect definition of table %s.%s: "
+                     "expected the type of column '%s' at position %d "
+                     "to have character set '%s' but found "
+                     "character set '%s'.", table->s->db.str, table->alias,
+                     field_def->name.str, i, field_def->cset.str,
+                     field->charset()->csname);
         error= TRUE;
       }
     }
     else
     {
-      sql_print_error("Incorrect definition of table %s.%s: "
-                      "expected column '%s' at position %d to have type %s "
-                      " but the column is not found.",
-                      table->s->db.str, table->alias,
-                      table_def->name.str, i, table_def->type.str);
+      report_error(0, "Incorrect definition of table %s.%s: "
+                   "expected column '%s' at position %d to have type %s "
+                   " but the column is not found.",
+                   table->s->db.str, table->alias,
+                   field_def->name.str, i, field_def->type.str);
       error= TRUE;
     }
   }
+
+  if (! error)
+    table->s->table_field_def_cache= table_def;
+
   DBUG_RETURN(error);
 }
 

=== modified file 'sql/table.h'
--- a/sql/table.h	2009-12-03 11:19:05 +0000
+++ b/sql/table.h	2010-01-15 15:27:55 +0000
@@ -285,6 +285,36 @@ typedef enum enum_table_category TABLE_C
 TABLE_CATEGORY get_table_category(const LEX_STRING *db,
                                   const LEX_STRING *name);
 
+
+typedef struct st_table_field_type
+{
+  LEX_STRING name;
+  LEX_STRING type;
+  LEX_STRING cset;
+} TABLE_FIELD_TYPE;
+
+
+typedef struct st_table_field_def
+{
+  uint count;
+  const TABLE_FIELD_TYPE *field;
+} TABLE_FIELD_DEF;
+
+
+class Table_check_intact
+{
+protected:
+  virtual void report_error(uint code, const char *fmt, ...)= 0;
+
+public:
+  Table_check_intact() {}
+  virtual ~Table_check_intact() {}
+
+  /** Checks whether a table is intact. */
+  bool check(TABLE *table, const TABLE_FIELD_DEF *table_def);
+};
+
+
 /*
   This structure is shared between different table objects. There is one
   instance of table share per one table in the database.
@@ -423,6 +453,18 @@ typedef struct st_table_share
   handlerton *default_part_db_type;
 #endif
 
+  /**
+    Cache the checked structure of this table.
+
+    The pointer data is used to describe the structure that
+    a instance of the table must have. Each element of the
+    array specifies a field that must exist on the table.
+
+    The pointer is cached in order to perform the check only
+    once -- when the table is loaded from the disk.
+  */
+  const TABLE_FIELD_DEF *table_field_def_cache;
+
   /** place to store storage engine specific data */
   void *ha_data;
 
@@ -1674,17 +1716,6 @@ typedef struct st_open_table_list{
   uint32 in_use,locked;
 } OPEN_TABLE_LIST;
 
-typedef struct st_table_field_w_type
-{
-  LEX_STRING name;
-  LEX_STRING type;
-  LEX_STRING cset;
-} TABLE_FIELD_W_TYPE;
-
-
-my_bool
-table_check_intact(TABLE *table, const uint table_f_count,
-                   const TABLE_FIELD_W_TYPE *table_def);
 
 static inline my_bitmap_map *tmp_use_all_columns(TABLE *table,
                                                  MY_BITMAP *bitmap)

=== modified file 'storage/archive/CMakeLists.txt' (properties changed: -x to +x)
--- a/storage/archive/CMakeLists.txt	2009-06-10 08:59:49 +0000
+++ b/storage/archive/CMakeLists.txt	2009-11-10 19:41:43 +0000
@@ -13,6 +13,9 @@
 # along with this program; if not, write to the Free Software
 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX")
+SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX")
+
 INCLUDE("${PROJECT_SOURCE_DIR}/storage/mysql_storage_engine.cmake")
 SET(ARCHIVE_SOURCES  azio.c ha_archive.cc ha_archive.h)
 MYSQL_STORAGE_ENGINE(ARCHIVE)

=== modified file 'storage/archive/azio.c'
--- a/storage/archive/azio.c	2009-05-22 12:38:50 +0000
+++ b/storage/archive/azio.c	2010-01-15 15:27:55 +0000
@@ -71,7 +71,8 @@ int az_open (azio_stream *s, const char
   s->transparent = 0;
   s->mode = 'r';
   s->version = (unsigned char)az_magic[1]; /* this needs to be a define to version */
-  s->version = (unsigned char)az_magic[2]; /* minor version */
+  s->minor_version= (unsigned char) az_magic[2]; /* minor version */
+  s->dirty= AZ_STATE_CLEAN;
 
   /*
     We do our own version of append by nature. 
@@ -354,10 +355,19 @@ void read_header(azio_stream *s, unsigne
     s->comment_length= (unsigned int)uint4korr(buffer + AZ_COMMENT_LENGTH_POS);
     s->dirty= (unsigned int)buffer[AZ_DIRTY_POS];
   }
-  else
+  else if (buffer[0] == gz_magic[0]  && buffer[1] == gz_magic[1])
   {
-    DBUG_ASSERT(buffer[0] == az_magic[0]  && buffer[1] == az_magic[1]);
-    return;
+    /*
+      Set version number to previous version (2).
+    */
+    s->version= (unsigned char) 2;
+  } else {
+    /*
+      Unknown version.
+      Most probably due to a corrupt archive.
+    */
+    s->dirty= AZ_STATE_DIRTY;
+    s->z_err= Z_VERSION_ERROR;
   }
 }
 

=== modified file 'storage/archive/azlib.h'
--- a/storage/archive/azlib.h	2009-02-13 16:41:47 +0000
+++ b/storage/archive/azlib.h	2010-01-06 21:27:53 +0000
@@ -33,10 +33,9 @@
   (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
 */
 
-#include <zlib.h>
-
 #include "../../mysys/mysys_priv.h"
 #include <my_dir.h>
+#include <zlib.h>
 
 #ifdef  __cplusplus
 extern "C" {

=== modified file 'storage/archive/ha_archive.cc'
--- a/storage/archive/ha_archive.cc	2009-12-03 11:19:05 +0000
+++ b/storage/archive/ha_archive.cc	2010-01-15 15:27:55 +0000
@@ -360,6 +360,12 @@ ARCHIVE_SHARE *ha_archive::get_share(con
     stats.auto_increment_value= archive_tmp.auto_increment + 1;
     share->rows_recorded= (ha_rows)archive_tmp.rows;
     share->crashed= archive_tmp.dirty;
+    /*
+      If archive version is less than 3, It should be upgraded before
+      use.
+    */
+    if (archive_tmp.version < ARCHIVE_VERSION)
+      *rc= HA_ERR_TABLE_NEEDS_UPGRADE;
     azclose(&archive_tmp);
 
     VOID(my_hash_insert(&archive_open_tables, (uchar*) share));
@@ -491,7 +497,15 @@ int ha_archive::open(const char *name, i
                       (open_options & HA_OPEN_FOR_REPAIR) ? "yes" : "no"));
   share= get_share(name, &rc);
 
-  if (rc == HA_ERR_CRASHED_ON_USAGE && !(open_options & HA_OPEN_FOR_REPAIR))
+ /*
+    Allow open on crashed table in repair mode only.
+    Block open on 5.0 ARCHIVE table. Though we have almost all
+    routines to access these tables, they were not well tested.
+    For now we have to refuse to open such table to avoid
+    potential data loss.
+  */
+  if ((rc == HA_ERR_CRASHED_ON_USAGE && !(open_options & HA_OPEN_FOR_REPAIR))
+      ||  rc == HA_ERR_TABLE_NEEDS_UPGRADE)
   {
     /* purecov: begin inspected */
     free_share();

=== modified file 'storage/federated/CMakeLists.txt' (properties changed: -x to +x)
--- a/storage/federated/CMakeLists.txt	2009-06-10 08:59:49 +0000
+++ b/storage/federated/CMakeLists.txt	2009-11-10 19:41:43 +0000
@@ -1,18 +1,21 @@
 # Copyright (C) 2006 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
+SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX")
+SET(CMAKE_C_FLAGS_DEBUG "${CMAKE_C_FLAGS_DEBUG} -DSAFEMALLOC -DSAFE_MUTEX")
+
 INCLUDE("${PROJECT_SOURCE_DIR}/storage/mysql_storage_engine.cmake")
 SET(FEDERATED_SOURCES  ha_federated.cc)
 MYSQL_STORAGE_ENGINE(FEDERATED)

=== modified file 'storage/innobase/btr/btr0btr.c'
--- a/storage/innobase/btr/btr0btr.c	2007-07-10 14:34:21 +0000
+++ b/storage/innobase/btr/btr0btr.c	2009-11-30 08:50:08 +0000
@@ -709,8 +709,15 @@ btr_create(
 	} else {
 		/* It is a non-ibuf tree: create a file segment for leaf
 		pages */
-		fseg_create(space, page_no, PAGE_HEADER + PAGE_BTR_SEG_LEAF,
-			    mtr);
+		if (!fseg_create(space, page_no,
+				 PAGE_HEADER + PAGE_BTR_SEG_LEAF, mtr)) {
+			/* Not enough space for new segment, free root
+			segment before return. */
+			btr_free_root(space, page_no, mtr);
+
+			return(FIL_NULL);
+		}
+
 		/* The fseg create acquires a second latch on the page,
 		therefore we must declare it: */
 #ifdef UNIV_SYNC_DEBUG

=== modified file 'storage/innobase/data/data0type.c'
--- a/storage/innobase/data/data0type.c	2007-07-10 11:37:43 +0000
+++ b/storage/innobase/data/data0type.c	2009-11-30 08:53:52 +0000
@@ -252,6 +252,22 @@ dtype_print(
 		fputs("DATA_SYS", stderr);
 		break;
 
+	case DATA_FLOAT:
+		fputs("DATA_FLOAT", stderr);
+		break;
+
+	case DATA_DOUBLE:
+		fputs("DATA_DOUBLE", stderr);
+		break;
+
+	case DATA_DECIMAL:
+		fputs("DATA_DECIMAL", stderr);
+		break;
+
+	case DATA_VARMYSQL:
+		fputs("DATA_VARMYSQL", stderr);
+		break;
+
 	default:
 		fprintf(stderr, "type %lu", (ulong) mtype);
 		break;

=== modified file 'storage/innobase/handler/ha_innodb.cc'
--- a/storage/innobase/handler/ha_innodb.cc	2009-12-03 11:19:05 +0000
+++ b/storage/innobase/handler/ha_innodb.cc	2010-01-15 15:27:55 +0000
@@ -662,6 +662,12 @@ convert_error_code_to_mysql(
 
 	} else if (error == (int) DB_DUPLICATE_KEY) {
 
+		/* Be cautious with returning this error, since
+		mysql could re-enter the storage layer to get
+		duplicated key info, the operation requires a
+		valid table handle and/or transaction information,
+		which might not always be available in the error
+		handling stage. */
 		return(HA_ERR_FOUND_DUPP_KEY);
 
 	} else if (error == (int) DB_FOREIGN_DUPLICATE_KEY) {
@@ -765,35 +771,6 @@ convert_error_code_to_mysql(
 }
 
 /*****************************************************************
-If you want to print a thd that is not associated with the current thread,
-you must call this function before reserving the InnoDB kernel_mutex, to
-protect MySQL from setting thd->query NULL. If you print a thd of the current
-thread, we know that MySQL cannot modify thd->query, and it is not necessary
-to call this. Call innobase_mysql_end_print_arbitrary_thd() after you release
-the kernel_mutex.
-NOTE that /mysql/innobase/lock/lock0lock.c must contain the prototype for this
-function! */
-extern "C"
-void
-innobase_mysql_prepare_print_arbitrary_thd(void)
-/*============================================*/
-{
-	VOID(pthread_mutex_lock(&LOCK_thread_count));
-}
-
-/*****************************************************************
-Releases the mutex reserved by innobase_mysql_prepare_print_arbitrary_thd().
-NOTE that /mysql/innobase/lock/lock0lock.c must contain the prototype for this
-function! */
-extern "C"
-void
-innobase_mysql_end_print_arbitrary_thd(void)
-/*========================================*/
-{
-	VOID(pthread_mutex_unlock(&LOCK_thread_count));
-}
-
-/*****************************************************************
 Prints info of a THD object (== user session thread) to the given file.
 NOTE that /mysql/innobase/trx/trx0trx.c must contain the prototype for
 this function! */
@@ -1499,70 +1476,148 @@ innobase_invalidate_query_cache(
 #endif
 }
 
-/*********************************************************************
-Display an SQL identifier. */
-extern "C"
-void
-innobase_print_identifier(
-/*======================*/
-	FILE*		f,	/* in: output stream */
-	trx_t*		trx,	/* in: transaction */
-	ibool		table_id,/* in: TRUE=print a table name,
-				FALSE=print other identifier */
-	const char*	name,	/* in: name to print */
-	ulint		namelen)/* in: length of name */
-{
-	const char*	s	= name;
-	char*		qname	= NULL;
+/*****************************************************************//**
+Convert an SQL identifier to the MySQL system_charset_info (UTF-8)
+and quote it if needed.
+@return	pointer to the end of buf */
+static
+char*
+innobase_convert_identifier(
+/*========================*/
+	char*		buf,	/*!< out: buffer for converted identifier */
+	ulint		buflen,	/*!< in: length of buf, in bytes */
+	const char*	id,	/*!< in: identifier to convert */
+	ulint		idlen,	/*!< in: length of id, in bytes */
+	void*		thd,	/*!< in: MySQL connection thread, or NULL */
+	ibool		file_id)/*!< in: TRUE=id is a table or database name;
+				FALSE=id is an UTF-8 string */
+{
+	char nz[NAME_LEN + 1];
+#if MYSQL_VERSION_ID >= 50141
+	char nz2[NAME_LEN + 1 + EXPLAIN_FILENAME_MAX_EXTRA_LENGTH];
+#else /* MYSQL_VERSION_ID >= 50141 */
+	char nz2[NAME_LEN + 1 + sizeof srv_mysql50_table_name_prefix];
+#endif /* MYSQL_VERSION_ID >= 50141 */
+
+	const char*	s	= id;
 	int		q;
 
-	if (table_id) {
-		/* Decode the table name.  The filename_to_tablename()
-		function expects a NUL-terminated string.  The input and
-		output strings buffers must not be shared.  The function
-		only produces more output when the name contains other
-		characters than [0-9A-Z_a-z]. */
-          char*	temp_name = (char*) my_malloc((uint) namelen + 1, MYF(MY_WME));
-          uint	qnamelen = (uint) (namelen
-                                   + (1 + sizeof srv_mysql50_table_name_prefix));
-
-		if (temp_name) {
-                  qname = (char*) my_malloc(qnamelen, MYF(MY_WME));
-			if (qname) {
-				memcpy(temp_name, name, namelen);
-				temp_name[namelen] = 0;
-				s = qname;
-				namelen = filename_to_tablename(temp_name,
-						qname, qnamelen);
-			}
-			my_free(temp_name, MYF(0));
-		}
+	if (file_id) {
+		/* Decode the table name.  The MySQL function expects
+		a NUL-terminated string.  The input and output strings
+		buffers must not be shared. */
+
+		if (UNIV_UNLIKELY(idlen > (sizeof nz) - 1)) {
+			idlen = (sizeof nz) - 1;
+		}
+
+		memcpy(nz, id, idlen);
+		nz[idlen] = 0;
+
+		s = nz2;
+#if MYSQL_VERSION_ID >= 50141
+		idlen = explain_filename((THD*) thd, nz, nz2, sizeof nz2,
+					 EXPLAIN_PARTITIONS_AS_COMMENT);
+		goto no_quote;
+#else /* MYSQL_VERSION_ID >= 50141 */
+		idlen = filename_to_tablename(nz, nz2, sizeof nz2);
+#endif /* MYSQL_VERSION_ID >= 50141 */
 	}
 
-	if (!trx || !trx->mysql_thd) {
-
+	/* See if the identifier needs to be quoted. */
+	if (UNIV_UNLIKELY(!thd)) {
 		q = '"';
 	} else {
-		q = get_quote_char_for_identifier((THD*) trx->mysql_thd,
-						s, (int) namelen);
+		q = get_quote_char_for_identifier((THD*) thd, s, (int) idlen);
 	}
 
 	if (q == EOF) {
-		fwrite(s, 1, namelen, f);
-	} else {
-		const char*	e = s + namelen;
-		putc(q, f);
-		while (s < e) {
-			int	c = *s++;
-			if (c == q) {
-				putc(c, f);
+#if MYSQL_VERSION_ID >= 50141
+no_quote:
+#endif /* MYSQL_VERSION_ID >= 50141 */
+		if (UNIV_UNLIKELY(idlen > buflen)) {
+			idlen = buflen;
+		}
+		memcpy(buf, s, idlen);
+		return(buf + idlen);
+	}
+
+	/* Quote the identifier. */
+	if (buflen < 2) {
+		return(buf);
+	}
+
+	*buf++ = q;
+	buflen--;
+
+	for (; idlen; idlen--) {
+		int	c = *s++;
+		if (UNIV_UNLIKELY(c == q)) {
+			if (UNIV_UNLIKELY(buflen < 3)) {
+				break;
+			}
+
+			*buf++ = c;
+			*buf++ = c;
+			buflen -= 2;
+		} else {
+			if (UNIV_UNLIKELY(buflen < 2)) {
+				break;
 			}
-			putc(c, f);
+
+			*buf++ = c;
+			buflen--;
+		}
+	}
+
+	*buf++ = q;
+	return(buf);
+}
+
+/*****************************************************************//**
+Convert a table or index name to the MySQL system_charset_info (UTF-8)
+and quote it if needed.
+@return	pointer to the end of buf */
+extern "C"
+char*
+innobase_convert_name(
+/*==================*/
+	char*		buf,	/*!< out: buffer for converted identifier */
+	ulint		buflen,	/*!< in: length of buf, in bytes */
+	const char*	id,	/*!< in: identifier to convert */
+	ulint		idlen,	/*!< in: length of id, in bytes */
+	void*		thd,	/*!< in: MySQL connection thread, or NULL */
+	ibool		table_id)/*!< in: TRUE=id is a table or database name;
+				FALSE=id is an index name */
+{
+	char*		s	= buf;
+	const char*	bufend	= buf + buflen;
+
+	if (table_id) {
+		const char*	slash = (const char*) memchr(id, '/', idlen);
+		if (!slash) {
+
+			goto no_db_name;
 		}
-		putc(q, f);
+
+		/* Print the database name and table name separately. */
+		s = innobase_convert_identifier(s, bufend - s, id, slash - id,
+						thd, TRUE);
+		if (UNIV_LIKELY(s < bufend)) {
+			*s++ = '.';
+			s = innobase_convert_identifier(s, bufend - s,
+							slash + 1, idlen
+							- (slash - id) - 1,
+							thd, TRUE);
+		}
+	} else {
+no_db_name:
+		s = innobase_convert_identifier(buf, buflen, id, idlen,
+						thd, table_id);
 	}
 
-	my_free(qname, MYF(MY_ALLOW_ZERO_PTR));
+	return(s);
+
 }
 
 /**************************************************************************
@@ -3986,24 +4041,29 @@ no_commit:
 			update the table upper limit. Note: last_value
 			will be 0 if get_auto_increment() was not called.*/
 
-			if (auto_inc <= col_max_value
-			    && auto_inc >= prebuilt->autoinc_last_value) {
+			if (auto_inc >= prebuilt->autoinc_last_value) {
 set_max_autoinc:
-				ut_a(prebuilt->autoinc_increment > 0);
-
-				ulonglong	need;
-				ulonglong	offset;
-
-				offset = prebuilt->autoinc_offset;
-				need = prebuilt->autoinc_increment;
-
-				auto_inc = innobase_next_autoinc(
-					auto_inc, need, offset, col_max_value);
-
-				err = innobase_set_max_autoinc(auto_inc);
-
-				if (err != DB_SUCCESS) {
-					error = err;
+				/* This should filter out the negative
+				values set explicitly by the user. */
+				if (auto_inc <= col_max_value) {
+					ut_a(prebuilt->autoinc_increment > 0);
+
+					ulonglong	need;
+					ulonglong	offset;
+
+					offset = prebuilt->autoinc_offset;
+					need = prebuilt->autoinc_increment;
+
+					auto_inc = innobase_next_autoinc(
+						auto_inc,
+						need, offset, col_max_value);
+
+					err = innobase_set_max_autoinc(
+						auto_inc);
+
+					if (err != DB_SUCCESS) {
+						error = err;
+					}
 				}
 			}
 			break;
@@ -5970,6 +6030,24 @@ ha_innobase::rename_table(
 	innobase_commit_low(trx);
 	trx_free_for_mysql(trx);
 
+	/* Add a special case to handle the Duplicated Key error
+	and return DB_ERROR instead.
+	This is to avoid a possible SIGSEGV error from mysql error
+	handling code. Currently, mysql handles the Duplicated Key
+	error by re-entering the storage layer and getting dup key
+	info by calling get_dup_key(). This operation requires a valid
+	table handle ('row_prebuilt_t' structure) which could no
+	longer be available in the error handling stage. The suggested
+	solution is to report a 'table exists' error message (since
+	the dup key error here is due to an existing table whose name
+	is the one we are trying to rename to) and return the generic
+	error code. */
+	if (error == (int) DB_DUPLICATE_KEY) {
+		my_error(ER_TABLE_EXISTS_ERROR, MYF(0), to);
+
+		error = DB_ERROR;
+	}
+
 	error = convert_error_code_to_mysql(error, NULL);
 
 	DBUG_RETURN(error);
@@ -8204,8 +8282,7 @@ innobase_xa_prepare(
 		executing XA PREPARE and XA COMMIT commands.
 		In this case we cannot know how many minutes or hours
 		will be between XA PREPARE and XA COMMIT, and we don't want
-		to block for undefined period of time.
-		*/
+		to block for undefined period of time. */
 		pthread_mutex_lock(&prepare_commit_mutex);
 		trx->active_trans = 2;
 	}

=== modified file 'storage/innobase/include/ha_prototypes.h'
--- a/storage/innobase/include/ha_prototypes.h	2008-12-14 19:28:19 +0000
+++ b/storage/innobase/include/ha_prototypes.h	2009-11-30 08:26:45 +0000
@@ -24,18 +24,21 @@ innobase_convert_string(
 	CHARSET_INFO*	from_cs,
 	uint*		errors);
 
-/*********************************************************************
-Display an SQL identifier. */
+/*****************************************************************//**
+Convert a table or index name to the MySQL system_charset_info (UTF-8)
+and quote it if needed.
+@return	pointer to the end of buf */
 
-void
-innobase_print_identifier(
-/*======================*/
-	FILE*		f,	/* in: output stream */
-	trx_t*		trx,	/* in: transaction */
-	ibool		table_id,/* in: TRUE=print a table name,
-				FALSE=print other identifier */
-	const char*	name,	/* in: name to print */
-	ulint		namelen);/* in: length of name */
+char*
+innobase_convert_name(
+/*==================*/
+	char*		buf,	/*!< out: buffer for converted identifier */
+	ulint		buflen,	/*!< in: length of buf, in bytes */
+	const char*	id,	/*!< in: identifier to convert */
+	ulint		idlen,	/*!< in: length of id, in bytes */
+	void*		thd,	/*!< in: MySQL connection thread, or NULL */
+	ibool		table_id);/*!< in: TRUE=id is a table or database name;
+				FALSE=id is an index name */
 
 /**********************************************************************
 Returns true if the thread is the replication thread on the slave

=== modified file 'storage/innobase/include/mach0data.h'
--- a/storage/innobase/include/mach0data.h	2008-08-20 00:37:41 +0000
+++ b/storage/innobase/include/mach0data.h	2009-11-30 09:41:38 +0000
@@ -266,8 +266,8 @@ UNIV_INLINE
 double
 mach_double_read(
 /*=============*/
-			/* out: double read */
-	byte*	b);	 /* in: pointer to memory from where to read */
+				/* out: double read */
+	const byte*	b);	 /* in: pointer to memory from where to read */
 /*************************************************************
 Writes a double. It is stored in a little-endian format. */
 UNIV_INLINE
@@ -282,8 +282,8 @@ UNIV_INLINE
 float
 mach_float_read(
 /*============*/
-			/* out: float read */
-	byte*	b);	 /* in: pointer to memory from where to read */
+				/* out: float read */
+	const byte*	b);	 /* in: pointer to memory from where to read */
 /*************************************************************
 Writes a float. It is stored in a little-endian format. */
 UNIV_INLINE

=== modified file 'storage/innobase/include/mach0data.ic'
--- a/storage/innobase/include/mach0data.ic	2008-08-20 00:37:41 +0000
+++ b/storage/innobase/include/mach0data.ic	2009-11-30 09:41:38 +0000
@@ -504,8 +504,8 @@ UNIV_INLINE
 double
 mach_double_read(
 /*=============*/
-			/* out: double read */
-	byte*	b)	/* in: pointer to memory from where to read */
+				/* out: double read */
+	const byte*	b)	/* in: pointer to memory from where to read */
 {
 	double	d;
 	ulint	i;
@@ -553,8 +553,8 @@ UNIV_INLINE
 float
 mach_float_read(
 /*============*/
-			/* out: float read */
-	byte*	b)	/* in: pointer to memory from where to read */
+				/* out: float read */
+	const byte*	b)	/* in: pointer to memory from where to read */
 {
 	float	d;
 	ulint	i;

=== modified file 'storage/innobase/include/os0file.h'
--- a/storage/innobase/include/os0file.h	2007-07-10 14:34:21 +0000
+++ b/storage/innobase/include/os0file.h	2009-11-30 08:40:31 +0000
@@ -96,6 +96,8 @@ log. */
 						to become available again */
 #define	OS_FILE_SHARING_VIOLATION	76
 #define	OS_FILE_ERROR_NOT_SPECIFIED	77
+						/* 78 is used in the plugin */
+#define	OS_FILE_OPERATION_ABORTED	79
 
 /* Types for aio operations */
 #define OS_FILE_READ	10

=== modified file 'storage/innobase/include/trx0trx.h'
--- a/storage/innobase/include/trx0trx.h	2009-07-10 23:12:13 +0000
+++ b/storage/innobase/include/trx0trx.h	2009-12-01 10:38:40 +0000
@@ -318,9 +318,7 @@ trx_commit_step(
 
 /**************************************************************************
 Prints info about a transaction to the given file. The caller must own the
-kernel mutex and must have called
-innobase_mysql_prepare_print_arbitrary_thd(), unless he knows that MySQL
-or InnoDB cannot meanwhile change the info printed here. */
+kernel mutex. */
 
 void
 trx_print(

=== modified file 'storage/innobase/lock/lock0lock.c'
--- a/storage/innobase/lock/lock0lock.c	2009-07-10 23:12:13 +0000
+++ b/storage/innobase/lock/lock0lock.c	2009-12-01 10:38:40 +0000
@@ -22,31 +22,6 @@ Created 5/7/1996 Heikki Tuuri
 #include "trx0sys.h"
 
 
-/* 2 function prototypes copied from ha_innodb.cc: */
-
-/*****************************************************************
-If you want to print a thd that is not associated with the current thread,
-you must call this function before reserving the InnoDB kernel_mutex, to
-protect MySQL from setting thd->query NULL. If you print a thd of the current
-thread, we know that MySQL cannot modify thd->query, and it is not necessary
-to call this. Call innobase_mysql_end_print_arbitrary_thd() after you release
-the kernel_mutex.
-NOTE that /mysql/innobase/lock/lock0lock.c must contain the prototype for this
-function! */
-
-void
-innobase_mysql_prepare_print_arbitrary_thd(void);
-/*============================================*/
-
-/*****************************************************************
-Relases the mutex reserved by innobase_mysql_prepare_print_arbitrary_thd().
-NOTE that /mysql/innobase/lock/lock0lock.c must contain the prototype for this
-function! */
-
-void
-innobase_mysql_end_print_arbitrary_thd(void);
-/*========================================*/
-
 /* Restricts the length of search we will do in the waits-for
 graph of transactions */
 #define LOCK_MAX_N_STEPS_IN_DEADLOCK_CHECK 1000000
@@ -4222,11 +4197,6 @@ lock_print_info_summary(
 /*====================*/
 	FILE*	file)	/* in: file where to print */
 {
-	/* We must protect the MySQL thd->query field with a MySQL mutex, and
-	because the MySQL mutex must be reserved before the kernel_mutex of
-	InnoDB, we call innobase_mysql_prepare_print_arbitrary_thd() here. */
-
-	innobase_mysql_prepare_print_arbitrary_thd();
 	lock_mutex_enter_kernel();
 
 	if (lock_deadlock_found) {
@@ -4314,7 +4284,6 @@ loop:
 
 	if (trx == NULL) {
 		lock_mutex_exit_kernel();
-		innobase_mysql_end_print_arbitrary_thd();
 
 		ut_ad(lock_validate());
 
@@ -4386,7 +4355,6 @@ loop:
 
 		if (load_page_first) {
 			lock_mutex_exit_kernel();
-			innobase_mysql_end_print_arbitrary_thd();
 
 			mtr_start(&mtr);
 
@@ -4397,7 +4365,6 @@ loop:
 
 			load_page_first = FALSE;
 
-			innobase_mysql_prepare_print_arbitrary_thd();
 			lock_mutex_enter_kernel();
 
 			goto loop;

=== modified file 'storage/innobase/os/os0file.c'
--- a/storage/innobase/os/os0file.c	2008-12-14 19:15:12 +0000
+++ b/storage/innobase/os/os0file.c	2009-11-30 08:40:31 +0000
@@ -257,6 +257,13 @@ os_file_get_last_error(
 				" software or another instance\n"
 				"InnoDB: of MySQL."
 				" Please close it to get rid of this error.\n");
+		} else if (err == ERROR_OPERATION_ABORTED) {
+			fprintf(stderr,
+				"InnoDB: The error means that the I/O"
+				" operation has been aborted\n"
+				"InnoDB: because of either a thread exit"
+				" or an application request.\n"
+				"InnoDB: Retry attempt is made.\n");
 		} else {
 			fprintf(stderr,
 				"InnoDB: Some operating system error numbers"
@@ -278,6 +285,8 @@ os_file_get_last_error(
 	} else if (err == ERROR_SHARING_VIOLATION
 		   || err == ERROR_LOCK_VIOLATION) {
 		return(OS_FILE_SHARING_VIOLATION);
+	} else if (err == ERROR_OPERATION_ABORTED) {
+		return(OS_FILE_OPERATION_ABORTED);
 	} else {
 		return(100 + err);
 	}
@@ -402,6 +411,10 @@ os_file_handle_error_cond_exit(
 
 		os_thread_sleep(10000000);  /* 10 sec */
 		return(TRUE);
+	} else if (err == OS_FILE_OPERATION_ABORTED) {
+
+		os_thread_sleep(100000);	/* 100 ms */
+		return(TRUE);
 	} else {
 		if (name) {
 			fprintf(stderr, "InnoDB: File name %s\n", name);
@@ -3692,6 +3705,7 @@ os_aio_windows_handle(
 	ibool		ret_val;
 	BOOL		ret;
 	DWORD		len;
+	BOOL		retry		= FALSE;
 
 	if (segment == ULINT_UNDEFINED) {
 		array = os_aio_sync_array;
@@ -3745,14 +3759,52 @@ os_aio_windows_handle(
 			ut_a(TRUE == os_file_flush(slot->file));
 		}
 # endif /* UNIV_DO_FLUSH */
+	} else if (os_file_handle_error(slot->name, "Windows aio")) {
+
+		retry = TRUE;
 	} else {
-		os_file_handle_error(slot->name, "Windows aio");
 
 		ret_val = FALSE;
 	}
 
 	os_mutex_exit(array->mutex);
 
+	if (retry) {
+		/* retry failed read/write operation synchronously.
+		No need to hold array->mutex. */
+
+		switch (slot->type) {
+		case OS_FILE_WRITE:
+			ret = WriteFile(slot->file, slot->buf,
+					slot->len, &len,
+					&(slot->control));
+
+			break;
+		case OS_FILE_READ:
+			ret = ReadFile(slot->file, slot->buf,
+				       slot->len, &len,
+				       &(slot->control));
+
+			break;
+		default:
+			ut_error;
+		}
+
+		if (!ret && GetLastError() == ERROR_IO_PENDING) {
+			/* aio was queued successfully!
+			We want a synchronous i/o operation on a
+			file where we also use async i/o: in Windows
+			we must use the same wait mechanism as for
+			async i/o */
+
+			ret = GetOverlappedResult(slot->file,
+						  &(slot->control),
+						  &len, TRUE);
+		}
+
+		ret_val = ret && len == slot->len;
+	}
+
 	os_aio_array_free_slot(array, slot);
 
 	return(ret_val);

=== modified file 'storage/innobase/row/row0sel.c'
--- a/storage/innobase/row/row0sel.c	2009-07-10 23:12:13 +0000
+++ b/storage/innobase/row/row0sel.c	2009-11-30 09:41:38 +0000
@@ -4514,6 +4514,7 @@ row_search_autoinc_read_column(
 	dict_index_t*	index,		/* in: index to read from */
 	const rec_t*	rec,		/* in: current rec */
 	ulint		col_no,		/* in: column number */
+	ulint		mtype,		/*!< in: column main type */
 	ibool		unsigned_type)	/* in: signed or unsigned flag */
 {
 	ulint		len;
@@ -4535,9 +4536,26 @@ row_search_autoinc_read_column(
 	data = rec_get_nth_field((rec_t*)rec, offsets, col_no, &len);
 
 	ut_a(len != UNIV_SQL_NULL);
-	ut_a(len <= sizeof value);
 
-	value = mach_read_int_type(data, len, unsigned_type);
+	switch (mtype) {
+	case DATA_INT:
+		ut_a(len <= sizeof value);
+		value = mach_read_int_type(data, len, unsigned_type);
+		break;
+
+	case DATA_FLOAT:
+		ut_a(len == sizeof(float));
+		value = mach_float_read(data);
+		break;
+
+	case DATA_DOUBLE:
+		ut_a(len == sizeof(double));
+		value = mach_double_read(data);
+		break;
+
+	default:
+		ut_error;
+	}
 
 	if (UNIV_LIKELY_NULL(heap)) {
 		mem_heap_free(heap);
@@ -4625,7 +4643,8 @@ row_search_max_autoinc(
 					dfield->col->prtype & DATA_UNSIGNED);
 
 				*value = row_search_autoinc_read_column(
-					index, rec, i, unsigned_type);
+					index, rec, i,
+					dfield->col->mtype, unsigned_type);
 			}
 		}
 

=== modified file 'storage/innobase/trx/trx0trx.c'
--- a/storage/innobase/trx/trx0trx.c	2009-07-10 23:12:13 +0000
+++ b/storage/innobase/trx/trx0trx.c	2009-12-01 10:38:40 +0000
@@ -1652,9 +1652,7 @@ trx_mark_sql_stat_end(
 
 /**************************************************************************
 Prints info about a transaction to the given file. The caller must own the
-kernel mutex and must have called
-innobase_mysql_prepare_print_arbitrary_thd(), unless he knows that MySQL
-or InnoDB cannot meanwhile change the info printed here. */
+kernel mutex. */
 
 void
 trx_print(

=== modified file 'storage/innobase/ut/ut0ut.c'
--- a/storage/innobase/ut/ut0ut.c	2008-12-14 19:18:59 +0000
+++ b/storage/innobase/ut/ut0ut.c	2009-11-30 08:26:45 +0000
@@ -19,6 +19,7 @@ Created 5/11/1994 Heikki Tuuri
 #include "ut0sort.h"
 #include "trx0trx.h"
 #include "ha_prototypes.h"
+#include "mysql_com.h" /* NAME_LEN */
 
 ibool	ut_always_false	= FALSE;
 
@@ -484,26 +485,17 @@ ut_print_namel(
 	const char*	name,	/* in: name to print */
 	ulint		namelen)/* in: length of name */
 {
-#ifdef UNIV_HOTBACKUP
-	fwrite(name, 1, namelen, f);
-#else
-	if (table_id) {
-		char*	slash = memchr(name, '/', namelen);
-		if (!slash) {
-
-			goto no_db_name;
-		}
+	/* 2 * NAME_LEN for database and table name,
+	and some slack for the #mysql50# prefix and quotes */
+	char		buf[3 * NAME_LEN];
+	const char*	bufend;
+
+	bufend = innobase_convert_name(buf, sizeof buf,
+				       name, namelen,
+				       trx ? trx->mysql_thd : NULL,
+				       table_id);
 
-		/* Print the database name and table name separately. */
-		innobase_print_identifier(f, trx, TRUE, name, slash - name);
-		putc('.', f);
-		innobase_print_identifier(f, trx, TRUE, slash + 1,
-					  namelen - (slash - name) - 1);
-	} else {
-no_db_name:
-		innobase_print_identifier(f, trx, table_id, name, namelen);
-	}
-#endif
+	fwrite(buf, 1, bufend - buf, f);
 }
 
 /**************************************************************************

=== modified file 'storage/innodb_plugin/CMakeLists.txt'
--- a/storage/innodb_plugin/CMakeLists.txt	2009-12-03 11:19:05 +0000
+++ b/storage/innodb_plugin/CMakeLists.txt	2010-01-15 15:27:55 +0000
@@ -83,4 +83,4 @@ SET(INNODB_PLUGIN_SOURCES	btr/btr0btr.c
 ADD_DEFINITIONS(-DHAVE_WINDOWS_ATOMICS -DIB_HAVE_PAUSE_INSTRUCTION)
 
 #Disable storage engine, as we are using XtraDB
-#MYSQL_STORAGE_ENGINE(INNODB_PLUGIN)
+#MYSQL_STORAGE_ENGINE(INNOBASE)

=== modified file 'storage/innodb_plugin/ChangeLog'
--- a/storage/innodb_plugin/ChangeLog	2009-11-03 10:34:03 +0000
+++ b/storage/innodb_plugin/ChangeLog	2009-11-30 13:42:26 +0000
@@ -1,3 +1,87 @@
+2009-11-20	The InnoDB Team
+
+	* handler/ha_innodb.cc:
+	Add a workaround to prevent a crash due to Bug#45961 DDL on
+	partitioned innodb tables leaves data dictionary in an inconsistent
+	state
+
+2009-11-19	The InnoDB Team
+
+	* btr/btr0btr.c:
+	Fix Bug#48469 when innodb tablespace is configured too small, crash
+	and corruption!
+
+2009-11-19	The InnoDB Team
+
+	* data/data0type.c:
+	Fix Bug#48526 Data type for float and double is incorrectly reported
+	in InnoDB table monitor
+
+2009-11-19	The InnoDB Team
+
+	* CMakeLists.txt:
+	Fix Bug#48317 cannot build innodb as static library
+
+2009-11-18	The InnoDB Team
+
+	* handler/handler0alter.cc:
+	Fix Bug#48782 On lock wait timeout, CREATE INDEX (creating primary key)
+	attempts DROP TABLE
+
+2009-11-17	The InnoDB Team
+
+	* handler/ha_innodb.cc, mysql-test/innodb.result,
+	mysql-test/innodb.test, mysql-test/innodb_bug44369.result,
+	mysql-test/innodb_bug44369.test, mysql-test/patches/innodb-index.diff,
+	row/row0mysql.c:
+	Report duplicate table names to the client connection, not to the
+	error log.
+
+2009-11-12	The InnoDB Team
+
+	* handler/ha_innodb.cc, include/db0err.h, row/row0merge.c,
+	row/row0mysql.c:
+	Allow CREATE INDEX to be interrupted.
+	Also, when CHECK TABLE is interrupted, report ER_QUERY_INTERRUPTED.
+
+2009-11-11	The InnoDB Team
+
+	* handler/ha_innodb.cc, mysql-test/innodb_bug47167.result,
+	mysql-test/innodb_bug47167.test, mysql-test/innodb_file_format.result:
+	Fix Bug#47167 "set global innodb_file_format_check" cannot set value
+	by User-Defined Variable
+
+2009-11-11	The InnoDB Team
+
+	* include/os0file.h, os/os0file.c:
+	Fix Bug#3139 Mysql crashes: 'windows error 995' after several selects
+	on a large DB
+
+2009-11-04	The InnoDB Team
+
+	* handler/ha_innodb.cc:
+	Fix Bug#32430 'show innodb status' causes errors
+	Invalid (old?) table or database name in logs
+
+2009-11-02	The InnoDB Team
+
+	* btr/btr0sea.c, buf/buf0buf.c, dict/dict0dict.c, fil/fil0fil.c,
+	ibuf/ibuf0ibuf.c, include/btr0sea.h, include/dict0dict.h,
+	include/fil0fil.h, include/ibuf0ibuf.h, include/lock0lock.h,
+	include/log0log.h, include/log0recv.h, include/mem0mem.h,
+	include/mem0pool.h, include/os0file.h, include/pars0pars.h,
+	include/srv0srv.h, include/thr0loc.h, include/trx0i_s.h,
+	include/trx0purge.h, include/trx0rseg.h, include/trx0sys.h,
+	include/trx0undo.h, include/usr0sess.h, lock/lock0lock.c,
+	log/log0log.c, log/log0recv.c, mem/mem0dbg.c, mem/mem0pool.c,
+	os/os0file.c, os/os0sync.c, os/os0thread.c, pars/lexyy.c,
+	pars/pars0lex.l, que/que0que.c, srv/srv0srv.c, srv/srv0start.c,
+	sync/sync0arr.c, sync/sync0sync.c, thr/thr0loc.c, trx/trx0i_s.c,
+	trx/trx0purge.c, trx/trx0rseg.c, trx/trx0sys.c, trx/trx0undo.c,
+	usr/usr0sess.c, ut/ut0mem.c:
+	Fix Bug #45992 innodb memory not freed after shutdown
+	Fix Bug #46656 InnoDB plugin: memory leaks (Valgrind)
+
 2009-10-29	The InnoDB Team
 
 	* handler/ha_innodb.cc, mysql-test/innodb-autoinc.result,
@@ -66,6 +150,12 @@
 	Fix Bug#47058 Failure to compile innodb_plugin on solaris 10u7 + spro
 	cc/CC 5.10
 
+2009-10-13	The InnoDB Team
+
+	* buf/buf0flu.c:
+	Call fsync() on datafiles after a batch of pages is written to disk
+	even when skip_innodb_doublewrite is set.
+
 2009-10-05	The InnoDB Team
 
 	* buf/buf0buf.c:

=== modified file 'storage/innodb_plugin/btr/btr0btr.c'
--- a/storage/innodb_plugin/btr/btr0btr.c	2009-10-12 12:00:56 +0000
+++ b/storage/innodb_plugin/btr/btr0btr.c	2009-11-30 13:42:26 +0000
@@ -790,8 +790,15 @@ btr_create(
 	} else {
 		/* It is a non-ibuf tree: create a file segment for leaf
 		pages */
-		fseg_create(space, page_no,
-			    PAGE_HEADER + PAGE_BTR_SEG_LEAF, mtr);
+		if (!fseg_create(space, page_no,
+				 PAGE_HEADER + PAGE_BTR_SEG_LEAF, mtr)) {
+			/* Not enough space for new segment, free root
+			segment before return. */
+			btr_free_root(space, zip_size, page_no, mtr);
+
+			return(FIL_NULL);
+		}
+
 		/* The fseg create acquires a second latch on the page,
 		therefore we must declare it: */
 		buf_block_dbg_add_level(block, SYNC_TREE_NODE_NEW);

=== modified file 'storage/innodb_plugin/btr/btr0sea.c'
--- a/storage/innodb_plugin/btr/btr0sea.c	2009-10-08 11:28:37 +0000
+++ b/storage/innodb_plugin/btr/btr0sea.c	2009-11-30 11:32:05 +0000
@@ -175,6 +175,21 @@ btr_search_sys_create(
 	btr_search_sys->hash_index = ha_create(hash_size, 0, 0);
 }
 
+/*****************************************************************//**
+Frees the adaptive search system at a database shutdown. */
+UNIV_INTERN
+void
+btr_search_sys_free(void)
+/*=====================*/
+{
+	mem_free(btr_search_latch_temp);
+	btr_search_latch_temp = NULL;
+	mem_heap_free(btr_search_sys->hash_index->heap);
+	hash_table_free(btr_search_sys->hash_index);
+	mem_free(btr_search_sys);
+	btr_search_sys = NULL;
+}
+
 /********************************************************************//**
 Disable the adaptive hash search system and empty the index. */
 UNIV_INTERN

=== modified file 'storage/innodb_plugin/buf/buf0buf.c'
--- a/storage/innodb_plugin/buf/buf0buf.c	2009-11-03 10:26:07 +0000
+++ b/storage/innodb_plugin/buf/buf0buf.c	2009-11-30 11:32:05 +0000
@@ -1020,7 +1020,11 @@ buf_pool_free(void)
 		os_mem_free_large(chunk->mem, chunk->mem_size);
 	}
 
-	buf_pool->n_chunks = 0;
+	mem_free(buf_pool->chunks);
+	hash_table_free(buf_pool->page_hash);
+	hash_table_free(buf_pool->zip_hash);
+	mem_free(buf_pool);
+	buf_pool = NULL;
 }
 
 /********************************************************************//**

=== modified file 'storage/innodb_plugin/data/data0type.c'
--- a/storage/innodb_plugin/data/data0type.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/data/data0type.c	2009-11-30 13:35:20 +0000
@@ -237,6 +237,22 @@ dtype_print(
 		fputs("DATA_SYS", stderr);
 		break;
 
+	case DATA_FLOAT:
+		fputs("DATA_FLOAT", stderr);
+		break;
+
+	case DATA_DOUBLE:
+		fputs("DATA_DOUBLE", stderr);
+		break;
+
+	case DATA_DECIMAL:
+		fputs("DATA_DECIMAL", stderr);
+		break;
+
+	case DATA_VARMYSQL:
+		fputs("DATA_VARMYSQL", stderr);
+		break;
+
 	default:
 		fprintf(stderr, "type %lu", (ulong) mtype);
 		break;

=== modified file 'storage/innodb_plugin/dict/dict0dict.c'
--- a/storage/innodb_plugin/dict/dict0dict.c	2009-10-09 12:52:18 +0000
+++ b/storage/innodb_plugin/dict/dict0dict.c	2009-11-30 11:42:51 +0000
@@ -1200,7 +1200,7 @@ dict_index_too_big_for_undo(
 		= TRX_UNDO_PAGE_HDR - TRX_UNDO_PAGE_HDR_SIZE
 		+ 2 /* next record pointer */
 		+ 1 /* type_cmpl */
-		+ 11 /* trx->undo_no */ - 11 /* table->id */
+		+ 11 /* trx->undo_no */ + 11 /* table->id */
 		+ 1 /* rec_get_info_bits() */
 		+ 11 /* DB_TRX_ID */
 		+ 11 /* DB_ROLL_PTR */
@@ -4652,6 +4652,26 @@ dict_ind_init(void)
 	dict_ind_redundant->cached = dict_ind_compact->cached = TRUE;
 }
 
+/**********************************************************************//**
+Frees dict_ind_redundant and dict_ind_compact. */
+static
+void
+dict_ind_free(void)
+/*===============*/
+{
+	dict_table_t*	table;
+
+	table = dict_ind_compact->table;
+	dict_mem_index_free(dict_ind_compact);
+	dict_ind_compact = NULL;
+	dict_mem_table_free(table);
+
+	table = dict_ind_redundant->table;
+	dict_mem_index_free(dict_ind_redundant);
+	dict_ind_redundant = NULL;
+	dict_mem_table_free(table);
+}
+
 #ifndef UNIV_HOTBACKUP
 /**********************************************************************//**
 Get index by name
@@ -4777,4 +4797,55 @@ dict_table_check_for_dup_indexes(
 	}
 }
 #endif /* UNIV_DEBUG */
+
+/**************************************************************************
+Closes the data dictionary module. */
+UNIV_INTERN
+void
+dict_close(void)
+/*============*/
+{
+	ulint	i;
+
+	/* Free the hash elements. We don't remove them from the table
+	because we are going to destroy the table anyway. */
+	for (i = 0; i < hash_get_n_cells(dict_sys->table_hash); i++) {
+		dict_table_t*	table;
+
+		table = HASH_GET_FIRST(dict_sys->table_hash, i);
+
+		while (table) {
+			dict_table_t*	prev_table = table;
+
+			table = HASH_GET_NEXT(name_hash, prev_table);
+#ifdef UNIV_DEBUG
+			ut_a(prev_table->magic_n == DICT_TABLE_MAGIC_N);
+#endif
+			/* Acquire only because it's a pre-condition. */
+			mutex_enter(&dict_sys->mutex);
+
+			dict_table_remove_from_cache(prev_table);
+
+			mutex_exit(&dict_sys->mutex);
+		}
+	}
+
+	hash_table_free(dict_sys->table_hash);
+
+	/* The elements are the same instance as in dict_sys->table_hash,
+	therefore we don't delete the individual elements. */
+	hash_table_free(dict_sys->table_id_hash);
+
+	dict_ind_free();
+
+	mutex_free(&dict_sys->mutex);
+
+	rw_lock_free(&dict_operation_lock);
+	memset(&dict_operation_lock, 0x0, sizeof(dict_operation_lock));
+
+	mutex_free(&dict_foreign_err_mutex);
+
+	mem_free(dict_sys);
+	dict_sys = NULL;
+}
 #endif /* !UNIV_HOTBACKUP */

=== modified file 'storage/innodb_plugin/fil/fil0fil.c'
--- a/storage/innodb_plugin/fil/fil0fil.c	2009-11-03 10:24:21 +0000
+++ b/storage/innodb_plugin/fil/fil0fil.c	2009-11-30 11:32:05 +0000
@@ -321,6 +321,17 @@ fil_get_space_id_for_table(
 /*=======================*/
 	const char*	name);	/*!< in: table name in the standard
 				'databasename/tablename' format */
+/*******************************************************************//**
+Frees a space object from the tablespace memory cache. Closes the files in
+the chain but does not delete them. There must not be any pending i/o's or
+flushes on the files. */
+static
+ibool
+fil_space_free(
+/*===========*/
+				/* out: TRUE if success */
+	ulint		id,	/* in: space id */
+	ibool		own_mutex);/* in: TRUE if own system->mutex */
 /********************************************************************//**
 Reads data from a space to a buffer. Remember that the possible incomplete
 blocks at the end of file are ignored: they are not taken into account when
@@ -1144,7 +1155,7 @@ try_again:
 
 		mutex_exit(&fil_system->mutex);
 
-		fil_space_free(namesake_id);
+		fil_space_free(namesake_id, FALSE);
 
 		goto try_again;
 	}
@@ -1269,17 +1280,21 @@ Frees a space object from the tablespace
 the chain but does not delete them. There must not be any pending i/o's or
 flushes on the files.
 @return	TRUE if success */
-UNIV_INTERN
+static
 ibool
 fil_space_free(
 /*===========*/
-	ulint	id)	/*!< in: space id */
+					/* out: TRUE if success */
+	ulint		id,		/* in: space id */
+	ibool		own_mutex)	/* in: TRUE if own system->mutex */
 {
 	fil_space_t*	space;
 	fil_space_t*	namespace;
 	fil_node_t*	fil_node;
 
-	mutex_enter(&fil_system->mutex);
+	if (!own_mutex) {
+		mutex_enter(&fil_system->mutex);
+	}
 
 	space = fil_space_get_by_id(id);
 
@@ -1326,7 +1341,9 @@ fil_space_free(
 
 	ut_a(0 == UT_LIST_GET_LEN(space->chain));
 
-	mutex_exit(&fil_system->mutex);
+	if (!own_mutex) {
+		mutex_exit(&fil_system->mutex);
+	}
 
 	rw_lock_free(&(space->latch));
 
@@ -1586,6 +1603,8 @@ fil_close_all_files(void)
 	space = UT_LIST_GET_FIRST(fil_system->space_list);
 
 	while (space != NULL) {
+		fil_space_t*	prev_space = space;
+
 		node = UT_LIST_GET_FIRST(space->chain);
 
 		while (node != NULL) {
@@ -1595,6 +1614,7 @@ fil_close_all_files(void)
 			node = UT_LIST_GET_NEXT(chain, node);
 		}
 		space = UT_LIST_GET_NEXT(space_list, space);
+		fil_space_free(prev_space->id, TRUE);
 	}
 
 	mutex_exit(&fil_system->mutex);
@@ -2226,7 +2246,7 @@ try_again:
 #endif
 	/* printf("Deleting tablespace %s id %lu\n", space->name, id); */
 
-	success = fil_space_free(id);
+	success = fil_space_free(id, FALSE);
 
 	if (success) {
 		success = os_file_delete(path);
@@ -4753,3 +4773,26 @@ fil_page_get_type(
 
 	return(mach_read_from_2(page + FIL_PAGE_TYPE));
 }
+
+/********************************************************************
+Initializes the tablespace memory cache. */
+UNIV_INTERN
+void
+fil_close(void)
+/*===========*/
+{
+	/* The mutex should already have been freed. */
+	ut_ad(fil_system->mutex.magic_n == 0);
+
+	hash_table_free(fil_system->spaces);
+
+	hash_table_free(fil_system->name_hash);
+
+	ut_a(UT_LIST_GET_LEN(fil_system->LRU) == 0);
+	ut_a(UT_LIST_GET_LEN(fil_system->unflushed_spaces) == 0);
+	ut_a(UT_LIST_GET_LEN(fil_system->space_list) == 0);
+
+	mem_free(fil_system);
+
+	fil_system = NULL;
+}

=== modified file 'storage/innodb_plugin/handler/ha_innodb.cc'
--- a/storage/innodb_plugin/handler/ha_innodb.cc	2009-11-03 10:34:38 +0000
+++ b/storage/innodb_plugin/handler/ha_innodb.cc	2009-12-08 09:26:11 +0000
@@ -269,10 +269,10 @@ innobase_file_format_check_on_off(
 /************************************************************//**
 Validate the file format check config parameters, as a side effect it
 sets the srv_check_file_format_at_startup variable.
-@return	true if valid config value */
+@return	the format_id if valid config value, otherwise, return -1 */
 static
-bool
-innobase_file_format_check_validate(
+int
+innobase_file_format_validate_and_set(
 /*================================*/
 	const char*	format_check);		/*!< in: parameter value */
 /****************************************************************//**
@@ -785,11 +785,20 @@ convert_error_code_to_mysql(
 	case DB_SUCCESS:
 		return(0);
 
+	case DB_INTERRUPTED:
+		my_error(ER_QUERY_INTERRUPTED, MYF(0));
+		/* fall through */
 	case DB_ERROR:
 	default:
 		return(-1); /* unspecified error */
 
 	case DB_DUPLICATE_KEY:
+		/* Be cautious with returning this error, since
+		mysql could re-enter the storage layer to get
+		duplicated key info, the operation requires a
+		valid table handle and/or transaction information,
+		which might not always be available in the error
+		handling stage. */
 		return(HA_ERR_FOUND_DUPP_KEY);
 
 	case DB_FOREIGN_DUPLICATE_KEY:
@@ -890,36 +899,6 @@ convert_error_code_to_mysql(
 }
 
 /*************************************************************//**
-If you want to print a thd that is not associated with the current thread,
-you must call this function before reserving the InnoDB kernel_mutex, to
-protect MySQL from setting thd->query NULL. If you print a thd of the current
-thread, we know that MySQL cannot modify thd->query, and it is not necessary
-to call this. Call innobase_mysql_end_print_arbitrary_thd() after you release
-the kernel_mutex. */
-extern "C" UNIV_INTERN
-void
-innobase_mysql_prepare_print_arbitrary_thd(void)
-/*============================================*/
-{
-	ut_ad(!mutex_own(&kernel_mutex));
-	VOID(pthread_mutex_lock(&LOCK_thread_count));
-}
-
-/*************************************************************//**
-Releases the mutex reserved by innobase_mysql_prepare_print_arbitrary_thd().
-In the InnoDB latching order, the mutex sits right above the
-kernel_mutex.  In debug builds, we assert that the kernel_mutex is
-released before this function is invoked. */
-extern "C" UNIV_INTERN
-void
-innobase_mysql_end_print_arbitrary_thd(void)
-/*========================================*/
-{
-	ut_ad(!mutex_own(&kernel_mutex));
-	VOID(pthread_mutex_unlock(&LOCK_thread_count));
-}
-
-/*************************************************************//**
 Prints info of a THD object (== user session thread) to the given file. */
 extern "C" UNIV_INTERN
 void
@@ -1707,15 +1686,19 @@ innobase_convert_identifier(
 				FALSE=id is an UTF-8 string */
 {
 	char nz[NAME_LEN + 1];
+#if MYSQL_VERSION_ID >= 50141
+	char nz2[NAME_LEN + 1 + EXPLAIN_FILENAME_MAX_EXTRA_LENGTH];
+#else /* MYSQL_VERSION_ID >= 50141 */
 	char nz2[NAME_LEN + 1 + sizeof srv_mysql50_table_name_prefix];
+#endif /* MYSQL_VERSION_ID >= 50141 */
 
 	const char*	s	= id;
 	int		q;
 
 	if (file_id) {
-		/* Decode the table name.  The filename_to_tablename()
-		function expects a NUL-terminated string.  The input and
-		output strings buffers must not be shared. */
+		/* Decode the table name.  The MySQL function expects
+		a NUL-terminated string.  The input and output strings
+		buffers must not be shared. */
 
 		if (UNIV_UNLIKELY(idlen > (sizeof nz) - 1)) {
 			idlen = (sizeof nz) - 1;
@@ -1725,7 +1708,13 @@ innobase_convert_identifier(
 		nz[idlen] = 0;
 
 		s = nz2;
+#if MYSQL_VERSION_ID >= 50141
+		idlen = explain_filename((THD*) thd, nz, nz2, sizeof nz2,
+					 EXPLAIN_PARTITIONS_AS_COMMENT);
+		goto no_quote;
+#else /* MYSQL_VERSION_ID >= 50141 */
 		idlen = filename_to_tablename(nz, nz2, sizeof nz2);
+#endif /* MYSQL_VERSION_ID >= 50141 */
 	}
 
 	/* See if the identifier needs to be quoted. */
@@ -1736,6 +1725,9 @@ innobase_convert_identifier(
 	}
 
 	if (q == EOF) {
+#if MYSQL_VERSION_ID >= 50141
+no_quote:
+#endif /* MYSQL_VERSION_ID >= 50141 */
 		if (UNIV_UNLIKELY(idlen > buflen)) {
 			idlen = buflen;
 		}
@@ -2133,8 +2125,8 @@ mem_free_and_error:
 		/* Did the user specify a format name that we support ?
 		As a side effect it will update the variable
 		srv_check_file_format_at_startup */
-		if (!innobase_file_format_check_validate(
-			innobase_file_format_check)) {
+		if (innobase_file_format_validate_and_set(
+				innobase_file_format_check) < 0) {
 
 			sql_print_error("InnoDB: invalid "
 					"innodb_file_format_check value: "
@@ -5225,8 +5217,10 @@ ha_innobase::change_active_index(
 							   prebuilt->index);
 
 	if (UNIV_UNLIKELY(!prebuilt->index_usable)) {
-		sql_print_warning("InnoDB: insufficient history for index %u",
-				  keynr);
+		push_warning_printf(user_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+				    HA_ERR_TABLE_DEF_CHANGED,
+				    "InnoDB: insufficient history for index %u",
+				    keynr);
 		/* The caller seems to ignore this.  Thus, we must check
 		this again in row_search_for_mysql(). */
 		DBUG_RETURN(2);
@@ -5713,17 +5707,8 @@ create_table_def(
 		/* First check whether the column to be added has a
 		system reserved name. */
 		if (dict_col_name_is_reserved(field->field_name)){
-			push_warning_printf(
-				(THD*) trx->mysql_thd,
-				MYSQL_ERROR::WARN_LEVEL_WARN,
-				ER_CANT_CREATE_TABLE,
-				"Error creating table '%s' with "
-				"column name '%s'. '%s' is a "
-				"reserved name. Please try to "
-				"re-create the table with a "
-				"different column name.",
-				table->name, (char*) field->field_name,
-				(char*) field->field_name);
+			my_error(ER_WRONG_COLUMN_NAME, MYF(0),
+				 field->field_name);
 
 			dict_mem_table_free(table);
 			trx_commit_for_mysql(trx);
@@ -5745,6 +5730,14 @@ create_table_def(
 
 	error = row_create_table_for_mysql(table, trx);
 
+	if (error == DB_DUPLICATE_KEY) {
+		char buf[100];
+		innobase_convert_identifier(buf, sizeof buf,
+					    table_name, strlen(table_name),
+					    trx->mysql_thd, TRUE);
+		my_error(ER_TABLE_EXISTS_ERROR, MYF(0), buf);
+	}
+
 error_ret:
 	error = convert_error_code_to_mysql(error, flags, NULL);
 
@@ -6798,6 +6791,24 @@ ha_innobase::rename_table(
 	innobase_commit_low(trx);
 	trx_free_for_mysql(trx);
 
+	/* Add a special case to handle the Duplicated Key error
+	and return DB_ERROR instead.
+	This is to avoid a possible SIGSEGV error from mysql error
+	handling code. Currently, mysql handles the Duplicated Key
+	error by re-entering the storage layer and getting dup key
+	info by calling get_dup_key(). This operation requires a valid
+	table handle ('row_prebuilt_t' structure) which could no
+	longer be available in the error handling stage. The suggested
+	solution is to report a 'table exists' error message (since
+	the dup key error here is due to an existing table whose name
+	is the one we are trying to rename to) and return the generic
+	error code. */
+	if (error == (int) DB_DUPLICATE_KEY) {
+		my_error(ER_TABLE_EXISTS_ERROR, MYF(0), to);
+
+		error = DB_ERROR;
+	}
+
 	error = convert_error_code_to_mysql(error, 0, NULL);
 
 	DBUG_RETURN(error);
@@ -7348,11 +7359,15 @@ ha_innobase::check(
 
 	ret = row_check_table_for_mysql(prebuilt);
 
-	if (ret == DB_SUCCESS) {
+	switch (ret) {
+	case DB_SUCCESS:
 		return(HA_ADMIN_OK);
+	case DB_INTERRUPTED:
+		my_error(ER_QUERY_INTERRUPTED, MYF(0));
+		return(-1);
+	default:
+		return(HA_ADMIN_CORRUPT);
 	}
-
-	return(HA_ADMIN_CORRUPT);
 }
 
 /*************************************************************//**
@@ -7899,7 +7914,10 @@ ha_innobase::external_lock(
 		ulong const tx_isolation = thd_tx_isolation(ha_thd());
 		if (tx_isolation <= ISO_READ_COMMITTED
                    && binlog_format == BINLOG_FORMAT_STMT
-                   && thd_binlog_filter_ok(thd))
+#if MYSQL_VERSION_ID > 50140
+                   && thd_binlog_filter_ok(thd)
+#endif /* MYSQL_VERSION_ID > 50140 */
+		   )
 		{
 			char buf[256];
 			my_snprintf(buf, sizeof(buf),
@@ -9148,8 +9166,7 @@ innobase_xa_prepare(
 		executing XA PREPARE and XA COMMIT commands.
 		In this case we cannot know how many minutes or hours
 		will be between XA PREPARE and XA COMMIT, and we don't want
-		to block for undefined period of time.
-		*/
+		to block for undefined period of time. */
 		pthread_mutex_lock(&prepare_commit_mutex);
 		trx->active_trans = 2;
 	}
@@ -9491,25 +9508,24 @@ innobase_file_format_check_on_off(
 /************************************************************//**
 Validate the file format check config parameters, as a side effect it
 sets the srv_check_file_format_at_startup variable.
-@return	true if valid config value */
+@return the format_id if valid config value, otherwise, return -1 */
 static
-bool
-innobase_file_format_check_validate(
+int
+innobase_file_format_validate_and_set(
 /*================================*/
 	const char*	format_check)	/*!< in: parameter value */
 {
 	uint		format_id;
-	bool		ret = true;
 
 	format_id = innobase_file_format_name_lookup(format_check);
 
 	if (format_id < DICT_TF_FORMAT_MAX + 1) {
 		srv_check_file_format_at_startup = format_id;
+
+		return((int) format_id);
 	} else {
-		ret = false;
+		return(-1);
 	}
-
-	return(ret);
 }
 
 /*************************************************************//**
@@ -9544,7 +9560,11 @@ innodb_file_format_name_validate(
 
 		if (format_id <= DICT_TF_FORMAT_MAX) {
 
-			*static_cast<const char**>(save) = file_format_input;
+			/* Save a pointer to the name in the
+			'file_format_name_map' constant array. */
+			*static_cast<const char**>(save) =
+			    trx_sys_file_format_id_to_name(format_id);
+
 			return(0);
 		}
 	}
@@ -9607,6 +9627,7 @@ innodb_file_format_check_validate(
 	const char*	file_format_input;
 	char		buff[STRING_BUFFER_USUAL_SIZE];
 	int		len = sizeof(buff);
+	int		format_id;
 
 	ut_a(save != NULL);
 	ut_a(value != NULL);
@@ -9619,24 +9640,35 @@ innodb_file_format_check_validate(
 		message if they did so. */
 
 		if (innobase_file_format_check_on_off(file_format_input)) {
-			sql_print_warning(
+			push_warning_printf(thd,
+				MYSQL_ERROR::WARN_LEVEL_WARN,
+				ER_WRONG_ARGUMENTS,
 				"InnoDB: invalid innodb_file_format_check "
 				"value; on/off can only be set at startup or "
 				"in the configuration file");
-		} else if (innobase_file_format_check_validate(
-				file_format_input)) {
+		} else {
+			format_id = innobase_file_format_validate_and_set(
+							file_format_input);
 
-			*static_cast<const char**>(save) = file_format_input;
+			if (format_id >= 0) {
+				/* Save a pointer to the name in the
+				'file_format_name_map' constant array. */
+				*static_cast<const char**>(save) =
+				    trx_sys_file_format_id_to_name(
+							(uint)format_id);
 
-			return(0);
+				return(0);
 
-		} else {
-			sql_print_warning(
-				"InnoDB: invalid innodb_file_format_check "
-				"value; can be any format up to %s "
-				"or its equivalent numeric id",
-				trx_sys_file_format_id_to_name(
-					DICT_TF_FORMAT_MAX));
+			} else {
+				push_warning_printf(thd,
+				  MYSQL_ERROR::WARN_LEVEL_WARN,
+				  ER_WRONG_ARGUMENTS,
+				  "InnoDB: invalid innodb_file_format_check "
+				  "value; can be any format up to %s "
+				  "or its equivalent numeric id",
+				  trx_sys_file_format_id_to_name(
+						DICT_TF_FORMAT_MAX));
+			}
 		}
 	}
 
@@ -9906,12 +9938,15 @@ static MYSQL_SYSVAR_STR(file_format, inn
   innodb_file_format_name_validate,
   innodb_file_format_name_update, "Antelope");
 
+/* If a new file format is introduced, the file format
+name needs to be updated accordingly. Please refer to
+file_format_name_map[] defined in trx0sys.c for the next
+file format name. */
 static MYSQL_SYSVAR_STR(file_format_check, innobase_file_format_check,
   PLUGIN_VAR_OPCMDARG,
   "The highest file format in the tablespace.",
   innodb_file_format_check_validate,
-  innodb_file_format_check_update,
-  "on");
+  innodb_file_format_check_update, "Barracuda");
 
 static MYSQL_SYSVAR_ULONG(flush_log_at_trx_commit, srv_flush_log_at_trx_commit,
   PLUGIN_VAR_OPCMDARG,

=== modified file 'storage/innodb_plugin/handler/ha_innodb.h'
--- a/storage/innodb_plugin/handler/ha_innodb.h	2009-11-03 10:07:51 +0000
+++ b/storage/innodb_plugin/handler/ha_innodb.h	2009-11-30 12:11:36 +0000
@@ -258,12 +258,14 @@ int thd_binlog_format(const MYSQL_THD th
 */
 void thd_mark_transaction_to_rollback(MYSQL_THD thd, bool all);
 
+#if MYSQL_VERSION_ID > 50140
 /**
   Check if binary logging is filtered for thread's current db.
   @param  thd   Thread handle
   @retval 1 the query is not filtered, 0 otherwise.
 */
 bool thd_binlog_filter_ok(const MYSQL_THD thd);
+#endif /* MYSQL_VERSION_ID > 50140 */
 }
 
 typedef struct trx_struct trx_t;

=== modified file 'storage/innodb_plugin/handler/handler0alter.cc'
--- a/storage/innodb_plugin/handler/handler0alter.cc	2009-11-03 10:07:51 +0000
+++ b/storage/innodb_plugin/handler/handler0alter.cc	2009-11-30 13:42:26 +0000
@@ -765,10 +765,11 @@ err_exit:
 	ut_ad(error == DB_SUCCESS);
 
 	/* Commit the data dictionary transaction in order to release
-	the table locks on the system tables.  Unfortunately, this
-	means that if MySQL crashes while creating a new primary key
-	inside row_merge_build_indexes(), indexed_table will not be
-	dropped on crash recovery.  Thus, it will become orphaned. */
+	the table locks on the system tables.  This means that if
+	MySQL crashes while creating a new primary key inside
+	row_merge_build_indexes(), indexed_table will not be dropped
+	by trx_rollback_active().  It will have to be recovered or
+	dropped by the database administrator. */
 	trx_commit_for_mysql(trx);
 
 	row_mysql_unlock_data_dictionary(trx);
@@ -882,7 +883,9 @@ error:
 		/* fall through */
 	default:
 		if (new_primary) {
-			row_merge_drop_table(trx, indexed_table);
+			if (indexed_table != innodb_table) {
+				row_merge_drop_table(trx, indexed_table);
+			}
 		} else {
 			if (!dict_locked) {
 				row_mysql_lock_data_dictionary(trx);

=== modified file 'storage/innodb_plugin/ibuf/ibuf0ibuf.c'
--- a/storage/innodb_plugin/ibuf/ibuf0ibuf.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/ibuf/ibuf0ibuf.c	2009-11-30 11:32:05 +0000
@@ -390,6 +390,27 @@ ibuf_count_set(
 #endif
 
 /******************************************************************//**
+Closes insert buffer and frees the data structures. */
+UNIV_INTERN
+void
+ibuf_close(void)
+/*============*/
+{
+	mutex_free(&ibuf_pessimistic_insert_mutex);
+	memset(&ibuf_pessimistic_insert_mutex,
+	       0x0, sizeof(ibuf_pessimistic_insert_mutex));
+
+	mutex_free(&ibuf_mutex);
+	memset(&ibuf_mutex, 0x0, sizeof(ibuf_mutex));
+
+	mutex_free(&ibuf_bitmap_mutex);
+	memset(&ibuf_bitmap_mutex, 0x0, sizeof(ibuf_mutex));
+
+	mem_free(ibuf);
+	ibuf = NULL;
+}
+
+/******************************************************************//**
 Updates the size information of the ibuf, assuming the segment size has not
 changed. */
 static

=== modified file 'storage/innodb_plugin/include/btr0sea.h'
--- a/storage/innodb_plugin/include/btr0sea.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/btr0sea.h	2009-11-30 11:32:05 +0000
@@ -41,6 +41,12 @@ void
 btr_search_sys_create(
 /*==================*/
 	ulint	hash_size);	/*!< in: hash index hash table size */
+/*****************************************************************//**
+Frees the adaptive search system at a database shutdown. */
+UNIV_INTERN
+void
+btr_search_sys_free(void);
+/*=====================*/
 
 /********************************************************************//**
 Disable the adaptive hash search system and empty the index. */

=== modified file 'storage/innodb_plugin/include/db0err.h'
--- a/storage/innodb_plugin/include/db0err.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/db0err.h	2009-11-30 12:24:54 +0000
@@ -32,6 +32,7 @@ enum db_err {
 
 	/* The following are error codes */
 	DB_ERROR,
+	DB_INTERRUPTED,
 	DB_OUT_OF_MEMORY,
 	DB_OUT_OF_FILE_SPACE,
 	DB_LOCK_WAIT,

=== modified file 'storage/innodb_plugin/include/dict0dict.h'
--- a/storage/innodb_plugin/include/dict0dict.h	2009-10-08 11:28:37 +0000
+++ b/storage/innodb_plugin/include/dict0dict.h	2009-11-30 11:32:05 +0000
@@ -1151,6 +1151,13 @@ void
 dict_ind_init(void);
 /*===============*/
 
+/**********************************************************************//**
+Closes the data dictionary module. */
+UNIV_INTERN
+void
+dict_close(void);
+/*============*/
+
 #ifndef UNIV_NONINL
 #include "dict0dict.ic"
 #endif

=== modified file 'storage/innodb_plugin/include/fil0fil.h'
--- a/storage/innodb_plugin/include/fil0fil.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/fil0fil.h	2009-11-30 11:32:05 +0000
@@ -224,15 +224,6 @@ fil_space_create(
 				0 for uncompressed tablespaces */
 	ulint		purpose);/*!< in: FIL_TABLESPACE, or FIL_LOG if log */
 /*******************************************************************//**
-Frees a space object from a the tablespace memory cache. Closes the files in
-the chain but does not delete them.
-@return	TRUE if success */
-UNIV_INTERN
-ibool
-fil_space_free(
-/*===========*/
-	ulint	id);	/*!< in: space id */
-/*******************************************************************//**
 Returns the size of the space in pages. The tablespace must be cached in the
 memory cache.
 @return	space size, 0 if space not found */
@@ -278,6 +269,12 @@ fil_init(
 	ulint	hash_size,	/*!< in: hash table size */
 	ulint	max_n_open);	/*!< in: max number of open files */
 /*******************************************************************//**
+Initializes the tablespace memory cache. */
+UNIV_INTERN
+void
+fil_close(void);
+/*===========*/
+/*******************************************************************//**
 Opens all log files and system tablespace data files. They stay open until the
 database server shutdown. This should be called at a server startup after the
 space objects for the log and the system tablespace have been created. The

=== modified file 'storage/innodb_plugin/include/ha_prototypes.h'
--- a/storage/innodb_plugin/include/ha_prototypes.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/ha_prototypes.h	2009-12-01 10:38:40 +0000
@@ -153,28 +153,6 @@ get_innobase_type_from_mysql_type(
 	const void*	field)		/*!< in: MySQL Field */
 	__attribute__((nonnull));
 
-/*************************************************************//**
-If you want to print a thd that is not associated with the current thread,
-you must call this function before reserving the InnoDB kernel_mutex, to
-protect MySQL from setting thd->query NULL. If you print a thd of the current
-thread, we know that MySQL cannot modify thd->query, and it is not necessary
-to call this. Call innobase_mysql_end_print_arbitrary_thd() after you release
-the kernel_mutex. */
-UNIV_INTERN
-void
-innobase_mysql_prepare_print_arbitrary_thd(void);
-/*============================================*/
-
-/*************************************************************//**
-Releases the mutex reserved by innobase_mysql_prepare_print_arbitrary_thd().
-In the InnoDB latching order, the mutex sits right above the
-kernel_mutex.  In debug builds, we assert that the kernel_mutex is
-released before this function is invoked. */
-UNIV_INTERN
-void
-innobase_mysql_end_print_arbitrary_thd(void);
-/*========================================*/
-
 /******************************************************************//**
 Get the variable length bounds of the given character set. */
 UNIV_INTERN

=== modified file 'storage/innodb_plugin/include/ibuf0ibuf.h'
--- a/storage/innodb_plugin/include/ibuf0ibuf.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/ibuf0ibuf.h	2009-11-30 11:32:05 +0000
@@ -356,6 +356,12 @@ void
 ibuf_print(
 /*=======*/
 	FILE*	file);	/*!< in: file where to print */
+/******************************************************************//**
+Closes insert buffer and frees the data structures. */
+UNIV_INTERN
+void
+ibuf_close(void);
+/*============*/
 
 #define IBUF_HEADER_PAGE_NO	FSP_IBUF_HEADER_PAGE_NO
 #define IBUF_TREE_ROOT_PAGE_NO	FSP_IBUF_TREE_ROOT_PAGE_NO

=== modified file 'storage/innodb_plugin/include/lock0lock.h'
--- a/storage/innodb_plugin/include/lock0lock.h	2009-10-08 12:18:19 +0000
+++ b/storage/innodb_plugin/include/lock0lock.h	2009-11-30 11:32:05 +0000
@@ -59,6 +59,12 @@ lock_sys_create(
 /*============*/
 	ulint	n_cells);	/*!< in: number of slots in lock hash table */
 /*********************************************************************//**
+Closes the lock system at database shutdown. */
+UNIV_INTERN
+void
+lock_sys_close(void);
+/*================*/
+/*********************************************************************//**
 Checks if some transaction has an implicit x-lock on a record in a clustered
 index.
 @return	transaction which has the x-lock, or NULL */

=== modified file 'storage/innodb_plugin/include/log0log.h'
--- a/storage/innodb_plugin/include/log0log.h	2009-10-08 12:18:19 +0000
+++ b/storage/innodb_plugin/include/log0log.h	2009-11-30 11:32:05 +0000
@@ -572,6 +572,18 @@ UNIV_INTERN
 void
 log_refresh_stats(void);
 /*===================*/
+/**********************************************************
+Shutdown the log system but do not release all the memory. */
+UNIV_INTERN
+void
+log_shutdown(void);
+/*==============*/
+/**********************************************************
+Free the log system data structures. */
+UNIV_INTERN
+void
+log_mem_free(void);
+/*==============*/
 
 extern log_t*	log_sys;
 
@@ -584,7 +596,7 @@ extern log_t*	log_sys;
 #define LOG_RECOVER	98887331
 
 /* The counting of lsn's starts from this value: this must be non-zero */
-#define LOG_START_LSN	((ib_uint64_t) (16 * OS_FILE_LOG_BLOCK_SIZE))
+#define LOG_START_LSN		((ib_uint64_t) (16 * OS_FILE_LOG_BLOCK_SIZE))
 
 #define LOG_BUFFER_SIZE		(srv_log_buffer_size * UNIV_PAGE_SIZE)
 #define LOG_ARCHIVE_BUF_SIZE	(srv_log_buffer_size * UNIV_PAGE_SIZE / 4)
@@ -721,9 +733,12 @@ struct log_group_struct{
 	ulint		lsn_offset;	/*!< the offset of the above lsn */
 	ulint		n_pending_writes;/*!< number of currently pending flush
 					writes for this log group */
+	byte**		file_header_bufs_ptr;/*!< unaligned buffers */
 	byte**		file_header_bufs;/*!< buffers for each file
 					header in the group */
+#ifdef UNIV_LOG_ARCHIVE
 	/*-----------------------------*/
+	byte**		archive_file_header_bufs_ptr;/*!< unaligned buffers */
 	byte**		archive_file_header_bufs;/*!< buffers for each file
 					header in the group */
 	ulint		archive_space_id;/*!< file space which
@@ -742,10 +757,12 @@ struct log_group_struct{
 					completion function then sets the new
 					value to ..._file_no */
 	ulint		next_archived_offset; /*!< like the preceding field */
+#endif /* UNIV_LOG_ARCHIVE */
 	/*-----------------------------*/
 	ib_uint64_t	scanned_lsn;	/*!< used only in recovery: recovery scan
 					succeeded up to this lsn in this log
 					group */
+	byte*		checkpoint_buf_ptr;/*!< unaligned checkpoint header */
 	byte*		checkpoint_buf;	/*!< checkpoint header is written from
 					this buffer to the group */
 	UT_LIST_NODE_T(log_group_t)
@@ -763,6 +780,7 @@ struct log_struct{
 #ifndef UNIV_HOTBACKUP
 	mutex_t		mutex;		/*!< mutex protecting the log */
 #endif /* !UNIV_HOTBACKUP */
+	byte*		buf_ptr;	/* unaligned log buffer */
 	byte*		buf;		/*!< log buffer */
 	ulint		buf_size;	/*!< log buffer size in bytes */
 	ulint		max_buf_free;	/*!< recommended maximum value of
@@ -899,6 +917,7 @@ struct log_struct{
 					should wait for this without owning
 					the log mutex */
 #endif /* !UNIV_HOTBACKUP */
+	byte*		checkpoint_buf_ptr;/* unaligned checkpoint header */
 	byte*		checkpoint_buf;	/*!< checkpoint header is read to this
 					buffer */
 	/* @} */

=== modified file 'storage/innodb_plugin/include/log0recv.h'
--- a/storage/innodb_plugin/include/log0recv.h	2009-10-09 14:13:15 +0000
+++ b/storage/innodb_plugin/include/log0recv.h	2009-11-30 11:32:05 +0000
@@ -239,6 +239,18 @@ UNIV_INTERN
 void
 recv_sys_create(void);
 /*=================*/
+/**********************************************************//**
+Release recovery system mutexes. */
+UNIV_INTERN
+void
+recv_sys_close(void);
+/*================*/
+/********************************************************//**
+Frees the recovery system memory. */
+UNIV_INTERN
+void
+recv_sys_mem_free(void);
+/*===================*/
 /********************************************************//**
 Inits the recovery system for a recovery operation. */
 UNIV_INTERN
@@ -246,6 +258,12 @@ void
 recv_sys_init(
 /*==========*/
 	ulint	available_memory);	/*!< in: available memory in bytes */
+/********************************************************//**
+Reset the state of the recovery system variables. */
+UNIV_INTERN
+void
+recv_sys_var_init(void);
+/*===================*/
 /*******************************************************************//**
 Empties the hash table of stored log records, applying them to appropriate
 pages. */

=== modified file 'storage/innodb_plugin/include/mem0mem.h'
--- a/storage/innodb_plugin/include/mem0mem.h	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/include/mem0mem.h	2009-11-30 11:32:05 +0000
@@ -82,6 +82,13 @@ void
 mem_init(
 /*=====*/
 	ulint	size);	/*!< in: common pool size in bytes */
+/******************************************************************//**
+Closes the memory system. */
+UNIV_INTERN
+void
+mem_close(void);
+/*===========*/
+
 /**************************************************************//**
 Use this macro instead of the corresponding function! Macro for memory
 heap creation. */

=== modified file 'storage/innodb_plugin/include/mem0pool.h'
--- a/storage/innodb_plugin/include/mem0pool.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/mem0pool.h	2009-11-30 11:32:05 +0000
@@ -62,6 +62,13 @@ mem_pool_create(
 /*============*/
 	ulint	size);	/*!< in: pool size in bytes */
 /********************************************************************//**
+Frees a memory pool. */
+UNIV_INTERN
+void
+mem_pool_free(
+/*==========*/
+	mem_pool_t*	pool);	/*!< in, own: memory pool */
+/********************************************************************//**
 Allocates memory from a pool. NOTE: This low-level function should only be
 used in mem0mem.*!
 @return	own: allocated memory buffer */

=== modified file 'storage/innodb_plugin/include/os0file.h'
--- a/storage/innodb_plugin/include/os0file.h	2009-11-03 09:59:06 +0000
+++ b/storage/innodb_plugin/include/os0file.h	2009-11-30 12:04:09 +0000
@@ -158,6 +158,7 @@ log. */
 #define	OS_FILE_SHARING_VIOLATION	76
 #define	OS_FILE_ERROR_NOT_SPECIFIED	77
 #define	OS_FILE_INSUFFICIENT_RESOURCE	78
+#define	OS_FILE_OPERATION_ABORTED	79
 /* @} */
 
 /** Types for aio operations @{ */
@@ -620,6 +621,13 @@ os_aio_init(
 	ulint	n_write_segs,	/*<! in: number of writer threads */
 	ulint	n_slots_sync);	/*<! in: number of slots in the sync aio
 				array */
+/***********************************************************************
+Frees the asynchronous io system. */
+UNIV_INTERN
+void
+os_aio_free(void);
+/*=============*/
+
 /*******************************************************************//**
 Requests an asynchronous i/o operation.
 @return	TRUE if request was queued successfully, FALSE if fail */

=== modified file 'storage/innodb_plugin/include/pars0pars.h'
--- a/storage/innodb_plugin/include/pars0pars.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/pars0pars.h	2009-11-30 11:32:05 +0000
@@ -583,6 +583,12 @@ pars_info_get_bound_id(
 	pars_info_t*		info,	/*!< in: info struct */
 	const char*		name);	/*!< in: bound id name to find */
 
+/******************************************************************//**
+Release any resources used by the lexer. */
+UNIV_INTERN
+void
+pars_lexer_close(void);
+/*==================*/
 
 /** Extra information supplied for pars_sql(). */
 struct pars_info_struct {

=== modified file 'storage/innodb_plugin/include/srv0srv.h'
--- a/storage/innodb_plugin/include/srv0srv.h	2009-10-08 11:28:37 +0000
+++ b/storage/innodb_plugin/include/srv0srv.h	2009-11-30 11:32:05 +0000
@@ -411,7 +411,7 @@ void
 srv_init(void);
 /*==========*/
 /*********************************************************************//**
-Frees the OS fast mutex created in srv_boot(). */
+Frees the data structures created in srv_init(). */
 UNIV_INTERN
 void
 srv_free(void);

=== modified file 'storage/innodb_plugin/include/thr0loc.h'
--- a/storage/innodb_plugin/include/thr0loc.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/thr0loc.h	2009-11-30 11:32:05 +0000
@@ -39,6 +39,12 @@ UNIV_INTERN
 void
 thr_local_init(void);
 /*================*/
+ /****************************************************************//**
+Close the thread local storage module. */
+UNIV_INTERN
+void
+thr_local_close(void);
+/*=================*/
 /*******************************************************************//**
 Creates a local storage struct for the calling new thread. */
 UNIV_INTERN

=== modified file 'storage/innodb_plugin/include/trx0i_s.h'
--- a/storage/innodb_plugin/include/trx0i_s.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/trx0i_s.h	2009-11-30 11:32:05 +0000
@@ -141,6 +141,13 @@ void
 trx_i_s_cache_init(
 /*===============*/
 	trx_i_s_cache_t*	cache);	/*!< out: cache to init */
+/*******************************************************************//**
+Free the INFORMATION SCHEMA trx related cache. */
+UNIV_INTERN
+void
+trx_i_s_cache_free(
+/*===============*/
+	trx_i_s_cache_t*	cache);	/*!< in/out: cache to free */
 
 /*******************************************************************//**
 Issue a shared/read lock on the tables cache. */

=== modified file 'storage/innodb_plugin/include/trx0purge.h'
--- a/storage/innodb_plugin/include/trx0purge.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/trx0purge.h	2009-11-30 11:32:05 +0000
@@ -71,6 +71,12 @@ void
 trx_purge_sys_create(void);
 /*======================*/
 /********************************************************************//**
+Frees the global purge system control structure. */
+UNIV_INTERN
+void
+trx_purge_sys_close(void);
+/*======================*/
+/************************************************************************
 Adds the update undo log as the first log in the history list. Removes the
 update undo log segment from the rseg slot if it is too big for reuse. */
 UNIV_INTERN

=== modified file 'storage/innodb_plugin/include/trx0rseg.h'
--- a/storage/innodb_plugin/include/trx0rseg.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/trx0rseg.h	2009-11-30 11:32:05 +0000
@@ -125,6 +125,13 @@ trx_rseg_create(
 	ulint	max_size,	/*!< in: max size in pages */
 	ulint*	id,		/*!< out: rseg id */
 	mtr_t*	mtr);		/*!< in: mtr */
+/***************************************************************************
+Free's an instance of the rollback segment in memory. */
+UNIV_INTERN
+void
+trx_rseg_mem_free(
+/*==============*/
+	trx_rseg_t*	rseg);		/* in, own: instance to free */
 
 
 /* Number of undo log slots in a rollback segment file copy */

=== modified file 'storage/innodb_plugin/include/trx0sys.h'
--- a/storage/innodb_plugin/include/trx0sys.h	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/include/trx0sys.h	2009-11-30 11:32:05 +0000
@@ -334,6 +334,12 @@ void
 trx_sys_file_format_tag_init(void);
 /*==============================*/
 /*****************************************************************//**
+Shutdown/Close the transaction system. */
+UNIV_INTERN
+void
+trx_sys_close(void);
+/*===============*/
+/*****************************************************************//**
 Get the name representation of the file format from its id.
 @return	pointer to the name */
 UNIV_INTERN

=== modified file 'storage/innodb_plugin/include/trx0trx.h'
--- a/storage/innodb_plugin/include/trx0trx.h	2009-10-08 13:05:59 +0000
+++ b/storage/innodb_plugin/include/trx0trx.h	2009-12-01 10:38:40 +0000
@@ -338,9 +338,7 @@ trx_commit_step(
 
 /**********************************************************************//**
 Prints info about a transaction to the given file. The caller must own the
-kernel mutex and must have called
-innobase_mysql_prepare_print_arbitrary_thd(), unless he knows that MySQL
-or InnoDB cannot meanwhile change the info printed here. */
+kernel mutex. */
 UNIV_INTERN
 void
 trx_print(

=== modified file 'storage/innodb_plugin/include/trx0undo.h'
--- a/storage/innodb_plugin/include/trx0undo.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/trx0undo.h	2009-11-30 11:32:05 +0000
@@ -333,6 +333,13 @@ trx_undo_parse_discard_latest(
 	byte*	end_ptr,/*!< in: buffer end */
 	page_t*	page,	/*!< in: page or NULL */
 	mtr_t*	mtr);	/*!< in: mtr or NULL */
+/************************************************************************
+Frees an undo log memory copy. */
+UNIV_INTERN
+void
+trx_undo_mem_free(
+/*==============*/
+	trx_undo_t*	undo);		/* in: the undo object to be freed */
 
 /* Types of an undo log segment */
 #define	TRX_UNDO_INSERT		1	/* contains undo entries for inserts */

=== modified file 'storage/innodb_plugin/include/univ.i'
--- a/storage/innodb_plugin/include/univ.i	2009-11-03 10:26:39 +0000
+++ b/storage/innodb_plugin/include/univ.i	2009-11-30 13:13:34 +0000
@@ -46,7 +46,7 @@ Created 1/20/1994 Heikki Tuuri
 
 #define INNODB_VERSION_MAJOR	1
 #define INNODB_VERSION_MINOR	0
-#define INNODB_VERSION_BUGFIX	5
+#define INNODB_VERSION_BUGFIX	6
 
 /* The following is the InnoDB version as shown in
 SELECT plugin_version FROM information_schema.plugins;

=== modified file 'storage/innodb_plugin/include/usr0sess.h'
--- a/storage/innodb_plugin/include/usr0sess.h	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/include/usr0sess.h	2009-11-30 11:32:05 +0000
@@ -44,14 +44,12 @@ sess_t*
 sess_open(void);
 /*============*/
 /*********************************************************************//**
-Closes a session, freeing the memory occupied by it, if it is in a state
-where it should be closed.
-@return	TRUE if closed */
+Closes a session, freeing the memory occupied by it. */
 UNIV_INTERN
-ibool
-sess_try_close(
-/*===========*/
-	sess_t*		sess);	/*!< in, own: session object */
+void
+sess_close(
+/*=======*/
+	sess_t*		sess);		/* in, own: session object */
 
 /* The session handle. All fields are protected by the kernel mutex */
 struct sess_struct{

=== modified file 'storage/innodb_plugin/lock/lock0lock.c'
--- a/storage/innodb_plugin/lock/lock0lock.c	2009-10-09 14:13:15 +0000
+++ b/storage/innodb_plugin/lock/lock0lock.c	2009-12-01 10:38:40 +0000
@@ -578,6 +578,23 @@ lock_sys_create(
 }
 
 /*********************************************************************//**
+Closes the lock system at database shutdown. */
+UNIV_INTERN
+void
+lock_sys_close(void)
+/*================*/
+{
+	if (lock_latest_err_file != NULL) {
+		fclose(lock_latest_err_file);
+		lock_latest_err_file = NULL;
+	}
+
+	hash_table_free(lock_sys->rec_hash);
+	mem_free(lock_sys);
+	lock_sys = NULL;
+}
+
+/*********************************************************************//**
 Gets the size of a lock struct.
 @return	size in bytes */
 UNIV_INTERN
@@ -4307,11 +4324,6 @@ lock_print_info_summary(
 /*====================*/
 	FILE*	file)	/*!< in: file where to print */
 {
-	/* We must protect the MySQL thd->query field with a MySQL mutex, and
-	because the MySQL mutex must be reserved before the kernel_mutex of
-	InnoDB, we call innobase_mysql_prepare_print_arbitrary_thd() here. */
-
-	innobase_mysql_prepare_print_arbitrary_thd();
 	lock_mutex_enter_kernel();
 
 	if (lock_deadlock_found) {
@@ -4394,7 +4406,6 @@ loop:
 
 	if (trx == NULL) {
 		lock_mutex_exit_kernel();
-		innobase_mysql_end_print_arbitrary_thd();
 
 		ut_ad(lock_validate());
 
@@ -4478,7 +4489,6 @@ loop:
 			}
 
 			lock_mutex_exit_kernel();
-			innobase_mysql_end_print_arbitrary_thd();
 
 			mtr_start(&mtr);
 
@@ -4489,7 +4499,6 @@ loop:
 
 			load_page_first = FALSE;
 
-			innobase_mysql_prepare_print_arbitrary_thd();
 			lock_mutex_enter_kernel();
 
 			goto loop;

=== modified file 'storage/innodb_plugin/log/log0log.c'
--- a/storage/innodb_plugin/log/log0log.c	2009-10-09 14:13:15 +0000
+++ b/storage/innodb_plugin/log/log0log.c	2009-11-30 11:32:05 +0000
@@ -771,8 +771,6 @@ void
 log_init(void)
 /*==========*/
 {
-	byte*	buf;
-
 	log_sys = mem_alloc(sizeof(log_t));
 
 	mutex_create(&log_sys->mutex, SYNC_LOG);
@@ -787,8 +785,8 @@ log_init(void)
 	ut_a(LOG_BUFFER_SIZE >= 16 * OS_FILE_LOG_BLOCK_SIZE);
 	ut_a(LOG_BUFFER_SIZE >= 4 * UNIV_PAGE_SIZE);
 
-	buf = mem_alloc(LOG_BUFFER_SIZE + OS_FILE_LOG_BLOCK_SIZE);
-	log_sys->buf = ut_align(buf, OS_FILE_LOG_BLOCK_SIZE);
+	log_sys->buf_ptr = mem_alloc(LOG_BUFFER_SIZE + OS_FILE_LOG_BLOCK_SIZE);
+	log_sys->buf = ut_align(log_sys->buf_ptr, OS_FILE_LOG_BLOCK_SIZE);
 
 	log_sys->buf_size = LOG_BUFFER_SIZE;
 
@@ -833,9 +831,9 @@ log_init(void)
 
 	rw_lock_create(&log_sys->checkpoint_lock, SYNC_NO_ORDER_CHECK);
 
-	log_sys->checkpoint_buf
-		= ut_align(mem_alloc(2 * OS_FILE_LOG_BLOCK_SIZE),
-			   OS_FILE_LOG_BLOCK_SIZE);
+	log_sys->checkpoint_buf_ptr = mem_alloc(2 * OS_FILE_LOG_BLOCK_SIZE);
+	log_sys->checkpoint_buf = ut_align(log_sys->checkpoint_buf_ptr,
+					   OS_FILE_LOG_BLOCK_SIZE);
 	memset(log_sys->checkpoint_buf, '\0', OS_FILE_LOG_BLOCK_SIZE);
 	/*----------------------------*/
 
@@ -918,23 +916,33 @@ log_group_init(
 	group->lsn_offset = LOG_FILE_HDR_SIZE;
 	group->n_pending_writes = 0;
 
+	group->file_header_bufs_ptr = mem_alloc(sizeof(byte*) * n_files);
 	group->file_header_bufs = mem_alloc(sizeof(byte*) * n_files);
 #ifdef UNIV_LOG_ARCHIVE
+	group->archive_file_header_bufs_ptr = mem_alloc(
+		sizeof(byte*) * n_files);
 	group->archive_file_header_bufs = mem_alloc(sizeof(byte*) * n_files);
 #endif /* UNIV_LOG_ARCHIVE */
 
 	for (i = 0; i < n_files; i++) {
-		*(group->file_header_bufs + i) = ut_align(
-			mem_alloc(LOG_FILE_HDR_SIZE + OS_FILE_LOG_BLOCK_SIZE),
+		group->file_header_bufs_ptr[i] = mem_alloc(
+			LOG_FILE_HDR_SIZE + OS_FILE_LOG_BLOCK_SIZE);
+
+		group->file_header_bufs[i] = ut_align(
+			group->file_header_bufs_ptr[i],
 			OS_FILE_LOG_BLOCK_SIZE);
 
 		memset(*(group->file_header_bufs + i), '\0',
 		       LOG_FILE_HDR_SIZE);
 
 #ifdef UNIV_LOG_ARCHIVE
-		*(group->archive_file_header_bufs + i) = ut_align(
-			mem_alloc(LOG_FILE_HDR_SIZE + OS_FILE_LOG_BLOCK_SIZE),
+		group->archive_file_header_bufs_ptr[i] = mem_alloc(
+			LOG_FILE_HDR_SIZE + OS_FILE_LOG_BLOCK_SIZE);
+
+		group->archive_file_header_bufs[i] = ut_align(
+			group->archive_file_header_bufs_ptr[i],
 			OS_FILE_LOG_BLOCK_SIZE);
+
 		memset(*(group->archive_file_header_bufs + i), '\0',
 		       LOG_FILE_HDR_SIZE);
 #endif /* UNIV_LOG_ARCHIVE */
@@ -947,8 +955,9 @@ log_group_init(
 	group->archived_offset = 0;
 #endif /* UNIV_LOG_ARCHIVE */
 
-	group->checkpoint_buf = ut_align(
-		mem_alloc(2 * OS_FILE_LOG_BLOCK_SIZE), OS_FILE_LOG_BLOCK_SIZE);
+	group->checkpoint_buf_ptr = mem_alloc(2 * OS_FILE_LOG_BLOCK_SIZE);
+	group->checkpoint_buf = ut_align(group->checkpoint_buf_ptr,
+					 OS_FILE_LOG_BLOCK_SIZE);
 
 	memset(group->checkpoint_buf, '\0', OS_FILE_LOG_BLOCK_SIZE);
 
@@ -3364,4 +3373,95 @@ log_refresh_stats(void)
 	log_sys->n_log_ios_old = log_sys->n_log_ios;
 	log_sys->last_printout_time = time(NULL);
 }
+
+/**********************************************************************
+Closes a log group. */
+static
+void
+log_group_close(
+/*===========*/
+	log_group_t*	group)		/* in,own: log group to close */
+{
+	ulint	i;
+
+	for (i = 0; i < group->n_files; i++) {
+		mem_free(group->file_header_bufs_ptr[i]);
+#ifdef UNIV_LOG_ARCHIVE
+		mem_free(group->archive_file_header_bufs_ptr[i]);
+#endif /* UNIV_LOG_ARCHIVE */
+	}
+
+	mem_free(group->file_header_bufs_ptr);
+	mem_free(group->file_header_bufs);
+
+#ifdef UNIV_LOG_ARCHIVE
+	mem_free(group->archive_file_header_bufs_ptr);
+	mem_free(group->archive_file_header_bufs);
+#endif /* UNIV_LOG_ARCHIVE */
+
+	mem_free(group->checkpoint_buf_ptr);
+
+	mem_free(group);
+}
+
+/**********************************************************
+Shutdown the log system but do not release all the memory. */
+UNIV_INTERN
+void
+log_shutdown(void)
+/*==============*/
+{
+	log_group_t*	group;
+
+	group = UT_LIST_GET_FIRST(log_sys->log_groups);
+
+	while (UT_LIST_GET_LEN(log_sys->log_groups) > 0) {
+		log_group_t*	prev_group = group;
+
+		group = UT_LIST_GET_NEXT(log_groups, group);
+		UT_LIST_REMOVE(log_groups, log_sys->log_groups, prev_group);
+
+		log_group_close(prev_group);
+	}
+
+	mem_free(log_sys->buf_ptr);
+	log_sys->buf_ptr = NULL;
+	log_sys->buf = NULL;
+	mem_free(log_sys->checkpoint_buf_ptr);
+	log_sys->checkpoint_buf_ptr = NULL;
+	log_sys->checkpoint_buf = NULL;
+
+	os_event_free(log_sys->no_flush_event);
+	os_event_free(log_sys->one_flushed_event);
+
+	rw_lock_free(&log_sys->checkpoint_lock);
+
+	mutex_free(&log_sys->mutex);
+
+#ifdef UNIV_LOG_ARCHIVE
+	rw_lock_free(&log_sys->archive_lock);
+	os_event_create(log_sys->archiving_on);
+#endif /* UNIV_LOG_ARCHIVE */
+
+#ifdef UNIV_LOG_DEBUG
+	recv_sys_debug_free();
+#endif
+
+	recv_sys_close();
+}
+
+/**********************************************************
+Free the log system data structures. */
+UNIV_INTERN
+void
+log_mem_free(void)
+/*==============*/
+{
+	if (log_sys != NULL) {
+		recv_sys_mem_free();
+		mem_free(log_sys);
+
+		log_sys = NULL;
+	}
+}
 #endif /* !UNIV_HOTBACKUP */

=== modified file 'storage/innodb_plugin/log/log0recv.c'
--- a/storage/innodb_plugin/log/log0recv.c	2009-10-09 14:13:15 +0000
+++ b/storage/innodb_plugin/log/log0recv.c	2009-11-30 11:32:05 +0000
@@ -69,15 +69,15 @@ UNIV_INTERN recv_sys_t*	recv_sys = NULL;
 /** TRUE when applying redo log records during crash recovery; FALSE
 otherwise.  Note that this is FALSE while a background thread is
 rolling back incomplete transactions. */
-UNIV_INTERN ibool	recv_recovery_on = FALSE;
+UNIV_INTERN ibool	recv_recovery_on;
 #ifdef UNIV_LOG_ARCHIVE
 /** TRUE when applying redo log records from an archived log file */
-UNIV_INTERN ibool	recv_recovery_from_backup_on = FALSE;
+UNIV_INTERN ibool	recv_recovery_from_backup_on;
 #endif /* UNIV_LOG_ARCHIVE */
 
 #ifndef UNIV_HOTBACKUP
 /** TRUE when recv_init_crash_recovery() has been called. */
-UNIV_INTERN ibool	recv_needed_recovery = FALSE;
+UNIV_INTERN ibool	recv_needed_recovery;
 # ifdef UNIV_DEBUG
 /** TRUE if writing to the redo log (mtr_commit) is forbidden.
 Protected by log_sys->mutex. */
@@ -87,7 +87,7 @@ UNIV_INTERN ibool	recv_no_log_write = FA
 /** TRUE if buf_page_is_corrupted() should check if the log sequence
 number (FIL_PAGE_LSN) is in the future.  Initially FALSE, and set by
 recv_recovery_from_checkpoint_start_func(). */
-UNIV_INTERN ibool	recv_lsn_checks_on = FALSE;
+UNIV_INTERN ibool	recv_lsn_checks_on;
 
 /** There are two conditions under which we scan the logs, the first
 is normal startup and the second is when we do a recovery from an
@@ -97,7 +97,7 @@ startup. If we find log entries that wer
 we know that the server was not cleanly shutdown. We must then initialize
 the crash recovery environment before attempting to store these entries in
 the log hash table. */
-static ibool		recv_log_scan_is_startup_type = FALSE;
+static ibool		recv_log_scan_is_startup_type;
 
 /** If the following is TRUE, the buffer pool file pages must be invalidated
 after recovery and no ibuf operations are allowed; this becomes TRUE if
@@ -108,7 +108,7 @@ buffer pool before the pages have been r
 
 TRUE means that recovery is running and no operations on the log files
 are allowed yet: the variable name is misleading. */
-UNIV_INTERN ibool	recv_no_ibuf_operations = FALSE;
+UNIV_INTERN ibool	recv_no_ibuf_operations;
 /** TRUE when the redo log is being backed up */
 # define recv_is_making_a_backup		FALSE
 /** TRUE when recovering from a backed up redo log file */
@@ -116,30 +116,30 @@ UNIV_INTERN ibool	recv_no_ibuf_operation
 #else /* !UNIV_HOTBACKUP */
 # define recv_needed_recovery			FALSE
 /** TRUE when the redo log is being backed up */
-UNIV_INTERN ibool	recv_is_making_a_backup = FALSE;
+UNIV_INTERN ibool	recv_is_making_a_backup	= FALSE;
 /** TRUE when recovering from a backed up redo log file */
 UNIV_INTERN ibool	recv_is_from_backup	= FALSE;
 # define buf_pool_get_curr_size() (5 * 1024 * 1024)
 #endif /* !UNIV_HOTBACKUP */
 /** The following counter is used to decide when to print info on
 log scan */
-static ulint	recv_scan_print_counter	= 0;
+static ulint	recv_scan_print_counter;
 
 /** The type of the previous parsed redo log record */
-static ulint	recv_previous_parsed_rec_type	= 999999;
+static ulint	recv_previous_parsed_rec_type;
 /** The offset of the previous parsed redo log record */
-static ulint	recv_previous_parsed_rec_offset	= 0;
+static ulint	recv_previous_parsed_rec_offset;
 /** The 'multi' flag of the previous parsed redo log record */
-static ulint	recv_previous_parsed_rec_is_multi = 0;
+static ulint	recv_previous_parsed_rec_is_multi;
 
 /** Maximum page number encountered in the redo log */
-UNIV_INTERN ulint	recv_max_parsed_page_no		= 0;
+UNIV_INTERN ulint	recv_max_parsed_page_no;
 
 /** This many frames must be left free in the buffer pool when we scan
 the log and store the scanned log records in the buffer pool: we will
 use these free frames to read in pages when we start applying the
 log records to the database. */
-UNIV_INTERN ulint	recv_n_pool_free_frames		= 256;
+UNIV_INTERN ulint	recv_n_pool_free_frames;
 
 /** The maximum lsn we see for a page during the recovery process. If this
 is bigger than the lsn we are able to scan up to, that is an indication that
@@ -170,7 +170,8 @@ recv_sys_create(void)
 		return;
 	}
 
-	recv_sys = mem_alloc(sizeof(recv_sys_t));
+	recv_sys = mem_alloc(sizeof(*recv_sys));
+	memset(recv_sys, 0x0, sizeof(*recv_sys));
 
 	mutex_create(&recv_sys->mutex, SYNC_RECV);
 
@@ -179,6 +180,106 @@ recv_sys_create(void)
 }
 
 /********************************************************//**
+Release recovery system mutexes. */
+UNIV_INTERN
+void
+recv_sys_close(void)
+/*================*/
+{
+	if (recv_sys != NULL) {
+		if (recv_sys->addr_hash != NULL) {
+			hash_table_free(recv_sys->addr_hash);
+		}
+
+		if (recv_sys->heap != NULL) {
+			mem_heap_free(recv_sys->heap);
+		}
+
+		if (recv_sys->buf != NULL) {
+			ut_free(recv_sys->buf);
+		}
+
+		if (recv_sys->last_block_buf_start != NULL) {
+			mem_free(recv_sys->last_block_buf_start);
+		}
+
+		mutex_free(&recv_sys->mutex);
+
+		mem_free(recv_sys);
+		recv_sys = NULL;
+	}
+}
+
+/********************************************************//**
+Frees the recovery system memory. */
+UNIV_INTERN
+void
+recv_sys_mem_free(void)
+/*===================*/
+{
+	if (recv_sys != NULL) {
+		if (recv_sys->addr_hash != NULL) {
+			hash_table_free(recv_sys->addr_hash);
+		}
+
+		if (recv_sys->heap != NULL) {
+			mem_heap_free(recv_sys->heap);
+		}
+
+		if (recv_sys->buf != NULL) {
+			ut_free(recv_sys->buf);
+		}
+
+		if (recv_sys->last_block_buf_start != NULL) {
+			mem_free(recv_sys->last_block_buf_start);
+		}
+
+		mem_free(recv_sys);
+		recv_sys = NULL;
+	}
+}
+
+/************************************************************
+Reset the state of the recovery system variables. */
+UNIV_INTERN
+void
+recv_sys_var_init(void)
+/*===================*/
+{
+	recv_lsn_checks_on = FALSE;
+
+	recv_n_pool_free_frames = 256;
+
+	recv_recovery_on = FALSE;
+
+#ifdef UNIV_LOG_ARCHIVE
+	recv_recovery_from_backup_on = FALSE;
+#endif /* UNIV_LOG_ARCHIVE */
+
+	recv_needed_recovery = FALSE;
+
+	recv_lsn_checks_on = FALSE;
+
+	recv_log_scan_is_startup_type = FALSE;
+
+	recv_no_ibuf_operations = FALSE;
+
+	recv_scan_print_counter	= 0;
+
+	recv_previous_parsed_rec_type	= 999999;
+
+	recv_previous_parsed_rec_offset	= 0;
+
+	recv_previous_parsed_rec_is_multi = 0;
+
+	recv_max_parsed_page_no	= 0;
+
+	recv_n_pool_free_frames	= 256;
+
+	recv_max_page_lsn = 0;
+}
+
+/************************************************************
 Inits the recovery system for a recovery operation. */
 UNIV_INTERN
 void
@@ -253,8 +354,8 @@ recv_sys_empty_hash(void)
 Frees the recovery system. */
 static
 void
-recv_sys_free(void)
-/*===============*/
+recv_sys_debug_free(void)
+/*=====================*/
 {
 	mutex_enter(&(recv_sys->mutex));
 
@@ -263,8 +364,10 @@ recv_sys_free(void)
 	ut_free(recv_sys->buf);
 	mem_free(recv_sys->last_block_buf_start);
 
-	recv_sys->addr_hash = NULL;
+	recv_sys->buf = NULL;
 	recv_sys->heap = NULL;
+	recv_sys->addr_hash = NULL;
+	recv_sys->last_block_buf_start = NULL;
 
 	mutex_exit(&(recv_sys->mutex));
 }
@@ -3149,7 +3252,7 @@ recv_recovery_from_checkpoint_finish(voi
 	recv_recovery_on = FALSE;
 
 #ifndef UNIV_LOG_DEBUG
-	recv_sys_free();
+	recv_sys_debug_free();
 #endif
 	/* Roll back any recovered data dictionary transactions, so
 	that the data dictionary tables will be free of any locks.

=== modified file 'storage/innodb_plugin/mem/mem0dbg.c'
--- a/storage/innodb_plugin/mem/mem0dbg.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/mem/mem0dbg.c	2009-11-30 11:32:05 +0000
@@ -170,6 +170,17 @@ mem_init(
 
 	mem_comm_pool = mem_pool_create(size);
 }
+
+/******************************************************************//**
+Closes the memory system. */
+UNIV_INTERN
+void
+mem_close(void)
+/*===========*/
+{
+	mem_pool_free(mem_comm_pool);
+	mem_comm_pool = NULL;
+}
 #endif /* !UNIV_HOTBACKUP */
 
 #ifdef UNIV_MEM_DEBUG

=== modified file 'storage/innodb_plugin/mem/mem0pool.c'
--- a/storage/innodb_plugin/mem/mem0pool.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/mem/mem0pool.c	2009-11-30 11:32:05 +0000
@@ -261,6 +261,18 @@ mem_pool_create(
 }
 
 /********************************************************************//**
+Frees a memory pool. */
+UNIV_INTERN
+void
+mem_pool_free(
+/*==========*/
+	mem_pool_t*	pool)	/*!< in, own: memory pool */
+{
+	ut_free(pool->buf);
+	ut_free(pool);
+}
+
+/********************************************************************//**
 Fills the specified free list.
 @return	TRUE if we were able to insert a block to the free list */
 static

=== modified file 'storage/innodb_plugin/os/os0file.c'
--- a/storage/innodb_plugin/os/os0file.c	2009-11-03 09:59:31 +0000
+++ b/storage/innodb_plugin/os/os0file.c	2009-11-30 12:04:09 +0000
@@ -323,6 +323,13 @@ os_file_get_last_error(
 				"InnoDB: The error means that there are no"
 				" sufficient system resources or quota to"
 				" complete the operation.\n");
+		} else if (err == ERROR_OPERATION_ABORTED) {
+			fprintf(stderr,
+				"InnoDB: The error means that the I/O"
+				" operation has been aborted\n"
+				"InnoDB: because of either a thread exit"
+				" or an application request.\n"
+				"InnoDB: Retry attempt is made.\n");
 		} else {
 			fprintf(stderr,
 				"InnoDB: Some operating system error numbers"
@@ -347,6 +354,8 @@ os_file_get_last_error(
 	} else if (err == ERROR_WORKING_SET_QUOTA
 		   || err == ERROR_NO_SYSTEM_RESOURCES) {
 		return(OS_FILE_INSUFFICIENT_RESOURCE);
+	} else if (err == ERROR_OPERATION_ABORTED) {
+		return(OS_FILE_OPERATION_ABORTED);
 	} else {
 		return(100 + err);
 	}
@@ -469,6 +478,10 @@ os_file_handle_error_cond_exit(
 
 		os_thread_sleep(100000);	/* 100 ms */
 		return(TRUE);
+	} else if (err == OS_FILE_OPERATION_ABORTED) {
+
+		os_thread_sleep(100000);	/* 100 ms */
+		return(TRUE);
 	} else {
 		if (name) {
 			fprintf(stderr, "InnoDB: File name %s\n", name);
@@ -3029,6 +3042,34 @@ os_aio_array_create(
 	return(array);
 }
 
+/************************************************************************//**
+Frees an aio wait array. */
+static
+void
+os_aio_array_free(
+/*==============*/
+	os_aio_array_t*	array)	/*!< in, own: array to free */
+{
+#ifdef WIN_ASYNC_IO
+	ulint	i;
+
+	for (i = 0; i < array->n_slots; i++) {
+		os_aio_slot_t*	slot = os_aio_array_get_nth_slot(array, i);
+		os_event_free(slot->event);
+	}
+#endif /* WIN_ASYNC_IO */
+
+#ifdef __WIN__
+	ut_free(array->native_events);
+#endif /* __WIN__ */
+	os_mutex_free(array->mutex);
+	os_event_free(array->not_full);
+	os_event_free(array->is_empty);
+
+	ut_free(array->slots);
+	ut_free(array);
+}
+
 /***********************************************************************
 Initializes the asynchronous io system. Creates one array each for ibuf
 and log i/o. Also creates one array each for read and write where each
@@ -3099,6 +3140,35 @@ os_aio_init(
 
 }
 
+/***********************************************************************
+Frees the asynchronous io system. */
+UNIV_INTERN
+void
+os_aio_free(void)
+/*=============*/
+{
+	ulint	i;
+
+	os_aio_array_free(os_aio_ibuf_array);
+	os_aio_ibuf_array = NULL;
+	os_aio_array_free(os_aio_log_array);
+	os_aio_log_array = NULL;
+	os_aio_array_free(os_aio_read_array);
+	os_aio_read_array = NULL;
+	os_aio_array_free(os_aio_write_array);
+	os_aio_write_array = NULL;
+	os_aio_array_free(os_aio_sync_array);
+	os_aio_sync_array = NULL;
+
+	for (i = 0; i < os_aio_n_segments; i++) {
+		os_event_free(os_aio_segment_wait_events[i]);
+	}
+
+	ut_free(os_aio_segment_wait_events);
+	os_aio_segment_wait_events = 0;
+	os_aio_n_segments = 0;
+}
+
 #ifdef WIN_ASYNC_IO
 /************************************************************************//**
 Wakes up all async i/o threads in the array in Windows async i/o at
@@ -3709,6 +3779,7 @@ os_aio_windows_handle(
 	ibool		ret_val;
 	BOOL		ret;
 	DWORD		len;
+	BOOL		retry		= FALSE;
 
 	if (segment == ULINT_UNDEFINED) {
 		array = os_aio_sync_array;
@@ -3762,14 +3833,52 @@ os_aio_windows_handle(
 			ut_a(TRUE == os_file_flush(slot->file));
 		}
 #endif /* UNIV_DO_FLUSH */
+	} else if (os_file_handle_error(slot->name, "Windows aio")) {
+
+		retry = TRUE;
 	} else {
-		os_file_handle_error(slot->name, "Windows aio");
 
 		ret_val = FALSE;
 	}
 
 	os_mutex_exit(array->mutex);
 
+	if (retry) {
+		/* retry failed read/write operation synchronously.
+		No need to hold array->mutex. */
+
+		switch (slot->type) {
+		case OS_FILE_WRITE:
+			ret = WriteFile(slot->file, slot->buf,
+					slot->len, &len,
+					&(slot->control));
+
+			break;
+		case OS_FILE_READ:
+			ret = ReadFile(slot->file, slot->buf,
+				       slot->len, &len,
+				       &(slot->control));
+
+			break;
+		default:
+			ut_error;
+		}
+
+		if (!ret && GetLastError() == ERROR_IO_PENDING) {
+			/* aio was queued successfully!
+			We want a synchronous i/o operation on a
+			file where we also use async i/o: in Windows
+			we must use the same wait mechanism as for
+			async i/o */
+
+			ret = GetOverlappedResult(slot->file,
+						  &(slot->control),
+						  &len, TRUE);
+		}
+
+		ret_val = ret && len == slot->len;
+	}
+
 	os_aio_array_free_slot(array, slot);
 
 	return(ret_val);

=== modified file 'storage/innodb_plugin/os/os0sync.c'
--- a/storage/innodb_plugin/os/os0sync.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/os/os0sync.c	2009-11-30 11:32:05 +0000
@@ -86,6 +86,9 @@ os_sync_init(void)
 	UT_LIST_INIT(os_event_list);
 	UT_LIST_INIT(os_mutex_list);
 
+	os_sync_mutex = NULL;
+	os_sync_mutex_inited = FALSE;
+
 	os_sync_mutex = os_mutex_create(NULL);
 
 	os_sync_mutex_inited = TRUE;
@@ -713,6 +716,7 @@ os_fast_mutex_free(
 		os_mutex_enter(os_sync_mutex);
 	}
 
+	ut_ad(os_fast_mutex_count > 0);
 	os_fast_mutex_count--;
 
 	if (UNIV_LIKELY(os_sync_mutex_inited)) {

=== modified file 'storage/innodb_plugin/os/os0thread.c'
--- a/storage/innodb_plugin/os/os0thread.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/os/os0thread.c	2009-11-30 11:32:05 +0000
@@ -233,6 +233,7 @@ os_thread_exit(
 #ifdef __WIN__
 	ExitThread((DWORD)exit_value);
 #else
+	pthread_detach(pthread_self());
 	pthread_exit(exit_value);
 #endif
 }

=== modified file 'storage/innodb_plugin/pars/lexyy.c'
--- a/storage/innodb_plugin/pars/lexyy.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/pars/lexyy.c	2009-11-30 11:32:05 +0000
@@ -2778,3 +2778,16 @@ static void yyfree (void * ptr )
 
 
 
+
+/**********************************************************************
+Release any resources used by the lexer. */
+UNIV_INTERN
+void
+pars_lexer_close(void)
+/*==================*/
+{
+	yylex_destroy();
+	free(stringbuf);
+	stringbuf = NULL;
+	stringbuf_len_alloc = stringbuf_len = 0;
+}

=== modified file 'storage/innodb_plugin/pars/pars0lex.l'
--- a/storage/innodb_plugin/pars/pars0lex.l	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/pars/pars0lex.l	2009-11-30 11:32:05 +0000
@@ -661,3 +661,16 @@ In the state 'id', only two actions are
 }
 
 %%
+
+/**********************************************************************
+Release any resources used by the lexer. */
+UNIV_INTERN
+void
+pars_lexer_close(void)
+/*==================*/
+{
+	yylex_destroy();
+	free(stringbuf);
+	stringbuf = NULL;
+	stringbuf_len_alloc = stringbuf_len = 0;
+}

=== modified file 'storage/innodb_plugin/que/que0que.c'
--- a/storage/innodb_plugin/que/que0que.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/que/que0que.c	2009-11-30 11:32:05 +0000
@@ -518,6 +518,7 @@ que_graph_free_recursive(
 	upd_node_t*	upd;
 	tab_node_t*	cre_tab;
 	ind_node_t*	cre_ind;
+	purge_node_t*	purge;
 
 	if (node == NULL) {
 
@@ -579,6 +580,13 @@ que_graph_free_recursive(
 		mem_heap_free(ins->entry_sys_heap);
 
 		break;
+	case QUE_NODE_PURGE:
+		purge = node;
+
+		mem_heap_free(purge->heap);
+
+		break;
+
 	case QUE_NODE_UPDATE:
 
 		upd = node;

=== modified file 'storage/innodb_plugin/row/row0merge.c'
--- a/storage/innodb_plugin/row/row0merge.c	2009-10-09 14:13:15 +0000
+++ b/storage/innodb_plugin/row/row0merge.c	2009-11-30 12:24:54 +0000
@@ -1200,6 +1200,12 @@ row_merge_read_clustered_index(
 		in order to release the latch on the old page. */
 
 		if (btr_pcur_is_after_last_on_page(&pcur)) {
+			if (UNIV_UNLIKELY(trx_is_interrupted(trx))) {
+				i = 0;
+				err = DB_INTERRUPTED;
+				goto err_exit;
+			}
+
 			btr_pcur_store_position(&pcur, &mtr);
 			mtr_commit(&mtr);
 			mtr_start(&mtr);
@@ -1557,6 +1563,7 @@ static __attribute__((nonnull))
 ulint
 row_merge(
 /*======*/
+	trx_t*			trx,	/*!< in: transaction */
 	const dict_index_t*	index,	/*!< in: index being created */
 	merge_file_t*		file,	/*!< in/out: file containing
 					index entries */
@@ -1590,6 +1597,10 @@ row_merge(
 	for (; foffs0 < ihalf && foffs1 < file->offset; foffs0++, foffs1++) {
 		ulint	ahalf;	/*!< arithmetic half the input file */
 
+		if (UNIV_UNLIKELY(trx_is_interrupted(trx))) {
+			return(DB_INTERRUPTED);
+		}
+
 		error = row_merge_blocks(index, file, block,
 					 &foffs0, &foffs1, &of, table);
 
@@ -1617,6 +1628,10 @@ row_merge(
 	/* Copy the last blocks, if there are any. */
 
 	while (foffs0 < ihalf) {
+		if (UNIV_UNLIKELY(trx_is_interrupted(trx))) {
+			return(DB_INTERRUPTED);
+		}
+
 		if (!row_merge_blocks_copy(index, file, block, &foffs0, &of)) {
 			return(DB_CORRUPTION);
 		}
@@ -1625,6 +1640,10 @@ row_merge(
 	ut_ad(foffs0 == ihalf);
 
 	while (foffs1 < file->offset) {
+		if (UNIV_UNLIKELY(trx_is_interrupted(trx))) {
+			return(DB_INTERRUPTED);
+		}
+
 		if (!row_merge_blocks_copy(index, file, block, &foffs1, &of)) {
 			return(DB_CORRUPTION);
 		}
@@ -1653,6 +1672,7 @@ static
 ulint
 row_merge_sort(
 /*===========*/
+	trx_t*			trx,	/*!< in: transaction */
 	const dict_index_t*	index,	/*!< in: index being created */
 	merge_file_t*		file,	/*!< in/out: file containing
 					index entries */
@@ -1671,7 +1691,8 @@ row_merge_sort(
 	do {
 		ulint	error;
 
-		error = row_merge(index, file, &half, block, tmpfd, table);
+		error = row_merge(trx, index, file, &half,
+				  block, tmpfd, table);
 
 		if (error != DB_SUCCESS) {
 			return(error);
@@ -2490,7 +2511,7 @@ row_merge_build_indexes(
 	sorting and inserting. */
 
 	for (i = 0; i < n_indexes; i++) {
-		error = row_merge_sort(indexes[i], &merge_files[i],
+		error = row_merge_sort(trx, indexes[i], &merge_files[i],
 				       block, &tmpfd, table);
 
 		if (error == DB_SUCCESS) {

=== modified file 'storage/innodb_plugin/row/row0mysql.c'
--- a/storage/innodb_plugin/row/row0mysql.c	2009-11-03 10:32:33 +0000
+++ b/storage/innodb_plugin/row/row0mysql.c	2009-11-30 13:13:34 +0000
@@ -1880,6 +1880,8 @@ err_exit:
 	if (UNIV_UNLIKELY(err != DB_SUCCESS)) {
 		trx->error_state = DB_SUCCESS;
 		trx_general_rollback_for_mysql(trx, NULL);
+		/* TO DO: free table?  The code below will dereference
+		table->name, though. */
 	}
 
 	switch (err) {
@@ -1898,31 +1900,6 @@ err_exit:
 		break;
 
 	case DB_DUPLICATE_KEY:
-		ut_print_timestamp(stderr);
-		fputs("  InnoDB: Error: table ", stderr);
-		ut_print_name(stderr, trx, TRUE, table->name);
-		fputs(" already exists in InnoDB internal\n"
-		      "InnoDB: data dictionary. Have you deleted"
-		      " the .frm file\n"
-		      "InnoDB: and not used DROP TABLE?"
-		      " Have you used DROP DATABASE\n"
-		      "InnoDB: for InnoDB tables in"
-		      " MySQL version <= 3.23.43?\n"
-		      "InnoDB: See the Restrictions section"
-		      " of the InnoDB manual.\n"
-		      "InnoDB: You can drop the orphaned table"
-		      " inside InnoDB by\n"
-		      "InnoDB: creating an InnoDB table with"
-		      " the same name in another\n"
-		      "InnoDB: database and copying the .frm file"
-		      " to the current database.\n"
-		      "InnoDB: Then MySQL thinks the table exists,"
-		      " and DROP TABLE will\n"
-		      "InnoDB: succeed.\n"
-		      "InnoDB: You can look for further help from\n"
-		      "InnoDB: " REFMAN "innodb-troubleshooting.html\n",
-		      stderr);
-
 		/* We may also get err == DB_ERROR if the .ibd file for the
 		table already exists */
 
@@ -4157,6 +4134,7 @@ row_check_table_for_mysql(
 			}
 
 			if (trx_is_interrupted(prebuilt->trx)) {
+				ret = DB_INTERRUPTED;
 				break;
 			}
 

=== modified file 'storage/innodb_plugin/srv/srv0srv.c'
--- a/storage/innodb_plugin/srv/srv0srv.c	2009-10-09 12:19:13 +0000
+++ b/storage/innodb_plugin/srv/srv0srv.c	2009-11-30 11:32:05 +0000
@@ -1006,13 +1006,26 @@ srv_init(void)
 }
 
 /*********************************************************************//**
-Frees the OS fast mutex created in srv_init(). */
+Frees the data structures created in srv_init(). */
 UNIV_INTERN
 void
 srv_free(void)
 /*==========*/
 {
 	os_fast_mutex_free(&srv_conc_mutex);
+	mem_free(srv_conc_slots);
+	srv_conc_slots = NULL;
+
+	mem_free(srv_sys->threads);
+	mem_free(srv_sys);
+	srv_sys = NULL;
+
+	mem_free(kernel_mutex_temp);
+	kernel_mutex_temp = NULL;
+	mem_free(srv_mysql_table);
+	srv_mysql_table = NULL;
+
+	trx_i_s_cache_free(trx_i_s_cache);
 }
 
 /*********************************************************************//**
@@ -1024,6 +1037,8 @@ srv_general_init(void)
 /*==================*/
 {
 	ut_mem_init();
+	/* Reset the system variables in the recovery module. */
+	recv_sys_var_init();
 	os_sync_init();
 	sync_init();
 	mem_init(srv_mem_pool_size);

=== modified file 'storage/innodb_plugin/srv/srv0start.c'
--- a/storage/innodb_plugin/srv/srv0start.c	2009-11-03 10:23:22 +0000
+++ b/storage/innodb_plugin/srv/srv0start.c	2009-11-30 11:32:05 +0000
@@ -103,6 +103,7 @@ Created 2/16/1996 Heikki Tuuri
 # include "row0row.h"
 # include "row0mysql.h"
 # include "btr0pcur.h"
+# include "thr0loc.h"
 # include "os0sync.h" /* for INNODB_RW_LOCKS_USE_ATOMICS */
 
 /** Log sequence number immediately after startup */
@@ -495,6 +496,8 @@ io_handler_thread(
 		mutex_exit(&ios_mutex);
 	}
 
+	thr_local_free(os_thread_get_curr_id());
+
 	/* We count the number of threads in os_thread_exit(). A created
 	thread should always use that to exit and not use return() to exit.
 	The thread actually never comes here because it is exited in an
@@ -531,32 +534,6 @@ srv_normalize_path_for_win(
 #endif
 }
 
-/*********************************************************************//**
-Adds a slash or a backslash to the end of a string if it is missing
-and the string is not empty.
-@return	string which has the separator if the string is not empty */
-UNIV_INTERN
-char*
-srv_add_path_separator_if_needed(
-/*=============================*/
-	char*	str)	/*!< in: null-terminated character string */
-{
-	char*	out_str;
-	ulint	len	= ut_strlen(str);
-
-	if (len == 0 || str[len - 1] == SRV_PATH_SEPARATOR) {
-
-		return(str);
-	}
-
-	out_str = ut_malloc(len + 2);
-	memcpy(out_str, str, len);
-	out_str[len] = SRV_PATH_SEPARATOR;
-	out_str[len + 1] = 0;
-
-	return(out_str);
-}
-
 #ifndef UNIV_HOTBACKUP
 /*********************************************************************//**
 Calculates the low 32 bits when a file size which is given as a number
@@ -605,19 +582,24 @@ open_or_create_log_file(
 	ulint	size;
 	ulint	size_high;
 	char	name[10000];
+	ulint	dirnamelen;
 
 	UT_NOT_USED(create_new_db);
 
 	*log_file_created = FALSE;
 
 	srv_normalize_path_for_win(srv_log_group_home_dirs[k]);
-	srv_log_group_home_dirs[k] = srv_add_path_separator_if_needed(
-		srv_log_group_home_dirs[k]);
 
-	ut_a(strlen(srv_log_group_home_dirs[k])
-	     < (sizeof name) - 10 - sizeof "ib_logfile");
-	sprintf(name, "%s%s%lu", srv_log_group_home_dirs[k],
-		"ib_logfile", (ulong) i);
+	dirnamelen = strlen(srv_log_group_home_dirs[k]);
+	ut_a(dirnamelen < (sizeof name) - 10 - sizeof "ib_logfile");
+	memcpy(name, srv_log_group_home_dirs[k], dirnamelen);
+
+	/* Add a path separator if needed. */
+	if (dirnamelen && name[dirnamelen - 1] != SRV_PATH_SEPARATOR) {
+		name[dirnamelen++] = SRV_PATH_SEPARATOR;
+	}
+
+	sprintf(name + dirnamelen, "%s%lu", "ib_logfile", (ulong) i);
 
 	files[i] = os_file_create(name, OS_FILE_CREATE, OS_FILE_NORMAL,
 				  OS_LOG_FILE, &ret);
@@ -780,14 +762,22 @@ open_or_create_data_files(
 	*create_new_db = FALSE;
 
 	srv_normalize_path_for_win(srv_data_home);
-	srv_data_home = srv_add_path_separator_if_needed(srv_data_home);
 
 	for (i = 0; i < srv_n_data_files; i++) {
+		ulint	dirnamelen;
+
 		srv_normalize_path_for_win(srv_data_file_names[i]);
+		dirnamelen = strlen(srv_data_home);
 
-		ut_a(strlen(srv_data_home) + strlen(srv_data_file_names[i])
+		ut_a(dirnamelen + strlen(srv_data_file_names[i])
 		     < (sizeof name) - 1);
-		sprintf(name, "%s%s", srv_data_home, srv_data_file_names[i]);
+		memcpy(name, srv_data_home, dirnamelen);
+		/* Add a path separator if needed. */
+		if (dirnamelen && name[dirnamelen - 1] != SRV_PATH_SEPARATOR) {
+			name[dirnamelen++] = SRV_PATH_SEPARATOR;
+		}
+
+		strcpy(name + dirnamelen, srv_data_file_names[i]);
 
 		if (srv_data_file_is_raw_partition[i] == 0) {
 
@@ -1009,7 +999,7 @@ skip_size_check:
 	return(DB_SUCCESS);
 }
 
-/****************************************************************//**
+/********************************************************************
 Starts InnoDB and creates a new database if database files
 are not found and the user wants.
 @return	DB_SUCCESS or error code */
@@ -1120,7 +1110,7 @@ innobase_start_or_create_for_mysql(void)
 
 	if (srv_start_has_been_called) {
 		fprintf(stderr,
-			"InnoDB: Error:startup called second time"
+			"InnoDB: Error: startup called second time"
 			" during the process lifetime.\n"
 			"InnoDB: In the MySQL Embedded Server Library"
 			" you cannot call server_init()\n"
@@ -1959,8 +1949,10 @@ innobase_shutdown_for_mysql(void)
 			/* All the threads have exited or are just exiting;
 			NOTE that the threads may not have completed their
 			exit yet. Should we use pthread_join() to make sure
-			they have exited? Now we just sleep 0.1 seconds and
-			hope that is enough! */
+			they have exited? If we did, we would have to
+			remove the pthread_detach() from
+			os_thread_exit().  Now we just sleep 0.1
+			seconds and hope that is enough! */
 
 			os_mutex_exit(os_sync_mutex);
 
@@ -1999,37 +1991,41 @@ innobase_shutdown_for_mysql(void)
 		srv_misc_tmpfile = 0;
 	}
 
+	/* This must be disabled before closing the buffer pool
+	and closing the data dictionary.  */
+	btr_search_disable();
+
+	ibuf_close();
+	log_shutdown();
+	lock_sys_close();
+	thr_local_close();
 	trx_sys_file_format_close();
+	trx_sys_close();
 
 	mutex_free(&srv_monitor_file_mutex);
 	mutex_free(&srv_dict_tmpfile_mutex);
 	mutex_free(&srv_misc_tmpfile_mutex);
+	dict_close();
+	btr_search_sys_free();
 
 	/* 3. Free all InnoDB's own mutexes and the os_fast_mutexes inside
 	them */
+	os_aio_free();
 	sync_close();
+	srv_free();
+	fil_close();
 
 	/* 4. Free the os_conc_mutex and all os_events and os_mutexes */
 
-	srv_free();
 	os_sync_free();
 
-	/* Check that all read views are closed except read view owned
-	by a purge. */
-
-	if (UT_LIST_GET_LEN(trx_sys->view_list) > 1) {
-		fprintf(stderr,
-			"InnoDB: Error: all read views were not closed"
-			" before shutdown:\n"
-			"InnoDB: %lu read views open \n",
-			UT_LIST_GET_LEN(trx_sys->view_list) - 1);
-	}
-
-	/* 5. Free all allocated memory and the os_fast_mutex created in
-	ut0mem.c */
+	/* 5. Free all allocated memory */
 
+	pars_lexer_close();
+	log_mem_free();
 	buf_pool_free();
 	ut_free_all_mem();
+	mem_close();
 
 	if (os_thread_count != 0
 	    || os_event_count != 0
@@ -2060,6 +2056,7 @@ innobase_shutdown_for_mysql(void)
 	}
 
 	srv_was_started = FALSE;
+	srv_start_has_been_called = FALSE;
 
 	return((int) DB_SUCCESS);
 }

=== modified file 'storage/innodb_plugin/sync/sync0arr.c'
--- a/storage/innodb_plugin/sync/sync0arr.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/sync/sync0arr.c	2009-11-30 11:32:05 +0000
@@ -227,24 +227,21 @@ sync_array_create(
 				SYNC_ARRAY_MUTEX: determines the type
 				of mutex protecting the data structure */
 {
+	ulint		sz;
 	sync_array_t*	arr;
-	sync_cell_t*	cell_array;
-	sync_cell_t*	cell;
-	ulint		i;
 
 	ut_a(n_cells > 0);
 
 	/* Allocate memory for the data structures */
 	arr = ut_malloc(sizeof(sync_array_t));
+	memset(arr, 0x0, sizeof(*arr));
 
-	cell_array = ut_malloc(sizeof(sync_cell_t) * n_cells);
+	sz = sizeof(sync_cell_t) * n_cells;
+	arr->array = ut_malloc(sz);
+	memset(arr->array, 0x0, sz);
 
 	arr->n_cells = n_cells;
-	arr->n_reserved = 0;
-	arr->array = cell_array;
 	arr->protection = protection;
-	arr->sg_count = 0;
-	arr->res_count = 0;
 
 	/* Then create the mutex to protect the wait array complex */
 	if (protection == SYNC_ARRAY_OS_MUTEX) {
@@ -255,13 +252,6 @@ sync_array_create(
 		ut_error;
 	}
 
-	for (i = 0; i < n_cells; i++) {
-		cell = sync_array_get_nth_cell(arr, i);
-	cell->wait_object = NULL;
-		cell->waiting = FALSE;
-		cell->signal_count = 0;
-	}
-
 	return(arr);
 }
 

=== modified file 'storage/innodb_plugin/sync/sync0sync.c'
--- a/storage/innodb_plugin/sync/sync0sync.c	2009-10-12 12:00:56 +0000
+++ b/storage/innodb_plugin/sync/sync0sync.c	2009-11-30 11:32:05 +0000
@@ -1377,7 +1377,12 @@ sync_close(void)
 	mutex_free(&mutex_list_mutex);
 #ifdef UNIV_SYNC_DEBUG
 	mutex_free(&sync_thread_mutex);
+
+	/* Switch latching order checks on in sync0sync.c */
+	sync_order_checks_on = FALSE;
 #endif /* UNIV_SYNC_DEBUG */
+
+	sync_initialized = FALSE;	
 }
 
 /*******************************************************************//**

=== modified file 'storage/innodb_plugin/thr/thr0loc.c'
--- a/storage/innodb_plugin/thr/thr0loc.c	2009-10-08 10:00:49 +0000
+++ b/storage/innodb_plugin/thr/thr0loc.c	2009-11-30 11:32:05 +0000
@@ -246,3 +246,34 @@ thr_local_init(void)
 
 	mutex_create(&thr_local_mutex, SYNC_THR_LOCAL);
 }
+
+/********************************************************************
+Close the thread local storage module. */
+UNIV_INTERN
+void
+thr_local_close(void)
+/*=================*/
+{
+	ulint		i;
+
+	ut_a(thr_local_hash != NULL);
+
+	/* Free the hash elements. We don't remove them from the table
+	because we are going to destroy the table anyway. */
+	for (i = 0; i < hash_get_n_cells(thr_local_hash); i++) {
+		thr_local_t*	local;
+
+		local = HASH_GET_FIRST(thr_local_hash, i);
+
+		while (local) {
+			thr_local_t*	prev_local = local;
+
+			local = HASH_GET_NEXT(hash, prev_local);
+			ut_a(prev_local->magic_n == THR_LOCAL_MAGIC_N);
+			mem_free(prev_local);
+		}
+	}
+
+	hash_table_free(thr_local_hash);
+	thr_local_hash = NULL;
+}

=== modified file 'storage/innodb_plugin/trx/trx0i_s.c'
--- a/storage/innodb_plugin/trx/trx0i_s.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/trx/trx0i_s.c	2009-12-01 10:38:40 +0000
@@ -60,7 +60,7 @@ Created July 17, 2007 Vasil Dimov
 /** @brief The maximum number of chunks to allocate for a table cache.
 
 The rows of a table cache are stored in a set of chunks. When a new
-row is added a new chunk is allocated if necessary.  Assuming that the
+row is added a new chunk is allocated if necessary. Assuming that the
 first one is 1024 rows (TABLE_CACHE_INITIAL_ROWSNUM) and each
 subsequent is N/2 where N is the number of rows we have allocated till
 now, then 39th chunk would accommodate 1677416425 rows and all chunks
@@ -238,6 +238,27 @@ table_cache_init(
 }
 
 /*******************************************************************//**
+Frees a table cache. */
+static
+void
+table_cache_free(
+/*=============*/
+	i_s_table_cache_t*	table_cache)	/*!< in/out: table cache */
+{
+	ulint	i;
+
+	for (i = 0; i < MEM_CHUNKS_IN_TABLE_CACHE; i++) {
+
+		/* the memory is actually allocated in
+		table_cache_create_empty_row() */
+		if (table_cache->chunks[i].base) {
+			mem_free(table_cache->chunks[i].base);
+			table_cache->chunks[i].base = NULL;
+		}
+	}
+}
+
+/*******************************************************************//**
 Returns an empty row from a table cache. The row is allocated if no more
 empty rows are available. The number of used rows is incremented.
 If the memory limit is hit then NULL is returned and nothing is
@@ -1184,9 +1205,6 @@ trx_i_s_possibly_fetch_data_into_cache(
 		return(1);
 	}
 
-	/* We are going to access trx->query in all transactions */
-	innobase_mysql_prepare_print_arbitrary_thd();
-
 	/* We need to read trx_sys and record/table lock queues */
 	mutex_enter(&kernel_mutex);
 
@@ -1194,8 +1212,6 @@ trx_i_s_possibly_fetch_data_into_cache(
 
 	mutex_exit(&kernel_mutex);
 
-	innobase_mysql_end_print_arbitrary_thd();
-
 	return(0);
 }
 
@@ -1252,6 +1268,22 @@ trx_i_s_cache_init(
 }
 
 /*******************************************************************//**
+Free the INFORMATION SCHEMA trx related cache. */
+UNIV_INTERN
+void
+trx_i_s_cache_free(
+/*===============*/
+	trx_i_s_cache_t*	cache)	/*!< in, own: cache to free */
+{
+	hash_table_free(cache->locks_hash);
+	ha_storage_free(cache->storage);
+	table_cache_free(&cache->innodb_trx);
+	table_cache_free(&cache->innodb_locks);
+	table_cache_free(&cache->innodb_lock_waits);
+	memset(cache, 0, sizeof *cache);
+}
+
+/*******************************************************************//**
 Issue a shared/read lock on the tables cache. */
 UNIV_INTERN
 void

=== modified file 'storage/innodb_plugin/trx/trx0purge.c'
--- a/storage/innodb_plugin/trx/trx0purge.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/trx/trx0purge.c	2009-11-30 11:32:05 +0000
@@ -249,6 +249,44 @@ trx_purge_sys_create(void)
 							    purge_sys->heap);
 }
 
+/************************************************************************
+Frees the global purge system control structure. */
+UNIV_INTERN
+void
+trx_purge_sys_close(void)
+/*======================*/
+{
+	ut_ad(!mutex_own(&kernel_mutex));
+
+	que_graph_free(purge_sys->query);
+
+	ut_a(purge_sys->sess->trx->is_purge);
+	purge_sys->sess->trx->conc_state = TRX_NOT_STARTED;
+	sess_close(purge_sys->sess);
+	purge_sys->sess = NULL;
+
+	if (purge_sys->view != NULL) {
+		/* Because acquiring the kernel mutex is a pre-condition
+		of read_view_close(). We don't really need it here. */
+		mutex_enter(&kernel_mutex);
+
+		read_view_close(purge_sys->view);
+		purge_sys->view = NULL;
+
+		mutex_exit(&kernel_mutex);
+	}
+
+	trx_undo_arr_free(purge_sys->arr);
+
+	rw_lock_free(&purge_sys->latch);
+	mutex_free(&purge_sys->mutex);
+
+	mem_heap_free(purge_sys->heap);
+	mem_free(purge_sys);
+
+	purge_sys = NULL;
+}
+
 /*================ UNDO LOG HISTORY LIST =============================*/
 
 /********************************************************************//**

=== modified file 'storage/innodb_plugin/trx/trx0rseg.c'
--- a/storage/innodb_plugin/trx/trx0rseg.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/trx/trx0rseg.c	2009-11-30 11:32:05 +0000
@@ -132,6 +132,49 @@ trx_rseg_header_create(
 }
 
 /***********************************************************************//**
+Free's an instance of the rollback segment in memory. */
+UNIV_INTERN
+void
+trx_rseg_mem_free(
+/*==============*/
+	trx_rseg_t*	rseg)	/* in, own: instance to free */
+{
+	trx_undo_t*	undo;
+
+	mutex_free(&rseg->mutex);
+
+	/* There can't be any active transactions. */
+	ut_a(UT_LIST_GET_LEN(rseg->update_undo_list) == 0);
+	ut_a(UT_LIST_GET_LEN(rseg->insert_undo_list) == 0);
+
+	undo = UT_LIST_GET_FIRST(rseg->update_undo_cached);
+
+	while (undo != NULL) {
+		trx_undo_t*	prev_undo = undo;
+
+		undo = UT_LIST_GET_NEXT(undo_list, undo);
+		UT_LIST_REMOVE(undo_list, rseg->update_undo_cached, prev_undo);
+
+		trx_undo_mem_free(prev_undo);
+	}
+
+	undo = UT_LIST_GET_FIRST(rseg->insert_undo_cached);
+
+	while (undo != NULL) {
+		trx_undo_t*	prev_undo = undo;
+
+		undo = UT_LIST_GET_NEXT(undo_list, undo);
+		UT_LIST_REMOVE(undo_list, rseg->insert_undo_cached, prev_undo);
+
+		trx_undo_mem_free(prev_undo);
+	}
+
+	trx_sys_set_nth_rseg(trx_sys, rseg->id, NULL);
+
+	mem_free(rseg);
+}
+
+/***************************************************************************
 Creates and initializes a rollback segment object. The values for the
 fields are read from the header. The object is inserted to the rseg
 list of the trx system object and a pointer is inserted in the rseg

=== modified file 'storage/innodb_plugin/trx/trx0sys.c'
--- a/storage/innodb_plugin/trx/trx0sys.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/trx/trx0sys.c	2009-11-30 11:32:05 +0000
@@ -40,6 +40,7 @@ Created 3/26/1996 Heikki Tuuri
 #include "trx0purge.h"
 #include "log0log.h"
 #include "os0file.h"
+#include "read0read.h"
 
 /** The file format tag structure with id and name. */
 struct file_format_struct {
@@ -1533,3 +1534,80 @@ trx_sys_file_format_id_to_name(
 }
 
 #endif /* !UNIV_HOTBACKUP */
+
+/*********************************************************************
+Shutdown/Close the transaction system. */
+UNIV_INTERN
+void
+trx_sys_close(void)
+/*===============*/
+{
+	trx_rseg_t*	rseg;
+	read_view_t*	view;
+
+	ut_ad(trx_sys != NULL);
+
+	/* Check that all read views are closed except read view owned
+	by a purge. */
+
+	if (UT_LIST_GET_LEN(trx_sys->view_list) > 1) {
+		fprintf(stderr,
+			"InnoDB: Error: all read views were not closed"
+			" before shutdown:\n"
+			"InnoDB: %lu read views open \n",
+			UT_LIST_GET_LEN(trx_sys->view_list) - 1);
+	}
+
+	sess_close(trx_dummy_sess);
+	trx_dummy_sess = NULL;
+
+	trx_purge_sys_close();
+
+	mutex_enter(&kernel_mutex);
+
+	/* Free the double write data structures. */
+	ut_a(trx_doublewrite != NULL);
+	ut_free(trx_doublewrite->write_buf_unaligned);
+	trx_doublewrite->write_buf_unaligned = NULL;
+
+	mem_free(trx_doublewrite->buf_block_arr);
+	trx_doublewrite->buf_block_arr = NULL;
+
+	mutex_free(&trx_doublewrite->mutex);
+	mem_free(trx_doublewrite);
+	trx_doublewrite = NULL;
+
+	/* There can't be any active transactions. */
+	rseg = UT_LIST_GET_FIRST(trx_sys->rseg_list);
+
+	while (rseg != NULL) {
+		trx_rseg_t*	prev_rseg = rseg;
+
+		rseg = UT_LIST_GET_NEXT(rseg_list, prev_rseg);
+		UT_LIST_REMOVE(rseg_list, trx_sys->rseg_list, prev_rseg);
+
+		trx_rseg_mem_free(prev_rseg);
+	}
+
+	view = UT_LIST_GET_FIRST(trx_sys->view_list);
+
+	while (view != NULL) {
+		read_view_t*	prev_view = view;
+
+		view = UT_LIST_GET_NEXT(view_list, prev_view);
+
+		/* Views are allocated from the trx_sys->global_read_view_heap.
+		So, we simply remove the element here. */
+		UT_LIST_REMOVE(view_list, trx_sys->view_list, prev_view);
+	}
+
+	ut_a(UT_LIST_GET_LEN(trx_sys->trx_list) == 0);
+	ut_a(UT_LIST_GET_LEN(trx_sys->rseg_list) == 0);
+	ut_a(UT_LIST_GET_LEN(trx_sys->view_list) == 0);
+	ut_a(UT_LIST_GET_LEN(trx_sys->mysql_trx_list) == 0);
+
+	mem_free(trx_sys);
+
+	trx_sys = NULL;
+	mutex_exit(&kernel_mutex);
+}

=== modified file 'storage/innodb_plugin/trx/trx0trx.c'
--- a/storage/innodb_plugin/trx/trx0trx.c	2009-10-09 14:13:15 +0000
+++ b/storage/innodb_plugin/trx/trx0trx.c	2009-12-01 10:38:40 +0000
@@ -1636,9 +1636,7 @@ trx_mark_sql_stat_end(
 
 /**********************************************************************//**
 Prints info about a transaction to the given file. The caller must own the
-kernel mutex and must have called
-innobase_mysql_prepare_print_arbitrary_thd(), unless he knows that MySQL
-or InnoDB cannot meanwhile change the info printed here. */
+kernel mutex. */
 UNIV_INTERN
 void
 trx_print(

=== modified file 'storage/innodb_plugin/trx/trx0undo.c'
--- a/storage/innodb_plugin/trx/trx0undo.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/trx/trx0undo.c	2009-11-30 11:32:05 +0000
@@ -1522,7 +1522,7 @@ trx_undo_mem_init_for_reuse(
 
 /********************************************************************//**
 Frees an undo log memory copy. */
-static
+UNIV_INTERN
 void
 trx_undo_mem_free(
 /*==============*/

=== modified file 'storage/innodb_plugin/usr/usr0sess.c'
--- a/storage/innodb_plugin/usr/usr0sess.c	2009-05-27 09:45:59 +0000
+++ b/storage/innodb_plugin/usr/usr0sess.c	2009-11-30 11:32:05 +0000
@@ -32,14 +32,6 @@ Created 6/25/1996 Heikki Tuuri
 #include "trx0trx.h"
 
 /*********************************************************************//**
-Closes a session, freeing the memory occupied by it. */
-static
-void
-sess_close(
-/*=======*/
-	sess_t*		sess);	/*!< in, own: session object */
-
-/*********************************************************************//**
 Opens a session.
 @return	own: session object */
 UNIV_INTERN
@@ -64,35 +56,16 @@ sess_open(void)
 
 /*********************************************************************//**
 Closes a session, freeing the memory occupied by it. */
-static
+UNIV_INTERN
 void
 sess_close(
 /*=======*/
 	sess_t*	sess)	/*!< in, own: session object */
 {
-	ut_ad(mutex_own(&kernel_mutex));
-	ut_ad(sess->trx == NULL);
-
-	mem_free(sess);
-}
-
-/*********************************************************************//**
-Closes a session, freeing the memory occupied by it, if it is in a state
-where it should be closed.
-@return	TRUE if closed */
-UNIV_INTERN
-ibool
-sess_try_close(
-/*===========*/
-	sess_t*	sess)	/*!< in, own: session object */
-{
-	ut_ad(mutex_own(&kernel_mutex));
+	ut_ad(!mutex_own(&kernel_mutex));
 
-	if (UT_LIST_GET_LEN(sess->graphs) == 0) {
-		sess_close(sess);
+	ut_a(UT_LIST_GET_LEN(sess->graphs) == 0);
 
-		return(TRUE);
-	}
-
-	return(FALSE);
+	trx_free_for_background(sess->trx);
+	mem_free(sess);
 }

=== modified file 'storage/innodb_plugin/ut/ut0mem.c'
--- a/storage/innodb_plugin/ut/ut0mem.c	2009-07-30 12:42:56 +0000
+++ b/storage/innodb_plugin/ut/ut0mem.c	2009-11-30 11:32:05 +0000
@@ -433,6 +433,8 @@ ut_free_all_mem(void)
 			" total allocated memory is %lu\n",
 			(ulong) ut_total_allocated_memory);
 	}
+
+	ut_mem_block_list_inited = FALSE;
 }
 #endif /* !UNIV_HOTBACKUP */
 

=== modified file 'storage/maria/ma_blockrec.c'
--- a/storage/maria/ma_blockrec.c	2009-10-03 20:13:58 +0000
+++ b/storage/maria/ma_blockrec.c	2010-01-06 21:27:53 +0000
@@ -6094,7 +6094,7 @@ uint _ma_apply_redo_insert_row_head_or_t
       DBUG_RETURN(0);
     }
 
-    if (((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) != page_type))
+    if (((uint) (buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) != page_type))
     {
       /*
         This is a page that has been freed before and now should be
@@ -6241,7 +6241,7 @@ uint _ma_apply_redo_purge_row_head_or_ta
       Note that in case the page is not anymore a head or tail page
       a future redo will fix the bitmap.
     */
-    if ((buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) == page_type)
+    if ((uint) (buff[PAGE_TYPE_OFFSET] & PAGE_TYPE_MASK) == page_type)
     {
       empty_space= uint2korr(buff+EMPTY_SPACE_OFFSET);
       if (_ma_bitmap_set(info, page, page_type == HEAD_PAGE,

=== modified file 'storage/maria/ma_check.c'
--- a/storage/maria/ma_check.c	2009-11-29 23:08:56 +0000
+++ b/storage/maria/ma_check.c	2010-01-14 16:51:00 +0000
@@ -6018,7 +6018,7 @@ int maria_update_state_info(HA_CHECK *pa
   {
     if (update & UPDATE_TIME)
     {
-      share->state.check_time= (long) time((time_t*) 0);
+      share->state.check_time= time((time_t*) 0);
       if (!share->state.create_time)
 	share->state.create_time= share->state.check_time;
     }

=== modified file 'storage/maria/ma_create.c'
--- a/storage/maria/ma_create.c	2009-02-19 09:01:25 +0000
+++ b/storage/maria/ma_create.c	2010-01-14 16:51:00 +0000
@@ -772,7 +772,7 @@ int maria_create(const char *name, enum
     share.base.min_block_length= share.base.pack_reclength;
 
   if (! (flags & HA_DONT_TOUCH_DATA))
-    share.state.create_time= (long) time((time_t*) 0);
+    share.state.create_time= time((time_t*) 0);
 
   pthread_mutex_lock(&THR_LOCK_maria);
 

=== modified file 'storage/maria/ma_loghandler.c'
--- a/storage/maria/ma_loghandler.c	2009-05-19 09:28:05 +0000
+++ b/storage/maria/ma_loghandler.c	2010-01-06 21:27:53 +0000
@@ -2823,8 +2823,8 @@ static my_bool translog_page_validator(u
 
   data->was_recovered= 0;
 
-  if (uint3korr(page) != page_no ||
-      uint3korr(page + 3) != data->number)
+  if ((pgcache_page_no_t) uint3korr(page) != page_no ||
+      (uint32) uint3korr(page + 3) != data->number)
   {
     DBUG_PRINT("error", ("Page (%lu,0x%lx): "
                          "page address written in the page is incorrect: "

=== modified file 'storage/maria/ma_test3.c'
--- a/storage/maria/ma_test3.c	2008-01-10 12:21:53 +0000
+++ b/storage/maria/ma_test3.c	2010-01-06 21:27:53 +0000
@@ -180,7 +180,7 @@ void start_test(int id)
   if (pagecacheing && rnd(2) == 0)
     init_pagecache(maria_pagecache, 65536L, 0, 0, MARIA_KEY_BLOCK_LENGTH,
                    MY_WME);
-  printf("Process %d, pid: %d\n",id,getpid()); fflush(stdout);
+  printf("Process %d, pid: %ld\n",id,(long) getpid()); fflush(stdout);
 
   for (error=i=0 ; i < tests && !error; i++)
   {
@@ -362,7 +362,7 @@ int test_write(MARIA_HA *file,int id,int
       maria_extra(file,HA_EXTRA_WRITE_CACHE,0);
   }
 
-  sprintf((char*) record.id,"%7d",getpid());
+  sprintf((char*) record.id,"%7ld", (long) getpid());
   strnmov((char*) record.text,"Testing...", sizeof(record.text));
 
   tries=(uint) rnd(100)+10;

=== modified file 'storage/myisam/ft_boolean_search.c'
--- a/storage/myisam/ft_boolean_search.c	2009-11-30 13:36:06 +0000
+++ b/storage/myisam/ft_boolean_search.c	2010-01-15 15:27:55 +0000
@@ -475,8 +475,7 @@ static void _ftb_init_index_search(FT_IN
   int i;
   FTB_WORD   *ftbw;
 
-  if ((ftb->state != READY && ftb->state !=INDEX_DONE) ||
-      ftb->keynr == NO_SUCH_KEY)
+  if (ftb->state == UNINITIALIZED || ftb->keynr == NO_SUCH_KEY)
     return;
   ftb->state=INDEX_SEARCH;
 

=== modified file 'storage/myisam/mi_check.c'
--- a/storage/myisam/mi_check.c	2009-12-03 11:34:11 +0000
+++ b/storage/myisam/mi_check.c	2010-01-14 16:51:00 +0000
@@ -4447,7 +4447,7 @@ int update_state_info(HA_CHECK *param, M
   {
     if (update & UPDATE_TIME)
     {
-      share->state.check_time= (long) time((time_t*) 0);
+      share->state.check_time= time((time_t*) 0);
       if (!share->state.create_time)
 	share->state.create_time=share->state.check_time;
     }

=== modified file 'storage/myisam/mi_create.c'
--- a/storage/myisam/mi_create.c	2009-10-15 21:38:29 +0000
+++ b/storage/myisam/mi_create.c	2010-01-14 16:51:00 +0000
@@ -575,7 +575,7 @@ int mi_create(const char *name,uint keys
     max(share.base.pack_reclength,MI_MIN_BLOCK_LENGTH) :
     MI_EXTEND_BLOCK_LENGTH;
   if (! (flags & HA_DONT_TOUCH_DATA))
-    share.state.create_time= (long) time((time_t*) 0);
+    share.state.create_time= time((time_t*) 0);
 
   pthread_mutex_lock(&THR_LOCK_myisam);
 

=== modified file 'storage/myisam/mi_test3.c'
--- a/storage/myisam/mi_test3.c	2008-04-28 16:24:05 +0000
+++ b/storage/myisam/mi_test3.c	2010-01-06 21:27:53 +0000
@@ -178,7 +178,8 @@ void start_test(int id)
   }
   if (key_cacheing && rnd(2) == 0)
     init_key_cache(dflt_key_cache, KEY_CACHE_BLOCK_SIZE, 65536L, 0, 0);
-  printf("Process %d, pid: %d\n",id,getpid()); fflush(stdout);
+  printf("Process %d, pid: %ld\n", id, (long) getpid());
+  fflush(stdout);
 
   for (error=i=0 ; i < tests && !error; i++)
   {
@@ -362,7 +363,7 @@ int test_write(MI_INFO *file,int id,int
       mi_extra(file,HA_EXTRA_WRITE_CACHE,0);
   }
 
-  sprintf((char*) record.id,"%7d",getpid());
+  sprintf((char*) record.id,"%7ld",(long) getpid());
   strnmov((char*) record.text,"Testing...", sizeof(record.text));
 
   tries=(uint) rnd(100)+10;

=== modified file 'storage/ndb/plug.in'
--- a/storage/ndb/plug.in	2006-08-19 04:19:19 +0000
+++ b/storage/ndb/plug.in	2009-12-27 13:54:41 +0000
@@ -1,5 +1,5 @@
 MYSQL_STORAGE_ENGINE(ndbcluster, ndbcluster, [Cluster Storage Engine],
-        [High Availability Clustered tables], [max])
+        [High Availability Clustered tables],)
 MYSQL_PLUGIN_DIRECTORY(ndbcluster,[storage/ndb])
 MYSQL_PLUGIN_STATIC(ndbcluster, [[\$(ndbcluster_libs) \$(ndbcluster_system_libs) \$(NDB_SCI_LIBS)]])
 MYSQL_PLUGIN_ACTIONS(ndbcluster,[MYSQL_SETUP_NDBCLUSTER])

=== modified file 'storage/pbxt/ChangeLog'
--- a/storage/pbxt/ChangeLog	2009-12-01 09:50:46 +0000
+++ b/storage/pbxt/ChangeLog	2009-12-21 13:13:15 +0000
@@ -1,6 +1,10 @@
 PBXT Release Notes
 ==================
 
+------- 1.0.09g RC3 - 2009-12-16
+
+RN292: Fixed a bug that resulted in 2-phase commit not being used between PBXT and the binlog. This bug was a result of a hack which as added to solve a problem in an pre-release version of MySQL 5.1. The hack was removed. 
+
 ------- 1.0.09f RC3 - 2009-11-30
 
 RN291: Fixed bug #489088: On shutdown MySQL reports: [Warning] Plugin 'PBXT' will be forced to shutdown.

=== modified file 'storage/pbxt/plug.in'
--- a/storage/pbxt/plug.in	2009-05-12 06:44:01 +0000
+++ b/storage/pbxt/plug.in	2009-12-09 21:39:23 +0000
@@ -5,3 +5,4 @@ MYSQL_PLUGIN_STATIC(pbxt,    [src/libpbx
 MYSQL_PLUGIN_ACTIONS(pbxt,  [
 #               AC_CONFIG_FILES(storage/pbxt/src/Makefile)
                ])
+MYSQL_PLUGIN_DEPENDS_ON_MYSQL_INTERNALS(pbxt, [[src/ha_pbxt.cc],[src/myxt_xt.cc],[src/discover_xt.cc]])

=== modified file 'storage/pbxt/src/Makefile.am'
--- a/storage/pbxt/src/Makefile.am	2009-11-24 10:55:06 +0000
+++ b/storage/pbxt/src/Makefile.am	2009-12-22 10:33:20 +0000
@@ -46,7 +46,5 @@ libpbxt_la_CFLAGS =		$(AM_CFLAGS) -DMYSQ
 EXTRA_LIBRARIES =		libpbxt.a
 noinst_LIBRARIES = 		libpbxt.a
 libpbxt_a_SOURCES =		$(libpbxt_la_SOURCES)
-libpbxt_a_CXXFLAGS =	$(AM_CXXFLAGS)
-libpbxt_a_CFLAGS =		$(AM_CFLAGS) -std=c99
 
 EXTRA_DIST =			pbms_enabled.cc win_inttypes.h

=== modified file 'storage/pbxt/src/discover_xt.cc'
--- a/storage/pbxt/src/discover_xt.cc	2009-12-16 08:13:18 +0000
+++ b/storage/pbxt/src/discover_xt.cc	2009-12-21 13:13:15 +0000
@@ -355,10 +355,10 @@ static int sort_keys(KEY *a, KEY *b)
   {
     if (!(b_flags & HA_NOSAME))
       return -1;
-    if ((a_flags ^ b_flags) & (HA_NULL_PART_KEY | HA_END_SPACE_KEY))
+    if ((a_flags ^ b_flags) & HA_NULL_PART_KEY)
     {
       /* Sort NOT NULL keys before other keys */
-      return (a_flags & (HA_NULL_PART_KEY | HA_END_SPACE_KEY)) ? 1 : -1;
+      return (a_flags & HA_NULL_PART_KEY) ? 1 : -1;
     }
     if (a->name == primary_key_name)
       return -1;

=== modified file 'storage/pbxt/src/ha_pbxt.cc'
--- a/storage/pbxt/src/ha_pbxt.cc	2009-11-27 15:37:02 +0000
+++ b/storage/pbxt/src/ha_pbxt.cc	2010-01-06 21:27:53 +0000
@@ -1175,8 +1175,13 @@ static int pbxt_init(void *p)
 		 * +1 Temporary thread (e.g. TempForClose, TempForEnd)
 		 */
 #ifndef DRIZZLED
-		if (pbxt_max_threads == 0)
-			pbxt_max_threads = max_connections + 7;
+		if (pbxt_max_threads == 0) {
+			// Embedded server sets max_connections=1
+			if (max_connections > 1)
+				pbxt_max_threads = max_connections + 7;
+			else
+				pbxt_max_threads = 100;
+		}
 #endif
 		self = xt_init_threading(pbxt_max_threads);				/* Create the main self: */
 		if (!self)
@@ -1289,7 +1294,7 @@ static int pbxt_init(void *p)
 				#6	0x000debe1 in THD::THD at sql_class.cc:631
 				#7	0x00e207a4 in myxt_create_thread at myxt_xt.cc:2666
 				#8	0x00e3134b in tabc_fr_run_thread at tabcache_xt.cc:982
-				#9	0x00e422ca in thr_main at thread_xt.cc:1006
+				#9	0x00e422ca in thr_main_pbxt at thread_xt.cc:1006
 				#10	0x91ff7c55 in _pthread_start
 				#11	0x91ff7b12 in thread_start
 			 *
@@ -1442,7 +1447,7 @@ static int pbxt_commit(handlerton *hton,
 	XTThreadPtr	self;
 
 	if ((self = (XTThreadPtr) *thd_ha_data(thd, hton))) {
-		XT_PRINT1(self, "pbxt_commit all=%d\n", all);
+		XT_PRINT2(self, "%s pbxt_commit all=%d\n", all ? "END CONN XACT" : "END STAT", all);
 
 		if (self->st_xact_data) {
 			/* There are no table locks, commit immediately in all cases
@@ -1474,7 +1479,7 @@ static int pbxt_rollback(handlerton *hto
 	XTThreadPtr	self;
 
 	if ((self = (XTThreadPtr) *thd_ha_data(thd, hton))) {
-		XT_PRINT1(self, "pbxt_rollback all=%d in pbxt_commit\n", all);
+		XT_PRINT2(self, "%s pbxt_rollback all=%d\n", all ? "CONN END XACT" : "STAT END", all);
 
 		if (self->st_xact_data) {
 			/* There are no table locks, rollback immediately in all cases
@@ -1538,7 +1543,7 @@ static int pbxt_prepare(handlerton *hton
 			 * except when this is a statement commit with an explicit
 			 * transaction (!all && !self->st_auto_commit).
 			 */
-			if (all) {
+			if (all || self->st_auto_commit) {
 				XID xid;
 
 				XT_PRINT0(self, "xt_xn_prepare in pbxt_prepare\n");
@@ -1552,7 +1557,7 @@ static int pbxt_prepare(handlerton *hton
 	return err;
 }
 
-static XTThreadPtr ha_temp_open_global_database(handlerton *hton, THD **ret_thd, int *temp_thread, char *thread_name, int *err)
+static XTThreadPtr ha_temp_open_global_database(handlerton *hton, THD **ret_thd, int *temp_thread, const char *thread_name, int *err)
 {
 	THD			*thd;
 	XTThreadPtr	self = NULL;
@@ -2620,26 +2625,7 @@ int ha_pbxt::write_row(byte *buf)
 	}
 #endif
 
-	/* GOTCHA: I have a huge problem with the transaction statement.
-	 * It is not ALWAYS committed (I mean ha_commit_trans() is
-	 * not always called - for example in SELECT).
-	 *
-	 * If I call trans_register_ha() but ha_commit_trans() is not called
-	 * then MySQL thinks a transaction is still running (while
-	 * I have committed the auto-transaction in ha_pbxt::external_lock()).
-	 *
-	 * This causes all kinds of problems, like transactions
-	 * are killed when they should not be.
-	 *
-	 * To prevent this, I only inform MySQL that a transaction
-	 * has beens started when an update is performed. I have determined that
-	 * ha_commit_trans() is only guarenteed to be called if an update is done. 
-	 */
-	if (!pb_open_tab->ot_thread->st_stat_trans) {
-		trans_register_ha(pb_mysql_thd, FALSE, pbxt_hton);
-		XT_PRINT0(pb_open_tab->ot_thread, "ha_pbxt::write_row trans_register_ha all=FALSE\n");
-		pb_open_tab->ot_thread->st_stat_trans = TRUE;
-	}
+	/* {START-STAT-HACK} previously position of start statement hack. */
 
 	xt_xlog_check_long_writer(pb_open_tab->ot_thread);
 
@@ -2730,11 +2716,7 @@ int ha_pbxt::update_row(const byte * old
 	XT_DISABLED_TRACE(("UPDATE tx=%d val=%d\n", (int) self->st_xact_data->xd_start_xn_id, (int) XT_GET_DISK_4(&new_data[1])));
 	//statistic_increment(ha_update_count,&LOCK_status);
 
-	if (!self->st_stat_trans) {
-		trans_register_ha(pb_mysql_thd, FALSE, pbxt_hton);
-		XT_PRINT0(self, "ha_pbxt::update_row trans_register_ha all=FALSE\n");
-		self->st_stat_trans = TRUE;
-	}
+	/* {START-STAT-HACK} previously position of start statement hack. */
 
 	xt_xlog_check_long_writer(self);
 
@@ -2821,11 +2803,7 @@ int ha_pbxt::delete_row(const byte * buf
 	}
 #endif
 
-	if (!pb_open_tab->ot_thread->st_stat_trans) {
-		trans_register_ha(pb_mysql_thd, FALSE, pbxt_hton);
-		XT_PRINT0(pb_open_tab->ot_thread, "ha_pbxt::delete_row trans_register_ha all=FALSE\n");
-		pb_open_tab->ot_thread->st_stat_trans = TRUE;
-	}
+	/* {START-STAT-HACK} previously position of start statement hack. */
 
 	xt_xlog_check_long_writer(pb_open_tab->ot_thread);
 
@@ -3155,15 +3133,12 @@ int ha_pbxt::index_init(uint idx, bool X
 
 		printf("index_init %s index %d cols req=%d/%d read_bits=%X write_bits=%X index_bits=%X\n", pb_open_tab->ot_table->tab_name->ps_path, (int) idx, pb_open_tab->ot_cols_req, pb_open_tab->ot_cols_req, (int) *table->read_set->bitmap, (int) *table->write_set->bitmap, (int) *ind->mi_col_map.bitmap);
 #endif
+		/* {START-STAT-HACK} previously position of start statement hack,
+		 * previous comment to code below: */
 		/* Start a statement based transaction as soon
 		 * as a read is done for a modify type statement!
 		 * Previously, this was done too late!
 		 */
-		if (!thread->st_stat_trans) {
-			trans_register_ha(pb_mysql_thd, FALSE, pbxt_hton);
-			XT_PRINT0(thread, "ha_pbxt::update_row trans_register_ha all=FALSE\n");
-			thread->st_stat_trans = TRUE;
-		}
 	}
 	else {
 		pb_open_tab->ot_cols_req = ha_get_max_bit(table->read_set);
@@ -3612,15 +3587,12 @@ int ha_pbxt::rnd_init(bool scan)
 	/* The number of columns required: */
 	if (pb_open_tab->ot_is_modify) {
 		pb_open_tab->ot_cols_req = table->read_set->MX_BIT_SIZE();
+		/* {START-STAT-HACK} previously position of start statement hack,
+		 * previous comment to code below: */
 		/* Start a statement based transaction as soon
 		 * as a read is done for a modify type statement!
 		 * Previously, this was done too late!
 		 */
-		if (!thread->st_stat_trans) {
-			trans_register_ha(pb_mysql_thd, FALSE, pbxt_hton);
-			XT_PRINT0(thread, "ha_pbxt::update_row trans_register_ha all=FALSE\n");
-			thread->st_stat_trans = TRUE;
-		}
 	}
 	else {
 		pb_open_tab->ot_cols_req = ha_get_max_bit(table->read_set);
@@ -4631,7 +4603,7 @@ xtPublic int ha_pbxt::external_lock(THD
 			cont_(b);
 		}
 
-		/* See (***) */
+		/* See {IS-UPDATE-STAT} */
 		self->st_is_update = FALSE;
 
 		/* Auto begin a transaction (if one is not already running): */
@@ -4660,7 +4632,7 @@ xtPublic int ha_pbxt::external_lock(THD
 			}
 
 			/*
-			 * (**) GOTCHA: trans_register_ha() is not mentioned in the documentation.
+			 * {START-TRANS} GOTCHA: trans_register_ha() is not mentioned in the documentation.
 			 * It must be called to inform MySQL that we have a transaction (see start_stmt).
 			 *
 			 * Here are some tests that confirm whether things are done correctly:
@@ -4698,10 +4670,46 @@ xtPublic int ha_pbxt::external_lock(THD
 			 */
 			if (!self->st_auto_commit) {
 				trans_register_ha(thd, TRUE, pbxt_hton);
-				XT_PRINT0(self, "ha_pbxt::external_lock trans_register_ha all=TRUE\n");
+				XT_PRINT0(self, "CONN START XACT - ha_pbxt::external_lock --> trans_register_ha\n");
 			}
 		}
 
+		/* Start a statment transaction: */
+		/* {START-STAT-HACK} The problem that ha_commit_trans() is not
+		 * called by MySQL seems to be fixed (tests confirm this).
+		 * Here is the previous comment when this code was execute 
+		 * here {START-STAT-HACK}
+		 *
+		 * GOTCHA: I have a huge problem with the transaction statement.
+		 * It is not ALWAYS committed (I mean ha_commit_trans() is
+		 * not always called - for example in SELECT).
+		 *
+		 * If I call trans_register_ha() but ha_commit_trans() is not called
+		 * then MySQL thinks a transaction is still running (while
+		 * I have committed the auto-transaction in ha_pbxt::external_lock()).
+		 *
+		 * This causes all kinds of problems, like transactions
+		 * are killed when they should not be.
+		 *
+		 * To prevent this, I only inform MySQL that a transaction
+		 * has beens started when an update is performed. I have determined that
+		 * ha_commit_trans() is only guarenteed to be called if an update is done.
+		 * --------
+		 *
+		 * So, this is the correct place to start a statement transaction.
+		 *
+		 * Note: if trans_register_ha() is not called before ha_write_row(), then 
+		 * PBXT is not registered correctly as a modification transaction.
+		 * (mark_trx_read_write call in ha_write_row).
+		 * This leads to 2-phase commit not being called as it should when
+		 * binary logging is enabled.
+		 */
+		if (!pb_open_tab->ot_thread->st_stat_trans) {
+			trans_register_ha(pb_mysql_thd, FALSE, pbxt_hton);
+			XT_PRINT0(pb_open_tab->ot_thread, "STAT START - ha_pbxt::external_lock --> trans_register_ha\n");
+			pb_open_tab->ot_thread->st_stat_trans = TRUE;
+		}
+
 		if (lock_type == F_WRLCK || self->st_xact_mode < XT_XACT_REPEATABLE_READ)
 			self->st_visible_time = self->st_database->db_xn_end_time;
 
@@ -4826,7 +4834,7 @@ int ha_pbxt::start_stmt(THD *thd, thr_lo
 		}
 	}
 
-	/* (***) This is required at this level!
+	/* {IS-UPDATE-STAT} This is required at this level!
 	 * No matter how often it is called, it is still the start of a
 	 * statement. We need to make sure statements that are NOT mistaken
 	 * for different type of statement.
@@ -4841,7 +4849,7 @@ int ha_pbxt::start_stmt(THD *thd, thr_lo
 	 */
 	self->st_is_update = FALSE;
 
-	/* See comment (**) */
+	/* See comment {START-TRANS} */
 	if (!self->st_xact_data) {
 		self->st_xact_mode = thd_tx_isolation(thd) <= ISO_READ_COMMITTED ? XT_XACT_COMMITTED_READ : XT_XACT_REPEATABLE_READ;
 		self->st_ignore_fkeys = (thd_test_options(thd, OPTION_NO_FOREIGN_KEY_CHECKS)) != 0;
@@ -4858,10 +4866,17 @@ int ha_pbxt::start_stmt(THD *thd, thr_lo
 		}
 		if (!self->st_auto_commit) {
 			trans_register_ha(thd, TRUE, pbxt_hton);
-			XT_PRINT0(self, "ha_pbxt::start_stmt trans_register_ha all=TRUE\n");
+			XT_PRINT0(self, "START CONN XACT - ha_pbxt::start_stmt --> trans_register_ha\n");
 		}
 	}
 
+	/* Start a statment (see {START-STAT-HACK}): */
+	if (!pb_open_tab->ot_thread->st_stat_trans) {
+		trans_register_ha(pb_mysql_thd, FALSE, pbxt_hton);
+		XT_PRINT0(pb_open_tab->ot_thread, "START STAT - ha_pbxt::start_stmt --> trans_register_ha\n");
+		pb_open_tab->ot_thread->st_stat_trans = TRUE;
+	}
+
 	if (pb_open_tab->ot_for_update || self->st_xact_mode < XT_XACT_REPEATABLE_READ)
 		self->st_visible_time = self->st_database->db_xn_end_time;
 

=== modified file 'storage/pbxt/src/restart_xt.cc'
--- a/storage/pbxt/src/restart_xt.cc	2009-11-27 15:37:02 +0000
+++ b/storage/pbxt/src/restart_xt.cc	2010-01-06 21:27:53 +0000
@@ -3314,7 +3314,7 @@ static void *xn_xres_run_recovery_thread
 	* #7	0x000c0db2 in THD::~THD at sql_class.cc:934
 	* #8	0x003b025b in myxt_destroy_thread at myxt_xt.cc:2999
 	* #9	0x003b66b5 in xn_xres_run_recovery_thread at restart_xt.cc:3196
-	* #10	0x003cbfbb in thr_main at thread_xt.cc:1020
+	* #10	0x003cbfbb in thr_main_pbxt at thread_xt.cc:1020
 	*
 	myxt_destroy_thread(mysql_thread, TRUE);
 	*/

=== modified file 'storage/pbxt/src/strutil_xt.cc'
--- a/storage/pbxt/src/strutil_xt.cc	2009-11-24 10:55:06 +0000
+++ b/storage/pbxt/src/strutil_xt.cc	2009-12-21 13:13:15 +0000
@@ -380,7 +380,7 @@ xtPublic void xt_int8_to_byte_size(xtInt
 /* Version number must also be set in configure.in! */
 xtPublic c_char *xt_get_version(void)
 {
-	return "1.0.09f RC";
+	return "1.0.09g RC";
 }
 
 /* Copy and URL decode! */

=== modified file 'storage/pbxt/src/table_xt.cc'
--- a/storage/pbxt/src/table_xt.cc	2009-11-25 15:40:51 +0000
+++ b/storage/pbxt/src/table_xt.cc	2009-12-22 10:33:20 +0000
@@ -1297,7 +1297,7 @@ xtPublic void xt_create_table(XTThreadPt
 	XTSortedListInfoRec	li_undo;
 
 #ifdef TRACE_CREATE_TABLES
-	printf("CREATE %s\n", name->ps_path);
+	fprintf(stderr, "CREATE %s\n", name->ps_path);
 #endif
 	enter_();
 	if (strlen(xt_last_name_of_path(name->ps_path)) > XT_TABLE_NAME_SIZE-1)
@@ -1619,7 +1619,7 @@ xtPublic void xt_drop_table(XTThreadPtr
 	enter_();
 
 #ifdef TRACE_CREATE_TABLES
-	printf("DROP %s\n", tab_name->ps_path);
+	fprintf(stderr, "DROP %s\n", tab_name->ps_path);
 #endif
 
 	table_pool = tab_lock_table(self, tab_name, FALSE, TRUE, TRUE, &tab);
@@ -1777,7 +1777,7 @@ xtPublic void xt_check_table(XTThreadPtr
 	u_llong					ext_data_len = 0;
 
 #if defined(DUMP_CHECK_TABLE) || defined(CHECK_TABLE_STATS)
-	printf("\nCHECK TABLE: %s\n", tab->tab_name->ps_path);
+	fprintf(stderr, "\nCHECK TABLE: %s\n", tab->tab_name->ps_path);
 #endif
 
 	xt_lock_mutex(self, &tab->tab_db->db_co_ext_lock);
@@ -1787,38 +1787,38 @@ xtPublic void xt_check_table(XTThreadPtr
 	pushr_(xt_unlock_mutex, &tab->tab_rec_lock);
 
 #ifdef CHECK_TABLE_STATS
-	printf("Record buffer size      = %lu\n", (u_long) tab->tab_dic.dic_mysql_buf_size);
-	printf("Fixed length rec. len.  = %lu\n", (u_long) tab->tab_dic.dic_mysql_rec_size);
-	printf("Handle data record size = %lu\n", (u_long) tab->tab_dic.dic_rec_size);
-	printf("Min/max header size     = %d/%d\n", (int) offsetof(XTTabRecFix, rf_data), tab->tab_dic.dic_rec_fixed ? (int) offsetof(XTTabRecFix, rf_data) : (int) offsetof(XTTabRecExtDRec, re_data));
-	printf("Min/avg/max record size = %llu/%llu/%llu\n", (u_llong) tab->tab_dic.dic_min_row_size, (u_llong) tab->tab_dic.dic_ave_row_size, (u_llong) tab->tab_dic.dic_max_row_size);
+	fprintf(stderr, "Record buffer size      = %lu\n", (u_long) tab->tab_dic.dic_mysql_buf_size);
+	fprintf(stderr, "Fixed length rec. len.  = %lu\n", (u_long) tab->tab_dic.dic_mysql_rec_size);
+	fprintf(stderr, "Handle data record size = %lu\n", (u_long) tab->tab_dic.dic_rec_size);
+	fprintf(stderr, "Min/max header size     = %d/%d\n", (int) offsetof(XTTabRecFix, rf_data), tab->tab_dic.dic_rec_fixed ? (int) offsetof(XTTabRecFix, rf_data) : (int) offsetof(XTTabRecExtDRec, re_data));
+	fprintf(stderr, "Min/avg/max record size = %llu/%llu/%llu\n", (u_llong) tab->tab_dic.dic_min_row_size, (u_llong) tab->tab_dic.dic_ave_row_size, (u_llong) tab->tab_dic.dic_max_row_size);
 	if (tab->tab_dic.dic_def_ave_row_size)
-		printf("Avg row len set for tab = %lu\n", (u_long) tab->tab_dic.dic_def_ave_row_size);
+		fprintf(stderr, "Avg row len set for tab = %lu\n", (u_long) tab->tab_dic.dic_def_ave_row_size);
 	else
-		printf("Avg row len set for tab = not specified\n");
-	printf("Rows fixed length       = %s\n", tab->tab_dic.dic_rec_fixed ? "YES" : "NO");
+		fprintf(stderr, "Avg row len set for tab = not specified\n");
+	fprintf(stderr, "Rows fixed length       = %s\n", tab->tab_dic.dic_rec_fixed ? "YES" : "NO");
 	if (tab->tab_dic.dic_tab_flags & XT_TAB_FLAGS_TEMP_TAB)
-		printf("Table type              = TEMP\n");
+		fprintf(stderr, "Table type              = TEMP\n");
 	if (tab->tab_dic.dic_def_ave_row_size)
-		printf("Maximum fixed size      = %lu\n", (u_long) XT_TAB_MAX_FIX_REC_LENGTH_SPEC);
+		fprintf(stderr, "Maximum fixed size      = %lu\n", (u_long) XT_TAB_MAX_FIX_REC_LENGTH_SPEC);
 	else
-		printf("Maximum fixed size      = %lu\n", (u_long) XT_TAB_MAX_FIX_REC_LENGTH);
-	printf("Minimum variable size   = %lu\n", (u_long) XT_TAB_MIN_VAR_REC_LENGTH);
-	printf("Minimum auto-increment  = %llu\n", (u_llong) tab->tab_dic.dic_min_auto_inc);
-	printf("Number of columns       = %lu\n", (u_long) tab->tab_dic.dic_no_of_cols);
-	printf("Number of fixed columns = %lu\n", (u_long) tab->tab_dic.dic_fix_col_count);
-	printf("Columns req. for index  = %lu\n", (u_long) tab->tab_dic.dic_ind_cols_req);
+		fprintf(stderr, "Maximum fixed size      = %lu\n", (u_long) XT_TAB_MAX_FIX_REC_LENGTH);
+	fprintf(stderr, "Minimum variable size   = %lu\n", (u_long) XT_TAB_MIN_VAR_REC_LENGTH);
+	fprintf(stderr, "Minimum auto-increment  = %llu\n", (u_llong) tab->tab_dic.dic_min_auto_inc);
+	fprintf(stderr, "Number of columns       = %lu\n", (u_long) tab->tab_dic.dic_no_of_cols);
+	fprintf(stderr, "Number of fixed columns = %lu\n", (u_long) tab->tab_dic.dic_fix_col_count);
+	fprintf(stderr, "Columns req. for index  = %lu\n", (u_long) tab->tab_dic.dic_ind_cols_req);
 	if (tab->tab_dic.dic_ind_rec_len)
-		printf("Rec len req. for index  = %llu\n", (u_llong) tab->tab_dic.dic_ind_rec_len);
-	printf("Columns req. for blobs  = %lu\n", (u_long) tab->tab_dic.dic_blob_cols_req);
-	printf("Number of blob columns  = %lu\n", (u_long) tab->tab_dic.dic_blob_count);
-	printf("Number of indices       = %lu\n", (u_long) tab->tab_dic.dic_key_count);
+		fprintf(stderr, "Rec len req. for index  = %llu\n", (u_llong) tab->tab_dic.dic_ind_rec_len);
+	fprintf(stderr, "Columns req. for blobs  = %lu\n", (u_long) tab->tab_dic.dic_blob_cols_req);
+	fprintf(stderr, "Number of blob columns  = %lu\n", (u_long) tab->tab_dic.dic_blob_count);
+	fprintf(stderr, "Number of indices       = %lu\n", (u_long) tab->tab_dic.dic_key_count);
 #endif
 
 #ifdef DUMP_CHECK_TABLE
-	printf("Records:-\n");
-	printf("Free list: %llu (%llu)\n", (u_llong) tab->tab_rec_free_id, (u_llong) tab->tab_rec_fnum);
-	printf("EOF:       %llu\n", (u_llong) tab->tab_rec_eof_id);
+	fprintf(stderr, "Records:-\n");
+	fprintf(stderr, "Free list: %llu (%llu)\n", (u_llong) tab->tab_rec_free_id, (u_llong) tab->tab_rec_fnum);
+	fprintf(stderr, "EOF:       %llu\n", (u_llong) tab->tab_rec_eof_id);
 #endif
 
 	rec_size = XT_REC_EXT_HEADER_SIZE;
@@ -1830,24 +1830,24 @@ xtPublic void xt_check_table(XTThreadPtr
 			xt_throw(self);
 
 #ifdef DUMP_CHECK_TABLE
-		printf("%-4llu ", (u_llong) rec_id);
+		fprintf(stderr, "%-4llu ", (u_llong) rec_id);
 #endif
 		switch (rec_buf->tr_rec_type_1 & XT_TAB_STATUS_MASK) {
 			case XT_TAB_STATUS_FREED:
 #ifdef DUMP_CHECK_TABLE
-				printf("======== ");
+				fprintf(stderr, "======== ");
 #endif
 				free_rec_count++;
 				break;
 			case XT_TAB_STATUS_DELETE:
 #ifdef DUMP_CHECK_TABLE
-				printf("delete   ");
+				fprintf(stderr, "delete   ");
 #endif
 				delete_rec_count++;
 				break;
 			case XT_TAB_STATUS_FIXED:
 #ifdef DUMP_CHECK_TABLE
-				printf("record-F ");
+				fprintf(stderr, "record-F ");
 #endif
 				alloc_rec_count++;
 				row_size = myxt_store_row_length(ot, (char *) ot->ot_row_rbuffer + XT_REC_FIX_HEADER_SIZE);
@@ -1859,7 +1859,7 @@ xtPublic void xt_check_table(XTThreadPtr
 				break;
 			case XT_TAB_STATUS_VARIABLE:
 #ifdef DUMP_CHECK_TABLE
-				printf("record-V ");
+				fprintf(stderr, "record-V ");
 #endif
 				alloc_rec_count++;
 				row_size = myxt_load_row_length(ot, tab->tab_dic.dic_rec_size, ot->ot_row_rbuffer + XT_REC_FIX_HEADER_SIZE, NULL);
@@ -1871,7 +1871,7 @@ xtPublic void xt_check_table(XTThreadPtr
 				break;
 			case XT_TAB_STATUS_EXT_DLOG:
 #ifdef DUMP_CHECK_TABLE
-				printf("record-X ");
+				fprintf(stderr, "record-X ");
 #endif
 				alloc_rec_count++;
 				ext_data_len += XT_GET_DISK_4(rec_buf->re_log_dat_siz_4);
@@ -1885,9 +1885,9 @@ xtPublic void xt_check_table(XTThreadPtr
 		}
 #ifdef DUMP_CHECK_TABLE
 		if (rec_buf->tr_rec_type_1 & XT_TAB_STATUS_CLEANED_BIT)
-			printf("C");
+			fprintf(stderr, "C");
 		else
-			printf(" ");
+			fprintf(stderr, " ");
 #endif
 		prev_rec_id = XT_GET_DISK_4(rec_buf->tr_prev_rec_id_4);
 		xn_id = XT_GET_DISK_4(rec_buf->tr_xact_id_4);
@@ -1895,12 +1895,12 @@ xtPublic void xt_check_table(XTThreadPtr
 		switch (rec_buf->tr_rec_type_1 & XT_TAB_STATUS_MASK) {
 			case XT_TAB_STATUS_FREED:
 #ifdef DUMP_CHECK_TABLE
-				printf(" prev=%-3llu (xact=%-3llu row=%lu)\n", (u_llong) prev_rec_id, (u_llong) xn_id, (u_long) row_id);
+				fprintf(stderr, " prev=%-3llu (xact=%-3llu row=%lu)\n", (u_llong) prev_rec_id, (u_llong) xn_id, (u_long) row_id);
 #endif
 				break;
 			case XT_TAB_STATUS_EXT_DLOG:
 #ifdef DUMP_CHECK_TABLE
-				printf(" prev=%-3llu  xact=%-3llu row=%lu  Xlog=%lu Xoff=%llu Xsiz=%lu\n", (u_llong) prev_rec_id, (u_llong) xn_id, (u_long) row_id, (u_long) XT_GET_DISK_2(rec_buf->re_log_id_2), (u_llong) XT_GET_DISK_6(rec_buf->re_log_offs_6), (u_long) XT_GET_DISK_4(rec_buf->re_log_dat_siz_4));
+				fprintf(stderr, " prev=%-3llu  xact=%-3llu row=%lu  Xlog=%lu Xoff=%llu Xsiz=%lu\n", (u_llong) prev_rec_id, (u_llong) xn_id, (u_long) row_id, (u_long) XT_GET_DISK_2(rec_buf->re_log_id_2), (u_llong) XT_GET_DISK_6(rec_buf->re_log_offs_6), (u_long) XT_GET_DISK_4(rec_buf->re_log_dat_siz_4));
 #endif
 
 				log_size = XT_GET_DISK_4(rec_buf->re_log_dat_siz_4);
@@ -1922,7 +1922,7 @@ xtPublic void xt_check_table(XTThreadPtr
 				break;
 			default:
 #ifdef DUMP_CHECK_TABLE
-				printf(" prev=%-3llu  xact=%-3llu row=%lu\n", (u_llong) prev_rec_id, (u_llong) xn_id, (u_long) row_id);
+				fprintf(stderr, " prev=%-3llu  xact=%-3llu row=%lu\n", (u_llong) prev_rec_id, (u_llong) xn_id, (u_long) row_id);
 #endif
 				break;
 		}
@@ -1931,16 +1931,16 @@ xtPublic void xt_check_table(XTThreadPtr
 	
 #ifdef CHECK_TABLE_STATS
 	if (!tab->tab_dic.dic_rec_fixed)
-		printf("Extendend data length   = %llu\n", ext_data_len);
+		fprintf(stderr, "Extendend data length   = %llu\n", ext_data_len);
 	
 	if (alloc_rec_count) {
-		printf("Minumum comp. rec. len. = %llu\n", (u_llong) min_comp_rec_len);
-		printf("Average comp. rec. len. = %llu\n", (u_llong) ((double) alloc_rec_bytes / (double) alloc_rec_count + (double) 0.5));
-		printf("Maximum comp. rec. len. = %llu\n", (u_llong) max_comp_rec_len);
-	}
-	printf("Free record count       = %llu\n", (u_llong) free_rec_count);
-	printf("Deleted record count    = %llu\n", (u_llong) delete_rec_count);
-	printf("Allocated record count  = %llu\n", (u_llong) alloc_rec_count);
+		fprintf(stderr, "Minumum comp. rec. len. = %llu\n", (u_llong) min_comp_rec_len);
+		fprintf(stderr, "Average comp. rec. len. = %llu\n", (u_llong) ((double) alloc_rec_bytes / (double) alloc_rec_count + (double) 0.5));
+		fprintf(stderr, "Maximum comp. rec. len. = %llu\n", (u_llong) max_comp_rec_len);
+	}
+	fprintf(stderr, "Free record count       = %llu\n", (u_llong) free_rec_count);
+	fprintf(stderr, "Deleted record count    = %llu\n", (u_llong) delete_rec_count);
+	fprintf(stderr, "Allocated record count  = %llu\n", (u_llong) alloc_rec_count);
 #endif
 	if (tab->tab_rec_fnum != free_rec_count)
 		xt_logf(XT_INFO, "Table %s: incorrect number of free blocks, %llu, should be: %llu\n", tab->tab_name, (u_llong) free_rec_count, (u_llong) tab->tab_rec_fnum);
@@ -1978,9 +1978,9 @@ xtPublic void xt_check_table(XTThreadPtr
 	pushr_(xt_unlock_mutex, &tab->tab_row_lock);
 
 #ifdef DUMP_CHECK_TABLE
-	printf("Rows:-\n");
-	printf("Free list: %llu (%llu)\n", (u_llong) tab->tab_row_free_id, (u_llong) tab->tab_row_fnum);
-	printf("EOF:       %llu\n", (u_llong) tab->tab_row_eof_id);
+	fprintf(stderr, "Rows:-\n");
+	fprintf(stderr, "Free list: %llu (%llu)\n", (u_llong) tab->tab_row_free_id, (u_llong) tab->tab_row_fnum);
+	fprintf(stderr, "EOF:       %llu\n", (u_llong) tab->tab_row_eof_id);
 #endif
 
 	rec_id = 1;
@@ -1988,13 +1988,13 @@ xtPublic void xt_check_table(XTThreadPtr
 		if (!tab->tab_rows.xt_tc_read_4(ot->ot_row_file, rec_id, &ref_id, self))
 			xt_throw(self);
 #ifdef DUMP_CHECK_TABLE
-		printf("%-3llu ", (u_llong) rec_id);
+		fprintf(stderr, "%-3llu ", (u_llong) rec_id);
 #endif
 #ifdef DUMP_CHECK_TABLE
 		if (ref_id == 0)
-			printf("====== 0\n");
+			fprintf(stderr, "====== 0\n");
 		else
-			printf("in use %llu\n", (u_llong) ref_id);
+			fprintf(stderr, "in use %llu\n", (u_llong) ref_id);
 #endif
 		rec_id++;
 	}
@@ -2026,7 +2026,7 @@ xtPublic void xt_rename_table(XTThreadPt
 	memset(&dic, 0, sizeof(dic));
 
 #ifdef TRACE_CREATE_TABLES
-	printf("RENAME %s --> %s\n", old_name->ps_path, new_name->ps_path);
+	fprintf(stderr, "RENAME %s --> %s\n", old_name->ps_path, new_name->ps_path);
 #endif
 	if (strlen(xt_last_name_of_path(new_name->ps_path)) > XT_TABLE_NAME_SIZE-1)
 		xt_throw_taberr(XT_CONTEXT, XT_ERR_NAME_TOO_LONG, new_name);
@@ -2221,7 +2221,7 @@ xtPublic xtBool xt_flush_record_row(XTOp
 	xt_tab_store_header(ot, &rec_head);
 
 #ifdef TRACE_FLUSH
-	printf("FLUSH rec/row %d %s\n", (int) tab->tab_bytes_to_flush, tab->tab_name->ps_path);
+	fprintf(stderr, "FLUSH rec/row %d %s\n", (int) tab->tab_bytes_to_flush, tab->tab_name->ps_path);
 	fflush(stdout);
 #endif
 	/* Write the table header: */
@@ -2276,7 +2276,7 @@ xtPublic xtBool xt_flush_record_row(XTOp
 	xt_unlock_mutex_ns(&cp->cp_state_lock);
 
 #ifdef TRACE_FLUSH
-	printf("FLUSH --end-- %s\n", tab->tab_name->ps_path);
+	fprintf(stderr, "FLUSH --end-- %s\n", tab->tab_name->ps_path);
 	fflush(stdout);
 #endif
 	xt_unlock_mutex_ns(&tab->tab_rec_flush_lock);

=== modified file 'storage/pbxt/src/thread_xt.cc'
--- a/storage/pbxt/src/thread_xt.cc	2009-11-24 10:55:06 +0000
+++ b/storage/pbxt/src/thread_xt.cc	2010-01-06 21:27:53 +0000
@@ -96,7 +96,7 @@ xtPublic xtBool xt_init_logging(void)
 {
 	int err;
 
-	log_file = stdout;
+	log_file = stderr;
 	log_level = XT_LOG_TRACE;
 	err = xt_p_mutex_init_with_autoname(&log_mutex, NULL);
 	if (err) {
@@ -1013,7 +1013,7 @@ static xtBool thr_setup_signals(void)
 
 typedef void *(*ThreadMainFunc)(XTThreadPtr self);
 
-extern "C" void *thr_main(void *data)
+extern "C" void *thr_main_pbxt(void *data)
 {
 	ThreadDataPtr	td = (ThreadDataPtr) data;
 	XTThreadPtr		self = td->td_thr;
@@ -1503,10 +1503,10 @@ xtPublic pthread_t xt_run_thread(XTThrea
 		pthread_attr_t	attr = { 0, 0, 0 };
 
 		attr.priority = THREAD_PRIORITY_NORMAL;
-		err = pthread_create(&child_thread, &attr, thr_main, &data);
+		err = pthread_create(&child_thread, &attr, thr_main_pbxt, &data);
 	}
 #else
-	err = pthread_create(&child_thread, NULL, thr_main, &data);
+	err = pthread_create(&child_thread, NULL, thr_main_pbxt, &data);
 #endif
 	if (err) {
 		xt_free_thread(child);

=== modified file 'storage/pbxt/src/thread_xt.h'
--- a/storage/pbxt/src/thread_xt.h	2009-11-24 10:55:06 +0000
+++ b/storage/pbxt/src/thread_xt.h	2010-01-06 21:27:53 +0000
@@ -536,7 +536,7 @@ extern struct XTThread	**xt_thr_array;
  * Function prototypes
  */
 
-extern "C" void *thr_main(void *data);
+extern "C" void *thr_main_pbxt(void *data);
 
 void			xt_get_now(char *buffer, size_t len);
 xtBool			xt_init_logging(void);

=== modified file 'storage/pbxt/src/trace_xt.cc'
--- a/storage/pbxt/src/trace_xt.cc	2009-08-17 11:12:36 +0000
+++ b/storage/pbxt/src/trace_xt.cc	2009-12-22 10:33:20 +0000
@@ -109,10 +109,10 @@ xtPublic void xt_print_trace(void)
 		xt_lock_mutex_ns(&trace_mutex);
 		if (trace_log_end > trace_log_offset+1) {
 			trace_log_buffer[trace_log_end] = 0;
-			printf("%s", trace_log_buffer + trace_log_offset + 1);
+			fprintf(stderr, "%s", trace_log_buffer + trace_log_offset + 1);
 		}
 		trace_log_buffer[trace_log_offset] = 0;
-		printf("%s", trace_log_buffer);
+		fprintf(stderr, "%s", trace_log_buffer);
 		trace_log_offset = 0;
 		trace_log_end = 0;
 		xt_unlock_mutex_ns(&trace_mutex);
@@ -379,9 +379,9 @@ xtPublic void xt_dump_conn_tracking(void
 	ptr = conn_info;
 	for (int i=0; i<XT_TRACK_MAX_CONNS; i++) {
 		if (ptr->ci_curr_xact_id || ptr->ci_prev_xact_id) {
-			printf("%3d curr=%d prev=%d prev-time=%ld\n", (int) ptr->cu_t_id, (int) ptr->ci_curr_xact_id, (int) ptr->ci_prev_xact_id, (long) ptr->ci_prev_xact_time);
+			fprintf(stderr, "%3d curr=%d prev=%d prev-time=%ld\n", (int) ptr->cu_t_id, (int) ptr->ci_curr_xact_id, (int) ptr->ci_prev_xact_id, (long) ptr->ci_prev_xact_time);
 			if (i+1<XT_TRACK_MAX_CONNS) {
-				printf("    diff=%d\n", (int) (ptr+1)->ci_curr_xact_id - (int) ptr->ci_curr_xact_id);
+				fprintf(stderr, "    diff=%d\n", (int) (ptr+1)->ci_curr_xact_id - (int) ptr->ci_curr_xact_id);
 			}
 		}
 		ptr++;

=== modified file 'storage/xtradb/handler/ha_innodb.cc'
--- a/storage/xtradb/handler/ha_innodb.cc	2009-12-03 11:34:11 +0000
+++ b/storage/xtradb/handler/ha_innodb.cc	2010-01-15 15:27:55 +0000
@@ -61,7 +61,9 @@ with this program; if not, write to the
 #pragma implementation				// gcc: Class implementation
 #endif
 
+#ifndef MYSQL_SERVER
 #define MYSQL_SERVER
+#endif
 
 #include <mysql_priv.h>
 #ifdef MYSQL_SERVER
@@ -1711,7 +1713,7 @@ innobase_convert_identifier(
 				FALSE=id is an UTF-8 string */
 {
 	char nz[NAME_LEN + 1];
-	char nz2[NAME_LEN + 1 + sizeof srv_mysql50_table_name_prefix];
+	char nz2[NAME_LEN + 1 + EXPLAIN_FILENAME_MAX_EXTRA_LENGTH];
 
 	const char*	s	= id;
 	int		q;
@@ -1729,7 +1731,14 @@ innobase_convert_identifier(
 		nz[idlen] = 0;
 
 		s = nz2;
-		idlen = filename_to_tablename(nz, nz2, sizeof nz2);
+		idlen = explain_filename((THD*) thd, nz, nz2, sizeof nz2,
+					 EXPLAIN_PARTITIONS_AS_COMMENT);
+
+		if (UNIV_UNLIKELY(idlen > buflen)) {
+			idlen = buflen;
+		}
+		memcpy(buf, s, idlen);
+		return(buf + idlen);
 	}
 
 	/* See if the identifier needs to be quoted. */
@@ -1739,14 +1748,6 @@ innobase_convert_identifier(
 		q = get_quote_char_for_identifier((THD*) thd, s, (int) idlen);
 	}
 
-	if (q == EOF) {
-		if (UNIV_UNLIKELY(idlen > buflen)) {
-			idlen = buflen;
-		}
-		memcpy(buf, s, idlen);
-		return(buf + idlen);
-	}
-
 	/* Quote the identifier. */
 	if (buflen < 2) {
 		return(buf);

=== modified file 'storage/xtradb/srv/srv0srv.c'
--- a/storage/xtradb/srv/srv0srv.c	2009-11-13 21:26:08 +0000
+++ b/storage/xtradb/srv/srv0srv.c	2010-01-12 17:31:11 +0000
@@ -102,6 +102,10 @@ Created 10/8/1995 Heikki Tuuri
 #include "row0mysql.h"
 #include "ha_prototypes.h"
 #include "trx0i_s.h"
+#include "os0sync.h" /* for HAVE_ATOMIC_BUILTINS */
+
+/* prototypes for new functions added to ha_innodb.cc */
+ibool	innobase_get_slow_log();
 
 /* This is set to TRUE if the MySQL user has set it in MySQL; currently
 affects only FOREIGN KEY definition parsing */
@@ -161,6 +165,7 @@ UNIV_INTERN ulint*	srv_data_file_sizes =
 UNIV_INTERN ibool	srv_extra_undoslots = FALSE;
 
 UNIV_INTERN ibool	srv_fast_recovery = FALSE;
+UNIV_INTERN ibool	srv_recovery_stats = FALSE;
 
 UNIV_INTERN ibool	srv_use_purge_thread = FALSE;
 
@@ -1076,7 +1081,7 @@ UNIV_INTERN ulong	srv_max_purge_lag		= 0
 Puts an OS thread to wait if there are too many concurrent threads
 (>= srv_thread_concurrency) inside InnoDB. The threads wait in a FIFO queue. */
 
-#ifdef INNODB_RW_LOCKS_USE_ATOMICS
+#ifdef HAVE_ATOMIC_BUILTINS
 static void
 enter_innodb_with_tickets(trx_t* trx)
 {
@@ -1102,12 +1107,12 @@ srv_conc_enter_innodb_timer_based(trx_t*
 	}
 retry:
 	if (srv_conc_n_threads < (lint) srv_thread_concurrency) {
-		conc_n_threads = __sync_add_and_fetch(&srv_conc_n_threads, 1);
+		conc_n_threads = os_atomic_increment_lint(&srv_conc_n_threads, 1);
 		if (conc_n_threads <= (lint) srv_thread_concurrency) {
 			enter_innodb_with_tickets(trx);
 			return;
 		}
-		__sync_add_and_fetch(&srv_conc_n_threads, -1);
+		os_atomic_increment_lint(&srv_conc_n_threads, -1);
 	}
 	if (!has_yielded)
 	{
@@ -1118,7 +1123,7 @@ retry:
 	if (trx->has_search_latch
 	    || NULL != UT_LIST_GET_FIRST(trx->trx_locks)) {
 
-		conc_n_threads = __sync_add_and_fetch(&srv_conc_n_threads, 1);
+		conc_n_threads = os_atomic_increment_lint(&srv_conc_n_threads, 1);
 		enter_innodb_with_tickets(trx);
 		return;
 	}
@@ -1129,7 +1134,7 @@ retry:
 		trx->op_info = "";
 		has_slept++;
 	}
-	conc_n_threads = __sync_add_and_fetch(&srv_conc_n_threads, 1);
+	conc_n_threads = os_atomic_increment_lint(&srv_conc_n_threads, 1);
 	enter_innodb_with_tickets(trx);
 	return;
 }
@@ -1137,7 +1142,7 @@ retry:
 static void
 srv_conc_exit_innodb_timer_based(trx_t* trx)
 {
-	__sync_add_and_fetch(&srv_conc_n_threads, -1);
+	os_atomic_increment_lint(&srv_conc_n_threads, -1);
 	trx->declared_to_be_inside_innodb = FALSE;
 	trx->n_tickets_to_enter_innodb = 0;
 	return;
@@ -1174,7 +1179,7 @@ srv_conc_enter_innodb(
 		return;
 	}
 
-#ifdef INNODB_RW_LOCKS_USE_ATOMICS
+#ifdef HAVE_ATOMIC_BUILTINS
 	if (srv_thread_concurrency_timer_based) {
 		srv_conc_enter_innodb_timer_based(trx);
 		return;
@@ -1324,9 +1329,9 @@ srv_conc_force_enter_innodb(
 	}
 
 	ut_ad(srv_conc_n_threads >= 0);
-#ifdef INNODB_RW_LOCKS_USE_ATOMICS
+#ifdef HAVE_ATOMIC_BUILTINS
 	if (srv_thread_concurrency_timer_based) {
-		__sync_add_and_fetch(&srv_conc_n_threads, 1);
+		os_atomic_increment_lint(&srv_conc_n_threads, 1);
 		trx->declared_to_be_inside_innodb = TRUE;
 		trx->n_tickets_to_enter_innodb = 1;
 		return;
@@ -1365,7 +1370,7 @@ srv_conc_force_exit_innodb(
 		return;
 	}
 
-#ifdef INNODB_RW_LOCKS_USE_ATOMICS
+#ifdef HAVE_ATOMIC_BUILTINS
 	if (srv_thread_concurrency_timer_based) {
 		srv_conc_exit_innodb_timer_based(trx);
 		return;

=== modified file 'support-files/compiler_warnings.supp'
--- a/support-files/compiler_warnings.supp	2009-10-03 20:13:58 +0000
+++ b/support-files/compiler_warnings.supp	2010-01-06 21:27:53 +0000
@@ -88,6 +88,9 @@ storage/maria/ma_pagecache.c: .*'info_ch
 #
 storage/pbxt/ : typedef.*was ignored in this declaration
 
+#
+# Yassl
+include/runtime.hpp: .*pure_error.*
 
 #
 # Groff warnings on OpenSUSE.

=== modified file 'tests/mysql_client_test.c'
--- a/tests/mysql_client_test.c	2009-12-03 11:19:05 +0000
+++ b/tests/mysql_client_test.c	2010-01-11 13:15:28 +0000
@@ -2465,6 +2465,34 @@ static uint query_cache_hits(MYSQL *conn
 
 
 /*
+  Check that query cache is available in server.
+*/
+static my_bool is_query_cache_available()
+{
+  int rc;
+  MYSQL_RES *result;
+  MYSQL_ROW row;
+  int res= -1;
+
+  rc= mysql_query(mysql, "SHOW VARIABLES LIKE 'have_query_cache'");
+  myquery(rc);
+
+  result= mysql_store_result(mysql);
+  DIE_UNLESS(result);
+
+  row= mysql_fetch_row(result);
+  DIE_UNLESS(row != NULL);
+  if (strcmp(row[1], "YES") == 0)
+    res= 1;
+  else if (strcmp(row[1], "NO") == 0)
+    res= 0;
+  mysql_free_result(result);
+
+  DIE_UNLESS(res == 0 || res == 1);
+  return res;
+}
+
+/*
   Test that prepared statements make use of the query cache just as normal
   statements (BUG#735).
 */
@@ -2508,6 +2536,12 @@ static void test_ps_query_cache()
 
   myheader("test_ps_query_cache");
 
+  if (! is_query_cache_available())
+  {
+    fprintf(stdout, "Skipping test_ps_query_cache: Query cache not available.\n");
+    return;
+  }
+
   rc= mysql_query(mysql, "SET SQL_MODE=''");
   myquery(rc);
 
@@ -17863,8 +17897,6 @@ static void test_bug43560(void)
   Bug#36326: nested transaction and select
 */
 
-#ifdef HAVE_QUERY_CACHE
-
 static void test_bug36326()
 {
   int rc;
@@ -17872,6 +17904,12 @@ static void test_bug36326()
   DBUG_ENTER("test_bug36326");
   myheader("test_bug36326");
 
+  if (! is_query_cache_available())
+  {
+    fprintf(stdout, "Skipping test_bug36326: Query cache not available.\n");
+    DBUG_VOID_RETURN;
+  }
+
   rc= mysql_autocommit(mysql, TRUE);
   myquery(rc);
   rc= mysql_query(mysql, "DROP TABLE IF EXISTS t1");
@@ -17911,8 +17949,6 @@ static void test_bug36326()
   DBUG_VOID_RETURN;
 }
 
-#endif
-
 /**
   Bug#41078: With CURSOR_TYPE_READ_ONLY mysql_stmt_fetch() returns short
              string value.
@@ -18373,9 +18409,7 @@ static struct my_tests_st my_tests[]= {
   { "test_bug38486", test_bug38486 },
   { "test_bug40365", test_bug40365 },
   { "test_bug43560", test_bug43560 },
-#ifdef HAVE_QUERY_CACHE
   { "test_bug36326", test_bug36326 },
-#endif
   { "test_bug41078", test_bug41078 },
   { "test_bug44495", test_bug44495 },
   { 0, 0 }

=== modified file 'vio/vio.c'
--- a/vio/vio.c	2009-11-02 22:19:58 +0000
+++ b/vio/vio.c	2009-11-20 12:09:50 +0000
@@ -62,10 +62,8 @@ static void vio_init(Vio* vio, enum enum
 
     vio->timeout=vio_win32_timeout;
     /* Set default timeout */
-    vio->read_timeout_millis = INFINITE;
-    vio->write_timeout_millis = INFINITE;
-
-    memset(&(vio->pipe_overlapped), 0, sizeof(OVERLAPPED));
+    vio->read_timeout_ms= INFINITE;
+    vio->write_timeout_ms= INFINITE;
     vio->pipe_overlapped.hEvent= CreateEvent(NULL, TRUE, FALSE, NULL);
     DBUG_VOID_RETURN;
   }
@@ -90,8 +88,8 @@ static void vio_init(Vio* vio, enum enum
     /* Currently, shared memory is on Windows only, hence the below is ok*/
     vio->timeout= vio_win32_timeout; 
     /* Set default timeout */
-    vio->read_timeout_millis= INFINITE;
-    vio->write_timeout_millis= INFINITE;
+    vio->read_timeout_ms= INFINITE;
+    vio->write_timeout_ms= INFINITE;
     DBUG_VOID_RETURN;
   }
 #endif   
@@ -115,22 +113,20 @@ static void vio_init(Vio* vio, enum enum
     DBUG_VOID_RETURN;
   }
 #endif /* HAVE_OPENSSL */
-  {
-    vio->viodelete	=vio_delete;
-    vio->vioerrno	=vio_errno;
-    vio->read= (flags & VIO_BUFFERED_READ) ? vio_read_buff : vio_read;
-    vio->write		=vio_write;
-    vio->fastsend	=vio_fastsend;
-    vio->viokeepalive	=vio_keepalive;
-    vio->should_retry	=vio_should_retry;
-    vio->was_interrupted=vio_was_interrupted;
-    vio->vioclose	=vio_close;
-    vio->peer_addr	=vio_peer_addr;
-    vio->in_addr	=vio_in_addr;
-    vio->vioblocking	=vio_blocking;
-    vio->is_blocking	=vio_is_blocking;
-    vio->timeout	=vio_timeout;
-  }
+  vio->viodelete	=vio_delete;
+  vio->vioerrno	=vio_errno;
+  vio->read= (flags & VIO_BUFFERED_READ) ? vio_read_buff : vio_read;
+  vio->write		=vio_write;
+  vio->fastsend	=vio_fastsend;
+  vio->viokeepalive	=vio_keepalive;
+  vio->should_retry	=vio_should_retry;
+  vio->was_interrupted=vio_was_interrupted;
+  vio->vioclose	=vio_close;
+  vio->peer_addr	=vio_peer_addr;
+  vio->in_addr	=vio_in_addr;
+  vio->vioblocking	=vio_blocking;
+  vio->is_blocking	=vio_is_blocking;
+  vio->timeout	=vio_timeout;
   DBUG_VOID_RETURN;
 }
 

=== modified file 'vio/viosocket.c'
--- a/vio/viosocket.c	2009-12-03 11:19:05 +0000
+++ b/vio/viosocket.c	2010-01-15 15:27:55 +0000
@@ -428,14 +428,14 @@ void vio_timeout(Vio *vio, uint which, u
 /*
   Finish pending IO on pipe. Honor wait timeout
 */
-static int pipe_complete_io(Vio* vio, char* buf, size_t size, DWORD timeout_millis)
+static size_t pipe_complete_io(Vio* vio, char* buf, size_t size, DWORD timeout_ms)
 {
   DWORD length;
   DWORD ret;
 
   DBUG_ENTER("pipe_complete_io");
 
-  ret= WaitForSingleObject(vio->pipe_overlapped.hEvent, timeout_millis);
+  ret= WaitForSingleObject(vio->pipe_overlapped.hEvent, timeout_ms);
   /*
     WaitForSingleObjects will normally return WAIT_OBJECT_O (success, IO completed)
     or WAIT_TIMEOUT.
@@ -444,14 +444,14 @@ static int pipe_complete_io(Vio* vio, ch
   {
     CancelIo(vio->hPipe);
     DBUG_PRINT("error",("WaitForSingleObject() returned  %d", ret));
-    DBUG_RETURN(-1);
+    DBUG_RETURN((size_t)-1);
   }
 
   if (!GetOverlappedResult(vio->hPipe,&(vio->pipe_overlapped),&length, FALSE))
   {
     DBUG_PRINT("error",("GetOverlappedResult() returned last error  %d", 
       GetLastError()));
-    DBUG_RETURN(-1);
+    DBUG_RETURN((size_t)-1);
   }
 
   DBUG_RETURN(length);
@@ -461,49 +461,58 @@ static int pipe_complete_io(Vio* vio, ch
 size_t vio_read_pipe(Vio * vio, uchar *buf, size_t size)
 {
   DWORD bytes_read;
+  size_t retval;
   DBUG_ENTER("vio_read_pipe");
   DBUG_PRINT("enter", ("sd: %d  buf: 0x%lx  size: %u", vio->sd, (long) buf,
                        (uint) size));
 
-  if (!ReadFile(vio->hPipe, buf, (DWORD)size, &bytes_read,
+  if (ReadFile(vio->hPipe, buf, (DWORD)size, &bytes_read,
       &(vio->pipe_overlapped)))
   {
+    retval= bytes_read;
+  }
+  else
+  {
     if (GetLastError() != ERROR_IO_PENDING)
     {
       DBUG_PRINT("error",("ReadFile() returned last error %d",
         GetLastError()));
       DBUG_RETURN((size_t)-1);
     }
-    bytes_read= pipe_complete_io(vio, buf, size,vio->read_timeout_millis);
+    retval= pipe_complete_io(vio, buf, size,vio->read_timeout_ms);
   }
 
-  DBUG_PRINT("exit", ("%d", bytes_read));
-  DBUG_RETURN(bytes_read);
+  DBUG_PRINT("exit", ("%lld", (longlong)retval));
+  DBUG_RETURN(retval);
 }
 
 
 size_t vio_write_pipe(Vio * vio, const uchar* buf, size_t size)
 {
   DWORD bytes_written;
+  size_t retval;
   DBUG_ENTER("vio_write_pipe");
   DBUG_PRINT("enter", ("sd: %d  buf: 0x%lx  size: %u", vio->sd, (long) buf,
                        (uint) size));
 
-  if (!WriteFile(vio->hPipe, buf, (DWORD)size, &bytes_written,
+  if (WriteFile(vio->hPipe, buf, (DWORD)size, &bytes_written, 
       &(vio->pipe_overlapped)))
   {
+    retval= bytes_written;
+  }
+  else
+  {
     if (GetLastError() != ERROR_IO_PENDING)
     {
       DBUG_PRINT("vio_error",("WriteFile() returned last error %d",
         GetLastError()));
       DBUG_RETURN((size_t)-1);
     }
-    bytes_written = pipe_complete_io(vio, (char *)buf, size, 
-        vio->write_timeout_millis);
+    retval= pipe_complete_io(vio, (char *)buf, size, vio->write_timeout_ms);
   }
 
-  DBUG_PRINT("exit", ("%d", bytes_written));
-  DBUG_RETURN(bytes_written);
+  DBUG_PRINT("exit", ("%lld", (longlong)retval));
+  DBUG_RETURN(retval);
 }
 
 
@@ -528,21 +537,21 @@ int vio_close_pipe(Vio * vio)
 
 void vio_win32_timeout(Vio *vio, uint which , uint timeout_sec)
 {
-    DWORD timeout_millis;
+    DWORD timeout_ms;
     /*
       Windows is measuring timeouts in milliseconds. Check for possible int 
       overflow.
     */
     if (timeout_sec > UINT_MAX/1000)
-      timeout_millis= INFINITE;
+      timeout_ms= INFINITE;
     else
-      timeout_millis= timeout_sec * 1000;
+      timeout_ms= timeout_sec * 1000;
 
     /* which == 1 means "write", which == 0 means "read".*/
     if(which)
-      vio->write_timeout_millis= timeout_millis;
+      vio->write_timeout_ms= timeout_ms;
     else
-      vio->read_timeout_millis= timeout_millis;
+      vio->read_timeout_ms= timeout_ms;
 }
 
 
@@ -577,7 +586,7 @@ size_t vio_read_shared_memory(Vio * vio,
          WAIT_ABANDONED_0 and WAIT_TIMEOUT - fail.  We can't read anything
       */
       if (WaitForMultipleObjects(array_elements(events), events, FALSE,
-                                 vio->read_timeout_millis) != WAIT_OBJECT_0)
+                                 vio->read_timeout_ms) != WAIT_OBJECT_0)
       {
         DBUG_RETURN(-1);
       };
@@ -634,7 +643,7 @@ size_t vio_write_shared_memory(Vio * vio
   while (remain != 0)
   {
     if (WaitForMultipleObjects(array_elements(events), events, FALSE,
-                               vio->write_timeout_millis) != WAIT_OBJECT_0)
+                               vio->write_timeout_ms) != WAIT_OBJECT_0)
     {
       DBUG_RETURN((size_t) -1);
     }