MySQL  8.0.16
Source Code Documentation
handler.cc File Reference

Implements functions in the handler interface that are shared between all storage engines. More...

#include "sql/handler.h"
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <atomic>
#include <boost/algorithm/string/case_conv.hpp>
#include <boost/foreach.hpp>
#include <boost/token_functions.hpp>
#include <boost/tokenizer.hpp>
#include <cmath>
#include <list>
#include <random>
#include <string>
#include <vector>
#include "binlog_event.h"
#include "keycache.h"
#include "m_ctype.h"
#include "m_string.h"
#include "my_bit.h"
#include "my_bitmap.h"
#include "my_check_opt.h"
#include "my_dbug.h"
#include "my_loglevel.h"
#include "my_macros.h"
#include "my_pointer_arithmetic.h"
#include "my_psi_config.h"
#include "my_sqlcommand.h"
#include "my_sys.h"
#include "myisam.h"
#include "mysql/components/services/log_builtins.h"
#include "mysql/components/services/log_shared.h"
#include "mysql/plugin.h"
#include "mysql/psi/mysql_file.h"
#include "mysql/psi/mysql_mutex.h"
#include "mysql/psi/mysql_table.h"
#include "mysql/psi/mysql_transaction.h"
#include "mysql/psi/psi_base.h"
#include "mysql/psi/psi_table.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql_com.h"
#include "mysql_version.h"
#include "mysqld_error.h"
#include "prealloced_array.h"
#include "sql/auth/auth_common.h"
#include "sql/binlog.h"
#include "sql/check_stack.h"
#include "sql/current_thd.h"
#include "sql/dd/cache/dictionary_client.h"
#include "sql/dd/dd.h"
#include "sql/dd/dictionary.h"
#include "sql/dd/types/table.h"
#include "sql/dd_table_share.h"
#include "sql/debug_sync.h"
#include "sql/derror.h"
#include "sql/error_handler.h"
#include "sql/field.h"
#include "sql/item.h"
#include "sql/lock.h"
#include "sql/log.h"
#include "sql/log_event.h"
#include "sql/mdl.h"
#include "sql/mysqld.h"
#include "sql/opt_costconstantcache.h"
#include "sql/opt_costmodel.h"
#include "sql/opt_hints.h"
#include "sql/protocol.h"
#include "sql/psi_memory_key.h"
#include "sql/query_options.h"
#include "sql/record_buffer.h"
#include "sql/rpl_filter.h"
#include "sql/rpl_gtid.h"
#include "sql/rpl_handler.h"
#include "sql/rpl_rli.h"
#include "sql/rpl_write_set_handler.h"
#include "sql/sdi_utils.h"
#include "sql/session_tracker.h"
#include "sql/sql_base.h"
#include "sql/sql_bitmap.h"
#include "sql/sql_class.h"
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_parse.h"
#include "sql/sql_plugin.h"
#include "sql/sql_select.h"
#include "sql/sql_table.h"
#include "sql/system_variables.h"
#include "sql/table.h"
#include "sql/tc_log.h"
#include "sql/thr_malloc.h"
#include "sql/transaction.h"
#include "sql/transaction_info.h"
#include "sql/xa.h"
#include "sql_string.h"
#include "template_utils.h"
#include "varlen_sort.h"

Classes

struct  st_sys_tbl_chk_params
 Structure used by SE during check for system table. More...
 
class  Ha_delete_table_error_handler
 
struct  st_discover_args
 Try to discover one table from handler(s). More...
 
struct  st_find_files_args
 Call this function in order to give the handler the possiblity to ask engine if there are any new tables that should be written to disk or any dropped tables that need to be removed from disk. More...
 
struct  st_table_exists_in_engine_args
 Ask handler if the table exists in engine. More...
 
struct  st_make_pushed_join_args
 Prepare (sub-) sequences of joins in this statement which may be pushed to each storage engine for execution. More...
 
struct  hton_list_st
 
struct  binlog_func_st
 
struct  binlog_log_query_st
 
struct  blob_len_ptr
 This structure is a helper structure for passing the length and pointer of blob space allocated by storage engine. More...
 
struct  HTON_NOTIFY_PARAMS
 Auxiliary structure for passing information to notify_*_helper() functions. More...
 

Macros

#define MYSQL_TABLE_IO_WAIT(OP, INDEX, RESULT, PAYLOAD)
 Instrumentation helper for table io_waits. More...
 
#define MYSQL_TABLE_LOCK_WAIT(OP, FLAGS, PAYLOAD)
 Instrumentation helper for table io_waits. More...
 
#define SETMSG(nr, msg)   handler_errmsgs[(nr)-HA_ERR_FIRST] = (msg)
 
#define AUTO_INC_DEFAULT_NB_ROWS   1
 Update the auto_increment field if necessary. More...
 
#define AUTO_INC_DEFAULT_NB_MAX_BITS   16
 
#define AUTO_INC_DEFAULT_NB_MAX   ((1 << AUTO_INC_DEFAULT_NB_MAX_BITS) - 1)
 
#define MAX_HTON_LIST_ST   63
 

Functions

st_plugin_inthton2plugin (uint slot)
 Maps from slot to plugin. May return NULL if plugin has been unloaded. More...
 
size_t num_hton2plugins ()
 Returns the size of the array holding pointers to plugins. More...
 
st_plugin_intinsert_hton2plugin (uint slot, st_plugin_int *plugin)
 For unit testing. More...
 
st_plugin_intremove_hton2plugin (uint slot)
 
const char * ha_resolve_storage_engine_name (const handlerton *db_type)
 
static bool check_engine_system_table_handlerton (THD *, plugin_ref plugin, void *arg)
 Called for each SE to check if given db, tablename is a system table. More...
 
static int ha_discover (THD *thd, const char *db, const char *name, uchar **frmblob, size_t *frmlen)
 
static plugin_ref ha_default_plugin (THD *thd)
 
handlertonha_default_handlerton (THD *thd)
 Return the default storage engine handlerton used for non-temp tables for thread. More...
 
static plugin_ref ha_default_temp_plugin (THD *thd)
 
handlertonha_default_temp_handlerton (THD *thd)
 Return the default storage engine handlerton used for explicitly created temp tables for a thread. More...
 
plugin_ref ha_resolve_by_name_raw (THD *thd, const LEX_CSTRING &name)
 Resolve handlerton plugin by name, without checking for "DEFAULT" or HTON_NOT_USER_SELECTABLE. More...
 
plugin_ref ha_resolve_by_name (THD *thd, const LEX_STRING *name, bool is_temp_table)
 Return the storage engine handlerton for the supplied name. More...
 
void ha_set_normalized_disabled_se_str (const std::string &disabled_se)
 
bool ha_is_storage_engine_disabled (handlerton *se_handle)
 
plugin_ref ha_lock_engine (THD *thd, const handlerton *hton)
 
handlertonha_resolve_by_legacy_type (THD *thd, enum legacy_db_type db_type)
 
handlertonha_checktype (THD *thd, enum legacy_db_type database_type, bool no_substitute, bool report_error)
 Use other database handler if databasehandler is not compiled in. More...
 
handlerget_new_handler (TABLE_SHARE *share, bool partitioned, MEM_ROOT *alloc, handlerton *db_type)
 Create handler object for the table in the storage engine. More...
 
static const char * get_handler_errmsg (int nr)
 
int ha_init_errors (void)
 Register handler error messages for use with my_error(). More...
 
int ha_finalize_handlerton (st_plugin_int *plugin)
 
int ha_initialize_handlerton (st_plugin_int *plugin)
 
int ha_init ()
 
void ha_end ()
 
static bool dropdb_handlerton (THD *, plugin_ref plugin, void *path)
 
void ha_drop_database (char *path)
 
static bool closecon_handlerton (THD *thd, plugin_ref plugin, void *)
 
void ha_close_connection (THD *thd)
 function to close a connection and thd, defined in sql/handler.cc More...
 
static bool kill_handlerton (THD *thd, plugin_ref plugin, void *)
 
void ha_kill_connection (THD *thd)
 
static bool pre_dd_shutdown_handlerton (THD *, plugin_ref plugin, void *)
 Invoke handlerton::pre_dd_shutdown() on a plugin. More...
 
void ha_pre_dd_shutdown (void)
 Invoke handlerton::pre_dd_shutdown() on every storage engine plugin. More...
 
void trans_register_ha (THD *thd, bool all, handlerton *ht_arg, const ulonglong *trxid)
 

Transaction handling in the server

More...
 
int ha_prepare (THD *thd)
 
static uint ha_check_and_coalesce_trx_read_only (THD *thd, Ha_trx_info *ha_list, bool all)
 Check if we can skip the two-phase commit. More...
 
int commit_owned_gtids (THD *thd, bool all, bool *need_clear_owned_gtid_ptr)
 The function computes condition to call gtid persistor wrapper, and executes it. More...
 
int commit_owned_gtid_by_partial_command (THD *thd)
 The function is a wrapper of commit_owned_gtids(...). More...
 
int ha_commit_trans (THD *thd, bool all, bool ignore_global_read_lock)
 
int ha_commit_low (THD *thd, bool all, bool run_after_commit)
 Commit the sessions outstanding transaction. More...
 
int ha_rollback_low (THD *thd, bool all)
 
int ha_rollback_trans (THD *thd, bool all)
 
int ha_commit_attachable (THD *thd)
 Commit the attachable transaction in storage engines. More...
 
bool ha_rollback_to_savepoint_can_release_mdl (THD *thd)
 Check if all storage engines used in transaction agree that after rollback to savepoint it is safe to release MDL locks acquired after savepoint creation. More...
 
int ha_rollback_to_savepoint (THD *thd, SAVEPOINT *sv)
 
int ha_prepare_low (THD *thd, bool all)
 
int ha_savepoint (THD *thd, SAVEPOINT *sv)
 
int ha_release_savepoint (THD *thd, SAVEPOINT *sv)
 
static bool snapshot_handlerton (THD *thd, plugin_ref plugin, void *arg)
 
int ha_start_consistent_snapshot (THD *thd)
 
static bool flush_handlerton (THD *, plugin_ref plugin, void *arg)
 
bool ha_flush_logs (bool binlog_group_flush)
 Flush the log(s) of storage engine(s). More...
 
const char * get_canonical_filename (handler *file, const char *path, char *tmp_path)
 make canonical filename More...
 
int ha_delete_table (THD *thd, handlerton *table_type, const char *path, const char *db, const char *alias, const dd::Table *table_def, bool generate_warning)
 Delete table from the storage engine. More...
 
ulonglong compute_next_insert_id (ulonglong nr, struct System_variables *variables)
 Generate the next auto-increment number based on increment and offset. More...
 
ulonglong prev_insert_id (ulonglong nr, struct System_variables *variables)
 Computes the largest number X: More...
 
const char * table_case_name (const HA_CREATE_INFO *info, const char *name)
 
void print_keydup_error (TABLE *table, KEY *key, const char *msg, myf errflag)
 Construct and emit duplicate key error message using information from table's record buffer. More...
 
void print_keydup_error (TABLE *table, KEY *key, myf errflag)
 Construct and emit duplicate key error message using information from table's record buffer. More...
 
int check_table_for_old_types (const TABLE *table, bool check_temporal_upgrade)
 Function identifies any old data type present in table. More...
 
int ha_enable_transaction (THD *thd, bool on)
 Tell the storage engine that it is allowed to "disable transaction" in the handler. More...
 
int ha_create_table (THD *thd, const char *path, const char *db, const char *table_name, HA_CREATE_INFO *create_info, bool update_create_info, bool is_temp_table, dd::Table *table_def)
 Initiates table-file and calls appropriate database-creator. More...
 
int ha_create_table_from_engine (THD *thd, const char *db, const char *name)
 Try to discover table from engine. More...
 
bool ha_check_if_table_exists (THD *thd, const char *db, const char *name, bool *exists)
 Try to find a table in a storage engine. More...
 
static bool check_if_system_table (const char *db, const char *table_name, bool *is_sql_layer_system_table)
 Check if a table specified by name is a system table. More...
 
bool ha_check_if_supported_system_table (handlerton *hton, const char *db, const char *table_name)
 Check if a given table is a system table. More...
 
static bool rm_tmp_tables_handlerton (THD *thd, plugin_ref plugin, void *files)
 
bool ha_rm_tmp_tables (THD *thd, List< LEX_STRING > *files)
 Ask all SEs to drop all temporary tables which have been left from previous server run. More...
 
bool default_rm_tmp_tables (handlerton *hton, THD *, List< LEX_STRING > *files)
 Default implementation for handlerton::rm_tmp_tables() method which simply removes all files from "files" list which have one of SE's extensions. More...
 
int ha_init_key_cache (const char *, KEY_CACHE *key_cache)
 Init a key cache if it has not been initied before. More...
 
int ha_resize_key_cache (KEY_CACHE *key_cache)
 Resize key cache. More...
 
int ha_change_key_cache (KEY_CACHE *old_key_cache, KEY_CACHE *new_key_cache)
 Move all tables from one key cache to another one. More...
 
static bool discover_handlerton (THD *thd, plugin_ref plugin, void *arg)
 
static bool find_files_handlerton (THD *thd, plugin_ref plugin, void *arg)
 
int ha_find_files (THD *thd, const char *db, const char *path, const char *wild, bool dir, List< LEX_STRING > *files)
 
static bool table_exists_in_engine_handlerton (THD *thd, plugin_ref plugin, void *arg)
 
int ha_table_exists_in_engine (THD *thd, const char *db, const char *name)
 
static bool make_pushed_join_handlerton (THD *thd, plugin_ref plugin, void *arg)
 
int ha_make_pushed_joins (THD *thd, const AQP::Join_plan *plan)
 
static bool binlog_func_list (THD *, plugin_ref plugin, void *arg)
 Listing handlertons first to avoid recursive calls and deadlock. More...
 
static bool binlog_func_foreach (THD *thd, binlog_func_st *bfn)
 
int ha_reset_logs (THD *thd)
 
void ha_reset_slave (THD *thd)
 
void ha_binlog_wait (THD *thd)
 
int ha_binlog_index_purge_file (THD *thd, const char *file)
 
static bool binlog_log_query_handlerton2 (THD *thd, handlerton *hton, void *args)
 
static bool binlog_log_query_handlerton (THD *thd, plugin_ref plugin, void *args)
 
void ha_binlog_log_query (THD *thd, handlerton *hton, enum_binlog_command binlog_command, const char *query, size_t query_length, const char *db, const char *table_name)
 
int ha_binlog_end (THD *thd)
 
static bool key_uses_partial_cols (TABLE *table, uint keyno)
 Check if key has partially-covered columns. More...
 
static void get_sort_and_sweep_cost (TABLE *table, ha_rows nrows, Cost_estimate *cost)
 
void get_sweep_read_cost (TABLE *table, ha_rows nrows, bool interrupted, Cost_estimate *cost)
 Get cost of reading nrows table records in a "disk sweep". More...
 
static bool key_has_vcol (const KEY_PART_INFO *part, uint length)
 Check if one of the columns in a key is a virtual generated column. More...
 
static void move_key_field_offsets (const key_range *range, const KEY_PART_INFO *key_part, my_ptrdiff_t diff)
 Change the offsets of all the fields in a key range. More...
 
uint calculate_key_len (TABLE *table, uint key, key_part_map keypart_map)
 Calculates length of key. More...
 
static bool exts_handlerton (THD *, plugin_ref plugin, void *arg)
 Returns a list of all known extensions. More...
 
TYPELIBha_known_exts ()
 
static bool stat_print (THD *thd, const char *type, size_t type_len, const char *file, size_t file_len, const char *status, size_t status_len)
 
static bool showstat_handlerton (THD *thd, plugin_ref plugin, void *arg)
 
bool ha_show_status (THD *thd, handlerton *db_type, enum ha_stat_type stat)
 
static bool check_table_binlog_row_based (THD *thd, TABLE *table)
 
static int write_locked_table_maps (THD *thd)
 Write table maps for all (manually or automatically) locked tables to the binary log. More...
 
int binlog_log_row (TABLE *table, const uchar *before_record, const uchar *after_record, Log_func *log_func)
 binlog a row operation More...
 
static void extract_blob_space_and_length_from_record_buff (const TABLE *table, const MY_BITMAP *const fields, blob_len_ptr *blob_len_ptr_array)
 Get the blob length and pointer of allocated space from the record buffer. More...
 
static void copy_blob_data (const TABLE *table, const MY_BITMAP *const fields, blob_len_ptr *blob_len_ptr_array)
 Copy the value of BLOB virtual generated columns into the space allocated by storage engine. More...
 
static bool my_eval_gcolumn_expr_helper (THD *thd, TABLE *table, const MY_BITMAP *const fields, uchar *record, bool in_purge)
 
static bool notify_exclusive_mdl_helper (THD *thd, plugin_ref plugin, void *arg)
 
bool ha_notify_exclusive_mdl (THD *thd, const MDL_key *mdl_key, ha_notification_type notification_type, bool *victimized)
 Notify/get permission from all interested storage engines before acquisition or after release of exclusive metadata lock on object represented by key. More...
 
static bool notify_alter_table_helper (THD *thd, plugin_ref plugin, void *arg)
 
bool ha_notify_alter_table (THD *thd, const MDL_key *mdl_key, ha_notification_type notification_type)
 Notify/get permission from all interested storage engines before or after executed ALTER TABLE on the table identified by key. More...
 
const char * ha_rkey_function_to_str (enum ha_rkey_function r)
 Generate a string representation of an ha_rkey_function enum value. More...
 
std::string table_definition (const char *table_name, const TABLE *mysql_table)
 Generate a human readable string that describes a table structure. More...
 
static std::string buf_to_raw (const uchar *buf, uint buf_size_bytes)
 Convert a binary buffer to a raw string, replacing non-printable characters with a dot. More...
 
static std::string buf_to_hex (const uchar *buf, uint buf_size_bytes)
 Convert a binary buffer to a hex string, replacing each character with its hex number. More...
 
std::string row_to_string (const uchar *mysql_row, TABLE *mysql_table)
 Generate a human readable string that describes the contents of a row. More...
 
std::string indexed_cells_to_string (const uchar *indexed_cells, uint indexed_cells_len, const KEY &mysql_index)
 Generate a human readable string that describes indexed cells that are given to handler::index_read() as input. More...
 
bool set_tx_isolation (THD *thd, enum_tx_isolation tx_isolation, bool one_shot)
 Set the transaction isolation level for the next transaction and update session tracker information about the transaction isolation level. More...
 
static bool post_recover_handlerton (THD *, plugin_ref plugin, void *)
 
void ha_post_recover (void)
 Perform SE-specific cleanup after recovery of transactions. More...
 
static bool is_reserved_db_name_handlerton (THD *, plugin_ref plugin, void *name)
 Checks if the database name is reserved word used by SE by invoking the handlerton method. More...
 
bool ha_check_reserved_db_name (const char *name)
 Check if the database name is reserved word used by SE. More...
 

Variables

static Prealloced_array< st_plugin_int *, PREALLOC_NUM_HAse_plugin_array (PSI_NOT_INSTRUMENTED)
 While we have legacy_db_type, we have this array to check for dups and to find handlerton from legacy_db_type. More...
 
static Prealloced_array< bool, PREALLOC_NUM_HAbuiltin_htons (PSI_NOT_INSTRUMENTED)
 Array allowing to check if handlerton is builtin without acquiring LOCK_plugin. More...
 
static handlertoninstalled_htons [128]
 
ulong total_ha_2pc = 0
 
ulong savepoint_alloc_size = 0
 
static const LEX_STRING sys_table_aliases []
 
const char * ha_row_type []
 
const char * tx_isolation_names []
 
TYPELIB tx_isolation_typelib
 
st_handler_tablename mysqld_system_tables []
 
std::string normalized_se_str = ""
 
static const char ** handler_errmsgs
 

Detailed Description

Implements functions in the handler interface that are shared between all storage engines.

Macro Definition Documentation

◆ AUTO_INC_DEFAULT_NB_MAX

#define AUTO_INC_DEFAULT_NB_MAX   ((1 << AUTO_INC_DEFAULT_NB_MAX_BITS) - 1)

◆ AUTO_INC_DEFAULT_NB_MAX_BITS

#define AUTO_INC_DEFAULT_NB_MAX_BITS   16

◆ AUTO_INC_DEFAULT_NB_ROWS

#define AUTO_INC_DEFAULT_NB_ROWS   1

Update the auto_increment field if necessary.

Updates columns with type NEXT_NUMBER if:

  • If column value is set to NULL (in which case auto_increment_field_not_null is 0)
  • If column is set to 0 and (sql_mode & MODE_NO_AUTO_VALUE_ON_ZERO) is not set. In the future we will only set NEXT_NUMBER fields if one sets them to NULL (or they are not included in the insert list).

    In those cases, we check if the currently reserved interval still has values we have not used. If yes, we pick the smallest one and use it. Otherwise:

  • If a list of intervals has been provided to the statement via SET INSERT_ID or via an Intvar_log_event (in a replication slave), we pick the first unused interval from this list, consider it as reserved.
  • Otherwise we set the column for the first row to the value next_insert_id(get_auto_increment(column))) which is usually max-used-column-value+1. We call get_auto_increment() for the first row in a multi-row statement. get_auto_increment() will tell us the interval of values it reserved for us.
  • In both cases, for the following rows we use those reserved values without calling the handler again (we just progress in the interval, computing each new value from the previous one). Until we have exhausted them, then we either take the next provided interval or call get_auto_increment() again to reserve a new interval.
  • In both cases, the reserved intervals are remembered in thd->auto_inc_intervals_in_cur_stmt_for_binlog if statement-based binlogging; the last reserved interval is remembered in auto_inc_interval_for_cur_row. The number of reserved intervals is remembered in auto_inc_intervals_count. It differs from the number of elements in thd->auto_inc_intervals_in_cur_stmt_for_binlog() because the latter list is cumulative over all statements forming one binlog event (when stored functions and triggers are used), and collapses two contiguous intervals in one (see its append() method).

    The idea is that generated auto_increment values are predictable and independent of the column values in the table. This is needed to be able to replicate into a table that already has rows with a higher auto-increment value than the one that is inserted.

    After we have already generated an auto-increment number and the user inserts a column with a higher value than the last used one, we will start counting from the inserted value.

    This function's "outputs" are: the table's auto_increment field is filled with a value, thd->next_insert_id is filled with the value to use for the next row, if a value was autogenerated for the current row it is stored in thd->insert_id_for_cur_row, if get_auto_increment() was called thd->auto_inc_interval_for_cur_row is modified, if that interval is not present in thd->auto_inc_intervals_in_cur_stmt_for_binlog it is added to this list.

Return values
0ok
HA_ERR_AUTOINC_READ_FAILEDget_auto_increment() was called and returned ~(ulonglong) 0
HA_ERR_AUTOINC_ERANGEstoring value in field caused strict mode failure.

◆ MAX_HTON_LIST_ST

#define MAX_HTON_LIST_ST   63

◆ MYSQL_TABLE_IO_WAIT

#define MYSQL_TABLE_IO_WAIT (   OP,
  INDEX,
  RESULT,
  PAYLOAD 
)

Instrumentation helper for table io_waits.

Note that this helper is intended to be used from within the handler class only, as it uses members from handler Performance schema events are instrumented as follows:

  • in non batch mode, one event is generated per call
  • in batch mode, the number of rows affected is saved in m_psi_numrows, so that end_psi_batch_mode() generates a single event for the batch.
    Parameters
    OPthe table operation to be performed
    INDEXthe table index used if any, or MAX_KEY.
    RESULTthe result of the table operation performed
    PAYLOADinstrumented code to execute
    See also
    handler::end_psi_batch_mode.

◆ MYSQL_TABLE_LOCK_WAIT

#define MYSQL_TABLE_LOCK_WAIT (   OP,
  FLAGS,
  PAYLOAD 
)
Value:
{ \
if (m_psi != NULL) { \
PSI_table_locker *locker; \
PSI_table_locker_state state; \
locker = PSI_TABLE_CALL(start_table_lock_wait)(&state, m_psi, OP, FLAGS, \
__FILE__, __LINE__); \
if (locker != NULL) PSI_TABLE_CALL(end_table_lock_wait)(locker); \
} else { \
PAYLOAD \
} \
}
Sergei Dialog Client Authentication NULL
Definition: dialog.cc:352
#define PSI_TABLE_CALL(M)
Definition: psi_table.h:31
if(++stacktop > STACKSIZ)
Definition: dbug_analyze.cc:141

Instrumentation helper for table io_waits.

Parameters
OPthe table operation to be performed
FLAGSper table operation flags.
PAYLOADthe code to instrument.
See also
MYSQL_END_TABLE_WAIT.

◆ SETMSG

#define SETMSG (   nr,
  msg 
)    handler_errmsgs[(nr)-HA_ERR_FIRST] = (msg)

Function Documentation

◆ binlog_func_foreach()

static bool binlog_func_foreach ( THD thd,
binlog_func_st bfn 
)
static

◆ binlog_func_list()

static bool binlog_func_list ( THD ,
plugin_ref  plugin,
void *  arg 
)
static

Listing handlertons first to avoid recursive calls and deadlock.

◆ binlog_log_query_handlerton()

static bool binlog_log_query_handlerton ( THD thd,
plugin_ref  plugin,
void *  args 
)
static

◆ binlog_log_query_handlerton2()

static bool binlog_log_query_handlerton2 ( THD thd,
handlerton hton,
void *  args 
)
static

◆ binlog_log_row()

int binlog_log_row ( TABLE table,
const uchar before_record,
const uchar after_record,
Log_func log_func 
)

binlog a row operation

◆ buf_to_hex()

static std::string buf_to_hex ( const uchar buf,
uint  buf_size_bytes 
)
static

Convert a binary buffer to a hex string, replacing each character with its hex number.

Parameters
[in]bufbuffer to convert
[in]buf_size_byteslength of the buffer in bytes
Returns
a hex string, e.g. "61 62 63" for an input "abc"

◆ buf_to_raw()

static std::string buf_to_raw ( const uchar buf,
uint  buf_size_bytes 
)
static

Convert a binary buffer to a raw string, replacing non-printable characters with a dot.

Parameters
[in]bufbuffer to convert
[in]buf_size_byteslength of the buffer in bytes
Returns
a printable string, e.g. "ab.d." for an input 0x61620064FF

◆ calculate_key_len()

uint calculate_key_len ( TABLE table,
uint  key,
key_part_map  keypart_map 
)

Calculates length of key.

Given a key index and a map of key parts return length of buffer used by key parts.

Parameters
tableTable containing the key
keyKey index
keypart_mapwhich key parts that is used
Returns
Length of used key parts.

◆ check_engine_system_table_handlerton()

static bool check_engine_system_table_handlerton ( THD ,
plugin_ref  plugin,
void *  arg 
)
static

Called for each SE to check if given db, tablename is a system table.

The primary purpose of introducing this function is to stop system tables to be created or being moved to undesired storage engines.

Parameters
pluginPoints to specific SE.
argIs of type struct st_sys_tbl_chk_params.
Note
args->status Indicates OUT param, see struct st_sys_tbl_chk_params definition for more info.
Returns
Operation status
Return values
trueThere was a match found. This will stop doing checks with other SE's.
falseThere was no match found. Other SE's will be checked to find a match.

◆ check_if_system_table()

static bool check_if_system_table ( const char *  db,
const char *  table_name,
bool is_sql_layer_system_table 
)
static

Check if a table specified by name is a system table.

Parameters
dbDatabase name for the table.
table_nameTable name to be checked.
[out]is_sql_layer_system_tableTrue if a system table belongs to sql_layer.
Returns
Operation status
Return values
trueIf the table name is a system table.
falseIf the table name is a user-level table.

◆ check_table_binlog_row_based()

static bool check_table_binlog_row_based ( THD thd,
TABLE table 
)
static

◆ check_table_for_old_types()

int check_table_for_old_types ( const TABLE table,
bool  check_temporal_upgrade 
)

Function identifies any old data type present in table.

This function was handler::check_old_types(). Function is not part of SE API. It is now converted to auxiliary standalone function.

Parameters
[in]tableTABLE object
[in]check_temporal_upgradeCheck if temporal upgrade is needed
Return values
0ON SUCCESS
errorcode ON FAILURE

◆ closecon_handlerton()

static bool closecon_handlerton ( THD thd,
plugin_ref  plugin,
void *   
)
static

◆ commit_owned_gtid_by_partial_command()

int commit_owned_gtid_by_partial_command ( THD thd)

The function is a wrapper of commit_owned_gtids(...).

It is invoked at committing a partially failed statement or transaction.

Parameters
thdThread context.
Return values
-1if error when persisting owned gtid.
0if succeed to commit owned gtid.
1if do not meet conditions to commit owned gtid.

◆ commit_owned_gtids()

int commit_owned_gtids ( THD thd,
bool  all,
bool need_clear_owned_gtid_ptr 
)

The function computes condition to call gtid persistor wrapper, and executes it.

It is invoked at committing a statement or transaction, including XA, and also at XA prepare handling.

Parameters
thdThread context.
allThe execution scope, true for the transaction one, false for the statement one.
[out]need_clear_owned_gtid_ptrA pointer to bool variable to return the computed decision value.
Returns
zero as no error indication, non-zero otherwise

◆ compute_next_insert_id()

ulonglong compute_next_insert_id ( ulonglong  nr,
struct System_variables variables 
)
inline

Generate the next auto-increment number based on increment and offset.

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:
    1,2,3,4,5,... 
    If increment=10 and offset=5 and previous number is 1, we get:
    1,5,15,25,35,... 

◆ copy_blob_data()

static void copy_blob_data ( const TABLE table,
const MY_BITMAP *const  fields,
blob_len_ptr blob_len_ptr_array 
)
static

Copy the value of BLOB virtual generated columns into the space allocated by storage engine.

This is because the table is closed after evaluating the value. In order to keep the BLOB value after the table is closed, we have to copy the value into the place where storage engine prepares for.

Parameters
tablepointer of the table to be operated on
fieldsbitmap of field index of evaluated generated column
blob_len_ptr_arrayarray of length and pointer of allocated space by storage engine.

◆ default_rm_tmp_tables()

bool default_rm_tmp_tables ( handlerton hton,
THD ,
List< LEX_STRING > *  files 
)

Default implementation for handlerton::rm_tmp_tables() method which simply removes all files from "files" list which have one of SE's extensions.

This implementation corresponds to default implementation of handler::delete_table() method.

◆ discover_handlerton()

static bool discover_handlerton ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ dropdb_handlerton()

static bool dropdb_handlerton ( THD ,
plugin_ref  plugin,
void *  path 
)
static

◆ extract_blob_space_and_length_from_record_buff()

static void extract_blob_space_and_length_from_record_buff ( const TABLE table,
const MY_BITMAP *const  fields,
blob_len_ptr blob_len_ptr_array 
)
static

Get the blob length and pointer of allocated space from the record buffer.

During evaluating the blob virtual generated columns, the blob space will be allocated by server. In order to keep the blob data after the table is closed, we need write the data into a specified space allocated by storage engine. Here, we have to extract the space pointer and length from the record buffer. After we get the value of virtual generated columns, copy the data into the specified space and store it in the record buffer (

See also
copy_blob_data()).
Parameters
tablethe pointer of table
fieldsbitmap of field index of evaluated generated column
[out]blob_len_ptr_arrayan array to record the length and pointer of allocated space by storage engine.
Note
The caller should provide the blob_len_ptr_array with a size of MAX_FIELDS.

◆ exts_handlerton()

static bool exts_handlerton ( THD ,
plugin_ref  plugin,
void *  arg 
)
static

Returns a list of all known extensions.

No mutexes, worst case race is a minor surplus memory allocation We have to recreate the extension map if mysqld is restarted (for example within libmysqld)

Return values
pointerpointer to TYPELIB structure

◆ find_files_handlerton()

static bool find_files_handlerton ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ flush_handlerton()

static bool flush_handlerton ( THD ,
plugin_ref  plugin,
void *  arg 
)
static

◆ get_canonical_filename()

const char* get_canonical_filename ( handler file,
const char *  path,
char *  tmp_path 
)

make canonical filename

Parameters
[in]filetable handler
[in]pathoriginal path
[out]tmp_pathbuffer for canonized path

Lower case db name and table name path parts for non file based tables when lower_case_table_names is 2 (store as is, compare in lower case). Filesystem path prefix (mysql_data_home or tmpdir) is left intact.

Note
tmp_path may be left intact if no conversion was performed.
Return values
canonizedpath

◆ get_handler_errmsg()

static const char* get_handler_errmsg ( int  nr)
static

◆ get_new_handler()

handler* get_new_handler ( TABLE_SHARE share,
bool  partitioned,
MEM_ROOT alloc,
handlerton db_type 
)

Create handler object for the table in the storage engine.

Parameters
shareTABLE_SHARE for the table, can be NULL if caller didn't perform full-blown open of table definition.
partitionedIndicates whether table is partitioned.
allocMemory root to be used for allocating handler object.
db_typeTable's storage engine.
Note
This function will try to use default storage engine if one which was specified through db_type parameter is not available.

◆ get_sort_and_sweep_cost()

static void get_sort_and_sweep_cost ( TABLE table,
ha_rows  nrows,
Cost_estimate cost 
)
static

◆ get_sweep_read_cost()

void get_sweep_read_cost ( TABLE table,
ha_rows  nrows,
bool  interrupted,
Cost_estimate cost 
)

Get cost of reading nrows table records in a "disk sweep".

A disk sweep read is a sequence of handler->rnd_pos(rowid) calls that made for an ordered sequence of rowids.

We take into account that some of the records might be in a memory buffer while others need to be read from a secondary storage device. The model for this assumes hard disk IO. A disk read is performed as follows:

  1. The disk head is moved to the needed cylinder
  2. The controller waits for the plate to rotate
  3. The data is transferred

Time to do #3 is insignificant compared to #2+#1.

Time to move the disk head is proportional to head travel distance.

Time to wait for the plate to rotate depends on whether the disk head was moved or not.

If disk head wasn't moved, the wait time is proportional to distance between the previous block and the block we're reading.

If the head was moved, we don't know how much we'll need to wait for the plate to rotate. We assume the wait time to be a variate with a mean of 0.5 of full rotation time.

Our cost units are "random disk seeks". The cost of random disk seek is actually not a constant, it depends one range of cylinders we're going to access. We make it constant by introducing a fuzzy concept of "typical datafile length" (it's fuzzy as it's hard to tell whether it should include index file, temp.tables etc). Then random seek cost is:

1 = half_rotation_cost + move_cost * 1/3 * typical_data_file_length

We define half_rotation_cost as disk_seek_base_cost() (see Cost_model_server::disk_seek_base_cost()).

Parameters
tableTable to be accessed
nrowsNumber of rows to retrieve
interruptedtrue <=> Assume that the disk sweep will be interrupted by other disk IO. false - otherwise.
[out]costthe cost

◆ ha_binlog_end()

int ha_binlog_end ( THD thd)

◆ ha_binlog_index_purge_file()

int ha_binlog_index_purge_file ( THD thd,
const char *  file 
)

◆ ha_binlog_log_query()

void ha_binlog_log_query ( THD thd,
handlerton hton,
enum_binlog_command  binlog_command,
const char *  query,
size_t  query_length,
const char *  db,
const char *  table_name 
)

◆ ha_binlog_wait()

void ha_binlog_wait ( THD thd)

◆ ha_change_key_cache()

int ha_change_key_cache ( KEY_CACHE old_key_cache,
KEY_CACHE new_key_cache 
)

Move all tables from one key cache to another one.

◆ ha_check_and_coalesce_trx_read_only()

static uint ha_check_and_coalesce_trx_read_only ( THD thd,
Ha_trx_info ha_list,
bool  all 
)
static

Check if we can skip the two-phase commit.

A helper function to evaluate if two-phase commit is mandatory. As a side effect, propagates the read-only/read-write flags of the statement transaction to its enclosing normal transaction.

If we have at least two engines with read-write changes we must run a two-phase commit. Otherwise we can run several independent commits as the only transactional engine has read-write changes and others are read-only.

Return values
0All engines are read-only.
1We have the only engine with read-write changes.
>1More than one engine have read-write changes. Note: return value might NOT be the exact number of engines with read-write changes.

◆ ha_check_if_supported_system_table()

bool ha_check_if_supported_system_table ( handlerton hton,
const char *  db,
const char *  table_name 
)

Check if a given table is a system table.

The primary purpose of introducing this function is to stop system tables to be created or being moved to undesired storage engines.

Parameters
htonHandlerton of new engine.
dbDatabase name.
table_nameTable name to be checked.
Returns
Operation status
Return values
trueIf the table name is a valid system table or if its a valid user table.
falseIf the table name is a system table name and does not belong to engine specified in the command.

◆ ha_check_if_table_exists()

bool ha_check_if_table_exists ( THD thd,
const char *  db,
const char *  name,
bool exists 
)

Try to find a table in a storage engine.

Parameters
thdThread handle
dbNormalized table schema name
nameNormalized table name.
[out]existsOnly valid if the function succeeded.
Return values
trueAn error is found
falseSuccess, check *exists

◆ ha_check_reserved_db_name()

bool ha_check_reserved_db_name ( const char *  name)

Check if the database name is reserved word used by SE.

Parameters
nameDatabase name.
Return values
trueIf the name is a reserved word.
falseIf the name is not a reserved word.

◆ ha_checktype()

handlerton* ha_checktype ( THD thd,
enum legacy_db_type  database_type,
bool  no_substitute,
bool  report_error 
)

Use other database handler if databasehandler is not compiled in.

◆ ha_close_connection()

void ha_close_connection ( THD thd)

function to close a connection and thd, defined in sql/handler.cc

Note
don't bother to rollback here, it's done already

◆ ha_commit_attachable()

int ha_commit_attachable ( THD thd)

Commit the attachable transaction in storage engines.

Note
This is slimmed down version of ha_commit_trans()/ha_commit_low() which commits attachable transaction but skips code which is unnecessary and unsafe for them (like dealing with GTIDs). Since attachable transactions are read-only their commit only needs to release resources and cleanup state in SE.
Parameters
thdCurrent thread
Return values
0- Success
non-0- Failure

◆ ha_commit_low()

int ha_commit_low ( THD thd,
bool  all,
bool  run_after_commit 
)

Commit the sessions outstanding transaction.

Precondition
thd->transaction.flags.commit_low == true
Postcondition
thd->transaction.flags.commit_low == false
Note
This function does not care about global read lock; the caller should.
Parameters
[in]thdThread handle.
[in]allIs set in case of explicit commit (COMMIT statement), or implicit commit issued by DDL. Is not set when called at the end of statement, even if autocommit=1.
[in]run_after_commitTrue by default, otherwise, does not execute the after_commit hook in the function.

◆ ha_commit_trans()

int ha_commit_trans ( THD thd,
bool  all,
bool  ignore_global_read_lock 
)
Parameters
[in]thdThread handle.
[in]allSession transaction if true, statement otherwise.
[in]ignore_global_read_lockAllow commit to complete even if a global read lock is active. This can be used to allow changes to internal tables (e.g. slave status tables).
Return values
0ok
1transaction was rolled back
2error during commit, data may be inconsistent

◆ ha_create_table()

int ha_create_table ( THD thd,
const char *  path,
const char *  db,
const char *  table_name,
HA_CREATE_INFO create_info,
bool  update_create_info,
bool  is_temp_table,
dd::Table table_def 
)

Initiates table-file and calls appropriate database-creator.

Parameters
thdThread context.
pathPath to table file (without extension).
dbDatabase name.
table_nameTable name.
create_infoHA_CREATE_INFO describing table.
update_create_infoIndicates that create_info needs to be updated from table share.
is_temp_tableIndicates that this is temporary table (for cases when this info is not available from HA_CREATE_INFO).
table_defData-dictionary object describing table to be used for table creation. Can be adjusted by storage engine if it supports atomic DDL. For non-temporary tables these changes will be saved to the data-dictionary by this call.
Return values
0ok
1error

◆ ha_create_table_from_engine()

int ha_create_table_from_engine ( THD thd,
const char *  db,
const char *  name 
)

Try to discover table from engine.

Note
If found, import the serialized dictionary information.
Return values
-1Table did not exists
0Table created ok
>0 Error, table existed but could not be created

◆ ha_default_handlerton()

handlerton* ha_default_handlerton ( THD thd)

Return the default storage engine handlerton used for non-temp tables for thread.

SYNOPSIS ha_default_handlerton(thd) thd current thread

RETURN pointer to handlerton

◆ ha_default_plugin()

static plugin_ref ha_default_plugin ( THD thd)
static

◆ ha_default_temp_handlerton()

handlerton* ha_default_temp_handlerton ( THD thd)

Return the default storage engine handlerton used for explicitly created temp tables for a thread.

SYNOPSIS ha_default_temp_handlerton(thd) thd current thread

RETURN pointer to handlerton

◆ ha_default_temp_plugin()

static plugin_ref ha_default_temp_plugin ( THD thd)
static

◆ ha_delete_table()

int ha_delete_table ( THD thd,
handlerton table_type,
const char *  path,
const char *  db,
const char *  alias,
const dd::Table table_def,
bool  generate_warning 
)

Delete table from the storage engine.

Parameters
thdThread context.
table_typeHandlerton for table's SE.
pathPath to table (without extension).
dbTable database.
aliasTable name.
table_defdd::Table object describing the table.
generate_warningIndicates whether errors during deletion should be reported as warnings.
Returns
0 - in case of success, non-0 in case of failure, ENOENT if the file doesn't exists.

◆ ha_discover()

static int ha_discover ( THD thd,
const char *  db,
const char *  name,
uchar **  frmblob,
size_t *  frmlen 
)
static

◆ ha_drop_database()

void ha_drop_database ( char *  path)

◆ ha_enable_transaction()

int ha_enable_transaction ( THD thd,
bool  on 
)

Tell the storage engine that it is allowed to "disable transaction" in the handler.

It is a hint that ACID is not required - it is used in NDB for ALTER TABLE, for example, when data are copied to temporary table. A storage engine may treat this hint any way it likes. NDB for example starts to commit every now and then automatically. This hint can be safely ignored.

◆ ha_end()

void ha_end ( )

◆ ha_finalize_handlerton()

int ha_finalize_handlerton ( st_plugin_int plugin)

◆ ha_find_files()

int ha_find_files ( THD thd,
const char *  db,
const char *  path,
const char *  wild,
bool  dir,
List< LEX_STRING > *  files 
)

◆ ha_flush_logs()

bool ha_flush_logs ( bool  binlog_group_flush = false)

Flush the log(s) of storage engine(s).

Parameters
binlog_group_flushtrue if we got invoked by binlog group commit during flush stage, false in other cases.
Return values
falseSucceed
trueError

◆ ha_init()

int ha_init ( void  )

◆ ha_init_errors()

int ha_init_errors ( void  )

Register handler error messages for use with my_error().

Return values
0OK
!=0Error

◆ ha_init_key_cache()

int ha_init_key_cache ( const char *  ,
KEY_CACHE key_cache 
)

Init a key cache if it has not been initied before.

◆ ha_initialize_handlerton()

int ha_initialize_handlerton ( st_plugin_int plugin)

◆ ha_is_storage_engine_disabled()

bool ha_is_storage_engine_disabled ( handlerton se_handle)

◆ ha_kill_connection()

void ha_kill_connection ( THD thd)

◆ ha_known_exts()

TYPELIB* ha_known_exts ( )

◆ ha_lock_engine()

plugin_ref ha_lock_engine ( THD thd,
const handlerton hton 
)

◆ ha_make_pushed_joins()

int ha_make_pushed_joins ( THD thd,
const AQP::Join_plan plan 
)

◆ ha_notify_alter_table()

bool ha_notify_alter_table ( THD thd,
const MDL_key mdl_key,
ha_notification_type  notification_type 
)

Notify/get permission from all interested storage engines before or after executed ALTER TABLE on the table identified by key.

Parameters
thdThread context.
mdl_keyMDL key identifying table.
notification_typeIndicates whether this is pre-ALTER or post-ALTER notification.

See

See also
handlerton::notify_alter_table for rationale, details about calling convention and error reporting.
Returns
False - if notification was successful/ALTER TABLE can proceed. True - if it has failed/ALTER TABLE should fail.

◆ ha_notify_exclusive_mdl()

bool ha_notify_exclusive_mdl ( THD thd,
const MDL_key mdl_key,
ha_notification_type  notification_type,
bool victimized 
)

Notify/get permission from all interested storage engines before acquisition or after release of exclusive metadata lock on object represented by key.

Parameters
thdThread context.
mdl_keyMDL key identifying object on which exclusive lock is to be acquired/was released.
notification_typeIndicates whether this is pre-acquire or post-release notification.
victimized'true' if locking failed as we were selected as a victim in order to avoid possible deadlocks.

See

See also
handlerton::notify_exclusive_mdl for details about calling convention and error reporting.
Returns
False - if notification was successful/lock can be acquired, True - if it has failed/lock should not be acquired.

◆ ha_post_recover()

void ha_post_recover ( )

Perform SE-specific cleanup after recovery of transactions.

Note
SE supporting atomic DDL can use this method to perform post-DDL actions for DDL statements which were committed or rolled back during recovery stage.

◆ ha_pre_dd_shutdown()

void ha_pre_dd_shutdown ( void  )

Invoke handlerton::pre_dd_shutdown() on every storage engine plugin.

◆ ha_prepare()

int ha_prepare ( THD thd)
Return values
0ok
1error, transaction was rolled back

◆ ha_prepare_low()

int ha_prepare_low ( THD thd,
bool  all 
)

◆ ha_release_savepoint()

int ha_release_savepoint ( THD thd,
SAVEPOINT sv 
)

◆ ha_reset_logs()

int ha_reset_logs ( THD thd)

◆ ha_reset_slave()

void ha_reset_slave ( THD thd)

◆ ha_resize_key_cache()

int ha_resize_key_cache ( KEY_CACHE key_cache)

Resize key cache.

◆ ha_resolve_by_legacy_type()

handlerton* ha_resolve_by_legacy_type ( THD thd,
enum legacy_db_type  db_type 
)

◆ ha_resolve_by_name()

plugin_ref ha_resolve_by_name ( THD thd,
const LEX_STRING name,
bool  is_temp_table 
)

Return the storage engine handlerton for the supplied name.

SYNOPSIS ha_resolve_by_name(thd, name) thd current thread name name of storage engine

RETURN pointer to storage engine plugin handle

◆ ha_resolve_by_name_raw()

plugin_ref ha_resolve_by_name_raw ( THD thd,
const LEX_CSTRING name 
)

Resolve handlerton plugin by name, without checking for "DEFAULT" or HTON_NOT_USER_SELECTABLE.

Parameters
thdThread context.
namePlugin name.
Returns
plugin or NULL if not found.

◆ ha_resolve_storage_engine_name()

const char* ha_resolve_storage_engine_name ( const handlerton db_type)

◆ ha_rkey_function_to_str()

const char* ha_rkey_function_to_str ( enum ha_rkey_function  r)

Generate a string representation of an ha_rkey_function enum value.

Parameters
[in]rvalue to turn into string
Returns
a string, e.g. "HA_READ_KEY_EXACT" if r == HA_READ_KEY_EXACT

◆ ha_rm_tmp_tables()

bool ha_rm_tmp_tables ( THD thd,
List< LEX_STRING > *  files 
)

Ask all SEs to drop all temporary tables which have been left from previous server run.

Used on server start-up.

Parameters
[in]thdThread context.
[in,out]filesList of files in directories for temporary files which match tmp_file_prefix and thus can belong to temporary tables. If any SE recognizes some file as belonging to temporary table in this SE and deletes the file it is also supposed to remove file from this list.

◆ ha_rollback_low()

int ha_rollback_low ( THD thd,
bool  all 
)

◆ ha_rollback_to_savepoint()

int ha_rollback_to_savepoint ( THD thd,
SAVEPOINT sv 
)

◆ ha_rollback_to_savepoint_can_release_mdl()

bool ha_rollback_to_savepoint_can_release_mdl ( THD thd)

Check if all storage engines used in transaction agree that after rollback to savepoint it is safe to release MDL locks acquired after savepoint creation.

Parameters
thdThe client thread that executes the transaction.
Returns
true - It is safe to release MDL locks. false - If it is not.

Checking whether it is safe to release metadata locks after rollback to savepoint in all the storage engines that are part of the transaction.

◆ ha_rollback_trans()

int ha_rollback_trans ( THD thd,
bool  all 
)

◆ ha_savepoint()

int ha_savepoint ( THD thd,
SAVEPOINT sv 
)
Note
according to the sql standard (ISO/IEC 9075-2:2003) section "4.33.4 SQL-statements and transaction states", SAVEPOINT is not transaction-initiating SQL-statement

◆ ha_set_normalized_disabled_se_str()

void ha_set_normalized_disabled_se_str ( const std::string &  disabled_se)

◆ ha_show_status()

bool ha_show_status ( THD thd,
handlerton db_type,
enum ha_stat_type  stat 
)

◆ ha_start_consistent_snapshot()

int ha_start_consistent_snapshot ( THD thd)

◆ ha_table_exists_in_engine()

int ha_table_exists_in_engine ( THD thd,
const char *  db,
const char *  name 
)

◆ hton2plugin()

st_plugin_int* hton2plugin ( uint  slot)

Maps from slot to plugin. May return NULL if plugin has been unloaded.

◆ indexed_cells_to_string()

std::string indexed_cells_to_string ( const uchar indexed_cells,
uint  indexed_cells_len,
const KEY mysql_index 
)

Generate a human readable string that describes indexed cells that are given to handler::index_read() as input.

The generated string is similar to the one generated by row_to_string(), but only contains the cells covered by the given index.

Parameters
[in]indexed_cellsraw buffer in handler::index_read() input format
[in]indexed_cells_lenlength of indexed_cells in bytes
[in]mysql_indexthe index that covers the cells, for querying metadata
Returns
textual dump of the cells

◆ insert_hton2plugin()

st_plugin_int* insert_hton2plugin ( uint  slot,
st_plugin_int plugin 
)

For unit testing.

Insert plugin into arbitrary slot in array. Remove plugin from arbitrary slot in array.

◆ is_reserved_db_name_handlerton()

static bool is_reserved_db_name_handlerton ( THD ,
plugin_ref  plugin,
void *  name 
)
static

Checks if the database name is reserved word used by SE by invoking the handlerton method.

Parameters
pluginSE plugin.
nameDatabase name.
Return values
trueIf the name is reserved word.
falseIf the name is not reserved word.

◆ key_has_vcol()

static bool key_has_vcol ( const KEY_PART_INFO part,
uint  length 
)
static

Check if one of the columns in a key is a virtual generated column.

Parameters
partthe first part of the key to check
lengththe length of the key
Return values
trueif the key contains a virtual generated column
falseif the key does not contain a virtual generated column

◆ key_uses_partial_cols()

static bool key_uses_partial_cols ( TABLE table,
uint  keyno 
)
static

Check if key has partially-covered columns.

We can't use DS-MRR to perform range scans when the ranges are over partially-covered keys, because we'll not have full key part values (we'll have their prefixes from the index) and will not be able to check if we've reached the end the range.

Parameters
tableTable to check keys for
keynoKey to check
Return values
trueYes
falseNo

◆ kill_handlerton()

static bool kill_handlerton ( THD thd,
plugin_ref  plugin,
void *   
)
static

◆ make_pushed_join_handlerton()

static bool make_pushed_join_handlerton ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ move_key_field_offsets()

static void move_key_field_offsets ( const key_range range,
const KEY_PART_INFO key_part,
my_ptrdiff_t  diff 
)
inlinestatic

Change the offsets of all the fields in a key range.

Parameters
rangethe key range
key_partthe first key part
diffhow much to change the offsets with

◆ my_eval_gcolumn_expr_helper()

static bool my_eval_gcolumn_expr_helper ( THD thd,
TABLE table,
const MY_BITMAP *const  fields,
uchar record,
bool  in_purge 
)
static

◆ notify_alter_table_helper()

static bool notify_alter_table_helper ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ notify_exclusive_mdl_helper()

static bool notify_exclusive_mdl_helper ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ num_hton2plugins()

size_t num_hton2plugins ( )

Returns the size of the array holding pointers to plugins.

◆ post_recover_handlerton()

static bool post_recover_handlerton ( THD ,
plugin_ref  plugin,
void *   
)
static

◆ pre_dd_shutdown_handlerton()

static bool pre_dd_shutdown_handlerton ( THD ,
plugin_ref  plugin,
void *   
)
static

Invoke handlerton::pre_dd_shutdown() on a plugin.

Parameters
pluginstorage engine plugin
Return values
false(always)

◆ prev_insert_id()

ulonglong prev_insert_id ( ulonglong  nr,
struct System_variables variables 
)
inline

Computes the largest number X:

  • smaller than or equal to "nr"
  • of the form: auto_increment_offset + N * auto_increment_increment where N>=0.

SYNOPSIS prev_insert_id nr Number to "round down" variables variables struct containing auto_increment_increment and auto_increment_offset

RETURN The number X if it exists, "nr" otherwise.

◆ print_keydup_error() [1/2]

void print_keydup_error ( TABLE table,
KEY key,
const char *  msg,
myf  errflag 
)

Construct and emit duplicate key error message using information from table's record buffer.

Parameters
tableTABLE object which record buffer should be used as source for column values.
keyKey description.
msgError message template to which key value should be added.
errflagFlags for my_error() call.

◆ print_keydup_error() [2/2]

void print_keydup_error ( TABLE table,
KEY key,
myf  errflag 
)

Construct and emit duplicate key error message using information from table's record buffer.

See also
print_keydup_error(table, key, msg, errflag).

◆ remove_hton2plugin()

st_plugin_int* remove_hton2plugin ( uint  slot)

◆ rm_tmp_tables_handlerton()

static bool rm_tmp_tables_handlerton ( THD thd,
plugin_ref  plugin,
void *  files 
)
static

◆ row_to_string()

std::string row_to_string ( const uchar mysql_row,
TABLE mysql_table 
)

Generate a human readable string that describes the contents of a row.

The row must be in the same format as provided to handler::write_row(). For example, given this table structure: t1 (pk int(11) not null, col_int_key int(11), col_varchar_key varchar(1), hash unique index0(pk, col_int_key, col_varchar_key))

something like this will be generated (without the new lines):

len=16, raw=..........c....., hex=f9 1d 00 00 00 08 00 00 00 01 63 a5 a5 a5 a5 a5, human=(pk=29, col_int_key=8, col_varchar_key=c)

Parameters
[in]mysql_rowrow to dump
[in]mysql_tabletable to which the row belongs, for querying metadata
Returns
textual dump of the row

◆ set_tx_isolation()

bool set_tx_isolation ( THD thd,
enum_tx_isolation  tx_isolation,
bool  one_shot 
)

Set the transaction isolation level for the next transaction and update session tracker information about the transaction isolation level.

Parameters
thdTHD session setting the tx_isolation.
tx_isolationThe isolation level to be set.
one_shotTrue if the isolation level should be restored to session default after finishing the transaction.

◆ showstat_handlerton()

static bool showstat_handlerton ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ snapshot_handlerton()

static bool snapshot_handlerton ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ stat_print()

static bool stat_print ( THD thd,
const char *  type,
size_t  type_len,
const char *  file,
size_t  file_len,
const char *  status,
size_t  status_len 
)
static

◆ table_case_name()

const char* table_case_name ( const HA_CREATE_INFO info,
const char *  name 
)

◆ table_definition()

std::string table_definition ( const char *  table_name,
const TABLE mysql_table 
)

Generate a human readable string that describes a table structure.

For example: t1 (c1 char(60) not null, c2 char(60), hash unique index0(c1, c2))

Parameters
[in]table_namename of the table to be described
[in]mysql_tabletable structure
Returns
a string similar to a CREATE TABLE statement

◆ table_exists_in_engine_handlerton()

static bool table_exists_in_engine_handlerton ( THD thd,
plugin_ref  plugin,
void *  arg 
)
static

◆ trans_register_ha()

void trans_register_ha ( THD thd,
bool  all,
handlerton ht_arg,
const ulonglong trxid 
)

Transaction handling in the server

In each client connection, MySQL maintains two transactional states:

  • a statement transaction,
  • a standard, also called normal transaction.

Historical note

"Statement transaction" is a non-standard term that comes from the times when MySQL supported BerkeleyDB storage engine.

First of all, it should be said that in BerkeleyDB auto-commit mode auto-commits operations that are atomic to the storage engine itself, such as a write of a record, and are too high-granular to be atomic from the application perspective (MySQL). One SQL statement could involve many BerkeleyDB auto-committed operations and thus BerkeleyDB auto-commit was of little use to MySQL.

Secondly, instead of SQL standard savepoints, BerkeleyDB provided the concept of "nested transactions". In a nutshell, transactions could be arbitrarily nested, but when the parent transaction was committed or aborted, all its child (nested) transactions were handled committed or aborted as well. Commit of a nested transaction, in turn, made its changes visible, but not durable: it destroyed the nested transaction, all its changes would become available to the parent and currently active nested transactions of this parent.

So the mechanism of nested transactions was employed to provide "all or nothing" guarantee of SQL statements required by the standard. A nested transaction would be created at start of each SQL statement, and destroyed (committed or aborted) at statement end. Such nested transaction was internally referred to as a "statement transaction" and gave birth to the term.

(Historical note ends)

Since then a statement transaction is started for each statement that accesses transactional tables or uses the binary log. If the statement succeeds, the statement transaction is committed. If the statement fails, the transaction is rolled back. Commits of statement transactions are not durable – each such transaction is nested in the normal transaction, and if the normal transaction is rolled back, the effects of all enclosed statement transactions are undone as well. Technically, a statement transaction can be viewed as a savepoint which is maintained automatically in order to make effects of one statement atomic.

The normal transaction is started by the user and is ended usually upon a user request as well. The normal transaction encloses transactions of all statements issued between its beginning and its end. In autocommit mode, the normal transaction is equivalent to the statement transaction.

Since MySQL supports PSEA (pluggable storage engine architecture), more than one transactional engine can be active at a time. Hence transactions, from the server point of view, are always distributed. In particular, transactional state is maintained independently for each engine. In order to commit a transaction the two phase commit protocol is employed.

Not all statements are executed in context of a transaction. Administrative and status information statements do not modify engine data, and thus do not start a statement transaction and also have no effect on the normal transaction. Examples of such statements are SHOW STATUS and RESET SLAVE.

Similarly DDL statements are not transactional, and therefore a transaction is [almost] never started for a DDL statement. The difference between a DDL statement and a purely administrative statement though is that a DDL statement always commits the current transaction before proceeding, if there is any.

At last, SQL statements that work with non-transactional engines also have no effect on the transaction state of the connection. Even though they are written to the binary log, and the binary log is, overall, transactional, the writes are done in "write-through" mode, directly to the binlog file, followed with a OS cache sync, in other words, bypassing the binlog undo log (translog). They do not commit the current normal transaction. A failure of a statement that uses non-transactional tables would cause a rollback of the statement transaction, but in case there no non-transactional tables are used, no statement transaction is started.

Data layout

The server stores its transaction-related data in thd->transaction. This structure has two members of type THD_TRANS. These members correspond to the statement and normal transactions respectively:

  • thd->transaction.stmt contains a list of engines that are participating in the given statement
  • thd->transaction.all contains a list of engines that have participated in any of the statement transactions started within the context of the normal transaction. Each element of the list contains a pointer to the storage engine, engine-specific transactional data, and engine-specific transaction flags.

In autocommit mode thd->transaction.all is empty. Instead, data of thd->transaction.stmt is used to commit/rollback the normal transaction.

The list of registered engines has a few important properties:

  • no engine is registered in the list twice
  • engines are present in the list a reverse temporal order – new participants are always added to the beginning of the list.

Transaction life cycle

When a new connection is established, thd->transaction members are initialized to an empty state. If a statement uses any tables, all affected engines are registered in the statement engine list. In non-autocommit mode, the same engines are registered in the normal transaction list. At the end of the statement, the server issues a commit or a roll back for all engines in the statement list. At this point transaction flags of an engine, if any, are propagated from the statement list to the list of the normal transaction. When commit/rollback is finished, the statement list is cleared. It will be filled in again by the next statement, and emptied again at the next statement's end.

The normal transaction is committed in a similar way (by going over all engines in thd->transaction.all list) but at different times:

  • upon COMMIT SQL statement is issued by the user
  • implicitly, by the server, at the beginning of a DDL statement or SET AUTOCOMMIT={0|1} statement.

The normal transaction can be rolled back as well:

  • if the user has requested so, by issuing ROLLBACK SQL statement
  • if one of the storage engines requested a rollback by setting thd->transaction_rollback_request. This may happen in case, e.g., when the transaction in the engine was chosen a victim of the internal deadlock resolution algorithm and rolled back internally. When such a situation happens, there is little the server can do and the only option is to rollback transactions in all other participating engines. In this case the rollback is accompanied by an error sent to the user.

As follows from the use cases above, the normal transaction is never committed when there is an outstanding statement transaction. In most cases there is no conflict, since commits of the normal transaction are issued by a stand-alone administrative or DDL statement, thus no outstanding statement transaction of the previous statement exists. Besides, all statements that manipulate with the normal transaction are prohibited in stored functions and triggers, therefore no conflicting situation can occur in a sub-statement either. The remaining rare cases when the server explicitly has to commit the statement transaction prior to committing the normal one cover error-handling scenarios (see for example SQLCOM_LOCK_TABLES).

When committing a statement or a normal transaction, the server either uses the two-phase commit protocol, or issues a commit in each engine independently. The two-phase commit protocol is used only if:

  • all participating engines support two-phase commit (provide handlerton::prepare PSEA API call) and
  • transactions in at least two engines modify data (i.e. are not read-only).

Note that the two phase commit is used for statement transactions, even though they are not durable anyway. This is done to ensure logical consistency of data in a multiple- engine transaction. For example, imagine that some day MySQL supports unique constraint checks deferred till the end of statement. In such case a commit in one of the engines may yield ER_DUP_KEY, and MySQL should be able to gracefully abort statement transactions of other participants.

After the normal transaction has been committed, thd->transaction.all list is cleared.

When a connection is closed, the current normal transaction, if any, is rolled back.

Roles and responsibilities

The server has no way to know that an engine participates in the statement and a transaction has been started in it unless the engine says so. Thus, in order to be a part of a transaction, the engine must "register" itself. This is done by invoking trans_register_ha() server call. Normally the engine registers itself whenever handler::external_lock() is called. trans_register_ha() can be invoked many times: if an engine is already registered, the call does nothing. In case autocommit is not set, the engine must register itself twice – both in the statement list and in the normal transaction list. In which list to register is a parameter of trans_register_ha().

Note, that although the registration interface in itself is fairly clear, the current usage practice often leads to undesired effects. E.g. since a call to trans_register_ha() in most engines is embedded into implementation of handler::external_lock(), some DDL statements start a transaction (at least from the server point of view) even though they are not expected to. E.g. CREATE TABLE does not start a transaction, since handler::external_lock() is never called during CREATE TABLE. But CREATE TABLE ... SELECT does, since handler::external_lock() is called for the table that is being selected from. This has no practical effects currently, but must be kept in mind nevertheless.

Once an engine is registered, the server will do the rest of the work.

During statement execution, whenever any of data-modifying PSEA API methods is used, e.g. handler::write_row() or handler::update_row(), the read-write flag is raised in the statement transaction for the involved engine. Currently All PSEA calls are "traced", and the data can not be changed in a way other than issuing a PSEA call. Important: unless this invariant is preserved the server will not know that a transaction in a given engine is read-write and will not involve the two-phase commit protocol!

At the end of a statement, server call trans_commit_stmt is invoked. This call in turn invokes handlerton::prepare() for every involved engine. Prepare is followed by a call to handlerton::commit_one_phase() If a one-phase commit will suffice, handlerton::prepare() is not invoked and the server only calls handlerton::commit_one_phase(). At statement commit, the statement-related read-write engine flag is propagated to the corresponding flag in the normal transaction. When the commit is complete, the list of registered engines is cleared.

Rollback is handled in a similar fashion.

Additional notes on DDL and the normal transaction.

DDLs and operations with non-transactional engines do not "register" in thd->transaction lists, and thus do not modify the transaction state. Besides, each DDL in MySQL is prefixed with an implicit normal transaction commit (a call to trans_commit_implicit()), and thus leaves nothing to modify. However, as it has been pointed out with CREATE TABLE .. SELECT, some DDL statements can start a new transaction.

Behaviour of the server in this case is currently badly defined. DDL statements use a form of "semantic" logging to maintain atomicity: if CREATE TABLE .. SELECT failed, the newly created table is deleted. In addition, some DDL statements issue interim transaction commits: e.g. ALTER TABLE issues a commit after data is copied from the original table to the internal temporary table. Other statements, e.g. CREATE TABLE ... SELECT do not always commit after itself. And finally there is a group of DDL statements such as RENAME/DROP TABLE that doesn't start a new transaction and doesn't commit.

This diversity makes it hard to say what will happen if by chance a stored function is invoked during a DDL – whether any modifications it makes will be committed or not is not clear. Fortunately, SQL grammar of few DDLs allows invocation of a stored function.

A consistent behaviour is perhaps to always commit the normal transaction after all DDLs, just like the statement transaction is always committed at the end of all statements. Register a storage engine for a transaction.

Every storage engine MUST call this function when it starts a transaction or a statement (that is it must be called both for the "beginning of transaction" and "beginning of statement"). Only storage engines registered for the transaction/statement will know when to commit/rollback it.

Note
trans_register_ha is idempotent - storage engine may register many times per transaction.

◆ write_locked_table_maps()

static int write_locked_table_maps ( THD thd)
static

Write table maps for all (manually or automatically) locked tables to the binary log.

SYNOPSIS write_locked_table_maps() thd Pointer to THD structure

DESCRIPTION This function will generate and write table maps for all tables that are locked by the thread 'thd'.

RETURN VALUE 0 All OK 1 Failed to write all table maps

SEE ALSO THD::lock

Variable Documentation

◆ builtin_htons

Array allowing to check if handlerton is builtin without acquiring LOCK_plugin.

◆ ha_row_type

const char* ha_row_type[]
Initial value:
= {"",
"FIXED",
"DYNAMIC",
"COMPRESSED",
"REDUNDANT",
"COMPACT",
"?",
"?",
"?",
"?"}

◆ handler_errmsgs

const char** handler_errmsgs
static

◆ installed_htons

handlerton* installed_htons[128]
static

◆ mysqld_system_tables

st_handler_tablename mysqld_system_tables[]
Initial value:
= {
{MYSQL_SCHEMA_NAME.str, "plugin"},
{MYSQL_SCHEMA_NAME.str, "servers"},
{MYSQL_SCHEMA_NAME.str, "procs_priv"},
{MYSQL_SCHEMA_NAME.str, "tables_priv"},
{MYSQL_SCHEMA_NAME.str, "proxies_priv"},
{MYSQL_SCHEMA_NAME.str, "columns_priv"},
{MYSQL_SCHEMA_NAME.str, "time_zone"},
{MYSQL_SCHEMA_NAME.str, "time_zone_name"},
{MYSQL_SCHEMA_NAME.str, "time_zone_leap_second"},
{MYSQL_SCHEMA_NAME.str, "time_zone_transition"},
{MYSQL_SCHEMA_NAME.str, "time_zone_transition_type"},
{MYSQL_SCHEMA_NAME.str, "help_category"},
{MYSQL_SCHEMA_NAME.str, "help_keyword"},
{MYSQL_SCHEMA_NAME.str, "help_relation"},
{MYSQL_SCHEMA_NAME.str, "help_topic"},
{(const char *)NULL, (const char *)NULL}
}
char * str
Definition: mysql_lex_string.h:35
Sergei Dialog Client Authentication NULL
Definition: dialog.cc:352
LEX_STRING MYSQL_SCHEMA_NAME
Definition: table.cc:130

◆ normalized_se_str

std::string normalized_se_str = ""

◆ savepoint_alloc_size

ulong savepoint_alloc_size = 0

◆ se_plugin_array

While we have legacy_db_type, we have this array to check for dups and to find handlerton from legacy_db_type.

Remove when legacy_db_type is finally gone

◆ sys_table_aliases

const LEX_STRING sys_table_aliases[]
static
Initial value:
= {
{C_STRING_WITH_LEN("INNOBASE")},
{C_STRING_WITH_LEN("INNODB")},
{C_STRING_WITH_LEN("NDBCLUSTER")},
{C_STRING_WITH_LEN("HEAP")},
{C_STRING_WITH_LEN("MEMORY")},
{C_STRING_WITH_LEN("MERGE")},
{C_STRING_WITH_LEN("MRG_MYISAM")},
{NullS, 0}}
#define NullS
Definition of the null string (a null pointer of type char *), used in some of our string handling co...
Definition: m_string.h:49
#define C_STRING_WITH_LEN(X)
Definition: m_string.h:316

◆ total_ha_2pc

ulong total_ha_2pc = 0

◆ tx_isolation_names

const char* tx_isolation_names[]
Initial value:
= {"READ-UNCOMMITTED", "READ-COMMITTED",
"REPEATABLE-READ", "SERIALIZABLE", NullS}
#define NullS
Definition of the null string (a null pointer of type char *), used in some of our string handling co...
Definition: m_string.h:49

◆ tx_isolation_typelib

TYPELIB tx_isolation_typelib
Initial value:
Sergei Dialog Client Authentication NULL
Definition: dialog.cc:352
constexpr size_t array_elements(T(&)[N]) noexcept
Definition: my_macros.h:77
const char * tx_isolation_names[]
Definition: handler.cc:280