summaryrefslogtreecommitdiff
path: root/sql
diff options
context:
space:
mode:
authorSergei Golubchik <sergii@pisem.net>2011-07-02 22:08:51 +0200
committerSergei Golubchik <sergii@pisem.net>2011-07-02 22:08:51 +0200
commit9809f05199aeb0b67991fac41bd86f38730768dc (patch)
treefa2792ff86d0da014b535d743759810612338042 /sql
parent0accbd0364e0333e0b119aa9ce93e34ded9df6cb (diff)
parent5a0e7394a5ae0c7b6a1ea35b7ea3a8985325987a (diff)
downloadmariadb-git-9809f05199aeb0b67991fac41bd86f38730768dc.tar.gz
5.5-merge
Diffstat (limited to 'sql')
-rw-r--r--sql/CMakeLists.txt11
-rw-r--r--sql/Makefile.am287
-rw-r--r--sql/client_settings.h3
-rw-r--r--sql/debug_sync.cc34
-rw-r--r--sql/debug_sync.h2
-rw-r--r--sql/derror.cc21
-rw-r--r--sql/event_data_objects.cc47
-rw-r--r--sql/event_data_objects.h7
-rw-r--r--sql/event_db_repository.cc110
-rw-r--r--sql/event_db_repository.h5
-rw-r--r--sql/event_parse_data.cc11
-rw-r--r--sql/event_parse_data.h1
-rw-r--r--sql/event_queue.cc32
-rw-r--r--sql/events.cc102
-rw-r--r--sql/events.h17
-rw-r--r--sql/field.cc92
-rw-r--r--sql/field.h128
-rw-r--r--sql/field_conv.cc7
-rw-r--r--sql/filesort.cc33
-rw-r--r--sql/gen_lex_hash.cc4
-rw-r--r--sql/ha_ndbcluster.cc69
-rw-r--r--sql/ha_ndbcluster_binlog.cc15
-rw-r--r--sql/ha_ndbcluster_cond.cc2
-rw-r--r--sql/ha_partition.cc824
-rw-r--r--sql/ha_partition.h49
-rw-r--r--sql/handler.cc156
-rw-r--r--sql/handler.h192
-rw-r--r--sql/hostname.cc50
-rw-r--r--sql/item.cc317
-rw-r--r--sql/item.h56
-rw-r--r--sql/item_cmpfunc.cc119
-rw-r--r--sql/item_cmpfunc.h2
-rw-r--r--sql/item_create.cc70
-rw-r--r--sql/item_func.cc209
-rw-r--r--sql/item_func.h71
-rw-r--r--sql/item_geofunc.h3
-rw-r--r--sql/item_row.cc10
-rw-r--r--sql/item_strfunc.cc242
-rw-r--r--sql/item_strfunc.h69
-rw-r--r--sql/item_subselect.cc51
-rw-r--r--sql/item_subselect.h1
-rw-r--r--sql/item_sum.cc163
-rw-r--r--sql/item_sum.h59
-rw-r--r--sql/item_timefunc.cc171
-rw-r--r--sql/item_timefunc.h143
-rw-r--r--sql/item_xmlfunc.cc4
-rw-r--r--sql/key.cc6
-rw-r--r--sql/lex.h5
-rw-r--r--sql/lock.cc363
-rw-r--r--sql/lock.h6
-rw-r--r--sql/log.cc721
-rw-r--r--sql/log.h79
-rw-r--r--sql/log_event.cc156
-rw-r--r--sql/log_event.h17
-rw-r--r--sql/mdl.cc603
-rw-r--r--sql/mdl.h218
-rw-r--r--sql/message.h14
-rw-r--r--sql/my_decimal.cc12
-rw-r--r--sql/my_decimal.h69
-rw-r--r--sql/mysqld.cc382
-rw-r--r--sql/mysqld.h63
-rw-r--r--sql/net_serv.cc14
-rw-r--r--sql/opt_range.cc11
-rw-r--r--sql/opt_range.h58
-rw-r--r--sql/opt_subselect.cc2
-rw-r--r--sql/opt_sum.cc45
-rw-r--r--sql/partition_info.cc65
-rw-r--r--sql/partition_info.h11
-rw-r--r--sql/password.c32
-rw-r--r--sql/protocol.cc21
-rw-r--r--sql/records.cc9
-rw-r--r--sql/repl_failsafe.cc370
-rw-r--r--sql/repl_failsafe.h11
-rw-r--r--sql/rpl_handler.cc21
-rw-r--r--sql/rpl_handler.h3
-rw-r--r--sql/rpl_injector.cc6
-rw-r--r--sql/rpl_record.cc63
-rw-r--r--sql/rpl_record.h7
-rw-r--r--sql/rpl_rli.cc26
-rw-r--r--sql/rpl_rli.h10
-rw-r--r--sql/scheduler.cc31
-rw-r--r--sql/scheduler.h24
-rw-r--r--sql/set_var.cc17
-rw-r--r--sql/set_var.h2
-rw-r--r--sql/share/Makefile.am60
-rw-r--r--sql/share/charsets/cp1251.xml2
-rw-r--r--sql/share/charsets/languages.html16
-rw-r--r--sql/share/errmsg-utf8.txt79
-rw-r--r--sql/slave.cc194
-rw-r--r--sql/slave.h2
-rw-r--r--sql/sp.cc157
-rw-r--r--sql/sp.h15
-rw-r--r--sql/sp_head.cc117
-rw-r--r--sql/sp_head.h5
-rw-r--r--sql/sp_rcontext.h1
-rw-r--r--sql/sql_acl.cc1427
-rw-r--r--sql/sql_acl.h12
-rw-r--r--sql/sql_admin.cc91
-rw-r--r--sql/sql_alter.cc13
-rw-r--r--sql/sql_analyse.cc9
-rw-r--r--sql/sql_audit.cc55
-rw-r--r--sql/sql_audit.h62
-rw-r--r--sql/sql_base.cc437
-rw-r--r--sql/sql_base.h64
-rw-r--r--sql/sql_binlog.cc12
-rw-r--r--sql/sql_cache.cc125
-rw-r--r--sql/sql_class.cc443
-rw-r--r--sql/sql_class.h213
-rw-r--r--sql/sql_connect.cc87
-rw-r--r--sql/sql_connect.h6
-rw-r--r--sql/sql_cursor.cc74
-rw-r--r--sql/sql_cursor.h2
-rw-r--r--sql/sql_db.cc288
-rw-r--r--sql/sql_delete.cc4
-rw-r--r--sql/sql_derived.cc21
-rw-r--r--sql/sql_derived.h12
-rw-r--r--sql/sql_error.cc26
-rw-r--r--sql/sql_error.h43
-rw-r--r--sql/sql_handler.cc40
-rw-r--r--sql/sql_handler.h2
-rw-r--r--sql/sql_help.cc14
-rw-r--r--sql/sql_insert.cc278
-rw-r--r--sql/sql_lex.cc8
-rw-r--r--sql/sql_lex.h82
-rw-r--r--sql/sql_load.cc110
-rw-r--r--sql/sql_parse.cc569
-rw-r--r--sql/sql_parse.h9
-rw-r--r--sql/sql_partition.cc480
-rw-r--r--sql/sql_partition.h8
-rw-r--r--sql/sql_partition_admin.cc99
-rw-r--r--sql/sql_partition_admin.h6
-rw-r--r--sql/sql_plist.h16
-rw-r--r--sql/sql_plugin.cc89
-rw-r--r--sql/sql_plugin.h10
-rw-r--r--sql/sql_prepare.cc102
-rw-r--r--sql/sql_priv.h39
-rw-r--r--sql/sql_reload.cc85
-rw-r--r--sql/sql_reload.h2
-rw-r--r--sql/sql_rename.cc14
-rw-r--r--sql/sql_repl.cc55
-rw-r--r--sql/sql_repl.h2
-rw-r--r--sql/sql_select.cc604
-rw-r--r--sql/sql_select.h5
-rw-r--r--sql/sql_show.cc692
-rw-r--r--sql/sql_show.h1
-rw-r--r--sql/sql_string.cc45
-rw-r--r--sql/sql_string.h31
-rw-r--r--sql/sql_table.cc549
-rw-r--r--sql/sql_table.h11
-rw-r--r--sql/sql_trigger.cc208
-rw-r--r--sql/sql_trigger.h39
-rw-r--r--sql/sql_truncate.cc495
-rw-r--r--sql/sql_truncate.h23
-rw-r--r--sql/sql_udf.cc12
-rw-r--r--sql/sql_union.cc10
-rw-r--r--sql/sql_update.cc235
-rw-r--r--sql/sql_update.h3
-rw-r--r--sql/sql_view.cc59
-rw-r--r--sql/sql_yacc.yy166
-rw-r--r--sql/strfunc.cc4
-rw-r--r--sql/sys_vars.cc130
-rw-r--r--sql/sys_vars.h67
-rw-r--r--sql/table.cc208
-rw-r--r--sql/table.h26
-rw-r--r--sql/transaction.cc88
-rw-r--r--sql/unireg.cc18
-rw-r--r--sql/unireg.h4
167 files changed, 11193 insertions, 6477 deletions
diff --git a/sql/CMakeLists.txt b/sql/CMakeLists.txt
index 9a808b62f24..966522b5aa3 100644
--- a/sql/CMakeLists.txt
+++ b/sql/CMakeLists.txt
@@ -50,7 +50,8 @@ SET (SQL_SOURCE
log_event_old.cc rpl_record_old.cc
message.h mf_iocache.cc my_decimal.cc ../sql-common/my_time.c
mysqld.cc net_serv.cc keycaches.cc
- ../sql-common/client_plugin.c create_options.cc
+ ../sql-common/client_plugin.c
+ create_options.cc
multi_range_read.cc opt_index_cond_pushdown.cc
opt_subselect.cc opt_table_elimination.cc
sql_expression_cache.cc sql_join_cache.cc
@@ -135,7 +136,7 @@ IF(NOT WITHOUT_DYNAMIC_PLUGINS)
ENDIF()
SET_TARGET_PROPERTIES(mysqld PROPERTIES ENABLE_EXPORTS TRUE)
-TARGET_LINK_LIBRARIES(mysqld sql)
+TARGET_LINK_LIBRARIES(mysqld sql mysys)
# Provide plugins with minimal set of libraries
SET(INTERFACE_LIBS ${LIBRT})
@@ -286,7 +287,11 @@ IF(WIN32 AND MYSQLD_EXECUTABLE)
COMPONENT DataFiles PATTERN "initdb.dep" EXCLUDE PATTERN "bootstrap.sql" EXCLUDE)
ELSE()
# Not windows or cross compiling, just install an empty directory
- INSTALL(FILES ${DUMMY_FILE} DESTINATION data/mysql)
+ INSTALL(FILES ${DUMMY_FILE} DESTINATION data/mysql COMPONENT DataFiles)
ENDIF()
ENDIF()
+ADD_CUSTOM_TARGET(show-dist-name
+ COMMAND ${CMAKE_COMMAND} -E echo "${CPACK_PACKAGE_FILE_NAME}"
+)
+
diff --git a/sql/Makefile.am b/sql/Makefile.am
deleted file mode 100644
index 2bc0d386935..00000000000
--- a/sql/Makefile.am
+++ /dev/null
@@ -1,287 +0,0 @@
-# Copyright (C) 2000-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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-#called from the top level Makefile
-
-MYSQLDATAdir = $(localstatedir)
-MYSQLSHAREdir = $(pkgdatadir)
-MYSQLBASEdir= $(prefix)
-MYSQLLIBdir= $(pkglibdir)
-pkgplugindir = $(pkglibdir)/plugin
-INCLUDES = @ZLIB_INCLUDES@ \
- -I$(top_builddir)/include -I$(top_srcdir)/include \
- -I$(top_srcdir)/regex -I$(srcdir) $(openssl_includes) \
- $(libevent_includes)
-WRAPLIBS= @WRAPLIBS@
-SUBDIRS = share
-libexec_PROGRAMS = mysqld
-EXTRA_PROGRAMS = gen_lex_hash
-bin_PROGRAMS = mysql_tzinfo_to_sql
-DTRACEFILES = filesort.o \
- .libs/libndb_la-ha_ndbcluster.o \
- handler.o \
- mysqld.o \
- net_serv.o \
- scheduler.o \
- sp_head.o \
- sql_cache.o \
- sql_connect.o \
- sql_cursor.o \
- sql_delete.o \
- sql_truncate.o \
- sql_reload.o \
- sql_insert.o \
- datadict.o \
- sql_parse.o \
- sql_prepare.o \
- sql_select.o \
- sql_update.o
-
-DTRACEFILES_DEPEND = filesort.o \
- libndb_la-ha_ndbcluster.lo \
- handler.o \
- mysqld.o \
- net_serv.o \
- scheduler.o \
- sp_head.o \
- sql_cache.o \
- sql_connect.o \
- sql_cursor.o \
- sql_delete.o \
- sql_truncate.o \
- sql_reload.o \
- sql_insert.o \
- datadict.o \
- sql_parse.o \
- sql_prepare.o \
- sql_select.o \
- sql_update.o
-
-
-noinst_LTLIBRARIES= libndb.la \
- udf_example.la
-
-SUPPORTING_LIBS = $(top_builddir)/vio/libvio.a \
- $(top_builddir)/mysys/libmysys.a \
- $(top_builddir)/dbug/libdbug.a \
- $(top_builddir)/regex/libregex.a \
- $(top_builddir)/strings/libmystrings.a
-mysqld_DEPENDENCIES= @mysql_plugin_libs@ $(SUPPORTING_LIBS) libndb.la
-LDADD = $(SUPPORTING_LIBS) @ZLIB_LIBS@ @NDB_SCI_LIBS@
-mysqld_LDADD = libndb.la \
- @MYSQLD_EXTRA_LDFLAGS@ \
- @pstack_libs@ $(libevent_libs) \
- @mysql_plugin_libs@ \
- $(LDADD) $(CXXLDFLAGS) $(WRAPLIBS) @LIBDL@ \
- $(yassl_libs) $(openssl_libs) @MYSQLD_EXTRA_LIBS@
-
-noinst_HEADERS = item.h item_func.h item_sum.h item_cmpfunc.h \
- item_strfunc.h item_timefunc.h \
- item_xmlfunc.h sql_plugin_services.h \
- item_create.h item_subselect.h item_row.h \
- sql_priv.h item_geofunc.h sql_bitmap.h \
- procedure.h sql_class.h sql_lex.h sql_list.h \
- sql_string.h unireg.h \
- sql_error.h field.h handler.h mysqld_suffix.h \
- sql_profile.h mysqld.h sql_help.h frm_crypt.h \
- ha_ndbcluster.h ha_ndbcluster_cond.h \
- ha_ndbcluster_binlog.h ha_ndbcluster_tables.h \
- ha_partition.h rpl_constants.h \
- debug_sync.h \
- opt_range.h protocol.h rpl_tblmap.h rpl_utility.h \
- rpl_reporting.h sql_locale.h sql_parse.h \
- log.h sql_show.h rpl_rli.h rpl_mi.h \
- opt_subselect.h log_slow.h multi_range_read.h \
- create_options.h sql_expression_cache.h \
- sql_select.h structs.h table.h sql_udf.h hash_filo.h \
- lex.h lex_symbol.h sql_acl.h sql_crypt.h sql_base.h \
- sql_table.h key.h lock.h thr_malloc.h strfunc.h \
- sql_delete.h sql_insert.h sql_update.h sql_db.h \
- sql_connect.h sql_rename.h sql_time.h sql_tablespace.h \
- hostname.h sql_test.h records.h filesort.h \
- sql_derived.h sql_load.h sql_handler.h init.h \
- derror.h sql_union.h des_key_file.h sql_binlog.h \
- discover.h sql_manager.h sql_do.h \
- sql_repl.h slave.h rpl_filter.h rpl_injector.h \
- log_event.h rpl_record.h sql_const.h \
- log_event_old.h rpl_record_old.h \
- sql_sort.h sql_cache.h set_var.h sys_vars_shared.h \
- spatial.h gstream.h client_settings.h tzfile.h \
- tztime.h my_decimal.h keycaches.h \
- sp_head.h sp_pcontext.h sp_rcontext.h sp.h sp_cache.h \
- parse_file.h sql_view.h sql_trigger.h \
- sql_array.h sql_cursor.h events.h scheduler.h \
- event_db_repository.h event_queue.h \
- sql_plugin.h authors.h event_parse_data.h \
- event_data_objects.h event_scheduler.h \
- sql_partition.h partition_info.h partition_element.h \
- sql_audit.h sql_alter.h sql_partition_admin.h \
- contributors.h sql_servers.h sql_signal.h records.h \
- sql_prepare.h rpl_handler.h replication.h mdl.h \
- sql_plist.h transaction.h sys_vars.h sql_truncate.h \
- sql_admin.h sql_reload.h datadict.h
-
-mysqld_SOURCES = sql_lex.cc sql_handler.cc sql_partition.cc \
- item.cc item_sum.cc item_buff.cc item_func.cc \
- item_cmpfunc.cc item_strfunc.cc item_timefunc.cc \
- thr_malloc.cc item_create.cc item_subselect.cc \
- item_row.cc item_geofunc.cc item_xmlfunc.cc \
- field.cc strfunc.cc key.cc sql_class.cc sql_list.cc \
- net_serv.cc protocol.cc sql_state.c \
- lock.cc sql_string.cc sql_manager.cc \
- main.cc mysqld.cc password.c hash_filo.cc hostname.cc \
- sql_connect.cc scheduler.cc sql_parse.cc \
- keycaches.cc set_var.cc sql_yacc.yy sys_vars.cc \
- sql_join_cache.cc opt_subselect.cc create_options.cc \
- opt_table_elimination.cc multi_range_read.cc \
- opt_index_cond_pushdown.cc sql_expression_cache.cc \
- sql_base.cc table.cc sql_select.cc sql_insert.cc \
- sql_reload.cc datadict.cc sql_profile.cc \
- sql_prepare.cc sql_error.cc sql_locale.cc \
- sql_update.cc sql_delete.cc uniques.cc sql_do.cc \
- procedure.cc sql_test.cc sql_admin.cc \
- sql_truncate.cc \
- log.cc init.cc derror.cc sql_acl.cc \
- unireg.cc des_key_file.cc \
- log_event.cc rpl_record.cc \
- log_event_old.cc rpl_record_old.cc \
- discover.cc sql_time.cc opt_range.cc opt_sum.cc \
- records.cc filesort.cc handler.cc \
- ha_partition.cc \
- debug_sync.cc \
- sql_db.cc sql_table.cc sql_rename.cc sql_crypt.cc \
- sql_load.cc mf_iocache.cc field_conv.cc sql_show.cc \
- sql_udf.cc sql_analyse.cc sql_analyse.h sql_cache.cc \
- slave.cc sql_repl.cc rpl_filter.cc rpl_tblmap.cc \
- rpl_utility.cc rpl_injector.cc rpl_rli.cc rpl_mi.cc \
- rpl_reporting.cc \
- sql_union.cc sql_derived.cc \
- sql_client.cc \
- repl_failsafe.h repl_failsafe.cc sql_view.cc \
- gstream.cc spatial.cc sql_help.cc sql_cursor.cc \
- tztime.cc my_decimal.cc\
- sp_head.cc sp_pcontext.cc sp_rcontext.cc sp.cc \
- sp_cache.cc parse_file.cc sql_trigger.cc \
- event_scheduler.cc event_data_objects.cc \
- event_queue.cc event_db_repository.cc events.cc \
- sql_plugin.cc sql_binlog.cc \
- sql_builtin.cc sql_tablespace.cc partition_info.cc \
- sql_servers.cc event_parse_data.cc sql_signal.cc \
- rpl_handler.cc mdl.cc transaction.cc sql_audit.cc \
- sql_alter.cc sql_partition_admin.cc sha2.cc
-
-nodist_mysqld_SOURCES = mini_client_errors.c pack.c client.c my_time.c my_user.c client_plugin.c
-
-libndb_la_CPPFLAGS= @ndbcluster_includes@
-libndb_la_SOURCES= ha_ndbcluster.cc \
- ha_ndbcluster_binlog.cc \
- ha_ndbcluster_cond.cc
-
-gen_lex_hash_SOURCES = gen_lex_hash.cc
-gen_lex_hash_LDFLAGS = @NOINST_LDFLAGS@
-
-mysql_tzinfo_to_sql_SOURCES = tztime.cc
-mysql_tzinfo_to_sql_CXXFLAGS= -DTZINFO2SQL
-
-DEFS = -DMYSQL_SERVER \
- -DDEFAULT_MYSQL_HOME='"$(MYSQLBASEdir)"' \
- -DMYSQL_DATADIR='"$(MYSQLDATAdir)"' \
- -DSHAREDIR='"$(MYSQLSHAREdir)"' \
- -DPLUGINDIR='"$(pkgplugindir)"' \
- -DHAVE_EVENT_SCHEDULER \
- @DEFS@
-
-BUILT_MAINT_SRC = sql_yacc.cc sql_yacc.h
-BUILT_SOURCES = $(BUILT_MAINT_SRC) lex_hash.h link_sources
-EXTRA_DIST = udf_example.c udf_example.def $(BUILT_MAINT_SRC) \
- nt_servc.cc nt_servc.h \
- message.mc message.h message.rc MSG00001.bin \
- CMakeLists.txt opt_range_mrr.cc
-
-CLEANFILES = lex_hash.h sql_yacc.output link_sources
-DISTCLEANFILES = $(EXTRA_PROGRAMS)
-MAINTAINERCLEANFILES = $(BUILT_MAINT_SRC)
-AM_YFLAGS = -d --verbose
-
-# These are listed in 'nodist_mysqld_SOURCES'
-link_sources:
- rm -f mini_client_errors.c
- @LN_CP_F@ $(top_srcdir)/libmysql/errmsg.c mini_client_errors.c
- rm -f pack.c
- @LN_CP_F@ $(top_srcdir)/sql-common/pack.c pack.c
- rm -f client.c
- @LN_CP_F@ $(top_srcdir)/sql-common/client.c client.c
- rm -f client_plugin.c
- @LN_CP_F@ $(top_srcdir)/sql-common/client_plugin.c client_plugin.c
- rm -f my_time.c
- @LN_CP_F@ $(top_srcdir)/sql-common/my_time.c my_time.c
- rm -f my_user.c
- @LN_CP_F@ $(top_srcdir)/sql-common/my_user.c my_user.c
- echo timestamp > link_sources
-
-# This generates lex_hash.h
-# NOTE Built sources should depend on their sources not the tool
-# this avoid the rebuild of the built files in a source dist
-lex_hash.h: gen_lex_hash.cc lex.h
- $(MAKE) $(AM_MAKEFLAGS) gen_lex_hash$(EXEEXT)
- ./gen_lex_hash$(EXEEXT) > $@-t
- $(MV) $@-t $@
-
-# For testing of udf_example.so
-udf_example_la_SOURCES= udf_example.c
-udf_example_la_LDFLAGS= -module -rpath $(pkglibdir)
-
-# We might have some stuff not built in this build, but that we want to install
-install-exec-hook:
- $(mkinstalldirs) $(DESTDIR)$(libexecdir) $(DESTDIR)$(pkglibdir)
- test ! -x mysqld-debug$(EXEEXT) || $(INSTALL_PROGRAM) mysqld-debug$(EXEEXT) $(DESTDIR)$(libexecdir)
- test ! -f mysqld-debug.sym.gz || $(INSTALL_DATA) mysqld-debug.sym.gz $(DESTDIR)$(pkglibdir)
- test ! -f mysqld.sym.gz || $(INSTALL_DATA) mysqld.sym.gz $(DESTDIR)$(pkglibdir)
-
-if HAVE_DTRACE_DASH_G
-libndb_la_LIBADD = probes_libndb.o
-libndb_la_DEPENDENCIES = dtrace_files dtrace_providers probes_libndb.o
-mysqld_LDADD += probes_all.o
-mysqld_DEPENDENCIES += dtrace_files dtrace_providers probes_all.o
-CLEANFILES += dtrace_files dtrace_providers probes_all.o
-DTRACEPROVIDER = probes_mysql.d
-CLEANFILES += $(DTRACEPROVIDER)
-
-dtrace_files:
- echo $(DTRACEFILES) > $@
-dtrace_providers: probes_mysql.d
- echo $(DTRACEPROVIDER) > $@
-probes_mysql.d:
- -$(RM) -f probes_mysql.d
- $(CP) $(top_srcdir)/include/probes_mysql.d.base probes_mysql.d
-
-DTRACEDIRS = . ../mysys $(patsubst %,$(top_builddir)/storage/%,@mysql_se_dirs@)
-
-probes_all.o: probes_mysql.d $(DTRACEFILES_DEPEND)
- providers=`(for i in $(DTRACEDIRS); do cat $$i/dtrace_providers 2>/dev/null; done) | tr " " "\n" | sort | uniq | sed -e '/^$$/d' -e 's/^/-s /'`; \
- objects=`for i in $(DTRACEDIRS); do f=\`cat $$i/dtrace_files 2>/dev/null\`; for j in $$f; do test -f $$i/$$j && echo "$$i/$$j "; done; done`; \
- $(DTRACE) $(DTRACEFLAGS) -G $$providers $$objects -o $@
-
-# Can't depend directly on .libs/*.o, because there is no generated rule for
-# that in the Makefile; it is a byproduct of *.lo
-probes_libndb.o: probes_mysql.d libndb_la-ha_ndbcluster.lo
- if test -f .libs/libndb_la-ha_ndbcluster.o ; then \
- $(DTRACE) $(DTRACEFLAGS) -G -s probes_mysql.d .libs/libndb_la-ha_ndbcluster.o -o $@; \
- fi; \
- if test -f libndb_la-ha_ndbcluster.o ; then \
- $(DTRACE) $(DTRACEFLAGS) -G -s probes_mysql.d libndb_la-ha_ndbcluster.o -o $@; \
- fi
-
-endif
diff --git a/sql/client_settings.h b/sql/client_settings.h
index 3152bc47845..0a61c12b64a 100644
--- a/sql/client_settings.h
+++ b/sql/client_settings.h
@@ -27,9 +27,6 @@
CLIENT_SECURE_CONNECTION | CLIENT_TRANSACTIONS | \
CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION)
-#define init_sigpipe_variables
-#define set_sigpipe(mysql)
-#define reset_sigpipe(mysql)
#define read_user_name(A) {}
#undef _CUSTOMCONFIG_
diff --git a/sql/debug_sync.cc b/sql/debug_sync.cc
index 74e5b2c70f3..7f69ae54037 100644
--- a/sql/debug_sync.cc
+++ b/sql/debug_sync.cc
@@ -1691,7 +1691,7 @@ static void debug_sync_execute(THD *thd, st_debug_sync_action *action)
if (action->execute)
{
- const char *old_proc_info;
+ const char *UNINIT_VAR(old_proc_info);
action->execute--;
@@ -1745,11 +1745,20 @@ static void debug_sync_execute(THD *thd, st_debug_sync_action *action)
We don't use enter_cond()/exit_cond(). They do not save old
mutex and cond. This would prohibit the use of DEBUG_SYNC
between other places of enter_cond() and exit_cond().
+
+ We need to check for existence of thd->mysys_var to also make
+ it possible to use DEBUG_SYNC framework in scheduler when this
+ variable has been set to NULL.
*/
- old_mutex= thd->mysys_var->current_mutex;
- old_cond= thd->mysys_var->current_cond;
- thd->mysys_var->current_mutex= &debug_sync_global.ds_mutex;
- thd->mysys_var->current_cond= &debug_sync_global.ds_cond;
+ if (thd->mysys_var)
+ {
+ old_mutex= thd->mysys_var->current_mutex;
+ old_cond= thd->mysys_var->current_cond;
+ thd->mysys_var->current_mutex= &debug_sync_global.ds_mutex;
+ thd->mysys_var->current_cond= &debug_sync_global.ds_cond;
+ }
+ else
+ old_mutex= NULL;
set_timespec(abstime, action->timeout);
DBUG_EXECUTE("debug_sync_exec", {
@@ -1804,11 +1813,16 @@ static void debug_sync_execute(THD *thd, st_debug_sync_action *action)
is locked. (See comment in THD::exit_cond().)
*/
mysql_mutex_unlock(&debug_sync_global.ds_mutex);
- mysql_mutex_lock(&thd->mysys_var->mutex);
- thd->mysys_var->current_mutex= old_mutex;
- thd->mysys_var->current_cond= old_cond;
- thd_proc_info(thd, old_proc_info);
- mysql_mutex_unlock(&thd->mysys_var->mutex);
+ if (old_mutex)
+ {
+ mysql_mutex_lock(&thd->mysys_var->mutex);
+ thd->mysys_var->current_mutex= old_mutex;
+ thd->mysys_var->current_cond= old_cond;
+ thd_proc_info(thd, old_proc_info);
+ mysql_mutex_unlock(&thd->mysys_var->mutex);
+ }
+ else
+ thd_proc_info(thd, old_proc_info);
}
else
{
diff --git a/sql/debug_sync.h b/sql/debug_sync.h
index 9ac7da39d4d..ba3739e8ad5 100644
--- a/sql/debug_sync.h
+++ b/sql/debug_sync.h
@@ -39,7 +39,7 @@ class THD;
} while (0)
/* Command line option --debug-sync-timeout. See mysqld.cc. */
-extern uint opt_debug_sync_timeout;
+extern MYSQL_PLUGIN_IMPORT uint opt_debug_sync_timeout;
/* Default WAIT_FOR timeout if command line option is given without argument. */
#define DEBUG_SYNC_DEFAULT_WAIT_TIMEOUT 300
diff --git a/sql/derror.cc b/sql/derror.cc
index db9cd3c0c58..2b4cc13073e 100644
--- a/sql/derror.cc
+++ b/sql/derror.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2005 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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 */
-
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@@ -108,7 +107,6 @@ bool read_texts(const char *file_name, const char *language,
char lang_path[FN_REFLEN];
uchar *buff;
uchar head[32],*pos;
- const char *errmsg;
DBUG_ENTER("read_texts");
LINT_INIT(buff);
@@ -185,18 +183,9 @@ Check that the above file is the right version for this program!",
DBUG_RETURN(0);
err:
- switch (funktpos) {
- case 2:
- errmsg= "Not enough memory for messagefile '%s'";
- break;
- case 1:
- errmsg= "Can't read from messagefile '%s'";
- break;
- default:
- errmsg= "Can't find messagefile '%s'";
- break;
- }
- sql_print_error(errmsg, name);
+ sql_print_error((funktpos == 2) ? "Not enough memory for messagefile '%s'" :
+ ((funktpos == 1) ? "Can't read from messagefile '%s'" :
+ "Can't find messagefile '%s'"), name);
if (file != FERR)
(void) mysql_file_close(file, MYF(MY_WME));
DBUG_RETURN(1);
diff --git a/sql/event_data_objects.cc b/sql/event_data_objects.cc
index 5a1844d730e..6d00d6fd74a 100644
--- a/sql/event_data_objects.cc
+++ b/sql/event_data_objects.cc
@@ -290,7 +290,6 @@ Event_basic::load_time_zone(THD *thd, const LEX_STRING tz_name)
*/
Event_queue_element::Event_queue_element():
- status_changed(FALSE), last_executed_changed(FALSE),
on_completion(Event_parse_data::ON_COMPLETION_DROP),
status(Event_parse_data::ENABLED), expression(0), dropped(FALSE),
execution_count(0)
@@ -539,7 +538,6 @@ Event_queue_element::load_from_row(THD *thd, TABLE *table)
TIME_NO_ZERO_DATE);
last_executed= my_tz_OFFSET0->TIME_to_gmt_sec(&time,&not_used);
}
- last_executed_changed= FALSE;
if ((ptr= get_field(&mem_root, table->field[ET_FIELD_STATUS])) == NullS)
DBUG_RETURN(TRUE);
@@ -934,7 +932,6 @@ Event_queue_element::compute_next_execution_time()
DBUG_PRINT("info",("One-time event will be dropped: %d.", dropped));
status= Event_parse_data::DISABLED;
- status_changed= TRUE;
}
goto ret;
}
@@ -954,7 +951,6 @@ Event_queue_element::compute_next_execution_time()
dropped= TRUE;
DBUG_PRINT("info", ("Dropped: %d", dropped));
status= Event_parse_data::DISABLED;
- status_changed= TRUE;
goto ret;
}
@@ -1017,7 +1013,6 @@ Event_queue_element::compute_next_execution_time()
if (on_completion == Event_parse_data::ON_COMPLETION_DROP)
dropped= TRUE;
status= Event_parse_data::DISABLED;
- status_changed= TRUE;
}
else
{
@@ -1107,7 +1102,6 @@ Event_queue_element::compute_next_execution_time()
execute_at= 0;
execute_at_null= TRUE;
status= Event_parse_data::DISABLED;
- status_changed= TRUE;
if (on_completion == Event_parse_data::ON_COMPLETION_DROP)
dropped= TRUE;
}
@@ -1143,50 +1137,11 @@ void
Event_queue_element::mark_last_executed(THD *thd)
{
last_executed= (my_time_t) thd->query_start();
- last_executed_changed= TRUE;
execution_count++;
}
-/*
- Saves status and last_executed_at to the disk if changed.
-
- SYNOPSIS
- Event_queue_element::update_timing_fields()
- thd - thread context
-
- RETURN VALUE
- FALSE OK
- TRUE Error while opening mysql.event for writing or during
- write on disk
-*/
-
-bool
-Event_queue_element::update_timing_fields(THD *thd)
-{
- Event_db_repository *db_repository= Events::get_db_repository();
- int ret;
-
- DBUG_ENTER("Event_queue_element::update_timing_fields");
-
- DBUG_PRINT("enter", ("name: %*s", (int) name.length, name.str));
-
- /* No need to update if nothing has changed */
- if (!(status_changed || last_executed_changed))
- DBUG_RETURN(0);
-
- ret= db_repository->update_timing_fields_for_event(thd,
- dbname, name,
- last_executed_changed,
- last_executed,
- status_changed,
- (ulonglong) status);
- last_executed_changed= status_changed= FALSE;
- DBUG_RETURN(ret);
-}
-
-
static
void
append_datetime(String *buf, Time_zone *time_zone, my_time_t secs,
@@ -1524,7 +1479,7 @@ end:
thd->end_statement();
thd->cleanup_after_query();
/* Avoid races with SHOW PROCESSLIST */
- thd->set_query(NULL, 0);
+ thd->reset_query();
DBUG_PRINT("info", ("EXECUTED %s.%s ret: %d", dbname.str, name.str, ret));
diff --git a/sql/event_data_objects.h b/sql/event_data_objects.h
index a70d38f2a9d..2c693e5ec43 100644
--- a/sql/event_data_objects.h
+++ b/sql/event_data_objects.h
@@ -82,10 +82,6 @@ protected:
class Event_queue_element : public Event_basic
{
-protected:
- bool status_changed;
- bool last_executed_changed;
-
public:
int on_completion;
int status;
@@ -117,9 +113,6 @@ public:
void
mark_last_executed(THD *thd);
-
- bool
- update_timing_fields(THD *thd);
};
diff --git a/sql/event_db_repository.cc b/sql/event_db_repository.cc
index 961f7966a12..83a9fdd083d 100644
--- a/sql/event_db_repository.cc
+++ b/sql/event_db_repository.cc
@@ -236,9 +236,16 @@ mysql_event_fill_row(THD *thd,
if (fields[f_num= ET_FIELD_NAME]->store(et->name.str, et->name.length, scs))
goto err_truncate;
- /* both ON_COMPLETION and STATUS are NOT NULL thus not calling set_notnull()*/
+ /* ON_COMPLETION field is NOT NULL thus not calling set_notnull()*/
rs|= fields[ET_FIELD_ON_COMPLETION]->store((longlong)et->on_completion, TRUE);
- rs|= fields[ET_FIELD_STATUS]->store((longlong)et->status, TRUE);
+
+ /*
+ Set STATUS value unconditionally in case of CREATE EVENT.
+ For ALTER EVENT set it only if value of this field was changed.
+ Since STATUS field is NOT NULL call to set_notnull() is not needed.
+ */
+ if (!is_update || et->status_changed)
+ rs|= fields[ET_FIELD_STATUS]->store((longlong)et->status, TRUE);
rs|= fields[ET_FIELD_ORIGINATOR]->store((longlong)et->originator, TRUE);
/*
@@ -435,7 +442,7 @@ Event_db_repository::index_read_for_db_for_i_s(THD *thd, TABLE *schema_table,
if (!(ret= event_table->file->ha_index_read_map(event_table->record[0],
key_buf,
(key_part_map)1,
- HA_READ_PREFIX)))
+ HA_READ_KEY_EXACT)))
{
DBUG_PRINT("info",("Found rows. Let's retrieve them. ret=%d", ret));
do
@@ -537,6 +544,13 @@ Event_db_repository::fill_schema_events(THD *thd, TABLE_LIST *i_s_table,
if (open_system_tables_for_read(thd, &event_table, &open_tables_backup))
DBUG_RETURN(TRUE);
+ if (table_intact.check(event_table.table, &event_table_def))
+ {
+ close_system_tables(thd, &open_tables_backup);
+ my_error(ER_EVENT_OPEN_TABLE_FAILED, MYF(0));
+ DBUG_RETURN(TRUE);
+ }
+
/*
1. SELECT I_S => use table scan. I_S.EVENTS does not guarantee order
thus we won't order it. OTOH, SHOW EVENTS will be
@@ -594,6 +608,14 @@ Event_db_repository::open_event_table(THD *thd, enum thr_lock_type lock_type,
*table= tables.table;
tables.table->use_all_columns();
+
+ if (table_intact.check(*table, &event_table_def))
+ {
+ close_thread_tables(thd);
+ my_error(ER_EVENT_OPEN_TABLE_FAILED, MYF(0));
+ DBUG_RETURN(TRUE);
+ }
+
DBUG_RETURN(FALSE);
}
@@ -608,23 +630,32 @@ Event_db_repository::open_event_table(THD *thd, enum thr_lock_type lock_type,
only creates a record on disk.
@pre The thread handle has no open tables.
- @param[in,out] thd THD
- @param[in] parse_data Parsed event definition
- @param[in] create_if_not TRUE if IF NOT EXISTS clause was provided
- to CREATE EVENT statement
-
+ @param[in,out] thd THD
+ @param[in] parse_data Parsed event definition
+ @param[in] create_if_not TRUE if IF NOT EXISTS clause was provided
+ to CREATE EVENT statement
+ @param[out] event_already_exists When method is completed successfully
+ set to true if event already exists else
+ set to false
@retval FALSE success
@retval TRUE error
*/
bool
Event_db_repository::create_event(THD *thd, Event_parse_data *parse_data,
- bool create_if_not)
+ bool create_if_not,
+ bool *event_already_exists)
{
int ret= 1;
TABLE *table= NULL;
sp_head *sp= thd->lex->sphead;
ulong saved_mode= thd->variables.sql_mode;
+ /*
+ Take a savepoint to release only the lock on mysql.event
+ table at the end but keep the global read lock and
+ possible other locks taken by the caller.
+ */
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
DBUG_ENTER("Event_db_repository::create_event");
@@ -645,6 +676,7 @@ Event_db_repository::create_event(THD *thd, Event_parse_data *parse_data,
{
if (create_if_not)
{
+ *event_already_exists= true;
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
ER_EVENT_ALREADY_EXISTS, ER(ER_EVENT_ALREADY_EXISTS),
parse_data->name.str);
@@ -652,8 +684,10 @@ Event_db_repository::create_event(THD *thd, Event_parse_data *parse_data,
}
else
my_error(ER_EVENT_ALREADY_EXISTS, MYF(0), parse_data->name.str);
+
goto end;
- }
+ } else
+ *event_already_exists= false;
DBUG_PRINT("info", ("non-existent, go forward"));
@@ -692,8 +726,6 @@ Event_db_repository::create_event(THD *thd, Event_parse_data *parse_data,
if (mysql_event_fill_row(thd, table, parse_data, sp, saved_mode, FALSE))
goto end;
- table->field[ET_FIELD_STATUS]->store((longlong)parse_data->status, TRUE);
-
if ((ret= table->file->ha_write_row(table->record[0])))
{
table->file->print_error(ret, MYF(0));
@@ -702,8 +734,8 @@ Event_db_repository::create_event(THD *thd, Event_parse_data *parse_data,
ret= 0;
end:
- if (table)
- close_mysql_tables(thd);
+ close_thread_tables(thd);
+ thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
thd->variables.sql_mode= saved_mode;
DBUG_RETURN(test(ret));
@@ -737,6 +769,12 @@ Event_db_repository::update_event(THD *thd, Event_parse_data *parse_data,
TABLE *table= NULL;
sp_head *sp= thd->lex->sphead;
ulong saved_mode= thd->variables.sql_mode;
+ /*
+ Take a savepoint to release only the lock on mysql.event
+ table at the end but keep the global read lock and
+ possible other locks taken by the caller.
+ */
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
int ret= 1;
DBUG_ENTER("Event_db_repository::update_event");
@@ -814,8 +852,8 @@ Event_db_repository::update_event(THD *thd, Event_parse_data *parse_data,
ret= 0;
end:
- if (table)
- close_mysql_tables(thd);
+ close_thread_tables(thd);
+ thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
thd->variables.sql_mode= saved_mode;
DBUG_RETURN(test(ret));
@@ -841,6 +879,12 @@ Event_db_repository::drop_event(THD *thd, LEX_STRING db, LEX_STRING name,
bool drop_if_exists)
{
TABLE *table= NULL;
+ /*
+ Take a savepoint to release only the lock on mysql.event
+ table at the end but keep the global read lock and
+ possible other locks taken by the caller.
+ */
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
int ret= 1;
DBUG_ENTER("Event_db_repository::drop_event");
@@ -869,8 +913,8 @@ Event_db_repository::drop_event(THD *thd, LEX_STRING db, LEX_STRING name,
ret= 0;
end:
- if (table)
- close_mysql_tables(thd);
+ close_thread_tables(thd);
+ thd->mdl_context.rollback_to_savepoint(mdl_savepoint);
DBUG_RETURN(test(ret));
}
@@ -944,7 +988,7 @@ Event_db_repository::drop_schema_events(THD *thd, LEX_STRING schema)
TABLE *table= NULL;
READ_RECORD read_record_info;
enum enum_events_table_field field= ET_FIELD_DB;
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
DBUG_ENTER("Event_db_repository::drop_schema_events");
DBUG_PRINT("enter", ("field=%d schema=%s", field, schema.str));
@@ -1025,6 +1069,13 @@ Event_db_repository::load_named_event(THD *thd, LEX_STRING dbname,
*/
if (!(ret= open_system_tables_for_read(thd, &event_table, &open_tables_backup)))
{
+ if (table_intact.check(event_table.table, &event_table_def))
+ {
+ close_system_tables(thd, &open_tables_backup);
+ my_error(ER_EVENT_OPEN_TABLE_FAILED, MYF(0));
+ DBUG_RETURN(TRUE);
+ }
+
if ((ret= find_named_event(dbname, name, event_table.table)))
my_error(ER_EVENT_DOES_NOT_EXIST, MYF(0), name.str);
else if ((ret= etn->load_from_row(thd, event_table.table)))
@@ -1050,15 +1101,14 @@ Event_db_repository::
update_timing_fields_for_event(THD *thd,
LEX_STRING event_db_name,
LEX_STRING event_name,
- bool update_last_executed,
my_time_t last_executed,
- bool update_status,
ulonglong status)
{
TABLE *table= NULL;
Field **fields;
int ret= 1;
bool save_binlog_row_based;
+ MYSQL_TIME time;
DBUG_ENTER("Event_db_repository::update_timing_fields_for_event");
@@ -1083,20 +1133,12 @@ update_timing_fields_for_event(THD *thd,
/* Don't update create on row update. */
table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
- if (update_last_executed)
- {
- MYSQL_TIME time;
- my_tz_OFFSET0->gmt_sec_to_TIME(&time, last_executed);
+ my_tz_OFFSET0->gmt_sec_to_TIME(&time, last_executed);
+ fields[ET_FIELD_LAST_EXECUTED]->set_notnull();
+ fields[ET_FIELD_LAST_EXECUTED]->store_time(&time, MYSQL_TIMESTAMP_DATETIME);
- fields[ET_FIELD_LAST_EXECUTED]->set_notnull();
- fields[ET_FIELD_LAST_EXECUTED]->store_time(&time,
- MYSQL_TIMESTAMP_DATETIME);
- }
- if (update_status)
- {
- fields[ET_FIELD_STATUS]->set_notnull();
- fields[ET_FIELD_STATUS]->store(status, TRUE);
- }
+ fields[ET_FIELD_STATUS]->set_notnull();
+ fields[ET_FIELD_STATUS]->store(status, TRUE);
if ((ret= table->file->ha_update_row(table->record[1], table->record[0])))
{
diff --git a/sql/event_db_repository.h b/sql/event_db_repository.h
index 4f1a6a28e4a..162ec5d1243 100644
--- a/sql/event_db_repository.h
+++ b/sql/event_db_repository.h
@@ -73,7 +73,8 @@ public:
Event_db_repository(){}
bool
- create_event(THD *thd, Event_parse_data *parse_data, bool create_if_not);
+ create_event(THD *thd, Event_parse_data *parse_data, bool create_if_not,
+ bool *event_already_exists);
bool
update_event(THD *thd, Event_parse_data *parse_data, LEX_STRING *new_dbname,
@@ -101,9 +102,7 @@ public:
update_timing_fields_for_event(THD *thd,
LEX_STRING event_db_name,
LEX_STRING event_name,
- bool update_last_executed,
my_time_t last_executed,
- bool update_status,
ulonglong status);
public:
static bool
diff --git a/sql/event_parse_data.cc b/sql/event_parse_data.cc
index c36567fc8e1..d8c9847d0a0 100644
--- a/sql/event_parse_data.cc
+++ b/sql/event_parse_data.cc
@@ -48,9 +48,8 @@ Event_parse_data::new_instance(THD *thd)
Event_parse_data::Event_parse_data()
:on_completion(Event_parse_data::ON_COMPLETION_DEFAULT),
- status(Event_parse_data::ENABLED),
- do_not_create(FALSE),
- body_changed(FALSE),
+ status(Event_parse_data::ENABLED), status_changed(false),
+ do_not_create(FALSE), body_changed(FALSE),
item_starts(NULL), item_ends(NULL), item_execute_at(NULL),
starts_null(TRUE), ends_null(TRUE), execute_at_null(TRUE),
item_expression(NULL), expression(0)
@@ -142,6 +141,7 @@ Event_parse_data::check_if_in_the_past(THD *thd, my_time_t ltime_utc)
else if (status == Event_parse_data::ENABLED)
{
status= Event_parse_data::DISABLED;
+ status_changed= true;
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
ER_EVENT_EXEC_TIME_IN_THE_PAST,
ER(ER_EVENT_EXEC_TIME_IN_THE_PAST));
@@ -571,7 +571,10 @@ void Event_parse_data::check_originator_id(THD *thd)
DBUG_PRINT("info", ("Invoked object status set to SLAVESIDE_DISABLED."));
if ((status == Event_parse_data::ENABLED) ||
(status == Event_parse_data::DISABLED))
- status = Event_parse_data::SLAVESIDE_DISABLED;
+ {
+ status= Event_parse_data::SLAVESIDE_DISABLED;
+ status_changed= true;
+ }
originator = thd->server_id;
}
else
diff --git a/sql/event_parse_data.h b/sql/event_parse_data.h
index b8cf4954195..85c620760cb 100644
--- a/sql/event_parse_data.h
+++ b/sql/event_parse_data.h
@@ -55,6 +55,7 @@ public:
int on_completion;
int status;
+ bool status_changed;
longlong originator;
/*
do_not_create will be set if STARTS time is in the past and
diff --git a/sql/event_queue.cc b/sql/event_queue.cc
index 7e49c9888ad..781f7fc4c4a 100644
--- a/sql/event_queue.cc
+++ b/sql/event_queue.cc
@@ -17,6 +17,8 @@
#include "unireg.h"
#include "event_queue.h"
#include "event_data_objects.h"
+#include "event_db_repository.h"
+#include "events.h"
#include "sql_audit.h"
#include "tztime.h" // my_tz_find, my_tz_OFFSET0, struct Time_zone
#include "log.h" // sql_print_error
@@ -451,7 +453,6 @@ Event_queue::recalculate_activation_times(THD *thd)
i++)
{
((Event_queue_element*)queue_element(&queue, i))->compute_next_execution_time();
- ((Event_queue_element*)queue_element(&queue, i))->update_timing_fields(thd);
}
queue_fix(&queue);
/*
@@ -581,6 +582,8 @@ Event_queue::get_top_for_execution_if_time(THD *thd,
{
bool ret= FALSE;
*event_name= NULL;
+ my_time_t UNINIT_VAR(last_executed);
+ int UNINIT_VAR(status);
DBUG_ENTER("Event_queue::get_top_for_execution_if_time");
LOCK_QUEUE_DATA();
@@ -646,8 +649,14 @@ Event_queue::get_top_for_execution_if_time(THD *thd,
top->execution_count++;
(*event_name)->dropped= top->dropped;
+ /*
+ Save new values of last_executed timestamp and event status on stack
+ in order to be able to update event description in system table once
+ QUEUE_DATA lock is released.
+ */
+ last_executed= top->last_executed;
+ status= top->status;
- top->update_timing_fields(thd);
if (top->status == Event_parse_data::DISABLED)
{
DBUG_PRINT("info", ("removing from the queue"));
@@ -670,9 +679,16 @@ end:
ret, (long) *event_name));
if (*event_name)
+ {
DBUG_PRINT("info", ("db: %s name: %s",
(*event_name)->dbname.str, (*event_name)->name.str));
+ Event_db_repository *db_repository= Events::get_db_repository();
+ (void) db_repository->update_timing_fields_for_event(thd,
+ (*event_name)->dbname, (*event_name)->name,
+ last_executed, (ulonglong) status);
+ }
+
DBUG_RETURN(ret);
}
@@ -755,11 +771,13 @@ Event_queue::cond_wait(THD *thd, struct timespec *abstime, const char* msg,
thd->enter_cond(&COND_queue_state, &LOCK_event_queue, msg);
- DBUG_PRINT("info", ("mysql_cond_%swait", abstime? "timed":""));
- if (!abstime)
- mysql_cond_wait(&COND_queue_state, &LOCK_event_queue);
- else
- mysql_cond_timedwait(&COND_queue_state, &LOCK_event_queue, abstime);
+ if (!thd->killed)
+ {
+ if (!abstime)
+ mysql_cond_wait(&COND_queue_state, &LOCK_event_queue);
+ else
+ mysql_cond_timedwait(&COND_queue_state, &LOCK_event_queue, abstime);
+ }
mutex_last_locked_in_func= func;
mutex_last_locked_at_line= line;
diff --git a/sql/events.cc b/sql/events.cc
index 9361242c570..789d4414e75 100644
--- a/sql/events.cc
+++ b/sql/events.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -30,6 +30,7 @@
#include "event_scheduler.h"
#include "sp_head.h" // for Stored_program_creation_ctx
#include "set_var.h"
+#include "lock.h" // lock_object_name
/**
@addtogroup Event_Scheduler
@@ -77,7 +78,6 @@ Event_queue *Events::event_queue;
Event_scheduler *Events::scheduler;
Event_db_repository *Events::db_repository;
ulong Events::opt_event_scheduler= Events::EVENTS_OFF;
-mysql_mutex_t Events::LOCK_event_metadata;
bool Events::check_system_tables_error= FALSE;
@@ -283,6 +283,7 @@ create_query_string(THD *thd, String *buf)
return 0;
}
+
/**
Create a new event.
@@ -303,8 +304,8 @@ bool
Events::create_event(THD *thd, Event_parse_data *parse_data,
bool if_not_exists)
{
- int ret;
- bool save_binlog_row_based;
+ bool ret;
+ bool save_binlog_row_based, event_already_exists;
DBUG_ENTER("Events::create_event");
if (check_if_system_tables_error())
@@ -339,31 +340,37 @@ Events::create_event(THD *thd, Event_parse_data *parse_data,
if ((save_binlog_row_based= thd->is_current_stmt_binlog_format_row()))
thd->clear_current_stmt_binlog_format_row();
- mysql_mutex_lock(&LOCK_event_metadata);
+ if (lock_object_name(thd, MDL_key::EVENT,
+ parse_data->dbname.str, parse_data->name.str))
+ DBUG_RETURN(TRUE);
/* On error conditions my_error() is called so no need to handle here */
- if (!(ret= db_repository->create_event(thd, parse_data, if_not_exists)))
+ if (!(ret= db_repository->create_event(thd, parse_data, if_not_exists,
+ &event_already_exists)))
{
Event_queue_element *new_element;
bool dropped= 0;
- if (!(new_element= new Event_queue_element()))
- ret= TRUE; // OOM
- else if ((ret= db_repository->load_named_event(thd, parse_data->dbname,
- parse_data->name,
- new_element)))
- {
- if (!db_repository->drop_event(thd, parse_data->dbname, parse_data->name,
- TRUE))
- dropped= 1;
- delete new_element;
- }
- else
+ if (!event_already_exists)
{
- /* TODO: do not ignore the out parameter and a possible OOM error! */
- bool created;
- if (event_queue)
- event_queue->create_event(thd, new_element, &created);
+ if (!(new_element= new Event_queue_element()))
+ ret= TRUE; // OOM
+ else if ((ret= db_repository->load_named_event(thd, parse_data->dbname,
+ parse_data->name,
+ new_element)))
+ {
+ if (!db_repository->drop_event(thd, parse_data->dbname, parse_data->name,
+ TRUE))
+ dropped= 1;
+ delete new_element;
+ }
+ else
+ {
+ /* TODO: do not ignore the out parameter and a possible OOM error! */
+ bool created;
+ if (event_queue)
+ event_queue->create_event(thd, new_element, &created);
+ }
}
/*
binlog the create event unless it's been successfully dropped
@@ -377,17 +384,16 @@ Events::create_event(THD *thd, Event_parse_data *parse_data,
{
sql_print_error("Event Error: An error occurred while creating query string, "
"before writing it into binary log.");
- ret= TRUE;
+ ret= true;
}
else
- {
- /* If the definer is not set or set to CURRENT_USER, the value of CURRENT_USER
- will be written into the binary log as the definer for the SQL thread. */
+ /*
+ If the definer is not set or set to CURRENT_USER, the value of CURRENT_USER
+ will be written into the binary log as the definer for the SQL thread.
+ */
ret= write_bin_log(thd, TRUE, log_query.c_ptr(), log_query.length());
- }
}
}
- mysql_mutex_unlock(&LOCK_event_metadata);
/* Restore the state of binlog format */
DBUG_ASSERT(!thd->is_current_stmt_binlog_format_row());
if (save_binlog_row_based)
@@ -443,7 +449,7 @@ Events::update_event(THD *thd, Event_parse_data *parse_data,
!sortcmp_lex_string(parse_data->name, *new_name,
system_charset_info))
{
- my_error(ER_EVENT_SAME_NAME, MYF(0), parse_data->name.str);
+ my_error(ER_EVENT_SAME_NAME, MYF(0));
DBUG_RETURN(TRUE);
}
@@ -471,7 +477,9 @@ Events::update_event(THD *thd, Event_parse_data *parse_data,
if ((save_binlog_row_based= thd->is_current_stmt_binlog_format_row()))
thd->clear_current_stmt_binlog_format_row();
- mysql_mutex_lock(&LOCK_event_metadata);
+ if (lock_object_name(thd, MDL_key::EVENT,
+ parse_data->dbname.str, parse_data->name.str))
+ DBUG_RETURN(TRUE);
/* On error conditions my_error() is called so no need to handle here */
if (!(ret= db_repository->update_event(thd, parse_data,
@@ -484,10 +492,7 @@ Events::update_event(THD *thd, Event_parse_data *parse_data,
ret= TRUE; // OOM
else if ((ret= db_repository->load_named_event(thd, dbname, name,
new_element)))
- {
- DBUG_ASSERT(ret == OP_LOAD_ERROR);
delete new_element;
- }
else
{
/*
@@ -504,7 +509,6 @@ Events::update_event(THD *thd, Event_parse_data *parse_data,
ret= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
}
}
- mysql_mutex_unlock(&LOCK_event_metadata);
/* Restore the state of binlog format */
DBUG_ASSERT(!thd->is_current_stmt_binlog_format_row());
if (save_binlog_row_based)
@@ -558,7 +562,9 @@ Events::drop_event(THD *thd, LEX_STRING dbname, LEX_STRING name, bool if_exists)
if ((save_binlog_row_based= thd->is_current_stmt_binlog_format_row()))
thd->clear_current_stmt_binlog_format_row();
- mysql_mutex_lock(&LOCK_event_metadata);
+ if (lock_object_name(thd, MDL_key::EVENT,
+ dbname.str, name.str))
+ DBUG_RETURN(TRUE);
/* On error conditions my_error() is called so no need to handle here */
if (!(ret= db_repository->drop_event(thd, dbname, name, if_exists)))
{
@@ -568,7 +574,6 @@ Events::drop_event(THD *thd, LEX_STRING dbname, LEX_STRING name, bool if_exists)
DBUG_ASSERT(thd->query() && thd->query_length());
ret= write_bin_log(thd, TRUE, thd->query(), thd->query_length());
}
- mysql_mutex_unlock(&LOCK_event_metadata);
/* Restore the state of binlog format */
DBUG_ASSERT(!thd->is_current_stmt_binlog_format_row());
if (save_binlog_row_based)
@@ -597,15 +602,12 @@ Events::drop_schema_events(THD *thd, char *db)
DBUG_PRINT("enter", ("dropping events from %s", db));
/*
- sic: no check if the scheduler is disabled or system tables
+ Sic: no check if the scheduler is disabled or system tables
are damaged, as intended.
*/
-
- mysql_mutex_lock(&LOCK_event_metadata);
if (event_queue)
event_queue->drop_schema_events(thd, db_lex);
db_repository->drop_schema_events(thd, db_lex);
- mysql_mutex_unlock(&LOCK_event_metadata);
DBUG_VOID_RETURN;
}
@@ -917,12 +919,11 @@ Events::deinit()
}
#ifdef HAVE_PSI_INTERFACE
-PSI_mutex_key key_LOCK_event_metadata, key_LOCK_event_queue,
+PSI_mutex_key key_LOCK_event_queue,
key_event_scheduler_LOCK_scheduler_state;
static PSI_mutex_info all_events_mutexes[]=
{
- { &key_LOCK_event_metadata, "LOCK_event_metadata", PSI_FLAG_GLOBAL},
{ &key_LOCK_event_queue, "LOCK_event_queue", PSI_FLAG_GLOBAL},
{ &key_event_scheduler_LOCK_scheduler_state, "Event_scheduler::LOCK_scheduler_state", PSI_FLAG_GLOBAL}
};
@@ -976,23 +977,6 @@ Events::init_mutexes()
#ifdef HAVE_PSI_INTERFACE
init_events_psi_keys();
#endif
-
- mysql_mutex_init(key_LOCK_event_metadata,
- &LOCK_event_metadata, MY_MUTEX_INIT_FAST);
-}
-
-
-/*
- Destroys Events mutexes
-
- SYNOPSIS
- Events::destroy_mutexes()
-*/
-
-void
-Events::destroy_mutexes()
-{
- mysql_mutex_destroy(&LOCK_event_metadata);
}
diff --git a/sql/events.h b/sql/events.h
index 4cb93ce8415..a94fbc17135 100644
--- a/sql/events.h
+++ b/sql/events.h
@@ -26,8 +26,7 @@
*/
#ifdef HAVE_PSI_INTERFACE
-extern PSI_mutex_key key_LOCK_event_metadata,
- key_event_scheduler_LOCK_scheduler_state;
+extern PSI_mutex_key key_event_scheduler_LOCK_scheduler_state;
extern PSI_cond_key key_event_scheduler_COND_state;
extern PSI_thread_key key_thread_event_scheduler, key_thread_event_worker;
#endif /* HAVE_PSI_INTERFACE */
@@ -43,19 +42,6 @@ struct TABLE_LIST;
class THD;
typedef class Item COND;
-/* Return codes */
-enum enum_events_error_code
-{
- OP_OK= 0,
- OP_NOT_RUNNING,
- OP_CANT_KILL,
- OP_CANT_INIT,
- OP_DISABLED_EVENT,
- OP_LOAD_ERROR,
- OP_ALREADY_EXISTS
-};
-
-
int
sortcmp_lex_string(LEX_STRING s, LEX_STRING t, CHARSET_INFO *cs);
@@ -91,7 +77,6 @@ public:
enum enum_opt_event_scheduler { EVENTS_OFF, EVENTS_ON, EVENTS_DISABLED };
/* Protected using LOCK_global_system_variables only. */
static ulong opt_event_scheduler;
- static mysql_mutex_t LOCK_event_metadata;
static bool check_if_system_tables_error();
static bool start();
static bool stop();
diff --git a/sql/field.cc b/sql/field.cc
index 26f3e0452c8..e6caaf947b1 100644
--- a/sql/field.cc
+++ b/sql/field.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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 */
-
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@@ -2615,7 +2614,7 @@ bool Field_new_decimal::store_value(const my_decimal *decimal_value)
DBUG_ENTER("Field_new_decimal::store_value");
#ifndef DBUG_OFF
{
- char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
+ char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("enter", ("value: %s", dbug_decimal_as_string(dbug_buff, decimal_value)));
}
#endif
@@ -2630,7 +2629,7 @@ bool Field_new_decimal::store_value(const my_decimal *decimal_value)
}
#ifndef DBUG_OFF
{
- char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
+ char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("info", ("saving with precision %d scale: %d value %s",
(int)precision, (int)dec,
dbug_decimal_as_string(dbug_buff, decimal_value)));
@@ -2699,7 +2698,7 @@ int Field_new_decimal::store(const char *from, uint length,
}
#ifndef DBUG_OFF
- char dbug_buff[DECIMAL_MAX_STR_LENGTH+1];
+ char dbug_buff[DECIMAL_MAX_STR_LENGTH+2];
DBUG_PRINT("enter", ("value: %s",
dbug_decimal_as_string(dbug_buff, &decimal_value)));
#endif
@@ -4196,7 +4195,7 @@ String *Field_float::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
- DBUG_ASSERT(field_length <= MAX_FIELD_CHARLENGTH);
+ DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
float nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
@@ -4519,7 +4518,7 @@ String *Field_double::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
ASSERT_COLUMN_MARKED_FOR_READ;
- DBUG_ASSERT(field_length <= MAX_FIELD_CHARLENGTH);
+ DBUG_ASSERT(!zerofill || field_length <= MAX_FIELD_CHARLENGTH);
double nr;
#ifdef WORDS_BIGENDIAN
if (table->s->db_low_byte_first)
@@ -5389,6 +5388,7 @@ double Field_year::val_real(void)
longlong Field_year::val_int(void)
{
ASSERT_COLUMN_MARKED_FOR_READ;
+ DBUG_ASSERT(field_length == 2 || field_length == 4);
int tmp= (int) ptr[0];
if (field_length != 4)
tmp%=100; // Return last 2 char
@@ -5401,6 +5401,7 @@ longlong Field_year::val_int(void)
String *Field_year::val_str(String *val_buffer,
String *val_ptr __attribute__((unused)))
{
+ DBUG_ASSERT(field_length < 5);
val_buffer->alloc(5);
val_buffer->length(field_length);
char *to=(char*) val_buffer->ptr();
@@ -6334,10 +6335,13 @@ int Field_str::store(double nr)
ASSERT_COLUMN_MARKED_FOR_WRITE_OR_COMPUTED;
char buff[DOUBLE_TO_STRING_CONVERSION_BUFFER_SIZE];
uint local_char_length= field_length / charset()->mbmaxlen;
- size_t length;
- my_bool error;
+ size_t length= 0;
+ my_bool error= (local_char_length == 0);
+
+ // my_gcvt() requires width > 0, and we may have a CHAR(0) column.
+ if (!error)
+ length= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, local_char_length, buff, &error);
- length= my_gcvt(nr, MY_GCVT_ARG_DOUBLE, local_char_length, buff, &error);
if (error)
{
if (table->in_use->abort_on_warning)
@@ -7731,12 +7735,6 @@ void Field_blob::sql_type(String &res) const
uchar *Field_blob::pack(uchar *to, const uchar *from,
uint max_length, bool low_byte_first)
{
- DBUG_ENTER("Field_blob::pack");
- DBUG_PRINT("enter", ("to: 0x%lx; from: 0x%lx;"
- " max_length: %u; low_byte_first: %d",
- (ulong) to, (ulong) from,
- max_length, low_byte_first));
- DBUG_DUMP("record", from, table->s->reclength);
uchar *save= ptr;
ptr= (uchar*) from;
uint32 length=get_length(); // Length of from string
@@ -7757,8 +7755,7 @@ uchar *Field_blob::pack(uchar *to, const uchar *from,
memcpy(to+packlength, from,length);
}
ptr=save; // Restore org row pointer
- DBUG_DUMP("packed", to, packlength + length);
- DBUG_RETURN(to+packlength+length);
+ return to+packlength+length;
}
@@ -8402,6 +8399,54 @@ uint Field_enum::is_equal(Create_field *new_field)
}
+uchar *Field_enum::pack(uchar *to, const uchar *from,
+ uint max_length, bool low_byte_first)
+{
+ DBUG_ENTER("Field_enum::pack");
+ DBUG_PRINT("debug", ("packlength: %d", packlength));
+ DBUG_DUMP("from", from, packlength);
+
+ switch (packlength)
+ {
+ case 1:
+ *to = *from;
+ DBUG_RETURN(to + 1);
+ case 2: DBUG_RETURN(pack_int16(to, from, low_byte_first));
+ case 3: DBUG_RETURN(pack_int24(to, from, low_byte_first));
+ case 4: DBUG_RETURN(pack_int32(to, from, low_byte_first));
+ case 8: DBUG_RETURN(pack_int64(to, from, low_byte_first));
+ default:
+ DBUG_ASSERT(0);
+ }
+ MY_ASSERT_UNREACHABLE();
+ DBUG_RETURN(NULL);
+}
+
+const uchar *Field_enum::unpack(uchar *to, const uchar *from,
+ uint param_data, bool low_byte_first)
+{
+ DBUG_ENTER("Field_enum::unpack");
+ DBUG_PRINT("debug", ("packlength: %d", packlength));
+ DBUG_DUMP("from", from, packlength);
+
+ switch (packlength)
+ {
+ case 1:
+ *to = *from;
+ DBUG_RETURN(from + 1);
+
+ case 2: DBUG_RETURN(unpack_int16(to, from, low_byte_first));
+ case 3: DBUG_RETURN(unpack_int24(to, from, low_byte_first));
+ case 4: DBUG_RETURN(unpack_int32(to, from, low_byte_first));
+ case 8: DBUG_RETURN(unpack_int64(to, from, low_byte_first));
+ default:
+ DBUG_ASSERT(0);
+ }
+ MY_ASSERT_UNREACHABLE();
+ DBUG_RETURN(NULL);
+}
+
+
/**
@return
returns 1 if the fields are equally defined
@@ -9037,6 +9082,7 @@ void Create_field::create_length_to_internal_length(void)
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
+ case MYSQL_TYPE_GEOMETRY:
case MYSQL_TYPE_VAR_STRING:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VARCHAR:
@@ -9236,7 +9282,7 @@ bool Create_field::init(THD *thd, char *fld_name, enum_field_types fld_type,
if (decimals >= NOT_FIXED_DEC)
{
my_error(ER_TOO_BIG_SCALE, MYF(0), decimals, fld_name,
- NOT_FIXED_DEC-1);
+ static_cast<ulong>(NOT_FIXED_DEC - 1));
DBUG_RETURN(TRUE);
}
@@ -9333,8 +9379,8 @@ bool Create_field::init(THD *thd, char *fld_name, enum_field_types fld_type,
my_decimal_trim(&length, &decimals);
if (length > DECIMAL_MAX_PRECISION)
{
- my_error(ER_TOO_BIG_PRECISION, MYF(0), length, fld_name,
- DECIMAL_MAX_PRECISION);
+ my_error(ER_TOO_BIG_PRECISION, MYF(0), static_cast<int>(length),
+ fld_name, static_cast<ulong>(DECIMAL_MAX_PRECISION));
DBUG_RETURN(TRUE);
}
if (length < decimals)
@@ -9558,7 +9604,7 @@ bool Create_field::init(THD *thd, char *fld_name, enum_field_types fld_type,
if (length > MAX_BIT_FIELD_LENGTH)
{
my_error(ER_TOO_BIG_DISPLAYWIDTH, MYF(0), fld_name,
- MAX_BIT_FIELD_LENGTH);
+ static_cast<ulong>(MAX_BIT_FIELD_LENGTH));
DBUG_RETURN(TRUE);
}
pack_length= (length + 7) / 8;
diff --git a/sql/field.h b/sql/field.h
index a7718df604a..0282deb9a3d 100644
--- a/sql/field.h
+++ b/sql/field.h
@@ -635,6 +635,48 @@ private:
{ return 0; }
protected:
+ static void handle_int16(uchar *to, const uchar *from,
+ bool low_byte_first_from, bool low_byte_first_to)
+ {
+ int16 val;
+#ifdef WORDS_BIGENDIAN
+ if (low_byte_first_from)
+ val = sint2korr(from);
+ else
+#endif
+ shortget(val, from);
+
+#ifdef WORDS_BIGENDIAN
+ if (low_byte_first_to)
+ int2store(to, val);
+ else
+#endif
+ shortstore(to, val);
+ }
+
+ static void handle_int24(uchar *to, const uchar *from,
+ bool low_byte_first_from, bool low_byte_first_to)
+ {
+ int32 val;
+#ifdef WORDS_BIGENDIAN
+ if (low_byte_first_from)
+ val = sint3korr(from);
+ else
+#endif
+ val= (from[0] << 16) + (from[1] << 8) + from[2];
+
+#ifdef WORDS_BIGENDIAN
+ if (low_byte_first_to)
+ int2store(to, val);
+ else
+#endif
+ {
+ to[0]= 0xFF & (val >> 16);
+ to[1]= 0xFF & (val >> 8);
+ to[2]= 0xFF & val;
+ }
+ }
+
/*
Helper function to pack()/unpack() int32 values
*/
@@ -679,6 +721,32 @@ protected:
longlongstore(to, val);
}
+ uchar *pack_int16(uchar *to, const uchar *from, bool low_byte_first_to)
+ {
+ handle_int16(to, from, table->s->db_low_byte_first, low_byte_first_to);
+ return to + sizeof(int16);
+ }
+
+ const uchar *unpack_int16(uchar* to, const uchar *from,
+ bool low_byte_first_from)
+ {
+ handle_int16(to, from, low_byte_first_from, table->s->db_low_byte_first);
+ return from + sizeof(int16);
+ }
+
+ uchar *pack_int24(uchar *to, const uchar *from, bool low_byte_first_to)
+ {
+ handle_int24(to, from, table->s->db_low_byte_first, low_byte_first_to);
+ return to + 3;
+ }
+
+ const uchar *unpack_int24(uchar* to, const uchar *from,
+ bool low_byte_first_from)
+ {
+ handle_int24(to, from, low_byte_first_from, table->s->db_low_byte_first);
+ return from + 3;
+ }
+
uchar *pack_int32(uchar *to, const uchar *from, bool low_byte_first_to)
{
handle_int32(to, from, table->s->db_low_byte_first, low_byte_first_to);
@@ -759,6 +827,17 @@ public:
uchar null_bit_arg, utype unireg_check_arg,
const char *field_name_arg, CHARSET_INFO *charset);
Item_result result_type () const { return STRING_RESULT; }
+ /*
+ match_collation_to_optimize_range() is to distinguish in
+ range optimizer (see opt_range.cc) between real string types:
+ CHAR, VARCHAR, TEXT
+ and the other string-alike types with result_type() == STRING_RESULT:
+ DATE, TIME, DATETIME, TIMESTAMP
+ We need it to decide whether to test if collation of the operation
+ matches collation of the field (needed only for real string types).
+ QQ: shouldn't DATE/TIME types have their own XXX_RESULT types eventually?
+ */
+ virtual bool match_collation_to_optimize_range() const=0;
uint decimals() const { return NOT_FIXED_DEC; }
int store(double nr);
int store(longlong nr, bool unsigned_val)=0;
@@ -999,41 +1078,13 @@ public:
virtual uchar *pack(uchar* to, const uchar *from,
uint max_length, bool low_byte_first)
{
- int16 val;
-#ifdef WORDS_BIGENDIAN
- if (table->s->db_low_byte_first)
- val = sint2korr(from);
- else
-#endif
- shortget(val, from);
-
-#ifdef WORDS_BIGENDIAN
- if (low_byte_first)
- int2store(to, val);
- else
-#endif
- shortstore(to, val);
- return to + sizeof(val);
+ return pack_int16(to, from, low_byte_first);
}
virtual const uchar *unpack(uchar* to, const uchar *from,
uint param_data, bool low_byte_first)
{
- int16 val;
-#ifdef WORDS_BIGENDIAN
- if (low_byte_first)
- val = sint2korr(from);
- else
-#endif
- shortget(val, from);
-
-#ifdef WORDS_BIGENDIAN
- if (table->s->db_low_byte_first)
- int2store(to, val);
- else
-#endif
- shortstore(to, val);
- return from + sizeof(val);
+ return unpack_int16(to, from, low_byte_first);
}
};
@@ -1268,6 +1319,7 @@ public:
unireg_check_arg, field_name_arg, cs)
{}
enum_field_types type() const { return MYSQL_TYPE_NULL;}
+ bool match_collation_to_optimize_range() const { return FALSE; }
int store(const char *to, uint length, CHARSET_INFO *cs)
{ null[0]=1; return 0; }
int store(double nr) { null[0]=1; return 0; }
@@ -1297,6 +1349,7 @@ public:
Field_timestamp(bool maybe_null_arg, const char *field_name_arg,
CHARSET_INFO *cs);
enum_field_types type() const { return MYSQL_TYPE_TIMESTAMP;}
+ bool match_collation_to_optimize_range() const { return FALSE; }
enum ha_base_keytype key_type() const { return HA_KEYTYPE_ULONG_INT; }
enum Item_result cmp_type () const { return INT_RESULT; }
enum Derivation derivation(void) const { return DERIVATION_NUMERIC; }
@@ -1401,6 +1454,7 @@ public:
:Field_str((uchar*) 0, MAX_DATE_WIDTH, maybe_null_arg ? (uchar*) "": 0,0,
NONE, field_name_arg, cs) { flags|= BINARY_FLAG; }
enum_field_types type() const { return MYSQL_TYPE_DATE;}
+ bool match_collation_to_optimize_range() const { return FALSE; }
enum ha_base_keytype key_type() const { return HA_KEYTYPE_ULONG_INT; }
enum Item_result cmp_type () const { return INT_RESULT; }
enum Derivation derivation(void) const { return DERIVATION_NUMERIC; }
@@ -1450,6 +1504,7 @@ public:
NONE, field_name_arg, cs) { flags|= BINARY_FLAG; }
enum_field_types type() const { return MYSQL_TYPE_DATE;}
enum_field_types real_type() const { return MYSQL_TYPE_NEWDATE; }
+ bool match_collation_to_optimize_range() const { return FALSE; }
enum ha_base_keytype key_type() const { return HA_KEYTYPE_UINT24; }
enum Item_result cmp_type () const { return INT_RESULT; }
enum Derivation derivation(void) const { return DERIVATION_NUMERIC; }
@@ -1489,6 +1544,7 @@ public:
:Field_str((uchar*) 0,8, maybe_null_arg ? (uchar*) "": 0,0,
NONE, field_name_arg, cs) { flags|= BINARY_FLAG; }
enum_field_types type() const { return MYSQL_TYPE_TIME;}
+ bool match_collation_to_optimize_range() const { return FALSE; }
enum ha_base_keytype key_type() const { return HA_KEYTYPE_INT24; }
enum Item_result cmp_type () const { return INT_RESULT; }
enum Derivation derivation(void) const { return DERIVATION_NUMERIC; }
@@ -1528,6 +1584,7 @@ public:
:Field_str((uchar*) 0, MAX_DATETIME_WIDTH, maybe_null_arg ? (uchar*) "": 0,0,
NONE, field_name_arg, cs) { flags|= BINARY_FLAG; }
enum_field_types type() const { return MYSQL_TYPE_DATETIME;}
+ bool match_collation_to_optimize_range() const { return FALSE; }
#ifdef HAVE_LONG_LONG
enum ha_base_keytype key_type() const { return HA_KEYTYPE_ULONGLONG; }
#endif
@@ -1596,6 +1653,7 @@ public:
orig_table->s->frm_version < FRM_VER_TRUE_VARCHAR ?
MYSQL_TYPE_VAR_STRING : MYSQL_TYPE_STRING);
}
+ bool match_collation_to_optimize_range() const { return TRUE; }
enum ha_base_keytype key_type() const
{ return binary() ? HA_KEYTYPE_BINARY : HA_KEYTYPE_TEXT; }
bool zero_pack() const { return 0; }
@@ -1676,6 +1734,7 @@ public:
}
enum_field_types type() const { return MYSQL_TYPE_VARCHAR; }
+ bool match_collation_to_optimize_range() const { return TRUE; }
enum ha_base_keytype key_type() const;
uint row_pack_length() { return field_length; }
bool zero_pack() const { return 0; }
@@ -1771,6 +1830,7 @@ public:
:Field_longstr((uchar*) 0, 0, (uchar*) "", 0, NONE, "temp", system_charset_info),
packlength(packlength_arg) {}
enum_field_types type() const { return MYSQL_TYPE_BLOB;}
+ bool match_collation_to_optimize_range() const { return TRUE; }
enum ha_base_keytype key_type() const
{ return binary() ? HA_KEYTYPE_VARBINARY2 : HA_KEYTYPE_VARTEXT2; }
int store(const char *to,uint length,CHARSET_INFO *charset);
@@ -1920,6 +1980,7 @@ public:
{ geom_type= geom_type_arg; }
enum ha_base_keytype key_type() const { return HA_KEYTYPE_VARBINARY2; }
enum_field_types type() const { return MYSQL_TYPE_GEOMETRY; }
+ bool match_collation_to_optimize_range() const { return FALSE; }
void sql_type(String &str) const;
int store(const char *to, uint length, CHARSET_INFO *charset);
int store(double nr);
@@ -1951,6 +2012,7 @@ public:
}
Field *new_field(MEM_ROOT *root, TABLE *new_table, bool keep_type);
enum_field_types type() const { return MYSQL_TYPE_STRING; }
+ bool match_collation_to_optimize_range() const { return FALSE; }
enum Item_result cmp_type () const { return INT_RESULT; }
enum Item_result cast_to_int_type () const { return INT_RESULT; }
enum ha_base_keytype key_type() const;
@@ -1976,6 +2038,12 @@ public:
bool has_charset(void) const { return TRUE; }
/* enum and set are sorted as integers */
CHARSET_INFO *sort_charset(void) const { return &my_charset_bin; }
+
+ virtual uchar *pack(uchar *to, const uchar *from,
+ uint max_length, bool low_byte_first);
+ virtual const uchar *unpack(uchar *to, const uchar *from,
+ uint param_data, bool low_byte_first);
+
private:
int do_save_field_metadata(uchar *first_byte);
uint is_equal(Create_field *new_field);
diff --git a/sql/field_conv.cc b/sql/field_conv.cc
index a27b471442b..2f6d84c999b 100644
--- a/sql/field_conv.cc
+++ b/sql/field_conv.cc
@@ -784,11 +784,8 @@ int field_conv(Field *to,Field *from)
((Field_varstring*)from)->length_bytes ==
((Field_varstring*)to)->length_bytes))
{ // Identical fields
-#ifdef HAVE_valgrind
- /* This may happen if one does 'UPDATE ... SET x=x' */
- if (to->ptr != from->ptr)
-#endif
- memcpy(to->ptr,from->ptr,to->pack_length());
+ // to->ptr==from->ptr may happen if one does 'UPDATE ... SET x=x'
+ memmove(to->ptr, from->ptr, to->pack_length());
return 0;
}
}
diff --git a/sql/filesort.cc b/sql/filesort.cc
index 69df42da95f..a70f6cbd2ed 100644
--- a/sql/filesort.cc
+++ b/sql/filesort.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -33,11 +33,7 @@
#include "sql_test.h" // TEST_filesort
#include "opt_range.h" // SQL_SELECT
#include "log_slow.h"
-#include "sql_base.h"
-
-#ifndef THREAD
-#define SKIP_DBUG_IN_FILESORT
-#endif
+#include "debug_sync.h"
/// How to write record_ref.
#define WRITE_REF(file,from) \
@@ -129,6 +125,7 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length,
Item_subselect *subselect= tab ? tab->containing_subselect() : 0;
MYSQL_FILESORT_START(table->s->db.str, table->s->table_name.str);
+ DEBUG_SYNC(thd, "filesort_start");
/*
Release InnoDB's adaptive hash index latch (if holding) before
@@ -332,8 +329,25 @@ ha_rows filesort(THD *thd, TABLE *table, SORT_FIELD *sortorder, uint s_length,
}
}
if (error)
- my_message(ER_FILSORT_ABORT, ER(ER_FILSORT_ABORT),
- MYF(ME_ERROR+ME_WAITTANG));
+ {
+ int kill_errno= thd->killed_errno();
+ DBUG_ASSERT(thd->is_error() || kill_errno);
+ my_printf_error(ER_FILSORT_ABORT,
+ "%s: %s",
+ MYF(ME_ERROR + ME_WAITTANG),
+ ER_THD(thd, ER_FILSORT_ABORT),
+ kill_errno ? ER(kill_errno) : thd->stmt_da->message());
+
+ if (global_system_variables.log_warnings > 1)
+ {
+ sql_print_warning("%s, host: %s, user: %s, thread: %lu, query: %-.4096s",
+ ER_THD(thd, ER_FILSORT_ABORT),
+ thd->security_ctx->host_or_ip,
+ &thd->security_ctx->priv_user[0],
+ (ulong) thd->thread_id,
+ thd->query());
+ }
+ }
else
statistic_add(thd->status_var.filesort_rows,
(ulong) records, &LOCK_status);
@@ -377,6 +391,9 @@ static char **make_char_array(char **old_pos, register uint fields,
char *char_pos;
DBUG_ENTER("make_char_array");
+ DBUG_EXECUTE_IF("make_char_array_fail",
+ DBUG_SET("+d,simulate_out_of_memory"););
+
if (old_pos ||
(old_pos= (char**) my_malloc((uint) fields*(length+sizeof(char*)),
my_flag)))
diff --git a/sql/gen_lex_hash.cc b/sql/gen_lex_hash.cc
index a9c03f7e2a7..d442d029ba0 100644
--- a/sql/gen_lex_hash.cc
+++ b/sql/gen_lex_hash.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB
+/* Copyright (C) 2000-2007 MySQL AB, 2009 Sun Microsystems, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
@@ -375,7 +375,7 @@ int main(int argc,char **argv)
printf("/*\n\n Do " "not " "edit " "this " "file " "directly!\n\n*/\n");
printf("\
-/* Copyright 2001-2008 MySQL AB, 2008 Sun Microsystems, Inc.\n\
+/* Copyright (C) 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.\n\
\n\
This program is free software; you can redistribute it and/or modify\n\
it under the terms of the GNU General Public License as published by\n\
diff --git a/sql/ha_ndbcluster.cc b/sql/ha_ndbcluster.cc
index e90c3ac3e6a..773b6155c68 100644
--- a/sql/ha_ndbcluster.cc
+++ b/sql/ha_ndbcluster.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2003 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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
-*/
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@@ -6436,9 +6435,8 @@ void ha_ndbcluster::get_auto_increment(ulonglong offset, ulonglong increment,
{
Ndb_tuple_id_range_guard g(m_share);
if ((m_skip_auto_increment &&
- ndb->readAutoIncrementValue(m_table, g.range, auto_value)) ||
- ndb->getAutoIncrementValue(m_table, g.range, auto_value, cache_size,
- increment, offset))
+ ndb->readAutoIncrementValue(m_table, g.range, auto_value)) ||
+ ndb->getAutoIncrementValue(m_table, g.range, auto_value, cache_size, increment, offset))
{
if (--retries &&
ndb->getNdbError().status == NdbError::TemporaryError)
@@ -7383,38 +7381,35 @@ int ndbcluster_find_files(handlerton *hton, THD *thd,
}
/*
+ Delete old files.
+
ndbcluster_find_files() may be called from I_S code and ndbcluster_binlog
thread in situations when some tables are already open. This means that
code below will try to obtain exclusive metadata lock on some table
- while holding shared meta-data lock on other tables. This might lead to
- a deadlock, and therefore is disallowed by assertions of the metadata
- locking subsystem. This is violation of metadata
- locking protocol which has to be closed ASAP.
+ while holding shared meta-data lock on other tables. This might lead to a
+ deadlock but such a deadlock should be detected by MDL deadlock detector.
+
XXX: the scenario described above is not covered with any test.
*/
- if (!global_read_lock)
- {
- // Delete old files
- List_iterator_fast<char> it3(delete_list);
- while ((file_name_str= it3++))
- {
- DBUG_PRINT("info", ("Remove table %s/%s", db, file_name_str));
- // Delete the table and all related files
- TABLE_LIST table_list;
- table_list.init_one_table(db, strlen(db), file_name_str,
- strlen(file_name_str), file_name_str,
- TL_WRITE);
- table_list.mdl_request.set_type(MDL_EXCLUSIVE);
- (void)mysql_rm_table_part2(thd, &table_list,
- FALSE, /* if_exists */
- FALSE, /* drop_temporary */
- FALSE, /* drop_view */
- TRUE /* dont_log_query*/);
- trans_commit_implicit(thd); /* Safety, should be unnecessary. */
- thd->mdl_context.release_transactional_locks();
- /* Clear error message that is returned when table is deleted */
- thd->clear_error();
- }
+ List_iterator_fast<char> it3(delete_list);
+ while ((file_name_str= it3++))
+ {
+ DBUG_PRINT("info", ("Remove table %s/%s", db, file_name_str));
+ /* Delete the table and all related files. */
+ TABLE_LIST table_list;
+ table_list.init_one_table(db, strlen(db), file_name_str,
+ strlen(file_name_str), file_name_str,
+ TL_WRITE);
+ table_list.mdl_request.set_type(MDL_EXCLUSIVE);
+ (void)mysql_rm_table_part2(thd, &table_list,
+ FALSE, /* if_exists */
+ FALSE, /* drop_temporary */
+ FALSE, /* drop_view */
+ TRUE /* dont_log_query*/);
+ trans_commit_implicit(thd); /* Safety, should be unnecessary. */
+ thd->mdl_context.release_transactional_locks();
+ /* Clear error message that is returned when table is deleted */
+ thd->clear_error();
}
/* Lock mutex before creating .FRM files. */
@@ -8703,7 +8698,7 @@ NDB_SHARE *ndbcluster_get_share(const char *key, TABLE *table,
DBUG_PRINT("error", ("get_share: failed to alloc share"));
if (!have_lock)
mysql_mutex_unlock(&ndbcluster_mutex);
- my_error(ER_OUTOFMEMORY, MYF(0), sizeof(*share));
+ my_error(ER_OUTOFMEMORY, MYF(0), static_cast<int>(sizeof(*share)));
DBUG_RETURN(0);
}
}
@@ -10275,10 +10270,8 @@ bool ha_ndbcluster::check_if_incompatible_data(HA_CREATE_INFO *create_info,
{
Field *field= table->field[i];
const NDBCOL *col= tab->getColumn(i);
- if ((col->getStorageType() == NDB_STORAGETYPE_MEMORY &&
- create_info->storage_media != HA_SM_MEMORY) ||
- (col->getStorageType() == NDB_STORAGETYPE_DISK &&
- create_info->storage_media != HA_SM_DISK))
+ if ((col->getStorageType() == NDB_STORAGETYPE_MEMORY && create_info->storage_media != HA_SM_MEMORY) ||
+ (col->getStorageType() == NDB_STORAGETYPE_DISK && create_info->storage_media != HA_SM_DISK))
{
DBUG_PRINT("info", ("Column storage media is changed"));
DBUG_RETURN(COMPATIBLE_DATA_NO);
diff --git a/sql/ha_ndbcluster_binlog.cc b/sql/ha_ndbcluster_binlog.cc
index e46b6b25f9c..c4b71bf32cf 100644
--- a/sql/ha_ndbcluster_binlog.cc
+++ b/sql/ha_ndbcluster_binlog.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2003 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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
-*/
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql_priv.h"
#include "unireg.h" // REQUIRED: for other includes
@@ -1225,12 +1224,14 @@ ndbcluster_update_slock(THD *thd,
}
if (ndb_error)
+ {
+ char buf[1024];
+ my_snprintf(buf, sizeof(buf), "Could not release lock on '%s.%s'",
+ db, table_name);
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_GET_ERRMSG, ER(ER_GET_ERRMSG),
- ndb_error->code,
- ndb_error->message,
- "Could not release lock on '%s.%s'",
- db, table_name);
+ ndb_error->code, ndb_error->message, buf);
+ }
if (trans)
ndb->closeTransaction(trans);
ndb->setDatabaseName(save_db);
diff --git a/sql/ha_ndbcluster_cond.cc b/sql/ha_ndbcluster_cond.cc
index 8a96ae41453..9ab7fb6208d 100644
--- a/sql/ha_ndbcluster_cond.cc
+++ b/sql/ha_ndbcluster_cond.cc
@@ -1472,4 +1472,4 @@ int ha_ndbcluster_cond::generate_scan_filter_from_key(NdbScanOperation *op,
DBUG_RETURN(0);
}
-#endif /* HAVE_NDBCLUSTER_DB */
+#endif
diff --git a/sql/ha_partition.cc b/sql/ha_partition.cc
index b0f50c0ca58..b35a6cb7bf3 100644
--- a/sql/ha_partition.cc
+++ b/sql/ha_partition.cc
@@ -1,4 +1,4 @@
-/* Copyright 2005-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,7 +11,7 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/*
This handler was developed by Mikael Ronstrom for version 5.1 of MySQL.
@@ -163,8 +163,7 @@ const uint ha_partition::NO_CURRENT_PART_ID= 0xFFFFFFFF;
*/
ha_partition::ha_partition(handlerton *hton, TABLE_SHARE *share)
- :handler(hton, share), m_part_info(NULL), m_create_handler(FALSE),
- m_is_sub_partitioned(0)
+ :handler(hton, share)
{
DBUG_ENTER("ha_partition::ha_partition(table)");
init_handler_variables();
@@ -184,15 +183,44 @@ ha_partition::ha_partition(handlerton *hton, TABLE_SHARE *share)
*/
ha_partition::ha_partition(handlerton *hton, partition_info *part_info)
- :handler(hton, NULL), m_part_info(part_info), m_create_handler(TRUE),
- m_is_sub_partitioned(m_part_info->is_sub_partitioned())
+ :handler(hton, NULL)
{
DBUG_ENTER("ha_partition::ha_partition(part_info)");
+ DBUG_ASSERT(part_info);
init_handler_variables();
- DBUG_ASSERT(m_part_info);
+ m_part_info= part_info;
+ m_create_handler= TRUE;
+ m_is_sub_partitioned= m_part_info->is_sub_partitioned();
DBUG_VOID_RETURN;
}
+/**
+ ha_partition constructor method used by ha_partition::clone()
+
+ @param hton Handlerton (partition_hton)
+ @param share Table share object
+ @param part_info_arg partition_info to use
+ @param clone_arg ha_partition to clone
+ @param clme_mem_root_arg MEM_ROOT to use
+
+ @return New partition handler
+*/
+
+ha_partition::ha_partition(handlerton *hton, TABLE_SHARE *share,
+ partition_info *part_info_arg,
+ ha_partition *clone_arg,
+ MEM_ROOT *clone_mem_root_arg)
+ :handler(hton, share)
+{
+ DBUG_ENTER("ha_partition::ha_partition(clone)");
+ init_handler_variables();
+ m_part_info= part_info_arg;
+ m_create_handler= TRUE;
+ m_is_sub_partitioned= m_part_info->is_sub_partitioned();
+ m_is_clone_of= clone_arg;
+ m_clone_mem_root= clone_mem_root_arg;
+ DBUG_VOID_RETURN;
+}
/*
Initialize handler object
@@ -244,7 +272,6 @@ void ha_partition::init_handler_variables()
m_rec0= 0;
m_curr_key_info[0]= NULL;
m_curr_key_info[1]= NULL;
- is_clone= FALSE,
m_part_func_monotonicity_info= NON_MONOTONIC;
auto_increment_lock= FALSE;
auto_increment_safe_stmt_log_lock= FALSE;
@@ -252,6 +279,11 @@ void ha_partition::init_handler_variables()
this allows blackhole to work properly
*/
m_num_locks= 0;
+ m_part_info= NULL;
+ m_create_handler= FALSE;
+ m_is_sub_partitioned= 0;
+ m_is_clone_of= NULL;
+ m_clone_mem_root= NULL;
#ifdef DONT_HAVE_TO_BE_INITALIZED
m_start_key.flag= 0;
@@ -359,7 +391,8 @@ bool ha_partition::initialize_partition(MEM_ROOT *mem_root)
*/
DBUG_RETURN(0);
}
- else if (get_from_handler_file(table_share->normalized_path.str, mem_root))
+ else if (get_from_handler_file(table_share->normalized_path.str,
+ mem_root, false))
{
my_error(ER_FAILED_READ_FROM_PAR_FILE, MYF(0));
DBUG_RETURN(1);
@@ -1037,6 +1070,10 @@ static int handle_opt_part(THD *thd, HA_CHECK_OPT *check_opt,
static bool print_admin_msg(THD* thd, const char* msg_type,
const char* db_name, const char* table_name,
const char* op_name, const char *fmt, ...)
+ ATTRIBUTE_FORMAT(printf, 6, 7);
+static bool print_admin_msg(THD* thd, const char* msg_type,
+ const char* db_name, const char* table_name,
+ const char* op_name, const char *fmt, ...)
{
va_list args;
Protocol *protocol= thd->protocol;
@@ -1891,7 +1928,7 @@ uint ha_partition::del_ren_cre_table(const char *from,
DBUG_RETURN(TRUE);
}
- if (get_from_handler_file(from, ha_thd()->mem_root))
+ if (get_from_handler_file(from, ha_thd()->mem_root, false))
DBUG_RETURN(TRUE);
DBUG_ASSERT(m_file_buffer);
DBUG_PRINT("enter", ("from: (%s) to: (%s)", from, to ? to : "(nil)"));
@@ -2108,18 +2145,16 @@ static uint name_add(char *dest, const char *first_name, const char *sec_name)
}
-/*
+/**
Create the special .par file
- SYNOPSIS
- create_handler_file()
- name Full path of table name
+ @param name Full path of table name
- RETURN VALUE
- >0 Error code
- 0 Success
+ @return Operation status
+ @retval FALSE Error code
+ @retval TRUE Success
- DESCRIPTION
+ @note
Method used to create handler file with names of partitions, their
engine types and the number of partitions.
*/
@@ -2183,19 +2218,22 @@ bool ha_partition::create_handler_file(const char *name)
Array of engine types n * 4 bytes where
n = (m_tot_parts + 3)/4
Length of name part in bytes 4 bytes
+ (Names in filename format)
Name part m * 4 bytes where
m = ((length_name_part + 3)/4)*4
All padding bytes are zeroed
*/
- tot_partition_words= (tot_parts + 3) / 4;
- tot_name_words= (tot_name_len + 3) / 4;
+ tot_partition_words= (tot_parts + PAR_WORD_SIZE - 1) / PAR_WORD_SIZE;
+ tot_name_words= (tot_name_len + PAR_WORD_SIZE - 1) / PAR_WORD_SIZE;
+ /* 4 static words (tot words, checksum, tot partitions, name length) */
tot_len_words= 4 + tot_partition_words + tot_name_words;
- tot_len_byte= 4 * tot_len_words;
+ tot_len_byte= PAR_WORD_SIZE * tot_len_words;
if (!(file_buffer= (uchar *) my_malloc(tot_len_byte, MYF(MY_ZEROFILL))))
DBUG_RETURN(TRUE);
- engine_array= (file_buffer + 12);
- name_buffer_ptr= (char*) (file_buffer + ((4 + tot_partition_words) * 4));
+ engine_array= (file_buffer + PAR_ENGINES_OFFSET);
+ name_buffer_ptr= (char*) (engine_array + tot_partition_words * PAR_WORD_SIZE
+ + PAR_WORD_SIZE);
part_it.rewind();
for (i= 0; i < num_parts; i++)
{
@@ -2233,13 +2271,15 @@ bool ha_partition::create_handler_file(const char *name)
}
chksum= 0;
int4store(file_buffer, tot_len_words);
- int4store(file_buffer + 8, tot_parts);
- int4store(file_buffer + 12 + (tot_partition_words * 4), tot_name_len);
+ int4store(file_buffer + PAR_NUM_PARTS_OFFSET, tot_parts);
+ int4store(file_buffer + PAR_ENGINES_OFFSET +
+ (tot_partition_words * PAR_WORD_SIZE),
+ tot_name_len);
for (i= 0; i < tot_len_words; i++)
- chksum^= uint4korr(file_buffer + 4 * i);
- int4store(file_buffer + 4, chksum);
+ chksum^= uint4korr(file_buffer + PAR_WORD_SIZE * i);
+ int4store(file_buffer + PAR_CHECKSUM_OFFSET, chksum);
/*
- Remove .frm extension and replace with .par
+ Add .par extension to the file name.
Create and write and close file
to be used at open, delete_table and rename_table
*/
@@ -2258,14 +2298,9 @@ bool ha_partition::create_handler_file(const char *name)
DBUG_RETURN(result);
}
-/*
- Clear handler variables and free some memory
-
- SYNOPSIS
- clear_handler_file()
- RETURN VALUE
- NONE
+/**
+ Clear handler variables and free some memory
*/
void ha_partition::clear_handler_file()
@@ -2278,16 +2313,15 @@ void ha_partition::clear_handler_file()
m_engine_array= NULL;
}
-/*
+
+/**
Create underlying handler objects
- SYNOPSIS
- create_handlers()
- mem_root Allocate memory through this
+ @param mem_root Allocate memory through this
- RETURN VALUE
- TRUE Error
- FALSE Success
+ @return Operation status
+ @retval TRUE Error
+ @retval FALSE Success
*/
bool ha_partition::create_handlers(MEM_ROOT *mem_root)
@@ -2325,6 +2359,7 @@ bool ha_partition::create_handlers(MEM_ROOT *mem_root)
DBUG_RETURN(FALSE);
}
+
/*
Create underlying handler objects from partition info
@@ -2396,101 +2431,165 @@ error_end:
}
-/*
- Get info about partition engines and their names from the .par file
+/**
+ Read the .par file to get the partitions engines and names
- SYNOPSIS
- get_from_handler_file()
- name Full path of table name
- mem_root Allocate memory through this
+ @param name Name of table file (without extention)
- RETURN VALUE
- TRUE Error
- FALSE Success
+ @return Operation status
+ @retval true Failure
+ @retval false Success
- DESCRIPTION
- Open handler file to get partition names, engine types and number of
- partitions.
+ @note On success, m_file_buffer is allocated and must be
+ freed by the caller. m_name_buffer_ptr and m_tot_parts is also set.
*/
-bool ha_partition::get_from_handler_file(const char *name, MEM_ROOT *mem_root)
+bool ha_partition::read_par_file(const char *name)
{
- char buff[FN_REFLEN], *address_tot_name_len;
+ char buff[FN_REFLEN], *tot_name_len_offset;
File file;
- char *file_buffer, *name_buffer_ptr;
- handlerton **engine_array;
+ char *file_buffer;
uint i, len_bytes, len_words, tot_partition_words, tot_name_words, chksum;
- DBUG_ENTER("ha_partition::get_from_handler_file");
+ DBUG_ENTER("ha_partition::read_par_file");
DBUG_PRINT("enter", ("table name: '%s'", name));
if (m_file_buffer)
- DBUG_RETURN(FALSE);
+ DBUG_RETURN(false);
fn_format(buff, name, "", ha_par_ext, MY_APPEND_EXT);
/* Following could be done with mysql_file_stat to read in whole file */
if ((file= mysql_file_open(key_file_partition,
buff, O_RDONLY | O_SHARE, MYF(0))) < 0)
DBUG_RETURN(TRUE);
- if (mysql_file_read(file, (uchar *) &buff[0], 8, MYF(MY_NABP)))
+ if (mysql_file_read(file, (uchar *) &buff[0], PAR_WORD_SIZE, MYF(MY_NABP)))
goto err1;
len_words= uint4korr(buff);
- len_bytes= 4 * len_words;
+ len_bytes= PAR_WORD_SIZE * len_words;
+ if (mysql_file_seek(file, 0, MY_SEEK_SET, MYF(0)) == MY_FILEPOS_ERROR)
+ goto err1;
if (!(file_buffer= (char*) my_malloc(len_bytes, MYF(0))))
goto err1;
- mysql_file_seek(file, 0, MY_SEEK_SET, MYF(0));
if (mysql_file_read(file, (uchar *) file_buffer, len_bytes, MYF(MY_NABP)))
goto err2;
chksum= 0;
for (i= 0; i < len_words; i++)
- chksum ^= uint4korr((file_buffer) + 4 * i);
+ chksum ^= uint4korr((file_buffer) + PAR_WORD_SIZE * i);
if (chksum)
goto err2;
- m_tot_parts= uint4korr((file_buffer) + 8);
+ m_tot_parts= uint4korr((file_buffer) + PAR_NUM_PARTS_OFFSET);
DBUG_PRINT("info", ("No of parts = %u", m_tot_parts));
- tot_partition_words= (m_tot_parts + 3) / 4;
+ tot_partition_words= (m_tot_parts + PAR_WORD_SIZE - 1) / PAR_WORD_SIZE;
+
+ tot_name_len_offset= file_buffer + PAR_ENGINES_OFFSET +
+ PAR_WORD_SIZE * tot_partition_words;
+ tot_name_words= (uint4korr(tot_name_len_offset) + PAR_WORD_SIZE - 1) /
+ PAR_WORD_SIZE;
+ /*
+ Verify the total length = tot size word, checksum word, num parts word +
+ engines array + name length word + name array.
+ */
+ if (len_words != (tot_partition_words + tot_name_words + 4))
+ goto err2;
+ (void) mysql_file_close(file, MYF(0));
+ m_file_buffer= file_buffer; // Will be freed in clear_handler_file()
+ m_name_buffer_ptr= tot_name_len_offset + PAR_WORD_SIZE;
+
+ DBUG_RETURN(false);
+
+err2:
+ my_free(file_buffer);
+err1:
+ (void) mysql_file_close(file, MYF(0));
+ DBUG_RETURN(true);
+}
+
+
+/**
+ Setup m_engine_array
+
+ @param mem_root MEM_ROOT to use for allocating new handlers
+
+ @return Operation status
+ @retval false Success
+ @retval true Failure
+*/
+
+bool ha_partition::setup_engine_array(MEM_ROOT *mem_root)
+{
+ uint i;
+ uchar *buff;
+ handlerton **engine_array;
+
+ DBUG_ASSERT(!m_file);
+ DBUG_ENTER("ha_partition::setup_engine_array");
engine_array= (handlerton **) my_alloca(m_tot_parts * sizeof(handlerton*));
+ if (!engine_array)
+ DBUG_RETURN(true);
+
+ buff= (uchar *) (m_file_buffer + PAR_ENGINES_OFFSET);
for (i= 0; i < m_tot_parts; i++)
{
engine_array[i]= ha_resolve_by_legacy_type(ha_thd(),
(enum legacy_db_type)
- *(uchar *) ((file_buffer) +
- 12 + i));
+ *(buff + i));
if (!engine_array[i])
- goto err3;
+ goto err;
}
- address_tot_name_len= file_buffer + 12 + 4 * tot_partition_words;
- tot_name_words= (uint4korr(address_tot_name_len) + 3) / 4;
- if (len_words != (tot_partition_words + tot_name_words + 4))
- goto err3;
- name_buffer_ptr= file_buffer + 16 + 4 * tot_partition_words;
- (void) mysql_file_close(file, MYF(0));
- m_file_buffer= file_buffer; // Will be freed in clear_handler_file()
- m_name_buffer_ptr= name_buffer_ptr;
-
if (!(m_engine_array= (plugin_ref*)
my_malloc(m_tot_parts * sizeof(plugin_ref), MYF(MY_WME))))
- goto err3;
+ goto err;
for (i= 0; i < m_tot_parts; i++)
m_engine_array[i]= ha_lock_engine(NULL, engine_array[i]);
my_afree((gptr) engine_array);
- if (!m_file && create_handlers(mem_root))
+ if (create_handlers(mem_root))
{
clear_handler_file();
- DBUG_RETURN(TRUE);
+ DBUG_RETURN(true);
}
- DBUG_RETURN(FALSE);
-err3:
+ DBUG_RETURN(false);
+
+err:
my_afree((gptr) engine_array);
-err2:
- my_free(file_buffer);
-err1:
- (void) mysql_file_close(file, MYF(0));
- DBUG_RETURN(TRUE);
+ DBUG_RETURN(true);
+}
+
+
+/**
+ Get info about partition engines and their names from the .par file
+
+ @param name Full path of table name
+ @param mem_root Allocate memory through this
+ @param is_clone If it is a clone, don't create new handlers
+
+ @return Operation status
+ @retval true Error
+ @retval false Success
+
+ @note Open handler file to get partition names, engine types and number of
+ partitions.
+*/
+
+bool ha_partition::get_from_handler_file(const char *name, MEM_ROOT *mem_root,
+ bool is_clone)
+{
+ DBUG_ENTER("ha_partition::get_from_handler_file");
+ DBUG_PRINT("enter", ("table name: '%s'", name));
+
+ if (m_file_buffer)
+ DBUG_RETURN(false);
+
+ if (read_par_file(name))
+ DBUG_RETURN(true);
+
+ if (!is_clone && setup_engine_array(mem_root))
+ DBUG_RETURN(true);
+
+ DBUG_RETURN(false);
}
@@ -2536,13 +2635,13 @@ void ha_data_partition_destroy(HA_DATA_PARTITION* ha_part_data)
int ha_partition::open(const char *name, int mode, uint test_if_locked)
{
- char *name_buffer_ptr= m_name_buffer_ptr;
- int error;
+ char *name_buffer_ptr;
+ int error= HA_ERR_INITIALIZATION;
uint alloc_len;
handler **file;
char name_buff[FN_REFLEN];
bool is_not_tmp_table= (table_share->tmp_table == NO_TMP_TABLE);
- ulonglong check_table_flags= 0;
+ ulonglong check_table_flags;
DBUG_ENTER("ha_partition::open");
DBUG_ASSERT(table->s == table_share);
@@ -2550,8 +2649,9 @@ int ha_partition::open(const char *name, int mode, uint test_if_locked)
m_mode= mode;
m_open_test_lock= test_if_locked;
m_part_field_array= m_part_info->full_part_field_array;
- if (get_from_handler_file(name, &table->mem_root))
- DBUG_RETURN(1);
+ if (get_from_handler_file(name, &table->mem_root, test(m_is_clone_of)))
+ DBUG_RETURN(error);
+ name_buffer_ptr= m_name_buffer_ptr;
m_start_key.length= 0;
m_rec0= table->record[0];
m_rec_length= table_share->stored_rec_length;
@@ -2561,7 +2661,7 @@ int ha_partition::open(const char *name, int mode, uint test_if_locked)
{
if (!(m_ordered_rec_buffer= (uchar*)my_malloc(alloc_len, MYF(MY_WME))))
{
- DBUG_RETURN(1);
+ DBUG_RETURN(error);
}
{
/*
@@ -2584,48 +2684,84 @@ int ha_partition::open(const char *name, int mode, uint test_if_locked)
/* Initialize the bitmap we use to minimize ha_start_bulk_insert calls */
if (bitmap_init(&m_bulk_insert_started, NULL, m_tot_parts + 1, FALSE))
- DBUG_RETURN(1);
+ DBUG_RETURN(error);
bitmap_clear_all(&m_bulk_insert_started);
/* Initialize the bitmap we use to determine what partitions are used */
- if (!is_clone)
+ if (!m_is_clone_of)
{
+ DBUG_ASSERT(!m_clone_mem_root);
if (bitmap_init(&(m_part_info->used_partitions), NULL, m_tot_parts, TRUE))
{
bitmap_free(&m_bulk_insert_started);
- DBUG_RETURN(1);
+ DBUG_RETURN(error);
}
bitmap_set_all(&(m_part_info->used_partitions));
}
+ if (m_is_clone_of)
+ {
+ uint i;
+ DBUG_ASSERT(m_clone_mem_root);
+ /* Allocate an array of handler pointers for the partitions handlers. */
+ alloc_len= (m_tot_parts + 1) * sizeof(handler*);
+ if (!(m_file= (handler **) alloc_root(m_clone_mem_root, alloc_len)))
+ goto err_alloc;
+ memset(m_file, 0, alloc_len);
+ /*
+ Populate them by cloning the original partitions. This also opens them.
+ Note that file->ref is allocated too.
+ */
+ file= m_is_clone_of->m_file;
+ for (i= 0; i < m_tot_parts; i++)
+ {
+ create_partition_name(name_buff, name, name_buffer_ptr, NORMAL_PART_NAME,
+ FALSE);
+ if (!(m_file[i]= file[i]->clone(name_buff, m_clone_mem_root)))
+ {
+ error= HA_ERR_INITIALIZATION;
+ file= &m_file[i];
+ goto err_handler;
+ }
+ name_buffer_ptr+= strlen(name_buffer_ptr) + 1;
+ }
+ }
+ else
+ {
+ file= m_file;
+ do
+ {
+ create_partition_name(name_buff, name, name_buffer_ptr, NORMAL_PART_NAME,
+ FALSE);
+ if ((error= (*file)->ha_open(table, name_buff, mode, test_if_locked)))
+ goto err_handler;
+ m_num_locks+= (*file)->lock_count();
+ name_buffer_ptr+= strlen(name_buffer_ptr) + 1;
+ } while (*(++file));
+ }
+
file= m_file;
- do
+ ref_length= (*file)->ref_length;
+ check_table_flags= (((*file)->ha_table_flags() &
+ ~(PARTITION_DISABLED_TABLE_FLAGS)) |
+ (PARTITION_ENABLED_TABLE_FLAGS));
+ while (*(++file))
{
- create_partition_name(name_buff, name, name_buffer_ptr, NORMAL_PART_NAME,
- FALSE);
- if ((error= (*file)->ha_open(table, (const char*) name_buff, mode,
- test_if_locked)))
- goto err_handler;
- m_num_locks+= (*file)->lock_count();
- name_buffer_ptr+= strlen(name_buffer_ptr) + 1;
+ /* MyISAM can have smaller ref_length for partitions with MAX_ROWS set */
set_if_bigger(ref_length, ((*file)->ref_length));
/*
Verify that all partitions have the same set of table flags.
Mask all flags that partitioning enables/disables.
*/
- if (!check_table_flags)
- {
- check_table_flags= (((*file)->ha_table_flags() &
- ~(PARTITION_DISABLED_TABLE_FLAGS)) |
- (PARTITION_ENABLED_TABLE_FLAGS));
- }
- else if (check_table_flags != (((*file)->ha_table_flags() &
- ~(PARTITION_DISABLED_TABLE_FLAGS)) |
- (PARTITION_ENABLED_TABLE_FLAGS)))
+ if (check_table_flags != (((*file)->ha_table_flags() &
+ ~(PARTITION_DISABLED_TABLE_FLAGS)) |
+ (PARTITION_ENABLED_TABLE_FLAGS)))
{
error= HA_ERR_INITIALIZATION;
+ /* set file to last handler, so all of them is closed */
+ file = &m_file[m_tot_parts - 1];
goto err_handler;
}
- } while (*(++file));
+ }
key_used_on_scan= m_file[0]->key_used_on_scan;
implicit_emptied= m_file[0]->implicit_emptied;
/*
@@ -2634,6 +2770,7 @@ int ha_partition::open(const char *name, int mode, uint test_if_locked)
*/
ref_length+= PARTITION_BYTES_IN_POS;
m_ref_length= ref_length;
+
/*
Release buffer read from .par file. It will not be reused again after
being opened once.
@@ -2693,25 +2830,54 @@ err_handler:
DEBUG_SYNC(ha_thd(), "partition_open_error");
while (file-- != m_file)
(*file)->close();
+err_alloc:
bitmap_free(&m_bulk_insert_started);
- if (!is_clone)
+ if (!m_is_clone_of)
bitmap_free(&(m_part_info->used_partitions));
DBUG_RETURN(error);
}
-handler *ha_partition::clone(MEM_ROOT *mem_root)
+
+/**
+ Clone the open and locked partitioning handler.
+
+ @param mem_root MEM_ROOT to use.
+
+ @return Pointer to the successfully created clone or NULL
+
+ @details
+ This function creates a new ha_partition handler as a clone/copy. The
+ original (this) must already be opened and locked. The clone will use
+ the originals m_part_info.
+ It also allocates memory for ref + ref_dup.
+ In ha_partition::open() it will clone its original handlers partitions
+ which will allocate then on the correct MEM_ROOT and also open them.
+*/
+
+handler *ha_partition::clone(const char *name, MEM_ROOT *mem_root)
{
- handler *new_handler= get_new_handler(table->s, mem_root,
- table->s->db_type());
- ((ha_partition*)new_handler)->m_part_info= m_part_info;
- ((ha_partition*)new_handler)->is_clone= TRUE;
- if (new_handler && !new_handler->ha_open(table,
- table->s->normalized_path.str,
- table->db_stat,
- HA_OPEN_IGNORE_IF_LOCKED))
- return new_handler;
- return NULL;
+ ha_partition *new_handler;
+
+ DBUG_ENTER("ha_partition::clone");
+ new_handler= new (mem_root) ha_partition(ht, table_share, m_part_info,
+ this, mem_root);
+ /*
+ Allocate new_handler->ref here because otherwise ha_open will allocate it
+ on this->table->mem_root and we will not be able to reclaim that memory
+ when the clone handler object is destroyed.
+ */
+ if (new_handler &&
+ !(new_handler->ref= (uchar*) alloc_root(mem_root,
+ ALIGN_SIZE(m_ref_length)*2)))
+ new_handler= NULL;
+
+ if (new_handler &&
+ new_handler->ha_open(table, name,
+ table->db_stat, HA_OPEN_IGNORE_IF_LOCKED))
+ new_handler= NULL;
+
+ DBUG_RETURN((handler*) new_handler);
}
@@ -2742,7 +2908,7 @@ int ha_partition::close(void)
DBUG_ASSERT(table->s == table_share);
delete_queue(&m_queue);
bitmap_free(&m_bulk_insert_started);
- if (!is_clone)
+ if (!m_is_clone_of)
bitmap_free(&(m_part_info->used_partitions));
file= m_file;
@@ -3096,7 +3262,9 @@ int ha_partition::write_row(uchar * buf)
bool have_auto_increment= table->next_number_field && buf == table->record[0];
my_bitmap_map *old_map;
THD *thd= ha_thd();
- timestamp_auto_set_type orig_timestamp_type= table->timestamp_field_type;
+ timestamp_auto_set_type saved_timestamp_type= table->timestamp_field_type;
+ ulong saved_sql_mode= thd->variables.sql_mode;
+ bool saved_auto_inc_field_not_null= table->auto_increment_field_not_null;
#ifdef NOT_NEEDED
uchar *rec0= m_rec0;
#endif
@@ -3132,6 +3300,22 @@ int ha_partition::write_row(uchar * buf)
*/
if (error)
goto exit;
+
+ /*
+ Don't allow generation of auto_increment value the partitions handler.
+ If a partitions handler would change the value, then it might not
+ match the partition any longer.
+ This can occur if 'SET INSERT_ID = 0; INSERT (NULL)',
+ So allow this by adding 'MODE_NO_AUTO_VALUE_ON_ZERO' to sql_mode.
+ The partitions handler::next_insert_id must always be 0. Otherwise
+ we need to forward release_auto_increment, or reset it for all
+ partitions.
+ */
+ if (table->next_number_field->val_int() == 0)
+ {
+ table->auto_increment_field_not_null= TRUE;
+ thd->variables.sql_mode|= MODE_NO_AUTO_VALUE_ON_ZERO;
+ }
}
old_map= dbug_tmp_use_all_columns(table, table->read_set);
@@ -3165,7 +3349,9 @@ int ha_partition::write_row(uchar * buf)
set_auto_increment_if_higher(table->next_number_field);
reenable_binlog(thd);
exit:
- table->timestamp_field_type= orig_timestamp_type;
+ thd->variables.sql_mode= saved_sql_mode;
+ table->auto_increment_field_not_null= saved_auto_inc_field_not_null;
+ table->timestamp_field_type= saved_timestamp_type;
DBUG_RETURN(error);
}
@@ -3232,11 +3418,24 @@ int ha_partition::update_row(const uchar *old_data, uchar *new_data)
}
else
{
+ Field *saved_next_number_field= table->next_number_field;
+ /*
+ Don't allow generation of auto_increment value for update.
+ table->next_number_field is never set on UPDATE.
+ But is set for INSERT ... ON DUPLICATE KEY UPDATE,
+ and since update_row() does not generate or update an auto_inc value,
+ we cannot have next_number_field set when moving a row
+ to another partition with write_row(), since that could
+ generate/update the auto_inc value.
+ This gives the same behavior for partitioned vs non partitioned tables.
+ */
+ table->next_number_field= NULL;
DBUG_PRINT("info", ("Update from partition %d to partition %d",
old_part_id, new_part_id));
tmp_disable_binlog(thd); /* Do not replicate the low-level changes. */
error= m_file[new_part_id]->ha_write_row(new_data);
reenable_binlog(thd);
+ table->next_number_field= saved_next_number_field;
if (error)
goto exit;
@@ -3260,9 +3459,13 @@ exit:
index)
mysql_update does not set table->next_number_field, so we use
table->found_next_number_field instead.
+ Also checking that the field is marked in the write set.
*/
- if (table->found_next_number_field && new_data == table->record[0] &&
- !table->s->next_number_keypart)
+ if (table->found_next_number_field &&
+ new_data == table->record[0] &&
+ !table->s->next_number_keypart &&
+ bitmap_is_set(table->write_set,
+ table->found_next_number_field->field_index))
{
if (!table_share->ha_part_data->auto_inc_initialized)
info(HA_STATUS_AUTO);
@@ -3340,113 +3543,128 @@ int ha_partition::delete_row(const uchar *buf)
Called from sql_delete.cc by mysql_delete().
Called from sql_select.cc by JOIN::reinit().
Called from sql_union.cc by st_select_lex_unit::exec().
-
- Also used for handle ALTER TABLE t TRUNCATE PARTITION ...
- NOTE: auto increment value will be truncated in that partition as well!
*/
int ha_partition::delete_all_rows()
{
int error;
- bool truncate= FALSE;
handler **file;
- THD *thd= ha_thd();
DBUG_ENTER("ha_partition::delete_all_rows");
- if (thd->lex->sql_command == SQLCOM_TRUNCATE)
+ file= m_file;
+ do
{
- Alter_info *alter_info= &thd->lex->alter_info;
- /* TRUNCATE also means resetting auto_increment */
- lock_auto_increment();
- table_share->ha_part_data->next_auto_inc_val= 0;
- table_share->ha_part_data->auto_inc_initialized= FALSE;
- unlock_auto_increment();
- if (alter_info->flags & ALTER_ADMIN_PARTITION)
- {
- /* ALTER TABLE t TRUNCATE PARTITION ... */
- List_iterator<partition_element> part_it(m_part_info->partitions);
- int saved_error= 0;
- uint num_parts= m_part_info->num_parts;
- uint num_subparts= m_part_info->num_subparts;
- uint i= 0;
- uint num_parts_set= alter_info->partition_names.elements;
- uint num_parts_found= set_part_state(alter_info, m_part_info,
- PART_ADMIN);
- if (num_parts_set != num_parts_found &&
- (!(alter_info->flags & ALTER_ALL_PARTITION)))
- DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
+ if ((error= (*file)->ha_delete_all_rows()))
+ DBUG_RETURN(error);
+ } while (*(++file));
+ DBUG_RETURN(0);
+}
+
+
+/**
+ Manually truncate the table.
+
+ @retval 0 Success.
+ @retval > 0 Error code.
+*/
+
+int ha_partition::truncate()
+{
+ int error;
+ handler **file;
+ DBUG_ENTER("ha_partition::truncate");
+
+ /*
+ TRUNCATE also means resetting auto_increment. Hence, reset
+ it so that it will be initialized again at the next use.
+ */
+ lock_auto_increment();
+ table_share->ha_part_data->next_auto_inc_val= 0;
+ table_share->ha_part_data->auto_inc_initialized= FALSE;
+ unlock_auto_increment();
- /*
- Cannot return HA_ERR_WRONG_COMMAND here without correct pruning
- since that whould delete the whole table row by row in sql_delete.cc
- */
- bitmap_clear_all(&m_part_info->used_partitions);
- do
- {
- partition_element *part_elem= part_it++;
- if (part_elem->part_state == PART_ADMIN)
- {
- if (m_is_sub_partitioned)
- {
- List_iterator<partition_element>
- subpart_it(part_elem->subpartitions);
- partition_element *sub_elem;
- uint j= 0, part;
- do
- {
- sub_elem= subpart_it++;
- part= i * num_subparts + j;
- bitmap_set_bit(&m_part_info->used_partitions, part);
- if (!saved_error)
- {
- DBUG_PRINT("info", ("truncate subpartition %u (%s)",
- part, sub_elem->partition_name));
- if ((error= m_file[part]->ha_delete_all_rows()))
- saved_error= error;
- /* If not reset_auto_increment is supported, just accept it */
- if (!saved_error &&
- (error= m_file[part]->ha_reset_auto_increment(0)) &&
- error != HA_ERR_WRONG_COMMAND)
- saved_error= error;
- }
- } while (++j < num_subparts);
- }
- else
- {
- DBUG_PRINT("info", ("truncate partition %u (%s)", i,
- part_elem->partition_name));
- bitmap_set_bit(&m_part_info->used_partitions, i);
- if (!saved_error)
- {
- if ((error= m_file[i]->ha_delete_all_rows()) && !saved_error)
- saved_error= error;
- /* If not reset_auto_increment is supported, just accept it */
- if (!saved_error &&
- (error= m_file[i]->ha_reset_auto_increment(0)) &&
- error != HA_ERR_WRONG_COMMAND)
- saved_error= error;
- }
- }
- part_elem->part_state= PART_NORMAL;
- }
- } while (++i < num_parts);
- DBUG_RETURN(saved_error);
- }
- truncate= TRUE;
- }
file= m_file;
do
{
- if ((error= (*file)->ha_delete_all_rows()))
+ if ((error= (*file)->ha_truncate()))
DBUG_RETURN(error);
- /* Ignore the error */
- if (truncate)
- (void) (*file)->ha_reset_auto_increment(0);
} while (*(++file));
DBUG_RETURN(0);
}
+/**
+ Truncate a set of specific partitions.
+
+ @remark Auto increment value will be truncated in that partition as well!
+
+ ALTER TABLE t TRUNCATE PARTITION ...
+*/
+
+int ha_partition::truncate_partition(Alter_info *alter_info, bool *binlog_stmt)
+{
+ int error= 0;
+ List_iterator<partition_element> part_it(m_part_info->partitions);
+ uint num_parts= m_part_info->num_parts;
+ uint num_subparts= m_part_info->num_subparts;
+ uint i= 0;
+ uint num_parts_set= alter_info->partition_names.elements;
+ uint num_parts_found= set_part_state(alter_info, m_part_info,
+ PART_ADMIN);
+ DBUG_ENTER("ha_partition::truncate_partition");
+
+ /* Only binlog when it starts any call to the partitions handlers */
+ *binlog_stmt= false;
+
+ /*
+ TRUNCATE also means resetting auto_increment. Hence, reset
+ it so that it will be initialized again at the next use.
+ */
+ lock_auto_increment();
+ table_share->ha_part_data->next_auto_inc_val= 0;
+ table_share->ha_part_data->auto_inc_initialized= FALSE;
+ unlock_auto_increment();
+
+ if (num_parts_set != num_parts_found &&
+ (!(alter_info->flags & ALTER_ALL_PARTITION)))
+ DBUG_RETURN(HA_ERR_NO_PARTITION_FOUND);
+
+ *binlog_stmt= true;
+
+ do
+ {
+ partition_element *part_elem= part_it++;
+ if (part_elem->part_state == PART_ADMIN)
+ {
+ if (m_is_sub_partitioned)
+ {
+ List_iterator<partition_element>
+ subpart_it(part_elem->subpartitions);
+ partition_element *sub_elem;
+ uint j= 0, part;
+ do
+ {
+ sub_elem= subpart_it++;
+ part= i * num_subparts + j;
+ DBUG_PRINT("info", ("truncate subpartition %u (%s)",
+ part, sub_elem->partition_name));
+ if ((error= m_file[part]->ha_truncate()))
+ break;
+ } while (++j < num_subparts);
+ }
+ else
+ {
+ DBUG_PRINT("info", ("truncate partition %u (%s)", i,
+ part_elem->partition_name));
+ error= m_file[i]->ha_truncate();
+ }
+ part_elem->part_state= PART_NORMAL;
+ }
+ } while (!error && (++i < num_parts));
+ DBUG_RETURN(error);
+}
+
+
/*
Start a large batch of insert rows
@@ -3883,19 +4101,16 @@ end_dont_reset_start_part:
void ha_partition::position(const uchar *record)
{
handler *file= m_file[m_last_part];
+ uint pad_length;
DBUG_ENTER("ha_partition::position");
file->position(record);
int2store(ref, m_last_part);
- memcpy((ref + PARTITION_BYTES_IN_POS), file->ref,
- (ref_length - PARTITION_BYTES_IN_POS));
-
-#ifdef SUPPORTING_PARTITION_OVER_DIFFERENT_ENGINES
-#ifdef HAVE_valgrind
- bzero(ref + PARTITION_BYTES_IN_POS + ref_length,
- max_ref_length-ref_length);
-#endif /* HAVE_valgrind */
-#endif
+ memcpy((ref + PARTITION_BYTES_IN_POS), file->ref, file->ref_length);
+ pad_length= m_ref_length - PARTITION_BYTES_IN_POS - file->ref_length;
+ if (pad_length)
+ memset((ref + PARTITION_BYTES_IN_POS + file->ref_length), 0, pad_length);
+
DBUG_VOID_RETURN;
}
@@ -3903,6 +4118,7 @@ void ha_partition::position(const uchar *record)
void ha_partition::column_bitmaps_signal()
{
handler::column_bitmaps_signal();
+ /* Must read all partition fields to make position() call possible */
bitmap_union(table->read_set, &m_part_info->full_part_field_set);
}
@@ -4357,8 +4573,12 @@ int ha_partition::index_read_idx_map(uchar *buf, uint index,
get_partition_set(table, buf, index, &m_start_key, &m_part_spec);
- /* How can it be more than one partition with the current use? */
- DBUG_ASSERT(m_part_spec.start_part == m_part_spec.end_part);
+ /*
+ We have either found exactly 1 partition
+ (in which case start_part == end_part)
+ or no matching partitions (start_part > end_part)
+ */
+ DBUG_ASSERT(m_part_spec.start_part >= m_part_spec.end_part);
for (part= m_part_spec.start_part; part <= m_part_spec.end_part; part++)
{
@@ -4371,6 +4591,8 @@ int ha_partition::index_read_idx_map(uchar *buf, uint index,
break;
}
}
+ if (part <= m_part_spec.end_part)
+ m_last_part= part;
}
else
{
@@ -4596,6 +4818,7 @@ int ha_partition::partition_scan_set_up(uchar * buf, bool idx_read_flag)
key not found.
*/
DBUG_PRINT("info", ("scan with no partition to scan"));
+ table->status= STATUS_NOT_FOUND;
DBUG_RETURN(HA_ERR_END_OF_FILE);
}
if (m_part_spec.start_part == m_part_spec.end_part)
@@ -4620,6 +4843,7 @@ int ha_partition::partition_scan_set_up(uchar * buf, bool idx_read_flag)
if (start_part == MY_BIT_NONE)
{
DBUG_PRINT("info", ("scan with no partition to scan"));
+ table->status= STATUS_NOT_FOUND;
DBUG_RETURN(HA_ERR_END_OF_FILE);
}
if (start_part > m_part_spec.start_part)
@@ -5129,6 +5353,8 @@ int ha_partition::handle_ordered_prev(uchar *buf)
int ha_partition::info(uint flag)
{
+ uint no_lock_flag= flag & HA_STATUS_NO_LOCK;
+ uint extra_var_flag= flag & HA_STATUS_VARIABLE_EXTRA;
DBUG_ENTER("ha_partition::info");
if (flag & HA_STATUS_AUTO)
@@ -5160,7 +5386,7 @@ int ha_partition::info(uint flag)
do
{
file= *file_array;
- file->info(HA_STATUS_AUTO);
+ file->info(HA_STATUS_AUTO | no_lock_flag);
set_if_bigger(auto_increment_value,
file->stats.auto_increment_value);
} while (*(++file_array));
@@ -5214,7 +5440,7 @@ int ha_partition::info(uint flag)
if (bitmap_is_set(&(m_part_info->used_partitions), (file_array - m_file)))
{
file= *file_array;
- file->info(HA_STATUS_VARIABLE);
+ file->info(HA_STATUS_VARIABLE | no_lock_flag | extra_var_flag);
stats.records+= file->stats.records;
stats.deleted+= file->stats.deleted;
stats.data_file_length+= file->stats.data_file_length;
@@ -5296,7 +5522,7 @@ int ha_partition::info(uint flag)
if (!(flag & HA_STATUS_VARIABLE) ||
!bitmap_is_set(&(m_part_info->used_partitions),
(file_array - m_file)))
- file->info(HA_STATUS_VARIABLE);
+ file->info(HA_STATUS_VARIABLE | no_lock_flag | extra_var_flag);
if (file->stats.records > max_records)
{
max_records= file->stats.records;
@@ -5306,7 +5532,7 @@ int ha_partition::info(uint flag)
} while (*(++file_array));
file= m_file[handler_instance];
- file->info(HA_STATUS_CONST);
+ file->info(HA_STATUS_CONST | no_lock_flag);
stats.block_size= file->stats.block_size;
stats.create_time= file->stats.create_time;
ref_length= m_ref_length;
@@ -5322,7 +5548,7 @@ int ha_partition::info(uint flag)
Note: all engines does not support HA_STATUS_ERRKEY, so set errkey.
*/
file->errkey= errkey;
- file->info(HA_STATUS_ERRKEY);
+ file->info(HA_STATUS_ERRKEY | no_lock_flag);
errkey= file->errkey;
}
if (flag & HA_STATUS_TIME)
@@ -5339,7 +5565,7 @@ int ha_partition::info(uint flag)
do
{
file= *file_array;
- file->info(HA_STATUS_TIME);
+ file->info(HA_STATUS_TIME | no_lock_flag);
if (file->stats.update_time > stats.update_time)
stats.update_time= file->stats.update_time;
} while (*(++file_array));
@@ -5353,7 +5579,7 @@ void ha_partition::get_dynamic_partition_info(PARTITION_STATS *stat_info,
{
handler *file= m_file[part_id];
file->info(HA_STATUS_CONST | HA_STATUS_TIME | HA_STATUS_VARIABLE |
- HA_STATUS_NO_LOCK);
+ HA_STATUS_VARIABLE_EXTRA | HA_STATUS_NO_LOCK);
stat_info->records= file->stats.records;
stat_info->mean_rec_length= file->stats.mean_rec_length;
@@ -6337,14 +6563,21 @@ void ha_partition::print_error(int error, myf errflag)
/* Should probably look for my own errors first */
DBUG_PRINT("enter", ("error: %d", error));
- if (error == HA_ERR_NO_PARTITION_FOUND &&
- thd->lex->sql_command != SQLCOM_TRUNCATE)
+ if ((error == HA_ERR_NO_PARTITION_FOUND) &&
+ ! (thd->lex->alter_info.flags & ALTER_TRUNCATE_PARTITION))
m_part_info->print_no_partition_found(table);
else
{
/* In case m_file has not been initialized, like in bug#42438 */
if (m_file)
+ {
+ if (m_last_part >= m_tot_parts)
+ {
+ DBUG_ASSERT(0);
+ m_last_part= 0;
+ }
m_file[m_last_part]->print_error(error, errflag);
+ }
else
handler::print_error(error, errflag);
}
@@ -6375,9 +6608,42 @@ bool ha_partition::get_error_message(int error, String *buf)
*/
uint ha_partition::alter_table_flags(uint flags)
{
+ uint flags_to_return, flags_to_check;
DBUG_ENTER("ha_partition::alter_table_flags");
- DBUG_RETURN(ht->alter_table_flags(flags) |
- m_file[0]->alter_table_flags(flags));
+
+ flags_to_return= ht->alter_table_flags(flags);
+ flags_to_return|= m_file[0]->alter_table_flags(flags);
+
+ /*
+ If one partition fails we must be able to revert the change for the other,
+ already altered, partitions. So both ADD and DROP can only be supported in
+ pairs.
+ */
+ flags_to_check= HA_INPLACE_ADD_INDEX_NO_READ_WRITE;
+ flags_to_check|= HA_INPLACE_DROP_INDEX_NO_READ_WRITE;
+ if ((flags_to_return & flags_to_check) != flags_to_check)
+ flags_to_return&= ~flags_to_check;
+ flags_to_check= HA_INPLACE_ADD_UNIQUE_INDEX_NO_READ_WRITE;
+ flags_to_check|= HA_INPLACE_DROP_UNIQUE_INDEX_NO_READ_WRITE;
+ if ((flags_to_return & flags_to_check) != flags_to_check)
+ flags_to_return&= ~flags_to_check;
+ flags_to_check= HA_INPLACE_ADD_PK_INDEX_NO_READ_WRITE;
+ flags_to_check|= HA_INPLACE_DROP_PK_INDEX_NO_READ_WRITE;
+ if ((flags_to_return & flags_to_check) != flags_to_check)
+ flags_to_return&= ~flags_to_check;
+ flags_to_check= HA_INPLACE_ADD_INDEX_NO_WRITE;
+ flags_to_check|= HA_INPLACE_DROP_INDEX_NO_WRITE;
+ if ((flags_to_return & flags_to_check) != flags_to_check)
+ flags_to_return&= ~flags_to_check;
+ flags_to_check= HA_INPLACE_ADD_UNIQUE_INDEX_NO_WRITE;
+ flags_to_check|= HA_INPLACE_DROP_UNIQUE_INDEX_NO_WRITE;
+ if ((flags_to_return & flags_to_check) != flags_to_check)
+ flags_to_return&= ~flags_to_check;
+ flags_to_check= HA_INPLACE_ADD_PK_INDEX_NO_WRITE;
+ flags_to_check|= HA_INPLACE_DROP_PK_INDEX_NO_WRITE;
+ if ((flags_to_return & flags_to_check) != flags_to_check)
+ flags_to_return&= ~flags_to_check;
+ DBUG_RETURN(flags_to_return);
}
@@ -6405,25 +6671,89 @@ bool ha_partition::check_if_incompatible_data(HA_CREATE_INFO *create_info,
/**
- Support of fast or online add/drop index
+ Support of in-place add/drop index
*/
-int ha_partition::add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys)
+int ha_partition::add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys,
+ handler_add_index **add)
{
handler **file;
int ret= 0;
+ DBUG_ENTER("ha_partition::add_index");
+ *add= new handler_add_index(table, key_info, num_of_keys);
/*
There has already been a check in fix_partition_func in mysql_alter_table
before this call, which checks for unique/primary key violations of the
partitioning function. So no need for extra check here.
*/
for (file= m_file; *file; file++)
- if ((ret= (*file)->add_index(table_arg, key_info, num_of_keys)))
- break;
- return ret;
+ {
+ handler_add_index *add_index;
+ if ((ret= (*file)->add_index(table_arg, key_info, num_of_keys, &add_index)))
+ goto err;
+ if ((ret= (*file)->final_add_index(add_index, true)))
+ goto err;
+ }
+ DBUG_RETURN(ret);
+err:
+ if (file > m_file)
+ {
+ uint *key_numbers= (uint*) ha_thd()->alloc(sizeof(uint) * num_of_keys);
+ uint old_num_of_keys= table_arg->s->keys;
+ uint i;
+ /* The newly created keys have the last id's */
+ for (i= 0; i < num_of_keys; i++)
+ key_numbers[i]= i + old_num_of_keys;
+ if (!table_arg->key_info)
+ table_arg->key_info= key_info;
+ while (--file >= m_file)
+ {
+ (void) (*file)->prepare_drop_index(table_arg, key_numbers, num_of_keys);
+ (void) (*file)->final_drop_index(table_arg);
+ }
+ if (table_arg->key_info == key_info)
+ table_arg->key_info= NULL;
+ }
+ DBUG_RETURN(ret);
}
+/**
+ Second phase of in-place add index.
+
+ @note If commit is false, index changes are rolled back by dropping the
+ added indexes. If commit is true, nothing is done as the indexes
+ were already made active in ::add_index()
+ */
+
+int ha_partition::final_add_index(handler_add_index *add, bool commit)
+{
+ DBUG_ENTER("ha_partition::final_add_index");
+ // Rollback by dropping indexes.
+ if (!commit)
+ {
+ TABLE *table_arg= add->table;
+ uint num_of_keys= add->num_of_keys;
+ handler **file;
+ uint *key_numbers= (uint*) ha_thd()->alloc(sizeof(uint) * num_of_keys);
+ uint old_num_of_keys= table_arg->s->keys;
+ uint i;
+ /* The newly created keys have the last id's */
+ for (i= 0; i < num_of_keys; i++)
+ key_numbers[i]= i + old_num_of_keys;
+ if (!table_arg->key_info)
+ table_arg->key_info= add->key_info;
+ for (file= m_file; *file; file++)
+ {
+ (void) (*file)->prepare_drop_index(table_arg, key_numbers, num_of_keys);
+ (void) (*file)->final_drop_index(table_arg);
+ }
+ if (table_arg->key_info == add->key_info)
+ table_arg->key_info= NULL;
+ }
+ DBUG_RETURN(0);
+}
+
int ha_partition::prepare_drop_index(TABLE *table_arg, uint *key_num,
uint num_of_keys)
{
diff --git a/sql/ha_partition.h b/sql/ha_partition.h
index efd0707252e..c2bdd23a256 100644
--- a/sql/ha_partition.h
+++ b/sql/ha_partition.h
@@ -36,6 +36,16 @@ enum partition_keywords
HA_DUPLICATE_POS | \
HA_CAN_SQL_HANDLER | \
HA_CAN_INSERT_DELAYED)
+
+/* First 4 bytes in the .par file is the number of 32-bit words in the file */
+#define PAR_WORD_SIZE 4
+/* offset to the .par file checksum */
+#define PAR_CHECKSUM_OFFSET 4
+/* offset to the total number of partitions */
+#define PAR_NUM_PARTS_OFFSET 8
+/* offset to the engines array */
+#define PAR_ENGINES_OFFSET 12
+
class ha_partition :public handler
{
private:
@@ -51,7 +61,7 @@ private:
/* Data for the partition handler */
int m_mode; // Open mode
uint m_open_test_lock; // Open test_if_locked
- char *m_file_buffer; // Buffer with names
+ char *m_file_buffer; // Content of the .par file
char *m_name_buffer_ptr; // Pointer to first partition name
plugin_ref *m_engine_array; // Array of types of the handlers
handler **m_file; // Array of references to handler inst.
@@ -113,6 +123,13 @@ private:
bool m_is_sub_partitioned; // Is subpartitioned
bool m_ordered_scan_ongoing;
+ /*
+ If set, this object was created with ha_partition::clone and doesn't
+ "own" the m_part_info structure.
+ */
+ ha_partition *m_is_clone_of;
+ MEM_ROOT *m_clone_mem_root;
+
/*
We keep track if all underlying handlers are MyISAM since MyISAM has a
great number of extra flags not needed by other handlers.
@@ -146,11 +163,6 @@ private:
*/
THR_LOCK_DATA lock; /* MySQL lock */
- /*
- TRUE <=> this object was created with ha_partition::clone and doesn't
- "own" the m_part_info structure.
- */
- bool is_clone;
bool auto_increment_lock; /**< lock reading/updating auto_inc */
/**
Flag to keep the auto_increment lock through out the statement.
@@ -163,7 +175,7 @@ private:
/** used for prediction of start_bulk_insert rows */
enum_monotonicity_info m_part_func_monotonicity_info;
public:
- handler *clone(MEM_ROOT *mem_root);
+ handler *clone(const char *name, MEM_ROOT *mem_root);
virtual void set_part_info(partition_info *part_info)
{
m_part_info= part_info;
@@ -182,6 +194,10 @@ public:
*/
ha_partition(handlerton *hton, TABLE_SHARE * table);
ha_partition(handlerton *hton, partition_info * part_info);
+ ha_partition(handlerton *hton, TABLE_SHARE *share,
+ partition_info *part_info_arg,
+ ha_partition *clone_arg,
+ MEM_ROOT *clone_mem_root_arg);
~ha_partition();
/*
A partition handler has no characteristics in itself. It only inherits
@@ -253,7 +269,10 @@ private:
And one method to read it in.
*/
bool create_handler_file(const char *name);
- bool get_from_handler_file(const char *name, MEM_ROOT *mem_root);
+ bool setup_engine_array(MEM_ROOT *mem_root);
+ bool read_par_file(const char *name);
+ bool get_from_handler_file(const char *name, MEM_ROOT *mem_root,
+ bool is_clone);
bool new_handlers_from_part_info(MEM_ROOT *mem_root);
bool create_handlers(MEM_ROOT *mem_root);
void clear_handler_file();
@@ -345,6 +364,7 @@ public:
virtual int update_row(const uchar * old_data, uchar * new_data);
virtual int delete_row(const uchar * buf);
virtual int delete_all_rows(void);
+ virtual int truncate();
virtual void start_bulk_insert(ha_rows rows);
virtual int end_bulk_insert();
private:
@@ -353,6 +373,15 @@ private:
long estimate_read_buffer_size(long original_size);
public:
+ /*
+ Method for truncating a specific partition.
+ (i.e. ALTER TABLE t1 TRUNCATE PARTITION p).
+
+ @remark This method is a partitioning-specific hook
+ and thus not a member of the general SE API.
+ */
+ int truncate_partition(Alter_info *, bool *binlog_stmt);
+
virtual bool is_fatal_error(int error, uint flags)
{
if (!handler::is_fatal_error(error, flags) ||
@@ -1023,7 +1052,9 @@ public:
They are used for on-line/fast alter table add/drop index:
-------------------------------------------------------------------------
*/
- virtual int add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys);
+ virtual int add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys,
+ handler_add_index **add);
+ virtual int final_add_index(handler_add_index *add, bool commit);
virtual int prepare_drop_index(TABLE *table_arg, uint *key_num,
uint num_of_keys);
virtual int final_drop_index(TABLE *table_arg);
diff --git a/sql/handler.cc b/sql/handler.cc
index 1737d5554b9..41bac077e3b 100644
--- a/sql/handler.cc
+++ b/sql/handler.cc
@@ -1,4 +1,5 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ Copyright (c) 2011 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
@@ -29,8 +30,6 @@
#include "sql_cache.h" // query_cache, query_cache_*
#include "key.h" // key_copy, key_unpack, key_cmp_if_same, key_cmp
#include "sql_table.h" // build_table_filename
-#include "lock.h" // wait_if_global_read_lock,
- // start_waiting_global_read_lock
#include "sql_parse.h" // check_stack_overrun
#include "sql_acl.h" // SUPER_ACL
#include "sql_base.h" // free_io_cache
@@ -42,7 +41,7 @@
#include "transaction.h"
#include "myisam.h"
#include "probes_mysql.h"
-#include "sql_connect.h"
+#include "debug_sync.h" // DEBUG_SYNC
#ifdef WITH_PARTITION_STORAGE_ENGINE
#include "ha_partition.h"
@@ -279,7 +278,7 @@ handler *get_ha_partition(partition_info *part_info)
}
else
{
- my_error(ER_OUTOFMEMORY, MYF(0), sizeof(ha_partition));
+ my_error(ER_OUTOFMEMORY, MYF(0), static_cast<int>(sizeof(ha_partition)));
}
DBUG_RETURN(((handler*) partition));
}
@@ -358,6 +357,7 @@ int ha_init_errors(void)
SETMSG(HA_ERR_AUTOINC_READ_FAILED, ER_DEFAULT(ER_AUTOINC_READ_FAILED));
SETMSG(HA_ERR_AUTOINC_ERANGE, ER_DEFAULT(ER_WARN_DATA_OUT_OF_RANGE));
SETMSG(HA_ERR_TOO_MANY_CONCURRENT_TRXS, ER_DEFAULT(ER_TOO_MANY_CONCURRENT_TRXS));
+ SETMSG(HA_ERR_INDEX_COL_TOO_LONG, ER_DEFAULT(ER_INDEX_COLUMN_TOO_LONG));
/* Register the error messages for use with my_error(). */
return my_error_register(get_handler_errmsgs, HA_ERR_FIRST, HA_ERR_LAST);
@@ -1168,8 +1168,9 @@ int ha_commit_trans(THD *thd, bool all)
{
uint rw_ha_count;
bool rw_trans;
+ MDL_request mdl_request;
- DBUG_EXECUTE_IF("crash_commit_before", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_commit_before", DBUG_SUICIDE(););
/* Close all cursors that can not survive COMMIT */
if (is_real_trans) /* not a statement commit */
@@ -1179,11 +1180,27 @@ int ha_commit_trans(THD *thd, bool all)
/* rw_trans is TRUE when we in a transaction changing data */
rw_trans= is_real_trans && (rw_ha_count > 0);
- if (rw_trans &&
- thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, FALSE))
+ if (rw_trans)
{
- ha_rollback_trans(thd, all);
- DBUG_RETURN(1);
+ /*
+ Acquire a metadata lock which will ensure that COMMIT is blocked
+ by an active FLUSH TABLES WITH READ LOCK (and vice versa:
+ COMMIT in progress blocks FTWRL).
+
+ We allow the owner of FTWRL to COMMIT; we assume that it knows
+ what it does.
+ */
+ mdl_request.init(MDL_key::COMMIT, "", "", MDL_INTENTION_EXCLUSIVE,
+ MDL_EXPLICIT);
+
+ if (thd->mdl_context.acquire_lock(&mdl_request,
+ thd->variables.lock_wait_timeout))
+ {
+ ha_rollback_trans(thd, all);
+ DBUG_RETURN(1);
+ }
+
+ DEBUG_SYNC(thd, "ha_commit_trans_after_acquire_commit_lock");
}
if (rw_trans &&
@@ -1221,7 +1238,7 @@ int ha_commit_trans(THD *thd, bool all)
}
status_var_increment(thd->status_var.ha_prepare_count);
}
- DBUG_EXECUTE_IF("crash_commit_after_prepare", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_commit_after_prepare", DBUG_SUICIDE(););
if (error || (is_real_trans && xid &&
(error= !(cookie= tc_log->log_xid(thd, xid)))))
{
@@ -1229,17 +1246,29 @@ int ha_commit_trans(THD *thd, bool all)
error= 1;
goto end;
}
- DBUG_EXECUTE_IF("crash_commit_after_log", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_commit_after_log", DBUG_SUICIDE(););
}
error=ha_commit_one_phase(thd, all) ? (cookie ? 2 : 1) : 0;
- DBUG_EXECUTE_IF("crash_commit_before_unlog", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_commit_before_unlog", DBUG_SUICIDE(););
if (cookie)
- tc_log->unlog(cookie, xid);
- DBUG_EXECUTE_IF("crash_commit_after", DBUG_ABORT(););
+ if(tc_log->unlog(cookie, xid))
+ {
+ error= 2;
+ goto end;
+ }
+ DBUG_EXECUTE_IF("crash_commit_after", DBUG_SUICIDE(););
RUN_HOOK(transaction, after_commit, (thd, FALSE));
end:
- if (rw_trans)
- thd->global_read_lock.start_waiting_global_read_lock(thd);
+ if (rw_trans && mdl_request.ticket)
+ {
+ /*
+ We do not always immediately release transactional locks
+ after ha_commit_trans() (see uses of ha_enable_transaction()),
+ thus we release the commit blocker lock as soon as it's
+ not needed.
+ */
+ thd->mdl_context.release_lock(mdl_request.ticket);
+ }
}
/* Free resources and perform other cleanup even for 'empty' transactions. */
else if (is_real_trans)
@@ -1614,7 +1643,8 @@ int ha_recover(HASH *commit_list)
}
if (!info.list)
{
- sql_print_error(ER(ER_OUTOFMEMORY), info.len*sizeof(XID));
+ sql_print_error(ER(ER_OUTOFMEMORY),
+ static_cast<int>(info.len*sizeof(XID)));
DBUG_RETURN(1);
}
@@ -2052,26 +2082,28 @@ int ha_delete_table(THD *thd, handlerton *table_type, const char *path,
/****************************************************************************
** General handler functions
****************************************************************************/
-handler *handler::clone(MEM_ROOT *mem_root)
+handler *handler::clone(const char *name, MEM_ROOT *mem_root)
{
- handler *new_handler= get_new_handler(table->s, mem_root, table->s->db_type());
-
- if (!new_handler)
- return NULL;
-
+ handler *new_handler= get_new_handler(table->s, mem_root, ht);
/*
Allocate handler->ref here because otherwise ha_open will allocate it
on this->table->mem_root and we will not be able to reclaim that memory
when the clone handler object is destroyed.
*/
- if (!(new_handler->ref= (uchar*) alloc_root(mem_root, ALIGN_SIZE(ref_length)*2)))
- return NULL;
- if (new_handler->ha_open(table,
- table->s->normalized_path.str,
- table->db_stat,
- HA_OPEN_IGNORE_IF_LOCKED))
- return NULL;
- new_handler->cloned= 1; // Marker for debugging
+ if (new_handler &&
+ !(new_handler->ref= (uchar*) alloc_root(mem_root,
+ ALIGN_SIZE(ref_length)*2)))
+ new_handler= NULL;
+ /*
+ TODO: Implement a more efficient way to have more than one index open for
+ the same table instance. The ha_open call is not cachable for clone.
+ */
+ if (new_handler && new_handler->ha_open(table,
+ name,
+ table->db_stat,
+ HA_OPEN_IGNORE_IF_LOCKED))
+ new_handler= NULL;
+
return new_handler;
}
@@ -2217,7 +2249,8 @@ int handler::read_first_row(uchar * buf, uint primary_key)
computes the lowest number
- strictly greater than "nr"
- of the form: auto_increment_offset + N * auto_increment_increment
-
+ If overflow happened then return MAX_ULONGLONG value as an
+ indication of overflow.
In most cases increment= offset= 1, in which case we get:
@verbatim 1,2,3,4,5,... @endverbatim
If increment=10 and offset=5 and previous number is 1, we get:
@@ -2226,13 +2259,23 @@ int handler::read_first_row(uchar * buf, uint primary_key)
inline ulonglong
compute_next_insert_id(ulonglong nr,struct system_variables *variables)
{
+ const ulonglong save_nr= nr;
+
if (variables->auto_increment_increment == 1)
- return (nr+1); // optimization of the formula below
- nr= (((nr+ variables->auto_increment_increment -
- variables->auto_increment_offset)) /
- (ulonglong) variables->auto_increment_increment);
- return (nr* (ulonglong) variables->auto_increment_increment +
- variables->auto_increment_offset);
+ nr= nr + 1; // optimization of the formula below
+ else
+ {
+ nr= (((nr+ variables->auto_increment_increment -
+ variables->auto_increment_offset)) /
+ (ulonglong) variables->auto_increment_increment);
+ nr= (nr* (ulonglong) variables->auto_increment_increment +
+ variables->auto_increment_offset);
+ }
+
+ if (unlikely(nr <= save_nr))
+ return ULONGLONG_MAX;
+
+ return nr;
}
@@ -2443,7 +2486,7 @@ int handler::update_auto_increment()
variables->auto_increment_increment,
nb_desired_values, &nr,
&nb_reserved_values);
- if (nr == ~(ulonglong) 0)
+ if (nr == ULONGLONG_MAX)
DBUG_RETURN(HA_ERR_AUTOINC_READ_FAILED); // Mark failure
/*
@@ -2474,6 +2517,9 @@ int handler::update_auto_increment()
}
}
+ if (unlikely(nr == ULONGLONG_MAX))
+ DBUG_RETURN(HA_ERR_AUTOINC_ERANGE);
+
DBUG_PRINT("info",("auto_increment: %lu", (ulong) nr));
if (unlikely(table->next_number_field->store((longlong) nr, TRUE)))
@@ -2701,6 +2747,7 @@ void handler::print_error(int error, myf errflag)
break;
case HA_ERR_KEY_NOT_FOUND:
case HA_ERR_NO_ACTIVE_RECORD:
+ case HA_ERR_RECORD_DELETED:
case HA_ERR_END_OF_FILE:
/*
This errors is not not normally fatal (for example for reads). However
@@ -2868,6 +2915,9 @@ void handler::print_error(int error, myf errflag)
case HA_ERR_TOO_MANY_CONCURRENT_TRXS:
textno= ER_TOO_MANY_CONCURRENT_TRXS;
break;
+ case HA_ERR_INDEX_COL_TOO_LONG:
+ textno= ER_INDEX_COLUMN_TOO_LONG;
+ break;
default:
{
/* The error was "unknown" to this function.
@@ -3235,9 +3285,13 @@ int handler::ha_repair(THD* thd, HA_CHECK_OPT* check_opt)
mark_trx_read_write();
- if ((result= repair(thd, check_opt)))
- return result;
- return update_frm_version(table);
+ result= repair(thd, check_opt);
+ DBUG_ASSERT(result == HA_ADMIN_NOT_IMPLEMENTED ||
+ ha_table_flags() & HA_CAN_REPAIR);
+
+ if (result == HA_ADMIN_OK)
+ result= update_frm_version(table);
+ return result;
}
@@ -3273,6 +3327,21 @@ handler::ha_delete_all_rows()
/**
+ Truncate table: public interface.
+
+ @sa handler::truncate()
+*/
+
+int
+handler::ha_truncate()
+{
+ mark_trx_read_write();
+
+ return truncate();
+}
+
+
+/**
Reset auto increment: public interface.
@sa handler::reset_auto_increment()
@@ -4807,6 +4876,7 @@ int handler::ha_reset()
free_io_cache(table);
/* reset the bitmaps to point to defaults */
table->default_column_bitmaps();
+ pushed_cond= NULL;
DBUG_RETURN(reset());
}
diff --git a/sql/handler.h b/sql/handler.h
index 656c9403b8c..8524ecfd695 100644
--- a/sql/handler.h
+++ b/sql/handler.h
@@ -1,19 +1,22 @@
#ifndef HANDLER_INCLUDED
#define HANDLER_INCLUDED
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ Copyright (c) 2010-2011 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 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
+ 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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ 02110-1301 USA */
/* Definitions for parameters to do with handler-routines */
@@ -28,7 +31,7 @@
#include "sql_cache.h"
#include "structs.h" /* SHOW_COMP_OPTION */
-#include <my_handler.h>
+#include <my_compare.h>
#include <ft_global.h>
#include <keycache.h>
@@ -63,7 +66,7 @@
a table with rnd_next()
- We will see all rows (including deleted ones)
- Row positions are 'table->s->db_record_offset' apart
- If this flag is not set, filesort will do a postion() call for each matched
+ If this flag is not set, filesort will do a position() call for each matched
row to be able to find the row later.
*/
#define HA_REC_NOT_IN_SEQ (1 << 3)
@@ -157,10 +160,18 @@
ordered.
*/
#define HA_DUPLICATE_KEY_NOT_IN_ORDER (LL(1) << 36)
+
+/*
+ Engine supports REPAIR TABLE. Used by CHECK TABLE FOR UPGRADE if an
+ incompatible table is detected. If this flag is set, CHECK TABLE FOR UPGRADE
+ will report ER_TABLE_NEEDS_UPGRADE, otherwise ER_TABLE_NEED_REBUILD.
+*/
+#define HA_CAN_REPAIR (LL(1) << 37)
+
/* Has automatic checksums and uses the new checksum format */
-#define HA_HAS_NEW_CHECKSUM (LL(1) << 37)
+#define HA_HAS_NEW_CHECKSUM (LL(1) << 38)
-#define HA_MRR_CANT_SORT (LL(1) << 38)
+#define HA_MRR_CANT_SORT (LL(1) << 39)
/*
Set of all binlog flags. Currently only contain the capabilities
@@ -189,26 +200,31 @@
bits in alter_table_flags:
*/
/*
- These bits are set if different kinds of indexes can be created
- off-line without re-create of the table (but with a table lock).
+ These bits are set if different kinds of indexes can be created or dropped
+ in-place without re-creating the table using a temporary table.
+ NO_READ_WRITE indicates that the handler needs concurrent reads and writes
+ of table data to be blocked.
+ Partitioning needs both ADD and DROP to be supported by its underlying
+ handlers, due to error handling, see bug#57778.
*/
-#define HA_ONLINE_ADD_INDEX_NO_WRITES (1L << 0) /*add index w/lock*/
-#define HA_ONLINE_DROP_INDEX_NO_WRITES (1L << 1) /*drop index w/lock*/
-#define HA_ONLINE_ADD_UNIQUE_INDEX_NO_WRITES (1L << 2) /*add unique w/lock*/
-#define HA_ONLINE_DROP_UNIQUE_INDEX_NO_WRITES (1L << 3) /*drop uniq. w/lock*/
-#define HA_ONLINE_ADD_PK_INDEX_NO_WRITES (1L << 4) /*add prim. w/lock*/
-#define HA_ONLINE_DROP_PK_INDEX_NO_WRITES (1L << 5) /*drop prim. w/lock*/
+#define HA_INPLACE_ADD_INDEX_NO_READ_WRITE (1L << 0)
+#define HA_INPLACE_DROP_INDEX_NO_READ_WRITE (1L << 1)
+#define HA_INPLACE_ADD_UNIQUE_INDEX_NO_READ_WRITE (1L << 2)
+#define HA_INPLACE_DROP_UNIQUE_INDEX_NO_READ_WRITE (1L << 3)
+#define HA_INPLACE_ADD_PK_INDEX_NO_READ_WRITE (1L << 4)
+#define HA_INPLACE_DROP_PK_INDEX_NO_READ_WRITE (1L << 5)
/*
- These are set if different kinds of indexes can be created on-line
- (without a table lock). If a handler is capable of one or more of
- these, it should also set the corresponding *_NO_WRITES bit(s).
+ These are set if different kinds of indexes can be created or dropped
+ in-place while still allowing concurrent reads (but not writes) of table
+ data. If a handler is capable of one or more of these, it should also set
+ the corresponding *_NO_READ_WRITE bit(s).
*/
-#define HA_ONLINE_ADD_INDEX (1L << 6) /*add index online*/
-#define HA_ONLINE_DROP_INDEX (1L << 7) /*drop index online*/
-#define HA_ONLINE_ADD_UNIQUE_INDEX (1L << 8) /*add unique online*/
-#define HA_ONLINE_DROP_UNIQUE_INDEX (1L << 9) /*drop uniq. online*/
-#define HA_ONLINE_ADD_PK_INDEX (1L << 10)/*add prim. online*/
-#define HA_ONLINE_DROP_PK_INDEX (1L << 11)/*drop prim. online*/
+#define HA_INPLACE_ADD_INDEX_NO_WRITE (1L << 6)
+#define HA_INPLACE_DROP_INDEX_NO_WRITE (1L << 7)
+#define HA_INPLACE_ADD_UNIQUE_INDEX_NO_WRITE (1L << 8)
+#define HA_INPLACE_DROP_UNIQUE_INDEX_NO_WRITE (1L << 9)
+#define HA_INPLACE_ADD_PK_INDEX_NO_WRITE (1L << 10)
+#define HA_INPLACE_DROP_PK_INDEX_NO_WRITE (1L << 11)
/*
HA_PARTITION_FUNCTION_SUPPORTED indicates that the function is
supported at all.
@@ -1102,7 +1118,7 @@ typedef struct st_ha_create_information
{
CHARSET_INFO *table_charset, *default_table_charset;
LEX_STRING connect_string;
- const char *password, *tablespace;
+ const char *password;
LEX_STRING comment;
const char *data_file_name, *index_file_name;
const char *alias;
@@ -1131,7 +1147,6 @@ typedef struct st_ha_create_information
enum ha_choice transactional;
bool frm_only; ///< 1 if no ha_create_table()
bool varchar; ///< 1 if table has a VARCHAR
- enum ha_storage_media storage_media; ///< DEFAULT, DISK or MEMORY
enum ha_choice page_checksum; ///< If we have page_checksums
engine_option_value *option_list; ///< list of table create options
/* the following three are only for ALTER TABLE, check_if_incompatible_data() */
@@ -1464,6 +1479,27 @@ uint calculate_key_len(TABLE *, uint, const uchar *, key_part_map);
*/
#define make_prev_keypart_map(N) (((key_part_map)1 << (N)) - 1)
+
+/**
+ Index creation context.
+ Created by handler::add_index() and freed by handler::final_add_index().
+*/
+
+class handler_add_index
+{
+public:
+ /* Table where the indexes are added */
+ TABLE* const table;
+ /* Indexes being created */
+ KEY* const key_info;
+ /* Size of key_info[] */
+ const uint num_of_keys;
+ handler_add_index(TABLE *table_arg, KEY *key_info_arg, uint num_of_keys_arg)
+ : table (table_arg), key_info (key_info_arg), num_of_keys (num_of_keys_arg)
+ {}
+ virtual ~handler_add_index() {}
+};
+
/**
The handler class is the interface for dynamically loadable
storage engines. Do not add ifdefs and take care when adding or
@@ -1522,7 +1558,6 @@ public:
bool locked;
bool implicit_emptied; /* Can be !=0 only if HEAP */
bool mark_trx_done;
- bool cloned; /* 1 if this was created with clone */
const COND *pushed_cond;
/**
next_insert_id is the next value which should be inserted into the
@@ -1584,7 +1619,7 @@ public:
in_range_check_pushed_down(FALSE),
ref_length(sizeof(my_off_t)),
ft_handler(0), inited(NONE),
- locked(FALSE), implicit_emptied(0), mark_trx_done(FALSE), cloned(0),
+ locked(FALSE), implicit_emptied(0), mark_trx_done(FALSE),
pushed_cond(0), next_insert_id(0), insert_id_for_cur_row(0),
pushed_idx_cond(NULL),
pushed_idx_cond_keyno(MAX_KEY),
@@ -1598,7 +1633,7 @@ public:
DBUG_ASSERT(locked == FALSE);
DBUG_ASSERT(inited == NONE);
}
- virtual handler *clone(MEM_ROOT *mem_root);
+ virtual handler *clone(const char *name, MEM_ROOT *mem_root);
/** This is called after create to allow us to set up cached variables */
void init()
{
@@ -1690,6 +1725,7 @@ public:
int ha_bulk_update_row(const uchar *old_data, uchar *new_data,
uint *dup_key_found);
int ha_delete_all_rows();
+ int ha_truncate();
int ha_reset_auto_increment(ulonglong value);
int ha_optimize(THD* thd, HA_CHECK_OPT* check_opt);
int ha_analyze(THD* thd, HA_CHECK_OPT* check_opt);
@@ -2049,8 +2085,33 @@ public:
{ return(NULL);} /* gets tablespace name from handler */
/** used in ALTER TABLE; 1 if changing storage engine is allowed */
virtual bool can_switch_engines() { return 1; }
- /** used in REPLACE; is > 0 if table is referred by a FOREIGN KEY */
- virtual int get_foreign_key_list(THD *thd, List<FOREIGN_KEY_INFO> *f_key_list)
+ /**
+ Get the list of foreign keys in this table.
+
+ @remark Returns the set of foreign keys where this table is the
+ dependent or child table.
+
+ @param thd The thread handle.
+ @param f_key_list[out] The list of foreign keys.
+
+ @return The handler error code or zero for success.
+ */
+ virtual int
+ get_foreign_key_list(THD *thd, List<FOREIGN_KEY_INFO> *f_key_list)
+ { return 0; }
+ /**
+ Get the list of foreign keys referencing this table.
+
+ @remark Returns the set of foreign keys where this table is the
+ referenced or parent table.
+
+ @param thd The thread handle.
+ @param f_key_list[out] The list of foreign keys.
+
+ @return The handler error code or zero for success.
+ */
+ virtual int
+ get_parent_foreign_key_list(THD *thd, List<FOREIGN_KEY_INFO> *f_key_list)
{ return 0; }
virtual uint referenced_by_foreign_key() { return 0;}
virtual void init_table_handle_for_HANDLER()
@@ -2084,8 +2145,36 @@ public:
virtual ulong index_flags(uint idx, uint part, bool all_parts) const =0;
- virtual int add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys)
+/**
+ First phase of in-place add index.
+ Handlers are supposed to create new indexes here but not make them
+ visible.
+
+ @param table_arg Table to add index to
+ @param key_info Information about new indexes
+ @param num_of_key Number of new indexes
+ @param add[out] Context of handler specific information needed
+ for final_add_index().
+
+ @note This function can be called with less than exclusive metadata
+ lock depending on which flags are listed in alter_table_flags.
+*/
+ virtual int add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys,
+ handler_add_index **add)
{ return (HA_ERR_WRONG_COMMAND); }
+
+/**
+ Second and last phase of in-place add index.
+ Commit or rollback pending new indexes.
+
+ @param add Context of handler specific information from add_index().
+ @param commit If true, commit. If false, rollback index changes.
+
+ @note This function is called with exclusive metadata lock.
+*/
+ virtual int final_add_index(handler_add_index *add, bool commit)
+ { return (HA_ERR_WRONG_COMMAND); }
+
virtual int prepare_drop_index(TABLE *table_arg, uint *key_num,
uint num_of_keys)
{ return (HA_ERR_WRONG_COMMAND); }
@@ -2411,7 +2500,10 @@ private:
upon the table.
*/
virtual int repair(THD* thd, HA_CHECK_OPT* check_opt)
- { return HA_ADMIN_NOT_IMPLEMENTED; }
+ {
+ DBUG_ASSERT(!(ha_table_flags() & HA_CAN_REPAIR));
+ return HA_ADMIN_NOT_IMPLEMENTED;
+ }
virtual void start_bulk_insert(ha_rows rows) {}
virtual int end_bulk_insert() { return 0; }
virtual int index_read(uchar * buf, const uchar * key, uint key_len,
@@ -2440,16 +2532,34 @@ private:
This is called to delete all rows in a table
If the handler don't support this, then this function will
return HA_ERR_WRONG_COMMAND and MySQL will delete the rows one
- by one. It should reset auto_increment if
- thd->lex->sql_command == SQLCOM_TRUNCATE.
+ by one.
*/
virtual int delete_all_rows()
{ return (my_errno=HA_ERR_WRONG_COMMAND); }
/**
+ Quickly remove all rows from a table.
+
+ @remark This method is responsible for implementing MySQL's TRUNCATE
+ TABLE statement, which is a DDL operation. As such, a engine
+ can bypass certain integrity checks and in some cases avoid
+ fine-grained locking (e.g. row locks) which would normally be
+ required for a DELETE statement.
+
+ @remark Typically, truncate is not used if it can result in integrity
+ violation. For example, truncate is not used when a foreign
+ key references the table, but it might be used if foreign key
+ checks are disabled.
+
+ @remark Engine is responsible for resetting the auto-increment counter.
+
+ @remark The table is locked in exclusive mode.
+ */
+ virtual int truncate()
+ { return HA_ERR_WRONG_COMMAND; }
+ /**
Reset the auto-increment counter to the given value, i.e. the next row
- inserted will get the given value. This is called e.g. after TRUNCATE
- is emulated by doing a 'DELETE FROM t'. HA_ERR_WRONG_COMMAND is
- returned by storage engines that don't support this operation.
+ inserted will get the given value. HA_ERR_WRONG_COMMAND is returned by
+ storage engines that don't support this operation.
*/
virtual int reset_auto_increment(ulonglong value)
{ return HA_ERR_WRONG_COMMAND; }
diff --git a/sql/hostname.cc b/sql/hostname.cc
index 5311d9ada73..d34df68587c 100644
--- a/sql/hostname.cc
+++ b/sql/hostname.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -366,41 +366,35 @@ bool ip_to_hostname(struct sockaddr_storage *ip_storage,
err_code= vio_getnameinfo(ip, hostname_buffer, NI_MAXHOST, NULL, 0,
NI_NAMEREQD);
- if (err_code == EAI_NONAME)
+ if (err_code)
{
- /*
- There is no reverse address mapping for the IP address. A host name
- can not be resolved.
- */
+ // NOTE: gai_strerror() returns a string ending by a dot.
- DBUG_PRINT("error", ("IP address '%s' could not be resolved: "
- "no reverse address mapping.",
- (const char *) ip_key));
+ DBUG_PRINT("error", ("IP address '%s' could not be resolved: %s",
+ (const char *) ip_key,
+ (const char *) gai_strerror(err_code)));
- sql_print_warning("IP address '%s' could not be resolved: "
- "no reverse address mapping.",
- (const char *) ip_key);
+ sql_print_warning("IP address '%s' could not be resolved: %s",
+ (const char *) ip_key,
+ (const char *) gai_strerror(err_code));
- err_status= add_hostname(ip_key, NULL);
+ if (vio_is_no_name_error(err_code))
+ {
+ /*
+ The no-name error means that there is no reverse address mapping
+ for the IP address. A host name can not be resolved.
- *hostname= NULL;
- *connect_errors= 0; /* New IP added to the cache. */
+ If it is not the no-name error, we should not cache the hostname
+ (or rather its absence), because the failure might be transient.
+ */
- DBUG_RETURN(err_status);
- }
- else if (err_code)
- {
- DBUG_PRINT("error", ("IP address '%s' could not be resolved: "
- "getnameinfo() returned %d.",
- (const char *) ip_key,
- (int) err_code));
+ add_hostname(ip_key, NULL);
- sql_print_warning("IP address '%s' could not be resolved: "
- "getnameinfo() returned error (code: %d).",
- (const char *) ip_key,
- (int) err_code);
+ *hostname= NULL;
+ *connect_errors= 0; /* New IP added to the cache. */
+ }
- DBUG_RETURN(TRUE);
+ DBUG_RETURN(FALSE);
}
DBUG_PRINT("info", ("IP '%s' resolved to '%s'.",
diff --git a/sql/item.cc b/sql/item.cc
index f2e9e8202c5..41228e532d5 100644
--- a/sql/item.cc
+++ b/sql/item.cc
@@ -230,8 +230,6 @@ bool Item::val_bool()
*/
String *Item::val_str_ascii(String *str)
{
- DBUG_ASSERT(fixed == 1);
-
if (!(collation.collation->state & MY_CS_NONASCII))
return val_str(str);
@@ -588,7 +586,7 @@ void Item::rename(char *new_name)
Item* Item::transform(Item_transformer transformer, uchar *arg)
{
- DBUG_ASSERT(!current_thd->is_stmt_prepare());
+ DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
return (this->*transformer)(arg);
}
@@ -1061,8 +1059,12 @@ bool Item::get_date(MYSQL_TIME *ltime,uint fuzzydate)
}
else
{
- longlong value= val_int();
int was_cut;
+ longlong value= val_int();
+
+ if (null_value)
+ goto err;
+
if (number_to_datetime(value, ltime, fuzzydate, &was_cut) == LL(-1))
{
char buff[22], *end;
@@ -1123,7 +1125,9 @@ int Item::save_in_field_no_warnings(Field *field, bool no_conversions)
ulonglong sql_mode= thd->variables.sql_mode;
thd->variables.sql_mode&= ~(MODE_NO_ZERO_IN_DATE | MODE_NO_ZERO_DATE);
thd->count_cuted_fields= CHECK_FIELD_IGNORE;
+
res= save_in_field(field, no_conversions);
+
thd->count_cuted_fields= tmp;
dbug_tmp_restore_column_map(table->write_set, old_map);
thd->variables.sql_mode= sql_mode;
@@ -1806,7 +1810,8 @@ bool agg_item_collations(DTCollation &c, const char *fname,
}
/* If all arguments where numbers, reset to @@collation_connection */
- if (c.derivation == DERIVATION_NUMERIC)
+ if (flags & MY_COLL_ALLOW_NUMERIC_CONV &&
+ c.derivation == DERIVATION_NUMERIC)
c.set(Item::default_charset(), DERIVATION_COERCIBLE, MY_REPERTOIRE_NUMERIC);
return FALSE;
@@ -1840,15 +1845,17 @@ bool agg_item_set_converter(DTCollation &coll, const char *fname,
}
THD *thd= current_thd;
- Query_arena *arena, backup;
bool res= FALSE;
uint i;
+
/*
In case we're in statement prepare, create conversion item
in its memory: it will be reused on each execute.
*/
- arena= thd->is_stmt_prepare() ? thd->activate_stmt_arena_if_needed(&backup)
- : NULL;
+ Query_arena backup;
+ Query_arena *arena= thd->stmt_arena->is_stmt_prepare() ?
+ thd->activate_stmt_arena_if_needed(&backup) :
+ NULL;
for (i= 0, arg= args; i < nargs; i++, arg+= item_sep)
{
@@ -1879,6 +1886,7 @@ bool agg_item_set_converter(DTCollation &coll, const char *fname,
if (!(conv= (*arg)->safe_charset_converter(coll.collation)) &&
((*arg)->collation.repertoire == MY_REPERTOIRE_ASCII))
+#if 0
{
/*
We should disable const subselect item evaluation because
@@ -1892,6 +1900,8 @@ bool agg_item_set_converter(DTCollation &coll, const char *fname,
thd->lex->view_prepare_mode) ? FALSE : TRUE;
conv= new Item_func_conv_charset(*arg, coll.collation, resolve_const);
}
+#endif
+ conv= new Item_func_conv_charset(*arg, coll.collation, 1);
if (!conv)
{
@@ -1917,15 +1927,16 @@ bool agg_item_set_converter(DTCollation &coll, const char *fname,
been created in prepare. In this case register the change for
rollback.
*/
- if (thd->is_stmt_prepare())
+ if (thd->stmt_arena->is_stmt_prepare())
*arg= conv;
else
thd->change_item_tree(arg, conv);
- /*
- We do not check conv->fixed, because Item_func_conv_charset which can
- be return by safe_charset_converter can't be fixed at creation
- */
- conv->fix_fields(thd, arg);
+
+ if (conv->fix_fields(thd, arg))
+ {
+ res= TRUE;
+ break; // we cannot return here, we need to restore "arena".
+ }
}
if (arena)
thd->restore_active_arena(arena, &backup);
@@ -2079,6 +2090,61 @@ Item_field::Item_field(THD *thd, Item_field *item)
collation.set(DERIVATION_IMPLICIT);
}
+
+/**
+ Calculate the max column length not taking into account the
+ limitations over integer types.
+
+ When storing data into fields the server currently just ignores the
+ limits specified on integer types, e.g. 1234 can safely be stored in
+ an int(2) and will not cause an error.
+ Thus when creating temporary tables and doing transformations
+ we must adjust the maximum field length to reflect this fact.
+ We take the un-restricted maximum length and adjust it similarly to
+ how the declared length is adjusted wrt unsignedness etc.
+ TODO: this all needs to go when we disable storing 1234 in int(2).
+
+ @param field_par Original field the use to calculate the lengths
+ @param max_length Item's calculated explicit max length
+ @return The adjusted max length
+*/
+
+inline static uint32
+adjust_max_effective_column_length(Field *field_par, uint32 max_length)
+{
+ uint32 new_max_length= field_par->max_display_length();
+ uint32 sign_length= (field_par->flags & UNSIGNED_FLAG) ? 0 : 1;
+
+ switch (field_par->type())
+ {
+ case MYSQL_TYPE_INT24:
+ /*
+ Compensate for MAX_MEDIUMINT_WIDTH being 1 too long (8)
+ compared to the actual number of digits that can fit into
+ the column.
+ */
+ new_max_length+= 1;
+ /* fall through */
+ case MYSQL_TYPE_LONG:
+ case MYSQL_TYPE_TINY:
+ case MYSQL_TYPE_SHORT:
+
+ /* Take out the sign and add a conditional sign */
+ new_max_length= new_max_length - 1 + sign_length;
+ break;
+
+ /* BINGINT is always 20 no matter the sign */
+ case MYSQL_TYPE_LONGLONG:
+ /* make gcc happy */
+ default:
+ break;
+ }
+
+ /* Adjust only if the actual precision based one is bigger than specified */
+ return new_max_length > max_length ? new_max_length : max_length;
+}
+
+
void Item_field::set_field(Field *field_par)
{
field=result_field=field_par; // for easy coding with fields
@@ -2092,6 +2158,9 @@ void Item_field::set_field(Field *field_par)
collation.set(field_par->charset(), field_par->derivation(),
field_par->repertoire());
fix_char_length(field_par->char_length());
+
+ max_length= adjust_max_effective_column_length(field_par, max_length);
+
fixed= 1;
if (field->table->s->tmp_table == SYSTEM_TMP_TABLE)
any_privileges= 0;
@@ -2625,7 +2694,9 @@ my_decimal *Item_float::val_decimal(my_decimal *decimal_value)
void Item_string::print(String *str, enum_query_type query_type)
{
- if (query_type == QT_ORDINARY && is_cs_specified())
+ const bool print_introducer=
+ !(query_type & QT_WITHOUT_INTRODUCERS) && is_cs_specified();
+ if (print_introducer)
{
str->append('_');
str->append(collation.collation->csname);
@@ -2633,27 +2704,52 @@ void Item_string::print(String *str, enum_query_type query_type)
str->append('\'');
- if (query_type == QT_ORDINARY ||
- my_charset_same(str_value.charset(), system_charset_info))
+ if (query_type & QT_TO_SYSTEM_CHARSET)
{
- str_value.print(str);
- }
- else
- {
- THD *thd= current_thd;
- LEX_STRING utf8_lex_str;
+ if (print_introducer)
+ {
+ /*
+ Because we wrote an introducer, we must print str_value in its
+ charset, and the resulting bytes must not be changed until they
+ reach the end client.
+ But the caller is asking for system_charset_info, and may later
+ convert into character_set_results. That means two conversions: we
+ must ensure that they don't change our printed bytes.
+ So we print str_value in the least common denominator of the three
+ charsets involved: ASCII. Non-ASCII characters are printed as \xFF
+ sequences (which is ASCII too). This way, our bytes will not be
+ changed.
+ */
+ ErrConvString tmp(str_value.ptr(), str_value.length(), &my_charset_bin);
+ str->append(tmp.ptr());
+ }
+ else
+ {
+ if (my_charset_same(str_value.charset(), system_charset_info))
+ str_value.print(str); // already in system_charset_info
+ else // need to convert
+ {
+ THD *thd= current_thd;
+ LEX_STRING utf8_lex_str;
- thd->convert_string(&utf8_lex_str,
- system_charset_info,
- str_value.c_ptr_safe(),
- str_value.length(),
- str_value.charset());
+ thd->convert_string(&utf8_lex_str,
+ system_charset_info,
+ str_value.c_ptr_safe(),
+ str_value.length(),
+ str_value.charset());
- String utf8_str(utf8_lex_str.str,
- utf8_lex_str.length,
- system_charset_info);
+ String utf8_str(utf8_lex_str.str,
+ utf8_lex_str.length,
+ system_charset_info);
- utf8_str.print(str);
+ utf8_str.print(str);
+ }
+ }
+ }
+ else
+ {
+ // Caller wants a result in the charset of str_value.
+ str_value.print(str);
}
str->append('\'');
@@ -2969,6 +3065,16 @@ bool Item_param::set_longdata(const char *str, ulong length)
(here), and first have to concatenate all pieces together,
write query to the binary log and only then perform conversion.
*/
+ if (str_value.length() + length > max_long_data_size)
+ {
+ my_message(ER_UNKNOWN_ERROR,
+ "Parameter of prepared statement which is set through "
+ "mysql_send_long_data() is longer than "
+ "'max_long_data_size' bytes",
+ MYF(0));
+ DBUG_RETURN(true);
+ }
+
if (str_value.append(str, length, &my_charset_bin))
DBUG_RETURN(TRUE);
state= LONG_DATA_VALUE;
@@ -3559,19 +3665,16 @@ Item_param::set_value(THD *thd, sp_rcontext *ctx, Item **it)
str_value.charset());
collation.set(str_value.charset(), DERIVATION_COERCIBLE);
decimals= 0;
- param_type= MYSQL_TYPE_STRING;
break;
}
case REAL_RESULT:
set_double(arg->val_real());
- param_type= MYSQL_TYPE_DOUBLE;
break;
case INT_RESULT:
set_int(arg->val_int(), arg->max_length);
- param_type= MYSQL_TYPE_LONG;
break;
case DECIMAL_RESULT:
@@ -3583,8 +3686,6 @@ Item_param::set_value(THD *thd, sp_rcontext *ctx, Item **it)
return TRUE;
set_decimal(dv);
- param_type= MYSQL_TYPE_NEWDECIMAL;
-
break;
}
@@ -3616,6 +3717,7 @@ void
Item_param::set_out_param_info(Send_field *info)
{
m_out_param_info= info;
+ param_type= m_out_param_info->type;
}
@@ -3661,6 +3763,7 @@ void Item_param::make_field(Send_field *field)
field->org_table_name= m_out_param_info->org_table_name;
field->col_name= m_out_param_info->col_name;
field->org_col_name= m_out_param_info->org_col_name;
+
field->length= m_out_param_info->length;
field->charsetnr= m_out_param_info->charsetnr;
field->flags= m_out_param_info->flags;
@@ -5679,17 +5782,43 @@ static uint nr_of_decimals(const char *str, const char *end)
break;
}
decimal_point= str;
- for (; my_isdigit(system_charset_info, *str) ; str++)
+ for ( ; str < end && my_isdigit(system_charset_info, *str) ; str++)
;
- if (*str == 'e' || *str == 'E')
+ if (str < end && (*str == 'e' || *str == 'E'))
return NOT_FIXED_DEC;
+ /*
+ QQ:
+ The number of decimal digist in fact should be (str - decimal_point - 1).
+ But it seems the result of nr_of_decimals() is never used!
+
+ In case of 'e' and 'E' nr_of_decimals returns NOT_FIXED_DEC.
+ In case if there is no 'e' or 'E' parser code in sql_yacc.yy
+ never calls Item_float::Item_float() - it creates Item_decimal instead.
+
+ The only piece of code where we call Item_float::Item_float(str, len)
+ without having 'e' or 'E' is item_xmlfunc.cc, but this Item_float
+ never appears in metadata itself. Changing the code to return
+ (str - decimal_point - 1) does not make any changes in the test results.
+
+ This should be addressed somehow.
+ Looks like a reminder from before real DECIMAL times.
+ */
return (uint) (str - decimal_point);
}
/**
- This function is only called during parsing. We will signal an error if
- value is not a true double value (overflow)
+ This function is only called during parsing:
+ - when parsing SQL query from sql_yacc.yy
+ - when parsing XPath query from item_xmlfunc.cc
+ We will signal an error if value is not a true double value (overflow):
+ eng: Illegal %s '%-.192s' value found during parsing
+
+ Note: the string is NOT null terminated when called from item_xmlfunc.cc,
+ so this->name will contain some SQL query tail behind the "length" bytes.
+ This is Ok for now, as this Item is never seen in SHOW,
+ or EXPLAIN, or anywhere else in metadata.
+ Item->name should be fixed to use LEX_STRING eventually.
*/
Item_float::Item_float(const char *str_arg, uint length)
@@ -5700,12 +5829,9 @@ Item_float::Item_float(const char *str_arg, uint length)
&error);
if (error)
{
- /*
- Note that we depend on that str_arg is null terminated, which is true
- when we are in the parser
- */
- DBUG_ASSERT(str_arg[length] == 0);
- my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", (char*) str_arg);
+ char tmp[NAME_LEN + 1];
+ my_snprintf(tmp, sizeof(tmp), "%.*s", length, str_arg);
+ my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "double", tmp);
}
presentation= name=(char*) str_arg;
decimals=(uint8) nr_of_decimals(str_arg, str_arg+length);
@@ -5977,6 +6103,10 @@ bool Item::send(Protocol *protocol, String *buffer)
String *res;
if ((res=val_str(buffer)))
result= protocol->store(res->ptr(),res->length(),res->charset());
+ else
+ {
+ DBUG_ASSERT(null_value);
+ }
break;
}
case MYSQL_TYPE_TINY:
@@ -6626,7 +6756,7 @@ void Item_ref::print(String *str, enum_query_type query_type)
{
THD *thd= current_thd;
append_identifier(thd, str, (*ref)->real_item()->name,
- (*ref)->real_item()->name_length);
+ strlen((*ref)->real_item()->name));
}
else
(*ref)->print(str, query_type);
@@ -7574,7 +7704,7 @@ int Item_default_value::save_in_field(Field *field_arg, bool no_conversions)
Item *Item_default_value::transform(Item_transformer transformer, uchar *args)
{
- DBUG_ASSERT(!current_thd->is_stmt_prepare());
+ DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
/*
If the value of arg is NULL, then this object represents a constant,
@@ -7740,8 +7870,26 @@ bool Item_trigger_field::set_value(THD *thd, sp_rcontext * /*ctx*/, Item **it)
{
Item *item= sp_prepare_func_item(thd, it);
- return (!item || (!fixed && fix_fields(thd, 0)) ||
- (item->save_in_field(field, 0) < 0));
+ if (!item)
+ return true;
+
+ if (!fixed)
+ {
+ if (fix_fields(thd, NULL))
+ return true;
+ }
+
+ // NOTE: field->table->copy_blobs should be false here, but let's
+ // remember the value at runtime to avoid subtle bugs.
+ bool copy_blobs_saved= field->table->copy_blobs;
+
+ field->table->copy_blobs= true;
+
+ int err_code= item->save_in_field(field, 0);
+
+ field->table->copy_blobs= copy_blobs_saved;
+
+ return err_code < 0;
}
@@ -8022,9 +8170,10 @@ Item_cache* Item_cache::get_cache(const Item *item, const Item_result type)
case DECIMAL_RESULT:
return new Item_cache_decimal();
case STRING_RESULT:
- if (item->field_type() == MYSQL_TYPE_DATE ||
- item->field_type() == MYSQL_TYPE_DATETIME ||
- item->field_type() == MYSQL_TYPE_TIME)
+ /* Not all functions that return DATE/TIME are actually DATE/TIME funcs. */
+ if ((item->is_datetime() ||
+ item->field_type() == MYSQL_TYPE_TIME) &&
+ (const_cast<Item*>(item))->result_as_longlong())
return new Item_cache_datetime(item->field_type());
return new Item_cache_str(item);
case ROW_RESULT:
@@ -8081,7 +8230,7 @@ String *Item_cache_int::val_str(String *str)
DBUG_ASSERT(fixed == 1);
if (!has_value())
return NULL;
- str->set(value, default_charset());
+ str->set_int(value, unsigned_flag, default_charset());
return str;
}
@@ -8114,16 +8263,43 @@ longlong Item_cache_int::val_int()
bool Item_cache_datetime::cache_value_int()
{
if (!example)
- return FALSE;
+ return false;
- value_cached= TRUE;
+ value_cached= true;
// Mark cached string value obsolete
- str_value_cached= FALSE;
- /* Assume here that the underlying item will do correct conversion.*/
- int_value= example->val_int_result();
+ str_value_cached= false;
+
+ MYSQL_TIME ltime;
+ const bool eval_error=
+ (field_type() == MYSQL_TYPE_TIME) ?
+ example->get_time(&ltime) :
+ example->get_date(&ltime, TIME_FUZZY_DATE);
+
+ if (eval_error)
+ int_value= 0;
+ else
+ {
+ switch(field_type())
+ {
+ case MYSQL_TYPE_DATETIME:
+ case MYSQL_TYPE_TIMESTAMP:
+ int_value= TIME_to_ulonglong_datetime(&ltime);
+ break;
+ case MYSQL_TYPE_TIME:
+ int_value= TIME_to_ulonglong_time(&ltime);
+ break;
+ default:
+ int_value= TIME_to_ulonglong_date(&ltime);
+ break;
+ }
+ if (ltime.neg)
+ int_value= -int_value;
+ }
+
null_value= example->null_value;
unsigned_flag= example->unsigned_flag;
- return TRUE;
+
+ return true;
}
@@ -8158,9 +8334,19 @@ void Item_cache_datetime::store(Item *item, longlong val_arg)
}
+void Item_cache_datetime::store(Item *item)
+{
+ Item_cache::store(item);
+ str_value_cached= FALSE;
+}
+
String *Item_cache_datetime::val_str(String *str)
{
DBUG_ASSERT(fixed == 1);
+
+ if ((value_cached || str_value_cached) && null_value)
+ return NULL;
+
if (!str_value_cached)
{
/*
@@ -8174,6 +8360,8 @@ String *Item_cache_datetime::val_str(String *str)
if (value_cached)
{
MYSQL_TIME ltime;
+ /* Return NULL in case of OOM/conversion error. */
+ null_value= TRUE;
if (str_value.alloc(MAX_DATE_STRING_REP_LENGTH))
return NULL;
if (cached_field_type == MYSQL_TYPE_TIME)
@@ -8196,13 +8384,14 @@ String *Item_cache_datetime::val_str(String *str)
{
int was_cut;
longlong res;
- res= number_to_datetime(val_int(), &ltime, TIME_FUZZY_DATE, &was_cut);
+ res= number_to_datetime(int_value, &ltime, TIME_FUZZY_DATE, &was_cut);
if (res == -1)
return NULL;
}
str_value.length(my_TIME_to_str(&ltime,
const_cast<char*>(str_value.ptr())));
str_value_cached= TRUE;
+ null_value= FALSE;
}
else if (!cache_value())
return NULL;
@@ -8223,7 +8412,7 @@ my_decimal *Item_cache_datetime::val_decimal(my_decimal *decimal_val)
double Item_cache_datetime::val_real()
{
DBUG_ASSERT(fixed == 1);
- if (!value_cached && !cache_value_int())
+ if ((!value_cached && !cache_value_int()) || null_value)
return 0.0;
return (double) int_value;
}
@@ -8231,7 +8420,7 @@ double Item_cache_datetime::val_real()
longlong Item_cache_datetime::val_int()
{
DBUG_ASSERT(fixed == 1);
- if (!value_cached && !cache_value_int())
+ if ((!value_cached && !cache_value_int()) || null_value)
return 0;
return int_value;
}
diff --git a/sql/item.h b/sql/item.h
index 26ee946f147..b13438b248f 100644
--- a/sql/item.h
+++ b/sql/item.h
@@ -1,7 +1,7 @@
#ifndef SQL_ITEM_INCLUDED
#define SQL_ITEM_INCLUDED
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -70,6 +70,8 @@ char_to_byte_length_safe(uint32 char_length_arg, uint32 mbmaxlen_arg)
(i.e. constant).
MY_COLL_ALLOW_CONV - allow any kind of conversion
(combination of the above two)
+ MY_COLL_ALLOW_NUMERIC_CONV - if all items were numbers, convert to
+ @@character_set_connection
MY_COLL_DISALLOW_NONE - don't allow return DERIVATION_NONE
(e.g. when aggregating for comparison)
MY_COLL_CMP_CONV - combination of MY_COLL_ALLOW_CONV
@@ -79,6 +81,7 @@ char_to_byte_length_safe(uint32 char_length_arg, uint32 mbmaxlen_arg)
#define MY_COLL_ALLOW_SUPERSET_CONV 1
#define MY_COLL_ALLOW_COERCIBLE_CONV 2
#define MY_COLL_DISALLOW_NONE 4
+#define MY_COLL_ALLOW_NUMERIC_CONV 8
#define MY_COLL_ALLOW_CONV (MY_COLL_ALLOW_SUPERSET_CONV | MY_COLL_ALLOW_COERCIBLE_CONV)
#define MY_COLL_CMP_CONV (MY_COLL_ALLOW_CONV | MY_COLL_DISALLOW_NONE)
@@ -568,6 +571,10 @@ public:
*/
Item *next;
uint32 max_length; /* Maximum length, in bytes */
+ /*
+ TODO: convert name and name_length fields into String to keep them in sync
+ (see bug #11829681/60295 etc).
+ */
uint name_length; /* Length of name */
int8 marker;
uint8 decimals;
@@ -1188,11 +1195,11 @@ public:
virtual bool set_no_const_sub(uchar *arg) { return FALSE; }
virtual Item *replace_equal_field(uchar * arg) { return this; }
/*
- Check if an expression value depends on the current timezone. Used by
- partitioning code to reject timezone-dependent expressions in a
- (sub)partitioning function.
+ Check if an expression value has allowed arguments, like DATE/DATETIME
+ for date functions. Also used by partitioning code to reject
+ timezone-dependent expressions in a (sub)partitioning function.
*/
- virtual bool is_timezone_dependent_processor(uchar *bool_arg)
+ virtual bool check_valid_arguments_processor(uchar *bool_arg)
{
return FALSE;
}
@@ -1353,7 +1360,7 @@ public:
maybe_null= 1;
}
else
- max_length= max_result_length;
+ max_length= (uint32) max_result_length;
}
void fix_length_and_charset_datetime(uint32 max_char_length_arg)
{
@@ -1708,7 +1715,8 @@ agg_item_charsets_for_string_result(DTCollation &c, const char *name,
int item_sep= 1)
{
uint flags= MY_COLL_ALLOW_SUPERSET_CONV |
- MY_COLL_ALLOW_COERCIBLE_CONV;
+ MY_COLL_ALLOW_COERCIBLE_CONV |
+ MY_COLL_ALLOW_NUMERIC_CONV;
return agg_item_charsets(c, name, items, nitems, flags, item_sep);
}
inline bool
@@ -1721,6 +1729,19 @@ agg_item_charsets_for_comparison(DTCollation &c, const char *name,
MY_COLL_DISALLOW_NONE;
return agg_item_charsets(c, name, items, nitems, flags, item_sep);
}
+inline bool
+agg_item_charsets_for_string_result_with_comparison(DTCollation &c,
+ const char *name,
+ Item **items, uint nitems,
+ int item_sep= 1)
+{
+ uint flags= MY_COLL_ALLOW_SUPERSET_CONV |
+ MY_COLL_ALLOW_COERCIBLE_CONV |
+ MY_COLL_ALLOW_NUMERIC_CONV |
+ MY_COLL_DISALLOW_NONE;
+ return agg_item_charsets(c, name, items, nitems, flags, item_sep);
+}
+
class Item_num: public Item_basic_constant
{
@@ -1816,6 +1837,8 @@ public:
String *val_str(String *str) { return field->val_str(str); }
my_decimal *val_decimal(my_decimal *dec) { return field->val_decimal(dec); }
void make_field(Send_field *tmp_field);
+ CHARSET_INFO *charset_for_protocol(void) const
+ { return field->charset_for_protocol(); }
};
@@ -2785,7 +2808,7 @@ public:
DBUG_ASSERT(fixed);
return (*ref)->get_time(ltime);
}
- virtual bool basic_const_item() const { return (*ref)->basic_const_item(); }
+ virtual bool basic_const_item() const { return ref && (*ref)->basic_const_item(); }
bool is_outer_field() const
{
DBUG_ASSERT(fixed);
@@ -3564,11 +3587,10 @@ class Item_cache: public Item_basic_constant
protected:
Item *example;
table_map used_table_map;
- /*
- Field that this object will get value from. This is set/used by
+ /**
+ Field that this object will get value from. This is used by
index-based subquery engines to detect and remove the equality injected
by IN->EXISTS transformation.
- For all other uses of Item_cache, cached_field doesn't matter.
*/
Field *cached_field;
enum enum_field_types cached_field_type;
@@ -3642,6 +3664,14 @@ public:
{
return (value_cached || cache_value()) && !null_value;
}
+
+ /**
+ If this item caches a field value, return pointer to underlying field.
+
+ @return Pointer to field, or NULL if this is not a cache for a field value.
+ */
+ Field* field() { return cached_field; }
+
virtual void store(Item *item);
virtual bool cache_value()= 0;
bool basic_const_item() const
@@ -3809,7 +3839,7 @@ class Item_cache_datetime: public Item_cache
{
protected:
String str_value;
- ulonglong int_value;
+ longlong int_value;
bool str_value_cached;
public:
Item_cache_datetime(enum_field_types field_type_arg):
@@ -3818,8 +3848,8 @@ public:
cmp_context= STRING_RESULT;
}
- virtual void store(Item *item) { Item_cache::store(item); }
void store(Item *item, longlong val_arg);
+ void store(Item *item);
double val_real();
longlong val_int();
String* val_str(String *str);
diff --git a/sql/item_cmpfunc.cc b/sql/item_cmpfunc.cc
index e8cf6e97a28..b0c2dac7b74 100644
--- a/sql/item_cmpfunc.cc
+++ b/sql/item_cmpfunc.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -403,7 +403,7 @@ static bool convert_constant_item(THD *thd, Item_field *field_item,
Field *field= field_item->field;
int result= 0;
- if (!(*item)->with_subselect && (*item)->const_item())
+ if ((*item)->const_item())
{
TABLE *table= field->table;
ulonglong orig_sql_mode= thd->variables.sql_mode;
@@ -499,7 +499,7 @@ void Item_bool_func2::fix_length_and_dec()
}
thd= current_thd;
- if (!thd->is_context_analysis_only())
+ if (!thd->lex->is_ps_or_view_context_analysis())
{
if (args[0]->real_item()->type() == FIELD_ITEM)
{
@@ -803,7 +803,7 @@ Arg_comparator::can_compare_as_dates(Item *a, Item *b, ulonglong *const_value)
confuse storage engines since in context analysis mode tables
aren't locked.
*/
- if (!thd->is_context_analysis_only() &&
+ if (!thd->lex->is_ps_or_view_context_analysis() &&
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))
@@ -923,7 +923,7 @@ int Arg_comparator::set_cmp_func(Item_result_field *owner_arg,
*/
Query_arena backup;
Query_arena *save_arena= thd->switch_to_arena_for_cached_items(&backup);
- Item_cache_int *cache= new Item_cache_int();
+ Item_cache_int *cache= new Item_cache_int(MYSQL_TYPE_DATETIME);
if (save_arena)
thd->set_query_arena(save_arena);
@@ -1044,7 +1044,7 @@ Item** Arg_comparator::cache_converted_constant(THD *thd_arg, Item **value,
Item_result type)
{
/* Don't need cache if doing context analysis only. */
- if (!thd_arg->is_context_analysis_only() &&
+ if (!thd->lex->is_ps_or_view_context_analysis() &&
(*value)->const_item() && type != (*value)->result_type())
{
Item_cache *cache= Item_cache::get_cache(*value, type);
@@ -1221,9 +1221,12 @@ get_year_value(THD *thd, Item ***item_arg, Item **cache_arg,
value of 2000.
*/
Item *real_item= item->real_item();
- if (!(real_item->type() == Item::FIELD_ITEM &&
- ((Item_field *)real_item)->field->type() == MYSQL_TYPE_YEAR &&
- ((Item_field *)real_item)->field->field_length == 4))
+ Field *field= NULL;
+ if (real_item->type() == Item::FIELD_ITEM)
+ field= ((Item_field *)real_item)->field;
+ else if (real_item->type() == Item::CACHE_ITEM)
+ field= ((Item_cache *)real_item)->field();
+ if (!(field && field->type() == MYSQL_TYPE_YEAR && field->field_length == 4))
{
if (value < 70)
value+= 100;
@@ -2211,7 +2214,6 @@ void Item_func_interval::fix_length_and_dec()
if (dec != &range->dec)
{
range->dec= *dec;
- range->dec.fix_buffer_pointer();
}
}
else
@@ -2763,7 +2765,7 @@ Item_func_if::fix_length_and_dec()
if (null1)
{
cached_result_type= arg2_type;
- collation.set(args[2]->collation.collation);
+ collation.set(args[2]->collation);
cached_field_type= args[2]->field_type();
max_length= args[2]->max_length;
return;
@@ -2772,7 +2774,7 @@ Item_func_if::fix_length_and_dec()
if (null2)
{
cached_result_type= arg1_type;
- collation.set(args[1]->collation.collation);
+ collation.set(args[1]->collation);
cached_field_type= args[1]->field_type();
max_length= args[1]->max_length;
return;
@@ -3154,6 +3156,14 @@ void Item_func_case::fix_length_and_dec()
{
if (agg_arg_charsets_for_string_result(collation, agg, nagg))
return;
+ /*
+ Copy all THEN and ELSE items back to args[] array.
+ Some of the items might have been changed to Item_func_conv_charset.
+ */
+ for (nagg= 0 ; nagg < ncases / 2 ; nagg++)
+ args[nagg * 2 + 1]= agg[nagg];
+ if (else_expr_num != -1)
+ args[else_expr_num]= agg[nagg++];
}
else
collation.set_numeric();
@@ -3169,20 +3179,53 @@ void Item_func_case::fix_length_and_dec()
agg[0]= args[first_expr_num];
left_result_type= agg[0]->result_type();
+ /*
+ As the first expression and WHEN expressions
+ are intermixed in args[] array THEN and ELSE items,
+ extract the first expression and all WHEN expressions into
+ a temporary array, to process them easier.
+ */
for (nagg= 0; nagg < ncases/2 ; nagg++)
agg[nagg+1]= args[nagg*2];
nagg++;
if (!(found_types= collect_cmp_types(agg, nagg)))
return;
- if (with_sum_func || current_thd->lex->current_select->group_list.elements)
+ if (found_types & (1 << STRING_RESULT))
{
/*
- See TODO commentary in the setup_copy_fields function:
- item in a group may be wrapped with an Item_copy_string item.
- That item has a STRING_RESULT result type, so we need
- to take this type into account.
+ If we'll do string comparison, we also need to aggregate
+ character set and collation for first/WHEN items and
+ install converters for some of them to cmp_collation when necessary.
+ This is done because cmp_item compatators cannot compare
+ strings in two different character sets.
+ Some examples when we install converters:
+
+ 1. Converter installed for the first expression:
+
+ CASE latin1_item WHEN utf16_item THEN ... END
+
+ is replaced to:
+
+ CASE CONVERT(latin1_item USING utf16) WHEN utf16_item THEN ... END
+
+ 2. Converter installed for the left WHEN item:
+
+ CASE utf16_item WHEN latin1_item THEN ... END
+
+ is replaced to:
+
+ CASE utf16_item WHEN CONVERT(latin1_item USING utf16) THEN ... END
*/
- found_types |= (1 << item_cmp_type(left_result_type, STRING_RESULT));
+ if (agg_arg_charsets_for_comparison(cmp_collation, agg, nagg))
+ return;
+ /*
+ Now copy first expression and all WHEN expressions back to args[]
+ arrray, because some of the items might have been changed to converters
+ (e.g. Item_func_conv_charset, or Item_string for constants).
+ */
+ args[first_expr_num]= agg[0];
+ for (nagg= 0; nagg < ncases / 2; nagg++)
+ args[nagg * 2]= agg[nagg + 1];
}
for (i= 0; i <= (uint)DECIMAL_RESULT; i++)
@@ -3190,9 +3233,6 @@ void Item_func_case::fix_length_and_dec()
if (found_types & (1 << i) && !cmp_items[i])
{
DBUG_ASSERT((Item_result)i != ROW_RESULT);
- if ((Item_result)i == STRING_RESULT &&
- agg_arg_charsets_for_comparison(cmp_collation, agg, nagg))
- return;
if (!(cmp_items[i]=
cmp_item::get_comparator((Item_result)i,
cmp_collation.collation)))
@@ -4154,13 +4194,11 @@ void Item_func_in::fix_length_and_dec()
uint j=0;
for (uint i=1 ; i < arg_count ; i++)
{
- if (!args[i]->null_value) // Skip NULL values
- {
- array->set(j,args[i]);
- j++;
- }
- else
- have_null= 1;
+ array->set(j,args[i]);
+ if (!args[i]->null_value) // Skip NULL values
+ j++;
+ else
+ have_null= 1;
}
if ((array->used_count= j))
array->sort();
@@ -4470,7 +4508,7 @@ bool Item_cond::walk(Item_processor processor, bool walk_subquery, uchar *arg)
Item *Item_cond::transform(Item_transformer transformer, uchar *arg)
{
- DBUG_ASSERT(!current_thd->is_stmt_prepare());
+ DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
List_iterator<Item> li(list);
Item *item;
@@ -4878,12 +4916,13 @@ bool Item_func_like::fix_fields(THD *thd, Item **ref)
return TRUE;
}
- if (escape_item->const_item() && !thd->lex->view_prepare_mode)
+ if (escape_item->const_item())
{
/* If we are on execution stage */
String *escape_str= escape_item->val_str(&cmp.value1);
if (escape_str)
{
+ const char *escape_str_ptr= escape_str->ptr();
if (escape_used_in_parsing && (
(((thd->variables.sql_mode & MODE_NO_BACKSLASH_ESCAPES) &&
escape_str->numchars() != 1) ||
@@ -4898,9 +4937,9 @@ bool Item_func_like::fix_fields(THD *thd, Item **ref)
CHARSET_INFO *cs= escape_str->charset();
my_wc_t wc;
int rc= cs->cset->mb_wc(cs, &wc,
- (const uchar*) escape_str->ptr(),
- (const uchar*) escape_str->ptr() +
- escape_str->length());
+ (const uchar*) escape_str_ptr,
+ (const uchar*) escape_str_ptr +
+ escape_str->length());
escape= (int) (rc > 0 ? wc : '\\');
}
else
@@ -4917,13 +4956,13 @@ bool Item_func_like::fix_fields(THD *thd, Item **ref)
{
char ch;
uint errors;
- uint32 cnvlen= copy_and_convert(&ch, 1, cs, escape_str->ptr(),
+ uint32 cnvlen= copy_and_convert(&ch, 1, cs, escape_str_ptr,
escape_str->length(),
escape_str->charset(), &errors);
escape= cnvlen ? ch : '\\';
}
else
- escape= *(escape_str->ptr());
+ escape= escape_str_ptr ? *escape_str_ptr : '\\';
}
}
else
@@ -5780,21 +5819,23 @@ longlong Item_equal::val_int()
return 0;
List_iterator_fast<Item_field> it(fields);
Item *item= const_item ? const_item : it++;
- if ((null_value= item->is_null()))
- return 0;
eval_item->store_value(item);
+ if ((null_value= item->null_value))
+ return 0;
while ((item_field= it++))
{
/* Skip fields of non-const tables. They haven't been read yet */
if (item_field->field->table->const_table)
{
- if ((null_value= item_field->is_null()) || eval_item->cmp(item_field))
+ int res= eval_item->cmp(item_field);
+ if ((null_value= item_field->null_value) || res)
return 0;
}
}
return 1;
}
+
void Item_equal::fix_length_and_dec()
{
Item *item= get_first(NULL);
@@ -5816,7 +5857,7 @@ bool Item_equal::walk(Item_processor processor, bool walk_subquery, uchar *arg)
Item *Item_equal::transform(Item_transformer transformer, uchar *arg)
{
- DBUG_ASSERT(!current_thd->is_stmt_prepare());
+ DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
List_iterator<Item_field> it(fields);
Item *item;
diff --git a/sql/item_cmpfunc.h b/sql/item_cmpfunc.h
index fd136cfbe0d..69b22fd66d5 100644
--- a/sql/item_cmpfunc.h
+++ b/sql/item_cmpfunc.h
@@ -1,7 +1,7 @@
#ifndef ITEM_CMPFUNC_INCLUDED
#define ITEM_CMPFUNC_INCLUDED
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
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
diff --git a/sql/item_create.cc b/sql/item_create.cc
index 6cb45f05efc..d0f1ab54eca 100644
--- a/sql/item_create.cc
+++ b/sql/item_create.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,7 +11,7 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@@ -1330,6 +1330,34 @@ protected:
};
+#ifndef DBUG_OFF
+class Create_func_like_range_min : public Create_func_arg2
+{
+public:
+ virtual Item *create(THD *thd, Item *arg1, Item *arg2);
+
+ static Create_func_like_range_min s_singleton;
+
+protected:
+ Create_func_like_range_min() {}
+ virtual ~Create_func_like_range_min() {}
+};
+
+
+class Create_func_like_range_max : public Create_func_arg2
+{
+public:
+ virtual Item *create(THD *thd, Item *arg1, Item *arg2);
+
+ static Create_func_like_range_max s_singleton;
+
+protected:
+ Create_func_like_range_max() {}
+ virtual ~Create_func_like_range_max() {}
+};
+#endif
+
+
class Create_func_ln : public Create_func_arg1
{
public:
@@ -3836,6 +3864,26 @@ Create_func_length::create_1_arg(THD *thd, Item *arg1)
}
+#ifndef DBUG_OFF
+Create_func_like_range_min Create_func_like_range_min::s_singleton;
+
+Item*
+Create_func_like_range_min::create(THD *thd, Item *arg1, Item *arg2)
+{
+ return new (thd->mem_root) Item_func_like_range_min(arg1, arg2);
+}
+
+
+Create_func_like_range_max Create_func_like_range_max::s_singleton;
+
+Item*
+Create_func_like_range_max::create(THD *thd, Item *arg1, Item *arg2)
+{
+ return new (thd->mem_root) Item_func_like_range_max(arg1, arg2);
+}
+#endif
+
+
Create_func_ln Create_func_ln::s_singleton;
Item*
@@ -4927,6 +4975,10 @@ static Native_func_registry func_array[] =
{ { C_STRING_WITH_LEN("LCASE") }, BUILDER(Create_func_lcase)},
{ { C_STRING_WITH_LEN("LEAST") }, BUILDER(Create_func_least)},
{ { C_STRING_WITH_LEN("LENGTH") }, BUILDER(Create_func_length)},
+#ifndef DBUG_OFF
+ { { C_STRING_WITH_LEN("LIKE_RANGE_MIN") }, BUILDER(Create_func_like_range_min)},
+ { { C_STRING_WITH_LEN("LIKE_RANGE_MAX") }, BUILDER(Create_func_like_range_max)},
+#endif
{ { C_STRING_WITH_LEN("LINEFROMTEXT") }, GEOM_BUILDER(Create_func_geometry_from_text)},
{ { C_STRING_WITH_LEN("LINEFROMWKB") }, GEOM_BUILDER(Create_func_geometry_from_wkb)},
{ { C_STRING_WITH_LEN("LINESTRINGFROMTEXT") }, GEOM_BUILDER(Create_func_geometry_from_text)},
@@ -5166,8 +5218,8 @@ create_func_cast(THD *thd, Item *a, Cast_target cast_type,
decoded_size= strtoul(c_len, NULL, 10);
if (errno != 0)
{
- my_error(ER_TOO_BIG_PRECISION, MYF(0), c_len, a->name,
- DECIMAL_MAX_PRECISION);
+ my_error(ER_TOO_BIG_PRECISION, MYF(0), INT_MAX, a->name,
+ static_cast<ulong>(DECIMAL_MAX_PRECISION));
return NULL;
}
len= decoded_size;
@@ -5180,8 +5232,8 @@ create_func_cast(THD *thd, Item *a, Cast_target cast_type,
decoded_size= strtoul(c_dec, NULL, 10);
if ((errno != 0) || (decoded_size > UINT_MAX))
{
- my_error(ER_TOO_BIG_SCALE, MYF(0), c_dec, a->name,
- DECIMAL_MAX_SCALE);
+ my_error(ER_TOO_BIG_SCALE, MYF(0), INT_MAX, a->name,
+ static_cast<ulong>(DECIMAL_MAX_SCALE));
return NULL;
}
dec= decoded_size;
@@ -5194,14 +5246,14 @@ create_func_cast(THD *thd, Item *a, Cast_target cast_type,
}
if (len > DECIMAL_MAX_PRECISION)
{
- my_error(ER_TOO_BIG_PRECISION, MYF(0), len, a->name,
- DECIMAL_MAX_PRECISION);
+ my_error(ER_TOO_BIG_PRECISION, MYF(0), static_cast<int>(len), a->name,
+ static_cast<ulong>(DECIMAL_MAX_PRECISION));
return 0;
}
if (dec > DECIMAL_MAX_SCALE)
{
my_error(ER_TOO_BIG_SCALE, MYF(0), dec, a->name,
- DECIMAL_MAX_SCALE);
+ static_cast<ulong>(DECIMAL_MAX_SCALE));
return 0;
}
res= new (thd->mem_root) Item_decimal_typecast(a, len, dec);
diff --git a/sql/item_func.cc b/sql/item_func.cc
index fb4883ec393..7eea131e648 100644
--- a/sql/item_func.cc
+++ b/sql/item_func.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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 */
-
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@@ -52,6 +51,8 @@
#include "sp.h"
#include "set_var.h"
#include "debug_sync.h"
+#include <mysql/plugin.h>
+#include <mysql/service_thd_wait.h>
#ifdef NO_EMBEDDED_ACCESS_CHECKS
#define sp_restore_security_context(A,B) while (0) {}
@@ -180,7 +181,14 @@ Item_func::fix_fields(THD *thd, Item **ref)
used_tables_cache= not_null_tables_cache= 0;
const_item_cache=1;
- if (check_stack_overrun(thd, STACK_MIN_SIZE, buff))
+ /*
+ Use stack limit of STACK_MIN_SIZE * 2 since
+ on some platforms a recursive call to fix_fields
+ requires more than STACK_MIN_SIZE bytes (e.g. for
+ MIPS, it takes about 22kB to make one recursive
+ call to Item_func::fix_fields())
+ */
+ if (check_stack_overrun(thd, STACK_MIN_SIZE * 2, buff))
return TRUE; // Fatal error if flag is set!
if (arg_count)
{ // Print purify happy
@@ -311,7 +319,7 @@ void Item_func::traverse_cond(Cond_traverser traverser,
Item *Item_func::transform(Item_transformer transformer, uchar *argument)
{
- DBUG_ASSERT(!current_thd->is_stmt_prepare());
+ DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
if (arg_count)
{
@@ -522,7 +530,10 @@ bool Item_func::is_expensive_processor(uchar *arg)
my_decimal *Item_func::val_decimal(my_decimal *decimal_value)
{
DBUG_ASSERT(fixed);
- int2my_decimal(E_DEC_FATAL_ERROR, val_int(), unsigned_flag, decimal_value);
+ longlong nr= val_int();
+ if (null_value)
+ return 0; /* purecov: inspected */
+ int2my_decimal(E_DEC_FATAL_ERROR, nr, unsigned_flag, decimal_value);
return decimal_value;
}
@@ -883,7 +894,7 @@ longlong Item_func_numhybrid::val_int()
return 0;
char *end= (char*) res->ptr() + res->length();
- CHARSET_INFO *cs= str_value.charset();
+ CHARSET_INFO *cs= res->charset();
return (*(cs->cset->strtoll10))(cs, res->ptr(), &end, &err_not_used);
}
default:
@@ -1108,7 +1119,7 @@ err:
push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_DATA_OUT_OF_RANGE,
ER(ER_WARN_DATA_OUT_OF_RANGE),
- name, 1);
+ name, 1L);
return dec;
}
@@ -1560,9 +1571,14 @@ void Item_func_div::fix_length_and_dec()
{
decimals=max(args[0]->decimals,args[1]->decimals)+prec_increment;
set_if_smaller(decimals, NOT_FIXED_DEC);
- max_length=args[0]->max_length - args[0]->decimals + decimals;
uint tmp=float_length(decimals);
- set_if_smaller(max_length,tmp);
+ if (decimals == NOT_FIXED_DEC)
+ max_length= tmp;
+ else
+ {
+ max_length=args[0]->max_length - args[0]->decimals + decimals;
+ set_if_smaller(max_length,tmp);
+ }
break;
}
case INT_RESULT:
@@ -1593,24 +1609,27 @@ longlong Item_func_int_div::val_int()
if (args[0]->result_type() != INT_RESULT ||
args[1]->result_type() != INT_RESULT)
{
- my_decimal value0, value1, tmp;
- my_decimal *val0, *val1;
- longlong res;
- int err;
+ my_decimal tmp;
+ my_decimal *val0p= args[0]->val_decimal(&tmp);
+ if ((null_value= args[0]->null_value))
+ return 0;
+ my_decimal val0= *val0p;
- val0= args[0]->val_decimal(&value0);
- val1= args[1]->val_decimal(&value1);
- if ((null_value= (args[0]->null_value || args[1]->null_value)))
+ my_decimal *val1p= args[1]->val_decimal(&tmp);
+ if ((null_value= args[1]->null_value))
return 0;
+ my_decimal val1= *val1p;
+ int err;
if ((err= my_decimal_div(E_DEC_FATAL_ERROR & ~E_DEC_DIV_ZERO, &tmp,
- val0, val1, 0)) > 3)
+ &val0, &val1, 0)) > 3)
{
if (err == E_DEC_DIV_ZERO)
signal_divide_by_null();
return 0;
}
+ longlong res;
if (my_decimal2int(E_DEC_FATAL_ERROR, &tmp, unsigned_flag, &res) &
E_DEC_OVERFLOW)
raise_integer_overflow();
@@ -2097,9 +2116,10 @@ void Item_func_integer::fix_length_and_dec()
void Item_func_int_val::fix_num_length_and_dec()
{
- max_length= args[0]->max_length - (args[0]->decimals ?
- args[0]->decimals + 1 :
- 0) + 2;
+ ulonglong tmp_max_length= (ulonglong ) args[0]->max_length -
+ (args[0]->decimals ? args[0]->decimals + 1 : 0) + 2;
+ max_length= tmp_max_length > (ulonglong) 4294967295U ?
+ (uint32) 4294967295U : (uint32) tmp_max_length;
uint tmp= float_length(decimals);
set_if_smaller(max_length,tmp);
decimals= 0;
@@ -2263,6 +2283,9 @@ void Item_func_round::fix_length_and_dec()
}
val1= args[1]->val_int();
+ if ((null_value= args[1]->is_null()))
+ return;
+
val1_unsigned= args[1]->unsigned_flag;
if (val1 < 0)
decimals_to_set= val1_unsigned ? INT_MAX : 0;
@@ -2414,10 +2437,7 @@ my_decimal *Item_func_round::decimal_op(my_decimal *decimal_value)
if (!(null_value= (args[0]->null_value || args[1]->null_value ||
my_decimal_round(E_DEC_FATAL_ERROR, value, (int) dec,
truncate, decimal_value) > 1)))
- {
- decimal_value->frac= decimals;
return decimal_value;
- }
return 0;
}
@@ -2544,7 +2564,8 @@ void Item_func_min_max::fix_length_and_dec()
}
if (cmp_type == STRING_RESULT)
{
- agg_arg_charsets_for_comparison(collation, args, arg_count);
+ agg_arg_charsets_for_string_result_with_comparison(collation,
+ args, arg_count);
if (datetime_found)
{
thd= current_thd;
@@ -3014,6 +3035,8 @@ void Item_func_find_in_set::fix_length_and_dec()
String *find=args[0]->val_str(&value);
if (find)
{
+ // find is not NULL pointer so args[0] is not a null-value
+ DBUG_ASSERT(!args[0]->null_value);
enum_value= find_type(((Field_enum*) field)->typelib,find->ptr(),
find->length(), 0);
enum_bit=0;
@@ -3032,11 +3055,22 @@ longlong Item_func_find_in_set::val_int()
DBUG_ASSERT(fixed == 1);
if (enum_value)
{
- ulonglong tmp=(ulonglong) args[1]->val_int();
- if (!(null_value=args[1]->null_value || args[0]->null_value))
+ // enum_value is set iff args[0]->const_item() in fix_length_and_dec().
+ DBUG_ASSERT(args[0]->const_item());
+
+ ulonglong tmp= (ulonglong) args[1]->val_int();
+ null_value= args[1]->null_value;
+ /*
+ No need to check args[0]->null_value since enum_value is set iff
+ args[0] is a non-null const item. Note: no DBUG_ASSERT on
+ args[0]->null_value here because args[0] may have been replaced
+ by an Item_cache on which val_int() has not been called. See
+ BUG#11766317
+ */
+ if (!null_value)
{
if (tmp & enum_bit)
- return enum_value;
+ return enum_value;
}
return 0L;
}
@@ -3147,7 +3181,7 @@ udf_handler::fix_fields(THD *thd, Item_result_field *func,
if (!tmp_udf)
{
- my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str, errno);
+ my_error(ER_CANT_FIND_UDF, MYF(0), u_d->name.str);
DBUG_RETURN(TRUE);
}
u_d=tmp_udf;
@@ -3734,48 +3768,92 @@ longlong Item_master_pos_wait::val_int()
}
+/**
+ Enables a session to wait on a condition until a timeout or a network
+ disconnect occurs.
+
+ @remark The connection is polled every m_interrupt_interval nanoseconds.
+*/
+
+class Interruptible_wait
+{
+ THD *m_thd;
+ struct timespec m_abs_timeout;
+ static const ulonglong m_interrupt_interval;
+
+ public:
+ Interruptible_wait(THD *thd)
+ : m_thd(thd) {}
+
+ ~Interruptible_wait() {}
+
+ public:
+ /**
+ Set the absolute timeout.
+
+ @param timeout The amount of time in nanoseconds to wait
+ */
+ void set_timeout(ulonglong timeout)
+ {
+ /*
+ Calculate the absolute system time at the start so it can
+ be controlled in slices. It relies on the fact that once
+ the absolute time passes, the timed wait call will fail
+ automatically with a timeout error.
+ */
+ set_timespec_nsec(m_abs_timeout, timeout);
+ }
+
+ /** The timed wait. */
+ int wait(mysql_cond_t *, mysql_mutex_t *);
+};
+
+
+/** Time to wait before polling the connection status. */
+const ulonglong Interruptible_wait::m_interrupt_interval= 5 * ULL(1000000000);
+
/**
- Wait for a given condition to be signaled within the specified timeout.
+ Wait for a given condition to be signaled.
+
+ @param cond The condition variable to wait on.
+ @param mutex The associated mutex.
- @param cond the condition variable to wait on
- @param lock the associated mutex
- @param abstime the amount of time in seconds to wait
+ @remark The absolute timeout is preserved across calls.
@retval return value from mysql_cond_timedwait
*/
-#define INTERRUPT_INTERVAL (5 * ULL(1000000000))
-
-static int interruptible_wait(THD *thd, mysql_cond_t *cond,
- mysql_mutex_t *lock, double time)
+int Interruptible_wait::wait(mysql_cond_t *cond, mysql_mutex_t *mutex)
{
int error;
- struct timespec abstime;
- ulonglong slice, timeout= (ulonglong) (time * 1000000000.0);
+ struct timespec timeout;
- do
+ while (1)
{
/* Wait for a fixed interval. */
- if (timeout > INTERRUPT_INTERVAL)
- slice= INTERRUPT_INTERVAL;
- else
- slice= timeout;
+ set_timespec_nsec(timeout, m_interrupt_interval);
- timeout-= slice;
- set_timespec_nsec(abstime, slice);
- error= mysql_cond_timedwait(cond, lock, &abstime);
+ /* But only if not past the absolute timeout. */
+ if (cmp_timespec(timeout, m_abs_timeout) > 0)
+ timeout= m_abs_timeout;
+
+ error= mysql_cond_timedwait(cond, mutex, &timeout);
if (error == ETIMEDOUT || error == ETIME)
{
/* Return error if timed out or connection is broken. */
- if (!timeout || !thd->is_connected())
+ if (!cmp_timespec(timeout, m_abs_timeout) || !m_thd->is_connected())
break;
}
- } while (error && timeout);
+ /* Otherwise, propagate status to the caller. */
+ else
+ break;
+ }
return error;
}
+
/**
Get a user level lock. If the thread has an old lock this is first released.
@@ -3791,10 +3869,11 @@ longlong Item_func_get_lock::val_int()
{
DBUG_ASSERT(fixed == 1);
String *res=args[0]->val_str(&value);
- double timeout= args[1]->val_real();
+ ulonglong timeout= args[1]->val_int();
THD *thd=current_thd;
User_level_lock *ull;
int error;
+ Interruptible_wait timed_cond(thd);
DBUG_ENTER("Item_func_get_lock::val_int");
/*
@@ -3855,11 +3934,14 @@ longlong Item_func_get_lock::val_int()
thd->mysys_var->current_mutex= &LOCK_user_locks;
thd->mysys_var->current_cond= &ull->cond;
+ timed_cond.set_timeout(timeout * ULL(1000000000));
+
error= 0;
+ thd_wait_begin(thd, THD_WAIT_USER_LOCK);
while (ull->locked && !thd->killed)
{
DBUG_PRINT("info", ("waiting on lock"));
- error= interruptible_wait(thd, &ull->cond, &LOCK_user_locks, timeout);
+ error= timed_cond.wait(&ull->cond, &LOCK_user_locks);
if (error == ETIMEDOUT || error == ETIME)
{
DBUG_PRINT("info", ("lock wait timeout"));
@@ -3867,6 +3949,7 @@ longlong Item_func_get_lock::val_int()
}
error= 0;
}
+ thd_wait_end(thd);
if (ull->locked)
{
@@ -4054,6 +4137,7 @@ void Item_func_benchmark::print(String *str, enum_query_type query_type)
longlong Item_func_sleep::val_int()
{
THD *thd= current_thd;
+ Interruptible_wait timed_cond(thd);
mysql_cond_t cond;
double timeout;
int error;
@@ -4073,6 +4157,8 @@ longlong Item_func_sleep::val_int()
if (timeout < 0.00001)
return 0;
+ timed_cond.set_timeout((ulonglong) (timeout * 1000000000.0));
+
mysql_cond_init(key_item_func_sleep_cond, &cond, NULL);
mysql_mutex_lock(&LOCK_user_locks);
@@ -4081,13 +4167,15 @@ longlong Item_func_sleep::val_int()
thd->mysys_var->current_cond= &cond;
error= 0;
+ thd_wait_begin(thd, THD_WAIT_SLEEP);
while (!thd->killed)
{
- error= interruptible_wait(thd, &cond, &LOCK_user_locks, timeout);
+ error= timed_cond.wait(&cond, &LOCK_user_locks);
if (error == ETIMEDOUT || error == ETIME)
break;
error= 0;
}
+ thd_wait_end(thd);
thd_proc_info(thd, 0);
mysql_mutex_unlock(&LOCK_user_locks);
mysql_mutex_lock(&thd->mysys_var->mutex);
@@ -4226,6 +4314,7 @@ Item_func_set_user_var::fix_length_and_dec()
fix_length_and_charset(args[0]->max_char_length(),
args[0]->collation.collation);
}
+ unsigned_flag= args[0]->unsigned_flag;
}
@@ -4337,7 +4426,7 @@ update_hash(user_var_entry *entry, bool set_null, void *ptr, uint length,
length--; // Fix length change above
entry->value[length]= 0; // Store end \0
}
- memcpy(entry->value,ptr,length);
+ memmove(entry->value, ptr, length);
if (type == DECIMAL_RESULT)
((my_decimal*)entry->value)->fix_buffer_pointer();
entry->length= length;
@@ -4477,7 +4566,7 @@ my_decimal *user_var_entry::val_decimal(bool *null_value, my_decimal *val)
int2my_decimal(E_DEC_FATAL_ERROR, *(longlong*) value, 0, val);
break;
case DECIMAL_RESULT:
- val= (my_decimal *)value;
+ my_decimal2decimal((my_decimal *) value, val);
break;
case STRING_RESULT:
str2my_decimal(E_DEC_FATAL_ERROR, value, length, collation.collation, val);
@@ -5741,7 +5830,17 @@ void Item_func_match::init_search(bool no_order)
/* Check if init_search() has been called before */
if (ft_handler)
+ {
+ /*
+ We should reset ft_handler as it is cleaned up
+ on destruction of FT_SELECT object
+ (necessary in case of re-execution of subquery).
+ TODO: FT_SELECT should not clean up ft_handler.
+ */
+ if (join_key)
+ table->file->ft_handler= ft_handler;
DBUG_VOID_RETURN;
+ }
if (key == NO_SUCH_KEY)
{
@@ -6489,7 +6588,7 @@ Item_func_sp::fix_fields(THD *thd, Item **ref)
if (res)
DBUG_RETURN(res);
- if (thd->lex->view_prepare_mode)
+ if (thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW)
{
/*
Here we check privileges of the stored routine only during view
diff --git a/sql/item_func.h b/sql/item_func.h
index 5156d4d238b..c3cb3e3ba02 100644
--- a/sql/item_func.h
+++ b/sql/item_func.h
@@ -1,7 +1,7 @@
#ifndef ITEM_FUNC_INCLUDED
#define ITEM_FUNC_INCLUDED
-/* Copyright 2000-2008 MySQL AB, 2008 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -166,6 +166,11 @@ public:
{
return agg_item_charsets(c, func_name(), items, nitems, flags, item_sep);
}
+ /*
+ Aggregate arguments for string result, e.g: CONCAT(a,b)
+ - convert to @@character_set_connection if all arguments are numbers
+ - allow DERIVATION_NONE
+ */
bool agg_arg_charsets_for_string_result(DTCollation &c,
Item **items, uint nitems,
int item_sep= 1)
@@ -173,6 +178,11 @@ public:
return agg_item_charsets_for_string_result(c, func_name(),
items, nitems, item_sep);
}
+ /*
+ Aggregate arguments for comparison, e.g: a=b, a LIKE b, a RLIKE b
+ - don't convert to @@character_set_connection if all arguments are numbers
+ - don't allow DERIVATION_NONE
+ */
bool agg_arg_charsets_for_comparison(DTCollation &c,
Item **items, uint nitems,
int item_sep= 1)
@@ -180,6 +190,21 @@ public:
return agg_item_charsets_for_comparison(c, func_name(),
items, nitems, item_sep);
}
+ /*
+ Aggregate arguments for string result, when some comparison
+ is involved internally, e.g: REPLACE(a,b,c)
+ - convert to @@character_set_connection if all arguments are numbers
+ - disallow DERIVATION_NONE
+ */
+ bool agg_arg_charsets_for_string_result_with_comparison(DTCollation &c,
+ Item **items,
+ uint nitems,
+ int item_sep= 1)
+ {
+ return agg_item_charsets_for_string_result_with_comparison(c, func_name(),
+ items, nitems,
+ item_sep);
+ }
bool walk(Item_processor processor, bool walk_subquery, uchar *arg);
Item *transform(Item_transformer transformer, uchar *arg);
Item* compile(Item_analyzer analyzer, uchar **arg_p,
@@ -238,6 +263,7 @@ public:
{
return (error == E_DEC_OVERFLOW) ? raise_decimal_overflow() : error;
}
+
bool has_timestamp_args()
{
DBUG_ASSERT(fixed == TRUE);
@@ -249,6 +275,45 @@ public:
}
return FALSE;
}
+
+ bool has_date_args()
+ {
+ DBUG_ASSERT(fixed == TRUE);
+ for (uint i= 0; i < arg_count; i++)
+ {
+ if (args[i]->type() == Item::FIELD_ITEM &&
+ (args[i]->field_type() == MYSQL_TYPE_DATE ||
+ args[i]->field_type() == MYSQL_TYPE_DATETIME))
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ bool has_time_args()
+ {
+ DBUG_ASSERT(fixed == TRUE);
+ for (uint i= 0; i < arg_count; i++)
+ {
+ if (args[i]->type() == Item::FIELD_ITEM &&
+ (args[i]->field_type() == MYSQL_TYPE_TIME ||
+ args[i]->field_type() == MYSQL_TYPE_DATETIME))
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ bool has_datetime_args()
+ {
+ DBUG_ASSERT(fixed == TRUE);
+ for (uint i= 0; i < arg_count; i++)
+ {
+ if (args[i]->type() == Item::FIELD_ITEM &&
+ args[i]->field_type() == MYSQL_TYPE_DATETIME)
+ return TRUE;
+ }
+ return FALSE;
+ }
+
/*
We assume the result of any function that has a TIMESTAMP argument to be
timezone-dependent, since a TIMESTAMP value in both numeric and string
@@ -257,7 +322,7 @@ public:
representation of a TIMESTAMP argument verbatim, and thus does not depend on
the timezone.
*/
- virtual bool is_timezone_dependent_processor(uchar *bool_arg)
+ virtual bool check_valid_arguments_processor(uchar *bool_arg)
{
return has_timestamp_args();
}
@@ -1649,7 +1714,7 @@ public:
join_key(0), ft_handler(0), table(0), master(0), concat_ws(0) { }
void cleanup()
{
- DBUG_ENTER("Item_func_match");
+ DBUG_ENTER("Item_func_match::cleanup");
Item_real_func::cleanup();
if (!master && ft_handler)
ft_handler->please->close_search(ft_handler);
diff --git a/sql/item_geofunc.h b/sql/item_geofunc.h
index 84034841ad5..c5c1eae2d39 100644
--- a/sql/item_geofunc.h
+++ b/sql/item_geofunc.h
@@ -1,7 +1,7 @@
#ifndef ITEM_GEOFUNC_INCLUDED
#define ITEM_GEOFUNC_INCLUDED
-/* Copyright (C) 2000-2003 MySQL AB
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -181,6 +181,7 @@ public:
String *val_str(String *);
void fix_length_and_dec()
{
+ Item_geometry_func::fix_length_and_dec();
for (unsigned int i= 0; i < arg_count; ++i)
{
if (args[i]->fixed && args[i]->field_type() != MYSQL_TYPE_GEOMETRY)
diff --git a/sql/item_row.cc b/sql/item_row.cc
index 27b846cd15b..9fae85518af 100644
--- a/sql/item_row.cc
+++ b/sql/item_row.cc
@@ -80,12 +80,8 @@ bool Item_row::fix_fields(THD *thd, Item **ref)
used_tables_cache |= item->used_tables();
const_item_cache&= item->const_item() && !with_null;
not_null_tables_cache|= item->not_null_tables();
- /*
- Some subqueries transformations aren't done in the view_prepare_mode thus
- is_null() will fail. So we skip is_null() calculation for CREATE VIEW as
- not necessary.
- */
- if (const_item_cache && !thd->lex->view_prepare_mode)
+
+ if (const_item_cache)
{
if (item->cols() > 1)
with_null|= item->null_inside();
@@ -188,7 +184,7 @@ bool Item_row::walk(Item_processor processor, bool walk_subquery, uchar *arg)
Item *Item_row::transform(Item_transformer transformer, uchar *arg)
{
- DBUG_ASSERT(!current_thd->is_stmt_prepare());
+ DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
for (uint i= 0; i < arg_count; i++)
{
diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc
index 4b87b0439ee..dbd7ed1d68f 100644
--- a/sql/item_strfunc.cc
+++ b/sql/item_strfunc.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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 */
-
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@@ -56,6 +55,9 @@ C_MODE_START
#include "../mysys/my_static.h" // For soundex_map
C_MODE_END
+/**
+ @todo Remove this. It is not safe to use a shared String object.
+ */
String my_empty_string("",default_charset_info);
/*
@@ -67,7 +69,7 @@ String my_empty_string("",default_charset_info);
Normally conversion does not happen, and val_str_ascii() is immediately
returned instead.
*/
-String *Item_str_ascii_func::val_str(String *str)
+String *Item_str_func::val_str_from_val_str_ascii(String *str, String *str2)
{
DBUG_ASSERT(fixed == 1);
@@ -79,19 +81,19 @@ String *Item_str_ascii_func::val_str(String *str)
return res;
}
- DBUG_ASSERT(str != &ascii_buf);
+ DBUG_ASSERT(str != str2);
uint errors;
- String *res= val_str_ascii(&ascii_buf);
+ String *res= val_str_ascii(str);
if (!res)
return 0;
- if ((null_value= str->copy(res->ptr(), res->length(),
- &my_charset_latin1, collation.collation,
- &errors)))
+ if ((null_value= str2->copy(res->ptr(), res->length(),
+ &my_charset_latin1, collation.collation,
+ &errors)))
return 0;
- return str;
+ return str2;
}
@@ -642,7 +644,7 @@ String *Item_func_des_encrypt::val_str(String *str)
if ((null_value= args[0]->null_value))
return 0; // ENCRYPT(NULL) == NULL
if ((res_length=res->length()) == 0)
- return &my_empty_string;
+ return make_empty_result();
if (arg_count == 1)
{
/* Protect against someone doing FLUSH DES_KEY_FILE */
@@ -697,6 +699,7 @@ String *Item_func_des_encrypt::val_str(String *str)
tmp_arg[res_length-1]=tail; // save extra length
tmp_value.realloc(res_length+1);
tmp_value.length(res_length+1);
+ tmp_value.set_charset(&my_charset_bin);
tmp_value[0]=(char) (128 | key_number);
// Real encryption
bzero((char*) &ivec,sizeof(ivec));
@@ -784,6 +787,7 @@ String *Item_func_des_decrypt::val_str(String *str)
if ((tail=(uint) (uchar) tmp_value[length-2]) > 8)
goto wrong_key; // Wrong key
tmp_value.length(length-1-tail);
+ tmp_value.set_charset(&my_charset_bin);
return &tmp_value;
error:
@@ -833,7 +837,7 @@ String *Item_func_concat_ws::val_str(String *str)
}
if (i == arg_count)
- return &my_empty_string;
+ return make_empty_result();
for (i++; i < arg_count ; i++)
{
@@ -979,7 +983,7 @@ String *Item_func_reverse::val_str(String *str)
return 0;
/* An empty string is a special case as the string pointer may be null */
if (!res->length())
- return &my_empty_string;
+ return make_empty_result();
if (tmp_value.alloced_length() < res->length() &&
tmp_value.realloc(res->length()))
{
@@ -1081,9 +1085,15 @@ String *Item_func_replace::val_str(String *str)
search=res2->ptr();
search_end=search+from_length;
redo:
+ DBUG_ASSERT(res->ptr() || !offset);
ptr=res->ptr()+offset;
strend=res->ptr()+res->length();
- end=strend-from_length+1;
+ /*
+ In some cases val_str() can return empty string
+ with ptr() == NULL and length() == 0.
+ Let's check strend to avoid overflow.
+ */
+ end= strend ? strend - from_length + 1 : NULL;
while (ptr < end)
{
if (*ptr == *search)
@@ -1158,7 +1168,7 @@ void Item_func_replace::fix_length_and_dec()
char_length+= max_substrs * (uint) diff;
}
- if (agg_arg_charsets_for_comparison(collation, args, 3))
+ if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 3))
return;
fix_char_length_ulonglong(char_length);
}
@@ -1185,6 +1195,20 @@ String *Item_func_insert::val_str(String *str)
if ((length < 0) || (length > res->length()))
length= res->length();
+ /*
+ There is one exception not handled (intentionaly) by the character set
+ aggregation code. If one string is strong side and is binary, and
+ another one is weak side and is a multi-byte character string,
+ then we need to operate on the second string in terms on bytes when
+ calling ::numchars() and ::charpos(), rather than in terms of characters.
+ Lets substitute its character set to binary.
+ */
+ if (collation.collation == &my_charset_bin)
+ {
+ res->set_charset(&my_charset_bin);
+ res2->set_charset(&my_charset_bin);
+ }
+
/* start and length are now sufficiently valid to pass to charpos function */
start= res->charpos((int) start);
length= res->charpos((int) length, (uint32) start);
@@ -1292,8 +1316,7 @@ String *Item_func_left::val_str(String *str)
/* if "unsigned_flag" is set, we have a *huge* positive number. */
if ((length <= 0) && (!args[1]->unsigned_flag))
- return &my_empty_string;
-
+ return make_empty_result();
if ((res->length() <= (ulonglong) length) ||
(res->length() <= (char_pos= res->charpos((int) length))))
return res;
@@ -1338,7 +1361,7 @@ String *Item_func_right::val_str(String *str)
/* if "unsigned_flag" is set, we have a *huge* positive number. */
if ((length <= 0) && (!args[1]->unsigned_flag))
- return &my_empty_string; /* purecov: inspected */
+ return make_empty_result(); /* purecov: inspected */
if (res->length() <= (ulonglong) length)
return res; /* purecov: inspected */
@@ -1378,7 +1401,7 @@ String *Item_func_substr::val_str(String *str)
/* Negative or zero length, will return empty string. */
if ((arg_count == 3) && (length <= 0) &&
(length == 0 || !args[2]->unsigned_flag))
- return &my_empty_string;
+ return make_empty_result();
/* Assumes that the maximum length of a String is < INT_MAX32. */
/* Set here so that rest of code sees out-of-bound value as such. */
@@ -1389,12 +1412,12 @@ String *Item_func_substr::val_str(String *str)
/* Assumes that the maximum length of a String is < INT_MAX32. */
if ((!args[1]->unsigned_flag && (start < INT_MIN32 || start > INT_MAX32)) ||
(args[1]->unsigned_flag && ((ulonglong) start > INT_MAX32)))
- return &my_empty_string;
+ return make_empty_result();
start= ((start < 0) ? res->numchars() + start : start - 1);
start= res->charpos((int) start);
if ((start < 0) || ((uint) start + 1 > res->length()))
- return &my_empty_string;
+ return make_empty_result();
length= res->charpos((int) length, (uint32) start);
tmp_length= res->length() - start;
@@ -1435,7 +1458,7 @@ void Item_func_substr::fix_length_and_dec()
void Item_func_substr_index::fix_length_and_dec()
{
- if (agg_arg_charsets_for_comparison(collation, args, 2))
+ if (agg_arg_charsets_for_string_result_with_comparison(collation, args, 2))
return;
fix_char_length(args[0]->max_char_length());
}
@@ -1457,7 +1480,7 @@ String *Item_func_substr_index::val_str(String *str)
null_value=0;
uint delimiter_length= delimiter->length();
if (!res->length() || !delimiter_length || !count)
- return &my_empty_string; // Wrong parameters
+ return make_empty_result(); // Wrong parameters
res->set_charset(collation.collation);
@@ -1774,7 +1797,8 @@ void Item_func_trim::fix_length_and_dec()
{
// Handle character set for args[1] and args[0].
// Note that we pass args[1] as the first item, and args[0] as the second.
- if (agg_arg_charsets_for_comparison(collation, &args[1], 2, -1))
+ if (agg_arg_charsets_for_string_result_with_comparison(collation,
+ &args[1], 2, -1))
return;
}
fix_char_length(args[0]->max_char_length());
@@ -1807,7 +1831,7 @@ String *Item_func_password::val_str_ascii(String *str)
if ((null_value=args[0]->null_value))
return 0;
if (res->length() == 0)
- return &my_empty_string;
+ return make_empty_result();
my_make_scrambled_password(tmp_value, res->ptr(), res->length());
str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH, &my_charset_latin1);
return str;
@@ -1831,7 +1855,7 @@ String *Item_func_old_password::val_str_ascii(String *str)
if ((null_value=args[0]->null_value))
return 0;
if (res->length() == 0)
- return &my_empty_string;
+ return make_empty_result();
my_make_scrambled_password_323(tmp_value, res->ptr(), res->length());
str->set(tmp_value, SCRAMBLED_PASSWORD_CHAR_LENGTH_323, &my_charset_latin1);
return str;
@@ -1859,8 +1883,7 @@ String *Item_func_encrypt::val_str(String *str)
if ((null_value=args[0]->null_value))
return 0;
if (res->length() == 0)
- return &my_empty_string;
-
+ return make_empty_result();
if (arg_count == 1)
{ // generate random salt
time_t timestamp=current_thd->query_start();
@@ -2122,7 +2145,7 @@ String *Item_func_soundex::val_str(String *str)
for ( ; ; ) /* Skip pre-space */
{
if ((rc= cs->cset->mb_wc(cs, &wc, (uchar*) from, (uchar*) end)) <= 0)
- return &my_empty_string; /* EOL or invalid byte sequence */
+ return make_empty_result(); /* EOL or invalid byte sequence */
if (rc == 1 && cs->ctype)
{
@@ -2147,7 +2170,7 @@ String *Item_func_soundex::val_str(String *str)
{
/* Extra safety - should not really happen */
DBUG_ASSERT(false);
- return &my_empty_string;
+ return make_empty_result();
}
to+= rc;
break;
@@ -2300,7 +2323,8 @@ String *Item_func_format::val_str_ascii(String *str)
if (lc->grouping[0] > 0 &&
str_length >= dec_length + 1 + lc->grouping[0])
{
- char buf[DECIMAL_MAX_STR_LENGTH * 2]; /* 2 - in the worst case when grouping=1 */
+ /* We need space for ',' between each group of digits as well. */
+ char buf[2 * FLOATING_POINT_BUFFER];
int count;
const char *grouping= lc->grouping;
char sign_length= *str->ptr() == '-' ? 1 : 0;
@@ -2324,7 +2348,7 @@ String *Item_func_format::val_str_ascii(String *str)
count will be initialized to -1 and
we'll never get into this "if" anymore.
*/
- if (!count)
+ if (count == 0)
{
*--dst= lc->thousand_sep;
if (grouping[1])
@@ -2487,7 +2511,7 @@ String *Item_func_make_set::val_str(String *str)
else
{
if (tmp_str.copy(*res)) // Don't use 'str'
- return &my_empty_string;
+ return make_empty_result();
result= &tmp_str;
}
}
@@ -2497,11 +2521,11 @@ String *Item_func_make_set::val_str(String *str)
{ // Copy data to tmp_str
if (tmp_str.alloc(result->length()+res->length()+1) ||
tmp_str.copy(*result))
- return &my_empty_string;
+ return make_empty_result();
result= &tmp_str;
}
if (tmp_str.append(STRING_WITH_LEN(","), &my_charset_bin) || tmp_str.append(*res))
- return &my_empty_string;
+ return make_empty_result();
}
}
}
@@ -2512,7 +2536,7 @@ String *Item_func_make_set::val_str(String *str)
Item *Item_func_make_set::transform(Item_transformer transformer, uchar *arg)
{
- DBUG_ASSERT(!current_thd->is_stmt_prepare());
+ DBUG_ASSERT(!current_thd->stmt_arena->is_stmt_prepare());
Item *new_item= item->transform(transformer, arg);
if (!new_item)
@@ -2646,7 +2670,7 @@ String *Item_func_repeat::val_str(String *str)
null_value= 0;
if (count <= 0 && (count == 0 || !args[1]->unsigned_flag))
- return &my_empty_string;
+ return make_empty_result();
/* Assumes that the maximum length of a String is < INT_MAX32. */
/* Bounds check on count: If this is triggered, we will error. */
@@ -2725,6 +2749,20 @@ String *Item_func_rpad::val_str(String *str)
/* Set here so that rest of code sees out-of-bound value as such. */
if ((ulonglong) count > INT_MAX32)
count= INT_MAX32;
+ /*
+ There is one exception not handled (intentionaly) by the character set
+ aggregation code. If one string is strong side and is binary, and
+ another one is weak side and is a multi-byte character string,
+ then we need to operate on the second string in terms on bytes when
+ calling ::numchars() and ::charpos(), rather than in terms of characters.
+ Lets substitute its character set to binary.
+ */
+ if (collation.collation == &my_charset_bin)
+ {
+ res->set_charset(&my_charset_bin);
+ rpad->set_charset(&my_charset_bin);
+ }
+
if (count <= (res_char_length= res->numchars()))
{ // String to pad is big enough
res->length(res->charpos((int) count)); // Shorten result if longer
@@ -2814,6 +2852,20 @@ String *Item_func_lpad::val_str(String *str)
if ((ulonglong) count > INT_MAX32)
count= INT_MAX32;
+ /*
+ There is one exception not handled (intentionaly) by the character set
+ aggregation code. If one string is strong side and is binary, and
+ another one is weak side and is a multi-byte character string,
+ then we need to operate on the second string in terms on bytes when
+ calling ::numchars() and ::charpos(), rather than in terms of characters.
+ Lets substitute its character set to binary.
+ */
+ if (collation.collation == &my_charset_bin)
+ {
+ res->set_charset(&my_charset_bin);
+ pad->set_charset(&my_charset_bin);
+ }
+
res_char_length= res->numchars();
if (count <= res_char_length)
@@ -2900,7 +2952,7 @@ String *Item_func_conv::val_str(String *str)
ptr= longlong2str(dec, ans, to_base);
if (str->copy(ans, (uint32) (ptr-ans), default_charset()))
- return &my_empty_string;
+ return make_empty_result();
return str;
}
@@ -2910,22 +2962,16 @@ String *Item_func_conv_charset::val_str(String *str)
DBUG_ASSERT(fixed == 1);
if (use_cached_value)
return null_value ? 0 : &str_value;
- /*
- Here we don't pass 'str' as a parameter to args[0]->val_str()
- as 'str' may point to 'str_value' (e.g. see Item::save_in_field()),
- which we use below to convert string.
- Use argument's 'str_value' instead.
- */
- String *arg= args[0]->val_str(&args[0]->str_value);
+ String *arg= args[0]->val_str(str);
uint dummy_errors;
if (!arg)
{
null_value=1;
return 0;
}
- null_value= str_value.copy(arg->ptr(),arg->length(),arg->charset(),
+ null_value= tmp_value.copy(arg->ptr(), arg->length(), arg->charset(),
conv_charset, &dummy_errors);
- return null_value ? 0 : check_well_formed_result(&str_value);
+ return null_value ? 0 : check_well_formed_result(&tmp_value);
}
void Item_func_conv_charset::fix_length_and_dec()
@@ -3067,7 +3113,7 @@ String *Item_func_hex::val_str_ascii(String *str)
return 0;
ptr= longlong2str(dec,ans,16);
if (str->copy(ans,(uint32) (ptr-ans), &my_charset_numeric))
- return &my_empty_string; // End of memory
+ return make_empty_result(); // End of memory
return str;
}
@@ -3128,6 +3174,41 @@ String *Item_func_unhex::val_str(String *str)
}
+#ifndef DBUG_OFF
+String *Item_func_like_range::val_str(String *str)
+{
+ DBUG_ASSERT(fixed == 1);
+ longlong nbytes= args[1]->val_int();
+ String *res= args[0]->val_str(str);
+ size_t min_len, max_len;
+ CHARSET_INFO *cs= collation.collation;
+
+ if (!res || args[0]->null_value || args[1]->null_value ||
+ nbytes < 0 || nbytes > MAX_BLOB_WIDTH ||
+ min_str.alloc(nbytes) || max_str.alloc(nbytes))
+ goto err;
+ null_value=0;
+
+ if (cs->coll->like_range(cs, res->ptr(), res->length(),
+ '\\', '_', '%', nbytes,
+ (char*) min_str.ptr(), (char*) max_str.ptr(),
+ &min_len, &max_len))
+ goto err;
+
+ min_str.set_charset(collation.collation);
+ max_str.set_charset(collation.collation);
+ min_str.length(min_len);
+ max_str.length(max_len);
+
+ return is_min ? &min_str : &max_str;
+
+err:
+ null_value= 1;
+ return 0;
+}
+#endif
+
+
void Item_func_binary::print(String *str, enum_query_type query_type)
{
str->append(STRING_WITH_LEN("cast("));
@@ -3370,14 +3451,68 @@ String *Item_func_quote::val_str(String *str)
}
arg_length= arg->length();
- new_length= arg_length+2; /* for beginning and ending ' signs */
- for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
- new_length+= get_esc_bit(escmask, (uchar) *from);
+ if (collation.collation->mbmaxlen == 1)
+ {
+ new_length= arg_length + 2; /* for beginning and ending ' signs */
+ for (from= (char*) arg->ptr(), end= from + arg_length; from < end; from++)
+ new_length+= get_esc_bit(escmask, (uchar) *from);
+ }
+ else
+ {
+ new_length= (arg_length * 2) + /* For string characters */
+ (2 * collation.collation->mbmaxlen); /* For quotes */
+ }
if (tmp_value.alloc(new_length))
goto null;
+ if (collation.collation->mbmaxlen > 1)
+ {
+ CHARSET_INFO *cs= collation.collation;
+ int mblen;
+ uchar *to_end;
+ to= (char*) tmp_value.ptr();
+ to_end= (uchar*) to + new_length;
+
+ /* Put leading quote */
+ if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
+ goto null;
+ to+= mblen;
+
+ for (start= (char*) arg->ptr(), end= start + arg_length; start < end; )
+ {
+ my_wc_t wc;
+ bool escape;
+ if ((mblen= cs->cset->mb_wc(cs, &wc, (uchar*) start, (uchar*) end)) <= 0)
+ goto null;
+ start+= mblen;
+ switch (wc) {
+ case 0: escape= 1; wc= '0'; break;
+ case '\032': escape= 1; wc= 'Z'; break;
+ case '\'': escape= 1; break;
+ case '\\': escape= 1; break;
+ default: escape= 0; break;
+ }
+ if (escape)
+ {
+ if ((mblen= cs->cset->wc_mb(cs, '\\', (uchar*) to, to_end)) <= 0)
+ goto null;
+ to+= mblen;
+ }
+ if ((mblen= cs->cset->wc_mb(cs, wc, (uchar*) to, to_end)) <= 0)
+ goto null;
+ to+= mblen;
+ }
+
+ /* Put trailing quote */
+ if ((mblen= cs->cset->wc_mb(cs, '\'', (uchar *) to, to_end)) <= 0)
+ goto null;
+ to+= mblen;
+ new_length= to - tmp_value.ptr();
+ goto ret;
+ }
+
/*
We replace characters from the end to the beginning
*/
@@ -3409,6 +3544,8 @@ String *Item_func_quote::val_str(String *str)
}
}
*to= '\'';
+
+ret:
tmp_value.length(new_length);
tmp_value.set_charset(collation.collation);
null_value= 0;
@@ -3565,7 +3702,8 @@ String *Item_func_uncompress::val_str(String *str)
push_warning_printf(current_thd,MYSQL_ERROR::WARN_LEVEL_WARN,
ER_TOO_BIG_FOR_UNCOMPRESS,
ER(ER_TOO_BIG_FOR_UNCOMPRESS),
- current_thd->variables.max_allowed_packet);
+ static_cast<int>(current_thd->variables.
+ max_allowed_packet));
goto err;
}
if (buffer.realloc((uint32)new_size))
diff --git a/sql/item_strfunc.h b/sql/item_strfunc.h
index 8c85d1cb8fd..ef059ae1780 100644
--- a/sql/item_strfunc.h
+++ b/sql/item_strfunc.h
@@ -1,7 +1,7 @@
#ifndef ITEM_STRFUNC_INCLUDED
#define ITEM_STRFUNC_INCLUDED
-/* Copyright (C) 2000-2003 MySQL AB
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -27,6 +27,16 @@ class MY_LOCALE;
class Item_str_func :public Item_func
{
+protected:
+ /**
+ Sets the result value of the function an empty string, using the current
+ character set. No memory is allocated.
+ @retval A pointer to the str_value member.
+ */
+ String *make_empty_result() {
+ str_value.set("", 0, collation.collation);
+ return &str_value;
+ }
public:
Item_str_func() :Item_func() { decimals=NOT_FIXED_DEC; }
Item_str_func(Item *a) :Item_func(a) {decimals=NOT_FIXED_DEC; }
@@ -41,6 +51,7 @@ public:
enum Item_result result_type () const { return STRING_RESULT; }
void left_right_max_length();
bool fix_fields(THD *thd, Item **ref);
+ String *val_str_from_val_str_ascii(String *str, String *str2);
};
@@ -56,8 +67,10 @@ public:
Item_str_ascii_func(Item *a) :Item_str_func(a) {}
Item_str_ascii_func(Item *a,Item *b) :Item_str_func(a,b) {}
Item_str_ascii_func(Item *a,Item *b,Item *c) :Item_str_func(a,b,c) {}
- String *val_str_convert_from_ascii(String *str, String *ascii_buf);
- String *val_str(String *str);
+ String *val_str(String *str)
+ {
+ return val_str_from_val_str_ascii(str, &ascii_buf);
+ }
virtual String *val_str_ascii(String *)= 0;
};
@@ -351,7 +364,9 @@ public:
{
maybe_null=1;
/* 9 = MAX ((8- (arg_len % 8)) + 1) */
- max_length = args[0]->max_length - 9;
+ max_length= args[0]->max_length;
+ if (max_length >= 9U)
+ max_length-= 9U;
}
const char *func_name() const { return "des_decrypt"; }
};
@@ -666,6 +681,46 @@ public:
};
+#ifndef DBUG_OFF
+class Item_func_like_range :public Item_str_func
+{
+protected:
+ String min_str;
+ String max_str;
+ const bool is_min;
+public:
+ Item_func_like_range(Item *a, Item *b, bool is_min_arg)
+ :Item_str_func(a, b), is_min(is_min_arg)
+ { maybe_null= 1; }
+ String *val_str(String *);
+ void fix_length_and_dec()
+ {
+ collation.set(args[0]->collation);
+ decimals=0;
+ max_length= MAX_BLOB_WIDTH;
+ }
+};
+
+
+class Item_func_like_range_min :public Item_func_like_range
+{
+public:
+ Item_func_like_range_min(Item *a, Item *b)
+ :Item_func_like_range(a, b, true) { }
+ const char *func_name() const { return "like_range_min"; }
+};
+
+
+class Item_func_like_range_max :public Item_func_like_range
+{
+public:
+ Item_func_like_range_max(Item *a, Item *b)
+ :Item_func_like_range(a, b, false) { }
+ const char *func_name() const { return "like_range_max"; }
+};
+#endif
+
+
class Item_func_binary :public Item_str_func
{
public:
@@ -745,15 +800,17 @@ public:
String *val_str(String *);
void fix_length_and_dec()
{
- ulonglong max_result_length= (ulonglong) args[0]->max_length * 2 + 2;
- max_length= (uint32) min(max_result_length, MAX_BLOB_WIDTH);
collation.set(args[0]->collation);
+ ulonglong max_result_length= (ulonglong) args[0]->max_length * 2 +
+ 2 * collation.collation->mbmaxlen;
+ max_length= (uint32) min(max_result_length, MAX_BLOB_WIDTH);
}
};
class Item_func_conv_charset :public Item_str_func
{
bool use_cached_value;
+ String tmp_value;
public:
bool safe;
CHARSET_INFO *conv_charset; // keep it public
diff --git a/sql/item_subselect.cc b/sql/item_subselect.cc
index a69910da700..44436a4a467 100644
--- a/sql/item_subselect.cc
+++ b/sql/item_subselect.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000 MySQL AB
+/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
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
@@ -133,20 +133,6 @@ void Item_subselect::cleanup()
}
-/*
- We cannot use generic Item::safe_charset_converter() because
- Subselect transformation does not happen in view_prepare_mode
- and thus we can not evaluate val_...() for const items.
-*/
-
-Item *Item_subselect::safe_charset_converter(CHARSET_INFO *tocs)
-{
- Item_func_conv_charset *conv=
- new Item_func_conv_charset(this, tocs, thd->lex->view_prepare_mode ? 0 : 1);
- return conv->safe ? conv : NULL;
-}
-
-
void Item_singlerow_subselect::cleanup()
{
DBUG_ENTER("Item_singlerow_subselect::cleanup");
@@ -471,29 +457,31 @@ bool Item_subselect::walk(Item_processor processor, bool walk_subquery,
bool Item_subselect::exec()
{
- int res;
+ DBUG_ENTER("Item_subselect::exec");
/*
Do not execute subselect in case of a fatal error
or if the query has been killed.
*/
if (thd->is_error() || thd->killed)
- return 1;
+ DBUG_RETURN(true);
+ DBUG_ASSERT(!thd->lex->context_analysis_only);
/*
Simulate a failure in sub-query execution. Used to test e.g.
out of memory or query being killed conditions.
*/
- DBUG_EXECUTE_IF("subselect_exec_fail", return 1;);
+ DBUG_EXECUTE_IF("subselect_exec_fail", DBUG_RETURN(true););
- res= engine->exec();
+ bool res= engine->exec();
if (engine_changed)
{
engine_changed= 0;
- return exec();
+ res= exec();
+ DBUG_RETURN(res);
}
- return (res);
+ DBUG_RETURN(res);
}
@@ -607,7 +595,7 @@ table_map Item_subselect::used_tables() const
bool Item_subselect::const_item() const
{
- return const_item_cache;
+ return thd->lex->context_analysis_only ? FALSE : const_item_cache;
}
Item *Item_subselect::get_tmp_table_item(THD *thd_arg)
@@ -1563,6 +1551,7 @@ Item_in_subselect::single_value_in_to_exists_transformer(JOIN * join, Comp_creat
select_lex->having= join->having= and_items(join->having, item);
if (join->having == item)
item->name= (char*)in_having_cond;
+ select_lex->having->top_level_item();
select_lex->having_fix_field= 1;
/*
we do not check join->having->fixed, because Item_and (from and_items)
@@ -2178,7 +2167,8 @@ bool Item_in_subselect::fix_fields(THD *thd_arg, Item **ref)
}
}
- if (thd_arg->lex->view_prepare_mode && left_expr && !left_expr->fixed &&
+ if ((thd_arg->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) &&
+ left_expr && !left_expr->fixed &&
left_expr->fix_fields(thd_arg, &left_expr))
return TRUE;
if (Item_subselect::fix_fields(thd_arg, ref))
@@ -2647,21 +2637,26 @@ int subselect_single_select_engine::exec()
DBUG_RETURN(join->error ? join->error : 1);
}
if (!select_lex->uncacheable && thd->lex->describe &&
- !(join->select_options & SELECT_DESCRIBE) &&
- join->need_tmp)
+ !(join->select_options & SELECT_DESCRIBE))
{
item->update_used_tables();
if (item->const_item())
{
/*
+ It's necessary to keep original JOIN table because
+ create_sort_index() function may overwrite original
+ JOIN_TAB::type and wrong optimization method can be
+ selected on re-execution.
+ */
+ select_lex->uncacheable|= UNCACHEABLE_EXPLAIN;
+ select_lex->master_unit()->uncacheable|= UNCACHEABLE_EXPLAIN;
+ /*
Force join->join_tmp creation, because this subquery will be replaced
by a simple select from the materialization temp table by optimize()
called by EXPLAIN and we need to preserve the initial query structure
so we can display it.
*/
- select_lex->uncacheable|= UNCACHEABLE_EXPLAIN;
- select_lex->master_unit()->uncacheable|= UNCACHEABLE_EXPLAIN;
- if (join->init_save_join_tab())
+ if (join->need_tmp && join->init_save_join_tab())
DBUG_RETURN(1); /* purecov: inspected */
}
}
diff --git a/sql/item_subselect.h b/sql/item_subselect.h
index e4a49fe032d..f85067c56fa 100644
--- a/sql/item_subselect.h
+++ b/sql/item_subselect.h
@@ -200,7 +200,6 @@ public:
{
return trace_unsupported_by_check_vcol_func_processor("subselect");
}
- Item *safe_charset_converter(CHARSET_INFO *tocs);
/**
Get the SELECT_LEX structure associated with this Item.
diff --git a/sql/item_sum.cc b/sql/item_sum.cc
index 4a7f2a54659..c3835c7536c 100644
--- a/sql/item_sum.cc
+++ b/sql/item_sum.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
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
@@ -557,24 +557,27 @@ Item *Item_sum::set_arg(uint i, THD *thd, Item *new_val)
int Item_sum::set_aggregator(Aggregator::Aggregator_type aggregator)
{
- if (aggr)
+ /*
+ Dependent subselects may be executed multiple times, making
+ set_aggregator to be called multiple times. The aggregator type
+ will be the same, but it needs to be reset so that it is
+ reevaluated with the new dependent data.
+ This function may also be called multiple times during query optimization.
+ In this case, the type may change, so we delete the old aggregator,
+ and create a new one.
+ */
+ if (aggr && aggregator == aggr->Aggrtype())
{
- /*
- Dependent subselects may be executed multiple times, making
- set_aggregator to be called multiple times. The aggregator type
- will be the same, but it needs to be reset so that it is
- reevaluated with the new dependent data.
- */
- DBUG_ASSERT(aggregator == aggr->Aggrtype());
aggr->clear();
return FALSE;
}
+
+ delete aggr;
switch (aggregator)
{
case Aggregator::DISTINCT_AGGREGATOR:
aggr= new Aggregator_distinct(this);
break;
-
case Aggregator::SIMPLE_AGGREGATOR:
aggr= new Aggregator_simple(this);
break;
@@ -1143,17 +1146,13 @@ Item_sum_hybrid::fix_fields(THD *thd, Item **ref)
switch (hybrid_type= item->result_type()) {
case INT_RESULT:
- max_length= 20;
- break;
case DECIMAL_RESULT:
+ case STRING_RESULT:
max_length= item->max_length;
break;
case REAL_RESULT:
max_length= float_length(decimals);
break;
- case STRING_RESULT:
- max_length= item->max_length;
- break;
case ROW_RESULT:
default:
DBUG_ASSERT(0);
@@ -1197,8 +1196,10 @@ void Item_sum_hybrid::setup_hybrid(Item *item, Item *value_arg)
value= Item_cache::get_cache(item);
value->setup(item);
value->store(value_arg);
+ arg_cache= Item_cache::get_cache(item);
+ arg_cache->setup(item);
cmp= new Arg_comparator();
- cmp->set_cmp_func(this, args, (Item**)&value, FALSE);
+ cmp->set_cmp_func(this, (Item**)&arg_cache, (Item**)&value, FALSE);
collation.set(item->collation);
}
@@ -1326,27 +1327,11 @@ void Item_sum_sum::fix_length_and_dec()
bool Item_sum_sum::add()
{
DBUG_ENTER("Item_sum_sum::add");
- bool arg_is_null;
if (hybrid_type == DECIMAL_RESULT)
{
- my_decimal value, *val;
- if (aggr->use_distinct_values)
- {
- /*
- We are aggregating distinct rows. Get the value from the distinct
- table pointer
- */
- Aggregator_distinct *daggr= (Aggregator_distinct *)aggr;
- val= daggr->table->field[0]->val_decimal (&value);
- arg_is_null= daggr->table->field[0]->is_null();
- }
- else
- {
- /* non-distinct aggregation */
- val= args[0]->val_decimal(&value);
- arg_is_null= args[0]->null_value;
- }
- if (!arg_is_null)
+ my_decimal value;
+ const my_decimal *val= aggr->arg_val_decimal(&value);
+ if (!aggr->arg_is_null())
{
my_decimal_add(E_DEC_FATAL_ERROR, dec_buffs + (curr_dec_buff^1),
val, dec_buffs + curr_dec_buff);
@@ -1356,25 +1341,8 @@ bool Item_sum_sum::add()
}
else
{
- double val;
- if (aggr->use_distinct_values)
- {
- /*
- We are aggregating distinct rows. Get the value from the distinct
- table pointer
- */
- Aggregator_distinct *daggr= (Aggregator_distinct *)aggr;
- val= daggr->table->field[0]->val_real ();
- arg_is_null= daggr->table->field[0]->is_null();
- }
- else
- {
- /* non-distinct aggregation */
- val= args[0]->val_real();
- arg_is_null= args[0]->null_value;
- }
- sum+= val;
- if (!arg_is_null)
+ sum+= aggr->arg_val_real();
+ if (!aggr->arg_is_null())
null_value= 0;
}
DBUG_RETURN(0);
@@ -1472,6 +1440,45 @@ Aggregator_distinct::~Aggregator_distinct()
}
+my_decimal *Aggregator_simple::arg_val_decimal(my_decimal *value)
+{
+ return item_sum->args[0]->val_decimal(value);
+}
+
+
+double Aggregator_simple::arg_val_real()
+{
+ return item_sum->args[0]->val_real();
+}
+
+
+bool Aggregator_simple::arg_is_null()
+{
+ return item_sum->args[0]->null_value;
+}
+
+
+my_decimal *Aggregator_distinct::arg_val_decimal(my_decimal * value)
+{
+ return use_distinct_values ? table->field[0]->val_decimal(value) :
+ item_sum->args[0]->val_decimal(value);
+}
+
+
+double Aggregator_distinct::arg_val_real()
+{
+ return use_distinct_values ? table->field[0]->val_real() :
+ item_sum->args[0]->val_real();
+}
+
+
+bool Aggregator_distinct::arg_is_null()
+{
+ return use_distinct_values ? table->field[0]->is_null() :
+ item_sum->args[0]->null_value;
+}
+
+
Item *Item_sum_count::copy_or_same(THD* thd)
{
return new (thd->mem_root) Item_sum_count(thd, this);
@@ -1577,7 +1584,7 @@ bool Item_sum_avg::add()
{
if (Item_sum_sum::add())
return TRUE;
- if (!args[0]->null_value)
+ if (!aggr->arg_is_null())
count++;
return FALSE;
}
@@ -1893,7 +1900,10 @@ double Item_sum_hybrid::val_real()
DBUG_ASSERT(fixed == 1);
if (null_value)
return 0.0;
- return value->val_real();
+ double retval= value->val_real();
+ if ((null_value= value->null_value))
+ DBUG_ASSERT(retval == 0.0);
+ return retval;
}
longlong Item_sum_hybrid::val_int()
@@ -1901,7 +1911,10 @@ longlong Item_sum_hybrid::val_int()
DBUG_ASSERT(fixed == 1);
if (null_value)
return 0;
- return value->val_int();
+ longlong retval= value->val_int();
+ if ((null_value= value->null_value))
+ DBUG_ASSERT(retval == 0);
+ return retval;
}
@@ -1910,7 +1923,10 @@ my_decimal *Item_sum_hybrid::val_decimal(my_decimal *val)
DBUG_ASSERT(fixed == 1);
if (null_value)
return 0;
- return value->val_decimal(val);
+ my_decimal *retval= value->val_decimal(val);
+ if ((null_value= value->null_value))
+ DBUG_ASSERT(retval == NULL);
+ return retval;
}
@@ -1920,7 +1936,10 @@ Item_sum_hybrid::val_str(String *str)
DBUG_ASSERT(fixed == 1);
if (null_value)
return 0;
- return value->val_str(str);
+ String *retval= value->val_str(str);
+ if ((null_value= value->null_value))
+ DBUG_ASSERT(retval == NULL);
+ return retval;
}
@@ -1975,11 +1994,11 @@ Item *Item_sum_min::copy_or_same(THD* thd)
bool Item_sum_min::add()
{
/* args[0] < value */
- int res= cmp->compare();
- if (!args[0]->null_value &&
- (null_value || res < 0))
+ arg_cache->cache_value();
+ if (!arg_cache->null_value &&
+ (null_value || cmp->compare() < 0))
{
- value->store(args[0]);
+ value->store(arg_cache);
value->cache_value();
null_value= 0;
}
@@ -1998,11 +2017,11 @@ Item *Item_sum_max::copy_or_same(THD* thd)
bool Item_sum_max::add()
{
/* args[0] > value */
- int res= cmp->compare();
- if (!args[0]->null_value &&
- (null_value || res > 0))
+ arg_cache->cache_value();
+ if (!arg_cache->null_value &&
+ (null_value || cmp->compare() > 0))
{
- value->store(args[0]);
+ value->store(arg_cache);
value->cache_value();
null_value= 0;
}
@@ -2244,7 +2263,7 @@ void Item_sum_avg::reset_field()
void Item_sum_bit::reset_field()
{
- reset();
+ reset_and_add();
int8store(result_field->ptr, bits);
}
@@ -3057,6 +3076,7 @@ Item_func_group_concat(Name_resolution_context *context_arg,
order_item->item= arg_ptr++;
}
}
+ memcpy(orig_args, args, sizeof(Item*) * arg_count);
}
@@ -3267,7 +3287,6 @@ Item_func_group_concat::fix_fields(THD *thd, Item **ref)
if (check_sum_func(thd, ref))
return TRUE;
- memcpy (orig_args, args, sizeof (Item *) * arg_count);
fixed= 1;
return FALSE;
}
@@ -3423,8 +3442,6 @@ String* Item_func_group_concat::val_str(String* str)
void Item_func_group_concat::print(String *str, enum_query_type query_type)
{
- /* orig_args is not filled with valid values until fix_fields() */
- Item **pargs= fixed ? orig_args : args;
str->append(STRING_WITH_LEN("group_concat("));
if (distinct)
str->append(STRING_WITH_LEN("distinct "));
@@ -3432,7 +3449,7 @@ void Item_func_group_concat::print(String *str, enum_query_type query_type)
{
if (i)
str->append(',');
- pargs[i]->print(str, query_type);
+ orig_args[i]->print(str, query_type);
}
if (arg_count_order)
{
@@ -3441,7 +3458,7 @@ void Item_func_group_concat::print(String *str, enum_query_type query_type)
{
if (i)
str->append(',');
- pargs[i + arg_count_field]->print(str, query_type);
+ orig_args[i + arg_count_field]->print(str, query_type);
if (order[i]->asc)
str->append(STRING_WITH_LEN(" ASC"));
else
diff --git a/sql/item_sum.h b/sql/item_sum.h
index 9e017aa98d5..cf5a08ca271 100644
--- a/sql/item_sum.h
+++ b/sql/item_sum.h
@@ -101,6 +101,15 @@ public:
*/
virtual void endup() = 0;
+ /** Decimal value of being-aggregated argument */
+ virtual my_decimal *arg_val_decimal(my_decimal * value) = 0;
+ /** Floating point value of being-aggregated argument */
+ virtual double arg_val_real() = 0;
+ /**
+ NULLness of being-aggregated argument; can be called only after
+ arg_val_decimal() or arg_val_real().
+ */
+ virtual bool arg_is_null() = 0;
};
@@ -304,6 +313,7 @@ class st_select_lex;
class Item_sum :public Item_result_field
{
friend class Aggregator_distinct;
+ friend class Aggregator_simple;
protected:
/**
@@ -402,14 +412,22 @@ public:
Item_sum(THD *thd, Item_sum *item);
enum Type type() const { return SUM_FUNC_ITEM; }
virtual enum Sumfunctype sum_func () const=0;
- inline bool reset() { aggregator_clear(); return aggregator_add(); };
+ /**
+ Resets the aggregate value to its default and aggregates the current
+ value of its attribute(s).
+ */
+ inline bool reset_and_add()
+ {
+ aggregator_clear();
+ return aggregator_add();
+ };
/*
Called when new group is started and results are being saved in
- a temporary table. Similar to reset(), but must also store value in
- result_field. Like reset() it is supposed to reset start value to
- default.
- This set of methods (reult_field(), reset_field, update_field()) of
+ a temporary table. Similarly to reset_and_add() it resets the
+ value to its default and aggregates the value of its
+ attribute(s), but must also store it in result_field.
+ This set of methods (result_item(), reset_field, update_field()) of
Item_sum is used only if quick_group is not null. Otherwise
copy_or_same() is used to obtain a copy of this item.
*/
@@ -442,6 +460,7 @@ public:
forced_const= TRUE;
}
virtual bool const_item() const { return forced_const; }
+ virtual bool const_during_execution() const { return false; }
virtual void print(String *str, enum_query_type query_type);
void fix_num_length_and_dec();
@@ -457,11 +476,10 @@ public:
*/
virtual void no_rows_in_result()
{
- if (!aggr)
- set_aggregator(with_distinct ?
- Aggregator::DISTINCT_AGGREGATOR :
- Aggregator::SIMPLE_AGGREGATOR);
- reset();
+ set_aggregator(with_distinct ?
+ Aggregator::DISTINCT_AGGREGATOR :
+ Aggregator::SIMPLE_AGGREGATOR);
+ aggregator_clear();
}
virtual void make_unique() { force_copy_fields= TRUE; }
Item *get_tmp_table_item(THD *thd);
@@ -511,11 +529,10 @@ public:
quick_group= with_distinct ? 0 : 1;
}
- /**
+ /*
Set the type of aggregation : DISTINCT or not.
- Called when the final determination is done about the aggregation
- type and the object is about to be used.
+ May be called multiple times.
*/
int set_aggregator(Aggregator::Aggregator_type aggregator);
@@ -619,6 +636,9 @@ public:
void clear();
bool add();
void endup();
+ virtual my_decimal *arg_val_decimal(my_decimal * value);
+ virtual double arg_val_real();
+ virtual bool arg_is_null();
bool unique_walk_function(void *element);
static int composite_key_cmp(void* arg, uchar* key1, uchar* key2);
@@ -642,6 +662,9 @@ public:
void clear() { item_sum->clear(); }
bool add() { return item_sum->add(); }
void endup() {};
+ virtual my_decimal *arg_val_decimal(my_decimal * value);
+ virtual double arg_val_real();
+ virtual bool arg_is_null();
};
@@ -997,7 +1020,7 @@ class Item_cache;
class Item_sum_hybrid :public Item_sum
{
protected:
- Item_cache *value;
+ Item_cache *value, *arg_cache;
Arg_comparator *cmp;
Item_result hybrid_type;
enum_field_types hybrid_field_type;
@@ -1007,14 +1030,14 @@ protected:
public:
Item_sum_hybrid(Item *item_par,int sign)
- :Item_sum(item_par), value(0), cmp(0),
+ :Item_sum(item_par), value(0), arg_cache(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(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)
+ :Item_sum(thd, item), value(item->value), arg_cache(0),
+ 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_hybrid(Item *item, Item *value_arg);
diff --git a/sql/item_timefunc.cc b/sql/item_timefunc.cc
index 6a5260ac235..d7cd2d459f4 100644
--- a/sql/item_timefunc.cc
+++ b/sql/item_timefunc.cc
@@ -315,8 +315,8 @@ static bool extract_date_time(DATE_TIME_FORMAT *format,
for (; ptr != end && val != val_end; ptr++)
{
/* Skip pre-space between each argument */
- while (val != val_end && my_isspace(cs, *val))
- val++;
+ if ((val+= cs->cset->scan(cs, val, val_end, MY_SEQ_SPACES)) >= val_end)
+ break;
if (*ptr == '%' && ptr+1 != end)
{
@@ -670,7 +670,7 @@ bool make_date_time(DATE_TIME_FORMAT *format, MYSQL_TIME *l_time,
system_charset_info);
break;
case 'W':
- if (type == MYSQL_TIMESTAMP_TIME)
+ if (type == MYSQL_TIMESTAMP_TIME || !(l_time->month || l_time->year))
return 1;
weekday= calc_weekday(calc_daynr(l_time->year,l_time->month,
l_time->day),0);
@@ -679,7 +679,7 @@ bool make_date_time(DATE_TIME_FORMAT *format, MYSQL_TIME *l_time,
system_charset_info);
break;
case 'a':
- if (type == MYSQL_TIMESTAMP_TIME)
+ if (type == MYSQL_TIMESTAMP_TIME || !(l_time->month || l_time->year))
return 1;
weekday=calc_weekday(calc_daynr(l_time->year,l_time->month,
l_time->day),0);
@@ -844,7 +844,7 @@ bool make_date_time(DATE_TIME_FORMAT *format, MYSQL_TIME *l_time,
}
break;
case 'w':
- if (type == MYSQL_TIMESTAMP_TIME)
+ if (type == MYSQL_TIMESTAMP_TIME || !(l_time->month || l_time->year))
return 1;
weekday=calc_weekday(calc_daynr(l_time->year,l_time->month,
l_time->day),1);
@@ -1140,16 +1140,13 @@ String* Item_func_monthname::val_str(String* str)
{
DBUG_ASSERT(fixed == 1);
const char *month_name;
- uint month= (uint) val_int();
uint err;
+ MYSQL_TIME ltime;
- if (null_value || !month)
- {
- null_value=1;
- return (String*) 0;
- }
- null_value=0;
- month_name= locale->month_names->type_names[month-1];
+ if ((null_value= (get_arg0_date(&ltime, TIME_FUZZY_DATE) || !ltime.month)))
+ return (String *) 0;
+
+ month_name= locale->month_names->type_names[ltime.month - 1];
str->copy(month_name, (uint) strlen(month_name), &my_charset_utf8_bin,
collation.collation, &err);
return str;
@@ -1398,6 +1395,26 @@ longlong Item_func_unix_timestamp::val_int()
return (longlong) TIME_to_timestamp(current_thd, &ltime, &not_used);
}
+enum_monotonicity_info Item_func_unix_timestamp::get_monotonicity_info() const
+{
+ if (args[0]->type() == Item::FIELD_ITEM &&
+ (args[0]->field_type() == MYSQL_TYPE_TIMESTAMP))
+ return MONOTONIC_INCREASING;
+ return NON_MONOTONIC;
+}
+
+
+longlong Item_func_unix_timestamp::val_int_endpoint(bool left_endp, bool *incl_endp)
+{
+ DBUG_ASSERT(fixed == 1);
+ DBUG_ASSERT(arg_count == 1 &&
+ args[0]->type() == Item::FIELD_ITEM &&
+ args[0]->field_type() == MYSQL_TYPE_TIMESTAMP);
+ Field *field=((Item_field*) args[0])->field;
+ /* Leave the incl_endp intact */
+ return ((Field_timestamp*) field)->get_timestamp(&null_value);
+}
+
longlong Item_func_time_to_sec::val_int()
{
@@ -1601,6 +1618,11 @@ bool Item_func_from_days::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
return 1;
bzero(ltime, sizeof(MYSQL_TIME));
get_date_from_daynr((long) value, &ltime->year, &ltime->month, &ltime->day);
+
+ if ((null_value= (fuzzy_date & TIME_NO_ZERO_DATE) &&
+ (ltime->year == 0 || ltime->month == 0 || ltime->day == 0)))
+ return TRUE;
+
ltime->time_type= MYSQL_TIMESTAMP_DATE;
return 0;
}
@@ -2212,8 +2234,6 @@ void Item_date_add_interval::fix_length_and_dec()
enum_field_types arg0_field_type;
maybe_null=1;
- fix_length_and_charset_datetime(MAX_DATETIME_FULL_WIDTH);
- value.alloc(max_length);
/*
The field type for the result of an Item_date function is defined as
@@ -2238,6 +2258,21 @@ void Item_date_add_interval::fix_length_and_dec()
else
cached_field_type= MYSQL_TYPE_DATETIME;
}
+
+ if (cached_field_type == MYSQL_TYPE_STRING)
+ {
+ /* Behave as a usual string function when return type is VARCHAR. */
+ fix_length_and_charset(MAX_DATETIME_FULL_WIDTH, default_charset());
+ }
+ else
+ {
+ /*
+ Follow the "Number-to-string conversion" rules as in WorkLog 2649
+ when return type is DATE or DATETIME.
+ */
+ fix_length_and_charset_datetime(MAX_DATETIME_FULL_WIDTH);
+ }
+ value.alloc(max_length);
}
@@ -2260,7 +2295,7 @@ bool Item_date_add_interval::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
}
-String *Item_date_add_interval::val_str(String *str)
+String *Item_date_add_interval::val_str_ascii(String *str)
{
DBUG_ASSERT(fixed == 1);
MYSQL_TIME ltime;
@@ -2521,6 +2556,19 @@ String *Item_char_typecast::val_str(String *str)
String *res;
uint32 length;
+ if (cast_length >= 0 &&
+ ((unsigned) cast_length) > current_thd->variables.max_allowed_packet)
+ {
+ push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ ER_WARN_ALLOWED_PACKET_OVERFLOWED,
+ ER(ER_WARN_ALLOWED_PACKET_OVERFLOWED),
+ cast_cs == &my_charset_bin ?
+ "cast_as_binary" : func_name(),
+ current_thd->variables.max_allowed_packet);
+ null_value= 1;
+ return 0;
+ }
+
if (!charset_conversion)
{
if (!(res= args[0]->val_str(str)))
@@ -2533,14 +2581,14 @@ String *Item_char_typecast::val_str(String *str)
{
// Convert character set if differ
uint dummy_errors;
- if (!(res= args[0]->val_str(&tmp_value)) ||
- str->copy(res->ptr(), res->length(), from_cs,
- cast_cs, &dummy_errors))
+ if (!(res= args[0]->val_str(str)) ||
+ tmp_value.copy(res->ptr(), res->length(), from_cs,
+ cast_cs, &dummy_errors))
{
null_value= 1;
return 0;
}
- res= str;
+ res= &tmp_value;
}
res->set_charset(cast_cs);
@@ -2575,9 +2623,9 @@ String *Item_char_typecast::val_str(String *str)
{
if (res->alloced_length() < (uint) cast_length)
{
- str->alloc(cast_length);
- str->copy(*res);
- res= str;
+ str_value.alloc(cast_length);
+ str_value.copy(*res);
+ res= &str_value;
}
bzero((char*) res->ptr() + res->length(),
(uint) cast_length - res->length());
@@ -2763,7 +2811,7 @@ String *Item_func_makedate::val_str(String *str)
long days;
if (args[0]->null_value || args[1]->null_value ||
- year < 0 || daynr <= 0)
+ year < 0 || year > 9999 || daynr <= 0)
goto err;
if (year < 100)
@@ -2806,7 +2854,7 @@ longlong Item_func_makedate::val_int()
long days;
if (args[0]->null_value || args[1]->null_value ||
- year < 0 || daynr <= 0)
+ year < 0 || year > 9999 || daynr <= 0)
goto err;
if (year < 100)
@@ -2864,10 +2912,11 @@ void Item_func_add_time::fix_length_and_dec()
Result: Time value or datetime value
*/
-String *Item_func_add_time::val_str(String *str)
+MYSQL_TIME *Item_func_add_time::val_datetime(MYSQL_TIME *time,
+ date_time_format_types *format)
{
DBUG_ASSERT(fixed == 1);
- MYSQL_TIME l_time1, l_time2, l_time3;
+ MYSQL_TIME l_time1, l_time2;
bool is_time= 0;
long days, microseconds;
longlong seconds;
@@ -2893,41 +2942,38 @@ String *Item_func_add_time::val_str(String *str)
if (l_time1.neg != l_time2.neg)
l_sign= -l_sign;
- bzero((char *)&l_time3, sizeof(l_time3));
+ bzero((char *)time, sizeof(MYSQL_TIME));
- l_time3.neg= calc_time_diff(&l_time1, &l_time2, -l_sign,
- &seconds, &microseconds);
+ time->neg= calc_time_diff(&l_time1, &l_time2, -l_sign,
+ &seconds, &microseconds);
/*
If first argument was negative and diff between arguments
is non-zero we need to swap sign to get proper result.
*/
if (l_time1.neg && (seconds || microseconds))
- l_time3.neg= 1-l_time3.neg; // Swap sign of result
+ time->neg= 1 - time->neg; // Swap sign of result
- if (!is_time && l_time3.neg)
+ if (!is_time && time->neg)
goto null_date;
days= (long)(seconds/86400L);
- calc_time_from_sec(&l_time3, (long)(seconds%86400L), microseconds);
+ calc_time_from_sec(time, (long)(seconds%86400L), microseconds);
if (!is_time)
{
- get_date_from_daynr(days,&l_time3.year,&l_time3.month,&l_time3.day);
- if (l_time3.day &&
- !make_datetime(l_time1.second_part || l_time2.second_part ?
- DATE_TIME_MICROSECOND : DATE_TIME,
- &l_time3, str))
- return str;
+ get_date_from_daynr(days, &time->year, &time->month, &time->day);
+ *format= l_time1.second_part || l_time2.second_part ?
+ DATE_TIME_MICROSECOND : DATE_TIME;
+ if (time->day)
+ return time;
goto null_date;
}
-
- l_time3.hour+= days*24;
- if (!make_datetime_with_warn(l_time1.second_part || l_time2.second_part ?
- TIME_MICROSECOND : TIME_ONLY,
- &l_time3, str))
- return str;
+ *format= l_time1.second_part || l_time2.second_part ?
+ TIME_MICROSECOND : TIME_ONLY;
+ time->hour+= days*24;
+ return time;
null_date:
null_value=1;
@@ -2935,6 +2981,38 @@ null_date:
}
+String *Item_func_add_time::val_str(String *str)
+{
+ MYSQL_TIME ltime;
+ date_time_format_types format;
+
+ val_datetime(&ltime, &format);
+
+ if (null_value)
+ return 0;
+
+ if (!make_datetime_with_warn(format, &ltime, str))
+ return str;
+
+ null_value= 1;
+ return 0;
+}
+
+
+longlong Item_func_add_time::val_int()
+{
+ MYSQL_TIME ltime;
+ date_time_format_types format;
+
+ val_datetime(&ltime, &format);
+
+ if (null_value)
+ return 0;
+
+ return TIME_to_ulonglong_datetime(&ltime);
+}
+
+
void Item_func_add_time::print(String *str, enum_query_type query_type)
{
if (is_date)
@@ -3372,6 +3450,7 @@ void Item_func_str_to_date::fix_length_and_dec()
{
maybe_null= 1;
decimals=0;
+ cached_format_type= DATE_TIME;
cached_field_type= MYSQL_TYPE_DATETIME;
max_length= MAX_DATETIME_FULL_WIDTH*MY_CHARSET_BIN_MB_MAXLEN;
cached_timestamp_type= MYSQL_TIMESTAMP_NONE;
@@ -3442,7 +3521,7 @@ bool Item_func_str_to_date::get_date(MYSQL_TIME *ltime, uint fuzzy_date)
return 0;
null_date:
- if (fuzzy_date & TIME_NO_ZERO_DATE)
+ if (val && (fuzzy_date & TIME_NO_ZERO_DATE))
{
char buff[128];
strmake(buff, val->ptr(), min(val->length(), sizeof(buff)-1));
diff --git a/sql/item_timefunc.h b/sql/item_timefunc.h
index c4c8fe39933..c6e081df182 100644
--- a/sql/item_timefunc.h
+++ b/sql/item_timefunc.h
@@ -1,7 +1,7 @@
#ifndef ITEM_TIMEFUNC_INCLUDED
#define ITEM_TIMEFUNC_INCLUDED
-/* Copyright (C) 2000-2006 MySQL AB
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -76,6 +76,10 @@ public:
longlong val_int_endpoint(bool left_endp, bool *incl_endp);
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -103,6 +107,12 @@ public:
*input_version= output_version;
return 0;
}
+
+ /* Only meaningful with date part and optional time part */
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -120,6 +130,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -132,8 +146,11 @@ public:
{ DBUG_ASSERT(fixed == 1); return (double) Item_func_month::val_int(); }
String *val_str(String *str)
{
- str->set(val_int(), collation.collation);
- return null_value ? 0 : str;
+ longlong nr= val_int();
+ if (null_value)
+ return 0;
+ str->set(nr, collation.collation);
+ return str;
}
const char *func_name() const { return "month"; }
enum Item_result result_type () const { return INT_RESULT; }
@@ -145,20 +162,27 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
-class Item_func_monthname :public Item_func_month
+class Item_func_monthname :public Item_str_func
{
MY_LOCALE *locale;
public:
- Item_func_monthname(Item *a) :Item_func_month(a) {}
+ Item_func_monthname(Item *a) :Item_str_func(a) {}
const char *func_name() const { return "monthname"; }
String *val_str(String *str);
- enum Item_result result_type () const { return STRING_RESULT; }
void fix_length_and_dec();
bool check_partition_func_processor(uchar *int_arg) {return TRUE;}
bool check_vcol_func_processor(uchar *int_arg) {return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -176,6 +200,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -193,6 +221,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_time_args();
+ }
};
@@ -210,6 +242,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_time_args();
+ }
};
@@ -227,6 +263,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -244,6 +284,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_time_args();
+ }
};
@@ -275,6 +319,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -294,6 +342,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
@@ -324,6 +376,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_date_args();
+ }
};
class Item_func_dayname :public Item_func_weekday
@@ -348,13 +404,15 @@ public:
Item_func_unix_timestamp(Item *a) :Item_int_func(a) {}
longlong val_int();
const char *func_name() const { return "unix_timestamp"; }
+ enum_monotonicity_info get_monotonicity_info() const;
+ longlong val_int_endpoint(bool left_endp, bool *incl_endp);
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
/*
UNIX_TIMESTAMP() depends on the current timezone
(and thus may not be used as a partitioning function)
when its argument is NOT of the TIMESTAMP type.
*/
- bool is_timezone_dependent_processor(uchar *int_arg)
+ bool check_valid_arguments_processor(uchar *int_arg)
{
return !has_timestamp_args();
}
@@ -382,11 +440,16 @@ public:
const char *func_name() const { return "time_to_sec"; }
void fix_length_and_dec()
{
+ maybe_null= TRUE;
decimals=0;
max_length=10*MY_CHARSET_BIN_MB_MAXLEN;
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_time_args();
+ }
};
@@ -655,6 +718,10 @@ public:
bool get_date(MYSQL_TIME *res, uint fuzzy_date);
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return has_date_args() || has_time_args();
+ }
};
@@ -749,16 +816,32 @@ class Item_date_add_interval :public Item_date_func
{
String value;
enum_field_types cached_field_type;
-
+ String ascii_buf;
public:
const interval_type int_type; // keep it public
const bool date_sub_interval; // keep it public
Item_date_add_interval(Item *a,Item *b,interval_type type_arg,bool neg_arg)
:Item_date_func(a,b),int_type(type_arg), date_sub_interval(neg_arg) {}
- String *val_str(String *);
+ String *val_str_ascii(String *str);
+ String *val_str(String *str)
+ {
+ return val_str_from_val_str_ascii(str, &ascii_buf);
+ }
const char *func_name() const { return "date_add_interval"; }
void fix_length_and_dec();
enum_field_types field_type() const { return cached_field_type; }
+ CHARSET_INFO *charset_for_protocol(void) const
+ {
+ /*
+ DATE_ADD() can return DATE, DATETIME or VARCHAR depending on arguments.
+ Send using "binary" when DATE or DATETIME,
+ or using collation.collation when VARCHAR
+ (which was fixed from @collation_connection in fix_length_and_dec).
+ */
+ DBUG_ASSERT(fixed == 1);
+ return cached_field_type == MYSQL_TYPE_STRING ?
+ collation.collation : &my_charset_bin;
+ }
longlong val_int();
bool get_date(MYSQL_TIME *res, uint fuzzy_date);
bool eq(const Item *item, bool binary_cmp) const;
@@ -781,6 +864,42 @@ class Item_extract :public Item_int_func
virtual void print(String *str, enum_query_type query_type);
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ switch (int_type) {
+ case INTERVAL_YEAR:
+ case INTERVAL_YEAR_MONTH:
+ case INTERVAL_QUARTER:
+ case INTERVAL_MONTH:
+ /* case INTERVAL_WEEK: Not allowed as partitioning function, bug#57071 */
+ case INTERVAL_DAY:
+ return !has_date_args();
+ case INTERVAL_DAY_HOUR:
+ case INTERVAL_DAY_MINUTE:
+ case INTERVAL_DAY_SECOND:
+ case INTERVAL_DAY_MICROSECOND:
+ return !has_datetime_args();
+ case INTERVAL_HOUR:
+ case INTERVAL_HOUR_MINUTE:
+ case INTERVAL_HOUR_SECOND:
+ case INTERVAL_MINUTE:
+ case INTERVAL_MINUTE_SECOND:
+ case INTERVAL_SECOND:
+ case INTERVAL_MICROSECOND:
+ case INTERVAL_HOUR_MICROSECOND:
+ case INTERVAL_MINUTE_MICROSECOND:
+ case INTERVAL_SECOND_MICROSECOND:
+ return !has_time_args();
+ default:
+ /*
+ INTERVAL_LAST is only an end marker,
+ INTERVAL_WEEK depends on default_week_format which is a session
+ variable and cannot be used for partitioning. See bug#57071.
+ */
+ break;
+ }
+ return true;
+ }
};
@@ -984,6 +1103,8 @@ public:
return save_date_in_field(field);
return Item_str_func::save_in_field(field, no_conversions);
}
+ longlong val_int();
+ MYSQL_TIME *val_datetime(MYSQL_TIME *time, date_time_format_types *format);
};
class Item_func_timediff :public Item_str_timefunc
@@ -1025,6 +1146,10 @@ public:
}
bool check_partition_func_processor(uchar *int_arg) {return FALSE;}
bool check_vcol_func_processor(uchar *int_arg) { return FALSE;}
+ bool check_valid_arguments_processor(uchar *int_arg)
+ {
+ return !has_time_args();
+ }
};
diff --git a/sql/item_xmlfunc.cc b/sql/item_xmlfunc.cc
index 792008ba35e..183c07c1781 100644
--- a/sql/item_xmlfunc.cc
+++ b/sql/item_xmlfunc.cc
@@ -2807,12 +2807,12 @@ String *Item_func_xml_extractvalue::val_str(String *str)
null_value= 0;
if (!nodeset_func ||
!(res= args[0]->val_str(str)) ||
- !parse_xml(res, &pxml))
+ !parse_xml(res, &pxml) ||
+ !(res= nodeset_func->val_str(&tmp_value)))
{
null_value= 1;
return 0;
}
- res= nodeset_func->val_str(&tmp_value);
return res;
}
diff --git a/sql/key.cc b/sql/key.cc
index 8c7eab2a688..819b79879e8 100644
--- a/sql/key.cc
+++ b/sql/key.cc
@@ -360,12 +360,10 @@ void key_unpack(String *to,TABLE *table,uint idx)
if (field->binary() && field->type() == MYSQL_TYPE_STRING && tmp.length())
{
const char *tmp_end= tmp.ptr() + tmp.length();
- while (tmp_end > tmp.ptr() && !*--tmp_end);
+ while (tmp_end > tmp.ptr() && !*--tmp_end) ;
tmp.length(tmp_end - tmp.ptr() + 1);
}
- if (cs->mbmaxlen > 1 &&
- table->field[key_part->fieldnr - 1]->field_length !=
- key_part->length)
+ if (cs->mbmaxlen > 1 && (key_part->key_part_flag & HA_PART_KEY_SEG))
{
/*
Prefix key, multi-byte charset.
diff --git a/sql/lex.h b/sql/lex.h
index b1c23e81748..982034c31af 100644
--- a/sql/lex.h
+++ b/sql/lex.h
@@ -427,8 +427,9 @@ static SYMBOL symbols[] = {
{ "PROCEDURE", SYM(PROCEDURE_SYM)},
{ "PROCESS" , SYM(PROCESS)},
{ "PROCESSLIST", SYM(PROCESSLIST_SYM)},
- { "PROFILE", SYM(PROFILE_SYM)},
- { "PROFILES", SYM(PROFILES_SYM)},
+ { "PROFILE", SYM(PROFILE_SYM)},
+ { "PROFILES", SYM(PROFILES_SYM)},
+ { "PROXY", SYM(PROXY_SYM)},
{ "PURGE", SYM(PURGE)},
{ "QUARTER", SYM(QUARTER_SYM)},
{ "QUERY", SYM(QUERY_SYM)},
diff --git a/sql/lock.cc b/sql/lock.cc
index 26a8a1ba35b..e88fa252517 100644
--- a/sql/lock.cc
+++ b/sql/lock.cc
@@ -806,8 +806,11 @@ bool lock_schema_name(THD *thd, const char *db)
return TRUE;
}
- global_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE);
- mdl_request.init(MDL_key::SCHEMA, db, "", MDL_EXCLUSIVE);
+ if (thd->global_read_lock.can_acquire_protection())
+ return TRUE;
+ global_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
+ MDL_STATEMENT);
+ mdl_request.init(MDL_key::SCHEMA, db, "", MDL_EXCLUSIVE, MDL_TRANSACTION);
mdl_requests.push_front(&mdl_request);
mdl_requests.push_front(&global_request);
@@ -822,13 +825,13 @@ bool lock_schema_name(THD *thd, const char *db)
/**
- Obtain an exclusive metadata lock on the stored routine name.
+ Obtain an exclusive metadata lock on an object name.
@param thd Thread handle.
- @param is_function Stored routine type (only functions or procedures
- are name-locked.
- @param db The schema the routine belongs to.
- @param name Routine name.
+ @param mdl_type Object type (currently functions, procedures
+ and events can be name-locked).
+ @param db The schema the object belongs to.
+ @param name Object name in the schema.
This function assumes that no metadata locks were acquired
before calling it. Additionally, it cannot be called while
@@ -844,12 +847,9 @@ bool lock_schema_name(THD *thd, const char *db)
or this connection was killed.
*/
-bool lock_routine_name(THD *thd, bool is_function,
+bool lock_object_name(THD *thd, MDL_key::enum_mdl_namespace mdl_type,
const char *db, const char *name)
{
- MDL_key::enum_mdl_namespace mdl_type= (is_function ?
- MDL_key::FUNCTION :
- MDL_key::PROCEDURE);
MDL_request_list mdl_requests;
MDL_request global_request;
MDL_request schema_request;
@@ -865,9 +865,13 @@ bool lock_routine_name(THD *thd, bool is_function,
DBUG_ASSERT(name);
DEBUG_SYNC(thd, "before_wait_locked_pname");
- global_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE);
- schema_request.init(MDL_key::SCHEMA, db, "", MDL_INTENTION_EXCLUSIVE);
- mdl_request.init(mdl_type, db, name, MDL_EXCLUSIVE);
+ if (thd->global_read_lock.can_acquire_protection())
+ return TRUE;
+ global_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
+ MDL_STATEMENT);
+ schema_request.init(MDL_key::SCHEMA, db, "", MDL_INTENTION_EXCLUSIVE,
+ MDL_TRANSACTION);
+ mdl_request.init(mdl_type, db, name, MDL_EXCLUSIVE, MDL_TRANSACTION);
mdl_requests.push_front(&mdl_request);
mdl_requests.push_front(&schema_request);
@@ -917,45 +921,24 @@ static void print_lock_error(int error, const char *table)
/****************************************************************************
Handling of global read locks
+ Global read lock is implemented using metadata lock infrastructure.
+
Taking the global read lock is TWO steps (2nd step is optional; without
it, COMMIT of existing transactions will be allowed):
lock_global_read_lock() THEN make_global_read_lock_block_commit().
- The global locks are handled through the global variables:
- global_read_lock
- count of threads which have the global read lock (i.e. have completed at
- least the first step above)
- global_read_lock_blocks_commit
- count of threads which have the global read lock and block
- commits (i.e. are in or have completed the second step above)
- waiting_for_read_lock
- count of threads which want to take a global read lock but cannot
- protect_against_global_read_lock
- count of threads which have set protection against global read lock.
-
- access to them is protected with a mutex LOCK_global_read_lock
-
- (XXX: one should never take LOCK_open if LOCK_global_read_lock is
- taken, otherwise a deadlock may occur. Other mutexes could be a
- problem too - grep the code for global_read_lock if you want to use
- any other mutex here) Also one must not hold LOCK_open when calling
- wait_if_global_read_lock(). When the thread with the global read lock
- tries to close its tables, it needs to take LOCK_open in
- close_thread_table().
-
How blocking of threads by global read lock is achieved: that's
- advisory. Any piece of code which should be blocked by global read lock must
- be designed like this:
- - call to wait_if_global_read_lock(). When this returns 0, no global read
- lock is owned; if argument abort_on_refresh was 0, none can be obtained.
- - job
- - if abort_on_refresh was 0, call to start_waiting_global_read_lock() to
- allow other threads to get the global read lock. I.e. removal of the
- protection.
- (Note: it's a bit like an implementation of rwlock).
-
- [ I am sorry to mention some SQL syntaxes below I know I shouldn't but found
- no better descriptive way ]
+ semi-automatic. We assume that any statement which should be blocked
+ by global read lock will either open and acquires write-lock on tables
+ or acquires metadata locks on objects it is going to modify. For any
+ such statement global IX metadata lock is automatically acquired for
+ its duration (in case of LOCK TABLES until end of LOCK TABLES mode).
+ And lock_global_read_lock() simply acquires global S metadata lock
+ and thus prohibits execution of statements which modify data (unless
+ they modify only temporary tables). If deadlock happens it is detected
+ by MDL subsystem and resolved in the standard fashion (by backing-off
+ metadata locks acquired so far and restarting open tables process
+ if possible).
Why does FLUSH TABLES WITH READ LOCK need to block COMMIT: because it's used
to read a non-moving SHOW MASTER STATUS, and a COMMIT writes to the binary
@@ -989,11 +972,6 @@ static void print_lock_error(int error, const char *table)
****************************************************************************/
-volatile uint global_read_lock=0;
-volatile uint global_read_lock_blocks_commit=0;
-static volatile uint protect_against_global_read_lock=0;
-static volatile uint waiting_for_read_lock=0;
-
/**
Take global read lock, wait if there is protection against lock.
@@ -1014,85 +992,17 @@ bool Global_read_lock::lock_global_read_lock(THD *thd)
if (!m_state)
{
MDL_request mdl_request;
- const char *old_message;
- const char *new_message= "Waiting to get readlock";
- (void) mysql_mutex_lock(&LOCK_global_read_lock);
-
-#if defined(ENABLED_DEBUG_SYNC)
- /*
- The below sync point fires if we have to wait for
- protect_against_global_read_lock.
-
- WARNING: Beware to use WAIT_FOR with this sync point. We hold
- LOCK_global_read_lock here.
-
- Call the sync point before calling enter_cond() as it does use
- enter_cond() and exit_cond() itself if a WAIT_FOR action is
- executed in spite of the above warning.
-
- Pre-set proc_info so that it is available immediately after the
- sync point sends a SIGNAL. This makes tests more reliable.
- */
- if (protect_against_global_read_lock)
- {
- thd_proc_info(thd, new_message);
- DEBUG_SYNC(thd, "wait_lock_global_read_lock");
- }
-#endif /* defined(ENABLED_DEBUG_SYNC) */
-
- old_message=thd->enter_cond(&COND_global_read_lock, &LOCK_global_read_lock,
- new_message);
- DBUG_PRINT("info",
- ("waiting_for: %d protect_against: %d",
- waiting_for_read_lock, protect_against_global_read_lock));
-
- waiting_for_read_lock++;
- while (protect_against_global_read_lock && !thd->killed)
- mysql_cond_wait(&COND_global_read_lock, &LOCK_global_read_lock);
- waiting_for_read_lock--;
- if (thd->killed)
- {
- thd->exit_cond(old_message);
- DBUG_RETURN(1);
- }
- m_state= GRL_ACQUIRED;
- global_read_lock++;
- thd->exit_cond(old_message); // this unlocks LOCK_global_read_lock
- /*
- When we perform FLUSH TABLES or ALTER TABLE under LOCK TABLES,
- tables being reopened are protected only by meta-data locks at
- some point. To avoid sneaking in with our global read lock at
- this moment we have to take global shared meta data lock.
-
- TODO: We should change this code to acquire global shared metadata
- lock before acquiring global read lock. But in order to do
- this we have to get rid of all those places in which
- wait_if_global_read_lock() is called before acquiring
- metadata locks first. Also long-term we should get rid of
- redundancy between metadata locks, global read lock and DDL
- blocker (see WL#4399 and WL#4400).
- */
DBUG_ASSERT(! thd->mdl_context.is_lock_owner(MDL_key::GLOBAL, "", "",
MDL_SHARED));
- mdl_request.init(MDL_key::GLOBAL, "", "", MDL_SHARED);
+ mdl_request.init(MDL_key::GLOBAL, "", "", MDL_SHARED, MDL_EXPLICIT);
if (thd->mdl_context.acquire_lock(&mdl_request,
thd->variables.lock_wait_timeout))
- {
- /* Our thread was killed -- return back to initial state. */
- mysql_mutex_lock(&LOCK_global_read_lock);
- if (!(--global_read_lock))
- {
- DBUG_PRINT("signal", ("Broadcasting COND_global_read_lock"));
- mysql_cond_broadcast(&COND_global_read_lock);
- }
- mysql_mutex_unlock(&LOCK_global_read_lock);
- m_state= GRL_NONE;
DBUG_RETURN(1);
- }
- thd->mdl_context.move_ticket_after_trans_sentinel(mdl_request.ticket);
+
m_mdl_global_shared_lock= mdl_request.ticket;
+ m_state= GRL_ACQUIRED;
}
/*
We DON'T set global_read_lock_blocks_commit now, it will be set after
@@ -1118,166 +1028,22 @@ bool Global_read_lock::lock_global_read_lock(THD *thd)
void Global_read_lock::unlock_global_read_lock(THD *thd)
{
- uint tmp;
DBUG_ENTER("unlock_global_read_lock");
- DBUG_PRINT("info",
- ("global_read_lock: %u global_read_lock_blocks_commit: %u",
- global_read_lock, global_read_lock_blocks_commit));
DBUG_ASSERT(m_mdl_global_shared_lock && m_state);
- thd->mdl_context.release_lock(m_mdl_global_shared_lock);
- m_mdl_global_shared_lock= NULL;
-
- mysql_mutex_lock(&LOCK_global_read_lock);
- tmp= --global_read_lock;
- if (m_state == GRL_ACQUIRED_AND_BLOCKS_COMMIT)
- --global_read_lock_blocks_commit;
- mysql_mutex_unlock(&LOCK_global_read_lock);
- /* Send the signal outside the mutex to avoid a context switch */
- if (!tmp)
+ if (m_mdl_blocks_commits_lock)
{
- DBUG_PRINT("signal", ("Broadcasting COND_global_read_lock"));
- mysql_cond_broadcast(&COND_global_read_lock);
+ thd->mdl_context.release_lock(m_mdl_blocks_commits_lock);
+ m_mdl_blocks_commits_lock= NULL;
}
+ thd->mdl_context.release_lock(m_mdl_global_shared_lock);
+ m_mdl_global_shared_lock= NULL;
m_state= GRL_NONE;
DBUG_VOID_RETURN;
}
-/**
- Wait if the global read lock is set, and optionally seek protection against
- global read lock.
-
- See also "Handling of global read locks" above.
-
- @param thd Reference to thread.
- @param abort_on_refresh If True, abort waiting if a refresh occurs,
- do NOT seek protection against GRL.
- If False, wait until the GRL is released and seek
- protection against GRL.
- @param is_not_commit If False, called from a commit operation,
- wait only if commit blocking is also enabled.
-
- @retval False Success, protection against global read lock is set
- (if !abort_on_refresh)
- @retval True Failure, wait was aborted or thread was killed.
-*/
-
-#define must_wait (global_read_lock && \
- (is_not_commit || \
- global_read_lock_blocks_commit))
-
-bool Global_read_lock::
-wait_if_global_read_lock(THD *thd, bool abort_on_refresh,
- bool is_not_commit)
-{
- const char *UNINIT_VAR(old_message);
- bool result= 0, need_exit_cond;
- DBUG_ENTER("wait_if_global_read_lock");
-
- /*
- If we already have protection against global read lock,
- just increment the counter.
- */
- if (unlikely(m_protection_count > 0))
- {
- if (!abort_on_refresh)
- m_protection_count++;
- DBUG_RETURN(FALSE);
- }
- /*
- Assert that we do not own LOCK_open. If we would own it, other
- threads could not close their tables. This would make a pretty
- deadlock.
- */
- mysql_mutex_assert_not_owner(&LOCK_open);
-
- mysql_mutex_lock(&LOCK_global_read_lock);
- if ((need_exit_cond= must_wait))
- {
- if (m_state) // This thread had the read locks
- {
- if (is_not_commit)
- my_message(ER_CANT_UPDATE_WITH_READLOCK,
- ER(ER_CANT_UPDATE_WITH_READLOCK), MYF(0));
- mysql_mutex_unlock(&LOCK_global_read_lock);
- /*
- We allow FLUSHer to COMMIT; we assume FLUSHer knows what it does.
- This allowance is needed to not break existing versions of innobackup
- which do a BEGIN; INSERT; FLUSH TABLES WITH READ LOCK; COMMIT.
- */
- DBUG_RETURN(is_not_commit);
- }
- old_message=thd->enter_cond(&COND_global_read_lock, &LOCK_global_read_lock,
- "Waiting for release of readlock");
- while (must_wait && ! thd->killed &&
- (!abort_on_refresh || !thd->open_tables ||
- thd->open_tables->s->version == refresh_version))
- {
- DBUG_PRINT("signal", ("Waiting for COND_global_read_lock"));
- mysql_cond_wait(&COND_global_read_lock, &LOCK_global_read_lock);
- DBUG_PRINT("signal", ("Got COND_global_read_lock"));
- }
- if (thd->killed)
- result=1;
- }
- if (!abort_on_refresh && !result)
- {
- m_protection_count++;
- protect_against_global_read_lock++;
- DBUG_PRINT("sql_lock", ("protect_against_global_read_lock incr: %u",
- protect_against_global_read_lock));
- }
- /*
- The following is only true in case of a global read locks (which is rare)
- and if old_message is set
- */
- if (unlikely(need_exit_cond))
- thd->exit_cond(old_message); // this unlocks LOCK_global_read_lock
- else
- mysql_mutex_unlock(&LOCK_global_read_lock);
- DBUG_RETURN(result);
-}
-
-
-/**
- Release protection against global read lock and restart
- global read lock waiters.
-
- Should only be called if we have protection against global read lock.
-
- See also "Handling of global read locks" above.
-
- @param thd Reference to thread.
-*/
-
-void Global_read_lock::start_waiting_global_read_lock(THD *thd)
-{
- bool tmp;
- DBUG_ENTER("start_waiting_global_read_lock");
- /*
- Ignore request if we do not have protection against global read lock.
- (Note that this is a violation of the interface contract, hence the assert).
- */
- DBUG_ASSERT(m_protection_count > 0);
- if (unlikely(m_protection_count == 0))
- DBUG_VOID_RETURN;
- /* Decrement local read lock protection counter, return if we still have it */
- if (unlikely(--m_protection_count > 0))
- DBUG_VOID_RETURN;
- if (unlikely(m_state))
- DBUG_VOID_RETURN;
- mysql_mutex_lock(&LOCK_global_read_lock);
- DBUG_ASSERT(protect_against_global_read_lock);
- tmp= (!--protect_against_global_read_lock &&
- (waiting_for_read_lock || global_read_lock_blocks_commit));
- mysql_mutex_unlock(&LOCK_global_read_lock);
- if (tmp)
- mysql_cond_broadcast(&COND_global_read_lock);
- DBUG_VOID_RETURN;
-}
-
/**
Make global read lock also block commits.
@@ -1296,8 +1062,7 @@ void Global_read_lock::start_waiting_global_read_lock(THD *thd)
bool Global_read_lock::make_global_read_lock_block_commit(THD *thd)
{
- bool error;
- const char *old_message;
+ MDL_request mdl_request;
DBUG_ENTER("make_global_read_lock_block_commit");
/*
If we didn't succeed lock_global_read_lock(), or if we already suceeded
@@ -1305,42 +1070,32 @@ bool Global_read_lock::make_global_read_lock_block_commit(THD *thd)
*/
if (m_state != GRL_ACQUIRED)
DBUG_RETURN(0);
- mysql_mutex_lock(&LOCK_global_read_lock);
- /* increment this BEFORE waiting on cond (otherwise race cond) */
- global_read_lock_blocks_commit++;
- /* For testing we set up some blocking, to see if we can be killed */
- DBUG_EXECUTE_IF("make_global_read_lock_block_commit_loop",
- protect_against_global_read_lock++;);
- old_message= thd->enter_cond(&COND_global_read_lock, &LOCK_global_read_lock,
- "Waiting for all running commits to finish");
- while (protect_against_global_read_lock && !thd->killed)
- mysql_cond_wait(&COND_global_read_lock, &LOCK_global_read_lock);
- DBUG_EXECUTE_IF("make_global_read_lock_block_commit_loop",
- protect_against_global_read_lock--;);
- if ((error= test(thd->killed)))
- global_read_lock_blocks_commit--; // undo what we did
- else
- m_state= GRL_ACQUIRED_AND_BLOCKS_COMMIT;
- thd->exit_cond(old_message); // this unlocks LOCK_global_read_lock
- DBUG_RETURN(error);
+
+ mdl_request.init(MDL_key::COMMIT, "", "", MDL_SHARED, MDL_EXPLICIT);
+
+ if (thd->mdl_context.acquire_lock(&mdl_request,
+ thd->variables.lock_wait_timeout))
+ DBUG_RETURN(TRUE);
+
+ m_mdl_blocks_commits_lock= mdl_request.ticket;
+ m_state= GRL_ACQUIRED_AND_BLOCKS_COMMIT;
+
+ DBUG_RETURN(FALSE);
}
/**
- Broadcast COND_global_read_lock.
-
- TODO/FIXME: Dmitry thinks that we broadcast on COND_global_read_lock
- when old instance of table is closed to avoid races
- between incrementing refresh_version and
- wait_if_global_read_lock(thd, TRUE, FALSE) call.
- Once global read lock implementation starts using MDL
- infrastructure this will became unnecessary and should
- be removed.
+ Set explicit duration for metadata locks which are used to implement GRL.
+
+ @param thd Reference to thread.
*/
-void broadcast_refresh(void)
+void Global_read_lock::set_explicit_lock_duration(THD *thd)
{
- mysql_cond_broadcast(&COND_global_read_lock);
+ if (m_mdl_global_shared_lock)
+ thd->mdl_context.set_lock_duration(m_mdl_global_shared_lock, MDL_EXPLICIT);
+ if (m_mdl_blocks_commits_lock)
+ thd->mdl_context.set_lock_duration(m_mdl_blocks_commits_lock, MDL_EXPLICIT);
}
/**
diff --git a/sql/lock.h b/sql/lock.h
index c097c8d269e..6f779595af8 100644
--- a/sql/lock.h
+++ b/sql/lock.h
@@ -2,6 +2,7 @@
#define LOCK_INCLUDED
#include "thr_lock.h" /* thr_lock_type */
+#include "mdl.h"
// Forward declarations
struct TABLE;
@@ -18,11 +19,10 @@ void mysql_lock_remove(THD *thd, MYSQL_LOCK *locked,TABLE *table);
void mysql_lock_abort(THD *thd, TABLE *table, bool upgrade_lock);
bool mysql_lock_abort_for_thread(THD *thd, TABLE *table);
MYSQL_LOCK *mysql_lock_merge(MYSQL_LOCK *a,MYSQL_LOCK *b);
-void broadcast_refresh(void);
/* Lock based on name */
bool lock_schema_name(THD *thd, const char *db);
/* Lock based on stored routine name */
-bool lock_routine_name(THD *thd, bool is_function, const char *db,
- const char *name);
+bool lock_object_name(THD *thd, MDL_key::enum_mdl_namespace mdl_type,
+ const char *db, const char *name);
#endif /* LOCK_INCLUDED */
diff --git a/sql/log.cc b/sql/log.cc
index a9452ed1c26..e3d42a41e10 100644
--- a/sql/log.cc
+++ b/sql/log.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -210,11 +210,11 @@ class binlog_cache_data
{
public:
binlog_cache_data(): m_pending(0), before_stmt_pos(MY_OFF_T_UNDEF),
- incident(FALSE), changes_to_non_trans_temp_table_flag(FALSE)
- {
- cache_log.end_of_file= max_binlog_cache_size;
- }
-
+ incident(FALSE), changes_to_non_trans_temp_table_flag(FALSE),
+ saved_max_binlog_cache_size(0), ptr_binlog_cache_use(0),
+ ptr_binlog_cache_disk_use(0)
+ { }
+
~binlog_cache_data()
{
DBUG_ASSERT(empty());
@@ -258,11 +258,19 @@ public:
void reset()
{
+ compute_statistics();
truncate(0);
changes_to_non_trans_temp_table_flag= FALSE;
incident= FALSE;
before_stmt_pos= MY_OFF_T_UNDEF;
- cache_log.end_of_file= max_binlog_cache_size;
+ /*
+ The truncate function calls reinit_io_cache that calls my_b_flush_io_cache
+ which may increase disk_writes. This breaks the disk_writes use by the
+ binary log which aims to compute the ratio between in-memory cache usage
+ and disk cache usage. To avoid this undesirable behavior, we reset the
+ variable after truncating the cache.
+ */
+ cache_log.disk_writes= 0;
DBUG_ASSERT(empty());
}
@@ -293,6 +301,36 @@ public:
before_stmt_pos= MY_OFF_T_UNDEF;
}
+ void set_binlog_cache_info(ulong param_max_binlog_cache_size,
+ ulong *param_ptr_binlog_cache_use,
+ ulong *param_ptr_binlog_cache_disk_use)
+ {
+ /*
+ The assertions guarantee that the set_binlog_cache_info is
+ called just once and information passed as parameters are
+ never zero.
+
+ This is done while calling the constructor binlog_cache_mngr.
+ We cannot set informaton in the constructor binlog_cache_data
+ because the space for binlog_cache_mngr is allocated through
+ a placement new.
+
+ In the future, we can refactor this and change it to avoid
+ the set_binlog_info.
+ */
+ DBUG_ASSERT(saved_max_binlog_cache_size == 0 &&
+ param_max_binlog_cache_size != 0 &&
+ ptr_binlog_cache_use == 0 &&
+ param_ptr_binlog_cache_use != 0 &&
+ ptr_binlog_cache_disk_use == 0 &&
+ param_ptr_binlog_cache_disk_use != 0);
+
+ saved_max_binlog_cache_size= param_max_binlog_cache_size;
+ ptr_binlog_cache_use= param_ptr_binlog_cache_use;
+ ptr_binlog_cache_disk_use= param_ptr_binlog_cache_disk_use;
+ cache_log.end_of_file= saved_max_binlog_cache_size;
+ }
+
/*
Cache to store data before copying it to the binary log.
*/
@@ -322,6 +360,40 @@ private:
*/
bool changes_to_non_trans_temp_table_flag;
+ /**
+ This function computes binlog cache and disk usage.
+ */
+ void compute_statistics()
+ {
+ if (!empty())
+ {
+ statistic_increment(*ptr_binlog_cache_use, &LOCK_status);
+ if (cache_log.disk_writes != 0)
+ statistic_increment(*ptr_binlog_cache_disk_use, &LOCK_status);
+ }
+ }
+
+ /*
+ Stores the values of maximum size of the cache allowed when this cache
+ is configured. This corresponds to either
+ . max_binlog_cache_size or max_binlog_stmt_cache_size.
+ */
+ ulong saved_max_binlog_cache_size;
+
+ /*
+ Stores a pointer to the status variable that keeps track of the in-memory
+ cache usage. This corresponds to either
+ . binlog_cache_use or binlog_stmt_cache_use.
+ */
+ ulong *ptr_binlog_cache_use;
+
+ /*
+ Stores a pointer to the status variable that keeps track of the disk
+ cache usage. This corresponds to either
+ . binlog_cache_disk_use or binlog_stmt_cache_disk_use.
+ */
+ ulong *ptr_binlog_cache_disk_use;
+
/*
It truncates the cache to a certain position. This includes deleting the
pending event.
@@ -335,7 +407,7 @@ private:
set_pending(0);
}
reinit_io_cache(&cache_log, WRITE_CACHE, pos, 0, 0);
- cache_log.end_of_file= max_binlog_cache_size;
+ cache_log.end_of_file= saved_max_binlog_cache_size;
}
binlog_cache_data& operator=(const binlog_cache_data& info);
@@ -344,7 +416,20 @@ private:
class binlog_cache_mngr {
public:
- binlog_cache_mngr() {}
+ binlog_cache_mngr(ulong param_max_binlog_stmt_cache_size,
+ ulong param_max_binlog_cache_size,
+ ulong *param_ptr_binlog_stmt_cache_use,
+ ulong *param_ptr_binlog_stmt_cache_disk_use,
+ ulong *param_ptr_binlog_cache_use,
+ ulong *param_ptr_binlog_cache_disk_use)
+ {
+ stmt_cache.set_binlog_cache_info(param_max_binlog_stmt_cache_size,
+ param_ptr_binlog_stmt_cache_use,
+ param_ptr_binlog_stmt_cache_disk_use);
+ trx_cache.set_binlog_cache_info(param_max_binlog_cache_size,
+ param_ptr_binlog_cache_use,
+ param_ptr_binlog_cache_disk_use);
+ }
void reset_cache(binlog_cache_data* cache_data)
{
@@ -1374,7 +1459,7 @@ void LOGGER::deactivate_log_handler(THD *thd, uint log_type)
file_log= file_log_handler->get_mysql_log();
break;
default:
- assert(0); // Impossible
+ MY_ASSERT_UNREACHABLE();
}
if (!(*tmp_opt))
@@ -1518,57 +1603,122 @@ static int binlog_close_connection(handlerton *hton, THD *thd)
}
/**
- This function flushes a transactional cache upon commit/rollback.
+ This function flushes a cache upon commit/rollback.
- @param thd The thread whose transaction should be flushed
- @param cache_mngr Pointer to the cache data to be flushed
- @param end_ev The end event either commit/rollback.
+ @param thd The thread whose transaction should be flushed
+ @param cache_data Pointer to the cache
+ @param end_ev The end event either commit/rollback
+ @param is_transactional The type of the cache: transactional or
+ non-transactional
@return
- nonzero if an error pops up when flushing the transactional cache.
+ nonzero if an error pops up when flushing the cache.
*/
-static int
-binlog_flush_trx_cache(THD *thd, binlog_cache_mngr *cache_mngr,
- Log_event *end_ev)
+static inline int
+binlog_flush_cache(THD *thd, binlog_cache_data* cache_data, Log_event *end_evt,
+ bool is_transactional)
{
- DBUG_ENTER("binlog_flush_trx_cache");
- int error=0;
- IO_CACHE *cache_log= &cache_mngr->trx_cache.cache_log;
-
- /*
- This function handles transactional changes and as such
- this flag equals to true.
- */
- bool const is_transactional= TRUE;
-
- if (thd->binlog_flush_pending_rows_event(TRUE, is_transactional))
- DBUG_RETURN(1);
- /*
- Doing a commit or a rollback including non-transactional tables,
- i.e., ending a transaction where we might write the transaction
- cache to the binary log.
-
- We can always end the statement when ending a transaction since
- transactions are not allowed inside stored functions. If they
- were, we would have to ensure that we're not ending a statement
- inside a stored function.
- */
- error= mysql_bin_log.write(thd, &cache_mngr->trx_cache.cache_log, end_ev,
- cache_mngr->trx_cache.has_incident());
- cache_mngr->reset_cache(&cache_mngr->trx_cache);
+ DBUG_ENTER("binlog_flush_cache");
+ int error= 0;
- statistic_increment(binlog_cache_use, &LOCK_status);
- if (cache_log->disk_writes != 0)
+ if (!cache_data->empty())
{
- statistic_increment(binlog_cache_disk_use, &LOCK_status);
- cache_log->disk_writes= 0;
+ if (thd->binlog_flush_pending_rows_event(TRUE, is_transactional))
+ DBUG_RETURN(1);
+ /*
+ Doing a commit or a rollback including non-transactional tables,
+ i.e., ending a transaction where we might write the transaction
+ cache to the binary log.
+
+ We can always end the statement when ending a transaction since
+ transactions are not allowed inside stored functions. If they
+ were, we would have to ensure that we're not ending a statement
+ inside a stored function.
+ */
+ error= mysql_bin_log.write(thd, &cache_data->cache_log, end_evt,
+ cache_data->has_incident());
}
+ cache_data->reset();
- DBUG_ASSERT(cache_mngr->trx_cache.empty());
+ DBUG_ASSERT(cache_data->empty());
DBUG_RETURN(error);
}
/**
+ This function flushes the stmt-cache upon commit.
+
+ @param thd The thread whose transaction should be flushed
+ @param cache_mngr Pointer to the cache manager
+
+ @return
+ nonzero if an error pops up when flushing the cache.
+*/
+static inline int
+binlog_commit_flush_stmt_cache(THD *thd,
+ binlog_cache_mngr *cache_mngr)
+{
+ Query_log_event end_evt(thd, STRING_WITH_LEN("COMMIT"),
+ FALSE, FALSE, TRUE, 0);
+ return (binlog_flush_cache(thd, &cache_mngr->stmt_cache, &end_evt,
+ FALSE));
+}
+
+/**
+ This function flushes the trx-cache upon commit.
+
+ @param thd The thread whose transaction should be flushed
+ @param cache_mngr Pointer to the cache manager
+
+ @return
+ nonzero if an error pops up when flushing the cache.
+*/
+static inline int
+binlog_commit_flush_trx_cache(THD *thd, binlog_cache_mngr *cache_mngr)
+{
+ Query_log_event end_evt(thd, STRING_WITH_LEN("COMMIT"),
+ TRUE, FALSE, TRUE, 0);
+ return (binlog_flush_cache(thd, &cache_mngr->trx_cache, &end_evt,
+ TRUE));
+}
+
+/**
+ This function flushes the trx-cache upon rollback.
+
+ @param thd The thread whose transaction should be flushed
+ @param cache_mngr Pointer to the cache manager
+
+ @return
+ nonzero if an error pops up when flushing the cache.
+*/
+static inline int
+binlog_rollback_flush_trx_cache(THD *thd, binlog_cache_mngr *cache_mngr)
+{
+ Query_log_event end_evt(thd, STRING_WITH_LEN("ROLLBACK"),
+ TRUE, FALSE, TRUE, 0);
+ return (binlog_flush_cache(thd, &cache_mngr->trx_cache, &end_evt,
+ TRUE));
+}
+
+/**
+ This function flushes the trx-cache upon commit.
+
+ @param thd The thread whose transaction should be flushed
+ @param cache_mngr Pointer to the cache manager
+ @param xid Transaction Id
+
+ @return
+ nonzero if an error pops up when flushing the cache.
+*/
+static inline int
+binlog_commit_flush_trx_cache(THD *thd, binlog_cache_mngr *cache_mngr,
+ my_xid xid)
+{
+ Xid_log_event end_evt(thd, xid);
+ return (binlog_flush_cache(thd, &cache_mngr->trx_cache, &end_evt,
+ TRUE));
+}
+
+/**
This function truncates the transactional cache upon committing or rolling
back either a transaction or a statement.
@@ -1591,23 +1741,24 @@ binlog_truncate_trx_cache(THD *thd, binlog_cache_mngr *cache_mngr, bool all)
*/
bool const is_transactional= TRUE;
- DBUG_PRINT("info", ("thd->options={ %s%s}, transaction: %s",
+ DBUG_PRINT("info", ("thd->options={ %s %s}, transaction: %s",
FLAGSTR(thd->variables.option_bits, OPTION_NOT_AUTOCOMMIT),
FLAGSTR(thd->variables.option_bits, OPTION_BEGIN),
all ? "all" : "stmt"));
+
+ thd->binlog_remove_pending_rows_event(TRUE, is_transactional);
/*
If rolling back an entire transaction or a single statement not
inside a transaction, we reset the transaction cache.
*/
- thd->binlog_remove_pending_rows_event(TRUE, is_transactional);
if (ending_trans(thd, all))
{
if (cache_mngr->trx_cache.has_incident())
error= mysql_bin_log.write_incident(thd, TRUE);
- cache_mngr->reset_cache(&cache_mngr->trx_cache);
-
thd->clear_binlog_table_maps();
+
+ cache_mngr->reset_cache(&cache_mngr->trx_cache);
}
/*
If rolling back a statement in a transaction, we truncate the
@@ -1632,51 +1783,6 @@ static int binlog_prepare(handlerton *hton, THD *thd, bool all)
}
/**
- This function flushes the non-transactional to the binary log upon
- committing or rolling back a statement.
-
- @param thd The thread whose transaction should be flushed
- @param cache_mngr Pointer to the cache data to be flushed
-
- @return
- nonzero if an error pops up when flushing the non-transactional cache.
-*/
-static int
-binlog_flush_stmt_cache(THD *thd, binlog_cache_mngr *cache_mngr)
-{
- int error= 0;
- DBUG_ENTER("binlog_flush_stmt_cache");
- /*
- If we are flushing the statement cache, it means that the changes get
- through otherwise the cache is empty and this routine should not be called.
- */
- DBUG_ASSERT(cache_mngr->stmt_cache.has_incident() == FALSE);
- /*
- This function handles non-transactional changes and as such this flag equals
- to false.
- */
- bool const is_transactional= FALSE;
- IO_CACHE *cache_log= &cache_mngr->stmt_cache.cache_log;
-
- if (thd->binlog_flush_pending_rows_event(TRUE, is_transactional))
- DBUG_RETURN(1);
-
- Query_log_event qev(thd, STRING_WITH_LEN("COMMIT"), TRUE, FALSE, TRUE, 0);
- if ((error= mysql_bin_log.write(thd, cache_log, &qev,
- cache_mngr->stmt_cache.has_incident())))
- DBUG_RETURN(error);
- cache_mngr->reset_cache(&cache_mngr->stmt_cache);
-
- statistic_increment(binlog_cache_use, &LOCK_status);
- if (cache_log->disk_writes != 0)
- {
- statistic_increment(binlog_cache_disk_use, &LOCK_status);
- cache_log->disk_writes= 0;
- }
- DBUG_RETURN(error);
-}
-
-/**
This function is called once after each statement.
It has the responsibility to flush the caches to the binary log on commits.
@@ -1704,7 +1810,7 @@ static int binlog_commit(handlerton *hton, THD *thd, bool all)
if (!cache_mngr->stmt_cache.empty())
{
- binlog_flush_stmt_cache(thd, cache_mngr);
+ error= binlog_commit_flush_stmt_cache(thd, cache_mngr);
}
if (cache_mngr->trx_cache.empty())
@@ -1713,7 +1819,7 @@ static int binlog_commit(handlerton *hton, THD *thd, bool all)
we're here because cache_log was flushed in MYSQL_BIN_LOG::log_xid()
*/
cache_mngr->reset_cache(&cache_mngr->trx_cache);
- DBUG_RETURN(0);
+ DBUG_RETURN(error);
}
/*
@@ -1722,17 +1828,15 @@ static int binlog_commit(handlerton *hton, THD *thd, bool all)
- We are in a transaction and a full transaction is committed.
Otherwise, we accumulate the changes.
*/
- if (ending_trans(thd, all))
- {
- Query_log_event qev(thd, STRING_WITH_LEN("COMMIT"), TRUE, FALSE, TRUE, 0);
- error= binlog_flush_trx_cache(thd, cache_mngr, &qev);
- }
+ if (!error && ending_trans(thd, all))
+ error= binlog_commit_flush_trx_cache(thd, cache_mngr);
/*
This is part of the stmt rollback.
*/
if (!all)
cache_mngr->trx_cache.set_prev_position(MY_OFF_T_UNDEF);
+
DBUG_RETURN(error);
}
@@ -1749,7 +1853,7 @@ static int binlog_commit(handlerton *hton, THD *thd, bool all)
static int binlog_rollback(handlerton *hton, THD *thd, bool all)
{
DBUG_ENTER("binlog_rollback");
- int error=0;
+ int error= 0;
binlog_cache_mngr *const cache_mngr=
(binlog_cache_mngr*) thd_get_ha_data(thd, binlog_hton);
@@ -1769,16 +1873,16 @@ static int binlog_rollback(handlerton *hton, THD *thd, bool all)
}
else if (!cache_mngr->stmt_cache.empty())
{
- binlog_flush_stmt_cache(thd, cache_mngr);
+ error= binlog_commit_flush_stmt_cache(thd, cache_mngr);
}
if (cache_mngr->trx_cache.empty())
{
- /*
+ /*
we're here because cache_log was flushed in MYSQL_BIN_LOG::log_xid()
*/
cache_mngr->reset_cache(&cache_mngr->trx_cache);
- DBUG_RETURN(0);
+ DBUG_RETURN(error);
}
if (mysql_bin_log.check_write_error(thd))
@@ -1794,9 +1898,9 @@ static int binlog_rollback(handlerton *hton, THD *thd, bool all)
We reach this point if the effect of a statement did not properly get into
a cache and need to be rolled back.
*/
- error= binlog_truncate_trx_cache(thd, cache_mngr, all);
+ error |= binlog_truncate_trx_cache(thd, cache_mngr, all);
}
- else
+ else if (!error)
{
/*
We flush the cache wrapped in a beging/rollback if:
@@ -1808,7 +1912,6 @@ static int binlog_rollback(handlerton *hton, THD *thd, bool all)
. the format is MIXED, non-trans table was updated and
aborting a single statement transaction;
*/
-
if (ending_trans(thd, all) &&
((thd->variables.option_bits & OPTION_KEEP_LOG) ||
(trans_has_updated_non_trans_table(thd) &&
@@ -1818,10 +1921,7 @@ static int binlog_rollback(handlerton *hton, THD *thd, bool all)
(trans_has_updated_non_trans_table(thd) &&
ending_single_stmt_trans(thd,all) &&
thd->variables.binlog_format == BINLOG_FORMAT_MIXED)))
- {
- Query_log_event qev(thd, STRING_WITH_LEN("ROLLBACK"), TRUE, FALSE, TRUE, 0);
- error= binlog_flush_trx_cache(thd, cache_mngr, &qev);
- }
+ error= binlog_rollback_flush_trx_cache(thd, cache_mngr);
/*
Truncate the cache if:
. aborting a single or multi-statement transaction or;
@@ -1844,11 +1944,12 @@ static int binlog_rollback(handlerton *hton, THD *thd, bool all)
This is part of the stmt rollback.
*/
if (!all)
- cache_mngr->trx_cache.set_prev_position(MY_OFF_T_UNDEF);
+ cache_mngr->trx_cache.set_prev_position(MY_OFF_T_UNDEF);
+
DBUG_RETURN(error);
}
-void MYSQL_BIN_LOG::set_write_error(THD *thd)
+void MYSQL_BIN_LOG::set_write_error(THD *thd, bool is_transactional)
{
DBUG_ENTER("MYSQL_BIN_LOG::set_write_error");
@@ -1858,9 +1959,20 @@ void MYSQL_BIN_LOG::set_write_error(THD *thd)
DBUG_VOID_RETURN;
if (my_errno == EFBIG)
- my_message(ER_TRANS_CACHE_FULL, ER(ER_TRANS_CACHE_FULL), MYF(MY_WME));
+ {
+ if (is_transactional)
+ {
+ my_message(ER_TRANS_CACHE_FULL, ER(ER_TRANS_CACHE_FULL), MYF(MY_WME));
+ }
+ else
+ {
+ my_message(ER_STMT_CACHE_FULL, ER(ER_STMT_CACHE_FULL), MYF(MY_WME));
+ }
+ }
else
+ {
my_error(ER_ERROR_ON_WRITE, MYF(MY_WME), name, errno);
+ }
DBUG_VOID_RETURN;
}
@@ -1877,6 +1989,7 @@ bool MYSQL_BIN_LOG::check_write_error(THD *thd)
switch (thd->stmt_da->sql_errno())
{
case ER_TRANS_CACHE_FULL:
+ case ER_STMT_CACHE_FULL:
case ER_ERROR_ON_WRITE:
case ER_BINLOG_LOGGING_IMPOSSIBLE:
checked= TRUE;
@@ -2085,7 +2198,8 @@ static int find_uniq_filename(char *name)
*end='.';
length= (size_t) (end - start + 1);
- if (!(dir_info= my_dir(buff,MYF(MY_DONT_SORT))))
+ if ((DBUG_EVALUATE_IF("error_unique_log_filename", 1,
+ !(dir_info= my_dir(buff,MYF(MY_DONT_SORT))))))
{ // This shouldn't happen
strmov(end,".1"); // use name+1
DBUG_RETURN(1);
@@ -2112,7 +2226,11 @@ updating the index files.", max_found);
}
next= max_found + 1;
- sprintf(ext_buf, "%06lu", next);
+ if (sprintf(ext_buf, "%06lu", next)<0)
+ {
+ error= 1;
+ goto end;
+ }
*end++='.';
/*
@@ -2129,7 +2247,11 @@ index files.", name, ext_buf, (strlen(ext_buf) + (end - name)));
goto end;
}
- sprintf(end, "%06lu", next);
+ if (sprintf(end, "%06lu", next)<0)
+ {
+ error= 1;
+ goto end;
+ }
/* print warning if reaching the end of available extensions. */
if ((next > (MAX_LOG_UNIQUE_FN_EXT - LOG_WARN_UNIQUE_FN_EXT_LEFT)))
@@ -2190,7 +2312,11 @@ bool MYSQL_LOG::init_and_set_log_file_name(const char *log_name,
1 error
*/
-bool MYSQL_LOG::open(const char *log_name, enum_log_type log_type_arg,
+bool MYSQL_LOG::open(
+#ifdef HAVE_PSI_INTERFACE
+ PSI_file_key log_file_key,
+#endif
+ const char *log_name, enum_log_type log_type_arg,
const char *new_name, enum cache_type io_cache_type_arg)
{
char buff[FN_REFLEN];
@@ -2218,7 +2344,12 @@ bool MYSQL_LOG::open(const char *log_name, enum_log_type log_type_arg,
db[0]= 0;
- if ((file= mysql_file_open(key_file_MYSQL_LOG,
+#ifdef HAVE_PSI_INTERFACE
+ /* Keep the key for reopen */
+ m_log_file_key= log_file_key;
+#endif
+
+ if ((file= mysql_file_open(log_file_key,
log_file_name, open_flags,
MYF(MY_WME | ME_WAITTANG))) < 0 ||
init_io_cache(&log_file, file, IO_SIZE, io_cache_type,
@@ -2353,13 +2484,8 @@ int MYSQL_LOG::generate_new_name(char *new_name, const char *log_name)
{
if (find_uniq_filename(new_name))
{
- /*
- This should be treated as error once propagation of error further
- up in the stack gets proper handling.
- */
- push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
- ER_NO_UNIQUE_LOGFILE, ER(ER_NO_UNIQUE_LOGFILE),
- log_name);
+ my_printf_error(ER_NO_UNIQUE_LOGFILE, ER(ER_NO_UNIQUE_LOGFILE),
+ MYF(ME_FATALERROR), log_name);
sql_print_error(ER(ER_NO_UNIQUE_LOGFILE), log_name);
return 1;
}
@@ -2402,7 +2528,11 @@ void MYSQL_QUERY_LOG::reopen_file()
Note that at this point, log_state != LOG_CLOSED (important for is_open()).
*/
- open(save_name, log_type, 0, io_cache_type);
+ open(
+#ifdef HAVE_PSI_INTERFACE
+ m_log_file_key,
+#endif
+ save_name, log_type, 0, io_cache_type);
my_free(save_name);
mysql_mutex_unlock(&LOCK_log);
@@ -2764,11 +2894,9 @@ void MYSQL_BIN_LOG::init(bool no_auto_events_arg, ulong max_size_arg)
void MYSQL_BIN_LOG::init_pthread_objects()
{
- DBUG_ASSERT(inited == 0);
- inited= 1;
- mysql_mutex_init(key_LOG_LOCK_log, &LOCK_log, MY_MUTEX_INIT_SLOW);
- mysql_mutex_init(key_BINLOG_LOCK_index, &LOCK_index, MY_MUTEX_INIT_SLOW);
- mysql_cond_init(key_BINLOG_update_cond, &update_cond, 0);
+ MYSQL_LOG::init_pthread_objects();
+ mysql_mutex_init(m_key_LOCK_index, &LOCK_index, MY_MUTEX_INIT_SLOW);
+ mysql_cond_init(m_key_update_cond, &update_cond, 0);
}
@@ -2791,7 +2919,7 @@ bool MYSQL_BIN_LOG::open_index_file(const char *index_file_name_arg,
}
fn_format(index_file_name, index_file_name_arg, mysql_data_home,
".index", opt);
- if ((index_file_nr= mysql_file_open(key_file_binlog_index,
+ if ((index_file_nr= mysql_file_open(m_key_file_log_index,
index_file_name,
O_RDWR | O_CREAT | O_BINARY,
MYF(MY_WME))) < 0 ||
@@ -2879,17 +3007,37 @@ bool MYSQL_BIN_LOG::open(const char *log_name,
sync_purge_index_file() ||
DBUG_EVALUATE_IF("fault_injection_registering_index", 1, 0))
{
+ /**
+ TODO: although this was introduced to appease valgrind
+ when injecting emulated faults using fault_injection_registering_index
+ it may be good to consider what actually happens when
+ open_purge_index_file succeeds but register or sync fails.
+
+ Perhaps we might need the code below in MYSQL_LOG_BIN::cleanup
+ for "real life" purposes as well?
+ */
+ DBUG_EXECUTE_IF("fault_injection_registering_index", {
+ if (my_b_inited(&purge_index_file))
+ {
+ end_io_cache(&purge_index_file);
+ my_close(purge_index_file.file, MYF(0));
+ }
+ });
+
sql_print_error("MSYQL_BIN_LOG::open failed to sync the index file.");
DBUG_RETURN(1);
}
- DBUG_EXECUTE_IF("crash_create_non_critical_before_update_index", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_create_non_critical_before_update_index", DBUG_SUICIDE(););
#endif
write_error= 0;
/* open the main log file */
- if (MYSQL_LOG::open(log_name, log_type_arg, new_name,
- io_cache_type_arg))
+ if (MYSQL_LOG::open(
+#ifdef HAVE_PSI_INTERFACE
+ m_key_file_log,
+#endif
+ log_name, log_type_arg, new_name, io_cache_type_arg))
{
#ifdef HAVE_REPLICATION
close_purge_index_file();
@@ -2979,7 +3127,7 @@ bool MYSQL_BIN_LOG::open(const char *log_name,
if (write_file_name_to_index_file)
{
#ifdef HAVE_REPLICATION
- DBUG_EXECUTE_IF("crash_create_critical_before_update_index", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_create_critical_before_update_index", DBUG_SUICIDE(););
#endif
DBUG_ASSERT(my_b_inited(&index_file) != 0);
@@ -2998,7 +3146,7 @@ bool MYSQL_BIN_LOG::open(const char *log_name,
goto err;
#ifdef HAVE_REPLICATION
- DBUG_EXECUTE_IF("crash_create_after_update_index", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_create_after_update_index", DBUG_SUICIDE(););
#endif
}
}
@@ -3257,12 +3405,6 @@ bool MYSQL_BIN_LOG::reset_logs(THD* thd)
DBUG_ENTER("reset_logs");
ha_reset_logs(thd);
- /*
- We need to get both locks to be sure that no one is trying to
- write to the index log file.
- */
- mysql_mutex_lock(&LOCK_log);
- mysql_mutex_lock(&LOCK_index);
/*
The following mutex is needed to ensure that no threads call
@@ -3272,6 +3414,13 @@ bool MYSQL_BIN_LOG::reset_logs(THD* thd)
*/
mysql_mutex_lock(&LOCK_thread_count);
+ /*
+ We need to get both locks to be sure that no one is trying to
+ write to the index log file.
+ */
+ mysql_mutex_lock(&LOCK_log);
+ mysql_mutex_lock(&LOCK_index);
+
/* Save variables so that we can reopen the log */
save_name=name;
name=0; // Protect against free
@@ -3328,7 +3477,7 @@ bool MYSQL_BIN_LOG::reset_logs(THD* thd)
}
/* Start logging with a new file */
- close(LOG_CLOSE_INDEX);
+ close(LOG_CLOSE_INDEX | LOG_CLOSE_TO_BE_OPENED);
if ((error= my_delete_allow_opened(index_file_name, MYF(0)))) // Reset (open will update)
{
if (my_errno == ENOENT)
@@ -3357,7 +3506,8 @@ bool MYSQL_BIN_LOG::reset_logs(THD* thd)
if (!thd->slave_thread)
need_start_event=1;
if (!open_index_file(index_file_name, 0, FALSE))
- open(save_name, log_type, 0, io_cache_type, no_auto_events, max_size, 0, FALSE);
+ if ((error= open(save_name, log_type, 0, io_cache_type, no_auto_events, max_size, 0, FALSE)))
+ goto err;
my_free((void *) save_name);
err:
@@ -3461,7 +3611,7 @@ int MYSQL_BIN_LOG::purge_first_log(Relay_log_info* rli, bool included)
/* Store where we are in the new file for the execution thread */
flush_relay_log_info(rli);
- DBUG_EXECUTE_IF("crash_before_purge_logs", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_before_purge_logs", DBUG_SUICIDE(););
mysql_mutex_lock(&rli->log_space_lock);
rli->relay_log.purge_logs(to_purge_if_included, included,
@@ -3589,7 +3739,7 @@ int MYSQL_BIN_LOG::purge_logs(const char *to_log,
break;
}
- DBUG_EXECUTE_IF("crash_purge_before_update_index", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_purge_before_update_index", DBUG_SUICIDE(););
if ((error= sync_purge_index_file()))
{
@@ -3604,7 +3754,7 @@ int MYSQL_BIN_LOG::purge_logs(const char *to_log,
goto err;
}
- DBUG_EXECUTE_IF("crash_purge_critical_after_update_index", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_purge_critical_after_update_index", DBUG_SUICIDE(););
err:
/* Read each entry from purge_index_file and delete the file. */
@@ -3614,7 +3764,7 @@ err:
" that would be purged.");
close_purge_index_file();
- DBUG_EXECUTE_IF("crash_purge_non_critical_after_update_index", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("crash_purge_non_critical_after_update_index", DBUG_SUICIDE(););
if (need_mutex)
mysql_mutex_unlock(&LOCK_index);
@@ -3756,7 +3906,7 @@ int MYSQL_BIN_LOG::purge_index_entry(THD *thd, ulonglong *decrease_log_space,
/* Get rid of the trailing '\n' */
log_info.log_file_name[length-1]= 0;
- if (!mysql_file_stat(key_file_binlog, log_info.log_file_name, &s, MYF(0)))
+ if (!mysql_file_stat(m_key_file_log, log_info.log_file_name, &s, MYF(0)))
{
if (my_errno == ENOENT)
{
@@ -3931,7 +4081,7 @@ int MYSQL_BIN_LOG::purge_logs_before_date(time_t purge_time)
!is_active(log_info.log_file_name) &&
!log_in_use(log_info.log_file_name))
{
- if (!mysql_file_stat(key_file_binlog,
+ if (!mysql_file_stat(m_key_file_log,
log_info.log_file_name, &stat_area, MYF(0)))
{
if (my_errno == ENOENT)
@@ -4022,17 +4172,23 @@ bool MYSQL_BIN_LOG::is_active(const char *log_file_name_arg)
incapsulation 3) allows external access to the class without
a lock (which is not possible with private new_file_without_locking
method).
+
+ @retval
+ nonzero - error
*/
-void MYSQL_BIN_LOG::new_file()
+int MYSQL_BIN_LOG::new_file()
{
- new_file_impl(1);
+ return new_file_impl(1);
}
-
-void MYSQL_BIN_LOG::new_file_without_locking()
+/*
+ @retval
+ nonzero - error
+ */
+int MYSQL_BIN_LOG::new_file_without_locking()
{
- new_file_impl(0);
+ return new_file_impl(0);
}
@@ -4041,19 +4197,23 @@ void MYSQL_BIN_LOG::new_file_without_locking()
@param need_lock Set to 1 if caller has not locked LOCK_log
+ @retval
+ nonzero - error
+
@note
The new file name is stored last in the index file
*/
-void MYSQL_BIN_LOG::new_file_impl(bool need_lock)
+int MYSQL_BIN_LOG::new_file_impl(bool need_lock)
{
- char new_name[FN_REFLEN], *new_name_ptr, *old_name;
+ int error= 0, close_on_error= FALSE;
+ char new_name[FN_REFLEN], *new_name_ptr, *old_name, *file_to_open;
DBUG_ENTER("MYSQL_BIN_LOG::new_file_impl");
if (!is_open())
{
DBUG_PRINT("info",("log is closed"));
- DBUG_VOID_RETURN;
+ DBUG_RETURN(error);
}
if (need_lock)
@@ -4091,7 +4251,7 @@ void MYSQL_BIN_LOG::new_file_impl(bool need_lock)
We have to do this here and not in open as we want to store the
new file name in the current binary log file.
*/
- if (generate_new_name(new_name, name))
+ if ((error= generate_new_name(new_name, name)))
goto end;
new_name_ptr=new_name;
@@ -4105,7 +4265,14 @@ void MYSQL_BIN_LOG::new_file_impl(bool need_lock)
*/
Rotate_log_event r(new_name+dirname_length(new_name),
0, LOG_EVENT_OFFSET, is_relay_log ? Rotate_log_event::RELAY_LOG : 0);
- r.write(&log_file);
+ if(DBUG_EVALUATE_IF("fault_injection_new_file_rotate_event", (error=close_on_error=TRUE), FALSE) ||
+ (error= r.write(&log_file)))
+ {
+ DBUG_EXECUTE_IF("fault_injection_new_file_rotate_event", errno=2;);
+ close_on_error= TRUE;
+ my_printf_error(ER_ERROR_ON_WRITE, ER(ER_CANT_OPEN_FILE), MYF(ME_FATALERROR), name, errno);
+ goto end;
+ }
bytes_written += r.data_written;
}
/*
@@ -4133,17 +4300,56 @@ void MYSQL_BIN_LOG::new_file_impl(bool need_lock)
*/
/* reopen index binlog file, BUG#34582 */
- if (!open_index_file(index_file_name, 0, FALSE))
- open(old_name, log_type, new_name_ptr,
- io_cache_type, no_auto_events, max_size, 1, FALSE);
+ file_to_open= index_file_name;
+ error= open_index_file(index_file_name, 0, FALSE);
+ if (!error)
+ {
+ /* reopen the binary log file. */
+ file_to_open= new_name_ptr;
+ error= open(old_name, log_type, new_name_ptr, io_cache_type,
+ no_auto_events, max_size, 1, FALSE);
+ }
+
+ /* handle reopening errors */
+ if (error)
+ {
+ my_printf_error(ER_CANT_OPEN_FILE, ER(ER_CANT_OPEN_FILE),
+ MYF(ME_FATALERROR), file_to_open, error);
+ close_on_error= TRUE;
+ }
+
my_free(old_name);
end:
+
+ if (error && close_on_error /* rotate or reopen failed */)
+ {
+ /*
+ Close whatever was left opened.
+
+ We are keeping the behavior as it exists today, ie,
+ we disable logging and move on (see: BUG#51014).
+
+ TODO: as part of WL#1790 consider other approaches:
+ - kill mysql (safety);
+ - try multiple locations for opening a log file;
+ - switch server to protected/readonly mode
+ - ...
+ */
+ close(LOG_CLOSE_INDEX);
+ sql_print_error("Could not open %s for logging (error %d). "
+ "Turning logging off for the whole duration "
+ "of the MySQL server process. To turn it on "
+ "again: fix the cause, shutdown the MySQL "
+ "server and restart it.",
+ new_name_ptr, errno);
+ }
+
if (need_lock)
mysql_mutex_unlock(&LOCK_log);
mysql_mutex_unlock(&LOCK_index);
- DBUG_VOID_RETURN;
+ DBUG_RETURN(error);
}
@@ -4168,8 +4374,7 @@ bool MYSQL_BIN_LOG::append(Log_event* ev)
if (flush_and_sync(0))
goto err;
if ((uint) my_b_append_tell(&log_file) > max_size)
- new_file_without_locking();
-
+ error= new_file_without_locking();
err:
mysql_mutex_unlock(&LOCK_log);
signal_update(); // Safe as we don't call close
@@ -4200,8 +4405,7 @@ bool MYSQL_BIN_LOG::appendv(const char* buf, uint len,...)
if (flush_and_sync(0))
goto err;
if ((uint) my_b_append_tell(&log_file) > max_size)
- new_file_without_locking();
-
+ error= new_file_without_locking();
err:
if (!error)
signal_update();
@@ -4390,7 +4594,7 @@ int THD::binlog_setup_trx_data()
cache_mngr= (binlog_cache_mngr*) my_malloc(sizeof(binlog_cache_mngr), MYF(MY_ZEROFILL));
if (!cache_mngr ||
open_cached_file(&cache_mngr->stmt_cache.cache_log, mysql_tmpdir,
- LOG_PREFIX, binlog_cache_size, MYF(MY_WME)) ||
+ LOG_PREFIX, binlog_stmt_cache_size, MYF(MY_WME)) ||
open_cached_file(&cache_mngr->trx_cache.cache_log, mysql_tmpdir,
LOG_PREFIX, binlog_cache_size, MYF(MY_WME)))
{
@@ -4399,8 +4603,13 @@ int THD::binlog_setup_trx_data()
}
thd_set_ha_data(this, binlog_hton, cache_mngr);
- cache_mngr= new (thd_get_ha_data(this, binlog_hton)) binlog_cache_mngr;
-
+ cache_mngr= new (thd_get_ha_data(this, binlog_hton))
+ binlog_cache_mngr(max_binlog_stmt_cache_size,
+ max_binlog_cache_size,
+ &binlog_stmt_cache_use,
+ &binlog_stmt_cache_disk_use,
+ &binlog_cache_use,
+ &binlog_cache_disk_use);
DBUG_RETURN(0);
}
@@ -4652,7 +4861,7 @@ MYSQL_BIN_LOG::flush_and_set_pending_rows_event(THD *thd,
*/
if (pending->write(file))
{
- set_write_error(thd);
+ set_write_error(thd, is_transactional);
if (check_write_error(thd) && cache_data &&
stmt_has_updated_non_trans_table(thd))
cache_data->set_incident();
@@ -4677,6 +4886,7 @@ bool MYSQL_BIN_LOG::write(Log_event *event_info)
bool error= 1;
DBUG_ENTER("MYSQL_BIN_LOG::write(Log_event *)");
binlog_cache_data *cache_data= 0;
+ bool is_trans_cache= FALSE;
if (thd->binlog_evt_union.do_union)
{
@@ -4739,7 +4949,7 @@ bool MYSQL_BIN_LOG::write(Log_event *event_info)
binlog_cache_mngr *const cache_mngr=
(binlog_cache_mngr*) thd_get_ha_data(thd, binlog_hton);
- bool is_trans_cache= use_trans_cache(thd, event_info->use_trans_cache());
+ is_trans_cache= use_trans_cache(thd, event_info->use_trans_cache());
file= cache_mngr->get_binlog_cache_log(is_trans_cache);
cache_data= cache_mngr->get_binlog_cache_data(is_trans_cache);
@@ -4819,7 +5029,6 @@ bool MYSQL_BIN_LOG::write(Log_event *event_info)
goto err;
error= 0;
-
err:
if (event_info->use_direct_logging())
{
@@ -4848,7 +5057,7 @@ unlock:
if (error)
{
- set_write_error(thd);
+ set_write_error(thd, is_trans_cache);
if (check_write_error(thd) && cache_data &&
stmt_has_updated_non_trans_table(thd))
cache_data->set_incident();
@@ -4928,8 +5137,19 @@ bool general_log_write(THD *thd, enum enum_server_command command,
return FALSE;
}
-void MYSQL_BIN_LOG::rotate_and_purge(uint flags)
+/**
+ @note
+ If rotation fails, for instance the server was unable
+ to create a new log file, we still try to write an
+ incident event to the current log.
+
+ @retval
+ nonzero - error
+*/
+int MYSQL_BIN_LOG::rotate_and_purge(uint flags)
{
+ int error= 0;
+ DBUG_ENTER("MYSQL_BIN_LOG::rotate_and_purge");
#ifdef HAVE_REPLICATION
bool check_purge= false;
#endif
@@ -4938,26 +5158,38 @@ void MYSQL_BIN_LOG::rotate_and_purge(uint flags)
if ((flags & RP_FORCE_ROTATE) ||
(my_b_tell(&log_file) >= (my_off_t) max_size))
{
- new_file_without_locking();
+ if ((error= new_file_without_locking()))
+ /**
+ Be conservative... There are possible lost events (eg,
+ failing to log the Execute_load_query_log_event
+ on a LOAD DATA while using a non-transactional
+ table)!
+
+ We give it a shot and try to write an incident event anyway
+ to the current log.
+ */
+ if (!write_incident(current_thd, FALSE))
+ flush_and_sync(0);
+
#ifdef HAVE_REPLICATION
check_purge= true;
#endif
}
if (!(flags & RP_LOCK_LOG_IS_ALREADY_LOCKED))
mysql_mutex_unlock(&LOCK_log);
-
#ifdef HAVE_REPLICATION
/*
NOTE: Run purge_logs wo/ holding LOCK_log
as it otherwise will deadlock in ndbcluster_binlog_index_purge_file
*/
- if (check_purge && expire_logs_days)
+ if (!error && check_purge && expire_logs_days)
{
time_t purge_time= my_time(0) - expire_logs_days*24*60*60;
if (purge_time >= 0)
purge_logs_before_date(purge_time);
}
#endif
+ DBUG_RETURN(error);
}
uint MYSQL_BIN_LOG::next_file_id()
@@ -5148,6 +5380,10 @@ bool MYSQL_BIN_LOG::write_incident(THD *thd, bool lock)
{
uint error= 0;
DBUG_ENTER("MYSQL_BIN_LOG::write_incident");
+
+ if (!is_open())
+ DBUG_RETURN(error);
+
LEX_STRING const write_error_msg=
{ C_STRING_WITH_LEN("error writing to the binary log") };
Incident incident= INCIDENT_LOST_EVENTS;
@@ -5161,7 +5397,7 @@ bool MYSQL_BIN_LOG::write_incident(THD *thd, bool lock)
if (!error && !(error= flush_and_sync(0)))
{
signal_update();
- rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
+ error= rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
}
mysql_mutex_unlock(&LOCK_log);
}
@@ -5225,7 +5461,7 @@ bool MYSQL_BIN_LOG::write(THD *thd, IO_CACHE *cache, Log_event *commit_event,
DBUG_PRINT("info", ("error writing binlog cache: %d",
write_error));
DBUG_PRINT("info", ("crashing before writing xid"));
- DBUG_ABORT();
+ DBUG_SUICIDE();
});
if ((write_error= write_cache(thd, cache, FALSE, FALSE)))
@@ -5245,7 +5481,7 @@ bool MYSQL_BIN_LOG::write(THD *thd, IO_CACHE *cache, Log_event *commit_event,
bool synced= 0;
if (flush_and_sync(&synced))
goto err;
- DBUG_EXECUTE_IF("half_binlogged_transaction", DBUG_ABORT(););
+ DBUG_EXECUTE_IF("half_binlogged_transaction", DBUG_SUICIDE(););
if (cache->error) // Error on read
{
sql_print_error(ER(ER_ERROR_ON_READ), cache->file_name, errno);
@@ -5279,7 +5515,8 @@ bool MYSQL_BIN_LOG::write(THD *thd, IO_CACHE *cache, Log_event *commit_event,
mysql_mutex_unlock(&LOCK_prep_xids);
}
else
- rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED);
+ if (rotate_and_purge(RP_LOCK_LOG_IS_ALREADY_LOCKED))
+ goto err;
}
mysql_mutex_unlock(&LOCK_log);
@@ -5501,80 +5738,26 @@ void sql_perror(const char *message)
}
-#ifdef __WIN__
+/*
+ Change the file associated with two output streams. Used to
+ redirect stdout and stderr to a file. The streams are reopened
+ only for appending (writing at end of file).
+*/
extern "C" my_bool reopen_fstreams(const char *filename,
FILE *outstream, FILE *errstream)
{
- int handle_fd;
- int err_fd, out_fd;
- HANDLE osfh;
-
- DBUG_ASSERT(filename && errstream);
-
- // Services don't have stdout/stderr on Windows, so _fileno returns -1.
- err_fd= _fileno(errstream);
- if (err_fd < 0)
- {
- if (!freopen(filename, "a+", errstream))
- return TRUE;
-
- setbuf(errstream, NULL);
- err_fd= _fileno(errstream);
- }
-
- if (outstream)
- {
- out_fd= _fileno(outstream);
- if (out_fd < 0)
- {
- if (!freopen(filename, "a+", outstream))
- return TRUE;
- out_fd= _fileno(outstream);
- }
- }
-
- if ((osfh= CreateFile(filename, GENERIC_READ | GENERIC_WRITE,
- FILE_SHARE_READ | FILE_SHARE_WRITE |
- FILE_SHARE_DELETE, NULL,
- OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL,
- NULL)) == INVALID_HANDLE_VALUE)
- return TRUE;
-
- if ((handle_fd= _open_osfhandle((intptr_t)osfh,
- _O_APPEND | _O_TEXT)) == -1)
- {
- CloseHandle(osfh);
- return TRUE;
- }
-
- if (_dup2(handle_fd, err_fd) < 0)
- {
- CloseHandle(osfh);
- return TRUE;
- }
-
- if (outstream && _dup2(handle_fd, out_fd) < 0)
- {
- CloseHandle(osfh);
+ if (outstream && !my_freopen(filename, "a", outstream))
return TRUE;
- }
- _close(handle_fd);
- return FALSE;
-}
-#else
-extern "C" my_bool reopen_fstreams(const char *filename,
- FILE *outstream, FILE *errstream)
-{
- if (outstream && !freopen(filename, "a+", outstream))
+ if (errstream && !my_freopen(filename, "a", errstream))
return TRUE;
- if (errstream && !freopen(filename, "a+", errstream))
- return TRUE;
+ /* The error stream must be unbuffered. */
+ if (errstream)
+ setbuf(errstream, NULL);
return FALSE;
}
-#endif
/*
@@ -5865,7 +6048,7 @@ int TC_LOG_MMAP::open(const char *opt_name)
{
pg->next=pg+1;
pg->waiters=0;
- pg->state=POOL;
+ pg->state=PS_POOL;
mysql_mutex_init(key_PAGE_lock, &pg->lock, MY_MUTEX_INIT_FAST);
mysql_cond_init(key_PAGE_cond, &pg->cond, 0);
pg->ptr= pg->start=(my_xid *)(data + i*tc_log_page_size);
@@ -6047,7 +6230,7 @@ int TC_LOG_MMAP::log_xid(THD *thd, my_xid xid)
cookie= (ulong)((uchar *)p->ptr - data); // can never be zero
*p->ptr++= xid;
p->free--;
- p->state= DIRTY;
+ p->state= PS_DIRTY;
mysql_mutex_unlock(&p->lock);
mysql_mutex_lock(&LOCK_sync);
@@ -6058,7 +6241,7 @@ int TC_LOG_MMAP::log_xid(THD *thd, my_xid xid)
p->waiters++;
for (;;)
{
- int not_dirty = p->state != DIRTY;
+ int not_dirty = p->state != PS_DIRTY;
mysql_mutex_unlock(&p->lock);
if (not_dirty || !syncing)
break;
@@ -6066,8 +6249,8 @@ int TC_LOG_MMAP::log_xid(THD *thd, my_xid xid)
mysql_mutex_lock(&p->lock);
}
p->waiters--;
- err= p->state == ERROR;
- if (p->state != DIRTY) // page was synced
+ err= p->state == PS_ERROR;
+ if (p->state != PS_DIRTY) // page was synced
{
mysql_mutex_unlock(&LOCK_sync);
if (p->waiters == 0)
@@ -6116,7 +6299,7 @@ int TC_LOG_MMAP::sync()
pool_last->next=syncing;
pool_last=syncing;
syncing->next=0;
- syncing->state= err ? ERROR : POOL;
+ syncing->state= err ? PS_ERROR : PS_POOL;
mysql_cond_signal(&COND_pool); // in case somebody's waiting
mysql_mutex_unlock(&LOCK_pool);
@@ -6143,7 +6326,7 @@ int TC_LOG_MMAP::sync()
cookie points directly to the memory where xid was logged.
*/
-void TC_LOG_MMAP::unlog(ulong cookie, my_xid xid)
+int TC_LOG_MMAP::unlog(ulong cookie, my_xid xid)
{
PAGE *p=pages+(cookie/tc_log_page_size);
my_xid *x=(my_xid *)(data+cookie);
@@ -6161,6 +6344,7 @@ void TC_LOG_MMAP::unlog(ulong cookie, my_xid xid)
if (p->waiters == 0) // the page is in pool and ready to rock
mysql_cond_signal(&COND_pool); // ping ... for overflow()
mysql_mutex_unlock(&p->lock);
+ return 0;
}
void TC_LOG_MMAP::close()
@@ -6393,27 +6577,30 @@ void TC_LOG_BINLOG::close()
int TC_LOG_BINLOG::log_xid(THD *thd, my_xid xid)
{
DBUG_ENTER("TC_LOG_BINLOG::log");
- Xid_log_event xle(thd, xid);
binlog_cache_mngr *cache_mngr=
(binlog_cache_mngr*) thd_get_ha_data(thd, binlog_hton);
/*
We always commit the entire transaction when writing an XID. Also
note that the return value is inverted.
*/
- DBUG_RETURN(!binlog_flush_stmt_cache(thd, cache_mngr) &&
- !binlog_flush_trx_cache(thd, cache_mngr, &xle));
+ DBUG_RETURN(!binlog_commit_flush_stmt_cache(thd, cache_mngr) &&
+ !binlog_commit_flush_trx_cache(thd, cache_mngr, xid));
}
-void TC_LOG_BINLOG::unlog(ulong cookie, my_xid xid)
+int TC_LOG_BINLOG::unlog(ulong cookie, my_xid xid)
{
+ DBUG_ENTER("TC_LOG_BINLOG::unlog");
mysql_mutex_lock(&LOCK_prep_xids);
- DBUG_ASSERT(prepared_xids > 0);
- if (--prepared_xids == 0) {
+ // prepared_xids can be 0 if the transaction had ignorable errors.
+ DBUG_ASSERT(prepared_xids >= 0);
+ if (prepared_xids > 0)
+ prepared_xids--;
+ if (prepared_xids == 0) {
DBUG_PRINT("info", ("prepared_xids=%lu", prepared_xids));
mysql_cond_signal(&COND_prep_xids);
}
mysql_mutex_unlock(&LOCK_prep_xids);
- rotate_and_purge(0); // as ::write() did not rotate
+ DBUG_RETURN(rotate_and_purge(0)); // as ::write() did not rotate
}
int TC_LOG_BINLOG::recover(IO_CACHE *log, Format_description_log_event *fdle)
diff --git a/sql/log.h b/sql/log.h
index aeecc80a928..402c90034c7 100644
--- a/sql/log.h
+++ b/sql/log.h
@@ -1,4 +1,4 @@
-/* Copyright (C) 2005 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,7 +11,7 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#ifndef LOG_H
#define LOG_H
@@ -45,7 +45,7 @@ class TC_LOG
virtual int open(const char *opt_name)=0;
virtual void close()=0;
virtual int log_xid(THD *thd, my_xid xid)=0;
- virtual void unlog(ulong cookie, my_xid xid)=0;
+ virtual int unlog(ulong cookie, my_xid xid)=0;
};
class TC_LOG_DUMMY: public TC_LOG // use it to disable the logging
@@ -55,7 +55,7 @@ public:
int open(const char *opt_name) { return 0; }
void close() { }
int log_xid(THD *thd, my_xid xid) { return 1; }
- void unlog(ulong cookie, my_xid xid) { }
+ int unlog(ulong cookie, my_xid xid) { return 0; }
};
#ifdef HAVE_MMAP
@@ -63,9 +63,9 @@ class TC_LOG_MMAP: public TC_LOG
{
public: // only to keep Sun Forte on sol9x86 happy
typedef enum {
- POOL, // page is in pool
- ERROR, // last sync failed
- DIRTY // new xids added since last sync
+ PS_POOL, // page is in pool
+ PS_ERROR, // last sync failed
+ PS_DIRTY // new xids added since last sync
} PAGE_STATE;
private:
@@ -100,7 +100,7 @@ class TC_LOG_MMAP: public TC_LOG
int open(const char *opt_name);
void close();
int log_xid(THD *thd, my_xid xid);
- void unlog(ulong cookie, my_xid xid);
+ int unlog(ulong cookie, my_xid xid);
int recover();
private:
@@ -196,7 +196,11 @@ public:
MYSQL_LOG();
void init_pthread_objects();
void cleanup();
- bool open(const char *log_name,
+ bool open(
+#ifdef HAVE_PSI_INTERFACE
+ PSI_file_key log_file_key,
+#endif
+ const char *log_name,
enum_log_type log_type,
const char *new_name,
enum cache_type io_cache_type_arg);
@@ -223,6 +227,10 @@ public:
volatile enum_log_state log_state;
enum cache_type io_cache_type;
friend class Log_event;
+#ifdef HAVE_PSI_INTERFACE
+ /** Instrumentation key to use for file io in @c log_file */
+ PSI_file_key m_log_file_key;
+#endif
};
class MYSQL_QUERY_LOG: public MYSQL_LOG
@@ -241,14 +249,22 @@ public:
bool open_slow_log(const char *log_name)
{
char buf[FN_REFLEN];
- return open(generate_name(log_name, "-slow.log", 0, buf), LOG_NORMAL, 0,
- WRITE_CACHE);
+ return open(
+#ifdef HAVE_PSI_INTERFACE
+ key_file_slow_log,
+#endif
+ generate_name(log_name, "-slow.log", 0, buf),
+ LOG_NORMAL, 0, WRITE_CACHE);
}
bool open_query_log(const char *log_name)
{
char buf[FN_REFLEN];
- return open(generate_name(log_name, ".log", 0, buf), LOG_NORMAL, 0,
- WRITE_CACHE);
+ return open(
+#ifdef HAVE_PSI_INTERFACE
+ key_file_query_log,
+#endif
+ generate_name(log_name, ".log", 0, buf),
+ LOG_NORMAL, 0, WRITE_CACHE);
}
private:
@@ -258,6 +274,16 @@ private:
class MYSQL_BIN_LOG: public TC_LOG, private MYSQL_LOG
{
private:
+#ifdef HAVE_PSI_INTERFACE
+ /** The instrumentation key to use for @ LOCK_index. */
+ PSI_mutex_key m_key_LOCK_index;
+ /** The instrumentation key to use for @ update_cond. */
+ PSI_cond_key m_key_update_cond;
+ /** The instrumentation key to use for opening the log file. */
+ PSI_file_key m_key_file_log;
+ /** The instrumentation key to use for opening the log index file. */
+ PSI_file_key m_key_file_log_index;
+#endif
/* LOCK_log and LOCK_index are inited by init_pthread_objects() */
mysql_mutex_t LOCK_index;
mysql_mutex_t LOCK_prep_xids;
@@ -318,8 +344,8 @@ class MYSQL_BIN_LOG: public TC_LOG, private MYSQL_LOG
new_file() is locking. new_file_without_locking() does not acquire
LOCK_log.
*/
- void new_file_without_locking();
- void new_file_impl(bool need_lock);
+ int new_file_without_locking();
+ int new_file_impl(bool need_lock);
public:
MYSQL_LOG::generate_name;
@@ -346,10 +372,23 @@ public:
on exit() - but only during the correct shutdown process
*/
+#ifdef HAVE_PSI_INTERFACE
+ void set_psi_keys(PSI_mutex_key key_LOCK_index,
+ PSI_cond_key key_update_cond,
+ PSI_file_key key_file_log,
+ PSI_file_key key_file_log_index)
+ {
+ m_key_LOCK_index= key_LOCK_index;
+ m_key_update_cond= key_update_cond;
+ m_key_file_log= key_file_log;
+ m_key_file_log_index= key_file_log_index;
+ }
+#endif
+
int open(const char *opt_name);
void close();
int log_xid(THD *thd, my_xid xid);
- void unlog(ulong cookie, my_xid xid);
+ int unlog(ulong cookie, my_xid xid);
int recover(IO_CACHE *log, Format_description_log_event *fdle);
#if !defined(MYSQL_CLIENT)
@@ -392,14 +431,14 @@ public:
bool open_index_file(const char *index_file_name_arg,
const char *log_name, bool need_mutex);
/* Use this to start writing a new log file */
- void new_file();
+ int new_file();
bool write(Log_event* event_info); // binary log write
bool write(THD *thd, IO_CACHE *cache, Log_event *commit_event, bool incident);
bool write_incident(THD *thd, bool lock);
int write_cache(THD *thd, IO_CACHE *cache, bool lock_log,
bool flush_and_sync);
- void set_write_error(THD *thd);
+ void set_write_error(THD *thd, bool is_transactional);
bool check_write_error(THD *thd);
void start_union_events(THD *thd, query_id_t query_id_param);
@@ -416,7 +455,7 @@ public:
void make_log_name(char* buf, const char* log_ident);
bool is_active(const char* log_file_name);
int update_log_index(LOG_INFO* linfo, bool need_update_threads);
- void rotate_and_purge(uint flags);
+ int rotate_and_purge(uint flags);
/**
Flush binlog cache and synchronize to disk.
@@ -648,7 +687,7 @@ void sql_print_warning(const char *format, ...) ATTRIBUTE_FORMAT(printf, 1, 2);
void sql_print_information(const char *format, ...)
ATTRIBUTE_FORMAT(printf, 1, 2);
typedef void (*sql_print_message_func)(const char *format, ...)
- ATTRIBUTE_FORMAT(printf, 1, 2);
+ ATTRIBUTE_FORMAT_FPTR(printf, 1, 2);
extern sql_print_message_func sql_print_message_handlers[];
int error_log_print(enum loglevel level, const char *format,
diff --git a/sql/log_event.cc b/sql/log_event.cc
index 6f83e5f4db2..c5935b86df9 100644
--- a/sql/log_event.cc
+++ b/sql/log_event.cc
@@ -158,16 +158,21 @@ static void inline slave_rows_error_report(enum loglevel level, int ha_error,
" %s, Error_code: %d;", err->get_message_text(),
err->get_sql_errno());
}
-
- rli->report(level, thd->is_error()? thd->stmt_da->sql_errno() : 0,
- "Could not execute %s event on table %s.%s;"
- "%s handler error %s; "
- "the event's master log %s, end_log_pos %lu",
- type, table->s->db.str,
- table->s->table_name.str,
- buff,
- handler_error == NULL? "<unknown>" : handler_error,
- log_name, pos);
+
+ if (ha_error != 0)
+ rli->report(level, thd->is_error() ? thd->stmt_da->sql_errno() : 0,
+ "Could not execute %s event on table %s.%s;"
+ "%s handler error %s; "
+ "the event's master log %s, end_log_pos %lu",
+ type, table->s->db.str, table->s->table_name.str,
+ buff, handler_error == NULL ? "<unknown>" : handler_error,
+ log_name, pos);
+ else
+ rli->report(level, thd->is_error() ? thd->stmt_da->sql_errno() : 0,
+ "Could not execute %s event on table %s.%s;"
+ "%s the event's master log %s, end_log_pos %lu",
+ type, table->s->db.str, table->s->table_name.str,
+ buff, log_name, pos);
}
#endif
@@ -1238,7 +1243,7 @@ Log_event* Log_event::read_log_event(const char* buf, uint event_len,
break;
#ifdef HAVE_REPLICATION
case SLAVE_EVENT: /* can never happen (unused event) */
- ev = new Slave_log_event(buf, event_len);
+ ev = new Slave_log_event(buf, event_len, description_event);
break;
#endif /* HAVE_REPLICATION */
case CREATE_FILE_EVENT:
@@ -1326,8 +1331,10 @@ Log_event* Log_event::read_log_event(const char* buf, uint event_len,
(because constructor is "void") ; so instead we leave the pointer we
wanted to allocate (e.g. 'query') to 0 and we test it in is_valid().
Same for Format_description_log_event, member 'post_header_len'.
+
+ SLAVE_EVENT is never used, so it should not be read ever.
*/
- if (!ev || !ev->is_valid())
+ if (!ev || !ev->is_valid() || (event_type == SLAVE_EVENT))
{
DBUG_PRINT("error",("Found invalid event in binary log"));
@@ -2324,7 +2331,7 @@ bool Query_log_event::write(IO_CACHE* file)
start+= 4;
}
- if (thd && thd->is_current_user_used())
+ if (thd && thd->need_binlog_invoker())
{
LEX_STRING user;
LEX_STRING host;
@@ -2961,7 +2968,12 @@ void Query_log_event::print_query_header(IO_CACHE* file,
error_code);
}
- if (!(flags & LOG_EVENT_SUPPRESS_USE_F) && db)
+ if ((flags & LOG_EVENT_SUPPRESS_USE_F))
+ {
+ if (!is_trans_keyword())
+ print_event_info->db[0]= '\0';
+ }
+ else if (db)
{
different_db= memcmp(print_event_info->db, db, db_len + 1);
if (different_db)
@@ -3233,7 +3245,8 @@ int Query_log_event::do_apply_event(Relay_log_info const *rli,
if (is_trans_keyword() || rpl_filter->db_ok(thd->db))
{
thd->set_time((time_t)when);
- thd->set_query_and_id((char*)query_arg, q_len_arg, next_query_id());
+ thd->set_query_and_id((char*)query_arg, q_len_arg,
+ thd->charset(), next_query_id());
thd->variables.pseudo_thread_id= thread_id; // for temp tables
DBUG_PRINT("query",("%s", thd->query()));
@@ -3285,6 +3298,18 @@ int Query_log_event::do_apply_event(Relay_log_info const *rli,
goto compare_errors;
}
thd->update_charset(); // for the charset change to take effect
+ /*
+ Reset thd->query_string.cs to the newly set value.
+ Note, there is a small flaw here. For a very short time frame
+ if the new charset is different from the old charset and
+ if another thread executes "SHOW PROCESSLIST" after
+ the above thd->set_query_and_id() and before this thd->set_query(),
+ and if the current query has some non-ASCII characters,
+ the another thread may see some '?' marks in the PROCESSLIST
+ result. This should be acceptable now. This is a reminder
+ to fix this if any refactoring happens here sometime.
+ */
+ thd->set_query((char*) query_arg, q_len_arg, thd->charset());
}
}
if (time_zone_len)
@@ -3345,6 +3370,8 @@ int Query_log_event::do_apply_event(Relay_log_info const *rli,
if (!parser_state.init(thd, thd->query(), thd->query_length()))
{
mysql_parse(thd, thd->query(), thd->query_length(), &parser_state);
+ /* Finalize server status flags after executing a statement. */
+ thd->update_server_status();
log_slow_statement(thd);
}
@@ -3419,7 +3446,8 @@ compare_errors:
rli->report(ERROR_LEVEL, 0,
"\
Query caused different errors on master and slave. \
-Error on master: '%s' (%d), Error on slave: '%s' (%d). \
+Error on master: message (format)='%s' error code=%d ; \
+Error on slave: actual message='%s', error code=%d. \
Default database: '%s'. Query: '%s'",
ER_SAFE(expected_error),
expected_error,
@@ -3505,7 +3533,7 @@ end:
*/
thd->catalog= 0;
thd->set_db(NULL, 0); /* will free the current database */
- thd->set_query(NULL, 0);
+ thd->reset_query();
DBUG_PRINT("info", ("end: query= 0"));
/*
As a disk space optimization, future masters will not log an event for
@@ -4742,7 +4770,7 @@ int Load_log_event::do_apply_event(NET* net, Relay_log_info const *rli,
new_db.str= (char *) rpl_filter->get_rewrite_db(db, &new_db.length);
thd->set_db(new_db.str, new_db.length);
DBUG_ASSERT(thd->query() == 0);
- thd->set_query_inner(NULL, 0); // Should not be needed
+ thd->reset_query_inner(); // Should not be needed
thd->is_slave_error= 0;
clear_all_errors(thd, const_cast<Relay_log_info*>(rli));
@@ -4936,7 +4964,7 @@ error:
const char *remember_db= thd->db;
thd->catalog= 0;
thd->set_db(NULL, 0); /* will free the current database */
- thd->set_query(NULL, 0);
+ thd->reset_query();
thd->stmt_da->can_overwrite_status= TRUE;
thd->is_error() ? trans_rollback_stmt(thd) : trans_commit_stmt(thd);
thd->stmt_da->can_overwrite_status= FALSE;
@@ -4953,6 +4981,8 @@ error:
*/
if (! thd->in_multi_stmt_transaction_mode())
thd->mdl_context.release_transactional_locks();
+ else
+ thd->mdl_context.release_statement_locks();
DBUG_EXECUTE_IF("LOAD_DATA_INFILE_has_fatal_error",
thd->is_slave_error= 0; thd->is_fatal_error= 1;);
@@ -6111,8 +6141,12 @@ void Slave_log_event::init_from_mem_pool(int data_size)
/** This code is not used, so has not been updated to be format-tolerant. */
-Slave_log_event::Slave_log_event(const char* buf, uint event_len)
- :Log_event(buf,0) /*unused event*/ ,mem_pool(0),master_host(0)
+/* We are using description_event so that slave does not crash on Log_event
+ constructor */
+Slave_log_event::Slave_log_event(const char* buf,
+ uint event_len,
+ const Format_description_log_event* description_event)
+ :Log_event(buf,description_event),mem_pool(0),master_host(0)
{
if (event_len < LOG_EVENT_HEADER_LEN)
return;
@@ -7711,6 +7745,14 @@ int Rows_log_event::do_apply_event(Relay_log_info const *rli)
// Do event specific preparations
error= do_before_row_operations(rli);
+ /*
+ Bug#56662 Assertion failed: next_insert_id == 0, file handler.cc
+ Don't allow generation of auto_increment value when processing
+ rows event by setting 'MODE_NO_AUTO_VALUE_ON_ZERO'.
+ */
+ ulong saved_sql_mode= thd->variables.sql_mode;
+ thd->variables.sql_mode= MODE_NO_AUTO_VALUE_ON_ZERO;
+
// row processing loop
while (error == 0 && m_curr_row < m_rows_end)
@@ -7773,6 +7815,11 @@ int Rows_log_event::do_apply_event(Relay_log_info const *rli)
thd->transaction.stmt.modified_non_trans_table= TRUE;
} // row processing loop
+ /*
+ Restore the sql_mode after the rows event is processed.
+ */
+ thd->variables.sql_mode= saved_sql_mode;
+
{/**
The following failure injecion works in cooperation with tests
setting @@global.debug= 'd,stop_slave_middle_group'.
@@ -7811,19 +7858,16 @@ int Rows_log_event::do_apply_event(Relay_log_info const *rli)
/Sven
*/
thd->reset_current_stmt_binlog_format_row();
- const_cast<Relay_log_info*>(rli)->cleanup_context(thd, error);
thd->is_slave_error= 1;
DBUG_RETURN(error);
}
- if (get_flags(STMT_END_F))
- if ((error= rows_event_stmt_cleanup(rli, thd)))
- rli->report(ERROR_LEVEL, error,
- "Error in %s event: commit of row events failed, "
- "table `%s`.`%s`",
- get_type_str(), m_table->s->db.str,
- m_table->s->table_name.str);
-
+ if (get_flags(STMT_END_F) && (error= rows_event_stmt_cleanup(rli, thd)))
+ slave_rows_error_report(ERROR_LEVEL,
+ thd->is_error() ? 0 : error,
+ rli, thd, table,
+ get_type_str(),
+ RPL_LOG_NAME, (ulong) log_pos);
DBUG_RETURN(error);
}
@@ -8502,6 +8546,8 @@ int Table_map_log_event::do_apply_event(Relay_log_info const *rli)
m_field_metadata, m_field_metadata_size,
m_null_bits, m_flags);
table_list->m_tabledef_valid= TRUE;
+ table_list->m_conv_table= NULL;
+ table_list->open_type= OT_BASE_ONLY;
/*
We record in the slave's information that the table should be
@@ -8606,7 +8652,7 @@ void Table_map_log_event::pack_info(Protocol *protocol)
#ifdef MYSQL_CLIENT
-void Table_map_log_event::print(FILE *file, PRINT_EVENT_INFO *print_event_info)
+void Table_map_log_event::print(FILE *, PRINT_EVENT_INFO *print_event_info)
{
if (!print_event_info->short_form)
{
@@ -8843,16 +8889,11 @@ Rows_log_event::write_row(const Relay_log_info *const rli,
int UNINIT_VAR(keynum);
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,
- table->file->ht->db_type != DB_TYPE_NDBCLUSTER,
- abort_on_warnings, m_curr_row == m_rows_buf)))
- DBUG_RETURN(error);
-
+ prepare_record(table, m_width,
+ table->file->ht->db_type != DB_TYPE_NDBCLUSTER);
+
/* unpack row into table->record[0] */
- if ((error= unpack_current_row(rli, abort_on_warnings)))
+ if ((error= unpack_current_row(rli)))
DBUG_RETURN(error);
if (m_curr_row == m_rows_buf)
@@ -9117,7 +9158,19 @@ static bool record_compare(TABLE *table)
}
}
- if (table->s->blob_fields + table->s->varchar_fields == 0)
+ /**
+ Compare full record only if:
+ - there are no blob fields (otherwise we would also need
+ to compare blobs contents as well);
+ - there are no varchar fields (otherwise we would also need
+ to compare varchar contents as well);
+ - there are no null fields, otherwise NULLed fields
+ contents (i.e., the don't care bytes) may show arbitrary
+ values, depending on how each engine handles internally.
+ */
+ if ((table->s->blob_fields +
+ table->s->varchar_fields +
+ table->s->null_fields) == 0)
{
result= cmp_record(table,record[1]);
goto record_compare_exit;
@@ -9132,13 +9185,22 @@ static bool record_compare(TABLE *table)
goto record_compare_exit;
}
- /* Compare updated fields */
+ /* Compare fields */
for (Field **ptr=table->field ; *ptr ; ptr++)
{
- if ((*ptr)->cmp_binary_offset(table->s->rec_buff_length))
+
+ /**
+ We only compare field contents that are not null.
+ NULL fields (i.e., their null bits) were compared
+ earlier.
+ */
+ if (!(*(ptr))->is_null())
{
- result= TRUE;
- goto record_compare_exit;
+ if ((*ptr)->cmp_binary_offset(table->s->rec_buff_length))
+ {
+ result= TRUE;
+ goto record_compare_exit;
+ }
}
}
@@ -9703,11 +9765,9 @@ Update_rows_log_event::do_exec_row(const Relay_log_info *const rli)
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;
/* this also updates m_curr_row_end */
- if ((error= unpack_current_row(rli, abort_on_warnings)))
+ if ((error= unpack_current_row(rli)))
return error;
/*
diff --git a/sql/log_event.h b/sql/log_event.h
index d900ddd36e6..e57115432ec 100644
--- a/sql/log_event.h
+++ b/sql/log_event.h
@@ -1039,7 +1039,7 @@ public:
return (void*) my_malloc((uint)size, MYF(MY_WME|MY_FAE));
}
- static void operator delete(void *ptr, size_t size)
+ static void operator delete(void *ptr, size_t)
{
my_free(ptr);
}
@@ -1858,7 +1858,9 @@ public:
void print(FILE* file, PRINT_EVENT_INFO* print_event_info);
#endif
- Slave_log_event(const char* buf, uint event_len);
+ Slave_log_event(const char* buf,
+ uint event_len,
+ const Format_description_log_event *description_event);
~Slave_log_event();
int get_data_size();
bool is_valid() const { return master_host != 0; }
@@ -2516,7 +2518,7 @@ class Xid_log_event: public Log_event
my_xid xid;
#ifdef MYSQL_SERVER
- Xid_log_event(THD* thd_arg, my_xid x): Log_event(thd_arg,0,0), xid(x) {}
+ Xid_log_event(THD* thd_arg, my_xid x): Log_event(thd_arg, 0, TRUE), xid(x) {}
#ifdef HAVE_REPLICATION
void pack_info(Protocol* protocol);
#endif /* HAVE_REPLICATION */
@@ -3679,16 +3681,13 @@ 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,
- const bool abort_on_warning= TRUE)
- {
+ int unpack_current_row(const Relay_log_info *const rli)
+ {
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,
- abort_on_warning, first_row);
+ &m_curr_row_end, &m_master_reclength);
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);
diff --git a/sql/mdl.cc b/sql/mdl.cc
index aa7c2a4b7f2..21410db2d22 100644
--- a/sql/mdl.cc
+++ b/sql/mdl.cc
@@ -18,6 +18,8 @@
#include "debug_sync.h"
#include <hash.h>
#include <mysqld_error.h>
+#include <mysql/plugin.h>
+#include <mysql/service_thd_wait.h>
#ifdef HAVE_PSI_INTERFACE
static PSI_mutex_key key_MDL_map_mutex;
@@ -68,8 +70,6 @@ static void init_mdl_psi_keys(void)
}
#endif /* HAVE_PSI_INTERFACE */
-void notify_shared_lock(THD *thd, MDL_ticket *conflicting_ticket);
-
/**
Thread state names to be used in case when we have to wait on resource
@@ -78,12 +78,14 @@ void notify_shared_lock(THD *thd, MDL_ticket *conflicting_ticket);
const char *MDL_key::m_namespace_to_wait_state_name[NAMESPACE_END]=
{
- "Waiting for global metadata lock",
+ "Waiting for global read lock",
"Waiting for schema metadata lock",
"Waiting for table metadata lock",
"Waiting for stored function metadata lock",
"Waiting for stored procedure metadata lock",
- NULL
+ "Waiting for trigger metadata lock",
+ "Waiting for event metadata lock",
+ "Waiting for commit lock"
};
static bool mdl_initialized= 0;
@@ -100,7 +102,6 @@ class MDL_map
public:
void init();
void destroy();
- MDL_lock *find(const MDL_key *key);
MDL_lock *find_or_insert(const MDL_key *key);
void remove(MDL_lock *lock);
private:
@@ -110,6 +111,10 @@ private:
HASH m_locks;
/* Protects access to m_locks hash. */
mysql_mutex_t m_mutex;
+ /** Pre-allocated MDL_lock object for GLOBAL namespace. */
+ MDL_lock *m_global_lock;
+ /** Pre-allocated MDL_lock object for COMMIT namespace. */
+ MDL_lock *m_commit_lock;
};
@@ -124,6 +129,7 @@ public:
Deadlock_detection_visitor(MDL_context *start_node_arg)
: m_start_node(start_node_arg),
m_victim(NULL),
+ m_current_search_depth(0),
m_found_deadlock(FALSE)
{}
virtual bool enter_node(MDL_context *node);
@@ -132,8 +138,6 @@ public:
virtual bool inspect_edge(MDL_context *dest);
MDL_context *get_victim() const { return m_victim; }
-
- void abort_traversal(MDL_context *node);
private:
/**
Change the deadlock victim to a new one if it has lower deadlock
@@ -148,6 +152,13 @@ private:
MDL_context *m_start_node;
/** If a deadlock is found, the context that identifies the victim. */
MDL_context *m_victim;
+ /** Set to the 0 at start. Increased whenever
+ we descend into another MDL context (aka traverse to the next
+ wait-for graph node). When MAX_SEARCH_DEPTH is reached, we
+ assume that a deadlock is found, even if we have not found a
+ loop.
+ */
+ uint m_current_search_depth;
/** TRUE if we found a deadlock. */
bool m_found_deadlock;
/**
@@ -181,7 +192,7 @@ private:
bool Deadlock_detection_visitor::enter_node(MDL_context *node)
{
- m_found_deadlock= m_current_search_depth >= MAX_SEARCH_DEPTH;
+ m_found_deadlock= ++m_current_search_depth >= MAX_SEARCH_DEPTH;
if (m_found_deadlock)
{
DBUG_ASSERT(! m_victim);
@@ -201,6 +212,7 @@ bool Deadlock_detection_visitor::enter_node(MDL_context *node)
void Deadlock_detection_visitor::leave_node(MDL_context *node)
{
+ --m_current_search_depth;
if (m_found_deadlock)
opt_change_victim_to(node);
}
@@ -245,21 +257,6 @@ Deadlock_detection_visitor::opt_change_victim_to(MDL_context *new_victim)
/**
- Abort traversal of a wait-for graph and report a deadlock.
-
- @param node Node which we were about to visit when abort
- was initiated.
-*/
-
-void Deadlock_detection_visitor::abort_traversal(MDL_context *node)
-{
- DBUG_ASSERT(! m_victim);
- m_found_deadlock= TRUE;
- opt_change_victim_to(node);
-}
-
-
-/**
Get a bit corresponding to enum_mdl_type value in a granted/waiting bitmaps
and compatibility matrices.
*/
@@ -362,18 +359,6 @@ public:
inline static MDL_lock *create(const MDL_key *key);
- void notify_shared_locks(MDL_context *ctx)
- {
- Ticket_iterator it(m_granted);
- MDL_ticket *conflicting_ticket;
-
- while ((conflicting_ticket= it++))
- {
- if (conflicting_ticket->get_ctx() != ctx)
- notify_shared_lock(ctx->get_thd(), conflicting_ticket);
- }
- }
-
void reschedule_waiters();
void remove_ticket(Ticket_list MDL_lock::*queue, MDL_ticket *ticket);
@@ -381,6 +366,9 @@ public:
bool visit_subgraph(MDL_ticket *waiting_ticket,
MDL_wait_for_graph_visitor *gvisitor);
+ virtual bool needs_notification(const MDL_ticket *ticket) const = 0;
+ virtual void notify_conflicting_locks(MDL_context *ctx) = 0;
+
/** List of granted tickets for this lock. */
Ticket_list m_granted;
/** Tickets for contexts waiting to acquire a lock. */
@@ -450,6 +438,11 @@ public:
{
return m_waiting_incompatible;
}
+ virtual bool needs_notification(const MDL_ticket *ticket) const
+ {
+ return (ticket->get_type() == MDL_SHARED);
+ }
+ virtual void notify_conflicting_locks(MDL_context *ctx);
private:
static const bitmap_t m_granted_incompatible[MDL_TYPE_END];
@@ -477,6 +470,11 @@ public:
{
return m_waiting_incompatible;
}
+ virtual bool needs_notification(const MDL_ticket *ticket) const
+ {
+ return ticket->is_upgradable_or_exclusive();
+ }
+ virtual void notify_conflicting_locks(MDL_context *ctx);
private:
static const bitmap_t m_granted_incompatible[MDL_TYPE_END];
@@ -544,9 +542,14 @@ void mdl_destroy()
void MDL_map::init()
{
+ MDL_key global_lock_key(MDL_key::GLOBAL, "", "");
+ MDL_key commit_lock_key(MDL_key::COMMIT, "", "");
+
mysql_mutex_init(key_MDL_map_mutex, &m_mutex, NULL);
my_hash_init(&m_locks, &my_charset_bin, 16 /* FIXME */, 0, 0,
mdl_locks_key, 0, 0);
+ m_global_lock= MDL_lock::create(&global_lock_key);
+ m_commit_lock= MDL_lock::create(&commit_lock_key);
}
@@ -560,6 +563,8 @@ void MDL_map::destroy()
DBUG_ASSERT(!m_locks.records);
mysql_mutex_destroy(&m_mutex);
my_hash_free(&m_locks);
+ MDL_lock::destroy(m_global_lock);
+ MDL_lock::destroy(m_commit_lock);
}
@@ -577,43 +582,28 @@ MDL_lock* MDL_map::find_or_insert(const MDL_key *mdl_key)
MDL_lock *lock;
my_hash_value_type hash_value;
- hash_value= my_calc_hash(&m_locks, mdl_key->ptr(), mdl_key->length());
-
-retry:
- mysql_mutex_lock(&m_mutex);
- if (!(lock= (MDL_lock*) my_hash_search_using_hash_value(&m_locks,
- hash_value,
- mdl_key->ptr(),
- mdl_key->length())))
+ if (mdl_key->mdl_namespace() == MDL_key::GLOBAL ||
+ mdl_key->mdl_namespace() == MDL_key::COMMIT)
{
- lock= MDL_lock::create(mdl_key);
- if (!lock || my_hash_insert(&m_locks, (uchar*)lock))
- {
- mysql_mutex_unlock(&m_mutex);
- MDL_lock::destroy(lock);
- return NULL;
- }
- }
+ /*
+ Avoid locking m_mutex when lock for GLOBAL or COMMIT namespace is
+ requested. Return pointer to pre-allocated MDL_lock instance instead.
+ Such an optimization allows to save one mutex lock/unlock for any
+ statement changing data.
- if (move_from_hash_to_lock_mutex(lock))
- goto retry;
+ It works since these namespaces contain only one element so keys
+ for them look like '<namespace-id>\0\0'.
+ */
+ DBUG_ASSERT(mdl_key->length() == 3);
- return lock;
-}
+ lock= (mdl_key->mdl_namespace() == MDL_key::GLOBAL) ? m_global_lock :
+ m_commit_lock;
+ mysql_prlock_wrlock(&lock->m_rwlock);
-/**
- Find MDL_lock object corresponding to the key.
-
- @retval non-NULL - MDL_lock instance for the key with locked
- MDL_lock::m_rwlock.
- @retval NULL - There was no MDL_lock for the key.
-*/
+ return lock;
+ }
-MDL_lock* MDL_map::find(const MDL_key *mdl_key)
-{
- MDL_lock *lock;
- my_hash_value_type hash_value;
hash_value= my_calc_hash(&m_locks, mdl_key->ptr(), mdl_key->length());
@@ -624,8 +614,13 @@ retry:
mdl_key->ptr(),
mdl_key->length())))
{
- mysql_mutex_unlock(&m_mutex);
- return NULL;
+ lock= MDL_lock::create(mdl_key);
+ if (!lock || my_hash_insert(&m_locks, (uchar*)lock))
+ {
+ mysql_mutex_unlock(&m_mutex);
+ MDL_lock::destroy(lock);
+ return NULL;
+ }
}
if (move_from_hash_to_lock_mutex(lock))
@@ -692,6 +687,17 @@ void MDL_map::remove(MDL_lock *lock)
{
uint ref_usage, ref_release;
+ if (lock->key.mdl_namespace() == MDL_key::GLOBAL ||
+ lock->key.mdl_namespace() == MDL_key::COMMIT)
+ {
+ /*
+ Never destroy pre-allocated MDL_lock objects for GLOBAL and
+ COMMIT namespaces.
+ */
+ mysql_prlock_unlock(&lock->m_rwlock);
+ return;
+ }
+
/*
Destroy the MDL_lock object, but ensure that anyone that is
holding a reference to the object is not remaining, if so he
@@ -727,8 +733,7 @@ void MDL_map::remove(MDL_lock *lock)
*/
MDL_context::MDL_context()
- :m_trans_sentinel(NULL),
- m_thd(NULL),
+ : m_thd(NULL),
m_needs_thr_lock_abort(FALSE),
m_waiting_for(NULL)
{
@@ -750,7 +755,9 @@ MDL_context::MDL_context()
void MDL_context::destroy()
{
- DBUG_ASSERT(m_tickets.is_empty());
+ DBUG_ASSERT(m_tickets[MDL_STATEMENT].is_empty() &&
+ m_tickets[MDL_TRANSACTION].is_empty() &&
+ m_tickets[MDL_EXPLICIT].is_empty());
mysql_prlock_destroy(&m_LOCK_waiting_for);
}
@@ -779,10 +786,12 @@ void MDL_context::destroy()
void MDL_request::init(MDL_key::enum_mdl_namespace mdl_namespace,
const char *db_arg,
const char *name_arg,
- enum enum_mdl_type mdl_type_arg)
+ enum_mdl_type mdl_type_arg,
+ enum_mdl_duration mdl_duration_arg)
{
key.mdl_key_init(mdl_namespace, db_arg, name_arg);
type= mdl_type_arg;
+ duration= mdl_duration_arg;
ticket= NULL;
}
@@ -797,49 +806,17 @@ void MDL_request::init(MDL_key::enum_mdl_namespace mdl_namespace,
*/
void MDL_request::init(const MDL_key *key_arg,
- enum enum_mdl_type mdl_type_arg)
+ enum_mdl_type mdl_type_arg,
+ enum_mdl_duration mdl_duration_arg)
{
key.mdl_key_init(key_arg);
type= mdl_type_arg;
+ duration= mdl_duration_arg;
ticket= NULL;
}
/**
- Allocate and initialize one lock request.
-
- Same as mdl_init_lock(), but allocates the lock and the key buffer
- on a memory root. Necessary to lock ad-hoc tables, e.g.
- mysql.* tables of grant and data dictionary subsystems.
-
- @param mdl_namespace Id of namespace of object to be locked
- @param db Name of database to which object belongs
- @param name Name of of object
- @param root MEM_ROOT on which object should be allocated
-
- @note The allocated lock request will have MDL_SHARED type.
-
- @retval 0 Error if out of memory
- @retval non-0 Pointer to an object representing a lock request
-*/
-
-MDL_request *
-MDL_request::create(MDL_key::enum_mdl_namespace mdl_namespace, const char *db,
- const char *name, enum_mdl_type mdl_type,
- MEM_ROOT *root)
-{
- MDL_request *mdl_request;
-
- if (!(mdl_request= (MDL_request*) alloc_root(root, sizeof(MDL_request))))
- return NULL;
-
- mdl_request->init(mdl_namespace, db, name, mdl_type);
-
- return mdl_request;
-}
-
-
-/**
Auxiliary functions needed for creation/destruction of MDL_lock objects.
@note Also chooses an MDL_lock descendant appropriate for object namespace.
@@ -854,6 +831,7 @@ inline MDL_lock *MDL_lock::create(const MDL_key *mdl_key)
{
case MDL_key::GLOBAL:
case MDL_key::SCHEMA:
+ case MDL_key::COMMIT:
return new MDL_scoped_lock(mdl_key);
default:
return new MDL_object_lock(mdl_key);
@@ -875,9 +853,17 @@ void MDL_lock::destroy(MDL_lock *lock)
on memory allocation by reusing released objects.
*/
-MDL_ticket *MDL_ticket::create(MDL_context *ctx_arg, enum_mdl_type type_arg)
+MDL_ticket *MDL_ticket::create(MDL_context *ctx_arg, enum_mdl_type type_arg
+#ifndef DBUG_OFF
+ , enum_mdl_duration duration_arg
+#endif
+ )
{
- return new MDL_ticket(ctx_arg, type_arg);
+ return new MDL_ticket(ctx_arg, type_arg
+#ifndef DBUG_OFF
+ , duration_arg
+#endif
+ );
}
@@ -989,10 +975,14 @@ MDL_wait::timed_wait(THD *thd, struct timespec *abs_timeout,
old_msg= thd_enter_cond(thd, &m_COND_wait_status, &m_LOCK_wait_status,
wait_state_name);
+ thd_wait_begin(thd, THD_WAIT_META_DATA_LOCK);
while (!m_wait_status && !thd_killed(thd) &&
wait_result != ETIMEDOUT && wait_result != ETIME)
+ {
wait_result= mysql_cond_timedwait(&m_COND_wait_status, &m_LOCK_wait_status,
abs_timeout);
+ }
+ thd_wait_end(thd);
if (m_wait_status == EMPTY)
{
@@ -1446,13 +1436,11 @@ bool MDL_ticket::is_incompatible_when_waiting(enum_mdl_type type) const
/**
Check whether the context already holds a compatible lock ticket
on an object.
- Start searching the transactional locks. If not
- found in the list of transactional locks, look at LOCK TABLES
- and HANDLER locks.
+ Start searching from list of locks for the same duration as lock
+ being requested. If not look at lists for other durations.
@param mdl_request Lock request object for lock to be acquired
- @param[out] is_transactional FALSE if we pass beyond m_trans_sentinel
- while searching for ticket, otherwise TRUE.
+ @param[out] result_duration Duration of lock which was found.
@note Tickets which correspond to lock types "stronger" than one
being requested are also considered compatible.
@@ -1462,24 +1450,28 @@ bool MDL_ticket::is_incompatible_when_waiting(enum_mdl_type type) const
MDL_ticket *
MDL_context::find_ticket(MDL_request *mdl_request,
- bool *is_transactional)
+ enum_mdl_duration *result_duration)
{
MDL_ticket *ticket;
- Ticket_iterator it(m_tickets);
+ int i;
- *is_transactional= TRUE;
-
- while ((ticket= it++))
+ for (i= 0; i < MDL_DURATION_END; i++)
{
- if (ticket == m_trans_sentinel)
- *is_transactional= FALSE;
+ enum_mdl_duration duration= (enum_mdl_duration)((mdl_request->duration+i) %
+ MDL_DURATION_END);
+ Ticket_iterator it(m_tickets[duration]);
- if (mdl_request->key.is_equal(&ticket->m_lock->key) &&
- ticket->has_stronger_or_equal_type(mdl_request->type))
- break;
+ while ((ticket= it++))
+ {
+ if (mdl_request->key.is_equal(&ticket->m_lock->key) &&
+ ticket->has_stronger_or_equal_type(mdl_request->type))
+ {
+ *result_duration= duration;
+ return ticket;
+ }
+ }
}
-
- return ticket;
+ return NULL;
}
@@ -1557,7 +1549,7 @@ MDL_context::try_acquire_lock_impl(MDL_request *mdl_request,
MDL_lock *lock;
MDL_key *key= &mdl_request->key;
MDL_ticket *ticket;
- bool is_transactional;
+ enum_mdl_duration found_duration;
DBUG_ASSERT(mdl_request->type != MDL_EXCLUSIVE ||
is_lock_owner(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE));
@@ -1571,7 +1563,7 @@ MDL_context::try_acquire_lock_impl(MDL_request *mdl_request,
Check whether the context already holds a shared lock on the object,
and if so, grant the request.
*/
- if ((ticket= find_ticket(mdl_request, &is_transactional)))
+ if ((ticket= find_ticket(mdl_request, &found_duration)))
{
DBUG_ASSERT(ticket->m_lock);
DBUG_ASSERT(ticket->has_stronger_or_equal_type(mdl_request->type));
@@ -1593,7 +1585,9 @@ MDL_context::try_acquire_lock_impl(MDL_request *mdl_request,
a different alias.
*/
mdl_request->ticket= ticket;
- if (!is_transactional && clone_ticket(mdl_request))
+ if ((found_duration != mdl_request->duration ||
+ mdl_request->duration == MDL_EXPLICIT) &&
+ clone_ticket(mdl_request))
{
/* Clone failed. */
mdl_request->ticket= NULL;
@@ -1602,7 +1596,11 @@ MDL_context::try_acquire_lock_impl(MDL_request *mdl_request,
return FALSE;
}
- if (!(ticket= MDL_ticket::create(this, mdl_request->type)))
+ if (!(ticket= MDL_ticket::create(this, mdl_request->type
+#ifndef DBUG_OFF
+ , mdl_request->duration
+#endif
+ )))
return TRUE;
/* The below call implicitly locks MDL_lock::m_rwlock on success. */
@@ -1620,7 +1618,7 @@ MDL_context::try_acquire_lock_impl(MDL_request *mdl_request,
mysql_prlock_unlock(&lock->m_rwlock);
- m_tickets.push_front(ticket);
+ m_tickets[mdl_request->duration].push_front(ticket);
mdl_request->ticket= ticket;
}
@@ -1655,7 +1653,11 @@ MDL_context::clone_ticket(MDL_request *mdl_request)
we effectively downgrade the cloned lock to the level of
the request.
*/
- if (!(ticket= MDL_ticket::create(this, mdl_request->type)))
+ if (!(ticket= MDL_ticket::create(this, mdl_request->type
+#ifndef DBUG_OFF
+ , mdl_request->duration
+#endif
+ )))
return TRUE;
/* clone() is not supposed to be used to get a stronger lock. */
@@ -1668,36 +1670,74 @@ MDL_context::clone_ticket(MDL_request *mdl_request)
ticket->m_lock->m_granted.add_ticket(ticket);
mysql_prlock_unlock(&ticket->m_lock->m_rwlock);
- m_tickets.push_front(ticket);
+ m_tickets[mdl_request->duration].push_front(ticket);
return FALSE;
}
/**
- Notify a thread holding a shared metadata lock which
- conflicts with a pending exclusive lock.
+ Notify threads holding a shared metadata locks on object which
+ conflict with a pending X, SNW or SNRW lock.
- @param thd Current thread context
- @param conflicting_ticket Conflicting metadata lock
+ @param ctx MDL_context for current thread.
*/
-void notify_shared_lock(THD *thd, MDL_ticket *conflicting_ticket)
+void MDL_object_lock::notify_conflicting_locks(MDL_context *ctx)
{
- /* Only try to abort locks on which we back off. */
- if (conflicting_ticket->get_type() < MDL_SHARED_NO_WRITE)
+ Ticket_iterator it(m_granted);
+ MDL_ticket *conflicting_ticket;
+
+ while ((conflicting_ticket= it++))
{
- MDL_context *conflicting_ctx= conflicting_ticket->get_ctx();
- THD *conflicting_thd= conflicting_ctx->get_thd();
- DBUG_ASSERT(thd != conflicting_thd); /* Self-deadlock */
+ /* Only try to abort locks on which we back off. */
+ if (conflicting_ticket->get_ctx() != ctx &&
+ conflicting_ticket->get_type() < MDL_SHARED_NO_WRITE)
- /*
- If thread which holds conflicting lock is waiting on table-level
- lock or some other non-MDL resource we might need to wake it up
- by calling code outside of MDL.
- */
- mysql_notify_thread_having_shared_lock(thd, conflicting_thd,
- conflicting_ctx->get_needs_thr_lock_abort());
+ {
+ MDL_context *conflicting_ctx= conflicting_ticket->get_ctx();
+
+ /*
+ If thread which holds conflicting lock is waiting on table-level
+ lock or some other non-MDL resource we might need to wake it up
+ by calling code outside of MDL.
+ */
+ mysql_notify_thread_having_shared_lock(ctx->get_thd(),
+ conflicting_ctx->get_thd(),
+ conflicting_ctx->get_needs_thr_lock_abort());
+ }
+ }
+}
+
+
+/**
+ Notify threads holding scoped IX locks which conflict with a pending S lock.
+
+ @param ctx MDL_context for current thread.
+*/
+
+void MDL_scoped_lock::notify_conflicting_locks(MDL_context *ctx)
+{
+ Ticket_iterator it(m_granted);
+ MDL_ticket *conflicting_ticket;
+
+ while ((conflicting_ticket= it++))
+ {
+ if (conflicting_ticket->get_ctx() != ctx &&
+ conflicting_ticket->get_type() == MDL_INTENTION_EXCLUSIVE)
+
+ {
+ MDL_context *conflicting_ctx= conflicting_ticket->get_ctx();
+
+ /*
+ Thread which holds global IX lock can be a handler thread for
+ insert delayed. We need to kill such threads in order to get
+ global shared lock. We do this my calling code outside of MDL.
+ */
+ mysql_notify_thread_having_shared_lock(ctx->get_thd(),
+ conflicting_ctx->get_thd(),
+ conflicting_ctx->get_needs_thr_lock_abort());
+ }
}
}
@@ -1755,8 +1795,8 @@ MDL_context::acquire_lock(MDL_request *mdl_request, ulong lock_wait_timeout)
*/
m_wait.reset_status();
- if (ticket->is_upgradable_or_exclusive())
- lock->notify_shared_locks(this);
+ if (lock->needs_notification(ticket))
+ lock->notify_conflicting_locks(this);
mysql_prlock_unlock(&lock->m_rwlock);
@@ -1767,7 +1807,7 @@ MDL_context::acquire_lock(MDL_request *mdl_request, ulong lock_wait_timeout)
find_deadlock();
- if (ticket->is_upgradable_or_exclusive())
+ if (lock->needs_notification(ticket))
{
struct timespec abs_shortwait;
set_timespec(abs_shortwait, 1);
@@ -1783,7 +1823,7 @@ MDL_context::acquire_lock(MDL_request *mdl_request, ulong lock_wait_timeout)
break;
mysql_prlock_wrlock(&lock->m_rwlock);
- lock->notify_shared_locks(this);
+ lock->notify_conflicting_locks(this);
mysql_prlock_unlock(&lock->m_rwlock);
set_timespec(abs_shortwait, 1);
}
@@ -1826,7 +1866,7 @@ MDL_context::acquire_lock(MDL_request *mdl_request, ulong lock_wait_timeout)
*/
DBUG_ASSERT(wait_status == MDL_wait::GRANTED);
- m_tickets.push_front(ticket);
+ m_tickets[mdl_request->duration].push_front(ticket);
mdl_request->ticket= ticket;
@@ -1867,7 +1907,7 @@ bool MDL_context::acquire_locks(MDL_request_list *mdl_requests,
{
MDL_request_list::Iterator it(*mdl_requests);
MDL_request **sort_buf, **p_req;
- MDL_ticket *mdl_svp= mdl_savepoint();
+ MDL_savepoint mdl_svp= mdl_savepoint();
ssize_t req_count= static_cast<ssize_t>(mdl_requests->elements());
if (req_count == 0)
@@ -1936,7 +1976,7 @@ MDL_context::upgrade_shared_lock_to_exclusive(MDL_ticket *mdl_ticket,
ulong lock_wait_timeout)
{
MDL_request mdl_xlock_request;
- MDL_ticket *mdl_svp= mdl_savepoint();
+ MDL_savepoint mdl_svp= mdl_savepoint();
bool is_new_ticket;
DBUG_ENTER("MDL_ticket::upgrade_shared_lock_to_exclusive");
@@ -1953,7 +1993,8 @@ MDL_context::upgrade_shared_lock_to_exclusive(MDL_ticket *mdl_ticket,
DBUG_ASSERT(mdl_ticket->m_type == MDL_SHARED_NO_WRITE ||
mdl_ticket->m_type == MDL_SHARED_NO_READ_WRITE);
- mdl_xlock_request.init(&mdl_ticket->m_lock->key, MDL_EXCLUSIVE);
+ mdl_xlock_request.init(&mdl_ticket->m_lock->key, MDL_EXCLUSIVE,
+ MDL_TRANSACTION);
if (acquire_lock(&mdl_xlock_request, lock_wait_timeout))
DBUG_RETURN(TRUE);
@@ -1977,7 +2018,7 @@ MDL_context::upgrade_shared_lock_to_exclusive(MDL_ticket *mdl_ticket,
if (is_new_ticket)
{
- m_tickets.remove(mdl_xlock_request.ticket);
+ m_tickets[MDL_TRANSACTION].remove(mdl_xlock_request.ticket);
MDL_ticket::destroy(mdl_xlock_request.ticket);
}
@@ -2064,13 +2105,8 @@ bool MDL_lock::visit_subgraph(MDL_ticket *waiting_ticket,
are visiting it but this is OK: in the worst case we might do some
extra work and one more context might be chosen as a victim.
*/
- ++gvisitor->m_current_search_depth;
-
if (gvisitor->enter_node(src_ctx))
- {
- --gvisitor->m_current_search_depth;
goto end;
- }
/*
We do a breadth-first search first -- that is, inspect all
@@ -2127,7 +2163,6 @@ bool MDL_lock::visit_subgraph(MDL_ticket *waiting_ticket,
end_leave_node:
gvisitor->leave_node(src_ctx);
- --gvisitor->m_current_search_depth;
end:
mysql_prlock_unlock(&m_rwlock);
@@ -2244,10 +2279,12 @@ void MDL_context::find_deadlock()
/**
Release lock.
- @param ticket Ticket for lock to be released.
+ @param duration Lock duration.
+ @param ticket Ticket for lock to be released.
+
*/
-void MDL_context::release_lock(MDL_ticket *ticket)
+void MDL_context::release_lock(enum_mdl_duration duration, MDL_ticket *ticket)
{
MDL_lock *lock= ticket->m_lock;
DBUG_ENTER("MDL_context::release_lock");
@@ -2257,12 +2294,9 @@ void MDL_context::release_lock(MDL_ticket *ticket)
DBUG_ASSERT(this == ticket->get_ctx());
mysql_mutex_assert_not_owner(&LOCK_open);
- if (ticket == m_trans_sentinel)
- m_trans_sentinel= ++Ticket_list::Iterator(m_tickets, ticket);
-
lock->remove_ticket(&MDL_lock::m_granted, ticket);
- m_tickets.remove(ticket);
+ m_tickets[duration].remove(ticket);
MDL_ticket::destroy(ticket);
DBUG_VOID_RETURN;
@@ -2270,50 +2304,56 @@ void MDL_context::release_lock(MDL_ticket *ticket)
/**
+ Release lock with explicit duration.
+
+ @param ticket Ticket for lock to be released.
+
+*/
+
+void MDL_context::release_lock(MDL_ticket *ticket)
+{
+ DBUG_ASSERT(ticket->m_duration == MDL_EXPLICIT);
+
+ release_lock(MDL_EXPLICIT, ticket);
+}
+
+
+/**
Release all locks associated with the context. If the sentinel
is not NULL, do not release locks stored in the list after and
including the sentinel.
- Transactional locks are added to the beginning of the list, i.e.
- stored in reverse temporal order. This allows to employ this
- function to:
+ Statement and transactional locks are added to the beginning of
+ the corresponding lists, i.e. stored in reverse temporal order.
+ This allows to employ this function to:
- back off in case of a lock conflict.
- - release all locks in the end of a transaction
+ - release all locks in the end of a statment or transaction
- rollback to a savepoint.
-
- The sentinel semantics is used to support LOCK TABLES
- mode and HANDLER statements: locks taken by these statements
- survive COMMIT, ROLLBACK, ROLLBACK TO SAVEPOINT.
*/
-void MDL_context::release_locks_stored_before(MDL_ticket *sentinel)
+void MDL_context::release_locks_stored_before(enum_mdl_duration duration,
+ MDL_ticket *sentinel)
{
MDL_ticket *ticket;
- Ticket_iterator it(m_tickets);
+ Ticket_iterator it(m_tickets[duration]);
DBUG_ENTER("MDL_context::release_locks_stored_before");
- if (m_tickets.is_empty())
+ if (m_tickets[duration].is_empty())
DBUG_VOID_RETURN;
while ((ticket= it++) && ticket != sentinel)
{
DBUG_PRINT("info", ("found lock to release ticket=%p", ticket));
- release_lock(ticket);
+ release_lock(duration, ticket);
}
- /*
- If all locks were released, then the sentinel was not present
- in the list. It must never happen because the sentinel was
- bogus, i.e. pointed to a ticket that no longer exists.
- */
- DBUG_ASSERT(! m_tickets.is_empty() || sentinel == NULL);
DBUG_VOID_RETURN;
}
/**
- Release all locks in the context which correspond to the same name/
- object as this lock request.
+ Release all explicit locks in the context which correspond to the
+ same name/object as this lock request.
@param ticket One of the locks for the name/object for which all
locks should be released.
@@ -2326,17 +2366,13 @@ void MDL_context::release_all_locks_for_name(MDL_ticket *name)
/* Remove matching lock tickets from the context. */
MDL_ticket *ticket;
- Ticket_iterator it_ticket(m_tickets);
+ Ticket_iterator it_ticket(m_tickets[MDL_EXPLICIT]);
while ((ticket= it_ticket++))
{
DBUG_ASSERT(ticket->m_lock);
- /*
- We rarely have more than one ticket in this loop,
- let's not bother saving on pthread_cond_broadcast().
- */
if (ticket->m_lock == lock)
- release_lock(ticket);
+ release_lock(MDL_EXPLICIT, ticket);
}
}
@@ -2391,9 +2427,10 @@ MDL_context::is_lock_owner(MDL_key::enum_mdl_namespace mdl_namespace,
enum_mdl_type mdl_type)
{
MDL_request mdl_request;
- bool is_transactional_unused;
- mdl_request.init(mdl_namespace, db, name, mdl_type);
- MDL_ticket *ticket= find_ticket(&mdl_request, &is_transactional_unused);
+ enum_mdl_duration not_unused;
+ /* We don't care about exact duration of lock here. */
+ mdl_request.init(mdl_namespace, db, name, mdl_type, MDL_TRANSACTION);
+ MDL_ticket *ticket= find_ticket(&mdl_request, &not_unused);
DBUG_ASSERT(ticket == NULL || ticket->m_lock);
@@ -2422,18 +2459,15 @@ bool MDL_ticket::has_pending_conflicting_lock() const
@note It's safe to iterate and unlock any locks after taken after this
savepoint because other statements that take other special locks
cause a implicit commit (ie LOCK TABLES).
-
- @param mdl_savepont The last acquired MDL lock when the
- savepoint was set.
*/
-void MDL_context::rollback_to_savepoint(MDL_ticket *mdl_savepoint)
+void MDL_context::rollback_to_savepoint(const MDL_savepoint &mdl_savepoint)
{
DBUG_ENTER("MDL_context::rollback_to_savepoint");
/* If savepoint is NULL, it is from the start of the transaction. */
- release_locks_stored_before(mdl_savepoint ?
- mdl_savepoint : m_trans_sentinel);
+ release_locks_stored_before(MDL_STATEMENT, mdl_savepoint.m_stmt_ticket);
+ release_locks_stored_before(MDL_TRANSACTION, mdl_savepoint.m_trans_ticket);
DBUG_VOID_RETURN;
}
@@ -2451,65 +2485,150 @@ void MDL_context::rollback_to_savepoint(MDL_ticket *mdl_savepoint)
void MDL_context::release_transactional_locks()
{
DBUG_ENTER("MDL_context::release_transactional_locks");
- release_locks_stored_before(m_trans_sentinel);
+ release_locks_stored_before(MDL_STATEMENT, NULL);
+ release_locks_stored_before(MDL_TRANSACTION, NULL);
+ DBUG_VOID_RETURN;
+}
+
+
+void MDL_context::release_statement_locks()
+{
+ DBUG_ENTER("MDL_context::release_transactional_locks");
+ release_locks_stored_before(MDL_STATEMENT, NULL);
DBUG_VOID_RETURN;
}
/**
Does this savepoint have this lock?
-
- @retval TRUE The ticket is older than the savepoint and
- is not LT, HA or GLR ticket. Thus it belongs
- to the savepoint.
- @retval FALSE The ticket is newer than the savepoint
- or is an LT, HA or GLR ticket.
+
+ @retval TRUE The ticket is older than the savepoint or
+ is an LT, HA or GLR ticket. Thus it belongs
+ to the savepoint or has explicit duration.
+ @retval FALSE The ticket is newer than the savepoint.
+ and is not an LT, HA or GLR ticket.
*/
-bool MDL_context::has_lock(MDL_ticket *mdl_savepoint,
+bool MDL_context::has_lock(const MDL_savepoint &mdl_savepoint,
MDL_ticket *mdl_ticket)
{
MDL_ticket *ticket;
/* Start from the beginning, most likely mdl_ticket's been just acquired. */
- MDL_context::Ticket_iterator it(m_tickets);
- bool found_savepoint= FALSE;
+ MDL_context::Ticket_iterator s_it(m_tickets[MDL_STATEMENT]);
+ MDL_context::Ticket_iterator t_it(m_tickets[MDL_TRANSACTION]);
- while ((ticket= it++) && ticket != m_trans_sentinel)
+ while ((ticket= s_it++) && ticket != mdl_savepoint.m_stmt_ticket)
{
- /*
- First met the savepoint. The ticket must be
- somewhere after it.
- */
- if (ticket == mdl_savepoint)
- found_savepoint= TRUE;
- /*
- Met the ticket. If we haven't yet met the savepoint,
- the ticket is newer than the savepoint.
- */
if (ticket == mdl_ticket)
- return found_savepoint;
+ return FALSE;
}
- /* Reached m_trans_sentinel. The ticket must be LT, HA or GRL ticket. */
- return FALSE;
+
+ while ((ticket= t_it++) && ticket != mdl_savepoint.m_trans_ticket)
+ {
+ if (ticket == mdl_ticket)
+ return FALSE;
+ }
+ return TRUE;
+}
+
+
+/**
+ Change lock duration for transactional lock.
+
+ @param ticket Ticket representing lock.
+ @param duration Lock duration to be set.
+
+ @note This method only supports changing duration of
+ transactional lock to some other duration.
+*/
+
+void MDL_context::set_lock_duration(MDL_ticket *mdl_ticket,
+ enum_mdl_duration duration)
+{
+ DBUG_ASSERT(mdl_ticket->m_duration == MDL_TRANSACTION &&
+ duration != MDL_TRANSACTION);
+
+ m_tickets[MDL_TRANSACTION].remove(mdl_ticket);
+ m_tickets[duration].push_front(mdl_ticket);
+#ifndef DBUG_OFF
+ mdl_ticket->m_duration= duration;
+#endif
}
/**
- Rearrange the ticket to reside in the part of the list that's
- beyond m_trans_sentinel. This effectively changes the ticket
- life cycle, from automatic to manual: i.e. the ticket is no
- longer released by MDL_context::release_transactional_locks() or
- MDL_context::rollback_to_savepoint(), it must be released manually.
+ Set explicit duration for all locks in the context.
*/
-void MDL_context::move_ticket_after_trans_sentinel(MDL_ticket *mdl_ticket)
+void MDL_context::set_explicit_duration_for_all_locks()
{
- m_tickets.remove(mdl_ticket);
- if (m_trans_sentinel == NULL)
+ int i;
+ MDL_ticket *ticket;
+
+ /*
+ In the most common case when this function is called list
+ of transactional locks is bigger than list of locks with
+ explicit duration. So we start by swapping these two lists
+ and then move elements from new list of transactional
+ locks and list of statement locks to list of locks with
+ explicit duration.
+ */
+
+ m_tickets[MDL_EXPLICIT].swap(m_tickets[MDL_TRANSACTION]);
+
+ for (i= 0; i < MDL_EXPLICIT; i++)
{
- m_trans_sentinel= mdl_ticket;
- m_tickets.push_back(mdl_ticket);
+ Ticket_iterator it_ticket(m_tickets[i]);
+
+ while ((ticket= it_ticket++))
+ {
+ m_tickets[i].remove(ticket);
+ m_tickets[MDL_EXPLICIT].push_front(ticket);
+ }
}
- else
- m_tickets.insert_after(m_trans_sentinel, mdl_ticket);
+
+#ifndef DBUG_OFF
+ Ticket_iterator exp_it(m_tickets[MDL_EXPLICIT]);
+
+ while ((ticket= exp_it++))
+ ticket->m_duration= MDL_EXPLICIT;
+#endif
+}
+
+
+/**
+ Set transactional duration for all locks in the context.
+*/
+
+void MDL_context::set_transaction_duration_for_all_locks()
+{
+ MDL_ticket *ticket;
+
+ /*
+ In the most common case when this function is called list
+ of explicit locks is bigger than two other lists (in fact,
+ list of statement locks is always empty). So we start by
+ swapping list of explicit and transactional locks and then
+ move contents of new list of explicit locks to list of
+ locks with transactional duration.
+ */
+
+ DBUG_ASSERT(m_tickets[MDL_STATEMENT].is_empty());
+
+ m_tickets[MDL_TRANSACTION].swap(m_tickets[MDL_EXPLICIT]);
+
+ Ticket_iterator it_ticket(m_tickets[MDL_EXPLICIT]);
+
+ while ((ticket= it_ticket++))
+ {
+ m_tickets[MDL_EXPLICIT].remove(ticket);
+ m_tickets[MDL_TRANSACTION].push_front(ticket);
+ }
+
+#ifndef DBUG_OFF
+ Ticket_iterator trans_it(m_tickets[MDL_TRANSACTION]);
+
+ while ((ticket= trans_it++))
+ ticket->m_duration= MDL_TRANSACTION;
+#endif
}
diff --git a/sql/mdl.h b/sql/mdl.h
index b9dad0597da..2fa89ea2f55 100644
--- a/sql/mdl.h
+++ b/sql/mdl.h
@@ -151,6 +151,15 @@ enum enum_mdl_type {
MDL_TYPE_END};
+/** Duration of metadata lock. */
+
+enum enum_mdl_duration { MDL_STATEMENT= 0,
+ MDL_TRANSACTION,
+ MDL_EXPLICIT,
+ /* This should be the last ! */
+ MDL_DURATION_END };
+
+
/** Maximal length of key for metadata locking subsystem. */
#define MAX_MDLKEY_LENGTH (1 + NAME_LEN + 1 + NAME_LEN + 1)
@@ -168,13 +177,16 @@ class MDL_key
{
public:
/**
- Object namespaces
+ Object namespaces.
+ Sic: when adding a new member to this enum make sure to
+ update m_namespace_to_wait_state_name array in mdl.cc!
Different types of objects exist in different namespaces
- TABLE is for tables and views.
- FUNCTION is for stored functions.
- PROCEDURE is for stored procedures.
- TRIGGER is for triggers.
+ - EVENT is for event scheduler events
Note that although there isn't metadata locking on triggers,
it's necessary to have a separate namespace for them since
MDL_key is also used outside of the MDL subsystem.
@@ -185,6 +197,8 @@ public:
FUNCTION,
PROCEDURE,
TRIGGER,
+ EVENT,
+ COMMIT,
/* This should be the last ! */
NAMESPACE_END };
@@ -239,7 +253,7 @@ public:
character set is utf-8, we can safely assume that no
character starts with a zero byte.
*/
- return memcmp(m_ptr, rhs->m_ptr, min(m_length, rhs->m_length)+1);
+ return memcmp(m_ptr, rhs->m_ptr, min(m_length, rhs->m_length));
}
MDL_key(const MDL_key *rhs)
@@ -273,21 +287,6 @@ private:
};
-
-/**
- Hook class which via its methods specifies which members
- of T should be used for participating in MDL lists.
-*/
-
-template <typename T, T* T::*next, T** T::*prev>
-struct I_P_List_adapter
-{
- static inline T **next_ptr(T *el) { return &(el->*next); }
-
- static inline T ***prev_ptr(T *el) { return &(el->*prev); }
-};
-
-
/**
A pending metadata lock request.
@@ -306,6 +305,8 @@ class MDL_request
public:
/** Type of metadata lock. */
enum enum_mdl_type type;
+ /** Duration for requested lock. */
+ enum enum_mdl_duration duration;
/**
Pointers for participating in the list of lock requests for this context.
@@ -328,17 +329,16 @@ public:
void init(MDL_key::enum_mdl_namespace namespace_arg,
const char *db_arg, const char *name_arg,
- enum_mdl_type mdl_type_arg);
- void init(const MDL_key *key_arg, enum_mdl_type mdl_type_arg);
+ enum_mdl_type mdl_type_arg,
+ enum_mdl_duration mdl_duration_arg);
+ void init(const MDL_key *key_arg, enum_mdl_type mdl_type_arg,
+ enum_mdl_duration mdl_duration_arg);
/** Set type of lock request. Can be only applied to pending locks. */
inline void set_type(enum_mdl_type type_arg)
{
DBUG_ASSERT(ticket == NULL);
type= type_arg;
}
- static MDL_request *create(MDL_key::enum_mdl_namespace mdl_namespace,
- const char *db, const char *name,
- enum_mdl_type mdl_type, MEM_ROOT *root);
/*
This is to work around the ugliness of TABLE_LIST
@@ -364,6 +364,7 @@ public:
MDL_request(const MDL_request *rhs)
:type(rhs->type),
+ duration(rhs->duration),
ticket(NULL),
key(&rhs->key)
{}
@@ -386,10 +387,7 @@ public:
virtual bool inspect_edge(MDL_context *dest) = 0;
virtual ~MDL_wait_for_graph_visitor();
- MDL_wait_for_graph_visitor() :m_lock_open_count(0),
- m_current_search_depth(0)
- { }
- virtual void abort_traversal(MDL_context *node) = 0;
+ MDL_wait_for_graph_visitor() :m_lock_open_count(0) {}
public:
/**
XXX, hack: During deadlock search, we may need to
@@ -400,17 +398,6 @@ public:
LOCK_open since it has significant performance impacts.
*/
uint m_lock_open_count;
- /**
- Set to the 0 at start. Increased whenever
- we descend into another MDL context (aka traverse to the next
- wait-for graph node). When MAX_SEARCH_DEPTH is reached, we
- assume that a deadlock is found, even if we have not found a
- loop.
-
- XXX: This member belongs to this class only temporarily until
- bug #56405 is fixed.
- */
- uint m_current_search_depth;
};
/**
@@ -499,17 +486,35 @@ public:
private:
friend class MDL_context;
- MDL_ticket(MDL_context *ctx_arg, enum_mdl_type type_arg)
+ MDL_ticket(MDL_context *ctx_arg, enum_mdl_type type_arg
+#ifndef DBUG_OFF
+ , enum_mdl_duration duration_arg
+#endif
+ )
: m_type(type_arg),
+#ifndef DBUG_OFF
+ m_duration(duration_arg),
+#endif
m_ctx(ctx_arg),
m_lock(NULL)
{}
- static MDL_ticket *create(MDL_context *ctx_arg, enum_mdl_type type_arg);
+ static MDL_ticket *create(MDL_context *ctx_arg, enum_mdl_type type_arg
+#ifndef DBUG_OFF
+ , enum_mdl_duration duration_arg
+#endif
+ );
static void destroy(MDL_ticket *ticket);
private:
/** Type of metadata lock. Externally accessible. */
enum enum_mdl_type m_type;
+#ifndef DBUG_OFF
+ /**
+ Duration of lock represented by this ticket.
+ Context private. Debug-only.
+ */
+ enum_mdl_duration m_duration;
+#endif
/**
Context of the owner of the metadata lock ticket. Externally accessible.
*/
@@ -527,6 +532,39 @@ private:
/**
+ Savepoint for MDL context.
+
+ Doesn't include metadata locks with explicit duration as
+ they are not released during rollback to savepoint.
+*/
+
+class MDL_savepoint
+{
+public:
+ MDL_savepoint() {};
+
+private:
+ MDL_savepoint(MDL_ticket *stmt_ticket, MDL_ticket *trans_ticket)
+ : m_stmt_ticket(stmt_ticket), m_trans_ticket(trans_ticket)
+ {}
+
+ friend class MDL_context;
+
+private:
+ /**
+ Pointer to last lock with statement duration which was taken
+ before creation of savepoint.
+ */
+ MDL_ticket *m_stmt_ticket;
+ /**
+ Pointer to last lock with transaction duration which was taken
+ before creation of savepoint.
+ */
+ MDL_ticket *m_trans_ticket;
+};
+
+
+/**
A reliable way to wait on an MDL lock.
*/
@@ -574,9 +612,7 @@ public:
typedef I_P_List<MDL_ticket,
I_P_List_adapter<MDL_ticket,
&MDL_ticket::next_in_context,
- &MDL_ticket::prev_in_context>,
- I_P_List_null_counter,
- I_P_List_fast_push_back<MDL_ticket> >
+ &MDL_ticket::prev_in_context> >
Ticket_list;
typedef Ticket_list::Iterator Ticket_iterator;
@@ -599,37 +635,28 @@ public:
const char *db, const char *name,
enum_mdl_type mdl_type);
- bool has_lock(MDL_ticket *mdl_savepoint, MDL_ticket *mdl_ticket);
+ bool has_lock(const MDL_savepoint &mdl_savepoint, MDL_ticket *mdl_ticket);
inline bool has_locks() const
{
- return !m_tickets.is_empty();
+ return !(m_tickets[MDL_STATEMENT].is_empty() &&
+ m_tickets[MDL_TRANSACTION].is_empty() &&
+ m_tickets[MDL_EXPLICIT].is_empty());
}
- MDL_ticket *mdl_savepoint()
+ MDL_savepoint mdl_savepoint()
{
- /*
- NULL savepoint represents the start of the transaction.
- Checking for m_trans_sentinel also makes sure we never
- return a pointer to HANDLER ticket as a savepoint.
- */
- return m_tickets.front() == m_trans_sentinel ? NULL : m_tickets.front();
+ return MDL_savepoint(m_tickets[MDL_STATEMENT].front(),
+ m_tickets[MDL_TRANSACTION].front());
}
- void set_trans_sentinel()
- {
- m_trans_sentinel= m_tickets.front();
- }
- MDL_ticket *trans_sentinel() const { return m_trans_sentinel; }
-
- void reset_trans_sentinel(MDL_ticket *sentinel_arg)
- {
- m_trans_sentinel= sentinel_arg;
- }
- void move_ticket_after_trans_sentinel(MDL_ticket *mdl_ticket);
+ void set_explicit_duration_for_all_locks();
+ void set_transaction_duration_for_all_locks();
+ void set_lock_duration(MDL_ticket *mdl_ticket, enum_mdl_duration duration);
+ void release_statement_locks();
void release_transactional_locks();
- void rollback_to_savepoint(MDL_ticket *mdl_savepoint);
+ void rollback_to_savepoint(const MDL_savepoint &mdl_savepoint);
inline THD *get_thd() const { return m_thd; }
@@ -670,46 +697,43 @@ public:
MDL_wait m_wait;
private:
/**
- All MDL tickets acquired by this connection.
-
- The order of tickets in m_tickets list.
- ---------------------------------------
- The entire set of locks acquired by a connection
- can be separated in two subsets: transactional and
- non-transactional locks.
-
- Transactional locks are locks with automatic scope. They
- are accumulated in the course of a transaction, and
- released only on COMMIT, ROLLBACK or ROLLBACK TO SAVEPOINT.
- They must not be (and never are) released manually,
+ Lists of all MDL tickets acquired by this connection.
+
+ Lists of MDL tickets:
+ ---------------------
+ The entire set of locks acquired by a connection can be separated
+ in three subsets according to their: locks released at the end of
+ statement, at the end of transaction and locks are released
+ explicitly.
+
+ Statement and transactional locks are locks with automatic scope.
+ They are accumulated in the course of a transaction, and released
+ either at the end of uppermost statement (for statement locks) or
+ on COMMIT, ROLLBACK or ROLLBACK TO SAVEPOINT (for transactional
+ locks). They must not be (and never are) released manually,
i.e. with release_lock() call.
- Non-transactional locks are taken for locks that span
+ Locks with explicit duration are taken for locks that span
multiple transactions or savepoints.
These are: HANDLER SQL locks (HANDLER SQL is
transaction-agnostic), LOCK TABLES locks (you can COMMIT/etc
under LOCK TABLES, and the locked tables stay locked), and
- SET GLOBAL READ_ONLY=1 global shared lock.
+ locks implementing "global read lock".
- Transactional locks are always prepended to the beginning
- of the list. In other words, they are stored in reverse
- temporal order. Thus, when we rollback to a savepoint,
- we start popping and releasing tickets from the front
- until we reach the last ticket acquired after the
- savepoint.
+ Statement/transactional locks are always prepended to the
+ beginning of the appropriate list. In other words, they are
+ stored in reverse temporal order. Thus, when we rollback to
+ a savepoint, we start popping and releasing tickets from the
+ front until we reach the last ticket acquired after the savepoint.
- Non-transactional locks are always stored after
- transactional ones, and among each other can be
- split into three sets:
+ Locks with explicit duration stored are not stored in any
+ particular order, and among each other can be split into
+ three sets:
[LOCK TABLES locks] [HANDLER locks] [GLOBAL READ LOCK locks]
The following is known about these sets:
- * we can never have both HANDLER and LOCK TABLES locks
- together -- HANDLER statements are prohibited under LOCK
- TABLES, entering LOCK TABLES implicitly closes all open
- HANDLERs.
* GLOBAL READ LOCK locks are always stored after LOCK TABLES
locks and after HANDLER locks. This is because one can't say
SET GLOBAL read_only=1 or FLUSH TABLES WITH READ LOCK
@@ -724,14 +748,9 @@ private:
However, one can open a few HANDLERs after entering the
read only mode.
* LOCK TABLES locks include intention exclusive locks on
- involved schemas.
- */
- Ticket_list m_tickets;
- /**
- Separates transactional and non-transactional locks
- in m_tickets list, @sa m_tickets.
+ involved schemas and global intention exclusive lock.
*/
- MDL_ticket *m_trans_sentinel;
+ Ticket_list m_tickets[MDL_DURATION_END];
THD *m_thd;
/**
TRUE - if for this context we will break protocol and try to
@@ -762,8 +781,9 @@ private:
MDL_wait_for_subgraph *m_waiting_for;
private:
MDL_ticket *find_ticket(MDL_request *mdl_req,
- bool *is_transactional);
- void release_locks_stored_before(MDL_ticket *sentinel);
+ enum_mdl_duration *duration);
+ void release_locks_stored_before(enum_mdl_duration duration, MDL_ticket *sentinel);
+ void release_lock(enum_mdl_duration duration, MDL_ticket *ticket);
bool try_acquire_lock_impl(MDL_request *mdl_request,
MDL_ticket **out_ticket);
diff --git a/sql/message.h b/sql/message.h
index 97d039352b4..102d38091e7 100644
--- a/sql/message.h
+++ b/sql/message.h
@@ -1,5 +1,19 @@
#ifndef MESSAGE_INCLUDED
#define MESSAGE_INCLUDED
+/* Copyright 2008 Sun Microsystems, Inc.
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; version 2 of the License.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/*
To change or add messages mysqld writes to the Windows error log, run
diff --git a/sql/my_decimal.cc b/sql/my_decimal.cc
index 72505054902..318cdfd10c4 100644
--- a/sql/my_decimal.cc
+++ b/sql/my_decimal.cc
@@ -13,6 +13,7 @@
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
+#include <my_global.h>
#include "sql_priv.h"
#include <time.h>
@@ -98,10 +99,11 @@ int my_decimal2string(uint mask, const my_decimal *d,
UNSIGNED. Hence the buffer for a ZEROFILLed value is the length
the user requested, plus one for a possible decimal point, plus
one if the user only wanted decimal places, but we force a leading
- zero on them. Because the type is implicitly UNSIGNED, we do not
- need to reserve a character for the sign. For all other cases,
- fixed_prec will be 0, and my_decimal_string_length() will be called
- instead to calculate the required size of the buffer.
+ zero on them, plus one for the '\0' terminator. Because the type
+ is implicitly UNSIGNED, we do not need to reserve a character for
+ the sign. For all other cases, fixed_prec will be 0, and
+ my_decimal_string_length() will be called instead to calculate the
+ required size of the buffer.
*/
int length= (fixed_prec
? (fixed_prec + ((fixed_prec == fixed_dec) ? 1 : 0) + 1)
@@ -331,7 +333,7 @@ print_decimal_buff(const my_decimal *dec, const uchar* ptr, int length)
const char *dbug_decimal_as_string(char *buff, const my_decimal *val)
{
- int length= DECIMAL_MAX_STR_LENGTH;
+ int length= DECIMAL_MAX_STR_LENGTH + 1; /* minimum size for buff */
if (!val)
return "NULL";
(void)decimal2string((decimal_t*) val, buff, &length, 0,0,0);
diff --git a/sql/my_decimal.h b/sql/my_decimal.h
index 330ded0c272..f566cbe6f26 100644
--- a/sql/my_decimal.h
+++ b/sql/my_decimal.h
@@ -1,4 +1,4 @@
-/* Copyright (C) 2005-2006 MySQL AB
+/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -62,7 +62,7 @@ typedef struct st_mysql_time MYSQL_TIME;
/**
maximum length of string representation (number of maximum decimal
- digits + 1 position for sign + 1 position for decimal point)
+ digits + 1 position for sign + 1 position for decimal point, no terminator)
*/
#define DECIMAL_MAX_STR_LENGTH (DECIMAL_MAX_POSSIBLE_PRECISION + 2)
@@ -102,6 +102,24 @@ class my_decimal :public decimal_t
public:
+ my_decimal(const my_decimal &rhs) : decimal_t(rhs)
+ {
+ for (uint i= 0; i < DECIMAL_BUFF_LENGTH; i++)
+ buffer[i]= rhs.buffer[i];
+ fix_buffer_pointer();
+ }
+
+ my_decimal& operator=(const my_decimal &rhs)
+ {
+ if (this == &rhs)
+ return *this;
+ decimal_t::operator=(rhs);
+ for (uint i= 0; i < DECIMAL_BUFF_LENGTH; i++)
+ buffer[i]= rhs.buffer[i];
+ fix_buffer_pointer();
+ return *this;
+ }
+
void init()
{
len= DECIMAL_BUFF_LENGTH;
@@ -160,7 +178,7 @@ void max_my_decimal(my_decimal *to, int precision, int frac)
{
DBUG_ASSERT((precision <= DECIMAL_MAX_PRECISION)&&
(frac <= DECIMAL_MAX_SCALE));
- max_decimal(precision, frac, (decimal_t*) to);
+ max_decimal(precision, frac, to);
}
inline void max_internal_decimal(my_decimal *to)
@@ -225,6 +243,7 @@ inline uint32 my_decimal_precision_to_length(uint precision, uint8 scale,
inline
int my_decimal_string_length(const my_decimal *d)
{
+ /* length of string representation including terminating '\0' */
return decimal_string_size(d);
}
@@ -248,7 +267,6 @@ inline
void my_decimal2decimal(const my_decimal *from, my_decimal *to)
{
*to= *from;
- to->fix_buffer_pointer();
}
@@ -260,14 +278,19 @@ inline
int binary2my_decimal(uint mask, const uchar *bin, my_decimal *d, int prec,
int scale)
{
- return check_result(mask, bin2decimal(bin, (decimal_t*) d, prec, scale));
+ return check_result(mask, bin2decimal(bin, d, prec, scale));
}
inline
int my_decimal_set_zero(my_decimal *d)
{
- decimal_make_zero(((decimal_t*) d));
+ /*
+ We need the up-cast here, since my_decimal has sign() member functions,
+ which conflicts with decimal_t::size
+ (and decimal_make_zero is a macro, rather than a funcion).
+ */
+ decimal_make_zero(static_cast<decimal_t*>(d));
return 0;
}
@@ -275,7 +298,7 @@ int my_decimal_set_zero(my_decimal *d)
inline
bool my_decimal_is_zero(const my_decimal *decimal_value)
{
- return decimal_is_zero((decimal_t*) decimal_value);
+ return decimal_is_zero(decimal_value);
}
@@ -283,7 +306,7 @@ inline
int my_decimal_round(uint mask, const my_decimal *from, int scale,
bool truncate, my_decimal *to)
{
- return check_result(mask, decimal_round((decimal_t*) from, to, scale,
+ return check_result(mask, decimal_round(from, to, scale,
(truncate ? TRUNCATE : HALF_UP)));
}
@@ -291,14 +314,14 @@ int my_decimal_round(uint mask, const my_decimal *from, int scale,
inline
int my_decimal_floor(uint mask, const my_decimal *from, my_decimal *to)
{
- return check_result(mask, decimal_round((decimal_t*) from, to, 0, FLOOR));
+ return check_result(mask, decimal_round(from, to, 0, FLOOR));
}
inline
int my_decimal_ceiling(uint mask, const my_decimal *from, my_decimal *to)
{
- return check_result(mask, decimal_round((decimal_t*) from, to, 0, CEILING));
+ return check_result(mask, decimal_round(from, to, 0, CEILING));
}
@@ -320,7 +343,7 @@ int my_decimal2int(uint mask, const my_decimal *d, my_bool unsigned_flag,
{
my_decimal rounded;
/* decimal_round can return only E_DEC_TRUNCATED */
- decimal_round((decimal_t*)d, &rounded, 0, HALF_UP);
+ decimal_round(d, &rounded, 0, HALF_UP);
return check_result(mask, (unsigned_flag ?
decimal2ulonglong(&rounded, (ulonglong *)l) :
decimal2longlong(&rounded, l)));
@@ -328,18 +351,17 @@ int my_decimal2int(uint mask, const my_decimal *d, my_bool unsigned_flag,
inline
-int my_decimal2double(uint mask, const my_decimal *d, double *result)
+int my_decimal2double(uint, const my_decimal *d, double *result)
{
/* No need to call check_result as this will always succeed */
- return decimal2double((decimal_t*) d, result);
+ return decimal2double(d, result);
}
inline
int str2my_decimal(uint mask, const char *str, my_decimal *d, char **end)
{
- return check_result_and_overflow(mask, string2decimal(str,(decimal_t*)d,end),
- d);
+ return check_result_and_overflow(mask, string2decimal(str, d, end), d);
}
@@ -362,7 +384,7 @@ my_decimal *date2my_decimal(MYSQL_TIME *ltime, my_decimal *dec);
inline
int double2my_decimal(uint mask, double val, my_decimal *d)
{
- return check_result_and_overflow(mask, double2decimal(val, (decimal_t*)d), d);
+ return check_result_and_overflow(mask, double2decimal(val, d), d);
}
@@ -392,7 +414,7 @@ int my_decimal_add(uint mask, my_decimal *res, const my_decimal *a,
const my_decimal *b)
{
return check_result_and_overflow(mask,
- decimal_add((decimal_t*)a,(decimal_t*)b,res),
+ decimal_add(a, b, res),
res);
}
@@ -402,7 +424,7 @@ int my_decimal_sub(uint mask, my_decimal *res, const my_decimal *a,
const my_decimal *b)
{
return check_result_and_overflow(mask,
- decimal_sub((decimal_t*)a,(decimal_t*)b,res),
+ decimal_sub(a, b, res),
res);
}
@@ -412,7 +434,7 @@ int my_decimal_mul(uint mask, my_decimal *res, const my_decimal *a,
const my_decimal *b)
{
return check_result_and_overflow(mask,
- decimal_mul((decimal_t*)a,(decimal_t*)b,res),
+ decimal_mul(a, b, res),
res);
}
@@ -422,8 +444,7 @@ int my_decimal_div(uint mask, my_decimal *res, const my_decimal *a,
const my_decimal *b, int div_scale_inc)
{
return check_result_and_overflow(mask,
- decimal_div((decimal_t*)a,(decimal_t*)b,res,
- div_scale_inc),
+ decimal_div(a, b, res, div_scale_inc),
res);
}
@@ -433,7 +454,7 @@ int my_decimal_mod(uint mask, my_decimal *res, const my_decimal *a,
const my_decimal *b)
{
return check_result_and_overflow(mask,
- decimal_mod((decimal_t*)a,(decimal_t*)b,res),
+ decimal_mod(a, b, res),
res);
}
@@ -445,14 +466,14 @@ int my_decimal_mod(uint mask, my_decimal *res, const my_decimal *a,
inline
int my_decimal_cmp(const my_decimal *a, const my_decimal *b)
{
- return decimal_cmp((decimal_t*) a, (decimal_t*) b);
+ return decimal_cmp(a, b);
}
inline
int my_decimal_intg(const my_decimal *a)
{
- return decimal_intg((decimal_t*) a);
+ return decimal_intg(a);
}
diff --git a/sql/mysqld.cc b/sql/mysqld.cc
index 5d581920a21..61f6c55bbdf 100644
--- a/sql/mysqld.cc
+++ b/sql/mysqld.cc
@@ -1,5 +1,5 @@
-/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
- 2009-2010 Monty Program Ab
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ Copyright (c) 2009-2011 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
@@ -62,6 +62,7 @@
#include "rpl_filter.h"
#include "client_settings.h"
#include "repl_failsafe.h"
+#include <sql_common.h>
#include <my_stacktrace.h>
#include "mysqld_suffix.h"
#include "mysys_err.h"
@@ -102,13 +103,6 @@
#define mysqld_charset &my_charset_latin1
-/* stack traces are only supported on linux intel */
-#if defined(__linux__) && defined(__i386__) && defined(USE_PSTACK)
-#define HAVE_STACK_TRACE_ON_SEGV
-#include "../pstack/pstack.h"
-char pstack_file_name[80];
-#endif /* __linux__ */
-
/* We have HAVE_valgrind below as this speeds up the shutdown of MySQL */
#if defined(HAVE_DEC_3_2_THREADS) || defined(SIGNALS_DONT_BREAK_READ) || defined(HAVE_valgrind) && defined(__linux__)
@@ -174,12 +168,12 @@ extern int memcntl(caddr_t, size_t, int, caddr_t, int, int);
int initgroups(const char *,unsigned int);
#endif
-#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H)
+#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H) && !defined(HAVE_FEDISABLEEXCEPT)
#include <ieeefp.h>
#ifdef HAVE_FP_EXCEPT // Fix type conflict
typedef fp_except fp_except_t;
#endif
-#endif /* __FreeBSD__ && HAVE_IEEEFP_H */
+#endif /* __FreeBSD__ && HAVE_IEEEFP_H && !HAVE_FEDISABLEEXCEPT */
#ifdef HAVE_SYS_FPU_H
/* for IRIX to use set_fpc_csr() */
#include <sys/fpu.h>
@@ -209,19 +203,24 @@ extern "C" my_bool reopen_fstreams(const char *filename,
inline void setup_fpu()
{
-#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H)
+#if defined(__FreeBSD__) && defined(HAVE_IEEEFP_H) && !defined(HAVE_FEDISABLEEXCEPT)
/* We can't handle floating point exceptions with threads, so disable
this on freebsd
- Don't fall for overflow, underflow,divide-by-zero or loss of precision
+ Don't fall for overflow, underflow,divide-by-zero or loss of precision.
+ fpsetmask() is deprecated in favor of fedisableexcept() in C99.
*/
-#if defined(__i386__)
+#if defined(FP_X_DNML)
fpsetmask(~(FP_X_INV | FP_X_DNML | FP_X_OFL | FP_X_UFL | FP_X_DZ |
FP_X_IMP));
#else
fpsetmask(~(FP_X_INV | FP_X_OFL | FP_X_UFL | FP_X_DZ |
FP_X_IMP));
-#endif /* __i386__ */
-#endif /* __FreeBSD__ && HAVE_IEEEFP_H */
+#endif /* FP_X_DNML */
+#endif /* __FreeBSD__ && HAVE_IEEEFP_H && !HAVE_FEDISABLEEXCEPT */
+
+#ifdef HAVE_FEDISABLEEXCEPT
+ fedisableexcept(FE_ALL_EXCEPT);
+#endif
#ifdef HAVE_FESETROUND
/* Set FPU rounding mode to "round-to-nearest" */
@@ -260,11 +259,7 @@ inline void setup_fpu()
#define MYSQL_KILL_SIGNAL SIGTERM
-#ifdef HAVE_GLIBC2_STYLE_GETHOSTBYNAME_R
-#include <sys/types.h>
-#else
#include <my_pthread.h> // For thr_setconcurency()
-#endif
#ifdef SOLARIS
extern "C" int gethostname(char *name, int namelen);
@@ -280,6 +275,8 @@ extern "C" sig_handler handle_segfault(int sig);
/* Constants */
+#include <welcome_copyright_notice.h> // ORACLE_WELCOME_COPYRIGHT_NOTICE
+
const char *show_comp_option_name[]= {"YES", "NO", "DISABLED"};
static const char *tc_heuristic_recover_names[]=
@@ -296,6 +293,7 @@ const char *first_keyword= "first", *binary_keyword= "BINARY";
const char *my_localhost= "localhost", *delayed_user= "DELAYED";
bool opt_large_files= sizeof(my_off_t) > 4;
+static my_bool opt_autocommit; ///< for --autocommit command-line option
/*
Used with --help for detailed option
@@ -336,8 +334,10 @@ static PSI_rwlock_key key_rwlock_openssl;
/* the default log output is log tables */
static bool lower_case_table_names_used= 0;
+static bool max_long_data_size_used= false;
static bool volatile select_thread_in_use, signal_thread_in_use;
-static bool volatile ready_to_exit;
+/* See Bug#56666 and Bug#56760 */;
+volatile bool ready_to_exit;
static my_bool opt_debugging= 0, opt_external_locking= 0, opt_console= 0;
static my_bool opt_short_log_format= 0;
static my_bool opt_sync= 0;
@@ -421,7 +421,8 @@ handlerton *heap_hton;
handlerton *myisam_hton;
handlerton *partition_hton;
-my_bool opt_readonly= 0, use_temp_pool, relay_log_purge;
+my_bool read_only= 0, opt_readonly= 0;
+my_bool use_temp_pool, relay_log_purge;
my_bool relay_log_recovery;
my_bool opt_sync_frm, opt_allow_suspicious_udfs;
my_bool opt_secure_auth= 0;
@@ -434,7 +435,7 @@ my_bool opt_super_large_pages= 0;
my_bool opt_myisam_use_mmap= 0;
uint opt_large_page_size= 0;
#if defined(ENABLED_DEBUG_SYNC)
-uint opt_debug_sync_timeout= 0;
+MYSQL_PLUGIN_IMPORT uint opt_debug_sync_timeout= 0;
#endif /* defined(ENABLED_DEBUG_SYNC) */
my_bool opt_old_style_user_limits= 0, trust_function_creators= 0;
/*
@@ -473,6 +474,8 @@ ulonglong slave_type_conversions_options;
ulong thread_cache_size=0;
ulong binlog_cache_size=0;
ulonglong max_binlog_cache_size=0;
+ulong binlog_stmt_cache_size=0;
+ulonglong max_binlog_stmt_cache_size=0;
ulong query_cache_size=0;
ulong refresh_version; /* Increments on each reload */
query_id_t global_query_id;
@@ -484,9 +487,17 @@ ulong delayed_insert_threads, delayed_insert_writes, delayed_rows_in_use;
ulong delayed_insert_errors,flush_time;
ulong specialflag=0;
ulong binlog_cache_use= 0, binlog_cache_disk_use= 0;
+ulong binlog_stmt_cache_use= 0, binlog_stmt_cache_disk_use= 0;
ulong max_connections, max_connect_errors;
ulong extra_max_connections;
ulonglong denied_connections;
+
+/*
+ Maximum length of parameter value which can be set through
+ mysql_send_long_data() call.
+*/
+ulong max_long_data_size;
+
/**
Limit of the total number of prepared statements in the server.
Is necessary to protect the server against out-of-memory attacks.
@@ -619,8 +630,7 @@ pthread_key(MEM_ROOT**,THR_MALLOC);
pthread_key(THD*, THR_THD);
mysql_mutex_t LOCK_thread_count;
mysql_mutex_t
- LOCK_status, LOCK_global_read_lock,
- LOCK_error_log, LOCK_uuid_generator,
+ LOCK_status, LOCK_error_log, LOCK_uuid_generator,
LOCK_delayed_insert, LOCK_delayed_status, LOCK_delayed_create,
LOCK_crypt,
LOCK_global_system_variables,
@@ -644,7 +654,6 @@ mysql_mutex_t LOCK_des_key_file;
mysql_rwlock_t LOCK_grant, LOCK_sys_init_connect, LOCK_sys_init_slave;
mysql_rwlock_t LOCK_system_variables_hash;
mysql_cond_t COND_thread_count;
-mysql_cond_t COND_global_read_lock;
pthread_t signal_thread;
pthread_attr_t connection_attrib;
mysql_mutex_t LOCK_server_started;
@@ -665,9 +674,6 @@ char *opt_logname, *opt_slow_logname;
/* Static variables */
static bool kill_in_progress, segfaulted;
-#ifdef HAVE_STACK_TRACE_ON_SEGV
-static my_bool opt_do_pstack;
-#endif /* HAVE_STACK_TRACE_ON_SEGV */
static my_bool opt_bootstrap, opt_myisam_log;
static int cleanup_done;
static ulong opt_specialflag;
@@ -1161,7 +1167,7 @@ static void close_connections(void)
tmp->thread_id,
(tmp->main_security_ctx.user ?
tmp->main_security_ctx.user : ""));
- close_connection(tmp,0,0);
+ close_connection(tmp);
}
#endif
DBUG_PRINT("quit",("Unlocking LOCK_thread_count"));
@@ -1311,10 +1317,10 @@ static void __cdecl kill_server(int sig_ptr)
else
sql_print_error(ER_DEFAULT(ER_GOT_SIGNAL),my_progname,sig); /* purecov: inspected */
-#if defined(HAVE_SMEM) && defined(__WIN__)
+#ifdef HAVE_SMEM
/*
- Send event to smem_event_connect_request for aborting
- */
+ Send event to smem_event_connect_request for aborting
+ */
if (opt_enable_shared_memory)
{
if (!SetEvent(smem_event_connect_request))
@@ -1602,7 +1608,6 @@ static void clean_up_mutexes()
mysql_mutex_destroy(&LOCK_global_user_client_stats);
mysql_mutex_destroy(&LOCK_global_table_stats);
mysql_mutex_destroy(&LOCK_global_index_stats);
- Events::destroy_mutexes();
#ifdef HAVE_OPENSSL
mysql_mutex_destroy(&LOCK_des_key_file);
#ifndef HAVE_YASSL
@@ -1620,12 +1625,10 @@ static void clean_up_mutexes()
mysql_rwlock_destroy(&LOCK_sys_init_slave);
mysql_mutex_destroy(&LOCK_global_system_variables);
mysql_rwlock_destroy(&LOCK_system_variables_hash);
- mysql_mutex_destroy(&LOCK_global_read_lock);
mysql_mutex_destroy(&LOCK_uuid_generator);
mysql_mutex_destroy(&LOCK_prepared_stmt_count);
mysql_mutex_destroy(&LOCK_error_messages);
mysql_cond_destroy(&COND_thread_count);
- mysql_cond_destroy(&COND_global_read_lock);
mysql_cond_destroy(&COND_thread_cache);
mysql_cond_destroy(&COND_flush_thread_cache);
mysql_cond_destroy(&COND_manager);
@@ -2063,38 +2066,28 @@ static void network_init(void)
/**
Close a connection.
- @param thd Thread handle
- @param errcode Error code to print to console
- @param lock 1 if we have have to lock LOCK_thread_count
+ @param thd Thread handle.
+ @param sql_errno The error code to send before disconnect.
@note
For the connection that is doing shutdown, this is called twice
*/
-void close_connection(THD *thd, uint errcode, bool lock)
+void close_connection(THD *thd, uint sql_errno)
{
- st_vio *vio;
DBUG_ENTER("close_connection");
- DBUG_PRINT("enter",("fd: %s error: '%s'",
- thd->net.vio ? vio_description(thd->net.vio) :
- "(not connected)",
- errcode ? ER_DEFAULT(errcode) : ""));
- if (lock)
- mysql_mutex_lock(&LOCK_thread_count);
- thd->killed= THD::KILL_CONNECTION;
- if ((vio= thd->net.vio) != 0)
- {
- if (errcode)
- net_send_error(thd, errcode,
- ER_DEFAULT(errcode), NULL); /* purecov: inspected */
- vio_close(vio); /* vio is freed in delete thd */
- }
- if (lock)
- mysql_mutex_unlock(&LOCK_thread_count);
- MYSQL_CONNECTION_DONE((int) errcode, thd->thread_id);
+
+ if (sql_errno)
+ net_send_error(thd, sql_errno, ER_DEFAULT(sql_errno), NULL);
+
+ thd->disconnect();
+
+ MYSQL_CONNECTION_DONE((int) sql_errno, thd->thread_id);
+
if (MYSQL_CONNECTION_DONE_ENABLED())
{
sleep(0); /* Workaround to avoid tailcall optimisation */
}
+ MYSQL_AUDIT_NOTIFY_CONNECTION_DISCONNECT(thd, sql_errno);
DBUG_VOID_RETURN;
}
#endif /* EMBEDDED_LIBRARY */
@@ -2113,6 +2106,49 @@ extern "C" sig_handler end_mysqld_signal(int sig __attribute__((unused)))
/*
+ Cleanup THD object
+
+ SYNOPSIS
+ thd_cleanup()
+ thd Thread handler
+*/
+
+void thd_cleanup(THD *thd)
+{
+ thd->cleanup();
+}
+
+/*
+ Decrease number of connections
+
+ SYNOPSIS
+ dec_connection_count()
+*/
+
+void dec_connection_count()
+{
+ mysql_mutex_lock(&LOCK_connection_count);
+ (*thd->scheduler->connection_count)--;
+ mysql_mutex_unlock(&LOCK_connection_count);
+}
+
+
+/*
+ Delete the THD object and decrease number of threads
+
+ SYNOPSIS
+ delete_thd()
+ thd Thread handler
+*/
+
+void delete_thd(THD *thd)
+{
+ thread_count--;
+ delete thd;
+}
+
+
+/*
Unlink thd from global list of available connections and free thd
SYNOPSIS
@@ -2127,15 +2163,17 @@ void unlink_thd(THD *thd)
{
DBUG_ENTER("unlink_thd");
DBUG_PRINT("enter", ("thd: 0x%lx", (long) thd));
- thd->cleanup();
-
- mysql_mutex_lock(&LOCK_connection_count);
- (*thd->scheduler->connection_count)--;
- mysql_mutex_unlock(&LOCK_connection_count);
+ thd_cleanup(thd);
+ dec_connection_count();
mysql_mutex_lock(&LOCK_thread_count);
- thread_count--;
- delete thd;
+ /*
+ Used by binlog_reset_master. It would be cleaner to use
+ DEBUG_SYNC here, but that's not possible because the THD's debug
+ sync feature has been shut down at this point.
+ */
+ DBUG_EXECUTE_IF("sleep_after_lock_thread_count_before_delete_thd", sleep(5););
+ delete_thd(thd);
DBUG_VOID_RETURN;
}
@@ -2535,7 +2573,7 @@ the thread stack. Please read http://dev.mysql.com/doc/mysql/en/linux.html\n\n",
if (!(test_flags & TEST_NO_STACKTRACE))
{
- fprintf(stderr, "thd: 0x%lx\n",(long) thd);
+ fprintf(stderr, "Thread pointer: 0x%lx\n", (long) thd);
fprintf(stderr, "Attempting backtrace. You can use the following "
"information to find out\nwhere mysqld died. If "
"you see no messages after this, something went\n"
@@ -2563,11 +2601,13 @@ the thread stack. Please read http://dev.mysql.com/doc/mysql/en/linux.html\n\n",
kreason= "KILLED_NO_VALUE";
break;
}
- fprintf(stderr, "Trying to get some variables.\n\
-Some pointers may be invalid and cause the dump to abort...\n");
- my_safe_print_str("thd->query", thd->query(), 1024);
- fprintf(stderr, "thd->thread_id=%lu\n", (ulong) thd->thread_id);
- fprintf(stderr, "thd->killed=%s\n", kreason);
+ fprintf(stderr, "\nTrying to get some variables.\n"
+ "Some pointers may be invalid and cause the dump to abort.\n");
+ fprintf(stderr, "Query (%p): ", thd->query());
+ my_safe_print_str(thd->query(), min(1024, thd->query_length()));
+ fprintf(stderr, "Connection ID (thread ID): %lu\n", (ulong) thd->thread_id);
+ fprintf(stderr, "Status: %s\n", kreason);
+ fputc('\n', stderr);
}
fprintf(stderr, "\
The manual page at http://dev.mysql.com/doc/mysql/en/crashing.html contains\n\
@@ -2789,14 +2829,6 @@ pthread_handler_t signal_hand(void *arg __attribute__((unused)))
if (!opt_bootstrap)
create_pid_file();
-#ifdef HAVE_STACK_TRACE_ON_SEGV
- if (opt_do_pstack)
- {
- sprintf(pstack_file_name,"mysqld-%lu-%%d-%%d.backtrace", (ulong)getpid());
- pstack_install_segv_action(pstack_file_name);
- }
-#endif /* HAVE_STACK_TRACE_ON_SEGV */
-
/*
signal to start_signal_handler that we are ready
This works by waiting for start_signal_handler to free mutex,
@@ -2861,7 +2893,7 @@ pthread_handler_t signal_hand(void *arg __attribute__((unused)))
case SIGHUP:
if (!abort_loop)
{
- bool not_used;
+ int not_used;
mysql_print_status(); // Print some debug info
reload_acl_and_cache((THD*) 0,
(REFRESH_LOG | REFRESH_TABLES | REFRESH_FAST |
@@ -3005,6 +3037,19 @@ sizeof(load_default_groups)/sizeof(load_default_groups[0]);
#endif
+#ifndef EMBEDDED_LIBRARY
+static
+int
+check_enough_stack_size()
+{
+ uchar stack_top;
+
+ return check_stack_overrun(current_thd, STACK_MIN_SIZE,
+ &stack_top);
+}
+#endif
+
+
/**
Initialize one of the global date/time format variables.
@@ -3143,7 +3188,6 @@ SHOW_VAR com_status_vars[]= {
{"show_keys", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_KEYS]), SHOW_LONG_STATUS},
{"show_index_statistics", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_INDEX_STATS]), SHOW_LONG_STATUS},
{"show_master_status", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_MASTER_STAT]), SHOW_LONG_STATUS},
- {"show_new_master", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_NEW_MASTER]), SHOW_LONG_STATUS},
{"show_open_tables", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_OPEN_TABLES]), SHOW_LONG_STATUS},
{"show_plugins", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PLUGINS]), SHOW_LONG_STATUS},
{"show_privileges", (char*) offsetof(STATUS_VAR, com_stat[(uint) SQLCOM_SHOW_PRIVILEGES]), SHOW_LONG_STATUS},
@@ -3210,12 +3254,6 @@ static int init_common_variables()
max_system_variables.pseudo_thread_id= (ulong)~0;
server_start_time= flush_status_time= my_time(0);
- /* TODO: remove this when my_time_t is 64 bit compatible */
- if (server_start_time >= (time_t) MY_TIME_T_MAX)
- {
- sql_print_error("This MySQL server doesn't support dates later then 2038");
- return 1;
- }
rpl_filter= new Rpl_filter;
binlog_filter= new Rpl_filter;
@@ -3246,6 +3284,18 @@ static int init_common_variables()
*/
global_system_variables.time_zone= my_tz_SYSTEM;
+#ifdef HAVE_PSI_INTERFACE
+ /*
+ Complete the mysql_bin_log initialization.
+ Instrumentation keys are known only after the performance schema initialization,
+ and can not be set in the MYSQL_BIN_LOG constructor (called before main()).
+ */
+ mysql_bin_log.set_psi_keys(key_BINLOG_LOCK_index,
+ key_BINLOG_update_cond,
+ key_file_binlog,
+ key_file_binlog_index);
+#endif
+
/*
Init mutexes for the global MYSQL_BIN_LOG objects.
As safe_mutex depends on what MY_INIT() does, we can't init the mutexes of
@@ -3254,6 +3304,13 @@ static int init_common_variables()
*/
mysql_bin_log.init_pthread_objects();
+ /* TODO: remove this when my_time_t is 64 bit compatible */
+ if (!IS_TIME_T_VALID_FOR_TIMESTAMP(server_start_time))
+ {
+ sql_print_error("This MySQL server doesn't support dates later then 2038");
+ return 1;
+ }
+
if (gethostname(glob_hostname,sizeof(glob_hostname)) < 0)
{
strmake(glob_hostname, STRING_WITH_LEN("localhost"));
@@ -3325,6 +3382,11 @@ static int init_common_variables()
return 1;
set_server_version();
+#ifndef EMBEDDED_LIBRARY
+ if (opt_help && !opt_verbose)
+ unireg_abort(0);
+#endif /*!EMBEDDED_LIBRARY*/
+
DBUG_PRINT("info",("%s Ver %s for %s on %s\n",my_progname,
server_version, SYSTEM_TYPE,MACHINE_TYPE));
@@ -3362,20 +3424,19 @@ static int init_common_variables()
desired page sizes.
*/
int nelem;
- int max_desired_page_size;
- int max_page_size;
+ size_t max_desired_page_size;
if (opt_super_large_pages)
- max_page_size= SUPER_LARGE_PAGESIZE;
+ max_desired_page_size= SUPER_LARGE_PAGESIZE;
else
- max_page_size= LARGE_PAGESIZE;
+ max_desired_page_size= LARGE_PAGESIZE;
nelem = getpagesizes(NULL, 0);
if (nelem > 0)
{
size_t *pagesize = (size_t *) malloc(sizeof(size_t) * nelem);
if (pagesize != NULL && getpagesizes(pagesize, nelem) > 0)
{
- size_t i, max_page_size= 0;
- for (i= 0; i < nelem; i++)
+ size_t max_page_size= 0;
+ for (int i= 0; i < nelem; i++)
{
if (pagesize[i] > max_page_size &&
pagesize[i] <= max_desired_page_size)
@@ -3462,12 +3523,16 @@ static int init_common_variables()
if (init_errmessage()) /* Read error messages from file */
return 1;
init_client_errs();
- mysql_library_init(never,never,never); /* for replication */
+ mysql_library_init(unused,unused,unused); /* for replication */
lex_init();
if (item_create_init())
return 1;
item_init();
- my_regex_init(&my_charset_latin1);
+#ifndef EMBEDDED_LIBRARY
+ my_regex_init(&my_charset_latin1, check_enough_stack_size);
+#else
+ my_regex_init(&my_charset_latin1, NULL);
+#endif
/*
Process a comma-separated character set list and choose
the first available character set. This is mostly for
@@ -3644,8 +3709,6 @@ static int init_thread_environment()
&LOCK_global_system_variables, MY_MUTEX_INIT_FAST);
mysql_rwlock_init(key_rwlock_LOCK_system_variables_hash,
&LOCK_system_variables_hash);
- mysql_mutex_init(key_LOCK_global_read_lock,
- &LOCK_global_read_lock, MY_MUTEX_INIT_FAST);
mysql_mutex_init(key_LOCK_prepared_stmt_count,
&LOCK_prepared_stmt_count, MY_MUTEX_INIT_FAST);
mysql_mutex_init(key_LOCK_error_messages,
@@ -3681,7 +3744,6 @@ static int init_thread_environment()
mysql_rwlock_init(key_rwlock_LOCK_sys_init_slave, &LOCK_sys_init_slave);
mysql_rwlock_init(key_rwlock_LOCK_grant, &LOCK_grant);
mysql_cond_init(key_COND_thread_count, &COND_thread_count, NULL);
- mysql_cond_init(key_COND_global_read_lock, &COND_global_read_lock, NULL);
mysql_cond_init(key_COND_thread_cache, &COND_thread_cache, NULL);
mysql_cond_init(key_COND_flush_thread_cache, &COND_flush_thread_cache, NULL);
mysql_cond_init(key_COND_manager, &COND_manager, NULL);
@@ -3910,12 +3972,12 @@ static int init_server_components()
unireg_abort(1);
}
- /* initialize delegates for extension observers */
+ /*
+ initialize delegates for extension observers, errors have already
+ been reported in the function
+ */
if (delegates_init())
- {
- sql_print_error("Initialize extension delegates failed");
unireg_abort(1);
- }
/* need to configure logging before initializing storage engines */
if (opt_log_slave_updates && !opt_bin_log)
@@ -4349,16 +4411,21 @@ int mysqld_main(int argc, char **argv)
to be able to read defaults files and parse options.
*/
my_progname= argv[0];
- if (my_basic_init())
+#ifndef _WIN32
+ // For windows, my_init() is called from the win specific mysqld_main
+ if (my_init()) // init my_sys library & pthreads
{
- fprintf(stderr, "my_basic_init() failed.");
+ fprintf(stderr, "my_init() failed.");
return 1;
}
+#endif
orig_argc= argc;
orig_argv= argv;
+ my_getopt_use_args_separator= TRUE;
if (load_defaults(MYSQL_CONFIG_NAME, load_default_groups, &argc, &argv))
return 1;
+ my_getopt_use_args_separator= FALSE;
defaults_argc= argc;
defaults_argv= argv;
remaining_argc= argc;
@@ -4450,11 +4517,10 @@ int mysqld_main(int argc, char **argv)
recreate objects which were initialised early,
so that they are instrumented as well.
*/
- my_thread_basic_global_reinit();
+ my_thread_global_reinit();
}
#endif /* HAVE_PSI_INTERFACE */
- my_init(); // init my_sys library & pthreads
init_error_log_mutex();
/* Initialize audit interface globals. Audit plugins are inited later. */
@@ -4770,10 +4836,15 @@ int mysqld_main(int argc, char **argv)
#if defined(__WIN__) && !defined(EMBEDDED_LIBRARY)
int mysql_service(void *p)
{
+ if (my_thread_init())
+ return 1;
+
if (use_opt_args)
win_main(opt_argc, opt_argv);
else
win_main(Service.my_argc, Service.my_argv);
+
+ my_thread_end();
return 0;
}
@@ -4873,6 +4944,12 @@ int mysqld_main(int argc, char **argv)
/* Must be initialized early for comparison of service name */
system_charset_info= &my_charset_utf8_general_ci;
+ if (my_init())
+ {
+ fprintf(stderr, "my_init() failed.");
+ return 1;
+ }
+
if (Service.GetOS()) /* true NT family */
{
char file_path[FN_REFLEN];
@@ -5022,6 +5099,14 @@ static bool read_init_file(char *file_name)
}
+/**
+ Increment number of created threads
+*/
+void inc_thread_created(void)
+{
+ thread_created++;
+}
+
#ifndef EMBEDDED_LIBRARY
/*
@@ -5087,10 +5172,10 @@ void create_thread_to_handle_connection(THD *thd)
statistic_increment(aborted_connects,&LOCK_status);
/* Can't use my_error() since store_globals has not been called. */
my_snprintf(error_message_buff, sizeof(error_message_buff),
- ER(ER_CANT_CREATE_THREAD), error);
+ ER_THD(thd, ER_CANT_CREATE_THREAD), error);
net_send_error(thd, ER_CANT_CREATE_THREAD, error_message_buff, NULL);
+ close_connection(thd);
mysql_mutex_lock(&LOCK_thread_count);
- close_connection(thd,0,0);
delete thd;
mysql_mutex_unlock(&LOCK_thread_count);
return;
@@ -5132,7 +5217,7 @@ static void create_new_thread(THD *thd)
mysql_mutex_unlock(&LOCK_connection_count);
DBUG_PRINT("error",("Too many connections"));
- close_connection(thd, ER_CON_COUNT_ERROR, 1);
+ close_connection(thd, ER_CON_COUNT_ERROR);
statistic_increment(denied_connections, &LOCK_status);
delete thd;
DBUG_VOID_RETURN;
@@ -5513,7 +5598,7 @@ pthread_handler_t handle_connections_namedpipes(void *arg)
if (!(thd->net.vio= vio_new_win32pipe(hConnectedPipe)) ||
my_net_init(&thd->net, thd->net.vio))
{
- close_connection(thd, ER_OUT_OF_RESOURCES, 1);
+ close_connection(thd, ER_OUT_OF_RESOURCES);
delete thd;
continue;
}
@@ -5708,7 +5793,7 @@ pthread_handler_t handle_connections_shared_memory(void *arg)
event_conn_closed)) ||
my_net_init(&thd->net, thd->net.vio))
{
- close_connection(thd, ER_OUT_OF_RESOURCES, 1);
+ close_connection(thd, ER_OUT_OF_RESOURCES);
errmsg= 0;
goto errorconn;
}
@@ -5801,6 +5886,13 @@ struct my_option my_long_options[]=
{"ansi", 'a', "Use ANSI SQL syntax instead of MySQL syntax. This mode "
"will also set transaction isolation level 'serializable'.", 0, 0, 0,
GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
+ /*
+ Because Sys_var_bit does not support command-line options, we need to
+ explicitely add one for --autocommit
+ */
+ {"autocommit", 0, "Set default value for autocommit (0 or 1)",
+ &opt_autocommit, &opt_autocommit, 0,
+ GET_BOOL, OPT_ARG, 1, 0, 0, 0, 0, NULL},
{"bind-address", OPT_BIND_ADDRESS, "IP address to bind to.",
&my_bind_addr_str, &my_bind_addr_str, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
@@ -5870,11 +5962,6 @@ struct my_option my_long_options[]=
&disconnect_slave_event_count, &disconnect_slave_event_count,
0, GET_INT, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif /* HAVE_REPLICATION */
-#ifdef HAVE_STACK_TRACE_ON_SEGV
- {"enable-pstack", 0, "Print a symbolic stack trace on failure.",
- &opt_do_pstack, &opt_do_pstack, 0, GET_BOOL, NO_ARG, 0, 0,
- 0, 0, 0, 0},
-#endif /* HAVE_STACK_TRACE_ON_SEGV */
{"exit-info", 'T', "Used for debugging. Use at your own risk.", 0, 0, 0,
GET_LONG, OPT_ARG, 0, 0, 0, 0, 0, 0},
@@ -6592,6 +6679,8 @@ SHOW_VAR status_vars[]= {
{"Access_denied_errors", (char*) offsetof(STATUS_VAR, access_denied_errors), SHOW_LONG_STATUS},
{"Binlog_cache_disk_use", (char*) &binlog_cache_disk_use, SHOW_LONG},
{"Binlog_cache_use", (char*) &binlog_cache_use, SHOW_LONG},
+ {"Binlog_stmt_cache_disk_use",(char*) &binlog_stmt_cache_disk_use, SHOW_LONG},
+ {"Binlog_stmt_cache_use", (char*) &binlog_stmt_cache_use, SHOW_LONG},
{"Busy_time", (char*) offsetof(STATUS_VAR, busy_time), SHOW_DOUBLE_STATUS},
{"Bytes_received", (char*) offsetof(STATUS_VAR, bytes_received), SHOW_LONGLONG_STATUS},
{"Bytes_sent", (char*) offsetof(STATUS_VAR, bytes_sent), SHOW_LONGLONG_STATUS},
@@ -6792,13 +6881,8 @@ static void usage(void)
if (!default_collation_name)
default_collation_name= (char*) default_charset_info->name;
print_version();
- puts("\
-Copyright (C) 2000-2008 MySQL AB, by Monty and others.\n\
-Copyright (C) 2008,2009 Sun Microsystems, Inc.\n\
-This software comes with ABSOLUTELY NO WARRANTY. This is free software,\n\
-and you are welcome to modify and redistribute it under the GPL license\n\n\
-Starts the MySQL database server.\n");
-
+ puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000, 2010"));
+ puts("Starts the MySQL database server.\n");
printf("Usage: %s [OPTIONS]\n", my_progname);
if (!opt_verbose)
puts("\nFor more help options (several pages), use mysqld --verbose --help.");
@@ -7325,6 +7409,10 @@ mysqld_get_one_option(int optid,
if (argument == NULL) /* no argument */
log_error_file_ptr= const_cast<char*>("");
break;
+ case OPT_MAX_LONG_DATA_SIZE:
+ max_long_data_size_used= true;
+ WARN_DEPRECATED(NULL, 5, 6, "--max_long_data_size", "'--max_allowed_packet'");
+ break;
}
return 0;
}
@@ -7440,6 +7528,14 @@ static int get_options(int *argc_ptr, char ***argv_ptr)
opt_log_slow_slave_statements) &&
!opt_slow_log)
sql_print_warning("options --log-slow-admin-statements, --log-queries-not-using-indexes and --log-slow-slave-statements have no effect if --log_slow_queries is not set");
+ if (global_system_variables.net_buffer_length >
+ global_system_variables.max_allowed_packet)
+ {
+ sql_print_warning("net_buffer_length (%lu) is set to be larger "
+ "than max_allowed_packet (%lu). Please rectify.",
+ global_system_variables.net_buffer_length,
+ global_system_variables.max_allowed_packet);
+ }
if (log_error_file_ptr != disabled_my_option)
opt_error_log= 1;
@@ -7478,10 +7574,12 @@ static int get_options(int *argc_ptr, char ***argv_ptr)
else
global_system_variables.option_bits&= ~OPTION_BIG_SELECTS;
- if (global_system_variables.option_bits & OPTION_AUTOCOMMIT)
- global_system_variables.option_bits&= ~OPTION_NOT_AUTOCOMMIT;
- else
- global_system_variables.option_bits|= OPTION_NOT_AUTOCOMMIT;
+ // Synchronize @@global.autocommit on --autocommit
+ const ulonglong turn_bit_on= opt_autocommit ?
+ OPTION_AUTOCOMMIT : OPTION_NOT_AUTOCOMMIT;
+ global_system_variables.option_bits=
+ (global_system_variables.option_bits &
+ ~(OPTION_NOT_AUTOCOMMIT | OPTION_AUTOCOMMIT)) | turn_bit_on;
global_system_variables.sql_mode=
expand_sql_mode(global_system_variables.sql_mode);
@@ -7558,6 +7656,15 @@ static int get_options(int *argc_ptr, char ***argv_ptr)
test(global_system_variables.optimizer_switch &
OPTIMIZER_SWITCH_ENGINE_CONDITION_PUSHDOWN);
+ opt_readonly= read_only;
+
+ /*
+ If max_long_data_size is not specified explicitly use
+ value of max_allowed_packet.
+ */
+ if (!max_long_data_size_used)
+ max_long_data_size= global_system_variables.max_allowed_packet;
+
return 0;
}
@@ -7876,8 +7983,8 @@ PSI_mutex_key key_BINLOG_LOCK_index, key_BINLOG_LOCK_prep_xids,
key_delayed_insert_mutex, key_hash_filo_lock, key_LOCK_active_mi,
key_LOCK_connection_count, key_LOCK_crypt, key_LOCK_delayed_create,
key_LOCK_delayed_insert, key_LOCK_delayed_status, key_LOCK_error_log,
- key_LOCK_gdl, key_LOCK_global_read_lock, key_LOCK_global_system_variables,
- key_LOCK_manager,
+ key_LOCK_gdl, key_LOCK_global_system_variables,
+ key_LOCK_manager,
key_LOCK_prepared_stmt_count,
key_LOCK_rpl_status, key_LOCK_server_started, key_LOCK_status,
key_LOCK_system_variables_hash, key_LOCK_table_share, key_LOCK_thd_data,
@@ -7888,6 +7995,7 @@ PSI_mutex_key key_BINLOG_LOCK_index, key_BINLOG_LOCK_prep_xids,
key_structure_guard_mutex, key_TABLE_SHARE_LOCK_ha_data,
key_LOCK_error_messages, key_LOG_INFO_lock, key_LOCK_thread_count,
key_PARTITION_LOCK_auto_inc;
+PSI_mutex_key key_RELAYLOG_LOCK_index;
PSI_mutex_key key_LOCK_stats,
key_LOCK_global_user_client_stats, key_LOCK_global_table_stats,
@@ -7908,6 +8016,7 @@ static PSI_mutex_info all_server_mutexes[]=
{ &key_BINLOG_LOCK_index, "MYSQL_BIN_LOG::LOCK_index", 0},
{ &key_BINLOG_LOCK_prep_xids, "MYSQL_BIN_LOG::LOCK_prep_xids", 0},
+ { &key_RELAYLOG_LOCK_index, "MYSQL_RELAY_LOG::LOCK_index", 0},
{ &key_delayed_insert_mutex, "Delayed_insert::mutex", 0},
{ &key_hash_filo_lock, "hash_filo::lock", 0},
{ &key_LOCK_active_mi, "LOCK_active_mi", PSI_FLAG_GLOBAL},
@@ -7918,7 +8027,6 @@ static PSI_mutex_info all_server_mutexes[]=
{ &key_LOCK_delayed_status, "LOCK_delayed_status", PSI_FLAG_GLOBAL},
{ &key_LOCK_error_log, "LOCK_error_log", PSI_FLAG_GLOBAL},
{ &key_LOCK_gdl, "LOCK_gdl", PSI_FLAG_GLOBAL},
- { &key_LOCK_global_read_lock, "LOCK_global_read_lock", PSI_FLAG_GLOBAL},
{ &key_LOCK_global_system_variables, "LOCK_global_system_variables", PSI_FLAG_GLOBAL},
{ &key_LOCK_manager, "LOCK_manager", PSI_FLAG_GLOBAL},
{ &key_LOCK_prepared_stmt_count, "LOCK_prepared_stmt_count", PSI_FLAG_GLOBAL},
@@ -7971,7 +8079,7 @@ PSI_cond_key key_PAGE_cond, key_COND_active, key_COND_pool;
#endif /* HAVE_MMAP */
PSI_cond_key key_BINLOG_COND_prep_xids, key_BINLOG_update_cond,
- key_COND_cache_status_changed, key_COND_global_read_lock, key_COND_manager,
+ key_COND_cache_status_changed, key_COND_manager,
key_COND_rpl_status, key_COND_server_started,
key_delayed_insert_cond, key_delayed_insert_cond_client,
key_item_func_sleep_cond, key_master_info_data_cond,
@@ -7980,6 +8088,7 @@ PSI_cond_key key_BINLOG_COND_prep_xids, key_BINLOG_update_cond,
key_relay_log_info_start_cond, key_relay_log_info_stop_cond,
key_TABLE_SHARE_cond, key_user_level_lock_cond,
key_COND_thread_count, key_COND_thread_cache, key_COND_flush_thread_cache;
+PSI_cond_key key_RELAYLOG_update_cond;
static PSI_cond_info all_server_conds[]=
{
@@ -7993,8 +8102,8 @@ static PSI_cond_info all_server_conds[]=
#endif /* HAVE_MMAP */
{ &key_BINLOG_COND_prep_xids, "MYSQL_BIN_LOG::COND_prep_xids", 0},
{ &key_BINLOG_update_cond, "MYSQL_BIN_LOG::update_cond", 0},
+ { &key_RELAYLOG_update_cond, "MYSQL_RELAY_LOG::update_cond", 0},
{ &key_COND_cache_status_changed, "Query_cache::COND_cache_status_changed", 0},
- { &key_COND_global_read_lock, "COND_global_read_lock", PSI_FLAG_GLOBAL},
{ &key_COND_manager, "COND_manager", PSI_FLAG_GLOBAL},
{ &key_COND_rpl_status, "COND_rpl_status", PSI_FLAG_GLOBAL},
{ &key_COND_server_started, "COND_server_started", PSI_FLAG_GLOBAL},
@@ -8053,9 +8162,11 @@ PSI_file_key key_file_binlog, key_file_binlog_index, key_file_casetest,
key_file_dbopt, key_file_des_key_file, key_file_ERRMSG, key_select_to_file,
key_file_fileparser, key_file_frm, key_file_global_ddl_log, key_file_load,
key_file_loadfile, key_file_log_event_data, key_file_log_event_info,
- key_file_master_info, key_file_misc, key_file_MYSQL_LOG, key_file_partition,
+ key_file_master_info, key_file_misc, key_file_partition,
key_file_pid, key_file_relay_log_info, key_file_send_file, key_file_tclog,
key_file_trg, key_file_trn, key_file_init;
+PSI_file_key key_file_query_log, key_file_slow_log;
+PSI_file_key key_file_relaylog, key_file_relaylog_index;
static PSI_file_info all_server_files[]=
{
@@ -8064,6 +8175,8 @@ static PSI_file_info all_server_files[]=
#endif /* HAVE_MMAP */
{ &key_file_binlog, "binlog", 0},
{ &key_file_binlog_index, "binlog_index", 0},
+ { &key_file_relaylog, "relaylog", 0},
+ { &key_file_relaylog_index, "relaylog_index", 0},
{ &key_file_casetest, "casetest", 0},
{ &key_file_dbopt, "dbopt", 0},
{ &key_file_des_key_file, "des_key_file", 0},
@@ -8078,11 +8191,12 @@ static PSI_file_info all_server_files[]=
{ &key_file_log_event_info, "log_event_info", 0},
{ &key_file_master_info, "master_info", 0},
{ &key_file_misc, "misc", 0},
- { &key_file_MYSQL_LOG, "MYSQL_LOG", 0},
{ &key_file_partition, "partition", 0},
{ &key_file_pid, "pid", 0},
+ { &key_file_query_log, "query_log", 0},
{ &key_file_relay_log_info, "relay_log_info", 0},
{ &key_file_send_file, "send_file", 0},
+ { &key_file_slow_log, "slow_log", 0},
{ &key_file_tclog, "tclog", 0},
{ &key_file_trg, "trigger_name", 0},
{ &key_file_trn, "trigger", 0},
diff --git a/sql/mysqld.h b/sql/mysqld.h
index a4482b655ee..4ede06f09a6 100644
--- a/sql/mysqld.h
+++ b/sql/mysqld.h
@@ -54,7 +54,7 @@ typedef Bitmap<((MAX_INDEXES+7)/8*8)> key_map; /* Used for finding keys */
some places */
/* Function prototypes */
void kill_mysql(void);
-void close_connection(THD *thd, uint errcode, bool lock);
+void close_connection(THD *thd, uint sql_errno= 0);
void handle_connection_in_main_thread(THD *thd);
void create_thread_to_handle_connection(THD *thd);
void unlink_thd(THD *thd);
@@ -63,7 +63,7 @@ void flush_thread_cache();
void refresh_status(THD *thd);
bool is_secure_file_path(char *path);
-extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *system_charset_info;
+extern "C" MYSQL_PLUGIN_IMPORT CHARSET_INFO *system_charset_info;
extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *files_charset_info ;
extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *national_charset_info;
extern MYSQL_PLUGIN_IMPORT CHARSET_INFO *table_alias_charset;
@@ -90,14 +90,15 @@ extern bool opt_ignore_builtin_innodb;
extern my_bool opt_character_set_client_handshake;
extern bool volatile abort_loop;
extern bool in_bootstrap;
-extern uint volatile thread_count, global_read_lock;
+extern uint volatile thread_count;
extern uint connection_count;
extern my_bool opt_safe_user_create;
extern my_bool opt_safe_show_db, opt_local_infile, opt_myisam_use_mmap;
extern my_bool opt_slave_compressed_protocol, use_temp_pool;
extern ulong slave_exec_mode_options;
extern ulonglong slave_type_conversions_options;
-extern my_bool opt_readonly, lower_case_file_system;
+extern my_bool read_only, opt_readonly;
+extern my_bool lower_case_file_system;
extern my_bool opt_enable_named_pipe, opt_sync_frm, opt_allow_suspicious_udfs;
extern my_bool opt_secure_auth;
extern char* opt_secure_file_priv;
@@ -115,6 +116,7 @@ extern char *default_storage_engine;
extern bool opt_endinfo, using_udf_functions;
extern my_bool locked_in_memory;
extern bool opt_using_transactions;
+extern ulong max_long_data_size;
extern ulong current_pid;
extern ulong expire_logs_days;
extern my_bool relay_log_recovery;
@@ -142,6 +144,7 @@ extern ulonglong keybuff_size;
extern ulonglong thd_startup_options;
extern ulong thread_id;
extern ulong binlog_cache_use, binlog_cache_disk_use;
+extern ulong binlog_stmt_cache_use, binlog_stmt_cache_disk_use;
extern ulong aborted_threads,aborted_connects;
extern ulong delayed_insert_timeout;
extern ulong delayed_insert_limit, delayed_queue_size;
@@ -161,14 +164,16 @@ extern uint slave_net_timeout;
extern uint max_user_connections;
extern ulong what_to_log,flush_time;
extern ulong max_prepared_stmt_count, prepared_stmt_count;
-extern ulong binlog_cache_size, open_files_limit;
-extern ulonglong max_binlog_cache_size;
+extern ulong open_files_limit;
+extern ulong binlog_cache_size, binlog_stmt_cache_size;
+extern ulonglong max_binlog_cache_size, max_binlog_stmt_cache_size;
extern ulong max_binlog_size, max_relay_log_size;
extern ulong opt_binlog_rows_event_max_size;
extern ulong rpl_recovery_rank, thread_cache_size;
extern ulong back_log;
extern char language[FN_REFLEN];
-extern ulong server_id, concurrency;
+extern "C" MYSQL_PLUGIN_IMPORT ulong server_id;
+extern ulong concurrency;
extern time_t server_start_time, flush_status_time;
extern char *opt_mysql_tmpdir, mysql_charsets_dir[];
extern int mysql_unpacked_real_data_home_len;
@@ -189,8 +194,8 @@ extern handlerton *heap_hton;
extern const char *load_default_groups[];
extern struct my_option my_long_options[];
extern int mysqld_server_started;
-extern int orig_argc;
-extern char **orig_argv;
+extern "C" MYSQL_PLUGIN_IMPORT int orig_argc;
+extern "C" MYSQL_PLUGIN_IMPORT char **orig_argv;
extern pthread_attr_t connection_attrib;
extern MYSQL_FILE *bootstrap_file;
extern my_bool old_mode;
@@ -201,6 +206,10 @@ extern char err_shared_dir[];
extern TYPELIB thread_handling_typelib;
extern my_decimal decimal_zero;
+/*
+ THR_MALLOC is a key which will be used to set/get MEM_ROOT** for a thread,
+ using my_pthread_setspecific_ptr()/my_thread_getspecific_ptr().
+*/
extern pthread_key(MEM_ROOT**,THR_MALLOC);
#ifdef HAVE_PSI_INTERFACE
@@ -217,7 +226,7 @@ extern PSI_mutex_key key_BINLOG_LOCK_index, key_BINLOG_LOCK_prep_xids,
key_delayed_insert_mutex, key_hash_filo_lock, key_LOCK_active_mi,
key_LOCK_connection_count, key_LOCK_crypt, key_LOCK_delayed_create,
key_LOCK_delayed_insert, key_LOCK_delayed_status, key_LOCK_error_log,
- key_LOCK_gdl, key_LOCK_global_read_lock, key_LOCK_global_system_variables,
+ key_LOCK_gdl, key_LOCK_global_system_variables,
key_LOCK_logger, key_LOCK_manager,
key_LOCK_prepared_stmt_count,
key_LOCK_rpl_status, key_LOCK_server_started, key_LOCK_status,
@@ -228,6 +237,7 @@ extern PSI_mutex_key key_BINLOG_LOCK_index, key_BINLOG_LOCK_prep_xids,
key_relay_log_info_log_space_lock, key_relay_log_info_run_lock,
key_structure_guard_mutex, key_TABLE_SHARE_LOCK_ha_data,
key_LOCK_error_messages, key_LOCK_thread_count, key_PARTITION_LOCK_auto_inc;
+extern PSI_mutex_key key_RELAYLOG_LOCK_index;
extern PSI_mutex_key key_LOCK_stats,
key_LOCK_global_user_client_stats, key_LOCK_global_table_stats,
@@ -242,7 +252,7 @@ extern PSI_cond_key key_PAGE_cond, key_COND_active, key_COND_pool;
#endif /* HAVE_MMAP */
extern PSI_cond_key key_BINLOG_COND_prep_xids, key_BINLOG_update_cond,
- key_COND_cache_status_changed, key_COND_global_read_lock, key_COND_manager,
+ key_COND_cache_status_changed, key_COND_manager,
key_COND_rpl_status, key_COND_server_started,
key_delayed_insert_cond, key_delayed_insert_cond_client,
key_item_func_sleep_cond, key_master_info_data_cond,
@@ -251,6 +261,7 @@ extern PSI_cond_key key_BINLOG_COND_prep_xids, key_BINLOG_update_cond,
key_relay_log_info_start_cond, key_relay_log_info_stop_cond,
key_TABLE_SHARE_cond, key_user_level_lock_cond,
key_COND_thread_count, key_COND_thread_cache, key_COND_flush_thread_cache;
+extern PSI_cond_key key_RELAYLOG_update_cond;
extern PSI_thread_key key_thread_bootstrap, key_thread_delayed_insert,
key_thread_handle_manager, key_thread_kill_server, key_thread_main,
@@ -264,9 +275,11 @@ extern PSI_file_key key_file_binlog, key_file_binlog_index, key_file_casetest,
key_file_dbopt, key_file_des_key_file, key_file_ERRMSG, key_select_to_file,
key_file_fileparser, key_file_frm, key_file_global_ddl_log, key_file_load,
key_file_loadfile, key_file_log_event_data, key_file_log_event_info,
- key_file_master_info, key_file_misc, key_file_MYSQL_LOG, key_file_partition,
+ key_file_master_info, key_file_misc, key_file_partition,
key_file_pid, key_file_relay_log_info, key_file_send_file, key_file_tclog,
key_file_trg, key_file_trn, key_file_init;
+extern PSI_file_key key_file_query_log, key_file_slow_log;
+extern PSI_file_key key_file_relaylog, key_file_relaylog_index;
void init_server_psi_keys();
#endif /* HAVE_PSI_INTERFACE */
@@ -296,7 +309,7 @@ extern uint mysql_real_data_home_len;
extern const char *mysql_real_data_home_ptr;
extern ulong thread_handling;
extern MYSQL_PLUGIN_IMPORT char *mysql_data_home;
-extern char server_version[SERVER_VERSION_LENGTH];
+extern "C" MYSQL_PLUGIN_IMPORT char server_version[SERVER_VERSION_LENGTH];
extern MYSQL_PLUGIN_IMPORT char mysql_real_data_home[];
extern char mysql_unpacked_real_data_home[];
extern MYSQL_PLUGIN_IMPORT struct system_variables global_system_variables;
@@ -314,7 +327,7 @@ extern mysql_mutex_t
LOCK_user_locks, LOCK_status,
LOCK_error_log, LOCK_delayed_insert, LOCK_uuid_generator,
LOCK_delayed_status, LOCK_delayed_create, LOCK_crypt, LOCK_timezone,
- LOCK_slave_list, LOCK_active_mi, LOCK_manager, LOCK_global_read_lock,
+ LOCK_slave_list, LOCK_active_mi, LOCK_manager,
LOCK_global_system_variables, LOCK_user_conn,
LOCK_prepared_stmt_count, LOCK_error_messages, LOCK_connection_count;
extern MYSQL_PLUGIN_IMPORT mysql_mutex_t LOCK_thread_count;
@@ -327,7 +340,6 @@ extern mysql_rwlock_t LOCK_grant, LOCK_sys_init_connect, LOCK_sys_init_slave;
extern mysql_rwlock_t LOCK_system_variables_hash;
extern mysql_cond_t COND_thread_count;
extern mysql_cond_t COND_manager;
-extern mysql_cond_t COND_global_read_lock;
extern int32 thread_running;
extern my_atomic_rwlock_t thread_running_lock;
@@ -387,21 +399,22 @@ enum options_mysqld
OPT_UPDATE_LOG,
OPT_WANT_CORE,
OPT_ENGINE_CONDITION_PUSHDOWN,
- OPT_LOG_ERROR
+ OPT_LOG_ERROR,
+ OPT_MAX_LONG_DATA_SIZE
};
#endif
/**
- Query type constants.
-
- QT_ORDINARY -- ordinary SQL query.
- QT_IS -- SQL query to be shown in INFORMATION_SCHEMA (in utf8 and without
- character set introducers).
+ Query type constants (usable as bitmap flags).
*/
enum enum_query_type
{
- QT_ORDINARY,
- QT_IS
+ /// Nothing specific, ordinary SQL query.
+ QT_ORDINARY= 0,
+ /// In utf8.
+ QT_TO_SYSTEM_CHARSET= (1 << 0),
+ /// Without character set introducers.
+ QT_WITHOUT_INTRODUCERS= (1 << 1)
};
/* query_id */
@@ -490,6 +503,10 @@ get_thread_running()
extern "C" THD *_current_thd_noinline();
#define _current_thd() _current_thd_noinline()
#else
+/*
+ THR_THD is a key which will be used to set/get THD* for a thread,
+ using my_pthread_setspecific_ptr()/my_thread_getspecific_ptr().
+*/
extern pthread_key(THD*, THR_THD);
inline THD *_current_thd(void)
{
diff --git a/sql/net_serv.cc b/sql/net_serv.cc
index 5f7f0b25fc1..974bc122d14 100644
--- a/sql/net_serv.cc
+++ b/sql/net_serv.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000 MySQL AB
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -157,17 +157,7 @@ my_bool net_realloc(NET *net, size_t length)
DBUG_ENTER("net_realloc");
DBUG_PRINT("enter",("length: %lu", (ulong) length));
- /*
- When compression is off, net->where_b is always 0.
- With compression turned on, net->where_b may indicate
- that we still have a piece of the previous logical
- packet in the buffer, unprocessed. Take it into account
- when checking that max_allowed_packet is not exceeded.
- This ensures that the client treats max_allowed_packet
- limit identically, regardless of compression being on
- or off.
- */
- if (length >= (net->max_packet_size + net->where_b))
+ if (length >= net->max_packet_size)
{
DBUG_PRINT("error", ("Packet too large. Max size: %lu",
net->max_packet_size));
diff --git a/sql/opt_range.cc b/sql/opt_range.cc
index ed39c632735..e0505e2d65c 100644
--- a/sql/opt_range.cc
+++ b/sql/opt_range.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
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
@@ -1429,7 +1429,7 @@ int QUICK_RANGE_SELECT::init_ror_merged_scan(bool reuse_handler)
}
thd= head->in_use;
- if (!(file= head->file->clone(thd->mem_root)))
+ if (!(file= head->file->clone(head->s->normalized_path.str, thd->mem_root)))
{
/*
Manually set the error flag. Note: there seems to be quite a few
@@ -5813,6 +5813,7 @@ get_mm_leaf(RANGE_OPT_PARAM *param, COND *conf_func, Field *field,
*/
if (field->result_type() == STRING_RESULT &&
+ ((Field_str*) field)->match_collation_to_optimize_range() &&
value->result_type() == STRING_RESULT &&
key_part->image_type == Field::itRAW &&
((Field_str*)field)->charset() != conf_func->compare_collation() &&
@@ -8149,7 +8150,7 @@ int QUICK_INDEX_MERGE_SELECT::read_keys_and_merge()
if (unique == NULL)
{
- DBUG_EXECUTE_IF("index_merge_may_not_create_a_Unique", abort(); );
+ DBUG_EXECUTE_IF("index_merge_may_not_create_a_Unique", DBUG_ABORT(); );
DBUG_EXECUTE_IF("only_one_Unique_may_be_created",
DBUG_SET("+d,index_merge_may_not_create_a_Unique"); );
@@ -11223,7 +11224,7 @@ void QUICK_GROUP_MIN_MAX_SELECT::update_min_result()
min_functions_it->rewind();
while ((min_func= (*min_functions_it)++))
- min_func->reset();
+ min_func->reset_and_add();
}
@@ -11255,7 +11256,7 @@ void QUICK_GROUP_MIN_MAX_SELECT::update_max_result()
max_functions_it->rewind();
while ((max_func= (*max_functions_it)++))
- max_func->reset();
+ max_func->reset_and_add();
}
diff --git a/sql/opt_range.h b/sql/opt_range.h
index 585f655aeac..1340f0a5525 100644
--- a/sql/opt_range.h
+++ b/sql/opt_range.h
@@ -288,6 +288,7 @@ public:
virtual bool reverse_sorted() = 0;
virtual bool unique_key_range() { return false; }
+ virtual bool clustered_pk_range() { return false; }
/*
Request that this quick select produces sorted output. Not all quick
@@ -350,6 +351,13 @@ public:
*/
virtual bool is_keys_used(const MY_BITMAP *fields);
+ /**
+ Simple sanity check that the quick select has been set up
+ correctly. Function is overridden by quick selects that merge
+ indices.
+ */
+ virtual bool is_valid() { return index != MAX_KEY; };
+
/*
rowid of last row retrieved by this quick select. This is used only when
doing ROR-index_merge selects
@@ -595,6 +603,24 @@ public:
THD *thd;
int read_keys_and_merge();
+ bool clustered_pk_range() { return test(pk_quick_select); }
+
+ virtual bool is_valid()
+ {
+ List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
+ QUICK_RANGE_SELECT *quick;
+ bool valid= true;
+ while ((quick= it++))
+ {
+ if (!quick->is_valid())
+ {
+ valid= false;
+ break;
+ }
+ }
+ return valid;
+ }
+
/* used to get rows collected in Unique */
READ_RECORD read_record;
};
@@ -648,6 +674,22 @@ public:
*/
List<QUICK_RANGE_SELECT> quick_selects;
+ virtual bool is_valid()
+ {
+ List_iterator_fast<QUICK_RANGE_SELECT> it(quick_selects);
+ QUICK_RANGE_SELECT *quick;
+ bool valid= true;
+ while ((quick= it++))
+ {
+ if (!quick->is_valid())
+ {
+ valid= false;
+ break;
+ }
+ }
+ return valid;
+ }
+
/*
Merged quick select that uses Clustered PK, if there is one. This quick
select is not used for row retrieval, it is used for row retrieval.
@@ -699,6 +741,22 @@ public:
List<QUICK_SELECT_I> quick_selects; /* Merged quick selects */
+ virtual bool is_valid()
+ {
+ List_iterator_fast<QUICK_SELECT_I> it(quick_selects);
+ QUICK_SELECT_I *quick;
+ bool valid= true;
+ while ((quick= it++))
+ {
+ if (!quick->is_valid())
+ {
+ valid= false;
+ break;
+ }
+ }
+ return valid;
+ }
+
QUEUE queue; /* Priority queue for merge operation */
MEM_ROOT alloc; /* Memory pool for this and merged quick selects data. */
diff --git a/sql/opt_subselect.cc b/sql/opt_subselect.cc
index a4e626e90cd..38fc52c830d 100644
--- a/sql/opt_subselect.cc
+++ b/sql/opt_subselect.cc
@@ -83,7 +83,7 @@ int check_and_do_in_subquery_rewrites(JOIN *join)
TODO: for PS, make the whole block execute only on the first execution
*/
Item_subselect *subselect;
- if (!thd->lex->view_prepare_mode && // (1)
+ if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) && // (1)
(subselect= select_lex->master_unit()->item)) // (2)
{
Item_in_subselect *in_subs= NULL;
diff --git a/sql/opt_sum.cc b/sql/opt_sum.cc
index d94777787fc..381dd1ab21c 100644
--- a/sql/opt_sum.cc
+++ b/sql/opt_sum.cc
@@ -212,6 +212,7 @@ static int get_index_max_value(TABLE *table, TABLE_REF *ref, uint range_fl)
/**
Substitutes constants for some COUNT(), MIN() and MAX() functions.
+ @param thd thread handler
@param tables list of leaves of join table tree
@param all_fields All fields to be returned
@param conds WHERE clause
@@ -229,9 +230,12 @@ static int get_index_max_value(TABLE *table, TABLE_REF *ref, uint range_fl)
HA_ERR_KEY_NOT_FOUND on impossible conditions
@retval
HA_ERR_... if a deadlock or a lock wait timeout happens, for example
+ @retval
+ ER_... e.g. ER_SUBQUERY_NO_1_ROW
*/
-int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
+int opt_sum_query(THD *thd,
+ TABLE_LIST *tables, List<Item> &all_fields, COND *conds)
{
List_iterator_fast<Item> it(all_fields);
int const_result= 1;
@@ -243,6 +247,8 @@ int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
Item *item;
int error;
+ DBUG_ENTER("opt_sum_query");
+
if (conds)
where_tables= conds->used_tables();
@@ -270,7 +276,7 @@ int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
WHERE t2.field IS NULL;
*/
if (tl->table->map & where_tables)
- return 0;
+ DBUG_RETURN(0);
}
else
used_tables|= tl->table->map;
@@ -297,7 +303,7 @@ int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
if(error)
{
tl->table->file->print_error(error, MYF(ME_FATALERROR));
- return error;
+ DBUG_RETURN(error);
}
count*= tl->table->file->stats.records;
}
@@ -389,10 +395,10 @@ int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
if (error)
{
if (error == HA_ERR_KEY_NOT_FOUND || error == HA_ERR_END_OF_FILE)
- return HA_ERR_KEY_NOT_FOUND; // No rows matching WHERE
+ DBUG_RETURN(HA_ERR_KEY_NOT_FOUND); // No rows matching WHERE
/* HA_ERR_LOCK_DEADLOCK or some other error */
table->file->print_error(error, MYF(0));
- return(error);
+ DBUG_RETURN(error);
}
removed_tables|= table->map;
}
@@ -423,7 +429,7 @@ int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
item_sum->aggregator_clear();
}
else
- item_sum->reset();
+ item_sum->reset_and_add();
item_sum->make_const();
recalc_const_item= 1;
break;
@@ -441,6 +447,10 @@ int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
const_result= 0;
}
}
+
+ if (thd->is_error())
+ DBUG_RETURN(thd->stmt_da->sql_errno());
+
/*
If we have a where clause, we can only ignore searching in the
tables if MIN/MAX optimisation replaced all used tables
@@ -450,7 +460,7 @@ int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds)
*/
if (removed_tables && used_tables != removed_tables)
const_result= 0; // We didn't remove all tables
- return const_result;
+ DBUG_RETURN(const_result);
}
@@ -736,6 +746,12 @@ static bool matching_cond(bool max_fl, TABLE_REF *ref, KEY *keyinfo,
if (is_null || (is_null_safe_eq && args[1]->is_null()))
{
+ /*
+ If we have a non-nullable index, we cannot use it,
+ since set_null will be ignored, and we will compare uninitialized data.
+ */
+ if (!part->field->real_maybe_null())
+ DBUG_RETURN(false);
part->field->set_null();
*key_ptr= (uchar) 1;
}
@@ -806,8 +822,9 @@ static bool matching_cond(bool max_fl, TABLE_REF *ref, KEY *keyinfo,
@param[out] prefix_len Length of prefix for the search range
@note
- This function may set table->key_read to 1, which must be reset after
- index is used! (This can only happen when function returns 1)
+ This function may set field->table->key_read to true,
+ which must be reset after index is used!
+ (This can only happen when function returns 1)
@retval
0 Index can not be used to optimize MIN(field)/MAX(field)
@@ -822,7 +839,9 @@ static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref,
uint *range_fl, uint *prefix_len)
{
if (!(field->flags & PART_KEY_FLAG))
- return 0; // Not key field
+ return false; // Not key field
+
+ DBUG_ENTER("find_key_for_maxmin");
TABLE *table= field->table;
uint idx= 0;
@@ -847,7 +866,7 @@ static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref,
part++, jdx++, key_part_to_use= (key_part_to_use << 1) | 1)
{
if (!(table->file->index_flags(idx, jdx, 0) & HA_READ_ORDER))
- return 0;
+ DBUG_RETURN(false);
/* Check whether the index component is partial */
Field *part_field= table->field[part->fieldnr-1];
@@ -896,12 +915,12 @@ static bool find_key_for_maxmin(bool max_fl, TABLE_REF *ref,
*/
if (field->part_of_key.is_set(idx))
table->enable_keyread();
- return 1;
+ DBUG_RETURN(true);
}
}
}
}
- return 0;
+ DBUG_RETURN(false);
}
diff --git a/sql/partition_info.cc b/sql/partition_info.cc
index 00c03806f77..baea5c2c086 100644
--- a/sql/partition_info.cc
+++ b/sql/partition_info.cc
@@ -742,7 +742,6 @@ bool partition_info::check_range_constants(THD *thd)
longlong part_range_value;
bool signed_flag= !part_expr->unsigned_flag;
- part_result_type= INT_RESULT;
range_int_array= (longlong*)sql_alloc(num_parts * sizeof(longlong));
if (unlikely(range_int_array == NULL))
{
@@ -917,7 +916,6 @@ bool partition_info::check_list_constants(THD *thd)
List_iterator<partition_element> list_func_it(partitions);
DBUG_ENTER("partition_info::check_list_constants");
- part_result_type= INT_RESULT;
num_list_values= 0;
/*
We begin by calculating the number of list values that have been
@@ -1608,6 +1606,52 @@ id_err:
return 1;
}
+
+/**
+ Check what kind of error to report
+
+ @param use_subpart_expr Use the subpart_expr instead of part_expr
+ @param part_str Name of partition to report error (or NULL)
+*/
+void partition_info::report_part_expr_error(bool use_subpart_expr)
+{
+ Item *expr= part_expr;
+ DBUG_ENTER("partition_info::report_part_expr_error");
+ if (use_subpart_expr)
+ expr= subpart_expr;
+
+ if (expr->type() == Item::FIELD_ITEM)
+ {
+ partition_type type= part_type;
+ bool list_of_fields= list_of_part_fields;
+ Item_field *item_field= (Item_field*) expr;
+ /*
+ The expression consists of a single field.
+ It must be of integer type unless KEY or COLUMNS partitioning.
+ */
+ if (use_subpart_expr)
+ {
+ type= subpart_type;
+ list_of_fields= list_of_subpart_fields;
+ }
+ if (!column_list &&
+ item_field->field &&
+ item_field->field->result_type() != INT_RESULT &&
+ !(type == HASH_PARTITION && list_of_fields))
+ {
+ my_error(ER_FIELD_TYPE_NOT_ALLOWED_AS_PARTITION_FIELD, MYF(0),
+ item_field->name);
+ DBUG_VOID_RETURN;
+ }
+ }
+ if (use_subpart_expr)
+ my_error(ER_PARTITION_FUNC_NOT_ALLOWED_ERROR, MYF(0), "SUBPARTITION");
+ else
+ my_error(ER_PARTITION_FUNC_NOT_ALLOWED_ERROR, MYF(0), "PARTITION");
+ DBUG_VOID_RETURN;
+}
+
+
/*
Create a new column value in current list with maxvalue
Called from parser
@@ -1891,7 +1935,7 @@ int partition_info::reorganize_into_single_field_col_val()
code.
SYNOPSIS
- fix_func_partition()
+ fix_partition_values()
thd Thread object
col_val Array of one value
part_elem The partition instance
@@ -1901,13 +1945,13 @@ int partition_info::reorganize_into_single_field_col_val()
TRUE Failure
FALSE Success
*/
-int partition_info::fix_func_partition(THD *thd,
- part_elem_value *val,
- partition_element *part_elem,
- uint part_id)
+int partition_info::fix_partition_values(THD *thd,
+ part_elem_value *val,
+ partition_element *part_elem,
+ uint part_id)
{
part_column_list_val *col_val= val->col_val_array;
- DBUG_ENTER("partition_info::fix_func_partition");
+ DBUG_ENTER("partition_info::fix_partition_values");
if (col_val->fixed)
{
@@ -1953,7 +1997,8 @@ int partition_info::fix_func_partition(THD *thd,
}
else if (item_expr->result_type() != INT_RESULT)
{
- my_error(ER_INCONSISTENT_TYPE_OF_FUNCTIONS_ERROR, MYF(0));
+ my_error(ER_VALUES_IS_NOT_INT_TYPE_ERROR, MYF(0),
+ part_elem->partition_name);
DBUG_RETURN(TRUE);
}
if (part_type == RANGE_PARTITION)
@@ -2168,7 +2213,7 @@ int partition_info::fix_parser_data(THD *thd)
}
else
{
- if (fix_func_partition(thd, val, part_elem, i))
+ if (fix_partition_values(thd, val, part_elem, i))
{
DBUG_RETURN(TRUE);
}
diff --git a/sql/partition_info.h b/sql/partition_info.h
index b196d0b59a2..6ae210d9574 100644
--- a/sql/partition_info.h
+++ b/sql/partition_info.h
@@ -166,7 +166,6 @@ public:
key_map some_fields_in_PF;
handlerton *default_engine_type;
- Item_result part_result_type;
partition_type part_type;
partition_type subpart_type;
@@ -226,7 +225,6 @@ public:
curr_part_elem(NULL), current_partition(NULL),
curr_list_object(0), num_columns(0),
default_engine_type(NULL),
- part_result_type(INT_RESULT),
part_type(NOT_A_PARTITION), subpart_type(NOT_A_PARTITION),
part_info_len(0),
part_func_len(0), subpart_func_len(0),
@@ -279,10 +277,10 @@ public:
void print_no_partition_found(TABLE *table);
void print_debug(const char *str, uint*);
Item* get_column_item(Item *item, Field *field);
- int fix_func_partition(THD *thd,
- part_elem_value *val,
- partition_element *part_elem,
- uint part_id);
+ int fix_partition_values(THD *thd,
+ part_elem_value *val,
+ partition_element *part_elem,
+ uint part_id);
bool fix_column_value_functions(THD *thd,
part_elem_value *val,
uint part_id);
@@ -299,6 +297,7 @@ public:
bool init_column_part();
bool add_column_list_value(THD *thd, Item *item);
void set_show_version_string(String *packet);
+ void report_part_expr_error(bool use_subpart_expr);
private:
static int list_part_cmp(const void* a, const void* b);
bool set_up_default_partitions(handler *file, HA_CREATE_INFO *info,
diff --git a/sql/password.c b/sql/password.c
index 0e2b454ff4d..1b3aa8f356d 100644
--- a/sql/password.c
+++ b/sql/password.c
@@ -176,21 +176,16 @@ void scramble_323(char *to, const char *message, const char *password)
}
-/*
- Check scrambled message
- Used in pre 4.1 password handling
- SYNOPSIS
- check_scramble_323()
- scrambled scrambled message to check.
- message original random message which was used for scrambling; must
- be exactly SCRAMBLED_LENGTH_323 bytes long and
- NULL-terminated.
- hash_pass password which should be used for scrambling
- All params are IN.
+/**
+ Check scrambled message. Used in pre 4.1 password handling.
- RETURN VALUE
- 0 - password correct
- !0 - password invalid
+ @param scrambled Scrambled message to check.
+ @param message Original random message which was used for scrambling.
+ @param hash_pass Password which should be used for scrambling.
+
+ @remark scrambled and message must be SCRAMBLED_LENGTH_323 bytes long.
+
+ @return FALSE if password is correct, TRUE otherwise.
*/
my_bool
@@ -199,9 +194,16 @@ check_scramble_323(const unsigned char *scrambled, const char *message,
{
struct my_rnd_struct rand_st;
ulong hash_message[2];
- uchar buff[16],*to,extra; /* Big enough for check */
+ /* Big enough for checks. */
+ uchar buff[16], scrambled_buff[SCRAMBLE_LENGTH_323 + 1];
+ uchar *to, extra;
const uchar *pos;
+ /* Ensure that the scrambled message is null-terminated. */
+ memcpy(scrambled_buff, scrambled, SCRAMBLE_LENGTH_323);
+ scrambled_buff[SCRAMBLE_LENGTH_323]= '\0';
+ scrambled= scrambled_buff;
+
hash_password(hash_message, message, SCRAMBLE_LENGTH_323);
my_rnd_init(&rand_st,hash_pass[0] ^ hash_message[0],
hash_pass[1] ^ hash_message[1]);
diff --git a/sql/protocol.cc b/sql/protocol.cc
index 1b5eaafbe7f..0c68df91121 100644
--- a/sql/protocol.cc
+++ b/sql/protocol.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011 Oracle and/or its affiliates. All rights reserved.
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
@@ -504,11 +504,11 @@ void Protocol::end_statement()
thd->stmt_da->get_sqlstate());
break;
case Diagnostics_area::DA_EOF:
- error= send_eof(thd->stmt_da->server_status(),
+ error= send_eof(thd->server_status,
thd->stmt_da->statement_warn_count());
break;
case Diagnostics_area::DA_OK:
- error= send_ok(thd->stmt_da->server_status(),
+ error= send_ok(thd->server_status,
thd->stmt_da->statement_warn_count(),
thd->stmt_da->affected_rows(),
thd->stmt_da->last_insert_id(),
@@ -541,9 +541,10 @@ bool Protocol::send_ok(uint server_status, uint statement_warn_count,
const char *message)
{
DBUG_ENTER("Protocol::send_ok");
-
- DBUG_RETURN(net_send_ok(thd, server_status, statement_warn_count,
- affected_rows, last_insert_id, message));
+ const bool retval=
+ net_send_ok(thd, server_status, statement_warn_count,
+ affected_rows, last_insert_id, message);
+ DBUG_RETURN(retval);
}
@@ -556,8 +557,8 @@ bool Protocol::send_ok(uint server_status, uint statement_warn_count,
bool Protocol::send_eof(uint server_status, uint statement_warn_count)
{
DBUG_ENTER("Protocol::send_eof");
-
- DBUG_RETURN(net_send_eof(thd, server_status, statement_warn_count));
+ const bool retval= net_send_eof(thd, server_status, statement_warn_count);
+ DBUG_RETURN(retval);
}
@@ -571,8 +572,8 @@ bool Protocol::send_error(uint sql_errno, const char *err_msg,
const char *sql_state)
{
DBUG_ENTER("Protocol::send_error");
-
- DBUG_RETURN(net_send_error_packet(thd, sql_errno, err_msg, sql_state));
+ const bool retval= net_send_error_packet(thd, sql_errno, err_msg, sql_state);
+ DBUG_RETURN(retval);
}
diff --git a/sql/records.cc b/sql/records.cc
index ed1edcaf487..5709eaf1df2 100644
--- a/sql/records.cc
+++ b/sql/records.cc
@@ -207,6 +207,15 @@ bool init_read_record(READ_RECORD *info,THD *thd, TABLE *table,
if (select && my_b_inited(&select->file))
tempfile= &select->file;
+ else if (select && select->quick && select->quick->clustered_pk_range())
+ {
+ /*
+ In case of QUICK_INDEX_MERGE_SELECT with clustered pk range we have to
+ use its own access method(i.e QUICK_INDEX_MERGE_SELECT::get_next()) as
+ sort file does not contain rowids which satisfy clustered pk range.
+ */
+ tempfile= 0;
+ }
else
tempfile= table->sort.io_cache;
if (tempfile && my_b_inited(tempfile) &&
diff --git a/sql/repl_failsafe.cc b/sql/repl_failsafe.cc
index 47eb2f7031d..bc710616a4c 100644
--- a/sql/repl_failsafe.cc
+++ b/sql/repl_failsafe.cc
@@ -41,7 +41,7 @@
#define SLAVE_ERRMSG_SIZE (FN_REFLEN+64)
-RPL_STATUS rpl_status=RPL_NULL;
+ulong rpl_status=RPL_NULL;
mysql_mutex_t LOCK_rpl_status;
mysql_cond_t COND_rpl_status;
HASH slave_list;
@@ -56,10 +56,6 @@ const char* rpl_status_type[]=
"RECOVERY_CAPTAIN","NULL",NullS
};
-static Slave_log_event* find_slave_event(IO_CACHE* log,
- const char* log_file_name,
- char* errmsg);
-
/*
All of the functions defined in this file which are not used (the ones to
handle failsafe) are not used; their code has not been updated for more than
@@ -68,7 +64,7 @@ static Slave_log_event* find_slave_event(IO_CACHE* log,
functions like register_slave()) are working.
*/
-void change_rpl_status(RPL_STATUS from_status, RPL_STATUS to_status)
+void change_rpl_status(ulong from_status, ulong to_status)
{
mysql_mutex_lock(&LOCK_rpl_status);
if (rpl_status == from_status || rpl_status == RPL_ANY)
@@ -91,13 +87,6 @@ void change_rpl_status(RPL_STATUS from_status, RPL_STATUS to_status)
}\
-static inline int cmp_master_pos(Slave_log_event* sev, LEX_MASTER_INFO* mi)
-{
- return cmp_master_pos(sev->master_log, sev->master_pos, mi->log_file_name,
- mi->pos);
-}
-
-
void unregister_slave(THD* thd, bool only_mine, bool need_mutex)
{
if (thd->server_id)
@@ -228,361 +217,6 @@ void end_slave_list()
}
}
-static int find_target_pos(LEX_MASTER_INFO *mi, IO_CACHE *log, char *errmsg)
-{
- my_off_t log_pos = (my_off_t) mi->pos;
- uint32 target_server_id = mi->server_id;
-
- for (;;)
- {
- Log_event* ev;
- if (!(ev= Log_event::read_log_event(log, (mysql_mutex_t*) 0, 0)))
- {
- if (log->error > 0)
- strmov(errmsg, "Binary log truncated in the middle of event");
- else if (log->error < 0)
- strmov(errmsg, "I/O error reading binary log");
- else
- strmov(errmsg, "Could not find target event in the binary log");
- return 1;
- }
-
- if (ev->log_pos >= log_pos && ev->server_id == target_server_id)
- {
- delete ev;
- mi->pos = my_b_tell(log);
- return 0;
- }
- delete ev;
- }
- /* Impossible */
-}
-
-/**
- @details
- Before 4.0.15 we had a member of THD called log_pos, it was meant for
- failsafe replication code in repl_failsafe.cc which is disabled until
- it is reworked. Event's log_pos used to be preserved through
- log-slave-updates to make code in repl_failsafe.cc work (this
- function, SHOW NEW MASTER); but on the other side it caused unexpected
- values in Exec_Master_Log_Pos in A->B->C replication setup,
- synchronization problems in master_pos_wait(), ... So we
- (Dmitri & Guilhem) removed it.
-
- So for now this function is broken.
-*/
-
-int translate_master(THD* thd, LEX_MASTER_INFO* mi, char* errmsg)
-{
- LOG_INFO linfo;
- char last_log_name[FN_REFLEN];
- IO_CACHE log;
- File file = -1, last_file = -1;
- mysql_mutex_t *log_lock;
- const char* errmsg_p;
- Slave_log_event* sev = 0;
- my_off_t last_pos = 0;
- int error = 1;
- int cmp_res;
- LINT_INIT(cmp_res);
- DBUG_ENTER("translate_master");
-
- if (!mysql_bin_log.is_open())
- {
- strmov(errmsg,"Binary log is not open");
- DBUG_RETURN(1);
- }
-
- if (!server_id_supplied)
- {
- strmov(errmsg, "Misconfigured master - server id was not set");
- DBUG_RETURN(1);
- }
-
- if (mysql_bin_log.find_log_pos(&linfo, NullS, 1))
- {
- strmov(errmsg,"Could not find first log");
- DBUG_RETURN(1);
- }
- thd->current_linfo = &linfo;
-
- bzero((char*) &log,sizeof(log));
- log_lock = mysql_bin_log.get_log_lock();
- mysql_mutex_lock(log_lock);
-
- for (;;)
- {
- if ((file=open_binlog(&log, linfo.log_file_name, &errmsg_p)) < 0)
- {
- strmov(errmsg, errmsg_p);
- goto err;
- }
-
- if (!(sev = find_slave_event(&log, linfo.log_file_name, errmsg)))
- goto err;
-
- cmp_res = cmp_master_pos(sev, mi);
- delete sev;
-
- if (!cmp_res)
- {
- /* Copy basename */
- fn_format(mi->log_file_name, linfo.log_file_name, "","",1);
- mi->pos = my_b_tell(&log);
- goto mi_inited;
- }
- else if (cmp_res > 0)
- {
- if (!last_pos)
- {
- strmov(errmsg,
- "Slave event in first log points past the target position");
- goto err;
- }
- end_io_cache(&log);
- mysql_file_close(file, MYF(MY_WME));
- if (init_io_cache(&log, (file = last_file), IO_SIZE, READ_CACHE, 0, 0,
- MYF(MY_WME)))
- {
- errmsg[0] = 0;
- goto err;
- }
- break;
- }
-
- strmov(last_log_name, linfo.log_file_name);
- last_pos = my_b_tell(&log);
-
- switch (mysql_bin_log.find_next_log(&linfo, 1)) {
- case LOG_INFO_EOF:
- if (last_file >= 0)
- mysql_file_close(last_file, MYF(MY_WME));
- last_file = -1;
- goto found_log;
- case 0:
- break;
- default:
- strmov(errmsg, "Error reading log index");
- goto err;
- }
-
- end_io_cache(&log);
- if (last_file >= 0)
- mysql_file_close(last_file, MYF(MY_WME));
- last_file = file;
- }
-
-found_log:
- my_b_seek(&log, last_pos);
- if (find_target_pos(mi,&log,errmsg))
- goto err;
- fn_format(mi->log_file_name, last_log_name, "","",1); /* Copy basename */
-
-mi_inited:
- error = 0;
-err:
- mysql_mutex_unlock(log_lock);
- end_io_cache(&log);
- mysql_mutex_lock(&LOCK_thread_count);
- thd->current_linfo = 0;
- mysql_mutex_unlock(&LOCK_thread_count);
- if (file >= 0)
- mysql_file_close(file, MYF(MY_WME));
- if (last_file >= 0 && last_file != file)
- mysql_file_close(last_file, MYF(MY_WME));
-
- DBUG_RETURN(error);
-}
-
-
-/**
- Caller must delete result when done.
-*/
-
-static Slave_log_event* find_slave_event(IO_CACHE* log,
- const char* log_file_name,
- char* errmsg)
-{
- Log_event* ev;
- int i;
- bool slave_event_found = 0;
- LINT_INIT(ev);
-
- for (i = 0; i < 2; i++)
- {
- if (!(ev= Log_event::read_log_event(log, (mysql_mutex_t*)0, 0)))
- {
- my_snprintf(errmsg, SLAVE_ERRMSG_SIZE,
- "Error reading event in log '%s'",
- (char*)log_file_name);
- return 0;
- }
- if (ev->get_type_code() == SLAVE_EVENT)
- {
- slave_event_found = 1;
- break;
- }
- delete ev;
- }
- if (!slave_event_found)
- {
- my_snprintf(errmsg, SLAVE_ERRMSG_SIZE,
- "Could not find slave event in log '%s'",
- (char*)log_file_name);
- return 0;
- }
-
- return (Slave_log_event*)ev;
-}
-
-/**
- This function is broken now.
-
- @seealso translate_master()
-*/
-
-bool show_new_master(THD* thd)
-{
- Protocol *protocol= thd->protocol;
- DBUG_ENTER("show_new_master");
- List<Item> field_list;
- char errmsg[SLAVE_ERRMSG_SIZE];
- LEX_MASTER_INFO* lex_mi= &thd->lex->mi;
-
- errmsg[0]=0; // Safety
- if (translate_master(thd, lex_mi, errmsg))
- {
- if (errmsg[0])
- my_error(ER_ERROR_WHEN_EXECUTING_COMMAND, MYF(0),
- "SHOW NEW MASTER", errmsg);
- DBUG_RETURN(TRUE);
- }
- else
- {
- field_list.push_back(new Item_empty_string("Log_name", 20));
- field_list.push_back(new Item_return_int("Log_pos", 10,
- MYSQL_TYPE_LONGLONG));
- if (protocol->send_result_set_metadata(&field_list,
- Protocol::SEND_NUM_ROWS | Protocol::SEND_EOF))
- DBUG_RETURN(TRUE);
- protocol->prepare_for_resend();
- protocol->store(lex_mi->log_file_name, &my_charset_bin);
- protocol->store((ulonglong) lex_mi->pos);
- if (protocol->write())
- DBUG_RETURN(TRUE);
- my_eof(thd);
- DBUG_RETURN(FALSE);
- }
-}
-
-/**
- Asks the master for the list of its other connected slaves.
-
- This is for failsafe replication:
- in order for failsafe replication to work, the servers involved in
- replication must know of each other. We accomplish this by having each
- slave report to the master how to reach it, and on connection, each
- slave receives information about where the other slaves are.
-
- @param mysql pre-existing connection to the master
- @param mi master info
-
- @note
- mi is used only to give detailed error messages which include the
- hostname/port of the master, the username used by the slave to connect to
- the master.
- If the user used by the slave to connect to the master does not have the
- REPLICATION SLAVE privilege, it will pop in this function because
- SHOW SLAVE HOSTS will fail on the master.
-
- @retval
- 1 error
- @retval
- 0 success
-*/
-
-int update_slave_list(MYSQL* mysql, Master_info* mi)
-{
- MYSQL_RES* res=0;
- MYSQL_ROW row;
- const char* error=0;
- bool have_auth_info;
- int port_ind;
- DBUG_ENTER("update_slave_list");
-
- if (mysql_real_query(mysql, STRING_WITH_LEN("SHOW SLAVE HOSTS")) ||
- !(res = mysql_store_result(mysql)))
- {
- error= mysql_error(mysql);
- goto err;
- }
-
- switch (mysql_num_fields(res)) {
- case 5:
- have_auth_info = 0;
- port_ind=2;
- break;
- case 7:
- have_auth_info = 1;
- port_ind=4;
- break;
- default:
- error= "the master returned an invalid number of fields for SHOW SLAVE \
-HOSTS";
- goto err;
- }
-
- mysql_mutex_lock(&LOCK_slave_list);
-
- while ((row= mysql_fetch_row(res)))
- {
- uint32 log_server_id;
- SLAVE_INFO* si, *old_si;
- log_server_id = atoi(row[0]);
- if ((old_si= (SLAVE_INFO*)my_hash_search(&slave_list,
- (uchar*)&log_server_id,4)))
- si = old_si;
- else
- {
- if (!(si = (SLAVE_INFO*)my_malloc(sizeof(SLAVE_INFO), MYF(MY_WME))))
- {
- error= "the slave is out of memory";
- mysql_mutex_unlock(&LOCK_slave_list);
- goto err;
- }
- si->server_id = log_server_id;
- if (my_hash_insert(&slave_list, (uchar*)si))
- {
- error= "the slave is out of memory";
- mysql_mutex_unlock(&LOCK_slave_list);
- goto err;
- }
- }
- strmake(si->host, row[1], sizeof(si->host)-1);
- si->port = atoi(row[port_ind]);
- si->rpl_recovery_rank = atoi(row[port_ind+1]);
- si->master_id = atoi(row[port_ind+2]);
- if (have_auth_info)
- {
- strmake(si->user, row[2], sizeof(si->user)-1);
- strmake(si->password, row[3], sizeof(si->password)-1);
- }
- }
- mysql_mutex_unlock(&LOCK_slave_list);
-
-err:
- if (res)
- mysql_free_result(res);
- if (error)
- {
- sql_print_error("While trying to obtain the list of slaves from the master "
- "'%s:%d', user '%s' got the following error: '%s'",
- mi->host, mi->port, mi->user, error);
- DBUG_RETURN(1);
- }
- DBUG_RETURN(0);
-}
-
/**
Execute a SHOW SLAVE HOSTS statement.
diff --git a/sql/repl_failsafe.h b/sql/repl_failsafe.h
index c6d00de47cb..2ba1f25c591 100644
--- a/sql/repl_failsafe.h
+++ b/sql/repl_failsafe.h
@@ -26,26 +26,19 @@ typedef enum {RPL_AUTH_MASTER=0,RPL_IDLE_SLAVE,RPL_ACTIVE_SLAVE,
RPL_LOST_SOLDIER,RPL_TROOP_SOLDIER,
RPL_RECOVERY_CAPTAIN,RPL_NULL /* inactive */,
RPL_ANY /* wild card used by change_rpl_status */ } RPL_STATUS;
-extern RPL_STATUS rpl_status;
+extern ulong rpl_status;
extern mysql_mutex_t LOCK_rpl_status;
extern mysql_cond_t COND_rpl_status;
extern TYPELIB rpl_role_typelib;
extern const char* rpl_role_type[], *rpl_status_type[];
-pthread_handler_t handle_failsafe_rpl(void *arg);
-void change_rpl_status(RPL_STATUS from_status, RPL_STATUS to_status);
+void change_rpl_status(ulong from_status, ulong to_status);
int find_recovery_captain(THD* thd, MYSQL* mysql);
-int update_slave_list(MYSQL* mysql, Master_info* mi);
extern HASH slave_list;
-bool load_master_data(THD* thd);
-int connect_to_master(THD *thd, MYSQL* mysql, Master_info* mi);
-
-bool show_new_master(THD* thd);
bool show_slave_hosts(THD* thd);
-int translate_master(THD* thd, LEX_MASTER_INFO* mi, char* errmsg);
void init_slave_list();
void end_slave_list();
int register_slave(THD* thd, uchar* packet, uint packet_length);
diff --git a/sql/rpl_handler.cc b/sql/rpl_handler.cc
index 9e59c4fe5fd..1b1b91c63e9 100644
--- a/sql/rpl_handler.cc
+++ b/sql/rpl_handler.cc
@@ -105,12 +105,20 @@ int delegates_init()
transaction_delegate= new (place_trans_mem) Trans_delegate;
if (!transaction_delegate->is_inited())
+ {
+ sql_print_error("Initialization of transaction delegates failed. "
+ "Please report a bug.");
return 1;
+ }
binlog_storage_delegate= new (place_storage_mem) Binlog_storage_delegate;
if (!binlog_storage_delegate->is_inited())
+ {
+ sql_print_error("Initialization binlog storage delegates failed. "
+ "Please report a bug.");
return 1;
+ }
#ifdef HAVE_REPLICATION
void *place_transmit_mem= transmit_mem.data;
@@ -119,16 +127,29 @@ int delegates_init()
binlog_transmit_delegate= new (place_transmit_mem) Binlog_transmit_delegate;
if (!binlog_transmit_delegate->is_inited())
+ {
+ sql_print_error("Initialization of binlog transmit delegates failed. "
+ "Please report a bug.");
return 1;
+ }
binlog_relay_io_delegate= new (place_relay_io_mem) Binlog_relay_IO_delegate;
if (!binlog_relay_io_delegate->is_inited())
+ {
+ sql_print_error("Initialization binlog relay IO delegates failed. "
+ "Please report a bug.");
return 1;
+ }
#endif
if (pthread_key_create(&RPL_TRANS_BINLOG_INFO, NULL))
+ {
+ sql_print_error("Error while creating pthread specific data key for replication. "
+ "Please report a bug.");
return 1;
+ }
+
return 0;
}
diff --git a/sql/rpl_handler.h b/sql/rpl_handler.h
index bf207e53e2d..9a181250efc 100644
--- a/sql/rpl_handler.h
+++ b/sql/rpl_handler.h
@@ -73,7 +73,10 @@ public:
while (info && info->observer != observer)
info= iter++;
if (info)
+ {
iter.remove();
+ delete info;
+ }
else
ret= TRUE;
unlock();
diff --git a/sql/rpl_injector.cc b/sql/rpl_injector.cc
index 43f8ddbaf43..8f1f494b35a 100644
--- a/sql/rpl_injector.cc
+++ b/sql/rpl_injector.cc
@@ -238,8 +238,7 @@ int injector::record_incident(THD *thd, Incident incident)
Incident_log_event ev(thd, incident);
if (int error= mysql_bin_log.write(&ev))
return error;
- mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
- return 0;
+ return mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
}
int injector::record_incident(THD *thd, Incident incident, LEX_STRING const message)
@@ -247,6 +246,5 @@ int injector::record_incident(THD *thd, Incident incident, LEX_STRING const mess
Incident_log_event ev(thd, incident, message);
if (int error= mysql_bin_log.write(&ev))
return error;
- mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
- return 0;
+ return mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
}
diff --git a/sql/rpl_record.cc b/sql/rpl_record.cc
index 8219f70727e..5a7984430ea 100644
--- a/sql/rpl_record.cc
+++ b/sql/rpl_record.cc
@@ -78,8 +78,6 @@ pack_row(TABLE *table, MY_BITMAP const* cols,
unsigned int null_mask= 1U;
for ( ; (field= *p_field) ; p_field++)
{
- DBUG_PRINT("debug", ("null_mask=%d; null_ptr=%p; row_data=%p; null_byte_count=%d",
- null_mask, null_ptr, row_data, null_byte_count));
if (bitmap_is_set(cols, p_field - table->field))
{
my_ptrdiff_t offset;
@@ -110,6 +108,7 @@ pack_row(TABLE *table, MY_BITMAP const* cols,
field->field_name, field->real_type(),
(ulong) old_pack_ptr, (ulong) pack_ptr,
(int) (pack_ptr - old_pack_ptr)));
+ DBUG_DUMP("packed_data", old_pack_ptr, pack_ptr - old_pack_ptr);
}
null_mask <<= 1;
@@ -186,8 +185,7 @@ 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,
- const bool abort_on_warning, const bool first_row)
+ uchar const **const row_end, ulong *const master_reclength)
{
DBUG_ENTER("unpack_row");
DBUG_ASSERT(row_data);
@@ -286,22 +284,9 @@ unpack_row(Relay_log_info const *rli,
}
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->set_default();
+ push_warning_printf(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ ER_BAD_NULL_ERROR, ER(ER_BAD_NULL_ERROR),
f->field_name);
}
}
@@ -380,8 +365,11 @@ unpack_row(Relay_log_info const *rli,
}
DBUG_ASSERT(null_mask & 0xFF); // One of the 8 LSB should be set
- if (!((null_bits & null_mask) && tabledef->maybe_null(i)))
- pack_ptr+= tabledef->calc_field_size(i, (uchar *) pack_ptr);
+ if (!((null_bits & null_mask) && tabledef->maybe_null(i))) {
+ uint32 len= tabledef->calc_field_size(i, (uchar *) pack_ptr);
+ DBUG_DUMP("field_data", pack_ptr, len);
+ pack_ptr+= len;
+ }
null_mask <<= 1;
}
}
@@ -418,20 +406,13 @@ unpack_row(Relay_log_info const *rli,
@param skip Number of columns for which default/nullable check
should be skipped.
@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 bool abort_on_warning, const bool first_row)
+int prepare_record(TABLE *const table, const uint skip, const bool check)
{
DBUG_ENTER("prepare_record");
- int error= 0;
restore_record(table, s->default_values);
/*
@@ -454,28 +435,16 @@ int prepare_record(TABLE *const table,
if ((f->flags & NO_DEFAULT_VALUE_FLAG) &&
(f->real_type() != MYSQL_TYPE_ENUM))
{
-
- 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,
+ f->set_default();
+ push_warning_printf(current_thd,
+ MYSQL_ERROR::WARN_LEVEL_WARN,
ER_NO_DEFAULT_FOR_FIELD,
ER(ER_NO_DEFAULT_FOR_FIELD),
f->field_name);
}
}
- DBUG_RETURN(error);
+ DBUG_RETURN(0);
}
#endif // HAVE_REPLICATION
diff --git a/sql/rpl_record.h b/sql/rpl_record.h
index 9b3829a435e..104d77738f1 100644
--- a/sql/rpl_record.h
+++ b/sql/rpl_record.h
@@ -32,13 +32,10 @@ size_t pack_row(TABLE* table, MY_BITMAP const* cols,
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,
- const bool abort_on_warning= TRUE, const bool first_row= TRUE);
+ uchar const **const row_end, ulong *const master_reclength);
// Fill table's record[0] with default values.
-int prepare_record(TABLE *const table, const uint skip, const bool check,
- const bool abort_on_warning= TRUE,
- const bool first_row= TRUE);
+int prepare_record(TABLE *const table, const uint skip, const bool check);
#endif
#endif
diff --git a/sql/rpl_rli.cc b/sql/rpl_rli.cc
index 41550e96377..61cf39a3e86 100644
--- a/sql/rpl_rli.cc
+++ b/sql/rpl_rli.cc
@@ -26,6 +26,8 @@
#include "rpl_utility.h"
#include "transaction.h"
#include "sql_parse.h" // end_trans, ROLLBACK
+#include <mysql/plugin.h>
+#include <mysql/service_thd_wait.h>
static int count_relay_log_space(Relay_log_info* rli);
@@ -54,6 +56,13 @@ Relay_log_info::Relay_log_info(bool is_slave_recovery)
{
DBUG_ENTER("Relay_log_info::Relay_log_info");
+#ifdef HAVE_PSI_INTERFACE
+ relay_log.set_psi_keys(key_RELAYLOG_LOCK_index,
+ key_RELAYLOG_update_cond,
+ key_file_relaylog,
+ key_file_relaylog_index);
+#endif
+
group_relay_log_name[0]= event_relay_log_name[0]=
group_master_log_name[0]= 0;
until_log_name[0]= ign_master_log_name_end[0]= 0;
@@ -356,7 +365,7 @@ static inline int add_relay_log(Relay_log_info* rli,LOG_INFO* linfo)
{
MY_STAT s;
DBUG_ENTER("add_relay_log");
- if (!mysql_file_stat(key_file_binlog,
+ if (!mysql_file_stat(key_file_relaylog,
linfo->log_file_name, &s, MYF(0)))
{
sql_print_error("log %s listed in the index, but failed to stat",
@@ -792,6 +801,7 @@ int Relay_log_info::wait_for_pos(THD* thd, String* log_name,
We are going to mysql_cond_(timed)wait(); if the SQL thread stops it
will wake us up.
*/
+ thd_wait_begin(thd, THD_WAIT_BINLOG);
if (timeout > 0)
{
/*
@@ -809,6 +819,7 @@ int Relay_log_info::wait_for_pos(THD* thd, String* log_name,
}
else
mysql_cond_wait(&data_cond, &data_lock);
+ thd_wait_end(thd);
DBUG_PRINT("info",("Got signal of master update or timed out"));
if (error == ETIMEDOUT || error == ETIME)
{
@@ -1247,6 +1258,16 @@ void Relay_log_info::clear_tables_to_lock()
tables_to_lock->m_tabledef.table_def::~table_def();
tables_to_lock->m_tabledef_valid= FALSE;
}
+
+ /*
+ If blob fields were used during conversion of field values
+ from the master table into the slave table, then we need to
+ free the memory used temporarily to store their values before
+ copying into the slave's table.
+ */
+ if (tables_to_lock->m_conv_table)
+ free_blobs(tables_to_lock->m_conv_table);
+
tables_to_lock=
static_cast<RPL_TABLE_LIST*>(tables_to_lock->next_global);
tables_to_lock_count--;
@@ -1274,6 +1295,9 @@ void Relay_log_info::slave_close_thread_tables(THD *thd)
*/
if (! thd->in_multi_stmt_transaction_mode())
thd->mdl_context.release_transactional_locks();
+ else
+ thd->mdl_context.release_statement_locks();
+
clear_tables_to_lock();
}
#endif
diff --git a/sql/rpl_rli.h b/sql/rpl_rli.h
index c3cfe1cf4a9..681832a4c36 100644
--- a/sql/rpl_rli.h
+++ b/sql/rpl_rli.h
@@ -97,6 +97,16 @@ public:
*/
MYSQL_BIN_LOG relay_log;
LOG_INFO linfo;
+
+ /*
+ cur_log
+ Pointer that either points at relay_log.get_log_file() or
+ &rli->cache_buf, depending on whether the log is hot or there was
+ the need to open a cold relay_log.
+
+ cache_buf
+ IO_CACHE used when opening cold relay logs.
+ */
IO_CACHE cache_buf,*cur_log;
/*
diff --git a/sql/scheduler.cc b/sql/scheduler.cc
index a9146682da6..b1083083c38 100644
--- a/sql/scheduler.cc
+++ b/sql/scheduler.cc
@@ -46,18 +46,32 @@ static bool no_threads_end(THD *thd, bool put_in_cache)
*/
/**@{*/
-static void scheduler_wait_begin(void) {
+extern "C"
+{
+static void scheduler_wait_lock_begin(void) {
+ THD *thd=current_thd;
+ scheduler_functions *func= thd->scheduler;
+ MYSQL_CALLBACK(func, thd_wait_begin, (thd, THD_WAIT_ROW_TABLE_LOCK));
+}
+
+static void scheduler_wait_lock_end(void) {
THD *thd=current_thd;
scheduler_functions *func= thd->scheduler;
- MYSQL_CALLBACK(func,
- thd_wait_begin, (thd, THD_WAIT_ROW_TABLE_LOCK));
+ MYSQL_CALLBACK(func, thd_wait_end, (thd));
+}
+
+static void scheduler_wait_sync_begin(void) {
+ THD *thd=current_thd;
+ scheduler_functions *func= thd->scheduler;
+ MYSQL_CALLBACK(func, thd_wait_begin, (thd, THD_WAIT_TABLE_LOCK));
}
-static void scheduler_wait_end(void) {
+static void scheduler_wait_sync_end(void) {
THD *thd=current_thd;
scheduler_functions *func= thd->scheduler;
MYSQL_CALLBACK(func, thd_wait_end, (thd));
}
+};
/**@}*/
/**
@@ -68,7 +82,10 @@ static void scheduler_wait_end(void) {
mysqld.cc, so this init function will always be called.
*/
static void scheduler_init() {
- thr_set_lock_wait_callback(scheduler_wait_begin, scheduler_wait_end);
+ thr_set_lock_wait_callback(scheduler_wait_lock_begin,
+ scheduler_wait_lock_end);
+ thr_set_sync_wait_callback(scheduler_wait_sync_begin,
+ scheduler_wait_sync_end);
}
/*
@@ -119,10 +136,6 @@ void one_thread_scheduler(scheduler_functions *func)
thd_scheduler::thd_scheduler()
: m_psi(NULL), logged_in(FALSE), io_event(NULL), thread_attached(FALSE)
{
-#ifndef DBUG_OFF
- dbug_explain[0]= '\0';
- set_explain= FALSE;
-#endif
}
diff --git a/sql/scheduler.h b/sql/scheduler.h
index cb7568b566a..247c98515ac 100644
--- a/sql/scheduler.h
+++ b/sql/scheduler.h
@@ -58,6 +58,13 @@ struct scheduler_functions
*/
enum scheduler_types
{
+ /*
+ The default of --thread-handling is the first one in the
+ thread_handling_names array, this array has to be consistent with
+ the order in this array, so to change default one has to change
+ the first entry in this enum and the first entry in the
+ thread_handling_names array.
+ */
SCHEDULER_ONE_THREAD_PER_CONNECTION=0,
SCHEDULER_NO_THREADS,
SCHEDULER_TYPES_COUNT
@@ -67,11 +74,6 @@ void one_thread_per_connection_scheduler(scheduler_functions *func,
ulong *arg_max_connections, uint *arg_connection_count);
void one_thread_scheduler(scheduler_functions *func);
-enum pool_command_op
-{
- NOT_IN_USE_OP= 0, NORMAL_OP= 1, CONNECT_OP, KILL_OP, DIE_OP
-};
-
#if defined(HAVE_LIBEVENT) && !defined(EMBEDDED_LIBRARY)
#define HAVE_POOL_OF_THREADS 1
@@ -98,11 +100,6 @@ public:
LIST list;
bool thread_attached; /* Indicates if THD is attached to the OS thread */
-# ifndef DBUG_OFF
- char dbug_explain[512];
- bool set_explain;
-# endif
-
thd_scheduler();
~thd_scheduler();
bool init(THD* parent_thd);
@@ -122,4 +119,11 @@ class thd_scheduler
#endif
+void *thd_get_scheduler_data(THD *thd);
+void thd_set_scheduler_data(THD *thd, void *data);
+PSI_thread* thd_get_psi(THD *thd);
+void thd_set_psi(THD *thd, PSI_thread *psi);
+
+extern scheduler_functions *thread_scheduler;
+
#endif
diff --git a/sql/set_var.cc b/sql/set_var.cc
index 34b66dea319..8e48e0213f0 100644
--- a/sql/set_var.cc
+++ b/sql/set_var.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2010 Sun Microsystems, Inc.
+/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
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
@@ -117,7 +117,8 @@ void sys_var_end()
sys_var constructor
@param chain variables are linked into chain for mysql_add_sys_var_chain()
- @param name_arg the name of the variable. @sa my_option::name
+ @param name_arg the name of the variable. Must be 0-terminated and exist
+ for the liftime of the sys_var object. @sa my_option::name
@param comment shown in mysqld --help, @sa my_option::comment
@param flags_arg or'ed flag_enum values
@param off offset of the global variable value from the
@@ -164,8 +165,8 @@ sys_var::sys_var(sys_var_chain *chain, const char *name_arg,
*/
DBUG_ASSERT(parse_flag == PARSE_NORMAL || getopt_id <= 0 || getopt_id >= 255);
- name.str= name_arg;
- name.length= strlen(name_arg);
+ name.str= name_arg; // ER_NO_DEFAULT relies on 0-termination of name_arg
+ name.length= strlen(name_arg); // and so does this.
DBUG_ASSERT(name.length <= NAME_CHAR_LEN);
bzero(&option, sizeof(option));
@@ -746,9 +747,9 @@ int set_var_password::check(THD *thd)
}
if (!user->user.str)
{
- DBUG_ASSERT(thd->security_ctx->priv_user);
- user->user.str= (char *) thd->security_ctx->priv_user;
- user->user.length= strlen(thd->security_ctx->priv_user);
+ DBUG_ASSERT(thd->security_ctx->user);
+ user->user.str= (char *) thd->security_ctx->user;
+ user->user.length= strlen(thd->security_ctx->user);
}
/* Returns 1 as the function sends error to client */
return check_change_password(thd, user->host.str, user->user.str,
@@ -776,7 +777,7 @@ int set_var_password::update(THD *thd)
int set_var_collation_client::check(THD *thd)
{
/* Currently, UCS-2 cannot be used as a client character set */
- if (character_set_client->mbminlen > 1)
+ if (!is_supported_parser_charset(character_set_client))
{
my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), "character_set_client",
character_set_client->csname);
diff --git a/sql/set_var.h b/sql/set_var.h
index 17792a689d2..acfc1d54aa4 100644
--- a/sql/set_var.h
+++ b/sql/set_var.h
@@ -1,6 +1,6 @@
#ifndef SET_VAR_INCLUDED
#define SET_VAR_INCLUDED
-/* Copyright (C) 2000-2008 MySQL AB, 2008-2010 Sun Microsystems, Inc.
+/* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
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
diff --git a/sql/share/Makefile.am b/sql/share/Makefile.am
deleted file mode 100644
index 73f2ca13bb6..00000000000
--- a/sql/share/Makefile.am
+++ /dev/null
@@ -1,60 +0,0 @@
-# Copyright (C) 2000 MySQL AB
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License as published by
-# the Free Software Foundation; version 2 of the License.
-#
-# This program is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-# GNU General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program; if not, write to the Free Software
-# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-## Process this file with automake to create Makefile.in
-
-EXTRA_DIST= errmsg-utf8.txt \
- CMakeLists.txt
-
-dist-hook:
- for dir in charsets @AVAILABLE_LANGUAGES@; do \
- test -d $(distdir)/$$dir || mkdir $(distdir)/$$dir; \
- $(INSTALL_DATA) $(srcdir)/$$dir/*.* $(distdir)/$$dir; \
- done; \
- sleep 1 ; touch $(srcdir)/*/errmsg.sys
- $(INSTALL_DATA) $(srcdir)/charsets/README $(distdir)/charsets
- $(INSTALL_DATA) $(srcdir)/charsets/Index.xml $(distdir)/charsets
-
-all-local: english/errmsg.sys
-
-# Use the english errmsg.sys as a flag that all errmsg.sys needs to be
-# created. Normally these are created by extra/Makefile
-
-english/errmsg.sys: errmsg-utf8.txt
- rm -f $(top_builddir)/include/mysqld_error.h
- (cd $(top_builddir)/extra && $(MAKE))
-
-install-data-local:
- for lang in @AVAILABLE_LANGUAGES@; \
- do \
- $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/$$lang; \
- $(INSTALL_DATA) $(srcdir)/$$lang/errmsg.sys \
- $(DESTDIR)$(pkgdatadir)/$$lang/errmsg.sys; \
- done
- $(mkinstalldirs) $(DESTDIR)$(pkgdatadir)/charsets
- $(INSTALL_DATA) $(srcdir)/errmsg-utf8.txt \
- $(DESTDIR)$(pkgdatadir)/errmsg-utf8.txt; \
- $(INSTALL_DATA) $(srcdir)/charsets/README $(DESTDIR)$(pkgdatadir)/charsets/README
- $(INSTALL_DATA) $(srcdir)/charsets/*.xml $(DESTDIR)$(pkgdatadir)/charsets
-
-# FIXME maybe shouldn't remove, could be needed by other installation?
-uninstall-local:
- @RM@ -f -r $(DESTDIR)$(pkgdatadir)
-
-distclean-local:
- @RM@ -f */errmsg.sys
-
-# Do nothing
-link_sources:
diff --git a/sql/share/charsets/cp1251.xml b/sql/share/charsets/cp1251.xml
index b80db9f8ec0..06ba8a5a4b9 100644
--- a/sql/share/charsets/cp1251.xml
+++ b/sql/share/charsets/cp1251.xml
@@ -98,7 +98,7 @@
0050 0051 0052 0053 0054 0055 0056 0057 0058 0059 005A 005B 005C 005D 005E 005F
0060 0061 0062 0063 0064 0065 0066 0067 0068 0069 006A 006B 006C 006D 006E 006F
0070 0071 0072 0073 0074 0075 0076 0077 0078 0079 007A 007B 007C 007D 007E 007F
- 0402 0403 201A 0453 201E 2026 2020 2021 0000 2030 0409 2039 040A 040C 040B 040F
+ 0402 0403 201A 0453 201E 2026 2020 2021 20AC 2030 0409 2039 040A 040C 040B 040F
0452 2018 2019 201C 201D 2022 2013 2014 0000 2122 0459 203A 045A 045C 045B 045F
00A0 040E 045E 0408 00A4 0490 00A6 00A7 0401 00A9 0404 00AB 00AC 00AD 00AE 0407
00B0 00B1 0406 0456 0491 00B5 00B6 00B7 0451 2116 0454 00BB 0458 0405 0455 0457
diff --git a/sql/share/charsets/languages.html b/sql/share/charsets/languages.html
index 6d1a8aafc5c..76af973113e 100644
--- a/sql/share/charsets/languages.html
+++ b/sql/share/charsets/languages.html
@@ -1,4 +1,20 @@
#!/bin/sh
+
+# Copyright (C) 2003 MySQL AB
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; version 2 of the License.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
#<pre>
(
echo "DROP TABLE lang;"
diff --git a/sql/share/errmsg-utf8.txt b/sql/share/errmsg-utf8.txt
index 06f8ca5e507..c86451b89e9 100644
--- a/sql/share/errmsg-utf8.txt
+++ b/sql/share/errmsg-utf8.txt
@@ -897,7 +897,7 @@ ER_OUT_OF_SORTMEMORY HY001 S1001
cze "M-Bálo paměti pro třídění. Zvyšte velikost třídícího bufferu"
dan "Ikke mere sorteringshukommelse. Øg sorteringshukommelse (sort buffer size) for serveren"
nla "Geen geheugen om te sorteren. Verhoog de server sort buffer size"
- eng "Out of sort memory; increase server sort buffer size"
+ eng "Out of sort memory, consider increasing server sort buffer size"
jps "Out of sort memory. sort buffer size が足りないようです.",
est "Mälu sai sorteerimisel otsa. Suurenda MySQL-i sorteerimispuhvrit"
fre "Manque de mémoire pour le tri. Augmentez-la."
@@ -907,10 +907,10 @@ ER_OUT_OF_SORTMEMORY HY001 S1001
ita "Memoria per gli ordinamenti esaurita. Incrementare il 'sort_buffer' al demone"
jpn "Out of sort memory. sort buffer size が足りないようです."
kor "Out of sort memory. daemon sort buffer의 크기를 증가시키세요"
- nor "Ikke mer sorteringsminne. Øk sorteringsminnet (sort buffer size) for tjenesten"
- norwegian-ny "Ikkje meir sorteringsminne. Auk sorteringsminnet (sorteringsbffer storleik) for tenesten"
+ nor "Ikke mer sorteringsminne. Vurder å øke sorteringsminnet (sort buffer size) for tjenesten"
+ norwegian-ny "Ikkje meir sorteringsminne. Vurder å auke sorteringsminnet (sorteringsbuffer storleik) for tenesten"
pol "Zbyt mało pamięci dla sortowania. Zwiększ wielko?ć bufora demona dla sortowania"
- por "Sem memória para ordenação. Aumente tamanho do 'buffer' de ordenação"
+ por "Não há memória suficiente para ordenação. Considere aumentar o tamanho do retentor (buffer) de ordenação."
rum "Out of memory pentru sortare. Largeste marimea buffer-ului pentru sortare in daemon (sort buffer size)"
rus "Недостаточно памяти для сортировки. Увеличьте размер буфера сортировки на сервере"
serbian "Nema memorije za sortiranje. Povećajte veličinu sort buffer-a MySQL server-u"
@@ -6152,7 +6152,7 @@ ER_WARN_ENGINE_TRANSACTION_ROLLBACK
ER_SLAVE_HEARTBEAT_FAILURE
eng "Unexpected master's heartbeat data: %s"
ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE
- eng "The requested value for the heartbeat period %s %s"
+ eng "The requested value for the heartbeat period is either negative or exceeds the maximum allowed (%s seconds)."
ER_NDB_REPLICATION_SCHEMA_ERROR
eng "Bad schema for mysql.ndb_replication table. Message: %-.64s"
@@ -6347,6 +6347,74 @@ ER_FAILED_READ_FROM_PAR_FILE
eng "Failed to read from the .par file"
swe "Misslyckades läsa från .par filen"
+ER_VALUES_IS_NOT_INT_TYPE_ERROR
+ eng "VALUES value for partition '%-.64s' must have type INT"
+ swe "Värden i VALUES för partition '%-.64s' måste ha typen INT"
+
+ER_ACCESS_DENIED_NO_PASSWORD_ERROR 28000
+ cze "P-Břístup pro uživatele '%-.48s'@'%-.64s'"
+ dan "Adgang nægtet bruger: '%-.48s'@'%-.64s'"
+ nla "Toegang geweigerd voor gebruiker: '%-.48s'@'%-.64s'"
+ eng "Access denied for user '%-.48s'@'%-.64s'"
+ est "Ligipääs keelatud kasutajale '%-.48s'@'%-.64s'"
+ fre "Accès refusé pour l'utilisateur: '%-.48s'@'@%-.64s'"
+ ger "Benutzer '%-.48s'@'%-.64s' hat keine Zugriffsberechtigung"
+ greek "Δεν επιτέρεται η πρόσβαση στο χρήστη: '%-.48s'@'%-.64s'"
+ hun "A(z) '%-.48s'@'%-.64s' felhasznalo szamara tiltott eleres."
+ ita "Accesso non consentito per l'utente: '%-.48s'@'%-.64s'"
+ kor "'%-.48s'@'%-.64s' 사용자는 접근이 거부 되었습니다."
+ nor "Tilgang nektet for bruker: '%-.48s'@'%-.64s'"
+ norwegian-ny "Tilgang ikke tillate for brukar: '%-.48s'@'%-.64s'"
+ por "Acesso negado para o usuário '%-.48s'@'%-.64s'"
+ rum "Acces interzis pentru utilizatorul: '%-.48s'@'%-.64s'"
+ rus "Доступ закрыт для пользователя '%-.48s'@'%-.64s'"
+ serbian "Pristup je zabranjen korisniku '%-.48s'@'%-.64s'"
+ slo "Zakázaný prístup pre užívateľa: '%-.48s'@'%-.64s'"
+ spa "Acceso negado para usuario: '%-.48s'@'%-.64s'"
+ swe "Användare '%-.48s'@'%-.64s' är ej berättigad att logga in"
+ ukr "Доступ заборонено для користувача: '%-.48s'@'%-.64s'"
+
+ER_SET_PASSWORD_AUTH_PLUGIN
+ eng "SET PASSWORD has no significance for users authenticating via plugins"
+
+ER_GRANT_PLUGIN_USER_EXISTS
+ eng "GRANT with IDENTIFIED WITH is illegal because the user %-.*s already exists"
+
+ER_TRUNCATE_ILLEGAL_FK 42000
+ eng "Cannot truncate a table referenced in a foreign key constraint (%.192s)"
+
+ER_PLUGIN_IS_PERMANENT
+ eng "Plugin '%s' is force_plus_permanent and can not be unloaded"
+
+ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN
+ eng "The requested value for the heartbeat period is less than 1 millisecond. The value is reset to 0, meaning that heartbeating will effectively be disabled."
+
+ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX
+ eng "The requested value for the heartbeat period exceeds the value of `slave_net_timeout' seconds. A sensible value for the period should be less than the timeout."
+
+ER_STMT_CACHE_FULL
+ eng "Multi-row statements required more than 'max_binlog_stmt_cache_size' bytes of storage; increase this mysqld variable and try again"
+
+ER_MULTI_UPDATE_KEY_CONFLICT
+ eng "Primary key/partition key update is not allowed since the table is updated both as '%-.192s' and '%-.192s'."
+
+# When translating this error message make sure to include "ALTER TABLE" in the
+# message as mysqlcheck parses the error message looking for ALTER TABLE.
+ER_TABLE_NEEDS_REBUILD
+ eng "Table rebuild required. Please do \"ALTER TABLE `%-.32s` FORCE\" or dump/reload to fix it!"
+
+WARN_OPTION_BELOW_LIMIT
+ eng "The value of '%s' should be no less than the value of '%s'"
+
+ER_INDEX_COLUMN_TOO_LONG
+ eng "Index column size too large. The maximum column size is %lu bytes."
+
+ER_ERROR_IN_TRIGGER_BODY
+ eng "Trigger '%-.64s' has an error in its body: '%-.256s'"
+
+ER_ERROR_IN_UNKNOWN_TRIGGER_BODY
+ eng "Unknown trigger has an error in its body: '%-.256s'"
+
ER_VCOL_BASED_ON_VCOL
eng "A computed column cannot be based on a computed column"
ER_VIRTUAL_COLUMN_FUNCTION_IS_NOT_ALLOWED
@@ -6372,4 +6440,3 @@ ER_UNKNOWN_OPTION
eng "Unknown option '%-.64s'"
ER_BAD_OPTION_VALUE
eng "Incorrect value '%-.64s' for option '%-.64s'"
-
diff --git a/sql/slave.cc b/sql/slave.cc
index ec693964726..1d99d2b606b 100644
--- a/sql/slave.cc
+++ b/sql/slave.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2003 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (C) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -113,7 +113,7 @@ static const char *reconnect_messages[SLAVE_RECON_ACT_MAX][SLAVE_RECON_MSG_MAX]=
registration on master",
"Reconnecting after a failed registration on master",
"failed registering on master, reconnecting to try again, \
-log '%s' at postion %s",
+log '%s' at position %s",
"COM_REGISTER_SLAVE",
"Slave I/O thread killed during or after reconnect"
},
@@ -121,7 +121,7 @@ log '%s' at postion %s",
"Waiting to reconnect after a failed binlog dump request",
"Slave I/O thread killed while retrying master dump",
"Reconnecting after a failed binlog dump request",
- "failed dump request, reconnecting to try again, log '%s' at postion %s",
+ "failed dump request, reconnecting to try again, log '%s' at position %s",
"COM_BINLOG_DUMP",
"Slave I/O thread killed during or after reconnect"
},
@@ -130,7 +130,7 @@ log '%s' at postion %s",
"Slave I/O thread killed while waiting to reconnect after a failed read",
"Reconnecting after a failed master event read",
"Slave I/O thread: Failed reading log event, reconnecting to retry, \
-log '%s' at postion %s",
+log '%s' at position %s",
"",
"Slave I/O thread killed during or after a reconnect done to recover from \
failed read"
@@ -504,53 +504,54 @@ int terminate_slave_threads(Master_info* mi,int thread_mask,bool skip_lock)
mysql_mutex_t *sql_lock = &mi->rli.run_lock, *io_lock = &mi->run_lock;
mysql_mutex_t *log_lock= mi->rli.relay_log.get_log_lock();
- if (thread_mask & (SLAVE_IO|SLAVE_FORCE_ALL))
+ if (thread_mask & (SLAVE_SQL|SLAVE_FORCE_ALL))
{
- DBUG_PRINT("info",("Terminating IO thread"));
- mi->abort_slave=1;
- if ((error=terminate_slave_thread(mi->io_thd, io_lock,
- &mi->stop_cond,
- &mi->slave_running,
+ DBUG_PRINT("info",("Terminating SQL thread"));
+ mi->rli.abort_slave=1;
+ if ((error=terminate_slave_thread(mi->rli.sql_thd, sql_lock,
+ &mi->rli.stop_cond,
+ &mi->rli.slave_running,
skip_lock)) &&
!force_all)
DBUG_RETURN(error);
mysql_mutex_lock(log_lock);
- DBUG_PRINT("info",("Flushing relay log and master info file."));
+ DBUG_PRINT("info",("Flushing relay-log info file."));
if (current_thd)
- thd_proc_info(current_thd, "Flushing relay log and master info files.");
- if (flush_master_info(mi, TRUE, FALSE))
- DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS);
-
- if (my_sync(mi->rli.relay_log.get_log_file()->file, MYF(MY_WME)))
+ thd_proc_info(current_thd, "Flushing relay-log info file.");
+ if (flush_relay_log_info(&mi->rli))
DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS);
-
- if (my_sync(mi->fd, MYF(MY_WME)))
+
+ if (my_sync(mi->rli.info_fd, MYF(MY_WME)))
DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS);
mysql_mutex_unlock(log_lock);
}
- if (thread_mask & (SLAVE_SQL|SLAVE_FORCE_ALL))
+ if (thread_mask & (SLAVE_IO|SLAVE_FORCE_ALL))
{
- DBUG_PRINT("info",("Terminating SQL thread"));
- mi->rli.abort_slave=1;
- if ((error=terminate_slave_thread(mi->rli.sql_thd, sql_lock,
- &mi->rli.stop_cond,
- &mi->rli.slave_running,
+ DBUG_PRINT("info",("Terminating IO thread"));
+ mi->abort_slave=1;
+ if ((error=terminate_slave_thread(mi->io_thd, io_lock,
+ &mi->stop_cond,
+ &mi->slave_running,
skip_lock)) &&
!force_all)
DBUG_RETURN(error);
mysql_mutex_lock(log_lock);
- DBUG_PRINT("info",("Flushing relay-log info file."));
+ DBUG_PRINT("info",("Flushing relay log and master info file."));
if (current_thd)
- thd_proc_info(current_thd, "Flushing relay-log info file.");
- if (flush_relay_log_info(&mi->rli))
+ thd_proc_info(current_thd, "Flushing relay log and master info files.");
+ if (flush_master_info(mi, TRUE, FALSE))
DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS);
-
- if (my_sync(mi->rli.info_fd, MYF(MY_WME)))
+
+ if (mi->rli.relay_log.is_open() &&
+ my_sync(mi->rli.relay_log.get_log_file()->file, MYF(MY_WME)))
+ DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS);
+
+ if (my_sync(mi->fd, MYF(MY_WME)))
DBUG_RETURN(ER_ERROR_DURING_FLUSH_LOGS);
mysql_mutex_unlock(log_lock);
@@ -721,9 +722,17 @@ int start_slave_thread(
while (start_id == *slave_run_id)
{
DBUG_PRINT("sleep",("Waiting for slave thread to start"));
- const char* old_msg = thd->enter_cond(start_cond,cond_lock,
- "Waiting for slave thread to start");
- mysql_cond_wait(start_cond, cond_lock);
+ const char *old_msg= thd->enter_cond(start_cond, cond_lock,
+ "Waiting for slave thread to start");
+ /*
+ It is not sufficient to test this at loop bottom. We must test
+ it after registering the mutex in enter_cond(). If the kill
+ happens after testing of thd->killed and before the mutex is
+ registered, we could otherwise go waiting though thd->killed is
+ set.
+ */
+ if (!thd->killed)
+ mysql_cond_wait(start_cond, cond_lock);
thd->exit_cond(old_msg);
mysql_mutex_lock(cond_lock); // re-acquire it as exit_cond() released
if (thd->killed)
@@ -881,21 +890,31 @@ static bool sql_slave_killed(THD* thd, Relay_log_info* rli)
DBUG_ASSERT(rli->slave_running == 1);// tracking buffer overrun
if (abort_loop || thd->killed || rli->abort_slave)
{
- if (thd->transaction.all.modified_non_trans_table && rli->is_in_group())
+ /*
+ The transaction should always be binlogged if OPTION_KEEP_LOG is set
+ (it implies that something can not be rolled back). And such case
+ should be regarded similarly as modifing a non-transactional table
+ because retrying of the transaction will lead to an error or inconsistency
+ as well.
+ Example: OPTION_KEEP_LOG is set if a temporary table is created or dropped.
+ */
+ if ((thd->transaction.all.modified_non_trans_table ||
+ (thd->variables.option_bits & OPTION_KEEP_LOG))
+ && rli->is_in_group())
{
char msg_stopped[]=
- "... The slave SQL is stopped, leaving the current group "
- "of events unfinished with a non-transaction table changed. "
- "If the group consists solely of Row-based events, you can try "
- "restarting the slave with --slave-exec-mode=IDEMPOTENT, which "
+ "... Slave SQL Thread stopped with incomplete event group "
+ "having non-transactional changes. "
+ "If the group consists solely of row-based events, you can try "
+ "to restart the slave with --slave-exec-mode=IDEMPOTENT, which "
"ignores duplicate key, key not found, and similar errors (see "
"documentation for details).";
if (rli->abort_slave)
{
- DBUG_PRINT("info", ("Slave SQL thread is being stopped in the middle of"
- " a group having updated a non-trans table, giving"
- " it some grace period"));
+ DBUG_PRINT("info", ("Request to stop slave SQL Thread received while "
+ "applying a group that has non-transactional "
+ "changes; waiting for completion of the group ... "));
/*
Slave sql thread shutdown in face of unfinished group modified
@@ -919,9 +938,9 @@ static bool sql_slave_killed(THD* thd, Relay_log_info* rli)
if (ret == 0)
{
rli->report(WARNING_LEVEL, 0,
- "slave SQL thread is being stopped in the middle "
- "of applying of a group having updated a non-transaction "
- "table; waiting for the group completion ... ");
+ "Request to stop slave SQL Thread received while "
+ "applying a group that has non-transactional "
+ "changes; waiting for completion of the group ... ");
}
else
{
@@ -2512,8 +2531,7 @@ static int exec_relay_log_event(THD* thd, Relay_log_info* rli)
if (slave_trans_retries)
{
- int temp_err;
- LINT_INIT(temp_err);
+ int UNINIT_VAR(temp_err);
if (exec_res && (temp_err= has_temporary_error(thd)))
{
const char *errmsg;
@@ -2544,9 +2562,7 @@ static int exec_relay_log_event(THD* thd, Relay_log_info* rli)
else
{
exec_res= 0;
- trans_rollback(thd);
- close_thread_tables(thd);
- thd->mdl_context.release_transactional_locks();
+ rli->cleanup_context(thd, 1);
/* chance for concurrent connection to get more locks */
safe_sleep(thd, min(rli->trans_retries, MAX_SLAVE_RETRY_PAUSE),
(CHECK_KILLED_FUNC)sql_slave_killed, (void*)rli);
@@ -3013,7 +3029,7 @@ err:
sql_print_information("Slave I/O thread exiting, read up to log '%s', position %s",
IO_RPL_LOG_NAME, llstr(mi->master_log_pos,llbuff));
RUN_HOOK(binlog_relay_io, thread_stop, (thd, mi));
- thd->set_query(NULL, 0);
+ thd->reset_query();
thd->reset_db(NULL, 0);
if (mysql)
{
@@ -3396,6 +3412,7 @@ the slave SQL thread with \"SLAVE START\". We stopped at log \
request is detected only by the present function, not by events), so we
must "proactively" clear playgrounds:
*/
+ thd->clear_error();
rli->cleanup_context(thd, 1);
/*
Some extra safety, which should not been needed (normally, event deletion
@@ -3403,7 +3420,7 @@ the slave SQL thread with \"SLAVE START\". We stopped at log \
variables is supposed to set them to 0 before terminating)).
*/
thd->catalog= 0;
- thd->set_query(NULL, 0);
+ thd->reset_query();
thd->reset_db(NULL, 0);
thd_proc_info(thd, "Waiting for slave mutex on exit");
mysql_mutex_lock(&rli->run_lock);
@@ -3626,8 +3643,7 @@ static int process_io_rotate(Master_info *mi, Rotate_log_event *rev)
Rotate the relay log makes binlog format detection easier (at next slave
start or mysqlbinlog)
*/
- rotate_relay_log(mi); /* will take the right mutexes */
- DBUG_RETURN(0);
+ DBUG_RETURN(rotate_relay_log(mi) /* will take the right mutexes */);
}
/*
@@ -4739,12 +4755,66 @@ static Log_event* next_event(Relay_log_info* rli)
DBUG_ASSERT(rli->cur_log_fd == -1);
/*
- Read pointer has to be at the start since we are the only
- reader.
- We must keep the LOCK_log to read the 4 first bytes, as this is a hot
- log (same as when we call read_log_event() above: for a hot log we
- take the mutex).
+ When the SQL thread is [stopped and] (re)started the
+ following may happen:
+
+ 1. Log was hot at stop time and remains hot at restart
+
+ SQL thread reads again from hot_log (SQL thread was
+ reading from the active log when it was stopped and the
+ very same log is still active on SQL thread restart).
+
+ In this case, my_b_seek is performed on cur_log, while
+ cur_log points to relay_log.get_log_file();
+
+ 2. Log was hot at stop time but got cold before restart
+
+ The log was hot when SQL thread stopped, but it is not
+ anymore when the SQL thread restarts.
+
+ In this case, the SQL thread reopens the log, using
+ cache_buf, ie, cur_log points to &cache_buf, and thence
+ its coordinates are reset.
+
+ 3. Log was already cold at stop time
+
+ The log was not hot when the SQL thread stopped, and, of
+ course, it will not be hot when it restarts.
+
+ In this case, the SQL thread opens the cold log again,
+ using cache_buf, ie, cur_log points to &cache_buf, and
+ thence its coordinates are reset.
+
+ 4. Log was hot at stop time, DBA changes to previous cold
+ log and restarts SQL thread
+
+ The log was hot when the SQL thread was stopped, but the
+ user changed the coordinates of the SQL thread to
+ restart from a previous cold log.
+
+ In this case, at start time, cur_log points to a cold
+ log, opened using &cache_buf as cache, and coordinates
+ are reset. However, as it moves on to the next logs, it
+ will eventually reach the hot log. If the hot log is the
+ same at the time the SQL thread was stopped, then
+ coordinates were not reset - the cur_log will point to
+ relay_log.get_log_file(), and not a freshly opened
+ IO_CACHE through cache_buf. For this reason we need to
+ deploy a my_b_seek before calling check_binlog_magic at
+ this point of the code (see: BUG#55263 for more
+ details).
+
+ NOTES:
+ - We must keep the LOCK_log to read the 4 first bytes, as
+ this is a hot log (same as when we call read_log_event()
+ above: for a hot log we take the mutex).
+
+ - Because of scenario #4 above, we need to have a
+ my_b_seek here. Otherwise, we might hit the assertion
+ inside check_binlog_magic.
*/
+
+ my_b_seek(cur_log, (my_off_t) 0);
if (check_binlog_magic(cur_log,&errmsg))
{
if (!hot_log)
@@ -4811,12 +4881,13 @@ err:
is void).
*/
-void rotate_relay_log(Master_info* mi)
+int rotate_relay_log(Master_info* mi)
{
DBUG_ENTER("rotate_relay_log");
Relay_log_info* rli= &mi->rli;
+ int error= 0;
- DBUG_EXECUTE_IF("crash_before_rotate_relaylog", abort(););
+ DBUG_EXECUTE_IF("crash_before_rotate_relaylog", DBUG_SUICIDE(););
/*
We need to test inited because otherwise, new_file() will attempt to lock
@@ -4829,7 +4900,8 @@ void rotate_relay_log(Master_info* mi)
}
/* If the relay log is closed, new_file() will do nothing. */
- rli->relay_log.new_file();
+ if ((error= rli->relay_log.new_file()))
+ goto end;
/*
We harvest now, because otherwise BIN_LOG_HEADER_SIZE will not immediately
@@ -4846,7 +4918,7 @@ void rotate_relay_log(Master_info* mi)
*/
rli->relay_log.harvest_bytes_written(&rli->log_space_total);
end:
- DBUG_VOID_RETURN;
+ DBUG_RETURN(error);
}
diff --git a/sql/slave.h b/sql/slave.h
index 737e23c6cdc..814d52f84fd 100644
--- a/sql/slave.h
+++ b/sql/slave.h
@@ -211,7 +211,7 @@ int purge_relay_logs(Relay_log_info* rli, THD *thd, bool just_reset,
const char** errmsg);
void set_slave_thread_options(THD* thd);
void set_slave_thread_default_charset(THD *thd, Relay_log_info const *rli);
-void rotate_relay_log(Master_info* mi);
+int rotate_relay_log(Master_info* mi);
int apply_event_and_update_pos(Log_event* ev, THD* thd, Relay_log_info* rli);
pthread_handler_t handle_slave_io(void *arg);
diff --git a/sql/sp.cc b/sql/sp.cc
index e6cf43c73a8..283db3539c9 100644
--- a/sql/sp.cc
+++ b/sql/sp.cc
@@ -27,7 +27,7 @@
#include "sql_acl.h" // SUPER_ACL
#include "sp_head.h"
#include "sp_cache.h"
-#include "lock.h" // lock_routine_name
+#include "lock.h" // lock_object_name
#include <my_user.h>
@@ -441,7 +441,7 @@ static TABLE *open_proc_table_for_update(THD *thd)
{
TABLE_LIST table_list;
TABLE *table;
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
DBUG_ENTER("open_proc_table_for_update");
table_list.init_one_table("mysql", 5, "proc", 4, "proc", TL_WRITE);
@@ -924,6 +924,8 @@ sp_create_routine(THD *thd, int type, sp_head *sp)
TABLE *table;
char definer[USER_HOST_BUFF_SIZE];
ulong saved_mode= thd->variables.sql_mode;
+ MDL_key::enum_mdl_namespace mdl_type= type == TYPE_ENUM_FUNCTION ?
+ MDL_key::FUNCTION : MDL_key::PROCEDURE;
CHARSET_INFO *db_cs= get_default_db_collation(thd, sp->m_db.str);
@@ -943,8 +945,7 @@ sp_create_routine(THD *thd, int type, sp_head *sp)
type == TYPE_ENUM_FUNCTION);
/* Grab an exclusive MDL lock. */
- if (lock_routine_name(thd, type == TYPE_ENUM_FUNCTION,
- sp->m_db.str, sp->m_name.str))
+ if (lock_object_name(thd, mdl_type, sp->m_db.str, sp->m_name.str))
DBUG_RETURN(SP_OPEN_TABLE_FAILED);
/* Reset sql_mode during data dictionary operations. */
@@ -1192,6 +1193,8 @@ sp_drop_routine(THD *thd, int type, sp_name *name)
TABLE *table;
int ret;
bool save_binlog_row_based;
+ MDL_key::enum_mdl_namespace mdl_type= type == TYPE_ENUM_FUNCTION ?
+ MDL_key::FUNCTION : MDL_key::PROCEDURE;
DBUG_ENTER("sp_drop_routine");
DBUG_PRINT("enter", ("type: %d name: %.*s",
type, (int) name->m_name.length, name->m_name.str));
@@ -1200,8 +1203,7 @@ sp_drop_routine(THD *thd, int type, sp_name *name)
type == TYPE_ENUM_FUNCTION);
/* Grab an exclusive MDL lock. */
- if (lock_routine_name(thd, type == TYPE_ENUM_FUNCTION,
- name->m_db.str, name->m_name.str))
+ if (lock_object_name(thd, mdl_type, name->m_db.str, name->m_name.str))
DBUG_RETURN(SP_DELETE_ROW_FAILED);
if (!(table= open_proc_table_for_update(thd)))
@@ -1272,6 +1274,8 @@ sp_update_routine(THD *thd, int type, sp_name *name, st_sp_chistics *chistics)
TABLE *table;
int ret;
bool save_binlog_row_based;
+ MDL_key::enum_mdl_namespace mdl_type= type == TYPE_ENUM_FUNCTION ?
+ MDL_key::FUNCTION : MDL_key::PROCEDURE;
DBUG_ENTER("sp_update_routine");
DBUG_PRINT("enter", ("type: %d name: %.*s",
type, (int) name->m_name.length, name->m_name.str));
@@ -1280,8 +1284,7 @@ sp_update_routine(THD *thd, int type, sp_name *name, st_sp_chistics *chistics)
type == TYPE_ENUM_FUNCTION);
/* Grab an exclusive MDL lock. */
- if (lock_routine_name(thd, type == TYPE_ENUM_FUNCTION,
- name->m_db.str, name->m_name.str))
+ if (lock_object_name(thd, mdl_type, name->m_db.str, name->m_name.str))
DBUG_RETURN(SP_OPEN_TABLE_FAILED);
if (!(table= open_proc_table_for_update(thd)))
@@ -1357,6 +1360,108 @@ err:
/**
+ This internal handler is used to trap errors from opening mysql.proc.
+*/
+
+class Lock_db_routines_error_handler : public Internal_error_handler
+{
+public:
+ bool handle_condition(THD *thd,
+ uint sql_errno,
+ const char* sqlstate,
+ MYSQL_ERROR::enum_warning_level level,
+ const char* msg,
+ MYSQL_ERROR ** cond_hdl)
+ {
+ if (sql_errno == ER_NO_SUCH_TABLE ||
+ sql_errno == ER_CANNOT_LOAD_FROM_TABLE ||
+ sql_errno == ER_COL_COUNT_DOESNT_MATCH_PLEASE_UPDATE ||
+ sql_errno == ER_COL_COUNT_DOESNT_MATCH_CORRUPTED)
+ return true;
+ return false;
+ }
+};
+
+
+/**
+ Acquires exclusive metadata lock on all stored routines in the
+ given database.
+
+ @note Will also return false (=success) if mysql.proc can't be opened
+ or is outdated. This allows DROP DATABASE to continue in these
+ cases.
+ */
+
+bool lock_db_routines(THD *thd, char *db)
+{
+ TABLE *table;
+ uint key_len;
+ int nxtres= 0;
+ Open_tables_backup open_tables_state_backup;
+ MDL_request_list mdl_requests;
+ Lock_db_routines_error_handler err_handler;
+ DBUG_ENTER("lock_db_routines");
+
+ /*
+ mysql.proc will be re-opened during deletion, so we can ignore
+ errors when opening the table here. The error handler is
+ used to avoid getting the same warning twice.
+ */
+ thd->push_internal_handler(&err_handler);
+ table= open_proc_table_for_read(thd, &open_tables_state_backup);
+ thd->pop_internal_handler();
+ if (!table)
+ {
+ /*
+ DROP DATABASE should not fail even if mysql.proc does not exist
+ or is outdated. We therefore only abort mysql_rm_db() if we
+ have errors not handled by the error handler.
+ */
+ DBUG_RETURN(thd->is_error() || thd->killed);
+ }
+
+ table->field[MYSQL_PROC_FIELD_DB]->store(db, strlen(db), system_charset_info);
+ key_len= table->key_info->key_part[0].store_length;
+ table->file->ha_index_init(0, 1);
+
+ if (! table->file->index_read_map(table->record[0],
+ table->field[MYSQL_PROC_FIELD_DB]->ptr,
+ (key_part_map)1, HA_READ_KEY_EXACT))
+ {
+ do
+ {
+ char *sp_name= get_field(thd->mem_root,
+ table->field[MYSQL_PROC_FIELD_NAME]);
+ longlong sp_type= table->field[MYSQL_PROC_MYSQL_TYPE]->val_int();
+ MDL_request *mdl_request= new (thd->mem_root) MDL_request;
+ mdl_request->init(sp_type == TYPE_ENUM_FUNCTION ?
+ MDL_key::FUNCTION : MDL_key::PROCEDURE,
+ db, sp_name, MDL_EXCLUSIVE, MDL_TRANSACTION);
+ mdl_requests.push_front(mdl_request);
+ } while (! (nxtres= table->file->index_next_same(table->record[0],
+ table->field[MYSQL_PROC_FIELD_DB]->ptr,
+ key_len)));
+ }
+ table->file->ha_index_end();
+ if (nxtres != 0 && nxtres != HA_ERR_END_OF_FILE)
+ {
+ table->file->print_error(nxtres, MYF(0));
+ close_system_tables(thd, &open_tables_state_backup);
+ DBUG_RETURN(true);
+ }
+ close_system_tables(thd, &open_tables_state_backup);
+
+ /* We should already hold a global IX lock and a schema X lock. */
+ DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::GLOBAL, "", "",
+ MDL_INTENTION_EXCLUSIVE) &&
+ thd->mdl_context.is_lock_owner(MDL_key::SCHEMA, db, "",
+ MDL_EXCLUSIVE));
+ DBUG_RETURN(thd->mdl_context.acquire_locks(&mdl_requests,
+ thd->variables.lock_wait_timeout));
+}
+
+
+/**
Drop all routines in database 'db'
@note Close the thread tables, the calling code might want to
@@ -1369,7 +1474,7 @@ sp_drop_db_routines(THD *thd, char *db)
TABLE *table;
int ret;
uint key_len;
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
uchar keybuf[MAX_KEY_LENGTH];
DBUG_ENTER("sp_drop_db_routines");
DBUG_PRINT("enter", ("db: %s", db));
@@ -1640,38 +1745,6 @@ sp_exist_routines(THD *thd, TABLE_LIST *routines, bool any)
}
-/**
- Check if a routine exists in the mysql.proc table, without actually
- parsing the definition. (Used for dropping).
-
- @param thd thread context
- @param name name of procedure
-
- @retval
- 0 Success
- @retval
- non-0 Error; SP_OPEN_TABLE_FAILED or SP_KEY_NOT_FOUND
-*/
-
-int
-sp_routine_exists_in_table(THD *thd, int type, sp_name *name)
-{
- TABLE *table;
- int ret;
- Open_tables_backup open_tables_state_backup;
-
- if (!(table= open_proc_table_for_read(thd, &open_tables_state_backup)))
- ret= SP_OPEN_TABLE_FAILED;
- else
- {
- if ((ret= db_find_routine_aux(thd, type, name, table)) != SP_OK)
- ret= SP_KEY_NOT_FOUND;
- close_system_tables(thd, &open_tables_state_backup);
- }
- return ret;
-}
-
-
extern "C" uchar* sp_sroutine_key(const uchar *ptr, size_t *plen,
my_bool first)
{
@@ -1727,7 +1800,7 @@ bool sp_add_used_routine(Query_tables_list *prelocking_ctx, Query_arena *arena,
(Sroutine_hash_entry *)arena->alloc(sizeof(Sroutine_hash_entry));
if (!rn) // OOM. Error will be reported using fatal_error().
return FALSE;
- rn->mdl_request.init(key, MDL_SHARED);
+ rn->mdl_request.init(key, MDL_SHARED, MDL_TRANSACTION);
if (my_hash_insert(&prelocking_ctx->sroutines, (uchar *)rn))
return FALSE;
prelocking_ctx->sroutines_list.link_in_list(rn, &rn->next);
diff --git a/sql/sp.h b/sql/sp.h
index 10e70261b86..68c45768857 100644
--- a/sql/sp.h
+++ b/sql/sp.h
@@ -84,6 +84,18 @@ enum
int
sp_drop_db_routines(THD *thd, char *db);
+/**
+ Acquires exclusive metadata lock on all stored routines in the
+ given database.
+
+ @param thd Thread handler
+ @param db Database name
+
+ @retval false Success
+ @retval true Failure
+ */
+bool lock_db_routines(THD *thd, char *db);
+
sp_head *
sp_find_routine(THD *thd, int type, sp_name *name,
sp_cache **cp, bool cache_only);
@@ -100,9 +112,6 @@ sp_cache_routine(THD *thd, int type, sp_name *name,
bool
sp_exist_routines(THD *thd, TABLE_LIST *procs, bool any);
-int
-sp_routine_exists_in_table(THD *thd, int type, sp_name *name);
-
bool
sp_show_create_routine(THD *thd, int type, sp_name *name);
diff --git a/sql/sp_head.cc b/sql/sp_head.cc
index 750ddee49c3..df258d49c0a 100644
--- a/sql/sp_head.cc
+++ b/sql/sp_head.cc
@@ -1,4 +1,4 @@
-/* Copyright 2002-2008 MySQL AB, 2008-2010 Sun Microsystems, Inc.
+/* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,7 +11,7 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "my_global.h" /* NO_EMBEDDED_ACCESS_CHECKS */
#include "sql_priv.h"
@@ -237,7 +237,6 @@ sp_get_flags_for_command(LEX *lex)
case SQLCOM_SHOW_EVENTS:
case SQLCOM_SHOW_KEYS:
case SQLCOM_SHOW_MASTER_STAT:
- case SQLCOM_SHOW_NEW_MASTER:
case SQLCOM_SHOW_OPEN_TABLES:
case SQLCOM_SHOW_PRIVILEGES:
case SQLCOM_SHOW_PROCESSLIST:
@@ -551,7 +550,7 @@ sp_head::operator delete(void *ptr, size_t size) throw()
sp_head::sp_head()
- :Query_arena(&main_mem_root, INITIALIZED_FOR_SP),
+ :Query_arena(&main_mem_root, STMT_INITIALIZED_FOR_SP),
m_flags(0),
m_sp_cache_version(0),
unsafe_flags(0),
@@ -1069,7 +1068,7 @@ void sp_head::recursion_level_error(THD *thd)
if (m_type == TYPE_ENUM_PROCEDURE)
{
my_error(ER_SP_RECURSION_LIMIT, MYF(0),
- thd->variables.max_sp_recursion_depth,
+ static_cast<int>(thd->variables.max_sp_recursion_depth),
m_name.str);
}
else
@@ -1178,10 +1177,17 @@ find_handler_after_execution(THD *thd, sp_rcontext *ctx)
/**
Execute the routine. The main instruction jump loop is there.
Assume the parameters already set.
+
+ @param thd Thread context.
+ @param merge_da_on_success Flag specifying if Warning Info should be
+ propagated to the caller on Completion
+ Condition or not.
+
@todo
- Will write this SP statement into binlog separately
(TODO: consider changing the condition to "not inside event union")
+ @return Error status.
@retval
FALSE on success
@retval
@@ -1189,7 +1195,7 @@ find_handler_after_execution(THD *thd, sp_rcontext *ctx)
*/
bool
-sp_head::execute(THD *thd)
+sp_head::execute(THD *thd, bool merge_da_on_success)
{
DBUG_ENTER("sp_head::execute");
char saved_cur_db_name_buf[SAFE_NAME_LEN+1];
@@ -1204,7 +1210,7 @@ sp_head::execute(THD *thd)
Query_arena *old_arena;
/* per-instruction arena */
MEM_ROOT execute_mem_root;
- Query_arena execute_arena(&execute_mem_root, INITIALIZED_FOR_SP),
+ Query_arena execute_arena(&execute_mem_root, STMT_INITIALIZED_FOR_SP),
backup_arena;
query_id_t old_query_id;
TABLE *old_derived_tables;
@@ -1213,9 +1219,33 @@ sp_head::execute(THD *thd)
String old_packet;
Reprepare_observer *save_reprepare_observer= thd->m_reprepare_observer;
Object_creation_ctx *saved_creation_ctx;
- Warning_info *saved_warning_info, warning_info(thd->warning_info->warn_id());
+ Warning_info *saved_warning_info;
+ Warning_info warning_info(thd->warning_info->warn_id(), false);
- /* Use some extra margin for possible SP recursion and functions */
+ /*
+ Just reporting a stack overrun error
+ (@sa check_stack_overrun()) requires stack memory for error
+ message buffer. Thus, we have to put the below check
+ relatively close to the beginning of the execution stack,
+ where available stack margin is still big. As long as the check
+ has to be fairly high up the call stack, the amount of memory
+ we "book" for has to stay fairly high as well, and hence
+ not very accurate. The number below has been calculated
+ by trial and error, and reflects the amount of memory necessary
+ to execute a single stored procedure instruction, be it either
+ an SQL statement, or, heaviest of all, a CALL, which involves
+ parsing and loading of another stored procedure into the cache
+ (@sa db_load_routine() and Bug#10100).
+ At the time of measuring, a recursive SP invocation required
+ 3232 bytes of stack on 32 bit Linux, 6016 bytes on 64 bit Mac
+ and 11152 on 64 bit Solaris sparc.
+ The same with db_load_routine() required circa 7k bytes and
+ 14k bytes accordingly. Hence, here we book the stack with some
+ reasonable margin.
+
+ Reverting back to 8 * STACK_MIN_SIZE until further fix.
+ 8 * STACK_MIN_SIZE is required on some exotic platforms.
+ */
if (check_stack_overrun(thd, 8 * STACK_MIN_SIZE, (uchar*)&old_packet))
DBUG_RETURN(TRUE);
@@ -1461,10 +1491,17 @@ sp_head::execute(THD *thd)
thd->m_reprepare_observer= save_reprepare_observer;
thd->stmt_arena= old_arena;
- state= EXECUTED;
+ state= STMT_EXECUTED;
- /* Restore the caller's original warning information area. */
- saved_warning_info->merge_with_routine_info(thd, thd->warning_info);
+ /*
+ Restore the caller's original warning information area:
+ - warnings generated during trigger execution should not be
+ propagated to the caller on success;
+ - if there was an exception during execution, warning info should be
+ propagated to the caller in any case.
+ */
+ if (err_status || merge_da_on_success)
+ saved_warning_info->merge_with_routine_info(thd, thd->warning_info);
thd->warning_info= saved_warning_info;
done:
@@ -1478,7 +1515,7 @@ sp_head::execute(THD *thd)
If the DB has changed, the pointer has changed too, but the
original thd->db will then have been freed
*/
- if (cur_db_changed && !thd->killed)
+ if (cur_db_changed && thd->killed != THD::KILL_CONNECTION)
{
/*
Force switching back to the saved current database, because it may be
@@ -1612,7 +1649,7 @@ sp_head::execute_trigger(THD *thd,
sp_rcontext *nctx = NULL;
bool err_status= FALSE;
MEM_ROOT call_mem_root;
- Query_arena call_arena(&call_mem_root, Query_arena::INITIALIZED_FOR_SP);
+ Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP);
Query_arena backup_arena;
DBUG_ENTER("sp_head::execute_trigger");
@@ -1686,7 +1723,7 @@ sp_head::execute_trigger(THD *thd,
thd->spcont= nctx;
- err_status= execute(thd);
+ err_status= execute(thd, FALSE);
err_with_cleanup:
thd->restore_active_arena(&call_arena, &backup_arena);
@@ -1753,7 +1790,7 @@ sp_head::execute_function(THD *thd, Item **argp, uint argcount,
String binlog_buf(buf, sizeof(buf), &my_charset_bin);
bool err_status= FALSE;
MEM_ROOT call_mem_root;
- Query_arena call_arena(&call_mem_root, Query_arena::INITIALIZED_FOR_SP);
+ Query_arena call_arena(&call_mem_root, Query_arena::STMT_INITIALIZED_FOR_SP);
Query_arena backup_arena;
DBUG_ENTER("sp_head::execute_function");
DBUG_PRINT("info", ("function %s", m_name.str));
@@ -1903,7 +1940,7 @@ sp_head::execute_function(THD *thd, Item **argp, uint argcount,
*/
thd->set_n_backup_active_arena(&call_arena, &backup_arena);
- err_status= execute(thd);
+ err_status= execute(thd, TRUE);
thd->restore_active_arena(&call_arena, &backup_arena);
@@ -2109,6 +2146,8 @@ sp_head::execute_procedure(THD *thd, List<Item> *args)
if (! thd->in_sub_stmt && ! thd->in_multi_stmt_transaction_mode())
thd->mdl_context.release_transactional_locks();
+ else if (! thd->in_sub_stmt)
+ thd->mdl_context.release_statement_locks();
thd->rollback_item_tree_changes();
@@ -2137,7 +2176,7 @@ sp_head::execute_procedure(THD *thd, List<Item> *args)
#endif
if (!err_status)
- err_status= execute(thd);
+ err_status= execute(thd, TRUE);
if (save_log_general)
thd->variables.option_bits &= ~OPTION_LOG_OFF;
@@ -2509,9 +2548,24 @@ void
sp_head::restore_thd_mem_root(THD *thd)
{
DBUG_ENTER("sp_head::restore_thd_mem_root");
- Item *flist= free_list; // The old list
+
+ /*
+ In some cases our parser detects a syntax error and calls
+ LEX::cleanup_lex_after_parse_error() method only after
+ finishing parsing the whole routine. In such a situation
+ sp_head::restore_thd_mem_root() will be called twice - the
+ first time as part of normal parsing process and the second
+ time by cleanup_lex_after_parse_error().
+ To avoid ruining active arena/mem_root state in this case we
+ skip restoration of old arena/mem_root if this method has been
+ already called for this routine.
+ */
+ if (!m_thd)
+ DBUG_VOID_RETURN;
+
+ Item *flist= free_list; // The old list
set_query_arena(thd); // Get new free_list and mem_root
- state= INITIALIZED_FOR_SP;
+ state= STMT_INITIALIZED_FOR_SP;
DBUG_PRINT("info", ("mem_root 0x%lx returned from thd mem root 0x%lx",
(ulong) &mem_root, (ulong) &thd->mem_root));
@@ -2946,6 +3000,8 @@ sp_lex_keeper::reset_lex_and_exec_core(THD *thd, uint *nextp,
if (! thd->in_sub_stmt && ! thd->in_multi_stmt_transaction_mode())
thd->mdl_context.release_transactional_locks();
+ else if (! thd->in_sub_stmt)
+ thd->mdl_context.release_statement_locks();
}
if (m_lex->query_tables_own_last)
@@ -2973,7 +3029,7 @@ sp_lex_keeper::reset_lex_and_exec_core(THD *thd, uint *nextp,
(thd->stmt_da->sql_errno() != ER_CANT_REOPEN_TABLE &&
thd->stmt_da->sql_errno() != ER_NO_SUCH_TABLE &&
thd->stmt_da->sql_errno() != ER_UPDATE_TABLE_USED))
- thd->stmt_arena->state= Query_arena::EXECUTED;
+ thd->stmt_arena->state= Query_arena::STMT_EXECUTED;
/*
Merge here with the saved parent's values
@@ -3033,14 +3089,11 @@ int sp_instr::exec_core(THD *thd, uint *nextp)
int
sp_instr_stmt::execute(THD *thd, uint *nextp)
{
- char *query;
- uint32 query_length;
int res;
DBUG_ENTER("sp_instr_stmt::execute");
DBUG_PRINT("info", ("command: %d", m_lex_keeper.sql_command()));
- query= thd->query();
- query_length= thd->query_length();
+ const CSET_STRING query_backup= thd->query_string;
#if defined(ENABLED_PROFILING)
/* This s-p instr is profilable and will be captured. */
thd->profiling.set_query_source(m_query.str, m_query.length);
@@ -3061,7 +3114,12 @@ sp_instr_stmt::execute(THD *thd, uint *nextp)
res= m_lex_keeper.reset_lex_and_exec_core(thd, nextp, FALSE, this);
if (thd->stmt_da->is_eof())
+ {
+ /* Finalize server status flags after executing a statement. */
+ thd->update_server_status();
+
thd->protocol->end_statement();
+ }
query_cache_end_of_result(thd);
@@ -3070,7 +3128,7 @@ sp_instr_stmt::execute(THD *thd, uint *nextp)
}
else
*nextp= m_ip+1;
- thd->set_query(query, query_length);
+ thd->set_query(query_backup);
thd->query_name_consts= 0;
if (!thd->is_error())
@@ -3118,7 +3176,7 @@ sp_instr_stmt::exec_core(THD *thd, uint *nextp)
MYSQL_QUERY_EXEC_START(thd->query(),
thd->thread_id,
(char *) (thd->db ? thd->db : ""),
- thd->security_ctx->priv_user,
+ &thd->security_ctx->priv_user[0],
(char *)thd->security_ctx->host_or_ip,
3);
int res= mysql_execute_command(thd);
@@ -4141,7 +4199,8 @@ sp_head::add_used_tables_to_table_list(THD *thd,
*/
table->mdl_request.init(MDL_key::TABLE, table->db, table->table_name,
table->lock_type >= TL_WRITE_ALLOW_WRITE ?
- MDL_SHARED_WRITE : MDL_SHARED_READ);
+ MDL_SHARED_WRITE : MDL_SHARED_READ,
+ MDL_TRANSACTION);
/* Everyting else should be zeroed */
@@ -4185,7 +4244,7 @@ sp_add_to_query_tables(THD *thd, LEX *lex,
table->select_lex= lex->current_select;
table->cacheable_table= 1;
table->mdl_request.init(MDL_key::TABLE, table->db, table->table_name,
- mdl_type);
+ mdl_type, MDL_TRANSACTION);
lex->add_to_query_tables(table);
return table;
diff --git a/sql/sp_head.h b/sql/sp_head.h
index b2446c8f680..4d5e2dd95ab 100644
--- a/sql/sp_head.h
+++ b/sql/sp_head.h
@@ -42,6 +42,7 @@
#define TYPE_ENUM_FUNCTION 1
#define TYPE_ENUM_PROCEDURE 2
#define TYPE_ENUM_TRIGGER 3
+#define TYPE_ENUM_PROXY 4
Item_result
sp_map_result_type(enum enum_field_types type);
@@ -526,7 +527,7 @@ private:
HASH m_sptabs;
bool
- execute(THD *thd);
+ execute(THD *thd, bool merge_da_on_success);
/**
Perform a forward flow analysis in the generated code.
@@ -559,7 +560,7 @@ public:
/// Should give each a name or type code for debugging purposes?
sp_instr(uint ip, sp_pcontext *ctx)
- :Query_arena(0, INITIALIZED_FOR_SP), marked(0), m_ip(ip), m_ctx(ctx)
+ :Query_arena(0, STMT_INITIALIZED_FOR_SP), marked(0), m_ip(ip), m_ctx(ctx)
{}
virtual ~sp_instr()
diff --git a/sql/sp_rcontext.h b/sql/sp_rcontext.h
index e11361c3d6a..95b865be491 100644
--- a/sql/sp_rcontext.h
+++ b/sql/sp_rcontext.h
@@ -220,6 +220,7 @@ private:
during execution.
*/
bool m_return_value_set;
+
/**
TRUE if the context is created for a sub-statement.
*/
diff --git a/sql/sql_acl.cc b/sql/sql_acl.cc
index 41163ee629e..77c467b7dcf 100644
--- a/sql/sql_acl.cc
+++ b/sql/sql_acl.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2003 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -44,11 +44,11 @@
#include "transaction.h"
#include "lock.h" // MYSQL_LOCK_IGNORE_TIMEOUT
#include "records.h" // init_read_record, end_read_record
-#include "hostname.h"
-#include "sql_db.h"
-#include "sql_connect.h"
#include <sql_common.h>
#include <mysql/plugin_auth.h>
+#include "sql_connect.h"
+#include "hostname.h"
+#include "sql_db.h"
bool mysql_user_table_is_in_short_password_format= false;
@@ -180,17 +180,17 @@ static LEX_STRING old_password_plugin_name= {
/// @todo make it configurable
LEX_STRING *default_auth_plugin_name= &native_password_plugin_name;
-static plugin_ref native_password_plugin;
#ifndef NO_EMBEDDED_ACCESS_CHECKS
static plugin_ref old_password_plugin;
#endif
+static plugin_ref native_password_plugin;
/* Classes */
struct acl_host_and_ip
{
char *hostname;
- long ip,ip_mask; // Used with masked ip:s
+ long ip, ip_mask; // Used with masked ip:s
};
class ACL_ACCESS {
@@ -215,7 +215,7 @@ public:
uint hostname_length;
USER_RESOURCES user_resource;
char *user;
- uint8 salt[SCRAMBLE_LENGTH+1]; // scrambled password in binary form
+ uint8 salt[SCRAMBLE_LENGTH + 1]; // scrambled password in binary form
uint8 salt_len; // 0 - no password, 4 - 3.20, 8 - 4.0, 20 - 4.1.1
enum SSL_type ssl_type;
const char *ssl_cipher, *x509_issuer, *x509_subject;
@@ -224,7 +224,7 @@ public:
ACL_USER *copy(MEM_ROOT *root)
{
- ACL_USER *dst= (ACL_USER *)alloc_root(root, sizeof(ACL_USER));
+ ACL_USER *dst= (ACL_USER *) alloc_root(root, sizeof(ACL_USER));
if (!dst)
return 0;
*dst= *this;
@@ -237,7 +237,7 @@ public:
dst->plugin= plugin;
else
dst->plugin.str= strmake_root(root, plugin.str, plugin.length);
- dst->auth_string.str = safe_strdup_root(root, auth_string.str);
+ dst->auth_string.str= safe_strdup_root(root, auth_string.str);
dst->host.hostname= safe_strdup_root(root, host.hostname);
return dst;
}
@@ -250,7 +250,253 @@ public:
char *user,*db;
};
+
#ifndef NO_EMBEDDED_ACCESS_CHECKS
+static void update_hostname(acl_host_and_ip *host, const char *hostname);
+static ulong get_sort(uint count,...);
+static bool compare_hostname(const acl_host_and_ip *host, const char *hostname,
+ const char *ip);
+static bool show_proxy_grants (THD *thd, LEX_USER *user,
+ char *buff, size_t buffsize);
+
+class ACL_PROXY_USER :public ACL_ACCESS
+{
+ acl_host_and_ip host;
+ const char *user;
+ acl_host_and_ip proxied_host;
+ const char *proxied_user;
+ bool with_grant;
+
+ typedef enum {
+ MYSQL_PROXIES_PRIV_HOST,
+ MYSQL_PROXIES_PRIV_USER,
+ MYSQL_PROXIES_PRIV_PROXIED_HOST,
+ MYSQL_PROXIES_PRIV_PROXIED_USER,
+ MYSQL_PROXIES_PRIV_WITH_GRANT,
+ MYSQL_PROXIES_PRIV_GRANTOR,
+ MYSQL_PROXIES_PRIV_TIMESTAMP } old_acl_proxy_users;
+public:
+ ACL_PROXY_USER () {};
+
+ void init(const char *host_arg, const char *user_arg,
+ const char *proxied_host_arg, const char *proxied_user_arg,
+ bool with_grant_arg)
+ {
+ user= (user_arg && *user_arg) ? user_arg : NULL;
+ update_hostname (&host,
+ (host_arg && *host_arg) ? host_arg : NULL);
+ proxied_user= (proxied_user_arg && *proxied_user_arg) ?
+ proxied_user_arg : NULL;
+ update_hostname (&proxied_host,
+ (proxied_host_arg && *proxied_host_arg) ?
+ proxied_host_arg : NULL);
+ with_grant= with_grant_arg;
+ sort= get_sort(4, host.hostname, user,
+ proxied_host.hostname, proxied_user);
+ }
+
+ void init(MEM_ROOT *mem, const char *host_arg, const char *user_arg,
+ const char *proxied_host_arg, const char *proxied_user_arg,
+ bool with_grant_arg)
+ {
+ init ((host_arg && *host_arg) ? strdup_root (mem, host_arg) : NULL,
+ (user_arg && *user_arg) ? strdup_root (mem, user_arg) : NULL,
+ (proxied_host_arg && *proxied_host_arg) ?
+ strdup_root (mem, proxied_host_arg) : NULL,
+ (proxied_user_arg && *proxied_user_arg) ?
+ strdup_root (mem, proxied_user_arg) : NULL,
+ with_grant_arg);
+ }
+
+ void init(TABLE *table, MEM_ROOT *mem)
+ {
+ init (get_field(mem, table->field[MYSQL_PROXIES_PRIV_HOST]),
+ get_field(mem, table->field[MYSQL_PROXIES_PRIV_USER]),
+ get_field(mem, table->field[MYSQL_PROXIES_PRIV_PROXIED_HOST]),
+ get_field(mem, table->field[MYSQL_PROXIES_PRIV_PROXIED_USER]),
+ table->field[MYSQL_PROXIES_PRIV_WITH_GRANT]->val_int() != 0);
+ }
+
+ bool get_with_grant() { return with_grant; }
+ const char *get_user() { return user; }
+ const char *get_host() { return host.hostname; }
+ const char *get_proxied_user() { return proxied_user; }
+ const char *get_proxied_host() { return proxied_host.hostname; }
+ void set_user(MEM_ROOT *mem, const char *user_arg)
+ {
+ user= user_arg && *user_arg ? strdup_root(mem, user_arg) : NULL;
+ }
+ void set_host(MEM_ROOT *mem, const char *host_arg)
+ {
+ update_hostname(&host,
+ (host_arg && *host_arg) ?
+ strdup_root(mem, host_arg) : NULL);
+ }
+
+ bool check_validity(bool check_no_resolve)
+ {
+ if (check_no_resolve &&
+ (hostname_requires_resolving(host.hostname) ||
+ hostname_requires_resolving(proxied_host.hostname)))
+ {
+ sql_print_warning("'proxies_priv' entry '%s@%s %s@%s' "
+ "ignored in --skip-name-resolve mode.",
+ proxied_user ? proxied_user : "",
+ proxied_host.hostname ? proxied_host.hostname : "",
+ user ? user : "",
+ host.hostname ? host.hostname : "");
+ return TRUE;
+ }
+ return FALSE;
+ }
+
+ bool matches(const char *host_arg, const char *user_arg, const char *ip_arg,
+ const char *proxied_user_arg)
+ {
+ DBUG_ENTER("ACL_PROXY_USER::matches");
+ DBUG_PRINT("info", ("compare_hostname(%s,%s,%s) &&"
+ "compare_hostname(%s,%s,%s) &&"
+ "wild_compare (%s,%s) &&"
+ "wild_compare (%s,%s)",
+ host.hostname ? host.hostname : "<NULL>",
+ host_arg ? host_arg : "<NULL>",
+ ip_arg ? ip_arg : "<NULL>",
+ proxied_host.hostname ? proxied_host.hostname : "<NULL>",
+ host_arg ? host_arg : "<NULL>",
+ ip_arg ? ip_arg : "<NULL>",
+ user_arg ? user_arg : "<NULL>",
+ user ? user : "<NULL>",
+ proxied_user_arg ? proxied_user_arg : "<NULL>",
+ proxied_user ? proxied_user : "<NULL>"));
+ DBUG_RETURN(compare_hostname(&host, host_arg, ip_arg) &&
+ compare_hostname(&proxied_host, host_arg, ip_arg) &&
+ (!user ||
+ (user_arg && !wild_compare(user_arg, user, TRUE))) &&
+ (!proxied_user ||
+ (proxied_user && !wild_compare(proxied_user_arg,
+ proxied_user, TRUE))));
+ }
+
+
+ inline static bool auth_element_equals(const char *a, const char *b)
+ {
+ return (a == b || (a != NULL && b != NULL && !strcmp(a,b)));
+ }
+
+
+ bool pk_equals(ACL_PROXY_USER *grant)
+ {
+ DBUG_ENTER("pk_equals");
+ DBUG_PRINT("info", ("strcmp(%s,%s) &&"
+ "strcmp(%s,%s) &&"
+ "wild_compare (%s,%s) &&"
+ "wild_compare (%s,%s)",
+ user ? user : "<NULL>",
+ grant->user ? grant->user : "<NULL>",
+ proxied_user ? proxied_user : "<NULL>",
+ grant->proxied_user ? grant->proxied_user : "<NULL>",
+ host.hostname ? host.hostname : "<NULL>",
+ grant->host.hostname ? grant->host.hostname : "<NULL>",
+ proxied_host.hostname ? proxied_host.hostname : "<NULL>",
+ grant->proxied_host.hostname ?
+ grant->proxied_host.hostname : "<NULL>"));
+
+ DBUG_RETURN(auth_element_equals(user, grant->user) &&
+ auth_element_equals(proxied_user, grant->proxied_user) &&
+ auth_element_equals(host.hostname, grant->host.hostname) &&
+ auth_element_equals(proxied_host.hostname,
+ grant->proxied_host.hostname));
+ }
+
+
+ bool granted_on(const char *host_arg, const char *user_arg)
+ {
+ return (((!user && (!user_arg || !user_arg[0])) ||
+ (user && user_arg && !strcmp(user, user_arg))) &&
+ ((!host.hostname && (!host_arg || !host_arg[0])) ||
+ (host.hostname && host_arg && !strcmp(host.hostname, host_arg))));
+ }
+
+
+ void print_grant(String *str)
+ {
+ str->append(STRING_WITH_LEN("GRANT PROXY ON '"));
+ if (proxied_user)
+ str->append(proxied_user, strlen(proxied_user));
+ str->append(STRING_WITH_LEN("'@'"));
+ if (proxied_host.hostname)
+ str->append(proxied_host.hostname, strlen(proxied_host.hostname));
+ str->append(STRING_WITH_LEN("' TO '"));
+ if (user)
+ str->append(user, strlen(user));
+ str->append(STRING_WITH_LEN("'@'"));
+ if (host.hostname)
+ str->append(host.hostname, strlen(host.hostname));
+ str->append(STRING_WITH_LEN("'"));
+ if (with_grant)
+ str->append(STRING_WITH_LEN(" WITH GRANT OPTION"));
+ }
+
+ void set_data(ACL_PROXY_USER *grant)
+ {
+ with_grant= grant->with_grant;
+ }
+
+ static int store_pk(TABLE *table,
+ const LEX_STRING *host,
+ const LEX_STRING *user,
+ const LEX_STRING *proxied_host,
+ const LEX_STRING *proxied_user)
+ {
+ DBUG_ENTER("ACL_PROXY_USER::store_pk");
+ DBUG_PRINT("info", ("host=%s, user=%s, proxied_host=%s, proxied_user=%s",
+ host->str ? host->str : "<NULL>",
+ user->str ? user->str : "<NULL>",
+ proxied_host->str ? proxied_host->str : "<NULL>",
+ proxied_user->str ? proxied_user->str : "<NULL>"));
+ if (table->field[MYSQL_PROXIES_PRIV_HOST]->store(host->str,
+ host->length,
+ system_charset_info))
+ DBUG_RETURN(TRUE);
+ if (table->field[MYSQL_PROXIES_PRIV_USER]->store(user->str,
+ user->length,
+ system_charset_info))
+ DBUG_RETURN(TRUE);
+ if (table->field[MYSQL_PROXIES_PRIV_PROXIED_HOST]->store(proxied_host->str,
+ proxied_host->length,
+ system_charset_info))
+ DBUG_RETURN(TRUE);
+ if (table->field[MYSQL_PROXIES_PRIV_PROXIED_USER]->store(proxied_user->str,
+ proxied_user->length,
+ system_charset_info))
+ DBUG_RETURN(TRUE);
+
+ DBUG_RETURN(FALSE);
+ }
+
+ static int store_data_record(TABLE *table,
+ const LEX_STRING *host,
+ const LEX_STRING *user,
+ const LEX_STRING *proxied_host,
+ const LEX_STRING *proxied_user,
+ bool with_grant,
+ const char *grantor)
+ {
+ DBUG_ENTER("ACL_PROXY_USER::store_pk");
+ if (store_pk(table, host, user, proxied_host, proxied_user))
+ DBUG_RETURN(TRUE);
+ DBUG_PRINT("info", ("with_grant=%s", with_grant ? "TRUE" : "FALSE"));
+ if (table->field[MYSQL_PROXIES_PRIV_WITH_GRANT]->store(with_grant ? 1 : 0,
+ TRUE))
+ DBUG_RETURN(TRUE);
+ if (table->field[MYSQL_PROXIES_PRIV_GRANTOR]->store(grantor,
+ strlen(grantor),
+ system_charset_info))
+ DBUG_RETURN(TRUE);
+
+ DBUG_RETURN(FALSE);
+ }
+};
#define FIRST_NON_YN_FIELD 26
@@ -270,17 +516,18 @@ static uchar* acl_entry_get_key(acl_entry *entry, size_t *length,
return (uchar*) entry->key;
}
-#define IP_ADDR_STRLEN (3+1+3+1+3+1+3)
-#define ACL_KEY_LENGTH (IP_ADDR_STRLEN+1+NAME_LEN+1+USERNAME_LENGTH+1)
+#define IP_ADDR_STRLEN (3 + 1 + 3 + 1 + 3 + 1 + 3)
+#define ACL_KEY_LENGTH (IP_ADDR_STRLEN + 1 + NAME_LEN + \
+ 1 + USERNAME_LENGTH + 1)
#if defined(HAVE_OPENSSL)
/*
Without SSL the handshake consists of one packet. This packet
- has both client capabilites and scrambled password.
+ has both client capabilities and scrambled password.
With SSL the handshake might consist of two packets. If the first
packet (client capabilities) has CLIENT_SSL flag set, we have to
switch to SSL and read the second packet. The scrambled password
- is in the second packet and client_capabilites field will be ignored.
+ is in the second packet and client_capabilities field will be ignored.
Maybe it is better to accept flags other than CLIENT_SSL from the
second packet?
*/
@@ -291,7 +538,7 @@ static uchar* acl_entry_get_key(acl_entry *entry, size_t *length,
#define MIN_HANDSHAKE_SIZE 6
#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */
-static DYNAMIC_ARRAY acl_hosts,acl_users,acl_dbs;
+static DYNAMIC_ARRAY acl_hosts, acl_users, acl_dbs, acl_proxy_users;
static MEM_ROOT mem, memex;
static bool initialized=0;
static bool allow_all_hosts=1;
@@ -306,11 +553,9 @@ static void init_check_host(void);
static void rebuild_check_host(void);
static ACL_USER *find_acl_user(const char *host, const char *user,
my_bool exact);
-static bool update_user_table(THD *, TABLE *, const char *, const char *,
- const char *, uint);
-static void update_hostname(acl_host_and_ip *host, const char *hostname);
-static bool compare_hostname(const acl_host_and_ip *host,const char *hostname,
- const char *ip);
+static bool update_user_table(THD *thd, TABLE *table, const char *host,
+ const char *user, const char *new_password,
+ uint new_password_len);
static my_bool acl_load(THD *thd, TABLE_LIST *tables);
static my_bool grant_load(THD *thd, TABLE_LIST *tables);
static inline void get_grantor(THD *thd, char* grantor);
@@ -445,6 +690,37 @@ my_bool acl_init(bool dont_read_acl_tables)
DBUG_RETURN(return_val);
}
+/**
+ Choose from either native or old password plugins when assigning a password
+*/
+
+static bool
+set_user_plugin (ACL_USER *user, int password_len)
+{
+ switch (password_len)
+ {
+ case 0: /* no password */
+ case SCRAMBLED_PASSWORD_CHAR_LENGTH:
+ user->plugin= native_password_plugin_name;
+ return FALSE;
+ case SCRAMBLED_PASSWORD_CHAR_LENGTH_323:
+ user->plugin= old_password_plugin_name;
+ return FALSE;
+ case 45: /* 4.1: to be removed */
+ sql_print_warning("Found 4.1.0 style password for user '%s@%s'. "
+ "Ignoring user. "
+ "You should change password for this user.",
+ user->user ? user->user : "",
+ user->host.hostname ? user->host.hostname : "");
+ return TRUE;
+ default:
+ sql_print_warning("Found invalid password for user: '%s@%s'; "
+ "Ignoring user", user->user ? user->user : "",
+ user->host.hostname ? user->host.hostname : "");
+ return TRUE;
+ }
+}
+
/*
Initialize structures responsible for user/db-level privilege checking
@@ -582,9 +858,6 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables)
while (!(read_record_info.read_record(&read_record_info)))
{
ACL_USER user;
- char *password;
- uint password_len;
-
bzero(&user, sizeof(user));
update_hostname(&user.host, get_field(&mem, table->field[0]));
user.user= get_field(&mem, table->field[1]);
@@ -597,33 +870,14 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables)
continue;
}
- password= get_field(&mem, table->field[2]);
- password_len= password ? strlen(password) : 0;
+ char *password= get_field(&mem, table->field[2]);
+ uint password_len= password ? strlen(password) : 0;
user.auth_string.str= password ? password : const_cast<char*>("");
user.auth_string.length= password_len;
set_user_salt(&user, password, password_len);
- switch (password_len) {
- case 0: /* no password */
- case SCRAMBLED_PASSWORD_CHAR_LENGTH:
- user.plugin= native_password_plugin_name;
- break;
- case SCRAMBLED_PASSWORD_CHAR_LENGTH_323:
- user.plugin= old_password_plugin_name;
- break;
- case 45: /* 4.1: to be removed */
- sql_print_warning("Found 4.1.0 style password for user '%s@%s'. "
- "Ignoring user. "
- "You should change password for this user.",
- user.user ? user.user : "",
- user.host.hostname ? user.host.hostname : "");
- continue;
- default:
- sql_print_warning("Found invalid password for user: '%s@%s'; "
- "Ignoring user", user.user ? user.user : "",
- user.host.hostname ? user.host.hostname : "");
+ if (set_user_plugin(&user, password_len))
continue;
- }
{
uint next_field;
@@ -816,6 +1070,38 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables)
sizeof(ACL_DB),(qsort_cmp) acl_compare);
end_read_record(&read_record_info);
freeze_size(&acl_dbs);
+
+ (void) my_init_dynamic_array(&acl_proxy_users, sizeof(ACL_PROXY_USER),
+ 50, 100);
+ if (tables[3].table)
+ {
+ init_read_record(&read_record_info, thd, table= tables[3].table, NULL, 1,
+ 0, FALSE);
+ table->use_all_columns();
+ while (!(read_record_info.read_record(&read_record_info)))
+ {
+ ACL_PROXY_USER proxy;
+ proxy.init(table, &mem);
+ if (proxy.check_validity(check_no_resolve))
+ continue;
+ if (push_dynamic(&acl_proxy_users, (uchar*) &proxy))
+ {
+ end_read_record(&read_record_info);
+ goto end;
+ }
+ }
+ my_qsort((uchar*) dynamic_element(&acl_proxy_users, 0, ACL_PROXY_USER*),
+ acl_proxy_users.elements,
+ sizeof(ACL_PROXY_USER), (qsort_cmp) acl_compare);
+ end_read_record(&read_record_info);
+ }
+ else
+ {
+ sql_print_error("Missing system table mysql.proxies_priv; "
+ "please run mysql_upgrade to create it");
+ }
+ freeze_size(&acl_proxy_users);
+
init_check_host();
initialized=1;
@@ -834,6 +1120,7 @@ void acl_free(bool end)
delete_dynamic(&acl_users);
delete_dynamic(&acl_dbs);
delete_dynamic(&acl_wild_hosts);
+ delete_dynamic(&acl_proxy_users);
my_hash_free(&acl_check_hosts);
plugin_unlock(0, native_password_plugin);
plugin_unlock(0, old_password_plugin);
@@ -868,8 +1155,8 @@ void acl_free(bool end)
my_bool acl_reload(THD *thd)
{
- TABLE_LIST tables[3];
- DYNAMIC_ARRAY old_acl_hosts,old_acl_users,old_acl_dbs;
+ TABLE_LIST tables[4];
+ DYNAMIC_ARRAY old_acl_hosts, old_acl_users, old_acl_dbs, old_acl_proxy_users;
MEM_ROOT old_mem;
bool old_initialized;
my_bool return_val= TRUE;
@@ -885,9 +1172,15 @@ my_bool acl_reload(THD *thd)
C_STRING_WITH_LEN("user"), "user", TL_READ);
tables[2].init_one_table(C_STRING_WITH_LEN("mysql"),
C_STRING_WITH_LEN("db"), "db", TL_READ);
- tables[0].next_local= tables[0].next_global= tables+1;
- tables[1].next_local= tables[1].next_global= tables+2;
- tables[0].open_type= tables[1].open_type= tables[2].open_type= OT_BASE_ONLY;
+ tables[3].init_one_table(C_STRING_WITH_LEN("mysql"),
+ C_STRING_WITH_LEN("proxies_priv"),
+ "proxies_priv", TL_READ);
+ tables[0].next_local= tables[0].next_global= tables + 1;
+ tables[1].next_local= tables[1].next_global= tables + 2;
+ tables[2].next_local= tables[2].next_global= tables + 3;
+ tables[0].open_type= tables[1].open_type= tables[2].open_type=
+ tables[3].open_type= OT_BASE_ONLY;
+ tables[3].open_strategy= TABLE_LIST::OPEN_IF_EXISTS;
if (open_and_lock_tables(thd, tables, FALSE, MYSQL_LOCK_IGNORE_TIMEOUT))
{
@@ -904,10 +1197,11 @@ my_bool acl_reload(THD *thd)
if ((old_initialized=initialized))
mysql_mutex_lock(&acl_cache->lock);
- old_acl_hosts=acl_hosts;
- old_acl_users=acl_users;
- old_acl_dbs=acl_dbs;
- old_mem=mem;
+ old_acl_hosts= acl_hosts;
+ old_acl_users= acl_users;
+ old_acl_proxy_users= acl_proxy_users;
+ old_acl_dbs= acl_dbs;
+ old_mem= mem;
delete_dynamic(&acl_wild_hosts);
my_hash_free(&acl_check_hosts);
@@ -915,10 +1209,11 @@ my_bool acl_reload(THD *thd)
{ // Error. Revert to old list
DBUG_PRINT("error",("Reverting to old privileges"));
acl_free(); /* purecov: inspected */
- acl_hosts=old_acl_hosts;
- acl_users=old_acl_users;
- acl_dbs=old_acl_dbs;
- mem=old_mem;
+ acl_hosts= old_acl_hosts;
+ acl_users= old_acl_users;
+ acl_proxy_users= old_acl_proxy_users;
+ acl_dbs= old_acl_dbs;
+ mem= old_mem;
init_check_host();
}
else
@@ -926,6 +1221,7 @@ my_bool acl_reload(THD *thd)
free_root(&old_mem,MYF(0));
delete_dynamic(&old_acl_hosts);
delete_dynamic(&old_acl_users);
+ delete_dynamic(&old_acl_proxy_users);
delete_dynamic(&old_acl_dbs);
}
if (old_initialized)
@@ -1172,6 +1468,7 @@ static void acl_update_user(const char *user, const char *host,
if (fix_user_plugin_ptr(acl_user))
acl_user->plugin.str= strmake_root(&mem, plugin->str, plugin->length);
}
+#if 0
else
if (password)
{
@@ -1179,6 +1476,7 @@ static void acl_update_user(const char *user, const char *host,
acl_user->auth_string.length= password_len;
set_user_salt(acl_user, password, password_len);
}
+#endif
acl_user->access=privileges;
if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR)
acl_user->user_resource.questions=mqh->questions;
@@ -1198,6 +1496,8 @@ static void acl_update_user(const char *user, const char *host,
acl_user->x509_subject= (x509_subject ?
strdup_root(&mem,x509_subject) : 0);
}
+ if (password)
+ set_user_salt(acl_user, password, password_len);
/* search complete: */
break;
}
@@ -1238,7 +1538,6 @@ static void acl_insert_user(const char *user, const char *host,
old_password_plugin_name : native_password_plugin_name;
acl_user.auth_string.str= strmake_root(&mem, password, password_len);
acl_user.auth_string.length= password_len;
- set_user_salt(&acl_user, password, password_len);
}
acl_user.access=privileges;
@@ -1251,6 +1550,8 @@ static void acl_insert_user(const char *user, const char *host,
acl_user.x509_issuer= x509_issuer ? strdup_root(&mem,x509_issuer) : 0;
acl_user.x509_subject=x509_subject ? strdup_root(&mem,x509_subject) : 0;
+ set_user_salt(&acl_user, password, password_len);
+
(void) push_dynamic(&acl_users,(uchar*) &acl_user);
if (!acl_user.host.hostname ||
(acl_user.host.hostname[0] == wild_many && !acl_user.host.hostname[1]))
@@ -1635,6 +1936,7 @@ bool change_password(THD *thd, const char *host, const char *user,
my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
goto end;
}
+
/* update loaded acl entry: */
if (acl_user->plugin.str == native_password_plugin_name.str ||
acl_user->plugin.str == old_password_plugin_name.str)
@@ -1642,7 +1944,11 @@ bool change_password(THD *thd, const char *host, const char *user,
acl_user->auth_string.str= strmake_root(&mem, new_password, new_password_len);
acl_user->auth_string.length= new_password_len;
set_user_salt(acl_user, new_password, new_password_len);
+ set_user_plugin(acl_user, new_password_len);
}
+ else
+ push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
+ ER_SET_PASSWORD_AUTH_PLUGIN, ER(ER_SET_PASSWORD_AUTH_PLUGIN));
if (update_user_table(thd, table,
acl_user->host.hostname ? acl_user->host.hostname : "",
@@ -2024,15 +2330,14 @@ static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
see also test_if_create_new_users()
*/
- else if (!password_len && no_auto_create)
+ else if (!password_len && !combo.plugin.length && no_auto_create)
{
- my_error(ER_PASSWORD_NO_MATCH, MYF(0), combo.user.str, combo.host.str);
+ my_error(ER_PASSWORD_NO_MATCH, MYF(0));
goto end;
}
else if (!can_create_user)
{
- my_error(ER_CANT_CREATE_USER_WITH_GRANT, MYF(0),
- thd->security_ctx->user, thd->security_ctx->host_or_ip);
+ my_error(ER_CANT_CREATE_USER_WITH_GRANT, MYF(0));
goto end;
}
else if (combo.plugin.str[0])
@@ -2057,6 +2362,15 @@ static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
{
old_row_exists = 1;
store_record(table,record[1]); // Save copy for update
+#if 0
+ /* what == 'N' means revoke */
+ if (combo.plugin.length && what != 'N')
+ {
+ my_error(ER_GRANT_PLUGIN_USER_EXISTS, MYF(0),
+ static_cast<int>(combo.user.length), combo.user.str);
+ goto end;
+ }
+#endif
if (combo.password.str) // If password given
table->field[2]->store(password, password_len, system_charset_info);
else if (!rights && !revoke_grant &&
@@ -2139,13 +2453,15 @@ static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo,
table->field[next_field+3]->store((longlong) mqh.user_conn, TRUE);
mqh_used= mqh_used || mqh.questions || mqh.updates || mqh.conn_per_hour;
- next_field+=4;
+ next_field+= 4;
if (table->s->fields >= 41 && combo.plugin.str[0])
{
table->field[next_field]->store(combo.plugin.str, combo.plugin.length,
- system_charset_info);
- table->field[next_field+1]->store(combo.auth.str, combo.auth.length,
- system_charset_info);
+ system_charset_info);
+ table->field[next_field]->set_notnull();
+ table->field[next_field + 1]->store(combo.auth.str, combo.auth.length,
+ system_charset_info);
+ table->field[next_field + 1]->set_notnull();
}
}
@@ -2319,6 +2635,164 @@ abort:
}
+static void
+acl_update_proxy_user(ACL_PROXY_USER *new_value, bool is_revoke)
+{
+ mysql_mutex_assert_owner(&acl_cache->lock);
+
+ DBUG_ENTER("acl_update_proxy_user");
+ for (uint i= 0; i < acl_proxy_users.elements; i++)
+ {
+ ACL_PROXY_USER *acl_user=
+ dynamic_element(&acl_proxy_users, i, ACL_PROXY_USER *);
+
+ if (acl_user->pk_equals(new_value))
+ {
+ if (is_revoke)
+ {
+ DBUG_PRINT("info", ("delting ACL_PROXY_USER"));
+ delete_dynamic_element(&acl_proxy_users, i);
+ }
+ else
+ {
+ DBUG_PRINT("info", ("updating ACL_PROXY_USER"));
+ acl_user->set_data(new_value);
+ }
+ break;
+ }
+ }
+ DBUG_VOID_RETURN;
+}
+
+
+static void
+acl_insert_proxy_user(ACL_PROXY_USER *new_value)
+{
+ DBUG_ENTER("acl_insert_proxy_user");
+ mysql_mutex_assert_owner(&acl_cache->lock);
+ (void) push_dynamic(&acl_proxy_users, (uchar *) new_value);
+ my_qsort((uchar*) dynamic_element(&acl_proxy_users, 0, ACL_PROXY_USER *),
+ acl_proxy_users.elements,
+ sizeof(ACL_PROXY_USER), (qsort_cmp) acl_compare);
+ DBUG_VOID_RETURN;
+}
+
+
+static int
+replace_proxies_priv_table(THD *thd, TABLE *table, const LEX_USER *user,
+ const LEX_USER *proxied_user, bool with_grant_arg,
+ bool revoke_grant)
+{
+ bool old_row_exists= 0;
+ int error;
+ uchar user_key[MAX_KEY_LENGTH];
+ ACL_PROXY_USER new_grant;
+ char grantor[USER_HOST_BUFF_SIZE];
+
+ DBUG_ENTER("replace_proxies_priv_table");
+
+ if (!initialized)
+ {
+ my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
+ DBUG_RETURN(-1);
+ }
+
+ /* Check if there is such a user in user table in memory? */
+ if (!find_acl_user(user->host.str,user->user.str, FALSE))
+ {
+ my_message(ER_PASSWORD_NO_MATCH, ER(ER_PASSWORD_NO_MATCH), MYF(0));
+ DBUG_RETURN(-1);
+ }
+
+ table->use_all_columns();
+ ACL_PROXY_USER::store_pk (table, &user->host, &user->user,
+ &proxied_user->host, &proxied_user->user);
+
+ key_copy(user_key, table->record[0], table->key_info,
+ table->key_info->key_length);
+
+ get_grantor(thd, grantor);
+
+ table->file->ha_index_init(0, 1);
+ if (table->file->index_read_map(table->record[0], user_key,
+ HA_WHOLE_KEY,
+ HA_READ_KEY_EXACT))
+ {
+ DBUG_PRINT ("info", ("Row not found"));
+ if (revoke_grant)
+ { // no row, no revoke
+ my_error(ER_NONEXISTING_GRANT, MYF(0), user->user.str, user->host.str);
+ goto abort;
+ }
+ old_row_exists= 0;
+ restore_record(table, s->default_values);
+ ACL_PROXY_USER::store_data_record(table, &user->host, &user->user,
+ &proxied_user->host,
+ &proxied_user->user,
+ with_grant_arg,
+ grantor);
+ }
+ else
+ {
+ DBUG_PRINT("info", ("Row found"));
+ old_row_exists= 1;
+ store_record(table, record[1]);
+ }
+
+ if (old_row_exists)
+ {
+ /* update old existing row */
+ if (!revoke_grant)
+ {
+ if ((error= table->file->ha_update_row(table->record[1],
+ table->record[0])) &&
+ error != HA_ERR_RECORD_IS_THE_SAME)
+ goto table_error; /* purecov: inspected */
+ }
+ else
+ {
+ if ((error= table->file->ha_delete_row(table->record[1])))
+ goto table_error; /* purecov: inspected */
+ }
+ }
+ else if ((error= table->file->ha_write_row(table->record[0])))
+ {
+ DBUG_PRINT("info", ("error inserting the row"));
+ if (table->file->is_fatal_error(error, HA_CHECK_DUP_KEY))
+ goto table_error; /* purecov: inspected */
+ }
+
+ acl_cache->clear(1); // Clear privilege cache
+ if (old_row_exists)
+ {
+ new_grant.init(user->host.str, user->user.str,
+ proxied_user->host.str, proxied_user->user.str,
+ with_grant_arg);
+ acl_update_proxy_user(&new_grant, revoke_grant);
+ }
+ else
+ {
+ new_grant.init(&mem, user->host.str, user->user.str,
+ proxied_user->host.str, proxied_user->user.str,
+ with_grant_arg);
+ acl_insert_proxy_user(&new_grant);
+ }
+
+ table->file->ha_index_end();
+ DBUG_RETURN(0);
+
+ /* This could only happen if the grant tables got corrupted */
+table_error:
+ DBUG_PRINT("info", ("table error"));
+ table->file->print_error(error, MYF(0)); /* purecov: inspected */
+
+abort:
+ DBUG_PRINT("info", ("aborting replace_proxies_priv_table"));
+ table->file->ha_index_end();
+ DBUG_RETURN(-1);
+}
+
+
class GRANT_COLUMN :public Sql_alloc
{
public:
@@ -3221,6 +3695,7 @@ int mysql_table_grant(THD *thd, TABLE_LIST *table_list,
{ // Should never happen
/* Restore the state of binlog format */
DBUG_ASSERT(!thd->is_current_stmt_binlog_format_row());
+ thd->lex->restore_backup_query_tables_list(&backup);
if (save_binlog_row_based)
thd->set_current_stmt_binlog_format_row();
DBUG_RETURN(TRUE); /* purecov: deadcode */
@@ -3535,10 +4010,10 @@ bool mysql_routine_grant(THD *thd, TABLE_LIST *table_list, bool is_proc,
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
- ulong rights, bool revoke_grant)
+ ulong rights, bool revoke_grant, bool is_proxy)
{
List_iterator <LEX_USER> str_list (list);
- LEX_USER *Str, *tmp_Str;
+ LEX_USER *Str, *tmp_Str, *proxied_user= NULL;
char tmp_db[SAFE_NAME_LEN+1];
bool create_new_users=0;
TABLE_LIST tables[2];
@@ -3558,11 +4033,26 @@ bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
db=tmp_db;
}
- /* open the mysql.user and mysql.db tables */
+ if (is_proxy)
+ {
+ DBUG_ASSERT(!db);
+ proxied_user= str_list++;
+ }
+
+ /* open the mysql.user and mysql.db or mysql.proxies_priv tables */
tables[0].init_one_table(C_STRING_WITH_LEN("mysql"),
C_STRING_WITH_LEN("user"), "user", TL_WRITE);
- tables[1].init_one_table(C_STRING_WITH_LEN("mysql"),
- C_STRING_WITH_LEN("db"), "db", TL_WRITE);
+ if (is_proxy)
+
+ tables[1].init_one_table(C_STRING_WITH_LEN("mysql"),
+ C_STRING_WITH_LEN("proxies_priv"),
+ "proxies_priv",
+ TL_WRITE);
+ else
+ tables[1].init_one_table(C_STRING_WITH_LEN("mysql"),
+ C_STRING_WITH_LEN("db"),
+ "db",
+ TL_WRITE);
tables[0].next_local= tables[0].next_global= tables+1;
/*
@@ -3648,6 +4138,13 @@ bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &list,
result= -1;
}
}
+ else if (is_proxy)
+ {
+ if (replace_proxies_priv_table (thd, tables[1].table, Str, proxied_user,
+ rights & GRANT_ACL ? TRUE : FALSE,
+ revoke_grant))
+ result= -1;
+ }
}
mysql_mutex_unlock(&acl_cache->lock);
@@ -4070,7 +4567,8 @@ end:
bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
bool any_combination_will_do, uint number, bool no_errors)
{
- TABLE_LIST *table, *first_not_own_table= thd->lex->first_not_own_table();
+ TABLE_LIST *tl;
+ TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
Security_context *sctx= thd->security_ctx;
uint i;
ulong orig_want_access= want_access;
@@ -4087,34 +4585,32 @@ bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
the given table list refers to the list for prelocking (contains tables
of other queries). For simple queries first_not_own_table is 0.
*/
- for (i= 0, table= tables;
- i < number && table != first_not_own_table;
- table= table->next_global, i++)
+ for (i= 0, tl= tables;
+ i < number && tl != first_not_own_table;
+ tl= tl->next_global, i++)
{
/*
Save a copy of the privileges without the SHOW_VIEW_ACL attribute.
It will be checked during making view.
*/
- table->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL);
+ tl->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL);
}
mysql_rwlock_rdlock(&LOCK_grant);
- for (table= tables;
- table && number-- && table != first_not_own_table;
- table= table->next_global)
+ for (tl= tables;
+ tl && number-- && tl != first_not_own_table;
+ tl= tl->next_global)
{
- GRANT_TABLE *grant_table;
- sctx = test(table->security_ctx) ?
- table->security_ctx : thd->security_ctx;
+ sctx = test(tl->security_ctx) ? tl->security_ctx : thd->security_ctx;
- const ACL_internal_table_access *access;
- access= get_cached_table_access(&table->grant.m_internal,
- table->get_db_name(),
- table->get_table_name());
+ const ACL_internal_table_access *access=
+ get_cached_table_access(&tl->grant.m_internal,
+ tl->get_db_name(),
+ tl->get_table_name());
if (access)
{
- switch(access->check(orig_want_access, &table->grant.privilege))
+ switch(access->check(orig_want_access, &tl->grant.privilege))
{
case ACL_INTERNAL_ACCESS_GRANTED:
/*
@@ -4138,29 +4634,33 @@ bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
if (!want_access)
continue; // ok
- if (!(~table->grant.privilege & want_access) ||
- table->is_anonymous_derived_table() || table->schema_table)
+ if (!(~tl->grant.privilege & want_access) ||
+ tl->is_anonymous_derived_table() || tl->schema_table)
{
/*
- It is subquery in the FROM clause. VIEW set table->derived after
+ It is subquery in the FROM clause. VIEW set tl->derived after
table opening, but this function always called before table opening.
*/
- if (!table->referencing_view)
+ if (!tl->referencing_view)
{
/*
If it's a temporary table created for a subquery in the FROM
clause, or an INFORMATION_SCHEMA table, drop the request for
a privilege.
*/
- table->grant.want_privilege= 0;
+ tl->grant.want_privilege= 0;
}
continue;
}
- if (!(grant_table= table_hash_search(sctx->host, sctx->ip,
- table->get_db_name(), sctx->priv_user,
- table->get_table_name(), FALSE)))
+ GRANT_TABLE *grant_table= table_hash_search(sctx->host, sctx->ip,
+ tl->get_db_name(),
+ sctx->priv_user,
+ tl->get_table_name(),
+ FALSE);
+
+ if (!grant_table)
{
- want_access &= ~table->grant.privilege;
+ want_access &= ~tl->grant.privilege;
goto err; // No grants
}
@@ -4171,18 +4671,17 @@ bool check_grant(THD *thd, ulong want_access, TABLE_LIST *tables,
if (any_combination_will_do)
continue;
- table->grant.grant_table=grant_table; // Remember for column test
- table->grant.version=grant_version;
- table->grant.privilege|= grant_table->privs;
- table->grant.want_privilege= ((want_access & COL_ACLS)
- & ~table->grant.privilege);
+ tl->grant.grant_table= grant_table; // Remember for column test
+ tl->grant.version= grant_version;
+ tl->grant.privilege|= grant_table->privs;
+ tl->grant.want_privilege= ((want_access & COL_ACLS) & ~tl->grant.privilege);
- if (!(~table->grant.privilege & want_access))
+ if (!(~tl->grant.privilege & want_access))
continue;
- if (want_access & ~(grant_table->cols | table->grant.privilege))
+ if (want_access & ~(grant_table->cols | tl->grant.privilege))
{
- want_access &= ~(grant_table->cols | table->grant.privilege);
+ want_access &= ~(grant_table->cols | tl->grant.privilege);
goto err; // impossible
}
}
@@ -4201,7 +4700,7 @@ err:
command,
sctx->priv_user,
sctx->host_or_ip,
- table ? table->get_table_name() : "unknown");
+ tl ? tl->get_table_name() : "unknown");
}
DBUG_RETURN(TRUE);
}
@@ -5093,6 +5592,12 @@ bool mysql_show_grants(THD *thd,LEX_USER *lex_user)
goto end;
}
+ if (show_proxy_grants(thd, lex_user, buff, sizeof(buff)))
+ {
+ error= -1;
+ goto end;
+ }
+
end:
mysql_mutex_unlock(&acl_cache->lock);
mysql_rwlock_unlock(&LOCK_grant);
@@ -5250,7 +5755,7 @@ void get_mqh(const char *user, const char *host, USER_CONN *uc)
< 0 Error.
*/
-#define GRANT_TABLES 5
+#define GRANT_TABLES 6
int open_grant_tables(THD *thd, TABLE_LIST *tables)
{
DBUG_ENTER("open_grant_tables");
@@ -5274,10 +5779,16 @@ int open_grant_tables(THD *thd, TABLE_LIST *tables)
(tables+4)->init_one_table(C_STRING_WITH_LEN("mysql"),
C_STRING_WITH_LEN("procs_priv"),
"procs_priv", TL_WRITE);
- tables->next_local= tables->next_global= tables+1;
- (tables+1)->next_local= (tables+1)->next_global= tables+2;
- (tables+2)->next_local= (tables+2)->next_global= tables+3;
- (tables+3)->next_local= (tables+3)->next_global= tables+4;
+ (tables+5)->init_one_table(C_STRING_WITH_LEN("mysql"),
+ C_STRING_WITH_LEN("proxies_priv"),
+ "proxies_priv", TL_WRITE);
+ tables[5].open_strategy= TABLE_LIST::OPEN_IF_EXISTS;
+
+ tables->next_local= tables->next_global= tables + 1;
+ (tables+1)->next_local= (tables+1)->next_global= tables + 2;
+ (tables+2)->next_local= (tables+2)->next_global= tables + 3;
+ (tables+3)->next_local= (tables+3)->next_global= tables + 4;
+ (tables+4)->next_local= (tables+4)->next_global= tables + 5;
#ifdef HAVE_REPLICATION
/*
@@ -5290,12 +5801,12 @@ int open_grant_tables(THD *thd, TABLE_LIST *tables)
The tables must be marked "updating" so that tables_ok() takes them into
account in tests.
*/
- tables[0].updating=tables[1].updating=tables[2].updating=
- tables[3].updating=tables[4].updating=1;
+ tables[0].updating= tables[1].updating= tables[2].updating=
+ tables[3].updating= tables[4].updating= tables[5].updating= 1;
if (!(thd->spcont || rpl_filter->tables_ok(0, tables)))
DBUG_RETURN(1);
- tables[0].updating=tables[1].updating=tables[2].updating=
- tables[3].updating=tables[4].updating=0;;
+ tables[0].updating= tables[1].updating= tables[2].updating=
+ tables[3].updating= tables[4].updating= tables[5].updating= 0;
}
#endif
@@ -5424,7 +5935,7 @@ static int handle_grant_table(TABLE_LIST *tables, uint table_no, bool drop,
int error;
TABLE *table= tables[table_no].table;
Field *host_field= table->field[0];
- Field *user_field= table->field[table_no ? 2 : 1];
+ Field *user_field= table->field[table_no && table_no != 5 ? 2 : 1];
char *host_str= user_from->host.str;
char *user_str= user_from->user.str;
const char *host;
@@ -5507,12 +6018,15 @@ static int handle_grant_table(TABLE_LIST *tables, uint table_no, bool drop,
user= "";
#ifdef EXTRA_DEBUG
- DBUG_PRINT("loop",("scan fields: '%s'@'%s' '%s' '%s' '%s'",
- user, host,
- get_field(thd->mem_root, table->field[1]) /*db*/,
- get_field(thd->mem_root, table->field[3]) /*table*/,
- get_field(thd->mem_root,
- table->field[4]) /*column*/));
+ if (table_no != 5)
+ {
+ DBUG_PRINT("loop",("scan fields: '%s'@'%s' '%s' '%s' '%s'",
+ user, host,
+ get_field(thd->mem_root, table->field[1]) /*db*/,
+ get_field(thd->mem_root, table->field[3]) /*table*/,
+ get_field(thd->mem_root,
+ table->field[4]) /*column*/));
+ }
#endif
if (strcmp(user_str, user) ||
my_strcasecmp(system_charset_info, host_str, host))
@@ -5535,18 +6049,15 @@ static int handle_grant_table(TABLE_LIST *tables, uint table_no, bool drop,
}
-/*
+/**
Handle an in-memory privilege structure.
- SYNOPSIS
- handle_grant_struct()
- struct_no The number of the structure to handle (0..3).
- drop If user_from is to be dropped.
- user_from The the user to be searched/dropped/renamed.
- user_to The new name for the user if to be renamed,
- NULL otherwise.
+ @param struct_no The number of the structure to handle (0..5).
+ @param drop If user_from is to be dropped.
+ @param user_from The the user to be searched/dropped/renamed.
+ @param user_to The new name for the user if to be renamed, NULL otherwise.
- DESCRIPTION
+ @note
Scan through all elements in an in-memory grant structure and apply
the requested operation.
Delete from grant structure if drop is true.
@@ -5556,12 +6067,13 @@ static int handle_grant_table(TABLE_LIST *tables, uint table_no, bool drop,
0 acl_users
1 acl_dbs
2 column_priv_hash
- 3 procs_priv_hash
+ 3 proc_priv_hash
+ 4 func_priv_hash
+ 5 acl_proxy_users
- RETURN
- > 0 At least one element matched.
- 0 OK, but no element matched.
- -1 Wrong arguments to function
+ @retval > 0 At least one element matched.
+ @retval 0 OK, but no element matched.
+ @retval -1 Wrong arguments to function.
*/
static int handle_grant_struct(uint struct_no, bool drop,
@@ -5574,7 +6086,9 @@ static int handle_grant_struct(uint struct_no, bool drop,
const char *host;
ACL_USER *acl_user= NULL;
ACL_DB *acl_db= NULL;
+ ACL_PROXY_USER *acl_proxy_user= NULL;
GRANT_NAME *grant_name= NULL;
+ HASH *grant_name_hash= NULL;
DBUG_ENTER("handle_grant_struct");
DBUG_PRINT("info",("scan struct: %u search: '%s'@'%s'",
struct_no, user_from->user.str, user_from->host.str));
@@ -5594,9 +6108,18 @@ static int handle_grant_struct(uint struct_no, bool drop,
break;
case 2:
elements= column_priv_hash.records;
+ grant_name_hash= &column_priv_hash;
break;
case 3:
elements= proc_priv_hash.records;
+ grant_name_hash= &proc_priv_hash;
+ break;
+ case 4:
+ elements= func_priv_hash.records;
+ grant_name_hash= &func_priv_hash;
+ break;
+ case 5:
+ elements= acl_proxy_users.elements;
break;
default:
return -1;
@@ -5626,16 +6149,19 @@ static int handle_grant_struct(uint struct_no, bool drop,
break;
case 2:
- grant_name= (GRANT_NAME*) my_hash_element(&column_priv_hash, idx);
+ case 3:
+ case 4:
+ grant_name= (GRANT_NAME*) my_hash_element(grant_name_hash, idx);
user= grant_name->user;
host= grant_name->host.hostname;
break;
- case 3:
- grant_name= (GRANT_NAME*) my_hash_element(&proc_priv_hash, idx);
- user= grant_name->user;
- host= grant_name->host.hostname;
+ case 5:
+ acl_proxy_user= dynamic_element(&acl_proxy_users, idx, ACL_PROXY_USER*);
+ user= acl_proxy_user->get_user();
+ host= acl_proxy_user->get_host();
break;
+
default:
DBUG_ASSERT(0);
}
@@ -5665,14 +6191,30 @@ static int handle_grant_struct(uint struct_no, bool drop,
break;
case 2:
- my_hash_delete(&column_priv_hash, (uchar*) grant_name);
- break;
-
case 3:
- my_hash_delete(&proc_priv_hash, (uchar*) grant_name);
+ case 4:
+ my_hash_delete(grant_name_hash, (uchar*) grant_name);
break;
+
+ case 5:
+ delete_dynamic_element(&acl_proxy_users, idx);
+ break;
+
}
elements--;
+ /*
+ - If we are iterating through an array then we just have moved all
+ elements after the current element one position closer to its head.
+ This means that we have to take another look at the element at
+ current position as it is a new element from the array's tail.
+ - If we are iterating through a hash the current element was replaced
+ with one of elements from the tail. So we also have to take a look
+ at the new element in current position.
+ Note that in our HASH implementation hash_delete() won't move any
+ elements with position after current one to position before the
+ current (i.e. from the tail to the head), so it is safe to continue
+ iteration without re-starting.
+ */
idx--;
}
else if ( user_to )
@@ -5690,22 +6232,47 @@ static int handle_grant_struct(uint struct_no, bool drop,
case 2:
case 3:
- /*
- Update the grant structure with the new user name and
- host name
- */
- grant_name->set_user_details(user_to->host.str, grant_name->db,
- user_to->user.str, grant_name->tname,
- TRUE);
+ case 4:
+ {
+ /*
+ Save old hash key and its length to be able properly update
+ element position in hash.
+ */
+ char *old_key= grant_name->hash_key;
+ size_t old_key_length= grant_name->key_length;
+
+ /*
+ Update the grant structure with the new user name and host name.
+ */
+ grant_name->set_user_details(user_to->host.str, grant_name->db,
+ user_to->user.str, grant_name->tname,
+ TRUE);
+
+ /*
+ Since username is part of the hash key, when the user name
+ is renamed, the hash key is changed. Update the hash to
+ ensure that the position matches the new hash key value
+ */
+ my_hash_update(grant_name_hash, (uchar*) grant_name, (uchar*) old_key,
+ old_key_length);
+ /*
+ hash_update() operation could have moved element from the tail
+ of the hash to the current position. So we need to take a look
+ at the element in current position once again.
+ Thanks to the fact that hash_update() for our HASH implementation
+ won't move any elements from the tail of the hash to the positions
+ before the current one (a.k.a. head) it is safe to continue
+ iteration without restarting.
+ */
+ idx--;
+ break;
+ }
+
+ case 5:
+ acl_proxy_user->set_user (&mem, user_to->user.str);
+ acl_proxy_user->set_host (&mem, user_to->host.str);
+ break;
- /*
- Since username is part of the hash key, when the user name
- is renamed, the hash key is changed. Update the hash to
- ensure that the position matches the new hash key value
- */
- my_hash_update(&column_priv_hash, (uchar*) grant_name,
- (uchar*) grant_name->hash_key, grant_name->key_length);
- break;
}
}
else
@@ -5791,7 +6358,7 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop,
}
}
- /* Handle procedures table. */
+ /* Handle stored routines table. */
if ((found= handle_grant_table(tables, 4, drop, user_from, user_to)) < 0)
{
/* Handle of table failed, don't touch in-memory array. */
@@ -5808,6 +6375,15 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop,
if (! drop && ! user_to)
goto end;
}
+ /* Handle funcs array. */
+ if (((handle_grant_struct(4, drop, user_from, user_to) && ! result) ||
+ found) && ! result)
+ {
+ result= 1; /* At least one record/element found. */
+ /* If search is requested, we do not need to search further. */
+ if (! drop && ! user_to)
+ goto end;
+ }
}
/* Handle tables table. */
@@ -5840,6 +6416,23 @@ static int handle_grant_data(TABLE_LIST *tables, bool drop,
result= 1; /* At least one record/element found. */
}
}
+
+ /* Handle proxies_priv table. */
+ if (tables[5].table)
+ {
+ if ((found= handle_grant_table(tables, 5, drop, user_from, user_to)) < 0)
+ {
+ /* Handle of table failed, don't touch the in-memory array. */
+ result= -1;
+ }
+ else
+ {
+ /* Handle proxies_priv array. */
+ if ((handle_grant_struct(5, drop, user_from, user_to) && !result) ||
+ found)
+ result= 1; /* At least one record/element found. */
+ }
+ }
end:
DBUG_RETURN(result);
}
@@ -6596,6 +7189,129 @@ template class List<LEX_COLUMN>;
template class List<LEX_USER>;
#endif
+/**
+ Validate if a user can proxy as another user
+
+ @thd current thread
+ @param user the logged in user (proxy user)
+ @param authenticated_as the effective user a plugin is trying to
+ impersonate as (proxied user)
+ @return proxy user definition
+ @retval NULL proxy user definition not found or not applicable
+ @retval non-null the proxy user data
+*/
+
+static ACL_PROXY_USER *
+acl_find_proxy_user(const char *user, const char *host, const char *ip,
+ const char *authenticated_as, bool *proxy_used)
+{
+ uint i;
+ /* if the proxied and proxy user are the same return OK */
+ DBUG_ENTER("acl_find_proxy_user");
+ DBUG_PRINT("info", ("user=%s host=%s ip=%s authenticated_as=%s",
+ user, host, ip, authenticated_as));
+
+ if (!strcmp(authenticated_as, user))
+ {
+ DBUG_PRINT ("info", ("user is the same as authenticated_as"));
+ DBUG_RETURN (NULL);
+ }
+
+ *proxy_used= TRUE;
+ for (i=0; i < acl_proxy_users.elements; i++)
+ {
+ ACL_PROXY_USER *proxy= dynamic_element(&acl_proxy_users, i,
+ ACL_PROXY_USER *);
+ if (proxy->matches(host, user, ip, authenticated_as))
+ DBUG_RETURN(proxy);
+ }
+
+ DBUG_RETURN(NULL);
+}
+
+
+bool
+acl_check_proxy_grant_access(THD *thd, const char *host, const char *user,
+ bool with_grant)
+{
+ DBUG_ENTER("acl_check_proxy_grant_access");
+ DBUG_PRINT("info", ("user=%s host=%s with_grant=%d", user, host,
+ (int) with_grant));
+ if (!initialized)
+ {
+ my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--skip-grant-tables");
+ DBUG_RETURN(1);
+ }
+
+ /* replication slave thread can do anything */
+ if (thd->slave_thread)
+ {
+ DBUG_PRINT("info", ("replication slave"));
+ DBUG_RETURN(FALSE);
+ }
+
+ /* one can grant proxy to himself to others */
+ if (!strcmp(thd->security_ctx->user, user) &&
+ !my_strcasecmp(system_charset_info, host,
+ thd->security_ctx->host))
+ {
+ DBUG_PRINT("info", ("strcmp (%s, %s) my_casestrcmp (%s, %s) equal",
+ thd->security_ctx->user, user,
+ host, thd->security_ctx->host));
+ DBUG_RETURN(FALSE);
+ }
+
+ /* check for matching WITH PROXY rights */
+ for (uint i=0; i < acl_proxy_users.elements; i++)
+ {
+ ACL_PROXY_USER *proxy= dynamic_element(&acl_proxy_users, i,
+ ACL_PROXY_USER *);
+ if (proxy->matches(thd->security_ctx->host,
+ thd->security_ctx->user,
+ thd->security_ctx->ip,
+ user) &&
+ proxy->get_with_grant())
+ {
+ DBUG_PRINT("info", ("found"));
+ DBUG_RETURN(FALSE);
+ }
+ }
+
+ my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0),
+ thd->security_ctx->user,
+ thd->security_ctx->host_or_ip);
+ DBUG_RETURN(TRUE);
+}
+
+
+static bool
+show_proxy_grants(THD *thd, LEX_USER *user, char *buff, size_t buffsize)
+{
+ Protocol *protocol= thd->protocol;
+ int error= 0;
+
+ for (uint i=0; i < acl_proxy_users.elements; i++)
+ {
+ ACL_PROXY_USER *proxy= dynamic_element(&acl_proxy_users, i,
+ ACL_PROXY_USER *);
+ if (proxy->granted_on(user->host.str, user->user.str))
+ {
+ String global(buff, buffsize, system_charset_info);
+ global.length(0);
+ proxy->print_grant(&global);
+ protocol->prepare_for_resend();
+ protocol->store(global.ptr(), global.length(), global.charset());
+ if (protocol->write())
+ {
+ error= -1;
+ break;
+ }
+ }
+ }
+ return error;
+}
+
+
#endif /*NO_EMBEDDED_ACCESS_CHECKS */
@@ -7183,18 +7899,17 @@ get_cached_table_access(GRANT_INTERNAL_INFO *grant_internal_info,
#ifndef HAVE_OPENSSL
#define ssl_acceptor_fd 0
#define sslaccept(A,B,C,D) 1
-#define NORMAL_HANDSHAKE_SIZE 6
#endif
/**
The internal version of what plugins know as MYSQL_PLUGIN_VIO,
basically the context of the authentication session
*/
-struct MPVIO_EXT : public MYSQL_PLUGIN_VIO
+struct MPVIO_EXT :public MYSQL_PLUGIN_VIO
{
MYSQL_SERVER_AUTH_INFO auth_info;
THD *thd;
- ACL_USER *acl_user; ///< a copy, independent from acl_users array
+ const ACL_USER *acl_user; ///< a copy, independent from acl_users array
plugin_ref plugin; ///< what plugin we're under
LEX_STRING db; ///< db name from the handshake packet
/** when restarting a plugin this caches the last client reply */
@@ -7213,18 +7928,16 @@ struct MPVIO_EXT : public MYSQL_PLUGIN_VIO
enum { SUCCESS, FAILURE, RESTART } status;
};
-
/**
a helper function to report an access denied error in all the proper places
*/
-
-static void login_failed_error(THD *thd, bool passwd_used)
+static void login_failed_error(THD *thd, int passwd_used)
{
- my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
+ my_error(access_denied_error_code(passwd_used), MYF(0),
thd->main_security_ctx.user,
thd->main_security_ctx.host_or_ip,
passwd_used ? ER(ER_YES) : ER(ER_NO));
- general_log_print(thd, COM_CONNECT, ER(ER_ACCESS_DENIED_ERROR),
+ general_log_print(thd, COM_CONNECT, ER(access_denied_error_code(passwd_used)),
thd->main_security_ctx.user,
thd->main_security_ctx.host_or_ip,
passwd_used ? ER(ER_YES) : ER(ER_NO));
@@ -7236,14 +7949,13 @@ static void login_failed_error(THD *thd, bool passwd_used)
*/
if (global_system_variables.log_warnings > 1)
{
- sql_print_warning(ER(ER_ACCESS_DENIED_ERROR),
+ sql_print_warning(ER(access_denied_error_code(passwd_used)),
thd->main_security_ctx.user,
thd->main_security_ctx.host_or_ip,
passwd_used ? ER(ER_YES) : ER(ER_NO));
}
}
-
/**
sends a server handshake initialization packet, the very first packet
after the connection was established
@@ -7269,7 +7981,6 @@ static void login_failed_error(THD *thd, bool passwd_used)
@retval 0 ok
@retval 1 error
*/
-
static bool send_server_handshake_packet(MPVIO_EXT *mpvio,
const char *data, uint data_len)
{
@@ -7277,14 +7988,26 @@ static bool send_server_handshake_packet(MPVIO_EXT *mpvio,
DBUG_ASSERT(data_len <= 255);
THD *thd= mpvio->thd;
- char *buff= (char *)my_alloca(1 + SERVER_VERSION_LENGTH + 1 + data_len + 64);
+ char *buff= (char *) my_alloca(1 + SERVER_VERSION_LENGTH + 1 + data_len + 64);
char scramble_buf[SCRAMBLE_LENGTH];
char *end= buff;
+ DBUG_ENTER("send_server_handshake_packet");
*end++= protocol_version;
thd->client_capabilities= CLIENT_BASIC_FLAGS;
+ if (opt_using_transactions)
+ thd->client_capabilities|= CLIENT_TRANSACTIONS;
+
+ thd->client_capabilities|= CAN_CLIENT_COMPRESS;
+
+ if (ssl_acceptor_fd)
+ {
+ thd->client_capabilities |= CLIENT_SSL;
+ thd->client_capabilities |= CLIENT_SSL_VERIFY_SERVER_CERT;
+ }
+
if (data_len)
{
mpvio->cached_server_packet.pkt= (char*)thd->memdup(data, data_len);
@@ -7294,12 +8017,13 @@ static bool send_server_handshake_packet(MPVIO_EXT *mpvio,
if (data_len < SCRAMBLE_LENGTH)
{
if (data_len)
- { /*
+ {
+ /*
the first packet *must* have at least 20 bytes of a scramble.
if a plugin provided less, we pad it to 20 with zeros
*/
memcpy(scramble_buf, data, data_len);
- bzero(scramble_buf+data_len, SCRAMBLE_LENGTH-data_len);
+ bzero(scramble_buf + data_len, SCRAMBLE_LENGTH - data_len);
data= scramble_buf;
}
else
@@ -7319,17 +8043,6 @@ static bool send_server_handshake_packet(MPVIO_EXT *mpvio,
data_len= SCRAMBLE_LENGTH;
}
- if (opt_using_transactions)
- thd->client_capabilities|= CLIENT_TRANSACTIONS;
-
- thd->client_capabilities|= CAN_CLIENT_COMPRESS;
-
- if (ssl_acceptor_fd)
- {
- thd->client_capabilities |= CLIENT_SSL;
- thd->client_capabilities |= CLIENT_SSL_VERIFY_SERVER_CERT;
- }
-
end= strnmov(end, server_version, SERVER_VERSION_LENGTH) + 1;
int4store((uchar*) end, mpvio->thd->thread_id);
end+= 4;
@@ -7339,29 +8052,30 @@ static bool send_server_handshake_packet(MPVIO_EXT *mpvio,
tail: that's why first part of the scramble is placed here, and second
part at the end of packet.
*/
- end= (char*)memcpy(end, data, SCRAMBLE_LENGTH_323);
+ end= (char*) memcpy(end, data, SCRAMBLE_LENGTH_323);
end+= SCRAMBLE_LENGTH_323;
*end++= 0;
int2store(end, thd->client_capabilities);
/* write server characteristics: up to 16 bytes allowed */
- end[2]=(char) default_charset_info->number;
+ end[2]= (char) default_charset_info->number;
int2store(end+3, mpvio->thd->server_status);
int2store(end+5, thd->client_capabilities >> 16);
end[7]= data_len;
- bzero(end+8, 10);
+ bzero(end + 8, 10);
end+= 18;
/* write scramble tail */
- end= (char*)memcpy(end, data + SCRAMBLE_LENGTH_323,
- data_len - SCRAMBLE_LENGTH_323);
+ end= (char*) memcpy(end, data + SCRAMBLE_LENGTH_323,
+ data_len - SCRAMBLE_LENGTH_323);
end+= data_len - SCRAMBLE_LENGTH_323;
end= strmake(end, plugin_name(mpvio->plugin)->str,
plugin_name(mpvio->plugin)->length);
- int res= my_net_write(&mpvio->thd->net, (uchar*) buff, (size_t) (end-buff)) ||
+ int res= my_net_write(&mpvio->thd->net, (uchar*) buff,
+ (size_t) (end - buff + 1)) ||
net_flush(&mpvio->thd->net);
my_afree(buff);
- return res;
+ DBUG_RETURN (res);
}
static bool secure_auth(THD *thd)
@@ -7411,7 +8125,6 @@ static bool secure_auth(THD *thd)
@retval 0 ok
@retval 1 error
*/
-
static bool send_plugin_request_packet(MPVIO_EXT *mpvio,
const uchar *data, uint data_len)
{
@@ -7419,12 +8132,12 @@ static bool send_plugin_request_packet(MPVIO_EXT *mpvio,
DBUG_ASSERT(mpvio->packets_read == 1);
NET *net= &mpvio->thd->net;
static uchar switch_plugin_request_buf[]= { 254 };
-
+ DBUG_ENTER("send_plugin_request_packet");
mpvio->status= MPVIO_EXT::FAILURE; // the status is no longer RESTART
const char *client_auth_plugin=
- ((st_mysql_auth *)(plugin_decl(mpvio->plugin)->info))->client_auth_plugin;
+ ((st_mysql_auth *) (plugin_decl(mpvio->plugin)->info))->client_auth_plugin;
DBUG_ASSERT(client_auth_plugin);
DBUG_ASSERT(my_strcasecmp(system_charset_info, client_auth_plugin,
@@ -7444,9 +8157,9 @@ static bool send_plugin_request_packet(MPVIO_EXT *mpvio,
client_auth_plugin == old_password_plugin_name.str;
if (switch_from_long_to_short_scramble)
- return secure_auth(mpvio->thd) ||
- my_net_write(net, switch_plugin_request_buf, 1) ||
- net_flush(net);
+ DBUG_RETURN (secure_auth(mpvio->thd) ||
+ my_net_write(net, switch_plugin_request_buf, 1) ||
+ net_flush(net));
/*
We never request a client to switch from a short to long scramble.
@@ -7461,16 +8174,17 @@ static bool send_plugin_request_packet(MPVIO_EXT *mpvio,
{
my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0));
general_log_print(mpvio->thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE));
- return 1;
+ DBUG_RETURN (1);
}
- return net_write_command(net, switch_plugin_request_buf[0],
- (uchar*)client_auth_plugin,
- strlen(client_auth_plugin)+1,
- (uchar*)data, data_len);
+ DBUG_PRINT("info", ("requesting client to use the %s plugin",
+ client_auth_plugin));
+ DBUG_RETURN(net_write_command(net, switch_plugin_request_buf[0],
+ (uchar*) client_auth_plugin,
+ strlen(client_auth_plugin) + 1,
+ (uchar*) data, data_len));
}
-
#ifndef NO_EMBEDDED_ACCESS_CHECKS
/**
Finds acl entry in user database for authentication purposes.
@@ -7484,15 +8198,16 @@ static bool send_plugin_request_packet(MPVIO_EXT *mpvio,
@retval 0 found
@retval 1 not found
*/
-
-static bool find_mpvio_user(MPVIO_EXT *mpvio, Security_context *sctx)
+static bool find_mpvio_user(MPVIO_EXT *mpvio)
{
+ Security_context *sctx= mpvio->thd->security_ctx;
+ DBUG_ENTER("find_mpvio_user");
DBUG_ASSERT(mpvio->acl_user == 0);
mysql_mutex_lock(&acl_cache->lock);
- for (uint i=0 ; i < acl_users.elements ; i++)
+ for (uint i=0; i < acl_users.elements; i++)
{
- ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*);
+ ACL_USER *acl_user_tmp= dynamic_element(&acl_users, i, ACL_USER*);
if ((!acl_user_tmp->user || !strcmp(sctx->user, acl_user_tmp->user)) &&
compare_hostname(&acl_user_tmp->host, sctx->host, sctx->ip))
{
@@ -7505,7 +8220,7 @@ static bool find_mpvio_user(MPVIO_EXT *mpvio, Security_context *sctx)
if (!mpvio->acl_user)
{
login_failed_error(mpvio->thd, 0);
- return 1;
+ DBUG_RETURN (1);
}
/* user account requires non-default plugin and the client is too old */
@@ -7519,19 +8234,27 @@ static bool find_mpvio_user(MPVIO_EXT *mpvio, Security_context *sctx)
old_password_plugin_name.str));
my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0));
general_log_print(mpvio->thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE));
- return 1;
+ DBUG_RETURN (1);
}
mpvio->auth_info.user_name= sctx->user;
+ mpvio->auth_info.user_name_length= user_len;
mpvio->auth_info.auth_string= mpvio->acl_user->auth_string.str;
+ mpvio->auth_info.auth_string_length=
+ (unsigned long) mpvio->acl_user->auth_string.length;
strmake(mpvio->auth_info.authenticated_as, mpvio->acl_user->user ?
mpvio->acl_user->user : "", USERNAME_LENGTH);
- return 0;
+ DBUG_PRINT("info", ("exit: user=%s, auth_string=%s, authenticated as=%s"
+ "plugin=%s",
+ mpvio->auth_info.user_name,
+ mpvio->auth_info.auth_string,
+ mpvio->auth_info.authenticated_as,
+ mpvio->acl_user->plugin.str));
+ DBUG_RETURN(0);
}
#endif
-
/* the packet format is described in send_change_user_packet() */
static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length)
{
@@ -7542,17 +8265,18 @@ static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length)
char *user= (char*) net->read_pos;
char *end= user + packet_length;
/* Safe because there is always a trailing \0 at the end of the packet */
- char *passwd= strend(user)+1;
+ char *passwd= strend(user) + 1;
uint user_len= passwd - user - 1;
char *db= passwd;
char db_buff[SAFE_NAME_LEN + 1]; // buffer to store db in utf8
char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8
uint dummy_errors;
+ DBUG_ENTER ("parse_com_change_user_packet");
if (passwd >= end)
{
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
- return 1;
+ DBUG_RETURN (1);
}
/*
@@ -7566,7 +8290,7 @@ static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length)
*passwd > 127 and become 2**32-127+ after casting to uint.
*/
uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ?
- (uchar)(*passwd++) : strlen(passwd));
+ (uchar) (*passwd++) : strlen(passwd));
db+= passwd_len + 1;
/*
@@ -7576,37 +8300,37 @@ static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length)
if (db >= end)
{
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
- return 1;
+ DBUG_RETURN (1);
}
uint db_len= strlen(db);
char *ptr= db + db_len + 1;
- if (ptr+1 < end)
+ if (ptr + 1 < end)
{
- uint cs_number= uint2korr(ptr);
- thd_init_client_charset(thd, cs_number);
+ if (thd_init_client_charset(thd, uint2korr(ptr)))
+ DBUG_RETURN(1);
thd->update_charset();
}
/* Convert database and user names to utf8 */
- db_len= copy_and_convert(db_buff, sizeof(db_buff)-1, system_charset_info,
+ db_len= copy_and_convert(db_buff, sizeof(db_buff) - 1, system_charset_info,
db, db_len, thd->charset(), &dummy_errors);
- user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
+ user_len= copy_and_convert(user_buff, sizeof(user_buff) - 1,
system_charset_info, user, user_len,
thd->charset(), &dummy_errors);
if (!(sctx->user= my_strndup(user_buff, user_len, MYF(MY_WME))))
- return 1;
+ DBUG_RETURN(1);
/* Clear variables that are allocated */
thd->user_connect= 0;
strmake(sctx->priv_user, sctx->user, USERNAME_LENGTH);
if (thd->make_lex_string(&mpvio->db, db_buff, db_len, 0) == 0)
- return 1; /* The error is set by make_lex_string(). */
+ DBUG_RETURN(1); /* The error is set by make_lex_string(). */
/*
Clear thd->db as it points to something, that will be freed when
@@ -7619,12 +8343,12 @@ static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length)
{
// if mysqld's been started with --skip-grant-tables option
mpvio->status= MPVIO_EXT::SUCCESS;
- return 0;
+ DBUG_RETURN(0);
}
#ifndef NO_EMBEDDED_ACCESS_CHECKS
- if (find_mpvio_user(mpvio, sctx))
- return 1;
+ if (find_mpvio_user(mpvio))
+ DBUG_RETURN(1);
char *client_plugin;
if (thd->client_capabilities & CLIENT_PLUGIN_AUTH)
@@ -7633,7 +8357,7 @@ static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length)
if (client_plugin >= end)
{
my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0));
- return 1;
+ DBUG_RETURN(1);
}
client_plugin= fix_plugin_ptr(client_plugin);
}
@@ -7654,15 +8378,19 @@ static bool parse_com_change_user_packet(MPVIO_EXT *mpvio, uint packet_length)
mpvio->acl_user->plugin= old_password_plugin_name;
}
}
-
- /* remember the data part of the packet, to present it to plugin in read_packet() */
+
+ DBUG_PRINT("info", ("client_plugin=%s, restart", client_plugin));
+ /*
+ Remember the data part of the packet, to present it to plugin in
+ read_packet()
+ */
mpvio->cached_client_reply.pkt= passwd;
mpvio->cached_client_reply.pkt_len= passwd_len;
mpvio->cached_client_reply.plugin= client_plugin;
mpvio->status= MPVIO_EXT::RESTART;
#endif
- return 0;
+ DBUG_RETURN (0);
}
@@ -7686,36 +8414,34 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio,
ulong client_capabilities= uint2korr(net->read_pos);
if (client_capabilities & CLIENT_PROTOCOL_41)
{
- client_capabilities|= ((ulong) uint2korr(net->read_pos+2)) << 16;
- thd->max_client_packet_length= uint4korr(net->read_pos+4);
+ client_capabilities|= ((ulong) uint2korr(net->read_pos + 2)) << 16;
+ thd->max_client_packet_length= uint4korr(net->read_pos + 4);
DBUG_PRINT("info", ("client_character_set: %d", (uint) net->read_pos[8]));
- thd_init_client_charset(thd, (uint) net->read_pos[8]);
+ if (thd_init_client_charset(thd, (uint) net->read_pos[8]))
+ return packet_error;
thd->update_charset();
- end= (char*) net->read_pos+32;
+ end= (char*) net->read_pos + 32;
}
else
{
- thd->max_client_packet_length= uint3korr(net->read_pos+2);
- end= (char*) net->read_pos+5;
+ mpvio->max_client_packet_length= uint3korr(net->read_pos + 2);
+ end= (char*) net->read_pos + 5;
}
/* Disable those bits which are not supported by the client. */
thd->client_capabilities&= client_capabilities;
- if (thd->client_capabilities & CLIENT_IGNORE_SPACE)
- thd->variables.sql_mode|= MODE_IGNORE_SPACE;
-
DBUG_PRINT("info", ("client capabilities: %lu", thd->client_capabilities));
if (thd->client_capabilities & CLIENT_SSL)
{
- char error_string[1024] __attribute__((unused));
+ unsigned long errptr __attribute__((unused));
/* Do the SSL layering. */
if (!ssl_acceptor_fd)
return packet_error;
DBUG_PRINT("info", ("IO layer change in progress..."));
- if (sslaccept(ssl_acceptor_fd, net->vio, net->read_timeout, error_string))
+ if (sslaccept(ssl_acceptor_fd, net->vio, net->read_timeout, &errptr))
{
DBUG_PRINT("error", ("Failed to accept new SSL connection"));
return packet_error;
@@ -7731,11 +8457,14 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio,
}
}
+ if (thd->client_capabilities & CLIENT_IGNORE_SPACE)
+ thd->variables.sql_mode|= MODE_IGNORE_SPACE;
+ if (thd->client_capabilities & CLIENT_INTERACTIVE)
+ thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout;
+
if (end >= (char*) net->read_pos+ pkt_len +2)
return packet_error;
- if (thd->client_capabilities & CLIENT_INTERACTIVE)
- thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout;
if ((thd->client_capabilities & CLIENT_TRANSACTIONS) &&
opt_using_transactions)
net->return_status= &thd->server_status;
@@ -7781,12 +8510,12 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio,
/* Since 4.1 all database names are stored in utf8 */
if (db)
{
- db_len= copy_and_convert(db_buff, sizeof(db_buff)-1, system_charset_info,
+ db_len= copy_and_convert(db_buff, sizeof(db_buff) - 1, system_charset_info,
db, db_len, thd->charset(), &dummy_errors);
db= db_buff;
}
- user_len= copy_and_convert(user_buff, sizeof(user_buff)-1,
+ user_len= copy_and_convert(user_buff, sizeof(user_buff) - 1,
system_charset_info, user, user_len,
thd->charset(), &dummy_errors);
user= user_buff;
@@ -7806,6 +8535,7 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio,
if (!(sctx->user= my_strndup(user, user_len, MYF(MY_WME))))
return packet_error; /* The error is set by my_strdup(). */
+
/*
Clear thd->db as it points to something, that will be freed when
connection is closed. We don't want to accidentally free a wrong
@@ -7820,7 +8550,7 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio,
return packet_error;
}
- if (find_mpvio_user(mpvio, sctx))
+ if (find_mpvio_user(mpvio))
return packet_error;
if (thd->client_capabilities & CLIENT_PLUGIN_AUTH)
@@ -7874,22 +8604,22 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio,
doesn't need to know.
*/
const char *client_auth_plugin=
- ((st_mysql_auth *)(plugin_decl(mpvio->plugin)->info))->client_auth_plugin;
+ ((st_mysql_auth *) (plugin_decl(mpvio->plugin)->info))->client_auth_plugin;
if (client_auth_plugin &&
my_strcasecmp(system_charset_info, client_plugin, client_auth_plugin))
{
mpvio->cached_client_reply.plugin= client_plugin;
if (send_plugin_request_packet(mpvio,
- (uchar*)mpvio->cached_server_packet.pkt,
+ (uchar*) mpvio->cached_server_packet.pkt,
mpvio->cached_server_packet.pkt_len))
return packet_error;
passwd_len= my_net_read(&mpvio->thd->net);
- passwd = (char*)mpvio->thd->net.read_pos;
+ passwd= (char*)mpvio->thd->net.read_pos;
}
- *buff= (uchar*)passwd;
+ *buff= (uchar*) passwd;
return passwd_len;
#else
return 0;
@@ -7907,18 +8637,19 @@ static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio,
and handles plugin negotiation with the client. If necessary,
it escapes the plugin data, if it starts with a mysql protocol packet byte.
*/
-
static int server_mpvio_write_packet(MYSQL_PLUGIN_VIO *param,
const uchar *packet, int packet_len)
{
- MPVIO_EXT *mpvio= (MPVIO_EXT*)param;
+ MPVIO_EXT *mpvio= (MPVIO_EXT *) param;
int res;
+ DBUG_ENTER("server_mpvio_write_packet");
/* reset cached_client_reply */
mpvio->cached_client_reply.pkt= 0;
+
/* for the 1st packet we wrap plugin data into the handshake packet */
if (mpvio->packets_written == 0)
- res= send_server_handshake_packet(mpvio, (char*)packet, packet_len);
+ res= send_server_handshake_packet(mpvio, (char*) packet, packet_len);
else if (mpvio->status == MPVIO_EXT::RESTART)
res= send_plugin_request_packet(mpvio, packet, packet_len);
else if (packet_len > 0 && (*packet == 1 || *packet == 255 || *packet == 254))
@@ -7938,10 +8669,9 @@ static int server_mpvio_write_packet(MYSQL_PLUGIN_VIO *param,
net_flush(&mpvio->thd->net);
}
mpvio->packets_written++;
- return res;
+ DBUG_RETURN(res);
}
-
/**
vio->read_packet() callback method for server authentication plugins
@@ -7952,12 +8682,11 @@ static int server_mpvio_write_packet(MYSQL_PLUGIN_VIO *param,
a client authentication handshake packet, and handles plugin negotiation
with the client, if necessary.
*/
-
static int server_mpvio_read_packet(MYSQL_PLUGIN_VIO *param, uchar **buf)
{
- MPVIO_EXT *mpvio= (MPVIO_EXT*)param;
+ MPVIO_EXT *mpvio= (MPVIO_EXT *) param;
ulong pkt_len;
-
+ DBUG_ENTER("server_mpvio_read_packet");
if (mpvio->packets_written == 0)
{
/*
@@ -7969,8 +8698,7 @@ static int server_mpvio_read_packet(MYSQL_PLUGIN_VIO *param, uchar **buf)
else
pkt_len= my_net_read(&mpvio->thd->net);
}
- else
- if (mpvio->cached_client_reply.pkt)
+ else if (mpvio->cached_client_reply.pkt)
{
DBUG_ASSERT(mpvio->status == MPVIO_EXT::RESTART);
DBUG_ASSERT(mpvio->packets_read > 0);
@@ -7981,17 +8709,18 @@ static int server_mpvio_read_packet(MYSQL_PLUGIN_VIO *param, uchar **buf)
cached data straight away and avoid one round trip.
*/
const char *client_auth_plugin=
- ((st_mysql_auth *)(plugin_decl(mpvio->plugin)->info))->client_auth_plugin;
+ ((st_mysql_auth *) (plugin_decl(mpvio->plugin)->info))->client_auth_plugin;
if (client_auth_plugin == 0 ||
my_strcasecmp(system_charset_info, mpvio->cached_client_reply.plugin,
client_auth_plugin) == 0)
{
mpvio->status= MPVIO_EXT::FAILURE;
- *buf= (uchar*)mpvio->cached_client_reply.pkt;
+ *buf= (uchar*) mpvio->cached_client_reply.pkt;
mpvio->cached_client_reply.pkt= 0;
mpvio->packets_read++;
- return (int)mpvio->cached_client_reply.pkt_len;
+ DBUG_RETURN ((int) mpvio->cached_client_reply.pkt_len);
}
+
/*
But if the client has used the wrong plugin, the cached data are
useless. Furthermore, we have to send a "change plugin" request
@@ -8021,39 +8750,36 @@ static int server_mpvio_read_packet(MYSQL_PLUGIN_VIO *param, uchar **buf)
goto err;
}
else
- *buf = mpvio->thd->net.read_pos;
+ *buf= mpvio->thd->net.read_pos;
- return (int)pkt_len;
+ DBUG_RETURN((int)pkt_len);
err:
- if (mpvio->status == MPVIO_EXT::FAILURE && !mpvio->thd->is_error())
+ if (mpvio->status == MPVIO_EXT::FAILURE)
{
- inc_host_errors(mpvio->thd->main_security_ctx.ip);
- my_error(ER_HANDSHAKE_ERROR, MYF(0),
- mpvio->thd->security_ctx->host_or_ip);
+ inc_host_errors(mpvio->thd->security_ctx.ip);
+ if (!mpvio->thd->is_error())
+ my_error(ER_HANDSHAKE_ERROR, MYF(0));
}
- return -1;
+ DBUG_RETURN(-1);
}
-
/**
fills MYSQL_PLUGIN_VIO_INFO structure with the information about the
connection
*/
-
static void server_mpvio_info(MYSQL_PLUGIN_VIO *vio,
MYSQL_PLUGIN_VIO_INFO *info)
{
- MPVIO_EXT *mpvio= (MPVIO_EXT*)vio;
+ MPVIO_EXT *mpvio= (MPVIO_EXT *) vio;
mpvio_info(mpvio->thd->net.vio, info);
}
-
-static bool acl_check_ssl(THD *thd, ACL_USER *acl_user)
+static bool acl_check_ssl(THD *thd, const ACL_USER *acl_user)
{
-#if defined(HAVE_OPENSSL)
- Vio *vio=thd->net.vio;
- SSL *ssl= (SSL*) vio->ssl_arg;
+#ifdef HAVE_OPENSSL
+ Vio *vio= thd->net.vio;
+ SSL *ssl= (SSL *) vio->ssl_arg;
X509 *cert;
#endif
@@ -8067,7 +8793,7 @@ static bool acl_check_ssl(THD *thd, ACL_USER *acl_user)
case SSL_TYPE_NOT_SPECIFIED: // Impossible
case SSL_TYPE_NONE: // SSL is not required
return 0;
-#if defined(HAVE_OPENSSL)
+#ifdef HAVE_OPENSSL
case SSL_TYPE_ANY: // Any kind of SSL is ok
return vio_type(vio) != VIO_TYPE_SSL;
case SSL_TYPE_X509: /* Client should have any valid certificate. */
@@ -8093,9 +8819,9 @@ static bool acl_check_ssl(THD *thd, ACL_USER *acl_user)
return 1;
if (acl_user->ssl_cipher)
{
- DBUG_PRINT("info",("comparing ciphers: '%s' and '%s'",
- acl_user->ssl_cipher,SSL_get_cipher(ssl)));
- if (strcmp(acl_user->ssl_cipher,SSL_get_cipher(ssl)))
+ DBUG_PRINT("info", ("comparing ciphers: '%s' and '%s'",
+ acl_user->ssl_cipher, SSL_get_cipher(ssl)));
+ if (strcmp(acl_user->ssl_cipher, SSL_get_cipher(ssl)))
{
if (global_system_variables.log_warnings)
sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'",
@@ -8109,8 +8835,8 @@ static bool acl_check_ssl(THD *thd, ACL_USER *acl_user)
/* If X509 issuer is specified, we check it... */
if (acl_user->x509_issuer)
{
- char *ptr = X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
- DBUG_PRINT("info",("comparing issuers: '%s' and '%s'",
+ char *ptr= X509_NAME_oneline(X509_get_issuer_name(cert), 0, 0);
+ DBUG_PRINT("info", ("comparing issuers: '%s' and '%s'",
acl_user->x509_issuer, ptr));
if (strcmp(acl_user->x509_issuer, ptr))
{
@@ -8127,9 +8853,9 @@ static bool acl_check_ssl(THD *thd, ACL_USER *acl_user)
if (acl_user->x509_subject)
{
char *ptr= X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
- DBUG_PRINT("info",("comparing subjects: '%s' and '%s'",
+ DBUG_PRINT("info", ("comparing subjects: '%s' and '%s'",
acl_user->x509_subject, ptr));
- if (strcmp(acl_user->x509_subject,ptr))
+ if (strcmp(acl_user->x509_subject, ptr))
{
if (global_system_variables.log_warnings)
sql_print_information("X509 subject mismatch: should be '%s' but is '%s'",
@@ -8154,18 +8880,17 @@ static bool acl_check_ssl(THD *thd, ACL_USER *acl_user)
return 1;
}
-static int do_auth_once(THD *thd, LEX_STRING *auth_plugin_name,
+
+static int do_auth_once(THD *thd, const LEX_STRING *auth_plugin_name,
MPVIO_EXT *mpvio)
{
int res= CR_OK, old_status= MPVIO_EXT::FAILURE;
bool unlock_plugin= false;
- plugin_ref plugin;
+ plugin_ref plugin= NULL;
-#ifdef EMBEDDED_LIBRARY
- plugin= native_password_plugin;
-#else
if (auth_plugin_name->str == native_password_plugin_name.str)
plugin= native_password_plugin;
+#ifndef EMBEDDED_LIBRARY
else if (auth_plugin_name->str == old_password_plugin_name.str)
plugin= old_password_plugin;
else if ((plugin= my_plugin_lock_by_name(thd, auth_plugin_name,
@@ -8178,7 +8903,7 @@ static int do_auth_once(THD *thd, LEX_STRING *auth_plugin_name,
if (plugin)
{
- st_mysql_auth *auth= (st_mysql_auth*)plugin_decl(plugin)->info;
+ st_mysql_auth *auth= (st_mysql_auth *) plugin_decl(plugin)->info;
res= auth->authenticate_user(mpvio, &mpvio->auth_info);
if (unlock_plugin)
@@ -8205,6 +8930,7 @@ static int do_auth_once(THD *thd, LEX_STRING *auth_plugin_name,
return res;
}
+
/**
Perform the handshake, authorize the client and update thd sctx variables.
@@ -8219,12 +8945,12 @@ static int do_auth_once(THD *thd, LEX_STRING *auth_plugin_name,
@retval 0 success, thd is updated.
@retval 1 error
*/
-
-bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_len)
+bool acl_authenticate(THD *thd, uint connect_errors,
+ uint com_change_user_pkt_len)
{
int res= CR_OK;
MPVIO_EXT mpvio;
- LEX_STRING *auth_plugin_name= default_auth_plugin_name;
+ const LEX_STRING *auth_plugin_name= default_auth_plugin_name;
enum enum_server_command command= com_change_user_pkt_len ? COM_CHANGE_USER
: COM_CONNECT;
DBUG_ENTER("acl_authenticate");
@@ -8239,6 +8965,8 @@ bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_le
mpvio.connect_errors= connect_errors;
mpvio.status= MPVIO_EXT::FAILURE;
+ DBUG_PRINT("info", ("com_change_user_pkt_len=%u", com_change_user_pkt_len));
+
if (command == COM_CHANGE_USER)
{
mpvio.packets_written++; // pretend that a server handshake packet was sent
@@ -8261,7 +8989,8 @@ bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_le
with a user name, and performs the authentication if everyone has used
the correct plugin.
*/
- res= do_auth_once(thd, auth_plugin_name, &mpvio);
+
+ res= do_auth_once(thd, auth_plugin_name, &mpvio);
}
/*
@@ -8279,7 +9008,7 @@ bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_le
}
Security_context *sctx= thd->security_ctx;
- ACL_USER *acl_user= mpvio.acl_user;
+ const ACL_USER *acl_user= mpvio.acl_user;
thd->password= mpvio.auth_info.password_used; // remember for error messages
@@ -8313,12 +9042,59 @@ bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_le
DBUG_RETURN(1);
}
+ sctx->proxy_user[0]= 0;
+
if (initialized) // if not --skip-grant-tables
{
+#ifndef NO_EMBEDDED_ACCESS_CHECKS
+ bool is_proxy_user= FALSE;
+ const char *auth_user = acl_user->user ? acl_user->user : "";
+ ACL_PROXY_USER *proxy_user;
+ /* check if the user is allowed to proxy as another user */
+ proxy_user= acl_find_proxy_user(auth_user, sctx->host, sctx->ip,
+ mpvio.auth_info.authenticated_as,
+ &is_proxy_user);
+ if (is_proxy_user)
+ {
+ ACL_USER *acl_proxy_user;
+
+ /* we need to find the proxy user, but there was none */
+ if (!proxy_user)
+ {
+ if (!thd->is_error())
+ login_failed_error(&mpvio, mpvio.auth_info.password_used);
+ DBUG_RETURN(1);
+ }
+
+ my_snprintf(sctx->proxy_user, sizeof(sctx->proxy_user) - 1,
+ "'%s'@'%s'", auth_user,
+ acl_user->host.hostname ? acl_user->host.hostname : "");
+
+ /* we're proxying : find the proxy user definition */
+ mysql_mutex_lock(&acl_cache->lock);
+ acl_proxy_user= find_acl_user(proxy_user->get_proxied_host() ?
+ proxy_user->get_proxied_host() : "",
+ mpvio.auth_info.authenticated_as, TRUE);
+ if (!acl_proxy_user)
+ {
+ if (!thd->is_error())
+ login_failed_error(&mpvio, mpvio.auth_info.password_used);
+ mysql_mutex_unlock(&acl_cache->lock);
+ DBUG_RETURN(1);
+ }
+ acl_user= acl_proxy_user->copy(thd->mem_root);
+ mysql_mutex_unlock(&acl_cache->lock);
+ }
+#endif
+
sctx->master_access= acl_user->access;
- strmake(sctx->priv_user, mpvio.auth_info.authenticated_as, USERNAME_LENGTH);
+ if (acl_user->user)
+ strmake(sctx->priv_user, acl_user->user, USERNAME_LENGTH - 1);
+ else
+ *sctx->priv_user= 0;
+
if (acl_user->host.hostname)
- strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME);
+ strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME - 1);
else
*sctx->priv_host= 0;
@@ -8405,6 +9181,9 @@ bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_le
thd->net.net_skip_rest_factor= 2; // skip at most 2*max_packet_size
+ if (mpvio.auth_info.external_user[0])
+ sctx->external_user= my_strdup(mpvio.auth_info.external_user, MYF(0));
+
if (res == CR_OK_HANDSHAKE_COMPLETE)
thd->stmt_da->disable_status();
else
@@ -8414,7 +9193,6 @@ bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_le
DBUG_RETURN(0);
}
-
/**
MySQL Server Password Authentication Plugin
@@ -8423,14 +9201,14 @@ bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_le
2. client sends the encrypted password back to the server
3. the server checks the password.
*/
-
-static int native_password_authenticate(MYSQL_PLUGIN_VIO *vio,
+static int native_password_authenticate(MYSQL_PLUGIN_VIO *vio,
MYSQL_SERVER_AUTH_INFO *info)
{
uchar *pkt;
int pkt_len;
- MPVIO_EXT *mpvio=(MPVIO_EXT*)vio;
+ MPVIO_EXT *mpvio= (MPVIO_EXT *) vio;
THD *thd=mpvio->thd;
+ DBUG_ENTER("native_password_authenticate");
/* generate the scramble, or reuse the old one */
if (thd->scramble[SCRAMBLE_LENGTH])
@@ -8480,33 +9258,37 @@ static int native_password_authenticate(MYSQL_PLUGIN_VIO *vio,
/* read the reply with the encrypted password */
if ((pkt_len= mpvio->read_packet(mpvio, &pkt)) < 0)
- return CR_ERROR;
+ DBUG_RETURN(CR_ERROR);
+ DBUG_PRINT("info", ("reply read : pkt_len=%d", pkt_len));
#ifdef NO_EMBEDDED_ACCESS_CHECKS
- return CR_OK;
+ DBUG_RETURN(CR_OK);
#endif
if (pkt_len == 0) /* no password */
- return info->auth_string[0] ? CR_ERROR : CR_OK;
+ DBUG_RETURN(info->auth_string[0] ? CR_ERROR : CR_OK);
- info->password_used = 1;
+ info->password_used= PASSWORD_USED_YES;
if (pkt_len == SCRAMBLE_LENGTH)
- return info->auth_string[0] == 0 ||
- check_scramble(pkt, thd->scramble, mpvio->acl_user->salt) ?
- CR_ERROR : CR_OK;
+ {
+ if (!mpvio->acl_user->salt_len)
+ DBUG_RETURN(CR_ERROR);
+
+ DBUG_RETURN(check_scramble(pkt, thd->scramble, mpvio->acl_user->salt) ?
+ CR_ERROR : CR_OK);
+ }
inc_host_errors(mpvio->thd->main_security_ctx.ip);
- my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
- return CR_ERROR;
+ my_error(ER_HANDSHAKE_ERROR, MYF(0));
+ DBUG_RETURN(CR_ERROR);
}
-
static int old_password_authenticate(MYSQL_PLUGIN_VIO *vio,
MYSQL_SERVER_AUTH_INFO *info)
{
uchar *pkt;
int pkt_len;
- MPVIO_EXT *mpvio=(MPVIO_EXT*)vio;
+ MPVIO_EXT *mpvio= (MPVIO_EXT *) vio;
THD *thd=mpvio->thd;
/* generate the scramble, or reuse the old one */
@@ -8531,7 +9313,7 @@ static int old_password_authenticate(MYSQL_PLUGIN_VIO *vio,
the password is sent \0-terminated, the pkt_len is always 9 bytes.
We need to figure out the correct scramble length here.
*/
- if (pkt_len == SCRAMBLE_LENGTH_323+1)
+ if (pkt_len == SCRAMBLE_LENGTH_323 + 1)
pkt_len= strnlen((char*)pkt, pkt_len);
if (pkt_len == 0) /* no password */
@@ -8540,15 +9322,20 @@ static int old_password_authenticate(MYSQL_PLUGIN_VIO *vio,
if (secure_auth(thd))
return CR_ERROR;
- info->password_used = 1;
+ info->password_used= PASSWORD_USED_YES;
if (pkt_len == SCRAMBLE_LENGTH_323)
- return info->auth_string[0] == 0 ||
- check_scramble_323(pkt, thd->scramble,
- (ulong *)mpvio->acl_user->salt) ? CR_ERROR : CR_OK;
+ {
+ if (!mpvio->acl_user->salt_len)
+ return CR_ERROR;
+
+ return check_scramble_323(pkt, thd->scramble,
+ (ulong *) mpvio->acl_user->salt) ?
+ CR_ERROR : CR_OK;
+ }
inc_host_errors(mpvio->thd->main_security_ctx.ip);
- my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
+ my_error(ER_HANDSHAKE_ERROR, MYF(0));
return CR_ERROR;
}
diff --git a/sql/sql_acl.h b/sql/sql_acl.h
index 2a62b605678..3079f376bee 100644
--- a/sql/sql_acl.h
+++ b/sql/sql_acl.h
@@ -173,6 +173,14 @@ enum mysql_db_table_field
extern const TABLE_FIELD_DEF mysql_db_table_def;
extern bool mysql_user_table_is_in_short_password_format;
+
+static inline int access_denied_error_code(int passwd_used)
+{
+ return passwd_used == 2 ? ER_ACCESS_DENIED_NO_PASSWORD_ERROR
+ : ER_ACCESS_DENIED_ERROR;
+}
+
+
/* prototypes */
bool hostname_requires_resolving(const char *hostname);
@@ -190,7 +198,7 @@ int check_change_password(THD *thd, const char *host, const char *user,
bool change_password(THD *thd, const char *host, const char *user,
char *password);
bool mysql_grant(THD *thd, const char *db, List <LEX_USER> &user_list,
- ulong rights, bool revoke);
+ ulong rights, bool revoke, bool is_proxy);
int mysql_table_grant(THD *thd, TABLE_LIST *table, List <LEX_USER> &user_list,
List <LEX_COLUMN> &column_list, ulong rights,
bool revoke);
@@ -372,4 +380,6 @@ get_cached_table_access(GRANT_INTERNAL_INFO *grant_internal_info,
const char *schema_name,
const char *table_name);
+bool acl_check_proxy_grant_access (THD *thd, const char *host, const char *user,
+ bool with_grant);
#endif /* SQL_ACL_INCLUDED */
diff --git a/sql/sql_admin.cc b/sql/sql_admin.cc
index 874e91c4040..709d1b9a701 100644
--- a/sql/sql_admin.cc
+++ b/sql/sql_admin.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2010, 2011 Oracle and/or its affiliates. All rights reserved.
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
@@ -114,7 +114,7 @@ static int prepare_for_repair(THD *thd, TABLE_LIST *table_list,
key_length= create_table_def_key(thd, key, table_list, 0);
table_list->mdl_request.init(MDL_key::TABLE,
table_list->db, table_list->table_name,
- MDL_EXCLUSIVE);
+ MDL_EXCLUSIVE, MDL_TRANSACTION);
if (lock_table_names(thd, table_list, table_list->next_global,
thd->variables.lock_wait_timeout,
@@ -140,9 +140,6 @@ static int prepare_for_repair(THD *thd, TABLE_LIST *table_list,
table= &tmp_table;
}
- /* A MERGE table must not come here. */
- DBUG_ASSERT(table->file->ht->db_type != DB_TYPE_MRG_MYISAM);
-
/*
REPAIR TABLE ... USE_FRM for temporary tables makes little sense.
*/
@@ -180,6 +177,9 @@ static int prepare_for_repair(THD *thd, TABLE_LIST *table_list,
if (!ext[0] || !ext[1])
goto end; // No data file
+ /* A MERGE table must not come here. */
+ DBUG_ASSERT(table->file->ht->db_type != DB_TYPE_MRG_MYISAM);
+
// Name of data file
strxmov(from, table->s->normalized_path.str, ext[1], NullS);
if (!mysql_file_stat(key_file_misc, from, &stat_info, MYF(0)))
@@ -260,6 +260,26 @@ end:
}
+/**
+ Check if a given error is something that could occur during
+ open_and_lock_tables() that does not indicate table corruption.
+
+ @param sql_errno Error number to check.
+
+ @retval TRUE Error does not indicate table corruption.
+ @retval FALSE Error could indicate table corruption.
+*/
+
+static inline bool table_not_corrupt_error(uint sql_errno)
+{
+ return (sql_errno == ER_NO_SUCH_TABLE ||
+ sql_errno == ER_FILE_NOT_FOUND ||
+ sql_errno == ER_LOCK_WAIT_TIMEOUT ||
+ sql_errno == ER_LOCK_DEADLOCK ||
+ sql_errno == ER_CANT_LOCK_LOG_TABLE ||
+ sql_errno == ER_OPEN_AS_READONLY);
+}
+
/*
RETURN VALUES
@@ -272,7 +292,7 @@ static bool mysql_admin_table(THD* thd, TABLE_LIST* tables,
const char *operator_name,
thr_lock_type lock_type,
bool open_for_modify,
- bool no_warnings_for_error,
+ bool repair_table_use_frm,
uint extra_open_options,
int (*prepare_func)(THD *, TABLE_LIST *,
HA_CHECK_OPT *),
@@ -341,15 +361,54 @@ static bool mysql_admin_table(THD* thd, TABLE_LIST* tables,
lex->query_tables= table;
lex->query_tables_last= &table->next_global;
lex->query_tables_own_last= 0;
- thd->no_warnings_for_error= no_warnings_for_error;
+
if (view_operator_func == NULL)
table->required_type=FRMTYPE_TABLE;
- open_error= open_and_lock_tables(thd, table, TRUE, 0);
- thd->no_warnings_for_error= 0;
+ if (!thd->locked_tables_mode && repair_table_use_frm)
+ {
+ /*
+ If we're not under LOCK TABLES and we're executing REPAIR TABLE
+ USE_FRM, we need to ignore errors from open_and_lock_tables().
+ REPAIR TABLE USE_FRM is a heavy weapon used when a table is
+ critically damaged, so open_and_lock_tables() will most likely
+ report errors. Those errors are not interesting for the user
+ because it's already known that the table is badly damaged.
+ */
+
+ Warning_info wi(thd->query_id, false);
+ Warning_info *wi_saved= thd->warning_info;
+
+ thd->warning_info= &wi;
+
+ open_error= open_and_lock_tables(thd, table, TRUE, 0);
+
+ thd->warning_info= wi_saved;
+ }
+ else
+ {
+ /*
+ It's assumed that even if it is REPAIR TABLE USE_FRM, the table
+ can be opened if we're under LOCK TABLES (otherwise LOCK TABLES
+ would fail). Thus, the only errors we could have from
+ open_and_lock_tables() are logical ones, like incorrect locking
+ mode. It does make sense for the user to see such errors.
+ */
+
+ open_error= open_and_lock_tables(thd, table, TRUE, 0);
+ }
+
table->next_global= save_next_global;
table->next_local= save_next_local;
thd->open_options&= ~extra_open_options;
+
+ /*
+ If open_and_lock_tables() failed, close_thread_tables() will close
+ the table and table->table can therefore be invalid.
+ */
+ if (open_error)
+ table->table= NULL;
+
/*
Under locked tables, we know that the table can be opened,
so any errors opening the table are logical errors.
@@ -448,9 +507,7 @@ static bool mysql_admin_table(THD* thd, TABLE_LIST* tables,
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_VIEW_CHECKSUM, ER(ER_VIEW_CHECKSUM));
if (thd->stmt_da->is_error() &&
- (thd->stmt_da->sql_errno() == ER_NO_SUCH_TABLE ||
- thd->stmt_da->sql_errno() == ER_FILE_NOT_FOUND))
- /* A missing table is just issued as a failed command */
+ table_not_corrupt_error(thd->stmt_da->sql_errno()))
result_code= HA_ADMIN_FAILED;
else
/* Default failure code is corrupt table */
@@ -706,7 +763,7 @@ send_result_message:
protocol->store(operator_name, system_charset_info);
if (result_code) // either mysql_recreate_table or analyze failed
{
- DBUG_ASSERT(thd->is_error());
+ DBUG_ASSERT(thd->is_error() || thd->killed);
if (thd->is_error())
{
const char *err_msg= thd->stmt_da->message();
@@ -749,8 +806,12 @@ send_result_message:
size_t length;
protocol->store(STRING_WITH_LEN("error"), system_charset_info);
- length=my_snprintf(buf, sizeof(buf), ER(ER_TABLE_NEEDS_UPGRADE),
- table->table_name);
+ if (table->table->file->ha_table_flags() & HA_CAN_REPAIR)
+ length= my_snprintf(buf, sizeof(buf), ER(ER_TABLE_NEEDS_UPGRADE),
+ table->table_name);
+ else
+ length= my_snprintf(buf, sizeof(buf), ER(ER_TABLE_NEEDS_REBUILD),
+ table->table_name);
protocol->store(buf, length, system_charset_info);
fatal_error=1;
break;
diff --git a/sql/sql_alter.cc b/sql/sql_alter.cc
index 046e09b20a3..5af01523aa7 100644
--- a/sql/sql_alter.cc
+++ b/sql/sql_alter.cc
@@ -13,8 +13,7 @@
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
-#include "sql_parse.h" // check_access,
- // check_merge_table_access
+#include "sql_parse.h" // check_access
#include "sql_table.h" // mysql_alter_table,
// mysql_exchange_partition
#include "sql_alter.h"
@@ -60,11 +59,15 @@ bool Alter_table_statement::execute(THD *thd)
check_access(thd, INSERT_ACL | CREATE_ACL, select_lex->db,
&priv,
NULL, /* Don't use first_tab->grant with sel_lex->db */
- 0, 0) ||
- check_merge_table_access(thd, first_table->db,
- create_info.merge_list.first))
+ 0, 0))
DBUG_RETURN(TRUE); /* purecov: inspected */
+ /* If it is a merge table, check privileges for merge children. */
+ if (create_info.merge_list.first &&
+ check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
+ create_info.merge_list.first, FALSE, UINT_MAX, FALSE))
+ DBUG_RETURN(TRUE);
+
if (check_grant(thd, priv_needed, first_table, FALSE, UINT_MAX, FALSE))
DBUG_RETURN(TRUE); /* purecov: inspected */
diff --git a/sql/sql_analyse.cc b/sql/sql_analyse.cc
index 6dccd594588..3e83aceb03b 100644
--- a/sql/sql_analyse.cc
+++ b/sql/sql_analyse.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -242,7 +242,7 @@ bool test_if_number(NUM_INFO *info, const char *str, uint str_len)
if (str == end)
{
info->is_float = 1; // we can't use variable decimals here
- return 1;
+ DBUG_RETURN(1);
}
DBUG_RETURN(0);
}
@@ -522,9 +522,6 @@ void field_decimal::add()
{
found = 1;
min_arg = max_arg = sum[0] = *dec;
- min_arg.fix_buffer_pointer();
- max_arg.fix_buffer_pointer();
- sum[0].fix_buffer_pointer();
my_decimal_mul(E_DEC_FATAL_ERROR, sum_sqr, dec, dec);
cur_sum= 0;
min_length = max_length = length;
@@ -546,12 +543,10 @@ void field_decimal::add()
if (my_decimal_cmp(dec, &min_arg) < 0)
{
min_arg= *dec;
- min_arg.fix_buffer_pointer();
}
if (my_decimal_cmp(dec, &max_arg) > 0)
{
max_arg= *dec;
- max_arg.fix_buffer_pointer();
}
}
}
diff --git a/sql/sql_audit.cc b/sql/sql_audit.cc
index 3f5c96ef9ff..be837ec51ba 100644
--- a/sql/sql_audit.cc
+++ b/sql/sql_audit.cc
@@ -21,11 +21,18 @@ extern int finalize_audit_plugin(st_plugin_int *plugin);
#ifndef EMBEDDED_LIBRARY
+struct st_mysql_event_generic
+{
+ unsigned int event_class;
+ const void *event;
+};
+
unsigned long mysql_global_audit_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];
static mysql_mutex_t LOCK_audit_mask;
-static void event_class_dispatch(THD *thd, const struct mysql_event *event);
+static void event_class_dispatch(THD *thd, unsigned int event_class,
+ const void *event);
static inline
@@ -64,7 +71,6 @@ typedef void (*audit_handler_t)(THD *thd, uint event_subtype, va_list ap);
static void general_class_handler(THD *thd, uint event_subtype, va_list ap)
{
mysql_event_general event;
- event.event_class= MYSQL_AUDIT_GENERAL_CLASS;
event.event_subclass= event_subtype;
event.general_error_code= va_arg(ap, int);
event.general_thread_id= thd ? thd->thread_id : 0;
@@ -77,13 +83,37 @@ static void general_class_handler(THD *thd, uint event_subtype, va_list ap)
event.general_query_length= va_arg(ap, unsigned int);
event.general_charset= va_arg(ap, struct charset_info_st *);
event.general_rows= (unsigned long long) va_arg(ap, ha_rows);
- event_class_dispatch(thd, (const mysql_event*) &event);
+ event_class_dispatch(thd, MYSQL_AUDIT_GENERAL_CLASS, &event);
+}
+
+
+static void connection_class_handler(THD *thd, uint event_subclass, va_list ap)
+{
+ mysql_event_connection event;
+ event.event_subclass= event_subclass;
+ event.status= va_arg(ap, int);
+ event.thread_id= va_arg(ap, unsigned long);
+ event.user= va_arg(ap, const char *);
+ event.user_length= va_arg(ap, unsigned int);
+ event.priv_user= va_arg(ap, const char *);
+ event.priv_user_length= va_arg(ap, unsigned int);
+ event.external_user= va_arg(ap, const char *);
+ event.external_user_length= va_arg(ap, unsigned int);
+ event.proxy_user= va_arg(ap, const char *);
+ event.proxy_user_length= va_arg(ap, unsigned int);
+ event.host= va_arg(ap, const char *);
+ event.host_length= va_arg(ap, unsigned int);
+ event.ip= va_arg(ap, const char *);
+ event.ip_length= va_arg(ap, unsigned int);
+ event.database= va_arg(ap, const char *);
+ event.database_length= va_arg(ap, unsigned int);
+ event_class_dispatch(thd, MYSQL_AUDIT_CONNECTION_CLASS, &event);
}
static audit_handler_t audit_handlers[] =
{
- general_class_handler
+ general_class_handler, connection_class_handler
};
static const uint audit_handlers_count=
@@ -408,18 +438,19 @@ int finalize_audit_plugin(st_plugin_int *plugin)
static my_bool plugins_dispatch(THD *thd, plugin_ref plugin, void *arg)
{
- const struct mysql_event *event= (const struct mysql_event *) arg;
+ const struct st_mysql_event_generic *event_generic=
+ (const struct st_mysql_event_generic *) arg;
unsigned long event_class_mask[MYSQL_AUDIT_CLASS_MASK_SIZE];
st_mysql_audit *data= plugin_data(plugin, struct st_mysql_audit *);
- set_audit_mask(event_class_mask, event->event_class);
+ set_audit_mask(event_class_mask, event_generic->event_class);
/* Check to see if the plugin is interested in this event */
if (check_audit_mask(data->class_mask, event_class_mask))
return 0;
/* Actually notify the plugin */
- data->event_notify(thd, event);
+ data->event_notify(thd, event_generic->event_class, event_generic->event);
return 0;
}
@@ -432,15 +463,19 @@ static my_bool plugins_dispatch(THD *thd, plugin_ref plugin, void *arg)
@param[in] event
*/
-static void event_class_dispatch(THD *thd, const struct mysql_event *event)
+static void event_class_dispatch(THD *thd, unsigned int event_class,
+ const void *event)
{
+ struct st_mysql_event_generic event_generic;
+ event_generic.event_class= event_class;
+ event_generic.event= event;
/*
Check if we are doing a slow global dispatch. This event occurs when
thd == NULL as it is not associated with any particular thread.
*/
if (unlikely(!thd))
{
- plugin_foreach(thd, plugins_dispatch, MYSQL_AUDIT_PLUGIN, (void*) event);
+ plugin_foreach(thd, plugins_dispatch, MYSQL_AUDIT_PLUGIN, &event_generic);
}
else
{
@@ -451,7 +486,7 @@ static void event_class_dispatch(THD *thd, const struct mysql_event *event)
plugins_last= plugins + thd->audit_class_plugins.elements;
for (; plugins < plugins_last; plugins++)
- plugins_dispatch(thd, *plugins, (void*) event);
+ plugins_dispatch(thd, *plugins, &event_generic);
}
}
diff --git a/sql/sql_audit.h b/sql/sql_audit.h
index 953e41f1f06..da44c4a023b 100644
--- a/sql/sql_audit.h
+++ b/sql/sql_audit.h
@@ -17,6 +17,8 @@
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
+#include <my_global.h>
+
#include <mysql/plugin_audit.h>
#include "sql_class.h"
@@ -32,8 +34,12 @@ extern void mysql_audit_free_thd(THD *thd);
extern void mysql_audit_acquire_plugins(THD *thd, uint event_class);
+#ifndef EMBEDDED_LIBRARY
extern void mysql_audit_notify(THD *thd, uint event_class,
uint event_subtype, ...);
+#else
+#define mysql_audit_notify(...)
+#endif
extern void mysql_audit_release(THD *thd);
#define MAX_USER_HOST_SIZE 512
@@ -41,7 +47,7 @@ static inline uint make_user_name(THD *thd, char *buf)
{
Security_context *sctx= thd->security_ctx;
return strxnmov(buf, MAX_USER_HOST_SIZE,
- sctx->priv_user ? sctx->priv_user : "", "[",
+ sctx->priv_user[0] ? sctx->priv_user : "", "[",
sctx->user ? sctx->user : "", "] @ ",
sctx->host ? sctx->host : "", " [",
sctx->ip ? sctx->ip : "", "]", NullS) - buf;
@@ -84,6 +90,7 @@ void mysql_audit_general_log(THD *thd, time_t time,
event_subtype should be set to one of:
MYSQL_AUDIT_GENERAL_ERROR
MYSQL_AUDIT_GENERAL_RESULT
+ MYSQL_AUDIT_GENERAL_STATUS
@param[in] thd
@param[in] event_subtype Type of general audit event.
@@ -99,35 +106,68 @@ void mysql_audit_general(THD *thd, uint event_subtype,
{
time_t time= my_time(0);
uint msglen= msg ? strlen(msg) : 0;
- const char *query, *user;
- uint querylen, userlen;
+ const char *user;
+ uint userlen;
char user_buff[MAX_USER_HOST_SIZE];
- CHARSET_INFO *clientcs;
+ CSET_STRING query;
ha_rows rows;
if (thd)
{
- query= thd->query();
- querylen= thd->query_length();
+ query= thd->query_string;
user= user_buff;
userlen= make_user_name(thd, user_buff);
- clientcs= thd->variables.character_set_client;
rows= thd->warning_info->current_row_for_warning();
}
else
{
- query= user= 0;
- querylen= userlen= 0;
- clientcs= global_system_variables.character_set_client;
+ user= 0;
+ userlen= 0;
rows= 0;
}
mysql_audit_notify(thd, MYSQL_AUDIT_GENERAL_CLASS, event_subtype,
error_code, time, user, userlen, msg, msglen,
- query, querylen, clientcs, rows);
+ query.str(), query.length(), query.charset(), rows);
}
#endif
}
+#define MYSQL_AUDIT_NOTIFY_CONNECTION_CONNECT(thd) mysql_audit_notify(\
+ (thd), MYSQL_AUDIT_CONNECTION_CLASS, MYSQL_AUDIT_CONNECTION_CONNECT,\
+ (thd)->stmt_da->is_error() ? (thd)->stmt_da->sql_errno() : 0,\
+ (thd)->thread_id, (thd)->security_ctx->user,\
+ (thd)->security_ctx->user ? strlen((thd)->security_ctx->user) : 0,\
+ (thd)->security_ctx->priv_user, strlen((thd)->security_ctx->priv_user),\
+ (thd)->security_ctx->external_user,\
+ (thd)->security_ctx->external_user ?\
+ strlen((thd)->security_ctx->external_user) : 0,\
+ (thd)->security_ctx->proxy_user, strlen((thd)->security_ctx->proxy_user),\
+ (thd)->security_ctx->host,\
+ (thd)->security_ctx->host ? strlen((thd)->security_ctx->host) : 0,\
+ (thd)->security_ctx->ip,\
+ (thd)->security_ctx->ip ? strlen((thd)->security_ctx->ip) : 0,\
+ (thd)->db, (thd)->db ? strlen((thd)->db) : 0)
+
+#define MYSQL_AUDIT_NOTIFY_CONNECTION_DISCONNECT(thd, errcode)\
+ mysql_audit_notify(\
+ (thd), MYSQL_AUDIT_CONNECTION_CLASS, MYSQL_AUDIT_CONNECTION_DISCONNECT,\
+ (errcode), (thd)->thread_id, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
+
+#define MYSQL_AUDIT_NOTIFY_CONNECTION_CHANGE_USER(thd) mysql_audit_notify(\
+ (thd), MYSQL_AUDIT_CONNECTION_CLASS, MYSQL_AUDIT_CONNECTION_CHANGE_USER,\
+ (thd)->stmt_da->is_error() ? (thd)->stmt_da->sql_errno() : 0,\
+ (thd)->thread_id, (thd)->security_ctx->user,\
+ (thd)->security_ctx->user ? strlen((thd)->security_ctx->user) : 0,\
+ (thd)->security_ctx->priv_user, strlen((thd)->security_ctx->priv_user),\
+ (thd)->security_ctx->external_user,\
+ (thd)->security_ctx->external_user ?\
+ strlen((thd)->security_ctx->external_user) : 0,\
+ (thd)->security_ctx->proxy_user, strlen((thd)->security_ctx->proxy_user),\
+ (thd)->security_ctx->host,\
+ (thd)->security_ctx->host ? strlen((thd)->security_ctx->host) : 0,\
+ (thd)->security_ctx->ip,\
+ (thd)->security_ctx->ip ? strlen((thd)->security_ctx->ip) : 0,\
+ (thd)->db, (thd)->db ? strlen((thd)->db) : 0)
#endif /* SQL_AUDIT_INCLUDED */
diff --git a/sql/sql_base.cc b/sql/sql_base.cc
index 7116d046a8c..7e0d17d1b0e 100644
--- a/sql/sql_base.cc
+++ b/sql/sql_base.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -21,7 +21,7 @@
#include "sql_priv.h"
#include "unireg.h"
#include "debug_sync.h"
-#include "lock.h" // broadcast_refresh, mysql_lock_remove,
+#include "lock.h" // mysql_lock_remove,
// mysql_unlock_tables,
// mysql_lock_have_duplicate
#include "sql_show.h" // append_identifier
@@ -101,14 +101,11 @@ bool No_such_table_error_handler::safely_trapped_errors()
TABLE_SHAREs, refresh_version and the table id counter.
*/
mysql_mutex_t LOCK_open;
-mysql_mutex_t LOCK_dd_owns_lock_open;
-uint dd_owns_lock_open= 0;
#ifdef HAVE_PSI_INTERFACE
-static PSI_mutex_key key_LOCK_open, key_LOCK_dd_owns_lock_open;
+static PSI_mutex_key key_LOCK_open;
static PSI_mutex_info all_tdc_mutexes[]= {
- { &key_LOCK_open, "LOCK_open", PSI_FLAG_GLOBAL },
- { &key_LOCK_dd_owns_lock_open, "LOCK_dd_owns_lock_open", PSI_FLAG_GLOBAL }
+ { &key_LOCK_open, "LOCK_open", PSI_FLAG_GLOBAL }
};
/**
@@ -251,7 +248,8 @@ static void check_unused(void)
Length of key
*/
-uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
+uint create_table_def_key(THD *thd, char *key,
+ const TABLE_LIST *table_list,
bool tmp_table)
{
char *db_end= strnmov(key, table_list->db, MAX_DBKEY_LENGTH - 2);
@@ -306,8 +304,6 @@ bool table_def_init(void)
init_tdc_psi_keys();
#endif
mysql_mutex_init(key_LOCK_open, &LOCK_open, MY_MUTEX_INIT_FAST);
- mysql_mutex_init(key_LOCK_dd_owns_lock_open, &LOCK_dd_owns_lock_open,
- MY_MUTEX_INIT_FAST);
oldest_unused_share= &end_of_unused_share;
end_of_unused_share.prev= &oldest_unused_share;
@@ -351,7 +347,6 @@ void table_def_free(void)
table_def_inited= 0;
/* Free table definitions. */
my_hash_free(&table_def_cache);
- mysql_mutex_destroy(&LOCK_dd_owns_lock_open);
mysql_mutex_destroy(&LOCK_open);
}
DBUG_VOID_RETURN;
@@ -1036,7 +1031,7 @@ bool close_cached_tables(THD *thd, TABLE_LIST *tables,
table_list= table_list->next_global)
{
/* A check that the table was locked for write is done by the caller. */
- TABLE *table= find_table_for_mdl_upgrade(thd->open_tables, table_list->db,
+ TABLE *table= find_table_for_mdl_upgrade(thd, table_list->db,
table_list->table_name, TRUE);
/* May return NULL if this table has already been closed via an alias. */
@@ -1295,20 +1290,12 @@ static void mark_used_tables_as_free_for_reuse(THD *thd, TABLE *table)
static void close_open_tables(THD *thd)
{
- bool found_old_table= 0;
-
mysql_mutex_assert_not_owner(&LOCK_open);
DBUG_PRINT("info", ("thd->open_tables: 0x%lx", (long) thd->open_tables));
while (thd->open_tables)
- found_old_table|= close_thread_table(thd, &thd->open_tables);
-
- if (found_old_table)
- {
- /* Tell threads waiting for refresh that something has happened */
- broadcast_refresh();
- }
+ (void) close_thread_table(thd, &thd->open_tables);
}
@@ -1376,11 +1363,6 @@ close_all_tables_for_name(THD *thd, TABLE_SHARE *share,
/* Remove the table share from the cache. */
tdc_remove_table(thd, TDC_RT_REMOVE_ALL, db, table_name,
FALSE);
- /*
- There could be a FLUSH thread waiting
- on the table to go away. Wake it up.
- */
- broadcast_refresh();
}
@@ -2014,39 +1996,60 @@ void update_non_unique_table_error(TABLE_LIST *update,
}
+/**
+ Find temporary table specified by database and table names in the
+ THD::temporary_tables list.
+
+ @return TABLE instance if a temporary table has been found; NULL otherwise.
+*/
+
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name)
{
- TABLE_LIST table_list;
+ TABLE_LIST tl;
- table_list.db= (char*) db;
- table_list.table_name= (char*) table_name;
- return find_temporary_table(thd, &table_list);
+ tl.db= (char*) db;
+ tl.table_name= (char*) table_name;
+
+ return find_temporary_table(thd, &tl);
}
-TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list)
+/**
+ Find a temporary table specified by TABLE_LIST instance in the
+ THD::temporary_tables list.
+
+ @return TABLE instance if a temporary table has been found; NULL otherwise.
+*/
+
+TABLE *find_temporary_table(THD *thd, const TABLE_LIST *tl)
{
- char key[MAX_DBKEY_LENGTH];
- uint key_length;
- TABLE *table;
- DBUG_ENTER("find_temporary_table");
- DBUG_PRINT("enter", ("table: '%s'.'%s'",
- table_list->db, table_list->table_name));
+ char key[MAX_DBKEY_LENGTH];
+ uint key_length= create_table_def_key(thd, key, tl, 1);
- key_length= create_table_def_key(thd, key, table_list, 1);
- for (table=thd->temporary_tables ; table ; table= table->next)
+ return find_temporary_table(thd, key, key_length);
+}
+
+
+/**
+ Find a temporary table specified by a key in the THD::temporary_tables list.
+
+ @return TABLE instance if a temporary table has been found; NULL otherwise.
+*/
+
+TABLE *find_temporary_table(THD *thd,
+ const char *table_key,
+ uint table_key_length)
+{
+ for (TABLE *table= thd->temporary_tables; table; table= table->next)
{
- if (table->s->table_cache_key.length == key_length &&
- !memcmp(table->s->table_cache_key.str, key, key_length))
+ if (table->s->table_cache_key.length == table_key_length &&
+ !memcmp(table->s->table_cache_key.str, table_key, table_key_length))
{
- DBUG_PRINT("info",
- ("Found table. server_id: %u pseudo_thread_id: %lu",
- (uint) thd->server_id,
- (ulong) thd->variables.pseudo_thread_id));
- DBUG_RETURN(table);
+ return table;
}
}
- DBUG_RETURN(0); // Not a temporary table
+
+ return NULL;
}
@@ -2474,7 +2477,8 @@ open_table_get_mdl_lock(THD *thd, Open_table_context *ot_ctx,
mdl_request_shared.init(&mdl_request->key,
(flags & MYSQL_OPEN_FORCE_SHARED_MDL) ?
- MDL_SHARED : MDL_SHARED_HIGH_PRIO);
+ MDL_SHARED : MDL_SHARED_HIGH_PRIO,
+ MDL_TRANSACTION);
mdl_request= &mdl_request_shared;
}
@@ -2639,32 +2643,6 @@ bool open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
TMP_TABLE_KEY_EXTRA);
/*
- We need this to work for all tables, including temporary
- tables, for backwards compatibility. But not under LOCK
- TABLES, since under LOCK TABLES one can't use a non-prelocked
- table. This code only works for updates done inside DO/SELECT
- f1() statements, normal DML is handled by means of
- sql_command_flags.
- */
- if (global_read_lock && table_list->lock_type >= TL_WRITE_ALLOW_WRITE &&
- ! (flags & MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK) &&
- ! thd->locked_tables_mode)
- {
- /*
- Someone has issued FLUSH TABLES WITH READ LOCK and we want
- a write lock. Wait until the lock is gone.
- */
- if (thd->global_read_lock.wait_if_global_read_lock(thd, 1, 1))
- DBUG_RETURN(TRUE);
-
- if (thd->open_tables && thd->open_tables->s->version != refresh_version)
- {
- (void)ot_ctx->request_backoff_action(Open_table_context::OT_REOPEN_TABLES,
- NULL);
- DBUG_RETURN(TRUE);
- }
- }
- /*
Unless requested otherwise, try to resolve this table in the list
of temporary tables of this thread. In MySQL temporary tables
are always thread-local and "shadow" possible base tables with the
@@ -2835,6 +2813,59 @@ bool open_table(THD *thd, TABLE_LIST *table_list, MEM_ROOT *mem_root,
if (! (flags & MYSQL_OPEN_HAS_MDL_LOCK))
{
+ /*
+ We are not under LOCK TABLES and going to acquire write-lock/
+ modify the base table. We need to acquire protection against
+ global read lock until end of this statement in order to have
+ this statement blocked by active FLUSH TABLES WITH READ LOCK.
+
+ We don't block acquire this protection under LOCK TABLES as
+ such protection already acquired at LOCK TABLES time and
+ not released until UNLOCK TABLES.
+
+ We don't block statements which modify only temporary tables
+ as these tables are not preserved by backup by any form of
+ backup which uses FLUSH TABLES WITH READ LOCK.
+
+ TODO: The fact that we sometimes acquire protection against
+ GRL only when we encounter table to be write-locked
+ slightly increases probability of deadlock.
+ This problem will be solved once Alik pushes his
+ temporary table refactoring patch and we can start
+ pre-acquiring metadata locks at the beggining of
+ open_tables() call.
+ */
+ if (table_list->mdl_request.type >= MDL_SHARED_WRITE &&
+ ! (flags & (MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK |
+ MYSQL_OPEN_FORCE_SHARED_MDL |
+ MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
+ MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK)) &&
+ ! ot_ctx->has_protection_against_grl())
+ {
+ MDL_request protection_request;
+ MDL_deadlock_handler mdl_deadlock_handler(ot_ctx);
+
+ if (thd->global_read_lock.can_acquire_protection())
+ DBUG_RETURN(TRUE);
+
+ protection_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
+ MDL_STATEMENT);
+
+ /*
+ Install error handler which if possible will convert deadlock error
+ into request to back-off and restart process of opening tables.
+ */
+ thd->push_internal_handler(&mdl_deadlock_handler);
+ bool result= thd->mdl_context.acquire_lock(&protection_request,
+ ot_ctx->get_timeout());
+ thd->pop_internal_handler();
+
+ if (result)
+ DBUG_RETURN(TRUE);
+
+ ot_ctx->set_has_protection_against_grl();
+ }
+
if (open_table_get_mdl_lock(thd, ot_ctx, &table_list->mdl_request,
flags, &mdl_ticket) ||
mdl_ticket == NULL)
@@ -2913,8 +2944,12 @@ retry_share:
*/
if (check_and_update_table_version(thd, table_list, share))
goto err_unlock;
- if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)
+ if (table_list->i_s_requested_object & OPEN_TABLE_ONLY)
+ {
+ my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db,
+ table_list->table_name);
goto err_unlock;
+ }
/* Open view */
if (open_new_frm(thd, share, alias,
@@ -2942,7 +2977,11 @@ retry_share:
*/
if (table_list->i_s_requested_object & OPEN_VIEW_ONLY)
+ {
+ my_error(ER_NO_SUCH_TABLE, MYF(0), table_list->db,
+ table_list->table_name);
goto err_unlock;
+ }
if (!(flags & MYSQL_OPEN_IGNORE_FLUSH))
{
@@ -3056,47 +3095,16 @@ retry_share:
table->reginfo.lock_type=TL_READ; /* Assume read */
reset:
- DBUG_ASSERT(table->s->ref_count > 0 || table->s->tmp_table != NO_TMP_TABLE);
-
- if (thd->lex->need_correct_ident())
- table->alias_name_used= my_strcasecmp(table_alias_charset,
- table->s->table_name.str, alias);
- /* Fix alias if table name changes */
- if (strcmp(table->alias, alias))
- {
- uint length=(uint) strlen(alias)+1;
- table->alias= (char*) my_realloc((char*) table->alias, length,
- MYF(MY_WME));
- memcpy((char*) table->alias, alias, length);
- }
- table->tablenr=thd->current_tablenr++;
- table->used_fields=0;
- table->const_table=0;
- table->null_row= 0;
- table->maybe_null= 0;
- table->force_index= table->force_index_order= table->force_index_group= 0;
- table->status=STATUS_NO_RECORD;
- table->insert_values= 0;
- table->fulltext_searched= 0;
- table->file->ha_start_of_new_statement();
- table->reginfo.impossible_range= 0;
- /* Catch wrong handling of the auto_increment_field_not_null. */
- DBUG_ASSERT(!table->auto_increment_field_not_null);
- table->auto_increment_field_not_null= FALSE;
- if (table->timestamp_field)
- table->timestamp_field_type= table->timestamp_field->get_auto_set_type();
- table->pos_in_table_list= table_list;
- table_list->updatable= 1; // It is not derived table nor non-updatable VIEW
- table->clear_column_bitmaps();
- table_list->table= table;
/*
- Fill record with random values to find bugs where we access fields
- without first reading them.
+ Check that there is no reference to a condition from an earlier query
+ (cf. Bug#58553).
*/
- TRASH(table->record[0], table->s->reclength);
- DBUG_ASSERT(table->key_read == 0);
- /* Tables may be reused in a sub statement. */
- DBUG_ASSERT(! table->file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN));
+ DBUG_ASSERT(table->file->pushed_cond == NULL);
+ table_list->updatable= 1; // It is not derived table nor non-updatable VIEW
+ table_list->table= table;
+
+ table->init(thd, table_list);
+
DBUG_RETURN(FALSE);
err_lock:
@@ -3139,22 +3147,26 @@ TABLE *find_locked_table(TABLE *list, const char *db, const char *table_name)
lock from the list of open tables, emit error if no such table
found.
- @param list List of TABLE objects to be searched
+ @param thd Thread context
@param db Database name.
@param table_name Name of table.
@param no_error Don't emit error if no suitable TABLE
instance were found.
+ @note This function checks if the connection holds a global IX
+ metadata lock. If no such lock is found, it is not safe to
+ upgrade the lock and ER_TABLE_NOT_LOCKED_FOR_WRITE will be
+ reported.
+
@return Pointer to TABLE instance with MDL_SHARED_NO_WRITE,
MDL_SHARED_NO_READ_WRITE, or MDL_EXCLUSIVE metadata
lock, NULL otherwise.
*/
-TABLE *find_table_for_mdl_upgrade(TABLE *list, const char *db,
- const char *table_name,
- bool no_error)
+TABLE *find_table_for_mdl_upgrade(THD *thd, const char *db,
+ const char *table_name, bool no_error)
{
- TABLE *tab= find_locked_table(list, db, table_name);
+ TABLE *tab= find_locked_table(thd->open_tables, db, table_name);
if (!tab)
{
@@ -3162,19 +3174,29 @@ TABLE *find_table_for_mdl_upgrade(TABLE *list, const char *db,
my_error(ER_TABLE_NOT_LOCKED, MYF(0), table_name);
return NULL;
}
- else
+
+ /*
+ It is not safe to upgrade the metadata lock without a global IX lock.
+ This can happen with FLUSH TABLES <list> WITH READ LOCK as we in these
+ cases don't take a global IX lock in order to be compatible with
+ global read lock.
+ */
+ if (!thd->mdl_context.is_lock_owner(MDL_key::GLOBAL, "", "",
+ MDL_INTENTION_EXCLUSIVE))
{
- while (tab->mdl_ticket != NULL &&
- !tab->mdl_ticket->is_upgradable_or_exclusive() &&
- (tab= find_locked_table(tab->next, db, table_name)))
- continue;
- if (!tab)
- {
- if (!no_error)
- my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), table_name);
- return 0;
- }
+ if (!no_error)
+ my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), table_name);
+ return NULL;
}
+
+ while (tab->mdl_ticket != NULL &&
+ !tab->mdl_ticket->is_upgradable_or_exclusive() &&
+ (tab= find_locked_table(tab->next, db, table_name)))
+ continue;
+
+ if (!tab && !no_error)
+ my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0), table_name);
+
return tab;
}
@@ -3418,7 +3440,6 @@ unlink_all_closed_tables(THD *thd, MYSQL_LOCK *lock, size_t reopen_count)
close_thread_table(thd, &thd->open_tables);
}
- broadcast_refresh();
}
/* Exclude all closed tables from the LOCK TABLES list. */
for (TABLE_LIST *table_list= m_locked_tables; table_list; table_list=
@@ -3860,7 +3881,7 @@ static bool auto_repair_table(THD *thd, TABLE_LIST *table_list)
{
/* Give right error message */
thd->clear_error();
- my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str, my_errno);
+ my_error(ER_NOT_KEYFILE, MYF(0), share->table_name.str);
sql_print_error("Couldn't repair table: %s.%s", share->db.str,
share->table_name.str);
if (entry->file)
@@ -3895,7 +3916,8 @@ Open_table_context::Open_table_context(THD *thd, uint flags)
LONG_TIMEOUT : thd->variables.lock_wait_timeout),
m_flags(flags),
m_action(OT_NO_ACTION),
- m_has_locks(thd->mdl_context.has_locks())
+ m_has_locks(thd->mdl_context.has_locks()),
+ m_has_protection_against_grl(FALSE)
{}
@@ -4052,6 +4074,12 @@ recover_from_failed_open(THD *thd)
for safety.
*/
m_failed_table= NULL;
+ /*
+ Reset flag indicating that we have already acquired protection
+ against GRL. It is no longer valid as the corresponding lock was
+ released by close_tables_for_reopen().
+ */
+ m_has_protection_against_grl= FALSE;
/* Prepare for possible another back-off. */
m_action= OT_NO_ACTION;
return result;
@@ -4569,13 +4597,15 @@ lock_table_names(THD *thd,
! (flags & MYSQL_OPEN_SKIP_TEMPORARY) &&
find_temporary_table(thd, table))))
{
- if (schema_set.insert(table))
+ if (! (flags & MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK) &&
+ schema_set.insert(table))
return TRUE;
mdl_requests.push_front(&table->mdl_request);
}
}
- if (! mdl_requests.is_empty())
+ if (! (flags & MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK) &&
+ ! mdl_requests.is_empty())
{
/*
Scoped locks: Take intention exclusive locks on all involved
@@ -4588,11 +4618,20 @@ lock_table_names(THD *thd,
if (schema_request == NULL)
return TRUE;
schema_request->init(MDL_key::SCHEMA, table->db, "",
- MDL_INTENTION_EXCLUSIVE);
+ MDL_INTENTION_EXCLUSIVE,
+ MDL_TRANSACTION);
mdl_requests.push_front(schema_request);
}
- /* Take the global intention exclusive lock. */
- global_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE);
+
+ /*
+ Protect this statement against concurrent global read lock
+ by acquiring global intention exclusive lock with statement
+ duration.
+ */
+ if (thd->global_read_lock.can_acquire_protection())
+ return TRUE;
+ global_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
+ MDL_STATEMENT);
mdl_requests.push_front(&global_request);
}
@@ -4655,8 +4694,7 @@ open_tables_check_upgradable_mdl(THD *thd, TABLE_LIST *tables_start,
Note that find_table_for_mdl_upgrade() will report an error if
no suitable ticket is found.
*/
- if (!find_table_for_mdl_upgrade(thd->open_tables, table->db,
- table->table_name, FALSE))
+ if (!find_table_for_mdl_upgrade(thd, table->db, table->table_name, false))
return TRUE;
}
}
@@ -4713,6 +4751,14 @@ bool open_tables(THD *thd, TABLE_LIST **start, uint *counter, uint flags,
bool has_prelocking_list;
DBUG_ENTER("open_tables");
+ /* Accessing data in XA_IDLE or XA_PREPARED is not allowed. */
+ enum xa_states xa_state= thd->transaction.xid_state.xa_state;
+ if (*start && (xa_state == XA_IDLE || xa_state == XA_PREPARED))
+ {
+ my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[xa_state]);
+ DBUG_RETURN(true);
+ }
+
/*
temporary mem_root for new .frm parsing.
TODO: variables for size
@@ -5210,6 +5256,8 @@ static bool check_lock_and_start_stmt(THD *thd,
@param[in] lock_type lock to use for table
@param[in] flags options to be used while opening and locking
table (see open_table(), mysql_lock_tables())
+ @param[in] prelocking_strategy Strategy which specifies how prelocking
+ algorithm should work for this statement.
@return table
@retval != NULL OK, opened table returned
@@ -5235,7 +5283,8 @@ static bool check_lock_and_start_stmt(THD *thd,
*/
TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
- thr_lock_type lock_type, uint flags)
+ thr_lock_type lock_type, uint flags,
+ Prelocking_strategy *prelocking_strategy)
{
TABLE_LIST *save_next_global;
DBUG_ENTER("open_n_lock_single_table");
@@ -5251,7 +5300,8 @@ TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
table_l->required_type= FRMTYPE_TABLE;
/* Open the table. */
- if (open_and_lock_tables(thd, table_l, FALSE, flags))
+ if (open_and_lock_tables(thd, table_l, FALSE, flags,
+ prelocking_strategy))
table_l->table= NULL; /* Just to be sure. */
/* Restore list. */
@@ -5360,7 +5410,11 @@ TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type lock_type,
end:
if (table == NULL)
+ {
+ if (!thd->in_sub_stmt)
+ trans_rollback_stmt(thd);
close_thread_tables(thd);
+ }
thd_proc_info(thd, 0);
DBUG_RETURN(table);
}
@@ -5391,7 +5445,7 @@ bool open_and_lock_tables(THD *thd, TABLE_LIST *tables,
Prelocking_strategy *prelocking_strategy)
{
uint counter;
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
DBUG_ENTER("open_and_lock_tables");
DBUG_PRINT("enter", ("derived handling: %d", derived));
@@ -5407,11 +5461,19 @@ bool open_and_lock_tables(THD *thd, TABLE_LIST *tables,
if (lock_tables(thd, tables, counter, flags))
goto err;
- if (derived &&
- (mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
- (thd->fill_derived_tables() &&
- mysql_handle_derived(thd->lex, &mysql_derived_filling))))
- goto err;
+ if (derived)
+ {
+ if (mysql_handle_derived(thd->lex, &mysql_derived_prepare))
+ goto err;
+ if (thd->fill_derived_tables() &&
+ mysql_handle_derived(thd->lex, &mysql_derived_filling))
+ {
+ mysql_handle_derived(thd->lex, &mysql_derived_cleanup);
+ goto err;
+ }
+ if (!thd->lex->describe)
+ mysql_handle_derived(thd->lex, &mysql_derived_cleanup);
+ }
DBUG_RETURN(FALSE);
err:
@@ -5448,7 +5510,7 @@ bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags)
{
DML_prelocking_strategy prelocking_strategy;
uint counter;
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
DBUG_ENTER("open_normal_and_derived_tables");
DBUG_ASSERT(!thd->fill_derived_tables());
if (open_tables(thd, &tables, &counter, flags, &prelocking_strategy) ||
@@ -5705,7 +5767,7 @@ bool lock_tables(THD *thd, TABLE_LIST *tables, uint count,
*/
void close_tables_for_reopen(THD *thd, TABLE_LIST **tables,
- MDL_ticket *start_of_statement_svp)
+ const MDL_savepoint &start_of_statement_svp)
{
TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table();
TABLE_LIST *tmp;
@@ -5743,35 +5805,37 @@ void close_tables_for_reopen(THD *thd, TABLE_LIST **tables,
}
-/*
- Open a single table without table caching and don't set it in open_list
-
- SYNPOSIS
- open_temporary_table()
- thd Thread object
- path Path (without .frm)
- db database
- table_name Table name
- link_in_list 1 if table should be linked into thd->temporary_tables
-
- NOTES:
- Used by alter_table to open a temporary table and when creating
- a temporary table with CREATE TEMPORARY ...
-
- RETURN
- 0 Error
- # TABLE object
+/**
+ Open a single table without table caching and don't add it to
+ THD::open_tables. Depending on the 'add_to_temporary_tables_list' value,
+ the opened TABLE instance will be addded to THD::temporary_tables list.
+
+ @param thd Thread context.
+ @param path Path (without .frm)
+ @param db Database name.
+ @param table_name Table name.
+ @param add_to_temporary_tables_list Specifies if the opened TABLE
+ instance should be linked into
+ THD::temporary_tables list.
+
+ @note This function is used:
+ - by alter_table() to open a temporary table;
+ - when creating a temporary table with CREATE TEMPORARY TABLE.
+
+ @return TABLE instance for opened table.
+ @retval NULL on error.
*/
-TABLE *open_temporary_table(THD *thd, const char *path, const char *db,
- const char *table_name, bool link_in_list)
+TABLE *open_table_uncached(THD *thd, const char *path, const char *db,
+ const char *table_name,
+ bool add_to_temporary_tables_list)
{
TABLE *tmp_table;
TABLE_SHARE *share;
char cache_key[MAX_DBKEY_LENGTH], *saved_cache_key, *tmp_path;
uint key_length;
TABLE_LIST table_list;
- DBUG_ENTER("open_temporary_table");
+ DBUG_ENTER("open_table_uncached");
DBUG_PRINT("enter",
("table: '%s'.'%s' path: '%s' server_id: %u "
"pseudo_thread_id: %lu",
@@ -5814,7 +5878,7 @@ TABLE *open_temporary_table(THD *thd, const char *path, const char *db,
share->tmp_table= (tmp_table->file->has_transactions() ?
TRANSACTIONAL_TMP_TABLE : NON_TRANSACTIONAL_TMP_TABLE);
- if (link_in_list)
+ if (add_to_temporary_tables_list)
{
/* growing temp list at the head */
tmp_table->next= thd->temporary_tables;
@@ -6144,6 +6208,8 @@ find_field_in_natural_join(THD *thd, TABLE_LIST *table_ref, const char *name,
/*
Find field by name in a base table or a view with temp table algorithm.
+ The caller is expected to check column-level privileges.
+
SYNOPSIS
find_field_in_table()
thd thread handler
@@ -6251,6 +6317,8 @@ find_field_in_table(THD *thd, TABLE *table, const char *name, uint length,
This procedure detects the type of the table reference 'table_list'
and calls the corresponding search routine.
+ The routine checks column-level privieleges for the found field.
+
RETURN
0 field is not found
view_ref_found found value in VIEW (real result is in *ref)
@@ -6526,8 +6594,16 @@ find_field_in_tables(THD *thd, Item_ident *item,
when table_ref->field_translation != NULL.
*/
if (table_ref->table && !table_ref->view)
+ {
found= find_field_in_table(thd, table_ref->table, name, length,
TRUE, &(item->cached_field_index));
+#ifndef NO_EMBEDDED_ACCESS_CHECKS
+ /* Check if there are sufficient access rights to the found field. */
+ if (found && check_privileges &&
+ check_column_grant_in_table_ref(thd, table_ref, name, length))
+ found= WRONG_GRANT;
+#endif
+ }
else
found= find_field_in_table_ref(thd, table_ref, name, length, item->name,
NULL, NULL, ref, check_privileges,
@@ -7567,9 +7643,10 @@ static bool setup_natural_join_row_types(THD *thd,
List<TABLE_LIST> *from_clause,
Name_resolution_context *context)
{
+ DBUG_ENTER("setup_natural_join_row_types");
thd->where= "from clause";
if (from_clause->elements == 0)
- return FALSE; /* We come here in the case of UNIONs. */
+ DBUG_RETURN(false); /* We come here in the case of UNIONs. */
List_iterator_fast<TABLE_LIST> table_ref_it(*from_clause);
TABLE_LIST *table_ref; /* Current table reference. */
@@ -7577,10 +7654,6 @@ static bool setup_natural_join_row_types(THD *thd,
TABLE_LIST *left_neighbor;
/* Table reference to the right of the current. */
TABLE_LIST *right_neighbor= NULL;
- bool save_first_natural_join_processing=
- context->select_lex->first_natural_join_processing;
-
- context->select_lex->first_natural_join_processing= FALSE;
/* Note that tables in the list are in reversed order */
for (left_neighbor= table_ref_it++; left_neighbor ; )
@@ -7592,12 +7665,11 @@ static bool setup_natural_join_row_types(THD *thd,
1) for stored procedures,
2) for multitable update after lock failure and table reopening.
*/
- if (save_first_natural_join_processing)
+ if (context->select_lex->first_natural_join_processing)
{
- context->select_lex->first_natural_join_processing= FALSE;
if (store_top_level_join_columns(thd, table_ref,
left_neighbor, right_neighbor))
- return TRUE;
+ DBUG_RETURN(true);
if (left_neighbor)
{
TABLE_LIST *first_leaf_on_the_right;
@@ -7617,8 +7689,9 @@ static bool setup_natural_join_row_types(THD *thd,
DBUG_ASSERT(right_neighbor);
context->first_name_resolution_table=
right_neighbor->first_leaf_for_name_resolution();
+ context->select_lex->first_natural_join_processing= false;
- return FALSE;
+ DBUG_RETURN (false);
}
@@ -7892,7 +7965,7 @@ bool setup_tables(THD *thd, Name_resolution_context *context,
}
if (tablenr > MAX_TABLES)
{
- my_error(ER_TOO_MANY_TABLES,MYF(0),MAX_TABLES);
+ my_error(ER_TOO_MANY_TABLES,MYF(0), static_cast<int>(MAX_TABLES));
DBUG_RETURN(1);
}
for (table_list= tables;
diff --git a/sql/sql_base.h b/sql/sql_base.h
index 2f365771416..a79c1a28e39 100644
--- a/sql/sql_base.h
+++ b/sql/sql_base.h
@@ -1,4 +1,4 @@
-/* Copyright 2006-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -17,7 +17,6 @@
#define SQL_BASE_INCLUDED
#include "unireg.h" // REQUIRED: for other includes
-#include "table.h" /* open_table_mode */
#include "sql_trigger.h" /* trg_event_type */
#include "sql_class.h" /* enum_mark_columns */
#include "mysqld.h" /* key_map */
@@ -71,8 +70,6 @@ enum enum_tdc_remove_table_type {TDC_RT_REMOVE_ALL, TDC_RT_REMOVE_NOT_OWN,
bool check_dup(const char *db, const char *name, TABLE_LIST *tables);
extern mysql_mutex_t LOCK_open;
-extern mysql_mutex_t LOCK_dd_owns_lock_open;
-extern uint dd_owns_lock_open;
bool table_cache_init(void);
void table_cache_free(void);
bool table_def_init(void);
@@ -81,7 +78,8 @@ void table_def_start_shutdown(void);
void assign_new_table_id(TABLE_SHARE *share);
uint cached_open_tables(void);
uint cached_table_definitions(void);
-uint create_table_def_key(THD *thd, char *key, TABLE_LIST *table_list,
+uint create_table_def_key(THD *thd, char *key,
+ const TABLE_LIST *table_list,
bool tmp_table);
TABLE_SHARE *get_table_share(THD *thd, TABLE_LIST *table_list, char *key,
uint key_length, uint db_flags, int *error,
@@ -124,6 +122,11 @@ TABLE *open_ltable(THD *thd, TABLE_LIST *table_list, thr_lock_type update,
(LONG_TIMEOUT = 1 year) rather than the user-supplied timeout value.
*/
#define MYSQL_LOCK_IGNORE_TIMEOUT 0x0800
+/**
+ When acquiring "strong" (SNW, SNRW, X) metadata locks on tables to
+ be open do not acquire global and schema-scope IX locks.
+*/
+#define MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK 0x1000
/** Please refer to the internals manual. */
#define MYSQL_OPEN_REOPEN (MYSQL_OPEN_IGNORE_FLUSH |\
@@ -143,8 +146,9 @@ bool open_new_frm(THD *thd, TABLE_SHARE *share, const char *alias,
bool get_key_map_from_key_list(key_map *map, TABLE *table,
List<String> *index_list);
-TABLE *open_temporary_table(THD *thd, const char *path, const char *db,
- const char *table_name, bool link_in_list);
+TABLE *open_table_uncached(THD *thd, const char *path, const char *db,
+ const char *table_name,
+ bool add_to_temporary_tables_list);
TABLE *find_locked_table(TABLE *list, const char *db, const char *table_name);
TABLE *find_write_locked_table(TABLE *list, const char *db,
const char *table_name);
@@ -155,13 +159,15 @@ thr_lock_type read_lock_type_for_table(THD *thd,
my_bool mysql_rm_tmp_tables(void);
bool rm_temporary_table(handlerton *base, char *path);
void close_tables_for_reopen(THD *thd, TABLE_LIST **tables,
- MDL_ticket *start_of_statement_svp);
+ const MDL_savepoint &start_of_statement_svp);
TABLE_LIST *find_table_in_list(TABLE_LIST *table,
TABLE_LIST *TABLE_LIST::*link,
const char *db_name,
const char *table_name);
TABLE *find_temporary_table(THD *thd, const char *db, const char *table_name);
-TABLE *find_temporary_table(THD *thd, TABLE_LIST *table_list);
+TABLE *find_temporary_table(THD *thd, const TABLE_LIST *tl);
+TABLE *find_temporary_table(THD *thd, const char *table_key,
+ uint table_key_length);
void close_thread_tables(THD *thd);
bool fill_record_n_invoke_before_triggers(THD *thd, List<Item> &fields,
List<Item> &values,
@@ -237,10 +243,10 @@ bool open_tables(THD *thd, TABLE_LIST **tables, uint *counter, uint flags,
bool open_and_lock_tables(THD *thd, TABLE_LIST *tables,
bool derived, uint flags,
Prelocking_strategy *prelocking_strategy);
-int open_and_lock_tables_derived(THD *thd, TABLE_LIST *tables, bool derived);
/* simple open_and_lock_tables without derived handling for single table */
TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
- thr_lock_type lock_type, uint flags);
+ thr_lock_type lock_type, uint flags,
+ Prelocking_strategy *prelocking_strategy);
bool open_normal_and_derived_tables(THD *thd, TABLE_LIST *tables, uint flags);
bool lock_tables(THD *thd, TABLE_LIST *tables, uint counter, uint flags);
int decide_logging_format(THD *thd, TABLE_LIST *tables);
@@ -284,7 +290,7 @@ bool tdc_open_view(THD *thd, TABLE_LIST *table_list, const char *alias,
char *cache_key, uint cache_key_length,
MEM_ROOT *mem_root, uint flags);
void tdc_flush_unused_tables();
-TABLE *find_table_for_mdl_upgrade(TABLE *list, const char *db,
+TABLE *find_table_for_mdl_upgrade(THD *thd, const char *db,
const char *table_name,
bool no_error);
void mark_tmp_table_for_reuse(TABLE *table);
@@ -450,6 +456,16 @@ open_tables(THD *thd, TABLE_LIST **tables, uint *counter, uint flags)
}
+inline TABLE *open_n_lock_single_table(THD *thd, TABLE_LIST *table_l,
+ thr_lock_type lock_type, uint flags)
+{
+ DML_prelocking_strategy prelocking_strategy;
+
+ return open_n_lock_single_table(thd, table_l, lock_type, flags,
+ &prelocking_strategy);
+}
+
+
/* open_and_lock_tables with derived handling */
inline bool open_and_lock_tables(THD *thd, TABLE_LIST *tables,
bool derived, uint flags)
@@ -492,7 +508,7 @@ public:
the statement, so that we can rollback to it before waiting on
locks.
*/
- MDL_ticket *start_of_statement_svp() const
+ const MDL_savepoint &start_of_statement_svp() const
{
return m_start_of_statement_svp;
}
@@ -503,6 +519,21 @@ public:
}
uint get_flags() const { return m_flags; }
+
+ /**
+ Set flag indicating that we have already acquired metadata lock
+ protecting this statement against GRL while opening tables.
+ */
+ void set_has_protection_against_grl()
+ {
+ m_has_protection_against_grl= TRUE;
+ }
+
+ bool has_protection_against_grl() const
+ {
+ return m_has_protection_against_grl;
+ }
+
private:
/**
For OT_DISCOVER and OT_REPAIR actions, the table list element for
@@ -510,7 +541,7 @@ private:
should be repaired.
*/
TABLE_LIST *m_failed_table;
- MDL_ticket *m_start_of_statement_svp;
+ MDL_savepoint m_start_of_statement_svp;
/**
Lock timeout in seconds. Initialized to LONG_TIMEOUT when opening system
tables or to the "lock_wait_timeout" system variable for regular tables.
@@ -526,6 +557,11 @@ private:
and we can't safely do back-off (and release them).
*/
bool m_has_locks;
+ /**
+ Indicates that in the process of opening tables we have acquired
+ protection against global read lock.
+ */
+ bool m_has_protection_against_grl;
};
diff --git a/sql/sql_binlog.cc b/sql/sql_binlog.cc
index 76c6e0e058a..f08125ca22f 100644
--- a/sql/sql_binlog.cc
+++ b/sql/sql_binlog.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2005-2006 MySQL AB
+/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -61,6 +61,13 @@ void mysql_client_binlog_statement(THD* thd)
size_t decoded_len= base64_needed_decoded_length(coded_len);
/*
+ option_bits will be changed when applying the event. But we don't expect
+ it be changed permanently after BINLOG statement, so backup it first.
+ It will be restored at the end of this function.
+ */
+ ulonglong thd_options= thd->variables.option_bits;
+
+ /*
Allocation
*/
@@ -235,7 +242,7 @@ void mysql_client_binlog_statement(THD* thd)
TODO: Maybe a better error message since the BINLOG statement
now contains several events.
*/
- my_error(ER_UNKNOWN_ERROR, MYF(0), "Error executing BINLOG statement");
+ my_error(ER_UNKNOWN_ERROR, MYF(0));
goto end;
}
}
@@ -246,6 +253,7 @@ void mysql_client_binlog_statement(THD* thd)
my_ok(thd);
end:
+ thd->variables.option_bits= thd_options;
rli->slave_close_thread_tables(thd);
my_free(buf);
DBUG_VOID_RETURN;
diff --git a/sql/sql_cache.cc b/sql/sql_cache.cc
index 30dd835e9eb..feb9614efe7 100644
--- a/sql/sql_cache.cc
+++ b/sql/sql_cache.cc
@@ -334,6 +334,7 @@ TODO list:
#include "tztime.h" // struct Time_zone
#include "sql_acl.h" // SELECT_ACL
#include "sql_base.h" // TMP_TABLE_KEY_EXTRA
+#include "debug_sync.h" // DEBUG_SYNC
#ifdef HAVE_QUERY_CACHE
#include <m_ctype.h>
#include <my_dir.h>
@@ -342,6 +343,7 @@ TODO list:
#include "../storage/myisammrg/myrg_def.h"
#include "probes_mysql.h"
#include "log_slow.h"
+#include "transaction.h"
#ifdef EMBEDDED_LIBRARY
#include "emb_qcache.h"
@@ -371,42 +373,6 @@ TODO list:
__LINE__,(ulong)(B)));B->query()->unlock_reading();}
#define DUMP(C) DBUG_EXECUTE("qcache", {\
(C)->cache_dump(); (C)->queries_dump();(C)->tables_dump();})
-
-
-/**
- Causes the thread to wait in a spin lock for a query kill signal.
- This function is used by the test frame work to identify race conditions.
-
- The signal is caught and ignored and the thread is not killed.
-*/
-
-static void debug_wait_for_kill(const char *info)
-{
- const char *prev_info;
- THD *thd;
- char buff[1024];
- DBUG_ENTER("debug_wait_for_kill");
-
- thd= current_thd;
- prev_info= thd->proc_info;
- thd->proc_info= info;
- sql_print_information("%s", info);
- while(!thd->killed)
- my_sleep(1000);
- thd->killed= THD::NOT_KILLED;
- /*
- Remove the set debug variable, to ensure we don't get stuck on it again
- This is needed as for MyISAM, invalidate_table() may be called twice
- (Once from mysql_delete() and once from mi_update_status())
- */
- sprintf(buff, "-d,%s", info);
- DBUG_SET(buff);
- sql_print_information("Exit debug_wait_for_kill");
- thd->proc_info= prev_info;
-
- DBUG_VOID_RETURN;
-}
-
#else
#define RW_WLOCK(M) mysql_rwlock_wrlock(M)
#define RW_RLOCK(M) mysql_rwlock_rdlock(M)
@@ -418,6 +384,52 @@ static void debug_wait_for_kill(const char *info)
#define DUMP(C)
#endif
+
+/**
+ Macro that executes the requested action at a synchronization point
+ only if the thread has a associated THD session.
+*/
+#if defined(ENABLED_DEBUG_SYNC)
+#define QC_DEBUG_SYNC(name) \
+ do { \
+ THD *thd= current_thd; \
+ if (thd) \
+ DEBUG_SYNC(thd, name); \
+ } while (0)
+#else
+#define QC_DEBUG_SYNC(name)
+#endif
+
+
+/**
+ Thread state to be used when the query cache lock needs to be acquired.
+ Sets the thread state name in the constructor, resets on destructor.
+*/
+
+struct Query_cache_wait_state
+{
+ THD *m_thd;
+ const char *m_proc_info;
+
+ Query_cache_wait_state(THD *thd, const char *func,
+ const char *file, unsigned int line)
+ : m_thd(thd),
+ m_proc_info(NULL)
+ {
+ if (m_thd)
+ m_proc_info= set_thd_proc_info(m_thd,
+ "Waiting for query cache lock",
+ func, file, line);
+ }
+
+ ~Query_cache_wait_state()
+ {
+ if (m_thd)
+ set_thd_proc_info(m_thd, m_proc_info, NULL, NULL, 0);
+ }
+};
+
+
/**
Serialize access to the query cache.
If the lock cannot be granted the thread hangs in a conditional wait which
@@ -439,6 +451,8 @@ static void debug_wait_for_kill(const char *info)
bool Query_cache::try_lock(bool use_timeout)
{
bool interrupt= FALSE;
+ THD *thd= current_thd;
+ Query_cache_wait_state wait_state(thd, __func__, __FILE__, __LINE__);
DBUG_ENTER("Query_cache::try_lock");
mysql_mutex_lock(&structure_guard_mutex);
@@ -448,7 +462,6 @@ bool Query_cache::try_lock(bool use_timeout)
{
m_cache_lock_status= Query_cache::LOCKED;
#ifndef DBUG_OFF
- THD *thd= current_thd;
if (thd)
m_cache_lock_thread_id= thd->thread_id;
#endif
@@ -507,6 +520,8 @@ bool Query_cache::try_lock(bool use_timeout)
void Query_cache::lock_and_suspend(void)
{
+ THD *thd= current_thd;
+ Query_cache_wait_state wait_state(thd, __func__, __FILE__, __LINE__);
DBUG_ENTER("Query_cache::lock_and_suspend");
mysql_mutex_lock(&structure_guard_mutex);
@@ -514,7 +529,6 @@ void Query_cache::lock_and_suspend(void)
mysql_cond_wait(&COND_cache_status_changed, &structure_guard_mutex);
m_cache_lock_status= Query_cache::LOCKED_NO_WAIT;
#ifndef DBUG_OFF
- THD *thd= current_thd;
if (thd)
m_cache_lock_thread_id= thd->thread_id;
#endif
@@ -535,6 +549,8 @@ void Query_cache::lock_and_suspend(void)
void Query_cache::lock(void)
{
+ THD *thd= current_thd;
+ Query_cache_wait_state wait_state(thd, __func__, __FILE__, __LINE__);
DBUG_ENTER("Query_cache::lock");
mysql_mutex_lock(&structure_guard_mutex);
@@ -542,7 +558,6 @@ void Query_cache::lock(void)
mysql_cond_wait(&COND_cache_status_changed, &structure_guard_mutex);
m_cache_lock_status= Query_cache::LOCKED;
#ifndef DBUG_OFF
- THD *thd= current_thd;
if (thd)
m_cache_lock_thread_id= thd->thread_id;
#endif
@@ -882,9 +897,7 @@ Query_cache::insert(Query_cache_tls *query_cache_tls,
if (is_disabled() || query_cache_tls->first_query_block == NULL)
DBUG_VOID_RETURN;
- DBUG_EXECUTE_IF("wait_in_query_cache_insert",
- debug_wait_for_kill("wait_in_query_cache_insert"); );
-
+ QC_DEBUG_SYNC("wait_in_query_cache_insert");
if (try_lock())
DBUG_VOID_RETURN;
@@ -1695,6 +1708,8 @@ def_week_frmt: %lu, in_trans: %d, autocommit: %d",
}
else
thd->lex->safe_to_cache_query= 0; // Don't try to cache this
+ /* End the statement transaction potentially started by engine. */
+ trans_rollback_stmt(thd);
goto err_unlock; // Parse query
}
else
@@ -1737,6 +1752,14 @@ def_week_frmt: %lu, in_trans: %d, autocommit: %d",
thd->limit_found_rows = query->found_rows();
thd->status_var.last_query_cost= 0.0;
thd->query_plan_flags= (thd->query_plan_flags & ~QPLAN_QC_NO) | QPLAN_QC;
+
+ /*
+ End the statement transaction potentially started by an
+ engine callback. We ignore the return value for now,
+ since as long as EOF packet is part of the query cache
+ response, we can't handle it anyway.
+ */
+ (void) trans_commit_stmt(thd);
if (!thd->stmt_da->is_set())
thd->stmt_da->disable_status();
@@ -1786,8 +1809,7 @@ void Query_cache::invalidate(THD *thd, TABLE_LIST *tables_used,
invalidate_table(thd, tables_used);
}
- DBUG_EXECUTE_IF("wait_after_query_cache_invalidate",
- debug_wait_for_kill("wait_after_query_cache_invalidate"););
+ DEBUG_SYNC(thd, "wait_after_query_cache_invalidate");
DBUG_VOID_RETURN;
}
@@ -1978,8 +2000,7 @@ void Query_cache::flush()
if (is_disabled())
DBUG_VOID_RETURN;
- DBUG_EXECUTE_IF("wait_in_query_cache_flush1",
- debug_wait_for_kill("wait_in_query_cache_flush1"););
+ QC_DEBUG_SYNC("wait_in_query_cache_flush1");
lock_and_suspend();
if (query_cache_size > 0)
@@ -2319,9 +2340,7 @@ void Query_cache::free_cache()
void Query_cache::flush_cache()
{
-
- DBUG_EXECUTE_IF("wait_in_query_cache_flush2",
- debug_wait_for_kill("wait_in_query_cache_flush2"););
+ QC_DEBUG_SYNC("wait_in_query_cache_flush2");
my_hash_reset(&queries);
while (queries_blocks != 0)
@@ -2767,8 +2786,7 @@ void Query_cache::invalidate_table(THD *thd, TABLE *table)
void Query_cache::invalidate_table(THD *thd, uchar * key, uint32 key_length)
{
- DBUG_EXECUTE_IF("wait_in_query_cache_invalidate1",
- debug_wait_for_kill("wait_in_query_cache_invalidate1"); );
+ DEBUG_SYNC(thd, "wait_in_query_cache_invalidate1");
/*
Lock the query cache and queue all invalidation attempts to avoid
@@ -2776,9 +2794,7 @@ void Query_cache::invalidate_table(THD *thd, uchar * key, uint32 key_length)
*/
lock();
- DBUG_EXECUTE_IF("wait_in_query_cache_invalidate2",
- debug_wait_for_kill("wait_in_query_cache_invalidate2"); );
-
+ DEBUG_SYNC(thd, "wait_in_query_cache_invalidate2");
if (query_cache_size > 0)
invalidate_table_internal(thd, key, key_length);
@@ -2828,7 +2844,6 @@ Query_cache::invalidate_query_block_list(THD *thd,
Query_cache_block *query_block= list_root->next->block();
BLOCK_LOCK_WR(query_block);
free_query(query_block);
- DBUG_EXECUTE_IF("debug_cache_locks", sleep(10););
}
}
diff --git a/sql/sql_class.cc b/sql/sql_class.cc
index 7638cf8f8f6..84adfddc4ac 100644
--- a/sql/sql_class.cc
+++ b/sql/sql_class.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,7 +11,7 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/*****************************************************************************
@@ -273,6 +273,252 @@ bool Foreign_key::validate(List<Create_field> &table_fields)
** Thread specific functions
****************************************************************************/
+/**
+ Get reference to scheduler data object
+
+ @param thd THD object
+
+ @retval Scheduler data object on THD
+*/
+void *thd_get_scheduler_data(THD *thd)
+{
+ return thd->scheduler.data;
+}
+
+/**
+ Set reference to Scheduler data object for THD object
+
+ @param thd THD object
+ @param psi Scheduler data object to set on THD
+*/
+void thd_set_scheduler_data(THD *thd, void *data)
+{
+ thd->scheduler.data= data;
+}
+
+/**
+ Get reference to Performance Schema object for THD object
+
+ @param thd THD object
+
+ @retval Performance schema object for thread on THD
+*/
+PSI_thread *thd_get_psi(THD *thd)
+{
+ return thd->scheduler.m_psi;
+}
+
+/**
+ Set reference to Performance Schema object for THD object
+
+ @param thd THD object
+ @param psi Performance schema object for thread
+*/
+void thd_set_psi(THD *thd, PSI_thread *psi)
+{
+ thd->scheduler.m_psi= psi;
+}
+
+/**
+ Set the state on connection to killed
+
+ @param thd THD object
+*/
+void thd_set_killed(THD *thd)
+{
+ thd->killed= THD::KILL_CONNECTION;
+}
+
+/**
+ Clear errors from the previous THD
+
+ @param thd THD object
+*/
+void thd_clear_errors(THD *thd)
+{
+ my_errno= 0;
+ thd->mysys_var->abort= 0;
+}
+
+/**
+ Set thread stack in THD object
+
+ @param thd Thread object
+ @param stack_start Start of stack to set in THD object
+*/
+void thd_set_thread_stack(THD *thd, char *stack_start)
+{
+ thd->thread_stack= stack_start;
+}
+
+/**
+ Lock connection data for the set of connections this connection
+ belongs to
+
+ @param thd THD object
+*/
+void thd_lock_thread_count(THD *)
+{
+ mysql_mutex_lock(&LOCK_thread_count);
+}
+
+/**
+ Lock connection data for the set of connections this connection
+ belongs to
+
+ @param thd THD object
+*/
+void thd_unlock_thread_count(THD *)
+{
+ mysql_cond_broadcast(&COND_thread_count);
+ mysql_mutex_unlock(&LOCK_thread_count);
+}
+
+/**
+ Close the socket used by this connection
+
+ @param thd THD object
+*/
+void thd_close_connection(THD *thd)
+{
+ if (thd->net.vio)
+ vio_close(thd->net.vio);
+}
+
+/**
+ Get current THD object from thread local data
+
+ @retval The THD object for the thread, NULL if not connection thread
+*/
+THD *thd_get_current_thd()
+{
+ return current_thd;
+}
+
+/**
+ Set up various THD data for a new connection
+
+ thd_new_connection_setup
+
+ @param thd THD object
+ @param stack_start Start of stack for connection
+*/
+void thd_new_connection_setup(THD *thd, char *stack_start)
+{
+#ifdef HAVE_PSI_INTERFACE
+ if (PSI_server)
+ thd_set_psi(thd,
+ PSI_server->new_thread(key_thread_one_connection,
+ thd,
+ thd_get_thread_id((MYSQL_THD)thd)));
+#endif
+ thd->set_time();
+ thd->prior_thr_create_utime= thd->thr_create_utime= thd->start_utime=
+ my_micro_time();
+ threads.append(thd);
+ thd_unlock_thread_count(thd);
+ DBUG_PRINT("info", ("init new connection. thd: 0x%lx fd: %d",
+ (ulong)thd, thd->net.vio->sd));
+ thd_set_thread_stack(thd, stack_start);
+}
+
+/**
+ Lock data that needs protection in THD object
+
+ @param thd THD object
+*/
+void thd_lock_data(THD *thd)
+{
+ mysql_mutex_lock(&thd->LOCK_thd_data);
+}
+
+/**
+ Unlock data that needs protection in THD object
+
+ @param thd THD object
+*/
+void thd_unlock_data(THD *thd)
+{
+ mysql_mutex_unlock(&thd->LOCK_thd_data);
+}
+
+/**
+ Support method to check if connection has already started transcaction
+
+ @param client_cntx Low level client context
+
+ @retval TRUE if connection already started transaction
+*/
+bool thd_is_transaction_active(THD *thd)
+{
+ return thd->transaction.is_active();
+}
+
+/**
+ Check if there is buffered data on the socket representing the connection
+
+ @param thd THD object
+*/
+int thd_connection_has_data(THD *thd)
+{
+ Vio *vio= thd->net.vio;
+ return vio->has_data(vio);
+}
+
+/**
+ Set reading/writing on socket, used by SHOW PROCESSLIST
+
+ @param thd THD object
+ @param val Value to set it to (0 or 1)
+*/
+void thd_set_net_read_write(THD *thd, uint val)
+{
+ thd->net.reading_or_writing= val;
+}
+
+/**
+ Set reference to mysys variable in THD object
+
+ @param thd THD object
+ @param mysys_var Reference to set
+*/
+void thd_set_mysys_var(THD *thd, st_my_thread_var *mysys_var)
+{
+ thd->set_mysys_var(mysys_var);
+}
+
+/**
+ Get socket file descriptor for this connection
+
+ @param thd THD object
+
+ @retval Socket of the connection
+*/
+my_socket thd_get_fd(THD *thd)
+{
+ return thd->net.vio->sd;
+}
+
+/**
+ Get thread attributes for connection threads
+
+ @retval Reference to thread attribute for connection threads
+*/
+pthread_attr_t *get_connection_attrib(void)
+{
+ return &connection_attrib;
+}
+
+/**
+ Get max number of connections
+
+ @retval Max number of connections for MySQL Server
+*/
+ulong get_max_connections(void)
+{
+ return max_connections;
+}
+
/*
The following functions form part of the C plugin API
*/
@@ -328,9 +574,11 @@ const char *set_thd_proc_info(void *thd_arg, const char *info,
thd= current_thd;
const char *old_info= thd->proc_info;
- DBUG_PRINT("proc_info", ("%s:%d %s", calling_file, calling_line, info));
+ const char *basename= calling_file ? base_name(calling_file) : NULL;
+ DBUG_PRINT("proc_info", ("%s:%d %s", basename, calling_line, info));
+
#if defined(ENABLED_PROFILING)
- thd->profiling.status_change(info, calling_function, calling_file, calling_line);
+ thd->profiling.status_change(info, calling_function, basename, calling_line);
#endif
thd->proc_info= info;
return old_info;
@@ -548,7 +796,7 @@ bool Drop_table_error_handler::handle_condition(THD *thd,
THD::THD()
- :Statement(&main_lex, &main_mem_root, CONVENTIONAL_EXECUTION,
+ :Statement(&main_lex, &main_mem_root, STMT_CONVENTIONAL_EXECUTION,
/* statement id */ 0),
rli_fake(0),
user_time(0), in_sub_stmt(0),
@@ -576,7 +824,7 @@ THD::THD()
#if defined(ENABLED_DEBUG_SYNC)
debug_sync_control(0),
#endif /* defined(ENABLED_DEBUG_SYNC) */
- main_warning_info(0)
+ main_warning_info(0, false)
{
ulong tmp;
@@ -594,7 +842,8 @@ THD::THD()
catalog= (char*)"std"; // the only catalog we have for now
main_security_ctx.init();
security_ctx= &main_security_ctx;
- no_errors=password= 0;
+ no_errors= 0;
+ password= 0;
query_start_used= 0;
count_cuted_fields= CHECK_FIELD_IGNORE;
killed= NOT_KILLED;
@@ -637,7 +886,7 @@ THD::THD()
client_capabilities= 0; // minimalistic client
ull=0;
system_thread= NON_SYSTEM_THREAD;
- cleanup_done= abort_on_warning= no_warnings_for_error= 0;
+ cleanup_done= abort_on_warning= 0;
peer_port= 0; // For SHOW PROCESSLIST
transaction.m_pending_rows_event= 0;
transaction.on= 1;
@@ -692,8 +941,8 @@ THD::THD()
thr_lock_info_init(&lock_info); /* safety: will be reset after start */
m_internal_handler= NULL;
+ m_binlog_invoker= FALSE;
arena_for_cached_items= 0;
- current_user_used= FALSE;
memset(&invoker_user, 0, sizeof(invoker_user));
memset(&invoker_host, 0, sizeof(invoker_host));
}
@@ -917,10 +1166,6 @@ MYSQL_ERROR* THD::raise_condition(uint sql_errno,
query_cache_abort(&query_cache_tls);
- /* FIXME: broken special case */
- if (no_warnings_for_error && (level == MYSQL_ERROR::WARN_LEVEL_ERROR))
- DBUG_RETURN(NULL);
-
/* When simulating OOM, skip writing to error log to avoid mtr errors */
DBUG_EXECUTE_IF("simulate_out_of_memory", DBUG_RETURN(NULL););
@@ -1313,36 +1558,70 @@ void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var,
#endif
+/**
+ Awake a thread.
+
+ @param[in] state_to_set value for THD::killed
+
+ This is normally called from another thread's THD object.
+
+ @note Do always call this while holding LOCK_thd_data.
+*/
+
void THD::awake(THD::killed_state state_to_set)
{
DBUG_ENTER("THD::awake");
- DBUG_PRINT("enter", ("this: 0x%lx", (long) this));
+ DBUG_PRINT("enter", ("this: %p current_thd: %p", this, current_thd));
THD_CHECK_SENTRY(this);
mysql_mutex_assert_owner(&LOCK_thd_data);
+ /* Set the 'killed' flag of 'this', which is the target THD object. */
killed= state_to_set;
+
if (state_to_set != THD::KILL_QUERY)
{
- thr_alarm_kill(thread_id);
- if (!slave_thread)
- MYSQL_CALLBACK(scheduler, post_kill_notification, (this));
#ifdef SIGNAL_WITH_VIO_CLOSE
if (this != current_thd)
{
/*
- In addition to a signal, let's close the socket of the thread that
- is being killed. This is to make sure it does not block if the
- signal is lost. This needs to be done only on platforms where
- signals are not a reliable interruption mechanism.
-
- If we're killing ourselves, we know that we're not blocked, so this
- hack is not used.
+ Before sending a signal, let's close the socket of the thread
+ that is being killed ("this", which is not the current thread).
+ This is to make sure it does not block if the signal is lost.
+ This needs to be done only on platforms where signals are not
+ a reliable interruption mechanism.
+
+ Note that the downside of this mechanism is that we could close
+ the connection while "this" target thread is in the middle of
+ sending a result to the application, thus violating the client-
+ server protocol.
+
+ On the other hand, without closing the socket we have a race
+ condition. If "this" target thread passes the check of
+ thd->killed, and then the current thread runs through
+ THD::awake(), sets the 'killed' flag and completes the
+ signaling, and then the target thread runs into read(), it will
+ block on the socket. As a result of the discussions around
+ Bug#37780, it has been decided that we accept the race
+ condition. A second KILL awakes the target from read().
+
+ If we are killing ourselves, we know that we are not blocked.
+ We also know that we will check thd->killed before we go for
+ reading the next statement.
*/
close_active_vio();
}
-#endif
+#endif
+
+ /* Mark the target thread's alarm request expired, and signal alarm. */
+ thr_alarm_kill(thread_id);
+
+ /* Send an event to the scheduler that a thread should be killed. */
+ if (!slave_thread)
+ MYSQL_CALLBACK(scheduler, post_kill_notification, (this));
}
+
+ /* Broadcast a condition to kick the target if it is waiting on it. */
if (mysys_var)
{
mysql_mutex_lock(&mysys_var->mutex);
@@ -1366,6 +1645,11 @@ void THD::awake(THD::killed_state state_to_set)
we issue a second KILL or the status it's waiting for happens).
It's true that we have set its thd->killed but it may not
see it immediately and so may have time to reach the cond_wait().
+
+ However, where possible, we test for killed once again after
+ enter_cond(). This should make the signaling as safe as possible.
+ However, there is still a small chance of failure on platforms with
+ instruction or memory write reordering.
*/
if (mysys_var->current_cond && mysys_var->current_mutex)
{
@@ -1378,6 +1662,40 @@ void THD::awake(THD::killed_state state_to_set)
DBUG_VOID_RETURN;
}
+
+/**
+ Close the Vio associated this session.
+
+ @remark LOCK_thd_data is taken due to the fact that
+ the Vio might be disassociated concurrently.
+*/
+
+void THD::disconnect()
+{
+ Vio *vio= NULL;
+
+ mysql_mutex_lock(&LOCK_thd_data);
+
+ killed= THD::KILL_CONNECTION;
+
+#ifdef SIGNAL_WITH_VIO_CLOSE
+ /*
+ Since a active vio might might have not been set yet, in
+ any case save a reference to avoid closing a inexistent
+ one or closing the vio twice if there is a active one.
+ */
+ vio= active_vio;
+ close_active_vio();
+#endif
+
+ /* Disconnect even if a active vio is not associated. */
+ if (net.vio != vio)
+ vio_close(net.vio);
+
+ mysql_mutex_unlock(&LOCK_thd_data);
+}
+
+
/*
Remember the location of thread info, the structure needed for
sql_alloc() and the structure for the net buffer
@@ -1422,7 +1740,6 @@ bool THD::store_globals()
return 0;
}
-
/**
Untie THD from current thread
@@ -1434,6 +1751,11 @@ void THD::reset_globals()
mysql_mutex_lock(&LOCK_thd_data);
mysys_var= 0;
mysql_mutex_unlock(&LOCK_thd_data);
+
+ /* Undocking the thread specific data. */
+ my_pthread_setspecific_ptr(THR_THD, NULL);
+ my_pthread_setspecific_ptr(THR_MALLOC, NULL);
+
}
/*
@@ -1486,7 +1808,7 @@ void THD::cleanup_after_query()
where= THD::DEFAULT_WHERE;
/* reset table map for multi-table update */
table_map_for_update= 0;
- clean_current_user_used();
+ m_binlog_invoker= FALSE;
}
@@ -1505,7 +1827,7 @@ LEX_STRING *THD::make_lex_string(LEX_STRING *lex_str,
bool allocate_lex_string)
{
if (allocate_lex_string)
- if (!(lex_str= (LEX_STRING *)alloc(sizeof(LEX_STRING))))
+ if (!(lex_str= (LEX_STRING *)alloc_root(mem_root, sizeof(LEX_STRING))))
return 0;
if (!(lex_str->str= strmake_root(mem_root, str, length)))
return 0;
@@ -1983,8 +2305,9 @@ void select_to_file::send_error(uint errcode,const char *err)
bool select_to_file::send_eof()
{
int error= test(end_io_cache(&cache));
- if (mysql_file_close(file, MYF(MY_WME)))
- error= 1;
+ if (mysql_file_close(file, MYF(MY_WME)) || thd->is_error())
+ error= true;
+
if (!error)
{
::my_ok(thd,row_count);
@@ -2262,7 +2585,7 @@ bool select_export::send_data(List<Item> &items)
ER_TRUNCATED_WRONG_VALUE_FOR_FIELD,
ER(ER_TRUNCATED_WRONG_VALUE_FOR_FIELD),
"string", printable_buff,
- item->name, (ulong) row_count);
+ item->name, static_cast<long>(row_count));
}
else if (from_end_pos < res->ptr() + res->length())
{
@@ -2271,7 +2594,7 @@ bool select_export::send_data(List<Item> &items)
*/
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
WARN_DATA_TRUNCATED, ER(WARN_DATA_TRUNCATED),
- item->full_name(), row_count);
+ item->full_name(), static_cast<long>(row_count));
}
cvt_str.length(bytes);
res= &cvt_str;
@@ -2725,8 +3048,6 @@ Statement::Statement(LEX *lex_arg, MEM_ROOT *mem_root_arg,
db(NULL),
db_length(0)
{
- query_string.length= 0;
- query_string.str= NULL;
name.str= NULL;
}
@@ -2765,15 +3086,6 @@ void Statement::restore_backup_statement(Statement *stmt, Statement *backup)
}
-/** Assign a new value to thd->query. */
-
-void Statement::set_query_inner(char *query_arg, uint32 query_length_arg)
-{
- query_string.str= query_arg;
- query_string.length= query_length_arg;
-}
-
-
void THD::end_statement()
{
/* Cleanup SQL processing state to reuse this statement in next query. */
@@ -3024,6 +3336,13 @@ bool select_dumpvar::send_eof()
if (! row_count)
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_SP_FETCH_NO_DATA, ER(ER_SP_FETCH_NO_DATA));
+ /*
+ Don't send EOF if we're in error condition (which implies we've already
+ sent or are sending an error)
+ */
+ if (thd->is_error())
+ return true;
+
::my_ok(thd,row_count);
return 0;
}
@@ -3157,9 +3476,9 @@ void THD::set_status_var_init()
void Security_context::init()
{
- host= user= ip= 0;
+ host= user= ip= external_user= 0;
host_or_ip= "connecting host";
- priv_user[0]= priv_host[0]= '\0';
+ priv_user[0]= priv_host[0]= proxy_user[0]= '\0';
master_access= 0;
#ifndef NO_EMBEDDED_ACCESS_CHECKS
db_access= NO_ACCESS;
@@ -3181,6 +3500,12 @@ void Security_context::destroy()
user= NULL;
}
+ if (external_user)
+ {
+ my_free(external_user);
+ user= NULL;
+ }
+
my_free(ip);
ip= NULL;
}
@@ -3375,7 +3700,7 @@ extern "C" const struct charset_info_st *thd_charset(MYSQL_THD thd)
*/
extern "C" char **thd_query(MYSQL_THD thd)
{
- return(&thd->query_string.str);
+ return (&thd->query_string.string.str);
}
/**
@@ -3386,7 +3711,7 @@ extern "C" char **thd_query(MYSQL_THD thd)
*/
extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd)
{
- return(&thd->query_string);
+ return(&thd->query_string.string);
}
extern "C" int thd_slave_thread(const MYSQL_THD thd)
@@ -3447,7 +3772,7 @@ extern "C" void thd_pool_wait_end(MYSQL_THD thd);
thd_wait_end MUST be called immediately after waking up again.
*/
-extern "C" void thd_wait_begin(MYSQL_THD thd, thd_wait_type wait_type)
+extern "C" void thd_wait_begin(MYSQL_THD thd, int wait_type)
{
MYSQL_CALLBACK(thd->scheduler, thd_wait_begin, (thd, wait_type));
}
@@ -3463,7 +3788,7 @@ extern "C" void thd_wait_end(MYSQL_THD thd)
MYSQL_CALLBACK(thd->scheduler, thd_wait_end, (thd));
}
#else
-extern "C" void thd_wait_begin(MYSQL_THD thd, thd_wait_type wait_type)
+extern "C" void thd_wait_begin(MYSQL_THD thd, int wait_type)
{
/* do NOTHING for the embedded library */
return;
@@ -3633,20 +3958,21 @@ void THD::set_statement(Statement *stmt)
/** Assign a new value to thd->query. */
-void THD::set_query(char *query_arg, uint32 query_length_arg)
+void THD::set_query(const CSET_STRING &string_arg)
{
mysql_mutex_lock(&LOCK_thd_data);
- set_query_inner(query_arg, query_length_arg);
+ set_query_inner(string_arg);
mysql_mutex_unlock(&LOCK_thd_data);
}
/** Assign a new value to thd->query and thd->query_id. */
void THD::set_query_and_id(char *query_arg, uint32 query_length_arg,
+ CHARSET_INFO *cs,
query_id_t new_query_id)
{
mysql_mutex_lock(&LOCK_thd_data);
- set_query_inner(query_arg, query_length_arg);
+ set_query_inner(query_arg, query_length_arg, cs);
query_id= new_query_id;
mysql_mutex_unlock(&LOCK_thd_data);
}
@@ -3676,16 +4002,20 @@ void THD::set_mysys_var(struct st_my_thread_var *new_mysys_var)
void THD::leave_locked_tables_mode()
{
locked_tables_mode= LTM_NONE;
- /* Make sure we don't release the global read lock when leaving LTM. */
- mdl_context.reset_trans_sentinel(global_read_lock.global_shared_lock());
+ mdl_context.set_transaction_duration_for_all_locks();
+ /*
+ Make sure we don't release the global read lock and commit blocker
+ when leaving LTM.
+ */
+ global_read_lock.set_explicit_lock_duration(this);
/* Also ensure that we don't release metadata locks for open HANDLERs. */
if (handler_tables_hash.records)
- mysql_ha_move_tickets_after_trans_sentinel(this);
+ mysql_ha_set_explicit_lock_duration(this);
}
void THD::get_definer(LEX_USER *definer)
{
- set_current_user_used();
+ binlog_invoker();
#if !defined(MYSQL_CLIENT) && defined(HAVE_REPLICATION)
if (slave_thread && has_invoker())
{
@@ -3814,6 +4144,7 @@ bool xid_cache_insert(XID *xid, enum xa_states xa_state)
xs->xa_state=xa_state;
xs->xid.set(xid);
xs->in_thd=0;
+ xs->rm_error=0;
res=my_hash_insert(&xid_cache, (uchar*)xs);
}
mysql_mutex_unlock(&LOCK_xid_cache);
diff --git a/sql/sql_class.h b/sql/sql_class.h
index 05082a8e8fe..9280fbd0640 100644
--- a/sql/sql_class.h
+++ b/sql/sql_class.h
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -111,6 +111,41 @@ extern MYSQL_PLUGIN_IMPORT const char **errmesg;
extern bool volatile shutdown_in_progress;
+extern "C" LEX_STRING * thd_query_string (MYSQL_THD thd);
+extern "C" char **thd_query(MYSQL_THD thd);
+
+/**
+ @class CSET_STRING
+ @brief Character set armed LEX_STRING
+*/
+class CSET_STRING
+{
+private:
+ LEX_STRING string;
+ CHARSET_INFO *cs;
+public:
+ CSET_STRING() : cs(&my_charset_bin)
+ {
+ string.str= NULL;
+ string.length= 0;
+ }
+ CSET_STRING(char *str_arg, size_t length_arg, CHARSET_INFO *cs_arg) :
+ cs(cs_arg)
+ {
+ DBUG_ASSERT(cs_arg != NULL);
+ string.str= str_arg;
+ string.length= length_arg;
+ }
+
+ inline char *str() const { return string.str; }
+ inline uint32 length() const { return string.length; }
+ CHARSET_INFO *charset() const { return cs; }
+
+ friend LEX_STRING * thd_query_string (MYSQL_THD thd);
+ friend char **thd_query(MYSQL_THD thd);
+};
+
+
#define TC_LOG_PAGE_SIZE 8192
#define TC_LOG_MIN_SIZE (3*TC_LOG_PAGE_SIZE)
@@ -630,14 +665,14 @@ public:
/*
The states relfects three diffrent life cycles for three
different types of statements:
- Prepared statement: INITIALIZED -> PREPARED -> EXECUTED.
- Stored procedure: INITIALIZED_FOR_SP -> EXECUTED.
- Other statements: CONVENTIONAL_EXECUTION never changes.
+ Prepared statement: STMT_INITIALIZED -> STMT_PREPARED -> STMT_EXECUTED.
+ Stored procedure: STMT_INITIALIZED_FOR_SP -> STMT_EXECUTED.
+ Other statements: STMT_CONVENTIONAL_EXECUTION never changes.
*/
enum enum_state
{
- INITIALIZED= 0, INITIALIZED_FOR_SP= 1, PREPARED= 2,
- CONVENTIONAL_EXECUTION= 3, EXECUTED= 4, ERROR= -1
+ STMT_INITIALIZED= 0, STMT_INITIALIZED_FOR_SP= 1, STMT_PREPARED= 2,
+ STMT_CONVENTIONAL_EXECUTION= 3, STMT_EXECUTED= 4, STMT_ERROR= -1
};
enum_state state;
@@ -660,18 +695,13 @@ public:
virtual Type type() const;
virtual ~Query_arena() {};
- inline bool is_stmt_prepare() const { return state == INITIALIZED; }
- inline bool is_first_sp_execute() const
- { return state == INITIALIZED_FOR_SP; }
+ inline bool is_stmt_prepare() const { return state == STMT_INITIALIZED; }
inline bool is_stmt_prepare_or_first_sp_execute() const
- { return (int)state < (int)PREPARED; }
+ { return (int)state < (int)STMT_PREPARED; }
inline bool is_stmt_prepare_or_first_stmt_execute() const
- { return (int)state <= (int)PREPARED; }
- inline bool is_first_stmt_execute() const { return state == PREPARED; }
- inline bool is_stmt_execute() const
- { return state == PREPARED || state == EXECUTED; }
+ { return (int)state <= (int)STMT_PREPARED; }
inline bool is_conventional() const
- { return state == CONVENTIONAL_EXECUTION; }
+ { return state == STMT_CONVENTIONAL_EXECUTION; }
inline void* alloc(size_t size) { return alloc_root(mem_root,size); }
inline void* calloc(size_t size)
@@ -763,12 +793,24 @@ public:
This printing is needed at least in SHOW PROCESSLIST and SHOW
ENGINE INNODB STATUS.
*/
- LEX_STRING query_string;
-
- inline char *query() { return query_string.str; }
- inline uint32 query_length() { return query_string.length; }
- void set_query_inner(char *query_arg, uint32 query_length_arg);
+ CSET_STRING query_string;
+ inline char *query() const { return query_string.str(); }
+ inline uint32 query_length() const { return query_string.length(); }
+ CHARSET_INFO *query_charset() const { return query_string.charset(); }
+ void set_query_inner(const CSET_STRING &string_arg)
+ {
+ query_string= string_arg;
+ }
+ void set_query_inner(char *query_arg, uint32 query_length_arg,
+ CHARSET_INFO *cs_arg)
+ {
+ set_query_inner(CSET_STRING(query_arg, query_length_arg, cs_arg));
+ }
+ void reset_query_inner()
+ {
+ set_query_inner(CSET_STRING());
+ }
/**
Name of the current (default) database.
@@ -863,8 +905,8 @@ struct st_savepoint {
char *name;
uint length;
Ha_trx_info *ha_list;
- /** Last acquired lock before this savepoint was set. */
- MDL_ticket *mdl_savepoint;
+ /** State of metadata locks before this savepoint was set. */
+ MDL_savepoint mdl_savepoint;
};
enum xa_states {XA_NOTR=0, XA_ACTIVE, XA_IDLE, XA_PREPARED, XA_ROLLBACK_ONLY};
@@ -905,8 +947,11 @@ public:
*/
char *host, *user, *ip;
char priv_user[USERNAME_LENGTH];
+ char proxy_user[USERNAME_LENGTH + MAX_HOSTNAME + 5];
/* The host privilege we are using */
char priv_host[MAX_HOSTNAME];
+ /* The external user (if available) */
+ char *external_user;
/* points to host if host is available, otherwise points to ip */
const char *host_or_ip;
ulong master_access; /* Global privileges from mysql.user */
@@ -1096,12 +1141,12 @@ class Open_tables_backup: public Open_tables_state
public:
/**
When we backup the open tables state to open a system
- table or tables, points at the last metadata lock
- acquired before the backup. Is used to release
- metadata locks on system tables after they are
+ table or tables, we want to save state of metadata
+ locks which were acquired before the backup. It is used
+ to release metadata locks on system tables after they are
no longer used.
*/
- MDL_ticket *mdl_system_tables_svp;
+ MDL_savepoint mdl_system_tables_svp;
};
/**
@@ -1376,26 +1421,43 @@ public:
};
Global_read_lock()
- :m_protection_count(0), m_state(GRL_NONE), m_mdl_global_shared_lock(NULL)
+ : m_state(GRL_NONE),
+ m_mdl_global_shared_lock(NULL),
+ m_mdl_blocks_commits_lock(NULL)
{}
bool lock_global_read_lock(THD *thd);
void unlock_global_read_lock(THD *thd);
- bool wait_if_global_read_lock(THD *thd, bool abort_on_refresh,
- bool is_not_commit);
- void start_waiting_global_read_lock(THD *thd);
+ /**
+ Check if this connection can acquire protection against GRL and
+ emit error if otherwise.
+ */
+ bool can_acquire_protection() const
+ {
+ if (m_state)
+ {
+ my_error(ER_CANT_UPDATE_WITH_READLOCK, MYF(0));
+ return TRUE;
+ }
+ return FALSE;
+ }
bool make_global_read_lock_block_commit(THD *thd);
bool is_acquired() const { return m_state != GRL_NONE; }
- bool has_protection() const { return m_protection_count > 0; }
- MDL_ticket *global_shared_lock() const { return m_mdl_global_shared_lock; }
+ void set_explicit_lock_duration(THD *thd);
private:
- uint m_protection_count; // GRL protection count
+ enum_grl_state m_state;
/**
In order to acquire the global read lock, the connection must
- acquire a global shared metadata lock, to prohibit all DDL.
+ acquire shared metadata lock in GLOBAL namespace, to prohibit
+ all DDL.
*/
- enum_grl_state m_state;
MDL_ticket *m_mdl_global_shared_lock;
+ /**
+ Also in order to acquire the global read lock, the connection
+ must acquire a shared metadata lock in COMMIT namespace, to
+ prohibit commits.
+ */
+ MDL_ticket *m_mdl_blocks_commits_lock;
};
@@ -1410,6 +1472,19 @@ extern "C" void my_message_sql(uint error, const char *str, myf MyFlags);
class THD :public Statement,
public Open_tables_state
{
+private:
+ inline bool is_stmt_prepare() const
+ { DBUG_ASSERT(0); return Statement::is_stmt_prepare(); }
+
+ inline bool is_stmt_prepare_or_first_sp_execute() const
+ { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_sp_execute(); }
+
+ inline bool is_stmt_prepare_or_first_stmt_execute() const
+ { DBUG_ASSERT(0); return Statement::is_stmt_prepare_or_first_stmt_execute(); }
+
+ inline bool is_conventional() const
+ { DBUG_ASSERT(0); return Statement::is_conventional(); }
+
public:
MDL_context mdl_context;
@@ -2008,6 +2083,12 @@ public:
DYNAMIC_ARRAY user_var_events; /* For user variables replication */
MEM_ROOT *user_var_events_alloc; /* Allocate above array elements here */
+ /*
+ If checking this in conjunction with a wait condition, please
+ include a check after enter_cond() if you want to avoid a race
+ condition. For details see the implementation of awake(),
+ especially the "broadcast" part.
+ */
enum killed_state
{
NOT_KILLED=0,
@@ -2025,6 +2106,9 @@ public:
bool no_errors, password;
bool extra_port; /* If extra connection */
+ bool no_errors;
+ uint8 password;
+
/**
Set to TRUE if execution of the current compound statement
can not continue. In particular, disables activation of
@@ -2075,7 +2159,6 @@ public:
bool enable_slow_log; /* enable slow log for current statement */
bool abort_on_warning;
bool got_warning; /* Set on call to push_warning() */
- bool no_warnings_for_error; /* no warnings on call to my_error() */
/* set during loop of derived table processing */
bool derived_tables_processing;
bool tablespace_op; /* This is TRUE in DISCARD/IMPORT TABLESPACE */
@@ -2213,6 +2296,9 @@ public:
#endif
void awake(THD::killed_state state_to_set);
+ /** Disconnect the associated communication endpoint. */
+ void disconnect();
+
#ifndef MYSQL_CLIENT
enum enum_binlog_query_type {
/* The query can be logged in row format or in statement format. */
@@ -2281,10 +2367,24 @@ public:
/*TODO: this will be obsolete when we have support for 64 bit my_time_t */
inline bool is_valid_time()
{
- return (start_time < (time_t) MY_TIME_T_MAX);
+ return (IS_TIME_T_VALID_FOR_TIMESTAMP(start_time));
}
void set_time_after_lock() { utime_after_lock= my_micro_time(); }
ulonglong current_utime() { return my_micro_time(); }
+ /**
+ Update server status after execution of a top level statement.
+
+ Currently only checks if a query was slow, and assigns
+ the status accordingly.
+ Evaluate the current time, and if it exceeds the long-query-time
+ setting, mark the query as slow.
+ */
+ void update_server_status()
+ {
+ ulonglong end_utime_of_query= current_utime();
+ if (end_utime_of_query > utime_after_lock + variables.long_query_time)
+ server_status|= SERVER_QUERY_WAS_SLOW;
+ }
inline ulonglong found_rows(void)
{
return limit_found_rows;
@@ -2493,8 +2593,6 @@ public:
(variables.sql_mode & MODE_STRICT_ALL_TABLES)));
}
void set_status_var_init();
- bool is_context_analysis_only()
- { return stmt_arena->is_stmt_prepare() || lex->view_prepare_mode; }
void reset_n_backup_open_tables_state(Open_tables_backup *backup);
void restore_backup_open_tables_state(Open_tables_backup *backup);
void reset_sub_statement_state(Sub_statement_state *backup, uint new_state);
@@ -2750,9 +2848,20 @@ public:
Assign a new value to thd->query and thd->query_id and mysys_var.
Protected with LOCK_thd_data mutex.
*/
- void set_query(char *query_arg, uint32 query_length_arg);
+ void set_query(char *query_arg, uint32 query_length_arg,
+ CHARSET_INFO *cs_arg)
+ {
+ set_query(CSET_STRING(query_arg, query_length_arg, cs_arg));
+ }
+ void set_query(char *query_arg, uint32 query_length_arg) /*Mutex protected*/
+ {
+ set_query(CSET_STRING(query_arg, query_length_arg, charset()));
+ }
+ void set_query(const CSET_STRING &str); /* Mutex protected */
+ void reset_query() /* Mutex protected */
+ { set_query(CSET_STRING()); }
void set_query_and_id(char *query_arg, uint32 query_length_arg,
- query_id_t new_query_id);
+ CHARSET_INFO *cs, query_id_t new_query_id);
void set_query_id(query_id_t new_query_id);
void set_open_tables(TABLE *open_tables_arg)
{
@@ -2765,14 +2874,13 @@ public:
{
DBUG_ASSERT(locked_tables_mode == LTM_NONE);
- mdl_context.set_trans_sentinel();
+ mdl_context.set_explicit_duration_for_all_locks();
locked_tables_mode= mode_arg;
}
void leave_locked_tables_mode();
int decide_logging_format(TABLE_LIST *tables);
- void set_current_user_used() { current_user_used= TRUE; }
- bool is_current_user_used() { return current_user_used; }
- void clean_current_user_used() { current_user_used= FALSE; }
+ void binlog_invoker() { m_binlog_invoker= TRUE; }
+ bool need_binlog_invoker() { return m_binlog_invoker; }
void get_definer(LEX_USER *definer);
void set_invoker(const LEX_STRING *user, const LEX_STRING *host)
{
@@ -2807,6 +2915,7 @@ private:
/** The current internal error handler for this thread, or NULL. */
Internal_error_handler *m_internal_handler;
+
/**
The lex to hold the parsed tree of conventional (non-prepared) queries.
Whereas for prepared and stored procedure statements we use an own lex
@@ -2834,7 +2943,7 @@ private:
Current user will be binlogged into Query_log_event if current_user_used
is TRUE; It will be stored into invoker_host and invoker_user by SQL thread.
*/
- bool current_user_used;
+ bool m_binlog_invoker;
/**
It points to the invoker in the Query_log_event.
@@ -3738,20 +3847,10 @@ public:
#define CF_DIAGNOSTIC_STMT (1U << 8)
/**
- SQL statements that must be protected against impending global read lock
- to prevent deadlock. This deadlock could otherwise happen if the statement
- starts waiting for the GRL to go away inside mysql_lock_tables while at the
- same time having "old" opened tables. The thread holding the GRL can be
- waiting for these "old" opened tables to be closed, causing a deadlock
- (FLUSH TABLES WITH READ LOCK).
- */
-#define CF_PROTECT_AGAINST_GRL (1U << 10)
-
-/**
Identifies statements that may generate row events
and that may end up in the binary log.
*/
-#define CF_CAN_GENERATE_ROW_EVENTS (1U << 11)
+#define CF_CAN_GENERATE_ROW_EVENTS (1U << 9)
/* Bits in server_command_flags */
diff --git a/sql/sql_connect.cc b/sql/sql_connect.cc
index 0fe43fb5ebb..c0646e6cec7 100644
--- a/sql/sql_connect.cc
+++ b/sql/sql_connect.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2007 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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 */
-
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/*
Functions to autenticate and handle reqests for a connection
@@ -52,7 +51,7 @@ static HASH hash_user_connections;
int get_or_create_user_conn(THD *thd, const char *user,
const char *host,
- USER_RESOURCES *mqh)
+ const USER_RESOURCES *mqh)
{
int return_val= 0;
size_t temp_len, user_len;
@@ -278,7 +277,6 @@ end:
#endif /* NO_EMBEDDED_ACCESS_CHECKS */
-
/*
Check for maximum allowable user connections, if the mysqld server is
started with corresponding variable that is greater then 0.
@@ -801,8 +799,23 @@ void update_global_user_stats(THD *thd, bool create_user, time_t now)
}
-void thd_init_client_charset(THD *thd, uint cs_number)
+/**
+ Set thread character set variables from the given ID
+
+ @param thd thread handle
+ @param cs_number character set and collation ID
+
+ @retval 0 OK; character_set_client, collation_connection and
+ character_set_results are set to the new value,
+ or to the default global values.
+
+ @retval 1 error, e.g. the given ID is not supported by parser.
+ Corresponding SQL error is sent.
+*/
+
+bool thd_init_client_charset(THD *thd, uint cs_number)
{
+ CHARSET_INFO *cs;
/*
Use server character set and collation if
- opt_character_set_client_handshake is not set
@@ -811,10 +824,10 @@ void thd_init_client_charset(THD *thd, uint cs_number)
- client character set doesn't exists in server
*/
if (!opt_character_set_client_handshake ||
- !(thd->variables.character_set_client= get_charset(cs_number, MYF(0))) ||
+ !(cs= get_charset(cs_number, MYF(0))) ||
!my_strcasecmp(&my_charset_latin1,
global_system_variables.character_set_client->name,
- thd->variables.character_set_client->name))
+ cs->name))
{
thd->variables.character_set_client=
global_system_variables.character_set_client;
@@ -825,10 +838,18 @@ void thd_init_client_charset(THD *thd, uint cs_number)
}
else
{
+ if (!is_supported_parser_charset(cs))
+ {
+ /* Disallow non-supported parser character sets: UCS2, UTF16, UTF32 */
+ my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), "character_set_client",
+ cs->csname);
+ return true;
+ }
thd->variables.character_set_results=
thd->variables.collation_connection=
- thd->variables.character_set_client;
+ thd->variables.character_set_client= cs;
}
+ return false;
}
@@ -874,7 +895,7 @@ static int check_connection(THD *thd)
if (vio_peer_addr(net->vio, ip, &thd->peer_port, NI_MAXHOST))
{
- my_error(ER_BAD_HOST_ERROR, MYF(0), thd->main_security_ctx.host_or_ip);
+ my_error(ER_BAD_HOST_ERROR, MYF(0));
return 1;
}
if (!(thd->main_security_ctx.ip= my_strdup(ip,MYF(MY_WME))))
@@ -885,7 +906,7 @@ static int check_connection(THD *thd)
if (ip_to_hostname(&net->vio->remote, thd->main_security_ctx.ip,
&thd->main_security_ctx.host, &connect_errors))
{
- my_error(ER_BAD_HOST_ERROR, MYF(0), ip);
+ my_error(ER_BAD_HOST_ERROR, MYF(0));
return 1;
}
@@ -949,7 +970,7 @@ bool setup_connection_thread_globals(THD *thd)
{
if (thd->store_globals())
{
- close_connection(thd, ER_OUT_OF_RESOURCES, 1);
+ close_connection(thd, ER_OUT_OF_RESOURCES);
statistic_increment(aborted_connects,&LOCK_status);
MYSQL_CALLBACK(thd->scheduler, end_thread, (thd, 0));
return 1; // Error
@@ -1124,6 +1145,32 @@ pthread_handler_t handle_one_connection(void *arg)
return 0;
}
+bool thd_prepare_connection(THD *thd)
+{
+ bool rc;
+ lex_start(thd);
+ rc= login_connection(thd);
+ MYSQL_AUDIT_NOTIFY_CONNECTION_CONNECT(thd);
+ if (rc)
+ return rc;
+
+ MYSQL_CONNECTION_START(thd->thread_id, &thd->security_ctx->priv_user[0],
+ (char *) thd->security_ctx->host_or_ip);
+
+ prepare_new_connection_state(thd);
+ return FALSE;
+}
+
+bool thd_is_connection_alive(THD *thd)
+{
+ NET *net= &thd->net;
+ if (!net->error &&
+ net->vio != 0 &&
+ !(thd->killed == THD::KILL_CONNECTION))
+ return TRUE;
+ return FALSE;
+}
+
void do_handle_one_connection(THD *thd_arg)
{
THD *thd= thd_arg;
@@ -1132,7 +1179,7 @@ void do_handle_one_connection(THD *thd_arg)
if (MYSQL_CALLBACK_ELSE(&thread_scheduler, init_new_connection_thread, (), 0))
{
- close_connection(thd, ER_OUT_OF_RESOURCES, 1);
+ close_connection(thd, ER_OUT_OF_RESOURCES);
statistic_increment(aborted_connects,&LOCK_status);
MYSQL_CALLBACK(thd->scheduler, end_thread, (thd, 0));
return;
@@ -1166,23 +1213,15 @@ void do_handle_one_connection(THD *thd_arg)
for (;;)
{
- NET *net= &thd->net;
bool create_user= TRUE;
- lex_start(thd);
- if (login_connection(thd))
+ if (thd_prepare_connection(thd))
{
create_user= FALSE;
goto end_thread;
}
- MYSQL_CONNECTION_START(thd->thread_id, thd->security_ctx->priv_user,
- (char *) thd->security_ctx->host_or_ip);
-
- prepare_new_connection_state(thd);
-
- while (!net->error && net->vio != 0 &&
- !(thd->killed == THD::KILL_CONNECTION))
+ while (thd_is_connection_alive(thd))
{
mysql_audit_release(thd);
if (do_command(thd))
@@ -1191,7 +1230,7 @@ void do_handle_one_connection(THD *thd_arg)
end_connection(thd);
end_thread:
- close_connection(thd, 0, 1);
+ close_connection(thd);
if (thd->userstat_running)
update_global_user_stats(thd, create_user, time(NULL));
diff --git a/sql/sql_connect.h b/sql/sql_connect.h
index 18dd2b31305..2f3096b496a 100644
--- a/sql/sql_connect.h
+++ b/sql/sql_connect.h
@@ -41,15 +41,17 @@ void reset_mqh(LEX_USER *lu, bool get_them);
bool check_mqh(THD *thd, uint check_command);
void time_out_user_resource_limits(THD *thd, USER_CONN *uc);
void decrease_user_connections(USER_CONN *uc);
-void thd_init_client_charset(THD *thd, uint cs_number);
+bool thd_init_client_charset(THD *thd, uint cs_number);
bool setup_connection_thread_globals(THD *thd);
+bool thd_prepare_connection(THD *thd);
+bool thd_is_connection_alive(THD *thd);
bool login_connection(THD *thd);
void prepare_new_connection_state(THD* thd);
void end_connection(THD *thd);
void update_global_user_stats(THD* thd, bool create_user, time_t now);
int get_or_create_user_conn(THD *thd, const char *user,
- const char *host, USER_RESOURCES *mqh);
+ const char *host, const USER_RESOURCES *mqh);
int check_for_max_user_connections(THD *thd, USER_CONN *uc);
extern HASH global_user_stats;
diff --git a/sql/sql_cursor.cc b/sql/sql_cursor.cc
index 5bd5f9df680..96a2d50538b 100644
--- a/sql/sql_cursor.cc
+++ b/sql/sql_cursor.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2005-2006 MySQL AB
+/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -46,7 +46,7 @@ class Materialized_cursor: public Server_side_cursor
public:
Materialized_cursor(select_result *result, TABLE *table);
- int fill_item_list(THD *thd, List<Item> &send_result_set_metadata);
+ int send_result_set_metadata(THD *thd, List<Item> &send_result_set_metadata);
virtual bool is_open() const { return table != 0; }
virtual int open(JOIN *join __attribute__((unused)));
virtual void fetch(ulong num_rows);
@@ -111,7 +111,7 @@ int mysql_open_cursor(THD *thd, select_result *result,
MYSQL_QUERY_EXEC_START(thd->query(),
thd->thread_id,
(char *) (thd->db ? thd->db : ""),
- thd->security_ctx->priv_user,
+ &thd->security_ctx->priv_user[0],
(char *) thd->security_ctx->host_or_ip,
2);
rc= mysql_execute_command(thd);
@@ -133,7 +133,13 @@ int mysql_open_cursor(THD *thd, select_result *result,
if (rc)
{
if (result_materialize->materialized_cursor)
+ {
+ /* Rollback metadata in the client-server protocol. */
+ result_materialize->abort_result_set();
+
delete result_materialize->materialized_cursor;
+ }
+
goto end;
}
@@ -142,6 +148,12 @@ int mysql_open_cursor(THD *thd, select_result *result,
Materialized_cursor *materialized_cursor=
result_materialize->materialized_cursor;
+ /*
+ NOTE: close_thread_tables() has been called in
+ mysql_execute_command(), so all tables except from the cursor
+ temporary table have been closed.
+ */
+
if ((rc= materialized_cursor->open(0)))
{
delete materialized_cursor;
@@ -202,14 +214,16 @@ Materialized_cursor::Materialized_cursor(select_result *result_arg,
/**
- Preserve the original metadata that would be sent to the client.
+ Preserve the original metadata to be sent to the client.
+ Initiate sending of the original metadata to the client
+ (call Protocol::send_result_set_metadata()).
@param thd Thread identifier.
@param send_result_set_metadata List of fields that would be sent.
*/
-int Materialized_cursor::fill_item_list(THD *thd,
- List<Item> &send_result_set_metadata)
+int Materialized_cursor::send_result_set_metadata(
+ THD *thd, List<Item> &send_result_set_metadata)
{
Query_arena backup_arena;
int rc;
@@ -241,6 +255,14 @@ int Materialized_cursor::fill_item_list(THD *thd,
ident->db_name= thd->strdup(send_field.db_name);
ident->table_name= thd->strdup(send_field.table_name);
}
+
+ /*
+ Original metadata result set should be sent here. After
+ mysql_execute_command() is finished, item_list can not be used for
+ sending metadata, because it references closed table.
+ */
+ rc= result->send_result_set_metadata(item_list, Protocol::SEND_NUM_ROWS);
+
end:
thd->restore_active_arena(this, &backup_arena);
/* Check for thd->is_error() in case of OOM */
@@ -253,32 +275,29 @@ int Materialized_cursor::open(JOIN *join __attribute__((unused)))
THD *thd= fake_unit.thd;
int rc;
Query_arena backup_arena;
+
thd->set_n_backup_active_arena(this, &backup_arena);
- /* Create a list of fields and start sequential scan */
+
+ /* Create a list of fields and start sequential scan. */
+
rc= result->prepare(item_list, &fake_unit);
- if (!rc && !(rc= table->file->ha_rnd_init_with_error(TRUE)))
- is_rnd_inited= 1;
+ rc= !rc && table->file->ha_rnd_init_with_error(TRUE);
+ is_rnd_inited= !rc;
thd->restore_active_arena(this, &backup_arena);
- if (rc == 0)
+
+ /* Commit or rollback metadata in the client-server protocol. */
+
+ if (!rc)
{
- /*
- Now send the result set metadata to the client. We need to
- do it here, as in Select_materialize::send_result_set_metadata the items
- for column types are not yet created (send_result_set_metadata requires
- a list of items). The new types may differ from the original
- ones sent at prepare if some of them were altered by MySQL
- HEAP tables mechanism -- used when create_tmp_field_from_item
- may alter the original column type.
-
- We can't simply supply SEND_EOF flag to send_result_set_metadata, because
- send_result_set_metadata doesn't flush the network buffer.
- */
- rc= result->send_result_set_metadata(item_list, Protocol::SEND_NUM_ROWS);
thd->server_status|= SERVER_STATUS_CURSOR_EXISTS;
result->send_eof();
- thd->server_status&= ~SERVER_STATUS_CURSOR_EXISTS;
}
+ else
+ {
+ result->abort_result_set();
+ }
+
return rc;
}
@@ -318,12 +337,10 @@ void Materialized_cursor::fetch(ulong num_rows)
case 0:
thd->server_status|= SERVER_STATUS_CURSOR_EXISTS;
result->send_eof();
- thd->server_status&= ~SERVER_STATUS_CURSOR_EXISTS;
break;
case HA_ERR_END_OF_FILE:
thd->server_status|= SERVER_STATUS_LAST_ROW_SENT;
result->send_eof();
- thd->server_status&= ~SERVER_STATUS_LAST_ROW_SENT;
close();
break;
default:
@@ -375,13 +392,14 @@ bool Select_materialize::send_result_set_metadata(List<Item> &list, uint flags)
materialized_cursor= new (&table->mem_root)
Materialized_cursor(result, table);
- if (! materialized_cursor)
+ if (!materialized_cursor)
{
free_tmp_table(table->in_use, table);
table= 0;
return TRUE;
}
- if (materialized_cursor->fill_item_list(unit->thd, list))
+
+ if (materialized_cursor->send_result_set_metadata(unit->thd, list))
{
delete materialized_cursor;
table= 0;
diff --git a/sql/sql_cursor.h b/sql/sql_cursor.h
index ed7bfac821a..d19d14fa167 100644
--- a/sql/sql_cursor.h
+++ b/sql/sql_cursor.h
@@ -46,7 +46,7 @@ protected:
select_result *result;
public:
Server_side_cursor(MEM_ROOT *mem_root_arg, select_result *result_arg)
- :Query_arena(mem_root_arg, INITIALIZED), result(result_arg)
+ :Query_arena(mem_root_arg, STMT_INITIALIZED), result(result_arg)
{}
virtual bool is_open() const= 0;
diff --git a/sql/sql_db.cc b/sql/sql_db.cc
index 8b92259573e..56dd266acb9 100644
--- a/sql/sql_db.cc
+++ b/sql/sql_db.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2003 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -28,6 +28,8 @@
#include "sql_acl.h" // SELECT_ACL, DB_ACLS,
// acl_get, check_grant_db
#include "log_event.h" // Query_log_event
+#include "sql_base.h" // lock_table_names, tdc_remove_table
+#include "sql_handler.h" // mysql_ha_rm_tables
#include <mysys_err.h>
#include "sp.h"
#include "events.h"
@@ -44,10 +46,12 @@ const char *del_exts[]= {".frm", ".BAK", ".TMD",".opt", NullS};
static TYPELIB deletable_extentions=
{array_elements(del_exts)-1,"del_exts", del_exts, NULL};
-static long mysql_rm_known_files(THD *thd, MY_DIR *dirp,
- const char *db, const char *path, uint level,
- TABLE_LIST **dropped_tables);
-
+static bool find_db_tables_and_rm_known_files(THD *thd, MY_DIR *dirp,
+ const char *db,
+ const char *path,
+ TABLE_LIST **tables,
+ bool *found_other_files);
+
long mysql_rm_arc_files(THD *thd, MY_DIR *dirp, const char *org_path);
static my_bool rm_dir_w_symlink(const char *org_path, my_bool send_error);
static void mysql_change_db_impl(THD *thd,
@@ -736,36 +740,37 @@ exit:
}
-/*
- Drop all tables in a database and the database itself
-
- SYNOPSIS
- mysql_rm_db()
- thd Thread handle
- db Database name in the case given by user
- It's already validated and set to lower case
- (if needed) when we come here
- if_exists Don't give error if database doesn't exists
- silent Don't generate errors
-
- RETURN
- FALSE ok (Database dropped)
- ERROR Error
+/**
+ Drop all tables, routines and events in a database and the database itself.
+
+ @param thd Thread handle
+ @param db Database name in the case given by user
+ It's already validated and set to lower case
+ (if needed) when we come here
+ @param if_exists Don't give error if database doesn't exists
+ @param silent Don't write the statement to the binary log and don't
+ send ok packet to the client
+
+ @retval false OK (Database dropped)
+ @retval true Error
*/
bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
{
- long deleted=0;
- int error= 0;
+ ulong deleted_tables= 0;
+ bool error= true;
char path[FN_REFLEN+16];
MY_DIR *dirp;
uint length;
- TABLE_LIST* dropped_tables= 0;
+ bool found_other_files= false;
+ TABLE_LIST *tables= NULL;
+ TABLE_LIST *table;
+ Drop_table_error_handler err_handler;
DBUG_ENTER("mysql_rm_db");
if (lock_schema_name(thd, db))
- DBUG_RETURN(TRUE);
+ DBUG_RETURN(true);
length= build_table_filename(path, sizeof(path) - 1, db, "", "", 0);
strmov(path+length, MY_DB_OPT_FILE); // Append db option file name
@@ -777,20 +782,61 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
{
if (!if_exists)
{
- error= -1;
my_error(ER_DB_DROP_EXISTS, MYF(0), db);
- goto exit;
+ DBUG_RETURN(true);
}
else
+ {
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
ER_DB_DROP_EXISTS, ER(ER_DB_DROP_EXISTS), db);
+ error= false;
+ goto update_binlog;
+ }
}
- else
+
+ if (find_db_tables_and_rm_known_files(thd, dirp, db, path, &tables,
+ &found_other_files))
+ goto exit;
+
+ /*
+ Disable drop of enabled log tables, must be done before name locking.
+ This check is only needed if we are dropping the "mysql" database.
+ */
+ if ((my_strcasecmp(system_charset_info, MYSQL_SCHEMA_NAME.str, db) == 0))
{
- Drop_table_error_handler err_handler;
- thd->push_internal_handler(&err_handler);
+ for (table= tables; table; table= table->next_local)
+ {
+ if (check_if_log_table(table->db_length, table->db,
+ table->table_name_length, table->table_name, true))
+ {
+ my_error(ER_BAD_LOG_STATEMENT, MYF(0), "DROP");
+ goto exit;
+ }
+ }
+ }
+
+ /* Lock all tables and stored routines about to be dropped. */
+ if (lock_table_names(thd, tables, NULL, thd->variables.lock_wait_timeout,
+ MYSQL_OPEN_SKIP_TEMPORARY) ||
+ lock_db_routines(thd, db))
+ goto exit;
+
+ /* mysql_ha_rm_tables() requires a non-null TABLE_LIST. */
+ if (tables)
+ mysql_ha_rm_tables(thd, tables);
- error= -1;
+ for (table= tables; table; table= table->next_local)
+ {
+ tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table->db, table->table_name,
+ false);
+ deleted_tables++;
+ }
+
+ thd->push_internal_handler(&err_handler);
+ if (!thd->killed &&
+ !(tables &&
+ mysql_rm_table_no_locks(thd, tables, true, false, true, true)))
+ {
/*
We temporarily disable the binary log while dropping the objects
in the database. Since the DROP DATABASE statement is always
@@ -808,23 +854,30 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
ha_drop_database(), since NDB otherwise detects the binary log
as disabled and will not log the drop database statement on any
other connected server.
- */
- if ((deleted= mysql_rm_known_files(thd, dirp, db, path, 0,
- &dropped_tables)) >= 0)
- {
- ha_drop_database(path);
- tmp_disable_binlog(thd);
- query_cache_invalidate1(db);
- (void) sp_drop_db_routines(thd, db); /* @todo Do not ignore errors */
+ */
+
+ ha_drop_database(path);
+ tmp_disable_binlog(thd);
+ query_cache_invalidate1(db);
+ (void) sp_drop_db_routines(thd, db); /* @todo Do not ignore errors */
#ifdef HAVE_EVENT_SCHEDULER
- Events::drop_schema_events(thd, db);
+ Events::drop_schema_events(thd, db);
#endif
- error = 0;
- reenable_binlog(thd);
- }
- thd->pop_internal_handler();
+ reenable_binlog(thd);
+
+ /*
+ If the directory is a symbolic link, remove the link first, then
+ remove the directory the symbolic link pointed at
+ */
+ if (found_other_files)
+ my_error(ER_DB_DROP_RMDIR, MYF(0), path, EEXIST);
+ else
+ error= rm_dir_w_symlink(path, true);
}
- if (!silent && deleted>=0)
+ thd->pop_internal_handler();
+
+update_binlog:
+ if (!silent && !error)
{
const char *query;
ulong query_length;
@@ -859,16 +912,15 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
*/
if (mysql_bin_log.write(&qinfo))
{
- error= -1;
+ error= true;
goto exit;
}
}
thd->clear_error();
thd->server_status|= SERVER_STATUS_DB_DROPPED;
- my_ok(thd, (ulong) deleted);
- thd->server_status&= ~SERVER_STATUS_DB_DROPPED;
+ my_ok(thd, deleted_tables);
}
- else if (mysql_bin_log.is_open())
+ else if (mysql_bin_log.is_open() && !silent)
{
char *query, *query_pos, *query_end, *query_data_start;
TABLE_LIST *tbl;
@@ -880,9 +932,19 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
query_end= query + MAX_DROP_TABLE_Q_LEN;
db_len= strlen(db);
- for (tbl= dropped_tables; tbl; tbl= tbl->next_local)
+ for (tbl= tables; tbl; tbl= tbl->next_local)
{
uint tbl_name_len;
+ bool exists;
+
+ // Only write drop table to the binlog for tables that no longer exist.
+ if (check_if_table_exists(thd, tbl, &exists))
+ {
+ error= true;
+ goto exit;
+ }
+ if (exists)
+ continue;
/* 3 for the quotes and the comma*/
tbl_name_len= strlen(tbl->table_name) + 3;
@@ -894,7 +956,7 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
*/
if (write_to_binlog(thd, query, query_pos -1 - query, db, db_len))
{
- error= -1;
+ error= true;
goto exit;
}
query_pos= query_data_start;
@@ -914,7 +976,7 @@ bool mysql_rm_db(THD *thd,char *db,bool if_exists, bool silent)
*/
if (write_to_binlog(thd, query, query_pos -1 - query, db, db_len))
{
- error= -1;
+ error= true;
goto exit;
}
}
@@ -927,28 +989,23 @@ exit:
SELECT DATABASE() in the future). For this we free() thd->db and set
it to 0.
*/
- if (thd->db && !strcmp(thd->db, db) && error == 0)
+ if (thd->db && !strcmp(thd->db, db) && !error)
mysql_change_db_impl(thd, NULL, 0, thd->variables.collation_server);
+ my_dirend(dirp);
DBUG_RETURN(error);
}
-/*
- Removes files with known extensions plus all found subdirectories that
- are 2 hex digits (raid directories).
- thd MUST be set when calling this function!
-*/
-static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db,
- const char *org_path, uint level,
- TABLE_LIST **dropped_tables)
+static bool find_db_tables_and_rm_known_files(THD *thd, MY_DIR *dirp,
+ const char *db,
+ const char *path,
+ TABLE_LIST **tables,
+ bool *found_other_files)
{
- long deleted=0;
- ulong found_other_files=0;
char filePath[FN_REFLEN];
TABLE_LIST *tot_list=0, **tot_list_next_local, **tot_list_next_global;
- List<String> raid_dirs;
- DBUG_ENTER("mysql_rm_known_files");
- DBUG_PRINT("enter",("path: %s", org_path));
+ DBUG_ENTER("find_db_tables_and_rm_known_files");
+ DBUG_PRINT("enter",("path: %s", path));
tot_list_next_local= tot_list_next_global= &tot_list;
@@ -965,36 +1022,7 @@ static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db,
(file->name[1] == '.' && !file->name[2])))
continue;
- /* Check if file is a raid directory */
- if ((my_isdigit(system_charset_info, file->name[0]) ||
- (file->name[0] >= 'a' && file->name[0] <= 'f')) &&
- (my_isdigit(system_charset_info, file->name[1]) ||
- (file->name[1] >= 'a' && file->name[1] <= 'f')) &&
- !file->name[2] && !level)
- {
- char newpath[FN_REFLEN], *copy_of_path;
- MY_DIR *new_dirp;
- String *dir;
- uint length;
-
- strxmov(newpath,org_path,"/",file->name,NullS);
- length= unpack_filename(newpath,newpath);
- if ((new_dirp = my_dir(newpath,MYF(MY_DONT_SORT))))
- {
- DBUG_PRINT("my",("New subdir found: %s", newpath));
- if ((mysql_rm_known_files(thd, new_dirp, NullS, newpath,1,0)) < 0)
- goto err;
- if (!(copy_of_path= (char*) thd->memdup(newpath, length+1)) ||
- !(dir= new (thd->mem_root) String(copy_of_path, length,
- &my_charset_bin)) ||
- raid_dirs.push_back(dir))
- goto err;
- continue;
- }
- found_other_files++;
- continue;
- }
- else if (file->name[0] == 'a' && file->name[1] == 'r' &&
+ if (file->name[0] == 'a' && file->name[1] == 'r' &&
file->name[2] == 'c' && file->name[3] == '\0')
{
/* .frm archive:
@@ -1003,24 +1031,24 @@ static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db,
*/
char newpath[FN_REFLEN];
MY_DIR *new_dirp;
- strxmov(newpath, org_path, "/", "arc", NullS);
+ strxmov(newpath, path, "/", "arc", NullS);
(void) unpack_filename(newpath, newpath);
if ((new_dirp = my_dir(newpath, MYF(MY_DONT_SORT))))
{
DBUG_PRINT("my",("Archive subdir found: %s", newpath));
if ((mysql_rm_arc_files(thd, new_dirp, newpath)) < 0)
- goto err;
+ DBUG_RETURN(true);
continue;
}
- found_other_files++;
+ *found_other_files= true;
continue;
}
if (!(extension= strrchr(file->name, '.')))
extension= strend(file->name);
- if (find_type(extension, &deletable_extentions,1+2) <= 0)
+ if (find_type(extension, &deletable_extentions, FIND_TYPE_NO_PREFIX) <= 0)
{
- if (find_type(extension, ha_known_exts(),1+2) <= 0)
- found_other_files++;
+ if (find_type(extension, ha_known_exts(), FIND_TYPE_NO_PREFIX) <= 0)
+ *found_other_files= true;
continue;
}
/* just for safety we use files_charset_info */
@@ -1036,7 +1064,7 @@ static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db,
strlen(file->name) + 1);
if (!table_list)
- goto err;
+ DBUG_RETURN(true);
table_list->db= (char*) (table_list+1);
table_list->db_length= strmov(table_list->db, db) - table_list->db;
table_list->table_name= table_list->db + table_list->db_length + 1;
@@ -1054,61 +1082,31 @@ static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db,
table_list->alias= table_list->table_name; // If lower_case_table_names=2
table_list->internal_tmp_table= is_prefix(file->name, tmp_file_prefix);
table_list->mdl_request.init(MDL_key::TABLE, table_list->db,
- table_list->table_name, MDL_EXCLUSIVE);
+ table_list->table_name, MDL_EXCLUSIVE,
+ MDL_TRANSACTION);
/* Link into list */
(*tot_list_next_local)= table_list;
(*tot_list_next_global)= table_list;
tot_list_next_local= &table_list->next_local;
tot_list_next_global= &table_list->next_global;
- deleted++;
}
else
{
- strxmov(filePath, org_path, "/", file->name, NullS);
- if (mysql_file_delete_with_symlink(key_file_misc, filePath, MYF(MY_WME)))
+ strxmov(filePath, path, "/", file->name, NullS);
+ /*
+ We ignore ENOENT error in order to skip files that was deleted
+ by concurrently running statement like REAPIR TABLE ...
+ */
+ if (my_delete_with_symlink(filePath, MYF(0)) &&
+ my_errno != ENOENT)
{
- goto err;
+ my_error(EE_DELETE, MYF(0), filePath, my_errno);
+ DBUG_RETURN(true);
}
}
}
- if (thd->killed ||
- (tot_list && mysql_rm_table_part2(thd, tot_list, 1, 0, 1, 1)))
- goto err;
-
- /* Remove RAID directories */
- {
- List_iterator<String> it(raid_dirs);
- String *dir;
- while ((dir= it++))
- if (rmdir(dir->c_ptr()) < 0)
- found_other_files++;
- }
- my_dirend(dirp);
-
- if (dropped_tables)
- *dropped_tables= tot_list;
-
- /*
- If the directory is a symbolic link, remove the link first, then
- remove the directory the symbolic link pointed at
- */
- if (found_other_files)
- {
- my_error(ER_DB_DROP_RMDIR, MYF(0), org_path, EEXIST);
- DBUG_RETURN(-1);
- }
- else
- {
- /* Don't give errors if we can't delete 'RAID' directory */
- if (rm_dir_w_symlink(org_path, level == 0))
- DBUG_RETURN(-1);
- }
-
- DBUG_RETURN(deleted);
-
-err:
- my_dirend(dirp);
- DBUG_RETURN(-1);
+ *tables= tot_list;
+ DBUG_RETURN(false);
}
diff --git a/sql/sql_delete.cc b/sql/sql_delete.cc
index d80eb4d4dfe..8dd611e4ccf 100644
--- a/sql/sql_delete.cc
+++ b/sql/sql_delete.cc
@@ -533,9 +533,7 @@ int mysql_multi_delete_prepare(THD *thd)
if (!(target_tbl->table= target_tbl->correspondent_table->table))
{
DBUG_ASSERT(target_tbl->correspondent_table->view &&
- target_tbl->correspondent_table->merge_underlying_list &&
- target_tbl->correspondent_table->merge_underlying_list->
- next_local);
+ target_tbl->correspondent_table->multitable_view);
my_error(ER_VIEW_DELETE_MERGE_VIEW, MYF(0),
target_tbl->correspondent_table->view_db.str,
target_tbl->correspondent_table->view_name.str);
diff --git a/sql/sql_derived.cc b/sql/sql_derived.cc
index a4063e0dce9..0c7ffb48935 100644
--- a/sql/sql_derived.cc
+++ b/sql/sql_derived.cc
@@ -151,10 +151,11 @@ bool mysql_derived_prepare(THD *thd, LEX *lex, TABLE_LIST *orig_table_list)
if (!(derived_result= new select_union))
DBUG_RETURN(TRUE); // out of memory
+ lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_DERIVED;
// st_select_lex_unit::prepare correctly work for single select
if ((res= unit->prepare(thd, derived_result, 0)))
goto exit;
-
+ lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_DERIVED;
if ((res= check_duplicate_names(unit->types, 0)))
goto exit;
@@ -307,13 +308,21 @@ bool mysql_derived_filling(THD *thd, LEX *lex, TABLE_LIST *orig_table_list)
*/
if (derived_result->flush())
res= TRUE;
-
- if (!lex->describe)
- unit->cleanup();
}
- else
- unit->cleanup();
lex->current_select= save_current_select;
}
return res;
}
+
+
+/**
+ Cleans up the SELECT_LEX_UNIT for the derived table (if any).
+*/
+
+bool mysql_derived_cleanup(THD *thd, LEX *lex, TABLE_LIST *derived)
+{
+ SELECT_LEX_UNIT *unit= derived->derived;
+ if (unit)
+ unit->cleanup();
+ return false;
+}
diff --git a/sql/sql_derived.h b/sql/sql_derived.h
index 0d4eddedf22..11a6fd4105e 100644
--- a/sql/sql_derived.h
+++ b/sql/sql_derived.h
@@ -26,4 +26,16 @@ bool mysql_handle_derived(LEX *lex, bool (*processor)(THD *thd,
bool mysql_derived_prepare(THD *thd, LEX *lex, TABLE_LIST *t);
bool mysql_derived_filling(THD *thd, LEX *lex, TABLE_LIST *t);
+/**
+ Cleans up the SELECT_LEX_UNIT for the derived table (if any).
+
+ @param thd Thread handler
+ @param lex LEX for this thread
+ @param derived TABLE_LIST for the derived table
+
+ @retval false Success
+ @retval true Failure
+*/
+bool mysql_derived_cleanup(THD *thd, LEX *lex, TABLE_LIST *derived);
+
#endif /* SQL_DERIVED_INCLUDED */
diff --git a/sql/sql_error.cc b/sql/sql_error.cc
index 44bfe0a4f44..7988523dd3b 100644
--- a/sql/sql_error.cc
+++ b/sql/sql_error.cc
@@ -1,5 +1,4 @@
-/* Copyright (C) 1995-2002 MySQL AB,
- Copyright (C) 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -334,7 +333,6 @@ Diagnostics_area::reset_diagnostics_area()
/** Don't take chances in production */
m_message[0]= '\0';
m_sql_errno= 0;
- m_server_status= 0;
m_affected_rows= 0;
m_last_insert_id= 0;
m_statement_warn_count= 0;
@@ -365,7 +363,6 @@ Diagnostics_area::set_ok_status(THD *thd, ulonglong affected_rows_arg,
if (is_error() || is_disabled())
return;
- m_server_status= thd->server_status;
m_statement_warn_count= thd->warning_info->statement_warn_count();
m_affected_rows= affected_rows_arg;
m_last_insert_id= last_insert_id_arg;
@@ -395,7 +392,6 @@ Diagnostics_area::set_eof_status(THD *thd)
if (is_error() || is_disabled())
return;
- m_server_status= thd->server_status;
/*
If inside a stored procedure, do not return the total
number of warnings, since they are not available to the client
@@ -461,10 +457,11 @@ Diagnostics_area::disable_status()
m_status= DA_DISABLED;
}
-Warning_info::Warning_info(ulonglong warn_id_arg)
+Warning_info::Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings)
:m_statement_warn_count(0),
m_current_row_for_warning(1),
m_warn_id(warn_id_arg),
+ m_allow_unlimited_warnings(allow_unlimited_warnings),
m_read_only(FALSE)
{
/* Initialize sub structures */
@@ -546,7 +543,8 @@ MYSQL_ERROR *Warning_info::push_warning(THD *thd,
if (! m_read_only)
{
- if (m_warn_list.elements < thd->variables.max_error_count)
+ if (m_allow_unlimited_warnings ||
+ m_warn_list.elements < thd->variables.max_error_count)
{
cond= new (& m_warn_root) MYSQL_ERROR(& m_warn_root);
if (cond)
@@ -562,6 +560,20 @@ MYSQL_ERROR *Warning_info::push_warning(THD *thd,
return cond;
}
+MYSQL_ERROR *Warning_info::push_warning(THD *thd, const MYSQL_ERROR *sql_condition)
+{
+ MYSQL_ERROR *new_condition= push_warning(thd,
+ sql_condition->get_sql_errno(),
+ sql_condition->get_sqlstate(),
+ sql_condition->get_level(),
+ sql_condition->get_message_text());
+
+ if (new_condition)
+ new_condition->copy_opt_attributes(sql_condition);
+
+ return new_condition;
+}
+
/*
Push the warning to error list if there is still room in the list
diff --git a/sql/sql_error.h b/sql/sql_error.h
index 8495a8cfa57..5b9b5ee639a 100644
--- a/sql/sql_error.h
+++ b/sql/sql_error.h
@@ -1,5 +1,4 @@
-/* Copyright (C) 2000-2003 MySQL AB,
- Copyright (C) 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -12,7 +11,7 @@
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 */
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
#ifndef SQL_ERROR_H
#define SQL_ERROR_H
@@ -79,12 +78,6 @@ public:
const char* get_sqlstate() const
{ DBUG_ASSERT(m_status == DA_ERROR); return m_sqlstate; }
- uint server_status() const
- {
- DBUG_ASSERT(m_status == DA_OK || m_status == DA_EOF);
- return m_server_status;
- }
-
ulonglong affected_rows() const
{ DBUG_ASSERT(m_status == DA_OK); return m_affected_rows; }
@@ -118,15 +111,6 @@ private:
char m_sqlstate[SQLSTATE_LENGTH+1];
/**
- Copied from thd->server_status when the diagnostics area is assigned.
- We need this member as some places in the code use the following pattern:
- thd->server_status|= ...
- my_eof(thd);
- thd->server_status&= ~...
- Assigned by OK, EOF or ERROR.
- */
- uint m_server_status;
- /**
The number of rows affected by the last statement. This is
semantically close to thd->row_count_func, but has a different
life cycle. thd->row_count_func stores the value returned by
@@ -345,10 +329,13 @@ class Warning_info
{
/** A memory root to allocate warnings and errors */
MEM_ROOT m_warn_root;
+
/** List of warnings of all severities (levels). */
List <MYSQL_ERROR> m_warn_list;
+
/** A break down of the number of warnings per severity (level). */
uint m_warn_count[(uint) MYSQL_ERROR::WARN_LEVEL_END];
+
/**
The number of warnings of the current statement. Warning_info
life cycle differs from statement life cycle -- it may span
@@ -356,20 +343,25 @@ class Warning_info
m_statement_warn_count 0, whereas m_warn_list is not empty.
*/
uint m_statement_warn_count;
+
/*
Row counter, to print in errors and warnings. Not increased in
create_sort_index(); may differ from examined_row_count.
*/
ulong m_current_row_for_warning;
- /** Used to optionally clear warnings only once per statement. */
+
+ /** Used to optionally clear warnings only once per statement. */
ulonglong m_warn_id;
+ /** Indicates if push_warning() allows unlimited number of warnings. */
+ bool m_allow_unlimited_warnings;
+
private:
Warning_info(const Warning_info &rhs); /* Not implemented */
Warning_info& operator=(const Warning_info &rhs); /* Not implemented */
public:
- Warning_info(ulonglong warn_id_arg);
+ Warning_info(ulonglong warn_id_arg, bool allow_unlimited_warnings);
~Warning_info();
/**
@@ -406,19 +398,13 @@ public:
void append_warnings(THD *thd, List<MYSQL_ERROR> *src)
{
MYSQL_ERROR *err;
- MYSQL_ERROR *copy;
List_iterator_fast<MYSQL_ERROR> it(*src);
/*
Don't use ::push_warning() to avoid invocation of condition
handlers or escalation of warnings to errors.
*/
while ((err= it++))
- {
- copy= Warning_info::push_warning(thd, err->get_sql_errno(), err->get_sqlstate(),
- err->get_level(), err->get_message_text());
- if (copy)
- copy->copy_opt_attributes(err);
- }
+ Warning_info::push_warning(thd, err);
}
/**
@@ -484,6 +470,9 @@ public:
MYSQL_ERROR::enum_warning_level level,
const char* msg);
+ /** Add a new condition to the current list. */
+ MYSQL_ERROR *push_warning(THD *thd, const MYSQL_ERROR *sql_condition);
+
/**
Set the read only status for this statement area.
This is a privileged operation, reserved for the implementation of
diff --git a/sql/sql_handler.cc b/sql/sql_handler.cc
index 9620b759adb..3ea378ef19c 100644
--- a/sql/sql_handler.cc
+++ b/sql/sql_handler.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2004 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -55,7 +55,7 @@
#include "sql_handler.h"
#include "unireg.h" // REQUIRED: for other includes
#include "sql_base.h" // close_thread_tables
-#include "lock.h" // broadcast_refresh, mysql_unlock_tables
+#include "lock.h" // mysql_unlock_tables
#include "key.h" // key_copy
#include "sql_base.h" // insert_fields
#include "sql_select.h"
@@ -131,11 +131,7 @@ static void mysql_ha_close_table(THD *thd, TABLE_LIST *tables)
/* Non temporary table. */
tables->table->file->ha_index_or_rnd_end();
tables->table->open_by_handler= 0;
- if (close_thread_table(thd, &tables->table))
- {
- /* Tell threads waiting for refresh that something has happened */
- broadcast_refresh();
- }
+ (void) close_thread_table(thd, &tables->table);
thd->mdl_context.release_lock(tables->mdl_request.ticket);
}
else if (tables->table)
@@ -183,7 +179,7 @@ bool mysql_ha_open(THD *thd, TABLE_LIST *tables, bool reopen)
uint dblen, namelen, aliaslen, counter;
bool error;
TABLE *backup_open_tables;
- MDL_ticket *mdl_savepoint;
+ MDL_savepoint mdl_savepoint;
DBUG_ENTER("mysql_ha_open");
DBUG_PRINT("enter",("'%s'.'%s' as '%s' reopen: %d",
tables->db, tables->table_name, tables->alias,
@@ -252,7 +248,13 @@ bool mysql_ha_open(THD *thd, TABLE_LIST *tables, bool reopen)
memcpy(hash_tables->db, tables->db, dblen);
memcpy(hash_tables->table_name, tables->table_name, namelen);
memcpy(hash_tables->alias, tables->alias, aliaslen);
- hash_tables->mdl_request.init(MDL_key::TABLE, db, name, MDL_SHARED);
+ /*
+ We can't request lock with explicit duration for this table
+ right from the start as open_tables() can't handle properly
+ back-off for such locks.
+ */
+ hash_tables->mdl_request.init(MDL_key::TABLE, db, name, MDL_SHARED,
+ MDL_TRANSACTION);
/* for now HANDLER can be used only for real TABLES */
hash_tables->required_type= FRMTYPE_TABLE;
@@ -332,8 +334,8 @@ bool mysql_ha_open(THD *thd, TABLE_LIST *tables, bool reopen)
thd->set_open_tables(backup_open_tables);
if (hash_tables->mdl_request.ticket)
{
- thd->mdl_context.
- move_ticket_after_trans_sentinel(hash_tables->mdl_request.ticket);
+ thd->mdl_context.set_lock_duration(hash_tables->mdl_request.ticket,
+ MDL_EXPLICIT);
thd->mdl_context.set_needs_thr_lock_abort(TRUE);
}
@@ -611,7 +613,8 @@ retry:
if (keyname)
{
- if ((keyno=find_type(keyname, &table->s->keynames, 1+2)-1)<0)
+ if ((keyno= find_type(keyname, &table->s->keynames,
+ FIND_TYPE_NO_PREFIX) - 1) < 0)
{
my_error(ER_KEY_DOES_NOT_EXITS, MYF(0), keyname, tables->alias);
goto err;
@@ -971,24 +974,23 @@ void mysql_ha_cleanup(THD *thd)
/**
- Move tickets for metadata locks corresponding to open HANDLERs
- after transaction sentinel in order to protect them from being
- released at the end of transaction.
+ Set explicit duration for metadata locks corresponding to open HANDLERs
+ to protect them from being released at the end of transaction.
@param thd Thread identifier.
*/
-void mysql_ha_move_tickets_after_trans_sentinel(THD *thd)
+void mysql_ha_set_explicit_lock_duration(THD *thd)
{
TABLE_LIST *hash_tables;
- DBUG_ENTER("mysql_ha_move_tickets_after_trans_sentinel");
+ DBUG_ENTER("mysql_ha_set_explicit_lock_duration");
for (uint i= 0; i < thd->handler_tables_hash.records; i++)
{
hash_tables= (TABLE_LIST*) my_hash_element(&thd->handler_tables_hash, i);
if (hash_tables->table && hash_tables->table->mdl_ticket)
- thd->mdl_context.
- move_ticket_after_trans_sentinel(hash_tables->table->mdl_ticket);
+ thd->mdl_context.set_lock_duration(hash_tables->table->mdl_ticket,
+ MDL_EXPLICIT);
}
DBUG_VOID_RETURN;
}
diff --git a/sql/sql_handler.h b/sql/sql_handler.h
index c5da3c4d468..2eea552d7c9 100644
--- a/sql/sql_handler.h
+++ b/sql/sql_handler.h
@@ -31,6 +31,6 @@ void mysql_ha_flush(THD *thd);
void mysql_ha_flush_tables(THD *thd, TABLE_LIST *all_tables);
void mysql_ha_rm_tables(THD *thd, TABLE_LIST *tables);
void mysql_ha_cleanup(THD *thd);
-void mysql_ha_move_tickets_after_trans_sentinel(THD *thd);
+void mysql_ha_set_explicit_lock_duration(THD *thd);
#endif /* SQL_HANDLER_INCLUDED */
diff --git a/sql/sql_help.cc b/sql/sql_help.cc
index 7218d806c5f..9b2295f6fb3 100644
--- a/sql/sql_help.cc
+++ b/sql/sql_help.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000 MySQL AB
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -289,10 +289,12 @@ int get_topics_for_keyword(THD *thd, TABLE *topics, TABLE *relations,
Field *rtopic_id, *rkey_id;
DBUG_ENTER("get_topics_for_keyword");
- if ((iindex_topic= find_type((char*) primary_key_name,
- &topics->s->keynames, 1+2)-1)<0 ||
- (iindex_relations= find_type((char*) primary_key_name,
- &relations->s->keynames, 1+2)-1)<0)
+ if ((iindex_topic=
+ find_type(primary_key_name, &topics->s->keynames,
+ FIND_TYPE_NO_PREFIX) - 1) < 0 ||
+ (iindex_relations=
+ find_type(primary_key_name, &relations->s->keynames,
+ FIND_TYPE_NO_PREFIX) - 1) < 0)
{
my_message(ER_CORRUPT_HELP_DB, ER(ER_CORRUPT_HELP_DB), MYF(0));
DBUG_RETURN(-1);
@@ -709,7 +711,7 @@ bool mysqld_help(THD *thd, const char *mask)
if (count_topics == 0)
{
- int key_id;
+ int UNINIT_VAR(key_id);
if (!(select=
prepare_select_for_name(thd,mask,mlen,tables,tables[3].table,
used_fields[help_keyword_name].field,
diff --git a/sql/sql_insert.cc b/sql/sql_insert.cc
index 99a8378961e..d807ac36278 100644
--- a/sql/sql_insert.cc
+++ b/sql/sql_insert.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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 */
-
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/* Insert of records */
@@ -77,7 +76,8 @@
#include "sql_audit.h"
#ifndef EMBEDDED_LIBRARY
-static bool delayed_get_table(THD *thd, TABLE_LIST *table_list);
+static bool delayed_get_table(THD *thd, MDL_request *grl_protection_request,
+ TABLE_LIST *table_list);
static int write_delayed(THD *thd, TABLE *table, enum_duplicates duplic,
LEX_STRING query, bool ignore, bool log_on);
static void end_delayed_insert(THD *thd);
@@ -415,9 +415,9 @@ void prepare_triggers_for_insert_stmt(TABLE *table)
downgrade the lock in handler::store_lock() method.
*/
-void upgrade_lock_type_for_insert(THD *thd, thr_lock_type *lock_type,
- enum_duplicates duplic,
- bool is_multi_insert)
+static
+void upgrade_lock_type(THD *thd, thr_lock_type *lock_type,
+ enum_duplicates duplic)
{
if (duplic == DUP_UPDATE ||
(duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT))
@@ -466,10 +466,9 @@ void upgrade_lock_type_for_insert(THD *thd, thr_lock_type *lock_type,
return;
}
- bool log_on= (thd->variables.option_bits & OPTION_BIN_LOG ||
- ! (thd->security_ctx->master_access & SUPER_ACL));
+ bool log_on= (thd->variables.option_bits & OPTION_BIN_LOG);
if (global_system_variables.binlog_format == BINLOG_FORMAT_STMT &&
- log_on && mysql_bin_log.is_open() && is_multi_insert)
+ log_on && mysql_bin_log.is_open())
{
/*
Statement-based binary logging does not work in this case, because:
@@ -526,32 +525,28 @@ void upgrade_lock_type_for_insert(THD *thd, thr_lock_type *lock_type,
static
bool open_and_lock_for_insert_delayed(THD *thd, TABLE_LIST *table_list)
{
+ MDL_request protection_request;
DBUG_ENTER("open_and_lock_for_insert_delayed");
#ifndef EMBEDDED_LIBRARY
- if (thd->locked_tables_mode && thd->global_read_lock.is_acquired())
- {
- /*
- 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);
- }
-
/*
In order for the deadlock detector to be able to find any deadlocks
- caused by the handler thread locking this table, we take the metadata
- lock inside the connection thread. If this goes ok, the ticket is cloned
- and added to the list of granted locks held by the handler thread.
+ caused by the handler thread waiting for GRL or this table, we acquire
+ protection against GRL (global IX metadata lock) and metadata lock on
+ table to being inserted into inside the connection thread.
+ If this goes ok, the tickets are cloned and added to the list of granted
+ locks held by the handler thread.
*/
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ if (thd->global_read_lock.can_acquire_protection())
+ DBUG_RETURN(TRUE);
+
+ protection_request.init(MDL_key::GLOBAL, "", "", MDL_INTENTION_EXCLUSIVE,
+ MDL_STATEMENT);
+
+ if (thd->mdl_context.acquire_lock(&protection_request,
+ thd->variables.lock_wait_timeout))
+ DBUG_RETURN(TRUE);
+
if (thd->mdl_context.acquire_lock(&table_list->mdl_request,
thd->variables.lock_wait_timeout))
/*
@@ -561,7 +556,7 @@ bool open_and_lock_for_insert_delayed(THD *thd, TABLE_LIST *table_list)
DBUG_RETURN(TRUE);
bool error= FALSE;
- if (delayed_get_table(thd, table_list))
+ if (delayed_get_table(thd, &protection_request, table_list))
error= TRUE;
else if (table_list->table)
{
@@ -586,13 +581,13 @@ bool open_and_lock_for_insert_delayed(THD *thd, TABLE_LIST *table_list)
}
/*
- If a lock was acquired above, we should release it after
- handle_delayed_insert() has cloned the ticket. Note that acquire_lock() can
- succeed because the connection already has the lock. In this case the ticket
- will be before the mdl_savepoint and we should not release it here.
+ We can't release protection against GRL and metadata lock on the table
+ being inserted into here. These locks might be required, for example,
+ because this INSERT DELAYED calls functions which may try to update
+ this or another tables (updating the same table is of course illegal,
+ but such an attempt can be discovered only later during statement
+ execution).
*/
- if (!thd->mdl_context.has_lock(mdl_savepoint, table_list->mdl_request.ticket))
- thd->mdl_context.release_lock(table_list->mdl_request.ticket);
/*
Reset the ticket in case we end up having to use normal insert and
@@ -631,14 +626,12 @@ bool open_and_lock_for_insert_delayed(THD *thd, TABLE_LIST *table_list)
static int
create_insert_stmt_from_insert_delayed(THD *thd, String *buf)
{
- /* Append the part of thd->query before "DELAYED" keyword */
- if (buf->append(thd->query(),
- thd->lex->keyword_delayed_begin - thd->query()))
- return 1;
- /* Append the part of thd->query after "DELAYED" keyword */
- if (buf->append(thd->lex->keyword_delayed_begin + 7))
+ /* Make a copy of thd->query() and then remove the "DELAYED" keyword */
+ if (buf->append(thd->query()) ||
+ buf->replace(thd->lex->keyword_delayed_begin_offset,
+ thd->lex->keyword_delayed_end_offset -
+ thd->lex->keyword_delayed_begin_offset, 0))
return 1;
-
return 0;
}
@@ -680,8 +673,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *table_list,
By default, both logs are enabled (this won't cause problems if the server
runs without --log-bin).
*/
- bool log_on= ((thd->variables.option_bits & OPTION_BIN_LOG) ||
- (!(thd->security_ctx->master_access & SUPER_ACL)));
+ bool log_on= (thd->variables.option_bits & OPTION_BIN_LOG);
#endif
thr_lock_type lock_type;
Item *unused_conds= 0;
@@ -691,8 +683,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *table_list,
Upgrade lock type if the requested lock is incompatible with
the current connection mode or table operation.
*/
- upgrade_lock_type_for_insert(thd, &table_list->lock_type, duplic,
- values_list.elements > 1);
+ upgrade_lock_type(thd, &table_list->lock_type, duplic);
/*
We can't write-delayed into a table locked with LOCK TABLES:
@@ -989,7 +980,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *table_list,
if (thd->transaction.stmt.modified_non_trans_table)
thd->transaction.all.modified_non_trans_table= TRUE;
- if ((changed && error <= 0) ||
+ if (error <= 0 ||
thd->transaction.stmt.modified_non_trans_table ||
was_insert_delayed)
{
@@ -1028,7 +1019,7 @@ bool mysql_insert(THD *thd,TABLE_LIST *table_list,
DBUG_ASSERT(thd->killed != THD::KILL_BAD_DATA || error > 0);
if (was_insert_delayed && table_list->lock_type == TL_WRITE)
{
- /* Binlog multi INSERT DELAYED as INSERT without DELAYED. */
+ /* Binlog INSERT DELAYED as INSERT without DELAYED. */
String log_query;
if (create_insert_stmt_from_insert_delayed(thd, &log_query))
{
@@ -1635,9 +1626,7 @@ int write_record(THD *thd, TABLE *table,COPY_INFO *info)
table->file->adjust_next_insert_id_after_explicit_value(
table->next_number_field->val_int());
info->touched++;
- if (((table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ) &&
- !bitmap_is_subset(table->write_set, table->read_set)) ||
- compare_record(table))
+ if (!records_are_comparable(table) || compare_records(table))
{
if ((error=table->file->ha_update_row(table->record[1],
table->record[0])) &&
@@ -1890,10 +1879,11 @@ public:
mysql_cond_t cond, cond_client;
volatile uint tables_in_use,stacked_inserts;
volatile bool status;
- /*
+ /**
When the handler thread starts, it clones a metadata lock ticket
- for the table to be inserted. This is done to allow the deadlock
- detector to detect deadlocks resulting from this lock.
+ which protects against GRL and ticket for the table to be inserted.
+ This is done to allow the deadlock detector to detect deadlocks
+ resulting from these locks.
Before this is done, the connection thread cannot safely exit
without causing problems for clone_ticket().
Once handler_thread_initialized has been set, it is safe for the
@@ -1905,6 +1895,11 @@ public:
I_List<delayed_row> rows;
ulong group_count;
TABLE_LIST table_list; // Argument
+ /**
+ Request for IX metadata lock protecting against GRL which is
+ passed from connection thread to the handler thread.
+ */
+ MDL_request grl_protection;
Delayed_insert()
:locks_in_memory(0), table(0),tables_in_use(0),stacked_inserts(0),
@@ -1920,22 +1915,6 @@ public:
thd.lex->current_select= 0; // for my_message_sql
thd.lex->sql_command= SQLCOM_INSERT; // For innodb::store_lock()
/*
- Statement-based replication of INSERT DELAYED has problems with
- RAND() and user variables, so in mixed mode we go to row-based.
- For normal commands, the unsafe flag is set at parse time.
- However, since the flag is a member of the THD object, of which
- the delayed_insert thread has its own copy, we must set the
- statement to unsafe here and explicitly set row logging mode.
-
- @todo set_current_stmt_binlog_format_row_if_mixed should not be
- called by anything else than thd->decide_logging_format(). When
- we call set_current_blah here, none of the checks in
- decide_logging_format is made. We should probably call
- thd->decide_logging_format() directly instead. /Sven
- */
- thd.lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_DELAYED);
- thd.set_current_stmt_binlog_format_row_if_mixed();
- /*
Prevent changes to global.lock_wait_timeout from affecting
delayed insert threads as any timeouts in delayed inserts
are not communicated to the client.
@@ -2083,7 +2062,8 @@ Delayed_insert *find_handler(THD *thd, TABLE_LIST *table_list)
*/
static
-bool delayed_get_table(THD *thd, TABLE_LIST *table_list)
+bool delayed_get_table(THD *thd, MDL_request *grl_protection_request,
+ TABLE_LIST *table_list)
{
int error;
Delayed_insert *di;
@@ -2116,7 +2096,8 @@ bool delayed_get_table(THD *thd, TABLE_LIST *table_list)
mysql_mutex_unlock(&LOCK_thread_count);
di->thd.set_db(table_list->db, (uint) strlen(table_list->db));
di->thd.set_query(my_strdup(table_list->table_name,
- MYF(MY_WME | ME_FATALERROR)), 0);
+ MYF(MY_WME | ME_FATALERROR)),
+ 0, system_charset_info);
if (di->thd.db == NULL || di->thd.query() == NULL)
{
/* The error is reported */
@@ -2127,7 +2108,10 @@ bool delayed_get_table(THD *thd, TABLE_LIST *table_list)
/* Replace volatile strings with local copies */
di->table_list.alias= di->table_list.table_name= di->thd.query();
di->table_list.db= di->thd.db;
- /* We need the ticket so that it can be cloned in handle_delayed_insert */
+ /* We need the tickets so that they can be cloned in handle_delayed_insert */
+ di->grl_protection.init(MDL_key::GLOBAL, "", "",
+ MDL_INTENTION_EXCLUSIVE, MDL_STATEMENT);
+ di->grl_protection.ticket= grl_protection_request->ticket;
init_mdl_requests(&di->table_list);
di->table_list.mdl_request.ticket= table_list->mdl_request.ticket;
@@ -2516,6 +2500,65 @@ void kill_delayed_threads(void)
/**
+ A strategy for the prelocking algorithm which prevents the
+ delayed insert thread from opening tables with engines which
+ do not support delayed inserts.
+
+ Particularly it allows to abort open_tables() as soon as we
+ discover that we have opened a MERGE table, without acquiring
+ metadata locks on underlying tables.
+*/
+
+class Delayed_prelocking_strategy : public Prelocking_strategy
+{
+public:
+ virtual bool handle_routine(THD *thd, Query_tables_list *prelocking_ctx,
+ Sroutine_hash_entry *rt, sp_head *sp,
+ bool *need_prelocking);
+ virtual bool handle_table(THD *thd, Query_tables_list *prelocking_ctx,
+ TABLE_LIST *table_list, bool *need_prelocking);
+ virtual bool handle_view(THD *thd, Query_tables_list *prelocking_ctx,
+ TABLE_LIST *table_list, bool *need_prelocking);
+};
+
+
+bool Delayed_prelocking_strategy::
+handle_table(THD *thd, Query_tables_list *prelocking_ctx,
+ TABLE_LIST *table_list, bool *need_prelocking)
+{
+ DBUG_ASSERT(table_list->lock_type == TL_WRITE_DELAYED);
+
+ if (!(table_list->table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED))
+ {
+ my_error(ER_DELAYED_NOT_SUPPORTED, MYF(0), table_list->table_name);
+ return TRUE;
+ }
+ return FALSE;
+}
+
+
+bool Delayed_prelocking_strategy::
+handle_routine(THD *thd, Query_tables_list *prelocking_ctx,
+ Sroutine_hash_entry *rt, sp_head *sp,
+ bool *need_prelocking)
+{
+ /* LEX used by the delayed insert thread has no routines. */
+ DBUG_ASSERT(0);
+ return FALSE;
+}
+
+
+bool Delayed_prelocking_strategy::
+handle_view(THD *thd, Query_tables_list *prelocking_ctx,
+ TABLE_LIST *table_list, bool *need_prelocking)
+{
+ /* We don't open views in the delayed insert thread. */
+ DBUG_ASSERT(0);
+ return FALSE;
+}
+
+
+/**
Open and lock table for use by delayed thread and check that
this table is suitable for delayed inserts.
@@ -2525,21 +2568,21 @@ void kill_delayed_threads(void)
bool Delayed_insert::open_and_lock_table()
{
+ Delayed_prelocking_strategy prelocking_strategy;
+
+ /*
+ Use special prelocking strategy to get ER_DELAYED_NOT_SUPPORTED
+ error for tables with engines which don't support delayed inserts.
+ */
if (!(table= open_n_lock_single_table(&thd, &table_list,
TL_WRITE_DELAYED,
- MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK)))
+ MYSQL_OPEN_IGNORE_GLOBAL_READ_LOCK,
+ &prelocking_strategy)))
{
thd.fatal_error(); // Abort waiting inserts
return TRUE;
}
- if (!(table->file->ha_table_flags() & HA_CAN_INSERT_DELAYED))
- {
- /* To rollback InnoDB statement transaction. */
- trans_rollback_stmt(&thd);
- my_error(ER_DELAYED_NOT_SUPPORTED, MYF(ME_FATALERROR),
- table_list.table_name);
- return TRUE;
- }
+
if (table->triggers)
{
/*
@@ -2605,21 +2648,23 @@ pthread_handler_t handle_delayed_insert(void *arg)
}
thd->lex->sql_command= SQLCOM_INSERT; // For innodb::store_lock()
+
/*
- Statement-based replication of INSERT DELAYED has problems with RAND()
- and user vars, so in mixed mode we go to row-based.
+ INSERT DELAYED has to go to row-based format because the time
+ at which rows are inserted cannot be determined in mixed mode.
*/
- thd->lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_DELAYED);
thd->set_current_stmt_binlog_format_row_if_mixed();
/*
- Clone the ticket representing the lock on the target table for
- the insert and add it to the list of granted metadata locks held by
- the handler thread. This is safe since the handler thread is
- not holding nor waiting on any metadata locks.
+ Clone tickets representing protection against GRL and the lock on
+ the target table for the insert and add them to the list of granted
+ metadata locks held by the handler thread. This is safe since the
+ handler thread is not holding nor waiting on any metadata locks.
*/
- if (thd->mdl_context.clone_ticket(&di->table_list.mdl_request))
+ if (thd->mdl_context.clone_ticket(&di->grl_protection) ||
+ thd->mdl_context.clone_ticket(&di->table_list.mdl_request))
{
+ thd->mdl_context.release_transactional_locks();
di->handler_thread_initialized= TRUE;
goto err;
}
@@ -2875,6 +2920,13 @@ bool Delayed_insert::handle_inserts(void)
if (log_query)
{
/*
+ Guaranteed that the INSERT DELAYED STMT will not be here
+ in SBR when mysql binlog is enabled.
+ */
+ DBUG_ASSERT(!(mysql_bin_log.is_open() &&
+ !thd.is_current_stmt_binlog_format_row()));
+
+ /*
This is the first value of an INSERT statement.
It is the right place to clear a forced insert_id.
This is usually done after the last value of an INSERT statement,
@@ -2941,39 +2993,6 @@ bool Delayed_insert::handle_inserts(void)
table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
}
- if (log_query && mysql_bin_log.is_open())
- {
- bool backup_time_zone_used = thd.time_zone_used;
- Time_zone *backup_time_zone = thd.variables.time_zone;
- if (row->time_zone != NULL)
- {
- thd.time_zone_used = true;
- thd.variables.time_zone = row->time_zone;
- }
-
- /* if the delayed insert was killed, the killed status is
- ignored while binlogging */
- int errcode= 0;
- if (thd.killed == THD::NOT_KILLED)
- errcode= query_error_code(&thd, TRUE);
-
- /*
- If the query has several rows to insert, only the first row will come
- here. In row-based binlogging, this means that the first row will be
- written to binlog as one Table_map event and one Rows event (due to an
- event flush done in binlog_query()), then all other rows of this query
- will be binlogged together as one single Table_map event and one
- single Rows event.
- */
- if (thd.binlog_query(THD::ROW_QUERY_TYPE,
- row->query.str, row->query.length,
- FALSE, FALSE, FALSE, errcode))
- goto err;
-
- thd.time_zone_used = backup_time_zone_used;
- thd.variables.time_zone = backup_time_zone;
- }
-
if (table->s->blob_fields)
free_delayed_insert_blobs(table);
thread_safe_decrement(delayed_rows_in_use,&LOCK_delayed_status);
@@ -3470,6 +3489,9 @@ bool select_insert::send_eof()
error= (thd->locked_tables_mode <= LTM_LOCK_TABLES ?
table->file->ha_end_bulk_insert() : 0);
+ if (!error && thd->is_error())
+ error= thd->stmt_da->sql_errno();
+
table->file->extra(HA_EXTRA_NO_IGNORE_DUP_KEY);
table->file->extra(HA_EXTRA_WRITE_CANNOT_REPLACE);
@@ -3895,7 +3917,7 @@ select_create::prepare(List<Item> &values, SELECT_LEX_UNIT *u)
if (table->s->fields < values.elements)
{
- my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1);
+ my_error(ER_WRONG_VALUE_COUNT_ON_ROW, MYF(0), 1L);
DBUG_RETURN(-1);
}
@@ -4022,7 +4044,7 @@ bool select_create::send_eof()
{
bool tmp=select_insert::send_eof();
if (tmp)
- abort();
+ abort_result_set();
else
{
/*
@@ -4054,7 +4076,7 @@ void select_create::abort_result_set()
DBUG_ENTER("select_create::abort_result_set");
/*
- In select_insert::abort() we roll back the statement, including
+ In select_insert::abort_result_set() we roll back the statement, including
truncating the transaction cache of the binary log. To do this, we
pretend that the statement is transactional, even though it might
be the case that it was not.
diff --git a/sql/sql_lex.cc b/sql/sql_lex.cc
index b24744571e6..53304d736d8 100644
--- a/sql/sql_lex.cc
+++ b/sql/sql_lex.cc
@@ -38,6 +38,11 @@ static int lex_one_token(void *arg, void *yythd);
sys_var *trg_new_row_fake_var= (sys_var*) 0x01;
/**
+ LEX_STRING constant for null-string to be used in parser and other places.
+*/
+const LEX_STRING null_lex_str= {NULL, 0};
+const LEX_STRING empty_lex_str= {(char *) "", 0};
+/**
@note The order of the elements of this array must correspond to
the order of elements in enum_binlog_stmt_unsafe.
*/
@@ -458,7 +463,7 @@ void lex_start(THD *thd)
lex->select_lex.group_list.empty();
lex->describe= 0;
lex->subqueries= FALSE;
- lex->view_prepare_mode= FALSE;
+ lex->context_analysis_only= 0;
lex->derived_tables= 0;
lex->safe_to_cache_query= 1;
lex->leaf_tables_insert= 0;
@@ -493,7 +498,6 @@ void lex_start(THD *thd)
lex->nest_level=0 ;
lex->allow_sum_func= 0;
lex->in_sum_func= NULL;
- lex->protect_against_global_read_lock= FALSE;
/*
ok, there must be a better solution for this, long-term
I tried "bzero" in the sql_yacc.yy code, but that for
diff --git a/sql/sql_lex.h b/sql/sql_lex.h
index 94d698d4358..662b22c3ec7 100644
--- a/sql/sql_lex.h
+++ b/sql/sql_lex.h
@@ -162,7 +162,7 @@ enum enum_sql_command {
SQLCOM_SHOW_OPEN_TABLES,
SQLCOM_HA_OPEN, SQLCOM_HA_CLOSE, SQLCOM_HA_READ,
SQLCOM_SHOW_SLAVE_HOSTS, SQLCOM_DELETE_MULTI, SQLCOM_UPDATE_MULTI,
- SQLCOM_SHOW_BINLOG_EVENTS, SQLCOM_SHOW_NEW_MASTER, SQLCOM_DO,
+ SQLCOM_SHOW_BINLOG_EVENTS, SQLCOM_DO,
SQLCOM_SHOW_WARNS, SQLCOM_EMPTY_QUERY, SQLCOM_SHOW_ERRORS,
SQLCOM_SHOW_STORAGE_ENGINES, SQLCOM_SHOW_PRIVILEGES,
SQLCOM_HELP, SQLCOM_CREATE_USER, SQLCOM_DROP_USER, SQLCOM_RENAME_USER,
@@ -272,8 +272,7 @@ typedef struct st_lex_server_options
/**
- Structure to hold parameters for CHANGE MASTER or START/STOP SLAVE
- or SHOW NEW MASTER.
+ Structure to hold parameters for CHANGE MASTER, START SLAVE, and STOP SLAVE.
Remark: this should not be confused with Master_info (and perhaps
would better be renamed to st_lex_replication_info). Some fields,
@@ -962,19 +961,19 @@ inline bool st_select_lex_unit::is_union ()
#define ALTER_CHANGE_COLUMN_DEFAULT (1L << 8)
#define ALTER_KEYS_ONOFF (1L << 9)
#define ALTER_CONVERT (1L << 10)
-#define ALTER_FORCE (1L << 11)
-#define ALTER_RECREATE (1L << 12)
-#define ALTER_ADD_PARTITION (1L << 13)
-#define ALTER_DROP_PARTITION (1L << 14)
-#define ALTER_COALESCE_PARTITION (1L << 15)
-#define ALTER_REORGANIZE_PARTITION (1L << 16)
-#define ALTER_PARTITION (1L << 17)
-#define ALTER_ADMIN_PARTITION (1L << 18)
-#define ALTER_TABLE_REORG (1L << 19)
-#define ALTER_REBUILD_PARTITION (1L << 20)
-#define ALTER_ALL_PARTITION (1L << 21)
-#define ALTER_REMOVE_PARTITIONING (1L << 22)
-#define ALTER_FOREIGN_KEY (1L << 23)
+#define ALTER_RECREATE (1L << 11)
+#define ALTER_ADD_PARTITION (1L << 12)
+#define ALTER_DROP_PARTITION (1L << 13)
+#define ALTER_COALESCE_PARTITION (1L << 14)
+#define ALTER_REORGANIZE_PARTITION (1L << 15)
+#define ALTER_PARTITION (1L << 16)
+#define ALTER_ADMIN_PARTITION (1L << 17)
+#define ALTER_TABLE_REORG (1L << 18)
+#define ALTER_REBUILD_PARTITION (1L << 19)
+#define ALTER_ALL_PARTITION (1L << 20)
+#define ALTER_REMOVE_PARTITIONING (1L << 21)
+#define ALTER_FOREIGN_KEY (1L << 22)
+#define ALTER_TRUNCATE_PARTITION (1L << 23)
enum enum_alter_table_change_level
{
@@ -1064,6 +1063,8 @@ struct st_sp_chistics
enum enum_sp_data_access daccess;
};
+extern const LEX_STRING null_lex_str;
+extern const LEX_STRING empty_lex_str;
struct st_trg_chistics
{
@@ -1404,6 +1405,7 @@ public:
STMT_ACCESS_TABLE_COUNT
};
+#ifndef DBUG_OFF
static inline const char *stmt_accessed_table_string(enum_stmt_accessed_table accessed_table)
{
switch (accessed_table)
@@ -1437,7 +1439,10 @@ public:
DBUG_ASSERT(0);
break;
}
+ MY_ASSERT_UNREACHABLE();
+ return "";
}
+#endif /* DBUG */
#define BINLOG_DIRECT_ON 0xF0 /* unsafe when
--binlog-direct-non-trans-updates
@@ -2306,19 +2311,12 @@ struct LEX: public Query_tables_list
uint8 derived_tables;
uint8 create_view_algorithm;
uint8 create_view_check;
+ uint8 context_analysis_only;
bool drop_if_exists, drop_temporary, local_file, one_shot_set;
bool autocommit;
bool verbose, no_write_to_binlog;
enum enum_yes_no_unknown tx_chain, tx_release;
- /*
- Special JOIN::prepare mode: changing of query is prohibited.
- When creating a view, we need to just check its syntax omitting
- any optimizations: afterwards definition of the view will be
- reconstructed by means of ::print() methods and written to
- to an .frm file. We need this definition to stay untouched.
- */
- bool view_prepare_mode;
bool safe_to_cache_query;
bool subqueries, ignore;
st_parsing_options parsing_options;
@@ -2344,6 +2342,7 @@ struct LEX: public Query_tables_list
sp_name *spname;
bool sp_lex_in_use; /* Keep track on lex usage in SPs for error handling */
bool all_privileges;
+ bool proxy_priv;
sp_pcontext *spcont;
st_sp_chistics sp_chistics;
@@ -2382,15 +2381,19 @@ struct LEX: public Query_tables_list
This pointer is required to add possibly omitted DEFINER-clause to the
DDL-statement before dumping it to the binlog.
- keyword_delayed_begin points to the begin of the DELAYED keyword in
- INSERT DELAYED statement.
+ keyword_delayed_begin_offset is the offset to the beginning of the DELAYED
+ keyword in INSERT DELAYED statement. keyword_delayed_end_offset is the
+ offset to the character right after the DELAYED keyword.
*/
union {
const char *stmt_definition_begin;
- const char *keyword_delayed_begin;
+ uint keyword_delayed_begin_offset;
};
- const char *stmt_definition_end;
+ union {
+ const char *stmt_definition_end;
+ uint keyword_delayed_end_offset;
+ };
/**
Collects create options for Field and KEY
@@ -2414,22 +2417,6 @@ struct LEX: public Query_tables_list
bool escape_used;
bool is_lex_started; /* If lex_start() did run. For debugging. */
- /*
- Special case for SELECT .. FOR UPDATE and LOCK TABLES .. WRITE.
-
- Protect from a impending GRL as otherwise the thread might deadlock
- if it starts waiting for the GRL in mysql_lock_tables.
-
- The protection is needed because there is a race between setting
- the global read lock and waiting for all open tables to be closed.
- The problem is a circular wait where a thread holding "old" open
- tables will wait for the global read lock to be released while the
- thread holding the global read lock will wait for all "old" open
- tables to be closed -- the flush part of flush tables with read
- lock.
- */
- bool protect_against_global_read_lock;
-
LEX();
virtual ~LEX()
@@ -2439,6 +2426,13 @@ struct LEX: public Query_tables_list
delete_dynamic(&plugins);
}
+ inline bool is_ps_or_view_context_analysis()
+ {
+ return (context_analysis_only &
+ (CONTEXT_ANALYSIS_ONLY_PREPARE |
+ CONTEXT_ANALYSIS_ONLY_VIEW));
+ }
+
inline void uncacheable(uint8 cause)
{
safe_to_cache_query= 0;
diff --git a/sql/sql_load.cc b/sql/sql_load.cc
index c7c20938dc3..44c2339f462 100644
--- a/sql/sql_load.cc
+++ b/sql/sql_load.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011 Oracle and/or its affiliates. All rights reserved.
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
@@ -363,58 +363,58 @@ int mysql_load(THD *thd,sql_exchange *ex,TABLE_LIST *table_list,
(void) fn_format(name, ex->file_name, mysql_real_data_home, "",
MY_RELATIVE_PATH | MY_UNPACK_FILENAME |
MY_RETURN_REAL_PATH);
-#if !defined(__WIN__)
- MY_STAT stat_info;
- if (!mysql_file_stat(key_file_load, name, &stat_info, MYF(MY_WME)))
- DBUG_RETURN(TRUE);
-
- // if we are not in slave thread, the file must be:
- if (!thd->slave_thread &&
- !((stat_info.st_mode & S_IROTH) == S_IROTH && // readable by others
- (stat_info.st_mode & S_IFLNK) != S_IFLNK && // and not a symlink
- ((stat_info.st_mode & S_IFREG) == S_IFREG ||
- (stat_info.st_mode & S_IFIFO) == S_IFIFO)))
- {
- my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), name);
- DBUG_RETURN(TRUE);
- }
- if ((stat_info.st_mode & S_IFIFO) == S_IFIFO)
- is_fifo = 1;
-#endif
+ }
- if (thd->slave_thread)
- {
+ if (thd->slave_thread)
+ {
#if defined(HAVE_REPLICATION) && !defined(MYSQL_CLIENT)
- if (strncmp(active_mi->rli.slave_patternload_file, name,
- active_mi->rli.slave_patternload_file_size))
- {
- /*
- LOAD DATA INFILE in the slave SQL Thread can only read from
- --slave-load-tmpdir". This should never happen. Please, report a bug.
- */
-
- sql_print_error("LOAD DATA INFILE in the slave SQL Thread can only read from --slave-load-tmpdir. " \
- "Please, report a bug.");
- my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--slave-load-tmpdir");
- DBUG_RETURN(TRUE);
- }
-#else
+ if (strncmp(active_mi->rli.slave_patternload_file, name,
+ active_mi->rli.slave_patternload_file_size))
+ {
/*
- This is impossible and should never happen.
+ LOAD DATA INFILE in the slave SQL Thread can only read from
+ --slave-load-tmpdir". This should never happen. Please, report a bug.
*/
- DBUG_ASSERT(FALSE);
-#endif
- }
- else if (!is_secure_file_path(name))
- {
- /* Read only allowed from within dir specified by secure_file_priv */
- my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
+
+ sql_print_error("LOAD DATA INFILE in the slave SQL Thread can only read from --slave-load-tmpdir. " \
+ "Please, report a bug.");
+ my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--slave-load-tmpdir");
DBUG_RETURN(TRUE);
}
+#else
+ /*
+ This is impossible and should never happen.
+ */
+ DBUG_ASSERT(FALSE);
+#endif
+ }
+ else if (!is_secure_file_path(name))
+ {
+ /* 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);
+ }
+#if !defined(__WIN__) && ! defined(__NETWARE__)
+ MY_STAT stat_info;
+ if (!my_stat(name,&stat_info,MYF(MY_WME)))
+ DBUG_RETURN(TRUE);
+
+ // if we are not in slave thread, the file must be:
+ if (!thd->slave_thread &&
+ !((stat_info.st_mode & S_IFLNK) != S_IFLNK && // symlink
+ ((stat_info.st_mode & S_IFREG) == S_IFREG || // regular file
+ (stat_info.st_mode & S_IFIFO) == S_IFIFO))) // named pipe
+ {
+ my_error(ER_TEXTFILE_NOT_READABLE, MYF(0), name);
+ DBUG_RETURN(TRUE);
}
+ if ((stat_info.st_mode & S_IFIFO) == S_IFIFO)
+ is_fifo = 1;
+#endif
if ((file= mysql_file_open(key_file_load,
name, O_RDONLY, MYF(MY_WME))) < 0)
+
DBUG_RETURN(TRUE);
}
@@ -625,6 +625,13 @@ int mysql_load(THD *thd,sql_exchange *ex,TABLE_LIST *table_list,
transactional_table,
errcode);
}
+
+ /*
+ Flushing the IO CACHE while writing the execute load query log event
+ may result in error (for instance, because the max_binlog_size has been
+ reached, and rotation of the binary log failed).
+ */
+ error= error || mysql_bin_log.get_log_file()->error;
}
if (error)
goto err;
@@ -736,8 +743,7 @@ static bool write_execute_load_query_log_event(THD *thd, sql_exchange* ex,
pfields.append("`");
pfields.append(item->name);
pfields.append("`");
- pfields.append("=");
- val->print(&pfields, QT_ORDINARY);
+ pfields.append(val->name);
}
}
@@ -1294,9 +1300,10 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs,
String &field_term, String &line_start, String &line_term,
String &enclosed_par, int escape, bool get_it_from_net,
bool is_fifo)
- :file(file_par),buffer(0),escape_char(escape)
+ :file(file_par), buffer(NULL), buff_length(tot_length), escape_char(escape),
+ found_end_of_line(false), eof(false), need_end_io_cache(false),
+ error(false), line_cuted(false), found_null(false), read_charset(cs)
{
- read_charset= cs;
field_term_ptr=(char*) field_term.ptr();
field_term_length= field_term.length();
line_term_ptr=(char*) line_term.ptr();
@@ -1324,12 +1331,10 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs,
(uchar) enclosed_par[0] : INT_MAX;
field_term_char= field_term_length ? (uchar) field_term_ptr[0] : INT_MAX;
line_term_char= line_term_length ? (uchar) line_term_ptr[0] : INT_MAX;
- error=eof=found_end_of_line=found_null=line_cuted=0;
- buff_length=tot_length;
/* Set of a stack for unget if long terminators */
- uint length=max(field_term_length,line_term_length)+1;
+ uint length= max(cs->mbmaxlen, max(field_term_length, line_term_length)) + 1;
set_if_bigger(length,line_start.length());
stack=stack_pos=(int*) sql_alloc(sizeof(int)*length);
@@ -1371,10 +1376,9 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs,
READ_INFO::~READ_INFO()
{
- if (!error && need_end_io_cache)
+ if (need_end_io_cache)
::end_io_cache(&cache);
- if (buffer)
- my_free(buffer);
+ my_free(buffer);
List_iterator<XML_TAG> xmlit(taglist);
XML_TAG *t;
while ((t= xmlit++))
diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc
index 1a4d6d9b38d..d12b314001a 100644
--- a/sql/sql_parse.cc
+++ b/sql/sql_parse.cc
@@ -1,4 +1,5 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ Copyright (c) 2011 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
@@ -11,19 +12,16 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#define MYSQL_LEX 1
#include "my_global.h"
#include "sql_priv.h"
#include "unireg.h" // REQUIRED: for other includes
#include "sql_parse.h" // sql_kill, *_precheck, *_prepare
-#include "lock.h" // wait_if_global_read_lock,
- // unlock_global_read_lock,
- // try_transactional_lock,
+#include "lock.h" // try_transactional_lock,
// check_transactional_lock,
// set_handler_table_locks,
- // start_waiting_global_read_lock,
// lock_global_read_lock,
// make_global_read_lock_block_commit
#include "sql_base.h" // find_temporary_tablesx
@@ -34,7 +32,7 @@
#include "sql_locale.h" // my_locale_en_US
#include "log.h" // flush_error_log
#include "sql_view.h" // mysql_create_view, mysql_drop_view
-#include "sql_delete.h" // mysql_truncate, mysql_delete
+#include "sql_delete.h" // mysql_delete
#include "sql_insert.h" // mysql_insert
#include "sql_update.h" // mysql_update, mysql_multi_update
#include "sql_partition.h" // struct partition_info
@@ -49,7 +47,6 @@
// mysql_recreate_table,
// mysql_backup_table,
// mysql_restore_table
-#include "sql_truncate.h" // mysql_truncate_table
#include "sql_reload.h" // reload_acl_and_cache
#include "sql_admin.h" // mysql_assign_to_keycache
#include "sql_connect.h" // check_user,
@@ -183,8 +180,7 @@ static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables)
for (TABLE_LIST *table= tables; table; table= table->next_global)
{
DBUG_ASSERT(table->db && table->table_name);
- if (table->updating &&
- !find_temporary_table(thd, table->db, table->table_name))
+ if (table->updating && !find_temporary_table(thd, table))
return 1;
}
return 0;
@@ -268,21 +264,20 @@ void init_update_queries(void)
the code, in particular in the Query_log_event's constructor.
*/
sql_command_flags[SQLCOM_CREATE_TABLE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL |
+ CF_AUTO_COMMIT_TRANS |
CF_CAN_GENERATE_ROW_EVENTS;
sql_command_flags[SQLCOM_CREATE_INDEX]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_ALTER_TABLE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
- CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
+ CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_TRUNCATE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND |
- CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
+ CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_DROP_TABLE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_LOAD]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_PROTECT_AGAINST_GRL |
CF_CAN_GENERATE_ROW_EVENTS;
- sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
- sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
- sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]= CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
- sql_command_flags[SQLCOM_ALTER_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_PROTECT_AGAINST_GRL;
+ sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]= CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_ALTER_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_RENAME_TABLE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_DROP_INDEX]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_CREATE_VIEW]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
@@ -293,26 +288,18 @@ void init_update_queries(void)
sql_command_flags[SQLCOM_CREATE_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_ALTER_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_DROP_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_CREATE_TRIGGER]= CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_DROP_TRIGGER]= CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_UPDATE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_PROTECT_AGAINST_GRL |
CF_CAN_GENERATE_ROW_EVENTS;
sql_command_flags[SQLCOM_UPDATE_MULTI]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_PROTECT_AGAINST_GRL |
CF_CAN_GENERATE_ROW_EVENTS;
sql_command_flags[SQLCOM_INSERT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_PROTECT_AGAINST_GRL |
CF_CAN_GENERATE_ROW_EVENTS;
sql_command_flags[SQLCOM_INSERT_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_PROTECT_AGAINST_GRL |
CF_CAN_GENERATE_ROW_EVENTS;
sql_command_flags[SQLCOM_DELETE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_PROTECT_AGAINST_GRL |
CF_CAN_GENERATE_ROW_EVENTS;
sql_command_flags[SQLCOM_DELETE_MULTI]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
- CF_PROTECT_AGAINST_GRL |
CF_CAN_GENERATE_ROW_EVENTS;
sql_command_flags[SQLCOM_REPLACE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE |
CF_CAN_GENERATE_ROW_EVENTS;
@@ -336,7 +323,6 @@ void init_update_queries(void)
sql_command_flags[SQLCOM_SHOW_VARIABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
sql_command_flags[SQLCOM_SHOW_CHARSETS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
sql_command_flags[SQLCOM_SHOW_COLLATIONS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE;
- sql_command_flags[SQLCOM_SHOW_NEW_MASTER]= CF_STATUS_COMMAND;
sql_command_flags[SQLCOM_SHOW_BINLOGS]= CF_STATUS_COMMAND;
sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND;
sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND;
@@ -373,20 +359,19 @@ void init_update_queries(void)
sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND | CF_SHOW_TABLE_COMMAND | CF_REEXECUTION_FRAGILE);
- sql_command_flags[SQLCOM_CREATE_USER]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL;
- sql_command_flags[SQLCOM_RENAME_USER]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL;
- sql_command_flags[SQLCOM_DROP_USER]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL;
+ sql_command_flags[SQLCOM_CREATE_USER]= CF_CHANGES_DATA;
+ sql_command_flags[SQLCOM_RENAME_USER]= CF_CHANGES_DATA;
+ sql_command_flags[SQLCOM_DROP_USER]= CF_CHANGES_DATA;
sql_command_flags[SQLCOM_GRANT]= CF_CHANGES_DATA;
sql_command_flags[SQLCOM_REVOKE]= CF_CHANGES_DATA;
- sql_command_flags[SQLCOM_REVOKE_ALL]= CF_PROTECT_AGAINST_GRL;
sql_command_flags[SQLCOM_OPTIMIZE]= CF_CHANGES_DATA;
sql_command_flags[SQLCOM_CREATE_FUNCTION]= CF_CHANGES_DATA;
- sql_command_flags[SQLCOM_CREATE_PROCEDURE]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_DROP_PROCEDURE]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_DROP_FUNCTION]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_ALTER_PROCEDURE]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_ALTER_FUNCTION]= CF_CHANGES_DATA | CF_PROTECT_AGAINST_GRL | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_CREATE_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_DROP_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_DROP_FUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_ALTER_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_ALTER_FUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_INSTALL_PLUGIN]= CF_CHANGES_DATA;
sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]= CF_CHANGES_DATA;
@@ -407,6 +392,7 @@ void init_update_queries(void)
sql_command_flags[SQLCOM_REPAIR]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_OPTIMIZE]|= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_ANALYZE]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
+ sql_command_flags[SQLCOM_CHECK]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_CREATE_USER]|= CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_DROP_USER]|= CF_AUTO_COMMIT_TRANS;
@@ -420,7 +406,6 @@ void init_update_queries(void)
sql_command_flags[SQLCOM_FLUSH]= CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_RESET]= CF_AUTO_COMMIT_TRANS;
- sql_command_flags[SQLCOM_CHECK]= CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_CREATE_SERVER]= CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_ALTER_SERVER]= CF_AUTO_COMMIT_TRANS;
sql_command_flags[SQLCOM_DROP_SERVER]= CF_AUTO_COMMIT_TRANS;
@@ -563,7 +548,7 @@ static void handle_bootstrap_impl(THD *thd)
query= (char *) thd->memdup_w_gap(buff, length + 1,
thd->db_length + 1 +
QUERY_CACHE_FLAGS_SIZE);
- thd->set_query_and_id(query, length, next_query_id());
+ thd->set_query_and_id(query, length, thd->charset(), next_query_id());
DBUG_PRINT("query",("%-.4096s",thd->query()));
#if defined(ENABLED_PROFILING)
thd->profiling.start_new_query();
@@ -626,7 +611,7 @@ void do_handle_bootstrap(THD *thd)
if (my_thread_init() || thd->store_globals())
{
#ifndef EMBEDDED_LIBRARY
- close_connection(thd, ER_OUT_OF_RESOURCES, 1);
+ close_connection(thd, ER_OUT_OF_RESOURCES);
#endif
thd->fatal_error();
goto end;
@@ -652,44 +637,6 @@ end:
return;
}
-/**
- @brief Check access privs for a MERGE table and fix children lock types.
-
- @param[in] thd thread handle
- @param[in] db database name
- @param[in,out] table_list list of child tables (merge_list)
- lock_type and optionally db set per table
-
- @return status
- @retval 0 OK
- @retval != 0 Error
-
- @detail
- This function is used for write access to MERGE tables only
- (CREATE TABLE, ALTER TABLE ... UNION=(...)). Set TL_WRITE for
- every child. Set 'db' for every child if not present.
-*/
-#ifndef NO_EMBEDDED_ACCESS_CHECKS
-bool check_merge_table_access(THD *thd, char *db, TABLE_LIST *table_list)
-{
- int error= 0;
-
- if (table_list)
- {
- /* Check that all tables use the current database */
- TABLE_LIST *tlist;
-
- for (tlist= table_list; tlist; tlist= tlist->next_local)
- {
- if (!tlist->db || !tlist->db[0])
- tlist->db= db; /* purecov: inspected */
- }
- error= check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
- table_list, FALSE, UINT_MAX, FALSE);
- }
- return error;
-}
-#endif
/* This works because items are allocated with sql_alloc() */
@@ -763,9 +710,26 @@ bool do_command(THD *thd)
net_new_transaction(net);
+
/* Save for user statistics */
thd->start_bytes_received= thd->status_var.bytes_received;
+ /*
+ Synchronization point for testing of KILL_CONNECTION.
+ This sync point can wait here, to simulate slow code execution
+ between the last test of thd->killed and blocking in read().
+
+ The goal of this test is to verify that a connection does not
+ hang, if it is killed at this point of execution.
+ (Bug#37780 - main.kill fails randomly)
+
+ Note that the sync point wait itself will be terminated by a
+ kill. In this case it consumes a condition broadcast, but does
+ not change anything else. The consumed broadcast should not
+ matter here, because the read/recv() below doesn't use it.
+ */
+ DEBUG_SYNC(thd, "before_do_command_net_read");
+
if ((packet_length= my_net_read(net)) == packet_error)
{
DBUG_PRINT("info",("Got error %d reading command from socket %s",
@@ -928,7 +892,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
thd->profiling.start_new_query();
#endif
MYSQL_COMMAND_START(thd->thread_id, command,
- thd->security_ctx->priv_user,
+ &thd->security_ctx->priv_user[0],
(char *) thd->security_ctx->host_or_ip);
thd->command=command;
@@ -989,6 +953,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
#endif
case COM_CHANGE_USER:
{
+ bool rc;
status_var_increment(thd->status_var.com_other);
thd->change_user();
@@ -1000,7 +965,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
uint save_db_length= thd->db_length;
char *save_db= thd->db;
USER_CONN *save_user_connect= thd->user_connect;
- Security_context save_security_ctx= *thd->security_ctx;
+ Security_context save_security_ctx= *thd->security_ctx;
CHARSET_INFO *save_character_set_client=
thd->variables.character_set_client;
CHARSET_INFO *save_collation_connection=
@@ -1008,7 +973,9 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
CHARSET_INFO *save_character_set_results=
thd->variables.character_set_results;
- if (acl_authenticate(thd, 0, packet_length))
+ rc= acl_authenticate(thd, 0, packet_length);
+ MYSQL_AUDIT_NOTIFY_CONNECTION_CHANGE_USER(thd);
+ if (rc)
{
my_free(thd->security_ctx->user);
*thd->security_ctx= save_security_ctx;
@@ -1067,7 +1034,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
break; // fatal error is set
MYSQL_QUERY_START(thd->query(), thd->thread_id,
(char *) (thd->db ? thd->db : ""),
- thd->security_ctx->priv_user,
+ &thd->security_ctx->priv_user[0],
(char *) thd->security_ctx->host_or_ip);
char *packet_end= thd->query() + thd->query_length();
general_log_write(thd, command, thd->query(), thd->query_length());
@@ -1084,17 +1051,15 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
while (!thd->killed && (parser_state.m_lip.found_semicolon != NULL) &&
! thd->is_error())
{
- char *beginning_of_next_stmt= (char*)
- parser_state.m_lip.found_semicolon;
-
/*
Multiple queries exits, execute them individually
*/
- close_thread_tables(thd);
+ char *beginning_of_next_stmt= (char*) parser_state.m_lip.found_semicolon;
+ /* Finalize server status flags after executing a statement. */
+ thd->update_server_status();
thd->protocol->end_statement();
query_cache_end_of_result(thd);
-
ulong length= (ulong)(packet_end - beginning_of_next_stmt);
log_slow_statement(thd);
@@ -1119,10 +1084,11 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id,
(char *) (thd->db ? thd->db : ""),
- thd->security_ctx->priv_user,
+ &thd->security_ctx->priv_user[0],
(char *) thd->security_ctx->host_or_ip);
- thd->set_query_and_id(beginning_of_next_stmt, length, next_query_id());
+ thd->set_query_and_id(beginning_of_next_stmt, length,
+ thd->charset(), next_query_id());
/*
Count each statement from the client.
*/
@@ -1152,7 +1118,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
SHOW statements should not add the used tables to the list of tables
used in a transaction.
*/
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]);
if (thd->copy_db_to(&db.str, &db.length))
@@ -1269,7 +1235,7 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
#endif
case COM_REFRESH:
{
- bool not_used;
+ int not_used;
status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]);
ulong options= (ulong) (uchar) packet[0];
if (trans_commit_implicit(thd))
@@ -1444,16 +1410,22 @@ bool dispatch_command(enum enum_server_command command, THD *thd,
(thd->open_tables == NULL ||
(thd->locked_tables_mode == LTM_LOCK_TABLES)));
+ /* Finalize server status flags after executing a command. */
+ thd->update_server_status();
thd->protocol->end_statement();
query_cache_end_of_result(thd);
if (!thd->is_error() && !thd->killed_errno())
mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_RESULT, 0, 0);
+ mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS,
+ thd->stmt_da->is_error() ? thd->stmt_da->sql_errno() : 0,
+ command_name[command].str);
+
log_slow_statement(thd);
thd_proc_info(thd, "cleaning up");
- thd->set_query(NULL, 0);
+ thd->reset_query();
thd->command=COM_SLEEP;
dec_thread_running();
thd_proc_info(thd, 0);
@@ -1512,8 +1484,7 @@ void log_slow_statement(THD *thd)
ulonglong end_utime_of_query= thd->current_utime();
thd_proc_info(thd, "logging slow query");
- if (((end_utime_of_query - thd->utime_after_lock) >
- thd->variables.long_query_time ||
+ if (((thd->server_status & SERVER_QUERY_WAS_SLOW) ||
((thd->server_status &
(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) &&
opt_log_queries_not_using_indexes &&
@@ -1819,17 +1790,68 @@ bool sp_process_definer(THD *thd)
/**
- Execute command saved in thd and lex->sql_command.
+ Auxiliary call that opens and locks tables for LOCK TABLES statement
+ and initializes the list of locked tables.
+
+ @param thd Thread context.
+ @param tables List of tables to be locked.
+
+ @return FALSE in case of success, TRUE in case of error.
+*/
+
+static bool lock_tables_open_and_lock_tables(THD *thd, TABLE_LIST *tables)
+{
+ Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;
+ uint counter;
+ TABLE_LIST *table;
+
+ thd->in_lock_tables= 1;
+
+ if (open_tables(thd, &tables, &counter, 0, &lock_tables_prelocking_strategy))
+ goto err;
+
+ /*
+ We allow to change temporary tables even if they were locked for read
+ by LOCK TABLES. To avoid a discrepancy between lock acquired at LOCK
+ TABLES time and by the statement which is later executed under LOCK TABLES
+ we ensure that for temporary tables we always request a write lock (such
+ discrepancy can cause problems for the storage engine).
+ We don't set TABLE_LIST::lock_type in this case as this might result in
+ extra warnings from THD::decide_logging_format() even though binary logging
+ is totally irrelevant for LOCK TABLES.
+ */
+ for (table= tables; table; table= table->next_global)
+ if (!table->placeholder() && table->table->s->tmp_table)
+ table->table->reginfo.lock_type= TL_WRITE;
- Before every operation that can request a write lock for a table
- wait if a global read lock exists. However do not wait if this
- thread has locked tables already. No new locks can be requested
- until the other locks are released. The thread that requests the
- global read lock waits for write locked tables to become unlocked.
+ if (lock_tables(thd, tables, counter, 0) ||
+ thd->locked_tables_list.init_locked_tables(thd))
+ goto err;
+
+ thd->in_lock_tables= 0;
- Note that wait_if_global_read_lock() sets a protection against a new
- global read lock when it succeeds. This needs to be released by
- start_waiting_global_read_lock() after the operation.
+ return FALSE;
+
+err:
+ thd->in_lock_tables= 0;
+
+ trans_rollback_stmt(thd);
+ /*
+ Need to end the current transaction, so the storage engine (InnoDB)
+ can free its locks if LOCK TABLES locked some tables before finding
+ that it can't lock a table in its list
+ */
+ trans_commit_implicit(thd);
+ /* Close tables and release metadata locks. */
+ close_thread_tables(thd);
+ DBUG_ASSERT(!thd->locked_tables_mode);
+ thd->mdl_context.release_transactional_locks();
+ return TRUE;
+}
+
+
+/**
+ Execute command saved in thd and lex->sql_command.
@param thd Thread handle
@@ -1864,7 +1886,6 @@ mysql_execute_command(THD *thd)
/* have table map for update for multi-update statement (BUG#37051) */
bool have_table_map_for_update= FALSE;
#endif
- /* Saved variable value */
DBUG_ENTER("mysql_execute_command");
#ifdef WITH_PARTITION_STORAGE_ENGINE
thd->work_part_info= 0;
@@ -2056,17 +2077,6 @@ mysql_execute_command(THD *thd)
thd->mdl_context.release_transactional_locks();
}
- /*
- Check if this command needs protection against the global read lock
- to avoid deadlock. See CF_PROTECT_AGAINST_GRL.
- start_waiting_global_read_lock() is called at the end of
- mysql_execute_command().
- */
- if (((sql_command_flags[lex->sql_command] & CF_PROTECT_AGAINST_GRL) != 0) &&
- !thd->locked_tables_mode)
- if (thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, TRUE))
- goto error;
-
#ifndef DBUG_OFF
if (lex->sql_command != SQLCOM_SET_OPTION)
DEBUG_SYNC(thd,"before_execute_sql_command");
@@ -2129,10 +2139,6 @@ mysql_execute_command(THD *thd)
if (res)
break;
- if (!thd->locked_tables_mode && lex->protect_against_global_read_lock &&
- thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, TRUE))
- break;
-
res= execute_sqlcom_select(thd, all_tables);
break;
}
@@ -2226,20 +2232,7 @@ case SQLCOM_PREPARE:
my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling");
goto error;
#endif
- }
- break;
- case SQLCOM_SHOW_NEW_MASTER:
- {
- if (check_global_access(thd, REPL_SLAVE_ACL))
- goto error;
- /* This query don't work now. See comment in repl_failsafe.cc */
-#ifndef WORKING_NEW_MASTER
- my_error(ER_NOT_SUPPORTED_YET, MYF(0), "SHOW NEW MASTER");
- goto error;
-#else
- res = show_new_master(thd);
break;
-#endif
}
#ifdef HAVE_REPLICATION
@@ -2391,20 +2384,6 @@ case SQLCOM_PREPARE:
create_info.default_table_charset= create_info.table_charset;
create_info.table_charset= 0;
}
- /*
- The create-select command will open and read-lock the select table
- and then create, open and write-lock the new table. If a global
- read lock steps in, we get a deadlock. The write lock waits for
- the global read lock, while the global read lock waits for the
- select table to be closed. So we wait until the global readlock is
- gone before starting both steps. Note that
- wait_if_global_read_lock() sets a protection against a new global
- read lock when it succeeds. This needs to be released by
- start_waiting_global_read_lock(). We protect the normal CREATE
- TABLE in the same way. That way we avoid that a new table is
- created during a global read lock.
- Protection against grl is covered by the CF_PROTECT_AGAINST_GRL flag.
- */
#ifdef WITH_PARTITION_STORAGE_ENGINE
{
@@ -2850,7 +2829,11 @@ end_with_restore_list:
{
Incident_log_event ev(thd, incident);
(void) mysql_bin_log.write(&ev); /* error is ignored */
- mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
+ if (mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE))
+ {
+ res= 1;
+ break;
+ }
}
DBUG_PRINT("debug", ("Just after generate_incident()"));
}
@@ -2876,6 +2859,15 @@ end_with_restore_list:
thd->first_successful_insert_id_in_cur_stmt=
thd->first_successful_insert_id_in_prev_stmt;
+ DBUG_EXECUTE_IF("after_mysql_insert",
+ {
+ const char act[]=
+ "now "
+ "wait_for signal.continue";
+ DBUG_ASSERT(opt_debug_sync_timeout > 0);
+ DBUG_ASSERT(!debug_sync_set_action(current_thd,
+ STRING_WITH_LEN(act)));
+ };);
break;
}
case SQLCOM_REPLACE_SELECT:
@@ -3162,36 +3154,13 @@ end_with_restore_list:
if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables,
FALSE, UINT_MAX, FALSE))
goto error;
- if (lex->protect_against_global_read_lock &&
- thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, TRUE))
- goto error;
thd->variables.option_bits|= OPTION_TABLE_LOCK;
- thd->in_lock_tables=1;
-
- {
- Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;
- res= (open_and_lock_tables(thd, all_tables, FALSE, 0,
- &lock_tables_prelocking_strategy) ||
- thd->locked_tables_list.init_locked_tables(thd));
- }
-
- thd->in_lock_tables= 0;
+ res= lock_tables_open_and_lock_tables(thd, all_tables);
if (res)
{
- trans_rollback_stmt(thd);
- /*
- Need to end the current transaction, so the storage engine (InnoDB)
- can free its locks if LOCK TABLES locked some tables before finding
- that it can't lock a table in its list
- */
- trans_commit_implicit(thd);
- /* Close tables and release metadata locks. */
- close_thread_tables(thd);
- DBUG_ASSERT(!thd->locked_tables_mode);
- thd->mdl_context.release_transactional_locks();
thd->variables.option_bits&= ~(OPTION_TABLE_LOCK);
}
else
@@ -3449,6 +3418,10 @@ end_with_restore_list:
if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) &&
check_global_access(thd,CREATE_USER_ACL))
break;
+
+ /* Replicate current user as grantor */
+ thd->binlog_invoker();
+
/* Conditionally writes to binlog */
if (!(res = mysql_revoke_all(thd, lex->users_list)))
my_ok(thd);
@@ -3457,16 +3430,21 @@ end_with_restore_list:
case SQLCOM_REVOKE:
case SQLCOM_GRANT:
{
- if (check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
+ if (lex->type != TYPE_ENUM_PROXY &&
+ check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL,
first_table ? first_table->db : select_lex->db,
first_table ? &first_table->grant.privilege : NULL,
first_table ? &first_table->grant.m_internal : NULL,
first_table ? 0 : 1, 0))
goto error;
+ /* Replicate current user as grantor */
+ thd->binlog_invoker();
+
if (thd->security_ctx->user) // If not replication
{
LEX_USER *user, *tmp_user;
+ bool first_user= TRUE;
List_iterator <LEX_USER> user_list(lex->users_list);
while ((tmp_user= user_list++))
@@ -3477,24 +3455,26 @@ end_with_restore_list:
hostname_requires_resolving(user->host.str))
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
ER_WARN_HOSTNAME_WONT_WORK,
- ER(ER_WARN_HOSTNAME_WONT_WORK),
- user->host.str);
+ ER(ER_WARN_HOSTNAME_WONT_WORK));
// Are we trying to change a password of another user
DBUG_ASSERT(user->host.str != 0);
- if (strcmp(thd->security_ctx->user, user->user.str) ||
- my_strcasecmp(system_charset_info,
- user->host.str, thd->security_ctx->host_or_ip))
+
+ /*
+ GRANT/REVOKE PROXY has the target user as a first entry in the list.
+ */
+ if (lex->type == TYPE_ENUM_PROXY && first_user)
{
- // TODO: use check_change_password()
- if (is_acl_user(user->host.str, user->user.str) &&
- user->password.str &&
- check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1))
- {
- my_message(ER_PASSWORD_NOT_ALLOWED,
- ER(ER_PASSWORD_NOT_ALLOWED), MYF(0));
+ first_user= FALSE;
+ if (acl_check_proxy_grant_access (thd, user->host.str, user->user.str,
+ lex->grant & GRANT_ACL))
goto error;
- }
- }
+ }
+ else if (is_acl_user(user->host.str, user->user.str) &&
+ user->password.str &&
+ check_change_password (thd, user->host.str, user->user.str,
+ user->password.str,
+ user->password.length))
+ goto error;
}
}
if (first_table)
@@ -3529,16 +3509,19 @@ end_with_restore_list:
}
else
{
- if (lex->columns.elements || lex->type)
+ if (lex->columns.elements || (lex->type && lex->type != TYPE_ENUM_PROXY))
{
my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE),
MYF(0));
goto error;
}
else
- /* Conditionally writes to binlog */
- res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
- lex->sql_command == SQLCOM_REVOKE);
+ {
+ /* Conditionally writes to binlog */
+ res = mysql_grant(thd, select_lex->db, lex->users_list, lex->grant,
+ lex->sql_command == SQLCOM_REVOKE,
+ lex->type == TYPE_ENUM_PROXY);
+ }
if (!res)
{
if (lex->sql_command == SQLCOM_GRANT)
@@ -3565,8 +3548,7 @@ end_with_restore_list:
lex->no_write_to_binlog= 1;
case SQLCOM_FLUSH:
{
- bool write_to_binlog;
-
+ int write_to_binlog;
if (check_global_access(thd,RELOAD_ACL))
goto error;
@@ -3595,12 +3577,22 @@ end_with_restore_list:
/*
Presumably, RESET and binlog writing doesn't require synchronization
*/
- if (!lex->no_write_to_binlog && write_to_binlog)
+
+ if (write_to_binlog > 0) // we should write
+ {
+ if (!lex->no_write_to_binlog)
+ res= write_bin_log(thd, FALSE, thd->query(), thd->query_length());
+ } else if (write_to_binlog < 0)
{
- if ((res= write_bin_log(thd, FALSE, thd->query(), thd->query_length())))
- break;
- }
- my_ok(thd);
+ /*
+ We should not write, but rather report error because
+ reload_acl_and_cache binlog interactions failed
+ */
+ res= 1;
+ }
+
+ if (!res)
+ my_ok(thd);
}
break;
@@ -3805,13 +3797,22 @@ end_with_restore_list:
Security_context *backup= NULL;
LEX_USER *definer= thd->lex->definer;
/*
- We're going to issue an implicit GRANT statement.
- It takes metadata locks and updates system tables.
- Make sure that sp_create_routine() did not leave any
- locks in the MDL context, so there is no risk to
- deadlock.
+ We're going to issue an implicit GRANT statement so we close all
+ open tables. We have to keep metadata locks as this ensures that
+ this statement is atomic against concurent FLUSH TABLES WITH READ
+ LOCK. Deadlocks which can arise due to fact that this implicit
+ statement takes metadata locks should be detected by a deadlock
+ detector in MDL subsystem and reported as errors.
+
+ No need to commit/rollback statement transaction, it's not started.
+
+ TODO: Long-term we should either ensure that implicit GRANT statement
+ is written into binary log as a separate statement or make both
+ creation of routine and implicit GRANT parts of one fully atomic
+ statement.
*/
- close_mysql_tables(thd);
+ DBUG_ASSERT(thd->transaction.stmt.is_empty());
+ close_thread_tables(thd);
/*
Check if the definer exists on slave,
then use definer privilege to insert routine privileges to mysql.procs_priv.
@@ -4059,49 +4060,48 @@ create_sp_error:
int sp_result;
int type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ?
TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION);
+ char *db= lex->spname->m_db.str;
+ char *name= lex->spname->m_name.str;
- /*
- @todo: here we break the metadata locking protocol by
- looking up the information about the routine without
- a metadata lock. Rewrite this piece to make sp_drop_routine
- return whether the routine existed or not.
- */
- sp_result= sp_routine_exists_in_table(thd, type, lex->spname);
- thd->warning_info->opt_clear_warning_info(thd->query_id);
- if (sp_result == SP_OK)
- {
- char *db= lex->spname->m_db.str;
- char *name= lex->spname->m_name.str;
-
- if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
- lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
- goto error;
+ if (check_routine_access(thd, ALTER_PROC_ACL, db, name,
+ lex->sql_command == SQLCOM_DROP_PROCEDURE, 0))
+ goto error;
- /* Conditionally writes to binlog */
- sp_result= sp_drop_routine(thd, type, lex->spname);
+ /* Conditionally writes to binlog */
+ sp_result= sp_drop_routine(thd, type, lex->spname);
#ifndef NO_EMBEDDED_ACCESS_CHECKS
- /*
- We're going to issue an implicit REVOKE statement.
- It takes metadata locks and updates system tables.
- Make sure that sp_create_routine() did not leave any
- locks in the MDL context, so there is no risk to
- deadlock.
- */
- close_mysql_tables(thd);
+ /*
+ We're going to issue an implicit REVOKE statement so we close all
+ open tables. We have to keep metadata locks as this ensures that
+ this statement is atomic against concurent FLUSH TABLES WITH READ
+ LOCK. Deadlocks which can arise due to fact that this implicit
+ statement takes metadata locks should be detected by a deadlock
+ detector in MDL subsystem and reported as errors.
+
+ No need to commit/rollback statement transaction, it's not started.
+
+ TODO: Long-term we should either ensure that implicit REVOKE statement
+ is written into binary log as a separate statement or make both
+ dropping of routine and implicit REVOKE parts of one fully atomic
+ statement.
+ */
+ DBUG_ASSERT(thd->transaction.stmt.is_empty());
+ close_thread_tables(thd);
- if (sp_automatic_privileges && !opt_noacl &&
- sp_revoke_privileges(thd, db, name,
- lex->sql_command == SQLCOM_DROP_PROCEDURE))
- {
- push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
- ER_PROC_AUTO_REVOKE_FAIL,
- ER(ER_PROC_AUTO_REVOKE_FAIL));
- /* If this happens, an error should have been reported. */
- goto error;
- }
-#endif
+ if (sp_result != SP_KEY_NOT_FOUND &&
+ sp_automatic_privileges && !opt_noacl &&
+ sp_revoke_privileges(thd, db, name,
+ lex->sql_command == SQLCOM_DROP_PROCEDURE))
+ {
+ push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ ER_PROC_AUTO_REVOKE_FAIL,
+ ER(ER_PROC_AUTO_REVOKE_FAIL));
+ /* If this happens, an error should have been reported. */
+ goto error;
}
+#endif
+
res= sp_result;
switch (sp_result) {
case SP_OK:
@@ -4378,14 +4378,6 @@ error:
res= TRUE;
finish:
- if (thd->global_read_lock.has_protection())
- {
- /*
- Release the protection against the global read lock and wake
- everyone, who might want to set a global read lock.
- */
- thd->global_read_lock.start_waiting_global_read_lock(thd);
- }
DBUG_ASSERT(!thd->in_active_multi_stmt_transaction() ||
thd->in_multi_stmt_transaction_mode());
@@ -4421,6 +4413,11 @@ finish:
close_thread_tables(thd);
thd_proc_info(thd, 0);
+#ifndef DBUG_OFF
+ if (lex->sql_command != SQLCOM_SET_OPTION && ! thd->in_sub_stmt)
+ DEBUG_SYNC(thd, "execute_command_after_close_tables");
+#endif
+
if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END))
{
/* No transaction control allowed in sub-statements. */
@@ -4446,6 +4443,10 @@ finish:
*/
thd->mdl_context.release_transactional_locks();
}
+ else if (! thd->in_sub_stmt)
+ {
+ thd->mdl_context.release_statement_locks();
+ }
DBUG_RETURN(res || thd->is_error());
}
@@ -4478,12 +4479,20 @@ static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables)
return 1; /* purecov: inspected */
thd->send_explain_fields(result);
res= mysql_explain_union(thd, &thd->lex->unit, result);
- if (lex->describe & DESCRIBE_EXTENDED)
+ /*
+ The code which prints the extended description is not robust
+ against malformed queries, so skip it if we have an error.
+ */
+ if (!res && (lex->describe & DESCRIBE_EXTENDED))
{
char buff[1024];
String str(buff,(uint32) sizeof(buff), system_charset_info);
str.length(0);
- thd->lex->unit.print(&str, QT_ORDINARY);
+ /*
+ The warnings system requires input in utf8, @see
+ mysqld_show_warnings().
+ */
+ thd->lex->unit.print(&str, QT_TO_SYSTEM_CHARSET);
str.append('\0');
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE,
ER_YES, str.ptr());
@@ -4802,7 +4811,7 @@ check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
if (!no_errors)
{
status_var_increment(thd->status_var.access_denied_errors);
- my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
+ my_error(access_denied_error_code(thd->password), MYF(0),
sctx->priv_user,
sctx->priv_host,
(thd->password ?
@@ -5222,10 +5231,17 @@ bool check_stack_overrun(THD *thd, long margin,
if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >=
(long) (my_thread_stack_size - margin))
{
- char ebuff[MYSQL_ERRMSG_SIZE];
- my_snprintf(ebuff, sizeof(ebuff), ER(ER_STACK_OVERRUN_NEED_MORE),
- stack_used, my_thread_stack_size, margin);
- my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR));
+ /*
+ Do not use stack for the message buffer to ensure correct
+ behaviour in cases we have close to no stack left.
+ */
+ char* ebuff= new char[MYSQL_ERRMSG_SIZE];
+ if (ebuff) {
+ my_snprintf(ebuff, MYSQL_ERRMSG_SIZE, ER(ER_STACK_OVERRUN_NEED_MORE),
+ stack_used, my_thread_stack_size, margin);
+ my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR));
+ delete [] ebuff;
+ }
return 1;
}
#ifndef DBUG_OFF
@@ -5411,17 +5427,10 @@ mysql_new_select(LEX *lex, bool move_down)
lex->nest_level++;
if (lex->nest_level > (int) MAX_SELECT_NESTING)
{
- my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT,MYF(0),MAX_SELECT_NESTING);
+ my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0));
DBUG_RETURN(1);
}
select_lex->nest_level= lex->nest_level;
- /*
- Don't evaluate this subquery during statement prepare even if
- it's a constant one. The flag is switched off in the end of
- mysqld_stmt_prepare.
- */
- if (thd->stmt_arena->is_stmt_prepare())
- select_lex->uncacheable|= UNCACHEABLE_PREPARE;
if (move_down)
{
SELECT_LEX_UNIT *unit;
@@ -5596,7 +5605,8 @@ void mysql_parse(THD *thd, char *rawbuf, uint length,
if (found_semicolon && (ulong) (found_semicolon - thd->query()))
thd->set_query_inner(thd->query(),
(uint32) (found_semicolon -
- thd->query() - 1));
+ thd->query() - 1),
+ thd->charset());
/* Actually execute the query */
if (found_semicolon)
{
@@ -5607,7 +5617,7 @@ void mysql_parse(THD *thd, char *rawbuf, uint length,
MYSQL_QUERY_EXEC_START(thd->query(),
thd->thread_id,
(char *) (thd->db ? thd->db : ""),
- thd->security_ctx->priv_user,
+ &thd->security_ctx->priv_user[0],
(char *) thd->security_ctx->host_or_ip,
0);
@@ -5992,7 +6002,8 @@ TABLE_LIST *st_select_lex::add_table_to_list(THD *thd,
ptr->next_name_resolution_table= NULL;
/* Link table in global list (all used tables) */
lex->add_to_query_tables(ptr);
- ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type);
+ ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type,
+ MDL_TRANSACTION);
DBUG_RETURN(ptr);
}
@@ -6990,10 +7001,16 @@ bool create_table_precheck(THD *thd, TABLE_LIST *tables,
if (check_access(thd, want_priv, create_table->db,
&create_table->grant.privilege,
&create_table->grant.m_internal,
- 0, 0) ||
- check_merge_table_access(thd, create_table->db,
- lex->create_info.merge_list.first))
+ 0, 0))
goto err;
+
+ /* If it is a merge table, check privileges for merge children. */
+ if (lex->create_info.merge_list.first &&
+ check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL,
+ lex->create_info.merge_list.first,
+ FALSE, UINT_MAX, FALSE))
+ goto err;
+
if (want_priv != CREATE_TMP_ACL &&
check_grant(thd, want_priv, create_table, FALSE, 1, FALSE))
goto err;
@@ -7342,10 +7359,20 @@ bool parse_sql(THD *thd,
bool mysql_parse_status= MYSQLparse(thd) != 0;
- /* Check that if MYSQLparse() failed, thd->is_error() is set. */
+ /*
+ Check that if MYSQLparse() failed either thd->is_error() is set, or an
+ internal error handler is set.
+
+ The assert will not catch a situation where parsing fails without an
+ error reported if an error handler exists. The problem is that the
+ error handler might have intercepted the error, so thd->is_error() is
+ not set. However, there is no way to be 100% sure here (the error
+ handler might be for other errors than parsing one).
+ */
DBUG_ASSERT(!mysql_parse_status ||
- (mysql_parse_status && thd->is_error()));
+ (mysql_parse_status && thd->is_error()) ||
+ (mysql_parse_status && thd->get_internal_handler()));
/* Reset parser state. */
diff --git a/sql/sql_parse.h b/sql/sql_parse.h
index 11177a9bcf7..650588c5cac 100644
--- a/sql/sql_parse.h
+++ b/sql/sql_parse.h
@@ -155,7 +155,6 @@ bool check_single_table_access(THD *thd, ulong privilege,
bool check_routine_access(THD *thd,ulong want_access,char *db,char *name,
bool is_proc, bool no_errors);
bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table);
-bool check_merge_table_access(THD *thd, char *db, TABLE_LIST *table_list);
bool check_some_routine_access(THD *thd, const char *db, const char *name, bool is_proc);
bool check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv,
GRANT_INTERNAL_INFO *grant_internal_info,
@@ -178,8 +177,6 @@ inline bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table)
table->grant.privilege= want_access;
return false;
}
-inline bool check_merge_table_access(THD *thd, char *db, TABLE_LIST *table_list)
-{ return false; }
inline bool check_some_routine_access(THD *thd, const char *db,
const char *name, bool is_proc)
{ return false; }
@@ -202,4 +199,10 @@ check_table_access(THD *thd, ulong requirements,TABLE_LIST *tables,
bool check_global_access(THD *thd, ulong want_access);
+inline bool is_supported_parser_charset(CHARSET_INFO *cs)
+{
+ return test(cs->mbminlen == 1);
+}
+
+
#endif /* SQL_PARSE_INCLUDED */
diff --git a/sql/sql_partition.cc b/sql/sql_partition.cc
index 2d15ca24733..de4ee14b3c1 100644
--- a/sql/sql_partition.cc
+++ b/sql/sql_partition.cc
@@ -1,4 +1,4 @@
-/* Copyright 2005-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -70,6 +70,7 @@
#ifdef WITH_PARTITION_STORAGE_ENGINE
#include "ha_partition.h"
+/* TODO: Change abort() to DBUG_SUICIDE() when bug#52002 is pushed */
#define ERROR_INJECT_CRASH(code) \
DBUG_EVALUATE_IF(code, (abort(), 0), 0)
#define ERROR_INJECT_ERROR(code) \
@@ -89,7 +90,6 @@ const LEX_STRING partition_keywords[]=
{ C_STRING_WITH_LEN(" COLUMNS") }
};
static const char *part_str= "PARTITION";
-static const char *subpart_str= "SUBPARTITION";
static const char *sub_str= "SUB";
static const char *by_str= "BY";
static const char *space_str= " ";
@@ -166,12 +166,13 @@ int get_part_iter_for_interval_via_walking(partition_info *part_info,
uint min_len, uint max_len,
uint flags,
PARTITION_ITERATOR *part_iter);
+
+#ifdef WITH_PARTITION_STORAGE_ENGINE
static int cmp_rec_and_tuple(part_column_list_val *val, uint32 nvals_in_rec);
static int cmp_rec_and_tuple_prune(part_column_list_val *val,
uint32 n_vals_in_rec,
bool tail_is_min);
-#ifdef WITH_PARTITION_STORAGE_ENGINE
/*
Convert constants in VALUES definition to the character set the
corresponding field uses.
@@ -1055,12 +1056,13 @@ static bool fix_fields_part_func(THD *thd, Item* func_expr, TABLE *table,
}
/*
- We don't allow creating partitions with timezone-dependent expressions as
- a (sub)partitioning function, but we want to allow such expressions when
- opening existing tables for easier maintenance. This exception should be
- deprecated at some point in future so that we always throw an error.
+ We don't allow creating partitions with expressions with non matching
+ arguments as a (sub)partitioning function,
+ but we want to allow such expressions when opening existing tables for
+ easier maintenance. This exception should be deprecated at some point
+ in future so that we always throw an error.
*/
- if (func_expr->walk(&Item::is_timezone_dependent_processor,
+ if (func_expr->walk(&Item::check_valid_arguments_processor,
0, NULL))
{
if (is_create_table_ind)
@@ -1688,8 +1690,7 @@ bool fix_partition_func(THD *thd, TABLE *table,
goto end;
if (unlikely(part_info->subpart_expr->result_type() != INT_RESULT))
{
- my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0),
- subpart_str);
+ part_info->report_part_expr_error(TRUE);
goto end;
}
}
@@ -1716,10 +1717,9 @@ bool fix_partition_func(THD *thd, TABLE *table,
goto end;
if (unlikely(part_info->part_expr->result_type() != INT_RESULT))
{
- my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0), part_str);
+ part_info->report_part_expr_error(FALSE);
goto end;
}
- part_info->part_result_type= INT_RESULT;
}
part_info->fixed= TRUE;
}
@@ -1765,18 +1765,22 @@ bool fix_partition_func(THD *thd, TABLE *table,
if (unlikely(!part_info->column_list &&
part_info->part_expr->result_type() != INT_RESULT))
{
- my_error(ER_PARTITION_FUNC_NOT_ALLOWED_ERROR, MYF(0), part_str);
+ part_info->report_part_expr_error(FALSE);
goto end;
}
}
if (((part_info->part_type != HASH_PARTITION ||
- part_info->list_of_part_fields == FALSE) &&
- (!part_info->column_list &&
- check_part_func_fields(part_info->part_field_array, TRUE))) ||
+ part_info->list_of_part_fields == FALSE) &&
+ !part_info->column_list &&
+ check_part_func_fields(part_info->part_field_array, TRUE)) ||
(part_info->list_of_subpart_fields == FALSE &&
part_info->is_sub_partitioned() &&
check_part_func_fields(part_info->subpart_field_array, TRUE)))
{
+ /*
+ Range/List/HASH (but not KEY) and not COLUMNS or HASH subpartitioning
+ with columns in the partitioning expression using unallowed charset.
+ */
my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
goto end;
}
@@ -1920,7 +1924,7 @@ static int add_part_field_list(File fptr, List<char> field_list)
String field_string("", 0, system_charset_info);
THD *thd= current_thd;
ulonglong save_options= thd->variables.option_bits;
- thd->variables.option_bits= 0;
+ thd->variables.option_bits&= ~OPTION_QUOTE_SHOW_CREATE;
append_identifier(thd, &field_string, field_str,
strlen(field_str));
thd->variables.option_bits= save_options;
@@ -1939,8 +1943,7 @@ static int add_name_string(File fptr, const char *name)
String name_string("", 0, system_charset_info);
THD *thd= current_thd;
ulonglong save_options= thd->variables.option_bits;
-
- thd->variables.option_bits= 0;
+ thd->variables.option_bits&= ~OPTION_QUOTE_SHOW_CREATE;
append_identifier(thd, &name_string, name,
strlen(name));
thd->variables.option_bits= save_options;
@@ -3902,7 +3905,7 @@ void get_partition_set(const TABLE *table, uchar *buf, const uint index,
part_spec->start_part= 0;
part_spec->end_part= num_parts - 1;
if ((index < MAX_KEY) &&
- key_spec->flag == (uint)HA_READ_KEY_EXACT &&
+ key_spec && key_spec->flag == (uint)HA_READ_KEY_EXACT &&
part_info->some_fields_in_PF.is_set(index))
{
key_info= table->key_info+index;
@@ -4279,43 +4282,31 @@ set_engine_all_partitions(partition_info *part_info,
}
} while (++i < part_info->num_parts);
}
-/*
- SYNOPSIS
- fast_end_partition()
- thd Thread object
- out:copied Number of records copied
- out:deleted Number of records deleted
- table_list Table list with the one table in it
- empty Has nothing been done
- lpt Struct to be used by error handler
- RETURN VALUES
- FALSE Success
- TRUE Failure
- DESCRIPTION
- Support routine to handle the successful cases for partition
- management.
+/**
+ Support routine to handle the successful cases for partition management.
+
+ @param thd Thread object
+ @param copied Number of records copied
+ @param deleted Number of records deleted
+ @param table_list Table list with the one table in it
+
+ @return Operation status
+ @retval FALSE Success
+ @retval TRUE Failure
*/
static int fast_end_partition(THD *thd, ulonglong copied,
ulonglong deleted,
- TABLE_LIST *table_list, bool is_empty,
- ALTER_PARTITION_PARAM_TYPE *lpt,
- bool written_bin_log)
+ TABLE_LIST *table_list)
{
char tmp_name[80];
DBUG_ENTER("fast_end_partition");
thd->proc_info="end";
- if (!is_empty)
- query_cache_invalidate3(thd, table_list, 0);
-
- if ((!is_empty) && (!written_bin_log) &&
- (!thd->lex->no_write_to_binlog) &&
- write_bin_log(thd, FALSE, thd->query(), thd->query_length()))
- DBUG_RETURN(TRUE);
+ query_cache_invalidate3(thd, table_list, 0);
my_snprintf(tmp_name, sizeof(tmp_name), ER(ER_INSERT_INFO),
(ulong) (copied + deleted),
@@ -4437,29 +4428,25 @@ uint set_part_state(Alter_info *alter_info, partition_info *tab_part_info,
}
-/*
+/**
Prepare for ALTER TABLE of partition structure
- SYNOPSIS
- prep_alter_part_table()
- thd Thread object
- table Table object
- inout:alter_info Alter information
- inout:create_info Create info for CREATE TABLE
- old_db_type Old engine type
- out:partition_changed Boolean indicating whether partition changed
- out:fast_alter_partition Boolean indicating whether fast partition
- change is requested
+ @param[in] thd Thread object
+ @param[in] table Table object
+ @param[in,out] alter_info Alter information
+ @param[in,out] create_info Create info for CREATE TABLE
+ @param[in] old_db_type Old engine type
+ @param[out] partition_changed Boolean indicating whether partition changed
+ @param[out] fast_alter_table Internal temporary table allowing fast
+ partition change or NULL if not possible
- RETURN VALUES
- TRUE Error
- FALSE Success
- partition_changed
- fast_alter_partition
+ @return Operation status
+ @retval TRUE Error
+ @retval FALSE Success
- DESCRIPTION
+ @note
This method handles all preparations for ALTER TABLE for partitioned
- tables
+ tables.
We need to handle both partition management command such as Add Partition
and others here as well as an ALTER TABLE that completely changes the
partitioning and yet others that don't change anything at all. We start
@@ -4471,8 +4458,12 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
HA_CREATE_INFO *create_info,
handlerton *old_db_type,
bool *partition_changed,
- uint *fast_alter_partition)
+ char *db,
+ const char *table_name,
+ const char *path,
+ TABLE **fast_alter_table)
{
+ TABLE *new_table= NULL;
DBUG_ENTER("prep_alter_part_table");
/* Foreign keys on partitioned tables are not supported, waits for WL#148 */
@@ -4481,15 +4472,9 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
my_error(ER_FOREIGN_KEY_ON_PARTITIONED, MYF(0));
DBUG_RETURN(TRUE);
}
- /*
- We are going to manipulate the partition info on the table object
- so we need to ensure that the table instance is removed from the
- table cache.
- */
- if (table->part_info)
- table->m_needs_reopen= TRUE;
thd->work_part_info= thd->lex->part_info;
+
if (thd->work_part_info &&
!(thd->work_part_info= thd->lex->part_info->get_clone()))
DBUG_RETURN(TRUE);
@@ -4502,7 +4487,7 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
ALTER_COALESCE_PARTITION | ALTER_REORGANIZE_PARTITION |
ALTER_TABLE_REORG | ALTER_REBUILD_PARTITION))
{
- partition_info *tab_part_info= table->part_info;
+ partition_info *tab_part_info;
partition_info *alt_part_info= thd->work_part_info;
uint flags= 0;
bool is_last_partition_reorged= FALSE;
@@ -4510,11 +4495,32 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
part_elem_value *alt_max_elem_val= NULL;
longlong tab_max_range= 0, alt_max_range= 0;
- if (!tab_part_info)
+ if (!table->part_info)
{
my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));
DBUG_RETURN(TRUE);
}
+
+ /*
+ Open our intermediate table, we will operate on a temporary instance
+ of the original table, to be able to skip copying all partitions.
+ Open it as a copy of the original table, and modify its partition_info
+ object to allow fast_alter_partition_table to perform the changes.
+ */
+ DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE, db, table_name,
+ MDL_INTENTION_EXCLUSIVE));
+ new_table= open_table_uncached(thd, path, db, table_name, 0);
+ if (!new_table)
+ DBUG_RETURN(TRUE);
+
+ /*
+ This table may be used for copy rows between partitions
+ and also read/write columns when fixing the partition_info struct.
+ */
+ new_table->use_all_columns();
+
+ tab_part_info= new_table->part_info;
+
if (alter_info->flags & ALTER_TABLE_REORG)
{
uint new_part_no, curr_part_no;
@@ -4522,9 +4528,9 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
tab_part_info->use_default_num_partitions)
{
my_error(ER_REORG_NO_PARAM_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
- new_part_no= table->file->get_default_no_partitions(create_info);
+ new_part_no= new_table->file->get_default_no_partitions(create_info);
curr_part_no= tab_part_info->num_parts;
if (new_part_no == curr_part_no)
{
@@ -4533,7 +4539,8 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
after the change as before. Thus we can reply ok immediately
without any changes at all.
*/
- *fast_alter_partition= TRUE;
+ *fast_alter_table= new_table;
+ thd->work_part_info= tab_part_info;
DBUG_RETURN(FALSE);
}
else if (new_part_no > curr_part_no)
@@ -4555,15 +4562,15 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
alter_info->num_parts= curr_part_no - new_part_no;
}
}
- if (!(flags= table->file->alter_table_flags(alter_info->flags)))
+ if (!(flags= new_table->file->alter_table_flags(alter_info->flags)))
{
my_error(ER_PARTITION_FUNCTION_FAILURE, MYF(0));
- DBUG_RETURN(1);
+ goto err;
}
- *fast_alter_partition=
- ((flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE)) != 0);
- DBUG_PRINT("info", ("*fast_alter_partition: %d flags: 0x%x",
- *fast_alter_partition, flags));
+ if ((flags & (HA_FAST_CHANGE_PARTITION | HA_PARTITION_ONE_PHASE)) != 0)
+ *fast_alter_table= new_table;
+ DBUG_PRINT("info", ("*fast_alter_table: %p flags: 0x%x",
+ *fast_alter_table, flags));
if ((alter_info->flags & ALTER_ADD_PARTITION) ||
(alter_info->flags & ALTER_REORGANIZE_PARTITION))
{
@@ -4574,12 +4581,12 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
if (tab_part_info->part_type == RANGE_PARTITION)
{
my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), "RANGE");
- DBUG_RETURN(TRUE);
+ goto err;
}
else if (tab_part_info->part_type == LIST_PARTITION)
{
my_error(ER_PARTITIONS_MUST_BE_DEFINED_ERROR, MYF(0), "LIST");
- DBUG_RETURN(TRUE);
+ goto err;
}
/*
Hash partitions can be altered without parser finds out about
@@ -4610,7 +4617,7 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
my_error(ER_PARTITION_REQUIRES_VALUES_ERROR, MYF(0),
"LIST", "IN");
}
- DBUG_RETURN(TRUE);
+ goto err;
}
}
if ((tab_part_info->column_list &&
@@ -4624,12 +4631,12 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
alt_part_info->num_columns != 0))
{
my_error(ER_PARTITION_COLUMN_LIST_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
alt_part_info->column_list= tab_part_info->column_list;
if (alt_part_info->fix_parser_data(thd))
{
- DBUG_RETURN(TRUE);
+ goto err;
}
}
if (alter_info->flags & ALTER_ADD_PARTITION)
@@ -4652,17 +4659,17 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
tab_part_info->part_type != HASH_PARTITION)
{
my_error(ER_NO_BINLOG_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
if (tab_part_info->defined_max_value)
{
my_error(ER_PARTITION_MAXVALUE_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
if (num_new_partitions == 0)
{
my_error(ER_ADD_PARTITION_NO_NEW_PARTITION, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
if (tab_part_info->is_sub_partitioned())
{
@@ -4671,7 +4678,7 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
else if (alt_part_info->num_subparts != tab_part_info->num_subparts)
{
my_error(ER_ADD_PARTITION_SUBPART_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
check_total_partitions= new_total_partitions*
alt_part_info->num_subparts;
@@ -4679,15 +4686,15 @@ uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
if (check_total_partitions > MAX_PARTITIONS)
{
my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
alt_part_info->part_type= tab_part_info->part_type;
alt_part_info->subpart_type= tab_part_info->subpart_type;
- if (alt_part_info->set_up_defaults_for_partitioning(table->file,
+ if (alt_part_info->set_up_defaults_for_partitioning(new_table->file,
ULL(0),
tab_part_info->num_parts))
{
- DBUG_RETURN(TRUE);
+ goto err;
}
/*
Handling of on-line cases:
@@ -4751,7 +4758,7 @@ adding and copying partitions, the second after completing the adding
and copying and finally the third line after also dropping the partitions
that are reorganised.
*/
- if (*fast_alter_partition &&
+ if (*fast_alter_table &&
tab_part_info->part_type == HASH_PARTITION)
{
uint part_no= 0, start_part= 1, start_sec_part= 1;
@@ -4856,12 +4863,12 @@ that are reorganised.
do
{
partition_element *part_elem= alt_it++;
- if (*fast_alter_partition)
+ if (*fast_alter_table)
part_elem->part_state= PART_TO_BE_ADDED;
if (tab_part_info->partitions.push_back(part_elem))
{
mem_alloc_error(1);
- DBUG_RETURN(TRUE);
+ goto err;
}
} while (++part_count < num_new_partitions);
tab_part_info->num_parts+= num_new_partitions;
@@ -4902,12 +4909,12 @@ that are reorganised.
tab_part_info->part_type == LIST_PARTITION))
{
my_error(ER_ONLY_ON_RANGE_LIST_PARTITION, MYF(0), "DROP");
- DBUG_RETURN(TRUE);
+ goto err;
}
if (num_parts_dropped >= tab_part_info->num_parts)
{
my_error(ER_DROP_LAST_PARTITION, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
do
{
@@ -4925,12 +4932,12 @@ that are reorganised.
if (num_parts_found != num_parts_dropped)
{
my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "DROP");
- DBUG_RETURN(TRUE);
+ goto err;
}
- if (table->file->is_fk_defined_on_table_or_index(MAX_KEY))
+ if (new_table->file->is_fk_defined_on_table_or_index(MAX_KEY))
{
my_error(ER_ROW_IS_REFERENCED, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
tab_part_info->num_parts-= num_parts_dropped;
}
@@ -4943,12 +4950,12 @@ that are reorganised.
(!(alter_info->flags & ALTER_ALL_PARTITION)))
{
my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "REBUILD");
- DBUG_RETURN(TRUE);
+ goto err;
}
- if (!(*fast_alter_partition))
+ if (!(*fast_alter_table))
{
- table->file->print_error(HA_ERR_WRONG_COMMAND, MYF(0));
- DBUG_RETURN(TRUE);
+ new_table->file->print_error(HA_ERR_WRONG_COMMAND, MYF(0));
+ goto err;
}
}
else if (alter_info->flags & ALTER_COALESCE_PARTITION)
@@ -4959,17 +4966,17 @@ that are reorganised.
if (tab_part_info->part_type != HASH_PARTITION)
{
my_error(ER_COALESCE_ONLY_ON_HASH_PARTITION, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
if (num_parts_coalesced == 0)
{
my_error(ER_COALESCE_PARTITION_NO_PARTITION, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
if (num_parts_coalesced >= tab_part_info->num_parts)
{
my_error(ER_DROP_LAST_PARTITION, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
/*
Online handling:
@@ -5008,7 +5015,7 @@ state of p1.
uint part_count= 0, start_part= 1, start_sec_part= 1;
uint end_part= 0, end_sec_part= 0;
bool all_parts= TRUE;
- if (*fast_alter_partition &&
+ if (*fast_alter_table &&
tab_part_info->linear_hash_ind)
{
uint upper_2n= tab_part_info->linear_hash_mask + 1;
@@ -5034,14 +5041,14 @@ state of p1.
do
{
partition_element *p_elem= part_it++;
- if (*fast_alter_partition &&
+ if (*fast_alter_table &&
(all_parts ||
(part_count >= start_part && part_count <= end_part) ||
(part_count >= start_sec_part && part_count <= end_sec_part)))
p_elem->part_state= PART_CHANGED;
if (++part_count > num_parts_remain)
{
- if (*fast_alter_partition)
+ if (*fast_alter_table)
p_elem->part_state= PART_REORGED_DROPPED;
else
part_it.remove();
@@ -5076,38 +5083,38 @@ state of p1.
if (num_parts_reorged > tab_part_info->num_parts)
{
my_error(ER_REORG_PARTITION_NOT_EXIST, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
if (!(tab_part_info->part_type == RANGE_PARTITION ||
tab_part_info->part_type == LIST_PARTITION) &&
(num_parts_new != num_parts_reorged))
{
my_error(ER_REORG_HASH_ONLY_ON_SAME_NO, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
if (tab_part_info->is_sub_partitioned() &&
alt_part_info->num_subparts &&
alt_part_info->num_subparts != tab_part_info->num_subparts)
{
my_error(ER_PARTITION_WRONG_NO_SUBPART_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
check_total_partitions= tab_part_info->num_parts + num_parts_new;
check_total_partitions-= num_parts_reorged;
if (check_total_partitions > MAX_PARTITIONS)
{
my_error(ER_TOO_MANY_PARTITIONS_ERROR, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
alt_part_info->part_type= tab_part_info->part_type;
alt_part_info->subpart_type= tab_part_info->subpart_type;
alt_part_info->num_subparts= tab_part_info->num_subparts;
DBUG_ASSERT(!alt_part_info->use_default_partitions);
- if (alt_part_info->set_up_defaults_for_partitioning(table->file,
+ if (alt_part_info->set_up_defaults_for_partitioning(new_table->file,
ULL(0),
0))
{
- DBUG_RETURN(TRUE);
+ goto err;
}
/*
Online handling:
@@ -5166,13 +5173,13 @@ the generated partition syntax in a correct manner.
}
else
tab_max_range= part_elem->range_value;
- if (*fast_alter_partition &&
+ if (*fast_alter_table &&
tab_part_info->temp_partitions.push_back(part_elem))
{
mem_alloc_error(1);
- DBUG_RETURN(TRUE);
+ goto err;
}
- if (*fast_alter_partition)
+ if (*fast_alter_table)
part_elem->part_state= PART_TO_BE_REORGED;
if (!found_first)
{
@@ -5192,7 +5199,7 @@ the generated partition syntax in a correct manner.
else
alt_max_range= alt_part_elem->range_value;
- if (*fast_alter_partition)
+ if (*fast_alter_table)
alt_part_elem->part_state= PART_TO_BE_ADDED;
if (alt_part_count == 0)
tab_it.replace(alt_part_elem);
@@ -5203,7 +5210,7 @@ the generated partition syntax in a correct manner.
else if (found_last)
{
my_error(ER_CONSECUTIVE_REORG_PARTITIONS, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
else
tab_it.remove();
@@ -5217,7 +5224,7 @@ the generated partition syntax in a correct manner.
if (drop_count != num_parts_reorged)
{
my_error(ER_DROP_PARTITION_NON_EXISTENT, MYF(0), "REORGANIZE");
- DBUG_RETURN(TRUE);
+ goto err;
}
tab_part_info->num_parts= check_total_partitions;
}
@@ -5238,9 +5245,9 @@ the generated partition syntax in a correct manner.
tab_part_info->use_default_num_subpartitions= FALSE;
}
if (tab_part_info->check_partition_info(thd, (handlerton**)NULL,
- table->file, ULL(0), TRUE))
+ new_table->file, ULL(0), TRUE))
{
- DBUG_RETURN(TRUE);
+ goto err;
}
/*
The check below needs to be performed after check_partition_info
@@ -5272,7 +5279,7 @@ the generated partition syntax in a correct manner.
to create "holes".
*/
my_error(ER_REORG_OUTSIDE_RANGE, MYF(0));
- DBUG_RETURN(TRUE);
+ goto err;
}
}
}
@@ -5389,7 +5396,7 @@ the generated partition syntax in a correct manner.
*partition_changed= TRUE;
if (thd->work_part_info->fix_parser_data(thd))
{
- DBUG_RETURN(TRUE);
+ goto err;
}
}
/*
@@ -5410,7 +5417,7 @@ the generated partition syntax in a correct manner.
if (check_native_partitioned(create_info, &is_native_partitioned,
part_info, thd))
{
- DBUG_RETURN(TRUE);
+ goto err;
}
if (!is_native_partitioned)
{
@@ -5420,6 +5427,17 @@ the generated partition syntax in a correct manner.
}
}
DBUG_RETURN(FALSE);
+err:
+ if (new_table)
+ {
+ /*
+ Only remove the intermediate table object and its share object,
+ do not remove the .frm file, since it is the original one.
+ */
+ close_temporary(new_table, 1, 0);
+ }
+ *fast_alter_table= NULL;
+ DBUG_RETURN(TRUE);
}
@@ -5462,6 +5480,11 @@ static bool mysql_change_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
if(mysql_trans_prepare_alter_copy_data(thd))
DBUG_RETURN(TRUE);
+ if (file->ha_external_lock(thd, F_WRLCK))
+ DBUG_RETURN(TRUE);
+
+ /* TODO: test if bulk_insert would increase the performance */
+
if ((error= file->ha_change_partitions(lpt->create_info, path, &lpt->copied,
&lpt->deleted, lpt->pack_frm_data,
lpt->pack_frm_len)))
@@ -5470,7 +5493,10 @@ static bool mysql_change_partitions(ALTER_PARTITION_PARAM_TYPE *lpt)
}
if (mysql_trans_commit_alter_copy_data(thd))
- DBUG_RETURN(TRUE); /* The error has been reported */
+ error= 1; /* The error has been reported */
+
+ if (file->ha_external_lock(thd, F_UNLCK))
+ error= 1;
DBUG_RETURN(test(error));
}
@@ -6220,8 +6246,18 @@ static void alter_partition_lock_handling(ALTER_PARTITION_PARAM_TYPE *lpt)
{
THD *thd= lpt->thd;
- close_all_tables_for_name(thd, lpt->table->s, FALSE);
+ if (lpt->old_table)
+ close_all_tables_for_name(thd, lpt->old_table->s, FALSE);
+ if (lpt->table)
+ {
+ /*
+ Only remove the intermediate table object and its share object,
+ do not remove the .frm file, since it is the original one.
+ */
+ close_temporary(lpt->table, 1, 0);
+ }
lpt->table= 0;
+ lpt->old_table= 0;
lpt->table_list->table= 0;
if (thd->locked_tables_list.reopen_tables(thd))
sql_print_warning("We failed to reacquire LOCKs in ALTER TABLE");
@@ -6233,62 +6269,40 @@ static void alter_partition_lock_handling(ALTER_PARTITION_PARAM_TYPE *lpt)
SYNOPSIS
alter_close_tables()
lpt Struct carrying parameters
+ close_old Close original table too
RETURN VALUES
0
*/
-static int alter_close_tables(ALTER_PARTITION_PARAM_TYPE *lpt)
+static int alter_close_tables(ALTER_PARTITION_PARAM_TYPE *lpt, bool close_old)
{
- TABLE_SHARE *share= lpt->table->s;
- THD *thd= lpt->thd;
- TABLE *table;
DBUG_ENTER("alter_close_tables");
- /*
- We must keep LOCK_open while manipulating with thd->open_tables.
- Another thread may be working on it.
- */
- mysql_mutex_lock(&LOCK_open);
- /*
- We can safely remove locks for all tables with the same name:
- later they will all be closed anyway in
- alter_partition_lock_handling().
- */
- for (table= thd->open_tables; table ; table= table->next)
+ if (lpt->table->db_stat)
{
- if (!strcmp(table->s->table_name.str, share->table_name.str) &&
- !strcmp(table->s->db.str, share->db.str))
- {
- mysql_lock_remove(thd, thd->lock, table);
- table->file->close();
- table->db_stat= 0; // Mark file closed
- /*
- Ensure that we won't end up with a crippled table instance
- in the table cache if an error occurs before we reach
- alter_partition_lock_handling() and the table is closed
- by close_thread_tables() instead.
- */
- tdc_remove_table(thd, TDC_RT_REMOVE_UNUSED,
- table->s->db.str,
- table->s->table_name.str, TRUE);
- }
+ lpt->table->file->close();
+ lpt->table->db_stat= 0; // Mark file closed
+ }
+ if (close_old && lpt->old_table)
+ {
+ close_all_tables_for_name(lpt->thd, lpt->old_table->s, FALSE);
+ lpt->old_table= 0;
}
- mysql_mutex_unlock(&LOCK_open);
DBUG_RETURN(0);
}
-/*
- Handle errors for ALTER TABLE for partitioning
- SYNOPSIS
- handle_alter_part_error()
- lpt Struct carrying parameters
- not_completed Was request in complete phase when error occurred
- RETURN VALUES
- NONE
+/**
+ Handle errors for ALTER TABLE for partitioning.
+
+ @param lpt Struct carrying parameters
+ @param action_completed The action must be completed, NOT reverted
+ @param drop_partition Partitions has not been dropped yet
+ @param frm_install The shadow frm-file has not yet been installed
+ @param close_table Table is still open, close it before reverting
*/
void handle_alter_part_error(ALTER_PARTITION_PARAM_TYPE *lpt,
- bool not_completed,
+ bool action_completed,
bool drop_partition,
bool frm_install,
bool close_table)
@@ -6305,7 +6319,7 @@ void handle_alter_part_error(ALTER_PARTITION_PARAM_TYPE *lpt,
so we clone it first to have a copy.
*/
part_info= lpt->part_info->get_clone();
- alter_close_tables(lpt);
+ alter_close_tables(lpt, action_completed);
}
if (part_info->first_log_entry &&
@@ -6318,7 +6332,7 @@ void handle_alter_part_error(ALTER_PARTITION_PARAM_TYPE *lpt,
*/
write_log_completed(lpt, FALSE);
release_log_entries(part_info);
- if (not_completed)
+ if (!action_completed)
{
if (drop_partition)
{
@@ -6383,7 +6397,7 @@ void handle_alter_part_error(ALTER_PARTITION_PARAM_TYPE *lpt,
else
{
release_log_entries(part_info);
- if (not_completed)
+ if (!action_completed)
{
/*
We hit an error before things were completed but managed
@@ -6426,25 +6440,24 @@ static void downgrade_mdl_if_lock_tables_mode(THD *thd, MDL_ticket *ticket,
}
-/*
+/**
Actually perform the change requested by ALTER TABLE of partitions
previously prepared.
- SYNOPSIS
- fast_alter_partition_table()
- thd Thread object
- table Table object
- alter_info ALTER TABLE info
- create_info Create info for CREATE TABLE
- table_list List of the table involved
- db Database name of new table
- table_name Table name of new table
+ @param thd Thread object
+ @param table Original table object
+ @param alter_info ALTER TABLE info
+ @param create_info Create info for CREATE TABLE
+ @param table_list List of the table involved
+ @param db Database name of new table
+ @param table_name Table name of new table
+ @param fast_alter_table Prepared table object
- RETURN VALUES
- TRUE Error
- FALSE Success
+ @return Operation status
+ @retval TRUE Error
+ @retval FALSE Success
- DESCRIPTION
+ @note
Perform all ALTER TABLE operations for partitioned tables that can be
performed fast without a full copy of the original table.
*/
@@ -6455,19 +6468,20 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
TABLE_LIST *table_list,
char *db,
const char *table_name,
- uint fast_alter_partition)
+ TABLE *fast_alter_table)
{
/* Set-up struct used to write frm files */
- partition_info *part_info= table->part_info;
+ partition_info *part_info;
ALTER_PARTITION_PARAM_TYPE lpt_obj;
ALTER_PARTITION_PARAM_TYPE *lpt= &lpt_obj;
- bool written_bin_log= TRUE;
- bool not_completed= TRUE;
+ bool action_completed= FALSE;
bool close_table_on_failure= FALSE;
bool frm_install= FALSE;
MDL_ticket *mdl_ticket= table->mdl_ticket;
+ DBUG_ASSERT(fast_alter_table);
DBUG_ENTER("fast_alter_partition_table");
+ part_info= fast_alter_table->part_info;
lpt->thd= thd;
lpt->table_list= table_list;
lpt->part_info= part_info;
@@ -6476,7 +6490,8 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
lpt->db_options= create_info->table_options;
if (create_info->row_type == ROW_TYPE_DYNAMIC)
lpt->db_options|= HA_OPTION_PACK_RECORD;
- lpt->table= table;
+ lpt->table= fast_alter_table;
+ lpt->old_table= table;
lpt->key_info_buffer= 0;
lpt->key_count= 0;
lpt->db= db;
@@ -6485,12 +6500,12 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
lpt->deleted= 0;
lpt->pack_frm_data= NULL;
lpt->pack_frm_len= 0;
- thd->work_part_info= part_info;
/* Never update timestamp columns when alter */
- table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
+ lpt->table->timestamp_field_type= TIMESTAMP_NO_AUTO_SET;
- if (fast_alter_partition & HA_PARTITION_ONE_PHASE)
+ if (table->file->alter_table_flags(alter_info->flags) &
+ HA_PARTITION_ONE_PHASE)
{
/*
In the case where the engine supports one phase online partition
@@ -6607,11 +6622,11 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
ERROR_INJECT_ERROR("fail_drop_partition_3") ||
(close_table_on_failure= TRUE, FALSE) ||
write_log_drop_partition(lpt) ||
+ (action_completed= TRUE, FALSE) ||
ERROR_INJECT_CRASH("crash_drop_partition_4") ||
ERROR_INJECT_ERROR("fail_drop_partition_4") ||
+ alter_close_tables(lpt, action_completed) ||
(close_table_on_failure= FALSE, FALSE) ||
- (not_completed= FALSE, FALSE) ||
- alter_close_tables(lpt) ||
ERROR_INJECT_CRASH("crash_drop_partition_5") ||
ERROR_INJECT_ERROR("fail_drop_partition_5") ||
((!thd->lex->no_write_to_binlog) &&
@@ -6632,7 +6647,7 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
ERROR_INJECT_ERROR("fail_drop_partition_9") ||
(alter_partition_lock_handling(lpt), FALSE))
{
- handle_alter_part_error(lpt, not_completed, TRUE, frm_install,
+ handle_alter_part_error(lpt, action_completed, TRUE, frm_install,
close_table_on_failure);
goto err;
}
@@ -6687,7 +6702,7 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
ERROR_INJECT_CRASH("crash_add_partition_5") ||
ERROR_INJECT_ERROR("fail_add_partition_5") ||
(close_table_on_failure= FALSE, FALSE) ||
- alter_close_tables(lpt) ||
+ alter_close_tables(lpt, action_completed) ||
ERROR_INJECT_CRASH("crash_add_partition_6") ||
ERROR_INJECT_ERROR("fail_add_partition_6") ||
((!thd->lex->no_write_to_binlog) &&
@@ -6696,11 +6711,12 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
ERROR_INJECT_CRASH("crash_add_partition_7") ||
ERROR_INJECT_ERROR("fail_add_partition_7") ||
write_log_rename_frm(lpt) ||
- (frm_install= TRUE, FALSE) ||
- (not_completed= FALSE, FALSE) ||
+ (action_completed= TRUE, FALSE) ||
ERROR_INJECT_CRASH("crash_add_partition_8") ||
ERROR_INJECT_ERROR("fail_add_partition_8") ||
+ (frm_install= TRUE, FALSE) ||
mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
+ (frm_install= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_add_partition_9") ||
ERROR_INJECT_ERROR("fail_add_partition_9") ||
(write_log_completed(lpt, FALSE), FALSE) ||
@@ -6708,7 +6724,7 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
ERROR_INJECT_ERROR("fail_add_partition_10") ||
(alter_partition_lock_handling(lpt), FALSE))
{
- handle_alter_part_error(lpt, not_completed, FALSE, frm_install,
+ handle_alter_part_error(lpt, action_completed, FALSE, frm_install,
close_table_on_failure);
goto err;
}
@@ -6757,10 +6773,10 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
can release all other locks on the table and since no one can open
the table, there can be no new threads accessing the table. They
will be hanging on this exclusive lock.
- 5) Close all instances of the table and remove them from the table cache.
- 6) Log that operation is completed and log all complete actions
+ 5) Log that operation is completed and log all complete actions
needed to complete operation from here
- 7) Write bin log
+ 6) Write bin log
+ 7) Close all instances of the table and remove them from the table cache.
8) Prepare handlers for rename and delete of partitions
9) Rename and drop the reorged partitions such that they are no
longer used and rename those added to their real new names.
@@ -6784,27 +6800,28 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN) ||
ERROR_INJECT_CRASH("crash_change_partition_5") ||
ERROR_INJECT_ERROR("fail_change_partition_5") ||
- alter_close_tables(lpt) ||
- (close_table_on_failure= FALSE) ||
+ write_log_final_change_partition(lpt) ||
+ (action_completed= TRUE, FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_6") ||
ERROR_INJECT_ERROR("fail_change_partition_6") ||
- write_log_final_change_partition(lpt) ||
- (not_completed= FALSE) ||
- ERROR_INJECT_CRASH("crash_change_partition_7") ||
- ERROR_INJECT_ERROR("fail_change_partition_7") ||
((!thd->lex->no_write_to_binlog) &&
(write_bin_log(thd, FALSE,
thd->query(), thd->query_length()), FALSE)) ||
+ ERROR_INJECT_CRASH("crash_change_partition_7") ||
+ ERROR_INJECT_ERROR("fail_change_partition_7") ||
+ ((frm_install= TRUE), FALSE) ||
+ mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
+ (frm_install= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_8") ||
ERROR_INJECT_ERROR("fail_change_partition_8") ||
- mysql_write_frm(lpt, WFRM_INSTALL_SHADOW) ||
+ alter_close_tables(lpt, action_completed) ||
+ (close_table_on_failure= FALSE, FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_9") ||
ERROR_INJECT_ERROR("fail_change_partition_9") ||
mysql_drop_partitions(lpt) ||
ERROR_INJECT_CRASH("crash_change_partition_10") ||
ERROR_INJECT_ERROR("fail_change_partition_10") ||
mysql_rename_partitions(lpt) ||
- ((frm_install= TRUE), FALSE) ||
ERROR_INJECT_CRASH("crash_change_partition_11") ||
ERROR_INJECT_ERROR("fail_change_partition_11") ||
(write_log_completed(lpt, FALSE), FALSE) ||
@@ -6812,7 +6829,7 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
ERROR_INJECT_ERROR("fail_change_partition_12") ||
(alter_partition_lock_handling(lpt), FALSE))
{
- handle_alter_part_error(lpt, not_completed, FALSE, frm_install,
+ handle_alter_part_error(lpt, action_completed, FALSE, frm_install,
close_table_on_failure);
goto err;
}
@@ -6822,12 +6839,25 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
A final step is to write the query to the binlog and send ok to the
user
*/
- DBUG_RETURN(fast_end_partition(thd, lpt->copied, lpt->deleted,
- table_list, FALSE, NULL,
- written_bin_log));
+ DBUG_RETURN(fast_end_partition(thd, lpt->copied, lpt->deleted, table_list));
err:
+ if (action_completed)
+ {
+ /*
+ Although error occurred, the action was forced to retry for completion.
+ Therefore we must close+reopen all instances of the table.
+ */
+ (void) alter_partition_lock_handling(lpt);
+ }
+ else
+ {
+ /*
+ The failed action was reverted, leave the original table as is and
+ close/destroy the intermediate table object and its share.
+ */
+ close_temporary(lpt->table, 1, 0);
+ }
downgrade_mdl_if_lock_tables_mode(thd, mdl_ticket, MDL_SHARED_NO_READ_WRITE);
- table->m_needs_reopen= TRUE;
DBUG_RETURN(TRUE);
}
#endif
@@ -6920,7 +6950,7 @@ void set_key_field_ptr(KEY *key_info, const uchar *new_buf,
void mem_alloc_error(size_t size)
{
- my_error(ER_OUTOFMEMORY, MYF(0), size);
+ my_error(ER_OUTOFMEMORY, MYF(0), static_cast<int>(size));
}
#ifdef WITH_PARTITION_STORAGE_ENGINE
@@ -7381,8 +7411,8 @@ int get_part_iter_for_interval_via_mapping(partition_info *part_info,
PARTITION_ITERATOR *part_iter)
{
Field *field= part_info->part_field_array[0];
- uint32 max_endpoint_val;
- get_endpoint_func get_endpoint;
+ uint32 UNINIT_VAR(max_endpoint_val);
+ get_endpoint_func UNINIT_VAR(get_endpoint);
bool can_match_multiple_values; /* is not '=' */
uint field_len= field->pack_length_in_rec();
DBUG_ENTER("get_part_iter_for_interval_via_mapping");
@@ -7425,8 +7455,8 @@ int get_part_iter_for_interval_via_mapping(partition_info *part_info,
}
}
else
- assert(0);
-
+ MY_ASSERT_UNREACHABLE();
+
can_match_multiple_values= (flags || !min_value || !max_value ||
memcmp(min_value, max_value, field_len));
if (can_match_multiple_values &&
diff --git a/sql/sql_partition.h b/sql/sql_partition.h
index c644e63794c..9a9a0bd56fa 100644
--- a/sql/sql_partition.h
+++ b/sql/sql_partition.h
@@ -54,6 +54,7 @@ typedef struct st_lock_param_type
HA_CREATE_INFO *create_info;
Alter_info *alter_info;
TABLE *table;
+ TABLE *old_table;
KEY *key_info_buffer;
const char *db;
const char *table_name;
@@ -252,14 +253,17 @@ uint fast_alter_partition_table(THD *thd, TABLE *table,
TABLE_LIST *table_list,
char *db,
const char *table_name,
- uint fast_alter_partition);
+ TABLE *fast_alter_table);
uint set_part_state(Alter_info *alter_info, partition_info *tab_part_info,
enum partition_state part_state);
uint prep_alter_part_table(THD *thd, TABLE *table, Alter_info *alter_info,
HA_CREATE_INFO *create_info,
handlerton *old_db_type,
bool *partition_changed,
- uint *fast_alter_partition);
+ char *db,
+ const char *table_name,
+ const char *path,
+ TABLE **fast_alter_table);
char *generate_partition_syntax(partition_info *part_info,
uint *buf_length, bool use_sql_alloc,
bool show_partition_options,
diff --git a/sql/sql_partition_admin.cc b/sql/sql_partition_admin.cc
index 795760c855c..cadfc587c1c 100644
--- a/sql/sql_partition_admin.cc
+++ b/sql/sql_partition_admin.cc
@@ -15,10 +15,13 @@
#include "sql_parse.h" // check_one_table_access
#include "sql_table.h" // mysql_alter_table, etc.
-#include "sql_truncate.h" // mysql_truncate_table,
- // Truncate_statement
+#include "sql_lex.h" // Sql_statement
#include "sql_admin.h" // Analyze/Check/.._table_statement
#include "sql_partition_admin.h" // Alter_table_*_partition
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+#include "ha_partition.h" // ha_partition
+#endif
+#include "sql_base.h" // open_and_lock_tables
#ifndef WITH_PARTITION_STORAGE_ENGINE
@@ -45,7 +48,7 @@ bool Alter_table_analyze_partition_statement::execute(THD *thd)
m_lex->alter_info.flags|= ALTER_ADMIN_PARTITION;
res= Analyze_table_statement::execute(thd);
-
+
DBUG_RETURN(res);
}
@@ -103,36 +106,88 @@ bool Alter_table_repair_partition_statement::execute(THD *thd)
bool Alter_table_truncate_partition_statement::execute(THD *thd)
{
+ int error;
+ ha_partition *partition;
+ ulong timeout= thd->variables.lock_wait_timeout;
TABLE_LIST *first_table= thd->lex->select_lex.table_list.first;
- bool res;
- enum_sql_command original_sql_command;
+ bool binlog_stmt;
DBUG_ENTER("Alter_table_truncate_partition_statement::execute");
/*
- Execute TRUNCATE PARTITION just like TRUNCATE TABLE.
- Some storage engines (InnoDB, partition) checks thd_sql_command,
- so we set it to SQLCOM_TRUNCATE during the execution.
- */
- original_sql_command= m_lex->sql_command;
- m_lex->sql_command= SQLCOM_TRUNCATE;
-
- /*
Flag that it is an ALTER command which administrates partitions, used
by ha_partition.
*/
- m_lex->alter_info.flags|= ALTER_ADMIN_PARTITION;
-
+ m_lex->alter_info.flags|= ALTER_ADMIN_PARTITION |
+ ALTER_TRUNCATE_PARTITION;
+
+ /* Fix the lock types (not the same as ordinary ALTER TABLE). */
+ first_table->lock_type= TL_WRITE;
+ first_table->mdl_request.set_type(MDL_EXCLUSIVE);
+
/*
- Fix the lock types (not the same as ordinary ALTER TABLE).
+ Check table permissions and open it with a exclusive lock.
+ Ensure it is a partitioned table and finally, upcast the
+ handler and invoke the partition truncate method. Lastly,
+ write the statement to the binary log if necessary.
*/
- first_table->lock_type= TL_WRITE;
- first_table->mdl_request.set_type(MDL_SHARED_NO_READ_WRITE);
- /* execute as a TRUNCATE TABLE */
- res= Truncate_statement::execute(thd);
+ if (check_one_table_access(thd, DROP_ACL, first_table))
+ DBUG_RETURN(TRUE);
- m_lex->sql_command= original_sql_command;
- DBUG_RETURN(res);
+ if (open_and_lock_tables(thd, first_table, FALSE, 0))
+ DBUG_RETURN(TRUE);
+
+ /*
+ TODO: Add support for TRUNCATE PARTITION for NDB and other
+ engines supporting native partitioning.
+ */
+ if (first_table->table->s->db_type() != partition_hton)
+ {
+ my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));
+ DBUG_RETURN(TRUE);
+ }
+
+ /*
+ Under locked table modes this might still not be an exclusive
+ lock. Hence, upgrade the lock since the handler truncate method
+ mandates an exclusive metadata lock.
+ */
+ MDL_ticket *ticket= first_table->table->mdl_ticket;
+ if (thd->mdl_context.upgrade_shared_lock_to_exclusive(ticket, timeout))
+ DBUG_RETURN(TRUE);
+
+ tdc_remove_table(thd, TDC_RT_REMOVE_NOT_OWN, first_table->db,
+ first_table->table_name, FALSE);
+
+ partition= (ha_partition *) first_table->table->file;
+
+ /* Invoke the handler method responsible for truncating the partition. */
+ if ((error= partition->truncate_partition(&thd->lex->alter_info,
+ &binlog_stmt)))
+ first_table->table->file->print_error(error, MYF(0));
+
+ /*
+ All effects of a truncate operation are committed even if the
+ operation fails. Thus, the query must be written to the binary
+ log. The exception is a unimplemented truncate method or failure
+ before any call to handler::truncate() is done.
+ Also, it is logged in statement format, regardless of the binlog format.
+ */
+ if (error != HA_ERR_WRONG_COMMAND && binlog_stmt)
+ error|= write_bin_log(thd, !error, thd->query(), thd->query_length());
+
+ /*
+ A locked table ticket was upgraded to a exclusive lock. After the
+ the query has been written to the binary log, downgrade the lock
+ to a shared one.
+ */
+ if (thd->locked_tables_mode)
+ ticket->downgrade_exclusive_lock(MDL_SHARED_NO_READ_WRITE);
+
+ if (! error)
+ my_ok(thd);
+
+ DBUG_RETURN(error);
}
#endif /* WITH_PARTITION_STORAGE_ENGINE */
diff --git a/sql/sql_partition_admin.h b/sql/sql_partition_admin.h
index 36bafec4202..564b8676be8 100644
--- a/sql/sql_partition_admin.h
+++ b/sql/sql_partition_admin.h
@@ -210,7 +210,7 @@ public:
/**
Class that represents the ALTER TABLE t1 TRUNCATE PARTITION p statement.
*/
-class Alter_table_truncate_partition_statement : public Truncate_statement
+class Alter_table_truncate_partition_statement : public Sql_statement
{
public:
/**
@@ -218,10 +218,10 @@ public:
@param lex the LEX structure for this statement.
*/
Alter_table_truncate_partition_statement(LEX *lex)
- : Truncate_statement(lex)
+ : Sql_statement(lex)
{}
- ~Alter_table_truncate_partition_statement()
+ virtual ~Alter_table_truncate_partition_statement()
{}
/**
diff --git a/sql/sql_plist.h b/sql/sql_plist.h
index db85266be15..b71136cd9ab 100644
--- a/sql/sql_plist.h
+++ b/sql/sql_plist.h
@@ -95,6 +95,7 @@ public:
*last= a;
*B::prev_ptr(a)= last;
I::set_last(B::next_ptr(a));
+ C::inc();
}
inline void insert_after(T *pos, T *a)
{
@@ -112,6 +113,7 @@ public:
}
else
I::set_last(B::next_ptr(a));
+ C::inc();
}
}
inline void remove(T *a)
@@ -188,6 +190,20 @@ public:
/**
+ Hook class which via its methods specifies which members
+ of T should be used for participating in a intrusive list.
+*/
+
+template <typename T, T* T::*next, T** T::*prev>
+struct I_P_List_adapter
+{
+ static inline T **next_ptr(T *el) { return &(el->*next); }
+
+ static inline T ***prev_ptr(T *el) { return &(el->*prev); }
+};
+
+
+/**
Element counting policy class for I_P_List to be used in
cases when no element counting should be done.
*/
diff --git a/sql/sql_plugin.cc b/sql/sql_plugin.cc
index 066a7512eaf..d36654c4c18 100644
--- a/sql/sql_plugin.cc
+++ b/sql/sql_plugin.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2005 MySQL AB, 2009 Sun Microsystems, Inc.
+/* Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,7 +11,7 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
#include "sql_priv.h" // SHOW_MY_BOOL
#include "unireg.h"
@@ -30,6 +30,7 @@
#include <my_pthread.h>
#include <my_getopt.h>
#include "sql_audit.h"
+#include <mysql/plugin_auth.h>
#include "lock.h" // MYSQL_LOCK_IGNORE_TIMEOUT
#include <mysql/plugin_auth.h>
#define REPORT_TO_LOG 1
@@ -42,9 +43,8 @@ extern struct st_maria_plugin *mysql_mandatory_plugins[];
@note The order of the enumeration is critical.
@see construct_options
*/
-static const char *global_plugin_typelib_names[]=
- { "OFF", "ON", "FORCE", NULL };
-enum enum_plugin_load_policy {PLUGIN_OFF, PLUGIN_ON, PLUGIN_FORCE};
+const char *global_plugin_typelib_names[]=
+ { "OFF", "ON", "FORCE", "FORCE_PLUS_PERMANENT", NULL };
static TYPELIB global_plugin_typelib=
{ array_elements(global_plugin_typelib_names)-1,
"", global_plugin_typelib_names, NULL };
@@ -301,6 +301,26 @@ static void report_error(int where_to, uint error, ...)
}
}
+/**
+ Check if the provided path is valid in the sense that it does cause
+ a relative reference outside the directory.
+
+ @note Currently, this function only check if there are any
+ characters in FN_DIRSEP in the string, but it might change in the
+ future.
+
+ @code
+ check_valid_path("../foo.so") -> true
+ check_valid_path("foo.so") -> false
+ @endcode
+ */
+bool check_valid_path(const char *path, size_t len)
+{
+ size_t prefix= my_strcspn(files_charset_info, path, path + len, FN_DIRSEP);
+ return prefix < len;
+}
+
+
/****************************************************************************
Value type thunks, allows the C world to play in the C++ world
****************************************************************************/
@@ -492,7 +512,8 @@ static my_bool read_mysql_plugin_info(struct st_plugin_dl *plugin_dl,
if (!cur)
{
free_plugin_mem(plugin_dl);
- report_error(report, ER_OUTOFMEMORY, plugin_dl->dl.length);
+ report_error(report, ER_OUTOFMEMORY,
+ static_cast<int>(plugin_dl.dl.length));
DBUG_RETURN(TRUE);
}
/*
@@ -617,7 +638,8 @@ static my_bool read_maria_plugin_info(struct st_plugin_dl *plugin_dl,
if (!cur)
{
free_plugin_mem(plugin_dl);
- report_error(report, ER_OUTOFMEMORY, plugin_dl->dl.length);
+ report_error(report, ER_OUTOFMEMORY,
+ static_cast<int>(plugin_dl.dl.length));
DBUG_RETURN(TRUE);
}
/*
@@ -648,13 +670,15 @@ static st_plugin_dl *plugin_dl_add(const LEX_STRING *dl, int report)
struct st_plugin_dl *tmp, plugin_dl;
void *sym;
DBUG_ENTER("plugin_dl_add");
+ DBUG_PRINT("enter", ("dl->str: '%s', dl->length: %d",
+ dl->str, (int) dl->length));
plugin_dir_len= strlen(opt_plugin_dir);
/*
Ensure that the dll doesn't have a path.
This is done to ensure that only approved libraries from the
plugin directory are used (to make this even remotely secure).
*/
- if (my_strchr(files_charset_info, dl->str, dl->str + dl->length, FN_LIBCHAR) ||
+ if (check_valid_path(dl->str, dl->length) ||
check_string_char_length((LEX_STRING *) dl, "", NAME_CHAR_LEN,
system_charset_info, 1) ||
plugin_dir_len + dl->length + 1 >= FN_REFLEN)
@@ -729,7 +753,8 @@ static st_plugin_dl *plugin_dl_add(const LEX_STRING *dl, int report)
if (! (plugin_dl.dl.str= (char*) my_malloc(plugin_dl.dl.length, MYF(0))))
{
free_plugin_mem(&plugin_dl);
- report_error(report, ER_OUTOFMEMORY, plugin_dl.dl.length);
+ report_error(report, ER_OUTOFMEMORY,
+ static_cast<int>(plugin_dl.dl.length));
DBUG_RETURN(0);
}
plugin_dl.dl.length= copy_and_convert(plugin_dl.dl.str, plugin_dl.dl.length,
@@ -740,7 +765,8 @@ static st_plugin_dl *plugin_dl_add(const LEX_STRING *dl, int report)
if (! (tmp= plugin_dl_insert_or_reuse(&plugin_dl)))
{
free_plugin_mem(&plugin_dl);
- report_error(report, ER_OUTOFMEMORY, sizeof(struct st_plugin_dl));
+ report_error(report, ER_OUTOFMEMORY,
+ static_cast<int>(sizeof(struct st_plugin_dl)));
DBUG_RETURN(0);
}
DBUG_RETURN(tmp);
@@ -1014,6 +1040,7 @@ static bool plugin_add(MEM_ROOT *tmp_root,
tmp.name.length= name_len;
tmp.ref_count= 0;
tmp.state= PLUGIN_IS_UNINITIALIZED;
+ tmp.load_option= PLUGIN_ON;
if (test_plugin_options(tmp_root, &tmp, argc, argv))
tmp.state= PLUGIN_IS_DISABLED;
@@ -1460,7 +1487,7 @@ int plugin_init(int *argc, char **argv, int flags)
tmp.name.str= (char *)plugin->name;
tmp.name.length= strlen(plugin->name);
tmp.state= 0;
- tmp.is_mandatory= mandatory;
+ tmp.load_option= mandatory ? PLUGIN_FORCE : PLUGIN_ON;
/*
If the performance schema is compiled in,
@@ -1479,7 +1506,7 @@ int plugin_init(int *argc, char **argv, int flags)
to work, by using '--skip-performance-schema' (the plugin)
*/
if (!my_strcasecmp(&my_charset_latin1, plugin->name, "PERFORMANCE_SCHEMA"))
- tmp.is_mandatory= true;
+ tmp.load_option= PLUGIN_FORCE;
free_root(&tmp_root, MYF(MY_MARK_BLOCKS_FREE));
if (test_plugin_options(&tmp_root, &tmp, argc, argv))
@@ -1557,7 +1584,8 @@ int plugin_init(int *argc, char **argv, int flags)
while ((plugin_ptr= *(--reap)))
{
mysql_mutex_unlock(&LOCK_plugin);
- if (plugin_ptr->is_mandatory)
+ if (plugin_ptr->load_option == PLUGIN_FORCE ||
+ plugin_ptr->load_option == PLUGIN_FORCE_PLUS_PERMANENT)
reaped_mandatory_plugin= TRUE;
plugin_deinitialize(plugin_ptr, true);
mysql_mutex_lock(&LOCK_plugin);
@@ -1961,7 +1989,11 @@ bool mysql_install_plugin(THD *thd, const LEX_STRING *name, const LEX_STRING *dl
mysql_mutex_lock(&LOCK_plugin);
mysql_rwlock_wrlock(&LOCK_system_variables_hash);
- my_load_defaults(MYSQL_CONFIG_NAME, load_default_groups, &argc, &argv, NULL);
+ if (my_load_defaults(MYSQL_CONFIG_NAME, load_default_groups, &argc, &argv, NULL))
+ {
+ report_error(REPORT_TO_USER, ER_PLUGIN_IS_NOT_LOADED, name->str);
+ goto err;
+ }
error= plugin_add(thd->mem_root, name, dl, &argc, argv, REPORT_TO_USER);
if (argv)
free_defaults(argv);
@@ -2073,6 +2105,11 @@ bool mysql_uninstall_plugin(THD *thd, const LEX_STRING *name)
my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PLUGIN", name->str);
goto err;
}
+ if (plugin->load_option == PLUGIN_FORCE_PLUS_PERMANENT)
+ {
+ my_error(ER_PLUGIN_IS_PERMANENT, MYF(0), name->str);
+ goto err;
+ }
plugin->state= PLUGIN_IS_DELETED;
if (plugin->ref_count)
@@ -3283,7 +3320,8 @@ static int construct_options(MEM_ROOT *mem_root, struct st_plugin_int *tmp,
plugin_dash.length + 1);
strxmov(plugin_name_with_prefix_ptr, plugin_dash.str, plugin_name_ptr, NullS);
- if (!tmp->is_mandatory)
+ if (tmp->load_option != PLUGIN_FORCE &&
+ tmp->load_option != PLUGIN_FORCE_PLUS_PERMANENT)
{
/* support --skip-plugin-foo syntax */
options[0].name= plugin_name_ptr;
@@ -3543,7 +3581,8 @@ static int test_plugin_options(MEM_ROOT *tmp_root, struct st_plugin_int *tmp,
{
struct sys_var_chain chain= { NULL, NULL };
bool disable_plugin;
- enum_plugin_load_policy plugin_load_policy= tmp->is_mandatory ? PLUGIN_FORCE : PLUGIN_ON;
+ enum_plugin_load_option plugin_load_option= tmp->load_option;
+
MEM_ROOT *mem_root= alloc_root_inited(&tmp->mem_root) ?
&tmp->mem_root : &plugin_mem_root;
st_mysql_sys_var **opt;
@@ -3557,13 +3596,11 @@ static int test_plugin_options(MEM_ROOT *tmp_root, struct st_plugin_int *tmp,
DBUG_ENTER("test_plugin_options");
DBUG_ASSERT(tmp->plugin && tmp->name.str);
-#ifdef WITH_NDBCLUSTER_STORAGE_ENGINE
/*
The 'ndbcluster' storage engines is always disabled by default.
*/
if (!my_strcasecmp(&my_charset_latin1, tmp->name.str, "ndbcluster"))
- plugin_load_policy= PLUGIN_OFF;
-#endif
+ plugin_load_option= PLUGIN_OFF;
for (opt= tmp->plugin->system_vars; opt && *opt; opt++)
count+= 2; /* --{plugin}-{optname} and --plugin-{plugin}-{optname} */
@@ -3587,8 +3624,9 @@ static int test_plugin_options(MEM_ROOT *tmp_root, struct st_plugin_int *tmp,
We adjust the default value to account for the hardcoded exceptions
we have set for the federated and ndbcluster storage engines.
*/
- if (!tmp->is_mandatory)
- opts[0].def_value= opts[1].def_value= plugin_load_policy;
+ if (tmp->load_option != PLUGIN_FORCE &&
+ tmp->load_option != PLUGIN_FORCE_PLUS_PERMANENT)
+ opts[0].def_value= opts[1].def_value= plugin_load_option;
error= handle_options(argc, &argv, opts, NULL);
(*argc)++; /* add back one for the program name */
@@ -3603,12 +3641,13 @@ static int test_plugin_options(MEM_ROOT *tmp_root, struct st_plugin_int *tmp,
Set plugin loading policy from option value. First element in the option
list is always the <plugin name> option value.
*/
- if (!tmp->is_mandatory)
- plugin_load_policy= (enum_plugin_load_policy)*(ulong*)opts[0].value;
+ if (tmp->load_option != PLUGIN_FORCE &&
+ tmp->load_option != PLUGIN_FORCE_PLUS_PERMANENT)
+ plugin_load_option= (enum_plugin_load_option) *(ulong*) opts[0].value;
}
- disable_plugin= (plugin_load_policy == PLUGIN_OFF);
- tmp->is_mandatory= (plugin_load_policy == PLUGIN_FORCE);
+ disable_plugin= (plugin_load_option == PLUGIN_OFF);
+ tmp->load_option= plugin_load_option;
/*
If the plugin is disabled it should not be initialized.
diff --git a/sql/sql_plugin.h b/sql/sql_plugin.h
index 478bc787d40..ee1d43e8a2f 100644
--- a/sql/sql_plugin.h
+++ b/sql/sql_plugin.h
@@ -16,6 +16,8 @@
#ifndef _sql_plugin_h
#define _sql_plugin_h
+#include <my_global.h>
+
/*
the following #define adds server-only members to enum_mysql_show_type,
that is defined in plugin.h
@@ -32,6 +34,9 @@
class sys_var;
enum SHOW_COMP_OPTION { SHOW_OPTION_YES, SHOW_OPTION_NO, SHOW_OPTION_DISABLED};
+enum enum_plugin_load_option { PLUGIN_OFF, PLUGIN_ON, PLUGIN_FORCE,
+ PLUGIN_FORCE_PLUS_PERMANENT };
+extern const char *global_plugin_typelib_names[];
#include <my_sys.h>
@@ -96,7 +101,7 @@ struct st_plugin_int
void *data; /* plugin type specific, e.g. handlerton */
MEM_ROOT mem_root; /* memory for dynamic plugin structures */
sys_var *system_vars; /* server variables for this plugin */
- bool is_mandatory; /* If true then plugin must not fail to load */
+ enum enum_plugin_load_option load_option; /* OFF, ON, FORCE, F+PERMANENT */
};
@@ -113,6 +118,7 @@ typedef struct st_plugin_int *plugin_ref;
#define plugin_data(pi,cast) ((cast)((pi)->data))
#define plugin_name(pi) (&((pi)->name))
#define plugin_state(pi) ((pi)->state)
+#define plugin_load_option(pi) ((pi)->load_option)
#define plugin_equals(p1,p2) ((p1) == (p2))
#else
typedef struct st_plugin_int **plugin_ref;
@@ -123,6 +129,7 @@ typedef struct st_plugin_int **plugin_ref;
#define plugin_data(pi,cast) ((cast)((pi)[0]->data))
#define plugin_name(pi) (&((pi)[0]->name))
#define plugin_state(pi) ((pi)[0]->state)
+#define plugin_load_option(pi) ((pi)[0]->load_option)
#define plugin_equals(p1,p2) ((p1) && (p2) && (p1)[0] == (p2)[0])
#endif
@@ -156,6 +163,7 @@ extern bool plugin_register_builtin(struct st_mysql_plugin *plugin);
extern void plugin_thdvar_init(THD *thd);
extern void plugin_thdvar_cleanup(THD *thd);
extern SHOW_COMP_OPTION plugin_status(const char *name, int len, size_t type);
+extern bool check_valid_path(const char *path, size_t length);
typedef my_bool (plugin_foreach_func)(THD *thd,
plugin_ref plugin,
diff --git a/sql/sql_prepare.cc b/sql/sql_prepare.cc
index c57c9dacceb..da1334ed0bf 100644
--- a/sql/sql_prepare.cc
+++ b/sql/sql_prepare.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 1995-2002 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,7 +11,7 @@
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 */
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
@@ -1185,7 +1185,7 @@ static bool insert_params_from_vars_with_log(Prepared_statement *stmt,
uint32 length= 0;
THD *thd= stmt->thd;
- DBUG_ENTER("insert_params_from_vars");
+ DBUG_ENTER("insert_params_from_vars_with_log");
if (query->copy(stmt->query(), stmt->query_length(), default_charset_info))
DBUG_RETURN(1);
@@ -1469,7 +1469,7 @@ static int mysql_test_select(Prepared_statement *stmt,
if (!lex->result && !(lex->result= new (stmt->mem_root) select_send))
{
- my_error(ER_OUTOFMEMORY, MYF(0), sizeof(select_send));
+ my_error(ER_OUTOFMEMORY, MYF(0), static_cast<int>(sizeof(select_send)));
goto error;
}
@@ -1783,7 +1783,7 @@ static bool mysql_test_create_view(Prepared_statement *stmt)
if (open_normal_and_derived_tables(thd, tables, MYSQL_OPEN_FORCE_SHARED_MDL))
goto err;
- lex->view_prepare_mode= 1;
+ lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW;
res= select_like_stmt_test(stmt, 0, 0);
err:
@@ -2295,19 +2295,6 @@ end:
}
-/** Init PS/SP specific parse tree members. */
-
-static void init_stmt_after_parse(LEX *lex)
-{
- SELECT_LEX *sl= lex->all_selects_list;
- /*
- Switch off a temporary flag that prevents evaluation of
- subqueries in statement prepare.
- */
- for (; sl; sl= sl->next_select_in_list())
- sl->uncacheable&= ~UNCACHEABLE_PREPARE;
-}
-
/**
SQLCOM_PREPARE implementation.
@@ -2559,7 +2546,7 @@ void mysqld_stmt_execute(THD *thd, char *packet_arg, uint packet_length)
if (!(stmt= find_prepared_statement(thd, stmt_id)))
{
char llbuf[22];
- my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
+ my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
llstr(stmt_id, llbuf), "mysqld_stmt_execute");
DBUG_VOID_RETURN;
}
@@ -2613,7 +2600,7 @@ void mysql_sql_stmt_execute(THD *thd)
if (!(stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
{
my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
- name->length, name->str, "EXECUTE");
+ static_cast<int>(name->length), name->str, "EXECUTE");
DBUG_VOID_RETURN;
}
@@ -2656,7 +2643,7 @@ void mysqld_stmt_fetch(THD *thd, char *packet, uint packet_length)
if (!(stmt= find_prepared_statement(thd, stmt_id)))
{
char llbuf[22];
- my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
+ my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
llstr(stmt_id, llbuf), "mysqld_stmt_fetch");
DBUG_VOID_RETURN;
}
@@ -2716,7 +2703,7 @@ void mysqld_stmt_reset(THD *thd, char *packet)
if (!(stmt= find_prepared_statement(thd, stmt_id)))
{
char llbuf[22];
- my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), sizeof(llbuf),
+ my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0), static_cast<int>(sizeof(llbuf)),
llstr(stmt_id, llbuf), "mysqld_stmt_reset");
DBUG_VOID_RETURN;
}
@@ -2729,7 +2716,7 @@ void mysqld_stmt_reset(THD *thd, char *packet)
*/
reset_stmt_params(stmt);
- stmt->state= Query_arena::PREPARED;
+ stmt->state= Query_arena::STMT_PREPARED;
general_log_print(thd, thd->command, NullS);
@@ -2791,7 +2778,7 @@ void mysql_sql_stmt_close(THD *thd)
if (! (stmt= (Prepared_statement*) thd->stmt_map.find_by_name(name)))
my_error(ER_UNKNOWN_STMT_HANDLER, MYF(0),
- name->length, name->str, "DEALLOCATE PREPARE");
+ static_cast<int>(name->length), name->str, "DEALLOCATE PREPARE");
else if (stmt->is_in_use())
my_error(ER_PS_NO_RECURSION, MYF(0));
else
@@ -2801,6 +2788,7 @@ void mysql_sql_stmt_close(THD *thd)
}
}
+
/**
Handle long data in pieces from client.
@@ -2847,7 +2835,7 @@ void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
if (param_number >= stmt->param_count)
{
/* Error will be sent in execute call */
- stmt->state= Query_arena::ERROR;
+ stmt->state= Query_arena::STMT_ERROR;
stmt->last_errno= ER_WRONG_ARGUMENTS;
sprintf(stmt->last_error, ER(ER_WRONG_ARGUMENTS),
"mysqld_stmt_send_long_data");
@@ -2857,16 +2845,26 @@ void mysql_stmt_get_longdata(THD *thd, char *packet, ulong packet_length)
param= stmt->param_array[param_number];
+ Diagnostics_area new_stmt_da, *save_stmt_da= thd->stmt_da;
+ Warning_info new_warnning_info(thd->query_id, false);
+ Warning_info *save_warinig_info= thd->warning_info;
+
+ thd->stmt_da= &new_stmt_da;
+ thd->warning_info= &new_warnning_info;
+
#ifndef EMBEDDED_LIBRARY
- if (param->set_longdata(packet, (ulong) (packet_end - packet)))
+ param->set_longdata(packet, (ulong) (packet_end - packet));
#else
- if (param->set_longdata(thd->extra_data, thd->extra_length))
+ param->set_longdata(thd->extra_data, thd->extra_length);
#endif
+ if (thd->stmt_da->is_error())
{
- stmt->state= Query_arena::ERROR;
- stmt->last_errno= ER_OUTOFMEMORY;
- sprintf(stmt->last_error, ER(ER_OUTOFMEMORY), 0);
+ stmt->state= Query_arena::STMT_ERROR;
+ stmt->last_errno= thd->stmt_da->sql_errno();
+ strncpy(stmt->last_error, thd->stmt_da->message(), MYSQL_ERRMSG_SIZE);
}
+ thd->stmt_da= save_stmt_da;
+ thd->warning_info= save_warinig_info;
general_log_print(thd, thd->command, NullS);
@@ -2902,8 +2900,15 @@ bool Select_fetch_protocol_binary::send_result_set_metadata(List<Item> &list, ui
bool Select_fetch_protocol_binary::send_eof()
{
+ /*
+ Don't send EOF if we're in error condition (which implies we've already
+ sent or are sending an error)
+ */
+ if (thd->is_error())
+ return true;
+
::my_eof(thd);
- return FALSE;
+ return false;
}
@@ -3009,7 +3014,7 @@ end:
Prepared_statement::Prepared_statement(THD *thd_arg)
:Statement(NULL, &main_mem_root,
- INITIALIZED, ++thd_arg->statement_id_counter),
+ STMT_INITIALIZED, ++thd_arg->statement_id_counter),
thd(thd_arg),
result(thd_arg),
param_array(0),
@@ -3176,7 +3181,6 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
bool error;
Statement stmt_backup;
Query_arena *old_stmt_arena;
- MDL_ticket *mdl_savepoint= NULL;
DBUG_ENTER("Prepared_statement::prepare");
/*
If this is an SQLCOM_PREPARE, we also increase Com_prepare_sql.
@@ -3221,6 +3225,7 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
parser_state.m_lip.multi_statements= FALSE;
lex_start(thd);
+ lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_PREPARE;
error= parse_sql(thd, & parser_state, NULL) ||
thd->is_error() ||
@@ -3248,7 +3253,7 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
Marker used to release metadata locks acquired while the prepared
statement is being checked.
*/
- mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
/*
The only case where we should have items in the thd->free_list is
@@ -3281,8 +3286,8 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len)
if (error == 0)
{
setup_set_params();
- init_stmt_after_parse(lex);
- state= Query_arena::PREPARED;
+ lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_PREPARE;
+ state= Query_arena::STMT_PREPARED;
flags&= ~ (uint) IS_IN_USE;
/*
@@ -3399,6 +3404,13 @@ Prepared_statement::execute_loop(String *expanded_query,
bool error;
int reprepare_attempt= 0;
+ /* Check if we got an error when sending long data */
+ if (state == Query_arena::STMT_ERROR)
+ {
+ my_message(last_errno, last_error, MYF(0));
+ return TRUE;
+ }
+
if (set_parameters(expanded_query, packet, packet_end))
return TRUE;
@@ -3456,7 +3468,7 @@ Prepared_statement::execute_server_runnable(Server_runnable *server_runnable)
Item_change_list save_change_list;
thd->change_list.move_elements_to(&save_change_list);
- state= CONVENTIONAL_EXECUTION;
+ state= STMT_CONVENTIONAL_EXECUTION;
if (!(lex= new (mem_root) st_lex_local))
return TRUE;
@@ -3666,12 +3678,6 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
status_var_increment(thd->status_var.com_stmt_execute);
- /* Check if we got an error when sending long data */
- if (state == Query_arena::ERROR)
- {
- my_message(last_errno, last_error, MYF(0));
- return TRUE;
- }
if (flags & (uint) IS_IN_USE)
{
my_error(ER_PS_NO_RECURSION, MYF(0));
@@ -3739,7 +3745,7 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
to point at it even after we restore from backup. This is ok, as
expanded query was allocated in thd->mem_root.
*/
- stmt_backup.set_query_inner(thd->query(), thd->query_length());
+ stmt_backup.set_query_inner(thd->query_string);
/*
At first execution of prepared statement we may perform logical
@@ -3769,7 +3775,7 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
MYSQL_QUERY_EXEC_START(thd->query(),
thd->thread_id,
(char *) (thd->db ? thd->db : ""),
- thd->security_ctx->priv_user,
+ &thd->security_ctx->priv_user[0],
(char *) thd->security_ctx->host_or_ip,
1);
error= mysql_execute_command(thd);
@@ -3797,8 +3803,8 @@ bool Prepared_statement::execute(String *expanded_query, bool open_cursor)
thd->set_statement(&stmt_backup);
thd->stmt_arena= old_stmt_arena;
- if (state == Query_arena::PREPARED)
- state= Query_arena::EXECUTED;
+ if (state == Query_arena::STMT_PREPARED)
+ state= Query_arena::STMT_EXECUTED;
if (error == 0 && this->lex->sql_command == SQLCOM_CALL)
{
@@ -3899,7 +3905,7 @@ Ed_result_set::Ed_result_set(List<Ed_row> *rows_arg,
*/
Ed_connection::Ed_connection(THD *thd)
- :m_warning_info(thd->query_id),
+ :m_warning_info(thd->query_id, false),
m_thd(thd),
m_rsets(0),
m_current_rset(0)
diff --git a/sql/sql_priv.h b/sql/sql_priv.h
index d36f62ebc5c..a85dea8b273 100644
--- a/sql/sql_priv.h
+++ b/sql/sql_priv.h
@@ -144,6 +144,12 @@
*/
#define OPTION_MASTER_SQL_ERROR (1ULL << 35)
+/*
+ Dont report errors for individual rows,
+ But just report error on commit (or read ofcourse)
+ Note! Reserved for use in MySQL Cluster
+*/
+#define OPTION_ALLOW_BATCH (ULL(1) << 36) // THD, intern (slave)
/* The rest of the file is included in the server only */
#ifndef MYSQL_CLIENT
@@ -198,17 +204,42 @@
*/
+/*
+ Flags below are set when we perform
+ context analysis of the statement and make
+ subqueries non-const. It prevents subquery
+ evaluation at context analysis stage.
+*/
+
+/*
+ Don't evaluate this subquery during statement prepare even if
+ it's a constant one. The flag is switched off in the end of
+ mysqld_stmt_prepare.
+*/
+#define CONTEXT_ANALYSIS_ONLY_PREPARE 1
+/*
+ Special JOIN::prepare mode: changing of query is prohibited.
+ When creating a view, we need to just check its syntax omitting
+ any optimizations: afterwards definition of the view will be
+ reconstructed by means of ::print() methods and written to
+ to an .frm file. We need this definition to stay untouched.
+*/
+#define CONTEXT_ANALYSIS_ONLY_VIEW 2
+/*
+ Don't evaluate this subquery during derived table prepare even if
+ it's a constant one.
+*/
+#define CONTEXT_ANALYSIS_ONLY_DERIVED 4
+
// uncachable cause
#define UNCACHEABLE_DEPENDENT 1
#define UNCACHEABLE_RAND 2
#define UNCACHEABLE_SIDEEFFECT 4
/// forcing to save JOIN for explain
#define UNCACHEABLE_EXPLAIN 8
-/** Don't evaluate subqueries in prepare even if they're not correlated */
-#define UNCACHEABLE_PREPARE 16
/* For uncorrelated SELECT in an UNION with some correlated SELECTs */
-#define UNCACHEABLE_UNITED 32
-#define UNCACHEABLE_CHECKOPTION 64
+#define UNCACHEABLE_UNITED 16
+#define UNCACHEABLE_CHECKOPTION 32
/* Used to check GROUP BY list in the MODE_ONLY_FULL_GROUP_BY mode */
#define UNDEF_POS (-1)
diff --git a/sql/sql_reload.cc b/sql/sql_reload.cc
index ea4f53187f9..64d484c0390 100644
--- a/sql/sql_reload.cc
+++ b/sql/sql_reload.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -33,7 +33,11 @@
@param thd Thread handler (can be NULL!)
@param options What should be reset/reloaded (tables, privileges, slave...)
@param tables Tables to flush (if any)
- @param write_to_binlog True if we can write to the binlog.
+ @param write_to_binlog < 0 if there was an error while interacting with the binary log inside
+ reload_acl_and_cache,
+ 0 if we should not write to the binary log,
+ > 0 if we can write to the binlog.
+
@note Depending on 'options', it may be very bad to write the
query to the binlog (e.g. FLUSH SLAVE); this is a
@@ -47,11 +51,11 @@
*/
bool reload_acl_and_cache(THD *thd, unsigned long options,
- TABLE_LIST *tables, bool *write_to_binlog)
+ TABLE_LIST *tables, int *write_to_binlog)
{
bool result=0;
select_errors=0; /* Write if more errors */
- bool tmp_write_to_binlog= 1;
+ int tmp_write_to_binlog= *write_to_binlog= 1;
DBUG_ASSERT(!thd || !thd->in_sub_stmt);
@@ -82,7 +86,7 @@ bool reload_acl_and_cache(THD *thd, unsigned long options,
When an error is returned, my_message may have not been called and
the client will hang waiting for a response.
*/
- my_error(ER_UNKNOWN_ERROR, MYF(0), "FLUSH PRIVILEGES failed");
+ my_error(ER_UNKNOWN_ERROR, MYF(0));
}
}
@@ -136,13 +140,17 @@ bool reload_acl_and_cache(THD *thd, unsigned long options,
*/
tmp_write_to_binlog= 0;
if (mysql_bin_log.is_open())
- mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE);
+ {
+ if (mysql_bin_log.rotate_and_purge(RP_FORCE_ROTATE))
+ *write_to_binlog= -1;
+ }
}
if (options & REFRESH_RELAY_LOG)
{
#ifdef HAVE_REPLICATION
mysql_mutex_lock(&LOCK_active_mi);
- rotate_relay_log(active_mi);
+ if (rotate_relay_log(active_mi))
+ *write_to_binlog= -1;
mysql_mutex_unlock(&LOCK_active_mi);
#endif
}
@@ -212,12 +220,26 @@ bool reload_acl_and_cache(THD *thd, unsigned long options,
if (tables)
{
for (TABLE_LIST *t= tables; t; t= t->next_local)
- if (!find_table_for_mdl_upgrade(thd->open_tables, t->db,
- t->table_name, FALSE))
+ if (!find_table_for_mdl_upgrade(thd, t->db, t->table_name, false))
return 1;
}
else
{
+ /*
+ It is not safe to upgrade the metadata lock without GLOBAL IX lock.
+ This can happen with FLUSH TABLES <list> WITH READ LOCK as we in these
+ cases don't take a GLOBAL IX lock in order to be compatible with
+ global read lock.
+ */
+ if (thd->open_tables &&
+ !thd->mdl_context.is_lock_owner(MDL_key::GLOBAL, "", "",
+ MDL_INTENTION_EXCLUSIVE))
+ {
+ my_error(ER_TABLE_NOT_LOCKED_FOR_WRITE, MYF(0),
+ thd->open_tables->s->table_name.str);
+ return true;
+ }
+
for (TABLE *tab= thd->open_tables; tab; tab= tab->next)
{
if (! tab->mdl_ticket->is_upgradable_or_exclusive())
@@ -303,7 +325,8 @@ bool reload_acl_and_cache(THD *thd, unsigned long options,
}
mysql_mutex_unlock(&LOCK_global_user_client_stats);
}
- *write_to_binlog= tmp_write_to_binlog;
+ if (*write_to_binlog != -1)
+ *write_to_binlog= tmp_write_to_binlog;
/*
If the query was killed then this function must fail.
*/
@@ -357,7 +380,6 @@ bool reload_acl_and_cache(THD *thd, unsigned long options,
-------------------------------------
- you can't flush WITH READ LOCK a non-existent table
- you can't flush WITH READ LOCK under LOCK TABLES
- - currently incompatible with the GRL (@todo: fix)
Effect on views and temporary tables.
------------------------------------
@@ -367,6 +389,13 @@ bool reload_acl_and_cache(THD *thd, unsigned long options,
if there is a base table, it's used, otherwise ER_NO_SUCH_TABLE
is returned.
+ Handling of MERGE tables
+ ------------------------
+ For MERGE table this statement will open and lock child tables
+ for read (it is impossible to lock parent table without it).
+ Child tables won't be flushed unless they are explicitly present
+ in the statement's table list.
+
Implicit commit
---------------
This statement causes an implicit commit before and
@@ -383,7 +412,6 @@ bool flush_tables_with_read_lock(THD *thd, TABLE_LIST *all_tables)
{
Lock_tables_prelocking_strategy lock_tables_prelocking_strategy;
TABLE_LIST *table_list;
- MDL_request_list mdl_requests;
/*
This is called from SQLCOM_FLUSH, the transaction has
@@ -397,17 +425,13 @@ bool flush_tables_with_read_lock(THD *thd, TABLE_LIST *all_tables)
}
/*
- Acquire SNW locks on tables to be flushed. We can't use
- lock_table_names() here as this call will also acquire global IX
- and database-scope IX locks on the tables, and this will make
+ Acquire SNW locks on tables to be flushed. Don't acquire global
+ IX and database-scope IX locks on the tables as this will make
this statement incompatible with FLUSH TABLES WITH READ LOCK.
*/
- for (table_list= all_tables; table_list;
- table_list= table_list->next_global)
- mdl_requests.push_front(&table_list->mdl_request);
-
- if (thd->mdl_context.acquire_locks(&mdl_requests,
- thd->variables.lock_wait_timeout))
+ if (lock_table_names(thd, all_tables, NULL,
+ thd->variables.lock_wait_timeout,
+ MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK))
goto error;
DEBUG_SYNC(thd,"flush_tables_with_read_lock_after_acquire_locks");
@@ -419,21 +443,24 @@ bool flush_tables_with_read_lock(THD *thd, TABLE_LIST *all_tables)
tdc_remove_table(thd, TDC_RT_REMOVE_UNUSED,
table_list->db,
table_list->table_name, FALSE);
-
- /* Skip views and temporary tables. */
- table_list->required_type= FRMTYPE_TABLE; /* Don't try to flush views. */
- table_list->open_type= OT_BASE_ONLY; /* Ignore temporary tables. */
+ /* Reset ticket to satisfy asserts in open_tables(). */
+ table_list->mdl_request.ticket= NULL;
}
/*
Before opening and locking tables the below call also waits
for old shares to go away, so the fact that we don't pass
MYSQL_LOCK_IGNORE_FLUSH flag to it is important.
+ Also we don't pass MYSQL_OPEN_HAS_MDL_LOCK flag as we want
+ to open underlying tables if merge table is flushed.
+ For underlying tables of the merge the below call has to
+ acquire SNW locks to ensure that they can be locked for
+ read without further waiting.
*/
- if (open_and_lock_tables(thd, all_tables, FALSE,
- MYSQL_OPEN_HAS_MDL_LOCK,
- &lock_tables_prelocking_strategy) ||
- thd->locked_tables_list.init_locked_tables(thd))
+ if (open_and_lock_tables(thd, all_tables, FALSE,
+ MYSQL_OPEN_SKIP_SCOPED_MDL_LOCK,
+ &lock_tables_prelocking_strategy) ||
+ thd->locked_tables_list.init_locked_tables(thd))
{
goto error;
}
diff --git a/sql/sql_reload.h b/sql/sql_reload.h
index 0df5485c907..ebb3d78c003 100644
--- a/sql/sql_reload.h
+++ b/sql/sql_reload.h
@@ -19,7 +19,7 @@ class THD;
struct TABLE_LIST;
bool reload_acl_and_cache(THD *thd, unsigned long options,
- TABLE_LIST *tables, bool *write_to_binlog);
+ TABLE_LIST *tables, int *write_to_binlog);
bool flush_tables_with_read_lock(THD *thd, TABLE_LIST *all_tables);
diff --git a/sql/sql_rename.cc b/sql/sql_rename.cc
index 97f8e46d052..6a7b0b0b3ad 100644
--- a/sql/sql_rename.cc
+++ b/sql/sql_rename.cc
@@ -24,8 +24,7 @@
#include "sql_table.h" // build_table_filename
#include "sql_view.h" // mysql_frm_type, mysql_rename_view
#include "sql_trigger.h"
-#include "lock.h" // wait_if_global_read_lock
- // start_waiting_global_read_lock
+#include "lock.h" // MYSQL_OPEN_SKIP_TEMPORARY
#include "sql_base.h" // tdc_remove_table, lock_table_names,
#include "sql_handler.h" // mysql_ha_rm_tables
#include "datadict.h"
@@ -63,9 +62,6 @@ bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent)
mysql_ha_rm_tables(thd, table_list);
- if (thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, TRUE))
- DBUG_RETURN(1);
-
if (logger.is_log_table_enabled(QUERY_LOG_GENERAL) ||
logger.is_log_table_enabled(QUERY_LOG_SLOW))
{
@@ -108,7 +104,7 @@ bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent)
*/
my_error(ER_CANT_RENAME_LOG_TABLE, MYF(0), ren_table->table_name,
ren_table->table_name);
- DBUG_RETURN(1);
+ goto err;
}
}
else
@@ -121,7 +117,7 @@ bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent)
*/
my_error(ER_CANT_RENAME_LOG_TABLE, MYF(0), ren_table->table_name,
ren_table->table_name);
- DBUG_RETURN(1);
+ goto err;
}
else
{
@@ -139,7 +135,7 @@ bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent)
else
my_error(ER_CANT_RENAME_LOG_TABLE, MYF(0), rename_log_table[1],
rename_log_table[1]);
- DBUG_RETURN(1);
+ goto err;
}
}
@@ -189,7 +185,6 @@ bool mysql_rename_tables(THD *thd, TABLE_LIST *table_list, bool silent)
query_cache_invalidate3(thd, table_list, 0);
err:
- thd->global_read_lock.start_waiting_global_read_lock(thd);
DBUG_RETURN(error || binlog_error);
}
@@ -285,6 +280,7 @@ do_rename(THD *thd, TABLE_LIST *ren_table, char *new_db, char *new_table_name,
{
if ((rc= Table_triggers_list::change_table_name(thd, ren_table->db,
old_alias,
+ ren_table->table_name,
new_db,
new_alias)))
{
diff --git a/sql/sql_repl.cc b/sql/sql_repl.cc
index ee9f1b5066f..7bea6e41184 100644
--- a/sql/sql_repl.cc
+++ b/sql/sql_repl.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB & Sasha, 2008-2009 Sun Microsystems, Inc
+/* Copyright (C) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -25,6 +25,7 @@
#include "rpl_filter.h"
#include <my_dir.h>
#include "rpl_handler.h"
+#include "debug_sync.h"
int max_binlog_dump_events = 0; // unlimited
my_bool opt_sporadic_binlog_dump_fail = 0;
@@ -675,8 +676,11 @@ impossible position";
file */
if (reset_transmit_packet(thd, flags, &ev_offset, &errmsg))
goto err;
+
+ my_off_t prev_pos= pos;
while (!(error = Log_event::read_log_event(&log, packet, log_lock)))
{
+ prev_pos= my_b_tell(&log);
#ifndef DBUG_OFF
if (max_binlog_dump_events && !left_events--)
{
@@ -693,6 +697,19 @@ impossible position";
coord->pos= uint4korr(packet->ptr() + ev_offset + LOG_POS_OFFSET);
event_type= (Log_event_type)((*packet)[LOG_EVENT_OFFSET+ev_offset]);
+ DBUG_EXECUTE_IF("dump_thread_wait_before_send_xid",
+ {
+ if (event_type == XID_EVENT)
+ {
+ net_flush(net);
+ const char act[]=
+ "now "
+ "wait_for signal.continue";
+ DBUG_ASSERT(opt_debug_sync_timeout > 0);
+ DBUG_ASSERT(!debug_sync_set_action(current_thd,
+ STRING_WITH_LEN(act)));
+ }
+ });
if (event_type == FORMAT_DESCRIPTION_EVENT)
{
binlog_can_be_corrupted= test((*packet)[FLAGS_OFFSET+ev_offset] &
@@ -718,6 +735,14 @@ impossible position";
goto err;
}
+ DBUG_EXECUTE_IF("dump_thread_wait_before_send_xid",
+ {
+ if (event_type == XID_EVENT)
+ {
+ net_flush(net);
+ }
+ });
+
DBUG_PRINT("info", ("log event code %d", event_type));
if (event_type == LOAD_EVENT)
{
@@ -745,8 +770,13 @@ impossible position";
here we were reading binlog that was not closed properly (as a result
of a crash ?). treat any corruption as EOF
*/
- if (binlog_can_be_corrupted && error != LOG_READ_MEM)
+ if (binlog_can_be_corrupted &&
+ error != LOG_READ_MEM && error != LOG_READ_EOF)
+ {
+ my_b_seek(&log, prev_pos);
error=LOG_READ_EOF;
+ }
+
/*
TODO: now that we are logging the offset, check to make sure
the recorded offset and the actual match.
@@ -1460,7 +1490,7 @@ bool change_master(THD* thd, Master_info* mi)
get_dynamic(&lex_mi->repl_ignore_server_ids, (uchar*) &s_id, i);
if (s_id == ::server_id && replicate_same_server_id)
{
- my_error(ER_SLAVE_IGNORE_SERVER_IDS, MYF(0), s_id);
+ my_error(ER_SLAVE_IGNORE_SERVER_IDS, MYF(0), static_cast<int>(s_id));
ret= TRUE;
goto err;
}
@@ -1664,23 +1694,6 @@ int reset_master(THD* thd)
return 0;
}
-int cmp_master_pos(const char* log_file_name1, ulonglong log_pos1,
- const char* log_file_name2, ulonglong log_pos2)
-{
- int res;
- size_t log_file_name1_len= strlen(log_file_name1);
- size_t log_file_name2_len= strlen(log_file_name2);
-
- // We assume that both log names match up to '.'
- if (log_file_name1_len == log_file_name2_len)
- {
- if ((res= strcmp(log_file_name1, log_file_name2)))
- return res;
- return (log_pos1 < log_pos2) ? -1 : (log_pos1 == log_pos2) ? 0 : 1;
- }
- return ((log_file_name1_len < log_file_name2_len) ? -1 : 1);
-}
-
/**
Execute a SHOW BINLOG EVENTS statement.
@@ -1925,7 +1938,7 @@ bool show_binlogs(THD* thd)
if (!mysql_bin_log.is_open())
{
- my_message(ER_NO_BINARY_LOGGING, ER(ER_NO_BINARY_LOGGING), MYF(0));
+ my_error(ER_NO_BINARY_LOGGING, MYF(0));
DBUG_RETURN(TRUE);
}
diff --git a/sql/sql_repl.h b/sql/sql_repl.h
index 4d3b0b8d62c..dfe41d8e688 100644
--- a/sql/sql_repl.h
+++ b/sql/sql_repl.h
@@ -43,8 +43,6 @@ int start_slave(THD* thd, Master_info* mi, bool net_report);
int stop_slave(THD* thd, Master_info* mi, bool net_report);
bool change_master(THD* thd, Master_info* mi);
bool mysql_show_binlog_events(THD* thd);
-int cmp_master_pos(const char* log_file_name1, ulonglong log_pos1,
- const char* log_file_name2, ulonglong log_pos2);
int reset_slave(THD *thd, Master_info* mi);
int reset_master(THD* thd);
bool purge_master_logs(THD* thd, const char* to_log);
diff --git a/sql/sql_select.cc b/sql/sql_select.cc
index 171e9a7f7a5..34c61dc2c2b 100644
--- a/sql/sql_select.cc
+++ b/sql/sql_select.cc
@@ -1,5 +1,5 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
- Copyright (c) 2009-2010 Monty Program Ab
+/* Copyright (c) 2000, 2011 Oracle and/or its affiliates. All rights reserved.
+ Copyright (c) 2009-2011 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
@@ -51,6 +51,7 @@
#include "opt_subselect.h"
#include "log_slow.h"
+#include "debug_sync.h" // DEBUG_SYNC
#include <m_ctype.h>
#include <my_bit.h>
#include <hash.h>
@@ -309,57 +310,60 @@ bool handle_select(THD *thd, LEX *lex, select_result *result,
}
-/*
+/**
Fix fields referenced from inner selects.
- SYNOPSIS
- fix_inner_refs()
- thd Thread handle
- all_fields List of all fields used in select
- select Current select
- ref_pointer_array Array of references to Items used in current select
- group_list GROUP BY list (is NULL by default)
+ @param thd Thread handle
+ @param all_fields List of all fields used in select
+ @param select Current select
+ @param ref_pointer_array Array of references to Items used in current select
+ @param group_list GROUP BY list (is NULL by default)
- DESCRIPTION
- The function serves 3 purposes - adds fields referenced from inner
- selects to the current select list, resolves which class to use
- to access referenced item (Item_ref of Item_direct_ref) and fixes
- references (Item_ref objects) to these fields.
+ @details
+ The function serves 3 purposes
+
+ - adds fields referenced from inner query blocks to the current select list
- If a field isn't already in the select list and the ref_pointer_array
+ - Decides which class to use to reference the items (Item_ref or
+ Item_direct_ref)
+
+ - fixes references (Item_ref objects) to these fields.
+
+ If a field isn't already on the select list and the ref_pointer_array
is provided then it is added to the all_fields list and the pointer to
it is saved in the ref_pointer_array.
The class to access the outer field is determined by the following rules:
- 1. If the outer field isn't used under an aggregate function
- then the Item_ref class should be used.
- 2. If the outer field is used under an aggregate function and this
- function is aggregated in the select where the outer field was
- resolved or in some more inner select then the Item_direct_ref
- class should be used.
- It used used also if we are grouping by a subquery that refers
- this outer field.
+
+ -#. If the outer field isn't used under an aggregate function then the
+ Item_ref class should be used.
+
+ -#. If the outer field is used under an aggregate function and this
+ function is, in turn, aggregated in the query block where the outer
+ field was resolved or some query nested therein, then the
+ Item_direct_ref class should be used. Also it should be used if we are
+ grouping by a subquery that references this outer field.
+
The resolution is done here and not at the fix_fields() stage as
- it can be done only after sum functions are fixed and pulled up to
- selects where they are have to be aggregated.
+ it can be done only after aggregate functions are fixed and pulled up to
+ selects where they are to be aggregated.
+
When the class is chosen it substitutes the original field in the
Item_outer_ref object.
After this we proceed with fixing references (Item_outer_ref objects) to
this field from inner subqueries.
- RETURN
- TRUE an error occured
- FALSE ok
-*/
+ @return Status
+ @retval true An error occured.
+ @retval false OK.
+ */
bool
fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
Item **ref_pointer_array)
{
Item_outer_ref *ref;
- bool res= FALSE;
- bool direct_ref= FALSE;
/*
Mark the references from the inner_refs_list that are occurred in
@@ -376,6 +380,7 @@ fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
while ((ref= ref_it++))
{
+ bool direct_ref= false;
Item *item= ref->outer_ref;
Item **item_ref= ref->ref;
Item_ref *new_ref;
@@ -434,7 +439,7 @@ fix_inner_refs(THD *thd, List<Item> &all_fields, SELECT_LEX *select,
return TRUE;
thd->used_tables|= item->used_tables();
}
- return res;
+ return false;
}
/**
@@ -765,6 +770,7 @@ JOIN::optimize()
if (optimized)
DBUG_RETURN(0);
optimized= 1;
+ DEBUG_SYNC(thd, "before_join_optimize");
thd_proc_info(thd, "optimizing");
@@ -903,7 +909,7 @@ JOIN::optimize()
If all items were resolved by opt_sum_query, there is no need to
open any tables.
*/
- if ((res=opt_sum_query(select_lex->leaf_tables, all_fields, conds)))
+ if ((res=opt_sum_query(thd, select_lex->leaf_tables, all_fields, conds)))
{
if (res == HA_ERR_KEY_NOT_FOUND)
{
@@ -1727,6 +1733,10 @@ JOIN::reinit()
while ((item= it++))
item->restore_to_before_no_rows_in_result();
}
+
+ if (!(select_options & SELECT_DESCRIBE))
+ init_ftfuncs(thd, select_lex, test(order));
+
DBUG_RETURN(0);
}
@@ -1938,7 +1948,11 @@ JOIN::exec()
JOIN_TAB *first_tab= curr_join->join_tab + curr_join->const_tables;
first_tab->sorted= test(first_tab->loosescan_match_tab);
}
- if ((tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table, 0)))
+
+ Procedure *save_proc= curr_join->procedure;
+ tmp_error= do_select(curr_join, (List<Item> *) 0, curr_tmp_table, 0);
+ curr_join->procedure= save_proc;
+ if (tmp_error)
{
error= tmp_error;
DBUG_VOID_RETURN;
@@ -2504,6 +2518,13 @@ mysql_select(THD *thd, Item ***rref_pointer_array,
{
DBUG_RETURN(TRUE);
}
+ /*
+ Original join tabs might be overwritten at first
+ subselect execution. So we need to restore them.
+ */
+ Item_subselect *subselect= select_lex->master_unit()->item;
+ if (subselect && subselect->is_uncacheable() && join->reinit())
+ DBUG_RETURN(TRUE);
}
else
{
@@ -3499,26 +3520,7 @@ add_key_field(KEY_FIELD **key_fields,uint and_level, Item_func *cond,
eq_func is NEVER true when num_values > 1
*/
if (!eq_func)
- {
- /*
- Additional optimization: if we're processing
- "t.key BETWEEN c1 AND c1" then proceed as if we were processing
- "t.key = c1".
- TODO: This is a very limited fix. A more generic fix is possible.
- There are 2 options:
- A) Make equality propagation code be able to handle BETWEEN
- (including cases like t1.key BETWEEN t2.key AND t3.key)
- B) Make range optimizer to infer additional "t.key = c" equalities
- and use them in equality propagation process (see details in
- OptimizerKBAndTodo)
- */
- if ((cond->functype() != Item_func::BETWEEN) ||
- ((Item_func_between*) cond)->negated ||
- !value[0]->eq(value[1], field->binary()))
- return;
- eq_func= TRUE;
- }
-
+ return;
if (field->result_type() == STRING_RESULT)
{
if ((*value)->result_type() != STRING_RESULT)
@@ -3741,9 +3743,65 @@ add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level,
case Item_func::OPTIMIZE_KEY:
{
Item **values;
- // BETWEEN, IN, NE
- if (is_local_field (cond_func->key_item()) &&
- !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
+ /*
+ Build list of possible keys for 'a BETWEEN low AND high'.
+ It is handled similar to the equivalent condition
+ 'a >= low AND a <= high':
+ */
+ if (cond_func->functype() == Item_func::BETWEEN)
+ {
+ Item_field *field_item;
+ bool equal_func= FALSE;
+ uint num_values= 2;
+ values= cond_func->arguments();
+
+ bool binary_cmp= (values[0]->real_item()->type() == Item::FIELD_ITEM)
+ ? ((Item_field*)values[0]->real_item())->field->binary()
+ : TRUE;
+
+ /*
+ Additional optimization: If 'low = high':
+ Handle as if the condition was "t.key = low".
+ */
+ if (!((Item_func_between*)cond_func)->negated &&
+ values[1]->eq(values[2], binary_cmp))
+ {
+ equal_func= TRUE;
+ num_values= 1;
+ }
+
+ /*
+ Append keys for 'field <cmp> value[]' if the
+ condition is of the form::
+ '<field> BETWEEN value[1] AND value[2]'
+ */
+ if (is_local_field (values[0]))
+ {
+ field_item= (Item_field *) (values[0]->real_item());
+ add_key_equal_fields(key_fields, *and_level, cond_func,
+ field_item, equal_func, &values[1],
+ num_values, usable_tables, sargables);
+ }
+ /*
+ Append keys for 'value[0] <cmp> field' if the
+ condition is of the form:
+ 'value[0] BETWEEN field1 AND field2'
+ */
+ for (uint i= 1; i <= num_values; i++)
+ {
+ if (is_local_field (values[i]))
+ {
+ field_item= (Item_field *) (values[i]->real_item());
+ add_key_equal_fields(key_fields, *and_level, cond_func,
+ field_item, equal_func, values,
+ 1, usable_tables, sargables);
+ }
+ }
+ } // if ( ... Item_func::BETWEEN)
+
+ // IN, NE
+ else if (is_local_field (cond_func->key_item()) &&
+ !(cond_func->used_tables() & OUTER_REF_TABLE_BIT))
{
values= cond_func->arguments()+1;
if (cond_func->functype() == Item_func::NE_FUNC &&
@@ -3757,21 +3815,6 @@ add_key_fields(JOIN *join, KEY_FIELD **key_fields, uint *and_level,
cond_func->argument_count()-1,
usable_tables, sargables);
}
- if (cond_func->functype() == Item_func::BETWEEN)
- {
- values= cond_func->arguments();
- for (uint i= 1 ; i < cond_func->argument_count() ; i++)
- {
- Item_field *field_item;
- if (is_local_field (cond_func->arguments()[i]))
- {
- field_item= (Item_field *) (cond_func->arguments()[i]->real_item());
- add_key_equal_fields(key_fields, *and_level, cond_func,
- field_item, 0, values, 1, usable_tables,
- sargables);
- }
- }
- }
break;
}
case Item_func::OPTIMIZE_OP:
@@ -4239,8 +4282,12 @@ update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab,
continue;
}
-#ifdef HAVE_valgrind
- /* Valgrind complains about overlapped memcpy when save_pos==use. */
+#if defined(__GNUC__) && !MY_GNUC_PREREQ(4,4)
+ /*
+ Old gcc used a memcpy(), which is undefined if save_pos==use:
+ http://gcc.gnu.org/bugzilla/show_bug.cgi?id=19410
+ http://gcc.gnu.org/bugzilla/show_bug.cgi?id=39480
+ */
if (save_pos != use)
#endif
*save_pos= *use;
@@ -6894,9 +6941,9 @@ make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
tab->set_select_cond(tmp, __LINE__);
/* Push condition to storage engine if this is enabled
and the condition is not guarded */
- tab->table->file->pushed_cond= NULL;
- if ((thd->variables.optimizer_switch &
- OPTIMIZER_SWITCH_ENGINE_CONDITION_PUSHDOWN) && !first_inner_tab)
+ if (tab->table && (thd->variables.optimizer_switch &
+ OPTIMIZER_SWITCH_ENGINE_CONDITION_PUSHDOWN) &&
+ !first_inner_tab)
{
COND *push_cond=
make_cond_for_table(tmp, current_map, current_map, FALSE);
@@ -6920,10 +6967,12 @@ make_join_select(JOIN *join,SQL_SELECT *select,COND *cond)
{
/* Use quick key read if it's a constant and it's not used
with key reading */
- if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF
- && tab->type != JT_FT && (tab->type != JT_REF ||
- (uint) tab->ref.key == tab->quick->index))
- {
+ if (tab->needed_reg.is_clear_all() && tab->type != JT_EQ_REF &&
+ tab->type != JT_FT &&
+ ((tab->type != JT_CONST && tab->type != JT_REF) ||
+ (uint)tab->ref.key == tab->quick->index))
+ {
+ DBUG_ASSERT(tab->quick->is_valid());
sel->quick=tab->quick; // Use value from get_quick_...
sel->quick_keys.clear_all();
sel->needed_reg.clear_all();
@@ -10670,24 +10719,41 @@ internal_remove_eq_conds(THD *thd, COND *cond, Item::cond_result *cond_value)
Field *field=((Item_field*) args[0])->field;
/* fix to replace 'NULL' dates with '0' (shreeve@uci.edu) */
/*
- datetime_field IS NULL has to be modified to
- datetime_field == 0
+ See BUG#12594011
+ Documentation says that
+ SELECT datetime_notnull d FROM t1 WHERE d IS NULL
+ shall return rows where d=='0000-00-00'
+
+ Thus, for DATE and DATETIME columns defined as NOT NULL,
+ "date_notnull IS NULL" has to be modified to
+ "date_notnull IS NULL OR date_notnull == 0" (if outer join)
+ "date_notnull == 0" (otherwise)
+
*/
if (((field->type() == MYSQL_TYPE_DATE) ||
(field->type() == MYSQL_TYPE_DATETIME)) &&
- (field->flags & NOT_NULL_FLAG) && !field->table->maybe_null)
+ (field->flags & NOT_NULL_FLAG))
{
- COND *new_cond;
- if ((new_cond= new Item_func_eq(args[0],new Item_int("0", 0, 2))))
- {
- cond=new_cond;
- /*
- Item_func_eq can't be fixed after creation so we do not check
- cond->fixed, also it do not need tables so we use 0 as second
- argument.
- */
- cond->fix_fields(thd, &cond);
- }
+ Item *item0= new(thd->mem_root) Item_int((longlong)0, 1);
+ Item *eq_cond= new(thd->mem_root) Item_func_eq(args[0], item0);
+ if (!eq_cond)
+ return cond;
+
+ if (field->table->pos_in_table_list->outer_join)
+ {
+ // outer join: transform "col IS NULL" to "col IS NULL or col=0"
+ Item *or_cond= new(thd->mem_root) Item_cond_or(eq_cond, cond);
+ if (!or_cond)
+ return cond;
+ cond= or_cond;
+ }
+ else
+ {
+ // not outer join: transform "col IS NULL" to "col=0"
+ cond= eq_cond;
+ }
+
+ cond->fix_fields(thd, &cond);
}
}
if (cond->const_item())
@@ -11235,7 +11301,12 @@ Field *create_tmp_field(THD *thd, TABLE *table,Item *item, Item::Type type,
convert_blob_length);
if (orig_type == Item::REF_ITEM && orig_modify)
((Item_ref*)orig_item)->set_result_field(result);
- if (field->field->eq_def(result))
+ /*
+ Fields that are used as arguments to the DEFAULT() function already have
+ their data pointers set to the default value during name resulotion. See
+ Item_default_value::fix_fields.
+ */
+ if (orig_type != Item::DEFAULT_VALUE_ITEM && field->field->eq_def(result))
*default_field= field->field;
return result;
}
@@ -11939,6 +12010,7 @@ create_tmp_table(THD *thd,TMP_TABLE_PARAM *param,List<Item> &fields,
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT1 ||
(ha_base_keytype) key_part_info->type == HA_KEYTYPE_VARTEXT2) ?
0 : FIELDFLAG_BINARY;
+ key_part_info->key_part_flag= 0;
if (!using_unique_constraint)
{
cur_group->buff=(char*) group_buff;
@@ -13462,7 +13534,6 @@ evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
condition is true => a match is found.
*/
bool found= 1;
- bool use_not_exists_opt= 0;
while (join_tab->first_unmatched && found)
{
/*
@@ -13478,17 +13549,29 @@ evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
first_unmatched->found= 1;
for (JOIN_TAB *tab= first_unmatched; tab <= join_tab; tab++)
{
- if (tab->table->reginfo.not_exists_optimize)
- use_not_exists_opt= 1;
/* Check all predicates that has just been activated. */
/*
Actually all predicates non-guarded by first_unmatched->found
will be re-evaluated again. It could be fixed, but, probably,
it's not worth doing now.
*/
+ /*
+ not_exists_optimize has been created from a
+ select_cond containing 'is_null'. This 'is_null'
+ predicate is still present on any 'tab' with
+ 'not_exists_optimize'. Furthermore, the usual rules
+ for condition guards also applies for
+ 'not_exists_optimize' -> When 'is_null==false' we
+ know all cond. guards are open and we can apply
+ the 'not_exists_optimize'.
+ */
+ DBUG_ASSERT(!(tab->table->reginfo.not_exists_optimize &&
+ !tab->select_cond));
+
if (tab->select_cond && !tab->select_cond->val_int())
{
/* The condition attached to table tab is false */
+
if (tab == join_tab)
found= 0;
else
@@ -13498,6 +13581,20 @@ evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
not to the last table of the current nest level.
*/
join->return_tab= tab;
+ }
+
+ if (tab->table->reginfo.not_exists_optimize)
+ {
+ /*
+ When not_exists_optimize is set: No need to further
+ explore more rows of 'tab' for this partial result.
+ Any found 'tab' matches are known to evaluate to 'false'.
+ Returning .._NO_MORE_ROWS will skip rem. 'tab' rows.
+ */
+ DBUG_RETURN(NESTED_LOOP_NO_MORE_ROWS);
+ }
+ else if (tab != join_tab)
+ {
DBUG_RETURN(NESTED_LOOP_OK);
}
}
@@ -13512,8 +13609,6 @@ evaluate_join_record(JOIN *join, JOIN_TAB *join_tab,
join_tab->first_unmatched= first_unmatched;
}
- if (use_not_exists_opt)
- DBUG_RETURN(NESTED_LOOP_NO_MORE_ROWS);
JOIN_TAB *return_tab= join->return_tab;
join_tab->found_match= TRUE;
@@ -13727,7 +13822,7 @@ join_read_const_table(JOIN_TAB *tab, POSITION *pos)
/* Mark for EXPLAIN that the row was not found */
pos->records_read=0.0;
pos->ref_depend_map= 0;
- if (!table->maybe_null || error > 0)
+ if (!table->pos_in_table_list->outer_join || error > 0)
DBUG_RETURN(error);
}
/*
@@ -13753,7 +13848,7 @@ join_read_const_table(JOIN_TAB *tab, POSITION *pos)
/* Mark for EXPLAIN that the row was not found */
pos->records_read=0.0;
pos->ref_depend_map= 0;
- if (!table->maybe_null || error > 0)
+ if (!table->pos_in_table_list->outer_join || error > 0)
DBUG_RETURN(error);
}
}
@@ -14342,10 +14437,14 @@ end_send(JOIN *join, JOIN_TAB *join_tab __attribute__((unused)),
}
if (join->having && join->having->val_int() == 0)
DBUG_RETURN(NESTED_LOOP_OK); // Didn't match having
- error=0;
if (join->procedure)
- error=join->procedure->send_row(join->procedure_fields_list);
- else if (join->do_send_rows)
+ {
+ if (join->procedure->send_row(join->procedure_fields_list))
+ DBUG_RETURN(NESTED_LOOP_ERROR);
+ DBUG_RETURN(NESTED_LOOP_OK);
+ }
+ error=0;
+ if (join->do_send_rows)
error=join->result->send_data(*join->fields);
if (error)
DBUG_RETURN(NESTED_LOOP_ERROR); /* purecov: inspected */
@@ -14841,6 +14940,42 @@ bool test_if_ref(Item *root_cond, Item_field *left_item,Item *right_item)
return 0; // keep test
}
+/**
+ Extract a condition that can be checked after reading given table
+
+ @param cond Condition to analyze
+ @param tables Tables for which "current field values" are available
+ @param used_table Table that we're extracting the condition for (may
+ also include PSEUDO_TABLE_BITS, and may be zero)
+ @param exclude_expensive_cond Do not push expensive conditions
+
+ @retval <>NULL Generated condition
+ @retval =NULL Already checked, OR error
+
+ @details
+ Extract the condition that can be checked after reading the table
+ specified in 'used_table', given that current-field values for tables
+ specified in 'tables' bitmap are available.
+ If 'used_table' is 0
+ - extract conditions for all tables in 'tables'.
+ - extract conditions are unrelated to any tables
+ in the same query block/level(i.e. conditions
+ which have used_tables == 0).
+
+ The function assumes that
+ - Constant parts of the condition has already been checked.
+ - Condition that could be checked for tables in 'tables' has already
+ been checked.
+
+ The function takes into account that some parts of the condition are
+ guaranteed to be true by employed 'ref' access methods (the code that
+ does this is located at the end, search down for "EQ_FUNC").
+
+ @note
+ Make sure to keep the implementations of make_cond_for_table() and
+ make_cond_after_sjm() synchronized.
+ make_cond_for_info_schema() uses similar algorithm as well.
+*/
/*
@@ -15060,7 +15195,7 @@ make_cond_after_sjm(Item *root_cond, Item *cond, table_map tables,
new_cond->argument_list()->push_back(fix);
}
/*
- Item_cond_and do not need fix_fields for execution, its parameters
+ Item_cond_or do not need fix_fields for execution, its parameters
are fixed or do not need fix_fields, too
*/
new_cond->quick_fix_field();
@@ -15384,6 +15519,8 @@ static bool
list_contains_unique_index(TABLE *table,
bool (*find_func) (Field *, void *), void *data)
{
+ if (table->pos_in_table_list->outer_join)
+ return 0;
for (uint keynr= 0; keynr < table->s->keys; keynr++)
{
if (keynr == table->s->primary_key ||
@@ -15397,7 +15534,7 @@ list_contains_unique_index(TABLE *table,
key_part < key_part_end;
key_part++)
{
- if (key_part->field->maybe_null() ||
+ if (key_part->field->real_maybe_null() ||
!find_func(key_part->field, data))
break;
}
@@ -15503,13 +15640,15 @@ test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
{
int ref_key;
uint ref_key_parts;
- int order_direction;
+ int order_direction= 0;
uint used_key_parts;
TABLE *table=tab->table;
SQL_SELECT *select=tab->select;
key_map usable_keys;
QUICK_SELECT_I *save_quick= 0;
COND *orig_select_cond= 0;
+ int best_key= -1;
+
DBUG_ENTER("test_if_skip_sort_order");
LINT_INIT(ref_key_parts);
@@ -15619,6 +15758,7 @@ test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
new_ref_key_map.clear_all(); // Force the creation of quick select
new_ref_key_map.set_bit(new_ref_key); // only for new_ref_key.
+ select->quick= 0;
if (select->test_quick_select(tab->join->thd, new_ref_key_map, 0,
(tab->join->select_options &
OPTION_FOUND_ROWS) ?
@@ -15640,8 +15780,7 @@ test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
{
uint UNINIT_VAR(best_key_parts);
uint saved_best_key_parts= 0;
- int UNINIT_VAR(best_key_direction);
- int best_key= -1;
+ int best_key_direction= 0;
JOIN *join= tab->join;
ha_rows table_records= table->file->stats.records;
@@ -15661,84 +15800,21 @@ test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
tab->join->tables > tab->join->const_tables + 1) &&
((unsigned) best_key != table->s->primary_key ||
!table->file->primary_key_is_clustered()))
- DBUG_RETURN(0);
+ goto use_filesort;
if (best_key >= 0)
{
- bool quick_created= FALSE;
if (table->quick_keys.is_set(best_key) && best_key != ref_key)
{
key_map map;
map.clear_all(); // Force the creation of quick select
map.set_bit(best_key); // only best_key.
- quick_created=
- select->test_quick_select(join->thd, map, 0,
- join->select_options & OPTION_FOUND_ROWS ?
- HA_POS_ERROR :
- join->unit->select_limit_cnt,
- TRUE, FALSE) > 0;
- }
- if (!no_changes)
- {
- /*
- If ref_key used index tree reading only ('Using index' in EXPLAIN),
- and best_key doesn't, then revert the decision.
- */
- if (!table->covering_keys.is_set(best_key))
- table->disable_keyread();
- if (!quick_created)
- {
- tab->index= best_key;
- tab->read_first_record= best_key_direction > 0 ?
- join_read_first:join_read_last;
- tab->type=JT_NEXT; // Read with index_first(), index_next()
- if (select && select->quick)
- {
- delete select->quick;
- select->quick= 0;
- }
- if (table->covering_keys.is_set(best_key) && ! table->key_read)
- table->enable_keyread();
- if (tab->pre_idx_push_select_cond)
- {
- COND *tmp_cond= tab->pre_idx_push_select_cond;
- if (orig_select_cond)
- {
- tmp_cond= and_conds(tmp_cond, orig_select_cond);
- tmp_cond->quick_fix_field();
- }
- tab->set_cond(tmp_cond);
- /* orig_select_cond was merged, no need to restore original one. */
- orig_select_cond= 0;
- }
- table->file->ha_index_or_rnd_end();
- if (join->select_options & SELECT_DESCRIBE)
- {
- tab->ref.key= -1;
- tab->ref.key_parts= 0;
- if (select_limit < table_records)
- tab->limit= select_limit;
- }
- }
- else if (tab->type != JT_ALL)
- {
- /*
- We're about to use a quick access to the table.
- We need to change the access method so as the quick access
- method is actually used.
- */
- DBUG_ASSERT(tab->select->quick);
- tab->type=JT_ALL;
- tab->use_quick=1;
- tab->ref.key= -1;
- tab->ref.key_parts=0; // Don't use ref key.
- tab->read_first_record= join_init_read_record;
- if (tab->is_using_loose_index_scan())
- join->tmp_table_param.precomputed_group_by= TRUE;
- /*
- TODO: update the number of records in join->best_positions[tablenr]
- */
- }
+ select->quick= 0;
+ select->test_quick_select(join->thd, map, 0,
+ join->select_options & OPTION_FOUND_ROWS ?
+ HA_POS_ERROR :
+ join->unit->select_limit_cnt,
+ TRUE, FALSE) > 0;
}
order_direction= best_key_direction;
/*
@@ -15751,10 +15827,12 @@ test_if_skip_sort_order(JOIN_TAB *tab,ORDER *order,ha_rows select_limit,
saved_best_key_parts : best_key_parts;
}
else
- goto use_filesort;
+ goto use_filesort;
}
check_reverse_order:
+ DBUG_ASSERT(order_direction != 0);
+
if (order_direction == -1) // If ORDER BY ... DESC
{
if (select && select->quick)
@@ -15763,9 +15841,10 @@ check_reverse_order:
Don't reverse the sort order, if it's already done.
(In some cases test_if_order_by_key() can be called multiple times
*/
- if (!select->quick->reverse_sorted())
+ if (select->quick->reverse_sorted())
+ goto skipped_filesort;
+ else
{
- QUICK_SELECT_I *tmp;
int quick_type= select->quick->get_type();
if (quick_type == QUICK_SELECT_I::QS_TYPE_INDEX_MERGE ||
quick_type == QUICK_SELECT_I::QS_TYPE_ROR_INTERSECT ||
@@ -15773,40 +15852,141 @@ check_reverse_order:
quick_type == QUICK_SELECT_I::QS_TYPE_GROUP_MIN_MAX)
{
tab->limit= 0;
- select->quick= save_quick;
- goto use_filesort; // Use filesort
+ goto use_filesort; // Use filesort
}
-
- /* ORDER BY range_key DESC */
- tmp= select->quick->make_reverse(used_key_parts);
- if (!tmp)
- {
- select->quick= save_quick;
- tab->limit= 0;
- goto use_filesort; // Reverse sort not supported
- }
- select->set_quick(tmp);
}
}
- else if (tab->type != JT_NEXT && tab->type != JT_REF_OR_NULL &&
- tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
+ }
+
+ /*
+ Update query plan with access pattern for doing
+ ordered access according to what we have decided
+ above.
+ */
+ if (!no_changes) // We are allowed to update QEP
+ {
+ if (best_key >= 0)
{
- /*
- SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
+ bool quick_created=
+ (select && select->quick && select->quick!=save_quick);
- Use a traversal function that starts by reading the last row
- with key part (A) and then traverse the index backwards.
+ /*
+ If ref_key used index tree reading only ('Using index' in EXPLAIN),
+ and best_key doesn't, then revert the decision.
*/
- tab->read_first_record= join_read_last_key;
- tab->read_record.read_record= join_read_prev_same;
+ if (!table->covering_keys.is_set(best_key))
+ table->disable_keyread();
+ if (!quick_created)
+ {
+ if (select) // Throw any existing quick select
+ select->quick= 0; // Cleanup either reset to save_quick,
+ // or 'delete save_quick'
+ tab->index= best_key;
+ tab->read_first_record= order_direction > 0 ?
+ join_read_first:join_read_last;
+ tab->type=JT_NEXT; // Read with index_first(), index_next()
+
+ if (table->covering_keys.is_set(best_key) && ! table->key_read)
+ table->enable_keyread();
+ if (tab->pre_idx_push_select_cond)
+ {
+ COND *tmp_cond= tab->pre_idx_push_select_cond;
+ if (orig_select_cond)
+ {
+ tmp_cond= and_conds(tmp_cond, orig_select_cond);
+ tmp_cond->quick_fix_field();
+ }
+ tab->set_cond(tmp_cond);
+ /* orig_select_cond was merged, no need to restore original one. */
+ orig_select_cond= 0;
+ }
+ table->file->ha_index_or_rnd_end();
+ if (tab->join->select_options & SELECT_DESCRIBE)
+ {
+ tab->ref.key= -1;
+ tab->ref.key_parts= 0;
+ if (select_limit < table->file->stats.records)
+ tab->limit= select_limit;
+ }
+ }
+ else if (tab->type != JT_ALL)
+ {
+ /*
+ We're about to use a quick access to the table.
+ We need to change the access method so as the quick access
+ method is actually used.
+ */
+ DBUG_ASSERT(tab->select->quick);
+ tab->type=JT_ALL;
+ tab->use_quick=1;
+ tab->ref.key= -1;
+ tab->ref.key_parts=0; // Don't use ref key.
+ tab->read_first_record= join_init_read_record;
+ if (tab->is_using_loose_index_scan())
+ tab->join->tmp_table_param.precomputed_group_by= TRUE;
+ /*
+ TODO: update the number of records in join->best_positions[tablenr]
+ */
+ }
+ } // best_key >= 0
+
+ if (order_direction == -1) // If ORDER BY ... DESC
+ {
+ if (select && select->quick)
+ {
+ /* ORDER BY range_key DESC */
+ QUICK_SELECT_I *tmp= select->quick->make_reverse(used_key_parts);
+ if (!tmp)
+ {
+ tab->limit= 0;
+ goto use_filesort; // Reverse sort failed -> filesort
+ }
+ if (select->quick == save_quick)
+ save_quick= 0; // make_reverse() consumed it
+ select->set_quick(tmp);
+ }
+ else if (tab->type != JT_NEXT && tab->type != JT_REF_OR_NULL &&
+ tab->ref.key >= 0 && tab->ref.key_parts <= used_key_parts)
+ {
+ /*
+ SELECT * FROM t1 WHERE a=1 ORDER BY a DESC,b DESC
+
+ Use a traversal function that starts by reading the last row
+ with key part (A) and then traverse the index backwards.
+ */
+ tab->read_first_record= join_read_last_key;
+ tab->read_record.read_record= join_read_prev_same;
+ }
}
+ else if (select && select->quick)
+ select->quick->need_sorted_output();
+
+ } // QEP has been modified
+
+ /*
+ Cleanup:
+ We may have both a 'select->quick' and 'save_quick' (original)
+ at this point. Delete the one that we wan't use.
+ */
+
+skipped_filesort:
+ // Keep current (ordered) select->quick
+ if (select && save_quick != select->quick)
+ {
+ delete save_quick;
+ save_quick= NULL;
}
- else if (select && select->quick)
- select->quick->need_sorted_output();
if (orig_select_cond)
tab->set_cond(orig_select_cond);
DBUG_RETURN(1);
+
use_filesort:
+ // Restore original save_quick
+ if (select && select->quick != save_quick)
+ {
+ delete select->quick;
+ select->quick= save_quick;
+ }
if (orig_select_cond)
tab->set_cond(orig_select_cond);
DBUG_RETURN(0);
@@ -15819,7 +15999,7 @@ use_filesort:
SYNOPSIS
create_sort_index()
thd Thread handler
- tab Table to sort (in join structure)
+ join Join with table to sort
order How table should be sorted
filesort_limit Max number of rows that needs to be sorted
select_limit Max number of rows in final output
@@ -15829,8 +16009,8 @@ use_filesort:
IMPLEMENTATION
- - If there is an index that can be used, 'tab' is modified to use
- this index.
+ - If there is an index that can be used, the first non-const join_tab in
+ 'join' is modified to use this index.
- If no index, create with filesort() an index file that can be used to
retrieve rows in order (should be done with 'read_record').
The sorted data is stored in tab->table and will be freed when calling
@@ -16966,6 +17146,8 @@ calc_group_buffer(JOIN *join,ORDER *group)
{
key_length+= 8;
}
+ else if (type == MYSQL_TYPE_BLOB)
+ key_length+= MAX_BLOB_WIDTH; // Can't be used as a key
else
{
/*
@@ -17612,7 +17794,7 @@ init_sum_functions(Item_sum **func_ptr, Item_sum **end_ptr)
{
for (; func_ptr != end_ptr ;func_ptr++)
{
- if ((*func_ptr)->reset())
+ if ((*func_ptr)->reset_and_add())
return 1;
}
/* If rollup, calculate the upper sum levels */
diff --git a/sql/sql_select.h b/sql/sql_select.h
index 8d487021a04..696cec99192 100644
--- a/sql/sql_select.h
+++ b/sql/sql_select.h
@@ -1,7 +1,7 @@
#ifndef SQL_SELECT_INCLUDED
#define SQL_SELECT_INCLUDED
-/* Copyright (C) 2000-2006 MySQL AB
+/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
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
@@ -1785,7 +1785,8 @@ bool is_indexed_agg_distinct(JOIN *join, List<Item_field> *out_args);
/* functions from opt_sum.cc */
bool simple_pred(Item_func *func_item, Item **args, bool *inv_order);
-int opt_sum_query(TABLE_LIST *tables, List<Item> &all_fields,COND *conds);
+int opt_sum_query(THD* thd,
+ TABLE_LIST *tables, List<Item> &all_fields, COND *conds);
/* from sql_delete.cc, used by opt_range.cc */
extern "C" int refpos_order_cmp(void* arg, const void *a,const void *b);
diff --git a/sql/sql_show.cc b/sql/sql_show.cc
index ea17cd73e1c..2d06f383612 100644
--- a/sql/sql_show.cc
+++ b/sql/sql_show.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -30,6 +30,8 @@
#include "repl_failsafe.h"
#include "sql_parse.h" // check_access, check_table_access
#include "sql_partition.h" // partition_element
+#include "sql_derived.h" // mysql_derived_prepare,
+ // mysql_handle_derived,
#include "sql_db.h" // check_db_dir_existence, load_db_opt_by_name
#include "sql_time.h" // interval_type_to_name
#include "tztime.h" // struct Time_zone
@@ -104,11 +106,13 @@ static const char *ha_choice_values[] = {"", "0", "1"};
static void store_key_options(THD *thd, String *packet, TABLE *table,
KEY *key_info);
+#ifdef WITH_PARTITION_STORAGE_ENGINE
static void get_cs_converted_string_value(THD *thd,
String *input_str,
String *output_str,
CHARSET_INFO *cs,
bool use_hex);
+#endif
static void
append_algorithm(TABLE_LIST *table, String *buff);
@@ -224,27 +228,27 @@ static my_bool show_plugins(THD *thd, plugin_ref plugin,
strlen(PLUGIN_LICENSE_PROPRIETARY_STRING), cs);
break;
}
- table->field[9]->set_notnull();
- if ((uint) plug->maturity <= MariaDB_PLUGIN_MATURITY_STABLE)
- table->field[10]->store(maturity_name[plug->maturity].str,
+ table->field[10]->store(
+ global_plugin_typelib_names[plugin_load_option(plugin)],
+ strlen(global_plugin_typelib_names[plugin_load_option(plugin)]),
+ cs);
+
+ if (plug->maturity <= MariaDB_PLUGIN_MATURITY_STABLE)
+ table->field[11]->store(maturity_name[plug->maturity].str,
maturity_name[plug->maturity].length,
cs);
else
- {
- DBUG_ASSERT(0);
- table->field[10]->store("Unknown", 7, cs);
- }
- table->field[10]->set_notnull();
+ table->field[11]->store("Unknown", 7, cs);
if (plug->version_info)
{
- table->field[11]->store(plug->version_info,
+ table->field[12]->store(plug->version_info,
strlen(plug->version_info), cs);
- table->field[11]->set_notnull();
+ table->field[12]->set_notnull();
}
else
- table->field[11]->set_null();
+ table->field[12]->set_null();
return schema_table_store_record(thd, table);
}
@@ -362,6 +366,7 @@ static struct show_privileges_st sys_privileges[]=
{"Insert", "Tables", "To insert data into tables"},
{"Lock tables","Databases","To use LOCK TABLES (together with SELECT privilege)"},
{"Process", "Server Admin", "To view the plain text of currently executing queries"},
+ {"Proxy", "Server Admin", "To make proxy user possible"},
{"References", "Databases,Tables", "To have references on tables"},
{"Reload", "Server Admin", "To reload or refresh tables, logs and privileges"},
{"Replication client","Server Admin","To ask where the slave or master servers are"},
@@ -506,12 +511,6 @@ find_files(THD *thd, List<LEX_STRING> *files, const char *db,
else if (wild_compare(uname, wild, 0))
continue;
}
- if (!(file_name=
- thd->make_lex_string(file_name, uname, file_name_len, TRUE)))
- {
- my_dirend(dirp);
- DBUG_RETURN(FIND_FILES_OOM);
- }
}
else
{
@@ -628,11 +627,11 @@ public:
return m_view_access_denied_message_ptr;
}
- bool handle_condition(THD *thd, uint sql_errno, const char */* sqlstate */,
+ bool handle_condition(THD *thd, uint sql_errno, const char * /* sqlstate */,
MYSQL_ERROR::enum_warning_level level,
- const char *message, MYSQL_ERROR **/* cond_hdl */)
+ const char *message, MYSQL_ERROR ** /* cond_hdl */)
{
- /*
+ /*
The handler does not handle the errors raised by itself.
At this point we know if top_view is really a view.
*/
@@ -642,7 +641,7 @@ public:
m_handling= TRUE;
bool is_handled;
-
+
switch (sql_errno)
{
case ER_TABLEACCESS_DENIED_ERROR:
@@ -703,17 +702,24 @@ mysqld_show_create(THD *thd, TABLE_LIST *table_list)
Metadata locks taken during SHOW CREATE should be released when
the statmement completes as it is an information statement.
*/
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
/* We want to preserve the tree for views. */
- thd->lex->view_prepare_mode= TRUE;
+ thd->lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW;
{
+ /*
+ Use open_tables() directly rather than open_normal_and_derived_tables().
+ This ensures that close_thread_tables() is not called if open tables fails
+ and the error is ignored. This allows us to handle broken views nicely.
+ */
+ uint counter;
Show_create_error_handler view_error_suppressor(thd, table_list);
thd->push_internal_handler(&view_error_suppressor);
bool open_error=
- open_normal_and_derived_tables(thd, table_list,
- MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL);
+ open_tables(thd, &table_list, &counter,
+ MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL) ||
+ mysql_handle_derived(thd->lex, &mysql_derived_prepare);
thd->pop_internal_handler();
if (open_error && (thd->killed || thd->is_error()))
goto exit;
@@ -1444,18 +1450,6 @@ int store_create_info(THD *thd, TABLE_LIST *table_list, String *packet,
if (!(thd->variables.sql_mode & MODE_NO_TABLE_OPTIONS) && !foreign_db_mode)
{
show_table_options= TRUE;
- /*
- Get possible table space definitions and append them
- to the CREATE TABLE statement
- */
-
- if ((for_str= file->get_tablespace_name(thd,0,0)))
- {
- packet->append(STRING_WITH_LEN(" /*!50100 TABLESPACE "));
- packet->append(for_str, strlen(for_str));
- packet->append(STRING_WITH_LEN(" STORAGE DISK */"));
- my_free(for_str);
- }
/*
IF check_create_info
@@ -1813,7 +1807,7 @@ public:
time_t start_time;
uint command;
const char *user,*host,*db,*proc_info,*state_info;
- char *query;
+ CSET_STRING query_string;
};
#ifdef HAVE_EXPLICIT_TEMPLATE_INSTANTIATION
@@ -1910,12 +1904,14 @@ void mysqld_list_processes(THD *thd,const char *user, bool verbose)
if (mysys_var)
mysql_mutex_unlock(&mysys_var->mutex);
- thd_info->query=0;
/* Lock THD mutex that protects its data when looking at it. */
if (tmp->query())
{
uint length= min(max_query_length, tmp->query_length());
- thd_info->query= (char*) thd->strmake(tmp->query(),length);
+ char *q= thd->strmake(tmp->query(),length);
+ /* Safety: in case strmake failed, we set length to 0. */
+ thd_info->query_string=
+ CSET_STRING(q, q ? length : 0, tmp->query_charset());
}
mysql_mutex_unlock(&tmp->LOCK_thd_data);
thd_info->start_time= tmp->start_time;
@@ -1943,7 +1939,8 @@ void mysqld_list_processes(THD *thd,const char *user, bool verbose)
else
protocol->store_null();
protocol->store(thd_info->state_info, system_charset_info);
- protocol->store(thd_info->query, system_charset_info);
+ protocol->store(thd_info->query_string.str(),
+ thd_info->query_string.charset());
if (protocol->write())
break; /* purecov: inspected */
}
@@ -2780,12 +2777,11 @@ bool schema_table_store_record(THD *thd, TABLE *table)
}
-int make_table_list(THD *thd, SELECT_LEX *sel,
- LEX_STRING *db_name, LEX_STRING *table_name)
+static int make_table_list(THD *thd, SELECT_LEX *sel,
+ LEX_STRING *db_name, LEX_STRING *table_name)
{
Table_ident *table_ident;
table_ident= new Table_ident(thd, *db_name, *table_name, 1);
- sel->init_query();
if (!sel->add_table_to_list(thd, table_ident, 0, 0, TL_READ, MDL_SHARED_READ))
return 1;
return 0;
@@ -3355,91 +3351,190 @@ make_table_name_list(THD *thd, List<LEX_STRING> *table_names, LEX *lex,
/**
- @brief Fill I_S table for SHOW COLUMNS|INDEX commands
+ Fill I_S table with data obtained by performing full-blown table open.
+
+ @param thd Thread handler.
+ @param is_show_fields_or_keys Indicates whether it is a legacy SHOW
+ COLUMNS or SHOW KEYS statement.
+ @param table TABLE object for I_S table to be filled.
+ @param schema_table I_S table description structure.
+ @param orig_db_name Database name.
+ @param orig_table_name Table name.
+ @param open_tables_state_backup Open_tables_state object which is used
+ to save/restore original status of
+ variables related to open tables state.
+ @param can_deadlock Indicates that deadlocks are possible
+ due to metadata locks, so to avoid
+ them we should not wait in case if
+ conflicting lock is present.
+
+ @retval FALSE - Success.
+ @retval TRUE - Failure.
+*/
+static bool
+fill_schema_table_by_open(THD *thd, bool is_show_fields_or_keys,
+ TABLE *table, ST_SCHEMA_TABLE *schema_table,
+ LEX_STRING *orig_db_name,
+ LEX_STRING *orig_table_name,
+ Open_tables_backup *open_tables_state_backup,
+ bool can_deadlock)
+{
+ Query_arena i_s_arena(thd->mem_root,
+ Query_arena::STMT_CONVENTIONAL_EXECUTION),
+ backup_arena, *old_arena;
+ LEX *old_lex= thd->lex, temp_lex, *lex;
+ LEX_STRING db_name, table_name;
+ TABLE_LIST *table_list;
+ bool result= true;
+
+ DBUG_ENTER("fill_schema_table_by_open");
+ /*
+ When a view is opened its structures are allocated on a permanent
+ statement arena and linked into the LEX tree for the current statement
+ (this happens even in cases when view is handled through TEMPTABLE
+ algorithm).
- @param[in] thd thread handler
- @param[in] tables TABLE_LIST for I_S table
- @param[in] schema_table pointer to I_S structure
- @param[in] can_deadlock Indicates that deadlocks are possible
- due to metadata locks, so to avoid
- them we should not wait in case if
- conflicting lock is present.
- @param[in] open_tables_state_backup pointer to Open_tables_backup object
- which is used to save|restore original
- status of variables related to
- open tables state
+ To prevent this process from unnecessary hogging of memory in the permanent
+ arena of our I_S query and to avoid damaging its LEX we use temporary
+ arena and LEX for table/view opening.
- @return Operation status
- @retval 0 success
- @retval 1 error
-*/
+ Use temporary arena instead of statement permanent arena. Also make
+ it active arena and save original one for successive restoring.
+ */
+ old_arena= thd->stmt_arena;
+ thd->stmt_arena= &i_s_arena;
+ thd->set_n_backup_active_arena(&i_s_arena, &backup_arena);
-static int
-fill_schema_show_cols_or_idxs(THD *thd, TABLE_LIST *tables,
- ST_SCHEMA_TABLE *schema_table,
- bool can_deadlock,
- Open_tables_backup *open_tables_state_backup)
-{
- LEX *lex= thd->lex;
- bool res;
- LEX_STRING tmp_lex_string, tmp_lex_string1, *db_name, *table_name;
- enum_sql_command save_sql_command= lex->sql_command;
- TABLE_LIST *show_table_list= tables->schema_select_lex->table_list.first;
- TABLE *table= tables->table;
- int error= 1;
- DBUG_ENTER("fill_schema_show");
+ /* Prepare temporary LEX. */
+ thd->lex= lex= &temp_lex;
+ lex_start(thd);
+
+ /* Disable constant subquery evaluation as we won't be locking tables. */
+ lex->context_analysis_only= CONTEXT_ANALYSIS_ONLY_VIEW;
+
+ /*
+ Some of process_table() functions rely on wildcard being passed from
+ old LEX (or at least being initialized).
+ */
+ lex->wild= old_lex->wild;
- lex->all_selects_list= tables->schema_select_lex;
/*
- Restore thd->temporary_tables to be able to process
- temporary tables(only for 'show index' & 'show columns').
- This should be changed when processing of temporary tables for
- I_S tables will be done.
+ Since make_table_list() might change database and table name passed
+ to it we create copies of orig_db_name and orig_table_name here.
+ These copies are used for make_table_list() while unaltered values
+ are passed to process_table() functions.
*/
- thd->temporary_tables= open_tables_state_backup->temporary_tables;
+ if (!thd->make_lex_string(&db_name, orig_db_name->str,
+ orig_db_name->length, FALSE) ||
+ !thd->make_lex_string(&table_name, orig_table_name->str,
+ orig_table_name->length, FALSE))
+ goto end;
+
+ /*
+ Create table list element for table to be open. Link it with the
+ temporary LEX. The latter is required to correctly open views and
+ produce table describing their structure.
+ */
+ if (make_table_list(thd, &lex->select_lex, &db_name, &table_name))
+ goto end;
+
+ table_list= lex->select_lex.table_list.first;
+
+ if (is_show_fields_or_keys)
+ {
+ /*
+ Restore thd->temporary_tables to be able to process
+ temporary tables (only for 'show index' & 'show columns').
+ This should be changed when processing of temporary tables for
+ I_S tables will be done.
+ */
+ thd->temporary_tables= open_tables_state_backup->temporary_tables;
+ }
+ else
+ {
+ /*
+ Apply optimization flags for table opening which are relevant for
+ this I_S table. We can't do this for SHOW COLUMNS/KEYS because of
+ backward compatibility.
+ */
+ table_list->i_s_requested_object= schema_table->i_s_requested_object;
+ }
+
/*
Let us set fake sql_command so views won't try to merge
themselves into main statement. If we don't do this,
SELECT * from information_schema.xxxx will cause problems.
- SQLCOM_SHOW_FIELDS is used because it satisfies 'only_view_structure()'
+ SQLCOM_SHOW_FIELDS is used because it satisfies
+ 'only_view_structure()'.
*/
lex->sql_command= SQLCOM_SHOW_FIELDS;
- res= open_normal_and_derived_tables(thd, show_table_list,
- (MYSQL_OPEN_IGNORE_FLUSH |
- MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
- (can_deadlock ?
- MYSQL_OPEN_FAIL_ON_MDL_CONFLICT : 0)));
- lex->sql_command= save_sql_command;
+ result= open_normal_and_derived_tables(thd, table_list,
+ (MYSQL_OPEN_IGNORE_FLUSH |
+ MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
+ (can_deadlock ?
+ MYSQL_OPEN_FAIL_ON_MDL_CONFLICT : 0)));
+ /*
+ Restore old value of sql_command back as it is being looked at in
+ process_table() function.
+ */
+ lex->sql_command= old_lex->sql_command;
DEBUG_SYNC(thd, "after_open_table_ignore_flush");
/*
- get_all_tables() returns 1 on failure and 0 on success thus
- return only these and not the result code of ::process_table()
-
- We should use show_table_list->alias instead of
- show_table_list->table_name because table_name
- could be changed during opening of I_S tables. It's safe
- to use alias because alias contains original table name
- in this case(this part of code is used only for
- 'show columns' & 'show statistics' commands).
+ XXX: show_table_list has a flag i_is_requested,
+ and when it's set, open_normal_and_derived_tables()
+ can return an error without setting an error message
+ in THD, which is a hack. This is why we have to
+ check for res, then for thd->is_error() and only then
+ for thd->main_da.sql_errno().
+
+ Again we don't do this for SHOW COLUMNS/KEYS because
+ of backward compatibility.
*/
- table_name= thd->make_lex_string(&tmp_lex_string1, show_table_list->alias,
- strlen(show_table_list->alias), FALSE);
- if (!show_table_list->view)
- db_name= thd->make_lex_string(&tmp_lex_string, show_table_list->db,
- show_table_list->db_length, FALSE);
- else
- db_name= &show_table_list->view_db;
+ if (!is_show_fields_or_keys && result && thd->is_error() &&
+ thd->stmt_da->sql_errno() == ER_NO_SUCH_TABLE)
+ {
+ /*
+ Hide error for a non-existing table.
+ For example, this error can occur when we use a where condition
+ with a db name and table, but the table does not exist.
+ */
+ result= false;
+ thd->clear_error();
+ }
+ else
+ {
+ result= schema_table->process_table(thd, table_list,
+ table, result,
+ orig_db_name,
+ orig_table_name);
+ }
+
+
+end:
+ lex->unit.cleanup();
+
+ /* Restore original LEX value, statement's arena and THD arena values. */
+ lex_end(thd->lex);
+
+ if (i_s_arena.free_list)
+ i_s_arena.free_items();
+
+ /*
+ For safety reset list of open temporary tables before closing
+ all tables open within this Open_tables_state.
+ */
+ thd->temporary_tables= NULL;
+ close_thread_tables(thd);
+ thd->mdl_context.rollback_to_savepoint(open_tables_state_backup->mdl_system_tables_svp);
+
+ thd->lex= old_lex;
+ thd->stmt_arena= old_arena;
+ thd->restore_active_arena(&i_s_arena, &backup_arena);
- error= test(schema_table->process_table(thd, show_table_list,
- table, res, db_name,
- table_name));
- thd->temporary_tables= 0;
- close_tables_for_reopen(thd, &show_table_list,
- open_tables_state_backup->mdl_system_tables_svp);
- DBUG_RETURN(error);
+ DBUG_RETURN(result);
}
@@ -3579,7 +3674,7 @@ try_acquire_high_prio_shared_mdl_lock(THD *thd, TABLE_LIST *table,
{
bool error;
table->mdl_request.init(MDL_key::TABLE, table->db, table->table_name,
- MDL_SHARED_HIGH_PRIO);
+ MDL_SHARED_HIGH_PRIO, MDL_TRANSACTION);
if (can_deadlock)
{
@@ -3789,6 +3884,45 @@ end:
/**
+ Trigger_error_handler is intended to intercept and silence SQL conditions
+ that might happen during trigger loading for SHOW statements.
+ The potential SQL conditions are:
+
+ - ER_PARSE_ERROR -- this error is thrown if a trigger definition file
+ is damaged or contains invalid CREATE TRIGGER statement. That should
+ not happen in normal life.
+
+ - ER_TRG_NO_DEFINER -- this warning is thrown when we're loading a
+ trigger created/imported in/from the version of MySQL, which does not
+ support trigger definers.
+
+ - ER_TRG_NO_CREATION_CTX -- this warning is thrown when we're loading a
+ trigger created/imported in/from the version of MySQL, which does not
+ support trigger creation contexts.
+*/
+
+class Trigger_error_handler : public Internal_error_handler
+{
+public:
+ bool handle_condition(THD *thd,
+ uint sql_errno,
+ const char* sqlstate,
+ MYSQL_ERROR::enum_warning_level level,
+ const char* msg,
+ MYSQL_ERROR ** cond_hdl)
+ {
+ if (sql_errno == ER_PARSE_ERROR ||
+ sql_errno == ER_TRG_NO_DEFINER ||
+ sql_errno == ER_TRG_NO_CREATION_CTX)
+ return true;
+
+ return false;
+ }
+};
+
+
+
+/**
@brief Fill I_S tables whose data are retrieved
from frm files and storage engine
@@ -3811,10 +3945,8 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
{
LEX *lex= thd->lex;
TABLE *table= tables->table;
- SELECT_LEX *old_all_select_lex= lex->all_selects_list;
SELECT_LEX *lsel= tables->schema_select_lex;
ST_SCHEMA_TABLE *schema_table= tables->schema_table;
- SELECT_LEX sel;
LOOKUP_FIELD_VALUES lookup_field_vals;
LEX_STRING *db_name, *table_name;
bool with_i_schema;
@@ -3822,11 +3954,8 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
List<LEX_STRING> db_names;
List_iterator_fast<LEX_STRING> it(db_names);
COND *partial_cond= 0;
- uint derived_tables= lex->derived_tables;
int error= 1;
Open_tables_backup open_tables_state_backup;
- bool save_view_prepare_mode= lex->view_prepare_mode;
- Query_tables_list query_tables_list_backup;
#ifndef NO_EMBEDDED_ACCESS_CHECKS
Security_context *sctx= thd->security_ctx;
#endif
@@ -3845,15 +3974,6 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
*/
can_deadlock= thd->mdl_context.has_locks();
- lex->view_prepare_mode= TRUE;
- lex->reset_n_backup_query_tables_list(&query_tables_list_backup);
- /*
- Restore Query_tables_list::sql_command value, which was reset
- above, as ST_SCHEMA_TABLE::process_table() functions often rely
- that this value reflects which SHOW statement is executed.
- */
- lex->sql_command= query_tables_list_backup.sql_command;
-
/*
We should not introduce deadlocks even if we already have some
tables open and locked, since we won't lock tables which we will
@@ -3873,9 +3993,19 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
*/
if (lsel && lsel->table_list.first)
{
- error= fill_schema_show_cols_or_idxs(thd, tables, schema_table,
- can_deadlock,
- &open_tables_state_backup);
+ LEX_STRING db_name, table_name;
+
+ db_name.str= lsel->table_list.first->db;
+ db_name.length= lsel->table_list.first->db_length;
+
+ table_name.str= lsel->table_list.first->table_name;
+ table_name.length= lsel->table_list.first->table_name_length;
+
+ error= fill_schema_table_by_open(thd, TRUE,
+ table, schema_table,
+ &db_name, &table_name,
+ &open_tables_state_backup,
+ can_deadlock);
goto err;
}
@@ -3937,7 +4067,6 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
acl_get(sctx->host, sctx->ip, sctx->priv_user, db_name->str, 0))
#endif
{
- thd->no_warnings_for_error= 1;
List<LEX_STRING> table_names;
int res= make_table_name_list(thd, &table_names, lex,
&lookup_field_vals,
@@ -3986,77 +4115,34 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
if (!(table_open_method & ~OPEN_FRM_ONLY) &&
!with_i_schema)
{
- if (!fill_schema_table_from_frm(thd, tables, schema_table, db_name,
- table_name, schema_table_idx,
- can_deadlock))
+ /*
+ Here we need to filter out warnings, which can happen
+ during loading of triggers in fill_schema_table_from_frm(),
+ because we don't need those warnings to pollute output of
+ SELECT from I_S / SHOW-statements.
+ */
+
+ Trigger_error_handler err_handler;
+ thd->push_internal_handler(&err_handler);
+
+ int res= fill_schema_table_from_frm(thd, tables, schema_table,
+ db_name, table_name,
+ schema_table_idx,
+ can_deadlock);
+
+ thd->pop_internal_handler();
+
+ if (!res)
continue;
}
- int res;
- LEX_STRING tmp_lex_string, orig_db_name;
- /*
- Set the parent lex of 'sel' because it is needed by
- sel.init_query() which is called inside make_table_list.
- */
- thd->no_warnings_for_error= 1;
- sel.parent_lex= lex;
- /* db_name can be changed in make_table_list() func */
- if (!thd->make_lex_string(&orig_db_name, db_name->str,
- db_name->length, FALSE))
- goto err;
- if (make_table_list(thd, &sel, db_name, table_name))
- goto err;
- TABLE_LIST *show_table_list= sel.table_list.first;
- lex->all_selects_list= &sel;
- lex->derived_tables= 0;
- lex->sql_command= SQLCOM_SHOW_FIELDS;
- show_table_list->i_s_requested_object=
- schema_table->i_s_requested_object;
DEBUG_SYNC(thd, "before_open_in_get_all_tables");
- res= open_normal_and_derived_tables(thd, show_table_list,
- (MYSQL_OPEN_IGNORE_FLUSH |
- MYSQL_OPEN_FORCE_SHARED_HIGH_PRIO_MDL |
- (can_deadlock ? MYSQL_OPEN_FAIL_ON_MDL_CONFLICT : 0)));
- lex->sql_command= query_tables_list_backup.sql_command;
- /*
- XXX: show_table_list has a flag i_is_requested,
- and when it's set, open_normal_and_derived_tables()
- can return an error without setting an error message
- in THD, which is a hack. This is why we have to
- check for res, then for thd->is_error() only then
- for thd->stmt_da->sql_errno().
- */
- if (res && thd->is_error() &&
- thd->stmt_da->sql_errno() == ER_NO_SUCH_TABLE)
- {
- /*
- Hide error for not existing table.
- This error can occur for example when we use
- where condition with db name and table name and this
- table does not exist.
- */
- res= 0;
- thd->clear_error();
- }
- else
- {
- /*
- We should use show_table_list->alias instead of
- show_table_list->table_name because table_name
- could be changed during opening of I_S tables. It's safe
- to use alias because alias contains original table name
- in this case.
- */
- thd->make_lex_string(&tmp_lex_string, show_table_list->alias,
- strlen(show_table_list->alias), FALSE);
- res= schema_table->process_table(thd, show_table_list, table,
- res, &orig_db_name,
- &tmp_lex_string);
- close_tables_for_reopen(thd, &show_table_list,
- open_tables_state_backup.mdl_system_tables_svp);
- }
- DBUG_ASSERT(!lex->query_tables_own_last);
- if (res)
+
+ if (fill_schema_table_by_open(thd, FALSE,
+ table, schema_table,
+ db_name, table_name,
+ &open_tables_state_backup,
+ can_deadlock))
goto err;
}
}
@@ -4072,10 +4158,7 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond)
error= 0;
err:
thd->restore_backup_open_tables_state(&open_tables_state_backup);
- lex->restore_backup_query_tables_list(&query_tables_list_backup);
- lex->derived_tables= derived_tables;
- lex->all_selects_list= old_all_select_lex;
- lex->view_prepare_mode= save_view_prepare_mode;
+
DBUG_RETURN(error);
}
@@ -4171,6 +4254,7 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
{
const char *tmp_buff;
MYSQL_TIME time;
+ int info_error= 0;
CHARSET_INFO *cs= system_charset_info;
DBUG_ENTER("get_schema_tables_record");
@@ -4178,22 +4262,21 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
table->field[0]->store(STRING_WITH_LEN("def"), cs);
table->field[1]->store(db_name->str, db_name->length, cs);
table->field[2]->store(table_name->str, table_name->length, cs);
+
if (res)
{
- /*
- there was errors during opening tables
- */
- const char *error= thd->is_error() ? thd->stmt_da->message() : "";
+ /* There was a table open error, so set the table type and return */
if (tables->view)
table->field[3]->store(STRING_WITH_LEN("VIEW"), cs);
else if (tables->schema_table)
table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs);
else
table->field[3]->store(STRING_WITH_LEN("BASE TABLE"), cs);
- table->field[20]->store(error, strlen(error), cs);
- thd->clear_error();
+
+ goto err;
}
- else if (tables->view)
+
+ if (tables->view)
{
table->field[3]->store(STRING_WITH_LEN("VIEW"), cs);
table->field[20]->store(STRING_WITH_LEN("VIEW"), cs);
@@ -4209,6 +4292,7 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
#ifdef WITH_PARTITION_STORAGE_ENGINE
bool is_partitioned= FALSE;
#endif
+
if (share->tmp_table == SYSTEM_TMP_TABLE)
table->field[3]->store(STRING_WITH_LEN("SYSTEM VIEW"), cs);
else if (share->tmp_table)
@@ -4222,6 +4306,9 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
continue;
table->field[i]->set_notnull();
}
+
+ /* Collect table info from the table share */
+
#ifdef WITH_PARTITION_STORAGE_ENGINE
if (share->db_type() == partition_hton &&
share->partition_info_str_len)
@@ -4230,73 +4317,96 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
is_partitioned= TRUE;
}
#endif
+
tmp_buff= (char *) ha_resolve_storage_engine_name(tmp_db_type);
table->field[4]->store(tmp_buff, strlen(tmp_buff), cs);
table->field[5]->store((longlong) share->frm_version, TRUE);
str.length(0);
+
if (share->min_rows)
{
str.qs_append(STRING_WITH_LEN(" min_rows="));
str.qs_append(share->min_rows);
}
+
if (share->max_rows)
{
str.qs_append(STRING_WITH_LEN(" max_rows="));
str.qs_append(share->max_rows);
}
+
if (share->avg_row_length)
{
str.qs_append(STRING_WITH_LEN(" avg_row_length="));
str.qs_append(share->avg_row_length);
}
+
if (share->db_create_options & HA_OPTION_PACK_KEYS)
str.qs_append(STRING_WITH_LEN(" pack_keys=1"));
+
if (share->db_create_options & HA_OPTION_NO_PACK_KEYS)
str.qs_append(STRING_WITH_LEN(" pack_keys=0"));
+
/* We use CHECKSUM, instead of TABLE_CHECKSUM, for backward compability */
if (share->db_create_options & HA_OPTION_CHECKSUM)
str.qs_append(STRING_WITH_LEN(" checksum=1"));
+
if (share->page_checksum != HA_CHOICE_UNDEF)
{
str.qs_append(STRING_WITH_LEN(" page_checksum="));
str.qs_append(ha_choice_values[(uint) share->page_checksum]);
}
+
if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE)
str.qs_append(STRING_WITH_LEN(" delay_key_write=1"));
+
if (share->row_type != ROW_TYPE_DEFAULT)
{
str.qs_append(STRING_WITH_LEN(" row_format="));
str.qs_append(ha_row_type[(uint) share->row_type]);
}
+
if (share->key_block_size)
{
str.qs_append(STRING_WITH_LEN(" key_block_size="));
str.qs_append(share->key_block_size);
}
+
#ifdef WITH_PARTITION_STORAGE_ENGINE
if (is_partitioned)
str.qs_append(STRING_WITH_LEN(" partitioned"));
#endif
+
if (share->transactional != HA_CHOICE_UNDEF)
{
str.qs_append(STRING_WITH_LEN(" transactional="));
str.qs_append(ha_choice_values[(uint) share->transactional]);
}
append_create_options(thd, &str, share->option_list);
+
if (str.length())
table->field[19]->store(str.ptr()+1, str.length()-1, cs);
tmp_buff= (share->table_charset ?
share->table_charset->name : "default");
+
table->field[17]->store(tmp_buff, strlen(tmp_buff), cs);
if (share->comment.str)
table->field[20]->store(share->comment.str, share->comment.length, cs);
+ /* Collect table info from the storage engine */
+
if(file)
{
- file->info(HA_STATUS_VARIABLE | HA_STATUS_TIME | HA_STATUS_AUTO);
+ /* If info() fails, then there's nothing else to do */
+ if ((info_error= file->info(HA_STATUS_VARIABLE |
+ HA_STATUS_TIME |
+ HA_STATUS_VARIABLE_EXTRA |
+ HA_STATUS_AUTO)) != 0)
+ goto err;
+
enum row_type row_type = file->get_row_type();
switch (row_type) {
case ROW_TYPE_NOT_USED:
@@ -4325,7 +4435,9 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
tmp_buff= "Page";
break;
}
+
table->field[6]->store(tmp_buff, strlen(tmp_buff), cs);
+
if (!tables->schema_table)
{
table->field[7]->store((longlong) file->stats.records, TRUE);
@@ -4374,6 +4486,26 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables,
}
}
}
+
+err:
+ if (res || info_error)
+ {
+ /*
+ If an error was encountered, push a warning, set the TABLE COMMENT
+ column with the error text, and clear the error so that the operation
+ can continue.
+ */
+ const char *error= thd->is_error() ? thd->stmt_da->message() : "";
+ table->field[20]->store(error, strlen(error), cs);
+
+ if (thd->is_error())
+ {
+ push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ thd->stmt_da->sql_errno(), thd->stmt_da->message());
+ thd->clear_error();
+ }
+ }
+
DBUG_RETURN(schema_table_store_record(thd, table));
}
@@ -5337,18 +5469,29 @@ static int get_schema_views_record(THD *thd, TABLE_LIST *tables,
else
table->field[4]->store(STRING_WITH_LEN("NONE"), cs);
- if (table->pos_in_table_list->table_open_method &
- OPEN_FULL_TABLE)
+ /*
+ Only try to fill in the information about view updatability
+ if it is requested as part of the top-level query (i.e.
+ it's select * from i_s.views, as opposed to, say, select
+ security_type from i_s.views). Do not try to access the
+ underlying tables if there was an error when opening the
+ view: all underlying tables are released back to the table
+ definition cache on error inside open_normal_and_derived_tables().
+ If a field is not assigned explicitly, it defaults to NULL.
+ */
+ if (res == FALSE &&
+ table->pos_in_table_list->table_open_method & OPEN_FULL_TABLE)
{
updatable_view= 0;
if (tables->algorithm != VIEW_ALGORITHM_TMPTABLE)
{
/*
- We should use tables->view->select_lex.item_list here and
- can not use Field_iterator_view because the view always uses
- temporary algorithm during opening for I_S and
- TABLE_LIST fields 'field_translation' & 'field_translation_end'
- are uninitialized is this case.
+ We should use tables->view->select_lex.item_list here
+ and can not use Field_iterator_view because the view
+ always uses temporary algorithm during opening for I_S
+ and TABLE_LIST fields 'field_translation'
+ & 'field_translation_end' are uninitialized is this
+ case.
*/
List<Item> *fields= &tables->view->select_lex.item_list;
List_iterator<Item> it(*fields);
@@ -5471,8 +5614,8 @@ static int get_schema_constraints_record(THD *thd, TABLE_LIST *tables,
while ((f_key_info=it++))
{
if (store_constraints(thd, table, db_name, table_name,
- f_key_info->forein_id->str,
- strlen(f_key_info->forein_id->str),
+ f_key_info->foreign_id->str,
+ strlen(f_key_info->foreign_id->str),
"FOREIGN KEY", 11))
DBUG_RETURN(1);
}
@@ -5671,8 +5814,8 @@ static int get_schema_key_column_usage_record(THD *thd,
f_idx++;
restore_record(table, s->default_values);
store_key_column_usage(table, db_name, table_name,
- f_key_info->forein_id->str,
- f_key_info->forein_id->length,
+ f_key_info->foreign_id->str,
+ f_key_info->foreign_id->length,
f_info->str, f_info->length,
(longlong) f_idx);
table->field[8]->store((longlong) f_idx, TRUE);
@@ -5832,12 +5975,9 @@ static void store_schema_partitions_record(THD *thd, TABLE *schema_table,
strlen(part_elem->tablespace_name), cs);
else
{
- char *ts= showing_table->file->get_tablespace_name(thd,0,0);
+ char *ts= showing_table->s->tablespace;
if(ts)
- {
table->field[24]->store(ts, strlen(ts), cs);
- my_free(ts);
- }
else
table->field[24]->set_null();
}
@@ -6461,8 +6601,8 @@ get_referential_constraints_record(THD *thd, TABLE_LIST *tables,
table->field[0]->store(STRING_WITH_LEN("def"), cs);
table->field[1]->store(db_name->str, db_name->length, cs);
table->field[9]->store(table_name->str, table_name->length, cs);
- table->field[2]->store(f_key_info->forein_id->str,
- f_key_info->forein_id->length, cs);
+ table->field[2]->store(f_key_info->foreign_id->str,
+ f_key_info->foreign_id->length, cs);
table->field[3]->store(STRING_WITH_LEN("def"), cs);
table->field[4]->store(f_key_info->referenced_db->str,
f_key_info->referenced_db->length, cs);
@@ -7086,6 +7226,92 @@ int make_schema_select(THD *thd, SELECT_LEX *sel,
}
+/**
+ Fill INFORMATION_SCHEMA-table, leave correct Diagnostics_area /
+ Warning_info state after itself.
+
+ This function is a wrapper around ST_SCHEMA_TABLE::fill_table(), which
+ may "partially silence" some errors. The thing is that during
+ fill_table() many errors might be emitted. These errors stem from the
+ nature of fill_table().
+
+ For example, SELECT ... FROM INFORMATION_SCHEMA.xxx WHERE TABLE_NAME = 'xxx'
+ results in a number of 'Table <db name>.xxx does not exist' errors,
+ because fill_table() tries to open the 'xxx' table in every possible
+ database.
+
+ Those errors are cleared (the error status is cleared from
+ Diagnostics_area) inside fill_table(), but they remain in Warning_info
+ (Warning_info is not cleared because it may contain useful warnings).
+
+ This function is responsible for making sure that Warning_info does not
+ contain warnings corresponding to the cleared errors.
+
+ @note: THD::no_warnings_for_error used to be set before calling
+ fill_table(), thus those errors didn't go to Warning_info. This is not
+ the case now (THD::no_warnings_for_error was eliminated as a hack), so we
+ need to take care of those warnings here.
+
+ @param thd Thread context.
+ @param table_list I_S table.
+ @param join_table JOIN/SELECT table.
+
+ @return Error status.
+ @retval TRUE Error.
+ @retval FALSE Success.
+*/
+static bool do_fill_table(THD *thd,
+ TABLE_LIST *table_list,
+ JOIN_TAB *join_table)
+{
+ // NOTE: fill_table() may generate many "useless" warnings, which will be
+ // ignored afterwards. On the other hand, there might be "useful"
+ // warnings, which should be presented to the user. Warning_info usually
+ // stores no more than THD::variables.max_error_count warnings.
+ // The problem is that "useless warnings" may occupy all the slots in the
+ // Warning_info, so "useful warnings" get rejected. In order to avoid
+ // that problem we create a Warning_info instance, which is capable of
+ // storing "unlimited" number of warnings.
+ Warning_info wi(thd->query_id, true);
+ Warning_info *wi_saved= thd->warning_info;
+
+ thd->warning_info= &wi;
+
+ bool res= table_list->schema_table->fill_table(
+ thd, table_list, join_table->select_cond);
+
+ thd->warning_info= wi_saved;
+
+ // Pass an error if any.
+
+ if (thd->stmt_da->is_error())
+ {
+ thd->warning_info->push_warning(thd,
+ thd->stmt_da->sql_errno(),
+ thd->stmt_da->get_sqlstate(),
+ MYSQL_ERROR::WARN_LEVEL_ERROR,
+ thd->stmt_da->message());
+ }
+
+ // Pass warnings (if any).
+ //
+ // Filter out warnings with WARN_LEVEL_ERROR level, because they
+ // correspond to the errors which were filtered out in fill_table().
+
+
+ List_iterator_fast<MYSQL_ERROR> it(wi.warn_list());
+ MYSQL_ERROR *err;
+
+ while ((err= it++))
+ {
+ if (err->get_level() != MYSQL_ERROR::WARN_LEVEL_ERROR)
+ thd->warning_info->push_warning(thd, err);
+ }
+
+ return res;
+}
+
+
/*
Fill temporary schema tables before SELECT
@@ -7108,7 +7334,6 @@ bool get_schema_tables_result(JOIN *join,
bool result= 0;
DBUG_ENTER("get_schema_tables_result");
- thd->no_warnings_for_error= 1;
for (JOIN_TAB *tab= join->join_tab; tab < tmp_join_tab; tab++)
{
if (!tab->table || !tab->table->pos_in_table_list)
@@ -7159,8 +7384,7 @@ bool get_schema_tables_result(JOIN *join,
else
table_list->table->file->stats.records= 0;
- if (table_list->schema_table->fill_table(thd, table_list,
- tab->select_cond))
+ if (do_fill_table(thd, table_list, tab))
{
result= 1;
join->error= 1;
@@ -7172,7 +7396,6 @@ bool get_schema_tables_result(JOIN *join,
table_list->schema_table_state= executed_place;
}
}
- thd->no_warnings_for_error= 0;
DBUG_RETURN(result);
}
@@ -7789,8 +8012,9 @@ ST_FIELD_INFO plugin_fields_info[]=
{"PLUGIN_LIBRARY_VERSION", 20, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE},
{"PLUGIN_AUTHOR", NAME_CHAR_LEN, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE},
{"PLUGIN_DESCRIPTION", 65535, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE},
- {"PLUGIN_LICENSE", 80, MYSQL_TYPE_STRING, 0, 1, "License", SKIP_OPEN_TABLE},
- {"PLUGIN_MATURITY", 12, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE},
+ {"PLUGIN_LICENSE", 80, MYSQL_TYPE_STRING, 0, 0, "License", SKIP_OPEN_TABLE},
+ {"LOAD_OPTION", 64, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE},
+ {"PLUGIN_MATURITY", 12, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE},
{"PLUGIN_AUTH_VERSION", 80, MYSQL_TYPE_STRING, 0, 1, 0, SKIP_OPEN_TABLE},
{0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}
};
@@ -8349,7 +8573,7 @@ bool show_create_trigger(THD *thd, const sp_name *trg_name)
Metadata locks taken during SHOW CREATE TRIGGER should be released when
the statement completes as it is an information statement.
*/
- MDL_ticket *mdl_savepoint= thd->mdl_context.mdl_savepoint();
+ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint();
/*
Open the table by name in order to load Table_triggers_list object.
@@ -8450,6 +8674,7 @@ void initialize_information_schema_acl()
&is_internal_schema_access);
}
+#ifdef WITH_PARTITION_STORAGE_ENGINE
/*
Convert a string in character set in column character set format
to utf8 character set if possible, the utf8 character set string
@@ -8541,3 +8766,4 @@ static void get_cs_converted_string_value(THD *thd,
}
return;
}
+#endif
diff --git a/sql/sql_show.h b/sql/sql_show.h
index d1323ede8c1..de8f2525baa 100644
--- a/sql/sql_show.h
+++ b/sql/sql_show.h
@@ -104,7 +104,6 @@ bool mysqld_show_storage_engines(THD *thd);
bool mysqld_show_authors(THD *thd);
bool mysqld_show_contributors(THD *thd);
bool mysqld_show_privileges(THD *thd);
-bool mysqld_show_column_types(THD *thd);
char *make_backup_log_name(char *buff, const char *name, const char* log_ext);
void calc_sum_of_all_status(STATUS_VAR *to);
void append_definer(THD *thd, String *buffer, const LEX_STRING *definer_user,
diff --git a/sql/sql_string.cc b/sql/sql_string.cc
index c5544164dbf..f6025390cb2 100644
--- a/sql/sql_string.cc
+++ b/sql/sql_string.cc
@@ -54,11 +54,33 @@ bool String::real_alloc(uint32 length)
}
-/*
-** Check that string is big enough. Set string[alloc_length] to 0
-** (for C functions)
-*/
+/**
+ Allocates a new buffer on the heap for this String.
+
+ - If the String's internal buffer is privately owned and heap allocated,
+ one of the following is performed.
+
+ - If the requested length is greater than what fits in the buffer, a new
+ buffer is allocated, data moved and the old buffer freed.
+
+ - If the requested length is less or equal to what fits in the buffer, a
+ null character is inserted at the appropriate position.
+ - If the String does not keep a private buffer on the heap, such a buffer
+ will be allocated and the string copied accoring to its length, as found
+ in String::length().
+
+ For C compatibility, the new string buffer is null terminated.
+
+ @param alloc_length The requested string size in characters, excluding any
+ null terminator.
+
+ @retval false Either the copy operation is complete or, if the size of the
+ new buffer is smaller than the currently allocated buffer (if one exists),
+ no allocation occured.
+
+ @retval true An error occured when attempting to allocate memory.
+*/
bool String::realloc(uint32 alloc_length)
{
if (Alloced_length <= alloc_length)
@@ -131,6 +153,17 @@ bool String::copy()
return FALSE;
}
+/**
+ Copies the internal buffer from str. If this String has a private heap
+ allocated buffer where new data does not fit, a new buffer is allocated
+ before copying and the old buffer freed. Character set information is also
+ copied.
+
+ @param str The string whose internal buffer is to be copied.
+
+ @retval false Success.
+ @retval true Memory allocation failed.
+*/
bool String::copy(const String &str)
{
if (alloc(str.str_length))
@@ -222,8 +255,8 @@ bool String::copy_aligned(const char *str,uint32 arg_length, uint32 offset,
CHARSET_INFO *cs)
{
/* How many bytes are in incomplete character */
- offset= cs->mbmaxlen - offset; /* How many zeros we should prepend */
- DBUG_ASSERT(offset && offset != cs->mbmaxlen);
+ offset= cs->mbminlen - offset; /* How many zeros we should prepend */
+ DBUG_ASSERT(offset && offset != cs->mbminlen);
uint32 aligned_length= arg_length + offset;
if (alloc(aligned_length))
diff --git a/sql/sql_string.h b/sql/sql_string.h
index c25a9cd8214..e5e7bfb1e0c 100644
--- a/sql/sql_string.h
+++ b/sql/sql_string.h
@@ -99,9 +99,13 @@ public:
}
static void *operator new(size_t size, MEM_ROOT *mem_root) throw ()
{ return (void*) alloc_root(mem_root, (uint) size); }
- static void operator delete(void *ptr_arg,size_t size)
- { TRASH(ptr_arg, size); }
- static void operator delete(void *ptr_arg, MEM_ROOT *mem_root)
+ static void operator delete(void *ptr_arg, size_t size)
+ {
+ (void) ptr_arg;
+ (void) size;
+ TRASH(ptr_arg, size);
+ }
+ static void operator delete(void *, MEM_ROOT *)
{ /* never called */ }
~String() { free(); }
@@ -117,6 +121,9 @@ public:
inline const char *ptr() const { return Ptr; }
inline char *c_ptr()
{
+ DBUG_ASSERT(!alloced || !Ptr || !Alloced_length ||
+ (Alloced_length >= (str_length + 1)));
+
if (!Ptr || Ptr[str_length]) /* Should be safe */
(void) realloc(str_length);
return Ptr;
@@ -152,6 +159,16 @@ public:
Alloced_length=0;
str_charset=str.str_charset;
}
+
+
+ /**
+ Points the internal buffer to the supplied one. The old buffer is freed.
+ @param str Pointer to the new buffer.
+ @param arg_length Length of the new buffer in characters, excluding any
+ null character.
+ @param cs Character set to use for interpreting string data.
+ @note The new buffer will not be null terminated.
+ */
inline void set(char *str,uint32 arg_length, CHARSET_INFO *cs)
{
free();
@@ -273,8 +290,12 @@ public:
CHARSET_INFO *csto, uint *errors);
bool append(const String &s);
bool append(const char *s);
- bool append(const char *s,uint32 arg_length);
- bool append(const char *s,uint32 arg_length, CHARSET_INFO *cs);
+ bool append(LEX_STRING *ls)
+ {
+ return append(ls->str, ls->length);
+ }
+ bool append(const char *s, uint32 arg_length);
+ bool append(const char *s, uint32 arg_length, CHARSET_INFO *cs);
bool append_ulonglong(ulonglong val);
bool append(IO_CACHE* file, uint32 arg_length);
bool append_with_prefill(const char *s, uint32 arg_length,
diff --git a/sql/sql_table.cc b/sql/sql_table.cc
index 1a7162313f5..7d59598d606 100644
--- a/sql/sql_table.cc
+++ b/sql/sql_table.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -22,10 +22,8 @@
#include "sql_rename.h" // do_rename
#include "sql_parse.h" // test_if_data_home_dir
#include "sql_cache.h" // query_cache_*
-#include "sql_base.h" // open_temporary_table, lock_table_names
-#include "lock.h" // wait_if_global_read_lock
- // start_waiting_global_read_lock,
- // mysql_unlock_tables
+#include "sql_base.h" // open_table_uncached, lock_table_names
+#include "lock.h" // mysql_unlock_tables
#include "strfunc.h" // find_type2, find_set
#include "sql_view.h" // view_checksum
#include "sql_truncate.h" // regenerate_locked_table
@@ -368,7 +366,11 @@ uint explain_filename(THD* thd,
Table name length.
*/
-uint filename_to_tablename(const char *from, char *to, uint to_length)
+uint filename_to_tablename(const char *from, char *to, uint to_length
+#ifndef DBUG_OFF
+ , bool stay_quiet
+#endif /* DBUG_OFF */
+ )
{
uint errors;
size_t res;
@@ -388,7 +390,13 @@ uint filename_to_tablename(const char *from, char *to, uint to_length)
{
res= (strxnmov(to, to_length, MYSQL50_TABLE_NAME_PREFIX, from, NullS) -
to);
- sql_print_error("Invalid (old?) table or database name '%s'", from);
+#ifndef DBUG_OFF
+ if (!stay_quiet) {
+#endif /* DBUG_OFF */
+ sql_print_error("Invalid (old?) table or database name '%s'", from);
+#ifndef DBUG_OFF
+ }
+#endif /* DBUG_OFF */
/*
TODO: add a stored procedure for fix table and database names,
and mention its name in error log.
@@ -1720,8 +1728,6 @@ bool mysql_write_frm(ALTER_PARTITION_PARAM_TYPE *lpt, uint flags)
CHF_DELETE_FLAG, NULL) ||
deactivate_ddl_log_entry(part_info->frm_log_entry->entry_pos) ||
(sync_ddl_log(), FALSE) ||
-#endif
-#ifdef WITH_PARTITION_STORAGE_ENGINE
mysql_file_rename(key_file_frm,
shadow_frm_name, frm_name, MYF(MY_WME)) ||
lpt->table->file->ha_create_handler_files(path, shadow_path,
@@ -1848,64 +1854,117 @@ bool mysql_rm_table(THD *thd,TABLE_LIST *tables, my_bool if_exists,
{
bool error;
Drop_table_error_handler err_handler;
+ TABLE_LIST *table;
DBUG_ENTER("mysql_rm_table");
- /* mark for close and remove all cached entries */
+ /* Disable drop of enabled log tables, must be done before name locking */
+ for (table= tables; table; table= table->next_local)
+ {
+ if (check_if_log_table(table->db_length, table->db,
+ table->table_name_length, table->table_name, true))
+ {
+ my_error(ER_BAD_LOG_STATEMENT, MYF(0), "DROP");
+ DBUG_RETURN(true);
+ }
+ }
+
+ mysql_ha_rm_tables(thd, tables);
if (!drop_temporary)
{
- if (!thd->locked_tables_mode &&
- thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, TRUE))
- DBUG_RETURN(TRUE);
+ if (!thd->locked_tables_mode)
+ {
+ if (lock_table_names(thd, tables, NULL, thd->variables.lock_wait_timeout,
+ MYSQL_OPEN_SKIP_TEMPORARY))
+ DBUG_RETURN(true);
+ for (table= tables; table; table= table->next_local)
+ tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table->db, table->table_name,
+ false);
+ }
+ else
+ {
+ for (table= tables; table; table= table->next_local)
+ if (table->open_type != OT_BASE_ONLY &&
+ find_temporary_table(thd, table))
+ {
+ /*
+ A temporary table.
+
+ Don't try to find a corresponding MDL lock or assign it
+ to table->mdl_request.ticket. There can't be metadata
+ locks for temporary tables: they are local to the session.
+
+ Later in this function we release the MDL lock only if
+ table->mdl_requeset.ticket is not NULL. Thus here we
+ ensure that we won't release the metadata lock on the base
+ table locked with LOCK TABLES as a side effect of temporary
+ table drop.
+ */
+ DBUG_ASSERT(table->mdl_request.ticket == NULL);
+ }
+ else
+ {
+ /*
+ Not a temporary table.
+
+ Since 'tables' list can't contain duplicates (this is ensured
+ by parser) it is safe to cache pointer to the TABLE instances
+ in its elements.
+ */
+ table->table= find_table_for_mdl_upgrade(thd, table->db,
+ table->table_name, false);
+ if (!table->table)
+ DBUG_RETURN(true);
+ table->mdl_request.ticket= table->table->mdl_ticket;
+ }
+ }
}
+ /* mark for close and remove all cached entries */
thd->push_internal_handler(&err_handler);
- error= mysql_rm_table_part2(thd, tables, if_exists, drop_temporary, 0, 0);
+ error= mysql_rm_table_no_locks(thd, tables, if_exists, drop_temporary,
+ false, false);
thd->pop_internal_handler();
- if (thd->global_read_lock.has_protection())
- thd->global_read_lock.start_waiting_global_read_lock(thd);
-
if (error)
DBUG_RETURN(TRUE);
my_ok(thd);
DBUG_RETURN(FALSE);
}
-/*
- Execute the drop of a normal or temporary table
-
- SYNOPSIS
- mysql_rm_table_part2()
- thd Thread handler
- tables Tables to drop
- if_exists If set, don't give an error if table doesn't exists.
- In this case we give an warning of level 'NOTE'
- drop_temporary Only drop temporary tables
- drop_view Allow to delete VIEW .frm
- dont_log_query Don't write query to log files. This will also not
- generate warnings if the handler files doesn't exists
-
- TODO:
- When logging to the binary log, we should log
- tmp_tables and transactional tables as separate statements if we
- are in a transaction; This is needed to get these tables into the
- cached binary log that is only written on COMMIT.
-
- The current code only writes DROP statements that only uses temporary
- tables to the cache binary log. This should be ok on most cases, but
- not all.
- RETURN
- 0 ok
- 1 Error
- -1 Thread was killed
+/**
+ Execute the drop of a normal or temporary table.
+
+ @param thd Thread handler
+ @param tables Tables to drop
+ @param if_exists If set, don't give an error if table doesn't exists.
+ In this case we give an warning of level 'NOTE'
+ @param drop_temporary Only drop temporary tables
+ @param drop_view Allow to delete VIEW .frm
+ @param dont_log_query Don't write query to log files. This will also not
+ generate warnings if the handler files doesn't exists
+
+ @retval 0 ok
+ @retval 1 Error
+ @retval -1 Thread was killed
+
+ @note This function assumes that metadata locks have already been taken.
+ It is also assumed that the tables have been removed from TDC.
+
+ @todo When logging to the binary log, we should log
+ tmp_tables and transactional tables as separate statements if we
+ are in a transaction; This is needed to get these tables into the
+ cached binary log that is only written on COMMIT.
+ The current code only writes DROP statements that only uses temporary
+ tables to the cache binary log. This should be ok on most cases, but
+ not all.
*/
-int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
- bool drop_temporary, bool drop_view,
- bool dont_log_query)
+int mysql_rm_table_no_locks(THD *thd, TABLE_LIST *tables, bool if_exists,
+ bool drop_temporary, bool drop_view,
+ bool dont_log_query)
{
TABLE_LIST *table;
char path[FN_REFLEN + 1], *alias= NULL;
@@ -1919,7 +1978,7 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
bool non_tmp_table_deleted= 0;
String built_query;
String built_trans_tmp_query, built_non_trans_tmp_query;
- DBUG_ENTER("mysql_rm_table_part2");
+ DBUG_ENTER("mysql_rm_table_no_locks");
/*
Prepares the drop statements that will be written into the binary
@@ -1973,71 +2032,6 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
}
}
- mysql_ha_rm_tables(thd, tables);
-
- /* Disable drop of enabled log tables, must be done before name locking */
- for (table= tables; table; table= table->next_local)
- {
- if (check_if_log_table(table->db_length, table->db,
- table->table_name_length, table->table_name, 1))
- {
- my_error(ER_BAD_LOG_STATEMENT, MYF(0), "DROP");
- DBUG_RETURN(1);
- }
- }
-
- if (!drop_temporary)
- {
- if (!thd->locked_tables_mode)
- {
- if (lock_table_names(thd, tables, NULL, thd->variables.lock_wait_timeout,
- MYSQL_OPEN_SKIP_TEMPORARY))
- DBUG_RETURN(1);
- for (table= tables; table; table= table->next_local)
- {
- tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table->db, table->table_name,
- FALSE);
- }
- }
- else
- {
- for (table= tables; table; table= table->next_local)
- if (table->open_type != OT_BASE_ONLY &&
- find_temporary_table(thd, table->db, table->table_name))
- {
- /*
- A temporary table.
-
- Don't try to find a corresponding MDL lock or assign it
- to table->mdl_request.ticket. There can't be metadata
- locks for temporary tables: they are local to the session.
-
- Later in this function we release the MDL lock only if
- table->mdl_requeset.ticket is not NULL. Thus here we
- ensure that we won't release the metadata lock on the base
- table locked with LOCK TABLES as a side effect of temporary
- table drop.
- */
- DBUG_ASSERT(table->mdl_request.ticket == NULL);
- }
- else
- {
- /*
- Not a temporary table.
-
- Since 'tables' list can't contain duplicates (this is ensured
- by parser) it is safe to cache pointer to the TABLE instances
- in its elements.
- */
- table->table= find_table_for_mdl_upgrade(thd->open_tables, table->db,
- table->table_name, FALSE);
- if (!table->table)
- DBUG_RETURN(1);
- table->mdl_request.ticket= table->table->mdl_ticket;
- }
- }
- }
-
for (table= tables; table; table= table->next_local)
{
bool is_trans;
@@ -2050,6 +2044,16 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
table->table ? (long) table->table->s : (long) -1));
/*
+ If we are in locked tables mode and are dropping a temporary table,
+ the ticket should be NULL to ensure that we don't release a lock
+ on a base table later.
+ */
+ DBUG_ASSERT(!(thd->locked_tables_mode &&
+ table->open_type != OT_BASE_ONLY &&
+ find_temporary_table(thd, table) &&
+ table->mdl_request.ticket != NULL));
+
+ /*
drop_temporary_table may return one of the following error codes:
. 0 - a temporary table was successfully dropped.
. 1 - a temporary table was not found.
@@ -2124,6 +2128,10 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
table->table= 0;
}
+ /* Check that we have an exclusive lock on the table to be dropped. */
+ DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE, table->db,
+ table->table_name,
+ MDL_EXCLUSIVE));
if (thd->killed)
{
error= -1;
@@ -2166,8 +2174,8 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
built_query.append("`,");
}
}
- DEBUG_SYNC(thd, "rm_table_part2_before_delete_table");
- DBUG_EXECUTE_IF("sleep_before_part2_delete_table",
+ DEBUG_SYNC(thd, "rm_table_no_locks_before_delete_table");
+ DBUG_EXECUTE_IF("sleep_before_no_locks_delete_table",
my_sleep(100000););
error= 0;
if (drop_temporary ||
@@ -2254,7 +2262,7 @@ int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
ER(ER_BAD_TABLE_ERROR), MYF(0),
table->table_name););
}
- DEBUG_SYNC(thd, "rm_table_part2_before_binlog");
+ DEBUG_SYNC(thd, "rm_table_no_locks_before_binlog");
thd->thread_specific_used|= (trans_tmp_table_deleted ||
non_trans_tmp_table_deleted);
error= 0;
@@ -2605,7 +2613,8 @@ int prepare_create_field(Create_field *sql_field,
MAX_FIELD_CHARLENGTH)
{
my_printf_error(ER_TOO_BIG_FIELDLENGTH, ER(ER_TOO_BIG_FIELDLENGTH),
- MYF(0), sql_field->field_name, MAX_FIELD_CHARLENGTH);
+ MYF(0), sql_field->field_name,
+ static_cast<ulong>(MAX_FIELD_CHARLENGTH));
DBUG_RETURN(1);
}
}
@@ -3648,12 +3657,12 @@ mysql_prepare_create_table(THD *thd, HA_CREATE_INFO *create_info,
(MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)))
{
my_error(ER_TOO_LONG_INDEX_COMMENT, MYF(0),
- key_info->name, (uint) INDEX_COMMENT_MAXLEN);
+ key_info->name, static_cast<ulong>(INDEX_COMMENT_MAXLEN));
DBUG_RETURN(-1);
}
char warn_buff[MYSQL_ERRMSG_SIZE];
my_snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_INDEX_COMMENT),
- key_info->name, (uint) INDEX_COMMENT_MAXLEN);
+ key_info->name, static_cast<ulong>(INDEX_COMMENT_MAXLEN));
/* do not push duplicate warnings */
if (!check_duplicate_warning(thd, warn_buff, strlen(warn_buff)))
push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
@@ -3787,7 +3796,8 @@ static bool prepare_blob_field(THD *thd, Create_field *sql_field)
MODE_STRICT_ALL_TABLES)))
{
my_error(ER_TOO_BIG_FIELDLENGTH, MYF(0), sql_field->field_name,
- MAX_FIELD_VARCHARLENGTH / sql_field->charset->mbmaxlen);
+ static_cast<ulong>(MAX_FIELD_VARCHARLENGTH /
+ sql_field->charset->mbmaxlen));
DBUG_RETURN(1);
}
sql_field->sql_type= MYSQL_TYPE_BLOB;
@@ -3865,6 +3875,46 @@ void sp_prepare_create_field(THD *thd, Create_field *sql_field)
(void) prepare_blob_field(thd, sql_field);
}
+
+/**
+ Auxiliary function which allows to check if freshly created .FRM
+ file for table can be opened.
+
+ @retval FALSE - Success.
+ @retval TRUE - Failure.
+*/
+
+static bool check_if_created_table_can_be_opened(THD *thd,
+ const char *path,
+ const char *db,
+ const char *table_name,
+ HA_CREATE_INFO *create_info,
+ handler *file)
+{
+ TABLE table;
+ TABLE_SHARE share;
+ bool result;
+
+ /*
+ It is impossible to open definition of partitioned table without .par file.
+ */
+ if (file->ha_create_handler_files(path, NULL, CHF_CREATE_FLAG, create_info))
+ return TRUE;
+
+ init_tmp_table_share(thd, &share, db, 0, table_name, path);
+
+ result= (open_table_def(thd, &share, 0) ||
+ open_table_from_share(thd, &share, "", 0, (uint) READ_ALL,
+ 0, &table, TRUE));
+ if (! result)
+ (void) closefrm(&table, 0);
+
+ free_table_share(&share);
+ (void) file->ha_create_handler_files(path, NULL, CHF_DELETE_FLAG, create_info);
+ return result;
+}
+
+
/*
Create a table
@@ -4282,9 +4332,14 @@ bool mysql_create_table_no_lock(THD *thd,
if (create_info->options & HA_LEX_CREATE_TMP_TABLE)
{
- TABLE *table= NULL;
- /* Open table and put in temporary table list */
- if (!(table= open_temporary_table(thd, path, db, table_name, 1)))
+ /*
+ Open a table (skipping table cache) and add it into
+ THD::temporary_tables list.
+ */
+
+ TABLE *table= open_table_uncached(thd, path, db, table_name, TRUE);
+
+ if (!table)
{
(void) rm_temporary_table(create_info->db_type, path);
goto err;
@@ -4295,6 +4350,29 @@ bool mysql_create_table_no_lock(THD *thd,
thd->thread_specific_used= TRUE;
}
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+ else if (part_info && create_info->frm_only)
+ {
+ /*
+ For partitioned tables we can't find some problems with table
+ until table is opened. Therefore in order to disallow creation
+ of corrupted tables we have to try to open table as the part
+ of its creation process.
+ In cases when both .FRM and SE part of table are created table
+ is implicitly open in ha_create_table() call.
+ In cases when we create .FRM without SE part we have to open
+ table explicitly.
+ */
+ if (check_if_created_table_can_be_opened(thd, path, db, table_name,
+ create_info, file))
+ {
+ char frm_name[FN_REFLEN];
+ strxmov(frm_name, path, reg_ext, NullS);
+ (void) mysql_file_delete(key_file_frm, frm_name, MYF(0));
+ goto err;
+ }
+ }
+#endif
error= FALSE;
err:
@@ -4561,6 +4639,11 @@ bool mysql_create_like_table(THD* thd, TABLE_LIST* table, TABLE_LIST* src_table,
local_create_info.options|= create_info->options & HA_LEX_CREATE_TMP_TABLE;
/* Reset auto-increment counter for the new table. */
local_create_info.auto_increment_value= 0;
+ /*
+ Do not inherit values of DATA and INDEX DIRECTORY options from
+ the original table. This is documented behavior.
+ */
+ local_create_info.data_file_name= local_create_info.index_file_name= NULL;
if ((res= mysql_create_table_no_lock(thd, table->db, table->table_name,
&local_create_info, &local_alter_info,
@@ -4726,7 +4809,7 @@ err:
@details Checks if any index is being modified (present as both DROP INDEX
and ADD INDEX) in the current ALTER TABLE statement. Needed for disabling
- online ALTER TABLE.
+ in-place ALTER TABLE.
@param table The table being altered
@param alter_info The ALTER TABLE structure
@@ -4843,7 +4926,7 @@ mysql_compare_tables(TABLE *table,
like to keep mysql_compare_tables() idempotent (not altering any
of the arguments) we create a copy of alter_info here and
pass it to mysql_prepare_create_table, then use the result
- to evaluate possibility of fast ALTER TABLE, and then
+ to evaluate possibility of in-place ALTER TABLE, and then
destroy the copy.
*/
Alter_info tmp_alter_info(*alter_info, thd->mem_root);
@@ -4887,9 +4970,9 @@ mysql_compare_tables(TABLE *table,
There was a bug prior to mysql-4.0.25. Number of null fields was
calculated incorrectly. As a result frm and data files gets out of
- sync after fast alter table. There is no way to determine by which
+ sync after in-place alter table. There is no way to determine by which
mysql version (in 4.0 and 4.1 branches) table was created, thus we
- disable fast alter table for all tables created by mysql versions
+ disable in-place alter table for all tables created by mysql versions
prior to 5.0 branch.
See BUG#6236.
*/
@@ -4920,7 +5003,7 @@ mysql_compare_tables(TABLE *table,
DBUG_RETURN(1);
/*
- Use transformed info to evaluate possibility of fast ALTER TABLE
+ Use transformed info to evaluate possibility of in-place ALTER TABLE
but use the preserved field to persist modifications.
*/
new_field_it.init(alter_info->create_list);
@@ -5230,7 +5313,7 @@ blob_length_by_type(enum_field_types type)
semantic checks.
This function is invoked when we know that we're going to
- perform ALTER TABLE via a temporary table -- i.e. fast ALTER TABLE
+ perform ALTER TABLE via a temporary table -- i.e. in-place ALTER TABLE
is not possible, perhaps because the ALTER statement contains
instructions that require change in table data, not only in
table definition or indexes.
@@ -5308,17 +5391,6 @@ mysql_prepare_alter_table(THD *thd, TABLE *table,
if (!(used_fields & HA_CREATE_USED_TRANSACTIONAL))
create_info->transactional= table->s->transactional;
- if (!create_info->tablespace && create_info->storage_media != HA_SM_MEMORY)
- {
- char *tablespace= static_cast<char *>(thd->alloc(FN_LEN + 1));
- /*
- Regular alter table of disk stored table (no tablespace/storage change)
- Copy tablespace name
- */
- if (tablespace &&
- (table->file->get_tablespace_name(thd, tablespace, FN_LEN)))
- create_info->tablespace= tablespace;
- }
restore_record(table, s->default_values); // Empty record for DEFAULT
create_info->option_list= merge_engine_table_options(table->s->option_list,
@@ -5706,7 +5778,6 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
TABLE *table, *new_table= 0;
MDL_ticket *mdl_ticket;
MDL_request target_mdl_request;
- bool has_target_mdl_lock= FALSE;
int error= 0;
char tmp_name[80],old_name[32],new_name_buff[FN_REFLEN + 1];
char new_alias_buff[FN_REFLEN], *table_name, *db, *new_alias, *alias;
@@ -5717,7 +5788,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
handlerton *old_db_type, *new_db_type, *save_old_db_type;
enum_alter_table_change_level need_copy_table= ALTER_TABLE_METADATA_ONLY;
#ifdef WITH_PARTITION_STORAGE_ENGINE
- uint fast_alter_partition= 0;
+ TABLE *table_for_fast_alter_partition= NULL;
bool partition_changed= FALSE;
#endif
bool need_lock_for_indexes= TRUE;
@@ -5725,6 +5796,8 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
uint index_drop_count= 0;
uint *index_drop_buffer= NULL;
uint index_add_count= 0;
+ handler_add_index *add= NULL;
+ bool pending_inplace_add_index= false;
uint *index_add_buffer= NULL;
uint candidate_key_count= 0;
bool no_pk;
@@ -5872,7 +5945,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
else
{
target_mdl_request.init(MDL_key::TABLE, new_db, new_name,
- MDL_EXCLUSIVE);
+ MDL_EXCLUSIVE, MDL_TRANSACTION);
/*
Global intention exclusive lock must have been already acquired when
table to be altered was open, so there is no need to do it here.
@@ -5890,7 +5963,6 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
DBUG_RETURN(TRUE);
}
DEBUG_SYNC(thd, "locked_table_name");
- has_target_mdl_lock= TRUE;
/*
Table maybe does not exist, but we got an exclusive lock
on the name, now we can safely try to find out for sure.
@@ -6037,7 +6109,8 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
*fn_ext(new_name)=0;
if (mysql_rename_table(old_db_type,db,table_name,new_db,new_alias, 0))
error= -1;
- else if (Table_triggers_list::change_table_name(thd, db, table_name,
+ else if (Table_triggers_list::change_table_name(thd, db,
+ alias, table_name,
new_db, new_alias))
{
(void) mysql_rename_table(old_db_type, new_db, new_alias, db,
@@ -6078,10 +6151,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
along with the implicit commit.
*/
if (new_name != table_name || new_db != db)
- {
- thd->mdl_context.release_lock(target_mdl_request.ticket);
thd->mdl_context.release_all_locks_for_name(mdl_ticket);
- }
else
mdl_ticket->downgrade_exclusive_lock(MDL_SHARED_NO_READ_WRITE);
}
@@ -6092,7 +6162,9 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
#ifdef WITH_PARTITION_STORAGE_ENGINE
if (prep_alter_part_table(thd, table, alter_info, create_info, old_db_type,
- &partition_changed, &fast_alter_partition))
+ &partition_changed,
+ db, table_name, path,
+ &table_for_fast_alter_partition))
goto err;
#endif
/*
@@ -6154,7 +6226,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
}
/*
- If there are index changes only, try to do them online. "Index
+ If there are index changes only, try to do them in-place. "Index
changes only" means also that the handler for the table does not
change. The table is open and locked. The handler can be accessed.
*/
@@ -6162,8 +6234,8 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
{
int pk_changed= 0;
ulong alter_flags= 0;
- ulong needed_online_flags= 0;
- ulong needed_fast_flags= 0;
+ ulong needed_inplace_with_read_flags= 0;
+ ulong needed_inplace_flags= 0;
KEY *key;
uint *idx_p;
uint *idx_end_p;
@@ -6187,8 +6259,8 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
{
DBUG_PRINT("info", ("Dropping primary key"));
/* Primary key. */
- needed_online_flags|= HA_ONLINE_DROP_PK_INDEX;
- needed_fast_flags|= HA_ONLINE_DROP_PK_INDEX_NO_WRITES;
+ needed_inplace_with_read_flags|= HA_INPLACE_DROP_PK_INDEX_NO_WRITE;
+ needed_inplace_flags|= HA_INPLACE_DROP_PK_INDEX_NO_READ_WRITE;
pk_changed++;
candidate_key_count--;
}
@@ -6198,8 +6270,9 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
bool is_candidate_key= true;
/* Non-primary unique key. */
- needed_online_flags|= HA_ONLINE_DROP_UNIQUE_INDEX;
- needed_fast_flags|= HA_ONLINE_DROP_UNIQUE_INDEX_NO_WRITES;
+ needed_inplace_with_read_flags|=
+ HA_INPLACE_DROP_UNIQUE_INDEX_NO_WRITE;
+ needed_inplace_flags|= HA_INPLACE_DROP_UNIQUE_INDEX_NO_READ_WRITE;
/*
Check if all fields in key are declared
@@ -6218,12 +6291,13 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
else
{
/* Non-unique key. */
- needed_online_flags|= HA_ONLINE_DROP_INDEX;
- needed_fast_flags|= HA_ONLINE_DROP_INDEX_NO_WRITES;
+ needed_inplace_with_read_flags|= HA_INPLACE_DROP_INDEX_NO_WRITE;
+ needed_inplace_flags|= HA_INPLACE_DROP_INDEX_NO_READ_WRITE;
}
}
no_pk= ((table->s->primary_key == MAX_KEY) ||
- (needed_online_flags & HA_ONLINE_DROP_PK_INDEX));
+ (needed_inplace_with_read_flags &
+ HA_INPLACE_DROP_PK_INDEX_NO_WRITE));
/* Check added indexes. */
for (idx_p= index_add_buffer, idx_end_p= idx_p + index_add_count;
idx_p < idx_end_p;
@@ -6261,57 +6335,59 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
{
DBUG_PRINT("info", ("Adding primary key"));
/* Primary key. */
- needed_online_flags|= HA_ONLINE_ADD_PK_INDEX;
- needed_fast_flags|= HA_ONLINE_ADD_PK_INDEX_NO_WRITES;
+ needed_inplace_with_read_flags|= HA_INPLACE_ADD_PK_INDEX_NO_WRITE;
+ needed_inplace_flags|= HA_INPLACE_ADD_PK_INDEX_NO_READ_WRITE;
pk_changed++;
no_pk= false;
}
else
{
/* Non-primary unique key. */
- needed_online_flags|= HA_ONLINE_ADD_UNIQUE_INDEX;
- needed_fast_flags|= HA_ONLINE_ADD_UNIQUE_INDEX_NO_WRITES;
+ needed_inplace_with_read_flags|= HA_INPLACE_ADD_UNIQUE_INDEX_NO_WRITE;
+ needed_inplace_flags|= HA_INPLACE_ADD_UNIQUE_INDEX_NO_READ_WRITE;
}
}
else
{
/* Non-unique key. */
- needed_online_flags|= HA_ONLINE_ADD_INDEX;
- needed_fast_flags|= HA_ONLINE_ADD_INDEX_NO_WRITES;
+ needed_inplace_with_read_flags|= HA_INPLACE_ADD_INDEX_NO_WRITE;
+ needed_inplace_flags|= HA_INPLACE_ADD_INDEX_NO_READ_WRITE;
}
}
- if ((candidate_key_count > 0) &&
- (needed_online_flags & HA_ONLINE_DROP_PK_INDEX))
+ if ((candidate_key_count > 0) &&
+ (needed_inplace_with_read_flags & HA_INPLACE_DROP_PK_INDEX_NO_WRITE))
{
/*
Dropped primary key when there is some other unique
not null key that should be converted to primary key
*/
- needed_online_flags|= HA_ONLINE_ADD_PK_INDEX;
- needed_fast_flags|= HA_ONLINE_ADD_PK_INDEX_NO_WRITES;
+ needed_inplace_with_read_flags|= HA_INPLACE_ADD_PK_INDEX_NO_WRITE;
+ needed_inplace_flags|= HA_INPLACE_ADD_PK_INDEX_NO_READ_WRITE;
pk_changed= 2;
}
- DBUG_PRINT("info", ("needed_online_flags: 0x%lx, needed_fast_flags: 0x%lx",
- needed_online_flags, needed_fast_flags));
+ DBUG_PRINT("info",
+ ("needed_inplace_with_read_flags: 0x%lx, needed_inplace_flags: 0x%lx",
+ needed_inplace_with_read_flags, needed_inplace_flags));
/*
- Online or fast add/drop index is possible only if
+ In-place add/drop index is possible only if
the primary key is not added and dropped in the same statement.
Otherwise we have to recreate the table.
need_copy_table is no-zero at this place.
*/
if ( pk_changed < 2 )
{
- if ((alter_flags & needed_online_flags) == needed_online_flags)
+ if ((alter_flags & needed_inplace_with_read_flags) ==
+ needed_inplace_with_read_flags)
{
- /* All required online flags are present. */
+ /* All required in-place flags to allow concurrent reads are present. */
need_copy_table= ALTER_TABLE_METADATA_ONLY;
need_lock_for_indexes= FALSE;
}
- else if ((alter_flags & needed_fast_flags) == needed_fast_flags)
+ else if ((alter_flags & needed_inplace_flags) == needed_inplace_flags)
{
- /* All required fast flags are present. */
+ /* All required in-place flags are present. */
need_copy_table= ALTER_TABLE_METADATA_ONLY;
}
}
@@ -6328,12 +6404,12 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
create_info->frm_only= 1;
#ifdef WITH_PARTITION_STORAGE_ENGINE
- if (fast_alter_partition)
+ if (table_for_fast_alter_partition)
{
DBUG_RETURN(fast_alter_partition_table(thd, table, alter_info,
create_info, table_list,
db, table_name,
- fast_alter_partition));
+ table_for_fast_alter_partition));
}
#endif
@@ -6428,8 +6504,8 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
/* table is a normal table: Create temporary table in same directory */
build_table_filename(path, sizeof(path) - 1, new_db, tmp_name, "",
FN_IS_TMP);
- /* Open our intermediate table */
- new_table= open_temporary_table(thd, path, new_db, tmp_name, 1);
+ /* Open our intermediate table. */
+ new_table= open_table_uncached(thd, path, new_db, tmp_name, TRUE);
}
if (!new_table)
goto err_new_table_cleanup;
@@ -6465,10 +6541,18 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
}
else
{
+ /*
+ Ensure that we will upgrade the metadata lock if
+ handler::enable/disable_indexes() will be called.
+ */
+ if (alter_info->keys_onoff != LEAVE_AS_IS ||
+ table->file->indexes_are_disabled())
+ need_lock_for_indexes= true;
if (!table->s->tmp_table &&
wait_while_table_is_used(thd, table, extra_func))
goto err_new_table_cleanup;
thd_proc_info(thd, "manage keys");
+ DEBUG_SYNC(thd, "alter_table_manage_keys");
alter_table_manage_keys(table, table->file->indexes_are_disabled(),
alter_info->keys_onoff);
error= trans_commit_stmt(thd);
@@ -6477,6 +6561,9 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
}
thd->count_cuted_fields= CHECK_FIELD_IGNORE;
+ if (error)
+ goto err_new_table_cleanup;
+
/* If we did not need to copy, we might still need to add/drop indexes. */
if (! new_table)
{
@@ -6508,7 +6595,8 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
key_part->field= table->field[key_part->fieldnr];
}
/* Add the indexes. */
- if ((error= table->file->add_index(table, key_info, index_add_count)))
+ if ((error= table->file->add_index(table, key_info, index_add_count,
+ &add)))
{
#ifdef MERGE_MONTY_ADDITION_THAT_BREAKS_5_5_TESTS
/* Only report error if handler has not already reported an error */
@@ -6526,11 +6614,27 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
}
goto err_new_table_cleanup;
}
+ pending_inplace_add_index= true;
}
/*end of if (index_add_count)*/
if (index_drop_count)
{
+ /* Currently we must finalize add index if we also drop indexes */
+ if (pending_inplace_add_index)
+ {
+ /* Committing index changes needs exclusive metadata lock. */
+ DBUG_ASSERT(thd->mdl_context.is_lock_owner(MDL_key::TABLE,
+ table_list->db,
+ table_list->table_name,
+ MDL_EXCLUSIVE));
+ if ((error= table->file->final_add_index(add, true)))
+ {
+ table->file->print_error(error, MYF(0));
+ goto err_new_table_cleanup;
+ }
+ pending_inplace_add_index= false;
+ }
/* The prepare_drop_index() method takes an array of key numbers. */
key_numbers= (uint*) thd->alloc(sizeof(uint) * index_drop_count);
keyno_p= key_numbers;
@@ -6571,11 +6675,14 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
}
/*end of if (! new_table) for add/drop index*/
- if (error)
- goto err_new_table_cleanup;
-
if (table->s->tmp_table != NO_TMP_TABLE)
{
+ /*
+ In-place operations are not supported for temporary tables, so
+ we don't have to call final_add_index() in this case. The assert
+ verifies that in-place add index has not been done.
+ */
+ DBUG_ASSERT(!pending_inplace_add_index);
/* Close lock if this is a transactional table */
if (thd->lock)
{
@@ -6642,8 +6749,30 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
my_casedn_str(files_charset_info, old_name);
if (wait_while_table_is_used(thd, table, HA_EXTRA_PREPARE_FOR_RENAME))
+ {
+ if (pending_inplace_add_index)
+ {
+ pending_inplace_add_index= false;
+ table->file->final_add_index(add, false);
+ }
+ // Mark this TABLE instance as stale to avoid out-of-sync index information.
+ table->m_needs_reopen= true;
goto err_new_table_cleanup;
-
+ }
+ if (pending_inplace_add_index)
+ {
+ pending_inplace_add_index= false;
+ DBUG_EXECUTE_IF("alter_table_rollback_new_index", {
+ table->file->final_add_index(add, false);
+ my_error(ER_UNKNOWN_ERROR, MYF(0));
+ goto err_new_table_cleanup;
+ });
+ if ((error= table->file->final_add_index(add, true)))
+ {
+ table->file->print_error(error, MYF(0));
+ goto err_new_table_cleanup;
+ }
+ }
close_all_tables_for_name(thd, table->s,
new_name != table_name || new_db != db);
@@ -6680,11 +6809,11 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
else if (mysql_rename_table(new_db_type, new_db, tmp_name, new_db,
new_alias, FN_FROM_IS_TMP) ||
((new_name != table_name || new_db != db) && // we also do rename
- (need_copy_table != ALTER_TABLE_METADATA_ONLY ||
- mysql_rename_table(save_old_db_type, db, table_name, new_db,
- new_alias, NO_FRM_RENAME)) &&
- Table_triggers_list::change_table_name(thd, db, table_name,
- new_db, new_alias)))
+ (need_copy_table != ALTER_TABLE_METADATA_ONLY ||
+ mysql_rename_table(save_old_db_type, db, table_name, new_db,
+ new_alias, NO_FRM_RENAME)) &&
+ Table_triggers_list::change_table_name(thd, db, alias, table_name,
+ new_db, new_alias)))
{
/* Try to get everything back. */
error=1;
@@ -6711,15 +6840,15 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
NO need to tamper with MERGE tables. The real open is done later.
*/
Open_table_context ot_ctx(thd, MYSQL_OPEN_REOPEN);
- TABLE *t_table;
+ TABLE_LIST temp_table_list;
+ TABLE_LIST *t_table_list;
if (new_name != table_name || new_db != db)
{
- table_list->alias= new_name;
- table_list->table_name= new_name;
- table_list->table_name_length= strlen(new_name);
- table_list->db= new_db;
- table_list->db_length= strlen(new_db);
- table_list->mdl_request.ticket= target_mdl_request.ticket;
+ temp_table_list.init_one_table(new_db, strlen(new_db),
+ new_name, strlen(new_name),
+ new_name, TL_READ_NO_INSERT);
+ temp_table_list.mdl_request.ticket= target_mdl_request.ticket;
+ t_table_list= &temp_table_list;
}
else
{
@@ -6729,20 +6858,21 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
to request the lock.
*/
table_list->mdl_request.ticket= mdl_ticket;
+ t_table_list= table_list;
}
- if (open_table(thd, table_list, thd->mem_root, &ot_ctx))
+ if (open_table(thd, t_table_list, thd->mem_root, &ot_ctx))
{
goto err_with_mdl;
}
- t_table= table_list->table;
/* Tell the handler that a new frm file is in place. */
- error= t_table->file->ha_create_handler_files(path, NULL, CHF_INDEX_FLAG,
- create_info);
+ error= t_table_list->table->file->ha_create_handler_files(path, NULL,
+ CHF_INDEX_FLAG,
+ create_info);
- DBUG_ASSERT(thd->open_tables == t_table);
+ DBUG_ASSERT(thd->open_tables == t_table_list->table);
close_thread_table(thd, &thd->open_tables);
- table_list->table= 0;
+ t_table_list->table= NULL;
if (error)
goto err_with_mdl;
@@ -6772,10 +6902,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name,
thd->locked_tables_mode == LTM_PRELOCKED_UNDER_LOCK_TABLES)
{
if ((new_name != table_name || new_db != db))
- {
- thd->mdl_context.release_lock(target_mdl_request.ticket);
thd->mdl_context.release_all_locks_for_name(mdl_ticket);
- }
else
mdl_ticket->downgrade_exclusive_lock(MDL_SHARED_NO_READ_WRITE);
}
@@ -6798,6 +6925,11 @@ err_new_table_cleanup:
create_info->frm_only ? FN_IS_TMP | FRM_ONLY : FN_IS_TMP);
err:
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+ /* If prep_alter_part_table created an intermediate table, destroy it. */
+ if (table_for_fast_alter_partition)
+ close_temporary(table_for_fast_alter_partition, 1, 0);
+#endif /* WITH_PARTITION_STORAGE_ENGINE */
/*
No default value was provided for a DATE/DATETIME field, the
current sql_mode doesn't allow the '0000-00-00' value and
@@ -6831,8 +6963,6 @@ err:
alter_info->datetime_field->field_name);
thd->abort_on_warning= save_abort_on_warning;
}
- if (has_target_mdl_lock)
- thd->mdl_context.release_lock(target_mdl_request.ticket);
DBUG_RETURN(TRUE);
@@ -6844,9 +6974,6 @@ err_with_mdl:
tables and release the exclusive metadata lock.
*/
thd->locked_tables_list.unlink_all_closed_tables(thd, NULL, 0);
- if (has_target_mdl_lock)
- thd->mdl_context.release_lock(target_mdl_request.ticket);
-
thd->mdl_context.release_all_locks_for_name(mdl_ticket);
DBUG_RETURN(TRUE);
}
diff --git a/sql/sql_table.h b/sql/sql_table.h
index a2df9ee7572..9d2f246dbf5 100644
--- a/sql/sql_table.h
+++ b/sql/sql_table.h
@@ -119,7 +119,11 @@ enum enum_explain_filename_mode
#define NO_FRM_RENAME (1 << 2)
#define FRM_ONLY (1 << 3)
-uint filename_to_tablename(const char *from, char *to, uint to_length);
+uint filename_to_tablename(const char *from, char *to, uint to_length
+#ifndef DBUG_OFF
+ , bool stay_quiet = false
+#endif /* DBUG_OFF */
+ );
uint tablename_to_filename(const char *from, char *to, uint to_length);
uint check_n_cut_mysql50_prefix(const char *from, char *to, uint to_length);
bool check_mysql50_prefix(const char *name);
@@ -170,8 +174,9 @@ bool mysql_checksum_table(THD* thd, TABLE_LIST* table_list,
HA_CHECK_OPT* check_opt);
bool mysql_rm_table(THD *thd,TABLE_LIST *tables, my_bool if_exists,
my_bool drop_temporary);
-int mysql_rm_table_part2(THD *thd, TABLE_LIST *tables, bool if_exists,
- bool drop_temporary, bool drop_view, bool log_query);
+int mysql_rm_table_no_locks(THD *thd, TABLE_LIST *tables, bool if_exists,
+ bool drop_temporary, bool drop_view,
+ bool log_query);
bool quick_rm_table(handlerton *base,const char *db,
const char *table_name, uint flags);
void close_cached_table(THD *thd, TABLE *table);
diff --git a/sql/sql_trigger.cc b/sql/sql_trigger.cc
index 26bc59a5886..756046ebc96 100644
--- a/sql/sql_trigger.cc
+++ b/sql/sql_trigger.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2004-2005 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -24,14 +24,14 @@
#include "parse_file.h"
#include "sp.h"
#include "sql_base.h" // find_temporary_table
-#include "lock.h" // wait_if_global_read_lock,
- // start_waiting_global_read_lock
#include "sql_show.h" // append_definer, append_identifier
#include "sql_table.h" // build_table_filename,
// check_n_cut_mysql50_prefix
#include "sql_db.h" // get_default_db_collation
#include "sql_acl.h" // *_ACL, is_acl_user
#include "sql_handler.h" // mysql_ha_rm_tables
+#include "sp_cache.h" // sp_invalidate_cache
+#include <mysys_err.h>
/*************************************************************************/
@@ -306,6 +306,55 @@ private:
/**
+ An error handler that catches all non-OOM errors which can occur during
+ parsing of trigger body. Such errors are ignored and corresponding error
+ message is used to construct a more verbose error message which contains
+ name of problematic trigger. This error message is later emitted when
+ one tries to perform DML or some of DDL on this table.
+ Also, if possible, grabs name of the trigger being parsed so it can be
+ used to correctly drop problematic trigger.
+*/
+class Deprecated_trigger_syntax_handler : public Internal_error_handler
+{
+private:
+
+ char m_message[MYSQL_ERRMSG_SIZE];
+ LEX_STRING *m_trigger_name;
+
+public:
+
+ Deprecated_trigger_syntax_handler() : m_trigger_name(NULL) {}
+
+ virtual bool handle_condition(THD *thd,
+ uint sql_errno,
+ const char* sqlstate,
+ MYSQL_ERROR::enum_warning_level level,
+ const char* message,
+ MYSQL_ERROR ** cond_hdl)
+ {
+ if (sql_errno != EE_OUTOFMEMORY &&
+ sql_errno != ER_OUT_OF_RESOURCES)
+ {
+ if(thd->lex->spname)
+ m_trigger_name= &thd->lex->spname->m_name;
+ if (m_trigger_name)
+ my_snprintf(m_message, sizeof(m_message),
+ ER(ER_ERROR_IN_TRIGGER_BODY),
+ m_trigger_name->str, message);
+ else
+ my_snprintf(m_message, sizeof(m_message),
+ ER(ER_ERROR_IN_UNKNOWN_TRIGGER_BODY), message);
+ return true;
+ }
+ return false;
+ }
+
+ LEX_STRING *get_trigger_name() { return m_trigger_name; }
+ char *get_error_message() { return m_message; }
+};
+
+
+/**
Create or drop trigger for table.
@param thd current thread context (including trigger definition in LEX)
@@ -391,15 +440,6 @@ bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create)
DBUG_RETURN(TRUE);
}
- /*
- We don't want perform our operations while global read lock is held
- so we have to wait until its end and then prevent it from occurring
- again until we are done, unless we are under lock tables.
- */
- if (!thd->locked_tables_mode &&
- thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, TRUE))
- DBUG_RETURN(TRUE);
-
if (!create)
{
bool if_exists= thd->lex->drop_if_exists;
@@ -458,7 +498,7 @@ bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create)
DBUG_ASSERT(tables->next_global == 0);
/* We do not allow creation of triggers on temporary tables. */
- if (create && find_temporary_table(thd, tables->db, tables->table_name))
+ if (create && find_temporary_table(thd, tables))
{
my_error(ER_TRG_ON_VIEW_OR_TEMP_TABLE, MYF(0), tables->alias);
goto end;
@@ -478,8 +518,7 @@ bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create)
if (thd->locked_tables_mode)
{
/* Under LOCK TABLES we must only accept write locked tables. */
- if (!(tables->table= find_table_for_mdl_upgrade(thd->open_tables,
- tables->db,
+ if (!(tables->table= find_table_for_mdl_upgrade(thd, tables->db,
tables->table_name,
FALSE)))
goto end;
@@ -530,6 +569,12 @@ bool mysql_create_or_drop_trigger(THD *thd, TABLE_LIST *tables, bool create)
if (thd->locked_tables_list.reopen_tables(thd))
thd->clear_error();
+ /*
+ Invalidate SP-cache. That's needed because triggers may change list of
+ pre-locking tables.
+ */
+ sp_cache_invalidate();
+
end:
if (!result)
{
@@ -548,9 +593,6 @@ end:
if (!create)
thd->lex->restore_backup_query_tables_list(&backup);
- if (thd->global_read_lock.has_protection())
- thd->global_read_lock.start_waiting_global_read_lock(thd);
-
if (!result)
my_ok(thd);
@@ -600,6 +642,8 @@ bool Table_triggers_list::create_trigger(THD *thd, TABLE_LIST *tables,
LEX_STRING *trg_connection_cl_name;
LEX_STRING *trg_db_cl_name;
+ if (check_for_broken_triggers())
+ return true;
/* Trigger must be in the same schema as target table. */
if (my_strcasecmp(table_alias_charset, table->s->db.str,
@@ -873,7 +917,7 @@ static bool rm_trigger_file(char *path, const char *db,
@param path char buffer of size FN_REFLEN to be used
for constructing path to .TRN file.
@param db trigger's database name
- @param table_name trigger's name
+ @param trigger_name trigger's name
@retval
False success
@@ -1234,13 +1278,12 @@ bool Table_triggers_list::check_n_load(THD *thd, const char *db,
DBUG_RETURN(1); // EOM
}
-
- if (!thd->no_warnings_for_error)
- push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
- ER_TRG_NO_CREATION_CTX,
- ER(ER_TRG_NO_CREATION_CTX),
- (const char*) db,
- (const char*) table_name);
+
+ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ ER_TRG_NO_CREATION_CTX,
+ ER(ER_TRG_NO_CREATION_CTX),
+ (const char*) db,
+ (const char*) table_name);
if (!(trg_client_cs_name= alloc_lex_string(&table->mem_root)) ||
!(trg_connection_cl_name= alloc_lex_string(&table->mem_root)) ||
@@ -1339,12 +1382,11 @@ bool Table_triggers_list::check_n_load(THD *thd, const char *db,
lex_start(thd);
thd->spcont= NULL;
- if (parse_sql(thd, & parser_state, creation_ctx))
- {
- /* Currently sphead is always deleted in case of a parse error */
- DBUG_ASSERT(lex.sphead == 0);
- goto err_with_lex_cleanup;
- }
+ Deprecated_trigger_syntax_handler error_handler;
+ thd->push_internal_handler(&error_handler);
+ bool parse_error= parse_sql(thd, & parser_state, creation_ctx);
+ thd->pop_internal_handler();
+
/*
Not strictly necessary to invoke this method here, since we know
that we've parsed CREATE TRIGGER and not an
@@ -1355,6 +1397,54 @@ bool Table_triggers_list::check_n_load(THD *thd, const char *db,
*/
lex.set_trg_event_type_for_tables();
+ if (parse_error)
+ {
+ if (!triggers->m_has_unparseable_trigger)
+ triggers->set_parse_error_message(error_handler.get_error_message());
+ /* Currently sphead is always set to NULL in case of a parse error */
+ DBUG_ASSERT(lex.sphead == 0);
+ if (error_handler.get_trigger_name())
+ {
+ LEX_STRING *trigger_name;
+ const LEX_STRING *orig_trigger_name= error_handler.get_trigger_name();
+
+ if (!(trigger_name= alloc_lex_string(&table->mem_root)) ||
+ !(trigger_name->str= strmake_root(&table->mem_root,
+ orig_trigger_name->str,
+ orig_trigger_name->length)))
+ goto err_with_lex_cleanup;
+
+ trigger_name->length= orig_trigger_name->length;
+
+ if (triggers->names_list.push_back(trigger_name,
+ &table->mem_root))
+ goto err_with_lex_cleanup;
+ }
+ else
+ {
+ /*
+ The Table_triggers_list is not constructed as a list of
+ trigger objects as one would expect, but rather of lists of
+ properties of equal length. Thus, even if we don't get the
+ trigger name, we still fill all in all the lists with
+ placeholders as we might otherwise create a skew in the
+ lists. Obviously, this has to be refactored.
+ */
+ LEX_STRING *empty= alloc_lex_string(&table->mem_root);
+ if (!empty)
+ goto err_with_lex_cleanup;
+
+ empty->str= const_cast<char*>("");
+ empty->length= 0;
+ if (triggers->names_list.push_back(empty, &table->mem_root))
+ goto err_with_lex_cleanup;
+ }
+ lex_end(&lex);
+ continue;
+ }
+
+ lex.sphead->set_info(0, 0, &lex.sp_chistics, (ulong) *trg_sql_mode);
+
int event= lex.trg_chistics.event;
int action_time= lex.trg_chistics.action_time;
@@ -1371,12 +1461,12 @@ bool Table_triggers_list::check_n_load(THD *thd, const char *db,
MySQL, which does not support triggers definers. We should emit
warning here.
*/
- if (!thd->no_warnings_for_error)
- push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
- ER_TRG_NO_DEFINER, ER(ER_TRG_NO_DEFINER),
- (const char*) db,
- (const char*) sp->m_name.str);
-
+
+ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ ER_TRG_NO_DEFINER, ER(ER_TRG_NO_DEFINER),
+ (const char*) db,
+ (const char*) sp->m_name.str);
+
/*
Set definer to the '' to correct displaying in the information
schema.
@@ -1421,9 +1511,8 @@ bool Table_triggers_list::check_n_load(THD *thd, const char *db,
char fname[SAFE_NAME_LEN + 1];
DBUG_ASSERT((!my_strcasecmp(table_alias_charset, lex.query_tables->db, db) ||
(check_n_cut_mysql50_prefix(db, fname, sizeof(fname)) &&
- !my_strcasecmp(table_alias_charset, lex.query_tables->db, fname))) &&
- (!my_strcasecmp(table_alias_charset, lex.query_tables->table_name,
- table_name) ||
+ !my_strcasecmp(table_alias_charset, lex.query_tables->db, fname))));
+ DBUG_ASSERT((!my_strcasecmp(table_alias_charset, lex.query_tables->table_name, table_name) ||
(check_n_cut_mysql50_prefix(table_name, fname, sizeof(fname)) &&
!my_strcasecmp(table_alias_charset, lex.query_tables->table_name, fname))));
#endif
@@ -1705,6 +1794,13 @@ bool Table_triggers_list::drop_all_triggers(THD *thd, char *db, char *name)
while ((trigger= it_name++))
{
+ /*
+ Trigger, which body we failed to parse during call
+ Table_triggers_list::check_n_load(), might be missing name.
+ Such triggers have zero-length name and are skipped here.
+ */
+ if (trigger->length == 0)
+ continue;
if (rm_trigname_file(path, db, trigger->str))
{
/*
@@ -1875,6 +1971,7 @@ Table_triggers_list::change_table_name_in_trignames(const char *old_db_name,
@param[in,out] thd Thread context
@param[in] db Old database of subject table
+ @param[in] old_alias Old alias of subject table
@param[in] old_table Old name of subject table
@param[in] new_db New database for subject table
@param[in] new_table New name of subject table
@@ -1891,6 +1988,7 @@ Table_triggers_list::change_table_name_in_trignames(const char *old_db_name,
*/
bool Table_triggers_list::change_table_name(THD *thd, const char *db,
+ const char *old_alias,
const char *old_table,
const char *new_db,
const char *new_table)
@@ -1912,7 +2010,7 @@ bool Table_triggers_list::change_table_name(THD *thd, const char *db,
MDL_EXCLUSIVE));
DBUG_ASSERT(my_strcasecmp(table_alias_charset, db, new_db) ||
- my_strcasecmp(table_alias_charset, old_table, new_table));
+ my_strcasecmp(table_alias_charset, old_alias, new_table));
if (Table_triggers_list::check_n_load(thd, db, old_table, &table, TRUE))
{
@@ -1921,7 +2019,12 @@ bool Table_triggers_list::change_table_name(THD *thd, const char *db,
}
if (table.triggers)
{
- LEX_STRING old_table_name= { (char *) old_table, strlen(old_table) };
+ if (table.triggers->check_for_broken_triggers())
+ {
+ result= 1;
+ goto end;
+ }
+ LEX_STRING old_table_name= { (char *) old_alias, strlen(old_alias) };
LEX_STRING new_table_name= { (char *) new_table, strlen(new_table) };
/*
Since triggers should be in the same schema as their subject tables
@@ -2009,6 +2112,9 @@ bool Table_triggers_list::process_triggers(THD *thd,
sp_head *sp_trigger= bodies[event][time_type];
SELECT_LEX *save_current_select;
+ if (check_for_broken_triggers())
+ return true;
+
if (sp_trigger == NULL)
return FALSE;
@@ -2143,6 +2249,22 @@ void Table_triggers_list::mark_fields_used(trg_event_type event)
/**
+ Signals to the Table_triggers_list that a parse error has occured when
+ reading a trigger from file. This makes the Table_triggers_list enter an
+ error state flagged by m_has_unparseable_trigger == true. The error message
+ will be used whenever a statement invoking or manipulating triggers is
+ issued against the Table_triggers_list's table.
+
+ @param error_message The error message thrown by the parser.
+ */
+void Table_triggers_list::set_parse_error_message(char *error_message)
+{
+ m_has_unparseable_trigger= true;
+ strcpy(m_parse_error_message, error_message);
+}
+
+
+/**
Trigger BUG#14090 compatibility hook.
@param[in,out] unknown_key reference on the line with unknown
diff --git a/sql/sql_trigger.h b/sql/sql_trigger.h
index 28bf0a60877..c98f5d72a58 100644
--- a/sql/sql_trigger.h
+++ b/sql/sql_trigger.h
@@ -97,6 +97,27 @@ class Table_triggers_list: public Sql_alloc
*/
GRANT_INFO subject_table_grants[TRG_EVENT_MAX][TRG_ACTION_MAX];
+ /**
+ This flag indicates that one of the triggers was not parsed successfully,
+ and as a precaution the object has entered a state where all trigger
+ access results in errors until all such triggers are dropped. It is not
+ safe to add triggers since we don't know if the broken trigger has the
+ same name or event type. Nor is it safe to invoke any trigger for the
+ aforementioned reasons. The only safe operations are drop_trigger and
+ drop_all_triggers.
+
+ @see Table_triggers_list::set_parse_error
+ */
+ bool m_has_unparseable_trigger;
+
+ /**
+ This error will be displayed when the user tries to manipulate or invoke
+ triggers on a table that has broken triggers. It will get set only once
+ per statement and thus will contain the first parse error encountered in
+ the trigger file.
+ */
+ char m_parse_error_message[MYSQL_ERRMSG_SIZE];
+
public:
/**
Field responsible for storing triggers definitions in file.
@@ -118,8 +139,9 @@ public:
/* End of character ser context. */
- Table_triggers_list(TABLE *table_arg):
- record1_field(0), trigger_table(table_arg)
+ Table_triggers_list(TABLE *table_arg)
+ :record1_field(0), trigger_table(table_arg),
+ m_has_unparseable_trigger(false)
{
bzero((char *)bodies, sizeof(bodies));
bzero((char *)trigger_fields, sizeof(trigger_fields));
@@ -157,6 +179,7 @@ public:
TABLE *table, bool names_only);
static bool drop_all_triggers(THD *thd, char *db, char *table_name);
static bool change_table_name(THD *thd, const char *db,
+ const char *old_alias,
const char *old_table,
const char *new_db,
const char *new_table);
@@ -175,6 +198,8 @@ public:
void mark_fields_used(trg_event_type event);
+ void set_parse_error_message(char *error_message);
+
friend class Item_trigger_field;
bool add_tables_and_routines_for_triggers(THD *thd,
@@ -192,6 +217,16 @@ private:
const char *new_db_name,
LEX_STRING *old_table_name,
LEX_STRING *new_table_name);
+
+ bool check_for_broken_triggers()
+ {
+ if (m_has_unparseable_trigger)
+ {
+ my_message(ER_PARSE_ERROR, m_parse_error_message, MYF(0));
+ return true;
+ }
+ return false;
+ }
};
extern const LEX_STRING trg_action_time_type_names[];
diff --git a/sql/sql_truncate.cc b/sql/sql_truncate.cc
index 99f3808c98e..67ed608f114 100644
--- a/sql/sql_truncate.cc
+++ b/sql/sql_truncate.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -13,11 +13,8 @@
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
-#include "sql_priv.h"
-#include "transaction.h"
-#include "debug_sync.h"
-#include "records.h" // READ_RECORD
-#include "table.h" // TABLE
+#include "debug_sync.h" // DEBUG_SYNC
+#include "table.h" // TABLE, FOREIGN_KEY_INFO
#include "sql_class.h" // THD
#include "sql_base.h" // open_and_lock_tables
#include "sql_table.h" // write_bin_log
@@ -29,145 +26,212 @@
#include "sql_truncate.h"
-/*
- Delete all rows of a locked table.
+/**
+ Append a list of field names to a string.
- @param thd Thread context.
- @param table_list Table list element for the table.
- @param rows_deleted Whether rows might have been deleted.
+ @param str The string.
+ @param fields The list of field names.
- @retval FALSE Success.
- @retval TRUE Error.
+ @return TRUE on failure, FALSE otherwise.
*/
-static bool
-delete_all_rows(THD *thd, TABLE *table)
+static bool fk_info_append_fields(String *str, List<LEX_STRING> *fields)
{
- int error;
- READ_RECORD info;
- bool is_bulk_delete;
- bool some_rows_deleted= FALSE;
- bool save_binlog_row_based= thd->is_current_stmt_binlog_format_row();
- DBUG_ENTER("delete_all_rows");
-
- /* Replication of truncate table must be statement based. */
- thd->clear_current_stmt_binlog_format_row();
+ bool res= FALSE;
+ LEX_STRING *field;
+ List_iterator_fast<LEX_STRING> it(*fields);
- /*
- Update handler statistics (e.g. table->file->stats.records).
- Might be used by the storage engine to aggregate information
- necessary to allow deletion. Currently, this seems to be
- meaningful only to the archive storage engine, which uses
- the info method to set the number of records. Although
- archive does not support deletion, it becomes necessary in
- order to return a error if the table is not empty.
- */
- error= table->file->info(HA_STATUS_VARIABLE | HA_STATUS_NO_LOCK);
- if (error && error != HA_ERR_WRONG_COMMAND)
+ while ((field= it++))
{
- table->file->print_error(error, MYF(0));
- goto end;
+ res|= str->append("`");
+ res|= str->append(field);
+ res|= str->append("`, ");
}
- /*
- Attempt to delete all rows in the table.
- If it is unsupported, switch to row by row deletion.
- */
- if (! (error= table->file->ha_delete_all_rows()))
- goto end;
+ str->chop();
+ str->chop();
- if (error != HA_ERR_WRONG_COMMAND)
- {
- /*
- If a transactional engine fails in the middle of deletion,
- we expect it to be able to roll it back. Some reasons
- for the engine to fail would be media failure or corrupted
- data dictionary (i.e. in case of a partitioned table). We
- have sufficiently strong metadata locks to rule out any
- potential deadlocks.
-
- If a non-transactional engine fails here (that would
- not be MyISAM, since MyISAM does TRUNCATE by recreate),
- and binlog is on, replication breaks, since nothing gets
- written to the binary log. (XXX: is this a bug?)
- */
- table->file->print_error(error, MYF(0));
- goto end;
- }
+ return res;
+}
+
+
+/**
+ Generate a foreign key description suitable for a error message.
+
+ @param thd Thread context.
+ @param fk_info The foreign key information.
+
+ @return A human-readable string describing the foreign key.
+*/
+
+static const char *fk_info_str(THD *thd, FOREIGN_KEY_INFO *fk_info)
+{
+ bool res= FALSE;
+ char buffer[STRING_BUFFER_USUAL_SIZE*2];
+ String str(buffer, sizeof(buffer), system_charset_info);
+
+ str.length(0);
/*
- A workaround for Bug#53696 "Performance schema engine violates the
- PSEA API by calling my_error()".
+ `db`.`tbl`, CONSTRAINT `id` FOREIGN KEY (`fk`) REFERENCES `db`.`tbl` (`fk`)
*/
- if (thd->is_error())
- goto end;
- /* Handler didn't support fast delete. Delete rows one by one. */
+ res|= str.append('`');
+ res|= str.append(fk_info->foreign_db);
+ res|= str.append("`.`");
+ res|= str.append(fk_info->foreign_table);
+ res|= str.append("`, CONSTRAINT `");
+ res|= str.append(fk_info->foreign_id);
+ res|= str.append("` FOREIGN KEY (");
+ res|= fk_info_append_fields(&str, &fk_info->foreign_fields);
+ res|= str.append(") REFERENCES `");
+ res|= str.append(fk_info->referenced_db);
+ res|= str.append("`.`");
+ res|= str.append(fk_info->referenced_table);
+ res|= str.append("` (");
+ res|= fk_info_append_fields(&str, &fk_info->referenced_fields);
+ res|= str.append(')');
+
+ return res ? NULL : thd->strmake(str.ptr(), str.length());
+}
+
- init_read_record(&info, thd, table, NULL, TRUE, TRUE, FALSE);
+/**
+ Check and emit a fatal error if the table which is going to be
+ affected by TRUNCATE TABLE is a parent table in some non-self-
+ referencing foreign key.
+
+ @remark The intention is to allow truncate only for tables that
+ are not dependent on other tables.
+
+ @param thd Thread context.
+ @param table Table handle.
+
+ @retval FALSE This table is not parent in a non-self-referencing foreign
+ key. Statement can proceed.
+ @retval TRUE This table is parent in a non-self-referencing foreign key,
+ error was emitted.
+*/
+
+static bool
+fk_truncate_illegal_if_parent(THD *thd, TABLE *table)
+{
+ FOREIGN_KEY_INFO *fk_info;
+ List<FOREIGN_KEY_INFO> fk_list;
+ List_iterator_fast<FOREIGN_KEY_INFO> it;
/*
- Start bulk delete. If the engine does not support it, go on,
- it's not an error.
+ Bail out early if the table is not referenced by a foreign key.
+ In this case, the table could only be, if at all, a child table.
*/
- is_bulk_delete= ! table->file->start_bulk_delete();
+ if (! table->file->referenced_by_foreign_key())
+ return FALSE;
- table->mark_columns_needed_for_delete();
+ /*
+ This table _is_ referenced by a foreign key. At this point, only
+ self-referencing keys are acceptable. For this reason, get the list
+ of foreign keys referencing this table in order to check the name
+ of the child (dependent) tables.
+ */
+ table->file->get_parent_foreign_key_list(thd, &fk_list);
- while (!(error= info.read_record(&info)) && !thd->killed)
+ /* Out of memory when building list. */
+ if (thd->is_error())
+ return TRUE;
+
+ it.init(fk_list);
+
+ /* Loop over the set of foreign keys for which this table is a parent. */
+ while ((fk_info= it++))
{
- if ((error= table->file->ha_delete_row(table->record[0])))
- {
- table->file->print_error(error, MYF(0));
+ DBUG_ASSERT(!my_strcasecmp(system_charset_info,
+ fk_info->referenced_db->str,
+ table->s->db.str));
+
+ DBUG_ASSERT(!my_strcasecmp(system_charset_info,
+ fk_info->referenced_table->str,
+ table->s->table_name.str));
+
+ if (my_strcasecmp(system_charset_info, fk_info->foreign_db->str,
+ table->s->db.str) ||
+ my_strcasecmp(system_charset_info, fk_info->foreign_table->str,
+ table->s->table_name.str))
break;
- }
-
- some_rows_deleted= TRUE;
}
- /* HA_ERR_END_OF_FILE */
- if (error == -1)
- error= 0;
-
- /* Close down the bulk delete. */
- if (is_bulk_delete)
+ /* Table is parent in a non-self-referencing foreign key. */
+ if (fk_info)
{
- int bulk_delete_error= table->file->end_bulk_delete();
- if (bulk_delete_error && !error)
- {
- table->file->print_error(bulk_delete_error, MYF(0));
- error= bulk_delete_error;
- }
+ my_error(ER_TRUNCATE_ILLEGAL_FK, MYF(0), fk_info_str(thd, fk_info));
+ return TRUE;
}
- end_read_record(&info);
+ return FALSE;
+}
+
+
+/*
+ Open and truncate a locked table.
+
+ @param thd Thread context.
+ @param table_ref Table list element for the table to be truncated.
+ @param is_tmp_table True if element refers to a temp table.
+
+ @retval 0 Success.
+ @retval > 0 Error code.
+*/
+
+int Truncate_statement::handler_truncate(THD *thd, TABLE_LIST *table_ref,
+ bool is_tmp_table)
+{
+ int error= 0;
+ uint flags;
+ DBUG_ENTER("Truncate_statement::handler_truncate");
/*
- Regardless of the error status, the query must be written to the
- binary log if rows of the table is non-transactional.
+ Can't recreate, the engine must mechanically delete all rows
+ in the table. Use open_and_lock_tables() to open a write cursor.
*/
- if (some_rows_deleted && !table->file->has_transactions())
+
+ /* If it is a temporary table, no need to take locks. */
+ if (is_tmp_table)
+ flags= MYSQL_OPEN_TEMPORARY_ONLY;
+ else
{
- thd->transaction.stmt.modified_non_trans_table= TRUE;
- thd->transaction.all.modified_non_trans_table= TRUE;
+ /* We don't need to load triggers. */
+ DBUG_ASSERT(table_ref->trg_event_map == 0);
+ /*
+ Our metadata lock guarantees that no transaction is reading
+ or writing into the table. Yet, to open a write cursor we need
+ a thr_lock lock. Allow to open base tables only.
+ */
+ table_ref->required_type= FRMTYPE_TABLE;
+ /*
+ Ignore pending FLUSH TABLES since we don't want to release
+ the MDL lock taken above and otherwise there is no way to
+ wait for FLUSH TABLES in deadlock-free fashion.
+ */
+ flags= MYSQL_OPEN_IGNORE_FLUSH | MYSQL_OPEN_SKIP_TEMPORARY;
+ /*
+ Even though we have an MDL lock on the table here, we don't
+ pass MYSQL_OPEN_HAS_MDL_LOCK to open_and_lock_tables
+ since to truncate a MERGE table, we must open and lock
+ merge children, and on those we don't have an MDL lock.
+ Thus clear the ticket to satisfy MDL asserts.
+ */
+ table_ref->mdl_request.ticket= NULL;
}
- if (error || thd->killed)
- goto end;
+ /* Open the table as it will handle some required preparations. */
+ if (open_and_lock_tables(thd, table_ref, FALSE, flags))
+ DBUG_RETURN(1);
- /* Truncate resets the auto-increment counter. */
- error= table->file->ha_reset_auto_increment(0);
- if (error)
- {
- if (error != HA_ERR_WRONG_COMMAND)
- table->file->print_error(error, MYF(0));
- else
- error= 0;
- }
+ /* Whether to truncate regardless of foreign keys. */
+ if (! (thd->variables.option_bits & OPTION_NO_FOREIGN_KEY_CHECKS))
+ error= fk_truncate_illegal_if_parent(thd, table_ref->table);
-end:
- if (save_binlog_row_based)
- thd->set_current_stmt_binlog_format_row();
+ if (!error && (error= table_ref->table->file->ha_truncate()))
+ table_ref->table->file->print_error(error, MYF(0));
DBUG_RETURN(error);
}
@@ -208,8 +272,8 @@ static bool recreate_temporary_table(THD *thd, TABLE *table)
ha_create_table(thd, share->normalized_path.str, share->db.str,
share->table_name.str, &create_info, 1);
- if (open_temporary_table(thd, share->path.str, share->db.str,
- share->table_name.str, 1))
+ if (open_table_uncached(thd, share->path.str, share->db.str,
+ share->table_name.str, TRUE))
{
error= FALSE;
thd->thread_specific_used= TRUE;
@@ -225,30 +289,29 @@ static bool recreate_temporary_table(THD *thd, TABLE *table)
/*
- Handle opening and locking if a base table for truncate.
+ Handle locking a base table for truncate.
@param[in] thd Thread context.
@param[in] table_ref Table list element for the table to
be truncated.
@param[out] hton_can_recreate Set to TRUE if table can be dropped
and recreated.
- @param[out] ticket_downgrade Set if a lock must be downgraded after
- truncate is done.
@retval FALSE Success.
@retval TRUE Error.
*/
-static bool open_and_lock_table_for_truncate(THD *thd, TABLE_LIST *table_ref,
- bool *hton_can_recreate,
- MDL_ticket **ticket_downgrade)
+bool Truncate_statement::lock_table(THD *thd, TABLE_LIST *table_ref,
+ bool *hton_can_recreate)
{
TABLE *table= NULL;
- handlerton *table_type;
- DBUG_ENTER("open_and_lock_table_for_truncate");
+ DBUG_ENTER("Truncate_statement::lock_table");
+ /* Lock types are set in the parser. */
DBUG_ASSERT(table_ref->lock_type == TL_WRITE);
- DBUG_ASSERT(table_ref->mdl_request.type == MDL_SHARED_NO_READ_WRITE);
+ /* The handler truncate protocol dictates a exclusive lock. */
+ DBUG_ASSERT(table_ref->mdl_request.type == MDL_EXCLUSIVE);
+
/*
Before doing anything else, acquire a metadata lock on the table,
or ensure we have one. We don't use open_and_lock_tables()
@@ -264,108 +327,49 @@ static bool open_and_lock_table_for_truncate(THD *thd, TABLE_LIST *table_ref,
*/
if (thd->locked_tables_mode)
{
- if (!(table= find_table_for_mdl_upgrade(thd->open_tables, table_ref->db,
+ if (!(table= find_table_for_mdl_upgrade(thd, table_ref->db,
table_ref->table_name, FALSE)))
DBUG_RETURN(TRUE);
- table_type= table->s->db_type();
- *hton_can_recreate= ha_check_storage_engine_flag(table_type,
+ *hton_can_recreate= ha_check_storage_engine_flag(table->s->db_type(),
HTON_CAN_RECREATE);
table_ref->mdl_request.ticket= table->mdl_ticket;
}
else
{
- /*
- Even though we could use the previous execution branch here just as
- well, we must not try to open the table:
- */
+ /* Acquire an exclusive lock. */
DBUG_ASSERT(table_ref->next_global == NULL);
if (lock_table_names(thd, table_ref, NULL,
thd->variables.lock_wait_timeout,
MYSQL_OPEN_SKIP_TEMPORARY))
DBUG_RETURN(TRUE);
- if (dd_frm_storage_engine(thd, table_ref->db, table_ref->table_name,
- &table_type))
+ if (dd_check_storage_engine_flag(thd, table_ref->db, table_ref->table_name,
+ HTON_CAN_RECREATE, hton_can_recreate))
DBUG_RETURN(TRUE);
- *hton_can_recreate= ha_check_storage_engine_flag(table_type,
- HTON_CAN_RECREATE);
}
-#ifdef WITH_PARTITION_STORAGE_ENGINE
/*
- TODO: Add support for TRUNCATE PARTITION for NDB and other engines
- supporting native partitioning.
+ A storage engine can recreate or truncate the table only if there
+ are no references to it from anywhere, i.e. no cached TABLE in the
+ table cache.
*/
- if (thd->lex->alter_info.flags & ALTER_ADMIN_PARTITION &&
- table_type != partition_hton)
- {
- my_error(ER_PARTITION_MGMT_ON_NONPARTITIONED, MYF(0));
- DBUG_RETURN(TRUE);
- }
-#endif
- DEBUG_SYNC(thd, "lock_table_for_truncate");
-
- if (*hton_can_recreate)
+ if (thd->locked_tables_mode)
{
- /*
- Acquire an exclusive lock. The storage engine can recreate the
- table only if there are no references to it from anywhere, i.e.
- no cached TABLE in the table cache. To remove the table from the
- cache we need an exclusive lock.
- */
- if (thd->locked_tables_mode)
- {
- if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
- DBUG_RETURN(TRUE);
- *ticket_downgrade= table->mdl_ticket;
+ DEBUG_SYNC(thd, "upgrade_lock_for_truncate");
+ /* To remove the table from the cache we need an exclusive lock. */
+ if (wait_while_table_is_used(thd, table, HA_EXTRA_FORCE_REOPEN))
+ DBUG_RETURN(TRUE);
+ m_ticket_downgrade= table->mdl_ticket;
+ /* Close if table is going to be recreated. */
+ if (*hton_can_recreate)
close_all_tables_for_name(thd, table->s, FALSE);
- }
- else
- {
- ulong timeout= thd->variables.lock_wait_timeout;
- if (thd->mdl_context.
- upgrade_shared_lock_to_exclusive(table_ref->mdl_request.ticket,
- timeout))
- DBUG_RETURN(TRUE);
-
- tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table_ref->db,
- table_ref->table_name, FALSE);
- }
}
else
{
- /*
- Can't recreate, we must mechanically delete all rows in
- the table. Our metadata lock guarantees that no transaction
- is reading or writing into the table. Yet, to open a write
- cursor we need a thr_lock lock. Use open_and_lock_tables()
- to do the necessary job.
- */
-
- /* Allow to open base tables only. */
- table_ref->required_type= FRMTYPE_TABLE;
- /* We don't need to load triggers. */
- DBUG_ASSERT(table_ref->trg_event_map == 0);
- /*
- Even though we have an MDL lock on the table here, we don't
- pass MYSQL_OPEN_HAS_MDL_LOCK to open_and_lock_tables
- since to truncate a MERGE table, we must open and lock
- merge children, and on those we don't have an MDL lock.
- Thus clear the ticket to satisfy MDL asserts.
- */
- table_ref->mdl_request.ticket= NULL;
-
- /*
- Open the table as it will handle some required preparations.
- Ignore pending FLUSH TABLES since we don't want to release
- the MDL lock taken above and otherwise there is no way to
- wait for FLUSH TABLES in deadlock-free fashion.
- */
- if (open_and_lock_tables(thd, table_ref, FALSE,
- MYSQL_OPEN_IGNORE_FLUSH |
- MYSQL_OPEN_SKIP_TEMPORARY))
- DBUG_RETURN(TRUE);
+ /* Table is already locked exclusively. Remove cached instances. */
+ tdc_remove_table(thd, TDC_RT_REMOVE_ALL, table_ref->db,
+ table_ref->table_name, FALSE);
}
DBUG_RETURN(FALSE);
@@ -386,14 +390,17 @@ static bool open_and_lock_table_for_truncate(THD *thd, TABLE_LIST *table_ref,
@retval TRUE Error.
*/
-bool mysql_truncate_table(THD *thd, TABLE_LIST *table_ref)
+bool Truncate_statement::truncate_table(THD *thd, TABLE_LIST *table_ref)
{
+ int error;
TABLE *table;
- bool error= TRUE, binlog_stmt;
- MDL_ticket *mdl_ticket= NULL;
- DBUG_ENTER("mysql_truncate_table");
+ bool binlog_stmt;
+ DBUG_ENTER("Truncate_statement::truncate_table");
+
+ /* Initialize, or reinitialize in case of reexecution (SP). */
+ m_ticket_downgrade= NULL;
- /* Remove tables from the HANDLER's hash. */
+ /* Remove table from the HANDLER's hash. */
mysql_ha_rm_tables(thd, table_ref);
/* If it is a temporary table, no need to take locks. */
@@ -414,14 +421,11 @@ bool mysql_truncate_table(THD *thd, TABLE_LIST *table_ref)
{
/*
The engine does not support truncate-by-recreate. Open the
- table and delete all rows. In such a manner this can in fact
- open several tables if it's a temporary MyISAMMRG table.
+ table and invoke the handler truncate. In such a manner this
+ can in fact open several tables if it's a temporary MyISAMMRG
+ table.
*/
- if (open_and_lock_tables(thd, table_ref, FALSE,
- MYSQL_OPEN_TEMPORARY_ONLY))
- DBUG_RETURN(TRUE);
-
- error= delete_all_rows(thd, table_ref->table);
+ error= handler_truncate(thd, table_ref, TRUE);
}
/*
@@ -435,8 +439,7 @@ bool mysql_truncate_table(THD *thd, TABLE_LIST *table_ref)
{
bool hton_can_recreate;
- if (open_and_lock_table_for_truncate(thd, table_ref,
- &hton_can_recreate, &mdl_ticket))
+ if (lock_table(thd, table_ref, &hton_can_recreate))
DBUG_RETURN(TRUE);
if (hton_can_recreate)
@@ -455,15 +458,27 @@ bool mysql_truncate_table(THD *thd, TABLE_LIST *table_ref)
}
else
{
- error= delete_all_rows(thd, table_ref->table);
+ /*
+ The engine does not support truncate-by-recreate.
+ Attempt to use the handler truncate method.
+ */
+ error= handler_truncate(thd, table_ref, FALSE);
/*
- Regardless of the error status, the query must be written to the
- binary log if rows of a non-transactional table were deleted.
+ All effects of a TRUNCATE TABLE operation are committed even if
+ truncation fails. Thus, the query must be written to the binary
+ log. The only exception is a unimplemented truncate method.
*/
- binlog_stmt= !error || thd->transaction.stmt.modified_non_trans_table;
+ binlog_stmt= !error || error != HA_ERR_WRONG_COMMAND;
}
+ /*
+ If we tried to open a MERGE table and failed due to problems with the
+ children tables, the table will have been closed and table_ref->table
+ will be invalid. Reset the pointer here in any case as
+ query_cache_invalidate does not need a valid TABLE object.
+ */
+ table_ref->table= NULL;
query_cache_invalidate3(thd, table_ref, FALSE);
}
@@ -472,49 +487,37 @@ bool mysql_truncate_table(THD *thd, TABLE_LIST *table_ref)
error|= write_bin_log(thd, !error, thd->query(), thd->query_length());
/*
- All effects of a TRUNCATE TABLE operation are rolled back if a row
- by row deletion fails. Otherwise, it is automatically committed at
- the end.
- */
- if (error)
- {
- trans_rollback_stmt(thd);
- trans_rollback(thd);
- }
-
- /*
A locked table ticket was upgraded to a exclusive lock. After the
the query has been written to the binary log, downgrade the lock
to a shared one.
*/
- if (mdl_ticket)
- mdl_ticket->downgrade_exclusive_lock(MDL_SHARED_NO_READ_WRITE);
+ if (m_ticket_downgrade)
+ m_ticket_downgrade->downgrade_exclusive_lock(MDL_SHARED_NO_READ_WRITE);
- DBUG_PRINT("exit", ("error: %d", error));
- DBUG_RETURN(test(error));
+ DBUG_RETURN(error);
}
+/**
+ Execute a TRUNCATE statement at runtime.
+
+ @param thd The current thread.
+
+ @return FALSE on success.
+*/
+
bool Truncate_statement::execute(THD *thd)
{
- TABLE_LIST *first_table= thd->lex->select_lex.table_list.first;
bool res= TRUE;
+ TABLE_LIST *first_table= thd->lex->select_lex.table_list.first;
DBUG_ENTER("Truncate_statement::execute");
if (check_one_table_access(thd, DROP_ACL, first_table))
- goto error;
- /*
- Don't allow this within a transaction because we want to use
- re-generate table
- */
- if (thd->in_active_multi_stmt_transaction())
- {
- my_message(ER_LOCK_OR_ACTIVE_TRANSACTION,
- ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0));
- goto error;
- }
- if (! (res= mysql_truncate_table(thd, first_table)))
+ DBUG_RETURN(res);
+
+ if (! (res= truncate_table(thd, first_table)))
my_ok(thd);
-error:
+
DBUG_RETURN(res);
}
+
diff --git a/sql/sql_truncate.h b/sql/sql_truncate.h
index b8b1d3da53d..95a2f35df4f 100644
--- a/sql/sql_truncate.h
+++ b/sql/sql_truncate.h
@@ -18,13 +18,15 @@
class THD;
struct TABLE_LIST;
-bool mysql_truncate_table(THD *thd, TABLE_LIST *table_ref);
-
/**
Truncate_statement represents the TRUNCATE statement.
*/
class Truncate_statement : public Sql_statement
{
+private:
+ /* Set if a lock must be downgraded after truncate is done. */
+ MDL_ticket *m_ticket_downgrade;
+
public:
/**
Constructor, used to represent a ALTER TABLE statement.
@@ -34,7 +36,7 @@ public:
: Sql_statement(lex)
{}
- ~Truncate_statement()
+ virtual ~Truncate_statement()
{}
/**
@@ -43,7 +45,20 @@ public:
@return false on success.
*/
bool execute(THD *thd);
-};
+protected:
+ /** Handle locking a base table for truncate. */
+ bool lock_table(THD *, TABLE_LIST *, bool *);
+
+ /** Truncate table via the handler method. */
+ int handler_truncate(THD *, TABLE_LIST *, bool);
+
+ /**
+ Optimized delete of all rows by doing a full regenerate of the table.
+ Depending on the storage engine, it can be accomplished through a
+ drop and recreate or via the handler truncate method.
+ */
+ bool truncate_table(THD *, TABLE_LIST *);
+};
#endif
diff --git a/sql/sql_udf.cc b/sql/sql_udf.cc
index 605b2367f48..3b3e96082cf 100644
--- a/sql/sql_udf.cc
+++ b/sql/sql_udf.cc
@@ -205,10 +205,7 @@ void udf_init()
On windows we must check both FN_LIBCHAR and '/'.
*/
- if (my_strchr(files_charset_info, dl_name,
- dl_name + strlen(dl_name), FN_LIBCHAR) ||
- IF_WIN(my_strchr(files_charset_info, dl_name,
- dl_name + strlen(dl_name), '/'), 0) ||
+ if (check_valid_path(dl_name, strlen(dl_name)) ||
check_string_char_length(&name, "", NAME_CHAR_LEN,
system_charset_info, 1))
{
@@ -448,13 +445,8 @@ int mysql_create_function(THD *thd,udf_func *udf)
Ensure that the .dll doesn't have a path
This is done to ensure that only approved dll from the system
directories are used (to make this even remotely secure).
-
- On windows we must check both FN_LIBCHAR and '/'.
*/
- if (my_strchr(files_charset_info, udf->dl,
- udf->dl + strlen(udf->dl), FN_LIBCHAR) ||
- IF_WIN(my_strchr(files_charset_info, udf->dl,
- udf->dl + strlen(udf->dl), '/'), 0))
+ if (check_valid_path(udf->dl, strlen(udf->dl)))
{
my_message(ER_UDF_NO_PATHS, ER(ER_UDF_NO_PATHS), MYF(0));
DBUG_RETURN(1);
diff --git a/sql/sql_union.cc b/sql/sql_union.cc
index faf0a81c40d..3382eba260c 100644
--- a/sql/sql_union.cc
+++ b/sql/sql_union.cc
@@ -199,7 +199,6 @@ bool st_select_lex_unit::prepare(THD *thd_arg, select_result *sel_result,
SELECT_LEX *sl, *first_sl= first_select();
select_result *tmp_result;
bool is_union_select;
- TABLE *empty_table= 0;
DBUG_ENTER("st_select_lex_unit::prepare");
describe= test(additional_options & SELECT_DESCRIBE);
@@ -301,14 +300,6 @@ bool st_select_lex_unit::prepare(THD *thd_arg, select_result *sel_result,
types= first_sl->item_list;
else if (sl == first_sl)
{
- /*
- We need to create an empty table object. It is used
- to create tmp_table fields in Item_type_holder.
- The main reason of this is that we can't create
- field object without table.
- */
- DBUG_ASSERT(!empty_table);
- empty_table= (TABLE*) thd->calloc(sizeof(TABLE));
types.empty();
List_iterator_fast<Item> it(sl->item_list);
Item *item_tmp;
@@ -466,6 +457,7 @@ bool st_select_lex_unit::prepare(THD *thd_arg, select_result *sel_result,
err:
thd_arg->lex->current_select= lex_select_save;
+ (void) cleanup();
DBUG_RETURN(TRUE);
}
diff --git a/sql/sql_update.cc b/sql/sql_update.cc
index 76c90e40b17..bb4540b48f3 100644
--- a/sql/sql_update.cc
+++ b/sql/sql_update.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
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
@@ -42,11 +42,68 @@
// mysql_handle_derived,
// mysql_derived_filling
-/* Return 0 if row hasn't changed */
-bool compare_record(TABLE *table)
+/**
+ True if the table's input and output record buffers are comparable using
+ compare_records(TABLE*).
+ */
+bool records_are_comparable(const TABLE *table) {
+ return ((table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ) == 0) ||
+ bitmap_is_subset(table->write_set, table->read_set);
+}
+
+
+/**
+ Compares the input and outbut record buffers of the table to see if a row
+ has changed. The algorithm iterates over updated columns and if they are
+ nullable compares NULL bits in the buffer before comparing actual
+ data. Special care must be taken to compare only the relevant NULL bits and
+ mask out all others as they may be undefined. The storage engine will not
+ and should not touch them.
+
+ @param table The table to evaluate.
+
+ @return true if row has changed.
+ @return false otherwise.
+*/
+bool compare_records(const TABLE *table)
{
+ DBUG_ASSERT(records_are_comparable(table));
+
+ if ((table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ) != 0)
+ {
+ /*
+ Storage engine may not have read all columns of the record. Fields
+ (including NULL bits) not in the write_set may not have been read and
+ can therefore not be compared.
+ */
+ for (Field **ptr= table->field ; *ptr != NULL; ptr++)
+ {
+ Field *field= *ptr;
+ if (bitmap_is_set(table->write_set, field->field_index))
+ {
+ if (field->real_maybe_null())
+ {
+ uchar null_byte_index= field->null_ptr - table->record[0];
+
+ if (((table->record[0][null_byte_index]) & field->null_bit) !=
+ ((table->record[1][null_byte_index]) & field->null_bit))
+ return TRUE;
+ }
+ if (field->cmp_binary_offset(table->s->rec_buff_length))
+ return TRUE;
+ }
+ }
+ return FALSE;
+ }
+
+ /*
+ The storage engine has read all columns, so it's safe to compare all bits
+ including those not in the write_set. This is cheaper than the field-by-field
+ comparison done above.
+ */
if (table->s->can_cmp_whole_record)
+ // Fixed-size record: do bitwise comparison of the records
return cmp_record(table,record[1]);
/* Compare null bits */
if (memcmp(table->null_flags,
@@ -204,7 +261,6 @@ int mysql_update(THD *thd,
bool using_limit= limit != HA_POS_ERROR;
bool safe_update= test(thd->variables.option_bits & OPTION_SAFE_UPDATES);
bool used_key_is_modified= FALSE, transactional_table, will_batch;
- bool can_compare_record;
int res;
int error, loc_error;
uint used_index, dup_key_found;
@@ -240,11 +296,17 @@ int mysql_update(THD *thd,
if (lock_tables(thd, table_list, table_count, 0))
DBUG_RETURN(1);
- if (mysql_handle_derived(thd->lex, &mysql_derived_prepare) ||
- (thd->fill_derived_tables() &&
- mysql_handle_derived(thd->lex, &mysql_derived_filling)))
+ if (mysql_handle_derived(thd->lex, &mysql_derived_prepare))
DBUG_RETURN(1);
+ if (thd->fill_derived_tables() &&
+ mysql_handle_derived(thd->lex, &mysql_derived_filling))
+ {
+ mysql_handle_derived(thd->lex, &mysql_derived_cleanup);
+ DBUG_RETURN(1);
+ }
+ mysql_handle_derived(thd->lex, &mysql_derived_cleanup);
+
thd_proc_info(thd, "init");
table= table_list->table;
@@ -582,15 +644,6 @@ int mysql_update(THD *thd,
if (table->file->ha_table_flags() & HA_PARTIAL_COLUMN_READ)
table->prepare_for_position();
- /*
- We can use compare_record() to optimize away updates if
- the table handler is returning all columns OR if
- if all updated columns are read
- */
- can_compare_record= (!(table->file->ha_table_flags() &
- HA_PARTIAL_COLUMN_READ) ||
- bitmap_is_subset(table->write_set, table->read_set));
-
while (!(error=info.read_record(&info)) && !thd->killed)
{
update_virtual_fields(thd, table);
@@ -608,7 +661,7 @@ int mysql_update(THD *thd,
found++;
- if (!can_compare_record || compare_record(table))
+ if (!records_are_comparable(table) || compare_records(table))
{
if ((res= table_list->view_check_option(thd, ignore)) !=
VIEW_CHECK_OK)
@@ -948,6 +1001,108 @@ static table_map get_table_map(List<Item> *items)
return map;
}
+/**
+ If one row is updated through two different aliases and the first
+ update physically moves the row, the second update will error
+ because the row is no longer located where expected. This function
+ checks if the multiple-table update is about to do that and if so
+ returns with an error.
+
+ The following update operations physically moves rows:
+ 1) Update of a column in a clustered primary key
+ 2) Update of a column used to calculate which partition the row belongs to
+
+ This function returns with an error if both of the following are
+ true:
+
+ a) A table in the multiple-table update statement is updated
+ through multiple aliases (including views)
+ b) At least one of the updates on the table from a) may physically
+ moves the row. Note: Updating a column used to calculate which
+ partition a row belongs to does not necessarily mean that the
+ row is moved. The new value may or may not belong to the same
+ partition.
+
+ @param leaves First leaf table
+ @param tables_for_update Map of tables that are updated
+
+ @return
+ true if the update is unsafe, in which case an error message is also set,
+ false otherwise.
+*/
+static
+bool unsafe_key_update(TABLE_LIST *leaves, table_map tables_for_update)
+{
+ TABLE_LIST *tl= leaves;
+
+ for (tl= leaves; tl ; tl= tl->next_leaf)
+ {
+ if (tl->table->map & tables_for_update)
+ {
+ TABLE *table1= tl->table;
+ bool primkey_clustered= (table1->file->primary_key_is_clustered() &&
+ table1->s->primary_key != MAX_KEY);
+
+ bool table_partitioned= false;
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+ table_partitioned= (table1->part_info != NULL);
+#endif
+
+ if (!table_partitioned && !primkey_clustered)
+ continue;
+
+ for (TABLE_LIST* tl2= tl->next_leaf; tl2 ; tl2= tl2->next_leaf)
+ {
+ /*
+ Look at "next" tables only since all previous tables have
+ already been checked
+ */
+ TABLE *table2= tl2->table;
+ if (table2->map & tables_for_update && table1->s == table2->s)
+ {
+ // A table is updated through two aliases
+ if (table_partitioned &&
+ (partition_key_modified(table1, table1->write_set) ||
+ partition_key_modified(table2, table2->write_set)))
+ {
+ // Partitioned key is updated
+ my_error(ER_MULTI_UPDATE_KEY_CONFLICT, MYF(0),
+ tl->belong_to_view ? tl->belong_to_view->alias
+ : tl->alias,
+ tl2->belong_to_view ? tl2->belong_to_view->alias
+ : tl2->alias);
+ return true;
+ }
+
+ if (primkey_clustered)
+ {
+ // The primary key can cover multiple columns
+ KEY key_info= table1->key_info[table1->s->primary_key];
+ KEY_PART_INFO *key_part= key_info.key_part;
+ KEY_PART_INFO *key_part_end= key_part + key_info.key_parts;
+
+ for (;key_part != key_part_end; ++key_part)
+ {
+ if (bitmap_is_set(table1->write_set, key_part->fieldnr-1) ||
+ bitmap_is_set(table2->write_set, key_part->fieldnr-1))
+ {
+ // Clustered primary key is updated
+ my_error(ER_MULTI_UPDATE_KEY_CONFLICT, MYF(0),
+ tl->belong_to_view ? tl->belong_to_view->alias
+ : tl->alias,
+ tl2->belong_to_view ? tl2->belong_to_view->alias
+ : tl2->alias);
+ return true;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ return false;
+}
+
/*
make update specific preparation and checks after opening tables
@@ -982,9 +1137,17 @@ int mysql_multi_update_prepare(THD *thd)
/* following need for prepared statements, to run next time multi-update */
thd->lex->sql_command= SQLCOM_UPDATE_MULTI;
- /* open tables and create derived ones, but do not lock and fill them */
+ /*
+ Open tables and create derived ones, but do not lock and fill them yet.
+
+ During prepare phase acquire only S metadata locks instead of SW locks to
+ keep prepare of multi-UPDATE compatible with concurrent LOCK TABLES WRITE
+ and global read lock.
+ */
if ((original_multiupdate &&
- open_tables(thd, &table_list, &table_count, 0)) ||
+ open_tables(thd, &table_list, &table_count,
+ (thd->stmt_arena->is_stmt_prepare() ?
+ MYSQL_OPEN_FORCE_SHARED_MDL : 0))) ||
mysql_handle_derived(lex, &mysql_derived_prepare))
DBUG_RETURN(TRUE);
/*
@@ -1019,10 +1182,14 @@ int mysql_multi_update_prepare(THD *thd)
thd->table_map_for_update= tables_for_update= get_table_map(fields);
+ leaves= lex->select_lex.leaf_tables;
+
+ if (unsafe_key_update(leaves, tables_for_update))
+ DBUG_RETURN(true);
+
/*
Setup timestamp handling and locking mode
*/
- leaves= lex->select_lex.leaf_tables;
for (tl= leaves; tl; tl= tl->next_leaf)
{
TABLE *table= tl->table;
@@ -1142,7 +1309,11 @@ int mysql_multi_update_prepare(THD *thd)
if (thd->fill_derived_tables() &&
mysql_handle_derived(lex, &mysql_derived_filling))
+ {
+ mysql_handle_derived(lex, &mysql_derived_cleanup);
DBUG_RETURN(TRUE);
+ }
+ mysql_handle_derived(lex, &mysql_derived_cleanup);
DBUG_RETURN (FALSE);
}
@@ -1647,18 +1818,8 @@ bool multi_update::send_data(List<Item> &not_used_values)
if (table->status & (STATUS_NULL_ROW | STATUS_UPDATED))
continue;
- /*
- We can use compare_record() to optimize away updates if
- the table handler is returning all columns OR if
- if all updated columns are read
- */
if (table == table_to_update)
{
- bool can_compare_record;
- can_compare_record= (!(table->file->ha_table_flags() &
- HA_PARTIAL_COLUMN_READ) ||
- bitmap_is_subset(table->write_set,
- table->read_set));
table->status|= STATUS_UPDATED;
store_record(table,record[1]);
if (fill_record_n_invoke_before_triggers(thd, *fields_for_table[offset],
@@ -1673,7 +1834,7 @@ bool multi_update::send_data(List<Item> &not_used_values)
*/
table->auto_increment_field_not_null= FALSE;
found++;
- if (!can_compare_record || compare_record(table))
+ if (!records_are_comparable(table) || compare_records(table))
{
int error;
if ((error= cur_table->view_check_option(thd, ignore)) !=
@@ -1864,7 +2025,6 @@ int multi_update::do_updates()
DBUG_RETURN(0);
for (cur_table= update_tables; cur_table; cur_table= cur_table->next_local)
{
- bool can_compare_record;
uint offset= cur_table->shared;
table = cur_table->table;
@@ -1913,11 +2073,6 @@ int multi_update::do_updates()
goto err;
}
- can_compare_record= (!(table->file->ha_table_flags() &
- HA_PARTIAL_COLUMN_READ) ||
- bitmap_is_subset(table->write_set,
- table->read_set));
-
for (;;)
{
if (thd->killed && trans_safe)
@@ -1965,7 +2120,7 @@ int multi_update::do_updates()
TRG_ACTION_BEFORE, TRUE))
goto err2;
- if (!can_compare_record || compare_record(table))
+ if (!records_are_comparable(table) || compare_records(table))
{
int error;
if ((error= cur_table->view_check_option(thd, ignore)) !=
@@ -2062,7 +2217,9 @@ bool multi_update::send_eof()
Does updates for the last n - 1 tables, returns 0 if ok;
error takes into account killed status gained in do_updates()
*/
- int local_error = (table_count) ? do_updates() : 0;
+ int local_error= thd->is_error();
+ if (!local_error)
+ local_error = (table_count) ? do_updates() : 0;
/*
if local_error is not set ON until after do_updates() then
later carried out killing should not affect binlogging.
diff --git a/sql/sql_update.h b/sql/sql_update.h
index 6bf022a171c..50ff50f025d 100644
--- a/sql/sql_update.h
+++ b/sql/sql_update.h
@@ -38,6 +38,7 @@ bool mysql_multi_update(THD *thd, TABLE_LIST *table_list,
enum enum_duplicates handle_duplicates, bool ignore,
SELECT_LEX_UNIT *unit, SELECT_LEX *select_lex,
multi_update **result);
-bool compare_record(TABLE *table);
+bool records_are_comparable(const TABLE *table);
+bool compare_records(const TABLE *table);
#endif /* SQL_UPDATE_INCLUDED */
diff --git a/sql/sql_view.cc b/sql/sql_view.cc
index 3d8b9323b2a..0a8c2eac1a0 100644
--- a/sql/sql_view.cc
+++ b/sql/sql_view.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2004 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -22,7 +22,7 @@
#include "sql_base.h" // find_table_in_global_list, lock_table_names
#include "sql_parse.h" // sql_parse
#include "sql_cache.h" // query_cache_*
-#include "lock.h" // wait_if_global_read_lock
+#include "lock.h" // MYSQL_OPEN_SKIP_TEMPORARY
#include "sql_show.h" // append_identifier
#include "sql_table.h" // build_table_filename
#include "sql_db.h" // mysql_opt_change_db, mysql_change_db
@@ -550,7 +550,7 @@ bool mysql_create_view(THD *thd, TABLE_LIST *views,
}
/* prepare select to resolve all fields */
- lex->view_prepare_mode= 1;
+ lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW;
if (unit->prepare(thd, 0, 0))
{
/*
@@ -649,13 +649,6 @@ bool mysql_create_view(THD *thd, TABLE_LIST *views,
}
#endif
-
- if (thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, TRUE))
- {
- res= TRUE;
- goto err;
- }
-
res= mysql_register_view(thd, view, mode);
if (mysql_bin_log.is_open())
@@ -704,7 +697,6 @@ bool mysql_create_view(THD *thd, TABLE_LIST *views,
if (mode != VIEW_CREATE_NEW)
query_cache_invalidate3(thd, view, 0);
- thd->global_read_lock.start_waiting_global_read_lock(thd);
if (res)
goto err;
@@ -849,7 +841,8 @@ static int mysql_register_view(THD *thd, TABLE_LIST *view,
thd->variables.sql_mode&= ~MODE_ANSI_QUOTES;
lex->unit.print(&view_query, QT_ORDINARY);
- lex->unit.print(&is_query, QT_IS);
+ lex->unit.print(&is_query,
+ enum_query_type(QT_TO_SYSTEM_CHARSET | QT_WITHOUT_INTRODUCERS));
thd->variables.sql_mode|= sql_mode;
}
@@ -1280,6 +1273,7 @@ bool mysql_make_view(THD *thd, File_parser *parser, TABLE_LIST *table,
TABLE_LIST *view_tables= lex->query_tables;
TABLE_LIST *view_tables_tail= 0;
TABLE_LIST *tbl;
+ Security_context *security_ctx;
/*
Check rights to run commands (EXPLAIN SELECT & SHOW CREATE) which show
@@ -1426,26 +1420,39 @@ bool mysql_make_view(THD *thd, File_parser *parser, TABLE_LIST *table,
if (table->view_suid)
{
/*
- Prepare a security context to check underlying objects of the view
+ For suid views prepare a security context for checking underlying
+ objects of the view.
*/
if (!(table->view_sctx= (Security_context *)
thd->stmt_arena->alloc(sizeof(Security_context))))
goto err;
- /* Assign the context to the tables referenced in the view */
- if (view_tables)
- {
- DBUG_ASSERT(view_tables_tail);
- for (tbl= view_tables; tbl != view_tables_tail->next_global;
- tbl= tbl->next_global)
- tbl->security_ctx= table->view_sctx;
- }
- /* assign security context to SELECT name resolution contexts of view */
- for(SELECT_LEX *sl= lex->all_selects_list;
- sl;
- sl= sl->next_select_in_list())
- sl->context.security_ctx= table->view_sctx;
+ security_ctx= table->view_sctx;
+ }
+ else
+ {
+ /*
+ For non-suid views inherit security context from view's table list.
+ This allows properly handle situation when non-suid view is used
+ from within suid view.
+ */
+ security_ctx= table->security_ctx;
}
+ /* Assign the context to the tables referenced in the view */
+ if (view_tables)
+ {
+ DBUG_ASSERT(view_tables_tail);
+ for (tbl= view_tables; tbl != view_tables_tail->next_global;
+ tbl= tbl->next_global)
+ tbl->security_ctx= security_ctx;
+ }
+
+ /* assign security context to SELECT name resolution contexts of view */
+ for(SELECT_LEX *sl= lex->all_selects_list;
+ sl;
+ sl= sl->next_select_in_list())
+ sl->context.security_ctx= security_ctx;
+
/*
Setup an error processor to hide error messages issued by stored
routines referenced in the view
diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy
index 9f34180662c..92209cc96f1 100644
--- a/sql/sql_yacc.yy
+++ b/sql/sql_yacc.yy
@@ -1,4 +1,4 @@
-/* Copyright (c) 2000, 2010 Oracle and/or its affiliates. All rights reserved.
+/* Copyright (c) 2000, 2011 Oracle and/or its affiliates. All rights reserved.
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
@@ -71,9 +71,6 @@
int yylex(void *yylval, void *yythd);
-const LEX_STRING null_lex_str= {0,0};
-const LEX_STRING empty_lex_str= { (char*) "", 0 };
-
#define yyoverflow(A,B,C,D,E,F) \
{ \
ulong val= *(F); \
@@ -1202,6 +1199,7 @@ bool my_yyoverflow(short **a, YYSTYPE **b, ulong *yystacksize);
%token PROCESSLIST_SYM
%token PROFILE_SYM
%token PROFILES_SYM
+%token PROXY_SYM
%token PURGE
%token QUARTER_SYM
%token QUERY_SYM
@@ -1955,35 +1953,28 @@ master_def:
| MASTER_HEARTBEAT_PERIOD_SYM EQ NUM_literal
{
Lex->mi.heartbeat_period= (float) $3->val_real();
- if (Lex->mi.heartbeat_period > SLAVE_MAX_HEARTBEAT_PERIOD ||
- Lex->mi.heartbeat_period < 0.0)
- {
- const char format[]= "%d seconds";
- char buf[4*sizeof(SLAVE_MAX_HEARTBEAT_PERIOD) + sizeof(format)];
- sprintf(buf, format, SLAVE_MAX_HEARTBEAT_PERIOD);
- my_error(ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE,
- MYF(0), " is negative or exceeds the maximum ", buf);
- MYSQL_YYABORT;
+ if (Lex->mi.heartbeat_period > SLAVE_MAX_HEARTBEAT_PERIOD ||
+ Lex->mi.heartbeat_period < 0.0)
+ {
+ const char format[]= "%d";
+ char buf[4*sizeof(SLAVE_MAX_HEARTBEAT_PERIOD) + sizeof(format)];
+ sprintf(buf, format, SLAVE_MAX_HEARTBEAT_PERIOD);
+ my_error(ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE, MYF(0), buf);
+ MYSQL_YYABORT;
}
if (Lex->mi.heartbeat_period > slave_net_timeout)
{
push_warning_printf(YYTHD, MYSQL_ERROR::WARN_LEVEL_WARN,
- ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE,
- ER(ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE),
- " exceeds the value of `slave_net_timeout' sec.",
- " A sensible value for the period should be"
- " less than the timeout.");
+ ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX,
+ ER(ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX));
}
if (Lex->mi.heartbeat_period < 0.001)
{
if (Lex->mi.heartbeat_period != 0.0)
{
push_warning_printf(YYTHD, MYSQL_ERROR::WARN_LEVEL_WARN,
- ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE,
- ER(ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE),
- " is less than 1 msec.",
- " The period is reset to zero which means"
- " no heartbeats will be sending");
+ ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN,
+ ER(ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MIN));
Lex->mi.heartbeat_period= 0.0;
}
Lex->mi.heartbeat_opt= LEX_MASTER_INFO::LEX_MI_DISABLE;
@@ -2256,16 +2247,19 @@ opt_ev_status:
| ENABLE_SYM
{
Lex->event_parse_data->status= Event_parse_data::ENABLED;
+ Lex->event_parse_data->status_changed= true;
$$= 1;
}
| DISABLE_SYM ON SLAVE
{
Lex->event_parse_data->status= Event_parse_data::SLAVESIDE_DISABLED;
+ Lex->event_parse_data->status_changed= true;
$$= 1;
}
| DISABLE_SYM
{
Lex->event_parse_data->status= Event_parse_data::DISABLED;
+ Lex->event_parse_data->status_changed= true;
$$= 1;
}
;
@@ -4842,7 +4836,7 @@ part_value_expr_item:
if (!lex->safe_to_cache_query)
{
- my_error(ER_PARTITION_FUNCTION_IS_NOT_ALLOWED, MYF(0));
+ my_parse_error(ER(ER_WRONG_EXPR_IN_PARTITION_FUNC_ERROR));
MYSQL_YYABORT;
}
if (part_info->add_column_list_value(YYTHD, part_expr))
@@ -6966,7 +6960,7 @@ alter_list_item:
}
| FORCE_SYM
{
- Lex->alter_info.flags|= ALTER_FORCE;
+ Lex->alter_info.flags|= ALTER_RECREATE;
}
| alter_order_clause
{
@@ -7602,7 +7596,6 @@ select_lock_type:
LEX *lex=Lex;
lex->current_select->set_lock_for_tables(TL_WRITE);
lex->safe_to_cache_query=0;
- lex->protect_against_global_read_lock= TRUE;
}
| LOCK_SYM IN_SYM SHARE_SYM MODE_SYM
{
@@ -9614,7 +9607,7 @@ table_factor:
;
select_derived_union:
- select_derived opt_order_clause opt_limit_clause
+ select_derived opt_union_order_or_limit
| select_derived_union
UNION_SYM
union_option
@@ -9630,7 +9623,7 @@ select_derived_union:
*/
Lex->pop_context();
}
- opt_order_clause opt_limit_clause
+ opt_union_order_or_limit
;
/* The equivalent of select_init2 for nested queries. */
@@ -10660,7 +10653,10 @@ insert_lock_option:
| LOW_PRIORITY { $$= TL_WRITE_LOW_PRIORITY; }
| DELAYED_SYM
{
- Lex->keyword_delayed_begin= YYLIP->get_tok_start();
+ Lex->keyword_delayed_begin_offset= (uint)(YYLIP->get_tok_start() -
+ YYTHD->query());
+ Lex->keyword_delayed_end_offset= Lex->keyword_delayed_begin_offset +
+ YYLIP->yyLength() + 1;
$$= TL_WRITE_DELAYED;
}
| HIGH_PRIORITY { $$= TL_WRITE; }
@@ -10670,7 +10666,10 @@ replace_lock_option:
opt_low_priority { $$= $1; }
| DELAYED_SYM
{
- Lex->keyword_delayed_begin= YYLIP->get_tok_start();
+ Lex->keyword_delayed_begin_offset= (uint)(YYLIP->get_tok_start() -
+ YYTHD->query());
+ Lex->keyword_delayed_end_offset= Lex->keyword_delayed_begin_offset +
+ YYLIP->yyLength() + 1;
$$= TL_WRITE_DELAYED;
}
;
@@ -10976,7 +10975,7 @@ truncate:
lex->select_lex.sql_cache= SELECT_LEX::SQL_CACHE_UNSPECIFIED;
lex->select_lex.init_order();
YYPS->m_lock_type= TL_WRITE;
- YYPS->m_mdl_type= MDL_SHARED_NO_READ_WRITE;
+ YYPS->m_mdl_type= MDL_EXCLUSIVE;
}
table_name
{
@@ -11135,19 +11134,6 @@ show_param:
if (prepare_schema_table(YYTHD, lex, $4, SCH_COLUMNS))
MYSQL_YYABORT;
}
- | NEW_SYM MASTER_SYM FOR_SYM SLAVE
- WITH MASTER_LOG_FILE_SYM EQ
- TEXT_STRING_sys /* $8 */
- AND_SYM MASTER_LOG_POS_SYM EQ
- ulonglong_num /* $12 */
- AND_SYM MASTER_SERVER_ID_SYM EQ
- ulong_num /* $16 */
- {
- Lex->sql_command = SQLCOM_SHOW_NEW_MASTER;
- Lex->mi.log_file_name = $8.str;
- Lex->mi.pos = $12;
- Lex->mi.server_id = $16;
- }
| master_or_binary LOGS_SYM
{
Lex->sql_command = SQLCOM_SHOW_BINLOGS;
@@ -11519,7 +11505,11 @@ opt_with_read_lock:
TABLE_LIST *tables= Lex->query_tables;
Lex->type|= REFRESH_READ_LOCK;
for (; tables; tables= tables->next_global)
+ {
tables->mdl_request.set_type(MDL_SHARED_NO_WRITE);
+ tables->required_type= FRMTYPE_TABLE; /* Don't try to flush views. */
+ tables->open_type= OT_BASE_ONLY; /* Ignore temporary tables. */
+ }
}
;
@@ -11829,7 +11819,23 @@ field_or_var:
opt_load_data_set_spec:
/* empty */ {}
- | SET insert_update_list {}
+ | SET load_data_set_list {}
+ ;
+
+load_data_set_list:
+ load_data_set_list ',' load_data_set_elem
+ | load_data_set_elem
+ ;
+
+load_data_set_elem:
+ simple_ident_nospvar equal remember_name expr_or_default remember_end
+ {
+ LEX *lex= Lex;
+ if (lex->update_list.push_back($1) ||
+ lex->value_list.push_back($4))
+ MYSQL_YYABORT;
+ $4->set_name($3, (uint) ($5 - $3), YYTHD->charset());
+ }
;
/* Common definitions */
@@ -12575,6 +12581,12 @@ user:
system_charset_info, 0) ||
check_host_name(&$$->host))
MYSQL_YYABORT;
+ /*
+ Convert hostname part of username to lowercase.
+ It's OK to use in-place lowercase as long as
+ the character set is utf8.
+ */
+ my_casedn_str(system_charset_info, $$->host.str);
}
| CURRENT_USER optional_braces
{
@@ -12734,6 +12746,7 @@ keyword_sp:
| FILE_SYM {}
| FIRST_SYM {}
| FIXED_SYM {}
+ | GENERAL {}
| GENERATED_SYM {}
| GEOMETRY_SYM {}
| GEOMETRYCOLLECTION {}
@@ -12744,6 +12757,7 @@ keyword_sp:
| HOSTS_SYM {}
| HOUR_SYM {}
| IDENTIFIED_SYM {}
+ | IGNORE_SERVER_IDS_SYM {}
| INDEX_STATS_SYM {}
| INVOKER_SYM {}
| IMPORT {}
@@ -12767,6 +12781,7 @@ keyword_sp:
| LOGS_SYM {}
| MAX_ROWS {}
| MASTER_SYM {}
+ | MASTER_HEARTBEAT_PERIOD_SYM {}
| MASTER_HOST_SYM {}
| MASTER_PORT_SYM {}
| MASTER_LOG_FILE_SYM {}
@@ -12836,6 +12851,7 @@ keyword_sp:
| PROCESSLIST_SYM {}
| PROFILE_SYM {}
| PROFILES_SYM {}
+ | PROXY_SYM {}
| QUARTER_SYM {}
| QUERY_SYM {}
| QUICK {}
@@ -12872,6 +12888,7 @@ keyword_sp:
| SIMPLE_SYM {}
| SHARE_SYM {}
| SHUTDOWN {}
+ | SLOW {}
| SNAPSHOT_SYM {}
| SOUNDS_SYM {}
| SOURCE_SYM {}
@@ -13226,7 +13243,7 @@ option_value:
if (!(user=(LEX_USER*) thd->alloc(sizeof(LEX_USER))))
MYSQL_YYABORT;
user->host=null_lex_str;
- user->user.str=thd->security_ctx->priv_user;
+ user->user.str=thd->security_ctx->user;
set_var_password *var= new set_var_password(user, $3);
if (var == NULL)
MYSQL_YYABORT;
@@ -13423,9 +13440,6 @@ table_lock:
MDL_SHARED_NO_READ_WRITE :
MDL_SHARED_READ)))
MYSQL_YYABORT;
- /* If table is to be write locked, protect from a impending GRL. */
- if (lock_for_write)
- Lex->protect_against_global_read_lock= TRUE;
}
;
@@ -13508,6 +13522,13 @@ handler:
handler_read_or_scan where_clause opt_limit_clause
{
Lex->expr_allows_subselect= TRUE;
+ /* Stored functions are not supported for HANDLER READ. */
+ if (Lex->uses_stored_routines())
+ {
+ my_error(ER_NOT_SUPPORTED_YET, MYF(0),
+ "stored functions in HANDLER ... READ");
+ MYSQL_YYABORT;
+ }
}
;
@@ -13586,6 +13607,13 @@ revoke_command:
{
Lex->sql_command = SQLCOM_REVOKE_ALL;
}
+ | PROXY_SYM ON user FROM grant_list
+ {
+ LEX *lex= Lex;
+ lex->users_list.push_front ($3);
+ lex->sql_command= SQLCOM_REVOKE;
+ lex->type= TYPE_ENUM_PROXY;
+ }
;
grant:
@@ -13625,6 +13653,13 @@ grant_command:
lex->sql_command= SQLCOM_GRANT;
lex->type= TYPE_ENUM_PROCEDURE;
}
+ | PROXY_SYM ON user TO_SYM grant_list opt_grant_option
+ {
+ LEX *lex= Lex;
+ lex->users_list.push_front ($3);
+ lex->sql_command= SQLCOM_GRANT;
+ lex->type= TYPE_ENUM_PROXY;
+ }
;
opt_table:
@@ -13814,10 +13849,15 @@ grant_list:
}
;
+via_or_with: VIA_SYM | WITH ;
+using_or_as: USING | AS ;
+
grant_user:
user IDENTIFIED_SYM BY TEXT_STRING
{
$$=$1; $1->password=$4;
+ if (Lex->sql_command == SQLCOM_REVOKE)
+ MYSQL_YYABORT;
if ($4.length)
{
if (YYTHD->variables.old_passwords)
@@ -13843,15 +13883,24 @@ grant_user:
}
}
| user IDENTIFIED_SYM BY PASSWORD TEXT_STRING
- { $$= $1; $1->password= $5; }
- | user IDENTIFIED_SYM VIA_SYM ident_or_text
+ {
+ if (Lex->sql_command == SQLCOM_REVOKE)
+ MYSQL_YYABORT;
+ $$= $1;
+ $1->password= $5;
+ }
+ | user IDENTIFIED_SYM via_or_with ident_or_text
{
+ if (Lex->sql_command == SQLCOM_REVOKE)
+ MYSQL_YYABORT;
$$= $1;
$1->plugin= $4;
$1->auth= empty_lex_str;
}
- | user IDENTIFIED_SYM VIA_SYM ident_or_text USING TEXT_STRING_sys
+ | user IDENTIFIED_SYM via_or_with ident_or_text using_or_as TEXT_STRING_sys
{
+ if (Lex->sql_command == SQLCOM_REVOKE)
+ MYSQL_YYABORT;
$$= $1;
$1->plugin= $4;
$1->auth= $6;
@@ -13927,6 +13976,11 @@ grant_options:
| WITH grant_option_list
;
+opt_grant_option:
+ /* empty */ {}
+ | WITH GRANT OPTION { Lex->grant |= GRANT_ACL;}
+ ;
+
grant_option_list:
grant_option_list grant_option {}
| grant_option {}
@@ -14075,6 +14129,11 @@ union_opt:
| union_order_or_limit { $$= 1; }
;
+opt_union_order_or_limit:
+ /* Empty */
+ | union_order_or_limit
+ ;
+
union_order_or_limit:
{
THD *thd= YYTHD;
@@ -14122,7 +14181,7 @@ query_specification:
;
query_expression_body:
- query_specification
+ query_specification opt_union_order_or_limit
| query_expression_body
UNION_SYM union_option
{
@@ -14130,6 +14189,7 @@ query_expression_body:
MYSQL_YYABORT;
}
query_specification
+ opt_union_order_or_limit
{
Lex->pop_context();
$$= $1;
diff --git a/sql/strfunc.cc b/sql/strfunc.cc
index a0e2f39f8dc..0c0742b3805 100644
--- a/sql/strfunc.cc
+++ b/sql/strfunc.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2003 MySQL AB
+/* Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -96,7 +96,7 @@ ulonglong find_set(TYPELIB *lib, const char *str, uint length, CHARSET_INFO *cs,
/*
Function to find a string in a TYPELIB
- (Same format as mysys/typelib.c)
+ (similar to find_type() of mysys/typelib.c)
SYNOPSIS
find_type()
diff --git a/sql/sys_vars.cc b/sql/sys_vars.cc
index 56440368acf..fceaad4eca9 100644
--- a/sql/sys_vars.cc
+++ b/sql/sys_vars.cc
@@ -231,14 +231,23 @@ static Sys_var_charptr Sys_basedir(
IN_FS_CHARSET, DEFAULT(0));
static Sys_var_ulong Sys_binlog_cache_size(
- "binlog_cache_size", "The size of the cache to "
- "hold the SQL statements for the binary log during a "
- "transaction. If you often use big, multi-statement "
- "transactions you can increase this to get more performance",
+ "binlog_cache_size", "The size of the transactional cache for "
+ "updates to transactional engines for the binary log. "
+ "If you often use transactions containing many statements, "
+ "you can increase this to get more performance",
GLOBAL_VAR(binlog_cache_size),
CMD_LINE(REQUIRED_ARG),
VALID_RANGE(IO_SIZE, ULONG_MAX), DEFAULT(32768), BLOCK_SIZE(IO_SIZE));
+static Sys_var_ulong Sys_binlog_stmt_cache_size(
+ "binlog_stmt_cache_size", "The size of the statement cache for "
+ "updates to non-transactional engines for the binary log. "
+ "If you often use statements updating a great number of rows, "
+ "you can increase this to get more performance",
+ GLOBAL_VAR(binlog_stmt_cache_size),
+ CMD_LINE(REQUIRED_ARG),
+ VALID_RANGE(IO_SIZE, ULONG_MAX), DEFAULT(32768), BLOCK_SIZE(IO_SIZE));
+
static bool check_has_super(sys_var *self, THD *thd, set_var *var)
{
DBUG_ASSERT(self->scope() != sys_var::GLOBAL);// don't abuse check_has_super()
@@ -684,7 +693,7 @@ static bool event_scheduler_update(sys_var *self, THD *thd, enum_var_type type)
: Events::stop();
mysql_mutex_lock(&LOCK_global_system_variables);
if (ret)
- my_error(ER_EVENT_SET_VAR_ERROR, MYF(0));
+ my_error(ER_EVENT_SET_VAR_ERROR, MYF(0), 0);
return ret;
}
@@ -1019,23 +1028,49 @@ static bool session_readonly(sys_var *self, THD *thd, set_var *var)
self->name.str, "GLOBAL");
return true;
}
+
+static bool
+check_max_allowed_packet(sys_var *self, THD *thd, set_var *var)
+{
+ longlong val;
+ if (session_readonly(self, thd, var))
+ return true;
+
+ val= var->save_result.ulonglong_value;
+ if (val < (longlong) global_system_variables.net_buffer_length)
+ {
+ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ WARN_OPTION_BELOW_LIMIT, ER(WARN_OPTION_BELOW_LIMIT),
+ "max_allowed_packet", "net_buffer_length");
+ }
+ return false;
+}
+
+
static Sys_var_ulong Sys_max_allowed_packet(
"max_allowed_packet",
"Max packet length to send to or receive from the server",
SESSION_VAR(max_allowed_packet), CMD_LINE(REQUIRED_ARG),
VALID_RANGE(1024, 1024*1024*1024), DEFAULT(1024*1024),
BLOCK_SIZE(1024), NO_MUTEX_GUARD, NOT_IN_BINLOG,
- ON_CHECK(session_readonly));
+ ON_CHECK(check_max_allowed_packet));
static Sys_var_ulonglong Sys_max_binlog_cache_size(
"max_binlog_cache_size",
- "Can be used to restrict the total size used to cache a "
- "multi-transaction query",
+ "Sets the total size of the transactional cache",
GLOBAL_VAR(max_binlog_cache_size), CMD_LINE(REQUIRED_ARG),
VALID_RANGE(IO_SIZE, ULONGLONG_MAX),
DEFAULT((ULONGLONG_MAX/IO_SIZE)*IO_SIZE),
BLOCK_SIZE(IO_SIZE));
+static Sys_var_ulonglong Sys_max_binlog_stmt_cache_size(
+ "max_binlog_stmt_cache_size",
+ "Sets the total size of the statement cache",
+ GLOBAL_VAR(max_binlog_stmt_cache_size), CMD_LINE(REQUIRED_ARG),
+ VALID_RANGE(IO_SIZE, ULONGLONG_MAX),
+ DEFAULT((ULONGLONG_MAX/IO_SIZE)*IO_SIZE),
+ BLOCK_SIZE(IO_SIZE));
+
static bool fix_max_binlog_size(sys_var *self, THD *thd, enum_var_type type)
{
mysql_bin_log.set_max_size(max_binlog_size);
@@ -1164,6 +1199,16 @@ static Sys_var_harows Sys_sql_max_join_size(
NO_MUTEX_GUARD, NOT_IN_BINLOG, ON_CHECK(0),
ON_UPDATE(fix_max_join_size), DEPRECATED(70000, 0));
+static Sys_var_ulong Sys_max_long_data_size(
+ "max_long_data_size",
+ "The maximum BLOB length to send to server from "
+ "mysql_send_long_data API. Deprecated option; "
+ "use max_allowed_packet instead.",
+ READ_ONLY GLOBAL_VAR(max_long_data_size),
+ CMD_LINE(REQUIRED_ARG, OPT_MAX_LONG_DATA_SIZE),
+ VALID_RANGE(1024, UINT_MAX32), DEFAULT(1024*1024),
+ BLOCK_SIZE(1));
+
static PolyLock_mutex PLock_prepared_stmt_count(&LOCK_prepared_stmt_count);
static Sys_var_ulong Sys_max_prepared_stmt_count(
"max_prepared_stmt_count",
@@ -1239,12 +1284,29 @@ static Sys_var_mybool Sys_named_pipe(
DEFAULT(FALSE));
#endif
+
+static bool
+check_net_buffer_length(sys_var *self, THD *thd, set_var *var)
+{
+ longlong val;
+ if (session_readonly(self, thd, var))
+ return true;
+
+ val= var->save_result.ulonglong_value;
+ if (val > (longlong) global_system_variables.max_allowed_packet)
+ {
+ push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
+ WARN_OPTION_BELOW_LIMIT, ER(WARN_OPTION_BELOW_LIMIT),
+ "max_allowed_packet", "net_buffer_length");
+ }
+ return false;
+}
static Sys_var_ulong Sys_net_buffer_length(
"net_buffer_length",
"Buffer length for TCP/IP and socket communication",
SESSION_VAR(net_buffer_length), CMD_LINE(REQUIRED_ARG),
VALID_RANGE(1024, 1024*1024), DEFAULT(16384), BLOCK_SIZE(1024),
- NO_MUTEX_GUARD, NOT_IN_BINLOG, ON_CHECK(session_readonly));
+ NO_MUTEX_GUARD, NOT_IN_BINLOG, ON_CHECK(check_net_buffer_length));
static bool fix_net_read_timeout(sys_var *self, THD *thd, enum_var_type type)
{
@@ -1428,6 +1490,14 @@ static Sys_var_uint Sys_protocol_version(
READ_ONLY GLOBAL_VAR(protocol_version), NO_CMD_LINE,
VALID_RANGE(0, ~0), DEFAULT(PROTOCOL_VERSION), BLOCK_SIZE(1));
+static Sys_var_proxy_user Sys_proxy_user(
+ "proxy_user", "The proxy user account name used when logging in",
+ IN_SYSTEM_CHARSET);
+
+static Sys_var_external_user Sys_exterenal_user(
+ "external_user", "The external user account used when logging in",
+ IN_SYSTEM_CHARSET);
+
static Sys_var_ulong Sys_read_buff_size(
"read_buffer_size",
"Each thread that does a sequential scan allocates a buffer of "
@@ -1437,7 +1507,6 @@ static Sys_var_ulong Sys_read_buff_size(
VALID_RANGE(IO_SIZE*2, INT_MAX32), DEFAULT(128*1024),
BLOCK_SIZE(IO_SIZE));
-static my_bool read_only;
static bool check_read_only(sys_var *self, THD *thd, set_var *var)
{
/* Prevent self dead-lock */
@@ -1521,6 +1590,16 @@ static bool fix_read_only(sys_var *self, THD *thd, enum_var_type type)
read_only= opt_readonly;
DBUG_RETURN(result);
}
+
+
+/**
+ The read_only boolean is always equal to the opt_readonly boolean except
+ during fix_read_only(); when that function is entered, opt_readonly is
+ the pre-update value and read_only is the post-update value.
+ fix_read_only() compares them and runs needed operations for the
+ transition (especially when transitioning from false to true) and
+ synchronizes both booleans in the end.
+*/
static Sys_var_mybool Sys_readonly(
"read_only",
"Make all non-temporary tables read-only, with the exception for "
@@ -2417,17 +2496,17 @@ static ulonglong read_timestamp(THD *thd)
static bool check_timestamp(sys_var *self, THD *thd, set_var *var)
{
- time_t val;
+ longlong val;
if (!var->value)
return FALSE;
- val= (time_t) var->save_result.ulonglong_value;
- if (val < (time_t) MY_TIME_T_MIN || val > (time_t) MY_TIME_T_MAX)
+ val= (longlong) var->save_result.ulonglong_value;
+ if (val != 0 && // this is how you set the default value
+ (val < TIMESTAMP_MIN_VALUE || val > TIMESTAMP_MAX_VALUE))
{
- my_message(ER_UNKNOWN_ERROR,
- "This version of MySQL doesn't support dates later than 2038",
- MYF(0));
+ char buf[64];
+ my_error(ER_WRONG_VALUE_FOR_VAR, MYF(0), "timestamp", llstr(val, buf));
return TRUE;
}
return FALSE;
@@ -2445,7 +2524,7 @@ static bool update_last_insert_id(THD *thd, set_var *var)
{
if (!var->value)
{
- my_error(ER_NO_DEFAULT, MYF(0), var->var->name);
+ my_error(ER_NO_DEFAULT, MYF(0), var->var->name.str);
return true;
}
thd->first_successful_insert_id_in_prev_stmt=
@@ -2494,7 +2573,7 @@ static bool update_insert_id(THD *thd, set_var *var)
{
if (!var->value)
{
- my_error(ER_NO_DEFAULT, MYF(0), var->var->name);
+ my_error(ER_NO_DEFAULT, MYF(0), var->var->name.str);
return true;
}
thd->force_one_auto_inc_interval(var->save_result.ulonglong_value);
@@ -2517,7 +2596,7 @@ static bool update_rand_seed1(THD *thd, set_var *var)
{
if (!var->value)
{
- my_error(ER_NO_DEFAULT, MYF(0), var->var->name);
+ my_error(ER_NO_DEFAULT, MYF(0), var->var->name.str);
return true;
}
thd->rand.seed1= (ulong) var->save_result.ulonglong_value;
@@ -2539,7 +2618,7 @@ static bool update_rand_seed2(THD *thd, set_var *var)
{
if (!var->value)
{
- my_error(ER_NO_DEFAULT, MYF(0), var->var->name);
+ my_error(ER_NO_DEFAULT, MYF(0), var->var->name.str);
return true;
}
thd->rand.seed2= (ulong) var->save_result.ulonglong_value;
@@ -2743,7 +2822,7 @@ static Sys_var_charptr Sys_slow_log_path(
ON_CHECK(check_log_path), ON_UPDATE(fix_slow_log_file));
/// @todo deprecate these four legacy have_PLUGIN variables and use I_S instead
-export SHOW_COMP_OPTION have_csv, have_innodb;
+export SHOW_COMP_OPTION have_csv, have_innodb= SHOW_OPTION_DISABLED;
export SHOW_COMP_OPTION have_ndbcluster, have_partitioning;
static Sys_var_have Sys_have_csv(
"have_csv", "have_csv",
@@ -2946,11 +3025,8 @@ static bool fix_slave_net_timeout(sys_var *self, THD *thd, enum_var_type type)
(active_mi? active_mi->heartbeat_period : 0.0)));
if (active_mi && slave_net_timeout < active_mi->heartbeat_period)
push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN,
- ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE,
- "The current value for master_heartbeat_period"
- " exceeds the new value of `slave_net_timeout' sec."
- " A sensible value for the period should be"
- " less than the timeout.");
+ ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX,
+ ER(ER_SLAVE_HEARTBEAT_VALUE_OUT_OF_RANGE_MAX));
mysql_mutex_unlock(&LOCK_active_mi);
return false;
}
@@ -3072,7 +3148,7 @@ static bool check_locale(sys_var *self, THD *thd, set_var *var)
String str(buff, sizeof(buff), system_charset_info), *res;
if (!(res=var->value->val_str(&str)))
return true;
- else if (!(locale= my_locale_by_name(res->c_ptr())))
+ else if (!(locale= my_locale_by_name(res->c_ptr_safe())))
{
ErrConvString err(res);
my_error(ER_UNKNOWN_LOCALE, MYF(0), err.ptr());
diff --git a/sql/sys_vars.h b/sql/sys_vars.h
index 25ad412e62c..348fede994b 100644
--- a/sql/sys_vars.h
+++ b/sql/sys_vars.h
@@ -452,6 +452,65 @@ public:
{ return type != STRING_RESULT; }
};
+
+class Sys_var_proxy_user: public sys_var
+{
+public:
+ Sys_var_proxy_user(const char *name_arg,
+ const char *comment, enum charset_enum is_os_charset_arg)
+ : sys_var(&all_sys_vars, name_arg, comment,
+ sys_var::READONLY+sys_var::ONLY_SESSION, 0, -1,
+ NO_ARG, SHOW_CHAR, 0, NULL, VARIABLE_NOT_IN_BINLOG,
+ NULL, NULL, 0, NULL, PARSE_NORMAL)
+ {
+ is_os_charset= is_os_charset_arg == IN_FS_CHARSET;
+ option.var_type= GET_STR;
+ }
+ bool do_check(THD *thd, set_var *var)
+ {
+ DBUG_ASSERT(FALSE);
+ return true;
+ }
+ bool session_update(THD *thd, set_var *var)
+ {
+ DBUG_ASSERT(FALSE);
+ return true;
+ }
+ bool global_update(THD *thd, set_var *var)
+ {
+ DBUG_ASSERT(FALSE);
+ return false;
+ }
+ void session_save_default(THD *thd, set_var *var)
+ { DBUG_ASSERT(FALSE); }
+ void global_save_default(THD *thd, set_var *var)
+ { DBUG_ASSERT(FALSE); }
+ bool check_update_type(Item_result type)
+ { return true; }
+protected:
+ virtual uchar *session_value_ptr(THD *thd, LEX_STRING *base)
+ {
+ return thd->security_ctx->proxy_user[0] ?
+ (uchar *) &(thd->security_ctx->proxy_user[0]) : NULL;
+ }
+};
+
+class Sys_var_external_user : public Sys_var_proxy_user
+{
+public:
+ Sys_var_external_user(const char *name_arg, const char *comment_arg,
+ enum charset_enum is_os_charset_arg)
+ : Sys_var_proxy_user (name_arg, comment_arg, is_os_charset_arg)
+ {}
+
+protected:
+ virtual uchar *session_value_ptr(THD *thd, LEX_STRING *base)
+ {
+ return thd->security_ctx->proxy_user[0] ?
+ (uchar *) &(thd->security_ctx->proxy_user[0]) : NULL;
+ }
+};
+
/**
The class for string variables. Useful for strings that aren't necessarily
\0-terminated. Otherwise the same as Sys_var_charptr.
@@ -1154,7 +1213,8 @@ public:
void global_save_default(THD *thd, set_var *var)
{
LEX_STRING pname;
- pname.str= *(char**)option.def_value;
+ char **default_value= reinterpret_cast<char**>(option.def_value);
+ pname.str= *default_value;
pname.length= strlen(pname.str);
plugin_ref plugin;
@@ -1519,7 +1579,10 @@ public:
void session_save_default(THD *thd, set_var *var)
{ var->save_result.ptr= global_var(void*); }
void global_save_default(THD *thd, set_var *var)
- { var->save_result.ptr= *(void**)option.def_value; }
+ {
+ void **default_value= reinterpret_cast<void**>(option.def_value);
+ var->save_result.ptr= *default_value;
+ }
bool check_update_type(Item_result type)
{ return type != INT_RESULT && type != STRING_RESULT; }
uchar *session_value_ptr(THD *thd, LEX_STRING *base)
diff --git a/sql/table.cc b/sql/table.cc
index a7fd0715f0f..f71df6b9665 100644
--- a/sql/table.cc
+++ b/sql/table.cc
@@ -1,4 +1,4 @@
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -434,6 +434,18 @@ void TABLE_SHARE::destroy()
info_it->flags= 0;
}
}
+ if (ha_data_destroy)
+ {
+ ha_data_destroy(ha_data);
+ ha_data_destroy= NULL;
+ }
+#ifdef WITH_PARTITION_STORAGE_ENGINE
+ if (ha_part_data_destroy)
+ {
+ ha_part_data_destroy(ha_part_data);
+ ha_part_data_destroy= NULL;
+ }
+#endif /* WITH_PARTITION_STORAGE_ENGINE */
/*
Make a copy since the share is allocated in its own root,
and free_root() updates its argument after freeing the memory.
@@ -748,14 +760,12 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
enum legacy_db_type legacy_db_type;
my_bitmap_map *bitmaps;
bool null_bits_are_used;
- uint vcol_screen_length, options_len;
+ uint vcol_screen_length, UNINIT_VAR(options_len);
char *vcol_screen_pos;
- uchar *options, *buff= 0;
+ uchar *UNINIT_VAR(options);
+ uchar *extra_segment_buff= 0;
DBUG_ENTER("open_binary_frm");
- LINT_INIT(options);
- LINT_INIT(options_len);
-
new_field_pack_flag= head[27];
new_frm_ver= (head[2] - FRM_VER);
field_pack_length= new_frm_ver < 2 ? 11 : 17;
@@ -950,19 +960,25 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
/* Read extra data segment */
uchar *next_chunk, *buff_end;
DBUG_PRINT("info", ("extra segment size is %u bytes", n_length));
- if (!(next_chunk= buff= (uchar*) my_malloc(n_length+1, MYF(MY_WME))))
+ if (!(extra_segment_buff= (uchar*) my_malloc(n_length + 1, MYF(MY_WME))))
goto err;
- if (mysql_file_pread(file, buff, n_length, record_offset + share->reclength,
+ next_chunk= extra_segment_buff;
+ if (mysql_file_pread(file, extra_segment_buff,
+ n_length, record_offset + share->reclength,
MYF(MY_NABP)))
- goto free_and_err;
- share->connect_string.length= uint2korr(buff);
+ {
+ goto err;
+ }
+ share->connect_string.length= uint2korr(next_chunk);
if (!(share->connect_string.str= strmake_root(&share->mem_root,
(char*) next_chunk + 2,
share->connect_string.
length)))
- goto free_and_err;
+ {
+ goto err;
+ }
next_chunk+= share->connect_string.length + 2;
- buff_end= buff + n_length;
+ buff_end= extra_segment_buff + n_length;
if (next_chunk + 2 < buff_end)
{
uint str_db_type_length= uint2korr(next_chunk);
@@ -979,7 +995,7 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
plugin_data(tmp_plugin, handlerton *)))
{
/* bad file, legacy_db_type did not match the name */
- goto free_and_err;
+ goto err;
}
/*
tmp_plugin is locked with a local lock.
@@ -1008,7 +1024,7 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
error= 8;
my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0),
"--skip-partition");
- goto free_and_err;
+ goto err;
}
plugin_unlock(NULL, share->db_plugin);
share->db_plugin= ha_lock_engine(NULL, partition_hton);
@@ -1023,7 +1039,7 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
error= 8;
name.str[name.length]=0;
my_error(ER_UNKNOWN_STORAGE_ENGINE, MYF(0), name.str);
- goto free_and_err;
+ goto err;
/* purecov: end */
}
next_chunk+= str_db_type_length + 2;
@@ -1038,13 +1054,15 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
if (!(share->partition_info_str= (char*)
memdup_root(&share->mem_root, next_chunk + 4,
partition_info_str_len + 1)))
- goto free_and_err;
+ {
+ goto err;
+ }
}
#else
if (partition_info_str_len)
{
DBUG_PRINT("info", ("WITH_PARTITION_STORAGE_ENGINE is not defined"));
- goto free_and_err;
+ goto err;
}
#endif
next_chunk+= 5 + partition_info_str_len;
@@ -1068,7 +1086,7 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
{
DBUG_PRINT("error",
("fulltext key uses parser that is not defined in .frm"));
- goto free_and_err;
+ goto err;
}
parser_name.str= (char*) next_chunk;
parser_name.length= strlen((char*) next_chunk);
@@ -1078,7 +1096,7 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
if (! keyinfo->parser)
{
my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), parser_name.str);
- goto free_and_err;
+ goto err;
}
}
}
@@ -1090,16 +1108,19 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
{
DBUG_PRINT("error",
("long table comment is not defined in .frm"));
- goto free_and_err;
+ goto err;
}
share->comment.length = uint2korr(next_chunk);
if (! (share->comment.str= strmake_root(&share->mem_root,
(char*)next_chunk + 2, share->comment.length)))
- goto free_and_err;
+ {
+ goto err;
+ }
next_chunk+= 2 + share->comment.length;
}
DBUG_ASSERT(next_chunk <= buff_end);
+
if (share->db_create_options & HA_OPTION_TEXT_CREATE_OPTIONS)
{
/*
@@ -1501,8 +1522,8 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
/* Fix key->name and key_part->field */
if (key_parts)
{
- uint primary_key=(uint) (find_type((char*) primary_key_name,
- &share->keynames, 3) - 1);
+ uint primary_key=(uint) (find_type(primary_key_name, &share->keynames,
+ FIND_TYPE_NO_PREFIX) - 1);
longlong ha_option= handler_file->ha_table_flags();
keyinfo= share->key_info;
key_part= keyinfo->key_part;
@@ -1787,24 +1808,30 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head,
if (use_hash)
(void) my_hash_check(&share->name_hash);
#endif
+ my_free(extra_segment_buff);
DBUG_RETURN (0);
- free_and_err:
- my_free(buff);
err:
share->error= error;
share->open_errno= my_errno;
share->errarg= errarg;
my_free(disk_buff);
+ my_free(extra_segment_buff);
delete crypted;
delete handler_file;
my_hash_free(&share->name_hash);
if (share->ha_data_destroy)
+ {
share->ha_data_destroy(share->ha_data);
+ share->ha_data_destroy= NULL;
+ }
#ifdef WITH_PARTITION_STORAGE_ENGINE
if (share->ha_part_data_destroy)
+ {
share->ha_part_data_destroy(share->ha_part_data);
-#endif
+ share->ha_data_destroy= NULL;
+ }
+#endif /* WITH_PARTITION_STORAGE_ENGINE */
open_table_error(share, error, share->open_errno, errarg);
DBUG_RETURN(error);
@@ -2315,7 +2342,8 @@ int open_table_from_share(THD *thd, TABLE_SHARE *share, const char *alias,
Query_arena *backup_stmt_arena_ptr= thd->stmt_arena;
Query_arena backup_arena;
- Query_arena part_func_arena(&outparam->mem_root, Query_arena::INITIALIZED);
+ Query_arena part_func_arena(&outparam->mem_root,
+ Query_arena::STMT_INITIALIZED);
thd->set_n_backup_active_arena(&part_func_arena, &backup_arena);
thd->stmt_arena= &part_func_arena;
bool tmp;
@@ -2535,7 +2563,15 @@ void free_blobs(register TABLE *table)
for (ptr= table->s->blob_field, end=ptr + table->s->blob_fields ;
ptr != end ;
ptr++)
- ((Field_blob*) table->field[*ptr])->free();
+ {
+ /*
+ Reduced TABLE objects which are used by row-based replication for
+ type conversion might have some fields missing. Skip freeing BLOB
+ buffers for such missing fields.
+ */
+ if (table->field[*ptr])
+ ((Field_blob*) table->field[*ptr])->free();
+ }
}
@@ -2769,7 +2805,7 @@ void open_table_error(TABLE_SHARE *share, int error, int db_errno, int errarg)
default: /* Better wrong error than none */
case 4:
strxmov(buff, share->normalized_path.str, reg_ext, NullS);
- my_error(ER_NOT_FORM_FILE, errortype, buff, 0);
+ my_error(ER_NOT_FORM_FILE, errortype, buff);
break;
}
DBUG_VOID_RETURN;
@@ -3364,7 +3400,8 @@ Table_check_intact::check(TABLE *table, const TABLE_FIELD_DEF *table_def)
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);
+ static_cast<int>(table->s->mysql_version),
+ MYSQL_VERSION_ID);
DBUG_RETURN(TRUE);
}
else if (MYSQL_VERSION_ID == table->s->mysql_version)
@@ -3519,30 +3556,7 @@ bool TABLE_SHARE::visit_subgraph(Wait_for_flush *wait_for_flush,
holding a write-lock on MDL_lock::m_rwlock.
*/
if (gvisitor->m_lock_open_count++ == 0)
- {
- /*
- To circumvent bug #56405 "Deadlock in the MDL deadlock detector"
- we don't try to lock LOCK_open mutex if some thread doing
- deadlock detection already owns it and current search depth is
- greater than 0. Instead we report a deadlock.
-
- TODO/FIXME: The proper fix for this bug is to use rwlocks for
- protection of table shares/instead of LOCK_open.
- Unfortunately it requires more effort/has significant
- performance effect.
- */
- mysql_mutex_lock(&LOCK_dd_owns_lock_open);
- if (gvisitor->m_current_search_depth > 0 && dd_owns_lock_open > 0)
- {
- mysql_mutex_unlock(&LOCK_dd_owns_lock_open);
- --gvisitor->m_lock_open_count;
- gvisitor->abort_traversal(src_ctx);
- return TRUE;
- }
- ++dd_owns_lock_open;
- mysql_mutex_unlock(&LOCK_dd_owns_lock_open);
mysql_mutex_lock(&LOCK_open);
- }
I_P_List_iterator <TABLE, TABLE_share> tables_it(used_tables);
@@ -3557,12 +3571,8 @@ bool TABLE_SHARE::visit_subgraph(Wait_for_flush *wait_for_flush,
goto end;
}
- ++gvisitor->m_current_search_depth;
if (gvisitor->enter_node(src_ctx))
- {
- --gvisitor->m_current_search_depth;
goto end;
- }
while ((table= tables_it++))
{
@@ -3585,16 +3595,10 @@ bool TABLE_SHARE::visit_subgraph(Wait_for_flush *wait_for_flush,
end_leave_node:
gvisitor->leave_node(src_ctx);
- --gvisitor->m_current_search_depth;
end:
if (gvisitor->m_lock_open_count-- == 1)
- {
mysql_mutex_unlock(&LOCK_open);
- mysql_mutex_lock(&LOCK_dd_owns_lock_open);
- --dd_owns_lock_open;
- mysql_mutex_unlock(&LOCK_dd_owns_lock_open);
- }
return result;
}
@@ -3690,6 +3694,68 @@ bool TABLE_SHARE::wait_for_old_version(THD *thd, struct timespec *abstime,
}
+/**
+ Initialize TABLE instance (newly created, or coming either from table
+ cache or THD::temporary_tables list) and prepare it for further use
+ during statement execution. Set the 'alias' attribute from the specified
+ TABLE_LIST element. Remember the TABLE_LIST element in the
+ TABLE::pos_in_table_list member.
+
+ @param thd Thread context.
+ @param tl TABLE_LIST element.
+*/
+
+void TABLE::init(THD *thd, TABLE_LIST *tl)
+{
+ DBUG_ASSERT(s->ref_count > 0 || s->tmp_table != NO_TMP_TABLE);
+
+ if (thd->lex->need_correct_ident())
+ alias_name_used= my_strcasecmp(table_alias_charset,
+ s->table_name.str,
+ tl->alias);
+ /* Fix alias if table name changes. */
+ if (strcmp(alias, tl->alias))
+ {
+ uint length= (uint) strlen(tl->alias)+1;
+ alias= (char*) my_realloc((char*) alias, length, MYF(MY_WME));
+ memcpy((char*) alias, tl->alias, length);
+ }
+
+ tablenr= thd->current_tablenr++;
+ used_fields= 0;
+ const_table= 0;
+ null_row= 0;
+ maybe_null= 0;
+ force_index= 0;
+ force_index_order= 0;
+ force_index_group= 0;
+ status= STATUS_NO_RECORD;
+ insert_values= 0;
+ fulltext_searched= 0;
+ file->ha_start_of_new_statement();
+ reginfo.impossible_range= 0;
+
+ /* Catch wrong handling of the auto_increment_field_not_null. */
+ DBUG_ASSERT(!auto_increment_field_not_null);
+ auto_increment_field_not_null= FALSE;
+
+ if (timestamp_field)
+ timestamp_field_type= timestamp_field->get_auto_set_type();
+
+ pos_in_table_list= tl;
+
+ clear_column_bitmaps();
+
+ DBUG_ASSERT(key_read == 0);
+
+ /* mark the record[0] uninitialized */
+ TRASH(table->record[0], table->s->reclength);
+
+ /* Tables may be reused in a sub statement. */
+ DBUG_ASSERT(!file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN));
+}
+
+
/*
Create Item_field for each column in the table.
@@ -4501,10 +4567,15 @@ bool TABLE_LIST::prepare_view_securety_context(THD *thd)
}
else
{
- my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
- thd->security_ctx->priv_user,
- thd->security_ctx->priv_host,
- (thd->password ? ER(ER_YES) : ER(ER_NO)));
+ if (thd->password == 2)
+ my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0),
+ thd->security_ctx->priv_user,
+ thd->security_ctx->priv_host);
+ else
+ my_error(ER_ACCESS_DENIED_ERROR, MYF(0),
+ thd->security_ctx->priv_user,
+ thd->security_ctx->priv_host,
+ (thd->password ? ER(ER_YES) : ER(ER_NO)));
}
DBUG_RETURN(TRUE);
}
@@ -5840,7 +5911,8 @@ void init_mdl_requests(TABLE_LIST *table_list)
table_list->mdl_request.init(MDL_key::TABLE,
table_list->db, table_list->table_name,
table_list->lock_type >= TL_WRITE_ALLOW_WRITE ?
- MDL_SHARED_WRITE : MDL_SHARED_READ);
+ MDL_SHARED_WRITE : MDL_SHARED_READ,
+ MDL_TRANSACTION);
}
diff --git a/sql/table.h b/sql/table.h
index 5b0a74a2828..79263723744 100644
--- a/sql/table.h
+++ b/sql/table.h
@@ -1,7 +1,7 @@
#ifndef TABLE_INCLUDED
#define TABLE_INCLUDED
-/* Copyright 2000-2008 MySQL AB, 2008-2009 Sun Microsystems, Inc.
+/* Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
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
@@ -83,18 +83,6 @@ enum enum_table_ref_type
};
-/**
- Opening modes for open_temporary_table and open_table_from_share
-*/
-
-enum open_table_mode
-{
- OTM_OPEN= 0,
- OTM_CREATE= 1,
- OTM_ALTER= 2
-};
-
-
/*************************************************************************/
/**
@@ -659,8 +647,8 @@ struct TABLE_SHARE
uint db_options_in_use; /* Options in use */
uint db_record_offset; /* if HA_REC_IN_SEQ */
uint rowid_field_offset; /* Field_nr +1 to rowid field */
- /* Index of auto-updated TIMESTAMP field in field array */
- uint primary_key;
+ /* Primary key index number, used in TABLE::key_info[] */
+ uint primary_key;
uint next_number_index; /* autoincrement key number */
uint next_number_key_offset; /* autoinc keypart offset in a key */
uint next_number_keypart; /* autoinc keypart number in a key */
@@ -1128,6 +1116,7 @@ public:
#endif
MDL_ticket *mdl_ticket;
+ void init(THD *thd, TABLE_LIST *tl);
bool fill_item_list(List<Item> *item_list) const;
void reset_item_list(List<Item> *item_list) const;
void clear_column_bitmaps(void);
@@ -1242,7 +1231,9 @@ enum enum_schema_table_state
typedef struct st_foreign_key_info
{
- LEX_STRING *forein_id;
+ LEX_STRING *foreign_id;
+ LEX_STRING *foreign_db;
+ LEX_STRING *foreign_table;
LEX_STRING *referenced_db;
LEX_STRING *referenced_table;
LEX_STRING *update_method;
@@ -1459,7 +1450,8 @@ struct TABLE_LIST
lock_type= lock_type_arg;
mdl_request.init(MDL_key::TABLE, db, table_name,
(lock_type >= TL_WRITE_ALLOW_WRITE) ?
- MDL_SHARED_WRITE : MDL_SHARED_READ);
+ MDL_SHARED_WRITE : MDL_SHARED_READ,
+ MDL_TRANSACTION);
}
/*
diff --git a/sql/transaction.cc b/sql/transaction.cc
index a28fba8805d..94a32200274 100644
--- a/sql/transaction.cc
+++ b/sql/transaction.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2008 Sun/MySQL
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -21,6 +21,7 @@
#include "sql_priv.h"
#include "transaction.h"
#include "rpl_handler.h"
+#include "debug_sync.h" // DEBUG_SYNC
/* Conditions under which the transaction state must not change. */
static bool trans_check(THD *thd)
@@ -78,6 +79,33 @@ static bool xa_trans_rolled_back(XID_STATE *xid_state)
/**
+ Rollback the active XA transaction.
+
+ @note Resets rm_error before calling ha_rollback(), so
+ the thd->transaction.xid structure gets reset
+ by ha_rollback() / THD::transaction::cleanup().
+
+ @return TRUE if the rollback failed, FALSE otherwise.
+*/
+
+static bool xa_trans_force_rollback(THD *thd)
+{
+ /*
+ We must reset rm_error before calling ha_rollback(),
+ so thd->transaction.xid structure gets reset
+ by ha_rollback()/THD::transaction::cleanup().
+ */
+ thd->transaction.xid_state.rm_error= 0;
+ if (ha_rollback_trans(thd, true))
+ {
+ my_error(ER_XAER_RMERR, MYF(0));
+ return true;
+ }
+ return false;
+}
+
+
+/**
Begin a new transaction.
@note Beginning a transaction implicitly commits any current
@@ -361,6 +389,13 @@ bool trans_savepoint(THD *thd, LEX_STRING name)
!opt_using_transactions)
DBUG_RETURN(FALSE);
+ enum xa_states xa_state= thd->transaction.xid_state.xa_state;
+ if (xa_state != XA_NOTR)
+ {
+ my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[xa_state]);
+ DBUG_RETURN(TRUE);
+ }
+
sv= find_savepoint(thd, name);
if (*sv) /* old savepoint of the same name exists */
@@ -391,15 +426,15 @@ bool trans_savepoint(THD *thd, LEX_STRING name)
thd->transaction.savepoints= newsv;
/*
- Remember the last acquired lock before the savepoint was set.
- This is used as a marker to only release locks acquired after
+ Remember locks acquired before the savepoint was set.
+ They are used as a marker to only release locks acquired after
the setting of this savepoint.
Note: this works just fine if we're under LOCK TABLES,
since mdl_savepoint() is guaranteed to be beyond
the last locked table. This allows to release some
locks acquired during LOCK TABLES.
*/
- newsv->mdl_savepoint = thd->mdl_context.mdl_savepoint();
+ newsv->mdl_savepoint= thd->mdl_context.mdl_savepoint();
DBUG_RETURN(FALSE);
}
@@ -434,6 +469,13 @@ bool trans_rollback_to_savepoint(THD *thd, LEX_STRING name)
DBUG_RETURN(TRUE);
}
+ enum xa_states xa_state= thd->transaction.xid_state.xa_state;
+ if (xa_state != XA_NOTR)
+ {
+ my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[xa_state]);
+ DBUG_RETURN(TRUE);
+ }
+
if (ha_rollback_to_savepoint(thd, sv))
res= TRUE;
else if (((thd->variables.option_bits & OPTION_KEEP_LOG) ||
@@ -565,7 +607,8 @@ bool trans_xa_end(THD *thd)
else if (!xa_trans_rolled_back(&thd->transaction.xid_state))
thd->transaction.xid_state.xa_state= XA_IDLE;
- DBUG_RETURN(thd->transaction.xid_state.xa_state != XA_IDLE);
+ DBUG_RETURN(thd->is_error() ||
+ thd->transaction.xid_state.xa_state != XA_IDLE);
}
@@ -596,7 +639,8 @@ bool trans_xa_prepare(THD *thd)
else
thd->transaction.xid_state.xa_state= XA_PREPARED;
- DBUG_RETURN(thd->transaction.xid_state.xa_state != XA_PREPARED);
+ DBUG_RETURN(thd->is_error() ||
+ thd->transaction.xid_state.xa_state != XA_PREPARED);
}
@@ -632,8 +676,8 @@ bool trans_xa_commit(THD *thd)
if (xa_trans_rolled_back(&thd->transaction.xid_state))
{
- if ((res= test(ha_rollback_trans(thd, TRUE))))
- my_error(ER_XAER_RMERR, MYF(0));
+ xa_trans_force_rollback(thd);
+ res= thd->is_error();
}
else if (xa_state == XA_IDLE && thd->lex->xa_opt == XA_ONE_PHASE)
{
@@ -643,17 +687,31 @@ bool trans_xa_commit(THD *thd)
}
else if (xa_state == XA_PREPARED && thd->lex->xa_opt == XA_NONE)
{
- if (thd->global_read_lock.wait_if_global_read_lock(thd, FALSE, FALSE))
+ MDL_request mdl_request;
+
+ /*
+ Acquire metadata lock which will ensure that COMMIT is blocked
+ by active FLUSH TABLES WITH READ LOCK (and vice versa COMMIT in
+ progress blocks FTWRL).
+
+ We allow FLUSHer to COMMIT; we assume FLUSHer knows what it does.
+ */
+ mdl_request.init(MDL_key::COMMIT, "", "", MDL_INTENTION_EXCLUSIVE,
+ MDL_TRANSACTION);
+
+ if (thd->mdl_context.acquire_lock(&mdl_request,
+ thd->variables.lock_wait_timeout))
{
ha_rollback_trans(thd, TRUE);
my_error(ER_XAER_RMERR, MYF(0));
}
else
{
+ DEBUG_SYNC(thd, "trans_xa_commit_after_acquire_commit_lock");
+
res= test(ha_commit_one_phase(thd, 1));
if (res)
my_error(ER_XAER_RMERR, MYF(0));
- thd->global_read_lock.start_waiting_global_read_lock(thd);
}
}
else
@@ -707,15 +765,7 @@ bool trans_xa_rollback(THD *thd)
DBUG_RETURN(TRUE);
}
- /*
- Resource Manager error is meaningless at this point, as we perform
- explicit rollback request by user. We must reset rm_error before
- calling ha_rollback(), so thd->transaction.xid structure gets reset
- by ha_rollback()/THD::transaction::cleanup().
- */
- thd->transaction.xid_state.rm_error= 0;
- if ((res= test(ha_rollback_trans(thd, TRUE))))
- my_error(ER_XAER_RMERR, MYF(0));
+ res= xa_trans_force_rollback(thd);
thd->variables.option_bits&= ~(OPTION_BEGIN | OPTION_KEEP_LOG);
thd->transaction.all.modified_non_trans_table= FALSE;
diff --git a/sql/unireg.cc b/sql/unireg.cc
index b4fbd2aea3e..2d75d1a6356 100644
--- a/sql/unireg.cc
+++ b/sql/unireg.cc
@@ -1,4 +1,4 @@
-/* Copyright (C) 2000-2006 MySQL AB, 2008-2009 Sun Microsystems, Inc
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -11,8 +11,7 @@
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 */
-
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/*
Functions to create a unireg form-file from a FIELD and a fieldname-fieldinfo
@@ -244,13 +243,13 @@ bool mysql_create_frm(THD *thd, const char *file_name,
(MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)))
{
my_error(ER_TOO_LONG_TABLE_COMMENT, MYF(0),
- real_table_name, (uint) TABLE_COMMENT_MAXLEN);
+ real_table_name, static_cast<ulong>(TABLE_COMMENT_MAXLEN));
my_free(screen_buff);
DBUG_RETURN(1);
}
char warn_buff[MYSQL_ERRMSG_SIZE];
my_snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_TABLE_COMMENT),
- real_table_name, (uint) TABLE_COMMENT_MAXLEN);
+ real_table_name, static_cast<ulong>(TABLE_COMMENT_MAXLEN));
/* do not push duplicate warnings */
if (!check_duplicate_warning(current_thd, warn_buff, strlen(warn_buff)))
push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
@@ -709,13 +708,14 @@ static bool pack_header(uchar *forminfo, enum legacy_db_type table_type,
if ((current_thd->variables.sql_mode &
(MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES)))
{
- my_error(ER_TOO_LONG_FIELD_COMMENT, MYF(0),
- field->field_name, (uint) COLUMN_COMMENT_MAXLEN);
+ my_error(ER_TOO_LONG_FIELD_COMMENT, MYF(0), field->field_name,
+ static_cast<ulong>(COLUMN_COMMENT_MAXLEN));
DBUG_RETURN(1);
}
char warn_buff[MYSQL_ERRMSG_SIZE];
my_snprintf(warn_buff, sizeof(warn_buff), ER(ER_TOO_LONG_FIELD_COMMENT),
- field->field_name, (uint) COLUMN_COMMENT_MAXLEN);
+ field->field_name,
+ static_cast<ulong>(COLUMN_COMMENT_MAXLEN));
/* do not push duplicate warnings */
if (!check_duplicate_warning(current_thd, warn_buff, strlen(warn_buff)))
push_warning(current_thd, MYSQL_ERROR::WARN_LEVEL_WARN,
@@ -825,7 +825,7 @@ static bool pack_header(uchar *forminfo, enum legacy_db_type table_type,
if (reclength > (ulong) file->max_record_length())
{
- my_error(ER_TOO_BIG_ROWSIZE, MYF(0), (uint) file->max_record_length());
+ my_error(ER_TOO_BIG_ROWSIZE, MYF(0), static_cast<long>(file->max_record_length()));
DBUG_RETURN(1);
}
/* Hack to avoid bugs with small static rows in MySQL */
diff --git a/sql/unireg.h b/sql/unireg.h
index 028cb0546d8..bafd9c96e47 100644
--- a/sql/unireg.h
+++ b/sql/unireg.h
@@ -1,7 +1,7 @@
#ifndef UNIREG_INCLUDED
#define UNIREG_INCLUDED
-/* Copyright (C) 2000-2006 MySQL AB
+/* Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
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
@@ -56,8 +56,6 @@ typedef struct st_ha_create_information HA_CREATE_INFO;
#define ER_THD_OR_DEFAULT(thd,X) ((thd) ? ER_THD(thd, X) : ER_DEFAULT(X))
-#define ERRMAPP 1 /* Errormap f|r my_error */
-
#define ME_INFO (ME_HOLDTANG+ME_OLDWIN+ME_NOREFRESH)
#define ME_ERROR (ME_BELL+ME_OLDWIN+ME_NOREFRESH)
#define MYF_RW MYF(MY_WME+MY_NABP) /* Vid my_read & my_write */