diff options
| author | Mikael Ronstrom <mikael@dator8> | 2011-01-04 18:46:01 +0100 |
|---|---|---|
| committer | Mikael Ronstrom <mikael@dator8> | 2011-01-04 18:46:01 +0100 |
| commit | c1986098bf5e4748b416e2e4d451baa55a9f3cee (patch) | |
| tree | 3099d3c6d9977c59627e466389081f2dae42b159 /sql | |
| parent | 7311054d1579462f13320a0ef12ed869bc0dc3f9 (diff) | |
| parent | 7313acfef7491fbfc722f7c84744955065a6360a (diff) | |
| download | mariadb-git-c1986098bf5e4748b416e2e4d451baa55a9f3cee.tar.gz | |
merge
Diffstat (limited to 'sql')
153 files changed, 8636 insertions, 5013 deletions
diff --git a/sql/CMakeLists.txt b/sql/CMakeLists.txt index 9d307da364d..4c75ae39755 100644 --- a/sql/CMakeLists.txt +++ b/sql/CMakeLists.txt @@ -50,6 +50,7 @@ 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 opt_range.cc opt_range.h opt_sum.cc ../sql-common/pack.c parse_file.cc password.c procedure.cc protocol.cc records.cc repl_failsafe.cc rpl_filter.cc set_var.cc @@ -131,7 +132,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}) @@ -282,7 +283,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 1bc195a2981..00000000000 --- a/sql/Makefile.am +++ /dev/null @@ -1,279 +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) -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@ \ - @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 \ - 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_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 - -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 - -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 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 7d103d5904d..ff35cff2440 100644 --- a/sql/client_settings.h +++ b/sql/client_settings.h @@ -21,6 +21,7 @@ #endif /* CLIENT_SETTINGS_INCLUDED */ #include <thr_alarm.h> +#include <sql_common.h> #define CLIENT_CAPABILITIES (CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | \ CLIENT_SECURE_CONNECTION | CLIENT_TRANSACTIONS | \ @@ -33,7 +34,8 @@ #undef HAVE_SMEM #undef _CUSTOMCONFIG_ -#define mysql_server_init(a,b,c) 0 +#define mysql_server_init(a,b,c) mysql_client_plugin_init() +#define mysql_server_end() mysql_client_plugin_deinit() #ifdef HAVE_REPLICATION C_MODE_START diff --git a/sql/debug_sync.cc b/sql/debug_sync.cc index 1390bac8352..5ec4953b546 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--; diff --git a/sql/event_data_objects.cc b/sql/event_data_objects.cc index 52c509621ac..ef14a061677 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,¬_used); } - last_executed_changed= FALSE; if ((ptr= get_field(&mem_root, table->field[ET_FIELD_STATUS])) == NullS) DBUG_RETURN(TRUE); @@ -935,7 +933,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; } @@ -955,7 +952,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; } @@ -1018,7 +1014,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 { @@ -1108,7 +1103,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; } @@ -1144,50 +1138,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, @@ -1526,7 +1481,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 9d17213bcb8..46740812d31 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 db508e4ea41..053558aa0c3 100644 --- a/sql/event_db_repository.cc +++ b/sql/event_db_repository.cc @@ -622,6 +622,12 @@ Event_db_repository::create_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(); DBUG_ENTER("Event_db_repository::create_event"); @@ -699,8 +705,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)); @@ -734,6 +740,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"); @@ -811,8 +823,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)); @@ -838,6 +850,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"); @@ -866,8 +884,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)); } @@ -940,7 +958,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)); @@ -1042,15 +1060,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"); @@ -1075,20 +1092,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 ea7f3bbac0e..58484d17f06 100644 --- a/sql/event_db_repository.h +++ b/sql/event_db_repository.h @@ -101,9 +101,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_queue.cc b/sql/event_queue.cc index f0310c676d1..bdc8fa258a8 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 @@ -444,7 +446,6 @@ Event_queue::recalculate_activation_times(THD *thd) for (i= 0; i < queue.elements; 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); /* @@ -567,6 +568,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(); @@ -632,8 +635,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")); @@ -656,9 +665,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); } @@ -741,11 +757,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 10a7535425f..23a0dc9eb52 100644 --- a/sql/events.cc +++ b/sql/events.cc @@ -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; @@ -340,7 +340,9 @@ 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))) @@ -388,7 +390,6 @@ Events::create_event(THD *thd, Event_parse_data *parse_data, } } } - 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) @@ -472,7 +473,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, @@ -485,10 +488,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 { /* @@ -505,7 +505,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) @@ -559,7 +558,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))) { @@ -569,7 +570,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) @@ -598,15 +598,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; } @@ -918,12 +915,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} }; @@ -977,23 +973,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 1482e736d29..a337b29049a 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 */ @@ -44,19 +43,6 @@ class THD; typedef class Item COND; typedef struct charset_info_st CHARSET_INFO; -/* 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); @@ -92,7 +78,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 728cd7e4090..50db2da97e4 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, 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 @@ -1564,7 +1564,7 @@ void Field::make_field(Send_field *field) } else field->org_table_name= field->db_name= ""; - if (orig_table) + if (orig_table && orig_table->alias) { field->table_name= orig_table->alias; field->org_col_name= field_name; @@ -4189,7 +4189,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) @@ -4512,7 +4512,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) @@ -6327,10 +6327,13 @@ int Field_str::store(double nr) ASSERT_COLUMN_MARKED_FOR_WRITE; 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) @@ -7725,12 +7728,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 @@ -7751,8 +7748,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; } @@ -8396,6 +8392,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 diff --git a/sql/field.h b/sql/field.h index 7b250c34fe4..e3db95260c3 100644 --- a/sql/field.h +++ b/sql/field.h @@ -554,6 +554,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 */ @@ -598,6 +640,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); @@ -678,6 +746,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; @@ -918,41 +997,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); } }; @@ -1187,6 +1238,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; } @@ -1216,6 +1268,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; } @@ -1320,6 +1373,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; } @@ -1369,6 +1423,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; } @@ -1408,6 +1463,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; } @@ -1447,6 +1503,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 @@ -1515,6 +1572,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; } @@ -1595,6 +1653,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; } @@ -1690,6 +1749,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); @@ -1839,6 +1899,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); @@ -1870,6 +1931,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; @@ -1895,6 +1957,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 ea6ff82e0aa..20c647ccc00 100644 --- a/sql/field_conv.cc +++ b/sql/field_conv.cc @@ -787,11 +787,8 @@ int field_conv(Field *to,Field *from) ((Field_varstring*)from)->length_bytes == ((Field_varstring*)to)->length_bytes)) { // Identical fields -#ifdef HAVE_purify - /* 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/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 15b017ece81..20745db9ce9 100644 --- a/sql/ha_ndbcluster.cc +++ b/sql/ha_ndbcluster.cc @@ -6435,8 +6435,8 @@ void ha_ndbcluster::get_auto_increment(ulonglong offset, ulonglong increment, for (;;) { Ndb_tuple_id_range_guard g(m_share); - if (m_skip_auto_increment && - ndb->readAutoIncrementValue(m_table, g.range, auto_value) || + 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)) { if (--retries && @@ -7382,38 +7382,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. */ @@ -9503,7 +9500,7 @@ pthread_handler_t ndb_util_thread_func(void *arg __attribute__((unused))) thd->client_capabilities = 0; my_net_init(&thd->net, 0); thd->main_security_ctx.master_access= ~0; - thd->main_security_ctx.priv_user = 0; + thd->main_security_ctx.priv_user[0] = 0; /* Do not use user-supplied timeout value for system threads. */ thd->variables.lock_wait_timeout= LONG_TIMEOUT; @@ -10271,8 +10268,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 861b44f74b1..e46b6b25f9c 100644 --- a/sql/ha_ndbcluster_binlog.cc +++ b/sql/ha_ndbcluster_binlog.cc @@ -3656,7 +3656,7 @@ pthread_handler_t ndb_binlog_thread_func(void *arg) thd->client_capabilities= 0; my_net_init(&thd->net, 0); thd->main_security_ctx.master_access= ~0; - thd->main_security_ctx.priv_user= 0; + thd->main_security_ctx.priv_user[0]= 0; /* Do not use user-supplied timeout value for system threads. */ thd->variables.lock_wait_timeout= LONG_TIMEOUT; diff --git a/sql/ha_partition.cc b/sql/ha_partition.cc index d9f69a0b28d..f717870915f 100644 --- a/sql/ha_partition.cc +++ b/sql/ha_partition.cc @@ -3093,7 +3093,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 @@ -3129,6 +3131,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); @@ -3162,7 +3180,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); } @@ -3229,11 +3249,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; @@ -3337,113 +3370,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 @@ -4382,8 +4430,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++) { @@ -4618,6 +4670,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) @@ -4642,6 +4695,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) @@ -5118,6 +5172,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) @@ -5149,7 +5205,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)); @@ -5203,7 +5259,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; @@ -5285,7 +5341,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; @@ -5295,7 +5351,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; @@ -5311,7 +5367,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) @@ -5328,7 +5384,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)); @@ -5342,7 +5398,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; @@ -5698,7 +5754,6 @@ int ha_partition::extra(enum ha_extra_function operation) DBUG_RETURN(prepare_for_rename()); break; case HA_EXTRA_PREPARE_FOR_UPDATE: - DBUG_ASSERT(m_extra_cache); /* Needs to be run on the first partition in the range now, and later in late_extra_cache, when switching to a new partition to scan. @@ -5706,6 +5761,8 @@ int ha_partition::extra(enum ha_extra_function operation) m_extra_prepare_for_update= TRUE; if (m_part_spec.start_part != NO_CURRENT_PART_ID) { + if (!m_extra_cache) + m_extra_cache_part_id= m_part_spec.start_part; DBUG_ASSERT(m_extra_cache_part_id == m_part_spec.start_part); (void) m_file[m_part_spec.start_part]->extra(HA_EXTRA_PREPARE_FOR_UPDATE); } @@ -5977,19 +6034,22 @@ void ha_partition::late_extra_cache(uint partition_id) { handler *file; DBUG_ENTER("ha_partition::late_extra_cache"); - DBUG_PRINT("info", ("extra_cache %u partid %u size %u", m_extra_cache, + DBUG_PRINT("info", ("extra_cache %u prepare %u partid %u size %u", + m_extra_cache, m_extra_prepare_for_update, partition_id, m_extra_cache_size)); if (!m_extra_cache && !m_extra_prepare_for_update) DBUG_VOID_RETURN; file= m_file[partition_id]; - if (m_extra_cache_size == 0) - (void) file->extra(HA_EXTRA_CACHE); - else - (void) file->extra_opt(HA_EXTRA_CACHE, m_extra_cache_size); + if (m_extra_cache) + { + if (m_extra_cache_size == 0) + (void) file->extra(HA_EXTRA_CACHE); + else + (void) file->extra_opt(HA_EXTRA_CACHE, m_extra_cache_size); + } if (m_extra_prepare_for_update) { - DBUG_ASSERT(m_extra_cache); (void) file->extra(HA_EXTRA_PREPARE_FOR_UPDATE); } m_extra_cache_part_id= partition_id; @@ -6323,8 +6383,8 @@ 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 { @@ -6361,9 +6421,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_ONLINE_ADD_INDEX_NO_WRITES; + flags_to_check|= HA_ONLINE_DROP_INDEX_NO_WRITES; + if ((flags_to_return & flags_to_check) != flags_to_check) + flags_to_return&= ~flags_to_check; + flags_to_check= HA_ONLINE_ADD_UNIQUE_INDEX_NO_WRITES; + flags_to_check|= HA_ONLINE_DROP_UNIQUE_INDEX_NO_WRITES; + if ((flags_to_return & flags_to_check) != flags_to_check) + flags_to_return&= ~flags_to_check; + flags_to_check= HA_ONLINE_ADD_PK_INDEX_NO_WRITES; + flags_to_check|= HA_ONLINE_DROP_PK_INDEX_NO_WRITES; + if ((flags_to_return & flags_to_check) != flags_to_check) + flags_to_return&= ~flags_to_check; + flags_to_check= HA_ONLINE_ADD_INDEX; + flags_to_check|= HA_ONLINE_DROP_INDEX; + if ((flags_to_return & flags_to_check) != flags_to_check) + flags_to_return&= ~flags_to_check; + flags_to_check= HA_ONLINE_ADD_UNIQUE_INDEX; + flags_to_check|= HA_ONLINE_DROP_UNIQUE_INDEX; + if ((flags_to_return & flags_to_check) != flags_to_check) + flags_to_return&= ~flags_to_check; + flags_to_check= HA_ONLINE_ADD_PK_INDEX; + flags_to_check|= HA_ONLINE_DROP_PK_INDEX; + if ((flags_to_return & flags_to_check) != flags_to_check) + flags_to_return&= ~flags_to_check; + DBUG_RETURN(flags_to_return); } @@ -6398,6 +6491,7 @@ int ha_partition::add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys) handler **file; int ret= 0; + DBUG_ENTER("ha_partition::add_index"); /* 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 @@ -6405,8 +6499,28 @@ int ha_partition::add_index(TABLE *table_arg, KEY *key_info, uint num_of_keys) */ for (file= m_file; *file; file++) if ((ret= (*file)->add_index(table_arg, key_info, num_of_keys))) - break; - return ret; + 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); } diff --git a/sql/ha_partition.h b/sql/ha_partition.h index 353e0d17159..57456ddf8ae 100644 --- a/sql/ha_partition.h +++ b/sql/ha_partition.h @@ -346,6 +346,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: @@ -354,6 +355,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) || diff --git a/sql/handler.cc b/sql/handler.cc index 567dbe6ea49..4e8af034fd8 100644 --- a/sql/handler.cc +++ b/sql/handler.cc @@ -29,8 +29,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 @@ -41,6 +39,7 @@ #include "transaction.h" #include <errno.h> #include "probes_mysql.h" +#include "debug_sync.h" // DEBUG_SYNC #ifdef WITH_PARTITION_STORAGE_ENGINE #include "ha_partition.h" @@ -1155,8 +1154,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 */ @@ -1166,11 +1166,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 && @@ -1208,7 +1224,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))))) { @@ -1216,17 +1232,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) @@ -2185,7 +2213,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: @@ -2194,13 +2223,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; } @@ -2411,7 +2450,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 /* @@ -2442,6 +2481,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))) @@ -3209,6 +3251,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() @@ -4145,7 +4202,7 @@ int handler::read_multi_range_first(KEY_MULTI_RANGE **found_range_p, */ int handler::read_multi_range_next(KEY_MULTI_RANGE **found_range_p) { - int result; + int UNINIT_VAR(result); DBUG_ENTER("handler::read_multi_range_next"); /* We should not be called after the last call returned EOF. */ diff --git a/sql/handler.h b/sql/handler.h index b1d64a1114b..0e03ea17dde 100644 --- a/sql/handler.h +++ b/sql/handler.h @@ -174,6 +174,8 @@ /* 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). + 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*/ @@ -1331,6 +1333,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); @@ -1644,8 +1647,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() @@ -2010,16 +2038,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/item.cc b/sql/item.cc index e782e90b874..18a88d64470 100644 --- a/sql/item.cc +++ b/sql/item.cc @@ -226,8 +226,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); @@ -1783,8 +1781,7 @@ bool agg_item_set_converter(DTCollation &coll, const char *fname, 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; + arena= thd->activate_stmt_arena_if_needed(&backup); for (i= 0, arg= args; i < nargs; i++, arg+= item_sep) { @@ -1815,16 +1812,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)) - { - /* - We should disable const subselect item evaluation because - subselect transformation does not happen in view_prepare_mode - and thus val_...() methods can not be called for const items. - */ - bool resolve_const= ((*arg)->type() == Item::SUBSELECT_ITEM && - thd->lex->view_prepare_mode) ? FALSE : TRUE; - conv= new Item_func_conv_charset(*arg, coll.collation, resolve_const); - } + conv= new Item_func_conv_charset(*arg, coll.collation, 1); if (!conv) { @@ -1854,11 +1842,12 @@ bool agg_item_set_converter(DTCollation &coll, const char *fname, *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); @@ -3459,19 +3448,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: @@ -3483,8 +3469,6 @@ Item_param::set_value(THD *thd, sp_rcontext *ctx, Item **it) return TRUE; set_decimal(dv); - param_type= MYSQL_TYPE_NEWDECIMAL; - break; } @@ -3516,6 +3500,7 @@ void Item_param::set_out_param_info(Send_field *info) { m_out_param_info= info; + param_type= m_out_param_info->type; } @@ -3561,6 +3546,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; @@ -5532,17 +5518,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) @@ -5553,12 +5565,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); @@ -5830,6 +5839,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: @@ -7356,9 +7369,11 @@ 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->field_type() == MYSQL_TYPE_DATE || + item->field_type() == MYSQL_TYPE_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: @@ -7492,9 +7507,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) { /* @@ -7508,6 +7533,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) @@ -7530,13 +7557,14 @@ String *Item_cache_datetime::val_str(String *str) { int was_cut; longlong res; - res= number_to_datetime(val_int(), <ime, TIME_FUZZY_DATE, &was_cut); + res= number_to_datetime(int_value, <ime, TIME_FUZZY_DATE, &was_cut); if (res == -1) return NULL; } str_value.length(my_TIME_to_str(<ime, const_cast<char*>(str_value.ptr()))); str_value_cached= TRUE; + null_value= FALSE; } else if (!cache_value()) return NULL; @@ -7557,7 +7585,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; } @@ -7565,7 +7593,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 8e8199ecac8..6d10c6a6076 100644 --- a/sql/item.h +++ b/sql/item.h @@ -1,7 +1,7 @@ #ifndef ITEM_INCLUDED #define ITEM_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 @@ -2572,7 +2572,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); @@ -3451,8 +3451,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 b7aad733e67..fe8ff3a74d0 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, 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 @@ -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)) @@ -1036,7 +1036,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); @@ -3029,6 +3029,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(); @@ -4706,12 +4714,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) || @@ -4726,9 +4735,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 @@ -4745,13 +4754,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 diff --git a/sql/item_cmpfunc.h b/sql/item_cmpfunc.h index f9851011563..b6928d63ea0 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 672e59986d5..1ae65926013 100644 --- a/sql/item_create.cc +++ b/sql/item_create.cc @@ -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(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* @@ -4924,6 +4972,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)}, diff --git a/sql/item_func.cc b/sql/item_func.cc index e20cae16094..27e069df3c4 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, 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 @@ -180,7 +180,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 @@ -1538,9 +1545,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: @@ -2555,7 +2567,7 @@ void Item_func_min_max::fix_length_and_dec() stored to the value pointer, if latter is provided. RETURN - 0 If one of arguments is NULL + 0 If one of arguments is NULL or there was a execution error # index of the least/greatest argument */ @@ -2569,6 +2581,14 @@ uint Item_func_min_max::cmp_datetimes(ulonglong *value) Item **arg= args + i; bool is_null; longlong res= get_datetime_value(thd, &arg, 0, datetime_item, &is_null); + + /* Check if we need to stop (because of error or KILL) and stop the loop */ + if (thd->is_error()) + { + null_value= 1; + return 0; + } + if ((null_value= args[i]->null_value)) return 0; if (i == 0 || (res < min_max ? cmp_sign : -cmp_sign) > 0) @@ -2597,6 +2617,12 @@ String *Item_func_min_max::val_str(String *str) if (null_value) return 0; str_res= args[min_max_idx]->val_str(str); + if (args[min_max_idx]->null_value) + { + // check if the call to val_str() above returns a NULL value + null_value= 1; + return NULL; + } str_res->set_charset(collation.collation); return str_res; } @@ -3679,48 +3705,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); + + /* But only if not past the absolute timeout. */ + if (cmp_timespec(timeout, m_abs_timeout) > 0) + timeout= m_abs_timeout; - timeout-= slice; - set_timespec_nsec(abstime, slice); - error= mysql_cond_timedwait(cond, lock, &abstime); + 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. @@ -3736,10 +3806,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"); /* @@ -3800,12 +3871,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; while (ull->locked && !thd->killed) { DBUG_PRINT("info", ("waiting on lock")); thd_wait_begin(thd, THD_WAIT_USER_LOCK); - error= interruptible_wait(thd, &ull->cond, &LOCK_user_locks, timeout); + error= timed_cond.wait(&ull->cond, &LOCK_user_locks); thd_wait_end(thd); if (error == ETIMEDOUT || error == ETIME) { @@ -4001,6 +4074,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; @@ -4020,6 +4094,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); @@ -4031,7 +4107,7 @@ longlong Item_func_sleep::val_int() while (!thd->killed) { thd_wait_begin(thd, THD_WAIT_SLEEP); - error= interruptible_wait(thd, &cond, &LOCK_user_locks, timeout); + error= timed_cond.wait(&cond, &LOCK_user_locks); thd_wait_end(thd); if (error == ETIMEDOUT || error == ETIME) break; @@ -4266,7 +4342,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; @@ -4629,6 +4705,14 @@ longlong Item_func_set_user_var::val_int_result() return entry->val_int(&null_value); } +bool Item_func_set_user_var::val_bool_result() +{ + DBUG_ASSERT(fixed == 1); + check(TRUE); + update(); // Store expression + return entry->val_int(&null_value) != 0; +} + String *Item_func_set_user_var::str_result(String *str) { DBUG_ASSERT(fixed == 1); @@ -5007,7 +5091,7 @@ void Item_func_get_user_var::fix_length_and_dec() decimals=0; break; case STRING_RESULT: - max_length= MAX_BLOB_WIDTH; + max_length= MAX_BLOB_WIDTH - 1; break; case DECIMAL_RESULT: fix_char_length(DECIMAL_MAX_STR_LENGTH); @@ -5661,7 +5745,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) { @@ -6409,7 +6503,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 834ecd60e21..1139442fe76 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, 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 @@ -1416,6 +1416,7 @@ public: my_decimal *val_decimal(my_decimal *); double val_result(); longlong val_int_result(); + bool val_bool_result(); String *str_result(String *str); my_decimal *val_decimal_result(my_decimal *); bool is_null_result(); @@ -1594,7 +1595,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 25755de1e2c..84034841ad5 100644 --- a/sql/item_geofunc.h +++ b/sql/item_geofunc.h @@ -179,6 +179,21 @@ public: item_type=it; } String *val_str(String *); + void fix_length_and_dec() + { + for (unsigned int i= 0; i < arg_count; ++i) + { + if (args[i]->fixed && args[i]->field_type() != MYSQL_TYPE_GEOMETRY) + { + String str; + args[i]->print(&str, QT_ORDINARY); + str.append('\0'); + my_error(ER_ILLEGAL_VALUE_FOR_TYPE, MYF(0), "non geometric", + str.ptr()); + } + } + } + const char *func_name() const { return "multipoint"; } }; diff --git a/sql/item_row.cc b/sql/item_row.cc index 2fbf0c12499..94515640625 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(); diff --git a/sql/item_strfunc.cc b/sql/item_strfunc.cc index 6d3514bf356..2a93bcd0153 100644 --- a/sql/item_strfunc.cc +++ b/sql/item_strfunc.cc @@ -1080,9 +1080,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) @@ -1184,6 +1190,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); @@ -2299,7 +2319,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; @@ -2323,7 +2344,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]) @@ -2724,6 +2745,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 @@ -2813,6 +2848,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) @@ -3127,6 +3176,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(")); diff --git a/sql/item_strfunc.h b/sql/item_strfunc.h index 5dcef2e671f..d76e139883c 100644 --- a/sql/item_strfunc.h +++ b/sql/item_strfunc.h @@ -657,6 +657,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: diff --git a/sql/item_subselect.cc b/sql/item_subselect.cc index 56bd8c75a20..9efe2a54f8b 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 @@ -131,20 +131,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"); @@ -279,6 +265,7 @@ bool Item_subselect::exec() if (thd->is_error() || thd->killed) return 1; + 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. @@ -315,7 +302,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) @@ -1646,7 +1633,8 @@ bool Item_in_subselect::fix_fields(THD *thd_arg, Item **ref) { bool result = 0; - 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) result = left_expr->fix_fields(thd_arg, &left_expr); return result || Item_subselect::fix_fields(thd_arg, ref); @@ -1910,19 +1898,28 @@ 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 && item->const_item()) + !(join->select_options & SELECT_DESCRIBE)) { - /* - 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()) - DBUG_RETURN(1); /* purecov: inspected */ + 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. + */ + if (join->need_tmp && join->init_save_join_tab()) + DBUG_RETURN(1); /* purecov: inspected */ + } } if (item->engine_changed) { diff --git a/sql/item_subselect.h b/sql/item_subselect.h index d8d18fd8ef6..3f8726eddc7 100644 --- a/sql/item_subselect.h +++ b/sql/item_subselect.h @@ -138,7 +138,6 @@ public: virtual void reset_value_registration() {} enum_parsing_place place() { return parsing_place; } bool walk(Item_processor processor, bool walk_subquery, uchar *arg); - 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 b6e5d6d3182..0fd526184c4 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 @@ -1196,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); } @@ -1325,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); @@ -1355,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); @@ -1471,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); @@ -1576,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; } @@ -1960,11 +1968,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; } @@ -1983,11 +1991,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; } @@ -2229,7 +2237,7 @@ void Item_sum_avg::reset_field() void Item_sum_bit::reset_field() { - reset(); + reset_and_add(); int8store(result_field->ptr, bits); } @@ -3028,6 +3036,7 @@ Item_func_group_concat(Name_resolution_context *context_arg, order_item->item= arg_ptr++; } } + memcpy(orig_args, args, sizeof(Item*) * arg_count); } @@ -3239,7 +3248,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; } @@ -3395,8 +3403,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 ")); @@ -3404,7 +3410,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) { @@ -3413,7 +3419,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 06a8c2c58a4..634d593935f 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: /** @@ -396,14 +406,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. */ @@ -446,7 +464,7 @@ public: set_aggregator(with_distinct ? Aggregator::DISTINCT_AGGREGATOR : Aggregator::SIMPLE_AGGREGATOR); - reset(); + aggregator_clear(); } virtual void make_unique() { force_copy_fields= TRUE; } Item *get_tmp_table_item(THD *thd); @@ -600,6 +618,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); @@ -623,6 +644,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(); }; @@ -970,7 +994,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; @@ -979,14 +1003,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 cc363398fdd..73b8b6047e0 100644 --- a/sql/item_timefunc.cc +++ b/sql/item_timefunc.cc @@ -2338,8 +2338,6 @@ void Item_extract::print(String *str, enum_query_type query_type) void Item_extract::fix_length_and_dec() { - value.alloc(32); // alloc buffer - maybe_null=1; // If wrong date switch (int_type) { case INTERVAL_YEAR: max_length=4; date_value=1; break; @@ -2382,6 +2380,8 @@ longlong Item_extract::val_int() } else { + char buf[40]; + String value(buf, sizeof(buf), &my_charset_bin);; String *res= args[0]->val_str(&value); if (!res || str_to_time_with_warn(res->charset(), res->ptr(), res->length(), @@ -2526,14 +2526,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); @@ -2568,9 +2568,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()); @@ -2857,10 +2857,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; @@ -2886,41 +2887,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, µseconds); + time->neg= calc_time_diff(&l_time1, &l_time2, -l_sign, + &seconds, µseconds); /* 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; @@ -2928,6 +2926,38 @@ null_date: } +String *Item_func_add_time::val_str(String *str) +{ + MYSQL_TIME ltime; + date_time_format_types format; + + val_datetime(<ime, &format); + + if (null_value) + return 0; + + if (!make_datetime_with_warn(format, <ime, 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(<ime, &format); + + if (null_value) + return 0; + + return TIME_to_ulonglong_datetime(<ime); +} + + void Item_func_add_time::print(String *str, enum_query_type query_type) { if (is_date) @@ -3435,7 +3465,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 6e31b5c6705..72a5aa0c296 100644 --- a/sql/item_timefunc.h +++ b/sql/item_timefunc.h @@ -361,6 +361,7 @@ 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; } @@ -733,7 +734,6 @@ public: class Item_extract :public Item_int_func { - String value; bool date_value; public: const interval_type int_type; // keep it public @@ -949,6 +949,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 diff --git a/sql/item_xmlfunc.cc b/sql/item_xmlfunc.cc index f124c37f0eb..49d18b1bb0f 100644 --- a/sql/item_xmlfunc.cc +++ b/sql/item_xmlfunc.cc @@ -2798,12 +2798,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 582334620ad..288afd034a9 100644 --- a/sql/key.cc +++ b/sql/key.cc @@ -361,12 +361,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 fbedddc6941..6d5d711eb60 100644 --- a/sql/lex.h +++ b/sql/lex.h @@ -420,8 +420,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 5abf90b0047..79fafd48e00 100644 --- a/sql/lock.cc +++ b/sql/lock.cc @@ -779,8 +779,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); @@ -795,13 +798,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 @@ -817,12 +820,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; @@ -838,9 +838,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); @@ -890,45 +894,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 @@ -962,11 +945,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. @@ -987,89 +965,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) - { - thd_wait_begin(thd, THD_WAIT_GLOBAL_LOCK); - mysql_cond_wait(&COND_global_read_lock, &LOCK_global_read_lock); - thd_wait_end(thd); - } - 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 @@ -1095,168 +1001,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")); - thd_wait_begin(thd, THD_WAIT_GLOBAL_LOCK); - mysql_cond_wait(&COND_global_read_lock, &LOCK_global_read_lock); - thd_wait_end(thd); - 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. @@ -1275,8 +1035,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 @@ -1284,46 +1043,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) - { - thd_wait_begin(thd, THD_WAIT_GLOBAL_LOCK); - mysql_cond_wait(&COND_global_read_lock, &LOCK_global_read_lock); - thd_wait_end(thd); - } - 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 0e15c3b8e79..b9be66f8ce7 100644 --- a/sql/log.cc +++ b/sql/log.cc @@ -209,11 +209,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()); @@ -257,11 +257,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()); } @@ -292,6 +300,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. */ @@ -321,6 +359,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. @@ -334,7 +406,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); @@ -343,7 +415,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) { @@ -1362,7 +1447,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)) @@ -1506,57 +1591,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. @@ -1579,23 +1729,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 @@ -1620,51 +1771,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. @@ -1692,7 +1798,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()) @@ -1701,7 +1807,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); } /* @@ -1710,17 +1816,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); } @@ -1737,7 +1841,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); @@ -1757,16 +1861,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)) @@ -1782,9 +1886,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: @@ -1796,7 +1900,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) && @@ -1806,10 +1909,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; @@ -1832,11 +1932,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"); @@ -1846,9 +1947,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; } @@ -1865,6 +1977,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; @@ -2072,7 +2185,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); @@ -2099,7 +2213,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++='.'; /* @@ -2116,7 +2234,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))) @@ -2177,7 +2299,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]; @@ -2205,7 +2331,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, @@ -2340,13 +2471,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; } @@ -2389,7 +2515,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); @@ -2846,17 +2976,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 + key_file_binlog, +#endif + log_name, log_type_arg, new_name, io_cache_type_arg)) { #ifdef HAVE_REPLICATION close_purge_index_file(); @@ -2946,7 +3096,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); @@ -2965,7 +3115,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 } } @@ -3295,7 +3445,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) @@ -3324,7 +3474,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: @@ -3428,7 +3579,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, @@ -3556,7 +3707,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())) { @@ -3571,7 +3722,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. */ @@ -3581,7 +3732,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); @@ -3989,17 +4140,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); } @@ -4008,19 +4165,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) @@ -4058,7 +4219,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; @@ -4072,7 +4233,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; } /* @@ -4100,17 +4268,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); } @@ -4135,8 +4342,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 @@ -4167,8 +4373,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(); @@ -4357,7 +4562,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))) { @@ -4366,8 +4571,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); } @@ -4619,7 +4829,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(); @@ -4644,6 +4854,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) { @@ -4704,7 +4915,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); @@ -4785,7 +4996,6 @@ bool MYSQL_BIN_LOG::write(Log_event *event_info) goto err; error= 0; - err: if (event_info->use_direct_logging()) { @@ -4810,7 +5020,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(); @@ -4890,8 +5100,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 @@ -4900,26 +5121,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() @@ -5105,6 +5338,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; @@ -5117,7 +5354,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); } @@ -5177,7 +5414,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(cache, false, false))) @@ -5192,7 +5429,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); @@ -5226,7 +5463,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); @@ -6059,7 +6297,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); @@ -6077,6 +6315,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() @@ -6309,19 +6548,19 @@ 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) { @@ -6329,7 +6568,7 @@ void TC_LOG_BINLOG::unlog(ulong cookie, my_xid xid) 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 5df05e7ff90..05f8a4ce286 100644 --- a/sql/log.h +++ b/sql/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 @@ -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: @@ -318,8 +334,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; @@ -349,7 +365,7 @@ public: 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 +408,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(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 +432,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. diff --git a/sql/log_event.cc b/sql/log_event.cc index 16290c58685..b9da915ba96 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 @@ -1239,7 +1244,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: @@ -1327,8 +1332,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")); @@ -2325,7 +2332,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; @@ -2962,7 +2969,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) @@ -3234,7 +3246,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())); @@ -3286,6 +3299,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) @@ -3346,6 +3371,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); } @@ -3420,7 +3447,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, @@ -3506,7 +3534,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 @@ -4743,7 +4771,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)); @@ -4937,7 +4965,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; @@ -4954,6 +4982,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;); @@ -6112,8 +6142,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); } @@ -8397,6 +8441,7 @@ 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->open_type= OT_BASE_ONLY; /* We record in the slave's information that the table should be @@ -8501,7 +8546,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) { @@ -8738,16 +8783,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) @@ -9591,11 +9631,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 5d7250d8ebd..1aa4af6c751 100644 --- a/sql/log_event.h +++ b/sql/log_event.h @@ -1032,7 +1032,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); } @@ -1846,7 +1846,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; } @@ -2504,7 +2506,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 */ @@ -3665,16 +3667,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 924a005eec7..6cab1238b43 100644 --- a/sql/mdl.cc +++ b/sql/mdl.cc @@ -70,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 @@ -80,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; @@ -102,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: @@ -112,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; }; @@ -126,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); @@ -134,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 @@ -150,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; /** @@ -183,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); @@ -203,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); } @@ -247,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. */ @@ -364,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); @@ -383,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. */ @@ -452,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]; @@ -479,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]; @@ -546,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); } @@ -562,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); } @@ -579,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; - } - } - - if (move_from_hash_to_lock_mutex(lock)) - goto retry; + /* + 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. - return lock; -} + 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); + lock= (mdl_key->mdl_namespace() == MDL_key::GLOBAL) ? m_global_lock : + m_commit_lock; -/** - Find MDL_lock object corresponding to the key. + mysql_prlock_wrlock(&lock->m_rwlock); - @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()); @@ -626,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)) @@ -694,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 @@ -729,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) { @@ -752,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); } @@ -781,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; } @@ -799,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. @@ -856,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); @@ -877,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 + ); } @@ -1452,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. @@ -1468,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); - - *is_transactional= TRUE; + int i; - 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; } @@ -1563,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)); @@ -1577,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)); @@ -1599,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; @@ -1608,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. */ @@ -1626,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; } @@ -1661,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. */ @@ -1674,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()); + } } } @@ -1761,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); @@ -1773,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); @@ -1789,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); } @@ -1832,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; @@ -1873,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) @@ -1942,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"); @@ -1959,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); @@ -1983,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); } @@ -2070,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 @@ -2133,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); @@ -2250,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"); @@ -2263,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; @@ -2276,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. @@ -2332,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); } } @@ -2397,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, ¬_unused); DBUG_ASSERT(ticket == NULL || ticket->m_lock); @@ -2428,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; } @@ -2457,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 e1d4cf74dd6..4a9397fe215 100644 --- a/sql/mdl.h +++ b/sql/mdl.h @@ -150,6 +150,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) @@ -167,13 +176,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. @@ -184,6 +196,8 @@ public: FUNCTION, PROCEDURE, TRIGGER, + EVENT, + COMMIT, /* This should be the last ! */ NAMESPACE_END }; @@ -238,7 +252,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) @@ -305,6 +319,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. @@ -327,17 +343,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 @@ -363,6 +378,7 @@ public: MDL_request(const MDL_request *rhs) :type(rhs->type), + duration(rhs->duration), ticket(NULL), key(&rhs->key) {} @@ -385,10 +401,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 @@ -399,17 +412,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; }; /** @@ -498,17 +500,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. */ @@ -526,6 +546,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. */ @@ -573,9 +626,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; @@ -598,37 +649,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; } @@ -669,46 +711,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 @@ -723,14 +762,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 @@ -761,8 +795,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 8a31cec6721..a5b60739b26 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> diff --git a/sql/my_decimal.h b/sql/my_decimal.h index abf4b178422..e5b1573608a 100644 --- a/sql/my_decimal.h +++ b/sql/my_decimal.h @@ -328,7 +328,7 @@ 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); diff --git a/sql/mysqld.cc b/sql/mysqld.cc index af98ed91adf..c3afa1a5399 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -58,6 +58,7 @@ #include "sql_repl.h" #include "rpl_filter.h" #include "repl_failsafe.h" +#include <sql_common.h> #include <my_stacktrace.h> #include "mysqld_suffix.h" #include "mysys_err.h" @@ -97,13 +98,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_purify below as this speeds up the shutdown of MySQL */ #if defined(HAVE_DEC_3_2_THREADS) || defined(SIGNALS_DONT_BREAK_READ) || defined(HAVE_purify) && defined(__linux__) @@ -271,6 +265,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[]= @@ -328,7 +324,8 @@ static PSI_rwlock_key key_rwlock_openssl; /* the default log output is log tables */ static bool lower_case_table_names_used= 0; 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 uint kill_cached_threads, wake_thread; @@ -413,7 +410,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; @@ -464,6 +462,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; @@ -475,6 +475,7 @@ 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; /** Limit of the total number of prepared statements in the server. @@ -608,8 +609,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, @@ -629,7 +629,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; @@ -650,9 +649,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; @@ -1138,7 +1134,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")); @@ -1491,6 +1487,7 @@ void clean_up(bool print_message) sql_print_information(ER_DEFAULT(ER_SHUTDOWN_COMPLETE),my_progname); cleanup_errmsgs(); MYSQL_CALLBACK(thread_scheduler, end, ()); + mysql_client_plugin_deinit(); finish_client_errs(); (void) my_error_unregister(ER_ERROR_FIRST, ER_ERROR_LAST); // finish server errs DBUG_PRINT("quit", ("Error messages freed")); @@ -1548,7 +1545,6 @@ static void clean_up_mutexes() mysql_mutex_destroy(&LOCK_crypt); mysql_mutex_destroy(&LOCK_user_conn); mysql_mutex_destroy(&LOCK_connection_count); - Events::destroy_mutexes(); #ifdef HAVE_OPENSSL mysql_mutex_destroy(&LOCK_des_key_file); #ifndef HAVE_YASSL @@ -1566,12 +1562,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); @@ -1966,38 +1960,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 */ @@ -2437,7 +2421,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" @@ -2465,11 +2449,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\ @@ -2686,14 +2672,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, @@ -2758,7 +2736,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 | @@ -3216,6 +3194,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)); @@ -3253,20 +3236,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) @@ -3351,6 +3333,7 @@ static int init_common_variables() if (init_errmessage()) /* Read error messages from file */ return 1; init_client_errs(); + mysql_client_plugin_init(); lex_init(); if (item_create_init()) return 1; @@ -3533,8 +3516,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, @@ -3562,7 +3543,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); @@ -3787,12 +3767,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) @@ -4958,10 +4938,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; @@ -5002,7 +4982,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); delete thd; DBUG_VOID_RETURN; } @@ -5383,7 +5363,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; } @@ -5578,7 +5558,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; } @@ -5671,6 +5651,12 @@ 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", OPT_AUTOCOMMIT, "Set default value for autocommit (0 or 1)", + NULL, NULL, 0, GET_BOOL, OPT_ARG, 0, 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}, @@ -5740,11 +5726,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}, @@ -6420,6 +6401,8 @@ SHOW_VAR status_vars[]= { {"Aborted_connects", (char*) &aborted_connects, SHOW_LONG}, {"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}, {"Bytes_received", (char*) offsetof(STATUS_VAR, bytes_received), SHOW_LONGLONG_STATUS}, {"Bytes_sent", (char*) offsetof(STATUS_VAR, bytes_sent), SHOW_LONGLONG_STATUS}, {"Com", (char*) com_status_vars, SHOW_ARRAY}, @@ -6613,13 +6596,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."); @@ -7133,6 +7111,13 @@ mysqld_get_one_option(int optid, if (argument == NULL) /* no argument */ log_error_file_ptr= const_cast<char*>(""); break; + case OPT_AUTOCOMMIT: + const ulonglong turn_bit_on= (argument && (atoi(argument) == 0)) ? + OPTION_NOT_AUTOCOMMIT : OPTION_AUTOCOMMIT; + global_system_variables.option_bits= + (global_system_variables.option_bits & + ~(OPTION_NOT_AUTOCOMMIT | OPTION_AUTOCOMMIT)) | turn_bit_on; + break; } return 0; } @@ -7355,6 +7340,8 @@ 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; + return 0; } @@ -7675,7 +7662,7 @@ 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_manager, key_LOCK_prepared_stmt_count, key_LOCK_rpl_status, key_LOCK_server_started, key_LOCK_status, @@ -7713,7 +7700,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}, @@ -7762,7 +7748,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, @@ -7785,7 +7771,6 @@ static PSI_cond_info all_server_conds[]= { &key_BINLOG_COND_prep_xids, "MYSQL_BIN_LOG::COND_prep_xids", 0}, { &key_BINLOG_update_cond, "MYSQL_BIN_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}, @@ -7844,9 +7829,10 @@ 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; static PSI_file_info all_server_files[]= { @@ -7869,11 +7855,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 6e81c240f7d..9218503d477 100644 --- a/sql/mysqld.h +++ b/sql/mysqld.h @@ -64,7 +64,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); @@ -100,14 +100,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; @@ -152,6 +153,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; @@ -171,8 +173,9 @@ 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; @@ -227,7 +230,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, @@ -248,7 +251,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, @@ -270,9 +273,10 @@ 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; void init_server_psi_keys(); #endif /* HAVE_PSI_INTERFACE */ @@ -320,7 +324,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; @@ -333,7 +337,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; @@ -391,7 +394,8 @@ enum options_mysqld OPT_UPDATE_LOG, OPT_WANT_CORE, OPT_ENGINE_CONDITION_PUSHDOWN, - OPT_LOG_ERROR + OPT_LOG_ERROR, + OPT_AUTOCOMMIT }; diff --git a/sql/net_serv.cc b/sql/net_serv.cc index 488e27296b6..ab88e87be69 100644 --- a/sql/net_serv.cc +++ b/sql/net_serv.cc @@ -1,4 +1,4 @@ -/* Copyright (C) 2000 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 diff --git a/sql/opt_range.cc b/sql/opt_range.cc index ffff9e3f6c8..4cdabab31ae 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 @@ -5796,6 +5796,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() && @@ -8277,7 +8278,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"); ); @@ -11390,7 +11391,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(); } @@ -11422,7 +11423,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 33b3d561ad8..caff3c622b8 100644 --- a/sql/opt_range.h +++ b/sql/opt_range.h @@ -279,6 +279,7 @@ public: virtual bool reverse_sorted() = 0; virtual bool unique_key_range() { return false; } + virtual bool clustered_pk_range() { return false; } enum { QS_TYPE_RANGE = 0, @@ -335,6 +336,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 @@ -553,6 +561,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; }; @@ -605,6 +631,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. @@ -655,6 +697,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_sum.cc b/sql/opt_sum.cc index e020c94a3bd..a2f8b9c4447 100644 --- a/sql/opt_sum.cc +++ b/sql/opt_sum.cc @@ -424,7 +424,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; diff --git a/sql/partition_info.cc b/sql/partition_info.cc index caf28fdd83e..b54339db354 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 b77cb618a46..3b69705cc87 100644 --- a/sql/password.c +++ b/sql/password.c @@ -223,13 +223,13 @@ void scramble_323(char *to, const char *message, const char *password) */ my_bool -check_scramble_323(const char *scrambled, const char *message, +check_scramble_323(const unsigned char *scrambled, const char *message, ulong *hash_pass) { struct rand_struct rand_st; ulong hash_message[2]; - char buff[16],*to,extra; /* Big enough for check */ - const char *pos; + uchar buff[16],*to,extra; /* Big enough for check */ + const uchar *pos; hash_password(hash_message, message, SCRAMBLE_LENGTH_323); randominit(&rand_st,hash_pass[0] ^ hash_message[0], @@ -244,7 +244,7 @@ check_scramble_323(const char *scrambled, const char *message, to=buff; while (*scrambled) { - if (*scrambled++ != (char) (*to++ ^ extra)) + if (*scrambled++ != (uchar) (*to++ ^ extra)) return 1; /* Wrong password */ } return 0; @@ -510,7 +510,7 @@ scramble(char *to, const char *message, const char *password) */ my_bool -check_scramble(const char *scramble_arg, const char *message, +check_scramble(const uchar *scramble_arg, const char *message, const uint8 *hash_stage2) { SHA1_CONTEXT sha1_context; @@ -523,7 +523,7 @@ check_scramble(const char *scramble_arg, const char *message, mysql_sha1_input(&sha1_context, hash_stage2, SHA1_HASH_SIZE); mysql_sha1_result(&sha1_context, buf); /* encrypt scramble */ - my_crypt((char *) buf, buf, (const uchar *) scramble_arg, SCRAMBLE_LENGTH); + my_crypt((char *) buf, buf, scramble_arg, SCRAMBLE_LENGTH); /* now buf supposedly contains hash_stage1: so we can get hash_stage2 */ mysql_sha1_reset(&sha1_context); mysql_sha1_input(&sha1_context, buf, SHA1_HASH_SIZE); diff --git a/sql/protocol.cc b/sql/protocol.cc index 953656d3a4f..03b151e4346 100644 --- a/sql/protocol.cc +++ b/sql/protocol.cc @@ -349,24 +349,6 @@ static bool write_eof_packet(THD *thd, NET *net, } /** - Please client to send scrambled_password in old format. - - @param thd thread handle - - @retval - 0 ok - @retval - !0 error -*/ - -bool send_old_password_request(THD *thd) -{ - NET *net= &thd->net; - return my_net_write(net, eof_buff, 1) || net_flush(net); -} - - -/** @param thd Thread handler @param sql_errno The error code to send @param err A pointer to the error message @@ -523,11 +505,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(), diff --git a/sql/protocol.h b/sql/protocol.h index f661c7663e5..1c86c6d6c49 100644 --- a/sql/protocol.h +++ b/sql/protocol.h @@ -204,7 +204,6 @@ public: void send_warning(THD *thd, uint sql_errno, const char *err=0); bool net_send_error(THD *thd, uint sql_errno, const char *err, const char* sqlstate); -bool send_old_password_request(THD *thd); uchar *net_store_data(uchar *to,const uchar *from, size_t length); uchar *net_store_data(uchar *to,int32 from); uchar *net_store_data(uchar *to,longlong from); diff --git a/sql/records.cc b/sql/records.cc index ccacdc33b36..d713c34dffe 100644 --- a/sql/records.cc +++ b/sql/records.cc @@ -206,6 +206,15 @@ void 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)) // Test if ref-records was used diff --git a/sql/repl_failsafe.cc b/sql/repl_failsafe.cc index 47eb2f7031d..540b62b9d3b 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; @@ -68,7 +68,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) diff --git a/sql/repl_failsafe.h b/sql/repl_failsafe.h index c6d00de47cb..a0c41686696 100644 --- a/sql/repl_failsafe.h +++ b/sql/repl_failsafe.h @@ -26,7 +26,7 @@ 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; @@ -34,7 +34,7 @@ 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); diff --git a/sql/rpl_handler.cc b/sql/rpl_handler.cc index 5f16544d855..4355942e47f 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_injector.cc b/sql/rpl_injector.cc index 75ccb617e9e..52c8b9f0655 100644 --- a/sql/rpl_injector.cc +++ b/sql/rpl_injector.cc @@ -237,8 +237,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) @@ -246,6 +245,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 d02aadee701..df20690d8d8 100644 --- a/sql/rpl_rli.cc +++ b/sql/rpl_rli.cc @@ -1278,6 +1278,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 bf8381933c0..09b58d4f3a0 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.h b/sql/scheduler.h index 40f0e28bc2c..b5a175434b6 100644 --- a/sql/scheduler.h +++ b/sql/scheduler.h @@ -57,6 +57,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 diff --git a/sql/set_var.cc b/sql/set_var.cc index 34b66dea319..27865aee3c2 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 @@ -746,9 +746,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, diff --git a/sql/set_var.h b/sql/set_var.h index 2972b430e48..52679aa636c 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 9e7fdbfeae5..b0dc4d9195b 100644 --- a/sql/share/errmsg-utf8.txt +++ b/sql/share/errmsg-utf8.txt @@ -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" @@ -6346,3 +6346,51 @@ ER_STORED_FUNCTION_PREVENTS_SWITCH_SQL_LOG_BIN 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" diff --git a/sql/slave.cc b/sql/slave.cc index dff6b6946d4..e081d2406be 100644 --- a/sql/slave.cc +++ b/sql/slave.cc @@ -523,7 +523,8 @@ int terminate_slave_threads(Master_info* mi,int thread_mask,bool skip_lock) 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))) + 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))) @@ -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,7 +890,17 @@ 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 " @@ -2503,7 +2522,7 @@ static int exec_relay_log_event(THD* thd, Relay_log_info* rli) if (slave_trans_retries) { - int temp_err; + int UNINIT_VAR(temp_err); if (exec_res && (temp_err= has_temporary_error(thd))) { const char *errmsg; @@ -2534,9 +2553,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); @@ -3003,7 +3020,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) { @@ -3385,6 +3402,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 @@ -3392,7 +3410,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); @@ -3615,8 +3633,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 */); } /* @@ -4727,12 +4744,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) @@ -4799,12 +4870,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 @@ -4817,7 +4889,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 @@ -4834,7 +4907,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 4073c90b612..73db3e4b61e 100644 --- a/sql/slave.h +++ b/sql/slave.h @@ -205,7 +205,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 8821dc9365d..ae11c2ad14c 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> @@ -440,7 +440,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); @@ -922,6 +922,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); @@ -941,8 +943,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. */ @@ -1190,6 +1191,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)); @@ -1198,8 +1201,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))) @@ -1270,6 +1272,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)); @@ -1278,8 +1282,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))) @@ -1355,6 +1358,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 @@ -1367,7 +1472,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(); DBUG_ENTER("sp_drop_db_routines"); DBUG_PRINT("enter", ("db: %s", db)); @@ -1636,38 +1741,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) { @@ -1723,7 +1796,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); @@ -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 a95bbe094c0..6959d21abd6 100644 --- a/sql/sp_head.cc +++ b/sql/sp_head.cc @@ -1176,10 +1176,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 @@ -1187,7 +1194,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[NAME_LEN+1]; @@ -1213,7 +1220,30 @@ sp_head::execute(THD *thd) Object_creation_ctx *saved_creation_ctx; Warning_info *saved_warning_info, warning_info(thd->warning_info->warn_id()); - /* 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,8 +1491,15 @@ sp_head::execute(THD *thd) thd->stmt_arena= old_arena; state= 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: @@ -1476,7 +1513,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 @@ -1684,7 +1721,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); @@ -1901,7 +1938,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); @@ -2106,6 +2143,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(); @@ -2134,7 +2173,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; @@ -2941,6 +2980,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) @@ -3028,14 +3069,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); @@ -3056,7 +3094,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); @@ -3065,7 +3108,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()) @@ -3113,7 +3156,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); @@ -4136,7 +4179,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 */ @@ -4180,7 +4224,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..5efd48fc7c6 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. diff --git a/sql/sp_rcontext.h b/sql/sp_rcontext.h index 1af758ed0af..ec8d82063e4 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 19373507955..5ac31d1f578 100644 --- a/sql/sql_acl.cc +++ b/sql/sql_acl.cc @@ -44,6 +44,11 @@ #include "transaction.h" #include "lock.h" // MYSQL_LOCK_IGNORE_TIMEOUT #include "records.h" // init_read_record, end_read_record +#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; @@ -164,7 +169,334 @@ TABLE_FIELD_TYPE mysql_db_table_fields[MYSQL_DB_FIELD_COUNT] = { const TABLE_FIELD_DEF mysql_db_table_def= {MYSQL_DB_FIELD_COUNT, mysql_db_table_fields}; +static LEX_STRING native_password_plugin_name= { + C_STRING_WITH_LEN("mysql_native_password") +}; + +static LEX_STRING old_password_plugin_name= { + C_STRING_WITH_LEN("mysql_old_password") +}; + +/// @todo make it configurable +LEX_STRING *default_auth_plugin_name= &native_password_plugin_name; + +#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 +}; + +class ACL_ACCESS { +public: + ulong sort; + ulong access; +}; + +/* ACL_HOST is used if no host is specified */ + +class ACL_HOST :public ACL_ACCESS +{ +public: + acl_host_and_ip host; + char *db; +}; + +class ACL_USER :public ACL_ACCESS +{ +public: + acl_host_and_ip host; + uint hostname_length; + USER_RESOURCES user_resource; + char *user; + 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; + LEX_STRING plugin; + LEX_STRING auth_string; + + ACL_USER *copy(MEM_ROOT *root) + { + ACL_USER *dst= (ACL_USER *) alloc_root(root, sizeof(ACL_USER)); + if (!dst) + return 0; + *dst= *this; + dst->user= safe_strdup_root(root, user); + dst->ssl_cipher= safe_strdup_root(root, ssl_cipher); + dst->x509_issuer= safe_strdup_root(root, x509_issuer); + dst->x509_subject= safe_strdup_root(root, x509_subject); + if (plugin.str == native_password_plugin_name.str || + plugin.str == old_password_plugin_name.str) + 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->host.hostname= safe_strdup_root(root, host.hostname); + return dst; + } +}; + +class ACL_DB :public ACL_ACCESS +{ +public: + acl_host_and_ip host; + 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 @@ -184,10 +516,29 @@ 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) -static DYNAMIC_ARRAY acl_hosts,acl_users,acl_dbs; +#if defined(HAVE_OPENSSL) +/* + Without SSL the handshake consists of one packet. This packet + 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_capabilities field will be ignored. + Maybe it is better to accept flags other than CLIENT_SSL from the + second packet? +*/ +#define SSL_HANDSHAKE_SIZE 2 +#define NORMAL_HANDSHAKE_SIZE 6 +#define MIN_HANDSHAKE_SIZE 2 +#else +#define MIN_HANDSHAKE_SIZE 6 +#endif /* HAVE_OPENSSL && !EMBEDDED_LIBRARY */ + +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; @@ -205,9 +556,6 @@ static ACL_USER *find_acl_user(const char *host, const char *user, static bool update_user_table(THD *thd, TABLE *table, const char *host, const char *user, const char *new_password, uint new_password_len); -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 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); @@ -263,6 +611,19 @@ my_bool acl_init(bool dont_read_acl_tables) (my_hash_get_key) acl_entry_get_key, (my_hash_free_key) free, &my_charset_utf8_bin); + + /* + cache built-in native authentication plugins, + to avoid hash searches and a global mutex lock on every connect + */ + native_password_plugin= my_plugin_lock_by_name(0, + &native_password_plugin_name, MYSQL_AUTHENTICATION_PLUGIN); + old_password_plugin= my_plugin_lock_by_name(0, + &old_password_plugin_name, MYSQL_AUTHENTICATION_PLUGIN); + + if (!native_password_plugin || !old_password_plugin) + DBUG_RETURN(1); + if (dont_read_acl_tables) { DBUG_RETURN(0); /* purecov: tested */ @@ -287,6 +648,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 @@ -419,6 +811,7 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) while (!(read_record_info.read_record(&read_record_info))) { ACL_USER user; + bzero(&user, sizeof(user)); update_hostname(&user.host, get_field(&mem, table->field[0])); user.user= get_field(&mem, table->field[1]); if (check_no_resolve && hostname_requires_resolving(user.host.hostname)) @@ -430,27 +823,15 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) continue; } - const char *password= get_field(thd->mem_root, table->field[2]); + 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); - if (user.salt_len == 0 && password_len != 0) - { - switch (password_len) { - case 45: /* 4.1: to be removed */ - sql_print_warning("Found 4.1 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 : ""); - break; - default: - sql_print_warning("Found invalid password for user: '%s@%s'; " - "Ignoring user", user.user ? user.user : "", - user.host.hostname ? user.host.hostname : ""); - break; - } - } - else // password is correct + + if (set_user_plugin(&user, password_len)) + continue; + { uint next_field; user.access= get_access(table,3,&next_field) & GLOBAL_ACLS; @@ -527,13 +908,43 @@ static my_bool acl_load(THD *thd, TABLE_LIST *tables) ptr= get_field(thd->mem_root, table->field[next_field++]); user.user_resource.user_conn= ptr ? atoi(ptr) : 0; } - else - user.user_resource.user_conn= 0; + + if (table->s->fields >= 41) + { + /* We may have plugin & auth_String fields */ + char *tmpstr= get_field(&mem, table->field[next_field++]); + if (tmpstr) + { + if (user.auth_string.length) + { + sql_print_warning("'user' entry '%s@%s' has both a password " + "and an authentication plugin specified. The " + "password will be ignored.", + user.user ? user.user : "", + user.host.hostname ? user.host.hostname : ""); + } + if (my_strcasecmp(system_charset_info, tmpstr, + native_password_plugin_name.str) == 0) + user.plugin= native_password_plugin_name; + else + if (my_strcasecmp(system_charset_info, tmpstr, + old_password_plugin_name.str) == 0) + user.plugin= old_password_plugin_name; + else + { + user.plugin.str= tmpstr; + user.plugin.length= strlen(tmpstr); + } + user.auth_string.str= get_field(&mem, table->field[next_field++]); + if (!user.auth_string.str) + user.auth_string.str= const_cast<char*>(""); + user.auth_string.length= strlen(user.auth_string.str); + } + } } else { user.ssl_type=SSL_TYPE_NONE; - bzero((char *)&(user.user_resource),sizeof(user.user_resource)); #ifndef TO_BE_REMOVED if (table->s->fields <= 13) { // Without grant @@ -617,6 +1028,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; @@ -635,7 +1078,10 @@ 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); if (!end) acl_cache->clear(1); /* purecov: inspected */ else @@ -667,8 +1113,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; @@ -684,9 +1130,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)) { @@ -703,10 +1155,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); @@ -714,10 +1167,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 @@ -725,6 +1179,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) @@ -830,246 +1285,10 @@ static int acl_compare(ACL_ACCESS *a,ACL_ACCESS *b) /* - Seek ACL entry for a user, check password, SSL cypher, and if - everything is OK, update THD user data and USER_RESOURCES struct. - - IMPLEMENTATION - This function does not check if the user has any sensible privileges: - only user's existence and validity is checked. - Note, that entire operation is protected by acl_cache_lock. + Gets user credentials without authentication and resource limit checks. SYNOPSIS acl_getroot() - thd thread handle. If all checks are OK, - thd->security_ctx->priv_user/master_access are updated. - thd->security_ctx->host/ip/user are used for checks. - mqh user resources; on success mqh is reset, else - unchanged - passwd scrambled & crypted password, received from client - (to check): thd->scramble or thd->scramble_323 is - used to decrypt passwd, so they must contain - original random string, - passwd_len length of passwd, must be one of 0, 8, - SCRAMBLE_LENGTH_323, SCRAMBLE_LENGTH - 'thd' and 'mqh' are updated on success; other params are IN. - - RETURN VALUE - 0 success: thd->priv_user, thd->priv_host, thd->master_access, mqh are - updated - 1 user not found or authentication failure - 2 user found, has long (4.1.1) salt, but passwd is in old (3.23) format. - -1 user found, has short (3.23) salt, but passwd is in new (4.1.1) format. -*/ - -int acl_getroot(THD *thd, USER_RESOURCES *mqh, - const char *passwd, uint passwd_len) -{ - ulong user_access= NO_ACCESS; - int res= 1; - ACL_USER *acl_user= 0; - Security_context *sctx= thd->security_ctx; - DBUG_ENTER("acl_getroot"); - - if (!initialized) - { - /* - here if mysqld's been started with --skip-grant-tables option. - */ - sctx->skip_grants(); - bzero((char*) mqh, sizeof(*mqh)); - DBUG_RETURN(0); - } - - mysql_mutex_lock(&acl_cache->lock); - - /* - Find acl entry in user database. Note, that find_acl_user is not the same, - because it doesn't take into account the case when user is not empty, - but acl_user->user is empty - */ - - for (uint i=0 ; i < acl_users.elements ; i++) - { - ACL_USER *acl_user_tmp= dynamic_element(&acl_users,i,ACL_USER*); - if (!acl_user_tmp->user || !strcmp(sctx->user, acl_user_tmp->user)) - { - if (compare_hostname(&acl_user_tmp->host, sctx->host, sctx->ip)) - { - /* check password: it should be empty or valid */ - if (passwd_len == acl_user_tmp->salt_len) - { - if (acl_user_tmp->salt_len == 0 || - (acl_user_tmp->salt_len == SCRAMBLE_LENGTH ? - check_scramble(passwd, thd->scramble, acl_user_tmp->salt) : - check_scramble_323(passwd, thd->scramble, - (ulong *) acl_user_tmp->salt)) == 0) - { - acl_user= acl_user_tmp; - res= 0; - } - } - else if (passwd_len == SCRAMBLE_LENGTH && - acl_user_tmp->salt_len == SCRAMBLE_LENGTH_323) - res= -1; - else if (passwd_len == SCRAMBLE_LENGTH_323 && - acl_user_tmp->salt_len == SCRAMBLE_LENGTH) - res= 2; - /* linear search complete: */ - break; - } - } - } - /* - This was moved to separate tree because of heavy HAVE_OPENSSL case. - If acl_user is not null, res is 0. - */ - - if (acl_user) - { - /* OK. User found and password checked continue validation */ -#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) - Vio *vio=thd->net.vio; - SSL *ssl= (SSL*) vio->ssl_arg; - X509 *cert; -#endif - - /* - At this point we know that user is allowed to connect - from given host by given username/password pair. Now - we check if SSL is required, if user is using SSL and - if X509 certificate attributes are OK - */ - switch (acl_user->ssl_type) { - case SSL_TYPE_NOT_SPECIFIED: // Impossible - case SSL_TYPE_NONE: // SSL is not required - user_access= acl_user->access; - break; -#if defined(HAVE_OPENSSL) && !defined(EMBEDDED_LIBRARY) - case SSL_TYPE_ANY: // Any kind of SSL is ok - if (vio_type(vio) == VIO_TYPE_SSL) - user_access= acl_user->access; - break; - case SSL_TYPE_X509: /* Client should have any valid certificate. */ - /* - Connections with non-valid certificates are dropped already - in sslaccept() anyway, so we do not check validity here. - - We need to check for absence of SSL because without SSL - we should reject connection. - */ - if (vio_type(vio) == VIO_TYPE_SSL && - SSL_get_verify_result(ssl) == X509_V_OK && - (cert= SSL_get_peer_certificate(ssl))) - { - user_access= acl_user->access; - X509_free(cert); - } - break; - case SSL_TYPE_SPECIFIED: /* Client should have specified attrib */ - /* - We do not check for absence of SSL because without SSL it does - not pass all checks here anyway. - If cipher name is specified, we compare it to actual cipher in - use. - */ - if (vio_type(vio) != VIO_TYPE_SSL || - SSL_get_verify_result(ssl) != X509_V_OK) - break; - 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))) - user_access= acl_user->access; - else - { - if (global_system_variables.log_warnings) - sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'", - acl_user->ssl_cipher, - SSL_get_cipher(ssl)); - break; - } - } - /* Prepare certificate (if exists) */ - DBUG_PRINT("info",("checkpoint 1")); - if (!(cert= SSL_get_peer_certificate(ssl))) - { - user_access=NO_ACCESS; - break; - } - DBUG_PRINT("info",("checkpoint 2")); - /* If X509 issuer is specified, we check it... */ - if (acl_user->x509_issuer) - { - DBUG_PRINT("info",("checkpoint 3")); - 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)) - { - if (global_system_variables.log_warnings) - sql_print_information("X509 issuer mismatch: should be '%s' " - "but is '%s'", acl_user->x509_issuer, ptr); - free(ptr); - X509_free(cert); - user_access=NO_ACCESS; - break; - } - user_access= acl_user->access; - free(ptr); - } - DBUG_PRINT("info",("checkpoint 4")); - /* X509 subject is specified, we check it .. */ - 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'", - 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'", - acl_user->x509_subject, ptr); - free(ptr); - X509_free(cert); - user_access=NO_ACCESS; - break; - } - user_access= acl_user->access; - free(ptr); - } - /* Deallocate the X509 certificate. */ - X509_free(cert); - break; -#else /* HAVE_OPENSSL */ - default: - /* - If we don't have SSL but SSL is required for this user the - authentication should fail. - */ - break; -#endif /* HAVE_OPENSSL */ - } - sctx->master_access= user_access; - sctx->priv_user= acl_user->user ? sctx->user : (char *) ""; - *mqh= acl_user->user_resource; - - if (acl_user->host.hostname) - strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME - 1); - else - *sctx->priv_host= 0; - } - mysql_mutex_unlock(&acl_cache->lock); - DBUG_RETURN(res); -} - - -/* - This is like acl_getroot() above, but it doesn't check password, - and we don't care about the user resources. - - SYNOPSIS - acl_getroot_no_password() sctx Context which should be initialized user user name host host name @@ -1081,13 +1300,13 @@ int acl_getroot(THD *thd, USER_RESOURCES *mqh, TRUE Error */ -bool acl_getroot_no_password(Security_context *sctx, char *user, char *host, - char *ip, char *db) +bool acl_getroot(Security_context *sctx, char *user, char *host, + char *ip, char *db) { int res= 1; uint i; ACL_USER *acl_user= 0; - DBUG_ENTER("acl_getroot_no_password"); + DBUG_ENTER("acl_getroot"); DBUG_PRINT("enter", ("Host: '%s', Ip: '%s', User: '%s', db: '%s'", (host ? host : "(NULL)"), (ip ? ip : "(NULL)"), @@ -1110,8 +1329,7 @@ bool acl_getroot_no_password(Security_context *sctx, char *user, char *host, sctx->master_access= 0; sctx->db_access= 0; - sctx->priv_user= (char *) ""; - *sctx->priv_host= 0; + *sctx->priv_user= *sctx->priv_host= 0; /* Find acl entry in user database. @@ -1153,7 +1371,11 @@ bool acl_getroot_no_password(Security_context *sctx, char *user, char *host, } } sctx->master_access= acl_user->access; - sctx->priv_user= acl_user->user ? user : (char *) ""; + + if (acl_user->user) + strmake(sctx->priv_user, user, USERNAME_LENGTH); + else + *sctx->priv_user= 0; if (acl_user->host.hostname) strmake(sctx->priv_host, acl_user->host.hostname, MAX_HOSTNAME - 1); @@ -1179,7 +1401,9 @@ static void acl_update_user(const char *user, const char *host, const char *x509_issuer, const char *x509_subject, USER_RESOURCES *mqh, - ulong privileges) + ulong privileges, + const LEX_STRING *plugin, + const LEX_STRING *auth) { mysql_mutex_assert_owner(&acl_cache->lock); @@ -1193,6 +1417,14 @@ static void acl_update_user(const char *user, const char *host, (acl_user->host.hostname && !my_strcasecmp(system_charset_info, host, acl_user->host.hostname))) { + if (plugin->str[0]) + { + acl_user->plugin.str= strmake_root(&mem, plugin->str, plugin->length); + acl_user->plugin.length= plugin->length; + acl_user->auth_string.str= auth->str ? + strmake_root(&mem, auth->str, auth->length) : const_cast<char*>(""); + acl_user->auth_string.length= auth->length; + } acl_user->access=privileges; if (mqh->specified_limits & USER_RESOURCES::QUERIES_PER_HOUR) acl_user->user_resource.questions=mqh->questions; @@ -1229,7 +1461,9 @@ static void acl_insert_user(const char *user, const char *host, const char *x509_issuer, const char *x509_subject, USER_RESOURCES *mqh, - ulong privileges) + ulong privileges, + const LEX_STRING *plugin, + const LEX_STRING *auth) { ACL_USER acl_user; @@ -1237,6 +1471,22 @@ static void acl_insert_user(const char *user, const char *host, acl_user.user=*user ? strdup_root(&mem,user) : 0; update_hostname(&acl_user.host, *host ? strdup_root(&mem, host): 0); + if (plugin->str[0]) + { + acl_user.plugin.str= strmake_root(&mem, plugin->str, plugin->length); + acl_user.plugin.length= plugin->length; + acl_user.auth_string.str= auth->str ? + strmake_root(&mem, auth->str, auth->length) : const_cast<char*>(""); + acl_user.auth_string.length= auth->length; + } + else + { + acl_user.plugin= password_len == SCRAMBLED_PASSWORD_CHAR_LENGTH_323 ? + 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; + } + acl_user.access=privileges; acl_user.user_resource = *mqh; acl_user.sort=get_sort(2,acl_user.host.hostname,acl_user.user); @@ -1632,8 +1882,18 @@ 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; } + + if (my_strcasecmp(system_charset_info, acl_user->plugin.str, + native_password_plugin_name.str) && + my_strcasecmp(system_charset_info, acl_user->plugin.str, + old_password_plugin_name.str)) + { + push_warning(thd, MYSQL_ERROR::WARN_LEVEL_NOTE, + ER_SET_PASSWORD_AUTH_PLUGIN, ER(ER_SET_PASSWORD_AUTH_PLUGIN)); + } /* update loaded acl entry: */ set_user_salt(acl_user, new_password, new_password_len); + set_user_plugin(acl_user, new_password_len); if (update_user_table(thd, table, acl_user->host.hostname ? acl_user->host.hostname : "", @@ -2013,7 +2273,7 @@ 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); goto end; @@ -2024,6 +2284,15 @@ static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo, thd->security_ctx->user, thd->security_ctx->host_or_ip); goto end; } + else if (combo.plugin.str[0]) + { + if (!plugin_is_ready(&combo.plugin, MYSQL_AUTHENTICATION_PLUGIN)) + { + my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), combo.plugin.str); + goto end; + } + } + old_row_exists = 0; restore_record(table,s->default_values); table->field[0]->store(combo.host.str,combo.host.length, @@ -2037,7 +2306,14 @@ 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 (combo.password.str) // If password given + /* what == 'N' means revoke */ + if (combo.plugin.length && what != 'N') + { + my_error(ER_GRANT_PLUGIN_USER_EXISTS, MYF(0), combo.user.length, + combo.user.str); + goto end; + } + if (combo.password.str) // If password given table->field[2]->store(password, password_len, system_charset_info); else if (!rights && !revoke_grant && lex->ssl_type == SSL_TYPE_NOT_SPECIFIED && @@ -2118,7 +2394,25 @@ static int replace_user_table(THD *thd, TABLE *table, const LEX_USER &combo, (mqh.specified_limits & USER_RESOURCES::USER_CONNECTIONS)) 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; + if (combo.plugin.str[0]) + { + 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); + } + else + { + my_error(ER_BAD_FIELD_ERROR, MYF(0), "plugin", "mysql.user"); + goto end; + } + } } + if (old_row_exists) { /* @@ -2162,7 +2456,9 @@ end: lex->x509_issuer, lex->x509_subject, &lex->mqh, - rights); + rights, + &combo.plugin, + &combo.auth); else acl_insert_user(combo.user.str, combo.host.str, password, password_len, lex->ssl_type, @@ -2170,7 +2466,9 @@ end: lex->x509_issuer, lex->x509_subject, &lex->mqh, - rights); + rights, + &combo.plugin, + &combo.auth); } DBUG_RETURN(error); } @@ -2285,6 +2583,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: @@ -3500,10 +3956,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[NAME_LEN+1]; bool create_new_users=0; TABLE_LIST tables[2]; @@ -3523,11 +3979,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; /* @@ -3613,6 +4084,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); @@ -4035,7 +4513,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; @@ -4052,34 +4531,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: /* @@ -4103,29 +4580,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 } @@ -4136,18 +4617,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 } } @@ -4164,7 +4644,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); } @@ -5045,6 +5525,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); @@ -5202,7 +5688,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"); @@ -5226,10 +5712,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 /* @@ -5242,12 +5734,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 @@ -5376,7 +5868,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; @@ -5459,12 +5951,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)) @@ -5526,6 +6021,7 @@ 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; DBUG_ENTER("handle_grant_struct"); DBUG_PRINT("info",("scan struct: %u search: '%s'@'%s'", @@ -5550,6 +6046,9 @@ static int handle_grant_struct(uint struct_no, bool drop, case 3: elements= proc_priv_hash.records; break; + case 5: + elements= acl_proxy_users.elements; + break; default: return -1; } @@ -5588,8 +6087,13 @@ static int handle_grant_struct(uint struct_no, bool drop, user= grant_name->user; host= grant_name->host.hostname; break; + 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: - assert(0); + MY_ASSERT_UNREACHABLE(); } if (! user) user= ""; @@ -5623,6 +6127,11 @@ static int handle_grant_struct(uint struct_no, bool drop, case 3: my_hash_delete(&proc_priv_hash, (uchar*) grant_name); break; + + case 5: + delete_dynamic_element(&acl_proxy_users, idx); + break; + } elements--; idx--; @@ -5658,6 +6167,12 @@ static int handle_grant_struct(uint struct_no, bool drop, my_hash_update(&column_priv_hash, (uchar*) grant_name, (uchar*) grant_name->hash_key, grant_name->key_length); break; + + case 5: + acl_proxy_user->set_user (&mem, user_to->user.str); + acl_proxy_user->set_host (&mem, user_to->host.str); + break; + } } else @@ -5792,6 +6307,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); } @@ -6478,38 +7010,44 @@ bool sp_grant_privileges(THD *thd, const char *sp_db, const char *sp_name, tables->db= (char*)sp_db; tables->table_name= tables->alias= (char*)sp_name; - combo->host.length= strlen(combo->host.str); - combo->user.length= strlen(combo->user.str); - combo->host.str= thd->strmake(combo->host.str,combo->host.length); - combo->user.str= thd->strmake(combo->user.str,combo->user.length); + thd->make_lex_string(&combo->user, + combo->user.str, strlen(combo->user.str), 0); + thd->make_lex_string(&combo->host, + combo->host.str, strlen(combo->host.str), 0); + combo->password= empty_lex_str; + combo->plugin= empty_lex_str; + combo->auth= empty_lex_str; - if(au && au->salt_len) + if(au) { - if (au->salt_len == SCRAMBLE_LENGTH) - { - make_password_from_salt(passwd_buff, au->salt); - combo->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH; - } - else if (au->salt_len == SCRAMBLE_LENGTH_323) + if (au->salt_len) { - make_password_from_salt_323(passwd_buff, (ulong *) au->salt); - combo->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH_323; + if (au->salt_len == SCRAMBLE_LENGTH) + { + make_password_from_salt(passwd_buff, au->salt); + combo->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH; + } + else if (au->salt_len == SCRAMBLE_LENGTH_323) + { + make_password_from_salt_323(passwd_buff, (ulong *) au->salt); + combo->password.length= SCRAMBLED_PASSWORD_CHAR_LENGTH_323; + } + else + { + push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, ER_PASSWD_LENGTH, + ER(ER_PASSWD_LENGTH), SCRAMBLED_PASSWORD_CHAR_LENGTH); + return TRUE; + } + combo->password.str= passwd_buff; } - else + + if (au->plugin.str != native_password_plugin_name.str && + au->plugin.str != old_password_plugin_name.str) { - push_warning_printf(thd, MYSQL_ERROR::WARN_LEVEL_WARN, - ER_PASSWD_LENGTH, - ER(ER_PASSWD_LENGTH), - SCRAMBLED_PASSWORD_CHAR_LENGTH); - return TRUE; + combo->plugin= au->plugin; + combo->auth= au->auth_string; } - combo->password.str= passwd_buff; - } - else - { - combo->password.str= (char*)""; - combo->password.length= 0; } if (user_list.push_back(combo)) @@ -6542,6 +7080,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 */ @@ -7109,3 +7770,1664 @@ get_cached_table_access(GRANT_INTERNAL_INFO *grant_internal_info, } +/**************************************************************************** + AUTHENTICATION CODE + including initial connect handshake, invoking appropriate plugins, + client-server plugin negotiation, COM_CHANGE_USER, and native + MySQL authentication plugins. +****************************************************************************/ + +/* few defines to have less ifdef's in the code below */ +#ifdef EMBEDDED_LIBRARY +#undef HAVE_OPENSSL +#ifdef NO_EMBEDDED_ACCESS_CHECKS +#define initialized 0 +#define decrease_user_connections(X) /* nothing */ +#define check_for_max_user_connections(X, Y) 0 +#endif +#endif +#ifndef HAVE_OPENSSL +#define ssl_acceptor_fd 0 +#define sslaccept(A,B,C) 1 +#endif + + +class Thd_charset_adapter +{ + THD *thd; +public: + Thd_charset_adapter(THD *thd_arg) : thd (thd_arg) {} + bool init_client_charset(uint cs_number) + { + thd_init_client_charset(thd, cs_number); + thd->update_charset(); + return thd->is_error(); + } + + CHARSET_INFO *charset() { return thd->charset(); } +}; + + +/** + 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 +{ + MYSQL_SERVER_AUTH_INFO auth_info; + const ACL_USER *acl_user; + 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 */ + struct { + char *plugin, *pkt; ///< pointers into NET::buff + uint pkt_len; + } cached_client_reply; + /** this caches the first plugin packet for restart request on the client */ + struct { + char *pkt; + uint pkt_len; + } cached_server_packet; + int packets_read, packets_written; ///< counters for send/received packets + uint connect_errors; ///< if there were connect errors for this host + /** when plugin returns a failure this tells us what really happened */ + enum { SUCCESS, FAILURE, RESTART } status; + + /* encapsulation members */ + ulong client_capabilities; + char *scramble; + MEM_ROOT *mem_root; + struct rand_struct *rand; + my_thread_id thread_id; + uint *server_status; + NET *net; + ulong max_client_packet_length; + char *ip; + char *host; + Thd_charset_adapter *charset_adapter; + LEX_STRING acl_user_plugin; +}; + +/** + a helper function to report an access denied error in all the proper places +*/ +static void login_failed_error(MPVIO_EXT *mpvio, int passwd_used) +{ + THD *thd= current_thd; + if (passwd_used == 2) + { + my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0), + mpvio->auth_info.user_name, + mpvio->auth_info.host_or_ip); + general_log_print(thd, COM_CONNECT, ER(ER_ACCESS_DENIED_NO_PASSWORD_ERROR), + mpvio->auth_info.user_name, + mpvio->auth_info.host_or_ip); + /* + Log access denied messages to the error log when log-warnings = 2 + so that the overhead of the general query log is not required to track + failed connections. + */ + if (global_system_variables.log_warnings > 1) + { + sql_print_warning(ER(ER_ACCESS_DENIED_NO_PASSWORD_ERROR), + mpvio->auth_info.user_name, + mpvio->auth_info.host_or_ip); + } + } + else + { + my_error(ER_ACCESS_DENIED_ERROR, MYF(0), + mpvio->auth_info.user_name, + mpvio->auth_info.host_or_ip, + passwd_used ? ER(ER_YES) : ER(ER_NO)); + general_log_print(thd, COM_CONNECT, ER(ER_ACCESS_DENIED_ERROR), + mpvio->auth_info.user_name, + mpvio->auth_info.host_or_ip, + passwd_used ? ER(ER_YES) : ER(ER_NO)); + /* + Log access denied messages to the error log when log-warnings = 2 + so that the overhead of the general query log is not required to track + failed connections. + */ + if (global_system_variables.log_warnings > 1) + { + sql_print_warning(ER(ER_ACCESS_DENIED_ERROR), + mpvio->auth_info.user_name, + mpvio->auth_info.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 + + Packet format: + + Bytes Content + ----- ---- + 1 protocol version (always 10) + n server version string, \0-terminated + 4 thread id + 8 first 8 bytes of the plugin provided data (scramble) + 1 \0 byte, terminating the first part of a scramble + 2 server capabilities (two lower bytes) + 1 server character set + 2 server status + 2 server capabilities (two upper bytes) + 1 length of the scramble + 10 reserved, always 0 + n rest of the plugin provided data (at least 12 bytes) + 1 \0 byte, terminating the second part of a scramble + + @retval 0 ok + @retval 1 error +*/ +static bool send_server_handshake_packet(MPVIO_EXT *mpvio, + const char *data, uint data_len) +{ + DBUG_ASSERT(mpvio->status == MPVIO_EXT::FAILURE); + DBUG_ASSERT(data_len <= 255); + + char *buff= (char *) my_alloca(1 + SERVER_VERSION_LENGTH + data_len + 64); + char scramble_buf[SCRAMBLE_LENGTH]; + char *end= buff; + + DBUG_ENTER("send_server_handshake_packet"); + *end++= protocol_version; + + mpvio->client_capabilities= CLIENT_BASIC_FLAGS; + + if (opt_using_transactions) + mpvio->client_capabilities|= CLIENT_TRANSACTIONS; + + mpvio->client_capabilities|= CAN_CLIENT_COMPRESS; + + if (ssl_acceptor_fd) + { + mpvio->client_capabilities|= CLIENT_SSL; + mpvio->client_capabilities|= CLIENT_SSL_VERIFY_SERVER_CERT; + } + + if (data_len) + { + mpvio->cached_server_packet.pkt= (char*) memdup_root(mpvio->mem_root, + data, data_len); + mpvio->cached_server_packet.pkt_len= data_len; + } + + 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); + data= scramble_buf; + } + else + { + /* + if the default plugin does not provide the data for the scramble at + all, we generate a scramble internally anyway, just in case the + user account (that will be known only later) uses a + native_password_plugin (which needs a scramble). If we don't send a + scramble now - wasting 20 bytes in the packet - + native_password_plugin will have to send it in a separate packet, + adding one more round trip. + */ + create_random_string(mpvio->scramble, SCRAMBLE_LENGTH, mpvio->rand); + data= mpvio->scramble; + } + data_len= SCRAMBLE_LENGTH; + } + + end= strnmov(end, server_version, SERVER_VERSION_LENGTH) + 1; + int4store((uchar*) end, mpvio->thread_id); + end+= 4; + + /* + Old clients does not understand long scrambles, but can ignore packet + 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+= SCRAMBLE_LENGTH_323; + *end++= 0; + + int2store(end, mpvio->client_capabilities); + /* write server characteristics: up to 16 bytes allowed */ + end[2]= (char) default_charset_info->number; + int2store(end + 3, mpvio->server_status[0]); + int2store(end + 5, mpvio->client_capabilities >> 16); + end[7]= data_len; + bzero(end + 8, 10); + end+= 18; + /* write scramble tail */ + 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->net, (uchar*) buff, (size_t) (end - buff)) || + net_flush(mpvio->net); + my_afree(buff); + DBUG_RETURN (res); +} + +static bool secure_auth(MPVIO_EXT *mpvio) +{ + THD *thd; + if (!opt_secure_auth) + return 0; + /* + If the server is running in secure auth mode, short scrambles are + forbidden. Extra juggling to report the same error as the old code. + */ + + thd= current_thd; + if (mpvio->client_capabilities & CLIENT_PROTOCOL_41) + { + my_error(ER_SERVER_IS_IN_SECURE_AUTH_MODE, MYF(0), + mpvio->auth_info.user_name, + mpvio->auth_info.host_or_ip); + general_log_print(thd, COM_CONNECT, ER(ER_SERVER_IS_IN_SECURE_AUTH_MODE), + mpvio->auth_info.user_name, + mpvio->auth_info.host_or_ip); + } + else + { + my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0)); + general_log_print(thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE)); + } + return 1; +} + +/** + sends a "change plugin" packet, requesting a client to restart authentication + using a different authentication plugin + + Packet format: + + Bytes Content + ----- ---- + 1 byte with the value 254 + n client plugin to use, \0-terminated + n plugin provided data + + In a special case of switching from native_password_plugin to + old_password_plugin, the packet contains only one - the first - byte, + plugin name is omitted, plugin data aren't needed as the scramble was + already sent. This one-byte packet is identical to the "use the short + scramble" packet in the protocol before plugins were introduced. + + @retval 0 ok + @retval 1 error +*/ +static bool send_plugin_request_packet(MPVIO_EXT *mpvio, + const uchar *data, uint data_len) +{ + DBUG_ASSERT(mpvio->packets_written == 1); + DBUG_ASSERT(mpvio->packets_read == 1); + NET *net= mpvio->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; + + DBUG_ASSERT(client_auth_plugin); + + /* + we send an old "short 4.0 scramble request", if we need to request a + client to use 4.0 auth plugin (short scramble) and the scramble was + already sent to the client + + below, cached_client_reply.plugin is the plugin name that client has used, + client_auth_plugin is derived from mysql.user table, for the given + user account, it's the plugin that the client need to use to login. + */ + bool switch_from_long_to_short_scramble= + native_password_plugin_name.str == mpvio->cached_client_reply.plugin && + client_auth_plugin == old_password_plugin_name.str; + + if (switch_from_long_to_short_scramble) + DBUG_RETURN (secure_auth(mpvio) || + 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. + Plugin-aware clients can do that, but traditionally it meant to + ask an old 4.0 client to use the new 4.1 authentication protocol. + */ + bool switch_from_short_to_long_scramble= + old_password_plugin_name.str == mpvio->cached_client_reply.plugin && + client_auth_plugin == native_password_plugin_name.str; + + if (switch_from_short_to_long_scramble) + { + my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0)); + general_log_print(current_thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE)); + DBUG_RETURN (1); + } + + /* + If we're dealing with an older client we can't just send a change plugin + packet to re-initiate the authentication handshake, because the client + won't understand it. The good thing is that we don't need to : the old client + expects us to just check the user credentials here, which we can do by just reading + the cached data that are placed there by parse_com_change_user_packet() + In this case we just do nothing and behave as if normal authentication + should continue. + */ + if (!(mpvio->client_capabilities & CLIENT_PLUGIN_AUTH)) + { + DBUG_PRINT("info", ("old client sent a COM_CHANGE_USER")); + DBUG_ASSERT(mpvio->cached_client_reply.pkt); + /* get the status back so the read can process the cached result */ + mpvio->status= MPVIO_EXT::RESTART; + DBUG_RETURN(0); + } + + 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. + + Finds a user and copies it into mpvio. Reports an authentication + failure if a user is not found. + + @note find_acl_user is not the same, because it doesn't take into + account the case when user is not empty, but acl_user->user is empty + + @retval 0 found + @retval 1 not found +*/ +static bool find_mpvio_user(MPVIO_EXT *mpvio) +{ + DBUG_ENTER("find_mpvio_user"); + DBUG_PRINT("info", ("entry: %s", mpvio->auth_info.user_name)); + DBUG_ASSERT(mpvio->acl_user == 0); + mysql_mutex_lock(&acl_cache->lock); + for (uint i=0; i < acl_users.elements; i++) + { + ACL_USER *acl_user_tmp= dynamic_element(&acl_users, i, ACL_USER*); + if ((!acl_user_tmp->user || + !strcmp(mpvio->auth_info.user_name, acl_user_tmp->user)) && + compare_hostname(&acl_user_tmp->host, mpvio->host, mpvio->ip)) + { + mpvio->acl_user= acl_user_tmp->copy(mpvio->mem_root); + if (acl_user_tmp->plugin.str == native_password_plugin_name.str || + acl_user_tmp->plugin.str == old_password_plugin_name.str) + mpvio->acl_user_plugin= acl_user_tmp->plugin; + else + make_lex_string_root(mpvio->mem_root, + &mpvio->acl_user_plugin, + acl_user_tmp->plugin.str, + acl_user_tmp->plugin.length, 0); + break; + } + } + mysql_mutex_unlock(&acl_cache->lock); + + if (!mpvio->acl_user) + { + login_failed_error(mpvio, 0); + DBUG_RETURN (1); + } + + /* user account requires non-default plugin and the client is too old */ + if (mpvio->acl_user->plugin.str != native_password_plugin_name.str && + mpvio->acl_user->plugin.str != old_password_plugin_name.str && + !(mpvio->client_capabilities & CLIENT_PLUGIN_AUTH)) + { + DBUG_ASSERT(my_strcasecmp(system_charset_info, mpvio->acl_user->plugin.str, + native_password_plugin_name.str)); + DBUG_ASSERT(my_strcasecmp(system_charset_info, mpvio->acl_user->plugin.str, + old_password_plugin_name.str)); + my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0)); + general_log_print(current_thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE)); + DBUG_RETURN (1); + } + + 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); + 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) +{ + NET *net= mpvio->net; + + 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; + uint user_len= passwd - user - 1; + char *db= passwd; + char db_buff[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)); + DBUG_RETURN (1); + } + + /* + Old clients send null-terminated string as password; new clients send + the size (1 byte) + string (not null-terminated). Hence in case of empty + password both send '\0'. + + This strlen() can't be easily deleted without changing protocol. + + Cast *passwd to an unsigned char, so that it doesn't extend the sign for + *passwd > 127 and become 2**32-127+ after casting to uint. + */ + uint passwd_len= (mpvio->client_capabilities & CLIENT_SECURE_CONNECTION ? + (uchar) (*passwd++) : strlen(passwd)); + + db+= passwd_len + 1; + /* + Database name is always NUL-terminated, so in case of empty database + the packet must contain at least the trailing '\0'. + */ + if (db >= end) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + DBUG_RETURN (1); + } + + uint db_len= strlen(db); + + char *ptr= db + db_len + 1; + + if (ptr + 1 < end) + { + if (mpvio->charset_adapter->init_client_charset(uint2korr(ptr))) + DBUG_RETURN(1); + } + + + /* Convert database and user names to utf8 */ + db_len= copy_and_convert(db_buff, sizeof(db_buff) - 1, system_charset_info, + db, db_len, mpvio->charset_adapter->charset(), + &dummy_errors); + db_buff[db_len]= 0; + + user_len= copy_and_convert(user_buff, sizeof(user_buff) - 1, + system_charset_info, user, user_len, + mpvio->charset_adapter->charset(), + &dummy_errors); + user_buff[user_len]= 0; + + /* we should not free mpvio->user here: it's saved by dispatch_command() */ + if (!(mpvio->auth_info.user_name= my_strndup(user_buff, user_len, MYF(MY_WME)))) + return 1; + mpvio->auth_info.user_name_length= user_len; + + if (make_lex_string_root(mpvio->mem_root, + &mpvio->db, db_buff, db_len, 0) == 0) + DBUG_RETURN(1); /* The error is set by make_lex_string(). */ + + if (!initialized) + { + // if mysqld's been started with --skip-grant-tables option + strmake(mpvio->auth_info.authenticated_as, + mpvio->auth_info.user_name, USERNAME_LENGTH); + + mpvio->status= MPVIO_EXT::SUCCESS; + DBUG_RETURN(0); + } + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + if (find_mpvio_user(mpvio)) + DBUG_RETURN(1); + + char *client_plugin; + if (mpvio->client_capabilities & CLIENT_PLUGIN_AUTH) + { + client_plugin= ptr + 2; + if (client_plugin >= end) + { + my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); + DBUG_RETURN(1); + } + } + else + { + if (mpvio->client_capabilities & CLIENT_SECURE_CONNECTION) + client_plugin= native_password_plugin_name.str; + else + { + client_plugin= old_password_plugin_name.str; + /* + For a passwordless accounts we use native_password_plugin. + But when an old 4.0 client connects to it, we change it to + old_password_plugin, otherwise MySQL will think that server + and client plugins don't match. + */ + if (mpvio->acl_user->auth_string.length == 0) + mpvio->acl_user_plugin= old_password_plugin_name; + } + } + + 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 + + DBUG_RETURN (0); +} + +/* the packet format is described in send_client_reply_packet() */ +static ulong parse_client_handshake_packet(MPVIO_EXT *mpvio, + uchar **buff, ulong pkt_len) +{ +#ifndef EMBEDDED_LIBRARY + NET *net= mpvio->net; + char *end; + + DBUG_ASSERT(mpvio->status == MPVIO_EXT::FAILURE); + + if (pkt_len < MIN_HANDSHAKE_SIZE) + return packet_error; + + if (mpvio->connect_errors) + reset_host_errors(mpvio->ip); + + ulong client_capabilities= uint2korr(net->read_pos); + if (client_capabilities & CLIENT_PROTOCOL_41) + { + client_capabilities|= ((ulong) uint2korr(net->read_pos + 2)) << 16; + mpvio->max_client_packet_length= uint4korr(net->read_pos + 4); + DBUG_PRINT("info", ("client_character_set: %d", (uint) net->read_pos[8])); + if (mpvio->charset_adapter->init_client_charset((uint) net->read_pos[8])) + return packet_error; + end= (char*) net->read_pos + 32; + } + else + { + 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. */ + mpvio->client_capabilities&= client_capabilities; + + +#if defined(HAVE_OPENSSL) + DBUG_PRINT("info", ("client capabilities: %lu", mpvio->client_capabilities)); + if (mpvio->client_capabilities & CLIENT_SSL) + { + char error_string[1024] __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)) + { + DBUG_PRINT("error", ("Failed to accept new SSL connection")); + return packet_error; + } + + DBUG_PRINT("info", ("Reading user information over SSL layer")); + pkt_len= my_net_read(net); + if (pkt_len == packet_error || pkt_len < NORMAL_HANDSHAKE_SIZE) + { + DBUG_PRINT("error", ("Failed to read user information (pkt_len= %lu)", + pkt_len)); + return packet_error; + } + } +#endif + + if (end >= (char*) net->read_pos + pkt_len + 2) + return packet_error; + + if ((mpvio->client_capabilities & CLIENT_TRANSACTIONS) && + opt_using_transactions) + net->return_status= mpvio->server_status; + + char *user= end; + char *passwd= strend(user) + 1; + uint user_len= passwd - user - 1, db_len; + char *db= passwd; + char db_buff[NAME_LEN + 1]; // buffer to store db in utf8 + char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8 + uint dummy_errors; + + /* + Old clients send null-terminated string as password; new clients send + the size (1 byte) + string (not null-terminated). Hence in case of empty + password both send '\0'. + + This strlen() can't be easily deleted without changing protocol. + + Cast *passwd to an unsigned char, so that it doesn't extend the sign for + *passwd > 127 and become 2**32-127+ after casting to uint. + */ + uint passwd_len= mpvio->client_capabilities & CLIENT_SECURE_CONNECTION ? + (uchar) (*passwd++) : strlen(passwd); + + if (mpvio->client_capabilities & CLIENT_CONNECT_WITH_DB) + { + db= db + passwd_len + 1; + /* strlen() can't be easily deleted without changing protocol */ + db_len= strlen(db); + } + else + { + db= 0; + db_len= 0; + } + + if (passwd + passwd_len + db_len > (char *) net->read_pos + pkt_len) + return packet_error; + + char *client_plugin= passwd + passwd_len + (db ? db_len + 1 : 0); + + /* 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, db_len, mpvio->charset_adapter->charset(), + &dummy_errors); + db= db_buff; + db_buff[db_len]= 0; + } + + user_len= copy_and_convert(user_buff, sizeof(user_buff) - 1, + system_charset_info, user, user_len, + mpvio->charset_adapter->charset(), + &dummy_errors); + user= user_buff; + user_buff[user_len]= 0; + + /* If username starts and ends in "'", chop them off */ + if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'') + { + user[user_len - 1]= 0; + user++; + user_len-= 2; + } + + if (make_lex_string_root(mpvio->mem_root, + &mpvio->db, db, db_len, 0) == 0) + return packet_error; /* The error is set by make_lex_string(). */ + if (mpvio->auth_info.user_name) + my_free(mpvio->auth_info.user_name); + if (!(mpvio->auth_info.user_name= my_strndup(user, user_len, MYF(MY_WME)))) + return packet_error; /* The error is set by my_strdup(). */ + mpvio->auth_info.user_name_length= user_len; + + if (!initialized) + { + // if mysqld's been started with --skip-grant-tables option + mpvio->status= MPVIO_EXT::SUCCESS; + return packet_error; + } + + if (find_mpvio_user(mpvio)) + return packet_error; + + if (mpvio->client_capabilities & CLIENT_PLUGIN_AUTH) + { + if ((client_plugin + strlen(client_plugin)) > + (char *) net->read_pos + pkt_len) + return packet_error; + } + else + { + if (mpvio->client_capabilities & CLIENT_SECURE_CONNECTION) + client_plugin= native_password_plugin_name.str; + else + { + client_plugin= old_password_plugin_name.str; + /* + For a passwordless accounts we use native_password_plugin. + But when an old 4.0 client connects to it, we change it to + old_password_plugin, otherwise MySQL will think that server + and client plugins don't match. + */ + if (mpvio->acl_user->auth_string.length == 0) + mpvio->acl_user_plugin= old_password_plugin_name; + } + } + + /* + if the acl_user needs a different plugin to authenticate + (specified in GRANT ... AUTHENTICATED VIA plugin_name ..) + we need to restart the authentication in the server. + But perhaps the client has already used the correct plugin - + in that case the authentication on the client may not need to be + restarted and a server auth plugin will read the data that the client + has just send. Cache them to return in the next server_mpvio_read_packet(). + */ + if (my_strcasecmp(system_charset_info, mpvio->acl_user_plugin.str, + plugin_name(mpvio->plugin)->str) != 0) + { + 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; + return packet_error; + } + + /* + ok, we don't need to restart the authentication on the server. + but if the client used the wrong plugin, we need to restart + the authentication on the client. Do it here, the server plugin + doesn't need to know. + */ + const char *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, + mpvio->cached_server_packet.pkt_len)) + return packet_error; + + passwd_len= my_net_read(mpvio->net); + passwd = (char*) mpvio->net->read_pos; + } + + *buff= (uchar*) passwd; + return passwd_len; +#else + return 0; +#endif +} + + +/** + Make sure that when sending plugin supplued data to the client they + are not considered a special out-of-band command, like e.g. + \255 (error) or \254 (change user request packet). + To avoid this we send plugin data packets starting with one of these + 2 bytes "wrapped" in a command \1. + For the above reason we have to wrap plugin data packets starting with + \1 as well. +*/ + +#define IS_OUT_OF_BAND_PACKET(packet,packet_len) \ + ((packet_len) > 0 && \ + (*(packet) == 1 || *(packet) == 255 || *(packet) == 254)) + +static inline int +wrap_plguin_data_into_proper_command(NET *net, + const uchar *packet, int packet_len) +{ + DBUG_ASSERT(IS_OUT_OF_BAND_PACKET(packet, packet_len)); + return net_write_command(net, 1, (uchar *) "", 0, packet, packet_len); +} + + +/** + vio->write_packet() callback method for server authentication plugins + + This function is called by a server authentication plugin, when it wants + to send data to the client. + + It transparently wraps the data into a handshake packet, + 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; + int res; + + DBUG_ENTER("server_mpvio_write_packet"); + /* + Reset cached_client_reply if not an old client doing mysql_change_user, + as this is where the password from COM_CHANGE_USER is stored. + */ + if (!((!(mpvio->client_capabilities & CLIENT_PLUGIN_AUTH)) && + mpvio->status == MPVIO_EXT::RESTART && + mpvio->cached_client_reply.plugin == + ((st_mysql_auth *) (plugin_decl(mpvio->plugin)->info))->client_auth_plugin + )) + 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); + else if (mpvio->status == MPVIO_EXT::RESTART) + res= send_plugin_request_packet(mpvio, packet, packet_len); + else if (IS_OUT_OF_BAND_PACKET(packet, packet_len)) + res= wrap_plguin_data_into_proper_command(mpvio->net, packet, packet_len); + else + { + res= my_net_write(mpvio->net, packet, packet_len) || + net_flush(mpvio->net); + } + mpvio->packets_written++; + DBUG_RETURN(res); +} + +/** + vio->read_packet() callback method for server authentication plugins + + This function is called by a server authentication plugin, when it wants + to read data from the client. + + It transparently extracts the client plugin data, if embedded into + 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; + ulong pkt_len; + + DBUG_ENTER("server_mpvio_read_packet"); + if (mpvio->packets_written == 0) + { + /* + plugin wants to read the data without sending anything first. + send an empty packet to force a server handshake packet to be sent + */ + if (mpvio->write_packet(mpvio, 0, 0)) + pkt_len= packet_error; + else + pkt_len= my_net_read(mpvio->net); + } + else if (mpvio->cached_client_reply.pkt) + { + DBUG_ASSERT(mpvio->status == MPVIO_EXT::RESTART); + DBUG_ASSERT(mpvio->packets_read > 0); + /* + if the have the data cached from the last server_mpvio_read_packet + (which can be the case if it's a restarted authentication) + and a client has used the correct plugin, then we can return the + 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; + 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; + mpvio->cached_client_reply.pkt= 0; + mpvio->packets_read++; + DBUG_RETURN ((int) mpvio->cached_client_reply.pkt_len); + } + + /* older clients don't support change of client plugin request */ + if (!(mpvio->client_capabilities & CLIENT_PLUGIN_AUTH)) + { + mpvio->status= MPVIO_EXT::FAILURE; + pkt_len= packet_error; + goto err; + } + + /* + But if the client has used the wrong plugin, the cached data are + useless. Furthermore, we have to send a "change plugin" request + to the client. + */ + if (mpvio->write_packet(mpvio, 0, 0)) + pkt_len= packet_error; + else + pkt_len= my_net_read(mpvio->net); + } + else + pkt_len= my_net_read(mpvio->net); + + if (pkt_len == packet_error) + goto err; + + mpvio->packets_read++; + + /* + the 1st packet has the plugin data wrapped into the client authentication + handshake packet + */ + if (mpvio->packets_read == 1) + { + pkt_len= parse_client_handshake_packet(mpvio, buf, pkt_len); + if (pkt_len == packet_error) + goto err; + } + else + *buf= mpvio->net->read_pos; + + DBUG_RETURN((int)pkt_len); + +err: + if (mpvio->status == MPVIO_EXT::FAILURE) + { + inc_host_errors(mpvio->ip); + my_error(ER_HANDSHAKE_ERROR, MYF(0), mpvio->auth_info.host_or_ip); + } + 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_info(mpvio->net->vio, info); +} + +#ifndef NO_EMBEDDED_ACCESS_CHECKS +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; + X509 *cert; +#endif + + /* + At this point we know that user is allowed to connect + from given host by given username/password pair. Now + we check if SSL is required, if user is using SSL and + if X509 certificate attributes are OK + */ + switch (acl_user->ssl_type) { + case SSL_TYPE_NOT_SPECIFIED: // Impossible + case SSL_TYPE_NONE: // SSL is not required + return 0; +#if defined(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. */ + /* + Connections with non-valid certificates are dropped already + in sslaccept() anyway, so we do not check validity here. + + We need to check for absence of SSL because without SSL + we should reject connection. + */ + if (vio_type(vio) == VIO_TYPE_SSL && + SSL_get_verify_result(ssl) == X509_V_OK && + (cert= SSL_get_peer_certificate(ssl))) + { + X509_free(cert); + return 0; + } + return 1; + case SSL_TYPE_SPECIFIED: /* Client should have specified attrib */ + /* If a cipher name is specified, we compare it to actual cipher in use. */ + if (vio_type(vio) != VIO_TYPE_SSL || + SSL_get_verify_result(ssl) != X509_V_OK) + 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))) + { + if (global_system_variables.log_warnings) + sql_print_information("X509 ciphers mismatch: should be '%s' but is '%s'", + acl_user->ssl_cipher, SSL_get_cipher(ssl)); + return 1; + } + } + /* Prepare certificate (if exists) */ + if (!(cert= SSL_get_peer_certificate(ssl))) + return 1; + /* 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'", + acl_user->x509_issuer, ptr)); + if (strcmp(acl_user->x509_issuer, ptr)) + { + if (global_system_variables.log_warnings) + sql_print_information("X509 issuer mismatch: should be '%s' " + "but is '%s'", acl_user->x509_issuer, ptr); + free(ptr); + X509_free(cert); + return 1; + } + free(ptr); + } + /* X509 subject is specified, we check it .. */ + 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'", + 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'", + acl_user->x509_subject, ptr); + free(ptr); + X509_free(cert); + return 1; + } + free(ptr); + } + X509_free(cert); + return 0; +#else /* HAVE_OPENSSL */ + default: + /* + If we don't have SSL but SSL is required for this user the + authentication should fail. + */ + return 1; +#endif /* HAVE_OPENSSL */ + } + return 1; +} +#endif + + +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; + + if (auth_plugin_name->str == native_password_plugin_name.str) + plugin= native_password_plugin; + else +#ifndef EMBEDDED_LIBRARY + 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, + MYSQL_AUTHENTICATION_PLUGIN))) + unlock_plugin= true; + else +#endif + plugin= NULL; + + mpvio->plugin= plugin; + old_status= mpvio->status; + + if (plugin) + { + st_mysql_auth *auth= (st_mysql_auth *) plugin_decl(plugin)->info; + res= auth->authenticate_user(mpvio, &mpvio->auth_info); + + if (unlock_plugin) + plugin_unlock(thd, plugin); + } + else + { + /* Server cannot load the required plugin. */ + my_error(ER_PLUGIN_IS_NOT_LOADED, MYF(0), auth_plugin_name->str); + res= CR_ERROR; + } + + /* + If the status was MPVIO_EXT::RESTART before the authenticate_user() call + it can never be MPVIO_EXT::RESTART after the call, because any call + to write_packet() or read_packet() will reset the status. + + But (!) if a plugin never called a read_packet() or write_packet(), the + status will stay unchanged. We'll fix it, by resetting the status here. + */ + if (old_status == MPVIO_EXT::RESTART && mpvio->status == MPVIO_EXT::RESTART) + mpvio->status= MPVIO_EXT::FAILURE; // reset to the default + + return res; +} + + +static void +server_mpvio_initialize(THD *thd, MPVIO_EXT *mpvio, uint connect_errors, + Thd_charset_adapter *charset_adapter) +{ + memset(mpvio, 0, sizeof(MPVIO_EXT)); + mpvio->read_packet= server_mpvio_read_packet; + mpvio->write_packet= server_mpvio_write_packet; + mpvio->info= server_mpvio_info; + mpvio->auth_info.host_or_ip= thd->security_ctx->host_or_ip; + mpvio->auth_info.host_or_ip_length= + (unsigned int) strlen(thd->security_ctx->host_or_ip); + mpvio->auth_info.user_name= thd->security_ctx->user; + mpvio->auth_info.user_name_length= thd->security_ctx->user ? + (unsigned int) strlen(thd->security_ctx->user) : 0; + mpvio->connect_errors= connect_errors; + mpvio->status= MPVIO_EXT::FAILURE; + + mpvio->client_capabilities= thd->client_capabilities; + mpvio->mem_root= thd->mem_root; + mpvio->scramble= thd->scramble; + mpvio->rand= &thd->rand; + mpvio->thread_id= thd->thread_id; + mpvio->server_status= &thd->server_status; + mpvio->net= &thd->net; + mpvio->ip= thd->security_ctx->ip; + mpvio->host= thd->security_ctx->host; + mpvio->charset_adapter= charset_adapter; +} + + +static void +server_mpvio_update_thd(THD *thd, MPVIO_EXT *mpvio) +{ + thd->client_capabilities= mpvio->client_capabilities; + thd->max_client_packet_length= mpvio->max_client_packet_length; + if (mpvio->client_capabilities & CLIENT_INTERACTIVE) + thd->variables.net_wait_timeout= thd->variables.net_interactive_timeout; + thd->security_ctx->user= mpvio->auth_info.user_name; + if (thd->client_capabilities & CLIENT_IGNORE_SPACE) + thd->variables.sql_mode|= MODE_IGNORE_SPACE; +} + +/** + Perform the handshake, authorize the client and update thd sctx variables. + + @param thd thread handle + @param connect_errors number of previous failed connect attemps + from this host + @param com_change_user_pkt_len size of the COM_CHANGE_USER packet + (without the first, command, byte) or 0 + if it's not a COM_CHANGE_USER (that is, if + it's a new connection) + + @retval 0 success, thd is updated. + @retval 1 error +*/ +bool +acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_len) +{ + int res= CR_OK; + MPVIO_EXT mpvio; + Thd_charset_adapter charset_adapter(thd); + + 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"); + compile_time_assert(MYSQL_USERNAME_LENGTH == USERNAME_LENGTH); + + server_mpvio_initialize(thd, &mpvio, connect_errors, &charset_adapter); + + DBUG_PRINT("info", ("com_change_user_pkt_len=%u", com_change_user_pkt_len)); + + /* + 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 + pointer if connect failed. + */ + thd->reset_db(NULL, 0); + + if (command == COM_CHANGE_USER) + { + mpvio.packets_written++; // pretend that a server handshake packet was sent + mpvio.packets_read++; // take COM_CHANGE_USER packet into account + + /* Clear variables that are allocated */ + thd->user_connect= 0; + + if (parse_com_change_user_packet(&mpvio, com_change_user_pkt_len)) + { + server_mpvio_update_thd(thd, &mpvio); + DBUG_RETURN(1); + } + + DBUG_ASSERT(mpvio.status == MPVIO_EXT::RESTART || + mpvio.status == MPVIO_EXT::SUCCESS); + } + else + { + /* mark the thd as having no scramble yet */ + mpvio.scramble[SCRAMBLE_LENGTH]= 1; + + /* + perform the first authentication attempt, with the default plugin. + This sends the server handshake packet, reads the client reply + with a user name, and performs the authentication if everyone has used + the correct plugin. + */ + + res= do_auth_once(thd, auth_plugin_name, &mpvio); + } + + /* + retry the authentication, if - after receiving the user name - + we found that we need to switch to a non-default plugin + */ + if (mpvio.status == MPVIO_EXT::RESTART) + { + DBUG_ASSERT(mpvio.acl_user); + DBUG_ASSERT(command == COM_CHANGE_USER || + my_strcasecmp(system_charset_info, auth_plugin_name->str, + mpvio.acl_user->plugin.str)); + auth_plugin_name= &mpvio.acl_user->plugin; + res= do_auth_once(thd, auth_plugin_name, &mpvio); + } + + server_mpvio_update_thd(thd, &mpvio); + + Security_context *sctx= thd->security_ctx; + const ACL_USER *acl_user= mpvio.acl_user; + + thd->password= mpvio.auth_info.password_used; // remember for error messages + + /* + Log the command here so that the user can check the log + for the tried logins and also to detect break-in attempts. + + if sctx->user is unset it's protocol failure, bad packet. + */ + if (mpvio.auth_info.user_name) + { + if (strcmp(mpvio.auth_info.authenticated_as, mpvio.auth_info.user_name)) + { + general_log_print(thd, command, "%s@%s as %s on %s", + mpvio.auth_info.user_name, mpvio.auth_info.host_or_ip, + mpvio.auth_info.authenticated_as ? + mpvio.auth_info.authenticated_as : "anonymous", + mpvio.db.str ? mpvio.db.str : (char*) ""); + } + else + general_log_print(thd, command, (char*) "%s@%s on %s", + mpvio.auth_info.user_name, mpvio.auth_info.host_or_ip, + mpvio.db.str ? mpvio.db.str : (char*) ""); + } + + if (res > CR_OK && mpvio.status != MPVIO_EXT::SUCCESS) + { + DBUG_ASSERT(mpvio.status == MPVIO_EXT::FAILURE); + + if (!thd->is_error()) + login_failed_error(&mpvio, mpvio.auth_info.password_used); + 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; + 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 - 1); + else + *sctx->priv_host= 0; + +#ifndef NO_EMBEDDED_ACCESS_CHECKS + /* + OK. Let's check the SSL. Historically it was checked after the password, + as an additional layer, not instead of the password + (in which case it would've been a plugin too). + */ + if (acl_check_ssl(thd, acl_user)) + { + if (!thd->is_error()) + login_failed_error(&mpvio, thd->password); + DBUG_RETURN(1); + } + + /* Don't allow the user to connect if he has done too many queries */ + if ((acl_user->user_resource.questions || acl_user->user_resource.updates || + acl_user->user_resource.conn_per_hour || + acl_user->user_resource.user_conn || + global_system_variables.max_user_connections) && + get_or_create_user_conn(thd, + (opt_old_style_user_limits ? sctx->user : sctx->priv_user), + (opt_old_style_user_limits ? sctx->host_or_ip : sctx->priv_host), + &acl_user->user_resource)) + DBUG_RETURN(1); // The error is set by get_or_create_user_conn() + +#endif + } + else + sctx->skip_grants(); + + if (thd->user_connect && + (thd->user_connect->user_resources.conn_per_hour || + thd->user_connect->user_resources.user_conn || + global_system_variables.max_user_connections) && + check_for_max_user_connections(thd, thd->user_connect)) + { + DBUG_RETURN(1); // The error is set in check_for_max_user_connections() + } + + DBUG_PRINT("info", + ("Capabilities: %lu packet_length: %ld Host: '%s' " + "Login user: '%s' Priv_user: '%s' Using password: %s " + "Access: %lu db: '%s'", + thd->client_capabilities, thd->max_client_packet_length, + sctx->host_or_ip, sctx->user, sctx->priv_user, + thd->password ? "yes": "no", + sctx->master_access, mpvio.db.str)); + + if (command == COM_CONNECT && + !(thd->main_security_ctx.master_access & SUPER_ACL)) + { + mysql_mutex_lock(&LOCK_connection_count); + bool count_ok= (connection_count <= max_connections); + mysql_mutex_unlock(&LOCK_connection_count); + if (!count_ok) + { // too many connections + my_error(ER_CON_COUNT_ERROR, MYF(0)); + DBUG_RETURN(1); + } + } + + /* + This is the default access rights for the current database. It's + set to 0 here because we don't have an active database yet (and we + may not have an active database to set. + */ + sctx->db_access=0; + + /* Change a database if necessary */ + if (mpvio.db.length) + { + if (mysql_change_db(thd, &mpvio.db, FALSE)) + { + /* mysql_change_db() has pushed the error message. */ + if (thd->user_connect) + { + decrease_user_connections(thd->user_connect); + thd->user_connect= 0; + } + DBUG_RETURN(1); + } + } + + 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 + my_ok(thd); + +#if defined(MYSQL_SERVER) && !defined(EMBEDDED_LIBRARY) + /* + Allow the network layer to skip big packets. Although a malicious + authenticated session might use this to trick the server to read + big packets indefinitely, this is a previously established behavior + that needs to be preserved as to not break backwards compatibility. + */ + thd->net.skip_big_packet= TRUE; +#endif + + /* Ready to handle queries */ + DBUG_RETURN(0); +} + +/** + MySQL Server Password Authentication Plugin + + In the MySQL authentication protocol: + 1. the server sends the random scramble to the client + 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, + MYSQL_SERVER_AUTH_INFO *info) +{ + uchar *pkt; + int pkt_len; + MPVIO_EXT *mpvio= (MPVIO_EXT *) vio; + + DBUG_ENTER("native_password_authenticate"); + + /* generate the scramble, or reuse the old one */ + if (mpvio->scramble[SCRAMBLE_LENGTH]) + create_random_string(mpvio->scramble, SCRAMBLE_LENGTH, mpvio->rand); + + /* send it to the client */ + if (mpvio->write_packet(mpvio, (uchar*) mpvio->scramble, SCRAMBLE_LENGTH + 1)) + DBUG_RETURN(CR_ERROR); + + /* reply and authenticate */ + + /* + <digression> + This is more complex than it looks. + + The plugin (we) may be called right after the client was connected - + and will need to send a scramble, read reply, authenticate. + + Or the plugin may be called after another plugin has sent a scramble, + and read the reply. If the client has used the correct client-plugin, + we won't need to read anything here from the client, the client + has already sent a reply with everything we need for authentication. + + Or the plugin may be called after another plugin has sent a scramble, + and read the reply, but the client has used the wrong client-plugin. + We'll need to sent a "switch to another plugin" packet to the + client and read the reply. "Use the short scramble" packet is a special + case of "switch to another plugin" packet. + + Or, perhaps, the plugin may be called after another plugin has + done the handshake but did not send a useful scramble. We'll need + to send a scramble (and perhaps a "switch to another plugin" packet) + and read the reply. + + Besides, a client may be an old one, that doesn't understand plugins. + Or doesn't even understand 4.0 scramble. + + And we want to keep the same protocol on the wire unless non-native + plugins are involved. + + Anyway, it still looks simple from a plugin point of view: + "send the scramble, read the reply and authenticate" + All the magic is transparently handled by the server. + </digression> + */ + + /* read the reply with the encrypted password */ + if ((pkt_len= mpvio->read_packet(mpvio, &pkt)) < 0) + DBUG_RETURN(CR_ERROR); + DBUG_PRINT("info", ("reply read : pkt_len=%d", pkt_len)); + +#ifdef NO_EMBEDDED_ACCESS_CHECKS + DBUG_RETURN(CR_OK); +#endif + + if (pkt_len == 0) /* no password */ + DBUG_RETURN(info->auth_string[0] ? CR_ERROR : CR_OK); + + info->password_used= PASSWORD_USED_YES; + if (pkt_len == SCRAMBLE_LENGTH) + { + if (!mpvio->acl_user->salt_len) + DBUG_RETURN(CR_ERROR); + + DBUG_RETURN(check_scramble(pkt, mpvio->scramble, mpvio->acl_user->salt) ? + CR_ERROR : CR_OK); + } + + inc_host_errors(mpvio->ip); + my_error(ER_HANDSHAKE_ERROR, MYF(0), mpvio->auth_info.host_or_ip); + 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; + + /* generate the scramble, or reuse the old one */ + if (mpvio->scramble[SCRAMBLE_LENGTH]) + create_random_string(mpvio->scramble, SCRAMBLE_LENGTH, mpvio->rand); + + /* send it to the client */ + if (mpvio->write_packet(mpvio, (uchar*) mpvio->scramble, SCRAMBLE_LENGTH + 1)) + return CR_ERROR; + + /* read the reply and authenticate */ + if ((pkt_len= mpvio->read_packet(mpvio, &pkt)) < 0) + return CR_ERROR; + +#ifdef NO_EMBEDDED_ACCESS_CHECKS + return CR_OK; +#endif + + /* + legacy: if switch_from_long_to_short_scramble, + 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) + pkt_len= strnlen((char*)pkt, pkt_len); + + if (pkt_len == 0) /* no password */ + return info->auth_string[0] ? CR_ERROR : CR_OK; + + if (secure_auth(mpvio)) + return CR_ERROR; + + info->password_used= PASSWORD_USED_YES; + + if (pkt_len == SCRAMBLE_LENGTH_323) + { + if (!mpvio->acl_user->salt_len) + return CR_ERROR; + + return check_scramble_323(pkt, mpvio->scramble, + (ulong *) mpvio->acl_user->salt) ? + CR_ERROR : CR_OK; + } + + inc_host_errors(mpvio->ip); + my_error(ER_HANDSHAKE_ERROR, MYF(0), mpvio->auth_info.host_or_ip); + return CR_ERROR; +} + +static struct st_mysql_auth native_password_handler= +{ + MYSQL_AUTHENTICATION_INTERFACE_VERSION, + native_password_plugin_name.str, + native_password_authenticate +}; + +static struct st_mysql_auth old_password_handler= +{ + MYSQL_AUTHENTICATION_INTERFACE_VERSION, + old_password_plugin_name.str, + old_password_authenticate +}; + +mysql_declare_plugin(mysql_password) +{ + MYSQL_AUTHENTICATION_PLUGIN, /* type constant */ + &native_password_handler, /* type descriptor */ + native_password_plugin_name.str, /* Name */ + "R.J.Silk, Sergei Golubchik", /* Author */ + "Native MySQL authentication", /* Description */ + PLUGIN_LICENSE_GPL, /* License */ + NULL, /* Init function */ + NULL, /* Deinit function */ + 0x0100, /* Version (1.0) */ + NULL, /* status variables */ + NULL, /* system variables */ + NULL /* config options */ +}, +{ + MYSQL_AUTHENTICATION_PLUGIN, /* type constant */ + &old_password_handler, /* type descriptor */ + old_password_plugin_name.str, /* Name */ + "R.J.Silk, Sergei Golubchik", /* Author */ + "Old MySQL-4.0 authentication", /* Description */ + PLUGIN_LICENSE_GPL, /* License */ + NULL, /* Init function */ + NULL, /* Deinit function */ + 0x0100, /* Version (1.0) */ + NULL, /* status variables */ + NULL, /* system variables */ + NULL /* config options */ +} +mysql_declare_plugin_end; + diff --git a/sql/sql_acl.h b/sql/sql_acl.h index c0b536b7740..3a7eefa058c 100644 --- a/sql/sql_acl.h +++ b/sql/sql_acl.h @@ -173,53 +173,6 @@ enum mysql_db_table_field extern const TABLE_FIELD_DEF mysql_db_table_def; extern bool mysql_user_table_is_in_short_password_format; -/* Classes */ - -struct acl_host_and_ip -{ - char *hostname; - long ip,ip_mask; // Used with masked ip:s -}; - - -class ACL_ACCESS { -public: - ulong sort; - ulong access; -}; - - -/* ACL_HOST is used if no host is specified */ - -class ACL_HOST :public ACL_ACCESS -{ -public: - acl_host_and_ip host; - char *db; -}; - - -class ACL_USER :public ACL_ACCESS -{ -public: - acl_host_and_ip host; - uint hostname_length; - USER_RESOURCES user_resource; - char *user; - uint8 salt[SCRAMBLE_LENGTH+1]; // scrambled password in binary form - uint8 salt_len; // 0 - no password, 4 - 3.20, 8 - 3.23, 20 - 4.1.1 - enum SSL_type ssl_type; - const char *ssl_cipher, *x509_issuer, *x509_subject; -}; - - -class ACL_DB :public ACL_ACCESS -{ -public: - acl_host_and_ip host; - char *user,*db; -}; - /* prototypes */ bool hostname_requires_resolving(const char *hostname); @@ -228,17 +181,16 @@ my_bool acl_reload(THD *thd); void acl_free(bool end=0); ulong acl_get(const char *host, const char *ip, const char *user, const char *db, my_bool db_is_pattern); -int acl_getroot(THD *thd, USER_RESOURCES *mqh, const char *passwd, - uint passwd_len); -bool acl_getroot_no_password(Security_context *sctx, char *user, char *host, - char *ip, char *db); +bool acl_authenticate(THD *thd, uint connect_errors, uint com_change_user_pkt_len); +bool acl_getroot(Security_context *sctx, char *user, char *host, + char *ip, char *db); bool acl_check_host(const char *host, const char *ip); int check_change_password(THD *thd, const char *host, const char *user, char *password, uint password_len); 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); @@ -420,4 +372,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 1f96f1cf0e4..f648d219fac 100644 --- a/sql/sql_admin.cc +++ b/sql/sql_admin.cc @@ -85,7 +85,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, @@ -111,9 +111,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. */ @@ -151,6 +148,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))) @@ -231,6 +231,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 @@ -311,7 +331,13 @@ 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; + /* + Under locked tables, we know that the table can be opened, + so any errors opening the table are logical errors. + In these cases it makes sense to report them. + */ + if (!thd->locked_tables_mode) + thd->no_warnings_for_error= no_warnings_for_error; if (view_operator_func == NULL) table->required_type=FRMTYPE_TABLE; @@ -320,6 +346,14 @@ static bool mysql_admin_table(THD* thd, TABLE_LIST* tables, 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. @@ -418,9 +452,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 */ 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_audit.cc b/sql/sql_audit.cc index b7d363dc09a..74e9e603ebe 100644 --- a/sql/sql_audit.cc +++ b/sql/sql_audit.cc @@ -81,9 +81,34 @@ static void general_class_handler(THD *thd, uint event_subtype, va_list ap) } +static void connection_class_handler(THD *thd, uint event_subclass, va_list ap) +{ + mysql_event_connection event; + event.event_class= MYSQL_AUDIT_CONNECTION_CLASS; + 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, (const mysql_event *) &event); +} + + static audit_handler_t audit_handlers[] = { - general_class_handler + general_class_handler, connection_class_handler }; static const uint audit_handlers_count= 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 c0ea60cac3b..9d75af5734a 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, 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 @@ -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 @@ -100,14 +100,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 } }; /** @@ -250,7 +247,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) { uint key_length= (uint) (strmov(strmov(key, table_list->db)+1, @@ -301,8 +299,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; @@ -346,7 +342,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; @@ -1290,20 +1285,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); } @@ -1369,11 +1356,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(); } @@ -1993,39 +1975,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); + + 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. +*/ - key_length= create_table_def_key(thd, key, table_list, 1); - for (table=thd->temporary_tables ; table ; table= table->next) +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; } @@ -2447,7 +2450,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; } @@ -2612,32 +2616,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 @@ -2808,6 +2786,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) @@ -2886,8 +2917,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, @@ -2915,7 +2950,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)) { @@ -3029,41 +3068,11 @@ 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= 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->ft_handler= 0; - 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; - DBUG_ASSERT(table->key_read == 0); - /* Tables may be reused in a sub statement. */ - DBUG_ASSERT(! table->file->extra(HA_EXTRA_IS_ATTACHED_CHILDREN)); + + table->init(thd, table_list); + DBUG_RETURN(FALSE); err_lock: @@ -3385,7 +3394,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= @@ -3862,7 +3870,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) {} @@ -4019,6 +4028,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; @@ -4536,13 +4551,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 @@ -4555,11 +4572,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); } @@ -5177,6 +5203,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 @@ -5202,7 +5230,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"); @@ -5218,7 +5247,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. */ @@ -5327,7 +5357,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); } @@ -5358,7 +5392,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)); @@ -5374,11 +5408,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: @@ -5415,7 +5457,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) || @@ -5672,7 +5714,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; @@ -5710,35 +5752,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", @@ -5781,7 +5825,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; diff --git a/sql/sql_base.h b/sql/sql_base.h index 2e4554313e5..35fa04b3674 100644 --- a/sql/sql_base.h +++ b/sql/sql_base.h @@ -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); @@ -449,6 +455,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) @@ -491,7 +507,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; } @@ -502,6 +518,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 @@ -509,7 +540,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. @@ -525,6 +556,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 6f59c3f51e1..503d830a10e 100644 --- a/sql/sql_binlog.cc +++ b/sql/sql_binlog.cc @@ -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 */ @@ -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_builtin.cc.in b/sql/sql_builtin.cc.in index d9d9b610baf..8265c781e79 100644 --- a/sql/sql_builtin.cc.in +++ b/sql/sql_builtin.cc.in @@ -23,7 +23,7 @@ extern "C" extern #endif builtin_plugin - @mysql_mandatory_plugins@ @mysql_optional_plugins@ builtin_binlog_plugin; + @mysql_mandatory_plugins@ @mysql_optional_plugins@ builtin_binlog_plugin, builtin_mysql_password_plugin; struct st_mysql_plugin *mysql_optional_plugins[]= { @@ -32,5 +32,5 @@ struct st_mysql_plugin *mysql_optional_plugins[]= struct st_mysql_plugin *mysql_mandatory_plugins[]= { - builtin_binlog_plugin, @mysql_mandatory_plugins@ 0 + builtin_binlog_plugin, builtin_mysql_password_plugin, @mysql_mandatory_plugins@ 0 }; diff --git a/sql/sql_cache.cc b/sql/sql_cache.cc index b57c851edf4..0dadc0f0cd4 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> @@ -341,6 +342,7 @@ TODO list: #include "../storage/myisammrg/ha_myisammrg.h" #include "../storage/myisammrg/myrg_def.h" #include "probes_mysql.h" +#include "transaction.h" #ifdef EMBEDDED_LIBRARY #include "emb_qcache.h" @@ -370,32 +372,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) -{ - DBUG_ENTER("debug_wait_for_kill"); - const char *prev_info; - THD *thd; - 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; - 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) @@ -407,6 +383,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 @@ -428,6 +450,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); @@ -437,7 +461,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 @@ -496,6 +519,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); @@ -503,7 +528,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 @@ -524,6 +548,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); @@ -531,7 +557,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 @@ -871,9 +896,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; @@ -1683,6 +1706,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 @@ -1724,6 +1749,13 @@ def_week_frmt: %lu, in_trans: %d, autocommit: %d", thd->limit_found_rows = query->found_rows(); thd->status_var.last_query_cost= 0.0; + /* + 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(); @@ -1769,8 +1801,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; } @@ -1961,8 +1992,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) @@ -2302,9 +2332,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) @@ -2750,8 +2778,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 @@ -2759,9 +2786,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); @@ -2811,7 +2836,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 f65e5c05826..c058e66df97 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -537,7 +537,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; @@ -630,7 +631,7 @@ THD::THD() thr_lock_info_init(&lock_info); /* safety: will be reset after start */ m_internal_handler= NULL; - current_user_used= FALSE; + m_binlog_invoker= FALSE; memset(&invoker_user, 0, sizeof(invoker_user)); memset(&invoker_host, 0, sizeof(invoker_host)); } @@ -1178,36 +1179,70 @@ void add_diff_to_status(STATUS_VAR *to_var, STATUS_VAR *from_var, } +/** + 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(thread_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(thread_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); @@ -1231,6 +1266,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) { @@ -1243,6 +1283,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 @@ -1335,10 +1409,24 @@ 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; } +LEX_STRING * +make_lex_string_root(MEM_ROOT *mem_root, + LEX_STRING *lex_str, const char* str, uint length, + bool allocate_lex_string) +{ + if (allocate_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; + lex_str->length= length; + return lex_str; +} + /** Create a LEX_STRING in this connection. @@ -1353,13 +1441,8 @@ LEX_STRING *THD::make_lex_string(LEX_STRING *lex_str, const char* str, uint length, bool allocate_lex_string) { - if (allocate_lex_string) - if (!(lex_str= (LEX_STRING *)alloc(sizeof(LEX_STRING)))) - return 0; - if (!(lex_str->str= strmake_root(mem_root, str, length))) - return 0; - lex_str->length= length; - return lex_str; + return make_lex_string_root (mem_root, lex_str, str, + length, allocate_lex_string); } @@ -1832,8 +1915,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); @@ -2575,8 +2659,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; } @@ -2615,15 +2697,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. */ @@ -2874,6 +2947,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; } @@ -2925,9 +3005,9 @@ void THD::set_status_var_init() void Security_context::init() { - host= user= priv_user= ip= 0; + host= user= ip= external_user= 0; host_or_ip= "connecting host"; - 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; @@ -2949,6 +3029,12 @@ void Security_context::destroy() user= NULL; } + if (external_user) + { + my_free(external_user); + user= NULL; + } + my_free(ip); ip= NULL; } @@ -2959,8 +3045,7 @@ void Security_context::skip_grants() /* privileges for the user are unknown everything is allowed */ host_or_ip= (char *)""; master_access= ~NO_ACCESS; - priv_user= (char *)""; - *priv_host= '\0'; + *priv_user= *priv_host= '\0'; } @@ -3002,7 +3087,7 @@ bool Security_context::set_user(char *user_arg) of a statement under credentials of a different user, e.g. definer of a procedure, we authenticate this user in a local instance of Security_context by means of this method (and - ultimately by means of acl_getroot_no_password), and make the + ultimately by means of acl_getroot), and make the local instance active in the thread by re-setting thd->security_ctx pointer. @@ -3036,19 +3121,12 @@ change_security_context(THD *thd, DBUG_ASSERT(definer_user->str && definer_host->str); *backup= NULL; - /* - The current security context may have NULL members - if we have just started the thread and not authenticated - any user. This use case is currently in events worker thread. - */ - needs_change= (thd->security_ctx->priv_user == NULL || - strcmp(definer_user->str, thd->security_ctx->priv_user) || - thd->security_ctx->priv_host == NULL || + needs_change= (strcmp(definer_user->str, thd->security_ctx->priv_user) || my_strcasecmp(system_charset_info, definer_host->str, thd->security_ctx->priv_host)); if (needs_change) { - if (acl_getroot_no_password(this, definer_user->str, definer_host->str, + if (acl_getroot(this, definer_user->str, definer_host->str, definer_host->str, db->str)) { my_error(ER_NO_SUCH_USER, MYF(0), definer_user->str, @@ -3151,7 +3229,7 @@ extern "C" 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); } /** @@ -3162,7 +3240,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) @@ -3407,20 +3485,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); } @@ -3450,16 +3529,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()) { @@ -3467,6 +3550,10 @@ void THD::get_definer(LEX_USER *definer) definer->host= invoker_host; definer->password.str= NULL; definer->password.length= 0; + definer->plugin.str= (char *) ""; + definer->plugin.length= 0; + definer->auth.str= (char *) ""; + definer->auth.length= 0; } else #endif diff --git a/sql/sql_class.h b/sql/sql_class.h index e86e42dc094..8b05497388e 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, 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 @@ -109,6 +109,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) @@ -722,12 +757,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. @@ -822,8 +869,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}; @@ -862,9 +909,13 @@ public: priv_user - The user privilege we are using. May be "" for anonymous user. ip - client IP */ - char *host, *user, *priv_user, *ip; + 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 */ @@ -1054,12 +1105,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; }; /** @@ -1332,26 +1383,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; }; @@ -1949,6 +2017,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, @@ -1963,7 +2037,8 @@ public: char scramble[SCRAMBLE_LENGTH+1]; bool slave_thread, one_shot_set; - bool no_errors, password; + bool no_errors; + uchar password; /** Set to TRUE if execution of the current compound statement can not continue. In particular, disables activation of @@ -2134,6 +2209,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. */ @@ -2206,6 +2284,20 @@ public: } 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; @@ -2414,8 +2506,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); @@ -2671,9 +2761,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) { @@ -2686,14 +2787,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) { @@ -2734,7 +2834,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. @@ -2774,6 +2874,11 @@ my_eof(THD *thd) #define reenable_binlog(A) (A)->variables.option_bits= tmp_disable_binlog__save_options;} +LEX_STRING * +make_lex_string_root(MEM_ROOT *mem_root, + LEX_STRING *lex_str, const char* str, uint length, + bool allocate_lex_string); + /* Used to hold information about file and file structure in exchange via non-DB file (...INTO OUTFILE..., ...LOAD DATA...) @@ -3488,20 +3593,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 3ba6deed0a4..ad6fe492056 100644 --- a/sql/sql_connect.cc +++ b/sql/sql_connect.cc @@ -62,9 +62,9 @@ #ifndef NO_EMBEDDED_ACCESS_CHECKS static HASH hash_user_connections; -static int get_or_create_user_conn(THD *thd, const char *user, - const char *host, - USER_RESOURCES *mqh) +int get_or_create_user_conn(THD *thd, const char *user, + const char *host, + const USER_RESOURCES *mqh) { int return_val= 0; size_t temp_len, user_len; @@ -130,7 +130,6 @@ end: 1 error */ -static int check_for_max_user_connections(THD *thd, USER_CONN *uc) { int error=0; @@ -291,256 +290,6 @@ end: #endif /* NO_EMBEDDED_ACCESS_CHECKS */ - -/** - Check if user exist and password supplied is correct. - - @param thd thread handle, thd->security_ctx->{host,user,ip} are used - @param command originator of the check: now check_user is called - during connect and change user procedures; used for - logging. - @param passwd scrambled password received from client - @param passwd_len length of scrambled password - @param db database name to connect to, may be NULL - @param check_count TRUE if establishing a new connection. In this case - check that we have not exceeded the global - max_connections limist - - @note Host, user and passwd may point to communication buffer. - Current implementation does not depend on that, but future changes - should be done with this in mind; 'thd' is INOUT, all other params - are 'IN'. - - @retval 0 OK; thd->security_ctx->user/master_access/priv_user/db_access and - thd->db are updated; OK is sent to the client. - @retval 1 error, e.g. access denied or handshake error, not sent to - the client. A message is pushed into the error stack. -*/ - -int -check_user(THD *thd, enum enum_server_command command, - const char *passwd, uint passwd_len, const char *db, - bool check_count) -{ - DBUG_ENTER("check_user"); - LEX_STRING db_str= { (char *) db, db ? strlen(db) : 0 }; - - /* - 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 - pointer if connect failed. Also in case of 'CHANGE USER' failure, - current database will be switched to 'no database selected'. - */ - thd->reset_db(NULL, 0); - -#ifdef NO_EMBEDDED_ACCESS_CHECKS - thd->main_security_ctx.master_access= GLOBAL_ACLS; // Full rights - /* Change database if necessary */ - if (db && db[0]) - { - if (mysql_change_db(thd, &db_str, FALSE)) - DBUG_RETURN(1); - } - my_ok(thd); - DBUG_RETURN(0); -#else - - my_bool opt_secure_auth_local; - mysql_mutex_lock(&LOCK_global_system_variables); - opt_secure_auth_local= opt_secure_auth; - mysql_mutex_unlock(&LOCK_global_system_variables); - - /* - If the server is running in secure auth mode, short scrambles are - forbidden. - */ - if (opt_secure_auth_local && passwd_len == SCRAMBLE_LENGTH_323) - { - my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0)); - general_log_print(thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE)); - DBUG_RETURN(1); - } - if (passwd_len != 0 && - passwd_len != SCRAMBLE_LENGTH && - passwd_len != SCRAMBLE_LENGTH_323) - { - my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip); - DBUG_RETURN(1); - } - - USER_RESOURCES ur; - int res= acl_getroot(thd, &ur, passwd, passwd_len); -#ifndef EMBEDDED_LIBRARY - if (res == -1) - { - /* - This happens when client (new) sends password scrambled with - scramble(), but database holds old value (scrambled with - scramble_323()). Here we please client to send scrambled_password - in old format. - */ - NET *net= &thd->net; - if (opt_secure_auth_local) - { - my_error(ER_SERVER_IS_IN_SECURE_AUTH_MODE, MYF(0), - thd->main_security_ctx.user, - thd->main_security_ctx.host_or_ip); - general_log_print(thd, COM_CONNECT, ER(ER_SERVER_IS_IN_SECURE_AUTH_MODE), - thd->main_security_ctx.user, - thd->main_security_ctx.host_or_ip); - DBUG_RETURN(1); - } - /* We have to read very specific packet size */ - if (send_old_password_request(thd) || - my_net_read(net) != SCRAMBLE_LENGTH_323 + 1) - { - inc_host_errors(thd->main_security_ctx.ip); - - my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip); - DBUG_RETURN(1); - } - /* Final attempt to check the user based on reply */ - /* So as passwd is short, errcode is always >= 0 */ - res= acl_getroot(thd, &ur, (char *) net->read_pos, SCRAMBLE_LENGTH_323); - } -#endif /*EMBEDDED_LIBRARY*/ - /* here res is always >= 0 */ - if (res == 0) - { - if (!(thd->main_security_ctx.master_access & - NO_ACCESS)) // authentication is OK - { - DBUG_PRINT("info", - ("Capabilities: %lu packet_length: %ld Host: '%s' " - "Login user: '%s' Priv_user: '%s' Using password: %s " - "Access: %lu db: '%s'", - thd->client_capabilities, - thd->max_client_packet_length, - thd->main_security_ctx.host_or_ip, - thd->main_security_ctx.user, - thd->main_security_ctx.priv_user, - passwd_len ? "yes": "no", - thd->main_security_ctx.master_access, - (thd->db ? thd->db : "*none*"))); - - if (check_count) - { - mysql_mutex_lock(&LOCK_connection_count); - bool count_ok= connection_count <= max_connections || - (thd->main_security_ctx.master_access & SUPER_ACL); - mysql_mutex_unlock(&LOCK_connection_count); - - if (!count_ok) - { // too many connections - my_error(ER_CON_COUNT_ERROR, MYF(0)); - DBUG_RETURN(1); - } - } - - /* - Log the command before authentication checks, so that the user can - check the log for the tried login tried and also to detect - break-in attempts. - */ - general_log_print(thd, command, - (thd->main_security_ctx.priv_user == - thd->main_security_ctx.user ? - (char*) "%s@%s on %s" : - (char*) "%s@%s as anonymous on %s"), - thd->main_security_ctx.user, - thd->main_security_ctx.host_or_ip, - db ? db : (char*) ""); - - /* - This is the default access rights for the current database. It's - set to 0 here because we don't have an active database yet (and we - may not have an active database to set. - */ - thd->main_security_ctx.db_access=0; - - /* Don't allow user to connect if he has done too many queries */ - if ((ur.questions || ur.updates || ur.conn_per_hour || ur.user_conn || - global_system_variables.max_user_connections) && - get_or_create_user_conn(thd, - (opt_old_style_user_limits ? thd->main_security_ctx.user : - thd->main_security_ctx.priv_user), - (opt_old_style_user_limits ? thd->main_security_ctx.host_or_ip : - thd->main_security_ctx.priv_host), - &ur)) - { - /* The error is set by get_or_create_user_conn(). */ - DBUG_RETURN(1); - } - if (thd->user_connect && - (thd->user_connect->user_resources.conn_per_hour || - thd->user_connect->user_resources.user_conn || - global_system_variables.max_user_connections) && - check_for_max_user_connections(thd, thd->user_connect)) - { - /* The error is set in check_for_max_user_connections(). */ - DBUG_RETURN(1); - } - - /* Change database if necessary */ - if (db && db[0]) - { - if (mysql_change_db(thd, &db_str, FALSE)) - { - /* mysql_change_db() has pushed the error message. */ - if (thd->user_connect) - { - decrease_user_connections(thd->user_connect); - thd->user_connect= 0; - } - DBUG_RETURN(1); - } - } - my_ok(thd); - thd->password= test(passwd_len); // remember for error messages -#ifndef EMBEDDED_LIBRARY - /* - Allow the network layer to skip big packets. Although a malicious - authenticated session might use this to trick the server to read - big packets indefinitely, this is a previously established behavior - that needs to be preserved as to not break backwards compatibility. - */ - thd->net.skip_big_packet= TRUE; -#endif - /* Ready to handle queries */ - DBUG_RETURN(0); - } - } - else if (res == 2) // client gave short hash, server has long hash - { - my_error(ER_NOT_SUPPORTED_AUTH_MODE, MYF(0)); - general_log_print(thd, COM_CONNECT, ER(ER_NOT_SUPPORTED_AUTH_MODE)); - DBUG_RETURN(1); - } - my_error(ER_ACCESS_DENIED_ERROR, MYF(0), - thd->main_security_ctx.user, - thd->main_security_ctx.host_or_ip, - passwd_len ? ER(ER_YES) : ER(ER_NO)); - general_log_print(thd, COM_CONNECT, ER(ER_ACCESS_DENIED_ERROR), - thd->main_security_ctx.user, - thd->main_security_ctx.host_or_ip, - passwd_len ? ER(ER_YES) : ER(ER_NO)); - /* - Log access denied messages to the error log when log-warnings = 2 - so that the overhead of the general query log is not required to track - failed connections. - */ - if (global_system_variables.log_warnings > 1) - { - sql_print_warning(ER(ER_ACCESS_DENIED_ERROR), - thd->main_security_ctx.user, - thd->main_security_ctx.host_or_ip, - passwd_len ? ER(ER_YES) : ER(ER_NO)); - } - DBUG_RETURN(1); -#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. @@ -673,17 +422,14 @@ bool init_new_connection_handler_thread() thd thread handle RETURN - 0 success, OK is sent to user, thd is updated. - -1 error, which is sent to user - > 0 error code (not sent to user) + 0 success, thd is updated. + 1 error */ static int check_connection(THD *thd) { uint connect_errors= 0; NET *net= &thd->net; - ulong pkt_len= 0; - char *end; DBUG_PRINT("info", ("New connection received on %s", vio_description(net->vio))); @@ -748,203 +494,10 @@ static int check_connection(THD *thd) } vio_keepalive(net->vio, TRUE); - ulong server_capabilites; - { - /* buff[] needs to big enough to hold the server_version variable */ - char buff[SERVER_VERSION_LENGTH + 1 + SCRAMBLE_LENGTH + 1 + 64]; - server_capabilites= CLIENT_BASIC_FLAGS; - - if (opt_using_transactions) - server_capabilites|= CLIENT_TRANSACTIONS; -#ifdef HAVE_COMPRESS - server_capabilites|= CLIENT_COMPRESS; -#endif /* HAVE_COMPRESS */ -#if defined(HAVE_OPENSSL) - if (ssl_acceptor_fd) - { - server_capabilites |= CLIENT_SSL; /* Wow, SSL is available! */ - server_capabilites |= CLIENT_SSL_VERIFY_SERVER_CERT; - } -#endif /* HAVE_OPENSSL */ - - end= strnmov(buff, server_version, SERVER_VERSION_LENGTH) + 1; - int4store((uchar*) end, thd->thread_id); - end+= 4; - /* - So as check_connection is the only entry point to authorization - procedure, scramble is set here. This gives us new scramble for - each handshake. - */ - create_random_string(thd->scramble, SCRAMBLE_LENGTH, &thd->rand); - /* - Old clients does not understand long scrambles, but can ignore packet - tail: that's why first part of the scramble is placed here, and second - part at the end of packet. - */ - end= strmake(end, thd->scramble, SCRAMBLE_LENGTH_323) + 1; - - int2store(end, server_capabilites); - /* write server characteristics: up to 16 bytes allowed */ - end[2]=(char) default_charset_info->number; - int2store(end+3, thd->server_status); - bzero(end+5, 13); - end+= 18; - /* write scramble tail */ - end= strmake(end, thd->scramble + SCRAMBLE_LENGTH_323, - SCRAMBLE_LENGTH - SCRAMBLE_LENGTH_323) + 1; - - /* At this point we write connection message and read reply */ - if (net_write_command(net, (uchar) protocol_version, (uchar*) "", 0, - (uchar*) buff, (size_t) (end-buff)) || - (pkt_len= my_net_read(net)) == packet_error || - pkt_len < MIN_HANDSHAKE_SIZE) - { - inc_host_errors(thd->main_security_ctx.ip); - - my_error(ER_HANDSHAKE_ERROR, MYF(0), - thd->main_security_ctx.host_or_ip); - return 1; - } - } -#ifdef _CUSTOMCONFIG_ -#include "_cust_sql_parse.h" -#endif - if (connect_errors) - reset_host_errors(thd->main_security_ctx.ip); if (thd->packet.alloc(thd->variables.net_buffer_length)) return 1; /* The error is set by alloc(). */ - thd->client_capabilities= uint2korr(net->read_pos); - if (thd->client_capabilities & CLIENT_PROTOCOL_41) - { - thd->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]); - thd->update_charset(); - end= (char*) net->read_pos+32; - } - else - { - thd->max_client_packet_length= uint3korr(net->read_pos+2); - end= (char*) net->read_pos+5; - } - /* - Disable those bits which are not supported by the server. - This is a precautionary measure, if the client lies. See Bug#27944. - */ - thd->client_capabilities&= server_capabilites; - - if (thd->client_capabilities & CLIENT_IGNORE_SPACE) - thd->variables.sql_mode|= MODE_IGNORE_SPACE; -#if defined(HAVE_OPENSSL) - DBUG_PRINT("info", ("client capabilities: %lu", thd->client_capabilities)); - if (thd->client_capabilities & CLIENT_SSL) - { - /* Do the SSL layering. */ - if (!ssl_acceptor_fd) - { - inc_host_errors(thd->main_security_ctx.ip); - my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip); - return 1; - } - DBUG_PRINT("info", ("IO layer change in progress...")); - if (sslaccept(ssl_acceptor_fd, net->vio, net->read_timeout)) - { - DBUG_PRINT("error", ("Failed to accept new SSL connection")); - inc_host_errors(thd->main_security_ctx.ip); - - my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip); - return 1; - } - DBUG_PRINT("info", ("Reading user information over SSL layer")); - if ((pkt_len= my_net_read(net)) == packet_error || - pkt_len < NORMAL_HANDSHAKE_SIZE) - { - DBUG_PRINT("error", ("Failed to read user information (pkt_len= %lu)", - pkt_len)); - inc_host_errors(thd->main_security_ctx.ip); - - my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip); - return 1; - } - } -#endif /* HAVE_OPENSSL */ - - if (end >= (char*) net->read_pos+ pkt_len +2) - { - inc_host_errors(thd->main_security_ctx.ip); - - my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip); - return 1; - } - - 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; - - char *user= end; - char *passwd= strend(user)+1; - uint user_len= passwd - user - 1; - char *db= passwd; - char db_buff[NAME_LEN + 1]; // buffer to store db in utf8 - char user_buff[USERNAME_LENGTH + 1]; // buffer to store user in utf8 - uint dummy_errors; - - /* - Old clients send null-terminated string as password; new clients send - the size (1 byte) + string (not null-terminated). Hence in case of empty - password both send '\0'. - - This strlen() can't be easily deleted without changing protocol. - - Cast *passwd to an unsigned char, so that it doesn't extend the sign for - *passwd > 127 and become 2**32-127+ after casting to uint. - */ - uint passwd_len= thd->client_capabilities & CLIENT_SECURE_CONNECTION ? - (uchar)(*passwd++) : strlen(passwd); - db= thd->client_capabilities & CLIENT_CONNECT_WITH_DB ? - db + passwd_len + 1 : 0; - /* strlen() can't be easily deleted without changing protocol */ - uint db_len= db ? strlen(db) : 0; - - if (passwd + passwd_len + db_len > (char *)net->read_pos + pkt_len) - { - inc_host_errors(thd->main_security_ctx.ip); - - my_error(ER_HANDSHAKE_ERROR, MYF(0), thd->main_security_ctx.host_or_ip); - return 1; - } - - /* Since 4.1 all database names are stored in utf8 */ - if (db) - { - db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1, - system_charset_info, - db, db_len, - thd->charset(), &dummy_errors)]= 0; - db= db_buff; - } - - user_buff[user_len= copy_and_convert(user_buff, sizeof(user_buff)-1, - system_charset_info, user, user_len, - thd->charset(), &dummy_errors)]= '\0'; - user= user_buff; - - /* If username starts and ends in "'", chop them off */ - if (user_len > 1 && user[0] == '\'' && user[user_len - 1] == '\'') - { - user[user_len-1]= 0; - user++; - user_len-= 2; - } - - my_free(thd->main_security_ctx.user); - if (!(thd->main_security_ctx.user= my_strdup(user, MYF(MY_WME)))) - return 1; /* The error is set by my_strdup(). */ - return check_user(thd, COM_CONNECT, passwd, passwd_len, db, TRUE); + return acl_authenticate(thd, connect_errors, 0); } @@ -965,7 +518,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(thread_scheduler, end_thread, (thd, 0)); return 1; // Error @@ -1140,7 +693,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(thread_scheduler, end_thread, (thd, 0)); return; @@ -1175,12 +728,15 @@ void do_handle_one_connection(THD *thd_arg) for (;;) { NET *net= &thd->net; + bool rc; lex_start(thd); - if (login_connection(thd)) + rc= login_connection(thd); + MYSQL_AUDIT_NOTIFY_CONNECTION_CONNECT(thd); + if (rc) goto end_thread; - MYSQL_CONNECTION_START(thd->thread_id, thd->security_ctx->priv_user, + MYSQL_CONNECTION_START(thd->thread_id, &thd->security_ctx->priv_user[0], (char *) thd->security_ctx->host_or_ip); prepare_new_connection_state(thd); @@ -1195,7 +751,7 @@ void do_handle_one_connection(THD *thd_arg) end_connection(thd); end_thread: - close_connection(thd, 0, 1); + close_connection(thd); if (MYSQL_CALLBACK_ELSE(thread_scheduler, end_thread, (thd, 1), 0)) return; // Probably no-threads diff --git a/sql/sql_connect.h b/sql/sql_connect.h index bfcc04ba093..666db4c6462 100644 --- a/sql/sql_connect.h +++ b/sql/sql_connect.h @@ -43,5 +43,8 @@ int check_user(THD *thd, enum enum_server_command command, bool login_connection(THD *thd); void prepare_new_connection_state(THD* thd); void end_connection(THD *thd); +int get_or_create_user_conn(THD *thd, const char *user, + const char *host, const USER_RESOURCES *mqh); +int check_for_max_user_connections(THD *thd, USER_CONN *uc); #endif /* SQL_CONNECT_INCLUDED */ diff --git a/sql/sql_cursor.cc b/sql/sql_cursor.cc index 7a9834b4cde..f607936d5b9 100644 --- a/sql/sql_cursor.cc +++ b/sql/sql_cursor.cc @@ -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); @@ -277,7 +277,6 @@ int Materialized_cursor::open(JOIN *join __attribute__((unused))) 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; } return rc; } @@ -318,12 +317,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: diff --git a/sql/sql_db.cc b/sql/sql_db.cc index 517cb9139e9..38f39ec0be7 100644 --- a/sql/sql_db.cc +++ b/sql/sql_db.cc @@ -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,64 @@ 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))) + { + tables= NULL; + } + else + { /* We temporarily disable the binary log while dropping the objects in the database. Since the DROP DATABASE statement is always @@ -808,23 +857,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,14 +915,13 @@ 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()) { @@ -880,7 +935,7 @@ 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; @@ -894,7 +949,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 +969,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 +982,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 +1015,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,16 +1024,16 @@ 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, '.'))) @@ -1020,7 +1041,7 @@ static long mysql_rm_known_files(THD *thd, MY_DIR *dirp, const char *db, if (find_type(extension, &deletable_extentions,1+2) <= 0) { if (find_type(extension, ha_known_exts(),1+2) <= 0) - found_other_files++; + *found_other_files= true; continue; } /* just for safety we use files_charset_info */ @@ -1036,7 +1057,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 +1075,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 2f69bac917e..685ce1c7b42 100644 --- a/sql/sql_delete.cc +++ b/sql/sql_delete.cc @@ -525,9 +525,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 47bc13beb53..9b1b9353a23 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; @@ -306,13 +307,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 8c038e10a1f..d0982b879e7 100644 --- a/sql/sql_error.cc +++ b/sql/sql_error.cc @@ -334,7 +334,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 +364,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 +393,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 diff --git a/sql/sql_error.h b/sql/sql_error.h index 87e98e27673..14dc5e6d12c 100644 --- a/sql/sql_error.h +++ b/sql/sql_error.h @@ -79,12 +79,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; } @@ -111,15 +105,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 diff --git a/sql/sql_handler.cc b/sql/sql_handler.cc index a5c126a8521..b5cd3ac9e9a 100644 --- a/sql/sql_handler.cc +++ b/sql/sql_handler.cc @@ -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); } @@ -969,24 +971,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 4e3df950134..7d106fbe936 100644 --- a/sql/sql_help.cc +++ b/sql/sql_help.cc @@ -699,7 +699,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 adbdc1ffbc8..0b463ff1202 100644 --- a/sql/sql_insert.cc +++ b/sql/sql_insert.cc @@ -77,7 +77,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); @@ -419,8 +420,7 @@ void prepare_triggers_for_insert_stmt(TABLE *table) static void upgrade_lock_type(THD *thd, thr_lock_type *lock_type, - enum_duplicates duplic, - bool is_multi_insert) + enum_duplicates duplic) { if (duplic == DUP_UPDATE || (duplic == DUP_REPLACE && *lock_type == TL_WRITE_CONCURRENT_INSERT)) @@ -469,10 +469,9 @@ void upgrade_lock_type(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: @@ -529,32 +528,28 @@ void upgrade_lock_type(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)) /* @@ -564,7 +559,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) { @@ -589,13 +584,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 @@ -634,14 +629,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())) + /* 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; - /* Append the part of thd->query after "DELAYED" keyword */ - if (buf->append(thd->lex->keyword_delayed_begin + 7)) - return 1; - return 0; } @@ -682,8 +675,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; @@ -693,8 +685,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(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: @@ -1027,7 +1018,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)) { @@ -1622,9 +1613,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])) && @@ -1877,10 +1866,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 @@ -1892,35 +1882,26 @@ 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), status(0), handler_thread_initialized(FALSE), group_count(0) { DBUG_ENTER("Delayed_insert constructor"); - thd.security_ctx->user=thd.security_ctx->priv_user=(char*) delayed_user; + thd.security_ctx->user=(char*) delayed_user; thd.security_ctx->host=(char*) my_localhost; + strmake(thd.security_ctx->priv_user, thd.security_ctx->user, + USERNAME_LENGTH); thd.current_tablenr=0; thd.command=COM_DELAYED_INSERT; 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. @@ -2068,7 +2049,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; @@ -2101,7 +2083,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 */ @@ -2112,7 +2095,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; @@ -2496,6 +2482,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. @@ -2505,21 +2550,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) { /* @@ -2585,21 +2630,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; } @@ -2855,6 +2902,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, @@ -2921,39 +2975,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); @@ -3449,6 +3470,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); @@ -3992,7 +4016,7 @@ bool select_create::send_eof() { bool tmp=select_insert::send_eof(); if (tmp) - abort(); + abort_result_set(); else { /* @@ -4024,7 +4048,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 ba508783133..5e8ecc6b815 100644 --- a/sql/sql_lex.cc +++ b/sql/sql_lex.cc @@ -41,6 +41,7 @@ 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. @@ -382,7 +383,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; @@ -416,7 +417,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 1f4c9420102..2d11bc7aad7 100644 --- a/sql/sql_lex.h +++ b/sql/sql_lex.h @@ -958,6 +958,7 @@ inline bool st_select_lex_unit::is_union () #define ALTER_ALL_PARTITION (1L << 21) #define ALTER_REMOVE_PARTITIONING (1L << 22) #define ALTER_FOREIGN_KEY (1L << 23) +#define ALTER_TRUNCATE_PARTITION (1L << 24) enum enum_alter_table_change_level { @@ -1047,6 +1048,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 { @@ -1386,6 +1389,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) @@ -1419,7 +1423,10 @@ public: DBUG_ASSERT(0); break; } + MY_ASSERT_UNREACHABLE(); + return ""; } +#endif /* DBUG */ #define BINLOG_DIRECT_ON 0xF0 /* unsafe when --binlog-direct-non-trans-updates @@ -2279,19 +2286,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; @@ -2317,6 +2317,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; @@ -2355,15 +2356,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; + }; /** During name resolution search only in the table list given by @@ -2382,22 +2387,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() @@ -2407,6 +2396,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 15efa488173..5ec6e4a0467 100644 --- a/sql/sql_load.cc +++ b/sql/sql_load.cc @@ -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; @@ -1345,6 +1352,7 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs, MYF(MY_WME))) { my_free(buffer); /* purecov: inspected */ + buffer= NULL; error=1; } else @@ -1371,13 +1379,11 @@ READ_INFO::READ_INFO(File file_par, uint tot_length, CHARSET_INFO *cs, READ_INFO::~READ_INFO() { - if (!error) - { - if (need_end_io_cache) - ::end_io_cache(&cache); + if (!error && need_end_io_cache) + ::end_io_cache(&cache); + + if (buffer != NULL) my_free(buffer); - error=1; - } 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 b78815f0e52..2086100db98 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.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 @@ -18,12 +18,9 @@ #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 +31,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 +46,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, @@ -177,8 +173,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; @@ -262,21 +257,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 | @@ -287,26 +281,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; @@ -368,20 +354,19 @@ void init_update_queries(void) 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; @@ -402,6 +387,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; @@ -415,7 +401,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; @@ -503,9 +488,8 @@ static void handle_bootstrap_impl(THD *thd) #endif /* EMBEDDED_LIBRARY */ thd_proc_info(thd, 0); - thd->security_ctx->priv_user= - thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME)); - thd->security_ctx->priv_host[0]=0; + thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME)); + thd->security_ctx->priv_user[0]= thd->security_ctx->priv_host[0]=0; /* Make the "client" handle multiple results. This is necessary to enable stored procedures with SELECTs and Dynamic SQL @@ -553,7 +537,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(); @@ -616,7 +600,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; @@ -643,45 +627,6 @@ end: } -/** - @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() */ void free_items(Item *item) @@ -754,6 +699,22 @@ bool do_command(THD *thd) net_new_transaction(net); + /* + 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", @@ -916,7 +877,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; @@ -976,97 +937,38 @@ 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); - char *user= (char*) packet, *packet_end= packet + packet_length; - /* Safe because there is always a trailing \0 at the end of the packet */ - char *passwd= strend(user)+1; thd->change_user(); thd->clear_error(); // if errors from rollback - /* - Old clients send null-terminated string ('\0' for empty string) for - password. New clients send the size (1 byte) + string (not null - terminated, so also '\0' for empty string). + /* acl_authenticate() takes the data from net->read_pos */ + net->read_pos= (uchar*)packet; - Cast *passwd to an unsigned char, so that it doesn't extend the sign - for *passwd > 127 and become 2**32-127 after casting to uint. - */ - char db_buff[NAME_LEN+1]; // buffer to store db in utf8 - char *db= passwd; - char *save_db; - /* - If there is no password supplied, the packet must contain '\0', - in any type of handshake (4.1 or pre-4.1). - */ - if (passwd >= packet_end) - { - my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); - break; - } - uint passwd_len= (thd->client_capabilities & CLIENT_SECURE_CONNECTION ? - (uchar)(*passwd++) : strlen(passwd)); - uint dummy_errors, save_db_length, db_length; - int res; + 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; - USER_CONN *save_user_connect; - - db+= passwd_len + 1; - /* - Database name is always NUL-terminated, so in case of empty database - the packet must contain at least the trailing '\0'. - */ - if (db >= packet_end) - { - my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); - break; - } - db_length= strlen(db); - - char *ptr= db + db_length + 1; - uint cs_number= 0; - - if (ptr < packet_end) - { - if (ptr + 2 > packet_end) - { - my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); - break; - } - - cs_number= uint2korr(ptr); - } + CHARSET_INFO *save_character_set_client= + thd->variables.character_set_client; + CHARSET_INFO *save_collation_connection= + thd->variables.collation_connection; + CHARSET_INFO *save_character_set_results= + thd->variables.character_set_results; - /* Convert database name to utf8 */ - db_buff[copy_and_convert(db_buff, sizeof(db_buff)-1, - system_charset_info, db, db_length, - thd->charset(), &dummy_errors)]= 0; - db= db_buff; - - /* Save user and privileges */ - save_db_length= thd->db_length; - save_db= thd->db; - save_user_connect= thd->user_connect; - - if (!(thd->security_ctx->user= my_strdup(user, MYF(0)))) - { - thd->security_ctx->user= save_security_ctx.user; - my_message(ER_OUT_OF_RESOURCES, ER(ER_OUT_OF_RESOURCES), MYF(0)); - break; - } - - /* Clear variables that are allocated */ - thd->user_connect= 0; - thd->security_ctx->priv_user= thd->security_ctx->user; - res= check_user(thd, COM_CHANGE_USER, passwd, passwd_len, db, FALSE); - - if (res) + 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; thd->user_connect= save_user_connect; - thd->db= save_db; - thd->db_length= save_db_length; + thd->reset_db (save_db, save_db_length); + thd->variables.character_set_client= save_character_set_client; + thd->variables.collation_connection= save_collation_connection; + thd->variables.character_set_results= save_character_set_results; + thd->update_charset(); } else { @@ -1077,12 +979,6 @@ bool dispatch_command(enum enum_server_command command, THD *thd, #endif /* NO_EMBEDDED_ACCESS_CHECKS */ my_free(save_db); my_free(save_security_ctx.user); - - if (cs_number) - { - thd_init_client_charset(thd, cs_number); - thd->update_charset(); - } } break; } @@ -1122,7 +1018,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(); /* 'b' stands for 'buffer' parameter', special for 'my_snprintf' */ @@ -1141,11 +1037,13 @@ 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 */ + 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); @@ -1172,10 +1070,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. */ @@ -1205,7 +1104,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)) @@ -1319,7 +1218,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)) @@ -1491,16 +1390,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); @@ -1545,8 +1450,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 && @@ -1848,16 +1752,6 @@ bool sp_process_definer(THD *thd) /** Execute command saved in thd and lex->sql_command. - 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. - - 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. - @param thd Thread handle @todo @@ -1891,7 +1785,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; @@ -2083,17 +1976,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"); @@ -2168,10 +2050,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; } @@ -2430,20 +2308,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 { @@ -2916,7 +2780,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()")); } @@ -2942,6 +2810,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: @@ -3228,9 +3105,6 @@ 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; @@ -3515,6 +3389,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); @@ -3523,16 +3401,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++)) @@ -3547,20 +3430,23 @@ end_with_restore_list: user->host.str); // 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) @@ -3595,16 +3481,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) @@ -3631,8 +3520,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; @@ -3661,12 +3549,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; @@ -3871,13 +3769,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. @@ -3904,8 +3811,8 @@ end_with_restore_list: if (sp_grant_privileges(thd, lex->sphead->m_db.str, name, lex->sql_command == SQLCOM_CREATE_PROCEDURE)) push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, - ER_PROC_AUTO_GRANT_FAIL, - ER(ER_PROC_AUTO_GRANT_FAIL)); + ER_PROC_AUTO_GRANT_FAIL, ER(ER_PROC_AUTO_GRANT_FAIL)); + thd->clear_error(); } /* @@ -4125,49 +4032,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: @@ -4442,14 +4348,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()); @@ -4485,6 +4383,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. */ @@ -4510,6 +4413,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()); } @@ -4799,12 +4706,19 @@ check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv, { // We can never grant this DBUG_PRINT("error",("No possible access")); if (!no_errors) - my_error(ER_ACCESS_DENIED_ERROR, MYF(0), - sctx->priv_user, - sctx->priv_host, - (thd->password ? - ER(ER_YES) : - ER(ER_NO))); /* purecov: tested */ + { + if (thd->password == 2) + my_error(ER_ACCESS_DENIED_NO_PASSWORD_ERROR, MYF(0), + sctx->priv_user, + sctx->priv_host); + else + my_error(ER_ACCESS_DENIED_ERROR, MYF(0), + sctx->priv_user, + sctx->priv_host, + (thd->password ? + ER(ER_YES) : + ER(ER_NO))); /* purecov: tested */ + } DBUG_RETURN(TRUE); /* purecov: tested */ } @@ -5214,10 +5128,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 @@ -5394,13 +5315,6 @@ mysql_new_select(LEX *lex, bool move_down) 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; @@ -5576,7 +5490,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) { @@ -5587,7 +5502,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); @@ -5965,7 +5880,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); } @@ -6964,10 +6880,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; @@ -7042,8 +6964,9 @@ void get_default_definer(THD *thd, LEX_USER *definer) definer->host.str= (char *) sctx->priv_host; definer->host.length= strlen(definer->host.str); - definer->password.str= NULL; - definer->password.length= 0; + definer->password= null_lex_str; + definer->plugin= empty_lex_str; + definer->auth= empty_lex_str; } diff --git a/sql/sql_parse.h b/sql/sql_parse.h index ad620544d29..c9b0f981d19 100644 --- a/sql/sql_parse.h +++ b/sql/sql_parse.h @@ -153,7 +153,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, @@ -176,8 +175,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; } diff --git a/sql/sql_partition.cc b/sql/sql_partition.cc index b72816f8ce3..cec047d11fc 100644 --- a/sql/sql_partition.cc +++ b/sql/sql_partition.cc @@ -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. @@ -1762,8 +1763,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; } } @@ -1790,10 +1790,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; } @@ -1839,18 +1838,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; } @@ -1994,7 +1997,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; @@ -2013,8 +2016,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; @@ -4353,43 +4355,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), @@ -4511,29 +4501,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 @@ -4545,8 +4531,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 */ @@ -4555,15 +4545,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); @@ -4576,7 +4560,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; @@ -4584,11 +4568,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; @@ -4596,9 +4601,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) { @@ -4607,7 +4612,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) @@ -4629,15 +4635,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)) { @@ -4648,12 +4654,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 @@ -4684,7 +4690,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 && @@ -4698,12 +4704,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) @@ -4726,17 +4732,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()) { @@ -4745,7 +4751,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; @@ -4753,15 +4759,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: @@ -4825,7 +4831,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; @@ -4930,12 +4936,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; @@ -4976,12 +4982,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 { @@ -4999,12 +5005,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; } @@ -5017,12 +5023,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) @@ -5033,17 +5039,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: @@ -5082,7 +5088,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; @@ -5108,14 +5114,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(); @@ -5150,38 +5156,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: @@ -5240,13 +5246,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) { @@ -5266,7 +5272,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); @@ -5277,7 +5283,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(); @@ -5291,7 +5297,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; } @@ -5312,9 +5318,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 @@ -5346,7 +5352,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; } } } @@ -5463,7 +5469,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; } } /* @@ -5484,7 +5490,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) { @@ -5494,6 +5500,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); } @@ -5536,6 +5553,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))) @@ -5544,7 +5566,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)); } @@ -6294,8 +6319,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"); @@ -6307,62 +6342,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) @@ -6379,7 +6392,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 && @@ -6392,7 +6405,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) { @@ -6457,7 +6470,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 @@ -6500,25 +6513,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. */ @@ -6529,19 +6541,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; @@ -6550,7 +6563,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; @@ -6559,12 +6573,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 @@ -6681,11 +6695,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) && @@ -6706,7 +6720,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; } @@ -6761,7 +6775,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) && @@ -6770,11 +6784,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) || @@ -6782,7 +6797,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; } @@ -6831,10 +6846,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. @@ -6858,27 +6873,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) || @@ -6886,7 +6902,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; } @@ -6896,12 +6912,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 @@ -7455,8 +7484,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"); @@ -7499,8 +7528,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 fee33303a04..cadfc587c1c 100644 --- a/sql/sql_partition_admin.cc +++ b/sql/sql_partition_admin.cc @@ -16,10 +16,12 @@ #include "sql_parse.h" // check_one_table_access #include "sql_table.h" // mysql_alter_table, etc. #include "sql_lex.h" // Sql_statement -#include "sql_truncate.h" // mysql_truncate_table, - // Truncate_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 @@ -46,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); } @@ -104,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_plugin.cc b/sql/sql_plugin.cc index f48a3183289..dc5b7b5a37b 100644 --- a/sql/sql_plugin.cc +++ b/sql/sql_plugin.cc @@ -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 #define REPORT_TO_LOG 1 #define REPORT_TO_USER 2 @@ -41,9 +42,8 @@ extern struct st_mysql_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 }; @@ -65,6 +65,7 @@ const LEX_STRING plugin_type_names[MYSQL_MAX_PLUGIN_TYPE_NUM]= { C_STRING_WITH_LEN("INFORMATION SCHEMA") }, { C_STRING_WITH_LEN("AUDIT") }, { C_STRING_WITH_LEN("REPLICATION") }, + { C_STRING_WITH_LEN("AUTHENTICATION") } }; extern int initialize_schema_table(st_plugin_int *plugin); @@ -81,13 +82,13 @@ extern int finalize_audit_plugin(st_plugin_int *plugin); plugin_type_init plugin_type_initialize[MYSQL_MAX_PLUGIN_TYPE_NUM]= { 0,ha_initialize_handlerton,0,0,initialize_schema_table, - initialize_audit_plugin + initialize_audit_plugin,0,0 }; plugin_type_init plugin_type_deinitialize[MYSQL_MAX_PLUGIN_TYPE_NUM]= { 0,ha_finalize_handlerton,0,0,finalize_schema_table, - finalize_audit_plugin + finalize_audit_plugin,0,0 }; #ifdef HAVE_DLOPEN @@ -110,7 +111,8 @@ static int min_plugin_info_interface_version[MYSQL_MAX_PLUGIN_TYPE_NUM]= MYSQL_DAEMON_INTERFACE_VERSION, MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION, MYSQL_AUDIT_INTERFACE_VERSION, - MYSQL_REPLICATION_INTERFACE_VERSION + MYSQL_REPLICATION_INTERFACE_VERSION, + MYSQL_AUTHENTICATION_INTERFACE_VERSION }; static int cur_plugin_info_interface_version[MYSQL_MAX_PLUGIN_TYPE_NUM]= { @@ -120,7 +122,8 @@ static int cur_plugin_info_interface_version[MYSQL_MAX_PLUGIN_TYPE_NUM]= MYSQL_DAEMON_INTERFACE_VERSION, MYSQL_INFORMATION_SCHEMA_INTERFACE_VERSION, MYSQL_AUDIT_INTERFACE_VERSION, - MYSQL_REPLICATION_INTERFACE_VERSION + MYSQL_REPLICATION_INTERFACE_VERSION, + MYSQL_AUTHENTICATION_INTERFACE_VERSION }; /* support for Services */ @@ -277,6 +280,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 ****************************************************************************/ @@ -405,13 +428,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) @@ -796,6 +821,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; @@ -1237,7 +1263,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, @@ -1256,7 +1282,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)) @@ -1334,7 +1360,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); @@ -1733,7 +1760,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); @@ -1844,6 +1875,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) @@ -3054,7 +3090,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; @@ -3314,7 +3351,7 @@ 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; @@ -3335,7 +3372,7 @@ static int test_plugin_options(MEM_ROOT *tmp_root, struct st_plugin_int *tmp, */ if (!(my_strcasecmp(&my_charset_latin1, tmp->name.str, "federated") && my_strcasecmp(&my_charset_latin1, tmp->name.str, "ndbcluster"))) - plugin_load_policy= PLUGIN_OFF; + plugin_load_option= PLUGIN_OFF; for (opt= tmp->plugin->system_vars; opt && *opt; opt++) count+= 2; /* --{plugin}-{optname} and --plugin-{plugin}-{optname} */ @@ -3359,8 +3396,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 */ @@ -3375,12 +3413,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 079dc4e6dca..1b7838ea085 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> @@ -95,7 +100,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 */ }; @@ -110,6 +115,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; @@ -118,6 +124,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 @@ -148,6 +155,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 366c46d9c92..64f252d11d3 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, 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 @@ -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); @@ -1780,7 +1780,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: @@ -2292,19 +2292,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. @@ -2420,11 +2407,15 @@ void reinit_stmt_before_use(THD *thd, LEX *lex) sl->where= sl->prep_where->copy_andor_structure(thd); sl->where->cleanup(); } + else + sl->where= NULL; if (sl->prep_having) { sl->having= sl->prep_having->copy_andor_structure(thd); sl->having->cleanup(); } + else + sl->having= NULL; DBUG_ASSERT(sl->join == 0); ORDER *order; /* Fix GROUP list */ @@ -2894,8 +2885,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; } @@ -3168,7 +3166,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. @@ -3213,6 +3210,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() || @@ -3240,7 +3238,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 @@ -3273,7 +3271,7 @@ bool Prepared_statement::prepare(const char *packet, uint packet_len) if (error == 0) { setup_set_params(); - init_stmt_after_parse(lex); + lex->context_analysis_only&= ~CONTEXT_ANALYSIS_ONLY_PREPARE; state= Query_arena::PREPARED; flags&= ~ (uint) IS_IN_USE; @@ -3731,7 +3729,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 @@ -3761,7 +3759,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); diff --git a/sql/sql_priv.h b/sql/sql_priv.h index f0f6a1969f5..434dfb1e306 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 @@ -176,17 +182,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 bf38af78536..0810459cb49 100644 --- a/sql/sql_reload.cc +++ b/sql/sql_reload.cc @@ -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); @@ -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 } @@ -274,7 +282,8 @@ bool reload_acl_and_cache(THD *thd, unsigned long options, #endif if (options & REFRESH_USER_RESOURCES) reset_mqh((LEX_USER *) NULL, 0); /* purecov: inspected */ - *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. */ @@ -328,7 +337,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. ------------------------------------ @@ -338,6 +346,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 @@ -354,7 +369,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 @@ -368,17 +382,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"); @@ -390,21 +400,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 7bca41f1265..4e8b70c58f6 100644 --- a/sql/sql_repl.cc +++ b/sql/sql_repl.cc @@ -1925,7 +1925,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_select.cc b/sql/sql_select.cc index bded06b2924..fc25e8ee0fa 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.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 @@ -47,6 +47,7 @@ #include "records.h" // init_read_record, end_read_record #include "filesort.h" // filesort_free_buffers #include "sql_union.h" // mysql_union +#include "debug_sync.h" // DEBUG_SYNC #include <m_ctype.h> #include <my_bit.h> #include <hash.h> @@ -566,7 +567,8 @@ JOIN::prepare(Item ***rref_pointer_array, thd->lex->allow_sum_func= save_allow_sum_func; } - if (!thd->lex->view_prepare_mode && !(select_options & SELECT_DESCRIBE)) + if (!(thd->lex->context_analysis_only & CONTEXT_ANALYSIS_ONLY_VIEW) && + !(select_options & SELECT_DESCRIBE)) { Item_subselect *subselect; /* Is it subselect? */ @@ -852,6 +854,7 @@ JOIN::optimize() if (optimized) DBUG_RETURN(0); optimized= 1; + DEBUG_SYNC(thd, "before_join_optimize"); thd_proc_info(thd, "optimizing"); row_limit= ((select_distinct || order || group_list) ? HA_POS_ERROR : @@ -1754,6 +1757,9 @@ JOIN::reinit() func->clear(); } + if (!(select_options & SELECT_DESCRIBE)) + init_ftfuncs(thd, select_lex, test(order)); + DBUG_RETURN(0); } @@ -2411,13 +2417,8 @@ JOIN::destroy() cleanup(1); /* Cleanup items referencing temporary table columns */ - if (!tmp_all_fields3.is_empty()) - { - List_iterator_fast<Item> it(tmp_all_fields3); - Item *item; - while ((item= it++)) - item->cleanup(); - } + cleanup_item_list(tmp_all_fields1); + cleanup_item_list(tmp_all_fields3); if (exec_tmp_table1) free_tmp_table(thd, exec_tmp_table1); if (exec_tmp_table2) @@ -2428,6 +2429,19 @@ JOIN::destroy() DBUG_RETURN(error); } + +void JOIN::cleanup_item_list(List<Item> &items) const +{ + if (!items.is_empty()) + { + List_iterator_fast<Item> it(items); + Item *item; + while ((item= it++)) + item->cleanup(); + } +} + + /** An entry point to single-unit select (a select without UNION). @@ -2503,6 +2517,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 { @@ -4040,8 +4061,12 @@ update_ref_and_keys(THD *thd, DYNAMIC_ARRAY *keyuse,JOIN_TAB *join_tab, continue; } -#ifdef HAVE_purify - /* 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; @@ -6474,10 +6499,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(); @@ -9017,10 +9044,10 @@ simplify_joins(JOIN *join, List<TABLE_LIST> *join_list, COND *conds, bool top) /* Flatten nested joins that can be flattened. */ TABLE_LIST *right_neighbor= NULL; - bool fix_name_res= FALSE; li.rewind(); while ((table= li++)) { + bool fix_name_res= FALSE; nested_join= table->nested_join; if (nested_join && !table->on_expr) { @@ -10693,6 +10720,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; @@ -13421,6 +13449,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 || @@ -13434,7 +13464,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; } @@ -13830,7 +13860,7 @@ check_reverse_order: 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 @@ -13840,8 +13870,8 @@ check_reverse_order: 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 @@ -15210,6 +15240,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 { /* @@ -15822,7 +15854,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 77fff4ee24c..bdb9d1a315c 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 @@ -583,6 +583,7 @@ private: */ bool implicit_grouping; bool make_simple_join(JOIN *join, TABLE *tmp_table); + void cleanup_item_list(List<Item> &items) const; }; diff --git a/sql/sql_show.cc b/sql/sql_show.cc index 6b24e3db7bc..9bf24bb88f9 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, 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 @@ -29,6 +29,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 @@ -98,11 +100,13 @@ static TYPELIB grant_types = { sizeof(grant_names)/sizeof(char **), 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); @@ -211,6 +215,11 @@ static my_bool show_plugins(THD *thd, plugin_ref plugin, } table->field[9]->set_notnull(); + table->field[10]->store( + global_plugin_typelib_names[plugin_load_option(plugin)], + strlen(global_plugin_typelib_names[plugin_load_option(plugin)]), + cs); + return schema_table_store_record(thd, table); } @@ -473,12 +482,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 { @@ -595,11 +598,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. */ @@ -609,7 +612,7 @@ public: m_handling= TRUE; bool is_handled; - + switch (sql_errno) { case ER_TABLEACCESS_DENIED_ERROR: @@ -670,17 +673,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; @@ -1726,7 +1736,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 @@ -1823,12 +1833,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; @@ -1856,7 +1868,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 */ } @@ -2242,7 +2255,7 @@ static bool show_status_array(THD *thd, const char *wild, end= int10_to_str(*(long*) value, buff, 10); break; case SHOW_LONGLONG_STATUS: - value= ((char *) status_var + (ulonglong) value); + value= ((char *) status_var + (ulong) value); /* fall through */ case SHOW_LONGLONG: end= longlong10_to_str(*(longlong*) value, buff, 10); @@ -3185,7 +3198,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) { @@ -3431,7 +3444,7 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond) 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; + uint8 save_context_analysis_only= lex->context_analysis_only; Query_tables_list query_tables_list_backup; #ifndef NO_EMBEDDED_ACCESS_CHECKS Security_context *sctx= thd->security_ctx; @@ -3451,7 +3464,7 @@ int get_all_tables(THD *thd, TABLE_LIST *tables, COND *cond) */ can_deadlock= thd->mdl_context.has_locks(); - lex->view_prepare_mode= TRUE; + lex->context_analysis_only|= CONTEXT_ANALYSIS_ONLY_VIEW; lex->reset_n_backup_query_tables_list(&query_tables_list_backup); /* Restore Query_tables_list::sql_command value, which was reset @@ -3681,7 +3694,7 @@ err: 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; + lex->context_analysis_only= save_context_analysis_only; DBUG_RETURN(error); } @@ -3777,6 +3790,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"); @@ -3784,22 +3798,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); @@ -3814,6 +3827,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) @@ -3827,6 +3841,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) @@ -3835,62 +3852,83 @@ 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); ptr=option_buff; + if (share->min_rows) { ptr=strmov(ptr," min_rows="); ptr=longlong10_to_str(share->min_rows,ptr,10); } + if (share->max_rows) { ptr=strmov(ptr," max_rows="); ptr=longlong10_to_str(share->max_rows,ptr,10); } + if (share->avg_row_length) { ptr=strmov(ptr," avg_row_length="); ptr=longlong10_to_str(share->avg_row_length,ptr,10); } + if (share->db_create_options & HA_OPTION_PACK_KEYS) ptr=strmov(ptr," pack_keys=1"); + if (share->db_create_options & HA_OPTION_NO_PACK_KEYS) ptr=strmov(ptr," pack_keys=0"); + /* We use CHECKSUM, instead of TABLE_CHECKSUM, for backward compability */ if (share->db_create_options & HA_OPTION_CHECKSUM) ptr=strmov(ptr," checksum=1"); + if (share->db_create_options & HA_OPTION_DELAY_KEY_WRITE) ptr=strmov(ptr," delay_key_write=1"); + if (share->row_type != ROW_TYPE_DEFAULT) ptr=strxmov(ptr, " row_format=", ha_row_type[(uint) share->row_type], NullS); + if (share->key_block_size) { ptr= strmov(ptr, " KEY_BLOCK_SIZE="); ptr= longlong10_to_str(share->key_block_size, ptr, 10); } + #ifdef WITH_PARTITION_STORAGE_ENGINE if (is_partitioned) ptr= strmov(ptr, " partitioned"); #endif + table->field[19]->store(option_buff+1, (ptr == option_buff ? 0 : (uint) (ptr-option_buff)-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: @@ -3919,7 +3957,9 @@ static int get_schema_tables_record(THD *thd, TABLE_LIST *tables, tmp_buff= "Paged"; break; } + table->field[6]->store(tmp_buff, strlen(tmp_buff), cs); + if (!tables->schema_table) { table->field[7]->store((longlong) file->stats.records, TRUE); @@ -3968,6 +4008,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)); } @@ -4929,18 +4989,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); @@ -5063,8 +5134,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); } @@ -5263,8 +5334,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); @@ -6053,8 +6124,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); @@ -7214,6 +7285,7 @@ ST_FIELD_INFO plugin_fields_info[]= {"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}, + {"LOAD_OPTION", 64, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE}, {0, 0, MYSQL_TYPE_STRING, 0, 0, 0, SKIP_OPEN_TABLE} }; @@ -7732,7 +7804,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. @@ -7833,6 +7905,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 @@ -7924,3 +7997,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.h b/sql/sql_string.h index 0ce67108423..3642a96de35 100644 --- a/sql/sql_string.h +++ b/sql/sql_string.h @@ -91,9 +91,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(); } @@ -104,7 +108,7 @@ public: inline uint32 alloced_length() const { return Alloced_length;} inline char& operator [] (uint32 i) const { return Ptr[i]; } inline void length(uint32 len) { str_length=len ; } - inline bool is_empty() { return (str_length == 0); } + inline bool is_empty() const { return (str_length == 0); } inline void mark_as_const() { Alloced_length= 0;} inline const char *ptr() const { return Ptr; } inline char *c_ptr() @@ -265,8 +269,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 72fb4ea930b..772496a10d5 100644 --- a/sql/sql_table.cc +++ b/sql/sql_table.cc @@ -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 @@ -1725,8 +1723,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, @@ -1853,64 +1849,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->open_tables, 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; @@ -1924,7 +1973,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 @@ -1978,71 +2027,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; @@ -2055,6 +2039,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. @@ -2129,6 +2123,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; @@ -2171,8 +2169,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 || @@ -2259,7 +2257,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; @@ -3817,6 +3815,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 @@ -4225,9 +4263,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; @@ -4238,6 +4281,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: @@ -5589,7 +5655,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; @@ -5600,7 +5665,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; @@ -5751,7 +5816,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. @@ -5769,7 +5834,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. @@ -5914,7 +5978,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, @@ -5955,10 +6020,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); } @@ -5969,7 +6031,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 /* @@ -6202,12 +6266,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 @@ -6302,8 +6366,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; @@ -6551,7 +6615,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name, (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, + Table_triggers_list::change_table_name(thd, db, alias, table_name, new_db, new_alias))) { /* Try to get everything back. */ @@ -6643,7 +6707,7 @@ bool mysql_alter_table(THD *thd,char *new_db, char *new_name, char path[FN_REFLEN]; TABLE *t_table; build_table_filename(path + 1, sizeof(path) - 1, new_db, table_name, "", 0); - t_table= open_temporary_table(thd, path, new_db, tmp_name, 0); + t_table= open_table_uncached(thd, path, new_db, tmp_name, FALSE); if (t_table) { intern_close_table(t_table); @@ -6661,10 +6725,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); } @@ -6687,6 +6748,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 @@ -6720,8 +6786,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); @@ -6733,9 +6797,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 eb0b1aa94dd..aa5738fd4c9 100644 --- a/sql/sql_table.h +++ b/sql/sql_table.h @@ -174,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 f0f9011f61f..c2e3cd9944a 100644 --- a/sql/sql_trigger.cc +++ b/sql/sql_trigger.cc @@ -24,8 +24,6 @@ #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 @@ -391,15 +389,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 +447,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; @@ -547,9 +536,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); @@ -1874,6 +1860,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 @@ -1890,6 +1877,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) @@ -1911,7 +1899,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)) { @@ -1920,7 +1908,7 @@ 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) }; + 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 diff --git a/sql/sql_trigger.h b/sql/sql_trigger.h index 28bf0a60877..dd954957f07 100644 --- a/sql/sql_trigger.h +++ b/sql/sql_trigger.h @@ -157,6 +157,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); diff --git a/sql/sql_truncate.cc b/sql/sql_truncate.cc index a61abdafe3e..909c6a08b67 100644 --- a/sql/sql_truncate.cc +++ b/sql/sql_truncate.cc @@ -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() @@ -268,103 +331,45 @@ static bool open_and_lock_table_for_truncate(THD *thd, TABLE_LIST *table_ref, 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); @@ -385,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. */ @@ -413,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); } /* @@ -434,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) @@ -454,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); } @@ -471,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 ba1d0ceadeb..94e2fe43f03 100644 --- a/sql/sql_udf.cc +++ b/sql/sql_udf.cc @@ -199,10 +199,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)) { @@ -442,13 +439,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 acc0f704c44..1c0c48c0fec 100644 --- a/sql/sql_union.cc +++ b/sql/sql_union.cc @@ -176,7 +176,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); @@ -278,14 +277,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; @@ -443,6 +434,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 68440f6623a..08d804efcb6 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->blob_fields + table->s->varchar_fields == 0) + // 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,10 +296,16 @@ 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; @@ -579,15 +641,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) { thd->examined_row_count++; @@ -605,7 +658,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) @@ -979,9 +1032,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); /* @@ -1139,7 +1200,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); } @@ -1645,18 +1710,8 @@ bool multi_update::send_data(List<Item> ¬_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], @@ -1671,7 +1726,7 @@ bool multi_update::send_data(List<Item> ¬_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)) != @@ -1860,7 +1915,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; @@ -1897,11 +1951,6 @@ int multi_update::do_updates() if ((local_error = tmp_table->file->ha_rnd_init(1))) 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) @@ -1942,7 +1991,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)) != @@ -2033,7 +2082,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 5fdf7b8d850..f569c679776 100644 --- a/sql/sql_view.cc +++ b/sql/sql_view.cc @@ -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; diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy index 83e9078f5cb..9aa938437b1 100644 --- a/sql/sql_yacc.yy +++ b/sql/sql_yacc.yy @@ -1189,6 +1189,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 @@ -1932,35 +1933,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; @@ -4814,7 +4808,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)) @@ -7391,7 +7385,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 { @@ -10447,7 +10440,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; } @@ -10457,7 +10453,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; } ; @@ -10763,7 +10762,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 { @@ -11278,7 +11277,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. */ + } } ; @@ -12306,6 +12309,9 @@ user: $$->user = $1; $$->host.str= (char *) "%"; $$->host.length= 1; + $$->password= null_lex_str; + $$->plugin= empty_lex_str; + $$->auth= empty_lex_str; if (check_string_char_length(&$$->user, ER(ER_USERNAME), USERNAME_CHAR_LENGTH, @@ -12318,12 +12324,21 @@ user: if (!($$=(LEX_USER*) thd->alloc(sizeof(st_lex_user)))) MYSQL_YYABORT; $$->user = $1; $$->host=$3; + $$->password= null_lex_str; + $$->plugin= empty_lex_str; + $$->auth= empty_lex_str; if (check_string_char_length(&$$->user, ER(ER_USERNAME), USERNAME_CHAR_LENGTH, 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 { @@ -12481,6 +12496,7 @@ keyword_sp: | FILE_SYM {} | FIRST_SYM {} | FIXED_SYM {} + | GENERAL {} | GEOMETRY_SYM {} | GEOMETRYCOLLECTION {} | GET_FORMAT {} @@ -12490,6 +12506,7 @@ keyword_sp: | HOSTS_SYM {} | HOUR_SYM {} | IDENTIFIED_SYM {} + | IGNORE_SERVER_IDS_SYM {} | INVOKER_SYM {} | IMPORT {} | INDEXES {} @@ -12512,6 +12529,7 @@ keyword_sp: | LOGS_SYM {} | MAX_ROWS {} | MASTER_SYM {} + | MASTER_HEARTBEAT_PERIOD_SYM {} | MASTER_HOST_SYM {} | MASTER_PORT_SYM {} | MASTER_LOG_FILE_SYM {} @@ -12580,6 +12598,7 @@ keyword_sp: | PROCESSLIST_SYM {} | PROFILE_SYM {} | PROFILES_SYM {} + | PROXY_SYM {} | QUARTER_SYM {} | QUERY_SYM {} | QUICK {} @@ -12616,6 +12635,7 @@ keyword_sp: | SIMPLE_SYM {} | SHARE_SYM {} | SHUTDOWN {} + | SLOW {} | SNAPSHOT_SYM {} | SOUNDS_SYM {} | SOURCE_SYM {} @@ -12966,7 +12986,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; @@ -13161,9 +13181,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; } ; @@ -13241,6 +13258,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; + } } ; @@ -13319,6 +13343,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: @@ -13358,6 +13389,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: @@ -13551,6 +13589,8 @@ 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) @@ -13576,7 +13616,28 @@ grant_user: } } | user IDENTIFIED_SYM BY PASSWORD TEXT_STRING - { $$= $1; $1->password= $5; } + { + if (Lex->sql_command == SQLCOM_REVOKE) + MYSQL_YYABORT; + $$= $1; + $1->password= $5; + } + | user IDENTIFIED_SYM WITH ident_or_text + { + if (Lex->sql_command == SQLCOM_REVOKE) + MYSQL_YYABORT; + $$= $1; + $1->plugin= $4; + $1->auth= empty_lex_str; + } + | user IDENTIFIED_SYM WITH ident_or_text AS TEXT_STRING_sys + { + if (Lex->sql_command == SQLCOM_REVOKE) + MYSQL_YYABORT; + $$= $1; + $1->plugin= $4; + $1->auth= $6; + } | user { $$= $1; $1->password= null_lex_str; } ; @@ -13648,6 +13709,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 {} diff --git a/sql/structs.h b/sql/structs.h index 5ffcc4dc62e..8290227830c 100644 --- a/sql/structs.h +++ b/sql/structs.h @@ -156,7 +156,7 @@ extern const char *show_comp_option_name[]; typedef int *(*update_var)(THD *, struct st_mysql_show_var *); typedef struct st_lex_user { - LEX_STRING user, host, password; + LEX_STRING user, host, password, plugin, auth; } LEX_USER; /* diff --git a/sql/sys_vars.cc b/sql/sys_vars.cc index ca3447dcc82..68bb77d467f 100644 --- a/sql/sys_vars.cc +++ b/sql/sys_vars.cc @@ -236,14 +236,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() @@ -1031,13 +1040,20 @@ static Sys_var_ulong Sys_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); @@ -1419,6 +1435,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 " @@ -1428,7 +1452,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 */ @@ -1512,6 +1535,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 " @@ -2006,15 +2039,6 @@ static Sys_var_ulong Sys_thread_cache_size( GLOBAL_VAR(thread_cache_size), CMD_LINE(REQUIRED_ARG), VALID_RANGE(0, 16384), DEFAULT(0), BLOCK_SIZE(1)); -#if HAVE_POOL_OF_THREADS == 1 -static Sys_var_ulong Sys_thread_pool_size( - "thread_pool_size", - "How many threads we should create to handle query requests in " - "case of 'thread_handling=pool-of-threads'", - GLOBAL_VAR(thread_pool_size), CMD_LINE(REQUIRED_ARG), - VALID_RANGE(1, 16384), DEFAULT(20), BLOCK_SIZE(0)); -#endif - /** Can't change the 'next' tx_isolation if we are already in a transaction. @@ -2935,11 +2959,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; } diff --git a/sql/sys_vars.h b/sql/sys_vars.h index 740c4f03e3e..c9987ed4674 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. @@ -1132,7 +1191,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; @@ -1497,7 +1557,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 030de6719c7..8cd2e9e9bab 100644 --- a/sql/table.cc +++ b/sql/table.cc @@ -426,6 +426,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. @@ -1704,11 +1716,17 @@ static int open_binary_frm(THD *thd, TABLE_SHARE *share, uchar *head, 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); @@ -3085,30 +3103,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); @@ -3123,12 +3118,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++)) { @@ -3151,16 +3142,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; } @@ -3256,6 +3241,65 @@ 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->ft_handler= 0; + 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); + + /* 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. @@ -4047,11 +4091,8 @@ bool TABLE_LIST::prepare_view_securety_context(THD *thd) { DBUG_PRINT("info", ("This table is suid view => load contest")); DBUG_ASSERT(view && view_sctx); - if (acl_getroot_no_password(view_sctx, - definer.user.str, - definer.host.str, - definer.host.str, - thd->db)) + if (acl_getroot(view_sctx, definer.user.str, definer.host.str, + definer.host.str, thd->db)) { if ((thd->lex->sql_command == SQLCOM_SHOW_CREATE) || (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) @@ -4070,10 +4111,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); } @@ -5173,7 +5219,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 45b9aa3e699..39e9ef2e0dd 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 -}; - - /*************************************************************************/ /** @@ -1096,6 +1084,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); @@ -1181,7 +1170,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; @@ -1393,7 +1384,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..b331fea89fe 100644 --- a/sql/transaction.cc +++ b/sql/transaction.cc @@ -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) @@ -391,15 +392,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); } @@ -565,7 +566,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 +598,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); } @@ -643,17 +646,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 diff --git a/sql/tztime.cc b/sql/tztime.cc index 43d43123158..a2f319d4307 100644 --- a/sql/tztime.cc +++ b/sql/tztime.cc @@ -2300,7 +2300,7 @@ my_tz_find(THD *thd, const String *name) DBUG_PRINT("enter", ("time zone name='%s'", name ? ((String *)name)->c_ptr_safe() : "NULL")); - if (!name) + if (!name || name->is_empty()) DBUG_RETURN(0); mysql_mutex_lock(&tz_LOCK); |
