diff options
Diffstat (limited to 'scripts')
35 files changed, 19089 insertions, 0 deletions
diff --git a/scripts/CMakeLists.txt b/scripts/CMakeLists.txt new file mode 100644 index 00000000..923b3110 --- /dev/null +++ b/scripts/CMakeLists.txt @@ -0,0 +1,395 @@ +# Copyright (c) 2006, 2017, Oracle and/or its affiliates. +# Copyright (c) 2011, 2020, MariaDB Corporation +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +# Build comp_sql - used for embedding SQL in C or C++ programs + +MACRO(INSTALL_LINK old new destination component) + EXECUTE_PROCESS( + COMMAND ${CMAKE_COMMAND} -E create_symlink ${old} ${new} + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + ) + INSTALL( + PROGRAMS ${CMAKE_CURRENT_BINARY_DIR}/${new} + DESTINATION ${destination} + COMPONENT ${component} + ) +ENDMACRO() + +IF(NOT CMAKE_CROSSCOMPILING OR DEFINED CMAKE_CROSSCOMPILING_EMULATOR) + INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include) + ADD_EXECUTABLE(comp_sql comp_sql.c) + TARGET_LINK_LIBRARIES(comp_sql) +ENDIF() + +# Build mysql_fix_privilege_tables.sql (concatenate 3 sql scripts) +IF(NOT WIN32 OR (CMAKE_CROSSCOMPILING AND NOT DEFINED CMAKE_CROSSCOMPILING_EMULATOR)) + FIND_PROGRAM(CAT_EXECUTABLE cat DOC "path to the executable") + MARK_AS_ADVANCED(CAT_EXECUTABLE) +ENDIF() + +IF(CAT_EXECUTABLE) + SET(CAT_COMMAND COMMAND + ${CMAKE_COMMAND} -E chdir ${CMAKE_CURRENT_SOURCE_DIR} + ${CAT_EXECUTABLE} mysql_system_tables_fix.sql mysql_system_tables.sql mysql_performance_tables.sql > + ${CMAKE_CURRENT_BINARY_DIR}/mysql_fix_privilege_tables.sql + ) +ELSEIF(WIN32) + FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_BINARY_DIR}/mysql_fix_privilege_tables.sql + native_outfile ) + SET(CAT_COMMAND + COMMAND ${CMAKE_COMMAND} -E chdir ${CMAKE_CURRENT_SOURCE_DIR} + cmd /c copy /b mysql_system_tables_fix.sql + mysql_system_tables.sql + mysql_performance_tables.sql + ${native_outfile} ) +ELSE() + MESSAGE(FATAL_ERROR "Cannot concatenate files") +ENDIF() + +# Build mysql_fix_privilege_tables.c +ADD_CUSTOM_COMMAND( + OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/mysql_fix_privilege_tables_sql.c + ${CAT_COMMAND} + COMMAND comp_sql + mysql_fix_privilege_tables + mysql_fix_privilege_tables.sql + mysql_fix_privilege_tables_sql.c + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + DEPENDS comp_sql + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_system_tables.sql + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_system_tables_fix.sql + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_performance_tables.sql +) + +# Add target for the above to be built +ADD_CUSTOM_TARGET(GenFixPrivs + ALL + DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/mysql_fix_privilege_tables_sql.c +) + +IF(UNIX) + FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/make_binary_distribution + "cd ${CMAKE_BINARY_DIR} && '${CMAKE_CPACK_COMMAND}' -G TGZ --config CPackConfig.cmake\n" ) + EXECUTE_PROCESS( + COMMAND chmod +x ${CMAKE_CURRENT_BINARY_DIR}/make_binary_distribution +) +ENDIF() + +# Configure two scripts from one 'in' file. +# The maria_add_gis_sp.sql - to be sent to 'mysql' tool +# and the maria_add_gis_sp_bootstrap.sql, that can be sent to +# the server as a bootstrap command. + +SET(ADD_GIS_SP_SET_DELIMITER "delimiter |") +SET(ADD_GIS_SP_RESET_DELIMITER "delimiter ;") +SET(ADD_GIS_SP_EOL "|") +CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/maria_add_gis_sp.sql.in + ${CMAKE_CURRENT_BINARY_DIR}/maria_add_gis_sp.sql ESCAPE_QUOTES @ONLY) + +SET(ADD_GIS_SP_SET_DELIMITER "") +SET(ADD_GIS_SP_RESET_DELIMITER "") +SET(ADD_GIS_SP_EOL ";") +CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/maria_add_gis_sp.sql.in + ${CMAKE_CURRENT_BINARY_DIR}/maria_add_gis_sp_bootstrap.sql ESCAPE_QUOTES @ONLY) + +IF (NOT WITHOUT_SERVER) +INSTALL(FILES + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_system_tables.sql + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_system_tables_data.sql + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_performance_tables.sql + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_test_db.sql + ${CMAKE_CURRENT_SOURCE_DIR}/fill_help_tables.sql + ${CMAKE_CURRENT_SOURCE_DIR}/mysql_test_data_timezone.sql + ${CMAKE_CURRENT_BINARY_DIR}/maria_add_gis_sp.sql + ${CMAKE_CURRENT_BINARY_DIR}/maria_add_gis_sp_bootstrap.sql + ${FIX_PRIVILEGES_SQL} + DESTINATION ${INSTALL_MYSQLSHAREDIR} COMPONENT Server +) +ENDIF() + +# TCMalloc hacks +IF(MALLOC_LIB) + MESSAGE("Using tcmalloc '${MALLOC_LIB}'") + INSTALL(FILES ${MALLOC_LIB} DESTINATION ${INSTALL_LIBDIR} OPTIONAL) +ENDIF() + +IF(CMAKE_GENERATOR MATCHES "Makefiles|Ninja") + FOREACH(ARCH ${CMAKE_OSX_ARCHITECTURES}) + SET(CFLAGS "${CFLAGS} -arch ${ARCH}") + SET(CXXFLAGS "${CXXFLAGS} -arch ${ARCH}") + ENDFOREACH() +ENDIF() + +IF(CMAKE_SYSTEM_NAME MATCHES "FreeBSD") + SET (PERL_PATH "/usr/local/bin/perl") +ELSE() + SET (PERL_PATH "/usr/bin/perl") +ENDIF() + +IF(UNIX) + # FIND_PROC and CHECK_PID are used by mysqld_safe +IF(CMAKE_SYSTEM_NAME MATCHES "Linux") + SET (FIND_PROC + "ps wwwp $PID | grep -v mysqld_safe | grep -- $MYSQLD > /dev/null") +ENDIF() +IF(NOT FIND_PROC AND CMAKE_SYSTEM_NAME MATCHES "SunOS") + SET (FIND_PROC + "ps -p $PID | grep -v mysqld_safe | grep -- $MYSQLD > /dev/null") +ENDIF() + +IF(NOT FIND_PROC) + # BSD style + EXECUTE_PROCESS(COMMAND ps -uaxww OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE result) + IF(result MATCHES 0) + SET( FIND_PROC + "ps -uaxww | grep -v mysqld_safe | grep -- $MYSQLD | grep $PID > /dev/null") + ENDIF() +ENDIF() + +IF(NOT FIND_PROC) + # SysV style + EXECUTE_PROCESS(COMMAND ps -ef OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE result) + IF(result MATCHES 0) + SET( FIND_PROC "ps -ef | grep -v mysqld_safe | grep -- $MYSQLD | grep $PID > /dev/null") + ENDIF() +ENDIF() + +EXECUTE_PROCESS(COMMAND sh -c "kill -0 $$" OUTPUT_QUIET ERROR_QUIET RESULT_VARIABLE result) +IF(result MATCHES 0) + SET(CHECK_PID "kill -0 $PID > /dev/null 2> /dev/null") +ELSE() + SET(CHECK_PID "kill -s SIGCONT $PID > /dev/null 2> /dev/null") +ENDIF() + +SET(HOSTNAME "uname -n") +SET(MYSQLD_USER "mysql") +ENDIF(UNIX) + +# Really ugly, one script, "mysql_install_db", needs prefix set to ".", +# i.e. makes access relative the current directory. This matches +# the documentation, so better not change this. + +IF(INSTALL_LAYOUT MATCHES "STANDALONE") + SET(prefix ".") + SET(bindir ${prefix}/${INSTALL_BINDIR}) + SET(sbindir ${prefix}/${INSTALL_SBINDIR}) + SET(scriptdir ${prefix}/${INSTALL_BINDIR}) + SET(libexecdir ${prefix}/${INSTALL_SBINDIR}) + SET(pkgdatadir ${prefix}/${INSTALL_MYSQLSHAREDIR}) + SET(pkgplugindir ${prefix}/${INSTALL_PLUGINDIR}) + SET(localstatedir ${prefix}/data) +ELSE() + SET(prefix "${CMAKE_INSTALL_PREFIX}") + SET(bindir ${INSTALL_BINDIRABS}) + SET(sbindir ${INSTALL_SBINDIRABS}) + SET(scriptdir ${INSTALL_BINDIRABS}) + SET(libexecdir ${INSTALL_SBINDIRABS}) + SET(pkgdatadir ${INSTALL_MYSQLSHAREDIRABS}) + SET(pkgplugindir ${INSTALL_PLUGINDIRABS}) + SET(localstatedir ${MYSQL_DATADIR}) +ENDIF() + +SET(resolveip_locations "$basedir/${INSTALL_BINDIR} $basedir/bin") +SET(mysqld_locations "$basedir/${INSTALL_SBINDIR} $basedir/libexec $basedir/sbin $basedir/bin") +SET(errmsg_locations "$basedir/${INSTALL_MYSQLSHAREDIR}/english $basedir/share/english $basedir/share/mysql/english") +SET(pkgdata_locations "$basedir/${INSTALL_MYSQLSHAREDIR} $basedir/share $basedir/share/mysql") + +# install mysql_install_db.sh at this point since it needs +# different values for the above variables that will change +# afterwards +IF(UNIX) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/mysql_install_db.sh + ${CMAKE_CURRENT_BINARY_DIR}/mariadb-install-db ESCAPE_QUOTES @ONLY) + EXECUTE_PROCESS(COMMAND chmod +x ${CMAKE_CURRENT_BINARY_DIR}/mariadb-install-db) + INSTALL_SCRIPT( + "${CMAKE_CURRENT_BINARY_DIR}/mariadb-install-db" + DESTINATION ${INSTALL_SCRIPTDIR} + COMPONENT Server) + + INSTALL_LINK(mariadb-install-db mysql_install_db ${INSTALL_SCRIPTDIR} Server) +ENDIF() + +SET(prefix "${CMAKE_INSTALL_PREFIX}") +IF(INSTALL_SYSCONFDIR) + SET(sysconfdir ${DEFAULT_SYSCONFDIR}) +ELSE() + SET(sysconfdir "/etc") +ENDIF() +SET(bindir ${INSTALL_BINDIRABS}) +SET(libexecdir ${INSTALL_SBINDIRABS}) +SET(scriptdir ${INSTALL_BINDIRABS}) +SET(datadir ${INSTALL_MYSQLSHAREDIRABS}) +SET(pkgdatadir ${INSTALL_MYSQLSHAREDIRABS}) +SET(libsubdir ${INSTALL_LIBDIR}) +SET(pkgincludedir ${INSTALL_INCLUDEDIRABS}) +SET(pkglibdir ${INSTALL_LIBDIRABS}) +SET(pkgplugindir ${INSTALL_PLUGINDIRABS}) +SET(localstatedir ${MYSQL_DATADIR}) + +SET(RPATH_OPTION "") +IF(CMAKE_SYSTEM_NAME STREQUAL "SunOS") + SET(RPATH_OPTION "-R$pkglibdir") +ENDIF() + +# some scripts use @TARGET_LINUX@ +IF(CMAKE_SYSTEM_NAME MATCHES "Linux") + SET(TARGET_LINUX "true") +ELSE() + SET(TARGET_LINUX "false") +ENDIF() + +SET(mysql_config_COMPONENT Development) +SET(msql2mysql_COMPONENT Client) +SET(mariadb-access_COMPONENT Client) +SET(mariadb-find-rows_COMPONENT Client) +SET(mytop_COMPONENT Mytop) + +IF(WIN32) + # On Windows, some .sh and some .pl.in files are configured + # The resulting files will have .pl extension (those are perl scripts) + + # Input files with pl.in extension + SET(PLIN_FILES mysql_config) + # Input files with .sh extension + + SET(SH_FILES mysql_convert_table_format mysqld_multi mysqldumpslow + mysqlhotcopy) + + FOREACH(file ${PLIN_FILES}) + IF(NOT ${file}_COMPONENT) + SET(${file}_COMPONENT Server_Scripts) + ENDIF() + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${file}.pl.in + ${CMAKE_CURRENT_BINARY_DIR}/${file}.pl ESCAPE_QUOTES @ONLY) + INSTALL_SCRIPT(${CMAKE_CURRENT_BINARY_DIR}/${file}.pl COMPONENT ${${file}_COMPONENT}) + ENDFOREACH() + + FOREACH(file ${SH_FILES}) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${file}.sh + ${CMAKE_CURRENT_BINARY_DIR}/${file}.pl ESCAPE_QUOTES @ONLY) + INSTALL_SCRIPT(${CMAKE_CURRENT_BINARY_DIR}/${file}.pl COMPONENT Server_Scripts) + ENDFOREACH() +ELSE() + IF(WITH_WSREP) + SET(WSREP_SCRIPTS + wsrep_sst_mysqldump + wsrep_sst_rsync + wsrep_sst_mariabackup + ) + # The following script is sourced from other SST scripts, so it should + # not be made executable. + SET(WSREP_SOURCE + wsrep_sst_common + ) + + INSTALL_LINK(wsrep_sst_rsync wsrep_sst_rsync_wan ${INSTALL_BINDIR} Server) + FOREACH(file ${WSREP_SOURCE}) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${file}.sh + ${CMAKE_CURRENT_BINARY_DIR}/${file} ESCAPE_QUOTES @ONLY) + IF(NOT ${file}_COMPONENT) + SET(${file}_COMPONENT Server) + ENDIF() + INSTALL(FILES + ${CMAKE_CURRENT_BINARY_DIR}/${file} + DESTINATION ${INSTALL_BINDIR} + COMPONENT ${${file}_COMPONENT} + ) + ENDFOREACH() + ENDIF() + IF (NOT WITHOUT_SERVER) + SET(SERVER_SCRIPTS + mariadb-fix-extensions + mariadbd-multi + mariadbd-safe + mariadb-dumpslow + ) + ENDIF() + # Configure this one, for testing, but do not install it. + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/mysql_config.pl.in + ${CMAKE_CURRENT_BINARY_DIR}/mysql_config.pl ESCAPE_QUOTES @ONLY) + # On Unix, most of the files end up in the bin directory + SET(BIN_SCRIPTS + msql2mysql + mariadb-setpermission + mariadb-secure-installation + mariadb-access + mariadb-convert-table-format + mariadb-find-rows + mysql_config + mytop + mariadb-hotcopy + ${SERVER_SCRIPTS} + ${WSREP_SCRIPTS} + ${SYSTEMD_SCRIPTS} + ) + + FOREACH(file ${BIN_SCRIPTS}) + # set name of executable + GET_SYMLINK(${file} binname) + + if("${binname}" STREQUAL "") + set(binname ${file}) + endif() + + IF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${binname}.sh) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${binname}.sh + ${CMAKE_CURRENT_BINARY_DIR}/${file} ESCAPE_QUOTES @ONLY) + ELSEIF(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${binname}) + CONFIGURE_FILE(${CMAKE_CURRENT_SOURCE_DIR}/${binname} + ${CMAKE_CURRENT_BINARY_DIR}/${file} COPYONLY) + ELSE() + MESSAGE(FATAL_ERROR "Cannot find ${binname}.sh or ${binname} in " + "${CMAKE_CURRENT_SOURCE_DIR}" ) + ENDIF() + + IF(NOT ${file}_COMPONENT) + SET(${file}_COMPONENT Server) + ENDIF() + + # install script + INSTALL_SCRIPT( + ${CMAKE_CURRENT_BINARY_DIR}/${file} + DESTINATION ${INSTALL_BINDIR} + COMPONENT ${${file}_COMPONENT} + ) + + # make scripts executable in build dir + IF(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${binname}) + EXECUTE_PROCESS(COMMAND chmod +x ${CMAKE_CURRENT_BINARY_DIR}/${binname}) + ELSEIF(EXISTS ${CMAKE_CURRENT_BINARY_DIR}/${file}) + EXECUTE_PROCESS(COMMAND chmod +x ${CMAKE_CURRENT_BINARY_DIR}/${file}) + ENDIF() + + # Create symlink + IF (NOT ${binname} STREQUAL ${file}) + INSTALL_LINK(${file} ${binname} ${INSTALL_BINDIR} ${${file}_COMPONENT}) + ENDIF() + ENDFOREACH() +ENDIF() + +# Install libgcc as mylibgcc.a +IF(CMAKE_COMPILER_IS_GNUCXX AND CMAKE_CXX_FLAGS MATCHES "-static") + EXECUTE_PROCESS ( + COMMAND ${CMAKE_CXX_COMPILER} ${CMAKE_CXX_COMPILER_ARG1} + ${CMAKE_CXX_FLAGS} --print-libgcc + OUTPUT_VARIABLE LIBGCC_LOCATION + RESULT_VARIABLE RESULT + OUTPUT_STRIP_TRAILING_WHITESPACE + ERROR_QUIET + ) + IF(${RESULT} EQUAL 0 AND EXISTS ${LIBGCC_LOCATION}) + INSTALL(FILES "${LIBGCC_LOCATION}" DESTINATION ${INSTALL_LIBDIR} + COMPONENT Development) + ENDIF() +ENDIF() diff --git a/scripts/comp_sql.c b/scripts/comp_sql.c new file mode 100644 index 00000000..5cd5642c --- /dev/null +++ b/scripts/comp_sql.c @@ -0,0 +1,193 @@ +/* Copyright (c) 2004, 2010, Oracle and/or its affiliates. + Copyright (c) 2012, 2014, Monty Program Ab + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; version 2 of the License. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA */ + +/* + Originally written by Magnus Svensson +*/ + +/* + Converts a SQL file into a C file that can be compiled and linked + into other programs +*/ + +#include <my_config.h> +#include <stdarg.h> +#include <stdlib.h> +#include <stdio.h> + +/* + This is an internal tool used during the build process only, + - do not make a library just for this, + which would make the Makefiles and the server link + more complex than necessary, + - do not duplicate the code either. + so just add the sql_bootstrap.cc code as is. +*/ +#include "../sql/sql_bootstrap.cc" + +FILE *in, *out; + +static void die(const char *fmt, ...) +{ + va_list args; + + /* Print the error message */ + fprintf(stderr, "FATAL ERROR: "); + if (fmt) + { + va_start(args, fmt); + vfprintf(stderr, fmt, args); + va_end(args); + } + else + fprintf(stderr, "unknown error"); + fprintf(stderr, "\n"); + fflush(stderr); + + /* Close any open files */ + if (in) + fclose(in); + if (out) + fclose(out); + + exit(1); +} + +char *fgets_fn(char *buffer, size_t size, fgets_input_t input, int *error) +{ + char *line= fgets(buffer, (int)size, (FILE*) input); + if (error) + *error= (line == NULL) ? ferror((FILE*)input) : 0; + return line; +} + +#define MAX_COLUMN 16000 + +static void print_query(FILE *out, const char *query) +{ + const char *ptr= query; + int column= 0; + + fprintf(out, "\""); + while (*ptr) + { + if(column >= MAX_COLUMN) + { + /* Wrap to the next line, tabulated. */ + fprintf(out, "\"\n \""); + column= 2; + } + switch(*ptr) + { + case '\n': + /* + Preserve the \n character in the query text, + and wrap to the next line, tabulated. + */ + fprintf(out, "\\n\"\n \""); + column= 2; + break; + case '\r': + /* Skipped */ + break; + case '\"': + fprintf(out, "\\\""); + column+=2; + break; + case '\\': + fprintf(out, "\\\\"); + column+=2; + break; + default: + putc(*ptr, out); + column++; + break; + } + ptr++; + } + fprintf(out, "\\n\",\n"); +} + +int main(int argc, char *argv[]) +{ + char query[MAX_BOOTSTRAP_QUERY_SIZE]; + char* struct_name= argv[1]; + char* infile_name= argv[2]; + char* outfile_name= argv[3]; + int rc; + int query_length; + int error= 0; + char *err_ptr; + + if (argc != 4) + die("Usage: comp_sql <struct_name> <sql_filename> <c_filename>"); + + /* Open input and output file */ + if (!(in= fopen(infile_name, "r"))) + die("Failed to open SQL file '%s'", infile_name); + if (!(out= fopen(outfile_name, "w"))) + die("Failed to open output file '%s'", outfile_name); + + fprintf(out, "/*\n"); + fprintf(out, " Do not edit this file, it is automatically generated from:\n"); + fprintf(out, " <%s>\n", infile_name); + fprintf(out, "*/\n"); + fprintf(out, "#include <stdlib.h>\n"); /* NULL */ + fprintf(out, "const char* %s[]={\n", struct_name); + + for ( ; ; ) + { + rc= read_bootstrap_query(query, &query_length, + (fgets_input_t) in, fgets_fn, &error); + + if (rc == READ_BOOTSTRAP_EOF) + break; + + if (rc != READ_BOOTSTRAP_SUCCESS) + { + /* Get the most recent query text for reference. */ + err_ptr= query + (query_length <= MAX_BOOTSTRAP_ERROR_LEN ? + 0 : (query_length - MAX_BOOTSTRAP_ERROR_LEN)); + switch (rc) + { + case READ_BOOTSTRAP_ERROR: + die("Failed to read the bootstrap input file. Return code (%d).\n" + "Last query: '%s'\n", error, err_ptr); + break; + + case READ_BOOTSTRAP_QUERY_SIZE: + die("Failed to read the boostrap input file. Query size exceeded %d bytes.\n" + "Last query: '%s'.\n", MAX_BOOTSTRAP_LINE_SIZE, err_ptr); + break; + + default: + die("Failed to read the boostrap input file. Unknown error.\n"); + break; + } + } + + print_query(out, query); + } + + fprintf(out, "NULL\n};\n"); + + fclose(in); + fclose(out); + + exit(0); + +} + diff --git a/scripts/convert-debug-for-diff.sh b/scripts/convert-debug-for-diff.sh new file mode 100755 index 00000000..5b3ce05b --- /dev/null +++ b/scripts/convert-debug-for-diff.sh @@ -0,0 +1,25 @@ +#!/usr/bin/perl -i +# +# This script converts all numbers that look like addresses or memory sizes, +# in a debug files generated by --debug (like mysqld --debug-dbug), to #. +# The script also deletes all thread id's from the start of the line. + +# This allows you to easily compare the files (for example with diff) +# to find out what changes between different executions. +# This is extremely useful for comparing two mysqld versions to see +# why things now work differently. + +# The script converts the files in place. +# +# Typical usage: +# +# convert-debug-for-diff /tmp/mysqld.trace /tmp/mysqld-old.trace +# diff /tmp/mysqld.trace /tmp/mysqld-old.trace + +while (<>) +{ + s/^T@[0-9]+\s*://g; + s/0x[0-9a-f]+(\s|\n|\))/#$1/g; + s/size: [0-9]+/size: #/g; + print $_; +} diff --git a/scripts/dheadgen.pl b/scripts/dheadgen.pl new file mode 100644 index 00000000..69ece2e7 --- /dev/null +++ b/scripts/dheadgen.pl @@ -0,0 +1,332 @@ +# Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. +# * Neither the name of the above-listed copyright holders nor the names +# of its contributors may be used to endorse or promote products derived +# from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS +# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED +# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A +# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER +# OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, +# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, +# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ident "@(#)dheadgen.pl 1.4 07/06/24 SMI" + +# +# DTrace Header Generator +# ----------------------- +# +# This script is meant to mimic the output of dtrace(1M) with the -h +# (headergen) flag on system that lack native support for DTrace. This script +# is intended to be integrated into projects that use DTrace's static tracing +# facilities (USDT), and invoked as part of the build process to have a +# common build process on all target systems. To facilitate this, this script +# is licensed under a BSD license. On system with native DTrace support, the +# dtrace(1M) command will be invoked to create the full header file; on other +# systems, this script will generated a stub header file. +# +# Normally, generated macros take the form PROVIDER_PROBENAME(). It may be +# desirable to customize the output of this script and of dtrace(1M) to +# tailor the precise macro name. To do this, edit the emit_dtrace() subroutine +# to pattern match for the lines you want to customize. +# + +use strict; + +my @lines; +my @tokens = (); +my $lineno = 0; +my $newline = 1; +my $eof = 0; +my $infile; +my $outfile; +my $force = 0; + +sub emit_dtrace { + my ($line) = @_; + + # + # Insert customization here. For example, if you want to change the + # name of the macros you may do something like this: + # + # $line =~ s/(\s)[A-Z]+_/\1TRACE_MOZILLA_/; + # + + print $line; +} + +# +# The remaining code deals with parsing D provider definitions and emitting +# the stub header file. There should be no need to edit this absent a bug. +# + +# +# Emit the two relevant macros for each probe in the given provider: +# PROVIDER_PROBENAME(<args>) +# PROVIDER_PROBENAME_ENABLED() (0) +# +sub emit_provider { + my ($provname, @probes) = @_; + + $provname = uc($provname); + + foreach my $probe (@probes) { + my $probename = uc($$probe{'name'}); + my $argc = $$probe{'argc'}; + my $line; + + $probename =~ s/__/_/g; + + $line = "#define\t${provname}_${probename}("; + for (my $i = 0; $i < $argc; $i++) { + $line .= ($i == 0 ? '' : ', '); + $line .= "arg$i"; + } + $line .= ")\n"; + emit_dtrace($line); + + $line = "#define\t${provname}_${probename}_ENABLED() (0)\n"; + emit_dtrace($line); + } + + emit_dtrace("\n"); +} + +sub emit_prologue { + my ($filename) = @_; + + $filename =~ s/.*\///g; + $filename = uc($filename); + $filename =~ s/\./_/g; + + emit_dtrace <<"EOF"; +/* + * Generated by dheadgen(1). + */ + +#ifndef\t_${filename} +#define\t_${filename} + +#ifdef\t__cplusplus +extern "C" { +#endif + +EOF +} + +sub emit_epilogue { + my ($filename) = @_; + + $filename =~ s/.*\///g; + $filename = uc($filename); + $filename =~ s/\./_/g; + + emit_dtrace <<"EOF"; +#ifdef __cplusplus +} +#endif + +#endif /* _$filename */ +EOF +} + +# +# Get the next token from the file keeping track of the line number. +# +sub get_token { + my ($eof_ok) = @_; + my $tok; + + while (1) { + while (scalar(@tokens) == 0) { + if (scalar(@lines) == 0) { + $eof = 1; + return if ($eof_ok); + die "expected more data at line $lineno"; + } + + $lineno++; + push(@tokens, split(/(\s+|\n|[(){},#;]|\/\*|\*\/)/, + shift(@lines))); + } + + $tok = shift(@tokens); + next if ($tok eq ''); + next if ($tok =~ /^[ \t]+$/); + + return ($tok); + } +} + +# +# Ignore newlines, comments and typedefs +# +sub next_token { + my ($eof_ok) = @_; + my $tok; + + while (1) { + $tok = get_token($eof_ok); + return if ($eof_ok && $eof); + if ($tok eq "typedef" or $tok =~ /^#/) { + while (1) { + $tok = get_token(0); + last if ($tok eq "\n"); + } + next; + } elsif ($tok eq '/*') { + while (get_token(0) ne '*/') { + next; + } + next; + } elsif ($tok eq "\n") { + next; + } + + last; + } + + return ($tok); +} + +sub expect_token { + my ($t) = @_; + my $tok; + + while (($tok = next_token(0)) eq "\n") { + next; + } + + die "expected '$t' at line $lineno rather than '$tok'" if ($t ne $tok); +} + +sub get_args { + expect_token('('); + + my $tok = next_token(0); + my @args = (); + + return (@args) if ($tok eq ')'); + + if ($tok eq 'void') { + expect_token(')'); + return (@args); + } + + my $arg = $tok; + + while (1) { + $tok = next_token(0); + if ($tok eq ',' || $tok eq ')') { + push(@args, $arg); + $arg = ''; + last if ($tok eq ')'); + } else { + $arg = "$arg $tok"; + } + } + + return (@args); +} + +sub usage { + die "usage: $0 [-f] <filename.d>\n"; +} + +usage() if (scalar(@ARGV) < 1); +if ($ARGV[0] eq '-f') { + usage() if (scalar(@ARGV < 2)); + $force = 1; + shift; +} +$infile = $ARGV[0]; +usage() if ($infile !~ /(.+)\.d$/); + +# +# If the system has native support for DTrace, we'll use that binary instead. +# +if (-x '/usr/sbin/dtrace' && !$force) { + open(DTRACE, "-| /usr/sbin/dtrace -C -h -s $infile -o /dev/stdout") + or die "can't invoke dtrace(1M)"; + + while (<DTRACE>) { + emit_dtrace($_); + } + + close(DTRACE); + + exit(0); +} + +emit_prologue($infile); + +open(D, "< $infile") or die "couldn't open $infile"; +@lines = <D>; +close(D); + +while (1) { + my $nl = 0; + my $tok = next_token(1); + last if $eof; + + if ($newline && $tok eq '#') { + while (1) { + $tok = get_token(0); + + last if ($tok eq "\n"); + } + $nl = 1; + } elsif ($tok eq "\n") { + $nl = 1; + } elsif ($tok eq 'provider') { + my $provname = next_token(0); + my @probes = (); + expect_token('{'); + + while (1) { + $tok = next_token(0); + if ($tok eq 'probe') { + my $probename = next_token(0); + my @args = get_args(); + + next while (next_token(0) ne ';'); + + push(@probes, { + 'name' => $probename, + 'argc' => scalar(@args) + }); + + } elsif ($tok eq '}') { + expect_token(';'); + + emit_provider($provname, @probes); + + last; + } + } + + } else { + die "syntax error at line $lineno near '$tok'\n"; + } + + $newline = $nl; +} + +emit_epilogue($infile); + +exit(0); diff --git a/scripts/fill_help_tables.sql b/scripts/fill_help_tables.sql new file mode 100644 index 00000000..d0efb750 --- /dev/null +++ b/scripts/fill_help_tables.sql @@ -0,0 +1,873 @@ + +-- Copyright (c) 2003, 2008-2012, 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 +-- the Free Software Foundation; version 2 of the License. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +-- DO NOT EDIT THIS FILE. It is generated automatically. + +-- To use this file, load its contents into the mysql database. For example, +-- with the mysql client program, process the file like this, where +-- file_name is the name of this file: + +-- mysql -u root -p mysql < file_name + +set names 'utf8'; + +set sql_log_bin = 0; + +use mysql; +delete from help_topic; +delete from help_category; +delete from help_keyword; +delete from help_relation; + +lock tables help_topic write, help_category write, help_keyword write, help_relation write; +insert into help_category (help_category_id,name,parent_category_id,url) values (1,'Geographic',0,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (2,'Polygon Properties',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (3,'WKT',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (4,'Numeric Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (5,'Plugins',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (6,'MBR',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (7,'Control Flow Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (8,'Transactions',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (9,'Help Metadata',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (10,'Account Management',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (11,'Point Properties',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (12,'Encryption Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (13,'LineString Properties',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (14,'Miscellaneous Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (15,'Logical Operators',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (16,'Functions and Modifiers for Use with GROUP BY',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (17,'Information Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (18,'Comparison Operators',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (19,'Bit Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (20,'Table Maintenance',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (21,'User-Defined Functions',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (22,'Data Types',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (23,'Compound Statements',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (24,'Geometry Constructors',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (25,'GeometryCollection Properties',1,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (26,'Administration',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (27,'Data Manipulation',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (28,'Utility',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (29,'Language Structure',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (30,'Geometry Relations',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (31,'Date and Time Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (32,'WKB',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (33,'Procedures',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (34,'Geographic Features',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (35,'Contents',0,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (36,'Geometry Properties',34,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (37,'String Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (38,'Functions',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (39,'Data Definition',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (40,'Sequences',35,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (41,'JSON Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (42,'Window Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (43,'Spider Functions',38,''); +insert into help_category (help_category_id,name,parent_category_id,url) values (44,'Dynamic Column Functions',38,''); + +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (1,9,'HELP_DATE','This help information was generated from the MariaDB Knowledge Base\non 22 July 2019.','',''); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (2,2,'AREA','A synonym for ST_AREA.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/polygon-properties-area/','','https://mariadb.com/kb/en/library/polygon-properties-area/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (3,2,'CENTROID','A synonym for ST_CENTROID.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/centroid/','','https://mariadb.com/kb/en/library/centroid/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (4,2,'ExteriorRing','A synonym for ST_ExteriorRing.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/polygon-properties-exteriorring/','','https://mariadb.com/kb/en/library/polygon-properties-exteriorring/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (5,2,'InteriorRingN','A synonym for ST_InteriorRingN.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/polygon-properties-interiorringn/','','https://mariadb.com/kb/en/library/polygon-properties-interiorringn/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (6,2,'NumInteriorRings','A synonym for ST_NumInteriorRings.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/polygon-properties-numinteriorrings/','','https://mariadb.com/kb/en/library/polygon-properties-numinteriorrings/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (7,2,'ST_AREA','Syntax\n------ \nST_Area(poly)\nArea(poly)\n \nDescription\n----------- \nReturns as a double-precision number the area of the Polygon\nvalue poly, as measured in its spatial reference system.\n \nST_Area() and Area() are synonyms.\n \nExamples\n-------- \nSET @poly = \'Polygon((0 0,0 3,3 0,0 0),(1 1,1 2,2 1,1\n1))\';\n \nSELECT Area(GeomFromText(@poly));\n+---------------------------+\n| Area(GeomFromText(@poly)) |\n+---------------------------+\n| 4 |\n+---------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_area/','','https://mariadb.com/kb/en/library/st_area/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (8,2,'ST_CENTROID','Syntax\n------ \nST_Centroid(mpoly)\nCentroid(mpoly)\n \nDescription\n----------- \nReturns a point reflecting the mathematical centroid\n(geometric center) for the MultiPolygon mpoly. The resulting\npoint will not necessarily be on the MultiPolygon. \n \nST_Centroid() and Centroid() are synonyms.\n \nExamples\n-------- \nSET @poly = ST_GeomFromText(\'POLYGON((0 0,20 0,20 20,0 20,0\n0))\');\nSELECT ST_AsText(ST_Centroid(@poly)) AS center;\n \n+--------------+\n| center |\n+--------------+\n| POINT(10 10) |\n+--------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_centroid/','','https://mariadb.com/kb/en/library/st_centroid/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (9,2,'ST_ExteriorRing','Syntax\n------ \nST_ExteriorRing(poly)\nExteriorRing(poly)\n \nDescription\n----------- \nReturns the exterior ring of the Polygon value poly as a\nLineString.\n \nST_ExteriorRing() and ExteriorRing() are synonyms.\n \nExamples\n-------- \nSET @poly = \'Polygon((0 0,0 3,3 3,3 0,0 0),(1 1,1 2,2 2,2\n1,1 1))\';\n \nSELECT AsText(ExteriorRing(GeomFromText(@poly)));\n+-------------------------------------------+\n| AsText(ExteriorRing(GeomFromText(@poly))) |\n+-------------------------------------------+\n| LINESTRING(0 0,0 3,3 3,3 0,0 0) |\n+-------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_exteriorring/','','https://mariadb.com/kb/en/library/st_exteriorring/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (10,2,'ST_InteriorRingN','Syntax\n------ \nST_InteriorRingN(poly,N)\nInteriorRingN(poly,N)\n \nDescription\n----------- \nReturns the N-th interior ring for the Polygon value poly as\na LineString. Rings are numbered beginning with 1.\n \nST_InteriorRingN() and InteriorRingN() are synonyms.\n \nExamples\n-------- \nSET @poly = \'Polygon((0 0,0 3,3 3,3 0,0 0),(1 1,1 2,2 2,2\n1,1 1))\';\n \nSELECT AsText(InteriorRingN(GeomFromText(@poly),1));\n+----------------------------------------------+\n| AsText(InteriorRingN(GeomFromText(@poly),1)) |\n+----------------------------------------------+\n| LINESTRING(1 1,1 2,2 2,2 1,1 1) |\n+----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_interiorringn/','','https://mariadb.com/kb/en/library/st_interiorringn/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (11,2,'ST_NumInteriorRings','Syntax\n------ \nST_NumInteriorRings(poly)\nNumInteriorRings(poly)\n \nDescription\n----------- \nReturns an integer containing the number of interior rings\nin the Polygon value poly.\n \nNote that according the the OpenGIS standard, a POLYGON\nshould have exactly one ExteriorRing and all other rings\nshould lie within that ExteriorRing and thus be the\nInteriorRings. Practically, however, some systems, including\nMariaDB\'s, permit polygons to have several\n\'ExteriorRings\'. In the case of there being multiple,\nnon-overlapping exterior rings ST_NumInteriorRings() will\nreturn 1.\n \nST_NumInteriorRings() and NumInteriorRings() are synonyms.\n \nExamples\n-------- \nSET @poly = \'Polygon((0 0,0 3,3 3,3 0,0 0),(1 1,1 2,2 2,2\n1,1 1))\';\n \nSELECT NumInteriorRings(GeomFromText(@poly));\n+---------------------------------------+\n| NumInteriorRings(GeomFromText(@poly)) |\n+---------------------------------------+\n| 1 |\n+---------------------------------------+\n \nNon-overlapping \'polygon\':\n \nSELECT ST_NumInteriorRings(ST_PolyFromText(\'POLYGON((0 0,10\n0,10 10,0 10,0 0),\n (-1 -1,-5 -1,-5 -5,-1 -5,-1 -1))\')) AS NumInteriorRings;\n \n+------------------+\n| NumInteriorRings |\n+------------------+\n| 1 |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_numinteriorrings/','','https://mariadb.com/kb/en/library/st_numinteriorrings/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (12,3,'WKT Definition','Description\n----------- \nThe Well-Known Text (WKT) representation of Geometry is\ndesigned to exchange geometry data in ASCII form. Examples\nof the basic geometry types include:\n \nGeometry Types | \n \nPOINT | \n \nLINESTRING | \n \nPOLYGON | \n \nMULTIPOINT | \n \nMULTILINESTRING | \n \nMULTIPOLYGON | \n \nGEOMETRYCOLLECTION | \n \nGEOMETRY | \n \n\n\nURL: https://mariadb.com/kb/en/library/wkt-definition/','','https://mariadb.com/kb/en/library/wkt-definition/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (13,3,'AsText','A synonym for ST_AsText().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkt-astext/','','https://mariadb.com/kb/en/library/wkt-astext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (14,3,'AsWKT','A synonym for ST_AsText().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkt-aswkt/','','https://mariadb.com/kb/en/library/wkt-aswkt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (15,3,'GeomCollFromText','A synonym for ST_GeomCollFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkt-geomcollfromtext/','','https://mariadb.com/kb/en/library/wkt-geomcollfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (16,3,'GeometryCollectionFromText','A synonym for ST_GeomCollFromText.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometrycollectionfromtext/','','https://mariadb.com/kb/en/library/geometrycollectionfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (17,3,'GeometryFromText','A synonym for ST_GeomFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/geometryfromtext/','','https://mariadb.com/kb/en/library/geometryfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (18,3,'GeomFromText','A synonym for ST_GeomFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkt-geomfromtext/','','https://mariadb.com/kb/en/library/wkt-geomfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (19,3,'LineFromText','A synonym for ST_LineFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkt-linefromtext/','','https://mariadb.com/kb/en/library/wkt-linefromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (20,3,'LineStringFromText','A synonym for ST_LineFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/linestringfromtext/','','https://mariadb.com/kb/en/library/linestringfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (21,3,'MLineFromText','Syntax\n------ \nMLineFromText(wkt[,srid])\nMultiLineStringFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a MULTILINESTRING value using its WKT\nrepresentation and SRID.\n \nMLineFromText() and MultiLineStringFromText() are synonyms.\n \nExamples\n-------- \nCREATE TABLE gis_multi_line (g MULTILINESTRING);\nSHOW FIELDS FROM gis_multi_line;\n \nINSERT INTO gis_multi_line VALUES\n (MultiLineStringFromText(\'MULTILINESTRING((10 48,10 21,10\n0),(16 0,16 23,16 48))\')),\n (MLineFromText(\'MULTILINESTRING((10 48,10 21,10 0))\')),\n (MLineFromWKB(AsWKB(MultiLineString(LineString(Point(1, 2),\nPoint(3, 5)), LineString(Point(2, 5), Point(5, 8), Point(21,\n7))))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mlinefromtext/','','https://mariadb.com/kb/en/library/mlinefromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (22,3,'MPointFromText','Syntax\n------ \nMPointFromText(wkt[,srid])\nMultiPointFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a MULTIPOINT value using its WKT representation\nand SRID.\n \nMPointFromText() and MultiPointFromText() are synonyms.\n \nExamples\n-------- \nCREATE TABLE gis_multi_point (g MULTIPOINT);\nSHOW FIELDS FROM gis_multi_point;\n \nINSERT INTO gis_multi_point VALUES\n (MultiPointFromText(\'MULTIPOINT(0 0,10 10,10 20,20\n20)\')),\n (MPointFromText(\'MULTIPOINT(1 1,11 11,11 21,21 21)\')),\n (MPointFromWKB(AsWKB(MultiPoint(Point(3, 6), Point(4,\n10)))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mpointfromtext/','','https://mariadb.com/kb/en/library/mpointfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (23,3,'MPolyFromText','Syntax\n------ \nMPolyFromText(wkt[,srid])\nMultiPolygonFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a MULTIPOLYGON value using its WKT representation\nand SRID.\n \nMPolyFromText() and MultiPolygonFromText() are synonyms.\n \nExamples\n-------- \nCREATE TABLE gis_multi_polygon (g MULTIPOLYGON);\nSHOW FIELDS FROM gis_multi_polygon;\n \nINSERT INTO gis_multi_polygon VALUES\n (MultiPolygonFromText(\'MULTIPOLYGON(((28 26,28 0,84 0,84\n42,28 26),(52 18,66 23,73 9,48 6,52 18)),((59 18,67 18,67\n13,59 13,59 18)))\')),\n (MPolyFromText(\'MULTIPOLYGON(((28 26,28 0,84 0,84 42,28\n26),(52 18,66 23,73 9,48 6,52 18)),((59 18,67 18,67 13,59\n13,59 18)))\')),\n (MPolyFromWKB(AsWKB(MultiPolygon(Polygon(LineString(Point(0,\n3), Point(3, 3), Point(3, 0), Point(0, 3)))))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mpolyfromtext/','','https://mariadb.com/kb/en/library/mpolyfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (24,3,'MultiLineStringFromText','A synonym for MLineFromText.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/multilinestringfromtext/','','https://mariadb.com/kb/en/library/multilinestringfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (25,3,'MultiPointFromText','A synonym for MPointFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/multipointfromtext/','','https://mariadb.com/kb/en/library/multipointfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (26,3,'MultiPolygonFromText','A synonym for MPolyFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/multipolygonfromtext/','','https://mariadb.com/kb/en/library/multipolygonfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (27,3,'PointFromText','A synonym for ST_PointFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkt-pointfromtext/','','https://mariadb.com/kb/en/library/wkt-pointfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (28,3,'PolyFromText','A synonym for ST_PolyFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkt-polyfromtext/','','https://mariadb.com/kb/en/library/wkt-polyfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (29,3,'PolygonFromText','A synonym for ST_PolyFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/polygonfromtext/','','https://mariadb.com/kb/en/library/polygonfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (30,3,'ST_AsText','Syntax\n------ \nST_AsText(g)\nAsText(g)\nST_AsWKT(g)\nAsWKT(g)\n \nDescription\n----------- \nConverts a value in internal geometry format to its WKT\nrepresentation and returns the string result.\n \nST_AsText(), AsText(), ST_AsWKT() and AsWKT() are all\nsynonyms.\n \nExamples\n-------- \nSET @g = \'LineString(1 1,4 4,6 6)\';\n \nSELECT ST_AsText(ST_GeomFromText(@g));\n+--------------------------------+\n| ST_AsText(ST_GeomFromText(@g)) |\n+--------------------------------+\n| LINESTRING(1 1,4 4,6 6) |\n+--------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_astext/','','https://mariadb.com/kb/en/library/st_astext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (31,3,'ST_ASWKT','A synonym for ST_ASTEXT().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_aswkt/','','https://mariadb.com/kb/en/library/st_aswkt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (32,3,'ST_GeomCollFromText','Syntax\n------ \nST_GeomCollFromText(wkt[,srid])\nST_GeometryCollectionFromText(wkt[,srid])\nGeomCollFromText(wkt[,srid])\nGeometryCollectionFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a GEOMETRYCOLLECTION value using its WKT \nrepresentation and SRID.\n \nST_GeomCollFromText(), ST_GeometryCollectionFromText(),\nGeomCollFromText() and GeometryCollectionFromText() are all\nsynonyms.\n \nExample\n \nCREATE TABLE gis_geometrycollection (g GEOMETRYCOLLECTION);\nSHOW FIELDS FROM gis_geometrycollection;\n \nINSERT INTO gis_geometrycollection VALUES\n (GeomCollFromText(\'GEOMETRYCOLLECTION(POINT(0 0),\nLINESTRING(0 0,10 10))\')),\n (GeometryFromWKB(AsWKB(GeometryCollection(Point(44, 6),\nLineString(Point(3, 6), Point(7, 9)))))),\n (GeomFromText(\'GeometryCollection()\')),\n (GeomFromText(\'GeometryCollection EMPTY\'));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geomcollfromtext/','','https://mariadb.com/kb/en/library/st_geomcollfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (33,3,'ST_GeometryCollectionFromText','A synonym for ST_GeomCollFromText.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/st_geometrycollectionfromtext/','','https://mariadb.com/kb/en/library/st_geometrycollectionfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (34,3,'ST_GeometryFromText','A synonym for ST_GeomFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geometryfromtext/','','https://mariadb.com/kb/en/library/st_geometryfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (35,3,'ST_GeomFromText','Syntax\n------ \nST_GeomFromText(wkt[,srid])\nST_GeometryFromText(wkt[,srid])\nGeomFromText(wkt[,srid])\nGeometryFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a geometry value of any type using its WKT\nrepresentation and SRID.\n \nGeomFromText(), GeometryFromText(), ST_GeomFromText() and\nST_GeometryFromText() are all synonyms.\n \nExample\n \nSET @g = ST_GEOMFROMTEXT(\'POLYGON((1 1,1 5,4 9,6 9,9 3,7\n2,1 1))\');\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geomfromtext/','','https://mariadb.com/kb/en/library/st_geomfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (36,3,'ST_LineFromText','Syntax\n------ \nST_LineFromText(wkt[,srid])\nST_LineStringFromText(wkt[,srid])\nLineFromText(wkt[,srid])\nLineStringFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a LINESTRING value using its WKT representation\nand SRID.\n \nST_LineFromText(), ST_LineStringFromText(),\nST_LineFromText() and ST_LineStringFromText() are all\nsynonyms.\n \nExamples\n-------- \nCREATE TABLE gis_line (g LINESTRING);\nSHOW FIELDS FROM gis_line;\n \nINSERT INTO gis_line VALUES\n (LineFromText(\'LINESTRING(0 0,0 10,10 0)\')),\n (LineStringFromText(\'LINESTRING(10 10,20 10,20 20,10 20,10\n10)\')),\n (LineStringFromWKB(AsWKB(LineString(Point(10, 10),\nPoint(40, 10)))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_linefromtext/','','https://mariadb.com/kb/en/library/st_linefromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (37,3,'ST_LineStringFromText','A synonym for ST_LineFromText.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/st_linestringfromtext/','','https://mariadb.com/kb/en/library/st_linestringfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (38,3,'ST_PointFromText','Syntax\n------ \nST_PointFromText(wkt[,srid])\nPointFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a POINT value using its WKT representation and\nSRID.\n \nST_PointFromText() and PointFromText() are synonyms.\n \nExamples\n-------- \nCREATE TABLE gis_point (g POINT);\nSHOW FIELDS FROM gis_point;\n \nINSERT INTO gis_point VALUES\n (PointFromText(\'POINT(10 10)\')),\n (PointFromText(\'POINT(20 10)\')),\n (PointFromText(\'POINT(20 20)\')),\n (PointFromWKB(AsWKB(PointFromText(\'POINT(10 20)\'))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_pointfromtext/','','https://mariadb.com/kb/en/library/st_pointfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (39,3,'ST_PolyFromText','Syntax\n------ \nST_PolyFromText(wkt[,srid])\nST_PolygonFromText(wkt[,srid])\nPolyFromText(wkt[,srid])\nPolygonFromText(wkt[,srid])\n \nDescription\n----------- \nConstructs a POLYGON value using its WKT representation and\nSRID.\n \nST_PolyFromText(), ST_PolygonFromText(), PolyFromText() and\nST_PolygonFromText() are all synonyms.\n \nExamples\n-------- \nCREATE TABLE gis_polygon (g POLYGON);\nINSERT INTO gis_polygon VALUES\n (PolygonFromText(\'POLYGON((10 10,20 10,20 20,10 20,10\n10))\')),\n (PolyFromText(\'POLYGON((0 0,50 0,50 50,0 50,0 0), (10\n10,20 10,20 20,10 20,10 10))\'));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_polyfromtext/','','https://mariadb.com/kb/en/library/st_polyfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (40,3,'ST_PolygonFromText','A synonym for ST_PolyFromText.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_polygonfromtext/','','https://mariadb.com/kb/en/library/st_polygonfromtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (41,4,'Addition Operator (+)','Syntax\n------ \n+\n \nDescription\n----------- \nAddition.\n \nIf both operands are integers, the result is calculated with\nBIGINT precision. If either integer is unsigned, the result\nis also an unsigned integer.\n \nFor real or string operands, the operand with the highest\nprecision determines the result precision.\n \nExamples\n-------- \nSELECT 3+5;\n \n+-----+\n| 3+5 |\n+-----+\n| 8 |\n+-----+\n \n\n\nURL: https://mariadb.com/kb/en/library/addition-operator/','','https://mariadb.com/kb/en/library/addition-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (42,4,'Subtraction Operator (-)','Syntax\n------ \n-\n \nDescription\n----------- \nSubtraction. The operator is also used as the unary minus\nfor changing sign.\n \nIf both operands are integers, the result is calculated with\nBIGINT precision. If either integer is unsigned, the result\nis also an unsigned integer, unless the\nNO_UNSIGNED_SUBTRACTION SQL_MODE is enabled, in which case\nthe result is always signed.\n \nFor real or string operands, the operand with the highest\nprecision determines the result precision.\n \nExamples\n-------- \nSELECT 96-9;\n \n+------+\n| 96-9 |\n+------+\n| 87 |\n+------+\n \nSELECT 15-17;\n \n+-------+\n| 15-17 |\n+-------+\n| -2 |\n+-------+\n \nSELECT 3.66 + 1.333;\n \n+--------------+\n| 3.66 + 1.333 |\n+--------------+\n| 4.993 |\n+--------------+\n \nUnary minus:\n \n SELECT - (3+5);\n+---------+\n| - (3+5) |\n+---------+\n| -8 |\n+---------+\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/subtraction-operator-/','','https://mariadb.com/kb/en/library/subtraction-operator-/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (43,4,'Division Operator (/)','Syntax\n------ \n/\n \nDescription\n----------- \nDivision operator. Dividing by zero will return NULL. By\ndefault, returns four digits after the decimal. This is\ndetermined by the server system variable\ndiv_precision_increment which by default is four. It can be\nset from 0 to 30.\n \nDividing by zero returns NULL. If the\nERROR_ON_DIVISION_BY_ZERO SQL_MODE is used (the default\nsince MariaDB 10.2.4), a division by zero also produces a\nwarning.\n \nExamples\n-------- \nSELECT 4/5;\n \n+--------+\n| 4/5 |\n+--------+\n| 0.8000 |\n+--------+\n \nSELECT 300/(2-2);\n+-----------+\n| 300/(2-2) |\n+-----------+\n| NULL |\n+-----------+\n \nSELECT 300/7;\n \n+---------+\n| 300/7 |\n+---------+\n| 42.8571 |\n+---------+\n \nChanging div_precision_increment for the session from the\ndefault of four to six:\n \nSET div_precision_increment = 6;\n \nSELECT 300/7;\n \n+-----------+\n| 300/7 |\n+-----------+\n| 42.857143 |\n+-----------+\n \nSELECT 300/7;\n \n+-----------+\n| 300/7 |\n+-----------+\n| 42.857143 |\n+-----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/division-operator/','','https://mariadb.com/kb/en/library/division-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (44,4,'Multiplication Operator (*)','Syntax\n------ \n*\n \nDescription\n----------- \nMultiplication operator.\n \nExamples\n-------- \nSELECT 7*6;\n \n+-----+\n| 7*6 |\n+-----+\n| 42 |\n+-----+\n \nSELECT 1234567890*9876543210;\n \n+-----------------------+\n| 1234567890*9876543210 |\n+-----------------------+\n| -6253480962446024716 |\n+-----------------------+\n \nSELECT 18014398509481984*18014398509481984.0;\n \n+---------------------------------------+\n| 18014398509481984*18014398509481984.0 |\n+---------------------------------------+\n| 324518553658426726783156020576256.0 |\n+---------------------------------------+\n \nSELECT 18014398509481984*18014398509481984;\n \n+-------------------------------------+\n| 18014398509481984*18014398509481984 |\n+-------------------------------------+\n| 0 |\n+-------------------------------------+\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/multiplication-operator/','','https://mariadb.com/kb/en/library/multiplication-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (45,4,'Modulo Operator (%)','Syntax\n------ \nN % M\n \nDescription\n----------- \nModulo operator. Returns the remainder of N divided by M.\nSee also MOD.\n \nExamples\n-------- \nSELECT 1042 % 50;\n \n+-----------+\n| 1042 % 50 |\n+-----------+\n| 42 |\n+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/modulo-operator/','','https://mariadb.com/kb/en/library/modulo-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (46,4,'DIV','Syntax\n------ \nDIV\n \nDescription\n----------- \nInteger division. Similar to FLOOR(), but is safe with\nBIGINT values.\nIncorrect results may occur for non-integer operands that\nexceed BIGINT range.\n \nIf the ERROR_ON_DIVISION_BY_ZERO SQL_MODE is used, a\ndivision by zero produces an error. Otherwise, it returns\nNULL.\n \nThe remainder of a division can be obtained using the MOD\noperator.\n \nExamples\n-------- \nSELECT 300 DIV 7;\n \n+-----------+\n| 300 DIV 7 |\n+-----------+\n| 42 |\n+-----------+\n \nSELECT 300 DIV 0;\n \n+-----------+\n| 300 DIV 0 |\n+-----------+\n| NULL |\n+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/div/','','https://mariadb.com/kb/en/library/div/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (47,4,'ABS','Syntax\n------ \nABS(X)\n \nDescription\n----------- \nReturns the absolute (non-negative) value of X. If X is not\na number, it is converted to a numeric type.\n \nExamples\n-------- \nSELECT ABS(42);\n+---------+\n| ABS(42) |\n+---------+\n| 42 |\n+---------+\n \nSELECT ABS(-42);\n+----------+\n| ABS(-42) |\n+----------+\n| 42 |\n+----------+\n \nSELECT ABS(DATE \'1994-01-01\');\n+------------------------+\n| ABS(DATE \'1994-01-01\') |\n+------------------------+\n| 19940101 |\n+------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/abs/','','https://mariadb.com/kb/en/library/abs/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (48,4,'ACOS','Syntax\n------ \nACOS(X)\n \nDescription\n----------- \nReturns the arc cosine of X, that is, the value whose cosine\nis X.\nReturns NULL if X is not in the range -1 to 1.\n \nExamples\n-------- \nSELECT ACOS(1);\n+---------+\n| ACOS(1) |\n+---------+\n| 0 |\n+---------+\n \nSELECT ACOS(1.0001);\n+--------------+\n| ACOS(1.0001) |\n+--------------+\n| NULL |\n+--------------+\n \nSELECT ACOS(0);\n+-----------------+\n| ACOS(0) |\n+-----------------+\n| 1.5707963267949 |\n+-----------------+\n \nSELECT ACOS(0.234);\n+------------------+\n| ACOS(0.234) |\n+------------------+\n| 1.33460644244679 |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/acos/','','https://mariadb.com/kb/en/library/acos/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (49,4,'ASIN','Syntax\n------ \nASIN(X)\n \nDescription\n----------- \nReturns the arc sine of X, that is, the value whose sine is\nX. Returns\nNULL if X is not in the range -1 to 1.\n \nExamples\n-------- \nSELECT ASIN(0.2);\n+--------------------+\n| ASIN(0.2) |\n+--------------------+\n| 0.2013579207903308 |\n+--------------------+\n \nSELECT ASIN(\'foo\');\n+-------------+\n| ASIN(\'foo\') |\n+-------------+\n| 0 |\n+-------------+\n \nSHOW WARNINGS;\n \n+---------+------+-----------------------------------------+\n| Level | Code | Message |\n+---------+------+-----------------------------------------+\n| Warning | 1292 | Truncated incorrect DOUBLE value: \'foo\'\n|\n+---------+------+-----------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/asin/','','https://mariadb.com/kb/en/library/asin/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (50,4,'ATAN','Syntax\n------ \nATAN(X)\n \nDescription\n----------- \nReturns the arc tangent of X, that is, the value whose\ntangent is X.\n \nExamples\n-------- \nSELECT ATAN(2);\n+--------------------+\n| ATAN(2) |\n+--------------------+\n| 1.1071487177940904 |\n+--------------------+\n \nSELECT ATAN(-2);\n+---------------------+\n| ATAN(-2) |\n+---------------------+\n| -1.1071487177940904 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/atan/','','https://mariadb.com/kb/en/library/atan/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (51,4,'ATAN2','Syntax\n------ \nATAN(Y,X), ATAN2(Y,X)\n \nDescription\n----------- \nReturns the arc tangent of the two variables X and Y. It is\nsimilar to\ncalculating the arc tangent of Y / X, except that the signs\nof both\narguments are used to determine the quadrant of the result.\n \nExamples\n-------- \nSELECT ATAN(-2,2);\n+---------------------+\n| ATAN(-2,2) |\n+---------------------+\n| -0.7853981633974483 |\n+---------------------+\n \nSELECT ATAN2(PI(),0);\n+--------------------+\n| ATAN2(PI(),0) |\n+--------------------+\n| 1.5707963267948966 |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/atan2/','','https://mariadb.com/kb/en/library/atan2/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (52,4,'CEIL','Syntax\n------ \nCEIL(X)\n \nDescription\n----------- \nCEIL() is a synonym for CEILING().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/ceil/','','https://mariadb.com/kb/en/library/ceil/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (53,4,'CEILING','Syntax\n------ \nCEILING(X)\n \nDescription\n----------- \nReturns the smallest integer value not less than X.\n \nExamples\n-------- \nSELECT CEILING(1.23);\n+---------------+\n| CEILING(1.23) |\n+---------------+\n| 2 |\n+---------------+\n \nSELECT CEILING(-1.23);\n+----------------+\n| CEILING(-1.23) |\n+----------------+\n| -1 |\n+----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/ceiling/','','https://mariadb.com/kb/en/library/ceiling/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (54,4,'CONV','Syntax\n------ \nCONV(N,from_base,to_base)\n \nDescription\n----------- \nConverts numbers between different number bases. Returns a\nstring\nrepresentation of the number N, converted from base\nfrom_base\nto base to_base.\n \nReturns NULL if any argument is NULL, or if the second or\nthird argument are not in the allowed range.\n \nThe argument N is interpreted as an integer, but may be\nspecified as an\ninteger or a string. The minimum base is 2 and the maximum\nbase is 36. If\nto_base is a negative number, N is regarded as a signed\nnumber.\nOtherwise, N is treated as unsigned. CONV() works with\n64-bit\nprecision.\n \nSome shortcuts for this function are also available: BIN(),\nOCT(), HEX(), UNHEX(). Also, MariaDB allows binary literal\nvalues and hexadecimal literal values.\n \nExamples\n-------- \nSELECT CONV(\'a\',16,2);\n+----------------+\n| CONV(\'a\',16,2) |\n+----------------+\n| 1010 |\n+----------------+\n \nSELECT CONV(\'6E\',18,8);\n+-----------------+\n| CONV(\'6E\',18,8) |\n+-----------------+\n| 172 |\n+-----------------+\n \nSELECT CONV(-17,10,-18);\n+------------------+\n| CONV(-17,10,-18) |\n+------------------+\n| -H |\n+------------------+\n \nSELECT CONV(12+\'10\'+\'10\'+0xa,10,10);\n+------------------------------+\n| CONV(12+\'10\'+\'10\'+0xa,10,10) |\n+------------------------------+\n| 42 |\n+------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/conv/','','https://mariadb.com/kb/en/library/conv/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (55,4,'COS','Syntax\n------ \nCOS(X)\n \nDescription\n----------- \nReturns the cosine of X, where X is given in radians.\n \nExamples\n-------- \nSELECT COS(PI());\n+-----------+\n| COS(PI()) |\n+-----------+\n| -1 |\n+-----------\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/cos/','','https://mariadb.com/kb/en/library/cos/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (56,4,'COT','Syntax\n------ \nCOT(X)\n \nDescription\n----------- \nReturns the cotangent of X.\n \nExamples\n-------- \nSELECT COT(42);\n+--------------------+\n| COT(42) |\n+--------------------+\n| 0.4364167060752729 |\n+--------------------+\n \nSELECT COT(12);\n+---------------------+\n| COT(12) |\n+---------------------+\n| -1.5726734063976893 |\n+---------------------+\n \nSELECT COT(0);\nERROR 1690 (22003): DOUBLE value is out of range in\n\'cot(0)\'\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/cot/','','https://mariadb.com/kb/en/library/cot/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (57,4,'CRC32','Syntax\n------ \nCRC32(expr)\n \nDescription\n----------- \nComputes a cyclic redundancy check value and returns a\n32-bit unsigned\nvalue. The result is NULL if the argument is NULL. The\nargument is\nexpected to be a string and (if possible) is treated as one\nif it is\nnot.\n \nExamples\n-------- \nSELECT CRC32(\'MariaDB\');\n+------------------+\n| CRC32(\'MariaDB\') |\n+------------------+\n| 4227209140 |\n+------------------+\n \nSELECT CRC32(\'mariadb\');\n+------------------+\n| CRC32(\'mariadb\') |\n+------------------+\n| 2594253378 |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/crc32/','','https://mariadb.com/kb/en/library/crc32/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (58,4,'DEGREES','Syntax\n------ \nDEGREES(X)\n \nDescription\n----------- \nReturns the argument X, converted from radians to degrees.\n \nThis is the converse of the RADIANS() function.\n \nExamples\n-------- \nSELECT DEGREES(PI());\n+---------------+\n| DEGREES(PI()) |\n+---------------+\n| 180 |\n+---------------+\n \nSELECT DEGREES(PI() / 2);\n+-------------------+\n| DEGREES(PI() / 2) |\n+-------------------+\n| 90 |\n+-------------------+\n \nSELECT DEGREES(45);\n+-----------------+\n| DEGREES(45) |\n+-----------------+\n| 2578.3100780887 |\n+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/degrees/','','https://mariadb.com/kb/en/library/degrees/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (59,4,'EXP','Syntax\n------ \nEXP(X)\n \nDescription\n----------- \nReturns the value of e (the base of natural logarithms)\nraised to the\npower of X. The inverse of this function is LOG() (using a\nsingle\nargument only) or LN().\n \nIf X is NULL, this function returns NULL.\n \nExamples\n-------- \nSELECT EXP(2);\n+------------------+\n| EXP(2) |\n+------------------+\n| 7.38905609893065 |\n+------------------+\n \nSELECT EXP(-2);\n+--------------------+\n| EXP(-2) |\n+--------------------+\n| 0.1353352832366127 |\n+--------------------+\n \nSELECT EXP(0);\n+--------+\n| EXP(0) |\n+--------+\n| 1 |\n+--------+\n \nSELECT EXP(NULL);\n+-----------+\n| EXP(NULL) |\n+-----------+\n| NULL |\n+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/exp/','','https://mariadb.com/kb/en/library/exp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (60,4,'FLOOR','Syntax\n------ \nFLOOR(X)\n \nDescription\n----------- \nReturns the largest integer value not greater than X.\n \nExamples\n-------- \nSELECT FLOOR(1.23);\n+-------------+\n| FLOOR(1.23) |\n+-------------+\n| 1 |\n+-------------+\n \nSELECT FLOOR(-1.23);\n+--------------+\n| FLOOR(-1.23) |\n+--------------+\n| -2 |\n+--------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/floor/','','https://mariadb.com/kb/en/library/floor/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (61,4,'LN','Syntax\n------ \nLN(X)\n \nDescription\n----------- \nReturns the natural logarithm of X; that is, the base-e\nlogarithm of X.\nIf X is less than or equal to 0, or NULL, then NULL is\nreturned.\n \nThe inverse of this function is EXP().\n \nExamples\n-------- \nSELECT LN(2);\n+-------------------+\n| LN(2) |\n+-------------------+\n| 0.693147180559945 |\n+-------------------+\n \nSELECT LN(-2);\n+--------+\n| LN(-2) |\n+--------+\n| NULL |\n+--------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/ln/','','https://mariadb.com/kb/en/library/ln/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (62,4,'LOG','Syntax\n------ \nLOG(X), LOG(B,X)\n \nDescription\n----------- \nIf called with one parameter, this function returns the\nnatural\nlogarithm of X. If X is less than or equal to 0, then NULL\nis\nreturned.\n \nIf called with two parameters, it returns the logarithm of X\nto the base B. If B is \n\nURL: https://mariadb.com/kb/en/library/log/','','https://mariadb.com/kb/en/library/log/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (63,4,'LOG10','Syntax\n------ \nLOG10(X)\n \nDescription\n----------- \nReturns the base-10 logarithm of X.\n \nExamples\n-------- \nSELECT LOG10(2);\n+-------------------+\n| LOG10(2) |\n+-------------------+\n| 0.301029995663981 |\n+-------------------+\n \nSELECT LOG10(100);\n+------------+\n| LOG10(100) |\n+------------+\n| 2 |\n+------------+\n \nSELECT LOG10(-100);\n+-------------+\n| LOG10(-100) |\n+-------------+\n| NULL |\n+-------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/log10/','','https://mariadb.com/kb/en/library/log10/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (64,4,'LOG2','Syntax\n------ \nLOG2(X)\n \nDescription\n----------- \nReturns the base-2 logarithm of X.\n \nExamples\n-------- \nSELECT LOG2(4398046511104);\n+---------------------+\n| LOG2(4398046511104) |\n+---------------------+\n| 42 |\n+---------------------+\n \nSELECT LOG2(65536);\n+-------------+\n| LOG2(65536) |\n+-------------+\n| 16 |\n+-------------+\n \nSELECT LOG2(-100);\n+------------+\n| LOG2(-100) |\n+------------+\n| NULL |\n+------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/log2/','','https://mariadb.com/kb/en/library/log2/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (65,4,'MOD','Syntax\n------ \nMOD(N,M), N % M, N MOD M\n \nDescription\n----------- \nModulo operation. Returns the remainder of N divided by M.\nSee also Modulo Operator.\n \nIf the ERROR_ON_DIVISION_BY_ZERO SQL_MODE is used, any\nnumber modulus zero produces an error. Otherwise, it returns\nNULL.\n \nThe integer part of a division can be obtained using DIV.\n \nExamples\n-------- \nSELECT 1042 % 50;\n \n+-----------+\n| 1042 % 50 |\n+-----------+\n| 42 |\n+-----------+\n \nSELECT MOD(234, 10);\n+--------------+\n| MOD(234, 10) |\n+--------------+\n| 4 |\n+--------------+\n \nSELECT 253 % 7;\n \n+---------+\n| 253 % 7 |\n+---------+\n| 1 |\n+---------+\n \nSELECT MOD(29,9);\n+-----------+\n| MOD(29,9) |\n+-----------+\n| 2 |\n+-----------+\n \nSELECT 29 MOD 9;\n \n+----------+\n| 29 MOD 9 |\n+----------+\n| 2 |\n+----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mod/','','https://mariadb.com/kb/en/library/mod/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (66,4,'OCT','Syntax\n------ \nOCT(N)\n \nDescription\n----------- \nReturns a string representation of the octal value of N,\nwhere N is a longlong (BIGINT) number. This is equivalent to\nCONV(N,10,8). Returns NULL if N is NULL.\n \nExamples\n-------- \nSELECT OCT(34);\n+---------+\n| OCT(34) |\n+---------+\n| 42 |\n+---------+\n \nSELECT OCT(12);\n+---------+\n| OCT(12) |\n+---------+\n| 14 |\n+---------+\n \n\n\nURL: https://mariadb.com/kb/en/library/oct/','','https://mariadb.com/kb/en/library/oct/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (67,4,'PI','Syntax\n------ \nPI()\n \nDescription\n----------- \nReturns the value of π (pi). The default number of decimal\nplaces\ndisplayed is six, but MariaDB uses the full double-precision\nvalue\ninternally.\n \nExamples\n-------- \nSELECT PI();\n+----------+\n| PI() |\n+----------+\n| 3.141593 |\n+----------+\n \nSELECT PI()+0.0000000000000000000000;\n \n+-------------------------------+\n| PI()+0.0000000000000000000000 |\n+-------------------------------+\n| 3.1415926535897931159980 |\n+-------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/pi/','','https://mariadb.com/kb/en/library/pi/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (68,4,'POW','Syntax\n------ \nPOW(X,Y)\n \nDescription\n----------- \nReturns the value of X raised to the power of Y.\n \nPOWER() is a synonym.\n \nExamples\n-------- \nSELECT POW(2,3);\n+----------+\n| POW(2,3) |\n+----------+\n| 8 |\n+----------+\n \nSELECT POW(2,-2);\n+-----------+\n| POW(2,-2) |\n+-----------+\n| 0.25 |\n+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/pow/','','https://mariadb.com/kb/en/library/pow/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (69,4,'POWER','Syntax\n------ \nPOWER(X,Y)\n \nDescription\n----------- \nThis is a synonym for POW(), which returns the value of X\nraised to the power of Y.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/power/','','https://mariadb.com/kb/en/library/power/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (70,4,'RADIANS','Syntax\n------ \nRADIANS(X)\n \nDescription\n----------- \nReturns the argument X, converted from degrees to radians.\nNote that\nπ radians equals 180 degrees. \n \nThis is the converse of the DEGREES() function.\n \nExamples\n-------- \nSELECT RADIANS(45);\n+-------------------+\n| RADIANS(45) |\n+-------------------+\n| 0.785398163397448 |\n+-------------------+\n \nSELECT RADIANS(90);\n+-----------------+\n| RADIANS(90) |\n+-----------------+\n| 1.5707963267949 |\n+-----------------+\n \nSELECT RADIANS(PI());\n+--------------------+\n| RADIANS(PI()) |\n+--------------------+\n| 0.0548311355616075 |\n+--------------------+\n \nSELECT RADIANS(180);\n+------------------+\n| RADIANS(180) |\n+------------------+\n| 3.14159265358979 |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/radians/','','https://mariadb.com/kb/en/library/radians/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (71,4,'RAND','Syntax\n------ \nRAND(), RAND(N)\n \nDescription\n----------- \nReturns a random DOUBLE precision floating point value v in\nthe range 0 \n\nURL: https://mariadb.com/kb/en/library/rand/','','https://mariadb.com/kb/en/library/rand/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (72,4,'ROUND','Syntax\n------ \nROUND(X), ROUND(X,D)\n \nDescription\n----------- \nRounds the argument X to D decimal places. The rounding\nalgorithm\ndepends on the data type of X. D defaults to 0 if not\nspecified.\nD can be negative to cause D digits left of the decimal\npoint of the\nvalue X to become zero.\n \nExamples\n-------- \nSELECT ROUND(-1.23);\n+--------------+\n| ROUND(-1.23) |\n+--------------+\n| -1 |\n+--------------+\n \nSELECT ROUND(-1.58);\n+--------------+\n| ROUND(-1.58) |\n+--------------+\n| -2 |\n+--------------+\n \nSELECT ROUND(1.58); \n+-------------+\n| ROUND(1.58) |\n+-------------+\n| 2 |\n+-------------+\n \nSELECT ROUND(1.298, 1);\n+-----------------+\n| ROUND(1.298, 1) |\n+-----------------+\n| 1.3 |\n+-----------------+\n \nSELECT ROUND(1.298, 0);\n+-----------------+\n| ROUND(1.298, 0) |\n+-----------------+\n| 1 |\n+-----------------+\n \nSELECT ROUND(23.298, -1);\n+-------------------+\n| ROUND(23.298, -1) |\n+-------------------+\n| 20 |\n+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/round/','','https://mariadb.com/kb/en/library/round/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (73,4,'SIGN','Syntax\n------ \nSIGN(X)\n \nDescription\n----------- \nReturns the sign of the argument as -1, 0, or 1, depending\non whether\nX is negative, zero, or positive.\n \nExamples\n-------- \nSELECT SIGN(-32);\n+-----------+\n| SIGN(-32) |\n+-----------+\n| -1 |\n+-----------+\n \nSELECT SIGN(0);\n+---------+\n| SIGN(0) |\n+---------+\n| 0 |\n+---------+\n \nSELECT SIGN(234);\n+-----------+\n| SIGN(234) |\n+-----------+\n| 1 |\n+-----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/sign/','','https://mariadb.com/kb/en/library/sign/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (74,4,'SIN','Syntax\n------ \nSIN(X)\n \nDescription\n----------- \nReturns the sine of X, where X is given in radians.\n \nExamples\n-------- \nSELECT SIN(1.5707963267948966);\n+-------------------------+\n| SIN(1.5707963267948966) |\n+-------------------------+\n| 1 |\n+-------------------------+\n \nSELECT SIN(PI());\n+----------------------+\n| SIN(PI()) |\n+----------------------+\n| 1.22460635382238e-16 |\n+----------------------+\n \nSELECT ROUND(SIN(PI()));\n+------------------+\n| ROUND(SIN(PI())) |\n+------------------+\n| 0 |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/sin/','','https://mariadb.com/kb/en/library/sin/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (75,4,'SQRT','Syntax\n------ \nSQRT(X)\n \nDescription\n----------- \nReturns the square root of X. If X is negative, NULL is\nreturned.\n \nExamples\n-------- \nSELECT SQRT(4);\n+---------+\n| SQRT(4) |\n+---------+\n| 2 |\n+---------+\n \nSELECT SQRT(20);\n+------------------+\n| SQRT(20) |\n+------------------+\n| 4.47213595499958 |\n+------------------+\n \nSELECT SQRT(-16);\n+-----------+\n| SQRT(-16) |\n+-----------+\n| NULL |\n+-----------+\n \nSELECT SQRT(1764);\n+------------+\n| SQRT(1764) |\n+------------+\n| 42 |\n+------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/sqrt/','','https://mariadb.com/kb/en/library/sqrt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (76,4,'TAN','Syntax\n------ \nTAN(X)\n \nDescription\n----------- \nReturns the tangent of X, where X is given in radians.\n \nExamples\n-------- \nSELECT TAN(0.7853981633974483);\n+-------------------------+\n| TAN(0.7853981633974483) |\n+-------------------------+\n| 0.9999999999999999 |\n+-------------------------+\n \nSELECT TAN(PI());\n+-----------------------+\n| TAN(PI()) |\n+-----------------------+\n| -1.22460635382238e-16 |\n+-----------------------+\n \nSELECT TAN(PI()+1);\n+-----------------+\n| TAN(PI()+1) |\n+-----------------+\n| 1.5574077246549 |\n+-----------------+\n \nSELECT TAN(RADIANS(PI()));\n+--------------------+\n| TAN(RADIANS(PI())) |\n+--------------------+\n| 0.0548861508080033 |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/tan/','','https://mariadb.com/kb/en/library/tan/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (77,4,'TRUNCATE','This page documents the TRUNCATE function. See TRUNCATE\nTABLE for the DDL statement.\n \nSyntax\n------ \nTRUNCATE(X,D)\n \nDescription\n----------- \nReturns the number X, truncated to D decimal places. If D is\n0, the\nresult has no decimal point or fractional part. D can be\nnegative to\ncause D digits left of the decimal point of the value X to\nbecome\nzero.\n \nExamples\n-------- \nSELECT TRUNCATE(1.223,1);\n+-------------------+\n| TRUNCATE(1.223,1) |\n+-------------------+\n| 1.2 |\n+-------------------+\n \nSELECT TRUNCATE(1.999,1);\n+-------------------+\n| TRUNCATE(1.999,1) |\n+-------------------+\n| 1.9 |\n+-------------------+\n \nSELECT TRUNCATE(1.999,0); \n+-------------------+\n| TRUNCATE(1.999,0) |\n+-------------------+\n| 1 |\n+-------------------+\n \nSELECT TRUNCATE(-1.999,1);\n+--------------------+\n| TRUNCATE(-1.999,1) |\n+--------------------+\n| -1.9 |\n+--------------------+\n \nSELECT TRUNCATE(122,-2);\n+------------------+\n| TRUNCATE(122,-2) |\n+------------------+\n| 100 |\n+------------------+\n \nSELECT TRUNCATE(10.28*100,0);\n+-----------------------+\n| TRUNCATE(10.28*100,0) |\n+-----------------------+\n| 1028 |\n+-----------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/truncate/','','https://mariadb.com/kb/en/library/truncate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (78,5,'Plugin Overview','Plugins are server components that enhance MariaDB in some\nway. These can be anything from new storage engines, plugins\nfor enhancing full-text parsing, or even small enhancements,\nsuch as a plugin to get a timestamp as an integer.\n \nQuerying Plugin Information\n \nThere are a number of ways to see which plugins are\ncurrently active.\n \nA server almost always has a large number of active plugins,\nbecause the server contains a large number of built-in\nplugins, which are active by default and cannot be\nuninstalled.\n \nQuerying Plugin Information with SHOW PLUGINS\n \nThe SHOW PLUGINS statement can be used to query information\nabout all active plugins.\n \nFor example:\n \nSHOW PLUGINS;\n \n+----------------------------+----------+--------------------+---------+---------+\n| Name | Status | Type | Library | License |\n+----------------------------+----------+--------------------+---------+---------+\n...\n| mysql_native_password | ACTIVE | AUTHENTICATION | NULL |\nGPL |\n| mysql_old_password | ACTIVE | AUTHENTICATION | NULL | GPL\n|\n| MRG_MyISAM | ACTIVE | STORAGE ENGINE | NULL | GPL |\n...\n+----------------------------+----------+--------------------+---------+---------+\n \nIf a plugin\'s Library column has the NULL value, then the\nplugin is built-in, and it cannot be uninstalled.\n \nQuerying Plugin Information with information_schema.PLUGINS\n \nThe information_schema.PLUGINS table can be queried to get\nmore detailed information about plugins.\n \nFor example:\n \nSELECT * FROM information_schema.PLUGINS\\G\n...\n*************************** 6. row\n***************************\n PLUGIN_NAME: CSV\n PLUGIN_VERSION: 1.0\n PLUGIN_STATUS: ACTIVE\n PLUGIN_TYPE: STORAGE ENGINE\n PLUGIN_TYPE_VERSION: 100003.0\n PLUGIN_LIBRARY: NULL\nPLUGIN_LIBRARY_VERSION: NULL\n PLUGIN_AUTHOR: Brian Aker, MySQL AB\n PLUGIN_DESCRIPTION: CSV storage engine\n PLUGIN_LICENSE: GPL\n LOAD_OPTION: FORCE\n PLUGIN_MATURITY: Stable\n PLUGIN_AUTH_VERSION: 1.0\n*************************** 7. row\n***************************\n PLUGIN_NAME: MEMORY\n PLUGIN_VERSION: 1.0\n PLUGIN_STATUS: ACTIVE\n PLUGIN_TYPE: STORAGE ENGINE\n PLUGIN_TYPE_VERSION: 100003.0\n PLUGIN_LIBRARY: NULL\nPLUGIN_LIBRARY_VERSION: NULL\n PLUGIN_AUTHOR: MySQL AB\n PLUGIN_DESCRIPTION: Hash based, stored in memory, useful\nfor temporary tables\n PLUGIN_LICENSE: GPL\n LOAD_OPTION: FORCE\n PLUGIN_MATURITY: Stable\n PLUGIN_AUTH_VERSION: 1.0\n...\n \nIf a plugin\'s PLUGIN_LIBRARY column has the NULL value,\nthen the plugin is built-in, and it cannot be uninstalled.\n \nQuerying Plugin Information with mysql.plugin\n \nThe mysql.plugin table can be queried to get information\nabout installed plugins.\n \nThis table only contains information about plugins that have\nbeen installed via the following methods:\nThe INSTALL SONAME statement.\nThe INSTALL PLUGIN statement.\nThe mysql_plugin utility.\n \nThis table does not contain information about:\nBuilt-in plugins.\nPlugins loaded with the --plugin-load-add option.\nPlugins loaded with the --plugin-load option.\n \nThis table only contains enough information to reload the\nplugin when the server is restarted, which means it only\ncontains the plugin name and the plugin library.\n \nFor example:\n \nSELECT * FROM mysql.plugin;\n \n+------+------------+\n| name | dl |\n+------+------------+\n| PBXT | libpbxt.so |\n+------+------------+\n \nInstalling a Plugin\n \nThere are three primary ways to install a plugin:\nA plugin can be installed dynamically with an SQL statement.\nA plugin can be installed with a mysqld option, but it\nrequires a server restart.\nA plugin can be installed with the mysql_plugin utility,\nwhile the server is completely offline.\n \nWhen you are installing a plugin, you also have to ensure\nthat:\nThe server\'s plugin directory is properly configured, and\nthe plugin\'s library is in the plugin directory.\nThe server\'s minimum plugin maturity is properly\nconfigured, and the plugin is mature enough to be installed.\n \nInstalling a Plugin Dynamically\n \nA plugin can be installed dynamically by executing either\nthe INSTALL SONAME or the INSTALL PLUGIN statement.\n \nIf a plugin is installed with one of these statements, then\na record will be added to the mysql.plugins table for the\nplugin. This means that the plugin will automatically be\nloaded every time the server restarts, unless specifically\nuninstalled or deactivated.\n \nInstalling a Plugin with INSTALL SONAME\n \nYou can install a plugin dynamically by executing the\nINSTALL SONAME statement. INSTALL SONAME installs all\nplugins from the given plugin library. This could be\nrequired for some plugin libraries.\n \nFor example, to install all plugins in the server_audit\nplugin library (which is currently only the server_audit\naudit plugin), you could execute the following:\n \nINSTALL SONAME \'server_audit\';\n \nInstalling a Plugin with INSTALL PLUGIN\n \nYou can install a plugin dynamically by executing the\nINSTALL PLUGIN statement. INSTALL PLUGIN installs a single\nplugin from the given plugin library.\n \nFor example, to install the server_audit audit plugin from\nthe server_audit plugin library, you could execute the\nfollowing:\n \nINSTALL PLUGIN server_audit SONAME \'server_audit\';\n \nInstalling a Plugin with Plugin Load Options\n \nA plugin can be installed with a mysqld option by providing\neither the --plugin-load-add or the --plugin-load option.\n \nIf a plugin is installed with one of these options, then a\nrecord will not be added to the mysql.plugins table for the\nplugin. This means that if the server is restarted without\nthe same option set, then the plugin will not automatically\nbe loaded.\n \nInstalling a Plugin with --plugin-load-add\n \nYou can install a plugin with the --plugin-load-add option\nby specifying the option as a command-line argument to\nmysqld or by specifying the option in a relevant server\noption group in an option file.\n \nThe --plugin-load-add option uses the following format:\nPlugins can be specified in the format name=library, where\nname is the plugin name and library is the plugin library.\nThis format installs a single plugin from the given plugin\nlibrary.\nPlugins can also be specified in the format library, where\nlibrary is the plugin library. This format installs all\nplugins from the given plugin library.\nMultiple plugins can be specified by separating them with\nsemicolons.\n \nFor example, to install all plugins in the server_audit\nplugin library (which is currently only the server_audit\naudit plugin) and also the ed25519 authentication plugin\nfrom the auth_ed25519 plugin library, you could set the\noption to the following values on the command-line:\n \n$ mysqld --user=mysql --plugin-load-add=\'server_audit\'\n--plugin-load-add=\'ed25519=auth_ed25519\'\n \nYou could also set the option to the same values in an\noption file:\n \n[mariadb]\n...\nplugin_load_add = server_audit\nplugin_load_add = ed25519=auth_ed25519\n \nSpecial care must be taken when specifying both the\n--plugin-load option and the --plugin-load-add option\ntogether. The --plugin-load option resets the plugin load\nlist, and this can cause unexpected problems if you are not\naware. The --plugin-load-add option does not reset the\nplugin load list, so it is much safer to use. See Specifying\nMultiple Plugin Load Options for more information.\n \nInstalling a Plugin with --plugin-load\n \nYou can install a plugin with the --plugin-load option by\nspecifying the option as a command-line argument to mysqld\nor by specifying the option in a relevant server option\ngroup in an option file.\n \nThe --plugin-load option uses the following format:\nPlugins can be specified in the format name=library, where\nname is the plugin name and library is the plugin library.\nThis format installs a single plugin from the given plugin\nlibrary.\nPlugins can also be specified in the format library, where\nlibrary is the plugin library. This format installs all\nplugins from the given plugin library.\nMultiple plugins can be specified by separating them with\nsemicolons.\n \nFor example, to install all plugins in the server_audit\nplugin library (which is currently only the server_audit\naudit plugin) and also the ed25519 authentication plugin\nfrom the auth_ed25519 plugin library, you could set the\noption to the following values on the command-line:\n \n$ mysqld --user=mysql\n--plugin-load=\'server_audit;ed25519=auth_ed25519\'\n \nYou could also set the option to the same values in an\noption file:\n \n[mariadb]\n...\nplugin_load = server_audit;ed25519=auth_ed25519\n \nSpecial care must be taken when specifying the --plugin-load\noption multiple times, or when specifying both the\n--plugin-load option and the --plugin-load-add option\ntogether. The --plugin-load option resets the plugin load\nlist, and this can cause unexpected problems if you are not\naware. The --plugin-load-add option does not reset the\nplugin load list, so it is much safer to use. See Specifying\nMultiple Plugin Load Options for more information.\n \nSpecifying Multiple Plugin Load Options\n \nSpecial care must be taken when specifying the --plugin-load\noption multiple times, or when specifying both the\n--plugin-load option and the --plugin-load-add option. The\n--plugin-load option resets the plugin load list, and this\ncan cause unexpected problems if you are not aware. The\n--plugin-load-add option does not reset the plugin load\nlist, so it is much safer to use.\n \nThis can have the following consequences:\nIf the --plugin-load option is specified multiple times,\nthen only the last instance will have any effect. For\nexample, in the following case, the first instance of the\noption is reset:\n \n[mariadb]\n...\nplugin_load = server_audit\nplugin_load = ed25519=auth_ed25519\nIf the --plugin-load option is specified after the\n--plugin-load-add option, then it will also reset the\nchanges made by that option. For example, in the following\ncase, the --plugin-load-add option does not do anything,\nbecause the subsequent --plugin-load option resets the\nplugin load list:\n \n[mariadb]\n...\nplugin_load_add = server_audit\nplugin_load = ed25519=auth_ed25519\nIn contrast, if the --plugin-load option is specified before\nthe --plugin-load-add option, then it will work fine,\nbecause the --plugin-load-add option does not reset the\nplugin load list. For example, in the following case, both\nplugins are properly loaded:\n \n[mariadb]\n...\nplugin_load = server_audit\nplugin_load_add = ed25519=auth_ed25519\n \nInstalling a Plugin with mysql_plugin\n \nA plugin can be installed with the mysql_plugin utility if\nthe server is completely offline. \n \nThe syntax is:\n \nmysql_plugin [options] \n ENABLE|DISABLE\n \nFor example, to install the server_audit audit plugin, you\ncould execute the following:\n \nmysql_plugin server_audit ENABLE\n \nIf a plugin is installed with this utility, then a record\nwill be added to the mysql.plugins table for the plugin.\nThis means that the plugin will automatically be loaded\nevery time the server restarts, unless specifically\nuninstalled or deactivated.\n \nConfiguring the Plugin Directory\n \nWhen a plugin is being installed, the server looks for the\nplugin\'s library in the server\'s plugin directory. This\ndirectory is configured by the plugin_dir system variable.\nThis can be specified as a command-line argument to mysqld\nor it can be specified in a relevant server option group in\nan option file. For example:\n \n[mariadb]\n...\nplugin_dir = /usr/lib64/mysql/plugin\n \nConfiguring the Minimum Plugin Maturity\n \nWhen a plugin is being installed, the server compares the\nplugin\'s maturity level against the server\'s minimum\nallowed plugin maturity. This can help prevent users from\nusing unstable plugins on production servers. This minimum\nplugin maturity is configured by the plugin_maturity system\nvariable. This can be specified as a command-line argument\nto mysqld or it can be specified in a relevant server option\ngroup in an option file. For example:\n \n[mariadb]\n...\nplugin_maturity = stable\n \nConfiguring Plugin Activation at Server Startup\n \nA plugin will be loaded by default when the server starts\nif:\nThe plugin was installed with the INSTALL SONAME statement.\nThe plugin was installed with the INSTALL PLUGIN statement.\nThe plugin was installed with the mysql_plugin utility.\nThe server is configured to load the plugin with the\n--plugin-load-add option.\nThe server is configured to load the plugin with the\n--plugin-load option.\n \nThis behavior can be changed with special options that take\nthe form --plugin-name. For example, for the server_audit\naudit plugin, the special option is called --server-audit.\n \nThe possible values for these special options are:\n \nOption Value | Description | \n \nOFF | Disables the plugin without removing it from the\nmysql.plugins table. | \n \nON | Enables the plugin. If the plugin cannot be\ninitialized, then the server will still continue starting\nup, but the plugin will be disabled. | \n \nFORCE | Enables the plugin. If the plugin cannot be\ninitialized, then the server will fail to start with an\nerror. | \n \nFORCE_PLUS_PERMANENT | Enables the plugin. If the plugin\ncannot be initialized, then the server will fail to start\nwith an error. In addition, the plugin cannot be uninstalled\nwith UNINSTALL SONAME or UNINSTALL PLUGIN while the server\nis running. | \n \nA plugin\'s status can be found by looking at the\nPLUGIN_STATUS column of the information_schema.PLUGINS\ntable.\n \nUninstalling Plugins\n \nPlugins that are found in the mysql.plugin table, that is\nthose that were installed with INSTALL SONAME, INSTALL\nPLUGIN or mysql_plugin can be uninstalled in one of two\nways:\nThe UNINSTALL SONAME or the UNINSTALL PLUGIN statement while\nthe server is running\nWith mysql_plugin while the server is offline.\n \nPlugins that were enabled as a --plugin-load option do not\nneed to be uninstalled. If --plugin-load is omitted the next\ntime the server starts, or the plugin is not listed as one\nof the --plugin-load entries, the plugin will not be loaded.\n \nUNINSTALL PLUGIN uninstalls a single installed plugin, while\nUNINSTALL SONAME uninstalls all plugins belonging to a given\nlibrary.\n \n\n\nURL: https://mariadb.com/kb/en/library/plugin-overview/','','https://mariadb.com/kb/en/library/plugin-overview/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (79,5,'INSTALL PLUGIN','Syntax\n------ \nINSTALL PLUGIN [IF NOT EXISTS] plugin_name SONAME\n\'plugin_library\'\n \nDescription\n----------- \nThis statement installs an individual plugin from the\nspecified library. To install the whole library (which could\nbe required), use INSTALL SONAME.\n \nplugin_name is the name of the plugin as defined in the\nplugin declaration structure contained in the library file.\nPlugin names are\nnot case sensitive. For maximal compatibility, plugin names\nshould be limited\nto ASCII letters, digits, and underscore, because they are\nused in C source\nfiles, shell command lines, M4 and Bourne shell scripts, and\nSQL environments.\n \nplugin_library is the name of the shared library that\ncontains the plugin code. Before MariaDB 5.5.21, the name\nshould include the file name extension (for\nexample, libmyplugin.so or libmyplugin.dll). Starting from\nMariaDB 5.5.21, the file name extension can be omitted\n(which makes the statement look the same on all\narchitectures).\n \nThe shared library must be located in the plugin directory\n(that is,\nthe directory named by the plugin_dir system variable). The\nlibrary must be in the plugin directory itself, not in a\nsubdirectory. By\ndefault, plugin_dir is plugin directory under the directory\nnamed by\nthe pkglibdir configuration variable, but it can be changed\nby setting\nthe value of plugin_dir at server startup. For example, set\nits value in a my.cnf file:\n \n[mysqld]\nplugin_dir=/path/to/plugin/directory\nIf the value of plugin_dir is a relative path name, it is\ntaken to be relative to the MySQL base directory (the value\nof the basedir\nsystem variable).\n \nINSTALL PLUGIN adds a line to the mysql.plugin table that\ndescribes the plugin. This table contains the plugin name\nand library file\nname.\n \nINSTALL PLUGIN causes the server to read\noption (my.cnf) files just as during server startup. This\nenables the plugin to\npick up any relevant options from those files. It is\npossible to add plugin\noptions to an option file even before loading a plugin (if\nthe loose prefix is\nused). It is also possible to uninstall a plugin, edit\nmy.cnf, and install the\nplugin again. Restarting the plugin this way enables it to\nthe new option\nvalues without a server restart.\n \nBefore MySQL 5.1.33, a plugin was started with each option\nset to its\ndefault value.\n \nINSTALL PLUGIN also loads and initializes the plugin code to\nmake the plugin available for use. A plugin is initialized\nby executing its\ninitialization function, which handles any setup that the\nplugin must perform\nbefore it can be used.\n \nTo use INSTALL PLUGIN, you must have the\nINSERT privilege for the mysql.plugin table.\n \nAt server startup, the server loads and initializes any\nplugin that is\nlisted in the mysql.plugin table. This means that a plugin\nis installed\nwith INSTALL PLUGIN only once, not every time the server\nstarts. Plugin loading at startup does not occur if the\nserver is started with\nthe --skip-grant-tables option.\n \nWhen the server shuts down, it executes the deinitialization\nfunction\nfor each plugin that is loaded so that the plugin has a\nchance to\nperform any final cleanup.\n \nIf you need to load plugins for a single server startup when\nthe\n--skip-grant-tables option is given (which tells the server\nnot to read system tables), use the \n--plugin-load mysqld option.\n \nIF NOT EXISTS\n \nWhen the IF NOT EXISTS clause is used, MariaDB will return a\nnote instead of an error if the specified plugin already\nexists. See SHOW WARNINGS.\n \nExamples\n-------- \nINSTALL PLUGIN sphinx SONAME \'ha_sphinx.so\';\n \nStarting from MariaDB 5.5.21, the extension can be omitted:\n \nINSTALL PLUGIN innodb SONAME \'ha_xtradb\';\n \nFrom MariaDB 10.4.0:\n \nINSTALL PLUGIN IF NOT EXISTS example SONAME \'ha_example\';\n \nQuery OK, 0 rows affected (0.104 sec)\n \nINSTALL PLUGIN IF NOT EXISTS example SONAME \'ha_example\';\n \nQuery OK, 0 rows affected, 1 warning (0.000 sec)\n \nSHOW WARNINGS;\n \n+-------+------+------------------------------------+\n| Level | Code | Message |\n+-------+------+------------------------------------+\n| Note | 1968 | Plugin \'example\' already installed |\n+-------+------+------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/install-plugin/','','https://mariadb.com/kb/en/library/install-plugin/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (80,5,'UNINSTALL PLUGIN','Syntax\n------ \nUNINSTALL PLUGIN [IF EXISTS] plugin_name\n \nDescription\n----------- \nThis statement removes a single installed plugin. To\nuninstall the whole library which contains the plugin, use\nUNINSTALL SONAME. You cannot uninstall a plugin if any table\nthat uses it is open.\n \nplugin_name must be the name of some plugin that is listed\nin the mysql.plugin table. The server executes the plugin\'s\ndeinitialization\nfunction and removes the row for the plugin from the\nmysql.plugin\ntable, so that subsequent server restarts will not load and\ninitialize\nthe plugin. UNINSTALL PLUGIN does not remove the plugin\'s\nshared library file.\n \nTo use UNINSTALL PLUGIN, you must have the\nDELETE privilege for the mysql.plugin table.\n \nIF EXISTS\n \nIf the IF EXISTS clause is used, MariaDB will return a note\ninstead of an error if the plugin does not exist. See SHOW\nWARNINGS.\n \nExamples\n-------- \nUNINSTALL PLUGIN example;\n \nFrom MariaDB 10.4.0:\n \nUNINSTALL PLUGIN IF EXISTS example;\n \nQuery OK, 0 rows affected (0.099 sec)\n \nUNINSTALL PLUGIN IF EXISTS example;\n \nQuery OK, 0 rows affected, 1 warning (0.000 sec)\n \nSHOW WARNINGS;\n \n+-------+------+-------------------------------+\n| Level | Code | Message |\n+-------+------+-------------------------------+\n| Note | 1305 | PLUGIN example does not exist |\n+-------+------+-------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/uninstall-plugin/','','https://mariadb.com/kb/en/library/uninstall-plugin/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (81,5,'INSTALL SONAME','INSTALL SONAME has been supported since MariaDB 5.5.21.\n \nSyntax\n------ \nINSTALL SONAME \'plugin_library\'\n \nDescription\n----------- \nThis statement is a variant of INSTALL PLUGIN. It installs\nall plugins from a given plugin_library. See INSTALL PLUGIN\nfor details.\n \nplugin_library is the name of the shared library that\ncontains the plugin code. The file name extension (for\nexample, libmyplugin.so or libmyplugin.dll) can be omitted\n(which makes the statement look the same on all\narchitectures).\n \nThe shared library must be located in the plugin directory\n(that is,\nthe directory named by the plugin_dir system variable). The\nlibrary must be in the plugin directory itself, not in a\nsubdirectory. By\ndefault, plugin_dir is plugin directory under the directory\nnamed by\nthe pkglibdir configuration variable, but it can be changed\nby setting\nthe value of plugin_dir at server startup. For example, set\nits value in a my.cnf file:\n \n[mysqld]\nplugin_dir=/path/to/plugin/directory\nIf the value of plugin_dir is a relative path name, it is\ntaken to be relative to the MySQL base directory (the value\nof the basedir\nsystem variable).\n \nINSTALL SONAME adds one or more lines to the mysql.plugin\ntable that\ndescribes the plugin. This table contains the plugin name\nand library file\nname.\n \nINSTALL SONAME causes the server to read\noption (my.cnf) files just as during server startup. This\nenables the plugin to\npick up any relevant options from those files. It is\npossible to add plugin\noptions to an option file even before loading a plugin (if\nthe loose prefix is\nused). It is also possible to uninstall a plugin, edit\nmy.cnf, and install the\nplugin again. Restarting the plugin this way enables it to\nthe new option\nvalues without a server restart.\n \nINSTALL SONAME also loads and initializes the plugin code to\nmake the plugin available for use. A plugin is initialized\nby executing its\ninitialization function, which handles any setup that the\nplugin must perform\nbefore it can be used.\n \nTo use INSTALL SONAME, you must have the\nINSERT privilege for the mysql.plugin table.\n \nAt server startup, the server loads and initializes any\nplugin that is\nlisted in the mysql.plugin table. This means that a plugin\nis installed\nwith INSTALL SONAME only once, not every time the server\nstarts. Plugin loading at startup does not occur if the\nserver is started with\nthe --skip-grant-tables option.\n \nWhen the server shuts down, it executes the deinitialization\nfunction\nfor each plugin that is loaded so that the plugin has a\nchance to\nperform any final cleanup.\n \nIf you need to load plugins for a single server startup when\nthe\n--skip-grant-tables option is given (which tells the server\nnot to read system tables), use the \n--plugin-load mysqld option.\n \nIf you need to install only one plugin from a library, use\nthe INSTALL PLUGIN statement.\n \nExamples\n-------- \nTo load the XtraDB storage engine and all of its\ninformation_schema tables with one statement, use\n \nINSTALL SONAME \'ha_xtradb\';\n \nThis statement can be used instead of INSTALL PLUGIN even\nwhen the library contains only one plugin:\n \nINSTALL SONAME \'ha_sequence\';\n \n\n\nURL: https://mariadb.com/kb/en/library/install-soname/','','https://mariadb.com/kb/en/library/install-soname/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (82,5,'UNINSTALL SONAME','UNINSTALL SONAMEhas been supported since MariaDB 5.5.21.\n \nSyntax\n------ \nUNINSTALL SONAME [IF EXISTS] \'plugin_library\'\n \nDescription\n----------- \nThis statement is a variant of UNINSTALL PLUGIN statement,\nthat removes all plugins belonging to a specified\nplugin_library. See UNINSTALL PLUGIN for details.\n \nplugin_library is the name of the shared library that\ncontains the plugin code. The file name extension (for\nexample, libmyplugin.so or libmyplugin.dll) can be omitted\n(which makes the statement look the same on all\narchitectures).\n \nTo use UNINSTALL SONAME, you must have the\nDELETE privilege for the mysql.plugin table.\n \nIF EXISTS\n \nIf the IF EXISTS clause is used, MariaDB will return a note\ninstead of an error if the plugin library does not exist.\nSee SHOW WARNINGS.\n \nExamples\n-------- \nTo uninstall the XtraDB plugin and all of its\ninformation_schema tables with one statement, use\n \nUNINSTALL SONAME \'ha_xtradb\';\n \nFrom MariaDB 10.4.0:\n \nUNINSTALL SONAME IF EXISTS \'ha_example\';\n \nQuery OK, 0 rows affected (0.099 sec)\n \nUNINSTALL SONAME IF EXISTS \'ha_example\';\n \nQuery OK, 0 rows affected, 1 warning (0.000 sec)\n \nSHOW WARNINGS;\n \n+-------+------+-------------------------------------+\n| Level | Code | Message |\n+-------+------+-------------------------------------+\n| Note | 1305 | SONAME ha_example.so does not exist |\n+-------+------+-------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/uninstall-soname/','','https://mariadb.com/kb/en/library/uninstall-soname/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (83,6,'MBR Definition','Description\n----------- \nThe MBR (Minimum Bounding Rectangle), or Envelope is the\nbounding\ngeometry, formed by the minimum and maximum (X,Y)\ncoordinates:\n \nExamples\n-------- \n((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX MINY))\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbr-definition/','','https://mariadb.com/kb/en/library/mbr-definition/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (84,6,'MBRContains','Syntax\n------ \nMBRContains(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether the Minimum Bounding\nRectangle of\ng1 contains the Minimum Bounding Rectangle of g2. This tests\nthe\nopposite relationship as MBRWithin().\n \nExamples\n-------- \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\n \nSET @g2 = GeomFromText(\'Point(1 1)\');\n \nSELECT MBRContains(@g1,@g2), MBRContains(@g2,@g1);\n+----------------------+----------------------+\n| MBRContains(@g1,@g2) | MBRContains(@g2,@g1) |\n+----------------------+----------------------+\n| 1 | 0 |\n+----------------------+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbrcontains/','','https://mariadb.com/kb/en/library/mbrcontains/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (85,6,'MBRDisjoint','Syntax\n------ \nMBRDisjoint(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether the Minimum Bounding\nRectangles of the two geometries g1 and g2 are disjoint. Two\ngeometries are disjoint if they do not intersect, that is\ntouch or overlap.\n \nExamples\n-------- \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((4 4,4 7,7 7,7 4,4 4))\');\nSELECTmbrdisjoint(@g1,@g2);\n+----------------------+\n| mbrdisjoint(@g1,@g2) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((3 3,3 6,6 6,6 3,3 3))\');\nSELECT mbrdisjoint(@g1,@g2);\n+----------------------+\n| mbrdisjoint(@g1,@g2) |\n+----------------------+\n| 0 |\n+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbrdisjoint/','','https://mariadb.com/kb/en/library/mbrdisjoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (86,6,'MBREqual','Syntax\n------ \nMBREqual(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether the Minimum Bounding\nRectangles of\nthe two geometries g1 and g2 are the same.\n \nExamples\n-------- \nSET @g1=GEOMFROMTEXT(\'LINESTRING(0 0, 1 2)\');\nSET @g2=GEOMFROMTEXT(\'POLYGON((0 0, 0 2, 1 2, 1 0, 0\n0))\');\nSELECT MbrEqual(@g1,@g2);\n+-------------------+\n| MbrEqual(@g1,@g2) |\n+-------------------+\n| 1 |\n+-------------------+\n \nSET @g1=GEOMFROMTEXT(\'LINESTRING(0 0, 1 3)\');\nSET @g2=GEOMFROMTEXT(\'POLYGON((0 0, 0 2, 1 4, 1 0, 0\n0))\');\nSELECT MbrEqual(@g1,@g2);\n+-------------------+\n| MbrEqual(@g1,@g2) |\n+-------------------+\n| 0 |\n+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbrequal/','','https://mariadb.com/kb/en/library/mbrequal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (87,6,'MBRIntersects','Syntax\n------ \nMBRIntersects(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether the Minimum Bounding\nRectangles of the two geometries g1 and g2 intersect.\n \nExamples\n-------- \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((3 3,3 6,6 6,6 3,3 3))\');\nSELECT mbrintersects(@g1,@g2);\n+------------------------+\n| mbrintersects(@g1,@g2) |\n+------------------------+\n| 1 |\n+------------------------+\n \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((4 4,4 7,7 7,7 4,4 4))\');\nSELECT mbrintersects(@g1,@g2);\n+------------------------+\n| mbrintersects(@g1,@g2) |\n+------------------------+\n| 0 |\n+------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbrintersects/','','https://mariadb.com/kb/en/library/mbrintersects/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (88,6,'MBROverlaps','Syntax\n------ \nMBROverlaps(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether the Minimum Bounding\nRectangles of\nthe two geometries g1 and g2 overlap. The term spatially\noverlaps is\nused if two geometries intersect and their intersection\nresults in a\ngeometry of the same dimension but not equal to either of\nthe given\ngeometries.\n \nExamples\n-------- \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((4 4,4 7,7 7,7 4,4 4))\');\nSELECT mbroverlaps(@g1,@g2);\n+----------------------+\n| mbroverlaps(@g1,@g2) |\n+----------------------+\n| 0 |\n+----------------------+\n \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((3 3,3 6,6 6,6 3,3 3))\');\nSELECT mbroverlaps(@g1,@g2);\n+----------------------+\n| mbroverlaps(@g1,@g2) |\n+----------------------+\n| 0 |\n+----------------------+\n \nSET @g1 = GeomFromText(\'Polygon((0 0,0 4,4 4,4 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((3 3,3 6,6 6,6 3,3 3))\');\nSELECT mbroverlaps(@g1,@g2);\n+----------------------+\n| mbroverlaps(@g1,@g2) |\n+----------------------+\n| 1 |\n+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbroverlaps/','','https://mariadb.com/kb/en/library/mbroverlaps/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (89,6,'MBRTouches','Syntax\n------ \nMBRTouches(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether the Minimum Bounding\nRectangles of\nthe two geometries g1 and g2 touch. Two geometries spatially\ntouch if\nthe interiors of the geometries do not intersect, but the\nboundary of\none of the geometries intersects either the boundary or the\ninterior\nof the other.\n \nExamples\n-------- \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((4 4,4 7,7 7,7 4,4 4))\');\nSELECT mbrtouches(@g1,@g2);\n+---------------------+\n| mbrtouches(@g1,@g2) |\n+---------------------+\n| 0 |\n+---------------------+\n \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((3 3,3 6,6 6,6 3,3 3))\');\nSELECT mbrtouches(@g1,@g2);\n+---------------------+\n| mbrtouches(@g1,@g2) |\n+---------------------+\n| 1 |\n+---------------------+\n \nSET @g1 = GeomFromText(\'Polygon((0 0,0 4,4 4,4 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((3 3,3 6,6 6,6 3,3 3))\');\nSELECT mbrtouches(@g1,@g2);\n+---------------------+\n| mbrtouches(@g1,@g2) |\n+---------------------+\n| 0 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbrtouches/','','https://mariadb.com/kb/en/library/mbrtouches/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (90,6,'MBRWithin','Syntax\n------ \nMBRWithin(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether the Minimum Bounding\nRectangle of\ng1 is within the Minimum Bounding Rectangle of g2. This\ntests the\nopposite relationship as MBRContains().\n \nExamples\n-------- \nSET @g1 = GeomFromText(\'Polygon((0 0,0 3,3 3,3 0,0 0))\');\nSET @g2 = GeomFromText(\'Polygon((0 0,0 5,5 5,5 0,0 0))\');\nSELECT MBRWithin(@g1,@g2), MBRWithin(@g2,@g1);\n+--------------------+--------------------+\n| MBRWithin(@g1,@g2) | MBRWithin(@g2,@g1) |\n+--------------------+--------------------+\n| 1 | 0 |\n+--------------------+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mbrwithin/','','https://mariadb.com/kb/en/library/mbrwithin/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (91,7,'CASE OPERATOR','Syntax\n------ \nCASE value WHEN [compare_value] THEN result [WHEN\n[compare_value] THEN\nresult ...] [ELSE result] END\n \nCASE WHEN [condition] THEN result [WHEN [condition] THEN\nresult ...]\n[ELSE result] END\n \nDescription\n----------- \nThe first version returns the result where\nvalue=compare_value. The\nsecond version returns the result for the first condition\nthat is\ntrue. If there was no matching result value, the result\nafter ELSE is\nreturned, or NULL if there is no ELSE part.\n \nThere is also a CASE statement, which differs from the CASE\noperator described here.\n \nExamples\n-------- \nSELECT CASE 1 WHEN 1 THEN \'one\' WHEN 2 THEN \'two\' ELSE\n\'more\' END;\n \n+------------------------------------------------------------+\n| CASE 1 WHEN 1 THEN \'one\' WHEN 2 THEN \'two\' ELSE\n\'more\' END |\n+------------------------------------------------------------+\n| one |\n+------------------------------------------------------------+\n \nSELECT CASE WHEN 1>0 THEN \'true\' ELSE \'false\' END;\n \n+--------------------------------------------+\n| CASE WHEN 1>0 THEN \'true\' ELSE \'false\' END |\n+--------------------------------------------+\n| true |\n+--------------------------------------------+\n \nSELECT CASE BINARY \'B\' WHEN \'a\' THEN 1 WHEN \'b\' THEN 2\nEND;\n \n+-----------------------------------------------------+\n| CASE BINARY \'B\' WHEN \'a\' THEN 1 WHEN \'b\' THEN 2 END\n|\n+-----------------------------------------------------+\n| NULL |\n+-----------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/case-operator/','','https://mariadb.com/kb/en/library/case-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (92,7,'IF Function','Syntax\n------ \nIF(expr1,expr2,expr3)\n \nDescription\n----------- \nIf expr1 is TRUE (expr1 0 and expr1 NULL) then IF()\nreturns expr2; otherwise it returns expr3. IF() returns a\nnumeric\nor string value, depending on the context in which it is\nused.\n \nNote: There is also an IF statement which differs from the\nIF() function described here.\n \nExamples\n-------- \nSELECT IF(1>2,2,3);\n+-------------+\n| IF(1>2,2,3) |\n+-------------+\n| 3 |\n+-------------+\n \nSELECT IF(1\n\nURL: https://mariadb.com/kb/en/library/if-function/','','https://mariadb.com/kb/en/library/if-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (93,7,'IFNULL','Syntax\n------ \nIFNULL(expr1,expr2)\n \nDescription\n----------- \nIf expr1 is not NULL, IFNULL() returns expr1; otherwise it\nreturns\nexpr2. IFNULL() returns a numeric or string value, depending\non the\ncontext in which it is used.\n \nExamples\n-------- \nSELECT IFNULL(1,0); \n+-------------+\n| IFNULL(1,0) |\n+-------------+\n| 1 |\n+-------------+\n \nSELECT IFNULL(NULL,10);\n+-----------------+\n| IFNULL(NULL,10) |\n+-----------------+\n| 10 |\n+-----------------+\n \nSELECT IFNULL(1/0,10);\n+----------------+\n| IFNULL(1/0,10) |\n+----------------+\n| 10.0000 |\n+----------------+\n \nSELECT IFNULL(1/0,\'yes\');\n+-------------------+\n| IFNULL(1/0,\'yes\') |\n+-------------------+\n| yes |\n+-------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/ifnull/','','https://mariadb.com/kb/en/library/ifnull/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (94,7,'NULLIF','Syntax\n------ \nNULLIF(expr1,expr2)\n \nDescription\n----------- \nReturns NULL if expr1 = expr2 is true, otherwise returns\nexpr1. This is\nthe same as CASE WHEN expr1 = expr2 THEN NULL ELSE expr1\nEND.\n \nExamples\n-------- \nSELECT NULLIF(1,1);\n+-------------+\n| NULLIF(1,1) |\n+-------------+\n| NULL |\n+-------------+\n \nSELECT NULLIF(1,2);\n+-------------+\n| NULLIF(1,2) |\n+-------------+\n| 1 |\n+-------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/nullif/','','https://mariadb.com/kb/en/library/nullif/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (95,8,'CHANGE MASTER TO','Syntax\n------ \nCHANGE MASTER [\'connection_name\'] TO master_def [,\nmaster_def] ...\n \nmaster_def:\n MASTER_BIND = \'interface_name\'\n | MASTER_HOST = \'host_name\'[\n | MASTER_USER = \'user_name\'\n | MASTER_PASSWORD = \'password\'\n | MASTER_PORT = port_num\n | MASTER_CONNECT_RETRY = interval\n | MASTER_HEARTBEAT_PERIOD = interval\n | MASTER_LOG_FILE = \'master_log_name\'\n | MASTER_LOG_POS = master_log_pos\n | RELAY_LOG_FILE = \'relay_log_name\'\n | RELAY_LOG_POS = relay_log_pos\n | MASTER_DELAY = interval\n | MASTER_SSL = {0|1}\n | MASTER_SSL_CA = \'ca_file_name\'\n | MASTER_SSL_CAPATH = \'ca_directory_name\'\n | MASTER_SSL_CERT = \'cert_file_name\'\n | MASTER_SSL_CRL = \'crl_file_name\'\n | MASTER_SSL_CRLPATH = \'crl_directory_name\'\n | MASTER_SSL_KEY = \'key_file_name\'\n | MASTER_SSL_CIPHER = \'cipher_list\'\n | MASTER_SSL_VERIFY_SERVER_CERT = {0|1}\n | MASTER_USE_GTID = {current_pos|slave_pos|no}\n | IGNORE_SERVER_IDS = (server_id_list)\n | DO_DOMAIN_IDS = ([N,..])\n | IGNORE_DOMAIN_IDS = ([N,..])\n \nDescription\n----------- \nThe CHANGE MASTER statement sets the options that a\nreplication slave uses to connect to and replicate from a\nreplication master. \n \nMariaDB until 10.0.7\n \nIn MariaDB 10.0.7 and before, the relay_log_purge system\nvariable was silently set to 0 when CHANGE MASTER was\nexecuted.\n \nMulti-Source Replication\n \nMulti-source replication was added in MariaDB 10.0.1.\n \nIf you are using multi-source replication, then you need to\nspecify a connection name when you execute CHANGE MASTER.\nThere are two ways to do this:\nSetting the default_master_connection system variable prior\nto executing CHANGE MASTER.\nSetting the connection_name parameter when executing CHANGE\nMASTER.\n \ndefault_master_connection\n \nSET default_master_connection = \'gandalf\';\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n MASTER_PASSWORD=\'new3cret\';\n \nSTART SLAVE;\n \nconnection_name\n \nSTOP SLAVE \'gandalf\';\n \nCHANGE MASTER \'gandalf\' TO \n MASTER_PASSWORD=\'new3cret\';\n \nSTART SLAVE \'gandalf\';\n \nOptions\n \nConnection Options\n \nMASTER_USER\n \nThe MASTER_USER option for CHANGE MASTER defines the user\naccount that the replication slave will use to connect to\nthe replication master.\n \nThis user account will need the REPLICATION SLAVE privilege\non the master.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_USER=\'repl\',\n MASTER_PASSWORD=\'new3cret\';\n \nSTART SLAVE;\n \nMASTER_PASSWORD\n \nThe MASTER_USER option for CHANGE MASTER defines the\npassword that the replication slave will use to connect to\nthe replication master as the user account defined by the\nMASTER_USER option.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n MASTER_PASSWORD=\'new3cret\';\n \nSTART SLAVE;\n \nMASTER_HOST\n \nThe MASTER_HOST option for CHANGE MASTER defines the\nhostname or IP address of the replication master.\n \nIf you set the value of the MASTER_HOST option to the empty\nstring, then that is not the same as not setting the\noption\'s value at all. In MariaDB 5.5 and later, if you set\nthe value of the MASTER_HOST option to the empty string,\nthen the CHANGE MASTER command will fail with an error. In\nMariaDB 5.3 and before, if you set the value of the\nMASTER_HOST option to the empty string, then the CHANGE\nMASTER command would succeed, but the subsequent START SLAVE\ncommand would fail.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_HOST=\'dbserver1.example.com\',\n MASTER_USER=\'repl\',\n MASTER_PASSWORD=\'new3cret\',\n MASTER_USE_GTID=slave_pos;\n \nSTART SLAVE;\n \nIf you set the value of the MASTER_HOST option in a CHANGE\nMASTER command, then the slave assumes that the master is\ndifferent from before, even if you set the value of this\noption to the same value it had previously. In this\nscenario, the slave will consider the old values for the\nmaster\'s binary\nlog file name and position to be invalid for the new master.\nAs a side effect, if you do not explicitly set the values of\nthe MASTER_LOG_FILE and MASTER_LOG_POS options in the\nstatement, then the statement will be implicitly appended\nwith MASTER_LOG_FILE=\'\' and MASTER_LOG_POS=4. However, if\nyou enable GTID mode for replication by setting the\nMASTER_USE_GTID option to some value other than no in the\nstatement, then these values will effectively be ignored\nanyway.\n \nReplication slaves cannot connect to replication masters\nusing Unix socket files or Windows named pipes. The\nreplication slave must connect to the replication master\nusing TCP/IP.\n \nMASTER_PORT\n \nThe MASTER_PORT option for CHANGE MASTER defines the TCP/IP\nport of the replication master.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_HOST=\'dbserver1.example.com\',\n MASTER_PORT=3307,\n MASTER_USER=\'repl\',\n MASTER_PASSWORD=\'new3cret\',\n MASTER_USE_GTID=slave_pos;\n \nSTART SLAVE;\n \nIf you set the value of the MASTER_PORT option in a CHANGE\nMASTER command, then the slave assumes that the master is\ndifferent from before, even if you set the value of this\noption to the same value it had previously. In this\nscenario, the slave will consider the old values for the\nmaster\'s binary\nlog file name and position to be invalid for the new master.\nAs a side effect, if you do not explicitly set the values of\nthe MASTER_LOG_FILE and MASTER_LOG_POS options in the\nstatement, then the statement will be implicitly appended\nwith MASTER_LOG_FILE=\'\' and MASTER_LOG_POS=4. However, if\nyou enable GTID mode for replication by setting the\nMASTER_USE_GTID option to some value other than no in the\nstatement, then these values will effectively be ignored\nanyway.\n \nReplication slaves cannot connect to replication masters\nusing Unix socket files or Windows named pipes. The\nreplication slave must connect to the replication master\nusing TCP/IP.\n \nMASTER_CONNECT_RETRY\n \nThe MASTER_CONNECT_RETRY option for CHANGE MASTER defines\nhow many seconds that the slave will wait between connection\nretries. The default is 60.\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n MASTER_CONNECT_RETRY=20;\n \nSTART SLAVE;\n \nThe number of connection attempts is limited by the\nmaster_retry_count option. It can be set either on the\ncommand-line or in a server option group in an option file\nprior to starting up the server. For example:\n \n[mariadb]\n...\nmaster_retry_count=4294967295\n \nMASTER_BIND\n \nThe MASTER_BIND option for CHANGE MASTER is only supported\nby MySQL 5.6.2 and later and by MySQL NDB Cluster 7.3.1 and\nlater. This option is not yet supported by MariaDB. See\nMDEV-19248 for more information.\n \nThe MASTER_BIND option for CHANGE MASTER can be used on\nreplication slaves that have multiple network interfaces to\nchoose which network interface the slave will use to connect\nto the master.\n \nMASTER_HEARTBEAT_PERIOD\n \nThe MASTER_HEARTBEAT_PERIOD option for CHANGE MASTER can be\nused to set the interval in seconds between replication\nheartbeats. Whenever the master\'s binary log is updated\nwith an event, the waiting period for the next heartbeat is\nreset.\n \nThis option\'s interval argument has the following\ncharacteristics:\nIt is a decimal value with a range of 0 to 4294967 seconds.\nIt has a resolution of hundredths of a second.\nIts smallest valid non-zero value is 0.001.\nIts default value is the value of the slave_net_timeout\nsystem variable divided by 2.\nIf it\'s set to 0, then heartbeats are disabled.\n \nHeartbeats are sent by the master only if there are no\nunsent events in the binary log file for a period longer\nthan the interval.\n \nIf the RESET SLAVE statement is executed, then the heartbeat\ninterval is reset to the default.\n \nIf the slave_net_timeout system variable is set to a value\nthat is lower than the current heartbeat interval, then a\nwarning will be issued.\n \nTLS Options\n \nThe TLS options are used for providing information about\nTLS. The options can be set even on slaves that are compiled\nwithout TLS support. The TLS options are saved to either the\ndefault master.info file or the file that is configured by\nthe master_info_file option, but these TLS options are\nignored unless the slave supports TLS.\n \nSee Replication with Secure Connections for more\ninformation.\n \nMASTER_SSL\n \nThe MASTER_SSL option for CHANGE MASTER tells the slave\nwhether to force TLS for the connection. The valid values\nare 0 or 1.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL=1;\n \nSTART SLAVE;\n \nMASTER_SSL_CA\n \nThe MASTER_SSL_CA option for CHANGE MASTER defines a path to\na PEM file that should contain one or more X509 certificates\nfor trusted Certificate Authorities (CAs) to use for TLS.\nThis option requires that you use the absolute path, not a\nrelative path. This option implies the MASTER_SSL option.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CA=\'/etc/my.cnf.d/certificates/ca.pem\',\n MASTER_SSL_VERIFY_SERVER_CERT=1;\n \nSTART SLAVE;\n \nSee Secure Connections Overview: Certificate Authorities\n(CAs) for more information.\n \nMASTER_SSL_CAPATH\n \nThe MASTER_SSL_CAPATH option for CHANGE MASTER defines a\npath to a directory that contains one or more PEM files that\nshould each contain one X509 certificate for a trusted\nCertificate Authority (CA) to use for TLS. This option\nrequires that you use the absolute path, not a relative\npath. The directory specified by this option needs to be run\nthrough the openssl rehash command. This option implies the\nMASTER_SSL option.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CAPATH=\'/etc/my.cnf.d/certificates/ca/\',\n MASTER_SSL_VERIFY_SERVER_CERT=1;\n \nSTART SLAVE;\n \nSee Secure Connections Overview: Certificate Authorities\n(CAs) for more information.\n \nMASTER_SSL_CERT\n \nThe MASTER_SSL_CERT option for CHANGE MASTER defines a path\nto the X509 certificate file to use for TLS. This option\nrequires that you use the absolute path, not a relative\npath. This option implies the MASTER_SSL option.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CA=\'/etc/my.cnf.d/certificates/ca.pem\',\n MASTER_SSL_VERIFY_SERVER_CERT=1;\n \nSTART SLAVE;\n \nMASTER_SSL_CRL\n \nThe MASTER_SSL_CRL option for CHANGE MASTER defines a path\nto a PEM file that should contain one or more revoked X509\ncertificates to use for TLS. This option requires that you\nuse the absolute path, not a relative path.\n \nThis option is only supported if the server was built with\nOpenSSL. If the server was built with yaSSL, then this\noption is not supported. See TLS and Cryptography Libraries\nUsed by MariaDB for more information about which libraries\nare used on which platforms.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CA=\'/etc/my.cnf.d/certificates/ca.pem\',\n MASTER_SSL_VERIFY_SERVER_CERT=1,\n MASTER_SSL_CRL=\'/etc/my.cnf.d/certificates/crl.pem\';\n \nSTART SLAVE;\n \nSee Secure Connections Overview: Certificate Revocation\nLists (CRLs) for more information.\n \nMASTER_SSL_CRLPATH\n \nThe MASTER_SSL_CRLPATH option for CHANGE MASTER defines a\npath to a directory that contains one or more PEM files that\nshould each contain one revoked X509 certificate to use for\nTLS. This option requires that you use the absolute path,\nnot a relative path. The directory specified by this\nvariable needs to be run through the openssl rehash command.\n \nThis option is only supported if the server was built with\nOpenSSL. If the server was built with yaSSL, then this\noption is not supported. See TLS and Cryptography Libraries\nUsed by MariaDB for more information about which libraries\nare used on which platforms.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CA=\'/etc/my.cnf.d/certificates/ca.pem\',\n MASTER_SSL_VERIFY_SERVER_CERT=1,\n MASTER_SSL_CRLPATH=\'/etc/my.cnf.d/certificates/crl/\';\n \nSTART SLAVE;\n \nSee Secure Connections Overview: Certificate Revocation\nLists (CRLs) for more information.\n \nMASTER_SSL_KEY\n \nThe MASTER_SSL_KEY option for CHANGE MASTER defines a path\nto a private key file to use for TLS. This option requires\nthat you use the absolute path, not a relative path. This\noption implies the MASTER_SSL option.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CA=\'/etc/my.cnf.d/certificates/ca.pem\',\n MASTER_SSL_VERIFY_SERVER_CERT=1;\n \nSTART SLAVE;\n \nMASTER_SSL_CIPHER\n \nThe MASTER_SSL_CIPHER option for CHANGE MASTER defines the\nlist of permitted ciphers or cipher suites to use for TLS.\nBesides cipher names, if MariaDB was compiled with OpenSSL,\nthis option could be set to \"SSLv3\" or \"TLSv1.2\" to\nallow all SSLv3 or all TLSv1.2 ciphers. Note that the\nTLSv1.3 ciphers cannot be excluded when using OpenSSL, even\nby using this option. See Using TLSv1.3 for details. This\noption implies the MASTER_SSL option.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CA=\'/etc/my.cnf.d/certificates/ca.pem\',\n MASTER_SSL_VERIFY_SERVER_CERT=1,\n MASTER_SSL_CIPHER=\'TLSv1.2\';\n \nSTART SLAVE;\n \nMASTER_SSL_VERIFY_SERVER_CERT\n \nThe MASTER_SSL_VERIFY_SERVER_CERT option for CHANGE MASTER\nenables server certificate verification. This option is\ndisabled by default.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_SSL_CERT=\'/etc/my.cnf.d/certificates/server-cert.pem\',\n MASTER_SSL_KEY=\'/etc/my.cnf.d/certificates/server-key.pem\',\n MASTER_SSL_CA=\'/etc/my.cnf.d/certificates/ca.pem\',\n MASTER_SSL_VERIFY_SERVER_CERT=1;\n \nSTART SLAVE;\n \nSee Secure Connections Overview: Server Certificate\nVerification for more information.\n \nBinary Log Options\n \nThese options are related to the binary log position on the\nmaster.\n \nMASTER_LOG_FILE\n \nThe MASTER_LOG_FILE option for CHANGE MASTER can be used\nalong with MASTER_LOG_POS to specify the coordinates at\nwhich the slave\'s I/O thread should begin reading from the\nmaster\'s binary logs the next time the thread starts.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_LOG_FILE=\'master2-bin.001\',\n MASTER_LOG_POS=4;\n \nSTART SLAVE;\n \nThe MASTER_LOG_FILE and MASTER_LOG_POS options cannot be\nspecified if the RELAY_LOG_FILE and RELAY_LOG_POS options\nwere also specified.\n \nThe MASTER_LOG_FILE and MASTER_LOG_POS options are\neffectively ignored if you enable GTID mode for replication\nby setting the MASTER_USE_GTID option to some value other\nthan no in the statement.\n \nMASTER_LOG_POS\n \nThe MASTER_LOG_POS option for CHANGE MASTER can be used\nalong with MASTER_LOG_FILE to specify the coordinates at\nwhich the slave\'s I/O thread should begin reading from the\nmaster\'s binary logs the next time the thread starts.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_LOG_FILE=\'master2-bin.001\',\n MASTER_LOG_POS=4;\n \nSTART SLAVE;\n \nThe MASTER_LOG_FILE and MASTER_LOG_POS options cannot be\nspecified if the RELAY_LOG_FILE and RELAY_LOG_POS options\nwere also specified.\n \nThe MASTER_LOG_FILE and MASTER_LOG_POS options are\neffectively ignored if you enable GTID mode for replication\nby setting the MASTER_USE_GTID option to some value other\nthan no in the statement.\n \nRelay Log Options\n \nThese options are related to the relay log position on the\nslave.\n \nRELAY_LOG_FILE\n \nThe RELAY_LOG_FILE option for CHANGE MASTER can be used\nalong with the RELAY_LOG_POS option to specify the\ncoordinates at which the slave\'s SQL thread should begin\nreading from the relay log the next time the thread starts.\n \nThe CHANGE MASTER statement usually deletes all relay log\nfiles. However, if the RELAY_LOG_FILE and/or RELAY_LOG_POS\noptions are specified, then existing relay log files are\nkept.\n \nWhen you want to change the relay log position, you only\nneed to stop the slave\'s SQL thread. The slave\'s I/O\nthread can continue running. The STOP SLAVE and START SLAVE\nstatements support the SQL_THREAD option for this scenario.\nFor example:\n \nSTOP SLAVE SQL_THREAD;\n \nCHANGE MASTER TO\n RELAY_LOG_FILE=\'slave-relay-bin.006\',\n RELAY_LOG_POS=4025;\n \nSTART SLAVE SQL_THREAD;\n \nWhen the value of this option is changed, the metadata about\nthe slave\'s SQL thread\'s position in the relay logs will\nalso be changed in the relay-log.info file or the file that\nis configured by the relay_log_info_file system variable.\n \nThe RELAY_LOG_FILE and RELAY_LOG_POS options cannot be\nspecified if the MASTER_LOG_FILE and MASTER_LOG_POS options\nwere also specified.\n \nRELAY_LOG_POS\n \nThe RELAY_LOG_POS option for CHANGE MASTER can be used along\nwith the RELAY_LOG_FILE option to specify the coordinates at\nwhich the slave\'s SQL thread should begin reading from the\nrelay log the next time the thread starts.\n \nThe CHANGE MASTER statement usually deletes all relay log\nfiles. However, if the RELAY_LOG_FILE and/or RELAY_LOG_POS\noptions are specified, then existing relay log files are\nkept.\n \nWhen you want to change the relay log position, you only\nneed to stop the slave\'s SQL thread. The slave\'s I/O\nthread can continue running. The STOP SLAVE and START SLAVE\nstatements support the SQL_THREAD option for this scenario.\nFor example:\n \nSTOP SLAVE SQL_THREAD;\n \nCHANGE MASTER TO\n RELAY_LOG_FILE=\'slave-relay-bin.006\',\n RELAY_LOG_POS=4025;\n \nSTART SLAVE SQL_THREAD;\n \nWhen the value of this option is changed, the metadata about\nthe slave\'s SQL thread\'s position in the relay logs will\nalso be changed in the relay-log.info file or the file that\nis configured by the relay_log_info_file system variable.\n \nThe RELAY_LOG_FILE and RELAY_LOG_POS options cannot be\nspecified if the MASTER_LOG_FILE and MASTER_LOG_POS options\nwere also specified.\n \nGTID Options\n \nMASTER_USE_GTID\n \nThe MASTER_USE_GTID option for CHANGE MASTER was first added\nin MariaDB 10.0.2 to enable replication with Global\nTransaction IDs (GTIDs).\n \nThe MASTER_USE_GTID option for CHANGE MASTER can be used to\nconfigure the slave to use the global transaction ID (GTID)\nwhen connecting to a master. The possible values are:\ncurrent_pos - Replicate in GTID mode and use\ngtid_current_pos as the position to start downloading\ntransactions from the master.\nslave_pos - Replicate in GTID mode and use gtid_slave_pos as\nthe position to start downloading transactions from the\nmaster.\nno - Don\'t replicate in GTID mode.\n \nFor example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO\n MASTER_USE_GTID = current_pos;\n \nSTART SLAVE;\n \nOr:\n \nSTOP SLAVE;\n \nSET GLOBAL gtid_slave_pos=\'0-1-153\';\n \nCHANGE MASTER TO\n MASTER_USE_GTID = slave','','https://mariadb.com/kb/en/library/change-master-to/'); +update help_topic set description = CONCAT(description, '_pos;\n \nSTART SLAVE;\n \nReplication Filter Options\n \nIGNORE_SERVER_IDS\n \nThe IGNORE_SERVER_IDS option for CHANGE MASTER can be used\nto configure a replication slave to ignore binary log events\nthat originated from certain servers. Filtered binary log\nevents will not get logged to the slave’s relay log, and\nthey will not be applied by the slave.\n \nThe option\'s value can be specified by providing a\ncomma-separated list of server_id values. For example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n IGNORE_SERVER_IDS = (3,5);\nSTART SLAVE;\n \nIf you would like to clear a previously set list, then you\ncan set the value to an empty list. For example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n IGNORE_SERVER_IDS = ();\nSTART SLAVE;\n \nDO_DOMAIN_IDS\n \nThe DO_DOMAIN_IDS option for CHANGE MASTER was first added\nin MariaDB 10.1.2.\n \nThe DO_DOMAIN_IDS option for CHANGE MASTER can be used to\nconfigure a replication slave to only apply binary log\nevents if the transaction\'s GTID is in a specific\ngtid_domain_id value. Filtered binary log events will not\nget logged to the slave’s relay log, and they will not be\napplied by the slave.\n \nThe option\'s value can be specified by providing a\ncomma-separated list of gtid_domain_id values. Duplicate\nvalues are automatically ignored. For example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n DO_DOMAIN_IDS = (1,2);\nSTART SLAVE;\n \nIf you would like to clear a previously set list, then you\ncan set the value to an empty list. For example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n DO_DOMAIN_IDS = ();\nSTART SLAVE;\n \nThe DO_DOMAIN_IDS option and the IGNORE_DOMAIN_IDS option\ncannot both be set to non-empty values at the same time. If\nyou want to set the DO_DOMAIN_IDS option, and the\nIGNORE_DOMAIN_IDS option was previously set, then you need\nto clear the value of the IGNORE_DOMAIN_IDS option. For\nexample:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n IGNORE_DOMAIN_IDS = (), \n DO_DOMAIN_IDS = (1,2);\nSTART SLAVE;\n \nThe DO_DOMAIN_IDS option can only be specified if the slave\nis replicating in GTID mode. Therefore, the MASTER_USE_GTID\noption must also be set to some value other than no in order\nto use this option.\n \nIGNORE_DOMAIN_IDS\n \nThe IGNORE_DOMAIN_IDS option for CHANGE MASTER was first\nadded in MariaDB 10.1.2.\n \nThe IGNORE_DOMAIN_IDS option for CHANGE MASTER can be used\nto configure a replication slave to ignore binary log events\nif the transaction\'s GTID is in a specific gtid_domain_id\nvalue. Filtered binary log events will not get logged to the\nslave’s relay log, and they will not be applied by the\nslave.\n \nThe option\'s value can be specified by providing a\ncomma-separated list of gtid_domain_id values. Duplicate\nvalues are automatically ignored. For example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n IGNORE_DOMAIN_IDS = (1,2);\nSTART SLAVE;\n \nIf you would like to clear a previously set list, then you\ncan set the value to an empty list. For example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n IGNORE_DOMAIN_IDS = ();\nSTART SLAVE;\n \nThe DO_DOMAIN_IDS option and the IGNORE_DOMAIN_IDS option\ncannot both be set to non-empty values at the same time. If\nyou want to set the IGNORE_DOMAIN_IDS option, and the\nDO_DOMAIN_IDS option was previously set, then you need to\nclear the value of the DO_DOMAIN_IDS option. For example:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n DO_DOMAIN_IDS = (), \n IGNORE_DOMAIN_IDS = (1,2);\nSTART SLAVE;\n \nThe IGNORE_DOMAIN_IDS option can only be specified if the\nslave is replicating in GTID mode. Therefore, the\nMASTER_USE_GTID option must also be set to some value other\nthan no in order to use this option.\n \nDelayed Replication Options\n \nMASTER_DELAY\n \nThe MASTER_DELAY option for CHANGE MASTER was first added in\nMariaDB 10.2.3 to enable delayed replication.\n \nThe MASTER_DELAY option for CHANGE MASTER can be used to\nenable delayed replication. This option specifies the time\nin seconds (at least) that a replication slave should lag\nbehind the master. Before executing an event, the slave will\nfirst wait, if necessary, until the given time has passed\nsince the event was created on the master. The result is\nthat the slave will reflect the state of the master some\ntime back in the past. The default is zero, no delay.\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n MASTER_DELAY=3600;\n \nSTART SLAVE;\n \nChanging Option Values\n \nIf you don\'t specify a given option when executing the\nCHANGE MASTER statement, then the option keeps its old value\nin most cases. Most of the time, there is no need to specify\nthe options that do not need to change. For example, if the\npassword for the user account that the slave uses to connect\nto its master has changed, but no other options need to\nchange, then you can just change the MASTER_PASSWORD option\nby executing the following commands:\n \nSTOP SLAVE;\n \nCHANGE MASTER TO \n MASTER_PASSWORD=\'new3cret\';\n \nSTART SLAVE;\n \nThere are some cases where options are implicitly reset,\nsuch as when the MASTER_HOST and MASTER_PORT options are\nchanged.\n \nOption Persistence\n \nThe values of the MASTER_LOG_FILE and MASTER_LOG_POS options\n(i.e. the binary log position on the master) and most other\noptions are written to either the default master.info file\nor the file that is configured by the master_info_file\noption. The slave\'s I/O thread keeps this binary log\nposition updated as it downloads events only when\nMASTER_USE_GTID option\n is set to NO. Otherwise the file is not updated on a per\nevent basis.\n \nThe master_info_file option can be set either on the\ncommand-line or in a server option group in an option file\nprior to starting up the server. For example:\n \n[mariadb]\n...\nmaster_info_file=/mariadb/myserver1-master.info\n \nThe values of the RELAY_LOG_FILE and RELAY_LOG_POS options\n(i.e. the relay log position) are written to either the\ndefault relay-log.info file or the file that is configured\nby the relay_log_info_file system variable. The slave\'s SQL\nthread keeps this relay log position updated as it applies\nevents.\n \nThe relay_log_info_file system variable can be set either on\nthe command-line or in a server option group in an option\nfile prior to starting up the server. For example:\n \n[mariadb]\n...\nrelay_log_info_file=/mariadb/myserver1-relay-log.info\n \nGTID Persistence\n \nIf the slave is replicating binary log events that contain\nGTIDs, then the slave\'s SQL thread will write every GTID\nthat it applies to the mysql.gtid_slave_pos table. This GTID\ncan be inspected and modified through the gtid_slave_pos\nsystem variable.\n \nIf the slave has the log_slave_updates system variable\nenabled and if the slave has the binary log enabled, then\nevery write by the slave\'s SQL thread will also go into the\nslave\'s binary log. This means that GTIDs of replicated\ntransactions would be reflected in the value of the\ngtid_binlog_pos system variable.\n \nCreating a Slave from a Backup\n \nThe CHANGE MASTER statement is useful for setting up a slave\nwhen you have a backup of the master and you also have the\nbinary log position or GTID position corresponding to the\nbackup.\n \nAfter restoring the backup on the slave, you could execute\nsomething like this to use the binary log position:\n \nCHANGE MASTER TO\n MASTER_LOG_FILE=\'master2-bin.001\',\n MASTER_LOG_POS=4;\n \nSTART SLAVE;\n \nOr you could execute something like this to use the GTID\nposition:\n \nSET GLOBAL gtid_slave_pos=\'0-1-153\';\n \nCHANGE MASTER TO\n MASTER_USE_GTID=slave_pos;\n \nSTART SLAVE;\n \nSee Setting up a Replication Slave with Mariabackup for more\ninformation on how to do this with Mariabackup.\n \nExample\n \nThe following example changes the master and master\'s\nbinary log coordinates.\nThis is used when you want to set up the slave to replicate\nthe master:\n \nCHANGE MASTER TO\n MASTER_HOST=\'master2.mycompany.com\',\n MASTER_USER=\'replication\',\n MASTER_PASSWORD=\'bigs3cret\',\n MASTER_PORT=3306,\n MASTER_LOG_FILE=\'master2-bin.001\',\n MASTER_LOG_POS=4,\n MASTER_CONNECT_RETRY=10;\n \nSTART SLAVE;\n \n\n\nURL: https://mariadb.com/kb/en/library/change-master-to/') WHERE help_topic_id = 95; +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (96,8,'COMMIT','The COMMIT statement ends a transaction, saving any changes\nto the data so that they become visible to subsequent\ntransactions. Also, unlocks metadata changed by current\ntransaction. If autocommit is set to 1, an implicit commit\nis performed after each statement. Otherwise, all\ntransactions which don\'t end with an explicit COMMIT are\nimplicitly rollbacked and the changes are lost. The ROLLBACK\nstatement can be used to do this explicitly.\n \nThe required syntax for the COMMIT statement is as follows:\n \nCOMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]\n \nCOMMIT is the more important transaction terminator, as well\nas the more interesting one. The basic form of the COMMIT\nstatement is simply the keyword COMMIT (the keyword WORK is\nsimply noise and can be omitted without changing the\neffect).\n \nThe optional AND CHAIN clause is a convenience for\ninitiating a new transaction as soon as the old transaction\nterminates. If AND CHAIN is specified, then there is\neffectively nothing between the old and new transactions,\nalthough they remain separate. The characteristics of the\nnew transaction will be the same as the characteristics of\nthe old one — that is, the new transaction will have the\nsame access mode, isolation level and diagnostics area size\n(we\'ll discuss all of these shortly) as the transaction\njust terminated. \n \nRELEASE tells the server to disconnect the client\nimmediately after the current transaction.\n \nThere are NO RELEASE and AND NO CHAIN options. By default,\ncommits do not RELEASE or CHAIN, but it\'s possible to\nchange this default behavior with the completion_type server\nsystem variable. In this case, the AND NO CHAIN and NO\nRELEASE options override the server default.\n \n\n\nURL: https://mariadb.com/kb/en/library/commit/','','https://mariadb.com/kb/en/library/commit/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (97,8,'DEALLOCATE / DROP PREPARE','Syntax\n------ \n{DEALLOCATE | DROP} PREPARE stmt_name\n \nDescription\n----------- \nTo deallocate a prepared statement produced with PREPARE,\nuse a\nDEALLOCATE PREPARE statement that refers to the prepared\nstatement\nname.\n \nA prepared statement is implicitly deallocated when a new\nPREPARE command is issued. In that case, there is no need to\nuse DEALLOCATE.\n \nAttempting to execute a prepared statement after\ndeallocating it\nresults in an error, as if it was not prepared at all:\n \nERROR 1243 (HY000): Unknown prepared statement handler\n(stmt_name) given to EXECUTE\n \nIf the specified statement has not been PREPAREd, an error\nsimilar to the following will be produced:\n \nERROR 1243 (HY000): Unknown prepared statement handler\n(stmt_name) given to DEALLOCATE PREPARE\n \nExample\n \nSee example in PREPARE.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/deallocate-drop-prepared-statement/','','https://mariadb.com/kb/en/library/deallocate-drop-prepared-statement/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (98,8,'EXECUTE Statement','Syntax\n------ \nEXECUTE stmt_name\n [USING expression[, expression] ...]\n \nEXECUTE with expression as parameters was introduced in\nMariaDB 10.2.3. Before that one could only use variables\n(@var_name) as parameters.\n \nDescription\n----------- \nAfter preparing a statement with PREPARE, you execute it\nwith an\nEXECUTE statement that refers to the prepared statement\nname. If the\nprepared statement contains any parameter markers, you must\nsupply a\nUSING clause that lists user variables containing the values\nto be\nbound to the parameters. Parameter values can be supplied\nonly by user\nvariables, and the USING clause must name exactly as many\nvariables as\nthe number of parameter markers in the statement.\n \nYou can execute a given prepared statement multiple times,\npassing\ndifferent variables to it or setting the variables to\ndifferent values\nbefore each execution.\n \nIf the specified statement has not been PREPAREd, an error\nsimilar to the following is produced:\n \nERROR 1243 (HY000): Unknown prepared statement handler\n(stmt_name) given to EXECUTE\n \nExample\n \nSee example in PREPARE.\n \n\n\nURL: https://mariadb.com/kb/en/library/execute-statement/','','https://mariadb.com/kb/en/library/execute-statement/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (99,8,'EXECUTE IMMEDIATE','EXECUTE IMMEDIATE was introduced in MariaDB 10.2.3.\n \nSyntax\n------ \nEXECUTE IMMEDIATE statement\n \nDescription\n----------- \nEXECUTE IMMEDIATE executes a dynamic SQL statement created\non the fly, which can reduce performance overhead.\n \nFor example:\n \nEXECUTE IMMEDIATE \'SELECT 1\' \n \nwhich is shorthand for:\n \nprepare stmt from \"select 1\";\n \nexecute stmt;\n \ndeallocate prepare stmt;\n \nEXECUTE IMMEDIATE supports complex expressions as prepare\nsource and parameters:\n \nEXECUTE IMMEDIATE CONCAT(\'SELECT COUNT(*) FROM \', \'t1\',\n\' WHERE a=?\') USING 5+5;\n \nLimitations: subselects and stored function calls are not\nsupported as a prepare source.\n \nThe following examples return an error:\n \nCREATE OR REPLACE FUNCTION f1() RETURNS VARCHAR(64) RETURN\n\'SELECT * FROM t1\';\nEXECUTE IMMEDIATE f1();\nERROR 1970 (42000): EXECUTE IMMEDIATE does not support\nsubqueries or stored functions\n \nEXECUTE IMMEDIATE (SELECT \'SELECT * FROM t1\');\nERROR 1064 (42000): You have an error in your SQL syntax;\ncheck the manual that \n corresponds to your MariaDB server version for the right\nsyntax to use near \n \'SELECT \'SELECT * FROM t1\')\' at line 1\n \nCREATE OR REPLACE FUNCTION f1() RETURNS INT RETURN 10;\nEXECUTE IMMEDIATE \'SELECT * FROM t1 WHERE a=?\' USING f1();\nERROR 1970 (42000): EXECUTE..USING does not support\nsubqueries or stored functions\n \nEXECUTE IMMEDIATE \'SELECT * FROM t1 WHERE a=?\' USING\n(SELECT 10);\nERROR 1064 (42000): You have an error in your SQL syntax;\ncheck the manual that \n corresponds to your MariaDB server version for the right\nsyntax to use near \n \'SELECT 10)\' at line 1\n \nOne can use a user or an SP variable as a workaround:\n \nCREATE OR REPLACE FUNCTION f1() RETURNS VARCHAR(64) RETURN\n\'SELECT * FROM t1\';\nSET @stmt=f1();\nEXECUTE IMMEDIATE @stmt;\n \nSET @stmt=(SELECT \'SELECT 1\');\nEXECUTE IMMEDIATE @stmt;\n \nCREATE OR REPLACE FUNCTION f1() RETURNS INT RETURN 10;\nSET @param=f1();\nEXECUTE IMMEDIATE \'SELECT * FROM t1 WHERE a=?\' USING\n@param;\n \nSET @param=(SELECT 10);\nEXECUTE IMMEDIATE \'SELECT * FROM t1 WHERE a=?\' USING\n@param;\n \nEXECUTE IMMEDIATE supports user variables and SP variables\nas OUT parameters\n \nDELIMITER $$\nCREATE OR REPLACE PROCEDURE p1(OUT a INT)\nBEGIN\n SET a:= 10;\nEND;\n$$\nDELIMITER ;\nSET @a=2;\nEXECUTE IMMEDIATE \'CALL p1(?)\' USING @a;\nSELECT @a;\n+------+\n| @a |\n+------+\n| 10 |\n+------+\n \nSimilar to PREPARE, EXECUTE IMMEDIATE is allowed in stored\nprocedures but is not allowed in stored functions.\n \nThis example uses EXECUTE IMMEDIATE inside a stored\nprocedure:\n \nDELIMITER $$\nCREATE OR REPLACE PROCEDURE p1()\nBEGIN\n EXECUTE IMMEDIATE \'SELECT 1\';\nEND;\n$$\nDELIMITER ;\nCALL p1;\n+---+\n| 1 |\n+---+\n| 1 |\n+---+\n \nThis script returns an error:\n \nDELIMITER $$\nCREATE FUNCTION f1() RETURNS INT\nBEGIN\n EXECUTE IMMEDIATE \'DO 1\';\n RETURN 1;\nEND;\n$$\nERROR 1336 (0A000): Dynamic SQL is not allowed in stored\nfunction or trigger\n \nEXECUTE IMMEDIATE can use DEFAULT and IGNORE indicators as\nbind parameters:\n \nCREATE OR REPLACE TABLE t1 (a INT DEFAULT 10);\nEXECUTE IMMEDIATE \'INSERT INTO t1 VALUES (?)\' USING\nDEFAULT;\nSELECT * FROM t1;\n+------+\n| a |\n+------+\n| 10 |\n+------+\n \nEXECUTE IMMEDIATE increments the Com_execute_immediate\nstatus variable, as well as the Com_stmt_prepare,\nCom_stmt_execute and Com_stmt_close status variables.\n \nNote, EXECUTE IMMEDIATE does not increment the\nCom_execute_sql status variable. Com_execute_sql is used\nonly for PREPARE..EXECUTE.\n \nThis session screenshot demonstrates how EXECUTE IMMEDIATE\naffects status variables:\n \nSELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS WHERE\nVARIABLE_NAME RLIKE \n (\'COM_(EXECUTE|STMT_PREPARE|STMT_EXECUTE|STMT_CLOSE)\');\n \n+-----------------------+----------------+\n| VARIABLE_NAME | VARIABLE_VALUE |\n+-----------------------+----------------+\n| COM_EXECUTE_IMMEDIATE | 0 |\n| COM_EXECUTE_SQL | 0 |\n| COM_STMT_CLOSE | 0 |\n| COM_STMT_EXECUTE | 0 |\n| COM_STMT_PREPARE | 0 |\n+-----------------------+----------------+\n \nEXECUTE IMMEDIATE \'SELECT 1\';\n+---+\n| 1 |\n+---+\n| 1 |\n+---+\n \nSELECT * FROM INFORMATION_SCHEMA.SESSION_STATUS WHERE\nVARIABLE_NAME RLIKE \n (\'COM_(EXECUTE|STMT_PREPARE|STMT_EXECUTE|STMT_CLOSE)\');\n+-----------------------+----------------+\n| VARIABLE_NAME | VARIABLE_VALUE |\n+-----------------------+----------------+\n| COM_EXECUTE_IMMEDIATE | 1 |\n| COM_EXECUTE_SQL | 0 |\n| COM_STMT_CLOSE | 1 |\n| COM_STMT_EXECUTE | 1 |\n| COM_STMT_PREPARE | 1 |\n+-----------------------+----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/execute-immediate/','','https://mariadb.com/kb/en/library/execute-immediate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (100,8,'LOCK TABLES','Syntax\n------ \nLOCK TABLE[S]\n tbl_name [[AS] alias] lock_type\n [, tbl_name [[AS] alias] lock_type] ...\n [WAIT n|NOWAIT]\n \nlock_type:\n READ [LOCAL]\n | [LOW_PRIORITY] WRITE\n | WRITE CONCURRENT\n \nUNLOCK TABLES\n \nDescription\n----------- \nThe lock_type can be one of:\n \nOption | Description | \n \nREAD | Read lock, no writes allowed | \n \nREAD LOCAL | Read lock, but allow concurrent inserts | \n \nWRITE | Exclusive write lock. No other connections can read\nor write to this table | \n \nLOW_PRIORITY WRITE | Exclusive write lock, but allow new\nread locks on the table until we get the write lock. | \n \nWRITE CONCURRENT | Exclusive write lock, but allow READ\nLOCAL locks to the table. | \n \nMariaDB enables client sessions to acquire table locks\nexplicitly for the\npurpose of cooperating with other sessions for access to\ntables, or to\nprevent other sessions from modifying tables during periods\nwhen a\nsession requires exclusive access to them. A session can\nacquire or\nrelease locks only for itself. One session cannot acquire\nlocks for\nanother session or release locks held by another session.\n \nLocks may be used to emulate transactions or to get more\nspeed when\nupdating tables.\n \nLOCK TABLES explicitly acquires table locks for the current\nclient session.\nTable locks can be acquired for base tables or views. To use\nLOCK TABLES,\nyou must have the LOCK TABLES privilege, and the SELECT\nprivilege for\neach object to be locked. See GRANT\n \nFor view locking, LOCK TABLES adds all base tables used in\nthe view to the\nset of tables to be locked and locks them automatically. If\nyou lock a table\nexplicitly with LOCK TABLES, any tables used in triggers are\nalso locked\nimplicitly, as described in Triggers and Implicit Locks.\n \nUNLOCK TABLES explicitly releases any table locks held by\nthe\ncurrent session.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \nLimitations\n \nLOCK TABLES doesn\'t work when using Galera cluster. You may\nexperience crashes or locks when used with Galera.\n \nLOCK TABLES works on XtraDB/InnoDB tables only if the\ninnodb_table_locks system variable is set to 1 (the default)\nand autocommit is set to 0 (1 is default). Please note that\nno error message will be returned on LOCK TABLES with\ninnodb_table_locks = 0.\n \nLOCK TABLES implicitly commits the active transaction, if\nany. Also, starting a transaction always releases all table\nlocks acquired with LOCK TABLES. This means that there is no\nway to have table locks and an active transaction at the\nsame time. The only exceptions are the transactions in\nautocommit mode. To preserve the data integrity between\ntransactional and non-transactional tables, the GET_LOCK()\nfunction can be used.\n \nWhile a connection holds an explicit read lock on a table,\nit cannot modify it. If you try, the following error will be\nproduced:\n \nERROR 1099 (HY000): Table \'tab_name\' was locked with a\nREAD lock and can\'t be updated\n \nWhile a connection holds an explicit lock on a table, it\ncannot access a non-locked table. If you try, the following\nerror will be produced:\n \nERROR 1100 (HY000): Table \'tab_name\' was not locked with\nLOCK TABLES\n \nWhile a connection holds an explicit lock on a table, it\ncannot issue the following: INSERT DELAYED, CREATE TABLE,\nCREATE TABLE ... LIKE, and DDL statements involving stored\nprograms and views (except for triggers). If you try, the\nfollowing error will be produced:\n \nERROR 1192 (HY000): Can\'t execute the given command because\nyou have active locked tables or an active transaction\n \nLOCK TABLES can not be used in stored routines - if you try,\nthe following error will be produced on creation:\n \nERROR 1314 (0A000): LOCK is not allowed in stored procedures\n \n\n\nURL: https://mariadb.com/kb/en/library/lock-tables/','','https://mariadb.com/kb/en/library/lock-tables/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (101,8,'ROLLBACK','The ROLLBACK statement rolls back (ends) a transaction,\ndestroying any changes to SQL-data so that they never become\nvisible to subsequent transactions. The required syntax for\nthe ROLLBACK statement is as follows. \n \nROLLBACK [ WORK ] [ AND [ NO ] CHAIN ] \n[ TO [ SAVEPOINT ] { | } ]\n \nThe ROLLBACK statement will either end a transaction,\ndestroying all data changes that happened during any of the\ntransaction, or it will just destroy any data changes that\nhappened since you established a savepoint. The basic form\nof the ROLLBACK statement is just the keyword ROLLBACK (the\nkeyword WORK is simply noise and can be omitted without\nchanging the effect). \n \nThe optional AND CHAIN clause is a convenience for\ninitiating a new transaction as soon as the old transaction\nterminates. If AND CHAIN is specified, then there is\neffectively nothing between the old and new transactions,\nalthough they remain separate. The characteristics of the\nnew transaction will be the same as the characteristics of\nthe old one — that is, the new transaction will have the\nsame access mode, isolation level and diagnostics area size\n(we\'ll discuss all of these shortly) as the transaction\njust terminated. The AND NO CHAIN option just tells your\nDBMS to end the transaction — that is, these four SQL\nstatements are equivalent: \n \nROLLBACK;\n \nROLLBACK WORK;\n \nROLLBACK AND NO CHAIN;\n \nROLLBACK WORK AND NO CHAIN;\n \nAll of them end a transaction without saving any transaction\ncharacteristics. The only other options, the equivalent\nstatements: \n \nROLLBACK AND CHAIN;\n \nROLLBACK WORK AND CHAIN;\n \nboth tell your DBMS to end a transaction, but to save that\ntransaction\'s characteristics for the next transaction. \n \nROLLBACK is much simpler than COMMIT: it may involve no more\nthan a few deletions (of Cursors, locks, prepared SQL\nstatements and log-file entries). It\'s usually assumed that\nROLLBACK can\'t fail, although such a thing is conceivable\n(for example, an encompassing transaction might reject an\nattempt to ROLLBACK because it\'s lining up for a COMMIT). \n \nROLLBACK cancels all effects of a transaction. It does not\ncancel effects on objects outside the DBMS\'s control (for\nexample the values in host program variables or the settings\nmade by some SQL/CLI function calls). But in general, it is\na convenient statement for those situations when you say\n\"oops, this isn\'t working\" or when you simply don\'t care\nwhether your temporary work becomes permanent or not.\n \nHere is a moot question. If all you\'ve been doing is\nSELECTs, so that there have been no data changes, should you\nend the transaction with ROLLBACK or COMMIT? It shouldn\'t\nreally matter because both ROLLBACK and COMMIT do the same\ntransaction-terminating job. However, the popular conception\nis that ROLLBACK implies failure, so after a successful\nseries of SELECT statements the convention is to end the\ntransaction with COMMIT rather than ROLLBACK.\n \nMariaDB (and most other DBMSs) supports rollback of SQL-data\nchange statements, but not of SQL-Schema statements. This\nmeans that if you use any of CREATE, ALTER, DROP, GRANT,\nREVOKE, you are implicitly committing at execution time.\n \nINSERT INTO Table_2 VALUES(5); \nDROP TABLE Table_3 CASCADE;\n \nROLLBACK;\n \nThe result will be that both the INSERT and the DROP will go\nthrough as separate transactions so the ROLLBACK will have\nno effect. \n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/rollback/','','https://mariadb.com/kb/en/library/rollback/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (102,8,'SAVEPOINT','Syntax\n------ \nSAVEPOINT identifier\nROLLBACK [WORK] TO [SAVEPOINT] identifier\nRELEASE SAVEPOINT identifier\n \nDescription\n----------- \nInnoDB supports the SQL statements SAVEPOINT,\nROLLBACK TO SAVEPOINT, RELEASE SAVEPOINT\nand the optional WORK keyword for\nROLLBACK.\n \nEach savepoint must have a legal MariaDB identifier. A\nsavepoint is a named sub-transaction.\n \nNormally ROLLBACK undoes the changes performed by the whole\ntransaction. When used with the TO clause, it undoes the\nchanges performed after the specified savepoint, and erases\nall subsequent savepoints. However, all locks that have been\nacquired after the save point will survive. RELEASE\nSAVEPOINT does not rollback or commit any changes, but\nremoves the specified savepoint.\n \nWhen the execution of a trigger or a stored function begins,\nit is not possible to use statements which reference a\nsavepoint which was defined from out of that stored program.\n \nWhen a COMMIT (including implicit commits) or a ROLLBACK\nstatement (with no TO clause) is performed, they act on the\nwhole transaction, and all savepoints are removed.\n \nErrors\n \nIf COMMIT or ROLLBACK is issued and no transaction was\nstarted, no error is reported.\n \nIf SAVEPOINT is issued and no transaction was started, no\nerror is reported but no savepoint is created. When ROLLBACK\nTO SAVEPOINT or RELEASE SAVEPOINT is called for a savepoint\nthat does not exist, an error like this is issued:\n \nERROR 1305 (42000): SAVEPOINT svp_name does not exist\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/savepoint/','','https://mariadb.com/kb/en/library/savepoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (103,8,'Metadata Locking','Metadata locking has been supported since MariaDB 5.5. This\nmeans that when a transaction (including XA transactions)\nuses a table, it locks its metadata until the end of\ntransaction. Non-transactional tables are also locked, as\nwell as views and objects which are related to locked\ntables/views (stored functions, triggers, etc). When a\nconnection tries to use a DDL statement (like an ALTER\nTABLE) which modifies a table that is locked, that\nconnection is queued, and has to wait until it\'s unlocked.\nUsing savepoints and performing a partial rollback does not\nrelease metadata locks.\n \nLOCK TABLES ... WRITE are also queued. Some wrong statements\nwhich produce an error may not need to wait for the lock to\nbe freed.\n \nMetadata lock\'s timeout is determined by the value of the\nlock_wait_timeout server system variable (in seconds).\nHowever, note that its default value is 31536000 (1 year).\nIf this timeout exceeds, the following error is returned:\n \nERROR 1205 (HY000): Lock wait timeout exceeded;\n try restarting transaction\n \nIf the metadata_lock_info plugin is installed, the\nInformation Schema metadata_lock_info table stores\ninformation about existing metadata locks.\n \nExample\n \nLet\'s use the following MEMORY (non-transactional) table:\n \nCREATE TABLE t (a INT) ENGINE = MEMORY;\n \nConnection 1 starts a transaction, and INSERTs a row into t:\n \nSTART TRANSACTION;\n \nINSERT INTO t SET a=1;\n \nt\'s metadata is now locked by connection 1. Connection 2\ntries to alter t, but has to wait:\n \nALTER TABLE t ADD COLUMN b INT;\n \nConnection 2\'s prompt is blocked now.\n \nNow connection 1 ends the transaction:\n \nCOMMIT;\n \n...and connection 2 finally gets the output of its command:\n \nQuery OK, 1 row affected (35.23 sec)\nRecords: 1 Duplicates: 0 Warnings: 0\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/metadata-locking/','','https://mariadb.com/kb/en/library/metadata-locking/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (104,8,'PREPARE Statement','Syntax\n------ \nPREPARE stmt_name FROM preparable_stmt\n \nDescription\n----------- \nThe PREPARE statement prepares a statement and assigns it a\nname,\nstmt_name, by which to refer to the statement later.\nStatement names\nare not case sensitive. preparable_stmt is either a string\nliteral or a user variable (not a local variable, an SQL\nexpression or a subquery) that contains the text of the\nstatement. The text must \nrepresent a single SQL statement, not multiple statements.\nWithin the\nstatement, \"?\" characters can be used as parameter markers\nto indicate\nwhere data values are to be bound to the query later when\nyou execute\nit. The \"?\" characters should not be enclosed within\nquotes, even if\nyou intend to bind them to string values. Parameter markers\ncan be used\nonly where data values should appear, not for SQL keywords,\nidentifiers, and so forth.\n \nThe scope of a prepared statement is the session within\nwhich it is\ncreated. Other sessions cannot see it.\n \nIf a prepared statement with the given name already exists,\nit is\ndeallocated implicitly before the new statement is prepared.\nThis means\nthat if the new statement contains an error and cannot be\nprepared, an\nerror is returned and no statement with the given name\nexists.\n \nPrepared statements can be PREPAREd and EXECUTEd in a stored\nprocedure, but not in a stored function or trigger. Also,\neven if the statement is PREPAREd in a procedure, it will\nnot be deallocated when the procedure execution ends.\n \nA prepared statement can access user-defined variables, but\nnot local variables or procedure\'s parameters.\n \nIf the prepared statement contains a syntax error, PREPARE\nwill fail. As a side effect, stored procedures can use it to\ncheck if a statement is valid. For example:\n \nCREATE PROCEDURE `test_stmt`(IN sql_text TEXT)\nBEGIN\n DECLARE EXIT HANDLER FOR SQLEXCEPTION\n BEGIN\n SELECT CONCAT(sql_text, \' is not valid\');\n END;\n SET @SQL := sql_text;\n PREPARE stmt FROM @SQL;\n DEALLOCATE PREPARE stmt;\nEND;\n \nThe FOUND_ROWS() and ROW_COUNT() functions, if called\nimmediatly after EXECUTE, return the number of rows read or\naffected by the prepared statements; however, if they are\ncalled after DEALLOCATE PREPARE, they provide information\nabout this statement. If the prepared statement produces\nerrors or warnings, GET DIAGNOSTICS return information about\nthem. DEALLOCATE PREPARE shouldn\'t clear the diagnostics\narea, unless it produces an error.\n \nA prepared statement is executed with EXECUTE and released \nwith DEALLOCATE PREPARE.\n \nThe max_prepared_stmt_count server system variable\ndetermines the number of allowed prepared statements that\ncan be prepared on the server. If it is set to 0, prepared\nstatements are not allowed. If the limit is reached, an\nerror similar to the following will be produced:\n \nERROR 1461 (42000): Can\'t create more than\nmax_prepared_stmt_count statements \n (current value: 0)\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, PREPARE stmt FROM \'SELECT\n:1, :2\' is used, instead of ?.\n \nPermitted Statements\n \nNot all statements can be prepared. Only the following SQL\ncommands are permitted:\nALTER TABLE\nANALYZE TABLE\nBINLOG\nCACHE INDEX\nCALL\nCHANGE MASTER\nCHECKSUM {TABLE | TABLES}\nCOMMIT\n{CREATE | DROP} DATABASE\n{CREATE | DROP} INDEX\n{CREATE | RENAME | DROP} TABLE\n{CREATE | RENAME | DROP} USER\n{CREATE | DROP} VIEW\nDELETE\nDESCRIBE\nDO\nEXPLAIN\nFLUSH {TABLE | TABLES | TABLES WITH READ LOCK | HOSTS |\nPRIVILEGES | LOGS | STATUS | \n MASTER | SLAVE | DES_KEY_FILE | USER_RESOURCES | QUERY\nCACHE | TABLE_STATISTICS | \n INDEX_STATISTICS | USER_STATISTICS | CLIENT_STATISTICS}\nGRANT\nINSERT\nINSTALL {PLUGIN | SONAME}\nHANDLER READ\nKILL\nLOAD INDEX INTO CACHE\nOPTIMIZE TABLE\nREPAIR TABLE\nREPLACE\nRESET {MASTER | SLAVE | QUERY CACHE}\nREVOKE\nROLLBACK\nSELECT\nSET\nSET GLOBAL SQL_SLAVE_SKIP_COUNTER\nSET ROLE\nSET SQL_LOG_BIN\nSET TRANSACTION ISOLATION LEVEL\nSHOW EXPLAIN\nSHOW {DATABASES | TABLES | OPEN TABLES | TABLE STATUS |\nCOLUMNS | INDEX | TRIGGERS | \n EVENTS | GRANTS | CHARACTER SET | COLLATION | ENGINES |\nPLUGINS [SONAME] | PRIVILEGES | \n PROCESSLIST | PROFILE | PROFILES | VARIABLES | STATUS |\nWARNINGS | ERRORS | \n TABLE_STATISTICS | INDEX_STATISTICS | USER_STATISTICS |\nCLIENT_STATISTICS | AUTHORS | \n CONTRIBUTORS}\nSHOW CREATE {DATABASE | TABLE | VIEW | PROCEDURE | FUNCTION\n| TRIGGER | EVENT}\nSHOW {FUNCTION | PROCEDURE} CODE\nSHOW BINLOG EVENTS\nSHOW SLAVE HOSTS\nSHOW {MASTER | BINARY} LOGS\nSHOW {MASTER | SLAVE | TABLES | INNODB | FUNCTION |\nPROCEDURE} STATUS\nSLAVE {START | STOP}\nTRUNCATE TABLE\nSHUTDOWN\nUNINSTALL {PLUGIN | SONAME}\nUPDATE\n \nSynonyms are not listed here, but can be used. For example,\nDESC can be used instead of DESCRIBE.\n \nCompound statements can be prepared too.\n \nNote that if a statement can be run in a stored routine, it\nwill work even if it is called by a prepared statement. For\nexample, SIGNAL can\'t be directly prepared. However, it is\nallowed in stored routines. If the x() procedure contains\nSIGNAL, you can still prepare and execute the \'CALL x();\'\nprepared statement.\n \nPREPARE now supports most kinds of expressions as well, for\nexample:\n \nPREPARE stmt FROM CONCAT(\'SELECT * FROM \', table_name);\n \nWhen PREPARE is used with a statement which is not\nsupported, the following error is produced:\n \nERROR 1295 (HY000): This command is not supported in the\nprepared statement protocol yet\n \nExample\n \ncreate table t1 (a int,b char(10));\ninsert into t1 values (1,\"one\"),(2,\n\"two\"),(3,\"three\");\nprepare test from \"select * from t1 where a=?\";\nset @param=2;\nexecute test using @param;\n+------+------+\n| a | b |\n+------+------+\n| 2 | two |\n+------+------+\nset @param=3;\nexecute test using @param;\n+------+-------+\n| a | b |\n+------+-------+\n| 3 | three |\n+------+-------+\ndeallocate prepare test;\n \nSince identifiers are not permitted as prepared statements\nparameters, sometimes it is necessary to dynamically compose\nan SQL statement. This technique is called dynamic SQL). The\nfollowing example shows how to use dynamic SQL:\n \nCREATE PROCEDURE test.stmt_test(IN tab_name VARCHAR(64))\nBEGIN\n SET @sql = CONCAT(\'SELECT COUNT(*) FROM \', tab_name);\n PREPARE stmt FROM @sql;\n EXECUTE stmt;\n DEALLOCATE PREPARE stmt;\nEND;\n \nCALL test.stmt_test(\'mysql.user\');\n+----------+\n| COUNT(*) |\n+----------+\n| 4 |\n+----------+\n \nUse of variables in prepared statements:\n \nPREPARE stmt FROM \'SELECT @x;\';\n \nSET @x = 1;\n \nEXECUTE stmt;\n+------+\n| @x |\n+------+\n| 1 |\n+------+\n \nSET @x = 0;\n \nEXECUTE stmt;\n+------+\n| @x |\n+------+\n| 0 |\n+------+\n \nDEALLOCATE PREPARE stmt;\n \n\n\nURL: https://mariadb.com/kb/en/library/prepare-statement/','','https://mariadb.com/kb/en/library/prepare-statement/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (105,8,'PURGE BINARY LOGS','Syntax\n------ \nPURGE { BINARY | MASTER } LOGS\n { TO \'log_name\' | BEFORE datetime_expr }\n \nDescription\n----------- \nThe PURGE BINARY LOGS statement deletes all the binary log\nfiles listed in the log index file prior to the specified\nlog file name or\ndate. BINARY and MASTER are synonyms.\nDeleted log files also are removed from the list recorded in\nthe index file, so\nthat the given log file becomes the first in the list.\n \nThe datetime expression is in the format \'YYYY-MM-DD\nhh:mm:ss\'. \n \nIf a slave is active but has yet to read from a binary log\nfile you attempt to delete, the statement will fail with an\nerror. However, if the slave is not connected and has yet to\nread from a log file you delete, the file will be deleted,\nbut the slave will be unable to continue replicating once it\nconnects again.\n \nThis statement has no effect if the server was not started\nwith the\n--log-bin option to enable binary logging.\n \nTo list the binary log files on the server, use SHOW BINARY\nLOGS. To see which files they are reading, use SHOW SLAVE\nSTATUS. You can only delete the files that are older than\nthe oldest file that is used by the slaves.\n \nTo delete all binary log files, use RESET MASTER.\nTo move to a new log file (for example if you want to remove\nthe current log file), use FLUSH LOGS before you execute\nPURGE LOGS.\n \nIf the expire_logs_days server system variable is not set to\n0, the server automatically deletes binary log files after\nthe given number of days.\n \nExamples\n-------- \nPURGE BINARY LOGS TO \'mariadb-bin.000063\';\n \nPURGE BINARY LOGS BEFORE \'2013-04-21\';\n \nPURGE BINARY LOGS BEFORE \'2013-04-22 09:55:22\';\n \n\n\nURL: https://mariadb.com/kb/en/library/purge-binary-logs/','','https://mariadb.com/kb/en/library/purge-binary-logs/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (106,8,'RESET MASTER','RESET MASTER [TO #]\n \nDeletes all binary log files listed in the index file,\nresets the\nbinary log index file to be empty, and creates a new binary\nlog file with a suffix of .000001.\n \nIf TO # is given, then the first new binary log file will\nstart from number #.\n \nThis statement is for use only when the master is started\nfor the first time, and should never be used if any slaves\nare actively replicating from the binary log.\n \n\n\nURL: https://mariadb.com/kb/en/library/reset-master/','','https://mariadb.com/kb/en/library/reset-master/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (107,8,'RESET SLAVE','RESET SLAVE [\"connection_name\"] [ALL] \n \nRESET SLAVE makes the slave forget its replication position\nin the\nmaster\'s binary log. This statement is meant to be used for\na clean\nstart. It deletes the master.info and relay-log.info files,\nall the\nrelay log files, and starts a new relay log file. To use\nRESET SLAVE,\nthe slave replication threads must be stopped (use STOP\nSLAVE if\nnecessary).\n \nNote: All relay log files are deleted, even if they have not\nbeen\ncompletely executed by the slave SQL thread. (This is a\ncondition\nlikely to exist on a replication slave if you have issued a\nSTOP SLAVE\nstatement or if the slave is highly loaded.)\n \nConnection information stored in the master.info file is\nimmediately\nreset using any values specified in the corresponding\nstartup options.\nThis information includes values such as master host, master\nport,\nmaster user, and master password. If the slave SQL thread\nwas in the\nmiddle of replicating temporary tables when it was stopped,\nand RESET\nSLAVE is issued, these replicated temporary tables are\ndeleted on the\nslave.\n \nThe ALL also resets the PORT, HOST, USER and PASSWORD\nparameters for the slave. If you are using a connection\nname, it will permanently delete it and it will not show up\nanymore in SHOW ALL SLAVES STATUS.\n \nconnection_name\n \nThe connection_name option was added as part of multi-source\nreplication added in MariaDB 10.0\n \nIf there is only one nameless master, or the default master\n(as specified by the default_master_connection system\nvariable) is intended, connection_name can be omitted. If\nprovided, the RESET SLAVE statement will apply to the\nspecified master. connection_name is case-insensitive.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/reset-slave-connection_name/','','https://mariadb.com/kb/en/library/reset-slave-connection_name/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (108,8,'SET TRANSACTION','Syntax\n------ \nSET [GLOBAL | SESSION] TRANSACTION\n transaction_property [, transaction_property] ...\n \ntransaction_property:\n ISOLATION LEVEL level\n | READ WRITE\n | READ ONLY\n \nlevel:\n REPEATABLE READ\n | READ COMMITTED\n | READ UNCOMMITTED\n | SERIALIZABLE\n \nDescription\n----------- \nThis statement sets the transaction isolation level or the\ntransaction access mode globally, for the current session,\nor for the next transaction:\nWith the GLOBAL keyword, the statement sets the default\n transaction level globally for all subsequent sessions.\nExisting sessions are\n unaffected.\nWith the SESSION keyword, the statement sets the default\n transaction level for all subsequent transactions performed\nwithin the\n current session.\nWithout any SESSION or GLOBAL keyword,\n the statement sets the isolation level for the next (not\nstarted) transaction\n performed within the current session.\n \nA change to the global default isolation level requires the \nSUPER privilege. Any session is free to change its\nsession isolation level (even in the middle of a\ntransaction), or the isolation\nlevel for its next transaction.\n \nIsolation Level\n \nTo set the global default isolation level at server startup,\nuse the\n--transaction-isolation=level option on the command line or\nin an option file. Values of level for this option use\ndashes\nrather than spaces, so the allowable values are\nREAD-UNCOMMITTED,\nREAD-COMMITTED, REPEATABLE-READ, or\nSERIALIZABLE. For example, to set the default isolation\nlevel to REPEATABLE READ, use these lines in the [mysqld]\nsection of an option file:\n \n[mysqld]\ntransaction-isolation = REPEATABLE-READ\nTo determine the global and session transaction isolation\nlevels at\nruntime, check the value of the tx_isolation system\nvariable:\n \nSELECT @@GLOBAL.tx_isolation, @@tx_isolation;\n \nInnoDB supports each of the translation isolation levels\ndescribed here\nusing different locking strategies. The default level is \nREPEATABLE READ. For additional information about InnoDB\nrecord-level locks and how it uses them to execute various\ntypes of statements,\nsee XtraDB/InnoDB Lock Modes,\nand\nhttp://dev.mysql.com/doc/refman/en/innodb-locks-set.html.\n \nIsolation Levels\n \nThe following sections describe how MariaDB supports the\ndifferent transaction levels.\n \nREAD UNCOMMITTED\n \nSELECT statements are performed in a non-locking fashion,\nbut a possible earlier version of a row might be used. Thus,\nusing this\nisolation level, such reads are not consistent. This is also\ncalled a \"dirty\nread.\" Otherwise, this isolation level works like \nREAD COMMITTED.\n \nREAD COMMITTED\n \nA somewhat Oracle-like isolation level with respect to\nconsistent\n(non-locking) reads: Each consistent read, even within the\nsame\ntransaction, sets and reads its own fresh snapshot. See\nhttp://dev.mysql.com/doc/refman/en/innodb-consistent-read.html.\n \nFor locking reads (SELECT with FOR UPDATE\nor LOCK IN SHARE MODE), InnoDB locks only index records, not\nthe gaps before them, and thus allows the free insertion of\nnew records next to\nlocked records. For UPDATE and DELETE\nstatements, locking depends on whether the statement uses a\nunique index with a\nunique search condition (such as WHERE id = 100), or a\nrange-type search condition (such as WHERE id > 100). For a\nunique index with a unique search condition, InnoDB locks\nonly the index record\nfound, not the gap before it. For range-type searches,\nInnoDB locks the index\nrange scanned, using gap locks or next-key (gap plus\nindex-record) locks to\nblock insertions by other sessions into the gaps covered by\nthe range. This is\nnecessary because \"phantom rows\" must be blocked for MySQL\nreplication and\nrecovery to work.\n \nNote: Since MariaDB 5.1, if the READ COMMITTED isolation\nlevel is used or the innodb_locks_unsafe_for_binlog system\nvariable is enabled,\nthere is no InnoDB gap locking except for foreign-key\nconstraint checking and\nduplicate-key checking. Also, record locks for non-matching\nrows are released\nafter MariaDB has evaluated the WHERE condition. As of\nMariaDB/MySQL\n5.1, if you use READ COMMITTED or enable\ninnodb_locks_unsafe_for_binlog, you must use row-based\nbinary logging.\n \nREPEATABLE READ\n \nThis is the default isolation level for InnoDB. For\nconsistent reads,\nthere is an important difference from the READ COMMITTED\nisolation level: All consistent reads within the same\ntransaction read the\nsnapshot established by the first read. This convention\nmeans that if you issue\nseveral plain (non-locking) SELECT statements within the\nsame transaction, these SELECT statements are consistent\nalso with respect to each other. See\nhttp://dev.mysql.com/doc/refman/en/innodb-consistent-read.html.\n \nFor locking reads (SELECT with FOR UPDATE or LOCK IN SHARE\nMODE),\nUPDATE, and DELETE statements, locking depends on whether\nthe\nstatement uses a unique index with a unique search\ncondition, or a\nrange-type search condition. For a unique index with a\nunique search\ncondition, InnoDB locks only the index record found, not the\ngap\nbefore it. For other search conditions, InnoDB locks the\nindex range\nscanned, using gap locks or next-key (gap plus index-record)\nlocks to\nblock insertions by other sessions into the gaps covered by\nthe range.\n \nThis is the minimum isolation level for non-distributed XA\ntransactions.\n \nSERIALIZABLE\n \nThis level is like REPEATABLE READ, but InnoDB implicitly\nconverts all\nplain SELECT statements to SELECT ... LOCK IN SHARE MODE if\nautocommit\nis disabled. If autocommit is enabled, the SELECT is its own\ntransaction. It therefore is known to be read only and can\nbe\nserialized if performed as a consistent (non-locking) read\nand need\nnot block for other transactions. (This means that to force\na plain\nSELECT to block if other transactions have modified the\nselected rows,\nyou should disable autocommit.)\n \nDistributed XA transactions should always use this isolation\nlevel.\n \nAccess Mode\n \nThese clauses appeared in MariaDB 10.0.\n \nThe access mode specifies whether the transaction is allowed\nto write data or not. By default, transactions are in READ\nWRITE mode (see the tx_read_only system variable). READ ONLY\nmode allows the storage engine to apply optimizations that\ncannot be used for transactions which write data. The only\nexception to this rule is that read only transactions can\nperform DDL statements on temporary tables.\n \nIt is not permitted to specify both READ WRITE and READ ONLY\nin the same statement.\n \nREAD WRITE and READ ONLY can also be specified in the START\nTRANSACTION statement, in which case the specified mode is\nonly valid for one transaction.\n \nExamples\n-------- \nSET GLOBAL TRANSACTION ISOLATION LEVEL SERIALIZABLE;\n \nAttempting to set the isolation level within an existing\ntransaction without specifying GLOBAL or SESSION.\n \nSTART TRANSACTION;\n \nSET TRANSACTION ISOLATION LEVEL SERIALIZABLE;\nERROR 1568 (25001): Transaction characteristics can\'t be\nchanged while a transaction is in progress\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/set-transaction/','','https://mariadb.com/kb/en/library/set-transaction/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (109,8,'START SLAVE','Syntax\n------ \nSTART SLAVE [\"connection_name\"] [thread_type [,\nthread_type] ... ]\nSTART SLAVE [\"connection_name\"] [SQL_THREAD] UNTIL \n MASTER_LOG_FILE = \'log_name\', MASTER_LOG_POS = log_pos\nSTART SLAVE [\"connection_name\"] [SQL_THREAD] UNTIL\n RELAY_LOG_FILE = \'log_name\', RELAY_LOG_POS = log_pos\nSTART SLAVE [\"connection_name\"] [SQL_THREAD] UNTIL\n MASTER_GTID_POS = \nSTART ALL SLAVES [thread_type [, thread_type]]\nthread_type: IO_THREAD | SQL_THREAD\n \nDescription\n----------- \nSTART SLAVE with no thread_type options starts both of the\nslave\nthreads (see replication). The I/O thread reads events from\nthe master server and stores\nthem in the relay log. The SQL thread reads events from the\nrelay log\nand executes them. START SLAVE requires the SUPER privilege.\n \nIf START SLAVE succeeds in starting the slave threads, it\nreturns\nwithout any error. However, even in that case, it might be\nthat the\nslave threads start and then later stop (for example,\nbecause they do\nnot manage to connect to the master or read its binary log,\nor some\nother problem). START SLAVE does not warn you about this.\nYou must\ncheck the slave\'s error log for error messages generated by\nthe slave\nthreads, or check that they are running satisfactorily with\nSHOW SLAVE\nSTATUS.\n \nSTART SLAVE UNTIL\n \nSTART SLAVE UNTIL refers to the SQL_THREAD slave position at\nwhich the SQL_THREAD replication will halt. If SQL_THREAD\nisn\'t specified both threads are started.\n \nSince version 10.0.2, START SLAVE UNTIL master_gtid_pos=xxx\nhas also been supported. See Global Transaction ID/START\nSLAVE UNTIL master_gtid_pos=xxx for more details.\n \nconnection_name\n \nThe connection_name option was added as part of multi-source\nreplication added in MariaDB 10.0\n \nIf there is only one nameless master, or the default master\n(as specified by the default_master_connection system\nvariable) is intended, connection_name can be omitted. If\nprovided, the START SLAVE statement will apply to the\nspecified master. connection_name is case-insensitive.\n \nSTART ALL SLAVES\n \nSTART ALL SLAVES starts all configured slaves (slaves with\nmaster_host not empty) that were not started before. It will\ngive a note for all started connections. You can check the\nnotes with SHOW WARNINGS.\n \n\n\nURL: https://mariadb.com/kb/en/library/start-slave/','','https://mariadb.com/kb/en/library/start-slave/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (110,8,'START TRANSACTION','Syntax\n------ \nSTART TRANSACTION [transaction_property [,\ntransaction_property] ...] | BEGIN [WORK]\nCOMMIT [WORK] [AND [NO] CHAIN] [[NO] RELEASE]\nROLLBACK [WORK] [AND [NO] CHAIN] [[NO] RELEASE]\nSET autocommit = {0 | 1}\n \ntransaction_property:\n WITH CONSISTENT SNAPSHOT\n | READ WRITE\n | READ ONLY\n \nDescription\n----------- \nThe START TRANSACTION or BEGIN statement\nbegins a new transaction. COMMIT commits the current\ntransaction, making its changes permanent. ROLLBACK rolls\nback the current transaction, canceling its changes. The SET\nautocommit statement disables or enables the default\nautocommit mode for the current session.\n \nSTART TRANSACTION and SET autocommit = 1 implicitly commit\nthe current transaction, if any.\n \nThe optional WORK keyword is supported for\nCOMMIT and ROLLBACK, as are the\nCHAIN and RELEASE clauses.\nCHAIN and RELEASE can be used for\nadditional control over transaction completion. The value of\nthe\ncompletion_type system variable determines the default\ncompletion behavior.\n \nThe AND CHAIN clause causes a new transaction to begin as\nsoon as the current one ends, and the new transaction has\nthe same isolation\nlevel as the just-terminated transaction. The RELEASE clause\ncauses the server to disconnect the current client session\nafter terminating\nthe current transaction. Including the NO keyword suppresses\nCHAIN or RELEASE completion, which can be\nuseful if the completion_type system variable is set to\ncause chaining or release completion by default.\n \nAccess Mode\n \nThese clauses appeared in MariaDB 10.0.\n \nThe access mode specifies whether the transaction is allowed\nto write data or not. By default, transactions are in READ\nWRITE mode (see the tx_read_only system variable). READ ONLY\nmode allows the storage engine to apply optimizations that\ncannot be used for transactions which write data. The only\nexception to this rule is that read only transactions can\nperform DDL statements on temporary tables.\n \nIt is not permitted to specify both READ WRITE and READ ONLY\nin the same statement.\n \nREAD WRITE and READ ONLY can also be specified in the SET\nTRANSACTION statement, in which case the specified mode is\nvalid for all sessions, or for all subsequent transaction\nused by the current session.\n \nautocommit\n \nBy default, MariaDB runs with autocommit mode enabled. This\nmeans that as soon as you execute a statement that updates\n(modifies) a table, MariaDB stores the update on disk to\nmake it permanent. To disable autocommit mode, use the\nfollowing statement:\n \nSET autocommit=0;\n \nAfter disabling autocommit mode by setting the autocommit\nvariable to zero, changes to transaction-safe tables (such\nas those for InnoDB or\nNDBCLUSTER) are not made permanent immediately. You must use\nCOMMIT to store your changes to disk or ROLLBACK to ignore\nthe changes.\n \nTo disable autocommit mode for a single series of\nstatements, use the START TRANSACTION statement.\n \nDDL Statements\n \nDDL statements (CREATE, ALTER, DROP) and administrative\nstatements (FLUSH, RESET, OPTIMIZE, ANALYZE, CHECK, REPAIR,\nCACHE INDEX), and LOAD DATA INFILE, cause an implicit COMMIT\nand start a new transaction. An exception to this rule are\nthe DDL that operate on temporary tables: you can CREATE,\nALTER and DROP them without causing any COMMIT, but those\nactions cannot be rolled back. This means that if you call\nROLLBACK, the temporary tables you created in the\ntransaction will remain, while the rest of the transaction\nwill be rolled back.\n \nTransactions cannot be used in Stored Functions or Triggers.\nIn Stored Procedures and Events BEGIN is not allowed, so you\nshould use START TRANSACTION instead.\n \nA transaction acquires a metadata lock on every table it\naccesses to prevent other connections from altering their\nstructure. The lock is released at the end of the\ntransaction. This happens even with non-transactional\nstorage engines (like MEMORY or CONNECT), so it makes sense\nto use transactions with non-transactional tables.\n \nin_transaction\n \nThe in_transaction system variable appeared in MariaDB 5.3.\n \nIt is a session-only, read-only variable that returns 1\ninside a transaction, and 0 if not in a transaction.\n \nWITH CONSISTENT SNAPSHOT\n \nThe WITH CONSISTENT SNAPSHOT option starts a consistent read\nfor storage engines such as XtraDB and InnoDB that can do\nso, the same as if a START TRANSACTION followed by a SELECT\nfrom any InnoDB table was issued. \n \nMariaDB 5.3 introduced enhancements to this feature. See\nEnhancements for START TRANSACTION WITH CONSISTENT SNAPSHOT.\n \nExamples\n-------- \nSTART TRANSACTION;\n \nSELECT @A:=SUM(salary) FROM table1 WHERE type=1;\n \nUPDATE table2 SET summary=@A WHERE type=1;\n \nCOMMIT;\n \n\n\nURL: https://mariadb.com/kb/en/library/start-transaction/','','https://mariadb.com/kb/en/library/start-transaction/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (111,8,'STOP SLAVE','Syntax\n------ \nSTOP SLAVE [\"connection_name\"] [thread_type [,\nthread_type] ... ]\n \nSTOP ALL SLAVES [thread_type [, thread_type]]\n \nthread_type: IO_THREAD | SQL_THREAD\n \nDescription\n----------- \nStops the slave threads. STOP SLAVE requires the SUPER\nprivilege.\n \nLike START SLAVE, this statement may be used with the\nIO_THREAD and\nSQL_THREAD options to name the thread or threads to be\nstopped. In almost all cases, one never need to use the\nthread_type options.\n \nSTOP SLAVE waits until any current replication event group\naffecting\none or more non-transactional tables has finished executing\n(if there\nis any such replication group), or until the user issues a\nKILL QUERY or KILL CONNECTION statement.\n \nNote that STOP SLAVE doesn\'t delete the connection\npermanently. Next time you execute START SLAVE or the\nMariaDB server restarts, the slave connection is restored\nwith it\'s original arguments. If you want to delete a\nconnection, you should execute RESET SLAVE.\n \nSTOP ALL SLAVES\n \nSTOP ALL SLAVES stops all your running slaves. It will give\nyou a note for every stopped connection. You can check the\nnotes with SHOW WARNINGS.\n \nconnection_name\n \nThe connection_name option was added as part of multi-source\nreplication added in MariaDB 10.0\n \nIf there is only one nameless master, or the default master\n(as specified by the default_master_connection system\nvariable) is intended, connection_name can be omitted. If\nprovided, the STOP SLAVE statement will apply to the\nspecified master. connection_name is case-insensitive.\n \n\n\nURL: https://mariadb.com/kb/en/library/stop-slave/','','https://mariadb.com/kb/en/library/stop-slave/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (112,8,'Transaction Timeouts','MariaDB has always had the wait_timeout and\ninteractive_timeout settings, which close connections after\na certain period of inactivity.\n \nHowever, these are by default set to a long wait period. In\nsituations where transactions may be started, but not\ncommitted or rolled back, more granular control and a\nshorter timeout may be desirable so as to avoid locks being\nheld for too long.\n \nMariaDB 10.3 introduced three new variables to handle this\nsituation.\nidle_transaction_timeout (all transactions)\nidle_write_transaction_timeout (write transactions - called\nidle_readwrite_transaction_timeout until MariaDB 10.3.2)\nidle_readonly_transaction_timeout (read transactions)\n \nThese accept a time in seconds to time out, by closing the\nconnection, transactions that are idle for longer than this\nperiod. By default all are set to zero, or no timeout.\n \nidle_transaction_timeout affects all transactions,\nidle_write_transaction_timeout affects write transactions\nonly and idle_readonly_transaction_timeout affects read\ntransactions only. The latter two variables work\nindependently. However, if either is set along with\nidle_transaction_timeout, the settings for\nidle_write_transaction_timeout or\nidle_readonly_transaction_timeout will take precedence.\n \nExamples\n-------- \nSET SESSION idle_transaction_timeout=2;\n \nBEGIN;\n \nSELECT * FROM t;\n \nEmpty set (0.000 sec)\n## wait 3 seconds\nSELECT * FROM t;\n \nERROR 2006 (HY000): MySQL server has gone away\n \nSET SESSION idle_write_transaction_timeout=2;\n \nBEGIN;\n \nSELECT * FROM t;\n \nEmpty set (0.000 sec)\n## wait 3 seconds\nSELECT * FROM t;\n \nEmpty set (0.000 sec)\nINSERT INTO t VALUES(1);\n## wait 3 seconds\nSELECT * FROM t;\n \nERROR 2006 (HY000): MySQL server has gone away\n \nSET SESSION idle_transaction_timeout=2, SESSION\nidle_readonly_transaction_timeout=10;\n \nBEGIN;\n \nSELECT * FROM t;\n \nEmpty set (0.000 sec)\n ## wait 3 seconds\nSELECT * FROM t;\n \nEmpty set (0.000 sec)\n## wait 11 seconds\nSELECT * FROM t;\n \nERROR 2006 (HY000): MySQL server has gone away\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/transaction-timeouts/','','https://mariadb.com/kb/en/library/transaction-timeouts/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (113,8,'UNLOCK TABLES','Syntax\n------ \nUNLOCK TABLES\n \nDescription\n----------- \nUNLOCK TABLES explicitly releases any table locks held by\nthe\ncurrent session. See LOCK TABLES for more information.\n \nIn addition to releasing table locks acquired by the LOCK\nTABLES statement, the UNLOCK TABLES statement also releases\nthe global read lock acquired by the FLUSH TABLES WITH READ\nLOCK statement. The FLUSH TABLES WITH READ LOCK statement is\nvery useful for performing backups. See FLUSH for more\ninformation about FLUSH TABLES WITH READ LOCK.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/transactions-unlock-tables/','','https://mariadb.com/kb/en/library/transactions-unlock-tables/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (114,8,'WAIT and NOWAIT','MariaDB 10.3.0 introduced extended syntax so that it is\npossible to set innodb_lock_wait_timeout and\nlock_wait_timeout for the following statements:\n \nSyntax\n------ \nALTER TABLE tbl_name [WAIT n|NOWAIT] ...\nCREATE ... INDEX ON tbl_name (index_col_name, ...) [WAIT\nn|NOWAIT] ...\nDROP INDEX ... [WAIT n|NOWAIT]\nDROP TABLE tbl_name [WAIT n|NOWAIT] ...\nLOCK TABLE ... [WAIT n|NOWAIT]\nOPTIMIZE TABLE tbl_name [WAIT n|NOWAIT]\nRENAME TABLE tbl_name [WAIT n|NOWAIT] ...\nSELECT ... FOR UPDATE [WAIT n|NOWAIT]\nSELECT ... LOCK IN SHARE MODE [WAIT n|NOWAIT]\nTRUNCATE TABLE tbl_name [WAIT n|NOWAIT]\n \nDescription\n----------- \nThe lock wait timeout can be explicitly set in the statement\nby using either WAIT n (to set the wait in seconds) or\nNOWAIT, in which case the statement will immediately fail if\nthe lock cannot be obtained. WAIT 0 is equivalent to NOWAIT.\n \n\n\nURL: https://mariadb.com/kb/en/library/wait-and-nowait/','','https://mariadb.com/kb/en/library/wait-and-nowait/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (115,8,'XA Transactions','Overview\n \nThe MariaDB XA implementation is based on the X/Open CAE\ndocument Distributed Transaction Processing: The XA\nSpecification. This document is published by The Open Group\nand available at\nhttp://www.opengroup.org/public/pubs/catalog/c193.htm.\n \nXA transactions are designed to allow distributed\ntransactions, where a transaction manager (the application)\ncontrols a transaction which involves multiple resources.\nSuch resources are usually DBMSs, but could be resources of\nany type. The whole set of required transactional operations\nis called a global transaction. Each subset of operations\nwhich involve a single resource is called a local\ntransaction. XA used a 2-phases commit (2PC). With the first\ncommit, the transaction manager tells each resource to\nprepare an effective commit, and waits for a confirm\nmessage. The changes are not still made effective at this\npoint. If any of the resources encountered an error, the\ntransaction manager will rollback the global transaction. If\nall resources communicate that the first commit is\nsuccessful, the transaction manager can require a second\ncommit, which makes the changes effective.\n \nIn MariaDB, XA transactions can only be used with storage\nengines that support them. At least InnoDB, TokuDB, SPIDER\nand MyRocks support them. For InnoDB, XA transactions can be\ndisabled by setting the innodb_support_xa server system\nvariable to 0. \n \nLike regular transactions, XA transactions create metadata\nlocks on accessed tables.\n \nXA transactions require REPEATABLE READ as a minimum\nisolation level. However, distributed transactions should\nalways use SERIALIZABLE.\n \nTrying to start more than one XA transaction at the same\ntime produces a 1400 error (SQLSTATE \'XAE09\'). The same\nerror is produced when attempting to start an XA transaction\nwhile a regular transaction is in effect. Trying to start a\nregular transaction while an XA transaction is in effect\nproduces a 1399 error (SQLSTATE \'XAE07\').\n \nThe statements that cause an implicit COMMIT for regular\ntransactions produce a 1400 error (SQLSTATE \'XAE09\') if a\nXA transaction is in effect.\n \nInternal XA vs External XA\n \nXA transactions are an overloaded term in MariaDB. If a\nstorage engine is XA-capable, it can mean one or both of\nthese:\nIt supports MariaDB\'s internal two-phase commit API. This\nis transparent to the user. Sometimes this is called\n\"internal XA\", since MariaDB\'s internal transaction\ncoordinator log can handle coordinating these transactions.\n \nIt supports XA transactions, with the XA START, XA PREPARE,\nXA COMMIT, etc. statements. Sometimes this is called\n\"external XA\", since it requires the use of an external\ntransaction coordinator to use this feature properly.\n \nTransaction Coordinator Log\n \nIf you have two or more XA-capable storage engines enabled,\nthen a transaction coordinator log must be available.\n \nThere are currently two implementations of the transaction\ncoordinator log:\nBinary log-based transaction coordinator log\nMemory-mapped file-based transaction coordinator log\n \nIf the binary log is enabled on a server, then the server\nwill use the binary log-based transaction coordinator log.\nOtherwise, it will use the memory-mapped file-based\ntransaction coordinator log.\n \nSee Transaction Coordinator Log for more information.\n \nSyntax\n------ \nXA {START|BEGIN} xid [JOIN|RESUME]\n \nXA END xid [SUSPEND [FOR MIGRATE]]\n \nXA PREPARE xid\n \nXA COMMIT xid [ONE PHASE]\n \nXA ROLLBACK xid\n \nXA RECOVER [FORMAT=[\'RAW\'|\'SQL\']]\n \nxid: gtrid [, bqual [, formatID ]]\n \nThe interface to XA transactions is a set of SQL statements\nstarting with XA. Each statement changes a transaction\'s\nstate, determining which actions it can perform. A\ntransaction which does not exist is in the NON-EXISTING\nstate.\n \nXA START (or BEGIN) starts a transaction and defines its xid\n(a transaction identifier). The JOIN or RESUME keywords have\nno effect. The new transaction will be in ACTIVE state.\n \nThe xid can have 3 components, though only the first one is\nmandatory. gtrid is a quoted string representing a global\ntransaction identifier. bqual is a quoted string\nrepresenting a local transaction identifier. formatID is an\nunsigned integer indicating the format used for the first\ntwo components; if not specified, defaults to 1. MariaDB\ndoes not interpret in any way these components, and only\nuses them to identify a transaction. xids of transactions in\neffect must be unique.\n \nXA END declares that the specified ACTIVE transaction is\nfinished and it changes its state to IDLE. SUSPEND [FOR\nMIGRATE] has no effect.\n \nXA PREPARE prepares an IDLE transaction for commit, changing\nits state to PREPARED. This is the first commit.\n \nXA COMMIT definitely commits and terminates a transaction\nwhich has already been PREPARED. If the ONE PHASE clause is\nspecified, this statements performs a 1-phase commit on an\nIDLE transaction.\n \nXA ROLLBACK rolls back and terminates an IDLE or PREPARED\ntransaction.\n \nXA RECOVER shows information about all PREPARED\ntransactions.\n \nWhen trying to execute an operation which is not allowed for\nthe transaction\'s current state, an error is produced:\n \nXA COMMIT \'test\' ONE PHASE;\n \nERROR 1399 (XAE07): XAER_RMFAIL: The command cannot be\nexecuted when global transaction is in the ACTIVE state\n \nXA COMMIT \'test2\';\n \nERROR 1399 (XAE07): XAER_RMFAIL: The command cannot be\nexecuted when global transaction is in the NON-EXISTING\nstate\n \nXA RECOVER\n \nThe XA RECOVER statement shows information about all\ntransactions which are in the PREPARED state. It does not\nmatter which connection created the transaction: if it has\nbeen PREPARED, it appears. But this does not mean that a\nconnection can commit or rollback a transaction which was\nstarted by another connection. Note that transactions using\na 1-phase commit are never in the PREPARED state, so they\ncannot be shown by XA RECOVER.\n \nXA RECOVER produces four columns:\n \nXA RECOVER;\n \n+----------+--------------+--------------+------+\n| formatID | gtrid_length | bqual_length | data |\n+----------+--------------+--------------+------+\n| 1 | 4 | 0 | test |\n+----------+--------------+--------------+------+\n \nYou can use XA RECOVER FORMAT=\'SQL\' to get the data in a\nhuman readable\nform that can be directly copy-pasted into XA COMMIT or XA\nROLLBACK. This is particularly useful for binary xid\ngenerated by some transaction coordinators.\n \nformatID is the formatID part of xid.\n \ndata are the gtrid and bqual parts of xid, concatenated.\n \ngtrid_length and bqual_length are the lengths of gtrid and\nbqual, respectevely.\n \nExamples\n-------- \n2-phases commit:\n \nXA START \'test\';\n \nINSERT INTO t VALUES (1,2);\n \nXA END \'test\';\n \nXA PREPARE \'test\';\n \nXA COMMIT \'test\';\n \n1-phase commit:\n \nXA START \'test\';\n \nINSERT INTO t VALUES (1,2);\n \nXA END \'test\';\n \nXA COMMIT \'test\' ONE PHASE;\n \nHuman-readable:\n \nxa start \'12\\r34\\t67\\v78\', \'abc\\ndef\', 3;\n \ninsert t1 values (40);\n \nxa end \'12\\r34\\t67\\v78\', \'abc\\ndef\', 3;\n \nxa prepare \'12\\r34\\t67\\v78\', \'abc\\ndef\', 3;\n \nxa recover format=\'RAW\';\n \n+----------+--------------+--------------+--------------------+\n| formatID | gtrid_length | bqual_length | data |\n+----------+--------------+--------------+--------------------+\n34 67v78abc 11 | 7 | 12\ndef |\n+----------+--------------+--------------+--------------------+\n \nxa recover format=\'SQL\';\n \n+----------+--------------+--------------+-----------------------------------------------+\n| formatID | gtrid_length | bqual_length | data |\n+----------+--------------+--------------+-----------------------------------------------+\n| 3 | 11 | 7 |\nX\'31320d3334093637763738\',X\'6162630a646566\',3 |\n+----------+--------------+--------------+-----------------------------------------------+\n \nxa rollback\nX\'31320d3334093637763738\',X\'6162630a646566\',3;\n \nKnown Issues\n \nMariaDB Galera Cluster\n \nMariaDB Galera Cluster does not support XA transactions. See\nMDEV-10532 for more information on that. The request to\nimplement that feature is being tracked at MDEV-17099.\n \nHowever, MariaDB Galera Cluster builds include a built-in\nplugin called wsrep. Prior to MariaDB 10.4.3, this plugin\nwas internally considered an XA-capable storage engine.\nConsequently, these MariaDB Galera Cluster builds have\nmultiple XA-capable storage engines by default, even if the\nonly \"real\" storage engine that supports external XA\ntransactions enabled on these builds by default is InnoDB.\nTherefore, when using one these builds MariaDB would be\nforced to use a transaction coordinator log by default,\nwhich could have performance implications.\n \nSee Transaction Coordinator Log Overview: MariaDB Galera\nCluster for more information.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/xa-transactions/','','https://mariadb.com/kb/en/library/xa-transactions/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (116,10,'Account Locking','Account locking was introduced in MariaDB 10.4.2.\n \nDescription\n----------- \nAccount locking permits privileged administrators to\nlock/unlock user accounts. No new client connections will be\npermitted if an account is locked (existing connections are\nnot affected).\n \nUser accounts can be locked at creation, with the CREATE\nUSER statement, or modified after creation with the ALTER\nUSER statement. For example:\n \nCREATE USER \'lorin\'@\'localhost\' ACCOUNT LOCK;\n \nor\n \nALTER USER \'marijn\'@\'localhost\' ACCOUNT LOCK;\n \nThe server will return an ER_ACCOUNT_HAS_BEEN_LOCKED error\nwhen locked users attempt to connect:\n \nmysql -ulorin\n ERROR 4151 (HY000): Access denied, this account is locked\n \nThe ALTER USER statement is also used to unlock a user:\n \nALTER USER \'lorin\'@\'localhost\' ACCOUNT UNLOCK;\n \nThe SHOW CREATE USER statement will show whether the account\nis locked:\n \nSHOW CREATE USER \'marijn\'@\'localhost\';\n \n+-----------------------------------------------+\n| CREATE USER for marijn@localhost |\n+-----------------------------------------------+\n| CREATE USER \'marijn\'@\'localhost\' ACCOUNT LOCK |\n+-----------------------------------------------+\n \nas well as querying the mysql.global_priv table:\n \nSELECT CONCAT(user, \'@\', host, \' => \',\nJSON_DETAILED(priv)) FROM mysql.global_priv \n WHERE user=\'marijn\';\n+--------------------------------------------------------------------------------------+\n| CONCAT(user, \'@\', host, \' => \', JSON_DETAILED(priv)) |\n+--------------------------------------------------------------------------------------+\n| marijn@localhost => {\n \"access\": 0,\n \"plugin\": \"mysql_native_password\",\n \"authentication_string\": \"\",\n \"account_locked\": true,\n \"password_last_changed\": 1558017158\n} |\n+--------------------------------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/account-locking/','','https://mariadb.com/kb/en/library/account-locking/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (117,10,'Authentication from MariaDB 10.4','MariaDB 10.4 introduces a number of changes to the\nauthentication process, intended to make things easier and\nmore intuitive.\n \nOverview\n \nThere are four main changes relating to authentication:\nIt is possible to use more than one authentication plugin\nfor each user account. For example, this can be useful to\nslowly migrate users to the more secure ed25519\nauthentication plugin over time, while allowing the old\nmysql_native_password authentication plugin as an\nalternative for the transitional period.\nThe root@localhost user account created by mysql_install_db\nis created with the ability to use two authentication\nplugins.\nFirst, it is configured to try to use the unix_socket\nauthentication plugin. This allows the the root@localhost\nuser to login without a password via the local Unix socket\nfile defined by the socket system variable, as long as the\nlogin is attempted from a process owned by the operating\nsystem root user account.\nSecond, if authentication fails with the unix_socket\nauthentication plugin, then it is configured to try to use\nthe mysql_native_password authentication plugin. However, an\ninvalid password is initially set, so in order to\nauthenticate this way, a password must be set with SET\nPASSWORD.\nHowever, just using the unix_socket authentication plugin\nmay be fine for many users, and it is very secure. You may\nwant to try going without password authentication to see how\nwell it works for you. Remember, the best way to keep your\npassword safe is not to have one!\n \nAll user accounts, passwords, and global privileges are now\nstored in the mysql.global_priv table. The mysql.user table\nstill exists and has exactly the same set of columns as\nbefore, but it’s now a view that references the\nmysql.global_priv table. Tools that analyze the mysql.user\ntable should continue to workas before.\nMariaDB 10.4 supports User Password Expiry, which is not\nactive by default.\n \nDescription\n----------- \nAs a result of the above changes, the open-for-everyone\nall-powerful root account is finally gone. And installation\nscripts will no longer demand that you “PLEASE REMEMBER TO\nSET A PASSWORD FOR THE MariaDB root USER !”, because the\nroot account is securely created automatically.\n \nTwo all-powerful accounts are created by default — root\nand the OS user that owns the data directory, typically\nmysql. They are created as:\n \nCREATE USER root@localhost IDENTIFIED VIA unix_socket OR\nmysql_native_password USING \'invalid\'\nCREATE USER mysql@localhost IDENTIFIED VIA unix_socket OR\nmysql_native_password USING \'invalid\'\n \nUsing unix_socket means that if you are the system root\nuser, you can login as root@locahost without a password.\nThis technique was pioneered by Otto Kekäläinen in Debian\nMariaDB packages and has been successfully used in Debian\nsince as early as MariaDB 10.0. \n \nIt is based on a simple fact that asking the system root for\na password adds no extra security — root has full access\nto all the data files and all process memory anyway. But not\nasking for a password means, there is no root password to\nforget (no need for the numerous tutorials on “how to\nreset MariaDB root password”). And if you want to script\nsome tedious database work, there is no need to store the\nroot password in plain text for the scipt to use (no need\nfor debian-sys-maint user).\n \nStill, some users may wish to log in as MariaDB root without\nusing sudo. Hence the old authentication method —\nconventional MariaDB password — is still available. By\ndefault it is disabled (“invalid” is not a valid\npassword hash), but one can set the password with a usual\nSET PASSWORD statement. And still retain the password-less\naccess via sudo.\n \nIf you install MariaDB locally (say from a tarball, you\nwould not want to use sudo to be able to login. This is why\nMariaDB creates a second all-powerful user with the same\nname as a system user that owns the data directory. In local\n(not system-wide) installations, this will be the user who\ninstalled MariaDB — they automatically get convenient\npassword-less root-like access, because they can access all\nthe data files anyway.\n \nEven if MariaDB is installed system-wide, you may not want\nto run your database maintenance scripts as system root —\nnow you can run them as system mysql user. And you will know\nthat they will never destroy your entire system, even if you\nmake a typo in a shell script.\n \nHowever, seasoned MariaDB DBAs who are used to the old ways\ndo need to makes some changes. See the examples below for\ncommon tasks. \n \nCookbook\n \nAfter installing MariaDB system-wide the first thing\nyou’ve got used to doing is logging in into the\nunprotected root account and protecting it, that is, setting\nthe root password:\n \n$ sudo dnf install MariaDB-server\n$ mysql -uroot\n...\nMariaDB> set password = password(\"XH4VmT3_jt\");\n \nThis is not only unnecessary now, it will simply not work\n— there is no unprotected root account. To login as root\nuse\n \n$ sudo dnf install MariaDB-server\n$ sudo mysql\n \nNote that it implies you are connecting via the unix socket,\nnot tcp. If you happen to have protocol=tcp in a system-wide\n/etc/my.cnf file, use sudo mysql --protocol=socket.\n \nAfter installing MariaDB locally you’ve also used to\nconnect to the unprotected root account using mysql -uroot.\nThis will not work either, simply use mysql without\nspecifying a username.\n \nIf you\'ve forgotten your root password, no problem — you\ncan still connect using sudo and change the password. And if\nyou\'ve also removed unix_socket authentication, to restore\naccess do as follows:\nrestart MariaDB with --skip-grant-tables\nlogin into the unprotected server\nrun FLUSH PRIVILEGES (note, before 10.4 this would’ve been\nthe last step, not anymore). This disables\n--skip-grant-tables and allows you to change the stored\nauthentication method.\nrun SET PASSWORD FOR root@localhost to change the root\npassword\n \nTo view inside privilege tables, the old mysql.user table\nstill exists. You can select from it as before, although you\ncannot update it anymore. It doesn’t show alternative\nauthentication plugins and this was one of the reasons for\nswitching to the mysql.global_priv table — complex\nauthentication rules did not fit into rigid structure of a\nrelational table. You can select from the new table, for\nexample: \n \nselect concat(user, \'@\', host, \' => \',\njson_detailed(priv)) from mysql.global_priv;\n \nReverting to the Previous Authentication Method for\nroot@localhost\n \nIf you don\'t want the root@localhost user account created\nby mysql_install_db to use unix_socket authentication by\ndefault, then there are a few ways to revert to the previous\nmysql_native_password authentication method for this user\naccount.\n \nConfiguring mysql_install_db to Revert to the Previous\nAuthentication Method\n \nOne way to revert to the previous mysql_native_password\nauthentication method for the root@localhost user account is\nto execute mysql_install_db with a special option. If\nmysql_install_db is executed while\n--auth-root-authentication-method=normal is specified, then\nit will create the default user accounts using the default\nbehavior of MariaDB 10.3 and before.\n \nThis means that the root@localhost user account will use\nmysql_native_password authentication by default. There are\nsome other differences as well. See mysql_install_db: User\nAccounts Created by Default for more information.\n \nFor example, the option can be set on the command-line while\nrunning mysql_install_db:\n \nmysql_install_db --user=mysql --datadir=/var/lib/mysql\n--auth-root-authentication-method=normal\n \nThe option can also be set in an option file in an option\ngroup supported by mysql_install_db. For example:\n \n[mysql_install_db]\nauth_root_authentication_method=normal\n \nIf the option is set in an option file and if\nmysql_install_db is executed, then mysql_install_db will\nread this option from the option file, and it will\nautomatically set this option.\n \nAltering the User Account to Revert to the Previous\nAuthentication Method\n \nIf you have already installed MariaDB, and if the\nroot@localhost user account is already using unix_socket\nauthentication, then you can revert to the old\nmysql_native_password authentication method for the user\naccount by executing the following:\n \nALTER USER root@localhost IDENTIFIED VIA\nmysql_native_password USING PASSWORD(\"verysecret\")\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/authentication-from-mariadb-104/','','https://mariadb.com/kb/en/library/authentication-from-mariadb-104/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (118,10,'CREATE USER','Syntax\n------ \nCREATE [OR REPLACE] USER [IF NOT EXISTS] \n user_specification [,user_specification ...] \n [REQUIRE {NONE | tls_option [[AND] tls_option ...] }]\n [WITH resource_option [resource_option ...] ]\n [password_option | lock_option] \n \nuser_specification:\n username [authentication_option]\n \nauthentication_option:\n IDENTIFIED BY \'password\' \n | IDENTIFIED BY PASSWORD \'password_hash\'\n | IDENTIFIED {VIA|WITH} authentication_rule [OR\nauthentication_rule ...]\n \nauthentication_rule:\n authentication_plugin\n | authentication_plugin {USING|AS}\n\'authentication_string\'\n | authentication_plugin {USING|AS} PASSWORD(\'password\')\n \ntls_option:\n SSL \n | X509\n | CIPHER \'cipher\'\n | ISSUER \'issuer\'\n | SUBJECT \'subject\'\n \nresource_option:\n MAX_QUERIES_PER_HOUR count\n | MAX_UPDATES_PER_HOUR count\n | MAX_CONNECTIONS_PER_HOUR count\n | MAX_USER_CONNECTIONS count\n | MAX_STATEMENT_TIME time\n \npassword_option:\n PASSWORD EXPIRE\n | PASSWORD EXPIRE DEFAULT\n | PASSWORD EXPIRE NEVER\n | PASSWORD EXPIRE INTERVAL N DAY\n \nlock_option:\n ACCOUNT LOCK\n | ACCOUNT UNLOCK\n}\n \nDescription\n----------- \nThe CREATE USER statement creates new MariaDB accounts. To\nuse it, you must have the global CREATE USER privilege or\nthe INSERT privilege for the mysql database. For each\naccount, CREATE USER creates a new row in\nthe mysql.user table that has no privileges.\n \nIf any of the specified accounts, or any permissions for the\nspecified accounts, already exist, then the server returns\nERROR 1396 (HY000). If an error occurs, CREATE USER will\nstill create the accounts that do not result in an error.\nOnly one error is produced for all users which have not been\ncreated:\n \nERROR 1396 (HY000): \n Operation CREATE USER failed for \'u1\'@\'%\',\'u2\'@\'%\'\n \nCREATE USER, DROP USER, CREATE ROLE, and DROP ROLE all\nproduce the\nsame error code when they fail.\n \nSee Account Names below for details on how account names are\nspecified. \n \nOR REPLACE\n \nIf the optional OR REPLACE clause is used, it is basically a\nshortcut for:\n \nDROP USER IF EXISTS name;\n \nCREATE USER name ...;\n \nFor example:\n \nCREATE USER foo2@test IDENTIFIED BY \'password\';\n \nERROR 1396 (HY000): Operation CREATE USER failed for\n\'foo2\'@\'test\'\n \nCREATE OR REPLACE USER foo2@test IDENTIFIED BY \'password\';\n \nQuery OK, 0 rows affected (0.00 sec)\n \nIF NOT EXISTS\n \nWhen the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the specified user already\nexists.\n \nFor example:\n \nCREATE USER foo2@test IDENTIFIED BY \'password\';\n \nERROR 1396 (HY000): Operation CREATE USER failed for\n\'foo2\'@\'test\'\n \nCREATE USER IF NOT EXISTS foo2@test IDENTIFIED BY\n\'password\';\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+----------------------------------------------------+\n| Level | Code | Message |\n+-------+------+----------------------------------------------------+\n| Note | 1973 | Can\'t create user \'foo2\'@\'test\';\n it already exists |\n+-------+------+----------------------------------------------------+\n1 row in set (0.00 sec\n \nAuthentication Options\n \nIDENTIFIED BY \'password\'\n \nThe optional IDENTIFIED BY clause can be used to provide an\naccount with a password. The password should be specified in\nplain text. It will be hashed by the PASSWORD function prior\nto being stored to the mysql.user table.\n \nFor example, if our password is mariadb, then we can create\nthe user with:\n \nCREATE USER foo2@test IDENTIFIED BY \'mariadb\';\n \nIf you do not specify a password with the IDENTIFIED BY\nclause, the user\nwill be able to connect without a password. A blank password\nis not a wildcard\nto match any password. The user must connect without\nproviding a password if no\npassword is set.\n \nThe only authentication plugins that this clause supports\nare mysql_native_password and mysql_old_password.\n \nIDENTIFIED BY PASSWORD \'password_hash\'\n \nThe optional IDENTIFIED BY PASSWORD clause can be used to\nprovide an account with a password that has already been\nhashed. The password should be specified as a hash that was\nprovided by the PASSWORD function. It will be stored to the\nmysql.user table as-is.\n \nFor example, if our password is mariadb, then we can find\nthe hash with:\n \nSELECT PASSWORD(\'mariadb\');\n+-------------------------------------------+\n| PASSWORD(\'mariadb\') |\n+-------------------------------------------+\n| *54958E764CE10E50764C2EECBB71D01F08549980 |\n+-------------------------------------------+\n1 row in set (0.00 sec)\n \nAnd then we can create a user with the hash:\n \nCREATE USER foo2@test IDENTIFIED BY PASSWORD\n\'*54958E764CE10E50764C2EECBB71D01F08549980\';\n \nIf you do not specify a password with the IDENTIFIED BY\nclause, the user\nwill be able to connect without a password. A blank password\nis not a wildcard\nto match any password. The user must connect without\nproviding a password if no\npassword is set.\n \nThe only authentication plugins that this clause supports\nare mysql_native_password and mysql_old_password.\n \nIDENTIFIED {VIA|WITH} authentication_plugin\n \nThe optional IDENTIFIED VIA authentication_plugin allows you\nto specify that the account should be authenticated by a\nspecific authentication plugin. The plugin name must be an\nactive authentication plugin as per SHOW PLUGINS. If it\ndoesn\'t show up in that output, then you will need to\ninstall it with INSTALL PLUGIN or INSTALL SONAME.\n \nFor example, this could be used with the PAM authentication\nplugin:\n \nCREATE USER foo2@test IDENTIFIED VIA pam;\n \nSome authentication plugins allow additional arguments to be\nspecified after a USING or AS keyword. For example, the PAM\nauthentication plugin accepts a service name:\n \nCREATE USER foo2@test IDENTIFIED VIA pam USING \'mariadb\';\n \nThe exact meaning of the additional argument would depend on\nthe specific authentication plugin.\n \nThe USING or AS keyword can also be used to provide a\nplain-text password to a plugin if it\'s provided as an\nargument to the PASSWORD() function. This is only valid for\nauthentication plugins that have implemented a hook for the\nPASSWORD() function. For example, the ed25519 authentication\nplugin supports this:\n \nCREATE USER safe@\'%\' IDENTIFIED VIA ed25519 USING\nPASSWORD(\'secret\');\n \nOne can specify many authentication plugins, they all works\nas alternatives ways of authenticating a user:\n \nCREATE USER safe@\'%\' IDENTIFIED VIA ed25519 USING\nPASSWORD(\'secret\') OR unix_socket;\n \nTLS Options\n \nBy default, MariaDB transmits data between the server and\nclients without encrypting it. This is generally acceptable\nwhen the server and client run on the same host or in\nnetworks where security is guaranteed through other means.\nHowever, in cases where the server and client exist on\nseparate networks or they are in a high-risk network, the\nlack of encryption does introduce security concerns as a\nmalicious actor could potentially eavesdrop on the traffic\nas it is sent over the network between them.\n \nTo mitigate this concern, MariaDB allows you to encrypt data\nin transit between the server and clients using the\nTransport Layer Security (TLS) protocol. TLS was formerly\nknown as Secure Socket Layer (SSL), but strictly speaking\nthe SSL protocol is a predecessor to TLS and, that version\nof the protocol is now considered insecure. The\ndocumentation still uses the term SSL often and for\ncompatibility reasons TLS-related server system and status\nvariables still use the prefix ssl_, but internally, MariaDB\nonly supports its secure successors.\n \nSee Secure Connections Overview for more information about\nhow to determine whether your MariaDB server has TLS\nsupport.\n \nYou can set certain TLS-related restrictions for specific\nuser accounts. For instance, you might use this with user\naccounts that require access to sensitive data while sending\nit across networks that you do not control. These\nrestrictions can be enabled for a user account with the\nCREATE USER, ALTER USER, or GRANT statements. The following\noptions are available:\n \nOption | Description | \n \nREQUIRE NONE | TLS is not required for this account, but can\nstill be used. | \n \nREQUIRE SSL | The account must use TLS, but no valid X509\ncertificate is required. This option cannot be combined with\nother TLS options. | \n \nREQUIRE X509 | The account must use TLS and must have a\nvalid X509 certificate. This option implies REQUIRE SSL.\nThis option cannot be combined with other TLS options. | \n \nREQUIRE ISSUER \'issuer\' | The account must use TLS and\nmust have a valid X509 certificate. Also, the Certificate\nAuthority must be the one specified via the string issuer.\nThis option implies REQUIRE X509. This option can be\ncombined with the SUBJECT, and CIPHER options in any order.\n| \n \nREQUIRE SUBJECT \'subject\' | The account must use TLS and\nmust have a valid X509 certificate. Also, the certificate\'s\nSubject must be the one specified via the string subject.\nThis option implies REQUIRE X509. This option can be\ncombined with the ISSUER, and CIPHER options in any order. |\n\n \nREQUIRE CIPHER \'cipher\' | The account must use TLS, but no\nvalid X509 certificate is required. Also, the encryption\nused for the connection must use one of the methods\nspecified in the string cipher. This option implies REQUIRE\nSSL. This option can be combined with the ISSUER, and\nSUBJECT options in any order. | \n \nThe REQUIRE keyword must be used only once for all specified\noptions, and the AND keyword can be used to separate\nindividual options, but it is not required.\n \nFor example, you can create a user account that requires\nthese TLS options with the following:\n \nCREATE USER \'alice\'@\'%\'\n REQUIRE SUBJECT \'/CN=alice/O=My Dom,\nInc./C=US/ST=Oregon/L=Portland\'\n AND ISSUER \'/C=FI/ST=Somewhere/L=City/ O=Some\nCompany/CN=Peter Parker/emailAddress=p.parker@marvel.com\'\n AND CIPHER \'TLSv1.2\';\n \nIf any of these options are set for a specific user account,\nthen any client who tries to connect with that user account\nwill have to be configured to connect with TLS.\n \nSee Securing Connections for Client and Server for\ninformation on how to enable TLS on the client and server.\n \nResource Limit Options\n \nMariaDB 10.2.0 introduced a number of resource limit\noptions.\n \nIt is possible to set per-account limits for certain server\nresources. The following table shows the values that can be\nset per account:\n \nLimit Type | Decription | \n \nMAX_QUERIES_PER_HOUR | Number of statements that the account\ncan issue per hour (including updates) | \n \nMAX_UPDATES_PER_HOUR | Number of updates (not queries) that\nthe account can issue per hour | \n \nMAX_CONNECTIONS_PER_HOUR | Number of connections that the\naccount can start per hour | \n \nMAX_USER_CONNECTIONS | Number of simultaneous connections\nthat can be accepted from the same account; if it is 0,\nmax_connections will be used instead; if max_connections is\n0, there is no limit for this account\'s simultaneous\nconnections. | \n \nMAX_STATEMENT_TIME | Timeout, in seconds, for statements\nexecuted by the user. See also Aborting Statements that\nExceed a Certain Time to Execute. | \n \nIf any of these limits are set to 0, then there is no limit\nfor that resource for that user.\n \nHere is an example showing how to create a user with\nresource limits:\n \nCREATE USER \'someone\'@\'localhost\' WITH\n MAX_USER_CONNECTIONS 10\n MAX_QUERIES_PER_HOUR 200;\n \nThe resources are tracked per account, which means\n\'user\'@\'server\'; not per user name or per connection.\n \nThe count can be reset for all users using FLUSH\nUSER_RESOURCES, FLUSH PRIVILEGES or mysqladmin reload.\n \nPer account resource limits are stored in the user table, in\nthe mysql database. Columns used for resources limits are\nnamed max_questions, max_updates, max_connections (for\nMAX_CONNECTIONS_PER_HOUR), and max_user_connections (for\nMAX_USER_CONNECTIONS).\n \nAccount Names\n \nAccount names have both a user name component and a host\nname component, and are specified as\n\'user_name\'@\'host_name\'.\n \nThe user name and host name may be unquoted, quoted as\nstrings using double quotes (\") or\nsingle quotes (\'), or quoted as identifiers using backticks\n(`). You must use quotes\nwhen using special characters (such as a hyphen) or wildcard\ncharacters. If you quote, you \nmust quote the user name and host name separately (for\nexample \'user_name\'@\'host_name\').\n \nHost Name Component\n \nIf the host name is not provided, it is assumed to be \'%\'.\n \nHost names may contain the wildcard characters % and _. They\nare matched as if by\nthe LIKE clause. If you need to use a wildcard character\nliterally (for example, to\nmatch a domain name with an underscore), prefix the\ncharacter with a backslash. See LIKE\nfor more information on escaping wildcard characters.\n \nHost name matches are case-insensitive. Host names can match\neither domain names or IP\naddresses. Use \'localhost\' as the host name to allow only\nlocal client connections.\n \nYou can use a netmask to match a range of IP addresses using\n\'base_ip/netmask\' as the\nhost name. A user with an IP address ip_addr will be allowed\nto connect if the following\ncondition is true:\n \nip_addr & netmask = base_ip\n \nYou can only use netmasks that specify a multiple of 8 bits\nof the address to match. That is,\nonly the following netmasks are allowed:\n \n255.0.0.0\n255.255.0.0\n255.255.255.0\n255.255.255.255\n \nUsing 255.255.255.255 is equivalent to not using a netmask\nat all.\n \nUser Name Component\n \nUser names must match exactly, including case. A user name\nthat is empty is known as an anonymous account and is\nallowed to match a login attempt with any user name\ncomponent. These are described more in the next section.\n \nFor valid identifiers to use as user names, see Identifier\nNames.\n \nIt is possible for more than one account to match when a\nuser connects. MariaDB selects\nthe first matching account after sorting according to the\nfollowing criteria:\nAccounts with an exact host name are sorted before accounts\nusing a wildcard in the\nhost name. Host names using a netmask are considered to be\nexact for sorting.\nAccounts with a wildcard in the host name are sorted\naccording to the position of\nthe first wildcard character. Those with a wildcard\ncharacter later in the host name\nsort before those with a wildcard character earlier in the\nhost name.\nAccounts with a non-empty user name sort before accounts\nwith an empty user name.\nAccounts with an empty user name are sorted last. As\nmentioned previously, these are known as anonymous accounts.\nThese are described more in the next section.\n \nThe following table shows a list of example account as\nsorted by these criteria:\n \n+---------+-------------+\n| User | Host |\n+---------+-------------+\n| joffrey | 192.168.0.3 |\n| | 192.168.0.% |\n| joffrey | 192.168.% |\n| | 192.168.% |\n+---------+-------------+\n \nOnce connected, you only have the privileges granted to the\naccount that matched,\nnot all accounts that could have matched. For example,\nconsider the following\ncommands:\n \nCREATE USER \'joffrey\'@\'192.168.0.3\';\n \nCREATE USER \'joffrey\'@\'%\';\n \nGRANT SELECT ON test.t1 to \'joffrey\'@\'192.168.0.3\';\n \nGRANT SELECT ON test.t2 to \'joffrey\'@\'%\';\n \nIf you connect as joffrey from 192.168.0.3, you will have\nthe SELECT\nprivilege on the table test.t1, but not on the table\ntest.t2. If you connect as joffrey from any other IP\naddress, you will have the SELECT privilege on the table\ntest.t2, but not\non the table test.t1.\n \nBeginning with MariaDB 5.5.31, usernames can be up to 80\ncharacters long. From MariaDB 10.0 the system tables are all\nby default this length. However, in order to enable this\nfeature in MariaDB 5.5, the following schema changes must be\nmade:\n \nALTER TABLE mysql.user MODIFY User CHAR(80) BINARY NOT NULL\nDEFAULT \'\';\n \nALTER TABLE mysql.db MODIFY User CHAR(80) BINARY NOT NULL\nDEFAULT \'\';\n \nALTER TABLE mysql.tables_priv MODIFY User CHAR(80) BINARY\nNOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.columns_priv MODIFY User CHAR(80) BINARY\nNOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.procs_priv MODIFY User CHAR(80) BINARY NOT\nNULL DEFAULT \'\';\n \nALTER TABLE mysql.proc MODIFY definer CHAR(141) COLLATE\nutf8_bin NOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.event MODIFY definer CHAR(141) COLLATE\nutf8_bin NOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.proxies_priv MODIFY User CHAR(80) COLLATE\nutf8_bin NOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.proxies_priv MODIFY Proxied_user CHAR(80)\nCOLLATE utf8_bin NOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.proxies_priv MODIFY Grantor CHAR(141)\nCOLLATE utf8_bin NOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.servers MODIFY Username CHAR(80) NOT NULL\nDEFAULT \'\';\n \nALTER TABLE mysql.procs_priv MODIFY Grantor CHAR(141)\nCOLLATE utf8_bin NOT NULL DEFAULT \'\';\n \nALTER TABLE mysql.tables_priv MODIFY Grantor CHAR(141)\nCOLLATE utf8_bin NOT NULL DEFAULT \'\';\n \nFLUSH PRIVILEGES;\n \nAnonymous Accounts\n \nAnonymous accounts are accounts where the user name portion\nof the account name is empty. These accounts act as special\ncatch-all accounts. If a user attempts to log into the\nsystem from a host, and an anonymous account exists with a\nhost name portion that matches the user\'s host, then the\nuser will log in as the anonymous account if there is no\nmore specific account match for the user name that the user\nentered.\n \nFor example, here are some anonymous accounts:\n \nCREATE USER \'\'@\'localhost\';\n \nCREATE USER \'\'@\'192.168.0.3\';\n \nFixing a Legacy Default Anonymous Account\n \nOn some systems, the mysql.db table has some entries for the\n\'\'@\'%\' anonymous account by default. Unfortunately,\nthere is no matching entry in the mysql.user table, which\nmeans that this anonymous account doesn\'t exactly exist,\nbut it does have privileges--usually on the default test\ndatabase created by mysql_install_db. These account-less\nprivileges are a legacy that is leftover from a time when\nMySQL\'s privilege system was less advanced.\n \nThis situation means that you will run into errors if you\ntry to create a \'\'@\'%\' account. For example:\n \nCREATE USER \'\'@\'%\';\n \nERROR 1396 (HY000): Operation CREATE USER failed for\n\'\'@\'%\'\n \nThe fix is to DELETE the row in the mysql.db table and then\nexecute FLUSH PRIVILEGES:\n \nDELETE FROM mysql.db WHERE User=\'\' AND Host=\'%\';\n \nFLUSH PRIVILEGES;\n \nAnd then the account can be created:\n \nCREATE USER \'\'@\'%\';\n \nQuery OK, 0 rows affected (0.01 sec)\n \nSee MDEV-13486 for more information.\n \nPassword Expiry\n \nBesides automatic password expiry, as determined by\ndefault_password_lifetime, password expiry times can be set\non an individual user basis, overriding the global setting,\nfor example:\n \nCREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE INTERVAL\n120 DAY;\n \nSee User Password Expiry for more details.\n \nAccount Locking\n \nAccount locking permits privileged administrators to\nlock/unlock user accounts. No new client connections will be\npermitted if an account is locked (existing connections are\nnot affected). For example:\n \nCREATE USER \'marijn\'@\'localhost\' ACCOUNT LOCK;\n \nSee Account Locking','','https://mariadb.com/kb/en/library/create-user/'); +update help_topic set description = CONCAT(description, ' for more details.\n \n\n\nURL: https://mariadb.com/kb/en/library/create-user/') WHERE help_topic_id = 118; +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (119,10,'ALTER USER','The ALTER USER statement was introduced in MariaDB 10.2.0.\n \nSyntax\n------ \nALTER USER [IF EXISTS] \n user_specification [,user_specification] ...\n [REQUIRE {NONE | tls_option [[AND] tls_option] ...}]\n [WITH resource_option [resource_option] ...]\n [password_option | lock_option] \n \nuser_specification:\n username [authentication_option]\n \nauthentication_option:\n IDENTIFIED BY \'password\' \n | IDENTIFIED BY PASSWORD \'password_hash\'\n | IDENTIFIED {VIA|WITH} authentication_plugin\n | IDENTIFIED {VIA|WITH} authentication_plugin {USING|AS}\n\'authentication_string\'\n | IDENTIFIED {VIA|WITH} authentication_plugin {USING|AS}\nPASSWORD(\'password\')\n \ntls_option\n SSL \n | X509\n | CIPHER \'cipher\'\n | ISSUER \'issuer\'\n | SUBJECT \'subject\'\n \nresource_option\n MAX_QUERIES_PER_HOUR count\n | MAX_UPDATES_PER_HOUR count\n | MAX_CONNECTIONS_PER_HOUR count\n | MAX_USER_CONNECTIONS count\n | MAX_STATEMENT_TIME time\n \npassword_option:\n PASSWORD EXPIRE\n | PASSWORD EXPIRE DEFAULT\n | PASSWORD EXPIRE NEVER\n | PASSWORD EXPIRE INTERVAL N DAY\n \nlock_option:\n ACCOUNT LOCK\n | ACCOUNT UNLOCK\n}\n \nDescription\n----------- \nThe ALTER USER statement modifies existing MariaDB accounts.\nTo use it, you must have the global CREATE USER privilege or\nthe UPDATE privilege for the mysql database. The global\nSUPER privilege is also required if the read_only system\nvariable is enabled.\n \nIf any of the specified user accounts do not yet exist, an\nerror results. If an error occurs, ALTER USER will still\nmodify the accounts that do not result in an error. Only one\nerror is produced for all users which have not been\nmodified.\n \nIF EXISTS\n \nWhen the IF EXISTS clause is used, MariaDB will return a\nwarning instead of an error for each specified user that\ndoes not exist.\n \nAccount Names\n \nFor ALTER USER statements, account names are specified as\nthe username argument in the same way as they are for CREATE\nUSER statements. See account names from the CREATE USER page\nfor details on how account names are specified.\n \nCURRENT_USER or CURRENT_USER() can also be used to alter the\naccount logged into the current session. For example, to\nchange the current user\'s password to mariadb:\n \nALTER USER CURRENT_USER() IDENTIFIED BY \'mariadb\';\n \nAuthentication Options\n \nIDENTIFIED BY \'password\'\n \nThe optional IDENTIFIED BY clause can be used to provide an\naccount with a password. The password should be specified in\nplain text. It will be hashed by the PASSWORD function prior\nto being stored to the mysql.user table.\n \nFor example, if our password is mariadb, then we can set the\naccount\'s password with:\n \nALTER USER foo2@test IDENTIFIED BY \'mariadb\';\n \nIf you do not specify a password with the IDENTIFIED BY\nclause, the user\nwill be able to connect without a password. A blank password\nis not a wildcard\nto match any password. The user must connect without\nproviding a password if no\npassword is set.\n \nThe only authentication plugins that this clause supports\nare mysql_native_password and mysql_old_password.\n \nIDENTIFIED BY PASSWORD \'password_hash\'\n \nThe optional IDENTIFIED BY PASSWORD clause can be used to\nprovide an account with a password that has already been\nhashed. The password should be specified as a hash that was\nprovided by the PASSWORD function. It will be stored to the\nmysql.user table as-is.\n \nFor example, if our password is mariadb, then we can find\nthe hash with:\n \nSELECT PASSWORD(\'mariadb\');\n+-------------------------------------------+\n| PASSWORD(\'mariadb\') |\n+-------------------------------------------+\n| *54958E764CE10E50764C2EECBB71D01F08549980 |\n+-------------------------------------------+\n1 row in set (0.00 sec)\n \nAnd then we can set an account\'s password with the hash:\n \nALTER USER foo2@test IDENTIFIED BY PASSWORD\n\'*54958E764CE10E50764C2EECBB71D01F08549980\';\n \nIf you do not specify a password with the IDENTIFIED BY\nclause, the user\nwill be able to connect without a password. A blank password\nis not a wildcard\nto match any password. The user must connect without\nproviding a password if no\npassword is set.\n \nThe only authentication plugins that this clause supports\nare mysql_native_password and mysql_old_password.\n \nIDENTIFIED {VIA|WITH} authentication_plugin\n \nThe optional IDENTIFIED VIA authentication_plugin allows you\nto specify that the account should be authenticated by a\nspecific authentication plugin. The plugin name must be an\nactive authentication plugin as per SHOW PLUGINS. If it\ndoesn\'t show up in that output, then you will need to\ninstall it with INSTALL PLUGIN or INSTALL SONAME.\n \nFor example, this could be used with the PAM authentication\nplugin:\n \nALTER USER foo2@test IDENTIFIED VIA pam;\n \nSome authentication plugins allow additional arguments to be\nspecified after a USING or AS keyword. For example, the PAM\nauthentication plugin accepts a service name:\n \nALTER USER foo2@test IDENTIFIED VIA pam USING \'mariadb\';\n \nThe exact meaning of the additional argument would depend on\nthe specific authentication plugin.\n \nIn MariaDB 10.4 and later, the USING or AS keyword can also\nbe used to provide a plain-text password to a plugin if\nit\'s provided as an argument to the PASSWORD() function.\nThis is only valid for authentication plugins that have\nimplemented a hook for the PASSWORD() function. For example,\nthe ed25519 authentication plugin supports this:\n \nALTER USER safe@\'%\' IDENTIFIED VIA ed25519 USING\nPASSWORD(\'secret\');\n \nTLS Options\n \nBy default, MariaDB transmits data between the server and\nclients without encrypting it. This is generally acceptable\nwhen the server and client run on the same host or in\nnetworks where security is guaranteed through other means.\nHowever, in cases where the server and client exist on\nseparate networks or they are in a high-risk network, the\nlack of encryption does introduce security concerns as a\nmalicious actor could potentially eavesdrop on the traffic\nas it is sent over the network between them.\n \nTo mitigate this concern, MariaDB allows you to encrypt data\nin transit between the server and clients using the\nTransport Layer Security (TLS) protocol. TLS was formerly\nknown as Secure Socket Layer (SSL), but strictly speaking\nthe SSL protocol is a predecessor to TLS and, that version\nof the protocol is now considered insecure. The\ndocumentation still uses the term SSL often and for\ncompatibility reasons TLS-related server system and status\nvariables still use the prefix ssl_, but internally, MariaDB\nonly supports its secure successors.\n \nSee Secure Connections Overview for more information about\nhow to determine whether your MariaDB server has TLS\nsupport.\n \nYou can set certain TLS-related restrictions for specific\nuser accounts. For instance, you might use this with user\naccounts that require access to sensitive data while sending\nit across networks that you do not control. These\nrestrictions can be enabled for a user account with the\nCREATE USER, ALTER USER, or GRANT statements. The following\noptions are available:\n \nOption | Description | \n \nREQUIRE NONE | TLS is not required for this account, but can\nstill be used. | \n \nREQUIRE SSL | The account must use TLS, but no valid X509\ncertificate is required. This option cannot be combined with\nother TLS options. | \n \nREQUIRE X509 | The account must use TLS and must have a\nvalid X509 certificate. This option implies REQUIRE SSL.\nThis option cannot be combined with other TLS options. | \n \nREQUIRE ISSUER \'issuer\' | The account must use TLS and\nmust have a valid X509 certificate. Also, the Certificate\nAuthority must be the one specified via the string issuer.\nThis option implies REQUIRE X509. This option can be\ncombined with the SUBJECT, and CIPHER options in any order.\n| \n \nREQUIRE SUBJECT \'subject\' | The account must use TLS and\nmust have a valid X509 certificate. Also, the certificate\'s\nSubject must be the one specified via the string subject.\nThis option implies REQUIRE X509. This option can be\ncombined with the ISSUER, and CIPHER options in any order. |\n\n \nREQUIRE CIPHER \'cipher\' | The account must use TLS, but no\nvalid X509 certificate is required. Also, the encryption\nused for the connection must use one of the methods\nspecified in the string cipher. This option implies REQUIRE\nSSL. This option can be combined with the ISSUER, and\nSUBJECT options in any order. | \n \nThe REQUIRE keyword must be used only once for all specified\noptions, and the AND keyword can be used to separate\nindividual options, but it is not required.\n \nFor example, you can alter a user account to require these\nTLS options with the following:\n \nALTER USER \'alice\'@\'%\'\n REQUIRE SUBJECT \'/CN=alice/O=My Dom,\nInc./C=US/ST=Oregon/L=Portland\'\n AND ISSUER \'/C=FI/ST=Somewhere/L=City/ O=Some\nCompany/CN=Peter Parker/emailAddress=p.parker@marvel.com\'\n AND CIPHER \'TLSv1.2\';\n \nIf any of these options are set for a specific user account,\nthen any client who tries to connect with that user account\nwill have to be configured to connect with TLS.\n \nSee Securing Connections for Client and Server for\ninformation on how to enable TLS on the client and server.\n \nResource Limit Options\n \nMariaDB 10.2.0 introduced a number of resource limit\noptions.\n \nIt is possible to set per-account limits for certain server\nresources. The following table shows the values that can be\nset per account:\n \nLimit Type | Decription | \n \nMAX_QUERIES_PER_HOUR | Number of statements that the account\ncan issue per hour (including updates) | \n \nMAX_UPDATES_PER_HOUR | Number of updates (not queries) that\nthe account can issue per hour | \n \nMAX_CONNECTIONS_PER_HOUR | Number of connections that the\naccount can start per hour | \n \nMAX_USER_CONNECTIONS | Number of simultaneous connections\nthat can be accepted from the same account; if it is 0,\nmax_connections will be used instead; if max_connections is\n0, there is no limit for this account\'s simultaneous\nconnections. | \n \nMAX_STATEMENT_TIME | Timeout, in seconds, for statements\nexecuted by the user. See also Aborting Statements that\nExceed a Certain Time to Execute. | \n \nIf any of these limits are set to 0, then there is no limit\nfor that resource for that user.\n \nHere is an example showing how to set an account\'s resource\nlimits:\n \nALTER USER \'someone\'@\'localhost\' WITH\n MAX_USER_CONNECTIONS 10\n MAX_QUERIES_PER_HOUR 200;\n \nThe resources are tracked per account, which means\n\'user\'@\'server\'; not per user name or per connection.\n \nThe count can be reset for all users using FLUSH\nUSER_RESOURCES, FLUSH PRIVILEGES or mysqladmin reload.\n \nPer account resource limits are stored in the user table, in\nthe mysql database. Columns used for resources limits are\nnamed max_questions, max_updates, max_connections (for\nMAX_CONNECTIONS_PER_HOUR), and max_user_connections (for\nMAX_USER_CONNECTIONS).\n \nPassword Expiry\n \nBesides automatic password expiry, as determined by\ndefault_password_lifetime, password expiry times can be set\non an individual user basis, overriding the global setting,\nfor example:\n \nALTER USER \'monty\'@\'localhost\' PASSWORD EXPIRE INTERVAL\n120 DAY;\n \nALTER USER \'monty\'@\'localhost\' PASSWORD EXPIRE NEVER;\n \nALTER USER \'monty\'@\'localhost\' PASSWORD EXPIRE DEFAULT;\n \nSee User Password Expiry for more details.\n \nAccount Locking\n \nAccount locking permits privileged administrators to\nlock/unlock user accounts. No new client connections will be\npermitted if an account is locked (existing connections are\nnot affected). For example:\n \nALTER USER \'marijn\'@\'localhost\' ACCOUNT LOCK;\n \nSee Account Locking for more details.\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-user/','','https://mariadb.com/kb/en/library/alter-user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (120,10,'DROP USER','Syntax\n------ \nDROP USER [IF EXISTS] user_name [, user_name] ...\n \nDescription\n----------- \nThe DROP USER statement removes one or more MariaDB\naccounts. It removes\nprivilege rows for the account from all grant tables. To use\nthis statement,\nyou must have the global CREATE USER privilege\nor the DELETE privilege for the mysql database.\nEach account is named using the same format as for the\nCREATE USER\nstatement; for example, \'jeffrey\'@\'localhost\'. If you\nspecify\nonly the user name part of the account name, a host name\npart of \'%\' is\nused. For additional information about specifying account\nnames, see\nCREATE USER.\n \nNote that, if you specify an account that is currently\nconnected, it will not\nbe deleted until the connection is closed. The connection\nwill not be\nautomatically closed.\n \nIf any of the specified user accounts do not exist, ERROR\n1396 (HY000)\nresults. If an error occurs, DROP USER will still drop the\naccounts that do\nnot result in an error. Only one error is produced for all\nusers which have not\nbeen dropped:\n \nERROR 1396 (HY000): Operation DROP USER failed for\n\'u1\'@\'%\',\'u2\'@\'%\'\n \nFailed CREATE or DROP operations, for both users and roles,\nproduce the\nsame error code.\n \nIF EXISTS\n \nThe IF EXISTS clause was added in MariaDB 10.1.3\n \nIf the IF EXISTS clause is used, MariaDB will return a note\ninstead of an error if the user does not exist.\n \nExamples\n-------- \nDROP USER bob;\n \nIF EXISTS:\n \nDROP USER bob;\n \nERROR 1396 (HY000): Operation DROP USER failed for\n\'bob\'@\'%\'\n \nDROP USER IF EXISTS bob;\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+---------------------------------------------+\n| Level | Code | Message |\n+-------+------+---------------------------------------------+\n| Note | 1974 | Can\'t drop user \'bob\'@\'%\'; it doesn\'t\nexist |\n+-------+------+---------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-user/','','https://mariadb.com/kb/en/library/drop-user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (121,10,'GRANT','Syntax\n------ \nGRANT\n priv_type [(column_list)]\n [, priv_type [(column_list)]] ...\n ON [object_type] priv_level\n TO user_specification [ user_options ...]\n \nuser_specification:\n username [authentication_option]\n \nauthentication_option:\n IDENTIFIED BY \'password\' \n | IDENTIFIED BY PASSWORD \'password_hash\'\n | IDENTIFIED {VIA|WITH} authentication_rule [OR\nauthentication_rule ...]\n \nauthentication_rule:\n authentication_plugin\n | authentication_plugin {USING|AS}\n\'authentication_string\'\n | authentication_plugin {USING|AS} PASSWORD(\'password\')\n \nGRANT PROXY ON username\n TO username [, username] ...\n [WITH GRANT OPTION]\n \nuser_options:\n [REQUIRE {NONE | tls_option [[AND] tls_option] ...}]\n [WITH with_option [with_option] ...]\n \nobject_type:\n TABLE\n | FUNCTION\n | PROCEDURE\n \npriv_level:\n *\n | *.*\n | db_name.*\n | db_name.tbl_name\n | tbl_name\n | db_name.routine_name\n \nwith_option:\n GRANT OPTION\n | resource_option\n \nresource_option:\n MAX_QUERIES_PER_HOUR count\n | MAX_UPDATES_PER_HOUR count\n | MAX_CONNECTIONS_PER_HOUR count\n | MAX_USER_CONNECTIONS count\n | MAX_STATEMENT_TIME time\n \ntls_option:\n SSL \n | X509\n | CIPHER \'cipher\'\n | ISSUER \'issuer\'\n | SUBJECT \'subject\'\n \nDescription\n----------- \nThe GRANT statement allows you to grant privileges or roles\nto accounts. To use GRANT, you must have the GRANT OPTION\nprivilege, and you must have the privileges that you are\ngranting.\n \nUse the REVOKE statement to revoke privileges granted with\nthe GRANT statement.\n \nUse the SHOW GRANTS statement to determine what privileges\nan account has.\n \nAccount Names\n \nFor GRANT statements, account names are specified as the\nusername argument in the same way as they are for CREATE\nUSER statements. See account names from the CREATE USER page\nfor details on how account names are specified.\n \nImplicit Account Creation\n \nThe GRANT statement also allows you to implicitly create\naccounts in some cases.\n \nIf the account does not yet exist, then GRANT can implicitly\ncreate it. To implicitly create an account with GRANT, a\nuser is required to have the same privileges that would be\nrequired to explicitly create the account with the CREATE\nUSER statement.\n \nIf the NO_AUTO_CREATE_USER SQL_MODE is set, then accounts\ncan only be created if authentication information is\nspecified, or with a CREATE USER statement. If no\nauthentication information is provided, GRANT will produce\nan error when the specified account does not exist, for\nexample:\n \nshow variables like \'%sql_mode%\' ;\n+---------------+--------------------------------------------+\n| Variable_name | Value |\n+---------------+--------------------------------------------+\n| sql_mode | NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION |\n+---------------+--------------------------------------------+\n \nGRANT USAGE ON *.* TO \'user123\'@\'%\' IDENTIFIED BY \'\';\nERROR 1133 (28000): Can\'t find any matching row in the user\ntable\n \nGRANT USAGE ON *.* TO \'user123\'@\'%\' IDENTIFIED VIA PAM\nusing \'mariadb\' require ssl ;\nQuery OK, 0 rows affected (0.00 sec)\n \nselect host, user from mysql.user where user=\'user123\' ;\n \n+------+----------+\n| host | user |\n+------+----------+\n| % | user123 |\n+------+----------+\n \nPrivilege Levels\n \nPrivileges can be set globally, for an entire database, for\na table or routine,\nor for individual columns in a table. Certain privileges can\nonly be set at\ncertain levels.\nGlobal privileges are granted using *.* for\npriv_level. Global privileges include privileges to\nadminister the database\nand manage user accounts, as well as privileges for all\ntables, functions, and\nprocedures. Global privileges are stored in the mysql.user\ntable.\nDatabase privileges are granted using db_name.*\nfor priv_level, or using just * to use default database.\nDatabase\nprivileges include privileges to create tables and\nfunctions, as well as\nprivileges for all tables, functions, and procedures in the\ndatabase. Database privileges are stored in the mysql.db\ntable.\nTable privileges are granted using db_name.tbl_name\nfor priv_level, or using just tbl_name to specify a table in\nthe default\ndatabase. The TABLE keyword is optional. Table privileges\ninclude the\nability to select and change data in the table. Certain\ntable privileges can\nbe granted for individual columns.\nColumn privileges are granted by specifying a table for\npriv_level and providing a column list after the privilege\ntype. They allow\nyou to control exactly which columns in a table users can\nselect and change.\nFunction privileges are granted using FUNCTION\ndb_name.routine_name\nfor priv_level, or using just FUNCTION routine_name to\nspecify a function\nin the default database.\nProcedure privileges are granted using PROCEDURE\ndb_name.routine_name\nfor priv_level, or using just PROCEDURE routine_name to\nspecify a procedure\nin the default database.\n \nThe USAGE Privilege\n \nThe USAGE privilege grants no real privileges. The SHOW\nGRANTS\nstatement will show a global USAGE privilege for a\nnewly-created user. You\ncan use USAGE with the GRANT statement to change options\nlike GRANT OPTION\nand MAX_USER_CONNECTIONS without changing any account\nprivileges.\n \nThe ALL PRIVILEGES Privilege\n \nThe ALL PRIVILEGES privilege grants all available\nprivileges. Granting all\nprivileges only affects the given privilege level. For\nexample, granting all\nprivileges on a table does not grant any privileges on the\ndatabase or globally.\n \nUsing ALL PRIVILEGES does not grant the special GRANT OPTION\nprivilege.\n \nYou can use ALL instead of ALL PRIVILEGES.\n \nThe GRANT OPTION Privilege\n \nUse the WITH GRANT OPTION clause to give users the ability\nto grant privileges\nto other users at the given privilege level. Users with the\nGRANT OPTION privilege can\nonly grant privileges they have. They cannot grant\nprivileges at a higher privilege level than\nthey have the GRANT OPTION privilege.\n \nThe GRANT OPTION privilege cannot be set for individual\ncolumns.\nIf you use WITH GRANT OPTION when specifying column\nprivileges,\nthe GRANT OPTION privilege will be granted for the entire\ntable.\n \nUsing the WITH GRANT OPTION clause is equivalent to listing\nGRANT OPTION\nas a privilege.\n \nGlobal Privileges\n \nThe following table lists the privileges that can be granted\nglobally. You can\nalso grant all database, table, and function privileges\nglobally. When granted\nglobally, these privileges apply to all databases, tables,\nor functions,\nincluding those created later.\n \nTo set a global privilege, use *.* for priv_level.\n \nPrivilege | Description | \n \nCREATE USER | Create a user using the CREATE USER statement,\nor implicitly create a user with the GRANT statement. | \n \nFILE | Read and write files on the server, using statements\nlike LOAD DATA INFILE or functions like LOAD_FILE(). Also\nneeded to create CONNECT outward tables. MariaDB server must\nhave the permissions to access those files. | \n \nGRANT OPTION | Grant global privileges. You can only grant\nprivileges that you have. | \n \nPROCESS | Show information about the active processes, via\nSHOW PROCESSLIST or mysqladmin processlist. | \n \nRELOAD | Execute FLUSH statements or equivalent mysqladmin\ncommands. | \n \nREPLICATION CLIENT | Execute SHOW MASTER STATUS and SHOW\nSLAVE STATUS informative statements. | \n \nREPLICATION SLAVE | Accounts used by slave servers on the\nmaster need this privilege. This is needed to get the\nupdates made on the master. | \n \nSHOW DATABASES | List all databases using the SHOW DATABASES\nstatement. Without the SHOW DATABASES privilege, you can\nstill issue the SHOW DATABASES statement, but it will only\nlist databases containing tables on which you have\nprivileges. | \n \nSHUTDOWN | Shut down the server using SHUTDOWN or the\nmysqladmin shutdown command. | \n \nSUPER | Execute superuser statements: CHANGE MASTER TO, KILL\n(users who do not have this privilege can only KILL their\nown threads), PURGE LOGS, SET global system variables, or\nthe mysqladmin debug command. Also, this permission allows\nthe user to write data even if the read_only startup option\nis set, enable or disable logging, enable or disable\nreplication on slaves, specify a DEFINER for statements that\nsupport that clause, connect once after reaching the\nMAX_CONNECTIONS. If a statement has been specified for the\ninit-connect mysqld option, that command will not be\nexecuted when a user with SUPER privileges connects to the\nserver. | \n \nDatabase Privileges\n \nThe following table lists the privileges that can be granted\nat the database\nlevel. You can also grant all table and function privileges\nat the database\nlevel. Table and function privileges on a database apply to\nall tables or\nfunctions in that database, including those created later.\n \nTo set a privilege for a database, specify the database\nusing\ndb_name.* for priv_level, or just use *\nto specify the default database.\n \nPrivilege | Description | \n \nCREATE | Create a database using the CREATE DATABASE\nstatement, when the privilege is granted for a database. You\ncan grant the CREATE privilege on databases that do not yet\nexist. This also grants the CREATE privilege on all tables\nin the database. | \n \nCREATE ROUTINE | Create Stored Programs using the CREATE\nPROCEDURE and CREATE FUNCTION statements. | \n \nCREATE TEMPORARY TABLES | Create temporary tables with the\nCREATE TEMPORARY TABLE statement. This privilege enable\nwriting and dropping those temporary tables | \n \nDROP | Drop a database using the DROP DATABASE statement,\nwhen the privilege is granted for a database. This also\ngrants the DROP privilege on all tables in the database. | \n \nEVENT | Create, drop and alter EVENTs. Added in MySQL 5.1.6.\n| \n \nGRANT OPTION | Grant database privileges. You can only grant\nprivileges that you have. | \n \nLOCK TABLES | Acquire explicit locks using the LOCK TABLES\nstatement; you also need to have the SELECT privilege on a\ntable, in order to lock it. | \n \nTable Privileges\n \nPrivilege | Description | \n \nALTER | Change the structure of an existing table using the\nALTER TABLE statement. | \n \nCREATE | Create a table using the CREATE TABLE statement.\nYou can grant the CREATE privilege on tables that do not yet\nexist. | \n \nCREATE VIEW | Create a view using the CREATE_VIEW statement.\n| \n \nDELETE | Remove rows from a table using the DELETE\nstatement. | \n \nDELETE HISTORY | Remove historical rows from a table using\nthe DELETE HISTORY statement. Displays as DELETE VERSIONING\nROWS when running SHOW GRANTS (MDEV-17655). From MariaDB\n10.3.4. From MariaDB 10.3.5, if a user has the SUPER\nprivilege but not this privilege, running mysql_upgrade will\ngrant this privilege as well. | \n \nDROP | Drop a table using the DROP TABLE statement or a view\nusing the DROP VIEW statement. Also required to execute the\nTRUNCATE TABLE statement. | \n \nGRANT OPTION | Grant table privileges. You can only grant\nprivileges that you have. | \n \nINDEX | Create an index on a table using the CREATE INDEX\nstatement. Without the INDEX privilege, you can still create\nindexes when creating a table using the CREATE TABLE\nstatement if the you have the CREATE privilege, and you can\ncreate indexes using the ALTER TABLE statement if you have\nthe ALTER privilege. | \n \nINSERT | Add rows to a table using the INSERT statement. The\nINSERT privilege can also be set on individual columns; see\nColumn Privileges below for details. | \n \nREFERENCES | Unused. | \n \nSELECT | Read data from a table using the SELECT statement.\nThe SELECT privilege can also be set on individual columns;\nsee Column Privileges below for details. | \n \nSHOW VIEW | Show the CREATE VIEW statement to create a view\nusing the SHOW CREATE VIEW statement. | \n \nTRIGGER | Execute triggers associated to tables you update,\nexecute the CREATE TRIGGER and DROP TRIGGER statements. You\nwill still be able to see triggers. | \n \nUPDATE | Update existing rows in a table using the UPDATE\nstatement. UPDATE statements usually include a WHERE clause\nto update only certain rows. You must have SELECT privileges\non the table or the appropriate columns for the WHERE\nclause. The UPDATE privilege can also be set on individual\ncolumns; see Column Privileges below for details. | \n \nColumn Privileges\n \nSome table privileges can be set for individual columns of a\ntable. To use\ncolumn privileges, specify the table explicitly and provide\na list of column\nnames after the privilege type. For example, the following\nstatement would allow\nthe user to read the names and positions of employees, but\nnot other information\nfrom the same table, such as salaries.\n \nGRANT SELECT (name, position) on Employee to\n\'jeffrey\'@\'localhost\';\n \nPrivilege | Description | \n \nINSERT (column_list) | Add rows specifying values in columns\nusing the INSERT statement. If you only have column-level\nINSERT privileges, you must specify the columns you are\nsetting in the INSERT statement. All other columns will be\nset to their default values, or NULL. | \n \nREFERENCES (column_list) | Unused. | \n \nSELECT (column_list) | Read values in columns using the\nSELECT statement. You cannot access or query any columns for\nwhich you do not have SELECT privileges, including in WHERE,\nON, GROUP BY, and ORDER BY clauses. | \n \nUPDATE (column_list) | Update values in columns of existing\nrows using the UPDATE statement. UPDATE statements usually\ninclude a WHERE clause to update only certain rows. You must\nhave SELECT privileges on the table or the appropriate\ncolumns for the WHERE clause. | \n \nFunction Privileges\n \nPrivilege | Description | \n \nALTER ROUTINE | Change the characteristics of a stored\nfunction using the ALTER FUNCTION statement. | \n \nEXECUTE | Use a stored function. You need SELECT privileges\nfor any tables or columns accessed by the function. | \n \nGRANT OPTION | Grant function privileges. You can only grant\nprivileges that you have. | \n \nProcedure Privileges\n \nPrivilege | Description | \n \nALTER ROUTINE | Change the characteristics of a stored\nprocedure using the ALTER PROCEDURE statement. | \n \nEXECUTE | Execute a stored procedure using the CALL\nstatement. The privilege to call a procedure may allow you\nto perform actions you wouldn\'t otherwise be able to do,\nsuch as insert rows into a table. | \n \nGRANT OPTION | Grant procedure privileges. You can only\ngrant privileges that you have. | \n \nProxy Privileges\n \nPrivilege | Description | \n \nPROXY | Permits one user to be a proxy for another. | \n \nThe PROXY privilege allows one user to proxy as another\nuser, which means their privileges change to that of the\nproxy user, and the CURRENT_USER() function returns the user\nname of the proxy user.\n \nThe PROXY privilege only works with authentication plugins\nthat support it. The default mysql_native_password\nauthentication plugin does not support proxy users.\n \nThe pam authentication plugin is the only plugin included\nwith MariaDB that currently supports proxy users. The PROXY\nprivilege is commonly used with the pam authentication\nplugin to enable user and group mapping with PAM.\n \nFor example, to grant the PROXY privilege to an anonymous\naccount that authenticates with the pam authentication\nplugin, you could execute the following:\n \nCREATE USER \'dba\'@\'%\' IDENTIFIED BY \'strongpassword\';\n \nGRANT ALL PRIVILEGES ON *.* TO \'dba\'@\'%\' ;\n \nCREATE USER \'\'@\'%\' IDENTIFIED VIA pam USING \'mariadb\';\n \nGRANT PROXY ON \'dba\'@\'%\' TO \'\'@\'%\';\n \nA user account can only grant the PROXY privilege for a\nspecific user account if the granter also has the PROXY\nprivilege for that specific user account, and if that\nprivilege is defined WITH GRANT OPTION. For example, the\nfollowing example fails because the granter does not have\nthe PROXY privilege for that specific user account at all:\n \nSELECT USER(), CURRENT_USER();\n+-----------------+-----------------+\n| USER() | CURRENT_USER() |\n+-----------------+-----------------+\n| alice@localhost | alice@localhost |\n+-----------------+-----------------+\n \nSHOW GRANTS;\n \n+-----------------------------------------------------------------------------------------------------------------------+\n| Grants for alice@localhost |\n+-----------------------------------------------------------------------------------------------------------------------+\n| GRANT ALL PRIVILEGES ON *.* TO \'alice\'@\'localhost\'\nIDENTIFIED BY PASSWORD\n\'*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19\' |\n+-----------------------------------------------------------------------------------------------------------------------+\n \nGRANT PROXY ON \'dba\'@\'localhost\' TO\n\'bob\'@\'localhost\';\n \nERROR 1698 (28000): Access denied for user\n\'alice\'@\'localhost\'\n \nAnd the following example fails because the granter does\nhave the PROXY privilege for that specific user account, but\nit is not defined WITH GRANT OPTION:\n \nSELECT USER(), CURRENT_USER();\n+-----------------+-----------------+\n| USER() | CURRENT_USER() |\n+-----------------+-----------------+\n| alice@localhost | alice@localhost |\n+-----------------+-----------------+\n \nSHOW GRANTS;\n \n+-----------------------------------------------------------------------------------------------------------------------+\n| Grants for alice@localhost |\n+-----------------------------------------------------------------------------------------------------------------------+\n| GRANT ALL PRIVILEGES ON *.* TO \'alice\'@\'localhost\'\nIDENTIFIED BY PASSWORD\n\'*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19\' |\n| GRANT PROXY ON \'dba\'@\'localhost\' TO\n\'alice\'@\'localhost\' |\n+-----------------------------------------------------------------------------------------------------------------------+\n \nMariaDB [(none)]> GRANT PROXY ON \'dba\'@\'localhost\' TO\n\'bob\'@\'localhost\';\n \nERROR 1698 (28000): Access denied for user\n\'alice\'@\'localhost\'\n \nBut the following example succeeds because the granter does\nhave the PROXY privilege for that specific user account, and\nit is defined WITH GRANT OPTION:\n \nSELECT USER(), CURRENT_USER();\n+-----------------+-----------------+\n| USER() | CURRENT_USER() |\n+-----------------+-----------------+\n| alice@localhost | alice@localhost |\n+-----------------+-----------------+\n \nSHOW GRANTS;\n \n+-----------------------------------------------------------------------------------------------------------------------------------------+\n| Grants for alice@localhost |\n+-----------------------------------------------------------------------------------------------------------------------------------------+\n| GRANT ALL PRIVILEGES ON *.* TO \'alice\'@\'localhost\'\nIDENTIFIED BY PASSWORD\n\'*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19\' WITH GRANT\nOPTION |\n| GRANT PROXY ON \'dba\'@\'localhost\' TO\n\'alice\'@\'localhost\' WITH GRANT OPTION |\n+-----------------------------------------------------------------------------------------------------------------------------------------+\n \nGRANT PROXY ON \'dba\'@\'localhost\' TO\n\'bob\'@\'localhost\';\n \nQuery OK, 0 rows affected (0.004 sec)\n \nA user account can grant the PROXY privilege for any other\nuser account if the granter has the PROXY privilege for the\n\'\'@\'%\' anonymous user account, like this:\n \nGR','','https://mariadb.com/kb/en/library/grant/'); +update help_topic set description = CONCAT(description, 'ANT PROXY ON \'\'@\'%\' TO \'dba\'@\'localhost\' WITH\nGRANT OPTION;\n \nFor example, the following example succeeds because the user\ncan grant the PROXY privilege for any other user account:\n \nSELECT USER(), CURRENT_USER();\n+-----------------+-----------------+\n| USER() | CURRENT_USER() |\n+-----------------+-----------------+\n| alice@localhost | alice@localhost |\n+-----------------+-----------------+\n \nSHOW GRANTS;\n \n+-----------------------------------------------------------------------------------------------------------------------------------------+\n| Grants for alice@localhost |\n+-----------------------------------------------------------------------------------------------------------------------------------------+\n| GRANT ALL PRIVILEGES ON *.* TO \'alice\'@\'localhost\'\nIDENTIFIED BY PASSWORD\n\'*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19\' WITH GRANT\nOPTION |\n| GRANT PROXY ON \'\'@\'%\' TO \'alice\'@\'localhost\' WITH\nGRANT OPTION |\n+-----------------------------------------------------------------------------------------------------------------------------------------+\n \nGRANT PROXY ON \'app1_dba\'@\'localhost\' TO\n\'bob\'@\'localhost\';\n \nQuery OK, 0 rows affected (0.004 sec)\n \nGRANT PROXY ON \'app2_dba\'@\'localhost\' TO\n\'carol\'@\'localhost\';\n \nQuery OK, 0 rows affected (0.004 sec)\n \nThe default root user accounts created by mysql_install_db\nhave this privilege. For example:\n \nGRANT ALL PRIVILEGES ON *.* TO \'root\'@\'localhost\' WITH\nGRANT OPTION;\n \nGRANT PROXY ON \'\'@\'%\' TO \'root\'@\'localhost\' WITH\nGRANT OPTION;\n \nThis allows the default root user accounts to grant the\nPROXY privilege for any other user account, and it also\nallows the default root user accounts to grant others the\nprivilege to do the same.\n \nAuthentication Options\n \nThe authentication options for the GRANT statement are the\nsame as those for the CREATE USER statement.\n \nIDENTIFIED BY \'password\'\n \nThe optional IDENTIFIED BY clause can be used to provide an\naccount with a password. The password should be specified in\nplain text. It will be hashed by the PASSWORD function prior\nto being stored to the mysql.user table.\n \nFor example, if our password is mariadb, then we can create\nthe user with:\n \nGRANT USAGE ON *.* TO foo2@test IDENTIFIED BY \'mariadb\';\n \nIf you do not specify a password with the IDENTIFIED BY\nclause, the user\nwill be able to connect without a password. A blank password\nis not a wildcard\nto match any password. The user must connect without\nproviding a password if no\npassword is set.\n \nIf the user account already exists and if you provide the\nIDENTIFIED BY clause, then the user\'s password will be\nchanged. You must have the privileges needed for the SET\nPASSWORD\nstatement to change a user\'s password with GRANT.\n \nThe only authentication plugins that this clause supports\nare mysql_native_password and mysql_old_password.\n \nIDENTIFIED BY PASSWORD \'password_hash\'\n \nThe optional IDENTIFIED BY PASSWORD clause can be used to\nprovide an account with a password that has already been\nhashed. The password should be specified as a hash that was\nprovided by the PASSWORD function. It will be stored to the\nmysql.user table as-is.\n \nFor example, if our password is mariadb, then we can find\nthe hash with:\n \nSELECT PASSWORD(\'mariadb\');\n+-------------------------------------------+\n| PASSWORD(\'mariadb\') |\n+-------------------------------------------+\n| *54958E764CE10E50764C2EECBB71D01F08549980 |\n+-------------------------------------------+\n1 row in set (0.00 sec)\n \nAnd then we can create a user with the hash:\n \nGRANT USAGE ON *.* TO foo2@test IDENTIFIED BY PASSWORD\n\'*54958E764CE10E50764C2EECBB71D01F08549980\';\n \nIf you do not specify a password with the IDENTIFIED BY\nclause, the user\nwill be able to connect without a password. A blank password\nis not a wildcard\nto match any password. The user must connect without\nproviding a password if no\npassword is set.\n \nIf the user account already exists and if you provide the\nIDENTIFIED BY clause, then the user\'s password will be\nchanged. You must have the privileges needed for the SET\nPASSWORD\nstatement to change a user\'s password with GRANT.\n \nThe only authentication plugins that this clause supports\nare mysql_native_password and mysql_old_password.\n \nIDENTIFIED {VIA|WITH} authentication_plugin\n \nThe optional IDENTIFIED VIA authentication_plugin allows you\nto specify that the account should be authenticated by a\nspecific authentication plugin. The plugin name must be an\nactive authentication plugin as per SHOW PLUGINS. If it\ndoesn\'t show up in that output, then you will need to\ninstall it with INSTALL PLUGIN or INSTALL SONAME.\n \nFor example, this could be used with the PAM authentication\nplugin:\n \nGRANT USAGE ON *.* TO foo2@test IDENTIFIED VIA pam;\n \nSome authentication plugins allow additional arguments to be\nspecified after a USING or AS keyword. For example, the PAM\nauthentication plugin accepts a service name:\n \nGRANT USAGE ON *.* TO foo2@test IDENTIFIED VIA pam USING\n\'mariadb\';\n \nThe exact meaning of the additional argument would depend on\nthe specific authentication plugin.\n \nThe USING or AS keyword can also be used to provide a\nplain-text password to a plugin if it\'s provided as an\nargument to the PASSWORD() function. This is only valid for\nauthentication plugins that have implemented a hook for the\nPASSWORD() function. For example, the ed25519 authentication\nplugin supports this:\n \nCREATE USER safe@\'%\' IDENTIFIED VIA ed25519 USING\nPASSWORD(\'secret\');\n \nOne can specify many authentication plugins, they all works\nas alternatives ways of authenticating a user:\n \nCREATE USER safe@\'%\' IDENTIFIED VIA ed25519 USING\nPASSWORD(\'secret\') OR unix_socket;\n \nResource Limit Options\n \nMariaDB 10.2.0 introduced a number of resource limit\noptions.\n \nIt is possible to set per-account limits for certain server\nresources. The following table shows the values that can be\nset per account:\n \nLimit Type | Decription | \n \nMAX_QUERIES_PER_HOUR | Number of statements that the account\ncan issue per hour (including updates) | \n \nMAX_UPDATES_PER_HOUR | Number of updates (not queries) that\nthe account can issue per hour | \n \nMAX_CONNECTIONS_PER_HOUR | Number of connections that the\naccount can start per hour | \n \nMAX_USER_CONNECTIONS | Number of simultaneous connections\nthat can be accepted from the same account; if it is 0,\nmax_connections will be used instead; if max_connections is\n0, there is no limit for this account\'s simultaneous\nconnections. | \n \nMAX_STATEMENT_TIME | Timeout, in seconds, for statements\nexecuted by the user. See also Aborting Statements that\nExceed a Certain Time to Execute. | \n \nIf any of these limits are set to 0, then there is no limit\nfor that resource for that user.\n \nTo set resource limits for an account, if you do not want to\nchange that account\'s privileges, you can issue a GRANT\nstatement with the USAGE privilege, which has no meaning.\nThe statement can name some or all limit types, in any\norder.\n \nHere is an example showing how to set resource limits:\n \nGRANT USAGE ON *.* TO \'someone\'@\'localhost\' WITH\n MAX_USER_CONNECTIONS 0\n MAX_QUERIES_PER_HOUR 200;\n \nThe resources are tracked per account, which means\n\'user\'@\'server\'; not per user name or per connection.\n \nThe count can be reset for all users using FLUSH\nUSER_RESOURCES, FLUSH PRIVILEGES or mysqladmin reload.\n \nPer account resource limits are stored in the user table, in\nthe mysql database. Columns used for resources limits are\nnamed max_questions, max_updates, max_connections (for\nMAX_CONNECTIONS_PER_HOUR), and max_user_connections (for\nMAX_USER_CONNECTIONS).\n \nTLS Options\n \nBy default, MariaDB transmits data between the server and\nclients without encrypting it. This is generally acceptable\nwhen the server and client run on the same host or in\nnetworks where security is guaranteed through other means.\nHowever, in cases where the server and client exist on\nseparate networks or they are in a high-risk network, the\nlack of encryption does introduce security concerns as a\nmalicious actor could potentially eavesdrop on the traffic\nas it is sent over the network between them.\n \nTo mitigate this concern, MariaDB allows you to encrypt data\nin transit between the server and clients using the\nTransport Layer Security (TLS) protocol. TLS was formerly\nknown as Secure Socket Layer (SSL), but strictly speaking\nthe SSL protocol is a predecessor to TLS and, that version\nof the protocol is now considered insecure. The\ndocumentation still uses the term SSL often and for\ncompatibility reasons TLS-related server system and status\nvariables still use the prefix ssl_, but internally, MariaDB\nonly supports its secure successors.\n \nSee Secure Connections Overview for more information about\nhow to determine whether your MariaDB server has TLS\nsupport.\n \nYou can set certain TLS-related restrictions for specific\nuser accounts. For instance, you might use this with user\naccounts that require access to sensitive data while sending\nit across networks that you do not control. These\nrestrictions can be enabled for a user account with the\nCREATE USER, ALTER USER, or GRANT statements. The following\noptions are available:\n \nOption | Description | \n \nREQUIRE NONE | TLS is not required for this account, but can\nstill be used. | \n \nREQUIRE SSL | The account must use TLS, but no valid X509\ncertificate is required. This option cannot be combined with\nother TLS options. | \n \nREQUIRE X509 | The account must use TLS and must have a\nvalid X509 certificate. This option implies REQUIRE SSL.\nThis option cannot be combined with other TLS options. | \n \nREQUIRE ISSUER \'issuer\' | The account must use TLS and\nmust have a valid X509 certificate. Also, the Certificate\nAuthority must be the one specified via the string issuer.\nThis option implies REQUIRE X509. This option can be\ncombined with the SUBJECT, and CIPHER options in any order.\n| \n \nREQUIRE SUBJECT \'subject\' | The account must use TLS and\nmust have a valid X509 certificate. Also, the certificate\'s\nSubject must be the one specified via the string subject.\nThis option implies REQUIRE X509. This option can be\ncombined with the ISSUER, and CIPHER options in any order. |\n\n \nREQUIRE CIPHER \'cipher\' | The account must use TLS, but no\nvalid X509 certificate is required. Also, the encryption\nused for the connection must use one of the methods\nspecified in the string cipher. This option implies REQUIRE\nSSL. This option can be combined with the ISSUER, and\nSUBJECT options in any order. | \n \nThe REQUIRE keyword must be used only once for all specified\noptions, and the AND keyword can be used to separate\nindividual options, but it is not required.\n \nFor example, you can create a user account that requires\nthese TLS options with the following:\n \nGRANT USAGE ON *.* TO \'alice\'@\'%\'\n REQUIRE SUBJECT \'/CN=alice/O=My Dom,\nInc./C=US/ST=Oregon/L=Portland\'\n AND ISSUER \'/C=FI/ST=Somewhere/L=City/ O=Some\nCompany/CN=Peter Parker/emailAddress=p.parker@marvel.com\'\n AND CIPHER \'TLSv1.2\';\n \nIf any of these options are set for a specific user account,\nthen any client who tries to connect with that user account\nwill have to be configured to connect with TLS.\n \nSee Securing Connections for Client and Server for\ninformation on how to enable TLS on the client and server.\n \nRoles\n \nRoles were introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nGRANT role TO grantee [, grantee2 ... ]\n[ WITH ADMIN OPTION ]\n \nThe GRANT statement is also used to grant the use a role to\none or more users or other roles. In order to be able to\ngrant a role, the grantor doing so must have permission to\ndo so (see WITH ADMIN in the CREATE ROLE article).\n \nSpecifying the WITH ADMIN OPTION permits the grantee to in\nturn grant the role to another.\n \nFor example, the following commands show how to grant the\nsame role to a couple different users.\n \nGRANT journalist TO hulda;\n \nGRANT journalist TO berengar WITH ADMIN OPTION;\n \nIf a user has been granted a role, they do not automatically\nobtain all permissions associated with that role. These\npermissions are only in use when the user activates the role\nwith the SET ROLE statement.\n \nGrant Examples\n \nGranting Root-like Privileges\n \nYou can create a user that has privileges similar to the\ndefault root accounts by executing the following:\n \nCREATE USER \'alexander\'@\'localhost\';\n \nGRANT ALL PRIVILEGES ON *.* to \'alexander\'@\'localhost\'\nWITH GRANT OPTION;\n \n\n\nURL: https://mariadb.com/kb/en/library/grant/') WHERE help_topic_id = 121; +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (122,10,'User Password Expiry','User password expiry was introduced in MariaDB 10.4.3.\n \nPassword expiry permits administrators to expire user\npasswords, either manually or automatically. \n \nSystem Variables\n \nThere are two system variables which affect password expiry:\ndefault_password_lifetime, which determines the amount of\ntime between requiring the user to change their password. 0,\nthe default, means automatic password expiry is not active.\n \nThe second variable, disconnect_on_expired_password\ndetermines whether a client is permitted to connect if their\npassword has expired, or whether they are permitted to\nconnect in sandbox mode, able to perform a limited subset of\nqueries related to resetting the password, in particular SET\nPASSWORD and SET.\n \nSetting a Password Expiry Limit for a User\n \nBesides automatic password expiry, as determined by\ndefault_password_lifetime, password expiry times can be set\non an individual user basis, overriding the global using the\nCREATE USER or ALTER USER statements, for example:\n \nCREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE INTERVAL\n120 DAY;\n \nALTER USER \'monty\'@\'localhost\' PASSWORD EXPIRE INTERVAL\n120 DAY;\n \nLimits can be disabled by use of the NEVER keyword, for\nexample:\n \nCREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE NEVER;\n \nALTER USER \'monty\'@\'localhost\' PASSWORD EXPIRE NEVER;\n \nA manually set limit can be restored the system default by\nuse of DEFAULT, for example:\n \nCREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE DEFAULT;\n \nALTER USER \'monty\'@\'localhost\' PASSWORD EXPIRE DEFAULT;\n \nSHOW CREATE USER\n \nThe SHOW CREATE USER statement will display information\nabout the password expiry status of the user. Unlike MySQL,\nit will not display if the user is unlocked, or if the\npassword expiry is set to default.\n \nCREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE INTERVAL\n120 DAY;\n \nCREATE USER \'konstantin\'@\'localhost\' PASSWORD EXPIRE\nNEVER;\n \nCREATE USER \'amse\'@\'localhost\' PASSWORD EXPIRE DEFAULT;\n \nSHOW CREATE USER \'monty\'@\'localhost\';\n \n+------------------------------------------------------------------+\n| CREATE USER for monty@localhost |\n+------------------------------------------------------------------+\n| CREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE\nINTERVAL 120 DAY |\n+------------------------------------------------------------------+\n \nSHOW CREATE USER \'konstantin\'@\'localhost\';\n \n+------------------------------------------------------------+\n| CREATE USER for konstantin@localhost |\n+------------------------------------------------------------+\n| CREATE USER \'konstantin\'@\'localhost\' PASSWORD EXPIRE\nNEVER |\n+------------------------------------------------------------+\n \nSHOW CREATE USER \'amse\'@\'localhost\';\n \n+--------------------------------+\n| CREATE USER for amse@localhost |\n+--------------------------------+\n| CREATE USER \'amse\'@\'localhost\' |\n+--------------------------------+\n \n--connect-expired-password Client Option\n \nThe mysql client --connect-expired-password option notifies\nthe server that the client is prepared to handle expired\npassword sandbox mode (even if the --batch option was\nspecified).\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/user-password-expiry/','','https://mariadb.com/kb/en/library/user-password-expiry/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (123,10,'RENAME USER','Syntax\n------ \nRENAME USER old_user TO new_user\n [, old_user TO new_user] ...\n \nDescription\n----------- \nThe RENAME USER statement renames existing MariaDB accounts.\nTo use it,\nyou must have the global CREATE USER privilege\nor the UPDATE privilege for the mysql database.\nEach account is named using the same format as for the\nCREATE USER\nstatement; for example, \'jeffrey\'@\'localhost\'.\nIf you specify only the user name part of the account name,\na host\nname part of \'%\' is used.\n \nIf any of the old user accounts do not exist or any of the\nnew user accounts already\nexist, ERROR 1396 (HY000) results. If an error occurs,\nRENAME USER\nwill still rename the accounts that do not result in an\nerror.\n \nExamples\n-------- \nCREATE USER \'donald\', \'mickey\';\n \nRENAME USER \'donald\' TO \'duck\'@\'localhost\', \'mickey\'\nTO \'mouse\'@\'localhost\';\n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/rename-user/','','https://mariadb.com/kb/en/library/rename-user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (124,10,'REVOKE','Privileges\n \nSyntax\n------ \nREVOKE \n priv_type [(column_list)]\n [, priv_type [(column_list)]] ...\n ON [object_type] priv_level\n FROM user [, user] ...\n \nREVOKE ALL PRIVILEGES, GRANT OPTION\n FROM user [, user] ...\n \nDescription\n----------- \nThe REVOKE statement enables system administrators to revoke\nprivileges (or roles - see section below) from MariaDB\naccounts. Each account is named using the same format\nas for the GRANT statement; for example,\n\'jeffrey\'@\'localhost\'. If you specify only the user name\npart\nof the account name, a host name part of \'%\' is used. For\ndetails on the levels at which privileges exist, the\nallowable\npriv_type and priv_level values, and the\nsyntax for specifying users and passwords, see GRANT.\n \nTo use the first REVOKE syntax, you must have the\nGRANT OPTION privilege, and you must have the privileges\nthat\nyou are revoking.\n \nTo revoke all privileges, use the second syntax, which drops\nall\nglobal, database, table, column, and routine privileges for\nthe named\nuser or users:\n \nREVOKE ALL PRIVILEGES, GRANT OPTION FROM user [, user] ...\n \nTo use this REVOKE syntax, you must have the global\nCREATE USER privilege or the\nUPDATE privilege for the mysql database. See\nGRANT.\n \nExamples\n-------- \nREVOKE SUPER ON *.* FROM \'alexander\'@\'localhost\';\n \nRoles\n \nRoles were introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nREVOKE role [, role ...]\n FROM grantee [, grantee2 ... ]\n \nDescription\n----------- \nREVOKE is also used to remove a role from a user or another\nrole that it\'s previously been assigned to. If a role has\npreviously been set as a default role, REVOKE does not\nremove the record of the default role from the mysql.user\ntable. If the role is subsequently granted again, it will\nagain be the user\'s default. Use SET DEFAULT ROLE NONE to\nexplicitly remove this.\n \nBefore MariaDB 10.1.13, the REVOKE role statement was not\npermitted in prepared statements.\n \nExample\n \nREVOKE journalist FROM hulda\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/revoke/','','https://mariadb.com/kb/en/library/revoke/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (125,10,'SET PASSWORD','Syntax\n------ \nSET PASSWORD [FOR user] =\n {\n PASSWORD(\'some password\')\n | OLD_PASSWORD(\'some password\')\n | \'encrypted password\'\n }\n \nDescription\n----------- \nThe SET PASSWORD statement assigns a password to an existing\nMariaDB user\naccount.\n \nIf the password is specified using the PASSWORD() or\nOLD_PASSWORD()\nfunction, the literal text of the password should be given.\nIf the\npassword is specified without using either function, the\npassword\nshould be the already-encrypted password value as returned\nby\nPASSWORD().\n \nOLD_PASSWORD() should only be used if your MariaDB/MySQL\nclients are very old (< 4.0.0).\n \nWith no FOR clause, this statement sets the password for the\ncurrent\nuser. Any client that has connected to the server using a\nnon-anonymous\naccount can change the password for that account.\n \nWith a FOR clause, this statement sets the password for a\nspecific\naccount on the current server host. Only clients that have\nthe UPDATE\nprivilege for the mysql database can do this. The user value\nshould be\ngiven in user_name@host_name format, where user_name and\nhost_name are\nexactly as they are listed in the User and Host columns of\nthe\nmysql.user table entry. \n \nThe argument to PASSWORD() and the password given to MariaDB\nclients can be of arbitrary length.\n \nAuthentication Plugin Support\n \nIn MariaDB 10.4 and later, SET PASSWORD (with or without\nPASSWORD()) works for accounts authenticated via any\nauthentication plugin that supports passwords stored in the\nmysql.global_priv table.\n \nThe ed25519, mysql_native_password, and mysql_old_password\nauthentication plugins store passwords in the\nmysql.global_priv table.\n \nIf you run SET PASSWORD on an account that authenticates\nwith one of these authentication plugins that stores\npasswords in the mysql.global_priv table, then the\nPASSWORD() function is evaluated by the specific\nauthentication plugin used by the account. The\nauthentication plugin hashes the password with a method that\nis compatible with that specific authentication plugin.\n \nThe unix_socket, named_pipe, gssapi, and pam authentication\nplugins do not store passwords in the mysql.global_priv\ntable. These authentication plugins rely on other methods to\nauthenticate the user.\n \nIf you attempt to run SET PASSWORD on an account that\nauthenticates with one of these authentication plugins that\ndoesn\'t store a password in the mysql.global_priv table,\nthen MariaDB Server will raise a warning like the following:\n \nSET PASSWORD is ignored for users authenticating via\nunix_socket plugin\n \nSee Authentication from MariaDB 10.4 for an overview of\nauthentication changes in MariaDB 10.4.\n \nMariaDB until 10.3\n \nIn MariaDB 10.3 and before, SET PASSWORD (with or without\nPASSWORD()) only works for accounts authenticated via\nmysql_native_password or mysql_old_password authentication\nplugins\n \nPasswordless User Accounts\n \nUser accounts do not always require passwords to login.\n \nThe unix_socket and named_pipe authentication plugins do not\nrequire a password to authenticate the user.\n \nThe gssapi and pam authentication plugins may or may not\nrequire a password to authenticate the user, depending on\nthe specific configuration.\n \nThe mysql_native_password and mysql_old_password\nauthentication plugins require passwords for authentication,\nbut the password can be blank. In that case, no password is\nrequired.\n \nIf you provide a password while attempting to log into the\nserver as an account that doesn\'t require a password, then\nMariaDB server will simply ignore the password.\n \nIn MariaDB 10.4 and later, a user account can be defined to\nuse multiple authentication plugins in a specific order of\npreference. This specific scenario may be more noticeable in\nthese versions, since an account could be associated with\nsome authentication plugins that require a password, and\nsome that do not.\n \nExample\n \nFor example, if you had an entry with User and\nHost column values of \'bob\' and \n\'%.loc.gov\', you would write the\nstatement like this:\n \nSET PASSWORD FOR \'bob\'@\'%.loc.gov\' =\nPASSWORD(\'newpass\');\n \n\n\nURL: https://mariadb.com/kb/en/library/set-password/','','https://mariadb.com/kb/en/library/set-password/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (126,10,'Roles Overview','Roles were introduced in MariaDB 10.0.5.\n \nDescription\n----------- \nA role bundles a number of privileges together. It assists\nlarger organizations where, typically, a number of users\nwould have the same privileges, and, previously, the only\nway to change the privileges for a group of users was by\nchanging each user\'s privileges individually. \n \nAlternatively, multiple external users could have been\nassigned the same user, and there would have been no way to\nsee which actual user was responsible for which action.\n \nWith roles, managing this is easy. For example, there could\nbe a number of users assigned to a journalist role, with\nidentical privileges. Changing the privileges for all the\njournalists is a matter of simply changing the role\'s\nprivileges, while the individual user is still linked with\nany changes that take place.\n \nRoles are created with the CREATE ROLE statement, and\ndropped with the DROP ROLE statement. Roles are then\nassigned to a user with an extension to the GRANT statement,\nwhile privileges are assigned to a role in the regular way\nwith GRANT. Similarly, the REVOKE statement can be used to\nboth revoke a role from a user, or revoke a privilege from a\nrole.\n \nOnce a user has connected, he can obtain all privileges\nassociated with a role by setting a role with the SET ROLE\nstatement. The CURRENT_ROLE function returns the currently\nset role for the session, if any.\n \nOnly roles granted directly to a user can be set, roles\ngranted to other roles cannot. Instead the privileges\ngranted to a role, which is, in turn, granted to another\nrole (grantee), will be immediately available to any user\nwho sets this second grantee role.\n \nRoles were implemented as a GSoC 2013 project by Vicentiu\nCiorbaru. \n \nThe SET DEFAULT ROLE statement allows one to set a default\nrole for a user. A default role is automatically enabled\nwhen a user connects (an implicit SET ROLE statement is\nexecuted immediately after a connection is established).\n \nSystem Tables\n \nInformation about roles and who they\'ve been granted to can\nbe found in the Information Schema APPLICABLE_ROLES table as\nwell as the mysql.ROLES_MAPPING table.\n \nThe Information Schema ENABLED_ROLES table shows the enabled\nroles for the current session.\n \nExamples\n-------- \nCreating a role and granting a privilege:\n \nCREATE ROLE journalist;\n \nGRANT SHOW DATABASES ON *.* TO journalist;\n \nGRANT journalist to hulda;\n \nNote, that hulda has no SHOW DATABASES privilege, even\nthough she was granted the journalist role. She needs to set\nthe role first:\n \nSHOW DATABASES;\n \n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n+--------------------+\n \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| NULL |\n+--------------+\n \nSET ROLE journalist;\n \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| journalist |\n+--------------+\n \nSHOW DATABASES;\n \n+--------------------+\n| Database |\n+--------------------+\n| ... |\n| information_schema |\n| mysql |\n| performance_schema |\n| test |\n| ... |\n+--------------------+\n \nSET ROLE NONE;\n \nRoles can be granted to roles:\n \nCREATE ROLE writer;\n \nGRANT SELECT ON data.* TO writer;\n \nGRANT writer TO journalist;\n \nBut one does not need to set a role granted to a role. For\nexample, hulda will automatically get all writer privileges\nwhen she sets the journalist role:\n \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| NULL |\n+--------------+\n \nSHOW TABLES FROM data;\n \nEmpty set (0.01 sec)\n \nSET ROLE journalist;\n \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| journalist |\n+--------------+\n \nSHOW TABLES FROM data;\n \n+------------------------------+\n| Tables_in_data |\n+------------------------------+\n| set1 |\n| ... |\n+------------------------------+\n \nRoles and Views (and Stored Routines)\n \nWhen a user sets a role, he, in a sense, has two identities\nwith two associated sets of privileges.\nBut a view (or a stored routine) can have only one definer.\nSo, when a view (or a stored routine) is created with the\nSQL SECURITY DEFINER, one can specify whether the definer\nshould be CURRENT_USER (and the view will have none of the\nprivileges of the user\'s role) or CURRENT_ROLE (in this\ncase, the view will use role\'s privileges, but none of the\nuser\'s privileges). As a result, sometimes one can create a\nview that is impossible to use.\n \nCREATE ROLE r1;\n \nGRANT ALL ON db1.* TO r1;\n \nGRANT r1 TO foo@localhost;\n \nGRANT ALL ON db.* TO foo@localhost;\n \nSELECT CURRENT_USER\n+---------------+\n| current_user |\n+---------------+\n| foo@localhost |\n+---------------+\n \nSET ROLE r1;\n \nCREATE TABLE db1.t1 (i int);\n \nCREATE VIEW db.v1 AS SELECT * FROM db1.t1;\n \nSHOW CREATE VIEW db.v1;\n \n+------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| View | Create View | character_set_client |\ncollation_connection |\n+------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| v1 | CREATE ALGORITHM=UNDEFINED DEFINER=`foo`@`localhost`\nSQL SECURITY DEFINER VIEW `db`.`v1` AS SELECT `db1`.`t1`.`i`\nAS `i` from `db1`.`t1` | utf8 | utf8_general_ci |\n+------+------------------------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n \nCREATE DEFINER=CURRENT_ROLE VIEW db.v2 AS SELECT * FROM\ndb1.t1;\n \nSHOW CREATE VIEW db.b2;\n \n+------+-----------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| View | Create View | character_set_client |\ncollation_connection |\n+------+-----------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n| v2 | CREATE ALGORITHM=UNDEFINED DEFINER=`r1` SQL SECURITY\nDEFINER VIEW `db`.`v2` AS select `db1`.`t1`.`a` AS `a` from\n`db1`.`t1` | utf8 | utf8_general_ci |\n+------+-----------------------------------------------------------------------------------------------------------------------------+----------------------+----------------------+\n \nOther Resources\n \nRoles Review by Peter Gulutzan\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/roles_overview/','','https://mariadb.com/kb/en/library/roles_overview/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (127,10,'CREATE ROLE','Roles were introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nCREATE [OR REPLACE] ROLE [IF NOT EXISTS] role \n [WITH ADMIN \n {CURRENT_USER | CURRENT_ROLE | user | role}]\n \nDescription\n----------- \nThe CREATE ROLE statement creates one or more MariaDB roles.\nTo\nuse it, you must have the global CREATE USER\nprivilege or the INSERT privilege for the mysql\ndatabase. For each account, CREATE ROLE creates a new row in\nthe\nmysql.user table that has no privileges, and with the\ncorresponding is_role field set to Y. It also creates a\nrecord in the\nmysql.roles_mapping table.\n \nIf any of the specified roles already exist, ERROR 1396\n(HY000) results. If\nan error occurs, CREATE ROLE will still create the roles\nthat do not result\nin an error. The maximum length for a role is 128\ncharacters. Role names can be\nquoted, as explained in the Identifier names page. Only\none error is produced for all roles which have not been\ncreated:\n \nERROR 1396 (HY000): Operation CREATE ROLE failed for\n\'a\',\'b\',\'c\'\n \nFailed CREATE or DROP operations, for both users and roles,\nproduce the\nsame error code.\n \nPUBLIC and NONE are reserved, and cannot be used as role\nnames.\n \nBefore MariaDB 10.1.13, the CREATE ROLE statement was not\npermitted in prepared statements.\n \nFor valid identifiers to use as role names, see Identifier\nNames.\n \nWITH ADMIN\n \nThe optional WITH ADMIN clause determines whether the\ncurrent user, the\ncurrent role or another user or role has use of the newly\ncreated role. If the\nclause is omitted, WITH ADMIN CURRENT_USER is treated as the\ndefault, which\nmeans that the current user will be able to GRANT this role\nto\nusers.\n \nOR REPLACE\n \nThe OR REPLACE clause was added in MariaDB 10.1.3\n \nIf the optional OR REPLACE clause is used, it acts as a\nshortcut for:\n \nDROP ROLE IF EXISTS name;\n \nCREATE ROLE name ...;\n \nIF NOT EXISTS\n \nThe IF NOT EXISTS clause was added in MariaDB 10.1.3\n \nWhen the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the specified role already\nexists. Cannot be used together with the OR REPLACE clause.\n \nExamples\n-------- \nCREATE ROLE journalist;\n \nCREATE ROLE developer WITH ADMIN lorinda;\n \nThe OR REPLACE and IF NOT EXISTS clauses:\n \nCREATE ROLE journalist;\nERROR 1396 (HY000): Operation CREATE ROLE failed for\n\'journalist\'\n \nCREATE OR REPLACE ROLE journalist;\nQuery OK, 0 rows affected (0.00 sec)\n \nCREATE ROLE IF NOT EXISTS journalist;\nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n+-------+------+---------------------------------------------------+\n| Level | Code | Message |\n+-------+------+---------------------------------------------------+\n| Note | 1975 | Can\'t create role \'journalist\'; it\nalready exists |\n+-------+------+---------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/create-role/','','https://mariadb.com/kb/en/library/create-role/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (128,10,'DROP ROLE','Roles were introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nDROP ROLE [IF EXISTS] role_name [,role_name ...]\n \nDescription\n----------- \nThe DROP ROLE statement removes one or more MariaDB roles.\nTo use this\nstatement, you must have the global CREATE USER privilege or\nthe DELETE privilege for the mysql database.\n \nDROP ROLE does not disable roles for connections which\nselected them with SET ROLE. If a role has previously been\nset as a default role, DROP ROLE does not remove the record\nof the default role from the mysql.user table. If the role\nis subsequently recreated and granted, it will again be the\nuser\'s default. Use SET DEFAULT ROLE NONE to explicitly\nremove this.\n \nIf any of the specified user accounts do not exist, ERROR\n1396 (HY000)\nresults. If an error occurs, DROP ROLE will still drop the\nroles that\ndo not result in an error. Only one error is produced for\nall roles which have not been dropped:\n \nERROR 1396 (HY000): Operation DROP ROLE failed for\n\'a\',\'b\',\'c\'\n \nFailed CREATE or DROP operations, for both users and roles,\nproduce the same error code.\n \nBefore MariaDB 10.1.13, the DROP ROLE statement was not\npermitted in prepared statements.\n \nIF EXISTS\n \nThe IF EXISTS clause was added in MariaDB 10.1.3\n \nIf the IF EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the role does not exist.\n \nExamples\n-------- \nDROP ROLE journalist;\n \nThe same thing using the optional IF EXISTS clause:\n \nDROP ROLE journalist;\n \nERROR 1396 (HY000): Operation DROP ROLE failed for\n\'journalist\'\n \nDROP ROLE IF EXISTS journalist;\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nNote (Code 1975): Can\'t drop role \'journalist\'; it\ndoesn\'t exist\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-role/','','https://mariadb.com/kb/en/library/drop-role/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (129,10,'SET ROLE','Roles were introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nSET ROLE { role | NONE }\n \nDescription\n----------- \nThe SET ROLE statement enables a role, along with all of its\nassociated permissions, for the current session. To unset a\nrole, use NONE .\n \nIf a role that doesn\'t exist, or to which the user has not\nbeen assigned, is specified, an ERROR 1959 (OP000): Invalid\nrole specification error occurs.\n \nFrom MariaDB 10.1.1, an automatic SET ROLE is implicitly\nperformed when a user connects if that user has been\nassigned a default role. See SET DEFAULT ROLE.\n \nExample\n \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| NULL |\n+--------------+\n \nSET ROLE staff;\n \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| staff |\n+--------------+\n \nSET ROLE NONE;\n \nQuery OK, 0 rows affected (0.00 sec)\n \nSELECT CURRENT_ROLE();\n+----------------+\n| CURRENT_ROLE() |\n+----------------+\n| NULL |\n+----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/set-role/','','https://mariadb.com/kb/en/library/set-role/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (130,10,'SET DEFAULT ROLE','Default roles were implemented in MariaDB 10.1.1.\n \nSyntax\n------ \nSET DEFAULT ROLE { role | NONE } [ FOR user@host ]\n \nDescription\n----------- \nThe SET DEFAULT ROLE statement sets a default role for a\nspecified (or current) user. A default role is automatically\nenabled when a user connects (an implicit SET ROLE statement\nis executed immediately after a connection is established).\n \nTo be able to set a role as a default, one needs the\nprivileges to enable this role (if you cannot do SET ROLE X,\nyou won\'t be able to do SET DEFAULT ROLE X). To set a\ndefault role for another user one needs to have write access\nto the mysql database.\n \nTo remove a user\'s default role, use SET DEFAULT ROLE NONE\n[ FOR user@host ]. The record of the default role is not\nremoved if the role is dropped or revoked, so if the role is\nsubsequently re-created or granted, it will again be the\nuser\'s default role.\n \nThe default role is stored in a new column in the mysql.user\ntable, and currently viewing this table is the only way to\nsee which role has been assigned to a user as the default. \n \nExamples\n-------- \nSetting a default role for the current user:\n \nSET DEFAULT ROLE journalist;\n \nRemoving a default role from the current user:\n \nSET DEFAULT ROLE NONE;\n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/set-default-role/','','https://mariadb.com/kb/en/library/set-default-role/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (131,11,'ST_X','Syntax\n------ \nST_X(p)\nX(p)\n \nDescription\n----------- \nReturns the X-coordinate value for the point p as a\ndouble-precision number.\n \nST_X() and X() are synonyms.\n \nExamples\n-------- \nSET @pt = \'Point(56.7 53.34)\';\n \nSELECT X(GeomFromText(@pt));\n+----------------------+\n| X(GeomFromText(@pt)) |\n+----------------------+\n| 56.7 |\n+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_x/','','https://mariadb.com/kb/en/library/st_x/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (132,11,'ST_Y','Syntax\n------ \nST_Y(p)\nY(p)\n \nDescription\n----------- \nReturns the Y-coordinate value for the point p as a\ndouble-precision number.\n \nST_Y() and Y() are synonyms.\n \nExamples\n-------- \nSET @pt = \'Point(56.7 53.34)\';\n \nSELECT Y(GeomFromText(@pt));\n+----------------------+\n| Y(GeomFromText(@pt)) |\n+----------------------+\n| 53.34 |\n+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_y/','','https://mariadb.com/kb/en/library/st_y/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (133,11,'X','A synonym for ST_X.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/point-properties-x/','','https://mariadb.com/kb/en/library/point-properties-x/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (134,11,'Y','A synonym for ST_Y.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/point-properties-y/','','https://mariadb.com/kb/en/library/point-properties-y/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (135,12,'AES_DECRYPT','Syntax\n------ \nAES_DECRYPT(crypt_str,key_str)\n \nDescription\n----------- \nThis function allows decryption of data using the official\nAES\n(Advanced Encryption Standard) algorithm. For more\ninformation, see\nthe description of AES_ENCRYPT().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/aes_decrypt/','','https://mariadb.com/kb/en/library/aes_decrypt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (136,12,'AES_ENCRYPT','Syntax\n------ \nAES_ENCRYPT(str,key_str)\n \nDescription\n----------- \nAES_ENCRYPT() and AES_DECRYPT() allow encryption and\ndecryption of\ndata using the official AES (Advanced Encryption Standard)\nalgorithm,\npreviously known as \"Rijndael.\" Encoding with a 128-bit\nkey length is\nused, but you can extend it up to 256 bits by modifying the\nsource. We\nchose 128 bits because it is much faster and it is secure\nenough for\nmost purposes.\n \nAES_ENCRYPT() encrypts a string str using the key key_str,\nand returns a binary string.\n \nAES_DECRYPT() decrypts the encrypted string and returns the\noriginal\nstring.\n \nThe input arguments may be any length. If either argument is\nNULL, the result of this function is also NULL.\n \nBecause AES is a block-level algorithm, padding is used to\nencode\nuneven length strings and so the result string length may be\ncalculated using this formula:\n \n16 x (trunc(string_length / 16) + 1)\n \nIf AES_DECRYPT() detects invalid data or incorrect padding,\nit returns\nNULL. However, it is possible for AES_DECRYPT() to return a\nnon-NULL\nvalue (possibly garbage) if the input data or the key is\ninvalid.\n \nExamples\n-------- \nINSERT INTO t VALUES\n(AES_ENCRYPT(\'text\',SHA2(\'password\',512)));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/aes_encrypt/','','https://mariadb.com/kb/en/library/aes_encrypt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (137,12,'COMPRESS','Syntax\n------ \nCOMPRESS(string_to_compress)\n \nDescription\n----------- \nCompresses a string and returns the result as a binary\nstring. This\nfunction requires MariaDB to have been compiled with a\ncompression\nlibrary such as zlib. Otherwise, the return value is always\nNULL. The\ncompressed string can be uncompressed with UNCOMPRESS().\n \nThe have_compress server system variable indicates whether a\ncompression library is present. \n \nExamples\n-------- \nSELECT LENGTH(COMPRESS(REPEAT(\'a\',1000)));\n+------------------------------------+\n| LENGTH(COMPRESS(REPEAT(\'a\',1000))) |\n+------------------------------------+\n| 21 |\n+------------------------------------+\n \nSELECT LENGTH(COMPRESS(\'\'));\n+----------------------+\n| LENGTH(COMPRESS(\'\')) |\n+----------------------+\n| 0 |\n+----------------------+\n \nSELECT LENGTH(COMPRESS(\'a\'));\n+-----------------------+\n| LENGTH(COMPRESS(\'a\')) |\n+-----------------------+\n| 13 |\n+-----------------------+\n \nSELECT LENGTH(COMPRESS(REPEAT(\'a\',16)));\n+----------------------------------+\n| LENGTH(COMPRESS(REPEAT(\'a\',16))) |\n+----------------------------------+\n| 15 |\n+----------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/compress/','','https://mariadb.com/kb/en/library/compress/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (138,12,'DECODE','Syntax\n------ \nDECODE(crypt_str,pass_str)\n \nDescription\n----------- \nDecrypts the encrypted string crypt_str using pass_str as\nthe\npassword. crypt_str should be a string returned from\nENCODE(). The resulting string will be the original string\nonly if pass_str is the same.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/decode/','','https://mariadb.com/kb/en/library/decode/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (139,12,'DES_DECRYPT','Syntax\n------ \nDES_DECRYPT(crypt_str[,key_str])\n \nDescription\n----------- \nDecrypts a string encrypted with DES_ENCRYPT(). If an error\noccurs,\nthis function returns NULL.\n \nThis function works only if MariaDB has been configured with\nTLS\nsupport.\n \nIf no key_str argument is given, DES_DECRYPT() examines the\nfirst byte\nof the encrypted string to determine the DES key number that\nwas used\nto encrypt the original string, and then reads the key from\nthe DES\nkey file to decrypt the message. For this to work, the user\nmust have\nthe SUPER privilege. The key file can be specified with the\n--des-key-file server option.\n \nIf you pass this function a key_str argument, that string is\nused as\nthe key for decrypting the message.\n \nIf the crypt_str argument does not appear to be an encrypted\nstring,\nMariaDB returns the given crypt_str.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/des_decrypt/','','https://mariadb.com/kb/en/library/des_decrypt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (140,12,'DES_ENCRYPT','Syntax\n------ \nDES_ENCRYPT(str[,{key_num|key_str}])\n \nDescription\n----------- \nEncrypts the string with the given key using the Triple-DES\nalgorithm.\n \nThis function works only if MariaDB has been configured with\nTLS support.\n \nThe encryption key to use is chosen based on the second\nargument to\nDES_ENCRYPT(), if one was given. With no argument, the first\nkey from\nthe DES key file is used. With a key_num argument, the given\nkey \nnumber (0-9) from the DES key file is used. With a key_str\nargument,\nthe given key string is used to encrypt str. \n \nThe key file can be specified with the --des-key-file server\noption.\n \nThe return string is a binary string where the first\ncharacter is \nCHAR(128 | key_num). If an error occurs, DES_ENCRYPT()\nreturns NULL.\n \nThe 128 is added to make it easier to recognize an encrypted\nkey. If\nyou use a string key, key_num is 127.\n \nThe string length for the result is given by this formula:\n \nnew_len = orig_len + (8 - (orig_len % 8)) + 1\n \nEach line in the DES key file has the following format:\n \nkey_num des_key_str\n \nEach key_num value must be a number in the range from 0 to\n9. Lines in\nthe file may be in any order. des_key_str is the string that\nis used\nto encrypt the message. There should be at least one space\nbetween the\nnumber and the key. The first key is the default key that is\nused if\nyou do not specify any key argument to DES_ENCRYPT().\n \nYou can tell MariaDB to read new key values from the key\nfile with the\nFLUSH DES_KEY_FILE statement. This requires the RELOAD\nprivilege.\n \nOne benefit of having a set of default keys is that it gives\napplications a way to check for the existence of encrypted\ncolumn\nvalues, without giving the end user the right to decrypt\nthose values.\n \nExamples\n-------- \nSELECT customer_address FROM customer_table \n WHERE crypted_credit_card =\nDES_ENCRYPT(\'credit_card_number\');\n \n\n\nURL: https://mariadb.com/kb/en/library/des_encrypt/','','https://mariadb.com/kb/en/library/des_encrypt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (141,12,'ENCODE','Syntax\n------ \nENCODE(str,pass_str)\n \nDescription\n----------- \nENCODE is not considered cryptographically secure, and\nshould not be used for password encryption.\n \nEncrypt str using pass_str as the password. To decrypt the\nresult, use\nDECODE().\n \nThe result is a binary string of the same length as str.\n \nThe strength of the encryption is based on how good the\nrandom generator is. \n \nIt is not recommended to rely on the encryption performed by\nthe ENCODE function. Using a salt value (changed when a\npassword is updated) will improve matters somewhat, but for\nstoring passwords, consider a more cryptographically secure\nfunction, such as SHA2().\n \nExamples\n-------- \nENCODE(\'not so secret text\',\nCONCAT(\'random_salt\',\'password\'))\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/encode/','','https://mariadb.com/kb/en/library/encode/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (142,12,'ENCRYPT','Syntax\n------ \nENCRYPT(str[,salt])\n \nDescription\n----------- \nEncrypts a string using the Unix crypt() system call,\nreturning an encrypted binary string. The salt argument\nshould be a string with at least two characters or the\nreturned result will be NULL. If no salt argument is given,\na random value of sufficient length is used.\n \nIt is not recommended to use ENCRYPT() with utf16, utf32 or\nucs2 multi-byte character sets because the crypt() system\ncall expects a string terminated with a zero byte.\n \nNote that the underlying crypt() system call may have some\nlimitations, such as ignoring all but the first eight\ncharacters.\n \nIf the have_crypt system variable is set to NO (because the\ncrypt() system call is not available), the ENCRYPT function\nwill always return NULL.\n \nExamples\n-------- \nSELECT ENCRYPT(\'encrypt me\');\n+-----------------------+\n| ENCRYPT(\'encrypt me\') |\n+-----------------------+\n| 4I5BsEx0lqTDk |\n+-----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/encrypt/','','https://mariadb.com/kb/en/library/encrypt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (143,12,'MD5','Syntax\n------ \nMD5(str)\n \nDescription\n----------- \nCalculates an MD5 128-bit checksum for the string. \n \nThe return value is a 32-hex digit string, and as of MariaDB\n5.5, is a nonbinary string in the connection character set\nand collation, determined by the values of the\ncharacter_set_connection and collation_connection system\nvariables. Before 5.5, the return value was a binary string.\n \nNULL is returned if the argument was NULL. \n \nExamples\n-------- \nSELECT MD5(\'testing\');\n+----------------------------------+\n| MD5(\'testing\') |\n+----------------------------------+\n| ae2b1fca515949e5d54fb22b8ed95575 |\n+----------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/md5/','','https://mariadb.com/kb/en/library/md5/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (144,12,'OLD_PASSWORD','Syntax\n------ \nOLD_PASSWORD(str)\n \nDescription\n----------- \nOLD_PASSWORD() was added to MySQL when the implementation of\n\nPASSWORD() was changed to improve security. OLD_PASSWORD()\nreturns the\nvalue of the old (pre-MySQL 4.1) implementation of\nPASSWORD() as a\nstring, and is intended to permit you to reset passwords for\nany\npre-4.1 clients that need to connect to a more recent MySQL\nserver version, or any version of MariaDB,\nwithout locking them out.\n \nAs of MariaDB 5.5, the return value is a nonbinary string in\nthe connection character set and collation, determined by\nthe values of the character_set_connection and\ncollation_connection system variables. Before 5.5, the\nreturn value was a binary string.\n \nThe return value is 16 bytes in length, or NULL if the\nargument was NULL.\n \n\n\nURL: https://mariadb.com/kb/en/library/old_password/','','https://mariadb.com/kb/en/library/old_password/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (145,12,'PASSWORD','Syntax\n------ \nPASSWORD(str)\n \nDescription\n----------- \nThe PASSWORD() function is used for hashing passwords for\nuse in authentication by the MariaDB server. It is not\nintended for use in other applications.\n \nCalculates and returns a hashed password string from the\nplaintext password str. Returns an empty string (>= MariaDB\n10.0.4) or NULL (\n\nURL: https://mariadb.com/kb/en/library/password/','','https://mariadb.com/kb/en/library/password/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (146,12,'SHA1','Syntax\n------ \nSHA1(str), SHA(str)\n \nDescription\n----------- \nCalculates an SHA-1 160-bit checksum for the string str, as\ndescribed in\nRFC 3174 (Secure Hash Algorithm).\n \nThe value is returned as a string of 40 hex digits, or NULL\nif the argument was NULL. As of MariaDB 5.5, the return\nvalue is a nonbinary string in the connection character set\nand collation, determined by the values of the\ncharacter_set_connection and collation_connection system\nvariables. Before 5.5, the return value was a binary string.\n \nExamples\n-------- \nSELECT SHA1(\'some boring text\');\n+------------------------------------------+\n| SHA1(\'some boring text\') |\n+------------------------------------------+\n| af969fc2085b1bb6d31e517d5c456def5cdd7093 |\n+------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/sha1/','','https://mariadb.com/kb/en/library/sha1/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (147,12,'SHA2','SHA2() was introduced in MariaDB 5.5\n \nSyntax\n------ \nSHA2(str,hash_len)\n \nDescription\n----------- \nGiven a string str, calculates an SHA-2 checksum, which is\nconsidered more cryptographically secure than its SHA-1\nequivalent. The SHA-2 family includes SHA-224, SHA-256,\nSHA-384, and SHA-512, and the hash_len must correspond to\none of these, i.e. 224, 256, 384 or 512. 0 is equivalent to\n256.\n \nThe return value is a nonbinary string in the connection\ncharacter set and collation, determined by the values of the\ncharacter_set_connection and collation_connection system\nvariables. \n \nNULL is returned if the hash length is not valid, or the\nstring str is NULL.\n \nSHA2 will only work if MariaDB was has been configured with\nTLS support. \n \nExamples\n-------- \nSELECT SHA2(\'Maria\',224);\n+----------------------------------------------------------+\n| SHA2(\'Maria\',224) |\n+----------------------------------------------------------+\n| 6cc67add32286412efcab9d0e1675a43a5c2ef3cec8879f81516ff83 |\n+----------------------------------------------------------+\n \nSELECT SHA2(\'Maria\',256);\n+------------------------------------------------------------------+\n| SHA2(\'Maria\',256) |\n+------------------------------------------------------------------+\n|\n9ff18ebe7449349f358e3af0b57cf7a032c1c6b2272cb2656ff85eb112232f16\n|\n+------------------------------------------------------------------+\n \nSELECT SHA2(\'Maria\',0);\n+------------------------------------------------------------------+\n| SHA2(\'Maria\',0) |\n+------------------------------------------------------------------+\n|\n9ff18ebe7449349f358e3af0b57cf7a032c1c6b2272cb2656ff85eb112232f16\n|\n+------------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/sha2/','','https://mariadb.com/kb/en/library/sha2/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (148,12,'UNCOMPRESS','Syntax\n------ \nUNCOMPRESS(string_to_uncompress)\n \nDescription\n----------- \nUncompresses a string compressed by the COMPRESS() function.\nIf the\nargument is not a compressed value, the result is NULL. This\nfunction\nrequires MariaDB to have been compiled with a compression\nlibrary such\nas zlib. Otherwise, the return value is always NULL. The\nhave_compress server system variable indicates whether a\ncompression library is present. \n \nExamples\n-------- \nSELECT UNCOMPRESS(COMPRESS(\'a string\'));\n+----------------------------------+\n| UNCOMPRESS(COMPRESS(\'a string\')) |\n+----------------------------------+\n| a string |\n+----------------------------------+\n \nSELECT UNCOMPRESS(\'a string\');\n+------------------------+\n| UNCOMPRESS(\'a string\') |\n+------------------------+\n| NULL |\n+------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/uncompress/','','https://mariadb.com/kb/en/library/uncompress/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (149,12,'UNCOMPRESSED_LENGTH','Syntax\n------ \nUNCOMPRESSED_LENGTH(compressed_string)\n \nDescription\n----------- \nReturns the length that the compressed string had before\nbeing\ncompressed with COMPRESS().\n \nUNCOMPRESSED_LENGTH() returns NULL or an incorrect result if\nthe string is not compressed.\n \nUntil MariaDB 10.3.1, returns MYSQL_TYPE_LONGLONG, or\nbigint(10), in all cases. From MariaDB 10.3.1, returns\nMYSQL_TYPE_LONG, or int(10), when the result would fit\nwithin 32-bits.\n \nExamples\n-------- \nSELECT UNCOMPRESSED_LENGTH(COMPRESS(REPEAT(\'a\',30)));\n+-----------------------------------------------+\n| UNCOMPRESSED_LENGTH(COMPRESS(REPEAT(\'a\',30))) |\n+-----------------------------------------------+\n| 30 |\n+-----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/uncompressed_length/','','https://mariadb.com/kb/en/library/uncompressed_length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (150,13,'ENDPOINT','A synonym for ST_ENDPOINT.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/linestring-properties-endpoint/','','https://mariadb.com/kb/en/library/linestring-properties-endpoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (151,13,'GLENGTH','Syntax\n------ \nGLength(ls)\n \nDescription\n----------- \nReturns as a double-precision number the length of the\nLineString value ls in its associated spatial reference.\n \nExamples\n-------- \nSET @ls = \'LineString(1 1,2 2,3 3)\';\n \nSELECT GLength(GeomFromText(@ls));\n+----------------------------+\n| GLength(GeomFromText(@ls)) |\n+----------------------------+\n| 2.82842712474619 |\n+----------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/glength/','','https://mariadb.com/kb/en/library/glength/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (152,13,'NumPoints','A synonym for ST_NumPoints.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/linestring-properties-numpoints/','','https://mariadb.com/kb/en/library/linestring-properties-numpoints/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (153,13,'PointN','A synonym for ST_PointN.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/linestring-properties-pointn/','','https://mariadb.com/kb/en/library/linestring-properties-pointn/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (154,13,'STARTPOINT','A synonym for ST_STARTPOINT.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/linestring-properties-startpoint/','','https://mariadb.com/kb/en/library/linestring-properties-startpoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (155,13,'ST_ENDPOINT','Syntax\n------ \nST_EndPoint(ls)\nEndPoint(ls)\n \nDescription\n----------- \nReturns the Point that is the endpoint of the\nLineString value ls.\n \nST_EndPoint() and EndPoint() are synonyms.\n \nExamples\n-------- \nSET @ls = \'LineString(1 1,2 2,3 3)\';\n \nSELECT AsText(EndPoint(GeomFromText(@ls)));\n+-------------------------------------+\n| AsText(EndPoint(GeomFromText(@ls))) |\n+-------------------------------------+\n| POINT(3 3) |\n+-------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_endpoint/','','https://mariadb.com/kb/en/library/st_endpoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (156,13,'ST_NUMPOINTS','Syntax\n------ \nST_NumPoints(ls)\nNumPoints(ls)\n \nDescription\n----------- \nReturns the number of Point objects in the LineString\nvalue ls.\n \nST_NumPoints() and NumPoints() are synonyms.\n \nExamples\n-------- \nSET @ls = \'LineString(1 1,2 2,3 3)\';\n \nSELECT NumPoints(GeomFromText(@ls));\n+------------------------------+\n| NumPoints(GeomFromText(@ls)) |\n+------------------------------+\n| 3 |\n+------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_numpoints/','','https://mariadb.com/kb/en/library/st_numpoints/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (157,13,'ST_POINTN','Syntax\n------ \nST_PointN(ls,N)\nPointN(ls,N)\n \nDescription\n----------- \nReturns the N-th Point in the LineString value ls.\nPoints are numbered beginning with 1.\n \nST_PointN() and PointN() are synonyms.\n \nExamples\n-------- \nSET @ls = \'LineString(1 1,2 2,3 3)\';\n \nSELECT AsText(PointN(GeomFromText(@ls),2));\n+-------------------------------------+\n| AsText(PointN(GeomFromText(@ls),2)) |\n+-------------------------------------+\n| POINT(2 2) |\n+-------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_pointn/','','https://mariadb.com/kb/en/library/st_pointn/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (158,14,'GET_LOCK','Syntax\n------ \nGET_LOCK(str,timeout)\n \nDescription\n----------- \nTries to obtain a lock with a name given by the string str,\nusing a timeout of timeout seconds. Returns 1 if the lock\nwas obtained successfully, 0 if the attempt timed out (for\nexample, because another client has previously locked the\nname), or NULL if an error occurred (such as running out of\nmemory or the thread was killed with mysqladmin kill).\n \nA lock is released with RELEASE_LOCK(), when the connection\nterminates (either normally or abnormally), or before\nMariaDB 10.0.2, when the connection executes another\nGET_LOCK statement. From MariaDB 10.0.2, a connection can\nhold multiple locks at the same time, so a lock that is no\nlonger needed needs to be explicitly released.\n \nThe IS_FREE_LOCK function returns whether a specified lock a\nfree or not, and the IS_USED_LOCK whether the function is in\nuse or not.\n \nLocks obtained with GET_LOCK() do not interact with\ntransactions. That is, committing a transaction does not\nrelease any such locks obtained during the transaction.\n \nFrom MariaDB 10.0.2, it is also possible to recursively set\nthe same lock. If a lock with the same name is set n times,\nit needs to be released n times as well. \n \nstr is case insensitive for GET_LOCK() and related\nfunctions. If str is an empty string or NULL, GET_LOCK()\nreturns NULL and does nothing. From MariaDB 10.2.2, timeout\nsupports microseconds. Before then, it was rounded to the\nclosest integer.\n \nIf the metadata_lock_info plugin is installed, locks\nacquired with this function are visible in the Information\nSchema METADATA_LOCK_INFO table.\n \nThis function can be used to implement application locks or\nto simulate record locks. Names are locked on a server-wide\nbasis. If a name has been locked by one client, GET_LOCK()\nblocks any request by another client for a lock with the\nsame name. This allows clients that agree on a given lock\nname to use the name to perform cooperative advisory\nlocking. But be aware that it also allows a client that is\nnot among the set of cooperating clients to lock a name,\neither inadvertently or deliberately, and thus prevent any\nof the cooperating clients from locking that name. One way\nto reduce the likelihood of this is to use lock names that\nare database-specific or application-specific. For example,\nuse lock names of the form db_name.str or app_name.str.\n \nStatements using the GET_LOCK() function are not safe for\nreplication.\n \nThe patch to permit multiple locks was contributed by\nKonstantin \"Kostja\" Osipov (MDEV-3917).\n \nExamples\n-------- \nSELECT GET_LOCK(\'lock1\',10);\n+----------------------+\n| GET_LOCK(\'lock1\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT IS_FREE_LOCK(\'lock1\'), IS_USED_LOCK(\'lock1\');\n+-----------------------+-----------------------+\n| IS_FREE_LOCK(\'lock1\') | IS_USED_LOCK(\'lock1\') |\n+-----------------------+-----------------------+\n| 0 | 46 |\n+-----------------------+-----------------------+\n \nSELECT IS_FREE_LOCK(\'lock2\'), IS_USED_LOCK(\'lock2\');\n+-----------------------+-----------------------+\n| IS_FREE_LOCK(\'lock2\') | IS_USED_LOCK(\'lock2\') |\n+-----------------------+-----------------------+\n| 1 | NULL |\n+-----------------------+-----------------------+\n \nFrom MariaDB 10.0.2, multiple locks can be held:\n \nSELECT GET_LOCK(\'lock2\',10);\n+----------------------+\n| GET_LOCK(\'lock2\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT IS_FREE_LOCK(\'lock1\'), IS_FREE_LOCK(\'lock2\');\n+-----------------------+-----------------------+\n| IS_FREE_LOCK(\'lock1\') | IS_FREE_LOCK(\'lock2\') |\n+-----------------------+-----------------------+\n| 0 | 0 |\n+-----------------------+-----------------------+\n \nSELECT RELEASE_LOCK(\'lock1\'), RELEASE_LOCK(\'lock2\');\n+-----------------------+-----------------------+\n| RELEASE_LOCK(\'lock1\') | RELEASE_LOCK(\'lock2\') |\n+-----------------------+-----------------------+\n| 1 | 1 |\n+-----------------------+-----------------------+\n \nBefore MariaDB 10.0.2, a connection could only hold a single\nlock:\n \nSELECT GET_LOCK(\'lock2\',10);\n+----------------------+\n| GET_LOCK(\'lock2\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT IS_FREE_LOCK(\'lock1\'), IS_FREE_LOCK(\'lock2\');\n+-----------------------+-----------------------+\n| IS_FREE_LOCK(\'lock1\') | IS_FREE_LOCK(\'lock2\') |\n+-----------------------+-----------------------+\n| 1 | 0 |\n+-----------------------+-----------------------+\n \nSELECT RELEASE_LOCK(\'lock1\'), RELEASE_LOCK(\'lock2\');\n+-----------------------+-----------------------+\n| RELEASE_LOCK(\'lock1\') | RELEASE_LOCK(\'lock2\') |\n+-----------------------+-----------------------+\n| NULL | 1 |\n+-----------------------+-----------------------+\n \nFrom MariaDB 10.0.2, it is possible to hold the same lock\nrecursively. This example is viewed using the\nmetadata_lock_info plugin:\n \nSELECT GET_LOCK(\'lock3\',10);\n+----------------------+\n| GET_LOCK(\'lock3\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT GET_LOCK(\'lock3\',10);\n+----------------------+\n| GET_LOCK(\'lock3\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT * FROM INFORMATION_SCHEMA.METADATA_LOCK_INFO;\n \n+-----------+---------------------+---------------+-----------+--------------+------------+\n| THREAD_ID | LOCK_MODE | LOCK_DURATION | LOCK_TYPE |\nTABLE_SCHEMA | TABLE_NAME |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n| 46 | MDL_SHARED_NO_WRITE | NULL | User lock | lock3 | |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n \nSELECT RELEASE_LOCK(\'lock3\');\n+-----------------------+\n| RELEASE_LOCK(\'lock3\') |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nSELECT * FROM INFORMATION_SCHEMA.METADATA_LOCK_INFO;\n \n+-----------+---------------------+---------------+-----------+--------------+------------+\n| THREAD_ID | LOCK_MODE | LOCK_DURATION | LOCK_TYPE |\nTABLE_SCHEMA | TABLE_NAME |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n| 46 | MDL_SHARED_NO_WRITE | NULL | User lock | lock3 | |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n \nSELECT RELEASE_LOCK(\'lock3\');\n+-----------------------+\n| RELEASE_LOCK(\'lock3\') |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nSELECT * FROM INFORMATION_SCHEMA.METADATA_LOCK_INFO;\n \nEmpty set (0.000 sec)\n \nTimeout example: Connection 1:\n \nSELECT GET_LOCK(\'lock4\',10);\n+----------------------+\n| GET_LOCK(\'lock4\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nConnection 2:\n \nSELECT GET_LOCK(\'lock4\',10);\n \nAfter 10 seconds...\n \n+----------------------+\n| GET_LOCK(\'lock4\',10) |\n+----------------------+\n| 0 |\n+----------------------+\n \nDeadlocks are automatically detected and resolved.\nConnection 1:\n \nSELECT GET_LOCK(\'lock5\',10); \n+----------------------+\n| GET_LOCK(\'lock5\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nConnection 2:\n \nSELECT GET_LOCK(\'lock6\',10);\n+----------------------+\n| GET_LOCK(\'lock6\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nConnection 1:\n \nSELECT GET_LOCK(\'lock6\',10); \n+----------------------+\n| GET_LOCK(\'lock6\',10) |\n+----------------------+\n| 0 |\n+----------------------+\n \nConnection 2:\n \nSELECT GET_LOCK(\'lock5\',10);\nERROR 1213 (40001): Deadlock found when trying to get lock;\n try restarting transaction\n \n\n\nURL: https://mariadb.com/kb/en/library/get_lock/','','https://mariadb.com/kb/en/library/get_lock/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (159,14,'INET6_ATON','INET6_ATON() has been available since MariaDB 10.0.12.\n \nSyntax\n------ \nINET6_ATON(expr)\n \nDescription\n----------- \nGiven an IPv6 or IPv4 network address as a string, returns a\nbinary string that represents the numeric value of the\naddress.\n \nNo trailing zone ID\'s or traling network masks are\npermitted. For IPv4 addresses, or IPv6 addresses with IPv4\naddress parts, no classful addresses or trailing port\nnumbers are permitted and octal numbers are not supported.\n \nThe returned binary string will be VARBINARY(16) or\nVARBINARY(4) for IPv6 and IPv4 addresses respectively.\n \nReturns NULL if the argument is not understood.\n \nExamples\n-------- \nSELECT HEX(INET6_ATON(\'10.0.1.1\'));\n+-----------------------------+\n| HEX(INET6_ATON(\'10.0.1.1\')) |\n+-----------------------------+\n| 0A000101 |\n+-----------------------------+\n \nSELECT HEX(INET6_ATON(\'48f3::d432:1431:ba23:846f\'));\n+----------------------------------------------+\n| HEX(INET6_ATON(\'48f3::d432:1431:ba23:846f\')) |\n+----------------------------------------------+\n| 48F3000000000000D4321431BA23846F |\n+----------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/inet6_aton/','','https://mariadb.com/kb/en/library/inet6_aton/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (160,14,'INET6_NTOA','INET6_NTOA() has been available from MariaDB 10.0.12.\n \nSyntax\n------ \nINET6_NTOA(expr)\n \nDescription\n----------- \nGiven an IPv6 or IPv4 network address as a numeric binary\nstring, returns the address as a nonbinary string in the\nconnection character set.\n \nThe return string is lowercase, and is platform independent,\nsince it does not use functions specific to the operating\nsystem. It has a maximum length of 39 characters.\n \nReturns NULL if the argument is not understood.\n \nExamples\n-------- \nSELECT INET6_NTOA(UNHEX(\'0A000101\'));\n+-------------------------------+\n| INET6_NTOA(UNHEX(\'0A000101\')) |\n+-------------------------------+\n| 10.0.1.1 |\n+-------------------------------+\n \nSELECT\nINET6_NTOA(UNHEX(\'48F3000000000000D4321431BA23846F\'));\n+-------------------------------------------------------+\n| INET6_NTOA(UNHEX(\'48F3000000000000D4321431BA23846F\')) |\n+-------------------------------------------------------+\n| 48f3::d432:1431:ba23:846f |\n+-------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/inet6_ntoa/','','https://mariadb.com/kb/en/library/inet6_ntoa/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (161,14,'INET_ATON','Syntax\n------ \nINET_ATON(expr)\n \nDescription\n----------- \nGiven the dotted-quad representation of an IPv4 network\naddress as a string,\nreturns an integer that represents the numeric value of the\naddress.\nAddresses may be 4- or 8-byte addresses.\n \nReturns NULL if the argument is not understood.\n \nExamples\n-------- \nSELECT INET_ATON(\'192.168.1.1\');\n+--------------------------+\n| INET_ATON(\'192.168.1.1\') |\n+--------------------------+\n| 3232235777 |\n+--------------------------+\n \nThis is calculated as follows: 192 x 2563 + 168 x 256 2 + 1\nx 256 + 1\n \n\n\nURL: https://mariadb.com/kb/en/library/inet_aton/','','https://mariadb.com/kb/en/library/inet_aton/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (162,14,'INET_NTOA','Syntax\n------ \nINET_NTOA(expr)\n \nDescription\n----------- \nGiven a numeric IPv4 network address in network byte order\n(4 or 8 byte),\nreturns the dotted-quad representation of the address as a\nstring.\n \nExamples\n-------- \nSELECT INET_NTOA(3232235777);\n+-----------------------+\n| INET_NTOA(3232235777) |\n+-----------------------+\n| 192.168.1.1 |\n+-----------------------+\n \n192.168.1.1 corresponds to 3232235777 since 192 x 2563 + 168\nx 256 2 + 1 x 256 + 1 = 3232235777\n \n\n\nURL: https://mariadb.com/kb/en/library/inet_ntoa/','','https://mariadb.com/kb/en/library/inet_ntoa/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (163,14,'IS_FREE_LOCK','Syntax\n------ \nIS_FREE_LOCK(str)\n \nDescription\n----------- \nChecks whether the lock named str is free to use (that is,\nnot locked).\nReturns 1 if the lock is free (no one is using the lock),\n 0 if the lock is in use, and NULL if an\nerror occurs (such as an incorrect argument, like an empty\nstring or NULL). str is case insensitive.\n \nIf the metadata_lock_info plugin is installed, the\nInformation Schema metadata_lock_info table contains\ninformation about locks of this kind (as well as metadata\nlocks).\n \nStatements using the IS_FREE_LOCK() function are not safe\nfor replication.\n \n\n\nURL: https://mariadb.com/kb/en/library/is_free_lock/','','https://mariadb.com/kb/en/library/is_free_lock/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (164,14,'IS_IPV4','IS_IPV4() has been available since MariaDB 10.0.12.\n \nSyntax\n------ \nIS_IPV4(expr)\n \nDescription\n----------- \nIf the expression is a valid IPv4 address, returns 1,\notherwise returns 0.\n \nIS_IPV4() is stricter than INET_ATON(), but as strict as\nINET6_ATON(), in determining the validity of an IPv4\naddress. This implies that if IS_IPV4 returns 1, the same\nexpression will always return a non-NULL result when passed\nto INET_ATON(), but that the reverse may not apply.\n \nExamples\n-------- \nSELECT IS_IPV4(\'1110.0.1.1\');\n+-----------------------+\n| IS_IPV4(\'1110.0.1.1\') |\n+-----------------------+\n| 0 |\n+-----------------------+\n \nSELECT IS_IPV4(\'48f3::d432:1431:ba23:846f\');\n+--------------------------------------+\n| IS_IPV4(\'48f3::d432:1431:ba23:846f\') |\n+--------------------------------------+\n| 0 |\n+--------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/is_ipv4/','','https://mariadb.com/kb/en/library/is_ipv4/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (165,14,'IS_IPV4_COMPAT','IS_IPV4_COMPAT() has been available since MariaDB 10.0.12.\n \nSyntax\n------ \nIS_IPV4_COMPAT(expr)\n \nDescription\n----------- \nReturns 1 if a given numeric binary string IPv6 address,\nsuch as returned by INET6_ATON(), is IPv4-compatible,\notherwise returns 0. \n \nExamples\n-------- \nSELECT IS_IPV4_COMPAT(INET6_ATON(\'::10.0.1.1\'));\n+------------------------------------------+\n| IS_IPV4_COMPAT(INET6_ATON(\'::10.0.1.1\')) |\n+------------------------------------------+\n| 1 |\n+------------------------------------------+\n \nSELECT\nIS_IPV4_COMPAT(INET6_ATON(\'::48f3::d432:1431:ba23:846f\'));\n+-----------------------------------------------------------+\n|\nIS_IPV4_COMPAT(INET6_ATON(\'::48f3::d432:1431:ba23:846f\'))\n|\n+-----------------------------------------------------------+\n| 0 |\n+-----------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/is_ipv4_compat/','','https://mariadb.com/kb/en/library/is_ipv4_compat/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (166,14,'IS_IPV4_MAPPED','IS_IPV4_MAPPED() has been available since MariaDB 10.0.12.\n \nSyntax\n------ \nIS_IPV4_MAPPED(expr)\n \nDescription\n----------- \nReturns 1 if a given a numeric binary string IPv6 address,\nsuch as returned by INET6_ATON(), is a valid IPv4-mapped\naddress, otherwise returns 0.\n \nExamples\n-------- \nSELECT IS_IPV4_MAPPED(INET6_ATON(\'::10.0.1.1\'));\n+------------------------------------------+\n| IS_IPV4_MAPPED(INET6_ATON(\'::10.0.1.1\')) |\n+------------------------------------------+\n| 0 |\n+------------------------------------------+\n \nSELECT IS_IPV4_MAPPED(INET6_ATON(\'::ffff:10.0.1.1\'));\n+-----------------------------------------------+\n| IS_IPV4_MAPPED(INET6_ATON(\'::ffff:10.0.1.1\')) |\n+-----------------------------------------------+\n| 1 |\n+-----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/is_ipv4_mapped/','','https://mariadb.com/kb/en/library/is_ipv4_mapped/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (167,14,'IS_IPV6','IS_IPV6() has been available since MariaDB 10.0.12.\n \nSyntax\n------ \nIS_IPV6(expr)\n \nDescription\n----------- \nReturns 1 if the expression is a valid IPv6 address\nspecified as a string, otherwise returns 0. Does not\nconsider IPv4 addresses to be valid IPv6 addresses.\n \nExamples\n-------- \n SELECT IS_IPV6(\'48f3::d432:1431:ba23:846f\');\n+--------------------------------------+\n| IS_IPV6(\'48f3::d432:1431:ba23:846f\') |\n+--------------------------------------+\n| 1 |\n+--------------------------------------+\n1 row in set (0.02 sec)\n \nSELECT IS_IPV6(\'10.0.1.1\');\n+---------------------+\n| IS_IPV6(\'10.0.1.1\') |\n+---------------------+\n| 0 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/is_ipv6/','','https://mariadb.com/kb/en/library/is_ipv6/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (168,14,'IS_USED_LOCK','Syntax\n------ \nIS_USED_LOCK(str)\n \nDescription\n----------- \nChecks whether the lock named str is in use (that is,\nlocked). If so,\nit returns the connection identifier of the client that\nholds the\nlock. Otherwise, it returns NULL. str is case insensitive.\n \nIf the metadata_lock_info plugin is installed, the\nInformation Schema metadata_lock_info table contains\ninformation about locks of this kind (as well as metadata\nlocks).\n \nStatements using the IS_USED_LOCK() function are not safe\nfor replication.\n \n\n\nURL: https://mariadb.com/kb/en/library/is_used_lock/','','https://mariadb.com/kb/en/library/is_used_lock/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (169,14,'MASTER_GTID_WAIT','MASTER_GTID_WAIT() was included in MariaDB 10.0.9.\n \nSyntax\n------ \nMASTER_GTID_WAIT(gtid-list[, timeout)\n \nDescription\n----------- \nThis function takes a string containing a comma-separated\nlist of global transaction id\'s\n(similar to the value of, for example, gtid_binlog_pos). It\nwaits until the value of gtid_slave_pos has the same or\nhigher seq_no within all replication domains specified in\nthe gtid-list; in other words, it waits until the slave has\nreached the specified GTID position.\n \nAn optional second argument gives a timeout in seconds. If\nthe timeout\nexpires before the specified GTID position is reached, then\nthe function\nreturns -1. Passing NULL or a negative number for the\ntimeout means no timeout, and the function will wait\nindefinitely.\n \n If the wait completes without a timeout, 0 is returned.\nPassing NULL for the\n gtid-list makes the function return NULL immediately,\nwithout waiting.\n \nThe gtid-list may be the empty string, in which case\nMASTER_GTID_WAIT()\nreturns immediately. If the gtid-list contains fewer domains\nthan\ngtid_slave_pos, then only those domains are waited upon. If\ngtid-list\ncontains a domain that is not present in @@gtid_slave_pos,\nthen\nMASTER_GTID_WAIT() will wait until an event containing such\ndomain_id arrives\non the slave (or until timed out or killed).\n \nMASTER_GTID_WAIT() can be useful to ensure that a slave has\ncaught up to\na master. Simply take the value of gtid_binlog_pos on the\nmaster, and use it in a MASTER_GTID_WAIT() call on the\nslave; when the call completes, the slave\nwill have caught up with that master position.\n \nMASTER_GTID_WAIT() can also be used in client applications\ntogether with the\nlast_gtid session variable. This is useful in a\nread-scaleout replication setup, where the application\nwrites to a single master but divides the\nreads out to a number of slaves to distribute the load. In\nsuch a setup, there\nis a risk that an application could first do an update on\nthe master, and then\na bit later do a read on a slave, and if the slave is not\nfast enough, the\ndata read from the slave might not include the update just\nmade, possibly\nconfusing the application and/or the end-user. One way to\navoid this is to\nrequest the value of last_gtid on the master just after the\nupdate. Then\nbefore doing the read on the slave, do a MASTER_GTID_WAIT()\non the value\nobtained from the master; this will ensure that the read is\nnot performed\nuntil the slave has replicated sufficiently far for the\nupdate to have become\nvisible.\n \nNote that MASTER_GTID_WAIT() can be used even if the slave\nis configured not\nto use GTID for connections (CHANGE MASTER TO\nmaster_use_gtid=no). This is\nbecause from MariaDB 10, GTIDs are always logged on the\nmaster server, and\nalways recorded on the slave servers.\n \nDifferences to MASTER_POS_WAIT()\n \nMASTER_GTID_WAIT() is global; it waits for any master\nconnection to reach\n the specified GTID position. MASTER_POS_WAIT() works only\nagainst a\n specific connection. This also means that while\nMASTER_POS_WAIT() aborts if\n its master connection is terminated with STOP SLAVE or due\nto an error,\n MASTER_GTID_WAIT() continues to wait while slaves are\nstopped.\n \nMASTER_GTID_WAIT() can take its timeout as a floating-point\nvalue, so a\n timeout in fractional seconds is supported, eg.\nMASTER_GTID_WAIT(\"0-1-100\",\n 0.5). (The minimum wait is one microsecond, 0.000001\nseconds).\n \nMASTER_GTID_WAIT() allows one to specify a timeout of zero\nin order to do a\n non-blocking check to see if the slaves have progressed to\na specific GTID position\n (MASTER_POS_WAIT() takes a zero timeout as meaning an\ninfinite wait). To do\n an infinite MASTER_GTID_WAIT(), specify a negative timeout,\nor omit the\n timeout argument.\n \nMASTER_GTID_WAIT() does not return the number of events\nexecuted since the\n wait started, nor does it return NULL if a slave thread is\nstopped. It\n always returns either 0 for successful wait completed, or\n-1 for timeout\n reached (or NULL if the specified gtid-pos is NULL).\n \nSince MASTER_GTID_WAIT() looks only at the seq_no part of\nthe GTIDs, not the\nserver_id, care is needed if a slave becomes diverged from\nanother server so\nthat two different GTIDs with the same seq_no (in the same\ndomain) arrive at\nthe same server. This situation is in any case best avoided;\nsetting\ngtid_strict_mode is recommended, as this will prevent any\nsuch out-of-order sequence numbers from ever being\nreplicated on a slave.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/master_gtid_wait/','','https://mariadb.com/kb/en/library/master_gtid_wait/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (170,14,'MASTER_POS_WAIT','MASTER_POS_WAIT was introduced in MariaDB 10.0.9.\n \nSyntax\n------ \nMASTER_POS_WAIT(log_name,log_pos[,timeout,[\"connection_name\"]])\n \nDescription\n----------- \nThis function is useful in replication for controlling\nmaster/slave synchronization. It blocks until the slave has\nread and applied all updates up to the specified position\n(log_name,log_pos) in the master log. The return value is\nthe number of log events the slave had to wait for to\nadvance to the specified position. The function returns NULL\nif\nthe slave SQL thread is not started, the slave\'s master\ninformation is not\ninitialized, the arguments are incorrect, or an error\noccurs. It returns -1 if\nthe timeout has been exceeded. If the slave SQL thread stops\nwhile\n MASTER_POS_WAIT() is waiting, the function returns NULL. If\nthe slave is past the specified position, the function\nreturns immediately.\n \nIf a timeout value is specified, MASTER_POS_WAIT() stops\nwaiting when timeout seconds have elapsed. timeout must be\ngreater than 0; a\nzero or negative timeout means no timeout.\n \nThe connection_name is used when you are using\nmulti-source-replication. If you don\'t specify it, it\'s\nset to the value of the default_master_connection system\nvariable.\n \nStatements using the MASTER_POS_WAIT() function are not safe\nfor replication.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/master_pos_wait/','','https://mariadb.com/kb/en/library/master_pos_wait/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (171,14,'NAME_CONST','Syntax\n------ \nNAME_CONST(name,value)\n \nDescription\n----------- \nReturns the given value. When used to produce a result set\ncolumn,\n NAME_CONST() causes the column to have the given name. The\narguments should be constants.\n \nThis function is used internally when replicating stored\nprocedures. It makes little sense to use it explicitly in\nSQL statements, and it was not supposed to be used like\nthat.\n \nSELECT NAME_CONST(\'myname\', 14);\n+--------+\n| myname |\n+--------+\n| 14 |\n+--------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/name_const/','','https://mariadb.com/kb/en/library/name_const/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (172,14,'RELEASE_LOCK','Syntax\n------ \nRELEASE_LOCK(str)\n \nDescription\n----------- \nReleases the lock named by the string str that was obtained\nwith GET_LOCK(). Returns 1 if the lock was released, 0 if\nthe lock was not established by this thread (in which case\nthe lock is not\nreleased), and NULL if the named lock did not exist. The\nlock does not exist if it was never obtained by a call to\nGET_LOCK() or if it has previously been released.\n \nMariaDB until 10.0.1\n \nBefore 10.0.2, GET_LOCK() released the existing lock, if\nany. Since 10.0.2 this does not happen, because multiple\nlocks are allowed.\n \nstr is case insensitive. If str is an empty string or NULL,\nRELEASE_LOCK() returns NULL and does nothing.\n \nStatements using the RELEASE_LOCK() function are not safe\nfor replication.\n \nThe DO statement is convenient to use with RELEASE_LOCK().\n \nExamples\n-------- \nConnection1:\n \nSELECT GET_LOCK(\'lock1\',10);\n+----------------------+\n| GET_LOCK(\'lock1\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nConnection 2:\n \nSELECT GET_LOCK(\'lock2\',10);\n+----------------------+\n| GET_LOCK(\'lock2\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nConnection 1:\n \nSELECT RELEASE_LOCK(\'lock1\'), RELEASE_LOCK(\'lock2\'),\nRELEASE_LOCK(\'lock3\');\n+-----------------------+-----------------------+-----------------------+\n| RELEASE_LOCK(\'lock1\') | RELEASE_LOCK(\'lock2\') |\nRELEASE_LOCK(\'lock3\') |\n+-----------------------+-----------------------+-----------------------+\n| 1 | 0 | NULL |\n+-----------------------+-----------------------+-----------------------+\n \nFrom MariaDB 10.0.2, it is possible to hold the same lock\nrecursively. This example is viewed using the\nmetadata_lock_info plugin:\n \nSELECT GET_LOCK(\'lock3\',10);\n+----------------------+\n| GET_LOCK(\'lock3\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT GET_LOCK(\'lock3\',10);\n+----------------------+\n| GET_LOCK(\'lock3\',10) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT * FROM INFORMATION_SCHEMA.METADATA_LOCK_INFO;\n \n+-----------+---------------------+---------------+-----------+--------------+------------+\n| THREAD_ID | LOCK_MODE | LOCK_DURATION | LOCK_TYPE |\nTABLE_SCHEMA | TABLE_NAME |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n| 46 | MDL_SHARED_NO_WRITE | NULL | User lock | lock3 | |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n \nSELECT RELEASE_LOCK(\'lock3\');\n+-----------------------+\n| RELEASE_LOCK(\'lock3\') |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nSELECT * FROM INFORMATION_SCHEMA.METADATA_LOCK_INFO;\n \n+-----------+---------------------+---------------+-----------+--------------+------------+\n| THREAD_ID | LOCK_MODE | LOCK_DURATION | LOCK_TYPE |\nTABLE_SCHEMA | TABLE_NAME |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n| 46 | MDL_SHARED_NO_WRITE | NULL | User lock | lock3 | |\n+-----------+---------------------+---------------+-----------+--------------+------------+\n \nSELECT RELEASE_LOCK(\'lock3\');\n+-----------------------+\n| RELEASE_LOCK(\'lock3\') |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nSELECT * FROM INFORMATION_SCHEMA.METADATA_LOCK_INFO;\n \nEmpty set (0.000 sec)\n \n\n\nURL: https://mariadb.com/kb/en/library/release_lock/','','https://mariadb.com/kb/en/library/release_lock/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (173,14,'SLEEP','Syntax\n------ \nSLEEP(duration)\n \nDescription\n----------- \nSleeps (pauses) for the number of seconds given by the\nduration argument, then\nreturns 0. If SLEEP() is interrupted, it\nreturns 1. The duration may have a fractional part given in\nmicroseconds.\n \nStatements using the SLEEP() function are not safe for\nreplication.\n \nExample\n \nSELECT SLEEP(5.5);\n+------------+\n| SLEEP(5.5) |\n+------------+\n| 0 |\n+------------+\n1 row in set (5.50 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/sleep/','','https://mariadb.com/kb/en/library/sleep/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (174,14,'UUID','Syntax\n------ \nUUID()\n \nDescription\n----------- \nReturns a Universal Unique Identifier (UUID) generated\naccording to \"DCE 1.1:\nRemote Procedure Call\" (Appendix A) CAE (Common\nApplications Environment)\nSpecifications published by The Open Group in October\n1997 \n(Document Number C706).\n \nA UUID is designed as a number that is globally unique in\nspace and time. Two\ncalls to UUID() are expected to generate two different\nvalues, even if these calls are performed on two separate\ncomputers that are\nnot connected to each other.\n \nA UUID is a 128-bit number represented by a utf8 string of\nfive\nhexadecimal numbers in aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee\nformat:\nThe first three numbers are generated from a timestamp.\nThe fourth number preserves temporal uniqueness in case the\ntimestamp value\n loses monotonicity (for example, due to daylight saving\ntime).\nThe fifth number is an IEEE 802 node number that provides\nspatial uniqueness.\n A random number is substituted if the latter is not\navailable (for example,\n because the host computer has no Ethernet card, or we do\nnot know how to find\n the hardware address of an interface on your operating\nsystem). In this case,\n spatial uniqueness cannot be guaranteed. Nevertheless, a\ncollision should\n have very low probability.\n \nCurrently, the MAC address of an interface is taken into\naccount only on FreeBSD and Linux. On other operating\nsystems, MariaDB uses a randomly generated 48-bit number.\n \nStatements using the UUID() function are not safe for\nreplication.\n \nUUID() results are intended to be unique, but cannot always\nbe relied upon to unpredictable and unguessable, so should\nnot be relied upon for these purposes.\n \nExamples\n-------- \nSELECT UUID();\n+--------------------------------------+\n| UUID() |\n+--------------------------------------+\n| cd41294a-afb0-11df-bc9b-00241dd75637 |\n+--------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/uuid/','','https://mariadb.com/kb/en/library/uuid/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (175,14,'UUID_SHORT','Syntax\n------ \nUUID_SHORT()\n \nDescription\n----------- \nReturns a \"short\" universal identifier as a 64-bit\nunsigned integer (rather\nthan a string-form 128-bit identifier as returned by the\nUUID() function).\n \nThe value of UUID_SHORT() is guaranteed to be unique if the\nfollowing conditions hold:\nThe server_id of the current host is unique among your set\nof master and\n slave servers\nserver_id is between 0 and 255\nYou don\'t set back your system time for your server between\nmysqld restarts\nYou do not invoke UUID_SHORT() on average more than 16\n million times per second between mysqld restarts\n \nThe UUID_SHORT() return value is constructed this way:\n \n (server_id & 255) \n\nURL: https://mariadb.com/kb/en/library/uuid_short/','','https://mariadb.com/kb/en/library/uuid_short/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (176,14,'VALUES / VALUE','Syntax\n------ \nVALUE(col_name) \n \nMariaDB until 10.3.2\n \nVALUES(col_name) \n \nDescription\n----------- \nIn an INSERT ... ON DUPLICATE KEY UPDATE statement, you can\nuse the VALUES(col_name) function in the UPDATE clause to\nrefer to column values from the INSERT portion of the\nstatement. In other words, VALUES(col_name) in the UPDATE\nclause refers to the value of col_name that would be\ninserted, had no duplicate-key conflict occurred. This\nfunction is especially useful in multiple-row inserts.\n \nThe VALUES() function is meaningful only in INSERT ... ON\nDUPLICATE KEY UPDATE statements and returns NULL otherwise.\n \nIn MariaDB 10.3.3 this function was renamed to VALUE(),\nbecause it\'s incompatible with the standard Table Value\nConstructors syntax, implemented in MariaDB 10.3.3.\n \nThe VALUES() function can still be used even from MariaDB\n10.3.3, but only in INSERT ... ON DUPLICATE KEY UPDATE\nstatements; it\'s a syntax error otherwise.\n \nExamples\n-------- \nINSERT INTO t (a,b,c) VALUES (1,2,3),(4,5,6)\n ON DUPLICATE KEY UPDATE c=VALUE(a)+VALUE(b);\n \nMariaDB until 10.3.2\n \nINSERT INTO t (a,b,c) VALUES (1,2,3),(4,5,6)\n ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/values-value/','','https://mariadb.com/kb/en/library/values-value/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (177,15,'!','Syntax\n------ \nNOT, !\n \nDescription\n----------- \nLogical NOT. Evaluates to 1 if the operand is 0, to 0 if the\noperand\nis non-zero, and NOT NULL returns NULL.\n \nBy default, the ! operator has a higher precedence. If the\nHIGH_NOT_PRECEDENCE SQL_MODE flag is set, NOT and ! have the\nsame precedence.\n \nExamples\n-------- \nSELECT NOT 10;\n \n+--------+\n| NOT 10 |\n+--------+\n| 0 |\n+--------+\n \nSELECT NOT 0;\n \n+-------+\n| NOT 0 |\n+-------+\n| 1 |\n+-------+\n \nSELECT NOT NULL;\n \n+----------+\n| NOT NULL |\n+----------+\n| NULL |\n+----------+\n \nSELECT ! (1+1);\n+---------+\n| ! (1+1) |\n+---------+\n| 0 |\n+---------+\n \nSELECT ! 1+1;\n \n+-------+\n| ! 1+1 |\n+-------+\n| 1 |\n+-------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/not/','','https://mariadb.com/kb/en/library/not/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (178,15,'&&','Syntax\n------ \nAND, &&\n \nDescription\n----------- \nLogical AND. Evaluates to 1 if all operands are non-zero and\nnot NULL,\nto 0 if one or more operands are 0, otherwise NULL is\nreturned.\n \nFor this operator, short-circuit evaluation can be used.\n \nExamples\n-------- \nSELECT 1 && 1;\n \n+--------+\n| 1 && 1 |\n+--------+\n| 1 |\n+--------+\n \nSELECT 1 && 0;\n \n+--------+\n| 1 && 0 |\n+--------+\n| 0 |\n+--------+\n \nSELECT 1 && NULL;\n \n+-----------+\n| 1 && NULL |\n+-----------+\n| NULL |\n+-----------+\n \nSELECT 0 && NULL;\n \n+-----------+\n| 0 && NULL |\n+-----------+\n| 0 |\n+-----------+\n \nSELECT NULL && 0;\n \n+-----------+\n| NULL && 0 |\n+-----------+\n| 0 |\n+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/and/','','https://mariadb.com/kb/en/library/and/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (179,15,'||','Syntax\n------ \nOR, ||\n \nDescription\n----------- \nLogical OR. When both operands are non-NULL, the result is 1\nif any\noperand is non-zero, and 0 otherwise. With a NULL operand,\nthe result\nis 1 if the other operand is non-zero, and NULL otherwise.\nIf both\noperands are NULL, the result is NULL.\n \nFor this operator, short-circuit evaluation can be used.\n \nNote that, if the PIPES_AS_CONCAT SQL_MODE is set, || is\nused as a string concatenation operator. This means that a\n|| b is the same as CONCAT(a,b). See CONCAT() for details.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, || ignores NULL.\n \nExamples\n-------- \nSELECT 1 || 1;\n \n+--------+\n| 1 || 1 |\n+--------+\n| 1 |\n+--------+\n \nSELECT 1 || 0;\n \n+--------+\n| 1 || 0 |\n+--------+\n| 1 |\n+--------+\n \nSELECT 0 || 0;\n \n+--------+\n| 0 || 0 |\n+--------+\n| 0 |\n+--------+\n \nSELECT 0 || NULL;\n \n+-----------+\n| 0 || NULL |\n+-----------+\n| NULL |\n+-----------+\n \nSELECT 1 || NULL;\n \n+-----------+\n| 1 || NULL |\n+-----------+\n| 1 |\n+-----------+\n \nIn Oracle mode, from MariaDB 10.3:\n \nSELECT 0 || NULL;\n \n+-----------+\n| 0 || NULL |\n+-----------+\n| 0 |\n+-----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/or/','','https://mariadb.com/kb/en/library/or/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (180,15,'XOR','Syntax\n------ \nXOR\n \nDescription\n----------- \nXOR stands for eXclusive OR. Returns NULL if either operand\nis NULL. For non-NULL\noperands, evaluates to 1 if an odd number of operands is\nnon-zero,\notherwise 0 is returned.\n \nExamples\n-------- \nSELECT 1 XOR 1;\n \n+---------+\n| 1 XOR 1 |\n+---------+\n| 0 |\n+---------+\n \nSELECT 1 XOR 0;\n \n+---------+\n| 1 XOR 0 |\n+---------+\n| 1 |\n+---------+\n \nSELECT 1 XOR NULL;\n \n+------------+\n| 1 XOR NULL |\n+------------+\n| NULL |\n+------------+\n \nIn the following example, the right 1 XOR 1 is evaluated\nfirst, and returns 0. Then, 1 XOR 0 is evaluated, and 1 is\nreturned.\n \nSELECT 1 XOR 1 XOR 1;\n \n+---------------+\n| 1 XOR 1 XOR 1 |\n+---------------+\n| 1 |\n+---------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/xor/','','https://mariadb.com/kb/en/library/xor/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (181,15,'Assignment Operator (=)','Syntax\n------ \nidentifier = expr\n \nDescription\n----------- \nThe equal sign is used as both an assignment operator in\ncertain contexts, and as a comparison operator. When used as\nassignment operator, the value on the right is assigned to\nthe variable (or column, in some contexts) on the left.\n \nSince its use can be ambiguous, unlike the := assignment\noperator, the = assignment operator cannot be used in all\ncontexts, and is only valid as part of a SET statement, or\nthe SET clause of an UPDATE statement\n \nThis operator works with both user-defined variables and\nlocal variables.\n \nExamples\n-------- \nUPDATE table_name SET x = 2 WHERE x > 100;\n \nSET @x = 1, @y := 2;\n \n\n \n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/assignment-operators-assignment-operator/','','https://mariadb.com/kb/en/library/assignment-operators-assignment-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (182,15,'Assignment Operator (:=)','Syntax\n------ \nvar_name := expr\n \nDescription\n----------- \nAssignment operator for assigning a value. The value on the\nright is assigned to the variable on left.\n \nUnlike the = operator, := can always be used to assign a\nvalue to a variable.\n \nThis operator works with both user-defined variables and\nlocal variables.\n \nWhen assigning the same value to several variables,\nLAST_VALUE() can be useful.\n \nExamples\n-------- \n SELECT @x := 10;\n \n+----------+\n| @x := 10 |\n+----------+\n| 10 |\n+----------+\n \nSELECT @x, @y := @x;\n \n+------+----------+\n| @x | @y := @x |\n+------+----------+\n| 10 | 10 |\n+------+----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/assignment-operator/','','https://mariadb.com/kb/en/library/assignment-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (183,16,'Stored Aggregate Functions','The ability to create stored aggregate functions was added\nin MariaDB 10.3.3.\n \nAggregate functions are functions that are computed over a\nsequence of rows and return one result for the sequence of\nrows.\n \nCreating a custom aggregate function is done using the\nCREATE FUNCTION statement with two main differences:\nThe addition of the AGGREGATE keyword, so CREATE AGGREGATE\nFUNCTION\nThe FETCH GROUP NEXT ROW instruction inside the loop\nOracle PL/SQL compatibility using SQL/PL is provided\n \nStandard Syntax\n \nCREATE AGGREGATE FUNCTION function_name (parameters) RETURNS\nreturn_type\nBEGIN\n All types of declarations\n DECLARE CONTINUE HANDLER FOR NOT FOUND RETURN return_val;\n LOOP\n FETCH GROUP NEXT ROW; // fetches next row from table\n other instructions\n END LOOP;\nEND\n \nStored aggregate functions were a 2016 Google Summer of Code\nproject by Varun Gupta.\n \nUsing SQL/PL\n \nSET sql_mode=Oracle;\nDELIMITER //\n \nCREATE AGGREGATE FUNCTION function_name (parameters) RETURN\nreturn_type\n declarations\nBEGIN\n LOOP\n FETCH GROUP NEXT ROW; -- fetches next row from table\n -- other instructions\n \n END LOOP;\nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN return_val;\nEND //\n \nDELIMITER ;\n \nExamples\n-------- \nFirst a simplified example:\n \nCREATE TABLE marks(stud_id INT, grade_count INT);\n \nINSERT INTO marks VALUES (1,6), (2,4), (3,7), (4,5), (5,8);\n \nSELECT * FROM marks;\n \n+---------+-------------+\n| stud_id | grade_count |\n+---------+-------------+\n| 1 | 6 |\n| 2 | 4 |\n| 3 | 7 |\n| 4 | 5 |\n| 5 | 8 |\n+---------+-------------+\n \nDELIMITER //\nCREATE AGGREGATE FUNCTION IF NOT EXISTS aggregate_count(x\nINT) RETURNS INT\nBEGIN\n DECLARE count_students INT DEFAULT 0;\n \n DECLARE CONTINUE HANDLER FOR NOT FOUND\n RETURN count_students;\n \n LOOP\n FETCH GROUP NEXT ROW;\n \n IF x THEN\n SET count_students = count_students+1;\n \n END IF;\n \n END LOOP;\n \nEND //\nDELIMITER ;\n \nA non-trivial example that cannot easily be rewritten using\nexisting functions:\n \nDELIMITER //\nCREATE AGGREGATE FUNCTION medi_int(x INT) RETURNS DOUBLE\nBEGIN\n DECLARE CONTINUE HANDLER FOR NOT FOUND\n BEGIN\n DECLARE res DOUBLE;\n \n DECLARE cnt INT DEFAULT (SELECT COUNT(*) FROM tt);\n DECLARE lim INT DEFAULT (cnt-1) DIV 2;\n \n IF cnt % 2 = 0 THEN\n SET res = (SELECT AVG(a) FROM (SELECT a FROM tt ORDER BY a\nLIMIT lim,2) ttt);\n ELSE\n SET res = (SELECT a FROM tt ORDER BY a LIMIT lim,1);\n END IF;\n \n DROP TEMPORARY TABLE tt;\n \n RETURN res;\n \n END;\n \n CREATE TEMPORARY TABLE tt (a INT);\n LOOP\n FETCH GROUP NEXT ROW;\n \n INSERT INTO tt VALUES (x);\n END LOOP;\n \nEND //\nDELIMITER ;\n \nSQL/PL Example\n \nThis uses the same marks table as created above.\n \nSET sql_mode=Oracle;\n \nDELIMITER //\n \nCREATE AGGREGATE FUNCTION aggregate_count(x INT) RETURN INT\nAS count_students INT DEFAULT 0;\n \nBEGIN\n LOOP\n FETCH GROUP NEXT ROW;\n \n IF x THEN\n SET count_students := count_students+1;\n \n END IF;\n \n END LOOP;\n \nEXCEPTION\n WHEN NO_DATA_FOUND THEN\n RETURN count_students;\n \nEND aggregate_count //\nDELIMITER ;\n \nSELECT aggregate_count(stud_id) FROM marks;\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/stored-aggregate-functions/','','https://mariadb.com/kb/en/library/stored-aggregate-functions/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (184,16,'AVG','Syntax\n------ \nAVG([DISTINCT] expr)\n \nDescription\n----------- \nReturns the average value of expr. The DISTINCT option can\nbe used to return the average of the distinct values of\nexpr. NULL values are ignored. It is an aggregate function,\nand so can be used with the GROUP BY clause.\n \nAVG() returns NULL if there were no matching rows.\n \nFrom MariaDB 10.2.0, AVG() can be used as a window function.\n \nExamples\n-------- \nCREATE TABLE sales (sales_value INT);\n \nINSERT INTO sales VALUES(10),(20),(20),(40);\n \nSELECT AVG(sales_value) FROM sales;\n \n+------------------+\n| AVG(sales_value) |\n+------------------+\n| 22.5000 |\n+------------------+\n \nSELECT AVG(DISTINCT(sales_value)) FROM sales;\n \n+----------------------------+\n| AVG(DISTINCT(sales_value)) |\n+----------------------------+\n| 23.3333 |\n+----------------------------+\n \nCommonly, AVG() is used with a GROUP BY clause:\n \nCREATE TABLE student (name CHAR(10), test CHAR(10), score\nTINYINT); \n \nINSERT INTO student VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87), (\'Tatiana\', \'Tuning\', 83);\n \nSELECT name, AVG(score) FROM student GROUP BY name;\n \n+---------+------------+\n| name | AVG(score) |\n+---------+------------+\n| Chun | 74.0000 |\n| Esben | 37.0000 |\n| Kaolin | 72.0000 |\n| Tatiana | 85.0000 |\n+---------+------------+\n \nBe careful to avoid this common mistake, not grouping\ncorrectly and returning mismatched data: \n \nSELECT name,test,AVG(score) FROM student;\n \n+------+------+------------+\n| name | test | MIN(score) |\n+------+------+------------+\n| Chun | SQL | 31 |\n+------+------+------------+\n \nAs a window function:\n \nCREATE TABLE student_test (name CHAR(10), test CHAR(10),\nscore TINYINT); \n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87), (\'Tatiana\', \'Tuning\', 83);\n \nSELECT name, test, score, AVG(score) OVER (PARTITION BY\ntest) \n AS average_by_test FROM student_test;\n \n+---------+--------+-------+-----------------+\n| name | test | score | average_by_test |\n+---------+--------+-------+-----------------+\n| Chun | SQL | 75 | 65.2500 |\n| Chun | Tuning | 73 | 68.7500 |\n| Esben | SQL | 43 | 65.2500 |\n| Esben | Tuning | 31 | 68.7500 |\n| Kaolin | SQL | 56 | 65.2500 |\n| Kaolin | Tuning | 88 | 68.7500 |\n| Tatiana | SQL | 87 | 65.2500 |\n| Tatiana | Tuning | 83 | 68.7500 |\n+---------+--------+-------+-----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/avg/','','https://mariadb.com/kb/en/library/avg/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (185,16,'BIT_AND','Syntax\n------ \nBIT_AND(expr)\n \nDescription\n----------- \nReturns the bitwise AND of all bits in expr. The calculation\nis performed with 64-bit (BIGINT) precision. It is an\naggregate function, and so can be used with the GROUP BY\nclause.\n \nFrom MariaDB 10.2.0, BIT_AND() can be used as a window\nfunction.\n \nExamples\n-------- \nCREATE TABLE vals (x INT);\n \nINSERT INTO vals VALUES(111),(110),(100);\n \nSELECT BIT_AND(x), BIT_OR(x), BIT_XOR(x) FROM vals;\n \n+------------+-----------+------------+\n| BIT_AND(x) | BIT_OR(x) | BIT_XOR(x) |\n+------------+-----------+------------+\n| 100 | 111 | 101 |\n+------------+-----------+------------+\n \nAs an aggregate function:\n \nCREATE TABLE vals2 (category VARCHAR(1), x INT);\n \nINSERT INTO vals2 VALUES\n (\'a\',111),(\'a\',110),(\'a\',100),\n (\'b\',\'000\'),(\'b\',001),(\'b\',011);\n \nSELECT category, BIT_AND(x), BIT_OR(x), BIT_XOR(x) \n FROM vals GROUP BY category;\n \n+----------+------------+-----------+------------+\n| category | BIT_AND(x) | BIT_OR(x) | BIT_XOR(x) |\n+----------+------------+-----------+------------+\n| a | 100 | 111 | 101 |\n| b | 0 | 11 | 10 |\n+----------+------------+-----------+------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/bit_and/','','https://mariadb.com/kb/en/library/bit_and/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (186,16,'BIT_OR','Syntax\n------ \nBIT_OR(expr)\n \nDescription\n----------- \nReturns the bitwise OR of all bits in expr. The calculation\nis performed with 64-bit (BIGINT) precision. It is an\naggregate function, and so can be used with the GROUP BY\nclause.\n \nFrom MariaDB 10.2.0, BIT_OR can be used as a window\nfunction.\n \nExamples\n-------- \nCREATE TABLE vals (x INT);\n \nINSERT INTO vals VALUES(111),(110),(100);\n \nSELECT BIT_AND(x), BIT_OR(x), BIT_XOR(x) FROM vals;\n \n+------------+-----------+------------+\n| BIT_AND(x) | BIT_OR(x) | BIT_XOR(x) |\n+------------+-----------+------------+\n| 100 | 111 | 101 |\n+------------+-----------+------------+\n \nAs an aggregate function:\n \nCREATE TABLE vals2 (category VARCHAR(1), x INT);\n \nINSERT INTO vals2 VALUES\n (\'a\',111),(\'a\',110),(\'a\',100),\n (\'b\',\'000\'),(\'b\',001),(\'b\',011);\n \nSELECT category, BIT_AND(x), BIT_OR(x), BIT_XOR(x) \n FROM vals GROUP BY category;\n \n+----------+------------+-----------+------------+\n| category | BIT_AND(x) | BIT_OR(x) | BIT_XOR(x) |\n+----------+------------+-----------+------------+\n| a | 100 | 111 | 101 |\n| b | 0 | 11 | 10 |\n+----------+------------+-----------+------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/bit_or/','','https://mariadb.com/kb/en/library/bit_or/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (187,16,'BIT_XOR','Syntax\n------ \nBIT_XOR(expr)\n \nDescription\n----------- \nReturns the bitwise XOR of all bits in expr. The calculation\nis performed with 64-bit (BIGINT) precision. It is an\naggregate function, and so can be used with the GROUP BY\nclause.\n \nFrom MariaDB 10.2.0, BIT_XOR() can be used as a window\nfunction.\n \nExamples\n-------- \nCREATE TABLE vals (x INT);\n \nINSERT INTO vals VALUES(111),(110),(100);\n \nSELECT BIT_AND(x), BIT_OR(x), BIT_XOR(x) FROM vals;\n \n+------------+-----------+------------+\n| BIT_AND(x) | BIT_OR(x) | BIT_XOR(x) |\n+------------+-----------+------------+\n| 100 | 111 | 101 |\n+------------+-----------+------------+\n \nAs an aggregate function:\n \nCREATE TABLE vals2 (category VARCHAR(1), x INT);\n \nINSERT INTO vals2 VALUES\n (\'a\',111),(\'a\',110),(\'a\',100),\n (\'b\',\'000\'),(\'b\',001),(\'b\',011);\n \nSELECT category, BIT_AND(x), BIT_OR(x), BIT_XOR(x) \n FROM vals GROUP BY category;\n \n+----------+------------+-----------+------------+\n| category | BIT_AND(x) | BIT_OR(x) | BIT_XOR(x) |\n+----------+------------+-----------+------------+\n| a | 100 | 111 | 101 |\n| b | 0 | 11 | 10 |\n+----------+------------+-----------+------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/bit_xor/','','https://mariadb.com/kb/en/library/bit_xor/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (188,16,'COUNT','Syntax\n------ \nCOUNT(expr)\n \nDescription\n----------- \nReturns a count of the number of non-NULL values of expr in\nthe rows retrieved by a SELECT statement. The result is a\nBIGINT value. It is an aggregate function, and so can be\nused with the GROUP BY clause.\n \nCOUNT(*) counts the total number of rows in a table.\n \nCOUNT() returns 0 if there were no matching rows.\n \nFrom MariaDB 10.2.0, COUNT() can be used as a window\nfunction.\n \nExamples\n-------- \nCREATE TABLE student (name CHAR(10), test CHAR(10), score\nTINYINT); \n \nINSERT INTO student VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87), (\'Tatiana\', \'Tuning\', 83);\n \nSELECT COUNT(*) FROM student;\n \n+----------+\n| COUNT(*) |\n+----------+\n| 8 |\n+----------+\n \nCOUNT(DISTINCT) example:\n \nSELECT COUNT(DISTINCT (name)) FROM student;\n \n+------------------------+\n| COUNT(DISTINCT (name)) |\n+------------------------+\n| 4 |\n+------------------------+\n \nAs a window function\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, COUNT(score) OVER (PARTITION BY\nname) \n AS tests_written FROM student_test;\n \n+---------+--------+-------+---------------+\n| name | test | score | tests_written |\n+---------+--------+-------+---------------+\n| Chun | SQL | 75 | 2 |\n| Chun | Tuning | 73 | 2 |\n| Esben | SQL | 43 | 2 |\n| Esben | Tuning | 31 | 2 |\n| Kaolin | SQL | 56 | 2 |\n| Kaolin | Tuning | 88 | 2 |\n| Tatiana | SQL | 87 | 1 |\n+---------+--------+-------+---------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/count/','','https://mariadb.com/kb/en/library/count/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (189,16,'GROUP_CONCAT','Syntax\n------ \nGROUP_CONCAT(expr)\n \nDescription\n----------- \nThis function returns a string result with the concatenated\nnon-NULL\nvalues from a group. It returns NULL if there are no\nnon-NULL values.\n \nThe maximum returned length in bytes is determined by the\ngroup_concat_max_len server system variable, which defaults\nto 1M (>= MariaDB 10.2.4) or 1K (\n\nURL: https://mariadb.com/kb/en/library/group_concat/','','https://mariadb.com/kb/en/library/group_concat/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (190,16,'MAX','Syntax\n------ \nMAX([DISTINCT] expr)\n \nDescription\n----------- \nReturns the largest, or maximum, value of expr. MAX() can\nalso take a string\nargument in which case it returns the maximum string value.\nThe DISTINCT\nkeyword can be used to find the maximum of the distinct\nvalues of expr,\nhowever, this produces the same result as omitting DISTINCT.\n \nNote that SET and ENUM fields are currently compared by\ntheir string value rather than their relative position in\nthe set, so MAX() may produce a different highest result\nthan ORDER BY DESC.\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, MAX() can be used as a window function.\n \nMAX() returns NULL if there were no matching rows.\n \nExamples\n-------- \nCREATE TABLE student (name CHAR(10), test CHAR(10), score\nTINYINT); \n \nINSERT INTO student VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87), (\'Tatiana\', \'Tuning\', 83);\n \nSELECT name, MAX(score) FROM student GROUP BY name;\n \n+---------+------------+\n| name | MAX(score) |\n+---------+------------+\n| Chun | 75 |\n| Esben | 43 |\n| Kaolin | 88 |\n| Tatiana | 87 |\n+---------+------------+\n \nMAX string:\n \nSELECT MAX(name) FROM student;\n \n+-----------+\n| MAX(name) |\n+-----------+\n| Tatiana |\n+-----------+\n \nBe careful to avoid this common mistake, not grouping\ncorrectly and returning mismatched data: \n \nSELECT name,test,MAX(SCORE) FROM student;\n \n+------+------+------------+\n| name | test | MAX(SCORE) |\n+------+------+------------+\n| Chun | SQL | 88 |\n+------+------+------------+\n \nDifference between ORDER BY DESC and MAX():\n \nCREATE TABLE student2(name CHAR(10),grade\nENUM(\'b\',\'c\',\'a\'));\n \nINSERT INTO student2\nVALUES(\'Chun\',\'b\'),(\'Esben\',\'c\'),(\'Kaolin\',\'a\');\n \nSELECT MAX(grade) FROM student2;\n \n+------------+\n| MAX(grade) |\n+------------+\n| c |\n+------------+\n \nSELECT grade FROM student2 ORDER BY grade DESC LIMIT 1;\n \n+-------+\n| grade |\n+-------+\n| a |\n+-------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, MAX(score) \n OVER (PARTITION BY name) AS highest_score FROM\nstudent_test;\n \n+---------+--------+-------+---------------+\n| name | test | score | highest_score |\n+---------+--------+-------+---------------+\n| Chun | SQL | 75 | 75 |\n| Chun | Tuning | 73 | 75 |\n| Esben | SQL | 43 | 43 |\n| Esben | Tuning | 31 | 43 |\n| Kaolin | SQL | 56 | 88 |\n| Kaolin | Tuning | 88 | 88 |\n| Tatiana | SQL | 87 | 87 |\n+---------+--------+-------+---------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/max/','','https://mariadb.com/kb/en/library/max/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (191,16,'MIN','Syntax\n------ \nMIN([DISTINCT] expr)\n \nDescription\n----------- \nReturns the minimum value of expr. MIN() may take a string\nargument, in which case it returns the minimum string value.\nThe DISTINCT\nkeyword can be used to find the minimum of the distinct\nvalues of expr,\nhowever, this produces the same result as omitting DISTINCT.\n \nNote that SET and ENUM fields are currently compared by\ntheir string value rather than their relative position in\nthe set, so MIN() may produce a different lowest result than\nORDER BY ASC.\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, MIN() can be used as a window function.\n \nMIN() returns NULL if there were no matching rows.\n \nExamples\n-------- \nCREATE TABLE student (name CHAR(10), test CHAR(10), score\nTINYINT); \n \nINSERT INTO student VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87), (\'Tatiana\', \'Tuning\', 83);\n \nSELECT name, MIN(score) FROM student GROUP BY name;\n \n+---------+------------+\n| name | MIN(score) |\n+---------+------------+\n| Chun | 73 |\n| Esben | 31 |\n| Kaolin | 56 |\n| Tatiana | 83 |\n+---------+------------+\n \nMIN() with a string:\n \nSELECT MIN(name) FROM student;\n \n+-----------+\n| MIN(name) |\n+-----------+\n| Chun |\n+-----------+\n \nBe careful to avoid this common mistake, not grouping\ncorrectly and returning mismatched data: \n \nSELECT name,test,MIN(score) FROM student;\n \n+------+------+------------+\n| name | test | MIN(score) |\n+------+------+------------+\n| Chun | SQL | 31 |\n+------+------+------------+\n \nDifference between ORDER BY ASC and MIN():\n \nCREATE TABLE student2(name CHAR(10),grade\nENUM(\'b\',\'c\',\'a\'));\n \nINSERT INTO student2\nVALUES(\'Chun\',\'b\'),(\'Esben\',\'c\'),(\'Kaolin\',\'a\');\n \nSELECT MIN(grade) FROM student2;\n \n+------------+\n| MIN(grade) |\n+------------+\n| a |\n+------------+\n \nSELECT grade FROM student2 ORDER BY grade ASC LIMIT 1;\n \n+-------+\n| grade |\n+-------+\n| b |\n+-------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, MIN(score) \n OVER (PARTITION BY name) AS lowest_score FROM student_test;\n \n+---------+--------+-------+--------------+\n| name | test | score | lowest_score |\n+---------+--------+-------+--------------+\n| Chun | SQL | 75 | 73 |\n| Chun | Tuning | 73 | 73 |\n| Esben | SQL | 43 | 31 |\n| Esben | Tuning | 31 | 31 |\n| Kaolin | SQL | 56 | 56 |\n| Kaolin | Tuning | 88 | 56 |\n| Tatiana | SQL | 87 | 87 |\n+---------+--------+-------+--------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/min/','','https://mariadb.com/kb/en/library/min/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (192,16,'STD','Syntax\n------ \nSTD(expr)\n \nDescription\n----------- \nReturns the population standard deviation of expr. This is\nan extension\nto standard SQL. The standard SQL function STDDEV_POP() can\nbe used instead. \n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, STD() can be used as a window function.\n \nThis function returns NULL if there were no matching rows.\n \nExamples\n-------- \nAs an aggregate function:\n \nCREATE OR REPLACE TABLE stats (category VARCHAR(2), x INT);\n \nINSERT INTO stats VALUES \n (\'a\',1),(\'a\',2),(\'a\',3),\n (\'b\',11),(\'b\',12),(\'b\',20),(\'b\',30),(\'b\',60);\n \nSELECT category, STDDEV_POP(x), STDDEV_SAMP(x), VAR_POP(x) \n FROM stats GROUP BY category;\n \n+----------+---------------+----------------+------------+\n| category | STDDEV_POP(x) | STDDEV_SAMP(x) | VAR_POP(x) |\n+----------+---------------+----------------+------------+\n| a | 0.8165 | 1.0000 | 0.6667 |\n| b | 18.0400 | 20.1693 | 325.4400 |\n+----------+---------------+----------------+------------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, STDDEV_POP(score) \n OVER (PARTITION BY test) AS stddev_results FROM\nstudent_test;\n \n+---------+--------+-------+----------------+\n| name | test | score | stddev_results |\n+---------+--------+-------+----------------+\n| Chun | SQL | 75 | 16.9466 |\n| Chun | Tuning | 73 | 24.1247 |\n| Esben | SQL | 43 | 16.9466 |\n| Esben | Tuning | 31 | 24.1247 |\n| Kaolin | SQL | 56 | 16.9466 |\n| Kaolin | Tuning | 88 | 24.1247 |\n| Tatiana | SQL | 87 | 16.9466 |\n+---------+--------+-------+----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/std/','','https://mariadb.com/kb/en/library/std/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (193,16,'STDDEV','Syntax\n------ \nSTDDEV(expr)\n \nDescription\n----------- \nReturns the population standard deviation of expr. This\nfunction is\nprovided for compatibility with Oracle. The standard SQL\nfunction\nSTDDEV_POP() can be used instead.\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, STDDEV() can be used as a window\nfunction.\n \nThis function returns NULL if there were no matching rows.\n \nExamples\n-------- \nAs an aggregate function:\n \nCREATE OR REPLACE TABLE stats (category VARCHAR(2), x INT);\n \nINSERT INTO stats VALUES \n (\'a\',1),(\'a\',2),(\'a\',3),\n (\'b\',11),(\'b\',12),(\'b\',20),(\'b\',30),(\'b\',60);\n \nSELECT category, STDDEV_POP(x), STDDEV_SAMP(x), VAR_POP(x) \n FROM stats GROUP BY category;\n \n+----------+---------------+----------------+------------+\n| category | STDDEV_POP(x) | STDDEV_SAMP(x) | VAR_POP(x) |\n+----------+---------------+----------------+------------+\n| a | 0.8165 | 1.0000 | 0.6667 |\n| b | 18.0400 | 20.1693 | 325.4400 |\n+----------+---------------+----------------+------------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, STDDEV_POP(score) \n OVER (PARTITION BY test) AS stddev_results FROM\nstudent_test;\n \n+---------+--------+-------+----------------+\n| name | test | score | stddev_results |\n+---------+--------+-------+----------------+\n| Chun | SQL | 75 | 16.9466 |\n| Chun | Tuning | 73 | 24.1247 |\n| Esben | SQL | 43 | 16.9466 |\n| Esben | Tuning | 31 | 24.1247 |\n| Kaolin | SQL | 56 | 16.9466 |\n| Kaolin | Tuning | 88 | 24.1247 |\n| Tatiana | SQL | 87 | 16.9466 |\n+---------+--------+-------+----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/stddev/','','https://mariadb.com/kb/en/library/stddev/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (194,16,'STDDEV_POP','Syntax\n------ \nSTDDEV_POP(expr)\n \nDescription\n----------- \nReturns the population standard deviation of expr (the\nsquare root of\nVAR_POP()). You can also use STD() or\nSTDDEV(), which are equivalent but not standard SQL.\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, STDDEV_POP() can be used as a window\nfunction.\n \nSTDDEV_POP() returns NULL if there were no matching rows.\n \nExamples\n-------- \nAs an aggregate function:\n \nCREATE OR REPLACE TABLE stats (category VARCHAR(2), x INT);\n \nINSERT INTO stats VALUES \n (\'a\',1),(\'a\',2),(\'a\',3),\n (\'b\',11),(\'b\',12),(\'b\',20),(\'b\',30),(\'b\',60);\n \nSELECT category, STDDEV_POP(x), STDDEV_SAMP(x), VAR_POP(x) \n FROM stats GROUP BY category;\n \n+----------+---------------+----------------+------------+\n| category | STDDEV_POP(x) | STDDEV_SAMP(x) | VAR_POP(x) |\n+----------+---------------+----------------+------------+\n| a | 0.8165 | 1.0000 | 0.6667 |\n| b | 18.0400 | 20.1693 | 325.4400 |\n+----------+---------------+----------------+------------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, STDDEV_POP(score) \n OVER (PARTITION BY test) AS stddev_results FROM\nstudent_test;\n \n+---------+--------+-------+----------------+\n| name | test | score | stddev_results |\n+---------+--------+-------+----------------+\n| Chun | SQL | 75 | 16.9466 |\n| Chun | Tuning | 73 | 24.1247 |\n| Esben | SQL | 43 | 16.9466 |\n| Esben | Tuning | 31 | 24.1247 |\n| Kaolin | SQL | 56 | 16.9466 |\n| Kaolin | Tuning | 88 | 24.1247 |\n| Tatiana | SQL | 87 | 16.9466 |\n+---------+--------+-------+----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/stddev_pop/','','https://mariadb.com/kb/en/library/stddev_pop/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (195,16,'STDDEV_SAMP','Syntax\n------ \nSTDDEV_SAMP(expr)\n \nDescription\n----------- \nReturns the sample standard deviation of expr (the square\nroot of VAR_SAMP()).\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, STDDEV_SAMP() can be used as a window\nfunction.\n \nSTDDEV_SAMP() returns NULL if there were no matching rows.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/stddev_samp/','','https://mariadb.com/kb/en/library/stddev_samp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (196,16,'SUM','Syntax\n------ \nSUM([DISTINCT] expr)\n \nDescription\n----------- \nReturns the sum of expr. If the return set has no rows,\nSUM() returns\nNULL. The DISTINCT keyword can be used to sum only the\ndistinct values\nof expr.\n \nFrom MariaDB 10.2.0, SUM() can be used as a window function,\nalthough not with the DISTINCT specifier.\n \nExamples\n-------- \nCREATE TABLE sales (sales_value INT);\nINSERT INTO sales VALUES(10),(20),(20),(40);\n \nSELECT SUM(sales_value) FROM sales;\n \n+------------------+\n| SUM(sales_value) |\n+------------------+\n| 90 |\n+------------------+\n \nSELECT SUM(DISTINCT(sales_value)) FROM sales;\n \n+----------------------------+\n| SUM(DISTINCT(sales_value)) |\n+----------------------------+\n| 70 |\n+----------------------------+\n \nCommonly, SUM is used with a GROUP BY clause:\n \nCREATE TABLE sales (name CHAR(10), month CHAR(10), units\nINT);\n \nINSERT INTO sales VALUES \n (\'Chun\', \'Jan\', 75), (\'Chun\', \'Feb\', 73),\n (\'Esben\', \'Jan\', 43), (\'Esben\', \'Feb\', 31),\n (\'Kaolin\', \'Jan\', 56), (\'Kaolin\', \'Feb\', 88),\n (\'Tatiana\', \'Jan\', 87), (\'Tatiana\', \'Feb\', 83);\n \nSELECT name, SUM(units) FROM sales GROUP BY name;\n \n+---------+------------+\n| name | SUM(units) |\n+---------+------------+\n| Chun | 148 |\n| Esben | 74 |\n| Kaolin | 144 |\n| Tatiana | 170 |\n+---------+------------+\n \nThe GROUP BY clause is required when using an aggregate\nfunction along with regular column data, otherwise the\nresult will be a mismatch, as in the following common type\nof mistake:\n \nSELECT name,SUM(units) FROM sales\n;\n+------+------------+\n| name | SUM(units) |\n+------+------------+\n| Chun | 536 |\n+------+------------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, SUM(score) OVER (PARTITION BY\nname) AS total_score FROM student_test;\n \n+---------+--------+-------+-------------+\n| name | test | score | total_score |\n+---------+--------+-------+-------------+\n| Chun | SQL | 75 | 148 |\n| Chun | Tuning | 73 | 148 |\n| Esben | SQL | 43 | 74 |\n| Esben | Tuning | 31 | 74 |\n| Kaolin | SQL | 56 | 144 |\n| Kaolin | Tuning | 88 | 144 |\n| Tatiana | SQL | 87 | 87 |\n+---------+--------+-------+-------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/sum/','','https://mariadb.com/kb/en/library/sum/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (197,16,'VARIANCE','Syntax\n------ \nVARIANCE(expr) \n \nDescription\n----------- \nReturns the population standard variance of expr. This is an\nextension to\nstandard SQL. The standard SQL function VAR_POP() can be\nused\ninstead.\n \nVariance is calculated by\nworking out the mean for the set\nfor each number, subtracting the mean and squaring the\nresult\ncalculate the average of the resulting differences\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, VARIANCE() can be used as a window\nfunction.\n \nVARIANCE() returns NULL if there were no matching rows.\n \nExamples\n-------- \nCREATE TABLE v(i tinyint);\n \nINSERT INTO v VALUES(101),(99);\n \nSELECT VARIANCE(i) FROM v;\n \n+-------------+\n| VARIANCE(i) |\n+-------------+\n| 1.0000 |\n+-------------+\n \nINSERT INTO v VALUES(120),(80);\n \nSELECT VARIANCE(i) FROM v;\n \n+-------------+\n| VARIANCE(i) |\n+-------------+\n| 200.5000 |\n+-------------+\n \nAs an aggregate function:\n \nCREATE OR REPLACE TABLE stats (category VARCHAR(2), x INT);\n \nINSERT INTO stats VALUES \n (\'a\',1),(\'a\',2),(\'a\',3),\n (\'b\',11),(\'b\',12),(\'b\',20),(\'b\',30),(\'b\',60);\n \nSELECT category, STDDEV_POP(x), STDDEV_SAMP(x), VAR_POP(x) \n FROM stats GROUP BY category;\n \n+----------+---------------+----------------+------------+\n| category | STDDEV_POP(x) | STDDEV_SAMP(x) | VAR_POP(x) |\n+----------+---------------+----------------+------------+\n| a | 0.8165 | 1.0000 | 0.6667 |\n| b | 18.0400 | 20.1693 | 325.4400 |\n+----------+---------------+----------------+------------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, VAR_POP(score) \n OVER (PARTITION BY test) AS variance_results FROM\nstudent_test;\n \n+---------+--------+-------+------------------+\n| name | test | score | variance_results |\n+---------+--------+-------+------------------+\n| Chun | SQL | 75 | 287.1875 |\n| Chun | Tuning | 73 | 582.0000 |\n| Esben | SQL | 43 | 287.1875 |\n| Esben | Tuning | 31 | 582.0000 |\n| Kaolin | SQL | 56 | 287.1875 |\n| Kaolin | Tuning | 88 | 582.0000 |\n| Tatiana | SQL | 87 | 287.1875 |\n+---------+--------+-------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/variance/','','https://mariadb.com/kb/en/library/variance/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (198,16,'VAR_POP','Syntax\n------ \nVAR_POP(expr)\n \nDescription\n----------- \nReturns the population standard variance of expr. It\nconsiders rows as\nthe whole population, not as a sample, so it has the number\nof rows as\nthe denominator. You can also use VARIANCE(), which is\nequivalent but\nis not standard SQL.\n \nVariance is calculated by\nworking out the mean for the set\nfor each number, subtracting the mean and squaring the\nresult\ncalculate the average of the resulting differences\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, VAR_POP() can be used as a window\nfunction.\n \nVAR_POP() returns NULL if there were no matching rows.\n \nExamples\n-------- \nCREATE TABLE v(i tinyint);\n \nINSERT INTO v VALUES(101),(99);\n \nSELECT VAR_POP(i) FROM v;\n \n+------------+\n| VAR_POP(i) |\n+------------+\n| 1.0000 |\n+------------+\n \nINSERT INTO v VALUES(120),(80);\n \nSELECT VAR_POP(i) FROM v;\n \n+------------+\n| VAR_POP(i) |\n+------------+\n| 200.5000 |\n+------------+\n \nAs an aggregate function:\n \nCREATE OR REPLACE TABLE stats (category VARCHAR(2), x INT);\n \nINSERT INTO stats VALUES \n (\'a\',1),(\'a\',2),(\'a\',3),\n (\'b\',11),(\'b\',12),(\'b\',20),(\'b\',30),(\'b\',60);\n \nSELECT category, STDDEV_POP(x), STDDEV_SAMP(x), VAR_POP(x) \n FROM stats GROUP BY category;\n \n+----------+---------------+----------------+------------+\n| category | STDDEV_POP(x) | STDDEV_SAMP(x) | VAR_POP(x) |\n+----------+---------------+----------------+------------+\n| a | 0.8165 | 1.0000 | 0.6667 |\n| b | 18.0400 | 20.1693 | 325.4400 |\n+----------+---------------+----------------+------------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, VAR_POP(score) \n OVER (PARTITION BY test) AS variance_results FROM\nstudent_test;\n \n+---------+--------+-------+------------------+\n| name | test | score | variance_results |\n+---------+--------+-------+------------------+\n| Chun | SQL | 75 | 287.1875 |\n| Chun | Tuning | 73 | 582.0000 |\n| Esben | SQL | 43 | 287.1875 |\n| Esben | Tuning | 31 | 582.0000 |\n| Kaolin | SQL | 56 | 287.1875 |\n| Kaolin | Tuning | 88 | 582.0000 |\n| Tatiana | SQL | 87 | 287.1875 |\n+---------+--------+-------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/var_pop/','','https://mariadb.com/kb/en/library/var_pop/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (199,16,'VAR_SAMP','Syntax\n------ \nVAR_SAMP(expr)\n \nDescription\n----------- \nReturns the sample variance of expr. That is, the\ndenominator is the number of rows minus one.\n \nIt is an aggregate function, and so can be used with the\nGROUP BY clause.\n \nFrom MariaDB 10.2.2, VAR_SAMP() can be used as a window\nfunction.\n \nVAR_SAMP() returns NULL if there were no matching rows.\n \nExamples\n-------- \nAs an aggregate function:\n \nCREATE OR REPLACE TABLE stats (category VARCHAR(2), x INT);\n \nINSERT INTO stats VALUES \n (\'a\',1),(\'a\',2),(\'a\',3),\n (\'b\',11),(\'b\',12),(\'b\',20),(\'b\',30),(\'b\',60);\n \nSELECT category, STDDEV_POP(x), STDDEV_SAMP(x), VAR_POP(x) \n FROM stats GROUP BY category;\n \n+----------+---------------+----------------+------------+\n| category | STDDEV_POP(x) | STDDEV_SAMP(x) | VAR_POP(x) |\n+----------+---------------+----------------+------------+\n| a | 0.8165 | 1.0000 | 0.6667 |\n| b | 18.0400 | 20.1693 | 325.4400 |\n+----------+---------------+----------------+------------+\n \nAs a window function:\n \nCREATE OR REPLACE TABLE student_test (name CHAR(10), test\nCHAR(10), score TINYINT);\n \nINSERT INTO student_test VALUES \n (\'Chun\', \'SQL\', 75), (\'Chun\', \'Tuning\', 73), \n (\'Esben\', \'SQL\', 43), (\'Esben\', \'Tuning\', 31), \n (\'Kaolin\', \'SQL\', 56), (\'Kaolin\', \'Tuning\', 88), \n (\'Tatiana\', \'SQL\', 87);\n \nSELECT name, test, score, VAR_SAMP(score) \n OVER (PARTITION BY test) AS variance_results FROM\nstudent_test;\n \n+---------+--------+-------+------------------+\n| name | test | score | variance_results |\n+---------+--------+-------+------------------+\n| Chun | SQL | 75 | 382.9167 |\n| Chun | Tuning | 73 | 873.0000 |\n| Esben | SQL | 43 | 382.9167 |\n| Esben | Tuning | 31 | 873.0000 |\n| Kaolin | SQL | 56 | 382.9167 |\n| Kaolin | Tuning | 88 | 873.0000 |\n| Tatiana | SQL | 87 | 382.9167 |\n+---------+--------+-------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/var_samp/','','https://mariadb.com/kb/en/library/var_samp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (200,17,'BENCHMARK','Syntax\n------ \nBENCHMARK(count,expr)\n \nDescription\n----------- \nThe BENCHMARK() function executes the expression expr\nrepeatedly count\ntimes. It may be used to time how quickly MariaDB processes\nthe\nexpression. The result value is always 0. The intended use\nis from\nwithin the mysql client, which reports query execution\ntimes.\n \nExamples\n-------- \nSELECT BENCHMARK(1000000,ENCODE(\'hello\',\'goodbye\'));\n+----------------------------------------------+\n| BENCHMARK(1000000,ENCODE(\'hello\',\'goodbye\')) |\n+----------------------------------------------+\n| 0 |\n+----------------------------------------------+\n1 row in set (0.21 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/benchmark/','','https://mariadb.com/kb/en/library/benchmark/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (201,17,'BINLOG_GTID_POS','From version 10.0.2, MariaDB supports global transaction IDs\nfor replication.\n \nSyntax\n------ \nBINLOG_GTID_POS(binlog_filename,binlog_offset)\n \nDescription\n----------- \nThe BINLOG_GTID_POS() function takes as input an old-style\nbinary log position in the form of a file name and a file\noffset. It looks up the position in the current binlog, and\nreturns a string representation of the corresponding GTID\nposition. If the position is not found in the current\nbinlog, NULL is returned.\n \nExamples\n-------- \nSELECT BINLOG_GTID_POS(\"master-bin.000001\", 600);\n \n\n\nURL: https://mariadb.com/kb/en/library/binlog_gtid_pos/','','https://mariadb.com/kb/en/library/binlog_gtid_pos/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (202,17,'CHARSET','Syntax\n------ \nCHARSET(str)\n \nDescription\n----------- \nReturns the character set of the string argument. If str is\nnot a string, it is considered as a binary string (so the\nfunction returns \'binary\'). This applies to NULL, too. The\nreturn value is a string in the utf8 character set.\n \nExamples\n-------- \nSELECT CHARSET(\'abc\');\n+----------------+\n| CHARSET(\'abc\') |\n+----------------+\n| latin1 |\n+----------------+\n \nSELECT CHARSET(CONVERT(\'abc\' USING utf8));\n+------------------------------------+\n| CHARSET(CONVERT(\'abc\' USING utf8)) |\n+------------------------------------+\n| utf8 |\n+------------------------------------+\n \nSELECT CHARSET(USER());\n+-----------------+\n| CHARSET(USER()) |\n+-----------------+\n| utf8 |\n+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/charset/','','https://mariadb.com/kb/en/library/charset/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (203,17,'COERCIBILITY','Syntax\n------ \nCOERCIBILITY(str)\n \nDescription\n----------- \nReturns the collation coercibility value of the string\nargument. Coercibility defines what will be converted to\nwhat in case of collation conflict, with an expression with\nhigher coercibility being converted to the collation of an\nexpression with lower coercibility.\n \nCoercibility | Description | Example | \n \n0 | Explicit | Value using a COLLATE clause | \n \n1 | No collation | Concatenated strings using different\ncollations | \n \n2 | Implicit | Column value | \n \n3 | Constant | USER() return value | \n \n4 | Coercible | Literal string | \n \n5 | Ignorable | NULL or derived from NULL | \n \nExamples\n-------- \nSELECT COERCIBILITY(\'abc\' COLLATE latin1_swedish_ci);\n+-----------------------------------------------+\n| COERCIBILITY(\'abc\' COLLATE latin1_swedish_ci) |\n+-----------------------------------------------+\n| 0 |\n+-----------------------------------------------+\n \nSELECT COERCIBILITY(USER());\n+----------------------+\n| COERCIBILITY(USER()) |\n+----------------------+\n| 3 |\n+----------------------+\n \nSELECT COERCIBILITY(\'abc\');\n+---------------------+\n| COERCIBILITY(\'abc\') |\n+---------------------+\n| 4 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/coercibility/','','https://mariadb.com/kb/en/library/coercibility/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (204,17,'COLLATION','Syntax\n------ \nCOLLATION(str)\n \nDescription\n----------- \nReturns the collation of the string argument. If str is not\na string, it is considered as a binary string (so the\nfunction returns \'binary\'). This applies to NULL, too. The\nreturn value is a string in the utf8 character set.\n \nSee Character Sets and Collations.\n \nExamples\n-------- \nSELECT COLLATION(\'abc\');\n+-------------------+\n| COLLATION(\'abc\') |\n+-------------------+\n| latin1_swedish_ci |\n+-------------------+\n \nSELECT COLLATION(_utf8\'abc\');\n+-----------------------+\n| COLLATION(_utf8\'abc\') |\n+-----------------------+\n| utf8_general_ci |\n+-----------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/collation/','','https://mariadb.com/kb/en/library/collation/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (205,17,'CONNECTION_ID','Syntax\n------ \nCONNECTION_ID()\n \nDescription\n----------- \nReturns the connection ID (thread ID) for the connection.\nEvery\nthread (including events) has an ID that is unique among the\nset of currently\nconnected clients.\n \nUntil MariaDB 10.3.1, returns MYSQL_TYPE_LONGLONG, or\nbigint(10), in all cases. From MariaDB 10.3.1, returns\nMYSQL_TYPE_LONG, or int(10), when the result would fit\nwithin 32-bits.\n \nExamples\n-------- \nSELECT CONNECTION_ID();\n+-----------------+\n| CONNECTION_ID() |\n+-----------------+\n| 3 |\n+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/connection_id/','','https://mariadb.com/kb/en/library/connection_id/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (206,17,'CURRENT_ROLE','Roles were introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nCURRENT_ROLE, CURRENT_ROLE()\n \nDescription\n----------- \nReturns the current role name. This determines your access\nprivileges. The return value is a string in the\nutf8 character set.\n \nIf there is no current role, NULL is returned.\n \nThe output of SELECT CURRENT_ROLE is equivalent to the\ncontents of the ENABLED_ROLES Information Schema table.\n \nUSER() returns the combination of user and host used to\nlogin. CURRENT_USER() returns the account used to determine\ncurrent connection\'s privileges.\n \nExamples\n-------- \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| NULL |\n+--------------+\n \nSET ROLE staff;\n \nSELECT CURRENT_ROLE;\n \n+--------------+\n| CURRENT_ROLE |\n+--------------+\n| staff |\n+--------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/current_role/','','https://mariadb.com/kb/en/library/current_role/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (207,17,'CURRENT_USER','Syntax\n------ \nCURRENT_USER, CURRENT_USER()\n \nDescription\n----------- \nReturns the user name and host name combination for the\nMariaDB account\nthat the server used to authenticate the current client.\nThis account\ndetermines your access privileges. The return value is a\nstring in the\nutf8 character set.\n \nThe value of CURRENT_USER() can differ from the value of\nUSER(). CURRENT_ROLE() returns the current active role.\n \nExamples\n-------- \nshell> mysql --user=\"anonymous\"\n \nMariaDB [(none)]> select user(),current_user();\n+---------------------+----------------+\n| user() | current_user() |\n+---------------------+----------------+\n| anonymous@localhost | @localhost |\n+---------------------+----------------+\n \nWhen calling CURRENT_USER() in a stored procedure, it\nreturns the owner of the stored procedure, as defined with\nDEFINER.\n \n\n\nURL: https://mariadb.com/kb/en/library/current_user/','','https://mariadb.com/kb/en/library/current_user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (208,17,'DATABASE','Syntax\n------ \nDATABASE()\n \nDescription\n----------- \nReturns the default (current) database name as a string in\nthe utf8 character set. If there is no default database,\nDATABASE() returns NULL. Within a stored routine, the\ndefault database is the database that the routine is\nassociated with, which is not necessarily the same as the\ndatabase that is the default in the calling context.\n \nSCHEMA() is a synonym for DATABASE().\n \nTo select a default database, the USE statement can be run.\nAnother way to set the default database is specifying its\nname at mysql command line client startup.\n \nExamples\n-------- \nSELECT DATABASE();\n+------------+\n| DATABASE() |\n+------------+\n| NULL |\n+------------+\n \nUSE test;\n \nDatabase changed\n \nSELECT DATABASE();\n+------------+\n| DATABASE() |\n+------------+\n| test |\n+------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/database/','','https://mariadb.com/kb/en/library/database/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (209,17,'DECODE_HISTOGRAM','DECODE_HISTOGRAM() was introduced in MariaDB 10.0.2\n \nSyntax\n------ \nDECODE_HISTOGRAM(hist_type,histogram)\n \nNote: Before MariaDB 10.0.10 the arguments were reversed.\n \nDescription\n----------- \nReturns a string of comma separated numeric values\ncorresponding to a probability distribution represented by\nthe histogram of type hist_type (SINGLE_PREC_HB or\nDOUBLE_PREC_HB). The hist_type and histogram would be\ncommonly used from the mysql.column_stats table.\n \nSee Histogram Based Statistics for details.\n \nExamples\n-------- \nCREATE TABLE origin (\n i INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,\n v INT UNSIGNED NOT NULL\n);\n \nINSERT INTO origin(v) VALUES \n (1),(2),(3),(4),(5),(10),(20),\n (30),(40),(50),(60),(70),(80),\n (90),(100),(200),(400),(800);\n \nSET histogram_size=10,histogram_type=SINGLE_PREC_HB;\n \nANALYZE TABLE origin PERSISTENT FOR ALL;\n \n+-------------+---------+----------+-----------------------------------------+\n| Table | Op | Msg_type | Msg_text |\n+-------------+---------+----------+-----------------------------------------+\n| test.origin | analyze | status | Engine-independent\nstatistics collected |\n| test.origin | analyze | status | OK |\n+-------------+---------+----------+-----------------------------------------+\n \nSELECT db_name,table_name,column_name,hist_type,\n hex(histogram),decode_histogram(hist_type,histogram) \n FROM mysql.column_stats WHERE db_name=\'test\' and\ntable_name=\'origin\';\n \n+---------+------------+-------------+----------------+----------------------+-------------------------------------------------------------------+\n| db_name | table_name | column_name | hist_type |\nhex(histogram) | decode_histogram(hist_type,histogram) |\n+---------+------------+-------------+----------------+----------------------+-------------------------------------------------------------------+\n| test | origin | i | SINGLE_PREC_HB | 0F2D3C5A7887A5C3D2F0\n|\n0.059,0.118,0.059,0.118,0.118,0.059,0.118,0.118,0.059,0.118,0.059\n|\n| test | origin | v | SINGLE_PREC_HB | 000001060C0F161C1F7F\n|\n0.000,0.000,0.004,0.020,0.024,0.012,0.027,0.024,0.012,0.376,0.502\n|\n+---------+------------+-------------+----------------+----------------------+-------------------------------------------------------------------+\n \nSET histogram_size=20,histogram_type=DOUBLE_PREC_HB;\n \nANALYZE TABLE origin PERSISTENT FOR ALL;\n \n+-------------+---------+----------+-----------------------------------------+\n| Table | Op | Msg_type | Msg_text |\n+-------------+---------+----------+-----------------------------------------+\n| test.origin | analyze | status | Engine-independent\nstatistics collected |\n| test.origin | analyze | status | OK |\n+-------------+---------+----------+-----------------------------------------+\n \nSELECT db_name,table_name,column_name,\n hist_type,hex(histogram),decode_histogram(hist_type,histogram)\n\n FROM mysql.column_stats WHERE db_name=\'test\' and\ntable_name=\'origin\';\n \n+---------+------------+-------------+----------------+------------------------------------------+-----------------------------------------------------------------------------------------+\n| db_name | table_name | column_name | hist_type |\nhex(histogram) | decode_histogram(hist_type,histogram) |\n+---------+------------+-------------+----------------+------------------------------------------+-----------------------------------------------------------------------------------------+\n| test | origin | i | DOUBLE_PREC_HB |\n0F0F2D2D3C3C5A5A78788787A5A5C3C3D2D2F0F0 |\n0.05882,0.11765,0.05882,0.11765,0.11765,0.05882,0.11765,0.11765,0.05882,0.11765,0.05882\n|\n| test | origin | v | DOUBLE_PREC_HB |\n5200F600480116067E0CB30F1B16831CB81FD67F |\n0.00125,0.00250,0.00125,0.01877,0.02502,0.01253,0.02502,0.02502,0.01253,0.37546,0.50063\n|\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/decode_histogram/','','https://mariadb.com/kb/en/library/decode_histogram/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (210,17,'DEFAULT','Syntax\n------ \nDEFAULT(col_name)\n \nDescription\n----------- \nReturns the default value for a table column. If the column\nhas no default value, NULL is returned.\nFor integer columns using AUTO_INCREMENT, 0 is returned.\n \nWhen using DEFAULT as a value to set in an INSERT or UPDATE\nstatement, you can use the bare keyword DEFAULT without the\nparentheses and argument to\nrefer to the column in context. You can only use DEFAULT as\na bare keyword if you are using it\nalone without a surrounding expression or function.\n \nExamples\n-------- \nSelect only non-default values for a column:\n \nSELECT i FROM t WHERE i != DEFAULT(i);\n \nUpdate values to be one greater than the default value:\n \nUPDATE t SET i = DEFAULT(i)+1 WHERE i \n\nURL: https://mariadb.com/kb/en/library/default/','','https://mariadb.com/kb/en/library/default/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (211,17,'FOUND_ROWS','Syntax\n------ \nFOUND_ROWS()\n \nDescription\n----------- \nA SELECT statement may include a LIMIT clause to restrict\nthe number\nof rows the server returns to the client. In some cases, it\nis\ndesirable to know how many rows the statement would have\nreturned\nwithout the LIMIT, but without running the statement again.\nTo obtain\nthis row count, include a SQL_CALC_FOUND_ROWS option in the\nSELECT\nstatement, and then invoke FOUND_ROWS() afterwards.\n \nYou can also use FOUND_ROWS() to obtain the number of rows\nreturned by a SELECT which does not contain a LIMIT clause.\nIn this case you don\'t need to use the SQL_CALC_FOUND_ROWS\noption. This can be useful for example in a stored\nprocedure.\n \nAlso, this function works with some other statements which\nreturn a resultset, including SHOW, DESC and HELP. For\nDELETE ... RETURNING you should use ROW_COUNT(). It also\nworks as a prepared statement, or after executing a prepared\nstatement.\n \nStatements which don\'t return any results don\'t affect\nFOUND_ROWS() - the previous value will still be returned.\n \nWarning: When used after a CALL statement, this function\nreturns the number of rows selected by the last query in the\nprocedure, not by the whole procedure.\n \nStatements using the FOUND_ROWS() function are not safe for\nreplication.\n \nExamples\n-------- \nSHOW ENGINES;\n \n+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+\n| Engine | Support | Comment | Transactions | XA |\nSavepoints |\n+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+\n| InnoDB | DEFAULT | Supports transactions, row-level\nlocking, and foreign keys | YES | YES | YES |\n...\n| SPHINX | YES | Sphinx storage engine | NO | NO | NO |\n+--------------------+---------+----------------------------------------------------------------+--------------+------+------------+\n11 rows in set (0.01 sec)\n \nSELECT FOUND_ROWS();\n+--------------+\n| FOUND_ROWS() |\n+--------------+\n| 11 |\n+--------------+\n \nSELECT SQL_CALC_FOUND_ROWS * FROM tbl_name WHERE id > 100\nLIMIT 10;\n \nSELECT FOUND_ROWS();\n+--------------+\n| FOUND_ROWS() |\n+--------------+\n| 23 |\n+--------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/found_rows/','','https://mariadb.com/kb/en/library/found_rows/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (212,17,'LAST_INSERT_ID','Syntax\n------ \nLAST_INSERT_ID(), LAST_INSERT_ID(expr)\n \nDescription\n----------- \nLAST_INSERT_ID() (no arguments) returns\nthe first automatically generated value successfully\ninserted for an\nAUTO_INCREMENT column as a result of the most recently\nexecuted INSERT\nstatement. The value of LAST_INSERT_ID() remains unchanged\nif no rows\nare successfully inserted.\n \nIf one gives an argument to LAST_INSERT_ID(), then it will\nreturn the value of the expression and\nthe next call to LAST_INSERT_ID() will return the same\nvalue. The value will also be sent to the client\nand can be accessed by the mysql_insert_id function.\n \nFor example, after inserting a row that generates an\nAUTO_INCREMENT\nvalue, you can get the value like this:\n \nSELECT LAST_INSERT_ID();\n+------------------+\n| LAST_INSERT_ID() |\n+------------------+\n| 9 |\n+------------------+\n \nYou can also use LAST_INSERT_ID() to delete the last\ninserted row:\n \nDELETE FROM product WHERE id = LAST_INSERT_ID();\n \nIf no rows were successfully inserted, LAST_INSERT_ID()\nreturns 0.\n \nThe value of LAST_INSERT_ID() will be consistent across all\nversions\nif all rows in the INSERT or UPDATE statement were\nsuccessful.\n \nThe currently executing statement does not affect the value\nof\nLAST_INSERT_ID(). Suppose that you generate an\nAUTO_INCREMENT value\nwith one statement, and then refer to LAST_INSERT_ID() in a\nmultiple-row INSERT statement that inserts rows into a table\nwith its\nown AUTO_INCREMENT column. The value of LAST_INSERT_ID()\nwill remain\nstable in the second statement; its value for the second and\nlater\nrows is not affected by the earlier row insertions.\n(However, if you\nmix references to LAST_INSERT_ID() and LAST_INSERT_ID(expr),\nthe\neffect is undefined.)\n \nIf the previous statement returned an error, the value of\nLAST_INSERT_ID() is undefined. For transactional tables, if\nthe\nstatement is rolled back due to an error, the value of\nLAST_INSERT_ID() is left undefined. For manual ROLLBACK, the\nvalue of\nLAST_INSERT_ID() is not restored to that before the\ntransaction; it\nremains as it was at the point of the ROLLBACK.\n \nWithin the body of a stored routine (procedure or function)\nor a\ntrigger, the value of LAST_INSERT_ID() changes the same way\nas for\nstatements executed outside the body of these kinds of\nobjects. The\neffect of a stored routine or trigger upon the value of\nLAST_INSERT_ID() that is seen by following statements\ndepends on the\nkind of routine:\nIf a stored procedure executes statements that change the\nvalue of LAST_INSERT_ID(), the new value will be seen by\nstatements that follow the procedure call.\n \nFor stored functions and triggers that change the value, the\nvalue is restored when the function or trigger ends, so\nfollowing statements will not see a changed value.\n \nExamples\n-------- \nCREATE TABLE t (\n id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY, \n f VARCHAR(1)) \nENGINE = InnoDB;\n \nINSERT INTO t(f) VALUES(\'a\');\n \nSELECT LAST_INSERT_ID();\n+------------------+\n| LAST_INSERT_ID() |\n+------------------+\n| 1 |\n+------------------+\n \nINSERT INTO t(f) VALUES(\'b\');\n \nINSERT INTO t(f) VALUES(\'c\');\n \nSELECT LAST_INSERT_ID();\n+------------------+\n| LAST_INSERT_ID() |\n+------------------+\n| 3 |\n+------------------+\n \nINSERT INTO t(f) VALUES(\'d\'),(\'e\');\n \nSELECT LAST_INSERT_ID();\n+------------------+\n| LAST_INSERT_ID() |\n+------------------+\n| 4 |\n+------------------+\n \nSELECT * FROM t;\n \n+----+------+\n| id | f |\n+----+------+\n| 1 | a |\n| 2 | b |\n| 3 | c |\n| 4 | d |\n| 5 | e |\n+----+------+\n \nSELECT LAST_INSERT_ID(12);\n+--------------------+\n| LAST_INSERT_ID(12) |\n+--------------------+\n| 12 |\n+--------------------+\n \nSELECT LAST_INSERT_ID();\n+------------------+\n| LAST_INSERT_ID() |\n+------------------+\n| 12 |\n+------------------+\n \nINSERT INTO t(f) VALUES(\'f\');\n \nSELECT LAST_INSERT_ID();\n+------------------+\n| LAST_INSERT_ID() |\n+------------------+\n| 6 |\n+------------------+\n \nSELECT * FROM t;\n \n+----+------+\n| id | f |\n+----+------+\n| 1 | a |\n| 2 | b |\n| 3 | c |\n| 4 | d |\n| 5 | e |\n| 6 | f |\n+----+------+\n \nSELECT LAST_INSERT_ID(12);\n+--------------------+\n| LAST_INSERT_ID(12) |\n+--------------------+\n| 12 |\n+--------------------+\n \nINSERT INTO t(f) VALUES(\'g\');\n \nSELECT * FROM t;\n \n+----+------+\n| id | f |\n+----+------+\n| 1 | a |\n| 2 | b |\n| 3 | c |\n| 4 | d |\n| 5 | e |\n| 6 | f |\n| 7 | g |\n+----+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/last_insert_id/','','https://mariadb.com/kb/en/library/last_insert_id/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (213,17,'LAST_VALUE','Syntax\n------ \nLAST_VALUE(expr,[expr,...])\n \nLAST_VALUE(expr) OVER (\n [ PARTITION BY partition_expression ]\n [ ORDER BY order_list ]\n) \n \nDescription\n----------- \nLAST_VALUE() evaluates all expressions and returns the last.\n \nThis is useful together with setting user variables to a\nvalue with @var:=expr, for example when you want to get data\nof rows updated/deleted without having to do two queries\nagainst the table.\n \nSince MariaDB 10.2.2, LAST_VALUE can be used as a window\nfunction.\n \nReturns NULL if no last value exists.\n \nExamples\n-------- \nCREATE TABLE t1 (a int, b int);\nINSERT INTO t1 VALUES(1,10),(2,20);\nDELETE FROM t1 WHERE a=1 AND last_value(@a:=a,@b:=b,1);\nSELECT @a,@b;\n \n+------+------+\n| @a | @b |\n+------+------+\n| 1 | 10 |\n+------+------+\n \nAs a window function:\n \nCREATE TABLE t1 (\n pk int primary key,\n a int,\n b int,\n c char(10),\n d decimal(10, 3),\n e real\n);\n \nINSERT INTO t1 VALUES\n( 1, 0, 1, \'one\', 0.1, 0.001),\n( 2, 0, 2, \'two\', 0.2, 0.002),\n( 3, 0, 3, \'three\', 0.3, 0.003),\n( 4, 1, 2, \'three\', 0.4, 0.004),\n( 5, 1, 1, \'two\', 0.5, 0.005),\n( 6, 1, 1, \'one\', 0.6, 0.006),\n( 7, 2, NULL, \'n_one\', 0.5, 0.007),\n( 8, 2, 1, \'n_two\', NULL, 0.008),\n( 9, 2, 2, NULL, 0.7, 0.009),\n(10, 2, 0, \'n_four\', 0.8, 0.010),\n(11, 2, 10, NULL, 0.9, NULL);\n \nSELECT pk, FIRST_VALUE(pk) OVER (ORDER BY pk) AS first_asc,\n LAST_VALUE(pk) OVER (ORDER BY pk) AS last_asc,\n FIRST_VALUE(pk) OVER (ORDER BY pk DESC) AS first_desc,\n LAST_VALUE(pk) OVER (ORDER BY pk DESC) AS last_desc\nFROM t1\nORDER BY pk DESC;\n \n+----+-----------+----------+------------+-----------+\n| pk | first_asc | last_asc | first_desc | last_desc |\n+----+-----------+----------+------------+-----------+\n| 11 | 1 | 11 | 11 | 11 |\n| 10 | 1 | 10 | 11 | 10 |\n| 9 | 1 | 9 | 11 | 9 |\n| 8 | 1 | 8 | 11 | 8 |\n| 7 | 1 | 7 | 11 | 7 |\n| 6 | 1 | 6 | 11 | 6 |\n| 5 | 1 | 5 | 11 | 5 |\n| 4 | 1 | 4 | 11 | 4 |\n| 3 | 1 | 3 | 11 | 3 |\n| 2 | 1 | 2 | 11 | 2 |\n| 1 | 1 | 1 | 11 | 1 |\n+----+-----------+----------+------------+-----------+\n \nCREATE OR REPLACE TABLE t1 (i int);\nINSERT INTO t1 VALUES\n(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);\n \nSELECT i,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW\nand 1 FOLLOWING) AS f_1f,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW and\n1 FOLLOWING) AS l_1f,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 PRECEDING\nAND 1 FOLLOWING) AS f_1p1f,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 PRECEDING AND\n1 FOLLOWING) AS f_1p1f,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 2 PRECEDING\nAND 1 PRECEDING) AS f_2p1p,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 2 PRECEDING AND\n1 PRECEDING) AS f_2p1p,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 FOLLOWING\nAND 2 FOLLOWING) AS f_1f2f,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 FOLLOWING AND\n2 FOLLOWING) AS f_1f2f\nFROM t1;\n \n+------+------+------+--------+--------+--------+--------+--------+--------+\n| i | f_1f | l_1f | f_1p1f | f_1p1f | f_2p1p | f_2p1p |\nf_1f2f | f_1f2f |\n+------+------+------+--------+--------+--------+--------+--------+--------+\n| 1 | 1 | 2 | 1 | 2 | NULL | NULL | 2 | 3 |\n| 2 | 2 | 3 | 1 | 3 | 1 | 1 | 3 | 4 |\n| 3 | 3 | 4 | 2 | 4 | 1 | 2 | 4 | 5 |\n| 4 | 4 | 5 | 3 | 5 | 2 | 3 | 5 | 6 |\n| 5 | 5 | 6 | 4 | 6 | 3 | 4 | 6 | 7 |\n| 6 | 6 | 7 | 5 | 7 | 4 | 5 | 7 | 8 |\n| 7 | 7 | 8 | 6 | 8 | 5 | 6 | 8 | 9 |\n| 8 | 8 | 9 | 7 | 9 | 6 | 7 | 9 | 10 |\n| 9 | 9 | 10 | 8 | 10 | 7 | 8 | 10 | 10 |\n| 10 | 10 | 10 | 9 | 10 | 8 | 9 | NULL | NULL |\n+------+------+------+--------+--------+--------+--------+--------+--------+\n \n\n\nURL: https://mariadb.com/kb/en/library/last_value/','','https://mariadb.com/kb/en/library/last_value/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (214,17,'PROCEDURE ANALYSE','Syntax\n------ \nanalyse([max_elements[,max_memory]])\n \nDescription\n----------- \nThis procedure is defined in the sql/sql_analyse.cc file. It\nexamines\nthe result from a query and returns an analysis of the\nresults that\nsuggests optimal data types for each column. To obtain this\nanalysis,\nappend PROCEDURE ANALYSE to the end of a SELECT statement:\n \nSELECT ... FROM ... WHERE ... PROCEDURE\nANALYSE([max_elements,[max_memory]])\n \nFor example:\n \nSELECT col1, col2 FROM table1 PROCEDURE ANALYSE(10, 2000);\n \nThe results show some statistics for the values returned by\nthe query,\nand propose an optimal data type for the columns. This can\nbe helpful\nfor checking your existing tables, or after importing new\ndata. You\nmay need to try different settings for the arguments so that\nPROCEDURE\nANALYSE() does not suggest the ENUM data type when it is not\nappropriate.\n \nThe arguments are optional and are used as follows:\nmax_elements (default 256) is the maximum number of distinct\nvalues that analyse notices per column. This is used by\nanalyse to check whether the optimal data type should be of\ntype ENUM; if there are more than max_elements distinct\nvalues, then ENUM is not a suggested type.\nmax_memory (default 8192) is the maximum amount of memory\nthat analyse should allocate per column while trying to find\nall distinct values.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/procedure-analyse/','','https://mariadb.com/kb/en/library/procedure-analyse/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (215,17,'ROW_COUNT','Syntax\n------ \nROW_COUNT()\n \nDescription\n----------- \nROW_COUNT() returns the number of rows updated, inserted or\ndeleted\nby the preceding statement. This is the same as the row\ncount that the\nmysql client displays and the value from the\nmysql_affected_rows() C\nAPI function.\n \nGenerally:\nFor statements which return a result set (such as SELECT,\nSHOW, DESC or HELP), returns -1, even when the result set is\nempty. This is also true for administrative statements, such\nas OPTIMIZE.\nFor DML statements other than SELECT and for ALTER TABLE,\nreturns the number of affected rows.\nFor DDL statements (including TRUNCATE) and for other\nstatements which don\'t return any result set (such as USE,\nDO, SIGNAL or DEALLOCATE PREPARE), returns 0.\n \nFor UPDATE, affected rows is by default the number of rows\nthat were actually changed. If the CLIENT_FOUND_ROWS flag to\nmysql_real_connect() is specified when connecting to mysqld,\naffected rows is instead the number of rows matched by the\nWHERE clause. \n \nFor REPLACE, deleted rows are also counted. So, if REPLACE\ndeletes a row and adds a new row, ROW_COUNT() returns 2.\n \nFor INSERT ... ON DUPLICATE KEY, updated rows are counted\ntwice. So, if INSERT adds a new rows and modifies another\nrow, ROW_COUNT() returns 3.\n \nROW_COUNT() does not take into account rows that are not\ndirectly deleted/updated by the last statement. This means\nthat rows deleted by foreign keys or triggers are not\ncounted.\n \nWarning: You can use ROW_COUNT() with prepared statements,\nbut you need to call it after EXECUTE, not after DEALLOCATE\nPREPARE, because the row count for allocate prepare is\nalways 0.\n \nWarning: When used after a CALL statement, this function\nreturns the number of rows affected by the last statement in\nthe procedure, not by the whole procedure.\n \nWarning: After INSERT DELAYED, ROW_COUNT() returns the\nnumber of the rows you tried to insert, not the number of\nthe successful writes.\n \nThis information can also be found in the diagnostics area.\n \nStatements using the ROW_COUNT() function are not safe for\nreplication.\n \nExamples\n-------- \nCREATE TABLE t (A INT);\n \nINSERT INTO t VALUES(1),(2),(3);\n \nSELECT ROW_COUNT();\n+-------------+\n| ROW_COUNT() |\n+-------------+\n| 3 |\n+-------------+\n \nDELETE FROM t WHERE A IN(1,2);\n \nSELECT ROW_COUNT(); \n+-------------+\n| ROW_COUNT() |\n+-------------+\n| 2 |\n+-------------+\n \nExample with prepared statements:\n \nSET @q = \'INSERT INTO t VALUES(1),(2),(3);\';\n \nPREPARE stmt FROM @q;\n \nEXECUTE stmt;\n \nQuery OK, 3 rows affected (0.39 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\n \nSELECT ROW_COUNT();\n+-------------+\n| ROW_COUNT() |\n+-------------+\n| 3 |\n+-------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/row_count/','','https://mariadb.com/kb/en/library/row_count/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (216,17,'SCHEMA','Syntax\n------ \nSCHEMA()\n \nDescription\n----------- \nThis function is a synonym for DATABASE().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/schema/','','https://mariadb.com/kb/en/library/schema/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (217,17,'SESSION_USER','Syntax\n------ \nSESSION_USER()\n \nDescription\n----------- \nSESSION_USER() is a synonym for USER().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/session_user/','','https://mariadb.com/kb/en/library/session_user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (218,17,'SYSTEM_USER','Syntax\n------ \nSYSTEM_USER()\n \nDescription\n----------- \nSYSTEM_USER() is a synonym for USER().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/system_user/','','https://mariadb.com/kb/en/library/system_user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (219,17,'USER','Syntax\n------ \nUSER()\n \nDescription\n----------- \nReturns the current MariaDB user name and host name, given\nwhen authenticating to MariaDB, as a string in the utf8\ncharacter set.\n \nNote that the value of USER() may differ from the value of\nCURRENT_USER(), which is the user used to authenticate the\ncurrent client. \nCURRENT_ROLE() returns the current active role.\n \nSYSTEM_USER() and SESSION_USER are synonyms for USER().\n \nStatements using the USER() function or one of its synonyms\nare not safe for statement level replication.\n \nExamples\n-------- \nshell> mysql --user=\"anonymous\"\n \nMariaDB [(none)]> select user(),current_user();\n+---------------------+----------------+\n| user() | current_user() |\n+---------------------+----------------+\n| anonymous@localhost | @localhost |\n+---------------------+----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/user/','','https://mariadb.com/kb/en/library/user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (220,17,'VERSION','Syntax\n------ \nVERSION()\n \nDescription\n----------- \nReturns a string that indicates the MariaDB server version.\nThe string\nuses the utf8 character set.\n \nExamples\n-------- \nSELECT VERSION();\n+------------------------------+\n| VERSION() |\n+------------------------------+\n| 10.0.3-MariaDB-1~precise-log |\n+------------------------------+\n \nThe VERSION() string may have one or more of the following\nsuffixes:\n \nSuffix | Description | \n \n-embedded | The server is an embedded server (libmysqld). | \n \n-log | General logging, slow logging or binary (replication)\nlogging is enabled. | \n \n-debug | The server is compiled for debugging. | \n \n-valgrind | The server is compiled to be instrumented with\nvalgrind. | \n \nChanging the Version String\n \nSome old legacy code may break because they are parsing the\nVERSION string and expecting a MySQL string or a simple\nversion\nstring like Joomla til API17, see MDEV-7780.\n \nIn MariaDB 10.2 one can fool these applications by setting\nthe version string from the command line or the my.cnf files\nwith --version=....\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/version/','','https://mariadb.com/kb/en/library/version/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (221,18,'!=','Syntax\n------ \n, !=\n \nDescription\n----------- \nNot equal operator. Evaluates both SQL expressions and\nreturns 1 if they are not equal and 0 if they are equal, or\nNULL if either expression is NULL. If the expressions return\ndifferent data types, (for instance, a number and a string),\nperforms type conversion.\n \nWhen used in row comparisons these two queries return the\nsame results:\n \nSELECT (t1.a, t1.b) != (t2.x, t2.y) \nFROM t1 INNER JOIN t2;\n \nSELECT (t1.a != t2.x) OR (t1.b != t2.y)\nFROM t1 INNER JOIN t2;\n \nExamples\n-------- \nSELECT \'.01\' \'0.01\';\n \n+-----------------+\n| \'.01\' \'0.01\' |\n+-----------------+\n| 1 |\n+-----------------+\n \nSELECT .01 \'0.01\';\n \n+---------------+\n| .01 \'0.01\' |\n+---------------+\n| 0 |\n+---------------+\n \nSELECT \'zapp\' \'zappp\';\n \n+-------------------+\n| \'zapp\' \'zappp\' |\n+-------------------+\n| 1 |\n+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/not-equal/','','https://mariadb.com/kb/en/library/not-equal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (222,18,'<','Syntax\n------ \n\n\nURL: https://mariadb.com/kb/en/library/less-than/','','https://mariadb.com/kb/en/library/less-than/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (223,18,'<=','Syntax\n------ \n\n\nURL: https://mariadb.com/kb/en/library/less-than-or-equal/','','https://mariadb.com/kb/en/library/less-than-or-equal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (224,18,'<=>','Syntax\n------ \n\n \nDescription\n----------- \nNULL-safe equal operator. It performs an equality comparison\nlike\nthe = operator, but returns 1 rather than NULL if both\noperands are\nNULL, and 0 rather than NULL if one operand is NULL.\n \na b is equivalent to a = b OR (a IS NULL AND b IS NULL).\n \nWhen used in row comparisons these two queries return the\nsame results:\n \nSELECT (t1.a, t1.b) (t2.x, t2.y) \nFROM t1 INNER JOIN t2;\n \nSELECT (t1.a t2.x) AND (t1.b t2.y)\nFROM t1 INNER JOIN t2;\n \nSee also NULL Values in MariaDB.\n \nExamples\n-------- \nSELECT 1 1, NULL NULL, 1 NULL;\n \n+---------+---------------+------------+\n| 1 1 | NULL NULL | 1 NULL |\n+---------+---------------+------------+\n| 1 | 1 | 0 |\n+---------+---------------+------------+\n \nSELECT 1 = 1, NULL = NULL, 1 = NULL;\n \n+-------+-------------+----------+\n| 1 = 1 | NULL = NULL | 1 = NULL |\n+-------+-------------+----------+\n| 1 | NULL | NULL |\n+-------+-------------+----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/null-safe-equal/','','https://mariadb.com/kb/en/library/null-safe-equal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (225,18,'=','Syntax\n------ \nleft_expr = right_expr\n \nDescription\n----------- \nEqual operator. Evaluates both SQL expressions and returns 1\nif they are equal, 0 if they are not equal, or NULL if\neither expression is NULL. If the expressions return\ndifferent data types (for example, a number and a string), a\ntype conversion is performed.\n \nWhen used in row comparisons these two queries are\nsynonymous and return the same results:\n \nSELECT (t1.a, t1.b) = (t2.x, t2.y) FROM t1 INNER JOIN t2;\n \nSELECT (t1.a = t2.x) AND (t1.b = t2.y) FROM t1 INNER JOIN\nt2;\n \nTo perform a NULL-safe comparison, use the operator.\n \n= can also be used as an assignment operator.\n \nExamples\n-------- \nSELECT 1 = 0;\n \n+-------+\n| 1 = 0 |\n+-------+\n| 0 |\n+-------+\n \nSELECT \'0\' = 0;\n \n+---------+\n| \'0\' = 0 |\n+---------+\n| 1 |\n+---------+\n \nSELECT \'0.0\' = 0;\n \n+-----------+\n| \'0.0\' = 0 |\n+-----------+\n| 1 |\n+-----------+\n \nSELECT \'0.01\' = 0;\n \n+------------+\n| \'0.01\' = 0 |\n+------------+\n| 0 |\n+------------+\n \nSELECT \'.01\' = 0.01;\n \n+--------------+\n| \'.01\' = 0.01 |\n+--------------+\n| 1 |\n+--------------+\n \nSELECT (5 * 2) = CONCAT(\'1\', \'0\');\n+----------------------------+\n| (5 * 2) = CONCAT(\'1\', \'0\') |\n+----------------------------+\n| 1 |\n+----------------------------+\n \nSELECT 1 = NULL;\n \n+----------+\n| 1 = NULL |\n+----------+\n| NULL |\n+----------+\n \nSELECT NULL = NULL;\n \n+-------------+\n| NULL = NULL |\n+-------------+\n| NULL |\n+-------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/equal/','','https://mariadb.com/kb/en/library/equal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (226,18,'>','Syntax\n------ \n>\n \nDescription\n----------- \nGreater than operator. Evaluates both SQL expressions and\nreturns 1 if the left value is greater than the right value\nand 0 if it is not, or NULL if either expression is NULL. If\nthe expressions return different data types, (for instance,\na number and a string), performs type conversion.\n \nWhen used in row comparisons these two queries return the\nsame results:\n \nSELECT (t1.a, t1.b) > (t2.x, t2.y) \nFROM t1 INNER JOIN t2;\n \nSELECT (t1.a > t2.x) OR ((t1.a = t2.x) AND (t1.b > t2.y))\nFROM t1 INNER JOIN t2;\n \nExamples\n-------- \nSELECT 2 > 2;\n \n+-------+\n| 2 > 2 |\n+-------+\n| 0 |\n+-------+\n \nSELECT \'b\' > \'a\';\n \n+-----------+\n| \'b\' > \'a\' |\n+-----------+\n| 1 |\n+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/greater-than/','','https://mariadb.com/kb/en/library/greater-than/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (227,18,'>=','Syntax\n------ \n>=\n \nDescription\n----------- \nGreater than or equal operator. Evaluates both SQL\nexpressions and returns 1 if the left value is greater than\nor equal to the right value and 0 if it is not, or NULL if\neither expression is NULL. If the expressions return\ndifferent data types, (for instance, a number and a string),\nperforms type conversion.\n \nWhen used in row comparisons these two queries return the\nsame results:\n \nSELECT (t1.a, t1.b) >= (t2.x, t2.y) \nFROM t1 INNER JOIN t2;\n \nSELECT (t1.a > t2.x) OR ((t1.a = t2.x) AND (t1.b >= t2.y))\nFROM t1 INNER JOIN t2;\n \nExamples\n-------- \nSELECT 2 >= 2;\n \n+--------+\n| 2 >= 2 |\n+--------+\n| 1 |\n+--------+\n \nSELECT \'A\' >= \'a\';\n \n+------------+\n| \'A\' >= \'a\' |\n+------------+\n| 1 |\n+------------+\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/greater-than-or-equal/','','https://mariadb.com/kb/en/library/greater-than-or-equal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (228,18,'BETWEEN AND','Syntax\n------ \nexpr BETWEEN min AND max\n \nDescription\n----------- \nIf expr is greater than or equal to min and expr is less\nthan or equal\nto max, BETWEEN returns 1, otherwise it returns 0. This is\nequivalent\nto the expression (min \n\nURL: https://mariadb.com/kb/en/library/between-and/','','https://mariadb.com/kb/en/library/between-and/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (229,18,'COALESCE','Syntax\n------ \nCOALESCE(value,...)\n \nDescription\n----------- \nReturns the first non-NULL value in the list, or NULL if\nthere are no\nnon-NULL values. At least one parameter must be passed.\n \nSee also NULL Values in MariaDB.\n \nExamples\n-------- \nSELECT COALESCE(NULL,1);\n+------------------+\n| COALESCE(NULL,1) |\n+------------------+\n| 1 |\n+------------------+\n \nSELECT COALESCE(NULL,NULL,NULL);\n+--------------------------+\n| COALESCE(NULL,NULL,NULL) |\n+--------------------------+\n| NULL |\n+--------------------------+\n \nWhen two arguments are given, COALESCE() is the same as\nIFNULL():\n \nSET @a=NULL, @b=1;\n \nSELECT COALESCE(@a, @b), IFNULL(@a, @b);\n+------------------+----------------+\n| COALESCE(@a, @b) | IFNULL(@a, @b) |\n+------------------+----------------+\n| 1 | 1 |\n+------------------+----------------+\n \nHex type confusion:\n \nCREATE TABLE t1 (a INT, b VARCHAR(10));\nINSERT INTO t1 VALUES (0x31, 0x61),(COALESCE(0x31),\nCOALESCE(0x61));\n \nSELECT * FROM t1;\n \n+------+------+\n| a | b |\n+------+------+\n| 49 | a |\n| 1 | a |\n+------+------+\n \nThe reason for the differing results above is that when 0x31\nis inserted directly to the column, it\'s treated as a\nnumber (see Hexadecimal Literals), while when 0x31 is passed\nto COALESCE(), it\'s treated as a string, because:\nHEX values have a string data type by default.\nCOALESCE() has the same data type as the argument. \n \n\n\nURL: https://mariadb.com/kb/en/library/coalesce/','','https://mariadb.com/kb/en/library/coalesce/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (230,18,'GREATEST','Syntax\n------ \nGREATEST(value1,value2,...)\n \nDescription\n----------- \nWith two or more arguments, returns the largest\n(maximum-valued)\nargument. The arguments are compared using the same rules as\nfor\nLEAST().\n \nExamples\n-------- \nSELECT GREATEST(2,0);\n+---------------+\n| GREATEST(2,0) |\n+---------------+\n| 2 |\n+---------------+\n \nSELECT GREATEST(34.0,3.0,5.0,767.0);\n+------------------------------+\n| GREATEST(34.0,3.0,5.0,767.0) |\n+------------------------------+\n| 767.0 |\n+------------------------------+\n \nSELECT GREATEST(\'B\',\'A\',\'C\');\n+-----------------------+\n| GREATEST(\'B\',\'A\',\'C\') |\n+-----------------------+\n| C |\n+-----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/greatest/','','https://mariadb.com/kb/en/library/greatest/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (231,18,'IN','Syntax\n------ \nexpr IN (value,...)\n \nDescription\n----------- \nReturns 1 if expr is equal to any of the values in the IN\nlist, else\nreturns 0. If all values are constants, they are evaluated\naccording\nto the type of expr and sorted. The search for the item then\nis done\nusing a binary search. This means IN is very quick if the IN\nvalue\nlist consists entirely of constants. Otherwise, type\nconversion takes\nplace according to the rules described at Type Conversion,\nbut\napplied to all the arguments.\n \nIf expr is NULL, IN always returns NULL. If at least one of\nthe values in the list is NULL, and one of the comparisons\nis true, the result is 1. If at least one of the values in\nthe list is NULL and none of the comparisons is true, the\nresult is NULL.\n \nExamples\n-------- \nSELECT 2 IN (0,3,5,7);\n+----------------+\n| 2 IN (0,3,5,7) |\n+----------------+\n| 0 |\n+----------------+\n \nSELECT \'wefwf\' IN (\'wee\',\'wefwf\',\'weg\');\n+----------------------------------+\n| \'wefwf\' IN (\'wee\',\'wefwf\',\'weg\') |\n+----------------------------------+\n| 1 |\n+----------------------------------+ \n \nType conversion:\n \nSELECT 1 IN (\'1\', \'2\', \'3\');\n+----------------------+\n| 1 IN (\'1\', \'2\', \'3\') |\n+----------------------+\n| 1 |\n+----------------------+\n \nSELECT NULL IN (1, 2, 3);\n+-------------------+\n| NULL IN (1, 2, 3) |\n+-------------------+\n| NULL |\n+-------------------+\n \nMariaDB [(none)]> SELECT 1 IN (1, 2, NULL);\n+-------------------+\n| 1 IN (1, 2, NULL) |\n+-------------------+\n| 1 |\n+-------------------+\n \nMariaDB [(none)]> SELECT 5 IN (1, 2, NULL);\n+-------------------+\n| 5 IN (1, 2, NULL) |\n+-------------------+\n| NULL |\n+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/in/','','https://mariadb.com/kb/en/library/in/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (232,18,'INTERVAL','Syntax\n------ \nINTERVAL(N,N1,N2,N3,...)\n \nDescription\n----------- \nReturns the index of the last argument that is less than the\nfirst argument or is NULL. \n \nReturns 0 if N < N1, 1 if N < N2, 2 if N < N3 and so on or\n-1 if N is NULL. All\narguments are treated as integers. It is required that N1 <\nN2 < N3 \n\nURL: https://mariadb.com/kb/en/library/interval/','','https://mariadb.com/kb/en/library/interval/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (233,18,'IS','Syntax\n------ \nIS boolean_value\n \nDescription\n----------- \nTests a value against a boolean value, where boolean_value\ncan be\nTRUE, FALSE, or UNKNOWN.\n \nThere is an important difference between using IS TRUE or\ncomparing a value with TRUE using =. When using =, only 1\nequals to TRUE. But when using IS TRUE, all values which are\nlogically true (like a number > 1) return TRUE.\n \nExamples\n-------- \nSELECT 1 IS TRUE, 0 IS FALSE, NULL IS UNKNOWN;\n+-----------+------------+-----------------+\n| 1 IS TRUE | 0 IS FALSE | NULL IS UNKNOWN |\n+-----------+------------+-----------------+\n| 1 | 1 | 1 |\n+-----------+------------+-----------------+\n \nDifference between = and IS TRUE:\n \nSELECT 2 = TRUE, 2 IS TRUE;\n+----------+-----------+\n| 2 = TRUE | 2 IS TRUE |\n+----------+-----------+\n| 0 | 1 |\n+----------+-----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/is/','','https://mariadb.com/kb/en/library/is/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (234,18,'IS NOT','Syntax\n------ \nIS NOT boolean_value\n \nDescription\n----------- \nTests a value against a boolean value, where boolean_value\ncan be\nTRUE, FALSE, or UNKNOWN. \n \nExamples\n-------- \nSELECT 1 IS NOT UNKNOWN, 0 IS NOT UNKNOWN, NULL IS NOT\nUNKNOWN;\n+------------------+------------------+---------------------+\n| 1 IS NOT UNKNOWN | 0 IS NOT UNKNOWN | NULL IS NOT UNKNOWN\n|\n+------------------+------------------+---------------------+\n| 1 | 1 | 0 |\n+------------------+------------------+---------------------+\n \nSELECT NULL IS NOT TRUE, NULL IS NOT FALSE;\n+------------------+-------------------+\n| NULL IS NOT TRUE | NULL IS NOT FALSE |\n+------------------+-------------------+\n| 1 | 1 |\n+------------------+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/is-not/','','https://mariadb.com/kb/en/library/is-not/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (235,18,'IS NOT NULL','Syntax\n------ \nIS NOT NULL\n \nDescription\n----------- \nTests whether a value is not NULL. See also NULL Values in\nMariaDB.\n \nExamples\n-------- \nSELECT 1 IS NOT NULL, 0 IS NOT NULL, NULL IS NOT NULL;\n+---------------+---------------+------------------+\n| 1 IS NOT NULL | 0 IS NOT NULL | NULL IS NOT NULL |\n+---------------+---------------+------------------+\n| 1 | 1 | 0 |\n+---------------+---------------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/is-not-null/','','https://mariadb.com/kb/en/library/is-not-null/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (236,18,'IS NULL','Syntax\n------ \nIS NULL\n \nDescription\n----------- \nTests whether a value is NULL. See also NULL Values in\nMariaDB.\n \nExamples\n-------- \nSELECT 1 IS NULL, 0 IS NULL, NULL IS NULL;\n+-----------+-----------+--------------+\n| 1 IS NULL | 0 IS NULL | NULL IS NULL |\n+-----------+-----------+--------------+\n| 0 | 0 | 1 |\n+-----------+-----------+--------------+\n \nCompatibility\n \nSome ODBC applications use the syntax auto_increment_field\nIS NOT NULL to find the latest row that was inserted with an\nautogenerated key value. If your applications need this, you\ncan set the sql_auto_is_null variable to 1.\n \nSET @@sql_auto_is_null=1;\nCREATE TABLE t1 (auto_increment_column INT NOT NULL\nAUTO_INCREMENT PRIMARY KEY);\nINSERT INTO t1 VALUES (NULL);\nSELECT * FROM t1 WHERE auto_increment_column IS NULL;\n \n+-----------------------+\n| auto_increment_column |\n+-----------------------+\n| 1 |\n+-----------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/is-null/','','https://mariadb.com/kb/en/library/is-null/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (237,18,'ISNULL','Syntax\n------ \nISNULL(expr)\n \nDescription\n----------- \nIf expr is NULL, ISNULL() returns 1, otherwise it returns 0.\n \nSee also NULL Values in MariaDB.\n \nExamples\n-------- \nSELECT ISNULL(1+1);\n+-------------+\n| ISNULL(1+1) |\n+-------------+\n| 0 |\n+-------------+\n \nSELECT ISNULL(1/0);\n+-------------+\n| ISNULL(1/0) |\n+-------------+\n| 1 |\n+-------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/isnull/','','https://mariadb.com/kb/en/library/isnull/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (238,18,'LEAST','Syntax\n------ \nLEAST(value1,value2,...)\n \nDescription\n----------- \nWith two or more arguments, returns the smallest\n(minimum-valued)\nargument. The arguments are compared using the following\nrules:\nIf the return value is used in an INTEGER context or all\narguments are integer-valued, they are compared as integers.\nIf the return value is used in a REAL context or all\narguments are real-valued, they are compared as reals.\nIf any argument is a case-sensitive string, the arguments\nare compared as case-sensitive strings.\nIn all other cases, the arguments are compared as\ncase-insensitive strings.\n \nLEAST() returns NULL if any argument is NULL.\n \nExamples\n-------- \nSELECT LEAST(2,0);\n+------------+\n| LEAST(2,0) |\n+------------+\n| 0 |\n+------------+\n \nSELECT LEAST(34.0,3.0,5.0,767.0);\n+---------------------------+\n| LEAST(34.0,3.0,5.0,767.0) |\n+---------------------------+\n| 3.0 |\n+---------------------------+\n \nSELECT LEAST(\'B\',\'A\',\'C\');\n+--------------------+\n| LEAST(\'B\',\'A\',\'C\') |\n+--------------------+\n| A |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/least/','','https://mariadb.com/kb/en/library/least/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (239,18,'NOT BETWEEN','Syntax\n------ \nexpr NOT BETWEEN min AND max\n \nDescription\n----------- \nThis is the same as NOT (expr BETWEEN min AND max).\n \nNote that the meaning of the alternative form NOT expr\nBETWEEN min AND max is affected by the HIGH_NOT_PRECEDENCE\nSQL_MODE flag.\n \nExamples\n-------- \nSELECT 1 NOT BETWEEN 2 AND 3;\n+-----------------------+\n| 1 NOT BETWEEN 2 AND 3 |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nSELECT \'b\' NOT BETWEEN \'a\' AND \'c\';\n+-----------------------------+\n| \'b\' NOT BETWEEN \'a\' AND \'c\' |\n+-----------------------------+\n| 0 |\n+-----------------------------+\n \nNULL:\n \nSELECT 1 NOT BETWEEN 1 AND NULL;\n+--------------------------+\n| 1 NOT BETWEEN 1 AND NULL |\n+--------------------------+\n| NULL |\n+--------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/not-between/','','https://mariadb.com/kb/en/library/not-between/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (240,18,'NOT IN','Syntax\n------ \nexpr NOT IN (value,...)\n \nDescription\n----------- \nThis is the same as NOT (expr IN (value,...)).\n \nExamples\n-------- \nSELECT 2 NOT IN (0,3,5,7);\n+--------------------+\n| 2 NOT IN (0,3,5,7) |\n+--------------------+\n| 1 |\n+--------------------+\n \nSELECT \'wefwf\' NOT IN (\'wee\',\'wefwf\',\'weg\');\n+--------------------------------------+\n| \'wefwf\' NOT IN (\'wee\',\'wefwf\',\'weg\') |\n+--------------------------------------+\n| 0 |\n+--------------------------------------+\n \nSELECT 1 NOT IN (\'1\', \'2\', \'3\');\n+--------------------------+\n| 1 NOT IN (\'1\', \'2\', \'3\') |\n+--------------------------+\n| 0 |\n+--------------------------+\n \nNULL:\n \nSELECT NULL NOT IN (1, 2, 3);\n+-----------------------+\n| NULL NOT IN (1, 2, 3) |\n+-----------------------+\n| NULL |\n+-----------------------+\n \nSELECT 1 NOT IN (1, 2, NULL);\n+-----------------------+\n| 1 NOT IN (1, 2, NULL) |\n+-----------------------+\n| 0 |\n+-----------------------+\n \nSELECT 5 NOT IN (1, 2, NULL);\n+-----------------------+\n| 5 NOT IN (1, 2, NULL) |\n+-----------------------+\n| NULL |\n+-----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/not-in/','','https://mariadb.com/kb/en/library/not-in/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (241,19,'Operator Precedence','The precedence is the order in which the SQL operators are\nevaluated.\n \nThe following list shows the SQL operator precedence.\nOperators that appear first in the list have a higher\nprecedence. Operators which are listed together have the\nsame precedence.\nINTERVAL\nBINARY, COLLATE\n!\n- (unary minus), [[bitwise-not|]] (unary bit inversion)\n|| (string concatenation)\n^\n*, /, DIV, %, MOD\n-, +\n \n&\n|\n= (comparison), , >=, >, \n\nURL: https://mariadb.com/kb/en/library/operator-precedence/','','https://mariadb.com/kb/en/library/operator-precedence/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (242,19,'&','Syntax\n------ \n&\n \nDescription\n----------- \nBitwise AND. Converts the values to binary and compares\nbits. Only if both the corresponding bits are 1 is the\nresulting bit also 1.\n \nSee also bitwise OR.\n \nExamples\n-------- \nSELECT 2&1;\n+-----+\n| 2&1 |\n+-----+\n| 0 |\n+-----+\n \nSELECT 3&1;\n+-----+\n| 3&1 |\n+-----+\n| 1 |\n+-----+\n \nSELECT 29 & 15;\n+---------+\n| 29 & 15 |\n+---------+\n| 13 |\n+---------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/bitwise_and/','','https://mariadb.com/kb/en/library/bitwise_and/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (243,19,'<<','Syntax\n------ \nvalue1 \n\nURL: https://mariadb.com/kb/en/library/shift-left/','','https://mariadb.com/kb/en/library/shift-left/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (244,19,'>>','Syntax\n------ \nvalue1 >> value2\n \nDescription\n----------- \nConverts a longlong (BIGINT) number (value1) to binary and\nshifts value2 units to the right.\n \nExamples\n-------- \nSELECT 4 >> 2;\n+--------+\n| 4 >> 2 |\n+--------+\n| 1 |\n+--------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/shift-right/','','https://mariadb.com/kb/en/library/shift-right/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (245,19,'BIT_COUNT','Syntax\n------ \nBIT_COUNT(N)\n \nDescription\n----------- \nReturns the number of bits that are set in the argument N.\n \nExamples\n-------- \nSELECT BIT_COUNT(29), BIT_COUNT(b\'101010\');\n+---------------+----------------------+\n| BIT_COUNT(29) | BIT_COUNT(b\'101010\') |\n+---------------+----------------------+\n| 4 | 3 |\n+---------------+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/bit_count/','','https://mariadb.com/kb/en/library/bit_count/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (246,19,'^','Syntax\n------ \n^\n \nDescription\n----------- \nBitwise XOR. Converts the values to binary and compares\nbits. If one (and only one) of the corresponding bits is 1\nis the resulting bit also 1.\n \nExamples\n-------- \nSELECT 1 ^ 1;\n+-------+\n| 1 ^ 1 |\n+-------+\n| 0 |\n+-------+\n \nSELECT 1 ^ 0;\n+-------+\n| 1 ^ 0 |\n+-------+\n| 1 |\n+-------+\n \nSELECT 11 ^ 3;\n+--------+\n| 11 ^ 3 |\n+--------+\n| 8 |\n+--------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/bitwise-xor/','','https://mariadb.com/kb/en/library/bitwise-xor/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (247,19,'|','Syntax\n------ \n|\n \nDescription\n----------- \nBitwise OR. Converts the values to binary and compares bits.\nIf either of the corresponding bits has a value of 1, the\nresulting bit is also 1.\n \nSee also bitwise AND.\n \nExamples\n-------- \nSELECT 2|1;\n+-----+\n| 2|1 |\n+-----+\n| 3 |\n+-----+\n \nSELECT 29 | 15;\n+---------+\n| 29 | 15 |\n+---------+\n| 31 |\n+---------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/bitwise-or/','','https://mariadb.com/kb/en/library/bitwise-or/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (248,19,'~','Syntax\n------ \n~\n \nDescription\n----------- \nBitwise NOT. Converts the value to 4 bytes binary and\ninverts all bits.\n \nExamples\n-------- \nSELECT 3 & ~1;\n+--------+\n| 3 & ~1 |\n+--------+\n| 2 |\n+--------+\n \nSELECT 5 & ~1;\n+--------+\n| 5 & ~1 |\n+--------+\n| 4 |\n+--------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/bitwise-not/','','https://mariadb.com/kb/en/library/bitwise-not/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (249,19,'Parentheses','Parentheses are sometimes called precedence operators - this\nmeans that they can be used to change the other operator\'s\nprecedence in an expression. The expressions that are\nwritten between parentheses are computed before the\nexpressions that are written outside. Parentheses must\nalways contain an expression (that is, they cannot be\nempty), and can be nested.\n \nFor example, the following expressions could return\ndifferent results:\nNOT a OR b\nNOT (a OR b)\n \nIn the first case, NOT applies to a, so if a is FALSE or b\nis TRUE, the expression returns TRUE. In the second case,\nNOT applies to the result of a OR b, so if at least one of a\nor b is TRUE, the expression is TRUE.\n \nWhen the precedence of operators is not intuitive, you can\nuse parentheses to make it immediately clear for whoever\nreads the statement.\n \nThe precedence of the NOT operator can also be affected by\nthe HIGH_NOT_PRECEDENCE SQL_MODE flag.\n \nOther uses\n \nParentheses must always be used to enclose subqueries.\n \nParentheses can also be used in a JOIN statement between\nmultiple tables to determine which tables must be joined\nfirst.\n \nAlso, parentheses are used to enclose the list of parameters\nto be passed to built-in functions, user-defined functions\nand stored routines. However, when no parameter is passed to\na stored procedure, parentheses are optional. For builtin\nfunctions and user-defined functions, spaces are not allowed\nbetween the function name and the open parenthesis, unless\nthe IGNORE_SPACE SQL_MODE is set. For stored routines (and\nfor functions if IGNORE_SPACE is set) spaces are allowed\nbefore the open parenthesis, including tab characters and\nnew line characters.\n \nSyntax errors\n \nIf there are more open parentheses than closed parentheses,\nthe error usually looks like this:\n \nERROR 1064 (42000): You have an error in your SQL syntax;\ncheck the manual that\ncorresponds to your MariaDB server version for the right\nsyntax to use near \'\' a\nt line 1\n \nNote the empty string.\n \nIf there are more closed parentheses than open parentheses,\nthe error usually looks like this:\n \nERROR 1064 (42000): You have an error in your SQL syntax;\ncheck the manual that\ncorresponds to your MariaDB server version for the right\nsyntax to use near \')\'\nat line 1\n \nNote the quoted closed parenthesis.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/parentheses/','','https://mariadb.com/kb/en/library/parentheses/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (250,19,'TRUE FALSE','Description\n----------- \nThe constants TRUE and FALSE evaluate to 1 and 0,\nrespectively. The\nconstant names can be written in any lettercase.\n \nExamples\n-------- \nSELECT TRUE, true, FALSE, false;\n \n+------+------+-------+-------+\n| TRUE | TRUE | FALSE | FALSE |\n+------+------+-------+-------+\n| 1 | 1 | 0 | 0 |\n+------+------+-------+-------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/true-false/','','https://mariadb.com/kb/en/library/true-false/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (251,20,'ANALYZE TABLE','Syntax\n------ \nANALYZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE tbl_name\n[,tbl_name ...] \n [PERSISTENT FOR [ALL|COLUMNS ([col_name [,col_name ...]])] \n [INDEXES ([index_name [,index_name ...]])]] \n \nDescription\n----------- \nANALYZE TABLE analyzes and stores the key distribution for a\ntable (index statistics). During the analysis, the table is\nlocked with a read lock. This statement works with MyISAM,\nAria and InnoDB tables. For MyISAM tables, this statement is\nequivalent\nto using myisamchk --analyze.\n \nFor more information on how the analysis works within\nInnoDB, see\nInnoDB Limitations.\n \nMariaDB uses the stored key distribution to decide the order\nin which\ntables should be joined when you perform a join on something\nother than\na constant. In addition, key distributions can be used when\ndeciding\nwhich indexes to use for a specific table within a query.\n \nThis statement requires SELECT and INSERT privileges for the\ntable.\n \nBy default, ANALYZE TABLE statements are written to the\nbinary log and will be replicated. The NO_WRITE_TO_BINLOG\nkeyword (LOCAL is an alias) will ensure the statement is not\nwritten to the binary log. \n \nANALYZE TABLE is also supported for partitioned tables. You\ncan use ALTER TABLE ... ANALYZE PARTITION to analyze one or\nmore partitions.\n \nEngine-Independent Statistics\n \nMariaDB 10.0.1 extended ANALYZE TABLE to support\nengine-independent statistics.\n \nEngine-independent statistics are collected by doing full\ntable and full index scans, and collecting can be quite\nexpensive. \n \nANALYZE TABLE behavior depends on the value of the\nuse_stat_tables system variable.\n \nIf use_stat_tables is set to never (default in = MariaDB\n10.4.1), ANALYZE TABLE t will collect storage engine\nstatistics, and not engine-independent statistics.\n \nIf use_stat_tables is set to complementary or preferably,\nANALYZE TABLE t will collect engine-independent statistics. \n \nIn order to collect engine-independent statistics when\nuse_stat_tables is not set to one of the above two values\n(it is not by default), the extended form of ANALYZE TABLE,\nusing PERSISTENT FOR, must be used. This also allows one to\ncollect statistics only for particular columns or indexes.\nNote that engine-independent statistics are used by default\nfrom MariaDB 10.4 (use_stat_tables=preferably_for_queries),\nso you will probably want to use PERSISTENT FOR.\n \nIt is recommended to collect engine-independent statistics\non as-needed basis, so typically one will not have\nengine-independent statistics for all indexes/all columns. \n \nNote that statistics for blob and text columns are not\ncollected. If explicitly specified, a warning is returned.\n \n-- update all engine-independent statistics for all columns\nand indexes\nANALYZE TABLE tbl PERSISTENT FOR ALL;\n \n-- update specific columns and indexes:\nANALYZE TABLE tbl PERSISTENT FOR COLUMNS (col1,col2,...)\nINDEXES (idx1,idx2,...);\n \n-- empty lists are allowed:\nANALYZE TABLE tbl PERSISTENT FOR COLUMNS (col1,col2,...)\nINDEXES ();\nANALYZE TABLE tbl PERSISTENT FOR COLUMNS () INDEXES\n(idx1,idx2,...);\n \n-- the following will only update mysql.table_stat fields:\nANALYZE TABLE tbl PERSISTENT FOR COLUMNS () INDEXES ();\n \n-- with use_stat_tables = COMPLEMENTARY, a simple ANALYZE\nTABLE \n-- collects engine-independent statistics for all columns\nand indexes.\nSET SESSION use_stat_tables=\'COMPLEMENTARY\';\n \nANALYZE TABLE tbl;\n \nThe PERSISTENT FOR is required to update the\nengine-independent statistics even if the table has the\noption STATS_PERSISTENT=1 (which refers to InnoDB Persistent\nStatistics).\n \nThe Aria storage engine supports progress reporting for the\nANALYZE TABLE statement.\n \n\n\nURL: https://mariadb.com/kb/en/library/analyze-table/','','https://mariadb.com/kb/en/library/analyze-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (252,20,'CHECK TABLE','Syntax\n------ \nCHECK TABLE tbl_name [, tbl_name] ... [option] ...\n \noption = {FOR UPGRADE | QUICK | FAST | MEDIUM | EXTENDED |\nCHANGED}\n \nDescription\n----------- \nCHECK TABLE checks a table or tables for errors. CHECK TABLE\nworks for\nArchive, Aria, CSV, InnoDB, and MyISAM tables. For Aria and\nMyISAM tables, the\nkey statistics are updated as well. For CSV, see also\nChecking and Repairing CSV Tables.\n \nAs an alternative, myisamchk is a commandline tool for\nchecking MyISAM tables when the tables are not being\naccessed.\n \nFor checking dynamic columns integrity, COLUMN_CHECK() can\nbe used.\n \nCHECK TABLE can also check views for problems, such as\ntables\nthat are referenced in the view definition that no longer\nexist.\n \nCHECK TABLE is also supported for partitioned tables. You\ncan\nuse ALTER TABLE ... CHECK PARTITION \nto check one or more partitions.\n \nThe meaning of the different options are as follows - note\nthat this can vary a bit between\nstorage engines:\n \nFOR UPGRADE | Do a very quick check if the storage format\nfor the table has changed so that one needs to do a REPAIR.\nThis is only needed when one upgrades between major versions\nof MariaDB or MySQL. This is usually done by running\nmysql_upgrade. | \n \nFAST | Only check tables that has not been closed properly\nor are marked as corrupt. Only supported by the MyISAM and\nAria engines. For other engines the table is checked\nnormally | \n \nCHANGED | Check only tables that has changed since last\nREPAIR / CHECK. Only supported by the MyISAM and Aria\nengines. For other engines the table is checked normally. | \n \nQUICK | Do a fast check. For MyISAM and Aria engine this\nmeans we skip checking the delete link chain which may take\nsome time. | \n \nMEDIUM | Scan also the data files. Checks integrity between\ndata and index files with checksums. In most cases this\nshould find all possible errors. | \n \nEXTENDED | Does a full check to verify every possible error.\nFor MyISAM and Aria we verify for each row that all it keys\nexists and points to the row. This may take a long time on\nbig tables! | \n \nFor most cases running CHECK TABLE without options or MEDIUM\nshould be\ngood enough.\n \nSince MariaDB 5.3, the Aria storage engine supports progress\nreporting for this statement.\n \nIf you want to know if two tables are identical, take a look\nat CHECKSUM TABLE.\n \nXtraDB/InnoDB\n \nIf CHECK TABLE finds an error in an InnoDB table, MariaDB\nmight shutdown to prevent the error propagation. In this\ncase, the problem will be reported in the error log.\nOtherwise, since MariaDB 5.5, the table or an index might be\nmarked as corrupted, to prevent use. This does not happen\nwith some minor problems, like a wrong number of entries in\na secondary index. Those problems are reported in the output\nof CHECK TABLE.\n \nEach tablespace contains a header with metadata. This header\nis not checked by this statement.\n \nDuring the execution of CHECK TABLE, other threads may be\nblocked.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/sql-commands-check-table/','','https://mariadb.com/kb/en/library/sql-commands-check-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (253,20,'CHECK VIEW','CHECK VIEW was introduced in MariaDB 10.0.18.\n \nSyntax\n------ \nCHECK VIEW view_name\n \nDescription\n----------- \nThe CHECK VIEW statement was introduced in MariaDB 10.0.18\nto assist with fixing MDEV-6916, an issue introduced in\nMariaDB 5.2 where the view algorithms were swapped. It\nchecks whether the view algorithm is correct. It is run as\npart of mysql_upgrade, and should not normally be required\nin regular use.\n \n\n\nURL: https://mariadb.com/kb/en/library/check-view/','','https://mariadb.com/kb/en/library/check-view/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (254,20,'CHECKSUM TABLE','Syntax\n------ \nCHECKSUM TABLE tbl_name [, tbl_name] ... [ QUICK | EXTENDED\n]\n \nDescription\n----------- \nCHECKSUM TABLE reports a table checksum. This is very\nuseful if you want to know if two tables are the same (for\nexample on a master\nand slave).\n \nWith QUICK, the live table checksum is reported if it is\navailable, or NULL otherwise. This is very fast. A live\nchecksum is enabled by specifying the CHECKSUM=1 table\noption when you create the table; currently, this is\nsupported\nonly for Aria and MyISAM tables.\n \nWith EXTENDED, the entire table is read row by row and the\nchecksum is calculated. This can be very slow for large\ntables.\n \nIf neither QUICK nor EXTENDED is\nspecified, MariaDB returns a live checksum if the table\nstorage engine supports\nit and scans the table otherwise.\n \nCHECKSUM TABLE requires the SELECT privilege for the table.\n \nFor a nonexistent table, CHECKSUM TABLE returns\nNULL and generates a warning.\n \nThe table row format affects the checksum value. If the row\nformat changes, the checksum will change. This means that\nwhen a table created with a MariaDB/MySQL version is\nupgraded to another version, the checksum value will\nprobably change.\n \nTwo identical tables should always match to the same\nchecksum value; however, also for non-identical tables there\nis a very slight chance that they will return the same value\nas the hashing algorithm is not completely collision-free.\n \nDifferences Between MariaDB and MySQL\n \nCHECKSUM TABLE may give a different result as MariaDB\ndoesn\'t\nignore NULLs in the columns as MySQL 5.1 does (Later MySQL\nversions should calculate checksums the same way as\nMariaDB). You can get the\n\'old style\' checksum in MariaDB by starting mysqld with\nthe\n--old option. Note however that that the MyISAM and Aria\nstorage engines in MariaDB are using the new checksum\ninternally, so if you are\nusing --old, the CHECKSUM command will be\nslower as it needs to calculate the checksum row by row.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/checksum-table/','','https://mariadb.com/kb/en/library/checksum-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (255,20,'OPTIMIZE TABLE','Syntax\n------ \nOPTIMIZE [NO_WRITE_TO_BINLOG | LOCAL] TABLE\n tbl_name [, tbl_name] ...\n [WAIT n | NOWAIT]\n \nDescription\n----------- \nOPTIMIZE TABLE has two main functions. It can either be used\nto defragment tables, or to update the InnoDB fulltext\nindex.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \nDefragmenting\n \nOPTIMIZE TABLE works for InnoDB (before MariaDB 10.1.1, only\nif the innodb_file_per_table server system variable is set),\nAria, MyISAM and ARCHIVE tables, and should be used if you\nhave deleted a large part of a table or if you have made\nmany changes to a table with variable-length\nrows (tables that have VARCHAR, VARBINARY, BLOB, or TEXT\ncolumns). Deleted rows are maintained in a\nlinked list and subsequent INSERT operations reuse old row\npositions.\n \nThis statement requires SELECT and INSERT privileges for the\ntable.\n \nBy default, OPTIMIZE TABLE statements are written to the\nbinary log and will be replicated. The NO_WRITE_TO_BINLOG\nkeyword (LOCAL is an alias) will ensure the statement is not\nwritten to the binary log. \n \nOPTIMIZE TABLE is also supported for partitioned tables. You\ncan use \nALTER TABLE ... OPTIMIZE PARTITION \nto optimize one or more partitions.\n \nYou can use OPTIMIZE TABLE to reclaim the unused\nspace and to defragment the data file. With other storage\nengines, OPTIMIZE TABLE does nothing by default, and returns\nthis message: \" The storage engine for the table doesn\'t\nsupport optimize\". However, if the server has been started\nwith the --skip-new option, OPTIMIZE TABLE is linked to\nALTER TABLE, and recreates the table. This operation frees\nthe unused space and updates index statistics.\n \nSince MariaDB 5.3, the Aria storage engine supports progress\nreporting for this statement.\n \nIf a MyISAM table is fragmented, concurrent inserts will not\nbe performed until an OPTIMIZE TABLE statement is executed\non that table, unless the concurrent_insert server system\nvariable is set to ALWAYS.\n \nUpdating an InnoDB fulltext index\n \nWhen rows are added or deleted to an InnoDB fulltext index,\nthe index is not immediately re-organized, as this can be an\nexpensive operation. Change statistics are stored in a\nseparate location . The fulltext index is only fully\nre-organized when an OPTIMIZE TABLE statement is run.\n \nBy default, an OPTIMIZE TABLE will defragment a table. In\norder to use it to update fulltext index statistics, the\ninnodb_optimize_fulltext_only system variable must be set to\n1. This is intended to be a temporary setting, and should be\nreset to 0 once the fulltext index has been re-organized.\n \nSince fulltext re-organization can take a long time, the\ninnodb_ft_num_word_optimize variable limits the\nre-organization to a number of words (2000 by default). You\ncan run multiple OPTIMIZE statements to fully re-organize\nthe index.\n \nDefragmenting InnoDB tablespaces\n \nMariaDB 10.1.1 merged the Facebook/Kakao defragmentation\npatch \n \nMariaDB 10.1.1 merged the Facebook/Kakao defragmentation\npatch, allowing one to use OPTIMIZE TABLE to defragment\nInnoDB tablespaces. For this functionality to be enabled,\nthe innodb_defragment system variable must be enabled. No\nnew tables are created and there is no need to copy data\nfrom old tables to new tables. Instead, this feature loads n\npages (determined by innodb-defragment-n-pages) and tries to\nmove records so that pages would be full of records and then\nfrees pages that are fully empty after the operation. Note\nthat tablespace files (including ibdata1) will not shrink as\nthe result of defragmentation, but one will get better\nmemory utilization in the InnoDB buffer pool as there are\nfewer data pages in use.\n \nSee Defragmenting InnoDB Tablespaces for more details.\n \n\n\nURL: https://mariadb.com/kb/en/library/optimize-table/','','https://mariadb.com/kb/en/library/optimize-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (256,20,'REPAIR TABLE','Syntax\n------ \nREPAIR [NO_WRITE_TO_BINLOG | LOCAL] TABLE\n tbl_name [, tbl_name] ...\n [QUICK] [EXTENDED] [USE_FRM]\n \nDescription\n----------- \nREPAIR TABLE repairs a possibly corrupted table. By default,\nit has the same effect as\n \nmyisamchk --recover tbl_name\n \nor\n \naria_chk --recover tbl_name\n \nSee aria_chk and myisamchk for more.\n \nREPAIR TABLE works for Archive, Aria, CSV and MyISAM tables.\nFor XtraDB/InnoDB, see recovery modes. For CSV, see also\nChecking and Repairing CSV Tables. For Archive, this\nstatement also improves compression. If the storage engine\ndoes not support this statement, a warning is issued.\n \nThis statement requires SELECT and INSERT privileges for the\ntable.\n \nBy default, REPAIR TABLE statements are written to the\nbinary log and will be replicated. The NO_WRITE_TO_BINLOG\nkeyword (LOCAL is an alias) will ensure the statement is not\nwritten to the binary log.\n \nWhen an index is recreated, the storage engine may use a\nconfigurable buffer in the process. Incrementing the buffer\nspeeds up the index creation. Aria and MyISAM allocate a\nbuffer whose size is defined by aria_sort_buffer_size or\nmyisam_sort_buffer_size, also used for ALTER TABLE.\n \nREPAIR TABLE is also supported for partitioned tables.\nHowever, the USE_FRM option cannot be used with this\nstatement\non a partitioned table.\n \n ALTER TABLE ... REPAIR PARTITION can be used\nto repair one or more partitions.\n \nThe Aria storage engine supports progress reporting for this\nstatement.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/repair-table/','','https://mariadb.com/kb/en/library/repair-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (257,20,'REPAIR VIEW','REPAIR VIEW was introduced in MariaDB 10.0.18 and MariaDB\n5.5.43.\n \nSyntax\n------ \nREPAIR [NO_WRITE_TO_BINLOG | LOCAL] VIEW view_name[,\nview_name] ... [FROM MYSQL]\n \nDescription\n----------- \nThe REPAIR VIEW statement was introduced to assist with\nfixing MDEV-6916, an issue introduced in MariaDB 5.2 where\nthe view algorithms were swapped compared to their MySQL on\ndisk representation. It checks whether the view algorithm is\ncorrect. It is run as part of mysql_upgrade, and should not\nnormally be required in regular use.\n \nBy default it corrects the checksum and if necessary adds\nthe mariadb-version field. If the optional FROM MYSQL clause\nis used, and no mariadb-version field is present, the MERGE\nand TEMPTABLE algorithms are toggled.\n \nBy default, REPAIR VIEW statements are written to the binary\nlog and will be replicated. The NO_WRITE_TO_BINLOG keyword\n(LOCAL is an alias) will ensure the statement is not written\nto the binary log.\n \nNote that REPAIR VIEW in MariaDB 10.0.18 and MariaDB 5.5.43\ncould crash the server (see MDEV-8115). Upgrade to a later\nversion.\n \n\n\nURL: https://mariadb.com/kb/en/library/repair-view/','','https://mariadb.com/kb/en/library/repair-view/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (258,21,'CREATE FUNCTION UDF','Syntax\n------ \nCREATE [OR REPLACE] [AGGREGATE] FUNCTION [IF NOT EXISTS]\nfunction_name\n RETURNS {STRING|INTEGER|REAL|DECIMAL}\n SONAME shared_library_name\n \nDescription\n----------- \nA user-defined function (UDF) is a way to extend MariaDB\nwith a new function\nthat works like a native (built-in) MariaDB function such as\nABS() or\nCONCAT().\n \nfunction_name is the name that should be used in SQL\nstatements to invoke\nthe function. \n \nTo create a function, you must have the INSERT privilege for\nthe\nmysql database. This is necessary because CREATE FUNCTION\nadds a row to the\nmysql.func system table that records the function\'s name,\ntype, and shared library name. If you do not have this\ntable, you should run\nthe mysql_upgrade command to create it.\n \nUDFs need to be written in C, C++ or another language that\nuses C calling\nconventions, MariaDB needs to have been dynamically\ncompiled, and your\noperating system must support dynamic loading.\n \nFor an example, see sql/udf_example.cc in the source tree.\nFor a collection of existing UDFs see\nhttp://www.mysqludf.org/.\n \nStatements making use of user-defined functions are not\nsafe for replication.\n \nFor creating a stored function as opposed to a user-defined\nfunction, see\nCREATE FUNCTION.\n \nFor valid identifiers to use as function names, see\nIdentifier Names.\n \nRETURNS\n \nThe RETURNS clause indicates the type of the function\'s\nreturn value, and can be one of STRING, INTEGER, REAL or\nDECIMAL. DECIMAL functions currently return string values\nand should be written like STRING functions.\n \nshared_library_name\n \nshared_library_name is the basename of the shared object\nfile that contains\nthe code that implements the function. The file must be\nlocated in the plugin\ndirectory. This directory is given by the value of the\nplugin_dir system variable. Note that\nbefore MariaDB/MySQL 5.1, the shared object could be located\nin any directory\nthat was searched by your system\'s dynamic linker.\n \nAGGREGATE\n \nAggregate functions are summary functions such as SUM() and\nAVG().\n \nAggregate UDF functions can be used as window functions.\n \nOR REPLACE\n \nThe OR REPLACE clause was added in MariaDB 10.1.3\n \nIf the optional OR REPLACE clause is used, it acts as a\nshortcut for:\n \nDROP FUNCTION IF EXISTS function_name;\n \nCREATE FUNCTION name ...;\n \nIF NOT EXISTS\n \nThe IF NOT EXISTS clause was added in MariaDB 10.1.3\n \nWhen the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the specified function\nalready exists. Cannot be used together with OR REPLACE.\n \nUpgrading a UDF\n \nTo upgrade the UDF\'s shared library, first run a\nDROP FUNCTION statement, then upgrade the shared library and\nfinally run the CREATE FUNCTION statement. If you upgrade\nwithout following\nthis process, you may crash the server.\n \nExamples\n-------- \nCREATE FUNCTION jsoncontains_path RETURNS integer SONAME\n\'ha_connect.so\';\n \nQuery OK, 0 rows affected (0.00 sec)\n \nOR REPLACE and IF NOT EXISTS:\n \nCREATE FUNCTION jsoncontains_path RETURNS integer SONAME\n\'ha_connect.so\';\n \nERROR 1125 (HY000): Function \'jsoncontains_path\' already\nexists\n \nCREATE OR REPLACE FUNCTION jsoncontains_path RETURNS integer\nSONAME \'ha_connect.so\';\n \nQuery OK, 0 rows affected (0.00 sec)\n \nCREATE FUNCTION IF NOT EXISTS jsoncontains_path RETURNS\ninteger SONAME \'ha_connect.so\';\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+---------------------------------------------+\n| Level | Code | Message |\n+-------+------+---------------------------------------------+\n| Note | 1125 | Function \'jsoncontains_path\' already\nexists |\n+-------+------+---------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/create-function-udf/','','https://mariadb.com/kb/en/library/create-function-udf/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (259,21,'DROP FUNCTION UDF','Syntax\n------ \nDROP FUNCTION [IF EXISTS] function_name\n \nDescription\n----------- \nThis statement drops the user-defined function (UDF) named\nfunction_name.\n \nTo drop a function, you must have the DELETE privilege for\nthe mysql database. This is because DROP FUNCTION removes\nthe row from the mysql.func system table that records the\nfunction\'s name, type and shared library name.\n \nFor dropping a stored function, see DROP FUNCTION.\n \nUpgrading a UDF\n \nTo upgrade the UDF\'s shared library, first run a DROP\nFUNCTION statement, then upgrade the shared library and\nfinally run the CREATE FUNCTION statement. If you upgrade\nwithout following this process, you may crash the server.\n \nExamples\n-------- \nDROP FUNCTION jsoncontains_path;\n \nIF EXISTS:\n \nDROP FUNCTION jsoncontains_path;\n \nERROR 1305 (42000): FUNCTION test.jsoncontains_path does not\nexist\n \nDROP FUNCTION IF EXISTS jsoncontains_path;\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+------------------------------------------------+\n| Level | Code | Message |\n+-------+------+------------------------------------------------+\n| Note | 1305 | FUNCTION test.jsoncontains_path does not\nexist |\n+-------+------+------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/drop-function-udf/','','https://mariadb.com/kb/en/library/drop-function-udf/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (260,21,'Creating User-Defined Functions','User-defined functions allow MariaDB to be extended with a\nnew function that works like a native (built-in) MariaDB\nfunction such as ABS() or CONCAT(). There are alternative\nways to add a new function: writing a native function (which\nrequires modifying and compiling the server source code), or\nwriting a stored function.\n \nStatements making use of user-defined functions are not safe\nfor replication.\n \nFunctions are written in C or C++, and to make use of them,\nthe operating system must support dynamic loading. \n \nEach new SQL function requires corresponding functions\nwritten in C/C++. In the list below, at least the main\nfunction - x() - and one other, are required. x should be\nreplaced by the name of the function you are creating.\n \nAll functions need to be thread-safe, so not global or\nstatic variables that change can be allocated. Memory is\nallocated in x_init()/ and freed in x_deinit(). \n \nSimple Functions\n \nx()\n \nRequired for all UDF\'s, this is where the results are\ncalculated.\n \nC/C++ type | SQL type | \n \nchar * | STRING | \n \nlong long | INTEGER | \n \ndouble | REAL | \n \nDECIMAL functions return string values, and so should be\nwritten accordingly. It is not possible to create ROW\nfunctions.\n \nx_init()\n \nInitialization function for x(). Can be used for the\nfollowing:\nCheck the number of arguments to X() (the SQL equivalent).\nVerify the argument types, or to force arguments to be of a\nparticular type after the function is called.\nSpecify whether the result can be NULL.\nSpecify the maximum result length.\nFor REAL functions, specify the maximum number of decimals\nfor the result.\nAllocate any required memory.\n To verify that the arguments are of a required type or,\nalternatively, to tell MySQL to coerce arguments to the\nrequired types when the main function is called.\n \nx_deinit()\n \nDe-initialization function for x(). Used to de-allocate\nmemory that was allocated in x_init().\n \nDescription\n----------- \nEach time the SQL function X() is called:\nMariaDB will first call the C/C++ initialization function,\nx_init(), assuming it exists. All setup will be performed,\nand if it returns an error, the SQL statement is aborted and\nno further functions are called.\nIf there is no x_init() function, or it has been called and\ndid not return an error, x() is then called once per row.\nAfter all rows have finished processing, x_deinit() is\ncalled, if present, to clean up by de-allocating any memory\nthat was allocated in x_init().\nSee User-defined Functions Calling Sequences for more\ndetails on the functions.\n \nAggregate Functions\n \nThe following functions are required for aggregate\nfunctions, such as AVG() and SUM(). \n \nx_clear()\n \nUsed to reset the current aggregate, but without inserting\nthe argument as the initial aggregate value for the new\ngroup.\n \nx_add()\n \nUsed to add the argument to the current aggregate. \n \nx_remove()\n \nStaring from MariaDB 10.4 it improves the support of window\nfunctions (so it is not obligatory to add it) and should\nremove the argument from the current aggregate.\n \nDescription\n----------- \nEach time the aggregate SQL function X() is called:\nMariaDB will first call the C/C++ initialization function,\nx_init(), assuming it exists. All setup will be performed,\nand if it returns an error, the SQL statement is aborted and\nno further functions are called.\nIf there is no x_init() function, or it has been called and\ndid not return an error, x() is then called once per row.\nAfter all rows have finished processing, x_deinit() is\ncalled, if present, to clean up by de-allocating any memory\nthat was allocated in x_init().\n \nMariaDB will first call the C/C++ initialization function,\nx_init(), assuming it exists. All setup will be performed,\nand if it returns an error, the SQL statement is aborted and\nno further functions are called.\nThe table is sorted according to the GROUP BY expression.\nx_clear() is called for the first row of each new group.\nx_add() is called once per row for each row in the same\ngroup.\nx() is called when the group changes, or after the last row,\nto get the aggregate result. \nThe latter three steps are repeated until all rows have been\nprocessed.\nAfter all rows have finished processing, x_deinit() is\ncalled, if present, to clean up by de-allocating any memory\nthat was allocated in x_init().\n \nExamples\n-------- \nFor an example, see sql/udf_example.cc in the source tree.\nFor a collection of existing UDFs see\nhttps://github.com/mysqludf.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/creating-user-defined-functions/','','https://mariadb.com/kb/en/library/creating-user-defined-functions/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (261,21,'User-Defined Functions Calling Sequences','The functions described in Creating User-defined Functions\nare expanded on this page. They are declared as follows:\n \nSimple Functions\n \nx()\n \nIf x() returns an integer, it is declared as follows:\n \nlong long x(UDF_INIT *initid, UDF_ARGS *args,\n char *is_null, char *error);\n \nIf x() returns a string (DECIMAL functions also return\nstring values), it is declared as follows:\n \nchar *x(UDF_INIT *initid, UDF_ARGS *args,\n char *result, unsigned long *length,\n char *is_null, char *error);\n \nIf x() returns a real, it is declared as follows:\n \ndouble x(UDF_INIT *initid, UDF_ARGS *args,\n char *is_null, char *error);\n \nx_init()\n \nmy_bool x_init(UDF_INIT *initid, UDF_ARGS *args, char\n*message);\n \nx_deinit()\n \nvoid x_deinit(UDF_INIT *initid);\n \nDescription\n----------- \ninitid is a parameter passed to all three functions that\npoints to a UDF_INIT structure, used for communicating\ninformation between the functions. Its structure members\nare:\nmy_bool maybe_null\nmaybe_null should be set to 1 if x_init can return a NULL\nvalue, Defaults to 1 if any arguments are declared\nmaybe_null.\n \nunsigned int decimals\nNumber of decimals after the decimal point. The default, if\nan explicit number of decimals is passed in the arguments to\nthe main function, is the maximum number of decimals, so if\n9.5, 9.55 and 9.555 are passed to the function, the default\nwould be three (based on 9.555, the maximum). If there are\nno explicit number of decimals, the default is set to 31, or\none more than the maximum for the DOUBLE, FLOAT and DECIMAL\ntypes. This default can be changed in the function to suit\nthe actual calculation.\n \nunsigned int max_length\nMaximum length of the result. For integers, the default is\n21. For strings, the length of the longest argument. For\nreals, the default is 13 plus the number of decimals\nindicated by initid->decimals. The length includes any signs\nor decimal points. Can also be set to 65KB or 16MB in order\nto return a BLOB. The memory remains unallocated, but this\nis used to decide on the data type to use if the data needs\nto be temporarily stored.\n \nchar *ptr\nA pointer for use as required by the function. Commonly,\ninitid->ptr is used to communicate allocated memory, with\nx_init() allocating the memory and assigning it to this\npointer, x() using it, and x_deinit() de-allocating it.\n \nmy_bool const_item\nShould be set to 1 in x_init() if x() always returns the\nsame value, otherwise 0.\n \n\nAggregate Functions\n \nx_clear()\n \nx_clear() is a required function for aggregate functions,\nand is declared as follows:\n \nvoid x_clear(UDF_INIT *initid, char *is_null, char *error);\n \nIt is called when the summary results need to be reset, that\nis at the beginning of each new group. but also to reset the\nvalues when there were no matching rows.\n \nis_null is set to point to CHAR(0) before calling x_clear().\n \nIn the case of an error, you can store the value to which\nthe error argument points (a single-byte variable, not a\nstring string buffer) in the variable.\n \nx_reset()\n \nx_reset() is declared as follows:\n \nvoid x_reset(UDF_INIT *initid, UDF_ARGS *args,\n char *is_null, char *error);\n \nIt is called on finding the first row in a new group. Should\nreset the summary variables, and then use UDF_ARGS as the\nfirst value in the group\'s internal summary value. The\nfunction is not required if the UDF interface uses\nx_clear().\n \nx_add()\n \nx_add() is declared as follows:\n \nvoid x_add(UDF_INIT *initid, UDF_ARGS *args,\n char *is_null, char *error);\n \nIt is called for all rows belonging to the same group, and\nshould be used to add the value in UDF_ARGS to the internal\nsummary variable.\n \nx_remove()\n \nx_remove() was added in MariaDB 10.4 and is declared as\nfollows (same as x_add()):\n \nvoid x_remove(UDF_INIT* initid, UDF_ARGS* args,\n char* is_null, char *error );\n \nIt adds more efficient support of aggregate UDFs as window\nfunctions. x_remove() should \"subtract\" the row (reverse\nx_add()). In MariaDB 10.4 aggregate UDFs will work as WINDOW\nfunctions without x_remove() but it will not be so\nefficient.\n \nIf x_remove() supported (defined) detected automatically.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/user-defined-functions-calling-sequences/','','https://mariadb.com/kb/en/library/user-defined-functions-calling-sequences/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (262,21,'User-Defined Functions Security','The MariaDB server imposes a number of limitations on\nuser-defined functions for security purposes.\nThe INSERT privilege for the mysql database is required to\nrun CREATE FUNCTION, as a record will be added to the\nmysql.func-table.\nThe DELETE privilege for the mysql database is required to\nrun DROP FUNCTION as the corresponding record will be\nremoved from the mysql.func-table.\nUDF object files can only be placed in the plugin directory,\nas specified by the value of the plugin_dir system variable.\nAt least one symbol, beyond the required x() - corresponding\nto an SQL function X()) - is required. These can be\nx_init(), x_deinit(), xxx_reset(), x_clear() and x_add()\nfunctions (see Creating User-defined Functions). The\nallow-suspicious-udfs mysqld option (by default unset)\nprovides a workaround, permitting only one symbol to be\nused. This is not recommended, as it opens the possibility\nof loading shared objects that are not legitimate\nuser-defined functions.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/user-defined-functions-security/','','https://mariadb.com/kb/en/library/user-defined-functions-security/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (263,21,'mysql.func Table','The mysql.func table stores information about user-defined\nfunctions (UDFs) created with the CREATE FUNCTION UDF\nstatement.\n \nIn MariaDB 10.4 and later, this table uses the Aria storage\nengine.\n \nMariaDB until 10.3\n \nIn MariaDB 10.3 and before, this table uses the MyISAM\nstorage engine.\n \nThe mysql.func table contains the following fields:\n \nField | Type | Null | Key | Default | Description | \n \nname | char(64) | NO | PRI | | UDF name | \n \nret | tinyint(1) | NO | | 0 | | \n \ndl | char(128) | NO | | | Shared library name | \n \ntype | enum(\'function\',\'aggregate\') | NO | | NULL |\nType, either function or aggregate. Aggregate functions are\nsummary functions such as SUM() and AVG(). | \n \nExample\n \nSELECT * FROM mysql.func;\n+------------------------------+-----+--------------+-----------+\n| name | ret | dl | type |\n+------------------------------+-----+--------------+-----------+\n| spider_direct_sql | 2 | ha_spider.so | function |\n| spider_bg_direct_sql | 2 | ha_spider.so | aggregate |\n| spider_ping_table | 2 | ha_spider.so | function |\n| spider_copy_tables | 2 | ha_spider.so | function |\n| spider_flush_table_mon_cache | 2 | ha_spider.so | function\n|\n+------------------------------+-----+--------------+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mysqlfunc-table/','','https://mariadb.com/kb/en/library/mysqlfunc-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (264,22,'AUTO_INCREMENT','Description\n----------- \nThe AUTO_INCREMENT attribute can be used to generate a\nunique identity for new rows. When you insert a new record\nto the table, and the auto_increment field is NULL or\nDEFAULT, the value will automatically be incremented. This\nalso applies to 0, unless the NO_AUTO_VALUE_ON_ZERO SQL_MODE\nis enabled.\n \nAUTO_INCREMENT columns start from 1 by default. The\nautomatically generated value can never be lower than 0.\n \nEach table can have only one AUTO_INCREMENT column. It must\ndefined as a key (not necessarily the PRIMARY KEY or UNIQUE\nkey). In some storage engines (including the default\nInnoDB), if the key consists of multiple columns, the\nAUTO_INCREMENT column must be the first column. Storage\nengines that permit the column to be placed elsewhere are\nAria, MyISAM, MERGE, Spider, TokuDB, BLACKHOLE, FederatedX\nand Federated.\n \nCREATE TABLE animals (\n id MEDIUMINT NOT NULL AUTO_INCREMENT,\n name CHAR(30) NOT NULL,\n PRIMARY KEY (id)\n );\n \nINSERT INTO animals (name) VALUES\n (\'dog\'),(\'cat\'),(\'penguin\'),\n (\'fox\'),(\'whale\'),(\'ostrich\');\n \nSELECT * FROM animals;\n \n+----+---------+\n| id | name |\n+----+---------+\n| 1 | dog |\n| 2 | cat |\n| 3 | penguin |\n| 4 | fox |\n| 5 | whale |\n| 6 | ostrich |\n+----+---------+\n \nSERIAL is an alias for BIGINT UNSIGNED NOT NULL\nAUTO_INCREMENT UNIQUE.\n \nCREATE TABLE t (id SERIAL, c CHAR(1)) ENGINE=InnoDB;\n \nSHOW CREATE TABLE t \\G\n*************************** 1. row\n***************************\n Table: t\nCreate Table: CREATE TABLE `t` (\n `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,\n `c` char(1) DEFAULT NULL,\n UNIQUE KEY `id` (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\n \nSetting or Changing the Auto_Increment Value\n \nYou can use an ALTER TABLE statement to assign a new value\nto the auto_increment table option, or set the insert_id\nserver system variable to change the next AUTO_INCREMENT\nvalue inserted by the current session.\n \nLAST_INSERT_ID() can be used to see the last AUTO_INCREMENT\nvalue inserted by the current session.\n \nALTER TABLE animals AUTO_INCREMENT=8;\n \nINSERT INTO animals (name) VALUES (\'aardvark\');\n \nSELECT * FROM animals;\n \n+----+-----------+\n| id | name |\n+----+-----------+\n| 1 | dog |\n| 2 | cat |\n| 3 | penguin |\n| 4 | fox |\n| 5 | whale |\n| 6 | ostrich |\n| 8 | aardvark |\n+----+-----------+\n \nSET insert_id=12;\n \nINSERT INTO animals (name) VALUES (\'gorilla\');\n \nSELECT * FROM animals;\n \n+----+-----------+\n| id | name |\n+----+-----------+\n| 1 | dog |\n| 2 | cat |\n| 3 | penguin |\n| 4 | fox |\n| 5 | whale |\n| 6 | ostrich |\n| 8 | aardvark |\n| 12 | gorilla |\n+----+-----------+\n \nInnoDB/XtraDB\n \nUntil MariaDB 10.2.3, InnoDB and XtraDB used an\nauto-increment counter that is stored in memory. When the\nserver restarts, the counter is re-initialized to the\nhighest value used in the table, which cancels the effects\nof any AUTO_INCREMENT = N option in the table statements.\n \nFrom MariaDB 10.2.4, this restriction has been lifted and\nAUTO_INCREMENT is persistent.\n \nSee also AUTO_INCREMENT Handling in XtraDB/InnoDB.\n \nSetting Explicit Values\n \nIt is possible to specify a value for an AUTO_INCREMENT\ncolumn. The value must not exist in the key.\n \nIf the new value is higher than the current maximum value,\nthe AUTO_INCREMENT value is updated, so the next value will\nbe higher. If the new value is lower than the current\nmaximum value, the AUTO_INCREMENT value remains unchanged.\n \nThe following example demonstrates these behaviours:\n \nCREATE TABLE t (id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY\nKEY) ENGINE = InnoDB;\n \nINSERT INTO t VALUES (NULL);\nSELECT id FROM t;\n \n+----+\n| id |\n+----+\n| 1 |\n+----+\n \nINSERT INTO t VALUES (10); -- higher value\nSELECT id FROM t;\n \n+----+\n| id |\n+----+\n| 1 |\n| 10 |\n+----+\n \nINSERT INTO t VALUES (2); -- lower value\nINSERT INTO t VALUES (NULL); -- auto value\nSELECT id FROM t;\n \n+----+\n| id |\n+----+\n| 1 |\n| 2 |\n| 10 |\n| 11 |\n+----+\n \nThe ARCHIVE storage engine does not allow to insert a value\nthat is lower than the current maximum.\n \nMissing Values\n \nAn AUTO_INCREMENT column normally has missing values. This\nhappens because if a row is deleted, or an AUTO_INCREMENT\nvalue is explicitly updated, old values are never re-used.\nThe REPLACE statement also deletes a row, and its value is\nwasted. With InnoDB, values can be reserved by a\ntransaction; but if the transaction fails (for example,\nbecause of a ROLLBACK) the reserved value will be lost.\n \nThus AUTO_INCREMENT values can be used to sort results in a\nchronological order, but not to create a numeric sequence.\n \nReplication\n \nTo make master-master or Galera safe to use AUTO_INCREMENT\none should use the system variables \n auto_increment_increment and auto_increment_offset to\ngenerate unique values for each server.\n \nCHECK Constraints, DEFAULT Values and Virtual Columns\n \nFrom MariaDB 10.2.6 auto_increment columns are no longer\npermitted in CHECK constraints, DEFAULT value expressions\nand virtual columns. They were permitted in earlier\nversions, but did not work correctly. See MDEV-11117.\n \n\n\nURL: https://mariadb.com/kb/en/library/auto_increment/','','https://mariadb.com/kb/en/library/auto_increment/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (265,22,'BIGINT','Syntax\n------ \nBIGINT[(M)] [SIGNED | UNSIGNED | ZEROFILL]\n \nDescription\n----------- \nA large integer. The signed range is -9223372036854775808 to\n9223372036854775807. The unsigned range is 0 to\n18446744073709551615.\n \nIf a column has been set to ZEROFILL, all values will be\nprepended by zeros so that the BIGINT value contains a\nnumber of M digits.\n \nNote: If the ZEROFILL attribute has been specified, the\ncolumn will automatically become UNSIGNED.\n \nFor more details on the attributes, see Numeric Data Type\nOverview.\n \nSERIAL is an alias for:\n \nBIGINT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE\n \nExamples\n-------- \nCREATE TABLE bigints (a BIGINT,b BIGINT UNSIGNED,c BIGINT\nZEROFILL);\n \nINSERT INTO bigints VALUES (-10,-10,-10);\nQuery OK, 1 row affected, 2 warnings (0.08 sec)\nWarning (Code 1264): Out of range value for column \'b\' at\nrow 1\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO bigints VALUES (-10,10,-10);Query OK, 1 row\naffected, 1 warning (0.08 sec)\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO bigints VALUES (-10,10,10);\n \nINSERT INTO bigints VALUES\n(9223372036854775808,9223372036854775808,9223372036854775808);\nQuery OK, 1 row affected, 1 warning (0.07 sec)\nWarning (Code 1264): Out of range value for column \'a\' at\nrow 1\n \nINSERT INTO bigints VALUES\n(9223372036854775807,9223372036854775808,9223372036854775808);\n \nSELECT * FROM bigints;\n+---------------------+---------------------+----------------------+\n| a | b | c |\n+---------------------+---------------------+----------------------+\n| -10 | 0 | 00000000000000000000 |\n| -10 | 10 | 00000000000000000000 |\n| -10 | 10 | 00000000000000000010 |\n| 9223372036854775807 | 9223372036854775808 |\n09223372036854775808 |\n| 9223372036854775807 | 9223372036854775808 |\n09223372036854775808 |\n+---------------------+---------------------+----------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/bigint/','','https://mariadb.com/kb/en/library/bigint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (266,22,'BINARY','Syntax\n------ \nBINARY(M)\n \nDescription\n----------- \nThe BINARY type is similar to the CHAR type, but stores\nbinary\nbyte strings rather than non-binary character strings. M\nrepresents the\ncolumn length in bytes.\n \nIt contains no character set, and comparison and sorting are\nbased on the numeric value of the bytes.\n \nIf the maximum length is exceeded, and SQL strict mode is\nnot enabled , the extra characters will be dropped with a\nwarning. If strict mode is enabled, an error will occur.\n \nBINARY values are right-padded with 0x00 (the zero byte) to\nthe specified length when inserted. The padding is not\nremoved on select, so this needs to be taken into account\nwhen sorting and comparing, where all bytes are significant.\nThe zero byte, 0x00 is less than a space for comparison\npurposes.\n \nExamples\n-------- \nInserting too many characters, first with strict mode off,\nthen with it on:\n \nCREATE TABLE bins (a BINARY(10));\n \nINSERT INTO bins VALUES(\'12345678901\');\nQuery OK, 1 row affected, 1 warning (0.04 sec)\n \nSELECT * FROM bins;\n \n+------------+\n| a |\n+------------+\n| 1234567890 |\n+------------+\n \nSET sql_mode=\'STRICT_ALL_TABLES\';\n \nINSERT INTO bins VALUES(\'12345678901\');\nERROR 1406 (22001): Data too long for column \'a\' at row 1\n \nSorting is performed with the byte value:\n \nTRUNCATE bins;\n \nINSERT INTO bins VALUES(\'A\'),(\'B\'),(\'a\'),(\'b\');\n \nSELECT * FROM bins ORDER BY a;\n \n+------+\n| a |\n+------+\n| A |\n| B |\n| a |\n| b |\n+------+\n \nUsing CAST to sort as a CHAR instead:\n \nSELECT * FROM bins ORDER BY CAST(a AS CHAR);\n+------+\n| a |\n+------+\n| a |\n| A |\n| b |\n| B |\n+------+\n \nThe field is a BINARY(10), so padding of two \'\\0\'s are\ninserted, causing comparisons that don\'t take this into\naccount to fail:\n \nTRUNCATE bins;\n \nINSERT INTO bins VALUES(\'12345678\');\n \nSELECT a = \'12345678\', a = \'12345678\\0\\0\' from bins;\n \n+----------------+--------------------+\n| a = \'12345678\' | a = \'12345678\\0\\0\' |\n+----------------+--------------------+\n| 0 | 1 |\n+----------------+--------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/binary/','','https://mariadb.com/kb/en/library/binary/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (267,22,'BIT','Syntax\n------ \nBIT[(M)]\n \nDescription\n----------- \nA bit-field type. M indicates the number of bits per value,\nfrom 1 to\n64. The default is 1 if M is omitted.\n \nBit values can be inserted with b\'value\' notation, where\nvalue is the bit value in 0\'s and 1\'s.\n \nBit fields are automatically zero-padded from the left to\nthe full length of the bit, so for example in a BIT(4)\nfield, \'10\' is equivalent to \'0010\'.\n \nBits are returned as binary, so to display them, either add\n0, or use a function such as HEX, OCT or BIN to convert\nthem.\n \nExamples\n-------- \nCREATE TEMPORARY TABLE b ( b1 BIT(8) );\nINSERT INTO b VALUES\n(b\'11111111\'),(b\'01010101\'),(b\'1111111111111\');\nQuery OK, 3 rows affected, 1 warning (0.10 sec)\nRecords: 3 Duplicates: 0 Warnings: 1\n \nSHOW WARNINGS;\n+---------+------+---------------------------------------------+\n| Level | Code | Message |\n+---------+------+---------------------------------------------+\n| Warning | 1264 | Out of range value for column \'b1\' at\nrow 3 |\n+---------+------+---------------------------------------------+\n \nSELECT b1+0, HEX(b1), OCT(b1), BIN(b1) FROM b;\n+------+---------+---------+----------+\n| b1+0 | HEX(b1) | OCT(b1) | BIN(b1) |\n+------+---------+---------+----------+\n| 255 | FF | 377 | 11111111 |\n| 85 | 55 | 125 | 1010101 |\n| 255 | FF | 377 | 11111111 |\n+------+---------+---------+----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/bit/','','https://mariadb.com/kb/en/library/bit/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (268,22,'BLOB','Syntax\n------ \nBLOB[(M)]\n \nDescription\n----------- \nA BLOB column with a maximum length of 65,535 (216 - 1)\nbytes. Each\nBLOB value is stored using a two-byte length prefix that\nindicates the\nnumber of bytes in the value.\n \nAn optional length M can be given for this type. If this is\ndone,\nMariaDB creates the column as the smallest BLOB type large\nenough to\nhold values M bytes long.\n \nBLOBS can also be used to store dynamic columns.\n \nBefore MariaDB 10.2.1, BLOB and TEXT columns could not be\nassigned a DEFAULT value. This restriction was lifted in\nMariaDB 10.2.1.\n \nIndexing\n \nIn MariaDB 10.4, it is possible to set a Unique index on a\ncolumn that uses the BLOB data type. In previous releases\nthis was not possible, as the index would only guarantee the\nuniqueness of a fixed number of characters.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, BLOB is a synonym for\nLONGBLOB.\n \n\n\nURL: https://mariadb.com/kb/en/library/blob/','','https://mariadb.com/kb/en/library/blob/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (269,22,'BLOB and TEXT Data Types','Description\n----------- \nA BLOB is a binary large object that can hold a variable\namount of\ndata. The four BLOB types are \nTINYBLOB,\nBLOB, \nMEDIUMBLOB, and\nLONGBLOB.\n \nThese differ only in the maximum length of the values they\ncan hold. \n \nThe TEXT types are \nTINYTEXT,\nTEXT,\nMEDIUMTEXT, and\nLONGTEXT.\nJSON (alias for LONGTEXT)\n \nThese correspond to the four BLOB types and have the same\nmaximum lengths and storage requirements.\n \nStarting from MariaDB 10.2.1, BLOB and TEXT columns can have\na DEFAULT value.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/blob-and-text-data-types/','','https://mariadb.com/kb/en/library/blob-and-text-data-types/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (270,22,'BOOLEAN','Syntax\n------ \nBOOL, BOOLEAN\n \nDescription\n----------- \nThese types are synonyms for TINYINT(1). \nA value of zero is considered false. Non-zero values are\nconsidered true:\n \nmysql> SELECT IF(0, \'true\', \'false\');\n+------------------------+\n| IF(0, \'true\', \'false\') |\n+------------------------+\n| false |\n+------------------------+\n \nmysql> SELECT IF(1, \'true\', \'false\');\n+------------------------+\n| IF(1, \'true\', \'false\') |\n+------------------------+\n| true |\n+------------------------+\n \nmysql> SELECT IF(2, \'true\', \'false\');\n+------------------------+\n| IF(2, \'true\', \'false\') |\n+------------------------+\n| true |\n+------------------------+\n \nHowever, the values TRUE and FALSE are merely aliases for 1\nand 0,\nrespectively, as shown here:\n \nmysql> SELECT IF(0 = FALSE, \'true\', \'false\');\n \n+--------------------------------+\n| IF(0 = FALSE, \'true\', \'false\') |\n+--------------------------------+\n| true |\n+--------------------------------+\n \nmysql> SELECT IF(1 = TRUE, \'true\', \'false\');\n+-------------------------------+\n| IF(1 = TRUE, \'true\', \'false\') |\n+-------------------------------+\n| true |\n+-------------------------------+\n \nmysql> SELECT IF(2 = TRUE, \'true\', \'false\');\n+-------------------------------+\n| IF(2 = TRUE, \'true\', \'false\') |\n+-------------------------------+\n| false |\n+-------------------------------+\n \nmysql> SELECT IF(2 = FALSE, \'true\', \'false\');\n+--------------------------------+\n| IF(2 = FALSE, \'true\', \'false\') |\n+--------------------------------+\n| false |\n+--------------------------------+\n \nUNKNOWN is an alias for NULL.\n \nThe last two statements display the results shown because 2\nis equal\nto neither 1 nor 0.\n \n\n\nURL: https://mariadb.com/kb/en/library/boolean/','','https://mariadb.com/kb/en/library/boolean/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (271,22,'CHAR','This article covers the CHAR data type. See CHAR Function\nfor the function.\n \nSyntax\n------ \n[NATIONAL] CHAR[(M)] [CHARACTER SET charset_name] [COLLATE\ncollation_name]\n \nDescription\n----------- \nA fixed-length string that is always right-padded with\nspaces to the specified\nlength when stored. M represents the column length in\ncharacters. The range\nof M is 0 to 255. If M is omitted, the length is 1.\n \nCHAR(0) columns can contain 2 values: an empty string or\nNULL. Such columns cannot be part of an index. The CONNECT\nstorage engine does not support CHAR(0).\n \nNote: Trailing spaces are removed when CHAR values are\nretrieved\nunless the PAD_CHAR_TO_FULL_LENGTH SQL mode is enabled.\n \nBefore MariaDB 10.2, all collations were of type PADSPACE,\nmeaning that CHAR (as well as VARCHAR and TEXT) values are\ncompared without regard for trailing spaces. This does not\napply to the LIKE pattern-matching operator, which takes\ninto account trailing spaces.\n \nIf a unique index consists of a column where trailing pad\ncharacters are stripped or ignored, inserts into that column\nwhere values differ only by the number of trailing pad\ncharacters will result in a duplicate-key error.\n \nExamples\n-------- \nTrailing spaces:\n \nCREATE TABLE strtest (c CHAR(10));\nINSERT INTO strtest VALUES(\'Maria \');\n \nSELECT c=\'Maria\',c=\'Maria \' FROM strtest;\n \n+-----------+--------------+\n| c=\'Maria\' | c=\'Maria \' |\n+-----------+--------------+\n| 1 | 1 |\n+-----------+--------------+\n \nSELECT c LIKE \'Maria\',c LIKE \'Maria \' FROM strtest;\n \n+----------------+-------------------+\n| c LIKE \'Maria\' | c LIKE \'Maria \' |\n+----------------+-------------------+\n| 1 | 0 |\n+----------------+-------------------+\n \nNO PAD Collations\n \nNO PAD collations regard trailing spaces as normal\ncharacters. You can get a list of all NO PAD collations by\nquerying the Information Schema Collations table, for\nexample:\n \nSELECT collation_name FROM information_schema.collations \n WHERE collation_name LIKE \"%nopad%\";\n \n+------------------------------+\n| collation_name |\n+------------------------------+\n| big5_chinese_nopad_ci |\n| big5_nopad_bin |\n...\n \n\n\nURL: https://mariadb.com/kb/en/library/char/','','https://mariadb.com/kb/en/library/char/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (272,22,'CHAR BYTE','Description\n----------- \nThe CHAR BYTE data type is an alias for the \nBINARY data type. This is a\ncompatibility feature.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/char-byte/','','https://mariadb.com/kb/en/library/char-byte/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (273,22,'DATE','Syntax\n------ \nDATE\n \nDescription\n----------- \nA date. The supported range is \'1000-01-01\' to\n\'9999-12-31\'. MariaDB\ndisplays DATE values in \'YYYY-MM-DD\' format, but can be\nassigned dates in looser formats, including strings or\nnumbers, as long as they make sense. These include a short\nyear, YY-MM-DD, no delimiters, YYMMDD, or any other\nacceptable delimiter, for example YYYY/MM/DD. For details,\nsee date and time literals.\n \n\'0000-00-00\' is a permitted special value (zero-date),\nunless the NO_ZERO_DATE SQL_MODE is used. Also, individual\ncomponents of a date can be set to 0 (for example:\n\'2015-00-12\'), unless the NO_ZERO_IN_DATE SQL_MODE is\nused. In many cases, the result of en expression involving a\nzero-date, or a date with zero-parts, is NULL. If the\nALLOW_INVALID_DATES SQL_MODE is enabled, if the day part is\nin the range between 1 and 31, the date does not produce any\nerror, even for months that have less than 31 days.\n \nExamples\n-------- \nCREATE TABLE t1 (d DATE);\n \nINSERT INTO t1 VALUES (\"2010-01-12\"), (\"2011-2-28\"),\n(\'120314\'),(\'13*04*21\');\n \nSELECT * FROM t1;\n \n+------------+\n| d |\n+------------+\n| 2010-01-12 |\n| 2011-02-28 |\n| 2012-03-14 |\n| 2013-04-21 |\n+------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/date/','','https://mariadb.com/kb/en/library/date/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (274,22,'DATETIME','Syntax\n------ \nDATETIME [(microsecond precision)]\n \nDescription\n----------- \nA date and time combination. The supported range is\n\'1000-01-01 00:00:00.000000\' to \'9999-12-31\n23:59:59.999999\'.\nMariaDB displays DATETIME values in \'YYYY-MM-DD HH:MM:SS\'\nformat, but\nallows assignment of values to DATETIME columns using either\nstrings or\nnumbers. For details, see date and time literals.\n \nThe microsecond precision can be from 0-6. If not specified\n0 is used.\n \n\'0000-00-00\' is a permitted special value (zero-date),\nunless the NO_ZERO_DATE SQL_MODE is used. Also, individual\ncomponents of a date can be set to 0 (for example:\n\'2015-00-12\'), unless the NO_ZERO_IN_DATE SQL_MODE is\nused. In many cases, the result of en expression involving a\nzero-date, or a date with zero-parts, is NULL. If the\nALLOW_INVALID_DATES SQL_MODE is enabled, if the day part is\nin the range between 1 and 31, the date does not produce any\nerror, even for months that have less than 31 days.\n \nSince MariaDB 10.0.1, DATETIME columns also accept\nCURRENT_TIMESTAMP as the default value.\n \nMariaDB 10.1.2 introduced the --mysql56-temporal-format\noption, on by default, which allows MariaDB to store\nDATETMEs using the same low-level format MySQL 5.6 uses. For\nmore information, see Internal Format, below.\n \nFor storage requirements, see Data Type Storage\nRequirements.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, DATE with a time portion\nis a synonym for DATETIME.\n \nInternal Format\n \nIn MariaDB 10.1.2 a new temporal format was introduced from\nMySQL 5.6 that alters how the TIME, DATETIME and TIMESTAMP\ncolumns operate at lower levels. These changes allow these\ntemporal data types to have fractional parts and negative\nvalues. You can disable this feature using the\nmysql56_temporal_format system variable.\n \nTables that include TIMESTAMP values that were created on an\nolder version of MariaDB or that were created while the\nmysql56_temporal_format system variable was disabled\ncontinue to store data using the older data type format.\n \nIn order to update table columns from the older format to\nthe newer format, execute an ALTER TABLE... MODIFY COLUMN\nstatement that changes the column to the *same* data type.\nThis change may be needed if you want to export the table\'s\ntablespace and import it onto a server that has\nmysql56_temporal_format=ON set (see MDEV-15225).\n \nFor instance, if you have a DATETIME column in your table: \n \nSHOW VARIABLES LIKE \'mysql56_temporal_format\';\n \n+-------------------------+-------+\n| Variable_name | Value |\n+-------------------------+-------+\n| mysql56_temporal_format | ON |\n+-------------------------+-------+\n \nALTER TABLE example_table MODIFY ts_col DATETIME;\n \nWhen MariaDB executes the ALTER TABLE statement, it converts\nthe data from the older temporal format to the newer one. \n \nIn the event that you have several tables and columns using\ntemporal data types that you want to switch over to the new\nformat, make sure the system variable is enabled, then\nperform a dump and restore using mysqldump. The columns\nusing relevant temporal data types are restored using the\nnew temporal format.\n \nExamples\n-------- \nCREATE TABLE t1 (d DATETIME);\n \nINSERT INTO t1 VALUES (\"2011-03-11\"), (\"2012-04-19\n13:08:22\"),\n (\"2013-07-18 13:44:22.123456\");\n \nSELECT * FROM t1;\n \n+---------------------+\n| d |\n+---------------------+\n| 2011-03-11 00:00:00 |\n| 2012-04-19 13:08:22 |\n| 2013-07-18 13:44:22 |\n+---------------------+\n \nCREATE TABLE t2 (d DATETIME(6));\n \nINSERT INTO t2 VALUES (\"2011-03-11\"), (\"2012-04-19\n13:08:22\"),\n (\"2013-07-18 13:44:22.123456\");\n \nSELECT * FROM t2;\n \n+----------------------------+\n| d |\n+----------------------------+\n| 2011-03-11 00:00:00.000000 |\n| 2012-04-19 13:08:22.000000 |\n| 2013-07-18 13:44:22.123456 |\n+----------------------------++\n \nStrings used in datetime context are automatically converted\nto datetime(6). If you want to have a datetime without\nseconds, you should use CONVERT(..,datetime).\n \nSELECT CONVERT(\'2007-11-30 10:30:19\',datetime);\n+-----------------------------------------+\n| CONVERT(\'2007-11-30 10:30:19\',datetime) |\n+-----------------------------------------+\n| 2007-11-30 10:30:19 |\n+-----------------------------------------+\n \nSELECT CONVERT(\'2007-11-30 10:30:19\',datetime(6));\n+--------------------------------------------+\n| CONVERT(\'2007-11-30 10:30:19\',datetime(6)) |\n+--------------------------------------------+\n| 2007-11-30 10:30:19.000000 |\n+--------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/datetime/','','https://mariadb.com/kb/en/library/datetime/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (275,22,'DECIMAL','Syntax\n------ \nDECIMAL[(M[,D])] [SIGNED | UNSIGNED | ZEROFILL]\n \nDescription\n----------- \nA packed \"exact\" fixed-point number. M is the total number\nof digits (the\nprecision) and D is the number of digits after the decimal\npoint (the\nscale). The decimal point and (for negative numbers) the\n\"-\" sign are not\ncounted in M. If D is 0, values have no decimal point or\nfractional\npart and on INSERT the value will be rounded to the nearest\nDECIMAL. The maximum number of digits (M) for DECIMAL is 65.\nThe maximum number of supported decimals (D) is 30 before\nMariadB 10.2.1 and 38 afterwards. If D is omitted, the\ndefault is 0. If M is omitted, the default is 10.\n \nUNSIGNED, if specified, disallows negative values.\n \nZEROFILL, if specified, pads the number with zeros, up to\nthe total number\nof digits specified by M.\n \nAll basic calculations (+, -, *, /) with DECIMAL columns are\ndone with\na precision of 65 digits.\n \nFor more details on the attributes, see Numeric Data Type\nOverview.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, NUMBER is a synonym.\n \nExamples\n-------- \nCREATE TABLE t1 (d DECIMAL UNSIGNED ZEROFILL);\n \nINSERT INTO t1 VALUES (1),(2),(3),(4.0),(5.2),(5.7);\nQuery OK, 6 rows affected, 2 warnings (0.16 sec)\nRecords: 6 Duplicates: 0 Warnings: 2\n \nNote (Code 1265): Data truncated for column \'d\' at row 5\nNote (Code 1265): Data truncated for column \'d\' at row 6\n \nSELECT * FROM t1;\n \n+------------+\n| d |\n+------------+\n| 0000000001 |\n| 0000000002 |\n| 0000000003 |\n| 0000000004 |\n| 0000000005 |\n| 0000000006 |\n+------------+\n \nINSERT INTO t1 VALUES (-7);\nERROR 1264 (22003): Out of range value for column \'d\' at\nrow 1\n \n\n\nURL: https://mariadb.com/kb/en/library/decimal/','','https://mariadb.com/kb/en/library/decimal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (276,22,'ENUM','Syntax\n------ \nENUM(\'value1\',\'value2\',...) [CHARACTER SET charset_name]\n[COLLATE collation_name]\n \nDescription\n----------- \nAn enumeration. A string object that can have only one\nvalue, chosen\nfrom the list of values \'value1\', \'value2\', ..., NULL or\nthe special \n\'\' error value. In theory, an ENUM column can have a\nmaximum of 65,535 distinct\nvalues; in practice, the real maximum depends on many\nfactors. ENUM values are represented internally as integers.\n \nTrailing spaces are automatically stripped from ENUM values\non table creation.\n \nENUMs require relatively little storage space compared to\nstrings, either one or two bytes depending on the number of\nenumeration values.\n \nNULL and empty values\n \nAn ENUM can also contain NULL and empty values. If the ENUM\ncolumn is declared to permit NULL values, NULL becomes a\nvalid value, as well as the default value (see below). If\nstrict SQL Mode is not enabled, and an invalid value is\ninserted into an ENUM, a special empty string, with an index\nvalue of zero (see Numeric index, below), is inserted, with\na warning. This may be confusing, because the empty string\nis also a possible value, and the only difference if that in\nthis case its index is not 0. Inserting will fail with an\nerror if strict mode is active.\n \nIf a DEFAULT clause is missing, the default value will be:\nNULL is the column is nullable;\notherwise, the first value in the enumaration.\n \nNumeric index\n \nENUM values are indexed numerically in the order they are\ndefined, and sorting will be performed in this numeric\norder. We suggest not using ENUM to store numerals, as there\nis little to no storage space benefit, and it is easy to\nconfuse the enum integer with the enum numeral value by\nleaving out the quotes.\n \nAn ENUM defined as ENUM(\'apple\',\'orange\',\'pear\') would\nhave the following index values:\n \nIndex | Value | \n \nNULL | NULL | \n \n0 | \'\' | \n \n1 | \'apple\' | \n \n2 | \'orange\' | \n \n3 | \'pear\' | \n \nExamples\n-------- \nCREATE TABLE fruits (\n id INT NOT NULL auto_increment PRIMARY KEY,\n fruit ENUM(\'apple\',\'orange\',\'pear\'),\n bushels INT);\n \nDESCRIBE fruits;\n \n+---------+-------------------------------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+---------+-------------------------------+------+-----+---------+----------------+\n| id | int(11) | NO | PRI | NULL | auto_increment |\n| fruit | enum(\'apple\',\'orange\',\'pear\') | YES | | NULL\n| |\n| bushels | int(11) | YES | | NULL | |\n+---------+-------------------------------+------+-----+---------+----------------+\n \nINSERT INTO fruits\n (fruit,bushels) VALUES\n (\'pear\',20),\n (\'apple\',100),\n (\'orange\',25);\n \nINSERT INTO fruits\n (fruit,bushels) VALUES\n (\'avocado\',10);\nERROR 1265 (01000): Data truncated for column \'fruit\' at\nrow 1\n \nSELECT * FROM fruits;\n \n+----+--------+---------+\n| id | fruit | bushels |\n+----+--------+---------+\n| 1 | pear | 20 |\n| 2 | apple | 100 |\n| 3 | orange | 25 |\n+----+--------+---------+\n \nSelecting by numeric index:\n \nSELECT * FROM fruits WHERE fruit=2;\n \n+----+--------+---------+\n| id | fruit | bushels |\n+----+--------+---------+\n| 3 | orange | 25 |\n+----+--------+---------+\n \nSorting is according to the index value:\n \nCREATE TABLE enums (a ENUM(\'2\',\'1\'));\n \nINSERT INTO enums VALUES (\'1\'),(\'2\');\n \nSELECT * FROM enums ORDER BY a ASC;\n \n+------+\n| a |\n+------+\n| 2 |\n| 1 |\n+------+\n \nIt\'s easy to get confused between returning the enum\ninteger with the stored value, so we don\'t suggest using\nENUM to store numerals. The first example returns the 1st\nindexed field (\'2\' has an index value of 1, as it\'s\ndefined first), while the second example returns the string\nvalue \'1\'.\n \nSELECT * FROM enums WHERE a=1;\n \n+------+\n| a |\n+------+\n| 2 |\n+------+\n \nSELECT * FROM enums WHERE a=\'1\';\n \n+------+\n| a |\n+------+\n| 1 |\n+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/enum/','','https://mariadb.com/kb/en/library/enum/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (277,22,'DOUBLE','Syntax\n------ \nDOUBLE[(M,D)] [SIGNED | UNSIGNED | ZEROFILL]\nDOUBLE PRECISION[(M,D)] [SIGNED | UNSIGNED | ZEROFILL]\nREAL[(M,D)] [SIGNED | UNSIGNED | ZEROFILL]\n \nDescription\n----------- \nA normal-size (double-precision) floating-point number (see\nFLOAT for a single-precision floating-point number).\n \nAllowable values are:\n-1.7976931348623157E+308 to -2.2250738585072014E-308\n0\n2.2250738585072014E-308 to 1.7976931348623157E+308\n \nThese are the theoretical limits, based on the IEEE\nstandard. The actual range\nmight be slightly smaller depending on your hardware or\noperating system.\n \nM is the total number of digits and D is the number of\ndigits\nfollowing the decimal point. If M and D are omitted, values\nare stored\nto the limits allowed by the hardware. A double-precision\nfloating-point number is accurate to approximately 15\ndecimal places.\n \nUNSIGNED, if specified, disallows negative values.\n \nZEROFILL, if specified, pads the number with zeros, up to\nthe total number\nof digits specified by M.\n \nREAL and DOUBLE PRECISION are synonyms, unless the\nREAL_AS_FLOAT SQL mode is enabled, in which case REAL is a\nsynonym for FLOAT rather than DOUBLE.\n \nSee Floating Point Accuracy for issues when using\nfloating-point numbers.\n \nFor more details on the attributes, see Numeric Data Type\nOverview.\n \nExamples\n-------- \nCREATE TABLE t1 (d DOUBLE(5,0) zerofill);\n \nINSERT INTO t1 VALUES (1),(2),(3),(4);\n \nSELECT * FROM t1;\n \n+-------+\n| d |\n+-------+\n| 00001 |\n| 00002 |\n| 00003 |\n| 00004 |\n+-------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/double/','','https://mariadb.com/kb/en/library/double/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (278,22,'FLOAT','Syntax\n------ \nFLOAT[(M,D)] [SIGNED | UNSIGNED | ZEROFILL]\n \nDescription\n----------- \nA small (single-precision) floating-point number (see DOUBLE\nfor a regular-size floating point number). Allowable values\nare:\n-3.402823466E+38 to -1.175494351E-38\n0\n1.175494351E-38 to 3.402823466E+38. \n \nThese are the theoretical limits, based on the IEEE \nstandard. The actual range might be slightly smaller\ndepending on your\nhardware or operating system.\n \nM is the total number of digits and D is the number of\ndigits\nfollowing the decimal point. If M and D are omitted, values\nare stored\nto the limits allowed by the hardware. A single-precision\nfloating-point number is accurate to approximately 7 decimal\nplaces.\n \nUNSIGNED, if specified, disallows negative values.\n \nUsing FLOAT might give you some unexpected problems because\nall\ncalculations in MariaDB are done with double precision. See\nFloating Point Accuracy.\n \nFor more details on the attributes, see Numeric Data Type\nOverview.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/float/','','https://mariadb.com/kb/en/library/float/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (279,22,'Geometry Types','Description\n----------- \nMariaDB provides a standard way of creating spatial columns\nfor geometry types,\nfor example, with CREATE TABLE or ALTER TABLE.\nCurrently, spatial columns are supported for MyISAM, InnoDB,\nNDB, and ARCHIVE\ntables. See also SPATIAL INDEX.\n \nThe basic geometry type is GEOMETRY. But the type can be\nmore specific. The following types are supported:\n \nGeometry Types | \n \nPOINT | \n \nLINESTRING | \n \nPOLYGON | \n \nMULTIPOINT | \n \nMULTILINESTRING | \n \nMULTIPOLYGON | \n \nGEOMETRYCOLLECTION | \n \nGEOMETRY | \n \nExamples\n-------- \nNote: For clarity, only one type is listed per table in the\nexamples below, but a table\nrow can contain multiple types. For example:\n \nCREATE TABLE object (shapeA POLYGON, shapeB LINESTRING);\n \nPOINT\n \nCREATE TABLE gis_point (g POINT);\nSHOW FIELDS FROM gis_point;\n \nINSERT INTO gis_point VALUES\n (PointFromText(\'POINT(10 10)\')),\n (PointFromText(\'POINT(20 10)\')),\n (PointFromText(\'POINT(20 20)\')),\n (PointFromWKB(AsWKB(PointFromText(\'POINT(10 20)\'))));\n \nLINESTRING\n \nCREATE TABLE gis_line (g LINESTRING);\nSHOW FIELDS FROM gis_line;\n \nINSERT INTO gis_line VALUES\n (LineFromText(\'LINESTRING(0 0,0 10,10 0)\')),\n (LineStringFromText(\'LINESTRING(10 10,20 10,20 20,10 20,10\n10)\')),\n (LineStringFromWKB(AsWKB(LineString(Point(10, 10),\nPoint(40, 10)))));\n \nPOLYGON\n \nCREATE TABLE gis_polygon (g POLYGON);\nSHOW FIELDS FROM gis_polygon;\n \nINSERT INTO gis_polygon VALUES\n (PolygonFromText(\'POLYGON((10 10,20 10,20 20,10 20,10\n10))\')),\n (PolyFromText(\'POLYGON((0 0,50 0,50 50,0 50,0 0), (10\n10,20 10,20 20,10 20,10 10))\')),\n (PolyFromWKB(AsWKB(Polygon(LineString(Point(0, 0),\nPoint(30, 0), Point(30, 30), Point(0, 0))))));\n \nMULTIPOINT\n \nCREATE TABLE gis_multi_point (g MULTIPOINT);\nSHOW FIELDS FROM gis_multi_point;\n \nINSERT INTO gis_multi_point VALUES\n (MultiPointFromText(\'MULTIPOINT(0 0,10 10,10 20,20\n20)\')),\n (MPointFromText(\'MULTIPOINT(1 1,11 11,11 21,21 21)\')),\n (MPointFromWKB(AsWKB(MultiPoint(Point(3, 6), Point(4,\n10)))));\n \nMULTILINESTRING\n \nCREATE TABLE gis_multi_line (g MULTILINESTRING);\nSHOW FIELDS FROM gis_multi_line;\n \nINSERT INTO gis_multi_line VALUES\n (MultiLineStringFromText(\'MULTILINESTRING((10 48,10 21,10\n0),(16 0,16 23,16 48))\')),\n (MLineFromText(\'MULTILINESTRING((10 48,10 21,10 0))\')),\n (MLineFromWKB(AsWKB(MultiLineString(LineString(Point(1, 2),\nPoint(3, 5)), LineString(Point(2, 5), Point(5, 8), Point(21,\n7))))));\n \nMULTIPOLYGON\n \nCREATE TABLE gis_multi_polygon (g MULTIPOLYGON);\nSHOW FIELDS FROM gis_multi_polygon;\n \nINSERT INTO gis_multi_polygon VALUES\n (MultiPolygonFromText(\'MULTIPOLYGON(((28 26,28 0,84 0,84\n42,28 26),(52 18,66 23,73 9,48 6,52 18)),((59 18,67 18,67\n13,59 13,59 18)))\')),\n (MPolyFromText(\'MULTIPOLYGON(((28 26,28 0,84 0,84 42,28\n26),(52 18,66 23,73 9,48 6,52 18)),((59 18,67 18,67 13,59\n13,59 18)))\')),\n (MPolyFromWKB(AsWKB(MultiPolygon(Polygon(LineString(Point(0,\n3), Point(3, 3), Point(3, 0), Point(0, 3)))))));\n \nGEOMETRYCOLLECTION\n \nCREATE TABLE gis_geometrycollection (g GEOMETRYCOLLECTION);\nSHOW FIELDS FROM gis_geometrycollection;\n \nINSERT INTO gis_geometrycollection VALUES\n (GeomCollFromText(\'GEOMETRYCOLLECTION(POINT(0 0),\nLINESTRING(0 0,10 10))\')),\n (GeometryFromWKB(AsWKB(GeometryCollection(Point(44, 6),\nLineString(Point(3, 6), Point(7, 9)))))),\n (GeomFromText(\'GeometryCollection()\')),\n (GeomFromText(\'GeometryCollection EMPTY\'));\n \nGEOMETRY\n \nCREATE TABLE gis_geometry (g GEOMETRY);\nSHOW FIELDS FROM gis_geometry;\n \nINSERT into gis_geometry SELECT * FROM gis_point;\n \nINSERT into gis_geometry SELECT * FROM gis_line;\n \nINSERT into gis_geometry SELECT * FROM gis_polygon;\n \nINSERT into gis_geometry SELECT * FROM gis_multi_point;\n \nINSERT into gis_geometry SELECT * FROM gis_multi_line;\n \nINSERT into gis_geometry SELECT * FROM gis_multi_polygon;\n \nINSERT into gis_geometry SELECT * FROM\ngis_geometrycollection;\n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/geometry-types/','','https://mariadb.com/kb/en/library/geometry-types/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (280,22,'JSON Data Type','The JSON alias was added in MariaDB 10.2.7. This was done to\nmake it possible to use JSON columns in statement based\nreplication from MySQL to MariaDB and to make it possible\nfor MariaDB to read mysqldumps from MySQL.\n \nJSON is an alias for LONGTEXT introduced for compatibility\nreasons with MySQL\'s JSON data type. MariaDB implements\nthis as a LONGTEXT rather, as the JSON data type contradicts\nthe SQL standard, and MariaDB\'s benchmarks indicate that\nperformance is at least equivalent.\n \nIn order to ensure that a a valid json document is inserted,\nthe JSON_VALID function can be used as a CHECK constraint.\nThis constraint is automatically included for types using\nthe JSON alias from MariaDB 10.4.3.\n \nExamples\n-------- \nCREATE TABLE t (j JSON);\n \nDESC t;\n+-------+----------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+----------+------+-----+---------+-------+\n| j | longtext | YES | | NULL | |\n+-------+----------+------+-----+---------+-------+\n \nWith validation:\n \nCREATE TABLE t2 (\n j JSON \n CHECK (JSON_VALID(j))\n);\n \nINSERT INTO t2 VALUES (\'invalid\');\nERROR 4025 (23000): CONSTRAINT `j` failed for `test`.`t2`\n \nINSERT INTO t2 VALUES (\'{\"id\": 1, \"name\":\n\"Monty\"}\');\nQuery OK, 1 row affected (0.13 sec)\n \nReplicating JSON Data Between MySQL and MariaDB\n \nThe JSON type in MySQL stores the JSON object in a compact\nform, not as LONGTEXT as in MariaDB.\nThis means that row based replication will not work for JSON\ntypes from MySQL to MariaDB.\n \nThere are a a few different ways to solve this:\nUse statement based replication.\nChange the JSON column to type TEXT in MySQL\n \nConverting a MySQL TABLE with JSON Fields to MariaDB\n \nMariaDB can\'t directly access MySQL JSON format.\n \nThere is a a few different ways to move the table to\nMariaDB:\nChange the JSON column to type TEXT in MySQL. After this\nMariaDB can directly use the table without any need for a\ndump and restore.\nUse mysqldump to copy the table.\n \nDifferences Between MySQL JSON Strings and MariaDB JSON\nStrings\n \nIn MySQL, JSON is an object and is compared according to\njson values. In MariaDB JSON strings are normal strings and\ncompared as strings. One exception is when using\nJSON_EXTRACT() in which case strings are unescaped before\ncomparison.\n \n\n\nURL: https://mariadb.com/kb/en/library/json-data-type/','','https://mariadb.com/kb/en/library/json-data-type/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (281,22,'LONGBLOB','Syntax\n------ \nLONGBLOB\n \nDescription\n----------- \nA BLOB column with a \nmaximum length of 4,294,967,295 bytes or 4GB (232 - 1). The\neffective maximum length of LONGBLOB columns depends on the\nconfigured maximum packet size in the client/server protocol\nand\navailable memory. Each LONGBLOB value is stored using a\nfour-byte\nlength prefix that indicates the number of bytes in the\nvalue.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, BLOB is a synonym for\nLONGBLOB.\n \n\n\nURL: https://mariadb.com/kb/en/library/longblob/','','https://mariadb.com/kb/en/library/longblob/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (282,22,'LONGTEXT','Syntax\n------ \nLONGTEXT [CHARACTER SET charset_name] [COLLATE\ncollation_name]\n \nDescription\n----------- \nA TEXT column with a maximum length of 4,294,967,295 or 4GB\n(232 - 1) characters. The effective maximum length is less\nif the value contains multi-byte characters. The effective\nmaximum length of LONGTEXT columns also depends on the\nconfigured maximum packet size in the client/server protocol\nand available memory. Each LONGTEXT value is stored using a\nfour-byte length prefix that indicates the number of bytes\nin the value.\n \nFrom MariaDB 10.2.7, JSON is an alias for LONGTEXT. See JSON\nData Type for details.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, CLOB is a synonym for\nLONGTEXT.\n \n\n\nURL: https://mariadb.com/kb/en/library/longtext/','','https://mariadb.com/kb/en/library/longtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (283,22,'MEDIUMBLOB','Syntax\n------ \nMEDIUMBLOB\n \nDescription\n----------- \nA BLOB column with a maximum\nlength of 16,777,215 (224 - 1) bytes.\nEach MEDIUMBLOB value is stored using a three-byte length\nprefix that\nindicates the number of bytes in the value. \n \n\n\nURL: https://mariadb.com/kb/en/library/mediumblob/','','https://mariadb.com/kb/en/library/mediumblob/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (284,22,'MEDIUMINT','Syntax\n------ \nMEDIUMINT[(M)] [SIGNED | UNSIGNED | ZEROFILL]\n \nDescription\n----------- \nA medium-sized integer. The signed range is -8388608 to\n8388607. The\nunsigned range is 0 to 16777215.\n \nZEROFILL pads the integer with zeroes and assumes UNSIGNED\n(even if UNSIGNED is not specified).\n \nFor details on the attributes, see Numeric Data Type\nOverview.\n \nExamples\n-------- \nCREATE TABLE mediumints (a MEDIUMINT,b MEDIUMINT UNSIGNED,c\nMEDIUMINT ZEROFILL);\n \nDESCRIBE mediumints;\n+-------+--------------------------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+--------------------------------+------+-----+---------+-------+\n| a | mediumint(9) | YES | | NULL | |\n| b | mediumint(8) unsigned | YES | | NULL | |\n| c | mediumint(8) unsigned zerofill | YES | | NULL | |\n+-------+--------------------------------+------+-----+---------+-------+\n \nINSERT INTO mediumints VALUES (-10,-10,-10);\nQuery OK, 1 row affected, 2 warnings (0.05 sec)\nWarning (Code 1264): Out of range value for column \'b\' at\nrow 1\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO mediumints VALUES (-10,10,-10);\nQuery OK, 1 row affected, 1 warning (0.08 sec)\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO mediumints VALUES (-10,10,10);\n \nINSERT INTO mediumints VALUES (8388608,8388608,8388608);\nQuery OK, 1 row affected, 1 warning (0.05 sec)\nWarning (Code 1264): Out of range value for column \'a\' at\nrow 1\n \nINSERT INTO mediumints VALUES (8388607,8388608,8388608);\n \nSELECT * FROM mediumints;\n+---------+---------+----------+\n| a | b | c |\n+---------+---------+----------+\n| -10 | 0 | 00000000 |\n| -10 | 0 | 00000000 |\n| -10 | 10 | 00000000 |\n| -10 | 10 | 00000010 |\n| 8388607 | 8388608 | 08388608 |\n| 8388607 | 8388608 | 08388608 |\n+---------+---------+----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/mediumint/','','https://mariadb.com/kb/en/library/mediumint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (285,22,'MEDIUMTEXT','Syntax\n------ \nMEDIUMTEXT [CHARACTER SET charset_name] [COLLATE\ncollation_name]\n \nDescription\n----------- \nA TEXT column with a \nmaximum length of 16,777,215 (224 - 1)\ncharacters. The effective maximum length is less if the\nvalue\ncontains multi-byte characters. Each MEDIUMTEXT value is\nstored using\na three-byte length prefix that indicates the number of\nbytes in the\nvalue.\n \n\n\nURL: https://mariadb.com/kb/en/library/mediumtext/','','https://mariadb.com/kb/en/library/mediumtext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (286,22,'Numeric Data Type Overview','There are a number of numeric data types:\nTINYINT\nBOOLEAN - Synonym for TINYINT(1)\nSMALLINT\nMEDIUMINT\nINT, INTEGER\nBIGINT\nDECIMAL, DEC, NUMERIC, FIXED\nFLOAT\nDOUBLE, DOUBLE PRECISION, REAL\nBIT\n \nSee the specific articles for detailed information on each.\n \nSIGNED, UNSIGNED and ZEROFILL\n \nMost numeric types can be defined as SIGNED, UNSIGNED or\nZEROFILL, for example:\n \nTINYINT[(M)] [SIGNED | UNSIGNED | ZEROFILL]\n \nIf SIGNED, or no attribute, is specified, a portion of the\nnumeric type will be reserved for the sign (plus or minus).\nFor example, a TINYINT SIGNED can range from -128 to 127. \n \nIf UNSIGNED is specified, no portion of the numeric type is\nreserved for the sign, so for integer types range can be\nlarger. For example, a TINYINT UNSIGNED can range from 0 to\n255. Floating point and fixed-point types also can be\nUNSIGNED, but this only prevents negative values from being\nstored and doesn\'t alter the range. \n \nIf ZEROFILL is specified, the column will be set to UNSIGNED\nand the spaces used by default to pad the field are replaced\nwith zeros. ZEROFILL is ignored in expressions or as part of\na UNION. ZEROFILL is a non-standard MySQL and MariaDB\nenhancement.\n \nNote that although the preferred syntax indicates that the\nattributes are exclusive, more than one attribute can be\nspecified.\n \nUntil MariaDB 10.2.7 (MDEV-8659), any combination of the\nattributes could be used in any order, with duplicates. In\nthis case:\nthe presence of ZEROFILL makes the column UNSIGNED ZEROFILL.\nthe presence of UNSIGNED makes the column UNSIGNED.\n \nFrom MariaDB 10.2.8, only the following combinations are\nsupported:\nSIGNED\nUNSIGNED\nZEROFILL\nUNSIGNED ZEROFILL\nZEROFILL UNSIGNED\n \nThe latter two should be replaced with simply ZEROFILL, but\nare still accepted by the parser.\n \nExamples\n-------- \nCREATE TABLE zf (\n i1 TINYINT SIGNED,\n i2 TINYINT UNSIGNED,\n i3 TINYINT ZEROFILL\n);\n \nINSERT INTO zf VALUES (2,2,2);\n \nSELECT * FROM zf;\n \n+------+------+------+\n| i1 | i2 | i3 |\n+------+------+------+\n| 2 | 2 | 002 |\n+------+------+------+\n \nRange\n \nWhen attempting to add a value that is out of the valid\nrange for the numeric type, MariaDB will react depending on\nthe strict SQL_MODE setting.\n \nIf strict_mode has been set (the default from MariaDB\n10.2.4), MariaDB will return an error.\n \nIf strict_mode has not been set (the default until MariaDB\n10.2.3), MariaDB will adjust the number to fit in the field,\nreturning a warning.\n \nExamples\n-------- \nWith strict_mode set:\n \nSHOW VARIABLES LIKE \'sql_mode\';\n \n+---------------+-------------------------------------------------------------------------------------------+\n| Variable_name | Value |\n+---------------+-------------------------------------------------------------------------------------------+\n| sql_mode |\nSTRICT_TRANS_TABLES,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\n|\n+---------------+-------------------------------------------------------------------------------------------+\n \nCREATE TABLE ranges (i1 TINYINT, i2 SMALLINT, i3 TINYINT\nUNSIGNED);\n \nINSERT INTO ranges VALUES (257,257,257);\nERROR 1264 (22003): Out of range value for column \'i1\' at\nrow 1\n \nSELECT * FROM ranges;\n \nEmpty set (0.10 sec)\n \nWith strict_mode unset:\n \nSHOW VARIABLES LIKE \'sql_mode%\';\n \n+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| sql_mode | |\n+---------------+-------+\n \nCREATE TABLE ranges (i1 TINYINT, i2 SMALLINT, i3 TINYINT\nUNSIGNED);\n \nINSERT INTO ranges VALUES (257,257,257);\nQuery OK, 1 row affected, 2 warnings (0.00 sec)\n \nSHOW WARNINGS;\n \n+---------+------+---------------------------------------------+\n| Level | Code | Message |\n+---------+------+---------------------------------------------+\n| Warning | 1264 | Out of range value for column \'i1\' at\nrow 1 |\n| Warning | 1264 | Out of range value for column \'i3\' at\nrow 1 |\n+---------+------+---------------------------------------------+\n2 rows in set (0.00 sec)\n \nSELECT * FROM ranges;\n \n+------+------+------+\n| i1 | i2 | i3 |\n+------+------+------+\n| 127 | 257 | 255 |\n+------+------+------+\n \nAuto_increment\n \nThe AUTO_INCREMENT attribute can be used to generate a\nunique identity for new rows. For more details, see\nauto_increment.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/numeric-data-type-overview/','','https://mariadb.com/kb/en/library/numeric-data-type-overview/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (287,22,'ROW','The ROW data type was introduced in MariaDB 10.3.0.\n \nSyntax\n------ \nROW ( [{, }... ])\n \nDescription\n----------- \nROW is a data type for stored procedure variables.\n \nFeatures\n \nROW fields as normal variables\n \nROW fields (members) act as normal variables, and are able\nto appear in all\nquery parts where a stored procedure variable is allowed:\nAssignment is using the := operator and the SET command:\n \na.x:= 10;\n \na.x:= b.x;\n \nSET a.x= 10, a.y=20, a.z= b.z;\n \nPassing to functions and operators:\n \nSELECT f1(rec.a), rec.a\n\nURL: https://mariadb.com/kb/en/library/row/','','https://mariadb.com/kb/en/library/row/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (288,22,'SET Data Type','Syntax\n------ \nSET(\'value1\',\'value2\',...) [CHARACTER SET charset_name]\n[COLLATE collation_name]\n \nDescription\n----------- \nA set. A string object that can have zero or more values,\neach of\nwhich must be chosen from the list of values \'value1\',\n\'value2\', ... A\nSET column can have a maximum of 64 members. SET values are\nrepresented internally as integers.\n \n\n\nURL: https://mariadb.com/kb/en/library/set-data-type/','','https://mariadb.com/kb/en/library/set-data-type/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (289,22,'SMALLINT','Syntax\n------ \nSMALLINT[(M)] [SIGNED | UNSIGNED | ZEROFILL]\n \nDescription\n----------- \nA small integer. The signed range is -32768 to 32767. The\nunsigned range is 0 to 65535.\n \nIf a column has been set to ZEROFILL, all values will be\nprepended by zeros so that the SMALLINT value contains a\nnumber of M digits.\n \nNote: If the ZEROFILL attribute has been specified, the\ncolumn will automatically become UNSIGNED.\n \nFor more details on the attributes, see Numeric Data Type\nOverview.\n \nExamples\n-------- \nCREATE TABLE smallints (a SMALLINT,b SMALLINT UNSIGNED,c\nSMALLINT ZEROFILL);\n \nINSERT INTO smallints VALUES (-10,-10,-10);\nQuery OK, 1 row affected, 2 warnings (0.09 sec)\nWarning (Code 1264): Out of range value for column \'b\' at\nrow 1\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO smallints VALUES (-10,10,-10);\nQuery OK, 1 row affected, 1 warning (0.08 sec)\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO smallints VALUES (-10,10,10);\n \nINSERT INTO smallints VALUES (32768,32768,32768);\nQuery OK, 1 row affected, 1 warning (0.04 sec)\nWarning (Code 1264): Out of range value for column \'a\' at\nrow 1\n \nINSERT INTO smallints VALUES (32767,32768,32768);\n \nSELECT * FROM smallints;\n+-------+-------+-------+\n| a | b | c |\n+-------+-------+-------+\n| -10 | 0 | 00000 |\n| -10 | 10 | 00000 |\n| -10 | 10 | 00010 |\n| 32767 | 32768 | 32768 |\n| 32767 | 32768 | 32768 |\n+-------+-------+-------+\n \n\n\nURL: https://mariadb.com/kb/en/library/smallint/','','https://mariadb.com/kb/en/library/smallint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (290,22,'String Literals','Strings are sequences of characters and are enclosed with\nquotes.\n \nThe syntax is:\n \n[_charset_name]\'string\' [COLLATE collation_name]\n \nFor example:\n \n\'The MariaDB Foundation\'\n_utf8 \'Foundation\' COLLATE utf8_unicode_ci;\n \nStrings can either be enclosed in single quotes or in double\nquotes (the same character must be used to both open and\nclose the string).\n \nThe ANSI SQL-standard does not permit double quotes for\nenclosing strings, and although MariaDB does by default, if\nthe MariaDB server has enabled the ANSI_QUOTES_SQL SQL_MODE,\ndouble quotes will be treated as being used for identifiers\ninstead of strings.\n \nStrings that are next to each other are automatically\nconcatenated. For example:\n \n\'The \' \'MariaDB \' \'Foundation\'\n \nand\n \n\'The MariaDB Foundation\'\n \nare equivalent.\n \nThe \\ (backslash character) is used to escape characters.\nFor example:\n \n\'MariaDB\'s new features\'\n \nis not a valid string because of the single quote in the\nmiddle of the string, which is treated as if it closes the\nstring, but is actually meant as part of the string, an\napostrophe. The backslash character helps in situations like\nthis:\n \n\'MariaDB\\\'s new features\'\n \nis now a valid string, and if displayed, will appear without\nthe backslash.\n \nSELECT \'MariaDB\\\'s new features\';\n+------------------------+\n| MariaDB\'s new features |\n+------------------------+\n| MariaDB\'s new features |\n+------------------------+\n \nAnother way to escape the quoting character is repeating it\ntwice:\n \nSELECT \'I\'\'m here\', \"\"\"Double\"\"\";\n+----------+----------+\n| I\'m here | \"Double\" |\n+----------+----------+\n| I\'m here | \"Double\" |\n+----------+----------+\n \nEscape sequences\n \nThere are other escape sequences also. Here is a full list:\n \nEscape sequence | Character | \n \n\\0 | ASCII NUL (0x00). | \n \n\\\' | Single quote (“\'”). | \n \n\\\" | Double quote (“\"”). | \n \n\\b | Backspace. | \n \n\\n | Newline, or linefeed,. | \n \n\\r | Carriage return. | \n \n\\t | Tab. | \n \n\\Z | ASCII 26 (Control+Z). See note following the table. | \n \n\\\\ | Backslash (“\\”). | \n \n\\% | “%” character. See note following the table. | \n \n\\_ | A “_” character. See note following the table. | \n \nEscaping the % and _ characters can be necessary when using\nthe LIKE operator, which treats them as special characters.\n \nThe ASCII 26 character (\\Z) needs to be escaped when\nincluded in a batch file which needs to be executed in\nWindows. The reason is that ASCII 26, in Windows, is the end\nof file (EOF).\n \nBackslash (\\), if not used as an escape character, must\nalways be escaped. When followed by a character that is not\nin the above table, backslashes will simply be ignored.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/string-literals/','','https://mariadb.com/kb/en/library/string-literals/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (291,22,'TEXT','Syntax\n------ \nTEXT[(M)] [CHARACTER SET charset_name] [COLLATE\ncollation_name]\n \nDescription\n----------- \nA TEXT column with a maximum length of 65,535 (216 - 1)\ncharacters. The effective maximum length is less if the\nvalue contains\nmulti-byte characters. Each TEXT value is stored using a\ntwo-byte length\nprefix that indicates the number of bytes in the value. If\nyou need a bigger storage, consider using MEDIUMTEXT\ninstead.\n \nAn optional length M can be given for this type. If this is\ndone, MariaDB\ncreates the column as the smallest TEXT type large enough to\nhold values\nM characters long.\n \nBefore MariaDB 10.2, all MariaDB collations were of type\nPADSPACE, meaning that TEXT (as well as VARCHAR and CHAR\nvalues) are compared without regard for trailing spaces.\nThis does not apply to the LIKE pattern-matching operator,\nwhich takes into account trailing spaces.\n \nBefore MariaDB 10.2.1, BLOB and TEXT columns could not be\nassigned a DEFAULT value. This restriction was lifted in\nMariaDB 10.2.1.\n \nExamples\n-------- \nTrailing spaces:\n \nCREATE TABLE strtest (d TEXT(10));\nINSERT INTO strtest VALUES(\'Maria \');\n \nSELECT d=\'Maria\',d=\'Maria \' FROM strtest;\n+-----------+--------------+\n| d=\'Maria\' | d=\'Maria \' |\n+-----------+--------------+\n| 1 | 1 |\n+-----------+--------------+\n \nSELECT d LIKE \'Maria\',d LIKE \'Maria \' FROM strtest;\n+----------------+-------------------+\n| d LIKE \'Maria\' | d LIKE \'Maria \' |\n+----------------+-------------------+\n| 0 | 1 |\n+----------------+-------------------+\n \nDifference between VARCHAR and TEXT\n \nVARCHAR columns can be fully indexed. TEXT columns can only\nbe indexed over a specified length.\nUsing TEXT or BLOB in a SELECT query that uses temporary\ntables for storing intermediate results will force the\ntemporary table to be disk based (using the Aria storage\nengine instead of the memory storage engine, which is a bit\nslower. This is not that bad as the Aria storage engine\ncaches the rows in memory. To get the benefit of this, one\nshould ensure that the aria_pagecache_buffer_size variable\nis big enough to hold most of the row and index data for\ntemporary tables.\n \nFor Storage Engine Developers\n \nInternally the full length of the VARCHAR column is\nallocated inside each TABLE objects record[] structure. As\nthere are three such buffers, each open table will allocate\n3 times max-length-to-store-varchar bytes of memory.\nTEXT and BLOB columns are stored with a pointer (4 or 8\nbytes) + a 1-4 bytes length. The TEXT data is only stored\nonce. This means that internally TEXT uses less memory for\neach open table but instead has the additional overhead that\neach TEXT object needs to be allocated and freed for each\nrow access (with some caching in between).\n \n\n\nURL: https://mariadb.com/kb/en/library/text/','','https://mariadb.com/kb/en/library/text/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (292,22,'TIME','Syntax\n------ \nTIME [()]\n \nDescription\n----------- \nA time. The range is \'-838:59:59.999999\' to\n\'838:59:59.999999\'. Microsecond precision can be from 0-6;\nif not specified 0 is used. Microseconds have been available\nsince MariaDB 5.3. \n \nMariaDB displays TIME values in \'HH:MM:SS.ssssss\' format,\nbut allows assignment of times in looser formats, including\n\'D HH:MM:SS\', \'HH:MM:SS\', \'HH:MM\', \'D HH:MM\', \'D\nHH\', \'SS\', or \'HHMMSS\', as well as permitting dropping\nof any leading zeros when a delimiter is provided, for\nexample \'3:9:10\'. For details, see date and time literals.\n \nMariaDB 10.1.2 introduced the --mysql56-temporal-format\noption, on by default, which allows MariaDB to store TIMEs\nusing the same low-level format MySQL 5.6 uses.\n \nInternal Format\n \nIn MariaDB 10.1.2 a new temporal format was introduced from\nMySQL 5.6 that alters how the TIME, DATETIME and TIMESTAMP\ncolumns operate at lower levels. These changes allow these\ntemporal data types to have fractional parts and negative\nvalues. You can disable this feature using the\nmysql56_temporal_format system variable.\n \nTables that include TIMESTAMP values that were created on an\nolder version of MariaDB or that were created while the\nmysql56_temporal_format system variable was disabled\ncontinue to store data using the older data type format.\n \nIn order to update table columns from the older format to\nthe newer format, execute an ALTER TABLE... MODIFY COLUMN\nstatement that changes the column to the *same* data type.\nThis change may be needed if you want to export the table\'s\ntablespace and import it onto a server that has\nmysql56_temporal_format=ON set (see MDEV-15225).\n \nFor instance, if you have a TIME column in your table: \n \nSHOW VARIABLES LIKE \'mysql56_temporal_format\';\n \n+-------------------------+-------+\n| Variable_name | Value |\n+-------------------------+-------+\n| mysql56_temporal_format | ON |\n+-------------------------+-------+\n \nALTER TABLE example_table MODIFY ts_col TIME;\n \nWhen MariaDB executes the ALTER TABLE statement, it converts\nthe data from the older temporal format to the newer one. \n \nIn the event that you have several tables and columns using\ntemporal data types that you want to switch over to the new\nformat, make sure the system variable is enabled, then\nperform a dump and restore using mysqldump. The columns\nusing relevant temporal data types are restored using the\nnew temporal format.\n \nExamples\n-------- \nINSERT INTO time VALUES (\'90:00:00\'), (\'800:00:00\'),\n(800), (22), (151413), (\'9:6:3\'), (\'12 09\');\n \nSELECT * FROM time;\n+-----------+\n| t |\n+-----------+\n| 90:00:00 |\n| 800:00:00 |\n| 00:08:00 |\n| 00:00:22 |\n| 15:14:13 |\n| 09:06:03 |\n| 297:00:00 |\n+-----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/time/','','https://mariadb.com/kb/en/library/time/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (293,22,'TIMESTAMP','Syntax\n------ \nTIMESTAMP [(\n\nURL: https://mariadb.com/kb/en/library/timestamp/','','https://mariadb.com/kb/en/library/timestamp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (294,22,'TINYBLOB','Syntax\n------ \nTINYBLOB\n \nDescription\n----------- \nA BLOB column with a maximum length of \n255 (28 - 1) bytes. Each\nTINYBLOB value is stored using a one-byte length prefix that\nindicates\nthe number of bytes in the value.\n \n\n\nURL: https://mariadb.com/kb/en/library/tinyblob/','','https://mariadb.com/kb/en/library/tinyblob/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (295,22,'TINYINT','Syntax\n------ \nTINYINT[(M)] [SIGNED | UNSIGNED | ZEROFILL]\n \nDescription\n----------- \nA very small integer. The signed range is -128 to 127. The\nunsigned range is 0 to 255. For details on the attributes,\nsee Numeric Data Type Overview.\n \nExamples\n-------- \nCREATE TABLE tinyints (a TINYINT,b TINYINT UNSIGNED,c\nTINYINT ZEROFILL);\nQuery OK, 0 rows affected (0.43 sec)\n \nINSERT INTO tinyints VALUES (-10,-10,-10);\nQuery OK, 1 row affected, 2 warnings (0.08 sec)\nWarning (Code 1264): Out of range value for column \'b\' at\nrow 1\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO tinyints VALUES (-10,10,-10);\nQuery OK, 1 row affected, 1 warning (0.11 sec)\nWarning (Code 1264): Out of range value for column \'c\' at\nrow 1\n \nINSERT INTO tinyints VALUES (-10,10,10);\n \nSELECT * FROM tinyints;\n+------+------+------+\n| a | b | c |\n+------+------+------+\n| -10 | 0 | 000 |\n| -10 | 10 | 000 |\n| -10 | 10 | 010 |\n+------+------+------+\n \nINSERT INTO tinyints VALUES (128,128,128);\nQuery OK, 1 row affected, 1 warning (0.19 sec)\nWarning (Code 1264): Out of range value for column \'a\' at\nrow 1\n \nINSERT INTO tinyints VALUES (127,128,128);\n \nSELECT * FROM tinyints;\n+------+------+------+\n| a | b | c |\n+------+------+------+\n| -10 | 0 | 000 |\n| -10 | 10 | 000 |\n| -10 | 10 | 010 |\n| 127 | 128 | 128 |\n| 127 | 128 | 128 |\n+------+------+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/tinyint/','','https://mariadb.com/kb/en/library/tinyint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (296,22,'TINYTEXT','Syntax\n------ \nTINYTEXT [CHARACTER SET charset_name] [COLLATE\ncollation_name]\n \nDescription\n----------- \nA TEXT column with a maximum length of 255 (28 - 1)\ncharacters. The effective maximum length is less if the\nvalue contains multi-byte characters. Each TINYTEXT value is\nstored using a one-byte length prefix that indicates the\nnumber of bytes in the value.\n \n\n\nURL: https://mariadb.com/kb/en/library/tinytext/','','https://mariadb.com/kb/en/library/tinytext/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (297,22,'VARBINARY','Syntax\n------ \nVARBINARY(M)\n \nDescription\n----------- \nThe VARBINARY type is similar to the VARCHAR type, but\nstores binary byte strings rather than non-binary character\nstrings. M represents the maximum column length in bytes. \n \nIt contains no character set, and comparison and sorting are\nbased on the numeric value of the bytes.\n \nIf the maximum length is exceeded, and SQL strict mode is\nnot enabled , the extra characters will be dropped with a\nwarning. If strict mode is enabled, an error will occur.\n \nUnlike BINARY values, VARBINARYs are not right-padded when\ninserting.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, RAW is a synonym for\nVARBINARY.\n \nExamples\n-------- \nInserting too many characters, first with strict mode off,\nthen with it on:\n \nCREATE TABLE varbins (a VARBINARY(10));\n \nINSERT INTO varbins VALUES(\'12345678901\');\nQuery OK, 1 row affected, 1 warning (0.04 sec)\n \nSELECT * FROM varbins;\n \n+------------+\n| a |\n+------------+\n| 1234567890 |\n+------------+\n \nSET sql_mode=\'STRICT_ALL_TABLES\';\n \nINSERT INTO varbins VALUES(\'12345678901\');\nERROR 1406 (22001): Data too long for column \'a\' at row 1\n \nSorting is performed with the byte value:\n \nTRUNCATE varbins;\n \nINSERT INTO varbins VALUES(\'A\'),(\'B\'),(\'a\'),(\'b\');\n \nSELECT * FROM varbins ORDER BY a;\n \n+------+\n| a |\n+------+\n| A |\n| B |\n| a |\n| b |\n+------+\n \nUsing CAST to sort as a CHAR instead:\n \nSELECT * FROM varbins ORDER BY CAST(a AS CHAR);\n+------+\n| a |\n+------+\n| a |\n| A |\n| b |\n| B |\n+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/varbinary/','','https://mariadb.com/kb/en/library/varbinary/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (298,22,'VARCHAR','Syntax\n------ \n[NATIONAL] VARCHAR(M) [CHARACTER SET charset_name] [COLLATE\ncollation_name]\n \nDescription\n----------- \nA variable-length string. M represents the maximum column\nlength in\ncharacters. The range of M is 0 to 65,532. The effective\nmaximum\nlength of a VARCHAR is subject to the maximum row size and\nthe character set used. For\nexample, utf8 characters can require up to three bytes per\ncharacter,\nso a VARCHAR column that uses the utf8 character set can be\ndeclared\nto be a maximum of 21,844 characters.\n \nMariaDB stores VARCHAR values as a one-byte or two-byte\nlength prefix\nplus data. The length prefix indicates the number of bytes\nin the\nvalue. A VARCHAR column uses one length byte if values\nrequire no more\nthan 255 bytes, two length bytes if values may require more\nthan 255\nbytes.\n \nNote: MariaDB 5.1 and later follow the standard SQL\nspecification, \nand do not remove trailing spaces from VARCHAR values.\n \nVARCHAR(0) columns can contain 2 values: an empty string or\nNULL. Such columns cannot be part of an index. The CONNECT\nstorage engine does not support VARCHAR(0).\n \nVARCHAR is shorthand for CHARACTER VARYING. NATIONAL VARCHAR\nis the\nstandard SQL way to define that a VARCHAR column should use\nsome\npredefined character set. MariaDB uses utf8 as this\npredefined character set, as does MySQL 4.1 and up.\nNVARCHAR is shorthand for NATIONAL VARCHAR.\n \nBefore MariaDB 10.2, all MariaDB collations were of type\nPADSPACE, meaning that VARCHAR (as well as CHAR and TEXT\nvalues) are compared without regard for trailing spaces.\nThis does not apply to the LIKE pattern-matching operator,\nwhich takes into account trailing spaces. From MariaDB 10.2,\na number of NO PAD collations are available.\n \nIf a unique index consists of a column where trailing pad\ncharacters are stripped or ignored, inserts into that column\nwhere values differ only by the number of trailing pad\ncharacters will result in a duplicate-key error.\n \nExamples\n-------- \nThe following are equivalent:\n \nVARCHAR(30) CHARACTER SET utf8\nNATIONAL VARCHAR(30)\nNVARCHAR(30)\nNCHAR VARCHAR(30)\nNATIONAL CHARACTER VARYING(30)\nNATIONAL CHAR VARYING(30)\n \nTrailing spaces:\n \nCREATE TABLE strtest (v VARCHAR(10));\nINSERT INTO strtest VALUES(\'Maria \');\n \nSELECT v=\'Maria\',v=\'Maria \' FROM strtest;\n+-----------+--------------+\n| v=\'Maria\' | v=\'Maria \' |\n+-----------+--------------+\n| 1 | 1 |\n+-----------+--------------+\n \nSELECT v LIKE \'Maria\',v LIKE \'Maria \' FROM strtest;\n+----------------+-------------------+\n| v LIKE \'Maria\' | v LIKE \'Maria \' |\n+----------------+-------------------+\n| 0 | 1 |\n+----------------+-------------------+\n \nTruncation\n \nDepending on whether or not strict sql mode is set, you will\neither get a warning or an error if you try to insert a\nstring that is too long into a VARCHAR column. If the extra\ncharacters are spaces, the spaces that can\'t fit will be\nremoved and you will always get a warning, regardless of the\nsql mode setting.\n \nDifference Between VARCHAR and TEXT\n \nVARCHAR columns can be fully indexed. TEXT columns can only\nbe indexed over a specified length.\nUsing TEXT or BLOB in a SELECT query that uses temporary\ntables for storing intermediate results will force the\ntemporary table to be disk based (using the Aria storage\nengine instead of the memory storage engine, which is a bit\nslower. This is not that bad as the Aria storage engine\ncaches the rows in memory. To get the benefit of this, one\nshould ensure that the aria_pagecache_buffer_size variable\nis big enough to hold most of the row and index data for\ntemporary tables.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, VARCHAR2 is a synonym.\n \nFor Storage Engine Developers\n \nInternally the full length of the VARCHAR column is\nallocated inside each TABLE objects record[] structure. As\nthere are three such buffers, each open table will allocate\n3 times max-length-to-store-varchar bytes of memory.\nTEXT and BLOB columns are stored with a pointer (4 or 8\nbytes) + a 1-4 bytes length. The TEXT data is only stored\nonce. This means that internally TEXT uses less memory for\neach open table but instead has the additional overhead that\neach TEXT object needs to be allocated and freed for each\nrow access (with some caching in between).\n \n\n\nURL: https://mariadb.com/kb/en/library/varchar/','','https://mariadb.com/kb/en/library/varchar/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (299,22,'YEAR Data Type','Syntax\n------ \nYEAR[(4)]\n \nDescription\n----------- \nA year in two-digit or four-digit format. The default is\nfour-digit format. Note that the two-digit format has been\ndeprecated since 5.5.27. \n \nIn four-digit format, the allowable values are 1901 to 2155,\nand 0000. In two-digit format, the allowable values are 70\nto 69,\nrepresenting years from 1970 to 2069. MariaDB displays YEAR\nvalues in\nYYYY format, but allows you to assign values to YEAR columns\nusing\neither strings or numbers.\n \nInserting numeric zero has a different result for YEAR(4)\nand YEAR(2). For YEAR(2), the value 00 reflects the year\n2000. For YEAR(4), the value 0000 reflects the year zero.\nThis only applies to numeric zero. String zero always\nreflects the year 2000.\n \nExamples\n-------- \nAccepting a string or a number:\n \nCREATE TABLE y(y YEAR);\n \nINSERT INTO y VALUES (1990),(\'2012\');\n \nSELECT * FROM y;\n+------+\n| y |\n+------+\n| 1990 |\n| 2012 |\n+------+\n \nOut of range:\n \nINSERT INTO y VALUES (1005),(\'3080\');\nQuery OK, 2 rows affected, 2 warnings (0.05 sec)\nRecords: 2 Duplicates: 0 Warnings: 2\n \nSHOW WARNINGS;\n+---------+------+--------------------------------------------+\n| Level | Code | Message |\n+---------+------+--------------------------------------------+\n| Warning | 1264 | Out of range value for column \'y\' at\nrow 1 |\n| Warning | 1264 | Out of range value for column \'y\' at\nrow 2 |\n+---------+------+--------------------------------------------+\n \nSELECT * FROM y;\n+------+\n| y |\n+------+\n| 1990 |\n| 2012 |\n| 0000 |\n| 0000 |\n+------+\n \nTruncating:\n \nINSERT INTO y VALUES (\'2013-12-12\');\nQuery OK, 1 row affected, 1 warning (0.05 sec)\n \nSHOW WARNINGS;\n+---------+------+----------------------------------------+\n| Level | Code | Message |\n+---------+------+----------------------------------------+\n| Warning | 1265 | Data truncated for column \'y\' at row 1\n|\n+---------+------+----------------------------------------+\n \nSELECT * FROM y;\n+------+\n| y |\n+------+\n| 1990 |\n| 2012 |\n| 0000 |\n| 0000 |\n| 2013 |\n+------+\n \nDifference between YEAR(2) and YEAR(4), and string and\nnumeric zero:\n \nCREATE TABLE y2(y YEAR(4), y2 YEAR(2));\nQuery OK, 0 rows affected, 1 warning (0.40 sec)\n \nNote (Code 1287): \'YEAR(2)\' is deprecated and will be\nremoved in a future release. Please use YEAR(4) instead\n \nINSERT INTO y2 VALUES(0,0),(\'0\',\'0\');\n \nSELECT YEAR(y),YEAR(y2) FROM y;\n+---------+----------+\n| YEAR(y) | YEAR(y2) |\n+---------+----------+\n| 0 | 2000 |\n| 2000 | 2000 |\n+---------+----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/year-data-type/','','https://mariadb.com/kb/en/library/year-data-type/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (300,23,'BEGIN END','Syntax\n------ \n[begin_label:] BEGIN [NOT ATOMIC]\n [statement_list]\nEND [end_label]\n \nNOT ATOMIC is required when used outside of a stored\nprocedure. Inside stored procedures or within an anonymous\nblock, BEGIN alone starts a new anonymous block.\n \nDescription\n----------- \nBEGIN ... END syntax is used for writing compound\nstatements. A compound statement can contain multiple\nstatements, enclosed by the BEGIN and END keywords.\nstatement_list represents a list of one or more statements,\neach\nterminated by a semicolon (i.e., ;) statement delimiter.\nstatement_list is\noptional, which means that the empty compound statement\n(BEGIN END) is\nlegal.\n \nNote that END will perform a commit. If you are running in\nautocommit mode, every statement will be committed\nseparately. If you are not running in autocommit mode, you\nmust execute a COMMIT or ROLLBACK after END to get the\ndatabase up to date.\n \nUse of multiple statements requires that a client is able to\nsend statement strings containing the ; statement delimiter.\nThis is handled in the mysql command-line client with the\nDELIMITER command.\nChanging the ; end-of-statement delimiter (for example, to\n//) allows ; to be used in a program body.\n \nA compound statement within a stored program can be\nlabeled. end_label cannot be given unless begin_label also\nis present. If both are present, they must be the same.\n \nBEGIN ... END constructs can be nested. Each block can\ndefine its own variables, a CONDITION, a HANDLER and a\nCURSOR, which don\'t exist in the outer blocks. The most\nlocal declarations override the outer objects which use the\nsame name (see example below).\n \nThe declarations order is the following:\nDECLARE local variables;\nDECLARE CONDITIONs;\nDECLARE CURSORs;\nDECLARE HANDLERs;\n \nNote that DECLARE HANDLER contains another BEGIN ... END\nconstruct.\n \nHere is an example of a very simple, anonymous block:\n \nBEGIN NOT ATOMIC\nSET @a=1;\n \nCREATE TABLE test.t1(a INT);\nEND|\n \nBelow is an example of nested blocks in a stored procedure:\n \nCREATE PROCEDURE t( )\nBEGIN\n DECLARE x TINYINT UNSIGNED DEFAULT 1;\n \n BEGIN\n DECLARE x CHAR(2) DEFAULT \'02\';\n \n DECLARE y TINYINT UNSIGNED DEFAULT 10;\n \n SELECT x, y;\n \n END;\n \n SELECT x;\n \nEND;\n \nIn this example, a TINYINT variable, x is declared in the\noutter block. But in the inner block x is re-declared as a\nCHAR and an y variable is declared. The inner SELECT shows\nthe \"new\" value of x, and the value of y. But when x is\nselected in the outer block, the \"old\" value is returned.\nThe final SELECT doesn\'t try to read y, because it doesn\'t\nexist in that context.\n \n\n\nURL: https://mariadb.com/kb/en/library/begin-end/','','https://mariadb.com/kb/en/library/begin-end/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (301,23,'CASE Statement','Syntax\n------ \nCASE case_value\n WHEN when_value THEN statement_list\n [WHEN when_value THEN statement_list] ...\n [ELSE statement_list]\nEND CASE\n \nOr:\n \nCASE\n WHEN search_condition THEN statement_list\n [WHEN search_condition THEN statement_list] ...\n [ELSE statement_list] \nEND CASE\n \nDescription\n----------- \nThe CASE statement for stored programs implements a complex\nconditional\nconstruct. If a search_condition evaluates to true, the\ncorresponding SQL\nstatement list is executed. If no search condition matches,\nthe statement list\nin the ELSE clause is executed. Each statement_list consists\nof one or\nmore statements.\n \nIf no when_value or search_condition matches the value\ntested and the CASE\nstatement contains no ELSE clause, a Case not found for CASE\nstatement\nerror results.\n \nEach statement_list consists of one or more statements; an\nempty\nstatement_list is not allowed. To handle situations where no\nvalue is\nmatched by any WHEN clause, use an ELSE containing an\nempty BEGIN ... END block, as shown in this example:\n \nDELIMITER |\nCREATE PROCEDURE p()\nBEGIN\n DECLARE v INT DEFAULT 1;\n \n CASE v\n WHEN 2 THEN SELECT v;\n \n WHEN 3 THEN SELECT 0;\n \n ELSE BEGIN END;\n \n END CASE;\n \nEND;\n \n|\n \nThe indentation used here in the ELSE clause is for purposes\nof clarity only,\nand is not otherwise significant. See Delimiters in the\nmysql client for more on the use of the delimiter command.\n \nNote: The syntax of the CASE statement used inside stored\nprograms\ndiffers slightly from that of the SQL CASE expression\ndescribed in\nCASE OPERATOR.\nThe CASE statement cannot have an ELSE NULL clause, and it\nis\nterminated with END CASE instead of END.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/case-statement/','','https://mariadb.com/kb/en/library/case-statement/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (302,23,'CLOSE','Syntax\n------ \nCLOSE cursor_name\n \nDescription\n----------- \nThis statement closes a previously opened cursor. The cursor\nmust have been previously opened or else an error occurs.\n \nIf not closed explicitly, a cursor is closed at the end of\nthe\ncompound statement in which it was declared.\n \nSee Cursor Overview for an example.\n \n\n\nURL: https://mariadb.com/kb/en/library/close/','','https://mariadb.com/kb/en/library/close/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (303,23,'DECLARE CONDITION','Syntax\n------ \nDECLARE condition_name CONDITION FOR condition_value\n \ncondition_value:\n SQLSTATE [VALUE] sqlstate_value\n | mysql_error_code\n \nDescription\n----------- \nThe DECLARE ... CONDITION statement defines a named error\ncondition.\nIt specifies a condition that needs specific handling and\nassociates a\nname with that condition. Later, the name can be used in a\nDECLARE ... HANDLER, SIGNAL or RESIGNAL statement (as long\nas the statement is located in the same BEGIN ... END\nblock).\n \nConditions must be declared after local variables, but\nbefore CURSORs and HANDLERs.\n \nA condition_value for DECLARE ... CONDITION can be an\nSQLSTATE value (a\n5-character string literal) or a MySQL error code (a\nnumber). You should not\nuse SQLSTATE value \'00000\' or MySQL error code 0, because\nthose indicate sucess\nrather than an error condition. If you try, or if you\nspecify an invalid SQLSTATE value, an error like this is\nproduced:\n \nERROR 1407 (42000): Bad SQLSTATE: \'00000\'\n \nFor a list of SQLSTATE values and MariaDB error\ncodes, see MariaDB Error Codes.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/declare-condition/','','https://mariadb.com/kb/en/library/declare-condition/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (304,23,'DECLARE CURSOR','Syntax\n------ \n\n\nURL: https://mariadb.com/kb/en/library/declare-cursor/','','https://mariadb.com/kb/en/library/declare-cursor/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (305,23,'DECLARE HANDLER','Syntax\n------ \nDECLARE handler_type HANDLER\n FOR condition_value [, condition_value] ...\n statement\n \nhandler_type:\n CONTINUE\n | EXIT \n | UNDO\n \ncondition_value:\n SQLSTATE [VALUE] sqlstate_value\n | condition_name\n | SQLWARNING\n | NOT FOUND\n | SQLEXCEPTION\n | mariadb_error_code\n \nDescription\n----------- \nThe DECLARE ... HANDLER statement specifies handlers that\neach may\ndeal with one or more conditions. If one of these conditions\noccurs,\nthe specified statement is executed. statement can be a\nsimple\nstatement (for example, SET var_name = value), or it can be\na compound\nstatement written using BEGIN and END.\n \nHandlers must be declared after local variables, a CONDITION\nand a CURSOR.\n \nFor a CONTINUE handler, execution of the current program\ncontinues\nafter execution of the handler statement. For an EXIT\nhandler,\nexecution terminates for the BEGIN ... END compound\nstatement in which\nthe handler is declared. (This is true even if the condition\noccurs in\nan inner block.) The UNDO handler type statement is not\nsupported.\n \nIf a condition occurs for which no handler has been\ndeclared, the\ndefault action is EXIT.\n \nA condition_value for DECLARE ... HANDLER can be any of the\nfollowing\nvalues:\nAn SQLSTATE value (a 5-character string literal) or a\nMariaDB error\ncode (a number). You should not use SQLSTATE value \'00000\'\nor MariaDB\nerror code 0, because those indicate sucess rather than an\nerror\ncondition. For a list of SQLSTATE values and MariaDB error\ncodes, see\nMariaDB Error Codes.\nA condition name previously specified with DECLARE ...\nCONDITION. It must be in the same stored program. See\nDECLARE CONDITION.\nSQLWARNING is shorthand for the class of SQLSTATE values\nthat begin\nwith \'01\'.\nNOT FOUND is shorthand for the class of SQLSTATE values that\nbegin\nwith \'02\'. This is relevant only the context of cursors\nand is used to\ncontrol what happens when a cursor reaches the end of a data\nset. If\nno more rows are available, a No Data condition occurs with\nSQLSTATE\nvalue 02000. To detect this condition, you can set up a\nhandler for it\n(or for a NOT FOUND condition). An example is shown in\nCursor Overview. This condition also occurs for SELECT ...\nINTO var_list statements that retrieve no\nrows.\nSQLEXCEPTION is shorthand for the class of SQLSTATE values\nthat do\nnot begin with \'00\', \'01\', or \'02\'.\n \nWhen an error raises, in some cases it could be handled by\nmultiple HANDLERs. For example, there may be an handler for\n1050 error, a separate handler for the 42S01 SQLSTATE, and\nanother separate handler for the SQLEXCEPTION class: in\ntheory all occurrences of HANDLER may catch the 1050 error,\nbut MariaDB chooses the HANDLER with the highest precedence.\nHere are the precedence rules:\nHandlers which refer to an error code have the highest\nprecedence.\nHandlers which refer to a SQLSTATE come next.\nHandlers which refer to an error class have the lowest\nprecedence.\n \nIn some cases, a statement could produce multiple errors. If\nthis happens, in some cases multiple handlers could have the\nhighest precedence. In such cases, the choice of the handler\nis indeterminate.\n \nNote that if an error occurs within a CONTINUE HANDLER\nblock, it can be handled by another HANDLER. However, a\nHANDLER which is already in the stack (that is, it has been\ncalled to handle an error and its execution didn\'t finish\nyet) cannot handle new errors—this prevents endless loops.\nFor example, suppose that a stored procedure contains a\nCONTINUE HANDLER for SQLWARNING and another CONTINUE HANDLER\nfor NOT FOUND. At some point, a NOT FOUND error occurs, and\nthe execution enters the NOT FOUND HANDLER. But within that\nhandler, a warning occurs, and the execution enters the\nSQLWARNING HANDLER. If another NOT FOUND error occurs, it\ncannot be handled again by the NOT FOUND HANDLER, because\nits execution is not finished.\n \nWhen a DECLARE HANDLER block can handle more than one error\ncondition, it may be useful to know which errors occurred.\nTo do so, you can use the GET DIAGNOSTICS statement.\n \nAn error that is handled by a DECLARE HANDLER construct can\nbe issued again using the RESIGNAL statement.\n \nBelow is an example using DECLARE HANDLER:\n \nCREATE TABLE test.t (s1 INT, PRIMARY KEY (s1));\n \nDELIMITER //\n \nCREATE PROCEDURE handlerdemo ( )\n BEGIN\n DECLARE CONTINUE HANDLER FOR SQLSTATE \'23000\' SET @x2 =\n1;\n \n SET @x = 1;\n \n INSERT INTO test.t VALUES (1);\n SET @x = 2;\n \n INSERT INTO test.t VALUES (1);\n SET @x = 3;\n \n END;\n \n //\n \nDELIMITER ;\n \nCALL handlerdemo( );\n \nSELECT @x;\n \n+------+\n| @x |\n+------+\n| 3 |\n+------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/declare-handler/','','https://mariadb.com/kb/en/library/declare-handler/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (306,23,'DECLARE Variable','Syntax\n------ \nDECLARE var_name [, var_name] ... [[ROW] TYPE OF]] type\n[DEFAULT value]\n \nDescription\n----------- \nThis statement is used to declare local variables within\nstored programs. To\nprovide a default value for the variable, include a DEFAULT\nclause. The\nvalue can be specified as an expression (even subqueries are\npermitted); it need not be a constant. If the\nDEFAULT clause is missing, the initial value is NULL.\n \nLocal variables are treated like stored routine parameters\nwith respect to data\ntype and overflow checking. See CREATE PROCEDURE.\n \nLocal variables must be declared before CONDITIONs, CURSORs\nand HANDLERs.\n \nLocal variable names are not case sensitive.\n \nThe scope of a local variable is within the BEGIN ... END\nblock where it is\ndeclared. The variable can be referred to in blocks nested\nwithin the declaring\nblock, except those blocks that declare a variable with the\nsame name.\n \nTYPE OF / ROW TYPE OF\n \nTYPE OF and ROW TYPE OF anchored data types for stored\nroutines were introduced in MariaDB 10.3.\n \nAnchored data types allow a data type to be defined based on\nanother object, such as a table row, rather than\nspecifically set in the declaration. If the anchor object\nchanges, so will the anchored data type. This can lead to\nroutines being easier to maintain, so that if the data type\nin the table is changed, it will automatically be changed in\nthe routine as well.\n \nVariables declared with ROW TYPE OF will have the same\nfeatures as implicit ROW variables. It is not possible to\nuse ROW TYPE OF variables in a LIMIT clause.\n \nThe real data type of TYPE OF and ROW TYPE OF table_name\nwill become known at the very beginning of the stored\nroutine call. ALTER TABLE or DROP TABLE statements performed\ninside the current routine on the tables that appear in\nanchors won\'t affect the data type of the anchored\nvariables, even if the variable is declared after an ALTER\nTABLE or DROP TABLE statement.\n \nThe real data type of a ROW TYPE OF cursor_name variable\nwill become known when execution enters into the block where\nthe variable is declared. Data type instantiation will\nhappen only once. In a cursor ROW TYPE OF variable that is\ndeclared inside a loop, its data type will become known on\nthe very first iteration and won\'t change on further loop\niterations.\n \nThe tables referenced in TYPE OF and ROW TYPE OF\ndeclarations will be checked for existence at the beginning\nof the stored routine call. CREATE PROCEDURE or CREATE\nFUNCTION will not check the referenced tables for existence.\n \nExamples\n-------- \nTYPE OF and ROW TYPE OF from MariaDB 10.3:\n \nDECLARE tmp TYPE OF t1.a;\n -- Get the data type from the column {{a}} in the table\n{{t1}}\n \nDECLARE rec1 ROW TYPE OF t1;\n -- Get the row data type from the table {{t1}}\n \nDECLARE rec2 ROW TYPE OF cur1;\n -- Get the row data type from the cursor {{cur1}}\n \n\n\nURL: https://mariadb.com/kb/en/library/declare-variable/','','https://mariadb.com/kb/en/library/declare-variable/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (307,23,'FETCH','Syntax\n------ \nFETCH cursor_name INTO var_name [, var_name] ...\n \nDescription\n----------- \nThis statement fetches the next row (if a row exists) using\nthe\nspecified open cursor, and advances the cursor pointer.\n \nvar_name can be a local variable, but not a user-defined\nvariable.\n \nIf no more rows are available, a No Data condition occurs\nwith\nSQLSTATE value 02000. To detect this condition, you can set\nup a\nhandler for it (or for a NOT FOUND condition).\n \nSee Cursor Overview for an example.\n \n\n\nURL: https://mariadb.com/kb/en/library/fetch/','','https://mariadb.com/kb/en/library/fetch/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (308,23,'FOR','FOR loops were introduced in MariaDB 10.3.\n \nSyntax\n------ \nInteger range FOR loop:\n \n[begin_label:]\nFOR var_name IN [ REVERSE ] lower_bound .. upper_bound\nDO statement_list\nEND FOR [ end_label ]\n \nExplicit cursor FOR loop\n \n[begin_label:]\nFOR record_name IN cursor_name [ (\ncursor_actual_parameter_list)]\nDO statement_list\nEND FOR [ end_label ]\n \nExplicit cursor FOR loop (Oracle mode)\n \n[begin_label:]\nFOR record_name IN cursor_name [ (\ncursor_actual_parameter_list)]\nLOOP\n statement_list\nEND LOOP [ end_label ]\n \nImplicit cursor FOR loop\n \n[begin_label:]\nFOR record_name IN ( select_statement )\nDO statement_list\nEND FOR [ end_label ]\n \nDescription\n----------- \nFOR loops allow code to be executed a fixed number of times.\n \nIn an integer range FOR loop, MariaDB will compare the lower\nbound and upper bound values, and assign the lower bound\nvalue to a counter. If REVERSE is not specified, and the\nupper bound value is greater than or equal to the counter,\nthe counter will be incremented and the statement will\ncontinue, after which the loop is entered again. If the\nupper bound value is greater than the counter, the loop will\nbe exited.\n \nIf REVERSE is specified, the counter is decremented, and the\nupper bound value needs to be less than or equal for the\nloop to continue.\n \nExamples\n-------- \nIntger range FOR loop:\n \nCREATE TABLE t1 (a INT);\n \nDELIMITER //\n \nFOR i IN 1..3\nDO\n INSERT INTO t1 VALUES (i);\nEND FOR;\n \n//\n \nDELIMITER ;\n \nSELECT * FROM t1;\n \n+------+\n| a |\n+------+\n| 1 |\n| 2 |\n| 3 |\n+------+\n \nREVERSE integer range FOR loop:\n \nCREATE OR REPLACE TABLE t1 (a INT);\n \nDELIMITER //\nFOR i IN REVERSE 12..4\n DO\n INSERT INTO t1 VALUES (i);\nEND FOR;\n \n//\nQuery OK, 9 rows affected (0.422 sec)\n \nDELIMITER ;\n \nSELECT * FROM t1;\n \n+------+\n| a |\n+------+\n| 12 |\n| 11 |\n| 10 |\n| 9 |\n| 8 |\n| 7 |\n| 6 |\n| 5 |\n| 4 |\n+------+\n \nExplicit cursor in Oracle mode:\n \nSET sql_mode=ORACLE;\n \nCREATE OR REPLACE TABLE t1 (a INT, b VARCHAR(32));\n \nINSERT INTO t1 VALUES (10,\'b0\');\nINSERT INTO t1 VALUES (11,\'b1\');\nINSERT INTO t1 VALUES (12,\'b2\');\n \nDELIMITER //\n \nCREATE OR REPLACE PROCEDURE p1(pa INT) AS \n CURSOR cur(va INT) IS\n SELECT a, b FROM t1 WHERE a=va;\n \nBEGIN\n FOR rec IN cur(pa)\n LOOP\n SELECT rec.a, rec.b;\n \n END LOOP;\n \nEND;\n \n//\n \nDELIMITER ;\n \nCALL p1(10);\n+-------+-------+\n| rec.a | rec.b |\n+-------+-------+\n| 10 | b0 |\n+-------+-------+\n \nCALL p1(11);\n+-------+-------+\n| rec.a | rec.b |\n+-------+-------+\n| 11 | b1 |\n+-------+-------+\n \nCALL p1(12);\n+-------+-------+\n| rec.a | rec.b |\n+-------+-------+\n| 12 | b2 |\n+-------+-------+\n \nCALL p1(13);\nQuery OK, 0 rows affected (0.000 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/for/','','https://mariadb.com/kb/en/library/for/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (309,23,'GOTO','The GOTO statement was introduced in MariaDB 10.3 for Oracle\ncompatibility.\n \nSyntax\n------ \nGOTO label\n \nDescription\n----------- \nThe GOTO statement causes the code to jump to the specified\nlabel, and continue operating from there. It is only\naccepted when in Oracle mode.\n \nExample\n \nSET sql_mode=ORACLE;\n \nDELIMITER //\n \nCREATE OR REPLACE PROCEDURE p1 AS\n \nBEGIN\n \n SELECT 1;\n \n GOTO label;\n \n SELECT 2;\n \n SELECT 3;\n \nEND;\n \n//\n \nDELIMITER \n \ncall p1();\n+---+\n| 1 |\n+---+\n| 1 |\n+---+\n1 row in set (0.000 sec)\n \n+---+\n| 3 |\n+---+\n| 3 |\n+---+\n1 row in set (0.000 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/goto/','','https://mariadb.com/kb/en/library/goto/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (310,23,'IF','Syntax\n------ \nIF search_condition THEN statement_list\n [ELSEIF search_condition THEN statement_list] ...\n [ELSE statement_list]\nEND IF;\n \nDescription\n----------- \nIF implements a basic conditional construct. If the\nsearch_condition\nevaluates to true, the corresponding SQL statement list is\nexecuted.\nIf no search_condition matches, the statement list in the\nELSE clause\nis executed. Each statement_list consists of one or more\nstatements.\n \n\n\nURL: https://mariadb.com/kb/en/library/if/','','https://mariadb.com/kb/en/library/if/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (311,23,'ITERATE','Syntax\n------ \nITERATE label\n \nITERATE can appear only within LOOP, REPEAT, and WHILE\nstatements.\nITERATE means \"do the loop again\", and uses the\nstatement\'s label to determine which statements to repeat.\nThe label must be in the same stored program, not in a\ncaller procedure.\n \nIf you try to use ITERATE with a non-existing label, or if\nthe label is associated to a construct which is not a loop,\nthe following error will be produced:\n \nERROR 1308 (42000): ITERATE with no matching label: \n \nBelow is an example of how ITERATE might be used:\n \nCREATE PROCEDURE doiterate(p1 INT)\nBEGIN\n label1: LOOP\n SET p1 = p1 + 1;\n \n IF p1 \n\nURL: https://mariadb.com/kb/en/library/iterate/','','https://mariadb.com/kb/en/library/iterate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (312,23,'Labels','Syntax\n------ \nlabel: \n[label]\n \nLabels are MariaDB identifiers which can be used to identify\na BEGIN ... END construct or a loop. They have a maximum\nlength of 16 characters and can be quoted with backticks\n(i.e.., `).\n \nLabels have a start part and an end part. The start part\nmust precede the portion of code it refers to, must be\nfollowed by a colon (:) and can be on the same or different\nline. The end part is optional and adds nothing, but can\nmake the code more readable. If used, the end part must\nprecede the construct\'s delimiter (;). Constructs\nidentified by a label can be nested. Each construct can be\nidentified by only one label.\n \nLabels need not be unique in the stored program they belong\nto. However, a label for an inner loop cannot be identical\nto a label for an outer loop. In this case, the following\nerror would be produced:\n \nERROR 1309 (42000): Redefining label \n \nLEAVE and ITERATE statements can be used to exit or repeat a\nportion of code identified by a label. They must be in the\nsame Stored Routine, Trigger or Event which contains the\ntarget label.\n \nBelow is an example using a simple label that is used to\nexit a LOOP:\n \nCREATE PROCEDURE `test_sp`()\nBEGIN\n `my_label`:\n LOOP\n SELECT \'looping\';\n \n LEAVE `my_label`;\n \n END LOOP;\n \n SELECT \'out of loop\';\n \nEND;\n \nThe following label is used to exit a procedure, and has an\nend part:\n \nCREATE PROCEDURE `test_sp`()\n`my_label`:\nBEGIN\n IF @var = 1 THEN\n LEAVE `my_label`;\n \n END IF;\n \n DO something();\nEND `my_label`;\n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/labels/','','https://mariadb.com/kb/en/library/labels/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (313,23,'LEAVE','Syntax\n------ \nLEAVE label\n \nThis statement is used to exit the flow control construct\nthat has the\ngiven label. The label must be in the same stored program,\nnot in a caller procedure. LEAVE can be used within BEGIN\n... END or loop constructs\n(LOOP, REPEAT, WHILE). In Stored Procedures, Triggers and\nEvents, LEAVE can refer to the outmost BEGIN ... END\nconstruct; in that case, the program exits the procedure. In\nStored Functions, RETURN can be used instead.\n \nNote that LEAVE cannot be used to exit a DECLARE HANDLER\nblock.\n \nIf you try to LEAVE a non-existing label, or if you try to\nLEAVE a HANDLER block, the following error will be produced:\n \nERROR 1308 (42000): LEAVE with no matching label: \n \nThe following example uses LEAVE to exit the procedure if a\ncondition is true:\n \nCREATE PROCEDURE proc(IN p TINYINT)\nCONTAINS SQL\n`whole_proc`:\nBEGIN\n SELECT 1;\n \n IF p \n\nURL: https://mariadb.com/kb/en/library/leave/','','https://mariadb.com/kb/en/library/leave/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (314,23,'LOOP','Syntax\n------ \n[begin_label:] LOOP\n statement_list\nEND LOOP [end_label]\n \nDescription\n----------- \nLOOP implements a simple loop construct, enabling repeated\nexecution\nof the statement list, which consists of one or more\nstatements, each\nterminated by a semicolon (i.e., ;) statement delimiter. The\nstatements\nwithin the loop are repeated until the loop is exited;\nusually this is\naccomplished with a LEAVE statement.\n \nA LOOP statement can be labeled. end_label cannot be given\nunless\nbegin_label also is present. If both are present, they must\nbe the\nsame.\n \nSee Delimiters in the mysql client for more on delimiter\nusage in the client.\n \n\n\nURL: https://mariadb.com/kb/en/library/loop/','','https://mariadb.com/kb/en/library/loop/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (315,23,'OPEN','Syntax\n------ \n\n\nURL: https://mariadb.com/kb/en/library/open/','','https://mariadb.com/kb/en/library/open/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (316,23,'REPEAT LOOP','Syntax\n------ \n[begin_label:] REPEAT\n statement_list\nUNTIL search_condition\nEND REPEAT [end_label]\n \nThe statement list within a REPEAT statement is repeated\nuntil the\nsearch_condition is true. Thus, a REPEAT always enters the\nloop at\nleast once. statement_list consists of one or more\nstatements, each\nterminated by a semicolon (i.e., ;) statement delimiter.\n \nA REPEAT statement can be labeled. end_label cannot be given\nunless\nbegin_label also is present. If both are present, they must\nbe the\nsame.\n \nSee Delimiters in the mysql client for more on client\ndelimiter usage.\n \nDELIMITER //\n \nCREATE PROCEDURE dorepeat(p1 INT)\n BEGIN\n SET @x = 0;\n \n REPEAT SET @x = @x + 1;\n UNTIL @x > p1 END REPEAT;\n \n END\n//\n \nCALL dorepeat(1000)//\n \nSELECT @x//\n+------+\n| @x |\n+------+\n| 1001 |\n+------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/repeat-loop/','','https://mariadb.com/kb/en/library/repeat-loop/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (317,23,'RESIGNAL','SIGNAL and RESIGNAL were both introduced in MariaDB 5.5.\n \nSyntax\n------ \nRESIGNAL [error_condition]\n [SET error_property\n [, error_property] ...]\n \nerror_condition:\n SQLSTATE [VALUE] \'sqlstate_value\'\n | condition_name\n \nerror_property:\n error_property_name = \n \nerror_property_name:\n CLASS_ORIGIN\n | SUBCLASS_ORIGIN\n | MESSAGE_TEXT\n | MYSQL_ERRNO\n | CONSTRAINT_CATALOG\n | CONSTRAINT_SCHEMA\n | CONSTRAINT_NAME\n | CATALOG_NAME\n | SCHEMA_NAME\n | TABLE_NAME\n | COLUMN_NAME\n | CURSOR_NAME\n \nDescription\n----------- \nThe syntax of RESIGNAL and its semantics are very similar to\nSIGNAL. This statement can only be used within an error\nHANDLER. It produces an error, like SIGNAL. RESIGNAL clauses\nare the same as SIGNAL, except that they all are optional,\neven SQLSTATE. All the properties which are not specified in\nRESIGNAL, will be identical to the properties of the error\nthat was received by the error HANDLER. For a description of\nthe clauses, see diagnostics area.\n \nNote that RESIGNAL does not empty the diagnostics area: it\njust appends another error condition.\n \nRESIGNAL, without any clauses, produces an error which is\nidentical to the error that was received by HANDLER.\n \nIf used out of a HANDLER construct, RESIGNAL produces the\nfollowing error:\n \nERROR 1645 (0K000): RESIGNAL when handler not active\n \nIn MariaDB 5.5, if a HANDLER contained a CALL to another\nprocedure, that procedure could use RESIGNAL. Since MariaDB\n10.0, trying to do this raises the above error.\n \nFor a list of SQLSTATE values and MariaDB error codes, see\nMariaDB Error Codes.\n \nThe following procedure tries to query two tables which\ndon\'t exist, producing a 1146 error in both cases. Those\nerrors will trigger the HANDLER. The first time the error\nwill be ignored and the client will not receive it, but the\nsecond time, the error is re-signaled, so the client will\nreceive it.\n \nCREATE PROCEDURE test_error( )\nBEGIN\n DECLARE CONTINUE HANDLER\n FOR 1146\n BEGIN\n IF @hide_errors IS FALSE THEN\n RESIGNAL;\n \n END IF;\n \n END;\n \n SET @hide_errors = TRUE;\n \n SELECT \'Next error will be ignored\' AS msg;\n \n SELECT `c` FROM `temptab_one`;\n \n SELECT \'Next error won\'\'t be ignored\' AS msg;\n \n SET @hide_errors = FALSE;\n \n SELECT `c` FROM `temptab_two`;\n \nEND;\n \nCALL test_error( );\n \n+----------------------------+\n| msg |\n+----------------------------+\n| Next error will be ignored |\n+----------------------------+\n \n+-----------------------------+\n| msg |\n+-----------------------------+\n| Next error won\'t be ignored |\n+-----------------------------+\n \nERROR 1146 (42S02): Table \'test.temptab_two\' doesn\'t\nexist\n \nThe following procedure re-signals an error, modifying only\nthe error message to clarify the cause of the problem.\n \nCREATE PROCEDURE test_error()\nBEGIN\n DECLARE CONTINUE HANDLER\n FOR 1146\n BEGIN\n RESIGNAL SET\n MESSAGE_TEXT = \'`temptab` does not exist\';\n \n END;\n \n SELECT `c` FROM `temptab`;\n \nEND;\n \nCALL test_error( );\nERROR 1146 (42S02): `temptab` does not exist\n \nAs explained above, this works on MariaDB 5.5, but produces\na 1645 error since 10.0.\n \nCREATE PROCEDURE handle_error()\nBEGIN\n RESIGNAL;\n \nEND;\n \nCREATE PROCEDURE p()\nBEGIN\n DECLARE EXIT HANDLER FOR SQLEXCEPTION CALL p();\n SIGNAL SQLSTATE \'45000\';\n \nEND;\n \n\n\nURL: https://mariadb.com/kb/en/library/resignal/','','https://mariadb.com/kb/en/library/resignal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (318,23,'RETURN','Syntax\n------ \nRETURN expr \n \nThe RETURN statement terminates execution of a stored\nfunction and\nreturns the value expr to the function caller. There must be\nat least\none RETURN statement in a stored function. If the function\nhas multiple exit points, all exit points must have a\nRETURN.\n \nThis statement is not used in stored procedures, triggers,\nor events. LEAVE can be used instead.\n \nThe following example shows that RETURN can return the\nresult of a scalar subquery:\n \nCREATE FUNCTION users_count() RETURNS BOOL\n READS SQL DATA\nBEGIN\n RETURN (SELECT COUNT(DISTINCT User) FROM mysql.user);\nEND;\n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/return/','','https://mariadb.com/kb/en/library/return/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (319,23,'SELECT INTO','Syntax\n------ \nSELECT col_name [, col_name] ...\n INTO var_name [, var_name] ...\n table_expr\n \nDescription\n----------- \nSELECT ... INTO enables selected columns to be stored\ndirectly\ninto variables. No resultset is produced. The query should\nreturn a single row. If the query\nreturns no rows, a warning with error code 1329 occurs (No\ndata), and\nthe variable values remain unchanged. If the query returns\nmultiple\nrows, error 1172 occurs (Result consisted of more than one\nrow). If it\nis possible that the statement may retrieve multiple rows,\nyou can use\nLIMIT 1 to limit the result set to a single row.\n \nThe INTO clause can also be specified at the end of the\nstatement.\n \nIn the context of such statements that occur as part of\nevents\nexecuted by the Event Scheduler, diagnostics messages (not\nonly\nerrors, but also warnings) are written to the error log,\nand, on\nWindows, to the application event log.\n \nThis statement can be used with both local variables and\nuser-defined variables.\n \nFor the complete syntax, see SELECT.\n \nAnother way to set a variable\'s value is the SET statement.\n \nSELECT ... INTO results are not stored in the query cache\neven if SQL_CACHE is specified.\n \nExamples\n-------- \nSELECT id, data INTO @x,@y \nFROM test.t1 LIMIT 1;\n \n\n\nURL: https://mariadb.com/kb/en/library/selectinto/','','https://mariadb.com/kb/en/library/selectinto/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (320,23,'SIGNAL','SIGNAL and RESIGNAL were both introduced in MariaDB 5.5.\n \nSyntax\n------ \nSIGNAL error_condition\n [SET error_property\n [, error_property] ...]\n \nerror_condition:\n SQLSTATE [VALUE] \'sqlstate_value\'\n | condition_name\n \nerror_property:\n error_property_name = \n \nerror_property_name:\n CLASS_ORIGIN\n | SUBCLASS_ORIGIN\n | MESSAGE_TEXT\n | MYSQL_ERRNO\n | CONSTRAINT_CATALOG\n | CONSTRAINT_SCHEMA\n | CONSTRAINT_NAME\n | CATALOG_NAME\n | SCHEMA_NAME\n | TABLE_NAME\n | COLUMN_NAME\n | CURSOR_NAME\n \nSIGNAL empties the diagnostics area and produces a custom\nerror. This statement can be used anywhere, but is generally\nuseful when used inside a stored program. When the error is\nproduced, it can be caught by a HANDLER. If not, the current\nstored program, or the current statement, will terminate\nwith the specified error.\n \nSometimes an error HANDLER just needs to SIGNAL the same\nerror it received, optionally with some changes. Usually the\nRESIGNAL statement is the most convenient way to do this.\n \nerror_condition can be an SQLSTATE value or a named error\ncondition defined via DECLARE CONDITION. SQLSTATE must be a\nconstant string consisting of five characters. These codes\nare standard to ODBC and ANSI SQL. For customized errors,\nthe recommended SQLSTATE is \'45000\'. For a list of\nSQLSTATE values used by MariaDB, see the MariaDB Error Codes\npage. The SQLSTATE can be read via the API method\nmysql_sqlstate( ). \n \nTo specify error properties user-defined variables and local\nvariables can be used, as well as character set conversions\n(but you can\'t set a collation).\n \nThe error properties, their type and their default values\nare explained in the diagnostics area page.\n \nErrors\n \nIf the SQLSTATE is not valid, the following error like this\nwill be produced:\n \nERROR 1407 (42000): Bad SQLSTATE: \'123456\'\n \nIf a property is specified more than once, an error like\nthis will be produced:\n \nERROR 1641 (42000): Duplicate condition information item\n\'MESSAGE_TEXT\'\n \nIf you specify a condition name which is not declared, an\nerror like this will be produced:\n \nERROR 1319 (42000): Undefined CONDITION: cond_name\n \nIf MYSQL_ERRNO is out of range, you will get an error like\nthis:\n \nERROR 1231 (42000): Variable \'MYSQL_ERRNO\' can\'t be set\nto the value of \'0\'\n \nExamples\n-------- \nHere\'s what happens if SIGNAL is used in the client to\ngenerate errors:\n \nSIGNAL SQLSTATE \'01000\';\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+---------+------+------------------------------------------+\n| Level | Code | Message |\n+---------+------+------------------------------------------+\n| Warning | 1642 | Unhandled user-defined warning condition\n|\n+---------+------+------------------------------------------+\n1 row in set (0.06 sec)\n \nSIGNAL SQLSTATE \'02000\';\n \nERROR 1643 (02000): Unhandled user-defined not found\ncondition\n \nHow to specify MYSQL_ERRNO and MESSAGE_TEXT properties:\n \nSIGNAL SQLSTATE \'45000\' SET MYSQL_ERRNO=30001,\nMESSAGE_TEXT=\'H\nello, world!\';\n \nERROR 30001 (45000): Hello, world!\n \nThe following code shows how to use user variables, local\nvariables and character set conversion with SIGNAL:\n \nCREATE PROCEDURE test_error(x INT)\nBEGIN\n DECLARE errno SMALLINT UNSIGNED DEFAULT 31001;\n \n SET @errmsg = \'Hello, world!\';\n \n IF x = 1 THEN\n SIGNAL SQLSTATE \'45000\' SET\n MYSQL_ERRNO = errno,\n MESSAGE_TEXT = @errmsg;\n \n ELSE\n SIGNAL SQLSTATE \'45000\' SET\n MYSQL_ERRNO = errno,\n MESSAGE_TEXT = _utf8\'Hello, world!\';\n \n END IF;\n \nEND;\n \nHow to use named error conditions:\n \nCREATE PROCEDURE test_error(n INT)\nBEGIN\n DECLARE `too_big` CONDITION FOR SQLSTATE \'45000\';\n \n IF n > 10 THEN\n SIGNAL `too_big`;\n \n END IF;\n \nEND;\n \nIn this example, we\'ll define a HANDLER for an error code.\nWhen the error occurs, we SIGNAL a more informative error\nwhich makes sense for our procedure:\n \nCREATE PROCEDURE test_error()\nBEGIN\n DECLARE EXIT HANDLER\n FOR 1146\n BEGIN\n SIGNAL SQLSTATE \'45000\' SET\n MESSAGE_TEXT = \'Temporary tables not found; did you call\ninit() procedure?\';\n \n END;\n \n -- this will produce a 1146 error\n SELECT `c` FROM `temptab`;\n \nEND;\n \n\n\nURL: https://mariadb.com/kb/en/library/signal/','','https://mariadb.com/kb/en/library/signal/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (321,23,'WHILE','Syntax\n------ \n[begin_label:] WHILE search_condition DO\n statement_list\nEND WHILE [end_label]\n \nDescription\n----------- \nThe statement list within a WHILE statement is repeated as\nlong as the\nsearch_condition is true. statement_list consists of one or\nmore\nstatements. If the loop must be executed at least once,\nREPEAT ... LOOP can be used instead.\n \nA WHILE statement can be labeled. end_label cannot be given\nunless\nbegin_label also is present. If both are present, they must\nbe the\nsame.\n \nExamples\n-------- \nCREATE PROCEDURE dowhile()\nBEGIN\n DECLARE v1 INT DEFAULT 5;\n \n WHILE v1 > 0 DO\n ...\n SET v1 = v1 - 1;\n \n END WHILE;\n \nEND\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/while/','','https://mariadb.com/kb/en/library/while/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (322,24,'BUFFER','A synonym for ST_BUFFER.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/buffer/','','https://mariadb.com/kb/en/library/buffer/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (323,24,'CONVEXHULL','A synonym for ST_CONVEXHULL.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/convexhull/','','https://mariadb.com/kb/en/library/convexhull/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (324,24,'GEOMETRYCOLLECTION','Syntax\n------ \nGeometryCollection(g1,g2,...)\n \nDescription\n----------- \nConstructs a WKB GeometryCollection. If any argument is not\na well-formed WKB representation of a geometry, the return\nvalue is NULL.\n \nExamples\n-------- \nCREATE TABLE gis_geometrycollection (g GEOMETRYCOLLECTION);\nSHOW FIELDS FROM gis_geometrycollection;\n \nINSERT INTO gis_geometrycollection VALUES\n (GeomCollFromText(\'GEOMETRYCOLLECTION(POINT(0 0),\nLINESTRING(0 0,10 10))\')),\n (GeometryFromWKB(AsWKB(GeometryCollection(Point(44, 6),\nLineString(Point(3, 6), Point(7, 9)))))),\n (GeomFromText(\'GeometryCollection()\')),\n (GeomFromText(\'GeometryCollection EMPTY\'));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/geometrycollection/','','https://mariadb.com/kb/en/library/geometrycollection/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (325,24,'LINESTRING','Syntax\n------ \nLineString(pt1,pt2,...)\n \nDescription\n----------- \nConstructs a WKB LineString value from a number of WKB Point\narguments. If any argument is not a WKB Point, the return\nvalue is\nNULL. If the number of Point arguments is less than two, the\nreturn value is NULL.\n \nExamples\n-------- \nSET @ls = \'LineString(1 1,2 2,3 3)\';\n \nSELECT AsText(EndPoint(GeomFromText(@ls)));\n+-------------------------------------+\n| AsText(EndPoint(GeomFromText(@ls))) |\n+-------------------------------------+\n| POINT(3 3) |\n+-------------------------------------+\n \nCREATE TABLE gis_line (g LINESTRING);\nINSERT INTO gis_line VALUES\n (LineFromText(\'LINESTRING(0 0,0 10,10 0)\')),\n (LineStringFromText(\'LINESTRING(10 10,20 10,20 20,10 20,10\n10)\')),\n (LineStringFromWKB(AsWKB(LineString(Point(10, 10),\nPoint(40, 10)))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/linestring/','','https://mariadb.com/kb/en/library/linestring/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (326,24,'MULTILINESTRING','Syntax\n------ \nMultiLineString(ls1,ls2,...)\n \nDescription\n----------- \nConstructs a WKB MultiLineString value using WKB LineString\narguments. If any argument is not a WKB LineString, the\nreturn value is\nNULL.\n \nExample\n \nCREATE TABLE gis_multi_line (g MULTILINESTRING);\nINSERT INTO gis_multi_line VALUES\n (MultiLineStringFromText(\'MULTILINESTRING((10 48,10 21,10\n0),(16 0,16 23,16 48))\')),\n (MLineFromText(\'MULTILINESTRING((10 48,10 21,10 0))\')),\n (MLineFromWKB(AsWKB(MultiLineString(LineString(Point(1, 2),\nPoint(3, 5)), LineString(Point(2, 5),Point(5, 8),Point(21,\n7))))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/multilinestring/','','https://mariadb.com/kb/en/library/multilinestring/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (327,24,'MULTIPOINT','Syntax\n------ \nMultiPoint(pt1,pt2,...)\n \nDescription\n----------- \nConstructs a WKB MultiPoint value using WKB Point arguments.\nIf any argument is not a WKB Point, the return value is\nNULL.\n \nExamples\n-------- \nSET @g = ST_GEOMFROMTEXT(\'MultiPoint( 1 1, 2 2, 5 3, 7 2, 9\n3, 8 4, 6 6, 6 9, 4 9, 1 5 )\');\n \nCREATE TABLE gis_multi_point (g MULTIPOINT);\nINSERT INTO gis_multi_point VALUES\n (MultiPointFromText(\'MULTIPOINT(0 0,10 10,10 20,20\n20)\')),\n (MPointFromText(\'MULTIPOINT(1 1,11 11,11 21,21 21)\')),\n (MPointFromWKB(AsWKB(MultiPoint(Point(3, 6), Point(4,\n10)))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/multipoint/','','https://mariadb.com/kb/en/library/multipoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (328,24,'MULTIPOLYGON','Syntax\n------ \nMultiPolygon(poly1,poly2,...)\n \nDescription\n----------- \nConstructs a WKB MultiPolygon value from a set of WKB\nPolygon arguments. If any argument is not a WKB Polygon, the\nreturn value is NULL.\n \nExample\n \nCREATE TABLE gis_multi_polygon (g MULTIPOLYGON);\nINSERT INTO gis_multi_polygon VALUES\n (MultiPolygonFromText(\'MULTIPOLYGON(((28 26,28 0,84 0,84\n42,28 26),(52 18,66 23,73 9,48 6,52 18)),((59 18,67 18,67\n13,59 13,59 18)))\')),\n (MPolyFromText(\'MULTIPOLYGON(((28 26,28 0,84 0,84 42,28\n26),(52 18,66 23,73 9,48 6,52 18)),((59 18,67 18,67 13,59\n13,59 18)))\')),\n (MPolyFromWKB(AsWKB(MultiPolygon(Polygon(LineString(Point(0,\n3), Point(3, 3), Point(3, 0), Point(0, 3)))))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/multipolygon/','','https://mariadb.com/kb/en/library/multipolygon/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (329,24,'POINT','Syntax\n------ \nPoint(x,y)\n \nDescription\n----------- \nConstructs a WKB Point using the given coordinates.\n \nExamples\n-------- \nSET @g = ST_GEOMFROMTEXT(\'Point(1 1)\');\n \nCREATE TABLE gis_point (g POINT);\nINSERT INTO gis_point VALUES\n (PointFromText(\'POINT(10 10)\')),\n (PointFromText(\'POINT(20 10)\')),\n (PointFromText(\'POINT(20 20)\')),\n (PointFromWKB(AsWKB(PointFromText(\'POINT(10 20)\'))));\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/point/','','https://mariadb.com/kb/en/library/point/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (330,24,'PointOnSurface','A synonym for ST_PointOnSurface.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/pointonsurface/','','https://mariadb.com/kb/en/library/pointonsurface/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (331,24,'POLYGON','Syntax\n------ \nPolygon(ls1,ls2,...)\n \nDescription\n----------- \nConstructs a WKB Polygon value from a number of WKB\nLineString\narguments. If any argument does not represent the WKB of a\nLinearRing (that is,\nnot a closed and simple LineString) the return value is\nNULL.\n \nNote that according to the OpenGIS standard, a POLYGON\nshould have exactly one ExteriorRing and all other rings\nshould lie within that ExteriorRing and thus be the\nInteriorRings. Practically, however, some systems, including\nMariaDB\'s, permit polygons to have several\n\'ExteriorRings\'. In the case of there being multiple,\nnon-overlapping exterior rings ST_NUMINTERIORRINGS() will\nreturn 1.\n \nExamples\n-------- \nSET @g = ST_GEOMFROMTEXT(\'POLYGON((1 1,1 5,4 9,6 9,9 3,7\n2,1 1))\');\n \nCREATE TABLE gis_polygon (g POLYGON);\nINSERT INTO gis_polygon VALUES\n (PolygonFromText(\'POLYGON((10 10,20 10,20 20,10 20,10\n10))\')),\n (PolyFromText(\'POLYGON((0 0,50 0,50 50,0 50,0 0), (10\n10,20 10,20 20,10 20,10 10))\')),\n (PolyFromWKB(AsWKB(Polygon(LineString(Point(0, 0),\nPoint(30, 0), Point(30, 30), Point(0, 0))))));\n \nNon-overlapping \'polygon\':\n \nSELECT ST_NumInteriorRings(ST_PolyFromText(\'POLYGON((0 0,10\n0,10 10,0 10,0 0),\n (-1 -1,-5 -1,-5 -5,-1 -5,-1 -1))\')) AS NumInteriorRings;\n \n+------------------+\n| NumInteriorRings |\n+------------------+\n| 1 |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/polygon/','','https://mariadb.com/kb/en/library/polygon/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (332,24,'ST_BUFFER','Syntax\n------ \nST_BUFFER(g1,r)\nBUFFER(g1,r)\n \nDescription\n----------- \nReturns a geometry that represents all points whose distance\nfrom geometry g1 is less than or equal to distance, or\nradius, r.\n \nUses for this function could include creating for example a\nnew geometry representing a buffer zone around an island.\n \nBUFFER() is a synonym.\n \nExamples\n-------- \nDetermining whether a point is within a buffer zone:\n \nSET @g1 = ST_GEOMFROMTEXT(\'POLYGON((10 10, 10 20, 20 20, 20\n10, 10 10))\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'POINT(8 8)\');\n \nSELECT ST_WITHIN(@g2,ST_BUFFER(@g1,5));\n+---------------------------------+\n| ST_WITHIN(@g2,ST_BUFFER(@g1,5)) |\n+---------------------------------+\n| 1 |\n+---------------------------------+\n \nSELECT ST_WITHIN(@g2,ST_BUFFER(@g1,1));\n+---------------------------------+\n| ST_WITHIN(@g2,ST_BUFFER(@g1,1)) |\n+---------------------------------+\n| 0 |\n+---------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_buffer/','','https://mariadb.com/kb/en/library/st_buffer/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (333,24,'ST_CONVEXHULL','ST_ConvexHull() was introduced in MariaDB 10.1.2\n \nSyntax\n------ \nST_ConvexHull(g)\nConvexHull(g)\n \nDescription\n----------- \nGiven a geometry, returns a geometry that is the minimum\nconvex geometry enclosing all geometries within the set.\nReturns NULL if the geometry value is NULL or an empty\nvalue.\n \nST_ConvexHull() and ConvexHull() are synonyms.\n \nExamples\n-------- \nThe ConvexHull of a single point is simply the single point:\n \nSET @g = ST_GEOMFROMTEXT(\'Point(0 0)\');\n \nSELECT ST_ASTEXT(ST_CONVEXHULL(@g));\n+------------------------------+\n| ST_ASTEXT(ST_CONVEXHULL(@g)) |\n+------------------------------+\n| POINT(0 0) |\n+------------------------------+\n \nSET @g = ST_GEOMFROMTEXT(\'MultiPoint(0 0, 1 2, 2 3)\');\n \nSELECT ST_ASTEXT(ST_CONVEXHULL(@g));\n+------------------------------+\n| ST_ASTEXT(ST_CONVEXHULL(@g)) |\n+------------------------------+\n| POLYGON((0 0,1 2,2 3,0 0)) |\n+------------------------------+\n \nSET @g = ST_GEOMFROMTEXT(\'MultiPoint( 1 1, 2 2, 5 3, 7 2, 9\n3, 8 4, 6 6, 6 9, 4 9, 1 5 )\');\n \nSELECT ST_ASTEXT(ST_CONVEXHULL(@g));\n+----------------------------------------+\n| ST_ASTEXT(ST_CONVEXHULL(@g)) |\n+----------------------------------------+\n| POLYGON((1 1,1 5,4 9,6 9,9 3,7 2,1 1)) |\n+----------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_convexhull/','','https://mariadb.com/kb/en/library/st_convexhull/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (334,24,'ST_INTERSECTION','Syntax\n------ \nST_INTERSECTION(g1,g2)\n \nDescription\n----------- \nReturns a geometry that is the intersection, or shared\nportion, of geometry g1 and geometry g2.\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(2 1)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(2 1, 0 2)\');\n \nSELECT ASTEXT(ST_INTERSECTION(@g1,@g2));\n+----------------------------------+\n| ASTEXT(ST_INTERSECTION(@g1,@g2)) |\n+----------------------------------+\n| POINT(2 1) |\n+----------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_intersection/','','https://mariadb.com/kb/en/library/st_intersection/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (335,24,'ST_POINTONSURFACE','ST_POINTONSURFACE() was introduced in MariaDB 10.1.2\n \nSyntax\n------ \nST_PointOnSurface(g)\nPointOnSurface(g)\n \nDescription\n----------- \nGiven a geometry, returns a POINT guaranteed to intersect a\nsurface. However, see MDEV-7514.\n \nST_PointOnSurface() and PointOnSurface() are synonyms.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_pointonsurface/','','https://mariadb.com/kb/en/library/st_pointonsurface/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (336,24,'ST_SYMDIFFERENCE','Syntax\n------ \nST_SYMDIFFERENCE(g1,g2)\n \nDescription\n----------- \nReturns a geometry that represents the portions of geometry\ng1 and geometry g2 that don\'t intersect.\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'LINESTRING(10 20, 10 40)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(10 15, 10 25)\');\n \nSELECT ASTEXT(ST_SYMDIFFERENCE(@g1,@g2));\n+----------------------------------------------+\n| ASTEXT(ST_SYMDIFFERENCE(@g1,@g2)) |\n+----------------------------------------------+\n| MULTILINESTRING((10 15,10 20),(10 25,10 40)) |\n+----------------------------------------------+\n \nSET @g2 = ST_GeomFromText(\'LINESTRING(10 20, 10 41)\');\n \nSELECT ASTEXT(ST_SYMDIFFERENCE(@g1,@g2));\n+-----------------------------------+\n| ASTEXT(ST_SYMDIFFERENCE(@g1,@g2)) |\n+-----------------------------------+\n| LINESTRING(10 40,10 41) |\n+-----------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_symdifference/','','https://mariadb.com/kb/en/library/st_symdifference/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (337,24,'ST_UNION','Syntax\n------ \nST_UNION(g1,g2)\n \nDescription\n----------- \nReturns a geometry that is the union of the geometry g1 and\ngeometry g2.\n \nExamples\n-------- \nSET @g1 = GEOMFROMTEXT(\'POINT (0 2)\');\n \nSET @g2 = GEOMFROMTEXT(\'POINT (2 0)\');\n \nSELECT ASTEXT(ST_UNION(@g1,@g2));\n+---------------------------+\n| ASTEXT(ST_UNION(@g1,@g2)) |\n+---------------------------+\n| MULTIPOINT(2 0,0 2) |\n+---------------------------+\n \nSET @g1 = GEOMFROMTEXT(\'POLYGON((0 0,0 3,3 3,3 0,0 0))\');\n \nSET @g2 = GEOMFROMTEXT(\'POLYGON((2 2,4 2,4 4,2 4,2 2))\');\n \nSELECT ASTEXT(ST_UNION(@g1,@g2));\n+------------------------------------------------+\n| ASTEXT(ST_UNION(@g1,@g2)) |\n+------------------------------------------------+\n| POLYGON((0 0,0 3,2 3,2 4,4 4,4 2,3 2,3 0,0 0)) |\n+------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_union/','','https://mariadb.com/kb/en/library/st_union/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (338,26,'BINLOG','Syntax\n------ \nBINLOG \'str\'\n \nDescription\n----------- \nBINLOG is an internal-use statement. It is generated by the\nmysqlbinlog program as the printable representation of\ncertain events\nin binary log files. The \'str\' value is a base 64-encoded\nstring the that server decodes to determine the data change\nindicated by the\ncorresponding event. This statement requires the SUPER\nprivilege. It was added in MySQL 5.1.5.\n \n\n\nURL: https://mariadb.com/kb/en/library/binlog/','','https://mariadb.com/kb/en/library/binlog/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (339,26,'CACHE INDEX','Syntax\n------ \nCACHE INDEX \n tbl_index_list [, tbl_index_list] ...\n IN key_cache_name \n \ntbl_index_list:\n tbl_name [[INDEX|KEY] (index_name[, index_name] ...)]\n \nDescription\n----------- \nThe CACHE INDEX statement assigns table indexes to a\nspecific key\ncache. It is used only for MyISAM tables.\n \nA default key cache exists and cannot be destroyed. To\ncreate more key caches, the key_buffer_size server system\nvariable.\n \nThe associations between tables indexes and key caches are\nlost on server restart. To recreate them automatically, it\nis necessary to configure caches in a configuration file and\ninclude some CACHE INDEX (and optionally LOAD INDEX)\nstatements in the init file.\n \nExamples\n-------- \nThe following statement assigns indexes from the tables t1,\nt2, and t3\nto the key cache named hot_cache:\n \nCACHE INDEX t1, t2, t3 IN hot_cache;\n+---------+--------------------+----------+----------+\n| Table | Op | Msg_type | Msg_text |\n+---------+--------------------+----------+----------+\n| test.t1 | assign_to_keycache | status | OK |\n| test.t2 | assign_to_keycache | status | OK |\n| test.t3 | assign_to_keycache | status | OK |\n+---------+--------------------+----------+----------+\n \nImplementation (for MyISAM)\n \nNormally CACHE INDEX should not take a long time to execute.\nInternally it\'s implemented the following way:\nFind the right key cache (under\nLOCK_global_system_variables)\nOpen the table with a TL_READ_NO_INSERT lock.\nFlush the original key cache for the given file (under key\ncache lock)\nFlush the new key cache for the given file (safety)\nMove the file to the new key cache (under file share lock)\n \nThe only possible long operations are getting the locks for\nthe table and flushing the original key cache, if there were\nmany key blocks for the file in it.\n \nWe plan to also add CACHE INDEX for Aria tables if there is\na need for this.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/cache-index/','','https://mariadb.com/kb/en/library/cache-index/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (340,26,'FLUSH','Syntax\n------ \nFLUSH [NO_WRITE_TO_BINLOG | LOCAL]\n flush_option [, flush_option] ...\n \nor when flushing tables:\n \nFLUSH [NO_WRITE_TO_BINLOG | LOCAL] TABLES [table_list]\n[table_flush_option]\n \nwhere table_list is a list of tables separated by , (comma).\n \nDescription\n----------- \nThe FLUSH statement clears or reloads various internal\ncaches used by\nMariaDB. To execute FLUSH, you must have the RELOAD\nprivilege. See GRANT.\n \nThe RESET statement is similar to FLUSH. See\nRESET.\n \nYou cannot issue a FLUSH statement from within a stored\nfunction or a trigger. Doing so within a stored procedure is\npermitted, as long as it is not called by a stored function\nor trigger. See Stored Routine Limitations, Stored Function\nLimitations and Trigger Limitations.\n \nIf a listed table is a view, an error like the following\nwill be produced:\n \nERROR 1347 (HY000): \'test.v\' is not BASE TABLE\n \nBy default, FLUSH statements are written to the binary log\nand will be replicated. The NO_WRITE_TO_BINLOG keyword\n(LOCAL is an alias) will ensure the statement is not written\nto the binary log. \n \nThe different flush options are:\n \nOption | Description | \n \nCHANGED_PAGE_BITMAPS | Internal command used for backup\npurposes. See the Information Schema CHANGED_PAGE_BITMAPS\nTable. | \n \nCLIENT_STATISTICS | Reset client statistics (see SHOW\nCLIENT_STATISTICS). | \n \nDES_KEY_FILE | Reloads the DES key file (Specified with the\n--des-key-file startup option). | \n \nHOSTS | Flush the hostname cache (used for converting ip to\nhost names and for unblocking blocked hosts. See\nmax_connect_errors) | \n \nINDEX_STATISTICS | Reset index statistics (see SHOW\nINDEX_STATISTICS). | \n \n[ERROR | ENGINE | GENERAL | SLOW | BINARY | RELAY] LOGS |\nClose and reopen the specified log type, or all log types if\nnone are specified. FLUSH RELAY LOGS [connection-name] can\nbe used to flush the relay logs for a specific connection.\nOnly one connection can be specified per FLUSH command. See\nMulti-source replication. FLUSH ENGINE LOGS will delete all\nunneeded Aria redo logs. | \n \nMASTER | Deprecated option, use RESET MASTER instead. | \n \nPRIVILEGES | Reload all privileges from the privilege tables\nin the mysql database. If the server is started with\n--skip-grant-table option, this will activate the privilege\ntables again. | \n \nQUERY CACHE | Defragment the query cache to better utilize\nits memory. If you want to reset the query cache, you can do\nit with RESET QUERY CACHE. | \n \nQUERY_RESPONSE_TIME | See the QUERY_RESPONSE_TIME plugin. | \n \nSLAVE | Deprecated option, use RESET SLAVE instead. | \n \nSSL | Used to dynamically reinitialize the server\'s TLS\ncontext by reloading the files defined by several TLS system\nvariables. See FLUSH SSL for more information. This command\nwas first added in MariaDB 10.4.1. | \n \nSTATUS | Resets all server status variables that can be\nreset to 0. Not all global status variables support this, so\nnot all global values are reset. See FLUSH STATUS for more\ninformation. | \n \nTABLE | Close tables given as options or all open tables if\nno table list was used. From MariaDB 10.4.1, using without\nany table list will only close tables not in use, and tables\nnot locked by the FLUSH TABLES connection. If there are no\nlocked tables, FLUSH TABLES will be instant and will not\ncause any waits, as it no longer waits for tables in use.\nWhen a table list is provided, from MariaDB 10.4.1, the\nserver will wait for the end of any transactions that are\nusing the tables. Previously, FLUSH TABLES only waited for\nthe statements to complete. | \n \nTABLES | Same as FLUSH TABLE. | \n \nTABLES ... FOR EXPORT | For InnoDB tables, flushes table\nchanges to disk to permit binary table copies while the\nserver is running. Introduced in MariaDB 10.0.8. See FLUSH\nTABLES ... FOR EXPORT for more. | \n \nTABLES WITH READ LOCK | Closes all open tables. New tables\nare only allowed to be opened with read locks until an\nUNLOCK TABLES is given. | \n \nTABLES WITH READ LOCK AND DISABLE CHECKPOINT | As TABLES\nWITH READ LOCK but also disable all checkpoint writes by\ntransactional table engines. This is useful when doing a\ndisk snapshot of all tables. | \n \nTABLE_STATISTICS | Reset table statistics (see SHOW\nTABLE_STATISTICS). | \n \nUSER_RESOURCES | Resets all per hour user resources. This\nenables clients that have exhausted their resources to\nconnect again. | \n \nUSER_STATISTICS | Reset user statistics (see SHOW\nUSER_STATISTICS). | \n \nYou can also use the mysqladmin client to flush things. Use\nmysqladmin --help to examine what flush commands it\nsupports.\n \nFLUSH STATUS\n \nServer status variables can be reset by executing the\nfollowing:\n \nFLUSH STATUS;\n \nGlobal Status Variables that Support FLUSH STATUS\n \nNot all global status variables support being reset by FLUSH\nSTATUS. Currently, the following status variables are reset\nby FLUSH STATUS:\nAborted_clients\nAborted_connects\nAria_pagecache_blocks_not_flushed\nAria_pagecache_blocks_unused\nAria_pagecache_blocks_used\nBinlog_cache_disk_use\nBinlog_cache_use\nBinlog_stmt_cache_disk_use\nBinlog_stmt_cache_use\nConnection_errors_accept\nConnection_errors_internal\nConnection_errors_max_connections\nConnection_errors_peer_address\nConnection_errors_select\nConnection_errors_tcpwrap\nCreated_tmp_files\nDelayed_errors\nDelayed_writes\nFeature_check_constraint\nFeature_delay_key_write\nMax_used_connections\nOpened_plugin_libraries\nPerformance_schema_accounts_lost\nPerformance_schema_cond_instances_lost\nPerformance_schema_digest_lost\nPerformance_schema_file_handles_lost\nPerformance_schema_file_instances_lost\nPerformance_schema_hosts_lost\nPerformance_schema_locker_lost\nPerformance_schema_mutex_instances_lost\nPerformance_schema_rwlock_instances_lost\nPerformance_schema_session_connect_attrs_lost\nPerformance_schema_socket_instances_lost\nPerformance_schema_stage_classes_lost\nPerformance_schema_statement_classes_lost\nPerformance_schema_table_handles_lost\nPerformance_schema_table_instances_lost\nPerformance_schema_thread_instances_lost\nPerformance_schema_users_lost\nQcache_hits\nQcache_inserts\nQcache_lowmem_prunes\nQcache_not_cached\nRpl_semi_sync_master_no_times\nRpl_semi_sync_master_no_tx\nRpl_semi_sync_master_timefunc_failures\nRpl_semi_sync_master_wait_pos_backtraverse\nRpl_semi_sync_master_yes_tx\nRpl_transactions_multi_engine\nServer_audit_writes_failed\nSlave_retried_transactions\nSlow_launch_threads\nSsl_accept_renegotiates\nSsl_accepts\nSsl_callback_cache_hits\nSsl_client_connects\nSsl_connect_renegotiates\nSsl_ctx_verify_depth\nSsl_ctx_verify_mode\nSsl_finished_accepts\nSsl_finished_connects\nSsl_session_cache_hits\nSsl_session_cache_misses\nSsl_session_cache_overflows\nSsl_session_cache_size\nSsl_session_cache_timeouts\nSsl_sessions_reused\nSsl_used_session_cache_entries\nSubquery_cache_hit\nSubquery_cache_miss\nTable_locks_immediate\nTable_locks_waited\nTc_log_max_pages_used\nTc_log_page_waits\nTransactions_gtid_foreign_engine\nTransactions_multi_engine\n \nFLUSH SSL\n \nThe FLUSH SSL command was first added in MariaDB 10.4.\n \nIn MariaDB 10.4 and later, the FLUSH SSL command can be used\nto dynamically reinitialize the server\'s TLS context. This\nis most useful if you need to replace a certificate that is\nabout to expire without restarting the server.\n \nThis operation is performed by reloading the files defined\nby the following TLS system variables:\nssl_cert\nssl_key\nssl_ca\nssl_capath\nssl_crl\nssl_crlpath\n \nThese TLS system variables are not dynamic, so their values\ncan not be changed without restarting the server.\n \nIf you want to dynamically reinitialize the server\'s TLS\ncontext, then you need to change the certificate and key\nfiles at the relevant paths defined by these TLS system\nvariables, without actually changing the values of the\nvariables. See MDEV-19341 for more information.\n \nReducing Memory Usage\n \nTo flush some of the global caches that take up memory, you\ncould execute the following command:\n \nFLUSH LOCAL HOSTS,\n QUERY CACHE, \n TABLE_STATISTICS, \n INDEX_STATISTICS, \n USER_STATISTICS;\n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/flush/','','https://mariadb.com/kb/en/library/flush/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (341,26,'FLUSH QUERY CACHE','Description\n----------- \nYou can defragment the query cache to better utilize its\nmemory with\nthe FLUSH QUERY CACHE statement. The statement does not\nremove any queries from the cache.\n \nThe RESET QUERY CACHE statement removes all query results\nfrom the query cache.\nThe FLUSH TABLES statement also does this.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/flush-query-cache/','','https://mariadb.com/kb/en/library/flush-query-cache/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (342,26,'FLUSH TABLES FOR EXPORT','FLUSH TABLES ... FOR EXPORT was introduced in MariaDB\n10.0.8.\n \nSyntax\n------ \nFLUSH TABLES table_name [, table_name] FOR EXPORT\n \nDescription\n----------- \nFLUSH TABLES ... FOR EXPORT flushes changes to the specified\ntables to disk so that binary copies can be made while the\nserver is still running. This works for Archive, Aria, CSV,\nInnoDB, MyISAM, MERGE, and XtraDB tables.\n \nThe table is read locked until one has issued UNLOCK TABLES.\n \nIf a storage engine does not support FLUSH TABLES FOR\nEXPORT, a 1031 error (SQLSTATE \'HY000\') is produced.\n \nIf FLUSH TABLES ... FOR EXPORT is in effect in the session,\nthe following statements will produce an error if attempted:\nFLUSH TABLES WITH READ LOCK\nFLUSH TABLES ... WITH READ LOCK\nFLUSH TABLES ... FOR EXPORT\nAny statement trying to update any table\n \nIf any of the following statements is in effect in the\nsession, attempting FLUSH TABLES ... FOR EXPORT will\nproduce an error.\nFLUSH TABLES ... WITH READ LOCK\nFLUSH TABLES ... FOR EXPORT\nLOCK TABLES ... READ\nLOCK TABLES ... WRITE\n \nFLUSH FOR EXPORT is not written to the binary log.\n \nThis statement requires the RELOAD and the LOCK TABLES\nprivileges.\n \nIf one of the specified tables cannot be locked, none of the\ntables will be locked.\n \nIf a table does not exist, an error like the following will\nbe produced:\n \nERROR 1146 (42S02): Table \'test.xxx\' doesn\'t exist\n \nIf a table is a view, an error like the following will be\nproduced:\n \nERROR 1347 (HY000): \'test.v\' is not BASE TABLE\n \nExample\n \nFLUSH TABLES test.t1 FOR EXPORT;\n# Copy files related to the table (see below)\nUNLOCK TABLES;\n \nFor a full description, please see copying MariaDB tables.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/flush-tables-for-export/','','https://mariadb.com/kb/en/library/flush-tables-for-export/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (343,26,'HELP Command','Syntax\n------ \nHELP search_string\n \nDescription\n----------- \nThe HELP command can be used in any MariaDB client, such as\nthe mysql command-line client, to get basic syntax help and\na short description for most commands and functions. \n \nIf you provide an argument to the HELP command, the mysql\nclient uses it as a search string to access server-side\nhelp. The proper operation of this command requires that the\nhelp tables in the mysql database be initialized with help\ntopic information.\n \nIf there is no match for the search string, the search\nfails. Use help contents to see a list of the help\ncategories:\n \nHELP contents\nYou asked for help about help category: \"Contents\"\nFor more information, type \'help \', where is one of the\nfollowing\ncategories:\n \n Account Management\n Administration\n Compound Statements\n Data Definition\n Data Manipulation\n Data Types\n Functions\n Functions and Modifiers for Use with GROUP BY\n Geographic Features\n Language Structure\n Plugins\n Table Maintenance\n Transactions\n User-Defined Functions\n Utility\n \nIf a search string matches multiple items, MariaDB shows a\nlist of matching topics:\n \nHELP create\nMany help items for your request exist.\nTo make a more specific request, please type \'help \',\nwhere is one of the following\ntopics:\n CREATE DATABASE\n CREATE EVENT\n CREATE FUNCTION\n CREATE FUNCTION UDF\n CREATE INDEX\n CREATE PROCEDURE\n CREATE SERVER\n CREATE TABLE\n CREATE TABLESPACE\n CREATE TRIGGER\n CREATE USER\n CREATE VIEW\n SHOW\n SHOW CREATE DATABASE\n SHOW CREATE EVENT\n SHOW CREATE FUNCTION\n SHOW CREATE PROCEDURE\n SHOW CREATE TABLE\n SPATIAL\n \nThen you can enter a topic as the search string to see the\nhelp entry for that topic.\n \nThe help is provided with the MariaDB server and makes use\nof four help tables found in the mysql database:\nhelp_relation, help_topic, help_category and help_keyword.\nThese tables are populated by the mysql_install_db or\nfill_help_table.sql scripts which currently contain data\ngenerated from an old version of MySQL.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/help-command/','','https://mariadb.com/kb/en/library/help-command/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (344,26,'KILL [CONNECTION | QUERY]','Syntax\n------ \nKILL [HARD | SOFT] [CONNECTION | QUERY [ID] ] [thread_id |\nUSER user_name | query_id]\n \nMariaDB 5.3.2\n \nThe options HARD | SOFT and USER username were introduced in\nMariaDB 5.3.2\n \nMariaDB 10.0.5\n \nKILL QUERY ID query_id, which permits killing a query by\nquery id rather than thread id, was introduced in MariaDB\n10.0.5.\n \nDescription\n----------- \nEach connection to mysqld runs in a separate thread. You can\nsee which threads\nare running with the SHOW PROCESSLIST statement and kill a\nthread with the KILL thread_id statement. \nKILL allows the optional CONNECTION or\nQUERY modifier:\nKILL CONNECTION is the same as KILL with no\n modifier: It terminates the connection associated with the\ngiven thread or query id.\nKILL QUERY terminates the statement that the connection\nthread_id is\n currently executing, but leaves the connection itself\nintact.\nKILL QUERY ID (introduced in MariaDB 10.0.5) terminates the\nquery by query_id, leaving the connection intact.\n \nIf a connection is terminated that has an active\ntransaction, the transaction will be rolled back. If only a\nquery is killed, the current transaction will stay active.\nSee also idle_transaction_timeout.\n \nIf you have the PROCESS privilege, you can see all threads.\nIf\nyou have the SUPER privilege, you can kill all threads and\nstatements. Otherwise, you can see and kill only your own\nthreads and\nstatements.\n \nKilling queries that repair or create indexes on MyISAM and\nAria tables may result in corrupted tables. Use the SOFT\noption to avoid this!\n \nThe HARD option (default) kills a command as soon as\npossible. If you use\nSOFT, then critical operations that may leave a table in an\ninconsistent state will not be interrupted. Such operations\ninclude REPAIR and INDEX creation for MyISAM and Aria tables\n(REPAIR TABLE, OPTIMIZE TABLE).\n \nKILL ... USER username will kill all connections/queries for\na\ngiven user. USER can be specified one of the following ways:\nusername (Kill without regard to hostname)\nusername@hostname\nCURRENT_USER or CURRENT_USER()\n \nIf you specify a thread id and that thread does not exist,\nyou get the following error:\n \nERROR 1094 (HY000): Unknown thread id: \n \nIf you specify a query id that doesn\'t exist, you get the\nfollowing error:\n \nERROR 1957 (HY000): Unknown query id: \n \nHowever, if you specify a user name, no error is issued for\nnon-connected (or even non-existing) users. To check if the\nconnection/query has been killed, you can use the\nROW_COUNT() function.\n \nA client whose connection is killed receives the following\nerror:\n \nERROR 1317 (70100): Query execution was interrupted\n \nTo obtain a list of existing sessions, use the SHOW\nPROCESSLIST statement or query the Information Schema\nPROCESSLIST table.\n \nNote: You cannot use KILL with the Embedded MySQL Server\nlibrary because the embedded server merely runs inside the\nthreads of the host\napplication. It does not create any connection threads of\nits own.\n \nNote: You can also use \nmysqladmin kill thread_id [,thread_id...]\nto kill connections. To get a list of running queries,\nuse mysqladmin processlist. See mysqladmin.\n \nPercona Toolkit contains a program, pt-kill that can be used\nto automatically kill connections that match certain\ncriteria. For example, it can be used to terminate idle\nconnections, or connections that have been busy for more\nthan 60 seconds.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/data-manipulation-kill-connection-query/','','https://mariadb.com/kb/en/library/data-manipulation-kill-connection-query/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (345,26,'LOAD INDEX','Syntax\n------ \nLOAD INDEX INTO CACHE\n tbl_index_list [, tbl_index_list] ...\n \ntbl_index_list:\n tbl_name\n [[INDEX|KEY] (index_name[, index_name] ...)]\n [IGNORE LEAVES]\n \nDescription\n----------- \nThe LOAD INDEX INTO CACHE statement preloads a table index\ninto the key\ncache to which it has been assigned by an explicit CACHE\nINDEX\nstatement, or into the default key cache otherwise. \nLOAD INDEX INTO CACHE is used only for MyISAM or Aria\ntables. Until MariaDB 5.3, it was not supported for tables\nhaving user-defined partitioning, but this limitation was\nremoved in MariaDB 5.5.\n \nThe IGNORE LEAVES modifier causes only blocks for the\nnonleaf nodes of\nthe index to be preloaded.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/load-index/','','https://mariadb.com/kb/en/library/load-index/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (346,26,'RESET','Syntax\n------ \nRESET reset_option [, reset_option] ...\n \nDescription\n----------- \nThe RESET statement is used to clear the state of various\nserver\noperations. You must have the RELOAD privilege to execute\nRESET.\n \nRESET acts as a stronger version of the FLUSH statement.\n \nThe different RESET options are:\n \nOption | Description | \n \nSLAVE [\"connection_name\"] [ALL] | Deletes all relay logs\nfrom the slave and reset the replication position in the\nmaster binary log. | \n \nMASTER | Deletes all old binary logs, makes the binary index\nfile (--log-bin-index) empty and creates a new binary log\nfile. This is useful when you want to reset the master to an\ninitial state. If you want to just delete old, not used\nbinary logs, you should use the PURGE BINARY LOGS command. |\n\n \nQUERY CACHE | Removes all queries from the query cache. See\nalso FLUSH QUERY CACHE. | \n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/reset/','','https://mariadb.com/kb/en/library/reset/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (347,26,'SET','Syntax\n------ \nSET variable_assignment [, variable_assignment] ...\n \nvariable_assignment:\n user_var_name = expr\n | [GLOBAL | SESSION] system_var_name = expr\n | [@@global. | @@session. | @@]system_var_name = expr\n \nOne can also set a user variable in any expression with this\nsyntax:\n \nuser_var_name:= expr\n \nDescription\n----------- \nThe SET statement assigns values to different types of\nvariables that affect the operation of the server or your\nclient. Older\nversions of MySQL employed SET OPTION, but this syntax was\ndeprecated in favor of SET without OPTION, and was removed\nin MariaDB 10.0.\n \nChanging a system variable by using the SET statement does\nnot make the change permanently. To do so, the change must\nbe made in a configuration file.\n \nFor setting variables on a per-query basis (from MariaDB\n10.1.2), see SET STATEMENT.\n \nSee SHOW VARIABLES for documentation on viewing server\nsystem variables.\n \nSee Server System Variables for a list of all the system\nvariables.\n \nGLOBAL / SESSION\n \nWhen setting a system variable, the scope can be specified\nas either GLOBAL or SESSION.\n \nA global variable change affects all new sessions. It does\nnot affect any currently open sessions, including the one\nthat made the change. \n \nA session variable change affects the current session only.\n \nIf the variable has a session value, not specifying either\nGLOBAL or SESSION will be the same as specifying SESSION. If\nthe variable only has a global value, not specifying GLOBAL\nor SESSION will apply to the change to the global value.\n \nDEFAULT\n \nSetting a global variable to DEFAULT will restore it to the\nserver default, and setting a session variable to DEFAULT\nwill restore it to the current global value.\n \nExamples\n-------- \ninnodb_sync_spin_loops is a global variable.\nskip_parallel_replication is a session variable.\nmax_error_count is both global and session.\n \nSELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM\n INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE \n VARIABLE_NAME LIKE \'max_error_count\' OR \n VARIABLE_NAME LIKE \'skip_parallel_replication\' OR \n VARIABLE_NAME LIKE \'innodb_sync_spin_loops\';\n \n+---------------------------+---------------+--------------+\n| VARIABLE_NAME | SESSION_VALUE | GLOBAL_VALUE |\n+---------------------------+---------------+--------------+\n| MAX_ERROR_COUNT | 64 | 64 |\n| SKIP_PARALLEL_REPLICATION | OFF | NULL |\n| INNODB_SYNC_SPIN_LOOPS | NULL | 30 |\n+---------------------------+---------------+--------------+\n \nSetting the session values:\n \nSET max_error_count=128;\nQuery OK, 0 rows affected (0.000 sec)\n \nSET skip_parallel_replication=ON;\nQuery OK, 0 rows affected (0.000 sec)\n \nSET innodb_sync_spin_loops=60;\n \nERROR 1229 (HY000): Variable \'innodb_sync_spin_loops\' is a\nGLOBAL variable \n and should be set with SET GLOBAL\n \nSELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM\n INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE \n VARIABLE_NAME LIKE \'max_error_count\' OR \n VARIABLE_NAME LIKE \'skip_parallel_replication\' OR \n VARIABLE_NAME LIKE \'innodb_sync_spin_loops\';\n \n+---------------------------+---------------+--------------+\n| VARIABLE_NAME | SESSION_VALUE | GLOBAL_VALUE |\n+---------------------------+---------------+--------------+\n| MAX_ERROR_COUNT | 128 | 64 |\n| SKIP_PARALLEL_REPLICATION | ON | NULL |\n| INNODB_SYNC_SPIN_LOOPS | NULL | 30 |\n+---------------------------+---------------+--------------+\n \nSetting the global values:\n \nSET GLOBAL max_error_count=256;\n \nSET GLOBAL skip_parallel_replication=ON;\n \nERROR 1228 (HY000): Variable \'skip_parallel_replication\'\nis a SESSION variable \n and can\'t be used with SET GLOBAL\n \nSET GLOBAL innodb_sync_spin_loops=120;\n \nSELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM\n INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE \n VARIABLE_NAME LIKE \'max_error_count\' OR \n VARIABLE_NAME LIKE \'skip_parallel_replication\' OR \n VARIABLE_NAME LIKE \'innodb_sync_spin_loops\';\n \n+---------------------------+---------------+--------------+\n| VARIABLE_NAME | SESSION_VALUE | GLOBAL_VALUE |\n+---------------------------+---------------+--------------+\n| MAX_ERROR_COUNT | 128 | 256 |\n| SKIP_PARALLEL_REPLICATION | ON | NULL |\n| INNODB_SYNC_SPIN_LOOPS | NULL | 120 |\n+---------------------------+---------------+--------------+\n \nSHOW VARIABLES will by default return the session value\nunless the variable is global only.\n \nSHOW VARIABLES LIKE \'max_error_count\';\n \n+-----------------+-------+\n| Variable_name | Value |\n+-----------------+-------+\n| max_error_count | 128 |\n+-----------------+-------+\n \nSHOW VARIABLES LIKE \'skip_parallel_replication\';\n \n+---------------------------+-------+\n| Variable_name | Value |\n+---------------------------+-------+\n| skip_parallel_replication | ON |\n+---------------------------+-------+\n \nSHOW VARIABLES LIKE \'innodb_sync_spin_loops\';\n \n+------------------------+-------+\n| Variable_name | Value |\n+------------------------+-------+\n| innodb_sync_spin_loops | 120 |\n+------------------------+-------+\n \nUsing the inplace syntax:\n \nSELECT (@a:=1);\n+---------+\n| (@a:=1) |\n+---------+\n| 1 |\n+---------+\n \nSELECT @a;\n \n+------+\n| @a |\n+------+\n| 1 |\n+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/set/','','https://mariadb.com/kb/en/library/set/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (348,26,'About SHOW','SHOW has many forms that provide information about\ndatabases, tables, columns, or status information about the\nserver. These include:\nSHOW AUTHORS\nSHOW CHARACTER SET [like_or_where]\nSHOW COLLATION [like_or_where]\nSHOW [FULL] COLUMNS FROM tbl_name [FROM db_name]\n[like_or_where]\nSHOW CONTRIBUTORS\nSHOW CREATE DATABASE db_name\nSHOW CREATE EVENT event_name\nSHOW CREATE PACKAGE package_name\nSHOW CREATE PACKAGE BODY package_name\nSHOW CREATE PROCEDURE proc_name\nSHOW CREATE TABLE tbl_name\nSHOW CREATE TRIGGER trigger_name\nSHOW CREATE VIEW view_name\nSHOW DATABASES [like_or_where]\nSHOW ENGINE engine_name {STATUS | MUTEX}\nSHOW [STORAGE] ENGINES\nSHOW ERRORS [LIMIT [offset,] row_count]\nSHOW [FULL] EVENTS\nSHOW FUNCTION CODE func_name\nSHOW FUNCTION STATUS [like_or_where]\nSHOW GRANTS FOR user\nSHOW INDEX FROM tbl_name [FROM db_name]\nSHOW INNODB STATUS\nSHOW OPEN TABLES [FROM db_name] [like_or_where]\nSHOW PLUGINS\nSHOW PROCEDURE CODE proc_name\nSHOW PROCEDURE STATUS [like_or_where]\nSHOW PRIVILEGES\nSHOW [FULL] PROCESSLIST\nSHOW PROFILE [types] [FOR QUERY n] [OFFSET n] [LIMIT n]\nSHOW PROFILES\nSHOW [GLOBAL | SESSION] STATUS [like_or_where]\nSHOW TABLE STATUS [FROM db_name] [like_or_where]\nSHOW TABLES [FROM db_name] [like_or_where]\nSHOW TRIGGERS [FROM db_name] [like_or_where]\nSHOW [GLOBAL | SESSION] VARIABLES [like_or_where]\nSHOW WARNINGS [LIMIT [offset,] row_count]\n \nlike_or_where:\n LIKE \'pattern\'\n | WHERE expr\n \nIf the syntax for a given SHOW statement includes a\nLIKE \'pattern\' part, \'pattern\' is a\nstring that can contain the SQL \"%\" and\n\"_\" wildcard characters. The pattern is useful for\nrestricting statement output to matching values.\n \nSeveral SHOW statements also accept a\nWHERE clause that provides more flexibility in specifying\nwhich rows to display. See Extended Show.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/about-show/','','https://mariadb.com/kb/en/library/about-show/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (349,26,'SHOW AUTHORS','Syntax\n------ \nSHOW AUTHORS\n \nDescription\n----------- \nThe SHOW AUTHORS statement displays information about the\npeople who work on MariaDB. For each author, it displays\nName, Location, and\nComment values. All columns are encoded as latin1.\n \nIn MariaDB 5.5 this is in somewhat random order.\n \nIn MariaDB 10.0.5 and later you have:\nFirst the active people in MariaDB are listed.\nThen the active people in MySQL.\nLast the people that has contributed to MariaDB/MySQL in the\npast.\n \nThe order is somewhat related to importance of the\ncontribution given to the MariaDB project, but this is not\n100% accurate. There is still room for improvements and\ndebate...\n \nExample\n \nSHOW AUTHORS;\n+--------------------------------+---------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+\n| Name | Location | Comment |\n+--------------------------------+---------------------------------------+-----------------------------------------------------------------------------------------------------------------------------------------+\n| Michael (Monty) Widenius | Tusby, Finland | Lead developer\nand main author |\n| Sergei Golubchik | Kerpen, Germany | Architect, Full-text\nsearch, precision math, plugin framework, merges etc |\n| Igor Babaev | Bellevue, USA | Optimizer, keycache, core\nwork |\n| Sergey Petrunia | St. Petersburg, Russia | Optimizer |\n| Oleksandr Byelkin | Lugansk, Ukraine | Query Cache (4.0),\nSubqueries (4.1), Views (5.0) |\n| Timour Katchaounov | Sofia , Bulgaria | Optimizer |\n| Kristian Nielsen | Copenhagen, Denmark | Replication,\nAsync client prototocol, General buildbot stuff |\n| Alexander (Bar) Barkov | Izhevsk, Russia | Unicode and\ncharacter sets |\n| Alexey Botchkov (Holyfoot) | Izhevsk, Russia | GIS\nextensions, embedded server, precision math |\n| Daniel Bartholomew | Raleigh, USA | MariaDB documentation\n|\n| Colin Charles | Selangor, Malesia | MariaDB documentation,\ntalks at a LOT of conferences |\n| Sergey Vojtovich | Izhevsk, Russia | initial\nimplementation of plugin architecture, maintained native\nstorage engines (MyISAM, MEMORY, ARCHIVE, etc), rewrite of\ntable cache |\n| Vladislav Vaintroub | Mannheim, Germany | MariaDB Java\nconnector, new thread pool, Windows optimizations |\n| Elena Stepanova | Sankt Petersburg, Russia | QA, test\ncases |\n| Georg Richter | Heidelberg, Germany | New LGPL C\nconnector, PHP connector |\n| Jan Lindström | Ylämylly, Finland | Working on InnoDB |\n| Lixun Peng | Hangzhou, China | Multi Source replication |\n| Percona | CA, USA | XtraDB, microslow patches, extensions\nto slow log \n...\n \nSee Also\n \nSHOW CONTRIBUTORS. This list all members and sponsors of the\nMariaDB Foundation and other sponsors.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-authors/','','https://mariadb.com/kb/en/library/show-authors/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (350,26,'SHOW BINARY LOGS','Syntax\n------ \nSHOW BINARY LOGS\nSHOW MASTER LOGS\n \nDescription\n----------- \nLists the binary log files on the server. This statement is\nused as part of the\nprocedure described in \nPURGE BINARY LOGS, that shows how to\ndetermine which logs can be purged.\n \nExamples\n-------- \nSHOW BINARY LOGS;\n+--------------------+-----------+\n| Log_name | File_size |\n+--------------------+-----------+\n| mariadb-bin.000001 | 19039 |\n| mariadb-bin.000002 | 717389 |\n| mariadb-bin.000003 | 300 |\n| mariadb-bin.000004 | 333 |\n| mariadb-bin.000005 | 899 |\n| mariadb-bin.000006 | 125 |\n| mariadb-bin.000007 | 18907 |\n| mariadb-bin.000008 | 19530 |\n| mariadb-bin.000009 | 151 |\n| mariadb-bin.000010 | 151 |\n| mariadb-bin.000011 | 125 |\n| mariadb-bin.000012 | 151 |\n| mariadb-bin.000013 | 151 |\n| mariadb-bin.000014 | 125 |\n| mariadb-bin.000015 | 151 |\n| mariadb-bin.000016 | 314 |\n+--------------------+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-binary-logs/','','https://mariadb.com/kb/en/library/show-binary-logs/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (351,26,'SHOW BINLOG EVENTS','Syntax\n------ \nSHOW BINLOG EVENTS\n [IN \'log_name\'] [FROM pos] [LIMIT [offset,] row_count]\n \nDescription\n----------- \nShows the events in the binary log. If you do not specify\n\'log_name\',\nthe first binary log is displayed.\n \nExample\n \nSHOW BINLOG EVENTS IN \'mysql_sandbox10019-bin.000002\';\n+-------------------------------+-----+-------------------+-----------+-------------+------------------------------------------------+\n| Log_name | Pos | Event_type | Server_id | End_log_pos |\nInfo |\n+-------------------------------+-----+-------------------+-----------+-------------+------------------------------------------------+\n| mysql_sandbox10019-bin.000002 | 4 | Format_desc | 1 | 248\n| Server ver: 10.0.19-MariaDB-log, Binlog ver: 4 |\n| mysql_sandbox10019-bin.000002 | 248 | Gtid_list | 1 | 273\n| [] |\n| mysql_sandbox10019-bin.000002 | 273 | Binlog_checkpoint |\n1 | 325 | mysql_sandbox10019-bin.000002 |\n| mysql_sandbox10019-bin.000002 | 325 | Gtid | 1 | 363 |\nGTID 0-1-1 |\n| mysql_sandbox10019-bin.000002 | 363 | Query | 1 | 446 |\nCREATE DATABASE blog |\n| mysql_sandbox10019-bin.000002 | 446 | Gtid | 1 | 484 |\nGTID 0-1-2 |\n| mysql_sandbox10019-bin.000002 | 484 | Query | 1 | 571 |\nuse `blog`; CREATE TABLE bb (id INT) |\n+-------------------------------+-----+-------------------+-----------+-------------+------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-binlog-events/','','https://mariadb.com/kb/en/library/show-binlog-events/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (352,26,'SHOW CHARACTER SET','Syntax\n------ \nSHOW CHARACTER SET\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nThe SHOW CHARACTER SET statement shows all available\ncharacter sets. The LIKE clause, if present on its own,\nindicates which character\nset names to match. The WHERE and LIKE clauses can be given\nto select rows using more general conditions, as discussed\nin Extended SHOW.\n \nThe same information can be queried from the\ninformation_schema.CHARACTER_SETS table.\n \nSee Setting Character Sets and Collations for details on\nspecifying the character set at the server, database, table\nand column levels.\n \nExamples\n-------- \nSHOW CHARACTER SET LIKE \'latin%\';\n+---------+-----------------------------+-------------------+--------+\n| Charset | Description | Default collation | Maxlen |\n+---------+-----------------------------+-------------------+--------+\n| latin1 | cp1252 West European | latin1_swedish_ci | 1 |\n| latin2 | ISO 8859-2 Central European | latin2_general_ci |\n1 |\n| latin5 | ISO 8859-9 Turkish | latin5_turkish_ci | 1 |\n| latin7 | ISO 8859-13 Baltic | latin7_general_ci | 1 |\n+---------+-----------------------------+-------------------+--------+\n \nSHOW CHARACTER SET WHERE Maxlen LIKE \'2\';\n+---------+---------------------------+-------------------+--------+\n| Charset | Description | Default collation | Maxlen |\n+---------+---------------------------+-------------------+--------+\n| big5 | Big5 Traditional Chinese | big5_chinese_ci | 2 |\n| sjis | Shift-JIS Japanese | sjis_japanese_ci | 2 |\n| euckr | EUC-KR Korean | euckr_korean_ci | 2 |\n| gb2312 | GB2312 Simplified Chinese | gb2312_chinese_ci | 2\n|\n| gbk | GBK Simplified Chinese | gbk_chinese_ci | 2 |\n| ucs2 | UCS-2 Unicode | ucs2_general_ci | 2 |\n| cp932 | SJIS for Windows Japanese | cp932_japanese_ci | 2\n|\n+---------+---------------------------+-------------------+--------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-character-set/','','https://mariadb.com/kb/en/library/show-character-set/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (353,26,'SHOW CLIENT_STATISTICS','MariaDB 5.2 introduced the User Statistics feature.\n \nSyntax\n------ \nSHOW CLIENT_STATISTICS\n \nDescription\n----------- \nThe SHOW CLIENT_STATISTICS statement was introduced in\nMariaDB 5.2 as part of the User Statistics feature. It was\nremoved as a separate statement in MariaDB 10.1.1, but\neffectively replaced by the generic SHOW\ninformation_schema_table statement. The\ninformation_schema.CLIENT_STATISTICS table holds statistics\nabout client connections.\n \nThe userstat system variable must be set to 1 to activate\nthis feature. See the User Statistics and\ninformation_schema.CLIENT_STATISTICS articles for more\ninformation.\n \nExample\n \nFrom MariaDB 10.0:\n \nSHOW CLIENT_STATISTICS\\G\n*************************** 1. row\n***************************\n Client: localhost\n Total_connections: 35\nConcurrent_connections: 0\n Connected_time: 708\n Busy_time: 2.5557979999999985\n Cpu_time: 0.04123740000000002\n Bytes_received: 3883\n Bytes_sent: 21595\n Binlog_bytes_written: 0\n Rows_read: 18\n Rows_sent: 115\n Rows_deleted: 0\n Rows_inserted: 0\n Rows_updated: 0\n Select_commands: 70\n Update_commands: 0\n Other_commands: 0\n Commit_transactions: 1\n Rollback_transactions: 0\n Denied_connections: 0\n Lost_connections: 0\n Access_denied: 0\n Empty_queries: 35\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/show-client-statistics/','','https://mariadb.com/kb/en/library/show-client-statistics/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (354,26,'SHOW COLLATION','Syntax\n------ \nSHOW COLLATION\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nThe output from SHOW COLLATION includes all available\ncollations. The LIKE clause, if present on its own,\nindicates which collation names to match. The WHERE and LIKE\nclauses can be given to select rows using more general\nconditions, as discussed in Extended SHOW.\n \nThe same information can be queried from the\ninformation_schema.COLLATIONS table.\n \nSee Setting Character Sets and Collations for details on\nspecifying the collation at the server, database, table and\ncolumn levels.\n \nExamples\n-------- \nSHOW COLLATION LIKE \'latin1%\';\n+-------------------+---------+----+---------+----------+---------+\n| Collation | Charset | Id | Default | Compiled | Sortlen |\n+-------------------+---------+----+---------+----------+---------+\n| latin1_german1_ci | latin1 | 5 | | Yes | 1 |\n| latin1_swedish_ci | latin1 | 8 | Yes | Yes | 1 |\n| latin1_danish_ci | latin1 | 15 | | Yes | 1 |\n| latin1_german2_ci | latin1 | 31 | | Yes | 2 |\n| latin1_bin | latin1 | 47 | | Yes | 1 |\n| latin1_general_ci | latin1 | 48 | | Yes | 1 |\n| latin1_general_cs | latin1 | 49 | | Yes | 1 |\n| latin1_spanish_ci | latin1 | 94 | | Yes | 1 |\n+-------------------+---------+----+---------+----------+---------+\n \nSHOW COLLATION WHERE Sortlen LIKE \'8\' AND Charset LIKE\n\'utf8\';\n+--------------------+---------+-----+---------+----------+---------+\n| Collation | Charset | Id | Default | Compiled | Sortlen |\n+--------------------+---------+-----+---------+----------+---------+\n| utf8_unicode_ci | utf8 | 192 | | Yes | 8 |\n| utf8_icelandic_ci | utf8 | 193 | | Yes | 8 |\n| utf8_latvian_ci | utf8 | 194 | | Yes | 8 |\n| utf8_romanian_ci | utf8 | 195 | | Yes | 8 |\n| utf8_slovenian_ci | utf8 | 196 | | Yes | 8 |\n| utf8_polish_ci | utf8 | 197 | | Yes | 8 |\n| utf8_estonian_ci | utf8 | 198 | | Yes | 8 |\n| utf8_spanish_ci | utf8 | 199 | | Yes | 8 |\n| utf8_swedish_ci | utf8 | 200 | | Yes | 8 |\n| utf8_turkish_ci | utf8 | 201 | | Yes | 8 |\n| utf8_czech_ci | utf8 | 202 | | Yes | 8 |\n| utf8_danish_ci | utf8 | 203 | | Yes | 8 |\n| utf8_lithuanian_ci | utf8 | 204 | | Yes | 8 |\n| utf8_slovak_ci | utf8 | 205 | | Yes | 8 |\n| utf8_spanish2_ci | utf8 | 206 | | Yes | 8 |\n| utf8_roman_ci | utf8 | 207 | | Yes | 8 |\n| utf8_persian_ci | utf8 | 208 | | Yes | 8 |\n| utf8_esperanto_ci | utf8 | 209 | | Yes | 8 |\n| utf8_hungarian_ci | utf8 | 210 | | Yes | 8 |\n| utf8_sinhala_ci | utf8 | 211 | | Yes | 8 |\n| utf8_croatian_ci | utf8 | 213 | | Yes | 8 |\n+--------------------+---------+-----+---------+----------+---------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-collation/','','https://mariadb.com/kb/en/library/show-collation/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (355,26,'SHOW COLUMNS','Syntax\n------ \nSHOW [FULL] {COLUMNS | FIELDS} FROM tbl_name [FROM db_name]\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nSHOW COLUMNS displays information about the columns in a\ngiven table. It also works for views. The LIKE clause, if\npresent on its own, indicates which column names to match.\nThe WHERE and LIKE clauses can be given to select rows using\nmore general conditions, as discussed in Extended SHOW.\n \nIf the data types differ from what you expect them to be\nbased on a\nCREATE TABLE statement, note that MariaDB sometimes changes\ndata types when you create or alter a table. The conditions\nunder which this\noccurs are described in the Silent Column Changes article.\n \nThe FULL keyword causes the output to include the column\ncollation and comments, as well as the privileges you have\nfor each column.\n \nYou can use db_name.tbl_name as an alternative to the\ntbl_name FROM db_name syntax. In other words, these two\nstatements are equivalent:\n \nSHOW COLUMNS FROM mytable FROM mydb;\nSHOW COLUMNS FROM mydb.mytable;\n \nSHOW COLUMNS displays the following values for each table\ncolumn:\n \nField indicates the column name.\n \nType indicates the column data type.\n \nCollation indicates the collation for non-binary string\ncolumns, or\nNULL for other columns. This value is displayed only if you\nuse the\nFULL keyword.\n \nThe Null field contains YES if NULL values can be stored in\nthe column,\nNO if not.\n \nThe Key field indicates whether the column is indexed:\nIf Key is empty, the column either is not indexed or is\nindexed only as a\n secondary column in a multiple-column, non-unique index.\nIf Key is PRI, the column is a PRIMARY KEY or\n is one of the columns in a multiple-column PRIMARY KEY.\nIf Key is UNI, the column is the first column of a\nunique-valued\n index that cannot contain NULL values.\nIf Key is MUL, multiple occurrences of a given value are\nallowed\n within the column. The column is the first column of a\nnon-unique index or a\n unique-valued index that can contain NULL values.\n \nIf more than one of the Key values applies to a given column\nof a\ntable, Key displays the one with the highest priority, in\nthe order\nPRI, UNI, MUL.\n \nA UNIQUE index may be displayed as PRI if\nit cannot contain NULL values and there is no\nPRIMARY KEY in the table. A UNIQUE index\nmay display as MUL if several columns form a composite\nUNIQUE index; although the combination of the columns is\nunique, each column can still hold multiple occurrences of a\ngiven value.\n \nThe Default field indicates the default value that is\nassigned to the\ncolumn.\n \nThe Extra field contains any additional information that is\navailable about a given column.\n \nValue | Description | \n \nAUTO_INCREMENT | The column was created with the\nAUTO_INCREMENT keyword. | \n \nPERSISTENT | The column was created with the PERSISTENT\nkeyword. (New in 5.3) | \n \nVIRTUAL | The column was created with the VIRTUAL keyword.\n(New in 5.3) | \n \non update CURRENT_TIMESTAMP | The column is a TIMESTAMP\ncolumn that is automatically updated on INSERT and UPDATE. |\n\n \nPrivileges indicates the privileges you have for the column.\nThis\nvalue is displayed only if you use the FULL keyword.\n \nComment indicates any comment the column has. This value is\ndisplayed\nonly if you use the FULL keyword.\n \nSHOW FIELDS is a synonym for\nSHOW COLUMNS. Also DESCRIBE and EXPLAIN can be used as\nshortcuts.\n \nYou can also list a table\'s columns with: \n \nmysqlshow db_name tbl_name\n \nSee the mysqlshow command for more details.\n \nThe DESCRIBE statement provides information similar to SHOW\nCOLUMNS. The information_schema.COLUMNS table provides\nsimilar, but more complete, information.\n \nThe SHOW CREATE TABLE, SHOW TABLE STATUS, and SHOW INDEX\nstatements also provide information about tables.\n \nExamples\n-------- \nSHOW COLUMNS FROM city;\n+------------+----------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+----------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| Name | char(35) | NO | | | |\n| Country | char(3) | NO | UNI | | |\n| District | char(20) | YES | MUL | | |\n| Population | int(11) | NO | | 0 | |\n+------------+----------+------+-----+---------+----------------+\n \nSHOW COLUMNS FROM employees WHERE Type LIKE \'Varchar%\';\n+---------------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+---------------+-------------+------+-----+---------+-------+\n| first_name | varchar(30) | NO | MUL | NULL | |\n| last_name | varchar(40) | NO | | NULL | |\n| position | varchar(25) | NO | | NULL | |\n| home_address | varchar(50) | NO | | NULL | |\n| home_phone | varchar(12) | NO | | NULL | |\n| employee_code | varchar(25) | NO | UNI | NULL | |\n+---------------+-------------+------+-----+---------+-------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-columns/','','https://mariadb.com/kb/en/library/show-columns/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (356,26,'SHOW CONTRIBUTORS','Syntax\n------ \nSHOW CONTRIBUTORS\n \nDescription\n----------- \nThe SHOW CONTRIBUTORS statement displays information about\nthe companies and people who financially contribute to\nMariaDB. For each contributor, it displays Name, Location,\nand Comment values. All columns are encoded as latin1.\n \nIn MariaDB 5.5 this is in somewhat random order, and the\nfeature was deprecated.\n \nIn MariaDB 10.0.5 it was un-deprecated, and since then\ndisplays all members and sponsors of the MariaDB Foundation\nas well as other financial contributors.\n \nExample\n \nSHOW CONTRIBUTORS;\n+---------------------+-------------------------------+-------------------------------------------------------------+\n| Name | Location | Comment |\n+---------------------+-------------------------------+-------------------------------------------------------------+\n| Booking.com | https://www.booking.com | Founding member,\nPlatinum Sponsor of the MariaDB Foundation |\n| Alibaba Cloud | https://www.alibabacloud.com/ | Platinum\nSponsor of the MariaDB Foundation |\n| Tencent Cloud | https://cloud.tencent.com | Platinum\nSponsor of the MariaDB Foundation |\n| Microsoft | https://microsoft.com/ | Platinum Sponsor of\nthe MariaDB Foundation |\n| MariaDB Corporation | https://mariadb.com | Founding\nmember, Platinum Sponsor of the MariaDB Foundation |\n| Visma | https://visma.com | Gold Sponsor of the MariaDB\nFoundation |\n| DBS | https://dbs.com | Gold Sponsor of the MariaDB\nFoundation |\n| IBM | https://www.ibm.com | Gold Sponsor of the MariaDB\nFoundation |\n| Tencent Games | http://game.qq.com/ | Gold Sponsor of the\nMariaDB Foundation |\n| Nexedi | https://www.nexedi.com | Silver Sponsor of the\nMariaDB Foundation |\n| Acronis | https://www.acronis.com | Silver Sponsor of the\nMariaDB Foundation |\n| Verkkokauppa.com | https://www.verkkokauppa.com | Bronze\nSponsor of the MariaDB Foundation |\n| Virtuozzo | https://virtuozzo.com | Bronze Sponsor of the\nMariaDB Foundation |\n| Tencent Game DBA | http://tencentdba.com/about | Bronze\nSponsor of the MariaDB Foundation |\n| Tencent TDSQL | http://tdsql.org | Bronze Sponsor of the\nMariaDB Foundation |\n| Percona | https://www.percona.com/ | Bronze Sponsor of the\nMariaDB Foundation |\n| Google | USA | Sponsoring encryption, parallel replication\nand GTID |\n| Facebook | USA | Sponsoring non-blocking API, LIMIT ROWS\nEXAMINED etc |\n| Ronald Bradford | Brisbane, Australia | EFF contribution\nfor UC2006 Auction |\n| Sheeri Kritzer | Boston, Mass. USA | EFF contribution for\nUC2006 Auction |\n| Mark Shuttleworth | London, UK. | EFF contribution for\nUC2006 Auction |\n+---------------------+-------------------------------+-------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-contributors/','','https://mariadb.com/kb/en/library/show-contributors/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (357,26,'SHOW CREATE DATABASE','Syntax\n------ \nSHOW CREATE {DATABASE | SCHEMA} db_name\n \nDescription\n----------- \nShows the CREATE DATABASE statement that\ncreates the given database. SHOW CREATE SCHEMA is a synonym\nfor SHOW CREATE DATABASE. SHOW CREATE DATABASE quotes\ndatabase names according to the value of the\nsql_quote_show_create server system variable.\n \nExamples\n-------- \nSHOW CREATE DATABASE test;\n+----------+-----------------------------------------------------------------+\n| Database | Create Database |\n+----------+-----------------------------------------------------------------+\n| test | CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER\nSET latin1 */ |\n+----------+-----------------------------------------------------------------+\n \nSHOW CREATE SCHEMA test;\n+----------+-----------------------------------------------------------------+\n| Database | Create Database |\n+----------+-----------------------------------------------------------------+\n| test | CREATE DATABASE `test` /*!40100 DEFAULT CHARACTER\nSET latin1 */ |\n+----------+-----------------------------------------------------------------+\n \nWith sql_quote_show_create off:\n \nSHOW CREATE DATABASE test;\n+----------+---------------------------------------------------------------+\n| Database | Create Database |\n+----------+---------------------------------------------------------------+\n| test | CREATE DATABASE test /*!40100 DEFAULT CHARACTER SET\nlatin1 */ |\n+----------+---------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-database/','','https://mariadb.com/kb/en/library/show-create-database/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (358,26,'SHOW CREATE EVENT','Syntax\n------ \nSHOW CREATE EVENT event_name\n \nDescription\n----------- \nThis statement displays the CREATE EVENT\nstatement needed to re-create a given event, as well as the\nSQL_MODE that was used when the trigger has been created and\nthe character set used by the connection.. To find out which\nevents are present, use SHOW EVENTS.\n \nThe output of this statement is unreliably affected by the\nsql_quote_show_create server system variable - see\nhttp://bugs.mysql.com/bug.php?id=12719\n \nThe information_schema.EVENTS table provides similar, but\nmore complete, information.\n \nExamples\n-------- \nSHOW CREATE EVENT test.e_daily\\G\n*************************** 1. row\n***************************\n Event: e_daily\n sql_mode: \n time_zone: SYSTEM\n Create Event: CREATE EVENT `e_daily`\n ON SCHEDULE EVERY 1 DAY\n STARTS CURRENT_TIMESTAMP + INTERVAL 6 HOUR\n ON COMPLETION NOT PRESERVE\n ENABLE\n COMMENT \'Saves total number of sessions then\n clears the table each day\'\n DO BEGIN\n INSERT INTO site_activity.totals (time, total)\n SELECT CURRENT_TIMESTAMP, COUNT(*) \n FROM site_activity.sessions;\n DELETE FROM site_activity.sessions;\n END\ncharacter_set_client: latin1\ncollation_connection: latin1_swedish_ci\n Database Collation: latin1_swedish_ci\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-event/','','https://mariadb.com/kb/en/library/show-create-event/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (359,26,'SHOW CREATE FUNCTION','Syntax\n------ \nSHOW CREATE FUNCTION func_name\n \nDescription\n----------- \nThis statement is similar to \nSHOW CREATE PROCEDURE but for\nstored functions.\n \nThe output of this statement is unreliably affected by the\nsql_quote_show_create server system variable - see\nhttp://bugs.mysql.com/bug.php?id=12719\n \nExample\n \nMariaDB [test]> SHOW CREATE FUNCTION VatCents\\G\n*************************** 1. row\n***************************\n Function: VatCents\n sql_mode: \n Create Function: CREATE DEFINER=`root`@`localhost` FUNCTION\n`VatCents`(price DECIMAL(10,2)) RETURNS int(11)\n DETERMINISTIC\nBEGIN\n DECLARE x INT;\n SET x = price * 114;\n RETURN x;\nEND\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-function/','','https://mariadb.com/kb/en/library/show-create-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (360,26,'SHOW CREATE PACKAGE','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nSHOW CREATE PACKAGE [ db_name . ] package_name\n \nDescription\n----------- \nThe SHOW CREATE PACKAGE statement can be used when Oracle\nSQL_MODE is set.\n \nShows the CREATE statement that creates the given package\nspecification.\n \nExamples\n-------- \nSHOW CREATE PACKAGE employee_tools\\G\n*************************** 1. row\n***************************\n Package: employee_tools\n sql_mode:\nPIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER\n Create Package: CREATE DEFINER=\"root\"@\"localhost\"\nPACKAGE \"employee_tools\" AS\n FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2);\n PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2));\n PROCEDURE raiseSalaryStd(eid INT);\n PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2));\nEND\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-package/','','https://mariadb.com/kb/en/library/show-create-package/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (361,26,'SHOW CREATE PACKAGE BODY','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nSHOW CREATE PACKAGE BODY [ db_name . ] package_name\n \nDescription\n----------- \nThe SHOW CREATE PACKAGE BODY statement can be used when\nOracle SQL_MODE is set.\n \nShows the CREATE statement that creates the given package\nbody (i.e. the implementation).\n \nExamples\n-------- \nSHOW CREATE PACKAGE BODY employee_tools\\G\n*************************** 1. row\n***************************\n Package body: employee_tools\n sql_mode:\nPIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER\n Create Package Body: CREATE DEFINER=\"root\"@\"localhost\"\nPACKAGE BODY \"employee_tools\" AS\n \n stdRaiseAmount DECIMAL(10,2):=500;\n \n PROCEDURE log (eid INT, ecmnt TEXT) AS\n BEGIN\n INSERT INTO employee_log (id, cmnt) VALUES (eid, ecmnt);\n END;\n \n PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2)) AS\n eid INT;\n BEGIN\n INSERT INTO employee (name, salary) VALUES (ename,\nesalary);\n eid:= last_insert_id();\n log(eid, \'hire \' || ename);\n END;\n \n FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2) AS\n nSalary DECIMAL(10,2);\n BEGIN\n SELECT salary INTO nSalary FROM employee WHERE id=eid;\n log(eid, \'getSalary id=\' || eid || \' salary=\' ||\nnSalary);\n RETURN nSalary;\n END;\n \n PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2)) AS\n BEGIN\n UPDATE employee SET salary=salary+amount WHERE id=eid;\n log(eid, \'raiseSalary id=\' || eid || \' amount=\' ||\namount);\n END;\n \n PROCEDURE raiseSalaryStd(eid INT) AS\n BEGIN\n raiseSalary(eid, stdRaiseAmount);\n log(eid, \'raiseSalaryStd id=\' || eid);\n END;\n \nBEGIN \n log(0, \'Session \' || connection_id() || \' \' ||\ncurrent_user || \' started\');\nEND\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/show-create-package-body/','','https://mariadb.com/kb/en/library/show-create-package-body/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (362,26,'SHOW CREATE PROCEDURE','Syntax\n------ \nSHOW CREATE PROCEDURE proc_name\n \nDescription\n----------- \nThis statement is a MariaDB extension. It returns the exact\nstring that\ncan be used to re-create the named stored procedure, as well\nas the SQL_MODE that was used when the trigger has been\ncreated and the character set used by the connection.. A\nsimilar\nstatement, SHOW CREATE FUNCTION,\ndisplays information about stored functions.\n \nBoth statements require that you are the owner of the\nroutine or have the SELECT privilege on the mysql.proc\ntable. When neither is true, the statements display NULL for\nthe Create Procedure or Create Function field.\n \nWarning Users with SELECT privileges on mysql.proc or USAGE\nprivileges on *.* can view the text of routines, even when\nthey do not have privileges for the function or procedure\nitself.\n \nThe output of these statements is unreliably affected by the\nsql_quote_show_create server system variable - see\nhttp://bugs.mysql.com/bug.php?id=12719\n \nExamples\n-------- \nHere\'s a comparison of the SHOW CREATE PROCEDURE and SHOW\nCREATE FUNCTION statements.\n \nSHOW CREATE PROCEDURE test.simpleproc\\G\n*************************** 1. row\n***************************\n Procedure: simpleproc\n sql_mode: \n Create Procedure: CREATE PROCEDURE `simpleproc`(OUT param1\nINT)\n BEGIN\n SELECT COUNT(*) INTO param1 FROM t;\n END\ncharacter_set_client: latin1\ncollation_connection: latin1_swedish_ci\n Database Collation: latin1_swedish_ci\n \nSHOW CREATE FUNCTION test.hello\\G\n*************************** 1. row\n***************************\n Function: hello\n sql_mode:\n Create Function: CREATE FUNCTION `hello`(s CHAR(20))\n RETURNS CHAR(50)\n RETURN CONCAT(\'Hello, \',s,\'!\')\ncharacter_set_client: latin1\ncollation_connection: latin1_swedish_ci\n Database Collation: latin1_swedish_ci\n \nWhen the user issuing the statement does not have privileges\non the routine, attempting to CALL the procedure raises\nError 1370.\n \nCALL test.prc1();\nError 1370 (42000): execute command denieed to user\n\'test_user\'@\'localhost\' for routine \'test\'.\'prc1\'\n \nIf the user neither has privilege to the routine nor the\nSELECT privilege on mysql.proc table, it raises Error 1305,\ninforming them that the procedure does not exist.\n \nSHOW CREATE TABLES test.prc1\\G\nError 1305 (42000): PROCEDURE prc1 does not exist\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/show-create-procedure/','','https://mariadb.com/kb/en/library/show-create-procedure/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (363,26,'SHOW CREATE SEQUENCE','Sequences were introduced in MariaDB 10.3.\n \nSyntax\n------ \nSHOW CREATE SEQUENCE sequence_name;\n \nDescription\n----------- \nShows the CREATE SEQUENCE statement that created the given\nsequence. The statement requires the SELECT privilege for\nthe table.\n \nExample\n \nCREATE SEQUENCE s1 START WITH 50;\n \nSHOW CREATE SEQUENCE s1\\G;\n \n*************************** 1. row\n***************************\n Table: t1\nCreate Table: CREATE SEQUENCE `s1` start with 50 minvalue 1\nmaxvalue 9223372036854775806\nincrement by 1 cache 1000 nocycle ENGINE=Aria\n \nNotes\n \nIf you want to see the underlying table structure used for\nthe SEQUENCE\nyou can use SHOW CREATE TABLE on the SEQUENCE. You can also\nuse SELECT to read the current recorded state of the\nSEQUENCE:\n \nCREATE SEQUENCE t1;\n \nSHOW CREATE TABLE s1\\G\n*************************** 1. row\n***************************\n Table: s1\nCreate Table: CREATE TABLE `s1` (\n `next_value` bigint(21) NOT NULL COMMENT \'next not cached\nvalue\',\n `min_value` bigint(21) NOT NULL COMMENT \'min value\',\n `max_value` bigint(21) NOT NULL COMMENT \'max value\',\n `start` bigint(21) NOT NULL COMMENT \'start value\',\n `increment` bigint(21) NOT NULL COMMENT \'increment\nvalue\',\n `cache` bigint(21) NOT NULL COMMENT \'cache size\',\n `cycle` tinyint(1) unsigned NOT NULL COMMENT \'cycle\nstate\',\n `round` bigint(21) NOT NULL COMMENT \'How many cycles has\nbeen done\'\n) ENGINE=Aria SEQUENCE=1\n \nSELECT * FROM s1;\n \n+------------+-----------+---------------------+-------+-----------+-------+-------+-------+\n| next_value | min_value | max_value | start | increment |\ncache | cycle | round |\n+------------+-----------+---------------------+-------+-----------+-------+-------+-------+\n| 1 | 1 | 9223372036854775806 | 1 | 1 | 1000 | 0 | 0 |\n+------------+-----------+---------------------+-------+-----------+-------+-------+-------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-sequence/','','https://mariadb.com/kb/en/library/show-create-sequence/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (364,26,'SHOW CREATE TABLE','Syntax\n------ \nSHOW CREATE TABLE tbl_name\n \nDescription\n----------- \nShows the CREATE TABLE statement that created the given\ntable. The statement requires the SELECT privilege for the\ntable. This statement also works with views and SEQUENCE.\n \nSHOW CREATE TABLE quotes table and\ncolumn names according to the value of the\nsql_quote_show_create server system variable.\n \nMariaDB and MySQL-specific table options, column options,\nand index options are not included in the output of this\nstatement if the NO_TABLE_OPTIONS, NO_FIELD_OPTIONS and\nNO_KEY_OPTIONS SQL_MODE flags are used.\n \nInvalid table options, column options and index options are\nnormally commented out (note, that it is possible to create\na table with invalid options, by altering a table of a\ndifferent engine, where these options were valid). To have\nthem uncommented, enable IGNORE_BAD_TABLE_OPTIONS SQL_MODE.\nRemember that replaying a CREATE TABLE statement with\nuncommented invalid options will fail with an error, unless\nIGNORE_BAD_TABLE_OPTIONS SQL_MODE is in effect.\n \nNote that SHOW CREATE TABLE is not meant to provide metadata\nabout a table. It provides information about how the table\nwas declared, but the real table structure could differ a\nbit. For example, if an index has been declared as HASH, the\nCREATE TABLE statement returned by SHOW CREATE TABLE will\ndeclare that index as HASH; however, it is possible that the\nindex is in fact a BTREE, because the storage engine does\nnot support HASH.\n \nMariaDB 10.2.1 permits TEXT and BLOB data types to be\nassigned a DEFAULT value. As a result, from MariaDB 10.2.1,\nSHOW CREATE TABLE will append a DEFAULT NULL to nullable\nTEXT or BLOB fields if no specific default is provided. \n \nFrom MariaDB 10.2.2, numbers are no longer quoted in the\nDEFAULT clause in SHOW CREATE statement. Previously, MariaDB\nquoted numbers. \n \nExamples\n-------- \nSHOW CREATE TABLE t\\G\n*************************** 1. row\n***************************\n Table: t\nCreate Table: CREATE TABLE `t` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `s` char(60) DEFAULT NULL,\n PRIMARY KEY (`id`)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\n \nWith sql_quote_show_create off:\n \nSHOW CREATE TABLE t\\G\n*************************** 1. row\n***************************\n Table: t\nCreate Table: CREATE TABLE t (\n id int(11) NOT NULL AUTO_INCREMENT,\n s char(60) DEFAULT NULL,\n PRIMARY KEY (id)\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\n \nUnquoted numeric DEFAULTs, from MariaDB 10.2.2:\n \nCREATE TABLE td (link TINYINT DEFAULT 1);\n \nSHOW CREATE TABLE td\\G\n*************************** 1. row\n***************************\n Table: td\nCreate Table: CREATE TABLE `td` (\n `link` tinyint(4) DEFAULT 1\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\n \nQuoted numeric DEFAULTs, until MariaDB 10.2.1:\n \nCREATE TABLE td (link TINYINT DEFAULT 1);\n \nSHOW CREATE TABLE td\\G\n*************************** 1. row\n***************************\n Table: td\nCreate Table: CREATE TABLE `td` (\n `link` tinyint(4) DEFAULT \'1\'\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-table/','','https://mariadb.com/kb/en/library/show-create-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (365,26,'SHOW CREATE TRIGGER','Syntax\n------ \nSHOW CREATE TRIGGER trigger_name\n \nDescription\n----------- \nThis statement shows a CREATE TRIGGER\nstatement that creates the given trigger, as well as the\nSQL_MODE that was used when the trigger has been created and\nthe character set used by the connection.\n \nThe output of this statement is unreliably affected by the\nsql_quote_show_create server system variable - see\nhttp://bugs.mysql.com/bug.php?id=12719\n \nExamples\n-------- \nSHOW CREATE TRIGGER example\\G\n*************************** 1. row\n***************************\n Trigger: example\n sql_mode:\nONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,STRICT_ALL_TABLES\n,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_\nENGINE_SUBSTITUTION\nSQL Original Statement: CREATE DEFINER=`root`@`localhost`\nTRIGGER example BEFORE\n INSERT ON t FOR EACH ROW\nBEGIN\n SET NEW.c = NEW.c * 2;\nEND\n character_set_client: cp850\n collation_connection: cp850_general_ci\n Database Collation: utf8_general_ci\n Created: 2016-09-29 13:53:34.35\n \nThe Created column was added in MySQL 5.7 and MariaDB 10.2.3\nas part of introducing multiple trigger events per action.\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-trigger/','','https://mariadb.com/kb/en/library/show-create-trigger/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (366,26,'SHOW CREATE USER','SHOW CREATE USER was introduced in MariaDB 10.2.0\n \nSyntax\n------ \nSHOW CREATE USER user_name\n \nDescription\n----------- \nShows the CREATE USER statement that created the given\nuser. The statement requires the SELECT privilege for the\nmysql database, except for the current user.\n \nExamples\n-------- \nCREATE USER foo4@test require cipher \'text\' \n issuer \'foo_issuer\' subject \'foo_subject\';\n \nSHOW CREATE USER foo4@test\\G\n*************************** 1. row\n***************************\nCREATE USER \'foo4\'@\'test\' \n REQUIRE ISSUER \'foo_issuer\' \n SUBJECT \'foo_subject\' \n CIPHER \'text\'\n \nUser Password Expiry:\n \nCREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE INTERVAL\n120 DAY;\n \nSHOW CREATE USER \'monty\'@\'localhost\';\n \n+------------------------------------------------------------------+\n| CREATE USER for monty@localhost |\n+------------------------------------------------------------------+\n| CREATE USER \'monty\'@\'localhost\' PASSWORD EXPIRE\nINTERVAL 120 DAY |\n+------------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-create-user/','','https://mariadb.com/kb/en/library/show-create-user/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (367,26,'SHOW CREATE VIEW','Syntax\n------ \nSHOW CREATE VIEW view_name\n \nDescription\n----------- \nThis statement shows a CREATE VIEW statement that creates\nthe given view, as well as the character set used by the\nconnection when the view was created. This statement\nalso works with views.\n \nSHOW CREATE VIEW quotes table, column and stored function\nnames according to the value of the sql_quote_show_create\nserver system variable.\n \nExamples\n-------- \nSHOW CREATE VIEW example\\G\n*************************** 1. row\n***************************\n View: example\n Create View: CREATE ALGORITHM=UNDEFINED\nDEFINER=`root`@`localhost` SQL\nSECURITY DEFINER VIEW `example` AS (select `t`.`id` AS\n`id`,`t`.`s` AS `s` from\n`t`)\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n \nWith sql_quote_show_create off:\n \nSHOW CREATE VIEW example\\G\n*************************** 1. row\n***************************\n View: example\n Create View: CREATE ALGORITHM=UNDEFINED\nDEFINER=root@localhost SQL SECU\nRITY DEFINER VIEW example AS (select t.id AS id,t.s AS s\nfrom t)\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-create-view/','','https://mariadb.com/kb/en/library/show-create-view/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (368,26,'SHOW DATABASES','Syntax\n------ \nSHOW {DATABASES | SCHEMAS}\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nSHOW DATABASES lists the databases on the MariaDB server\nhost.\nSHOW SCHEMAS is a synonym for \nSHOW DATABASES. The LIKE clause, if\npresent on its own, indicates which database names to match.\nThe WHERE and LIKE clauses can be given to select rows using\nmore general conditions, as discussed in Extended SHOW.\n \nYou see only those databases for which you have some kind of\nprivilege, unless you have the global \nSHOW DATABASES privilege. You\ncan also get this list using the mysqlshow command.\n \nIf the server was started with the --skip-show-database\noption, you cannot use this statement at all unless you have\nthe\nSHOW DATABASES privilege.\n \nExample\n \nSHOW DATABASES;\n+--------------------+\n| Database |\n+--------------------+\n| information_schema |\n| mysql |\n| performance_schema |\n| test |\n+--------------------+\n \nSHOW DATABASES LIKE \'m%\';\n+---------------+\n| Database (m%) |\n+---------------+\n| mysql |\n+---------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-databases/','','https://mariadb.com/kb/en/library/show-databases/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (369,26,'SHOW ENGINE','Syntax\n------ \nSHOW ENGINE engine_name {STATUS | MUTEX}\n \nDescription\n----------- \nSHOW ENGINE displays operational information about a storage\nengine. The following statements currently are supported:\n \nSHOW ENGINE INNODB STATUS\nSHOW ENGINE INNODB MUTEX\nSHOW ENGINE PERFORMANCE_SCHEMA STATUS\n \nIf the Sphinx Storage Engine is installed, the following is\nalso supported:\n \nSHOW ENGINE SPHINX STATUS\n \nSee SHOW ENGINE SPHINX STATUS.\n \nOlder (and now removed) synonyms were SHOW INNODB STATUS\nfor SHOW ENGINE INNODB STATUS and \nSHOW MUTEX STATUS for \nSHOW ENGINE INNODB MUTEX.\n \nSHOW ENGINE BDB LOGS formerly displayed status information\nabout BDB log files. It was deprecated in MySQL 5.1.12 and\nremoved in MariaDB and MySQL 5.5, so now produces an error.\n \nSHOW ENGINE INNODB STATUS\n \nSHOW ENGINE INNODB STATUS displays extensive information\nfrom the standard InnoDB Monitor about the state of the\nInnoDB storage engine.\nSee SHOW ENGINE INNODB STATUS for more.\n \nSHOW ENGINE INNODB MUTEX\n \nSHOW ENGINE INNODB MUTEX displays InnoDB mutex statistics.\n \nThe statement displays the following output fields:\nType: Always InnoDB.\nName: The source file where the mutex is implemented, and\nthe line number\n in the file where the mutex is created. The line number is\ndependent on the MariaDB version.\nStatus: This field displays the following values if\nUNIV_DEBUG was defined at compilation time (for example, in\ninclude/univ.h in the InnoDB part of the source tree). Only\nthe os_waits value is displayed if UNIV_DEBUG was not\ndefined. Without UNIV_DEBUG, the information on which the\noutput is based is insufficient to distinguish regular\nmutexes and mutexes that protect\n rw-locks (which allow multiple readers or a single writer).\nConsequently, the\n output may appear to contain multiple rows for the same\nmutex.\ncount indicates how many times the mutex was requested.\nspin_waits indicates how many times the spinlock had to run.\nspin_rounds indicates the number of spinlock rounds.\n(spin_rounds divided by\n spin_waits provides the average round count.)\nos_waits indicates the number of operating system waits.\nThis occurs when\n the spinlock did not work (the mutex was not locked during\nthe spinlock and\n it was necessary to yield to the operating system and\nwait).\nos_yields indicates the number of times a the thread trying\nto lock a mutex\n gave up its timeslice and yielded to the operating system\n(on the\n presumption that allowing other threads to run will free\nthe mutex so that\n it can be locked).\nos_wait_times indicates the amount of time (in ms) spent in\noperating system\n waits, if the timed_mutexes system variable is 1 (ON). If\ntimed_mutexes is 0\n (OFF), timing is disabled, so os_wait_times is 0.\ntimed_mutexes is off by\n default.\n \nInformation from this statement can be used to diagnose\nsystem problems. For\nexample, large values of spin_waits and spin_rounds may\nindicate scalability\nproblems.\n \nThe information_schema.INNODB_MUTEXES table provides similar\ninformation.\n \nSHOW ENGINE PERFORMANCE_SCHEMA STATUS\n \nThis statement shows how much memory is used for\nperformance_schema tables and internal buffers.\n \nThe output contains the following fields:\nType: Always performance_schema.\nName: The name of a table, the name of an internal buffer,\nor the performance_schema word, followed by a dot and an\nattribute. Internal buffers names are enclosed by\nparenthesis. performance_schema means that the attribute\nrefers to the whole database (it is a total). \nStatus: The value for the attribute.\n \nThe following attributes are shown, in this order, for all\ntables:\nrow_size: The memory used for an individual record. This\nvalue will never change.\nrow_count: The number of rows in the table or buffer. For\nsome tables, this value depends on a server system variable.\nmemory: For tables and performance_schema, this is the\nresult of row_size * row_count.\n \nFor internal buffers, the attributes are:\ncount\nsize\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-engine/','','https://mariadb.com/kb/en/library/show-engine/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (370,26,'SHOW ENGINE INNODB STATUS','SHOW ENGINE INNODB STATUS is a specific form of the SHOW\nENGINE statement that displays the InnoDB Monitor output,\nwhich is extensive InnoDB information which can be useful in\ndiagnosing problems.\n \nThe following sections are displayed\nStatus: Shows the timestamp, monitor name and the number of\nseconds, or the elapsed time between the current time and\nthe time the InnoDB Monitor output was last displayed. The\nper-second averages are based upon this time.\nBACKGROUND THREAD: srv_master_thread lines show work\nperformed by the main background thread.\nSEMAPHORES: Threads waiting for a semaphore and stats on how\nthe number of times threads have needed a spin or a wait on\na mutex or rw-lock semaphore. If this number of threads is\nlarge, there may be I/O or contention issues. Reducing the\nsize of the innodb_thread_concurrency system variable may\nhelp if contention is related to thread scheduling. Spin\nrounds per wait shows the number of spinlock rounds per OS\nwait for a mutex. \nLATEST FOREIGN KEY ERROR: Only shown if there has been a\nforeign key constraint error, it displays the failed\nstatement and information about the constraint and the\nrelated tables.\nLATEST DETECTED DEADLOCK: Only shown if there has been a\ndeadlock, it displays the transactions involved in the\ndeadlock and the statements being executed, held and\nrequired locked and the transaction rolled back to.\nTRANSACTIONS: The output of this section can help identify\nlock contention, as well as reasons for the deadlocks.\nFILE I/O: InnoDB thread information as well as pending I/O\noperations and I/O performance statistics.\nINSERT BUFFER AND ADAPTIVE HASH INDEX: InnoDB insert buffer\nand adaptive hash index status information, including the\nnumber of each type of operation performed, and adaptive\nhash index performance.\nLOG: InnoDB log information, including current log sequence\nnumber, how far the log has been flushed to disk, the\nposition at which InnoDB last took a checkpoint, pending\nwrites and write performance statistics.\nBUFFER POOL AND MEMORY: Information on buffer pool pages\nread and written, which allows you to see the number of data\nfile I/O operations performed by your queries. See InnoDB\nBuffer Pool for more. Similar information is also available\nfrom the INFORMATION_SCHEMA.INNODB_BUFFER_POOL_STATS table.\nROW OPERATIONS:Information about the main thread, including\nthe number and performance rate for each type of row\noperation. \n \nIf the innodb_status_output_locks system variable is set to\n1, extended lock information will be displayed.\n \nExample output:\n \n=====================================\n2016-09-12 04:42:15 7f226145fb00 INNODB MONITOR OUTPUT\n=====================================\nPer second averages calculated from the last 29 seconds\n-----------------\nBACKGROUND THREAD\n-----------------\nsrv_master_thread loops: 0 srv_active, 0 srv_shutdown, 527\nsrv_idle\nsrv_master_thread log flush and writes: 527\n----------\nSEMAPHORES\n----------\nOS WAIT ARRAY INFO: reservation count 4\nOS WAIT ARRAY INFO: signal count 4\nMutex spin waits 2, rounds 60, OS waits 2\nRW-shared spins 2, rounds 60, OS waits 2\nRW-excl spins 0, rounds 0, OS waits 0\nSpin rounds per wait: 30.00 mutex, 30.00 RW-shared, 0.00\nRW-excl\n------------\nTRANSACTIONS\n------------\nTrx id counter 2308\nPurge done for trx\'s n:o < 0 undo n:o < 0 state: running\nbut idle\nHistory list length 0\nLIST OF TRANSACTIONS FOR EACH SESSION:\n---TRANSACTION 0, not started\nMySQL thread id 3, OS thread handle 0x7f226145fb00, query id\n4 localhost root init\nSHOW ENGINE INNODB STATUS\n--------\nFILE I/O\n--------\nI/O thread 0 state: waiting for completed aio requests\n(insert buffer thread)\nI/O thread 1 state: waiting for completed aio requests (log\nthread)\nI/O thread 2 state: waiting for completed aio requests (read\nthread)\nI/O thread 3 state: waiting for completed aio requests (read\nthread)\nI/O thread 4 state: waiting for completed aio requests (read\nthread)\nI/O thread 5 state: waiting for completed aio requests (read\nthread)\nI/O thread 6 state: waiting for completed aio requests\n(write thread)\nI/O thread 7 state: waiting for completed aio requests\n(write thread)\nI/O thread 8 state: waiting for completed aio requests\n(write thread)\nI/O thread 9 state: waiting for completed aio requests\n(write thread)\nPending normal aio reads: 0 [0, 0, 0, 0] , aio writes: 0 [0,\n0, 0, 0] ,\n ibuf aio reads: 0, log i/o\'s: 0, sync i/o\'s: 0\nPending flushes (fsync) log: 0; buffer pool: 0\n172 OS file reads, 5 OS file writes, 5 OS fsyncs\n0.00 reads/s, 0 avg bytes/read, 0.00 writes/s, 0.00 fsyncs/s\n-------------------------------------\nINSERT BUFFER AND ADAPTIVE HASH INDEX\n-------------------------------------\nIbuf: size 1, free list len 0, seg size 2, 0 merges\nmerged operations:\n insert 0, delete mark 0, delete 0\ndiscarded operations:\n insert 0, delete mark 0, delete 0\n0.00 hash searches/s, 0.00 non-hash searches/s\n---\nLOG\n---\nLog sequence number 1616829\nLog flushed up to 1616829\nPages flushed up to 1616829\nLast checkpoint at 1616829\nMax checkpoint age 80826164\nCheckpoint age target 78300347\nModified age 0\nCheckpoint age 0\n0 pending log writes, 0 pending chkp writes\n8 log i/o\'s done, 0.00 log i/o\'s/second\n----------------------\nBUFFER POOL AND MEMORY\n----------------------\nTotal memory allocated 140771328; in additional pool\nallocated 0\nTotal memory allocated by read views 88\nInternal hash tables (constant factor + variable factor)\n Adaptive hash index 2217568 (2213368 + 4200)\n Page hash 139112 (buffer pool 0 only)\n Dictionary cache 630703 (554768 + 75935)\n File system 817648 (812272 + 5376)\n Lock system 333232 (332872 + 360)\n Recovery system 0 (0 + 0)\nDictionary memory allocated 75935\nBuffer pool size 8191\nBuffer pool size, bytes 134201344\nFree buffers 8037\nDatabase pages 154\nOld database pages 0\nModified db pages 0\nPercent of dirty pages(LRU & free pages): 0.000\nMax dirty pages percent: 75.000\nPending reads 0\nPending writes: LRU 0, flush list 0, single page 0\nPages made young 0, not young 0\n0.00 youngs/s, 0.00 non-youngs/s\nPages read 154, created 0, written 1\n0.00 reads/s, 0.00 creates/s, 0.00 writes/s\nNo buffer pool page gets since the last printout\nPages read ahead 0.00/s, evicted without access 0.00/s,\nRandom read ahead 0.00/s\nLRU len: 154, unzip_LRU len: 0\nI/O sum[0]:cur[0], unzip sum[0]:cur[0]\n--------------\nROW OPERATIONS\n--------------\n0 queries inside InnoDB, 0 queries in queue\n0 read views open inside InnoDB\n0 RW transactions active inside InnoDB\n0 RO transactions active inside InnoDB\n0 out of 1000 descriptors used\nMain thread process no. 3337, id 139784957703936, state:\nsleeping\nNumber of rows inserted 0, updated 0, deleted 0, read 0\n0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s\nNumber of system rows inserted 0, updated 0, deleted 0, read\n0\n0.00 inserts/s, 0.00 updates/s, 0.00 deletes/s, 0.00 reads/s\n----------------------------\nEND OF INNODB MONITOR OUTPUT\n============================\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/show-engine-innodb-status/','','https://mariadb.com/kb/en/library/show-engine-innodb-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (371,26,'SHOW ENGINES','Syntax\n------ \nSHOW [STORAGE] ENGINES\n \nDescription\n----------- \nSHOW ENGINES displays status information about the server\'s\nstorage engines. This is particularly useful for checking\nwhether a storage\nengine is supported, or to see what the default engine is. \nSHOW TABLE TYPES is a deprecated synonym.\n \nThe information_schema.ENGINES table provides the same\ninformation.\n \nSince storage engines are plugins, different information\nabout them is also shown in the information_schema.PLUGINS\ntable and by the SHOW PLUGINS statement.\n \nNote that both MySQL\'s InnoDB and Percona\'s XtraDB\nreplacement are labeled as InnoDB. However, if XtraDB is in\nuse, it will be specified in the COMMENT field. See XtraDB\nand InnoDB. The same applies to FederatedX.\n \nThe output consists of the following columns:\nEngine indicates the engine\'s name.\nSupport indicates whether the engine is installed, and\nwhether it is the default engine for the current session.\nComment is a brief description.\nTransactions, XA and Savepoints indicate whether\ntransactions, XA transactions and transaction savepoints are\nsupported by the engine.\n \nExamples\n-------- \nSHOW ENGINES\\G\n*************************** 1. row\n***************************\n Engine: InnoDB\n Support: DEFAULT\n Comment: Supports transactions, row-level locking, and\nforeign keys\nTransactions: YES\n XA: YES\n Savepoints: YES\n*************************** 2. row\n***************************\n Engine: CSV\n Support: YES\n Comment: CSV storage engine\nTransactions: NO\n XA: NO\n Savepoints: NO\n*************************** 3. row\n***************************\n Engine: MyISAM\n Support: YES\n Comment: MyISAM storage engine\nTransactions: NO\n XA: NO\n Savepoints: NO\n*************************** 4. row\n***************************\n Engine: BLACKHOLE\n Support: YES\n Comment: /dev/null storage engine (anything you write to it\ndisappears)\nTransactions: NO\n XA: NO\n Savepoints: NO\n*************************** 5. row\n***************************\n Engine: FEDERATED\n Support: YES\n Comment: FederatedX pluggable storage engine\nTransactions: YES\n XA: NO\n Savepoints: YES\n*************************** 6. row\n***************************\n Engine: MRG_MyISAM\n Support: YES\n Comment: Collection of identical MyISAM tables\nTransactions: NO\n XA: NO\n Savepoints: NO\n*************************** 7. row\n***************************\n Engine: ARCHIVE\n Support: YES\n Comment: Archive storage engine\nTransactions: NO\n XA: NO\n Savepoints: NO\n*************************** 8. row\n***************************\n Engine: MEMORY\n Support: YES\n Comment: Hash based, stored in memory, useful for temporary\ntables\nTransactions: NO\n XA: NO\n Savepoints: NO\n*************************** 9. row\n***************************\n Engine: PERFORMANCE_SCHEMA\n Support: YES\n Comment: Performance Schema\nTransactions: NO\n XA: NO\n Savepoints: NO\n*************************** 10. row\n***************************\n Engine: Aria\n Support: YES\n Comment: Crash-safe tables with MyISAM heritage\nTransactions: NO\n XA: NO\n Savepoints: NO\n10 rows in set (0.00 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-engines/','','https://mariadb.com/kb/en/library/show-engines/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (372,26,'SHOW ERRORS','Syntax\n------ \nSHOW ERRORS [LIMIT [offset,] row_count]\nSHOW ERRORS [LIMIT row_count OFFSET offset]\nSHOW COUNT(*) ERRORS\n \nDescription\n----------- \nThis statement is similar to SHOW WARNINGS, except that\ninstead of\ndisplaying errors, warnings, and notes, it displays only\nerrors.\n \nThe LIMIT clause has the same syntax as for the\nSELECT statement.\n \nThe SHOW COUNT(*) ERRORS statement displays the number of\nerrors. You can also retrieve this number from the\nerror_count variable.\n \nSHOW COUNT(*) ERRORS;\nSELECT @@error_count;\n \nThe value of error_count might be greater than the number of\nmessages displayed by SHOW WARNINGS if the max_error_count\nsystem variable is set so low that not all messages are\nstored.\n \nFor a list of MariaDB error codes, see MariaDB Error Codes.\n \nExamples\n-------- \nSELECT f();\nERROR 1305 (42000): FUNCTION f does not exist\n \nSHOW COUNT(*) ERRORS;\n \n+-----------------------+\n| @@session.error_count |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nSHOW ERRORS;\n \n+-------+------+---------------------------+\n| Level | Code | Message |\n+-------+------+---------------------------+\n| Error | 1305 | FUNCTION f does not exist |\n+-------+------+---------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-errors/','','https://mariadb.com/kb/en/library/show-errors/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (373,26,'SHOW EVENTS','Syntax\n------ \nSHOW EVENTS [{FROM | IN} schema_name]\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nShows information about Event Manager events (created with\nCREATE EVENT). Requires the EVENT privilege. Without any\narguments, SHOW EVENTS lists all of the events in the\ncurrent schema:\n \nSELECT CURRENT_USER(), SCHEMA();\n+----------------+----------+\n| CURRENT_USER() | SCHEMA() |\n+----------------+----------+\n| jon@ghidora | myschema |\n+----------------+----------+\n \nSHOW EVENTS\\G\n*************************** 1. row\n***************************\n Db: myschema\n Name: e_daily\n Definer: jon@ghidora\n Time zone: SYSTEM\n Type: RECURRING\n Execute at: NULL\n Interval value: 10\n Interval field: SECOND\n Starts: 2006-02-09 10:41:23\n Ends: NULL\n Status: ENABLED\n Originator: 0\ncharacter_set_client: latin1\ncollation_connection: latin1_swedish_ci\n Database Collation: latin1_swedish_ci\n \nTo see the event action, use SHOW CREATE EVENT instead, or\nlook at the information_schema.EVENTS table.\n \nTo see events for a specific schema, use the FROM clause.\nFor example, to see events for the test schema, use the\nfollowing statement:\n \nSHOW EVENTS FROM test;\n \nThe LIKE clause, if present, indicates which event names to\nmatch. The WHERE clause can be given to select rows using\nmore general conditions, as discussed in Extended Show.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-events/','','https://mariadb.com/kb/en/library/show-events/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (374,26,'SHOW EXPLAIN','The SHOW EXPLAIN command is a new feature in MariaDB 10.0.0.\n \nCommand description\n \nThe SHOW EXPLAIN command allows one to get an EXPLAIN (that\nis, a\ndescription of a query plan) of a query running in a certain\nthread.\n \nThe syntax is:\n \nSHOW EXPLAIN FOR ;\n \nwhich will produce an EXPLAIN output for the query that\nthread number thread_id is running. The thread id can be\nobtained with SHOW PROCESSLIST.\n \nSHOW EXPLAIN FOR 1;\n \n+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+\n| id | select_type | table | type | possible_keys | key |\nkey_len | ref | rows | Extra |\n+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+\n| 1 | SIMPLE | tbl | index | NULL | a | 5 | NULL | 1000107 |\nUsing index |\n+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+\n1 row in set, 1 warning (0.00 sec)\n \nThe output is always accompanied with a warning which shows\nthe query the\ntarget thread is running (this shows what the EXPLAIN is\nfor):\n \nSHOW WARNINGS;\n \n+-------+------+------------------------+\n| Level | Code | Message |\n+-------+------+------------------------+\n| Note | 1003 | select sum(a) from tbl |\n+-------+------+------------------------+\n1 row in set (0.00 sec)\n \nPossible errors\n \nThe output can be only produced if the target thread is\ncurrently running a\nquery, which has a ready query plan. If this is not the\ncase, the output will\nbe:\n \nSHOW EXPLAIN FOR 2;\n \nERROR 1932 (HY000): Target is not running an EXPLAINable\ncommand\n \nYou will get this error when:\nthe target thread is not running a command for which one can\nrun EXPLAIN\nthe target thread is running a command for which one can run\nEXPLAIN, but\nthere is no query plan yet (for example, tables are open and\nlocks are\n acquired before the query plan is produced)\n \n\nDifferences between SHOW EXPLAIN and EXPLAIN outputs\n \nBackground\n \nIn MySQL, EXPLAIN execution takes a slightly different route\nfrom the way\nthe real query (typically the SELECT) is optimized. This is\nunfortunate,\nand has caused a number of bugs in EXPLAIN. (For example,\nsee\nMDEV-326, MDEV-410, and\nlp:1013343.\nlp:992942 is not directly\nabout EXPLAIN, but it also would not have existed if MySQL\ndidn\'t try to delete\nparts of a query plan in the middle of the query) \n \nSHOW EXPLAIN examines a running SELECT, and hence its output\nmay be\nslightly different from what EXPLAIN SELECT would produce.\nWe did our best\nto make sure that either the difference is negligible, or\nSHOW EXPLAIN\'s\noutput is closer to reality than EXPLAIN\'s output.\n \nList of recorded differences\n \nSHOW EXPLAIN may have Extra=\'no matching row in const\ntable\', where EXPLAIN would produce Extra=\'Impossible\nWHERE ...\'\nFor queries with subqueries, SHOW EXPLAIN may print\nselect_type==PRIMARY where regular EXPLAIN used to print\nselect_type==SIMPLE, or vice versa.\n \nRequired permissions\n \nRunning SHOW EXPLAIN requires the same permissions as\nrunning SHOW PROCESSLIST would.\n \n\n\nURL: https://mariadb.com/kb/en/library/show-explain/','','https://mariadb.com/kb/en/library/show-explain/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (375,26,'SHOW FUNCTION CODE','Syntax\n------ \nSHOW FUNCTION CODE func_name\n \nDescription\n----------- \nSHOW FUNCTION CODE shows a representation of the internal\nimplementation of the stored function.\n \nIt is similar to SHOW PROCEDURE CODE but for stored\nfunctions.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-function-code/','','https://mariadb.com/kb/en/library/show-function-code/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (376,26,'SHOW FUNCTION STATUS','Syntax\n------ \nSHOW FUNCTION STATUS\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nThis statement is similar to \nSHOW PROCEDURE STATUS but for\nstored functions.\n \nThe LIKE clause, if present on its own, indicates which\nfunction names to match. \n \nThe WHERE and LIKE clauses can be given to select rows using\nmore general conditions, as discussed in Extended SHOW.\n \nThe information_schema.ROUTINES table contains more detailed\ninformation.\n \nExamples\n-------- \nShowing all stored functions:\n \nSHOW FUNCTION STATUS\\G\n*************************** 1. row\n***************************\n Db: test\n Name: VatCents\n Type: FUNCTION\n Definer: root@localhost\n Modified: 2013-06-01 12:40:31\n Created: 2013-06-01 12:40:31\n Security_type: DEFINER\n Comment: \ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \nStored functions whose name starts with \'V\': \n \nSHOW FUNCTION STATUS LIKE \'V%\' \\G\n*************************** 1. row\n***************************\n Db: test\n Name: VatCents\n Type: FUNCTION\n Definer: root@localhost\n Modified: 2013-06-01 12:40:31\n Created: 2013-06-01 12:40:31\n Security_type: DEFINER\n Comment: \ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \nStored functions with a security type of \'DEFINER\':\n \nSHOW FUNCTION STATUS WHERE Security_type LIKE \'DEFINER\'\n\\G\n*************************** 1. row\n***************************\n Db: test\n Name: VatCents\n Type: FUNCTION\n Definer: root@localhost\n Modified: 2013-06-01 12:40:31\n Created: 2013-06-01 12:40:31\n Security_type: DEFINER\n Comment: \ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-function-status/','','https://mariadb.com/kb/en/library/show-function-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (377,26,'SHOW GRANTS','Users\n \nSyntax\n------ \nSHOW GRANTS [FOR user]\n \nDescription\n----------- \nThis statement lists the GRANT statement or\nstatements that must be issued to duplicate the privileges\nthat are granted to\na MariaDB user account. The account is named using the same\nformat as for the\nGRANT statement; for example,\n\'jeffrey\'@\'localhost\'. If you specify only the user name\npart\nof the account name, a host name part of \'%\' is used. For\nadditional information about specifying account names, see\nGRANT.\n \nSHOW GRANTS FOR \'root\'@\'localhost\';\n+---------------------------------------------------------------------+\n| Grants for root@localhost |\n+---------------------------------------------------------------------+\n| GRANT ALL PRIVILEGES ON *.* TO \'root\'@\'localhost\' WITH\nGRANT OPTION |\n+---------------------------------------------------------------------+\n \nTo list the privileges granted to the account that you are\nusing to\nconnect to the server, you can use any of the following\nstatements:\n \nSHOW GRANTS;\n \nSHOW GRANTS FOR CURRENT_USER;\n \nSHOW GRANTS FOR CURRENT_USER();\n \nIf SHOW GRANTS FOR CURRENT_USER (or any\nof the equivalent syntaxes) is used in DEFINER context (such\nas within a stored procedure that is defined with \n SQL SECURITY DEFINER), the grants displayed are those of\nthe\ndefiner and not the invoker.\n \nNote that the DELETE HISTORY privilege, introduced in\nMariaDB 10.3.4, is displayed as DELETE VERSIONING ROWS when\nrunning SHOW GRANTS (MDEV-17655).\n \nRoles\n \nRoles were introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nSHOW GRANTS [FOR role]\n \nDescription\n----------- \nFrom MariaDB 10.0.5, SHOW GRANTS can also be used to view\nthe privileges granted to a role.\n \nExample\n \nSHOW GRANTS FOR journalist;\n+------------------------------------------+\n| Grants for journalist |\n+------------------------------------------+\n| GRANT USAGE ON *.* TO \'journalist\' |\n| GRANT DELETE ON `test`.* TO \'journalist\' |\n+------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-grants/','','https://mariadb.com/kb/en/library/show-grants/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (378,26,'SHOW INDEX','Syntax\n------ \nSHOW {INDEX | INDEXES | KEYS} \n FROM tbl_name [FROM db_name]\n [WHERE expr]\n \nDescription\n----------- \nSHOW INDEX returns table index information. The format\nresembles that of the SQLStatistics call in ODBC.\n \nYou can use db_name.tbl_name as an alternative to the\n tbl_name FROM db_name syntax. These two statements are\n equivalent:\n \nSHOW INDEX FROM mytable FROM mydb;\nSHOW INDEX FROM mydb.mytable;\n \nSHOW KEYS and SHOW INDEXES are synonyms for SHOW INDEX.\n \nYou can also list a table\'s indexes with the following\ncommand: \n \nmysqlshow -k db_name tbl_name\n \nSee mysqlshow for more details.\n \nThe information_schema.STATISTICS table stores similar\ninformation.\n \nThe following fields are returned by SHOW INDEX.\n \nField | Description | \n \nTable | Table name | \n \nNon_unique | 1 if the index permits duplicate values, 0 if\nvalues must be unique. | \n \nKey_name | Index name. The primary key is always named\nPRIMARY. | \n \nSeq_in_index | The column\'s sequence in the index,\nbeginning with 1. | \n \nColumn_name | Column name. | \n \nCollation | Either A, if the column is sorted in ascending\norder in the index, or NULL if it\'s not sorted. | \n \nCardinality | Estimated number of unique values in the\nindex. The cardinality statistics are calculated at various\ntimes, and can help the optimizer make improved decisions. |\n\n \nSub_part | NULL if the entire column is included in the\nindex, or the number of included characters if not. | \n \nPacked | NULL if the index is not packed, otherwise how the\nindex is packed. | \n \nNull | NULL if NULL values are permitted in the column, an\nempty string if NULL\'s are not permitted. | \n \nIndex_type | The index type, which can be BTREE, FULLTEXT,\nHASH or RTREE. See Storage Engine Index Types. | \n \nComment | Other information, such as whether the index is\ndisabled. | \n \nIndex_comment | Contents of the COMMENT attribute when the\nindex was created. | \n \nThe WHERE and LIKE clauses can be given to select rows using\nmore general conditions, as discussed in Extended SHOW.\n \nExamples\n-------- \nCREATE TABLE IF NOT EXISTS `employees_example` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `first_name` varchar(30) NOT NULL,\n `last_name` varchar(40) NOT NULL,\n `position` varchar(25) NOT NULL,\n `home_address` varchar(50) NOT NULL,\n `home_phone` varchar(12) NOT NULL,\n `employee_code` varchar(25) NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `employee_code` (`employee_code`),\n KEY `first_name` (`first_name`,`last_name`)\n) ENGINE=Aria;\n \nINSERT INTO `employees_example` (`first_name`, `last_name`,\n`position`, `home_address`, `home_phone`, `employee_code`)\n VALUES\n (\'Mustapha\', \'Mond\', \'Chief Executive Officer\', \'692\nPromiscuous Plaza\', \'326-555-3492\', \'MM1\'),\n (\'Henry\', \'Foster\', \'Store Manager\', \'314 Savage\nCircle\', \'326-555-3847\', \'HF1\'),\n (\'Bernard\', \'Marx\', \'Cashier\', \'1240 Ambient\nAvenue\', \'326-555-8456\', \'BM1\'),\n (\'Lenina\', \'Crowne\', \'Cashier\', \'281 Bumblepuppy\nBoulevard\', \'328-555-2349\', \'LC1\'),\n (\'Fanny\', \'Crowne\', \'Restocker\', \'1023 Bokanovsky\nLane\', \'326-555-6329\', \'FC1\'),\n (\'Helmholtz\', \'Watson\', \'Janitor\', \'944 Soma\nCourt\', \'329-555-2478\', \'HW1\');\n \nSHOW INDEXES FROM employees_example;\n \n+-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+\n| Table | Non_unique | Key_name | Seq_in_index | Column_name\n| Collation | Cardinality | Sub_part | Packed | Null |\nIndex_type | Comment | Index_comment |\n+-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+\n| employees_example | 0 | PRIMARY | 1 | id | A | 7 | NULL |\nNULL | | BTREE | | |\n| employees_example | 0 | employee_code | 1 | employee_code\n| A | 7 | NULL | NULL | | BTREE | | |\n| employees_example | 1 | first_name | 1 | first_name | A |\nNULL | NULL | NULL | | BTREE | | |\n| employees_example | 1 | first_name | 2 | last_name | A |\nNULL | NULL | NULL | | BTREE | | |\n+-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-index/','','https://mariadb.com/kb/en/library/show-index/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (379,26,'SHOW LOCALES','SHOW LOCALES was introduced as part of the Information\nSchema plugin extension in MariaDB 10.1.1.\n \nSHOW LOCALES is used to return locales information as part\nof the Locales plugin. While the information_schema.LOCALES\ntable has 8 columns, the SHOW LOCALES statement will only\ndisplay 4 of them:\n \nExample\n \nSHOW LOCALES;\n+-----+-------+-------------------------------------+------------------------+\n| Id | Name | Description | Error_Message_Language |\n+-----+-------+-------------------------------------+------------------------+\n| 0 | en_US | English - United States | english |\n| 1 | en_GB | English - United Kingdom | english |\n| 2 | ja_JP | Japanese - Japan | japanese |\n| 3 | sv_SE | Swedish - Sweden | swedish |\n...\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-locales/','','https://mariadb.com/kb/en/library/show-locales/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (380,26,'SHOW MASTER STATUS','Syntax\n------ \nSHOW MASTER STATUS\n \nDescription\n----------- \nProvides status information about the binary log files of\nthe master.\n \nThis statement requires the SUPER or the REPLICATION_CLIENT\nprivilege.\n \nTo see information about the current GTIDs in the binary\nlog, use the\ngtid_binlog_pos variable.\n \nExample\n \nSHOW MASTER STATUS;\n+--------------------+----------+--------------+------------------+\n| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |\n+--------------------+----------+--------------+------------------+\n| mariadb-bin.000016 | 475 | | |\n+--------------------+----------+--------------+------------------+\nSELECT @@global.gtid_binlog_pos;\n+--------------------------+\n| @@global.gtid_binlog_pos |\n+--------------------------+\n| 0-1-2 |\n+--------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-master-status/','','https://mariadb.com/kb/en/library/show-master-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (381,26,'SHOW OPEN TABLES','Syntax\n------ \nSHOW OPEN TABLES [FROM db_name]\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \n SHOW OPEN TABLES lists the non-TEMPORARY\ntables that are currently open in the table cache. See\nhttp://dev.mysql.com/doc/refman/5.1/en/table-cache.html.\n \nThe FROM and LIKE clauses may be used.\n \nThe FROM\nclause, if present, restricts the tables shown to those\npresent in the\ndb_name database. \n \nThe LIKE clause, if\npresent on its own, indicates which table names to match.\nThe WHERE and LIKE clauses can be given to select rows using\nmore general conditions, as discussed in Extended SHOW.\n \nThe following information is returned:\n \nColumn | Description | \n \nDatabase | Database name. | \n \nName | Table name. | \n \nIn_use | Number of table instances being used. | \n \nName_locked | 1 if the table is name-locked, e.g. if it is\nbeing dropped or renamed, otherwise 0. | \n \nBefore MariaDB 5.5, each use of, for example, LOCK TABLE ...\nWRITE would increment In_use for that table. With the\nimplementation of the metadata locking improvements in\nMariaDB 5.5, LOCK TABLE... WRITE acquires a strong MDL lock,\nand concurrent connections will wait on this MDL lock, so\nany subsequent LOCK TABLE... WRITE will not increment\nIn_use.\n \nExample\n \nSHOW OPEN TABLES;\n \n+----------+---------------------------+--------+-------------+\n| Database | Table | In_use | Name_locked |\n+----------+---------------------------+--------+-------------+\n...\n| test | xjson | 0 | 0 |\n| test | jauthor | 0 | 0 |\n| test | locks | 1 | 0 |\n...\n+----------+---------------------------+--------+-------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-open-tables/','','https://mariadb.com/kb/en/library/show-open-tables/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (382,26,'SHOW PACKAGE BODY STATUS','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nSHOW PACKAGE BODY STATUS\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nThe SHOW PACKAGE BODY STATUS statement returns\ncharacteristics of stored package bodies (implementations),\nsuch as the database, name, type, creator, creation and\nmodification dates, and character set information. A similar\nstatement, SHOW PACKAGE STATUS, displays information about\nstored package specifications.\n \nThe LIKE clause, if present, indicates which package names\nto match. The WHERE and LIKE clauses can be given to select\nrows using more general conditions, as discussed in Extended\nSHOW.\n \nThe ROUTINES table in the INFORMATION_SCHEMA database\ncontains more detailed information.\n \nExamples\n-------- \nSHOW PACKAGE BODY STATUS LIKE \'pkg1\'\\G\n*************************** 1. row\n***************************\n Db: test\n Name: pkg1\n Type: PACKAGE BODY\n Definer: root@localhost\n Modified: 2018-02-27 14:44:14\n Created: 2018-02-27 14:44:14\n Security_type: DEFINER\n Comment: This is my first package body\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/show-package-body-status/','','https://mariadb.com/kb/en/library/show-package-body-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (383,26,'SHOW PACKAGE STATUS','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nSHOW PACKAGE STATUS\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nThe SHOW PACKAGE STATUS statement returns characteristics of\nstored package specifications, such as the database, name,\ntype, creator, creation and modification dates, and\ncharacter set information. A similar statement, SHOW PACKAGE\nBODY STATUS, displays information about stored package\nbodies (i.e. implementations).\n \nThe LIKE clause, if present, indicates which package names\nto match. The WHERE and LIKE clauses can be given to select\nrows using more general conditions, as discussed in Extended\nSHOW.\n \nThe ROUTINES table in the INFORMATION_SCHEMA database\ncontains more detailed information.\n \nExamples\n-------- \nSHOW PACKAGE STATUS LIKE \'pkg1\'\\G\n*************************** 1. row\n***************************\n Db: test\n Name: pkg1\n Type: PACKAGE\n Definer: root@localhost\n Modified: 2018-02-27 14:38:15\n Created: 2018-02-27 14:38:15\n Security_type: DEFINER\n Comment: This is my first package\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \n\n\nURL: https://mariadb.com/kb/en/library/show-package-status/','','https://mariadb.com/kb/en/library/show-package-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (384,26,'SHOW PLUGINS','Syntax\n------ \nSHOW PLUGINS;\n \nDescription\n----------- \n SHOW PLUGINS displays information about installed plugins.\nThe Library column indicates the plugin library - if it is\nNULL, the plugin is built-in and cannot be uninstalled.\n \nThe PLUGINS table in the information_schema database\ncontains more detailed information.\n \nFor specific information about storage engines (a particular\ntype of plugin), see the information_schema.ENGINES table\nand the SHOW ENGINES statement.\n \nExamples\n-------- \nSHOW PLUGINS;\n+----------------------------+----------+--------------------+-------------+---------+\n| Name | Status | Type | Library | License |\n+----------------------------+----------+--------------------+-------------+---------+\n| binlog | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| mysql_native_password | ACTIVE | AUTHENTICATION | NULL |\nGPL |\n| mysql_old_password | ACTIVE | AUTHENTICATION | NULL | GPL\n|\n| MRG_MyISAM | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| MyISAM | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| CSV | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| MEMORY | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| FEDERATED | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| PERFORMANCE_SCHEMA | ACTIVE | STORAGE ENGINE | NULL | GPL\n|\n| Aria | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| InnoDB | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| INNODB_TRX | ACTIVE | INFORMATION SCHEMA | NULL | GPL |\n...\n| INNODB_SYS_FOREIGN | ACTIVE | INFORMATION SCHEMA | NULL |\nGPL |\n| INNODB_SYS_FOREIGN_COLS | ACTIVE | INFORMATION SCHEMA |\nNULL | GPL |\n| SPHINX | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| ARCHIVE | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| BLACKHOLE | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| FEEDBACK | DISABLED | INFORMATION SCHEMA | NULL | GPL |\n| partition | ACTIVE | STORAGE ENGINE | NULL | GPL |\n| pam | ACTIVE | AUTHENTICATION | auth_pam.so | GPL |\n+----------------------------+----------+--------------------+-------------+---------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-plugins/','','https://mariadb.com/kb/en/library/show-plugins/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (385,26,'SHOW PLUGINS SONAME','MariaDB 10.0.2\n \nSHOW PLUGINS SONAME was introduced in MariaDB 10.0.2\n \nSyntax\n------ \nSHOW PLUGINS SONAME { library | LIKE \'pattern\' | WHERE\nexpr };\n \nDescription\n----------- \nSHOW PLUGINS SONAME displays information about compiled-in\nand all server plugins in the plugin_dir directory,\nincluding plugins that haven\'t been installed.\n \nExamples\n-------- \nSHOW PLUGINS SONAME \'ha_example.so\';\n+----------+---------------+----------------+---------------+---------+\n| Name | Status | Type | Library | License |\n+----------+---------------+----------------+---------------+---------+\n| EXAMPLE | NOT INSTALLED | STORAGE ENGINE | ha_example.so |\nGPL |\n| UNUSABLE | NOT INSTALLED | DAEMON | ha_example.so | GPL |\n+----------+---------------+----------------+---------------+---------+\n \nThere is also a corresponding information_schema table,\ncalled ALL_PLUGINS, which contains more complete\ninformation.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-plugins-soname/','','https://mariadb.com/kb/en/library/show-plugins-soname/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (386,26,'SHOW PRIVILEGES','Syntax\n------ \nSHOW PRIVILEGES\n \nDescription\n----------- \n SHOW PRIVILEGES shows the list of system privileges that\nthe MariaDB server supports. The exact list of privileges\ndepends on the version of your server.\n \nExamples\n-------- \nSHOW PRIVILEGES;\n+-------------------------+---------------------------------------+-------------------------------------------------------+\n| Privilege | Context | Comment |\n+-------------------------+---------------------------------------+-------------------------------------------------------+\n| Alter | Tables | To alter the table |\n| Alter routine | Functions,Procedures | To alter or drop\nstored functions/procedures |\n| Create | Databases,Tables,Indexes | To create new\ndatabases and tables |\n| Create routine | Databases | To use CREATE\nFUNCTION/PROCEDURE |\n| Create temporary tables | Databases | To use CREATE\nTEMPORARY TABLE |\n| Create view | Tables | To create new views |\n| Create user | Server Admin | To create new users |\n| Delete | Tables | To delete existing rows |\n| Drop | Databases,Tables | To drop databases, tables, and\nviews |\n| Event | Server Admin | To create, alter, drop and execute\nevents |\n| Execute | Functions,Procedures | To execute stored\nroutines |\n| File | File access on server | To read and write files on\nthe server |\n| Grant option | Databases,Tables,Functions,Procedures | To\ngive to other users those privileges you possess |\n| Index | Tables | To create or drop indexes |\n| Insert | Tables | To insert data into tables |\n| Lock tables | Databases | To use LOCK TABLES (together\nwith SELECT privilege) |\n| Process | Server Admin | To view the plain text of\ncurrently executing queries |\n| Proxy | Server Admin | To make proxy user possible |\n| References | Databases,Tables | To have references on\ntables |\n| Reload | Server Admin | To reload or refresh tables, logs\nand privileges |\n| Replication client | Server Admin | To ask where the slave\nor master servers are |\n| Replication slave | Server Admin | To read binary log\nevents from the master |\n| Select | Tables | To retrieve rows from table |\n| Show databases | Server Admin | To see all databases with\nSHOW DATABASES |\n| Show view | Tables | To see views with SHOW CREATE VIEW |\n| Shutdown | Server Admin | To shut down the server |\n| Super | Server Admin | To use KILL thread, SET GLOBAL,\nCHANGE MASTER, etc. |\n| Trigger | Tables | To use triggers |\n| Create tablespace | Server Admin | To create/alter/drop\ntablespaces |\n| Update | Tables | To update existing rows |\n| Usage | Server Admin | No privileges - allow connect only\n|\n+-------------------------+---------------------------------------+-------------------------------------------------------+\n31 rows in set (0.07 sec)\n \n\n\nURL: https://mariadb.com/kb/en/library/show-privileges/','','https://mariadb.com/kb/en/library/show-privileges/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (387,26,'SHOW PROCEDURE CODE','Syntax\n------ \nSHOW PROCEDURE CODE proc_name\n \nDescription\n----------- \nThis statement is a MariaDB extension that is available only\nfor servers that\nhave been built with debugging support. It displays a\nrepresentation of the\ninternal implementation of the named stored procedure. A\nsimilar statement,\n SHOW FUNCTION CODE, displays\ninformation about stored functions.\n \nBoth statements require that you be the owner of the routine\nor have\n SELECT access to the mysql.proc table.\n \nIf the named routine is available, each statement produces a\nresult\nset. Each row in the result set corresponds to one\n\"instruction\" in\nthe routine. The first column is Pos, which is an ordinal\nnumber\nbeginning with 0. The second column is Instruction, which\ncontains an\nSQL statement (usually changed from the original source), or\na\ndirective which has meaning only to the stored-routine\nhandler.\n \nExamples\n-------- \nDELIMITER //\n \nCREATE PROCEDURE p1 ()\n BEGIN\n DECLARE fanta INT DEFAULT 55;\n DROP TABLE t2;\n LOOP\n INSERT INTO t3 VALUES (fanta);\n END LOOP;\n END//\nQuery OK, 0 rows affected (0.00 sec)\n \nSHOW PROCEDURE CODE p1//\n+-----+----------------------------------------+\n| Pos | Instruction |\n+-----+----------------------------------------+\n| 0 | set fanta@0 55 |\n| 1 | stmt 9 \"DROP TABLE t2\" |\n| 2 | stmt 5 \"INSERT INTO t3 VALUES (fanta)\" |\n| 3 | jump 2 |\n+-----+----------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-procedure-code/','','https://mariadb.com/kb/en/library/show-procedure-code/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (388,26,'SHOW PROCEDURE STATUS','Syntax\n------ \nSHOW PROCEDURE STATUS\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nThis statement is a MariaDB extension. It returns\ncharacteristics of a stored\nprocedure, such as the database, name, type, creator,\ncreation and modification\ndates, and character set information. A similar statement, \n SHOW FUNCTION STATUS, displays\ninformation about stored functions.\n \nThe LIKE clause, if present, indicates which procedure or\nfunction names to match. The WHERE and LIKE clauses can be\ngiven to select rows using more general conditions, as\ndiscussed in Extended SHOW.\n \nThe ROUTINES table in the INFORMATION_SCHEMA database\ncontains more detailed information.\n \nExamples\n-------- \nSHOW PROCEDURE STATUS LIKE \'p1\'\\G\n*************************** 1. row\n***************************\n Db: test\n Name: p1\n Type: PROCEDURE\n Definer: root@localhost\n Modified: 2010-08-23 13:23:03\n Created: 2010-08-23 13:23:03\n Security_type: DEFINER\n Comment: \ncharacter_set_client: latin1\ncollation_connection: latin1_swedish_ci\n Database Collation: latin1_swedish_ci\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/show-procedure-status/','','https://mariadb.com/kb/en/library/show-procedure-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (389,26,'SHOW PROCESSLIST','Syntax\n------ \nSHOW [FULL] PROCESSLIST\n \nDescription\n----------- \n SHOW PROCESSLIST shows you which threads are running. You\ncan also get this information from the\ninformation_schema.PROCESSLIST table or the mysqladmin\nprocesslist command. If you have the \nPROCESS privilege, you can see all threads.\nOtherwise, you can see only your own threads (that is,\nthreads associated with\nthe MariaDB account that you are using). If you do not use\nthe\nFULL keyword, only the first 100 characters of each\nstatement are shown in the Info field.\n \nThe columns shown in SHOW PROCESSLIST\n are:\n \nName | Description | Introduced | \n \nID | The client\'s process ID. | | \n \nUSER | The username associated with the process. | | \n \nHOST | The host the client is connected to. | | \n \nDB | The default database of the process (NULL if no\ndefault). | | \n \nCOMMAND | The command type. See Thread Command Values. | | \n \nTIME | The amount of time, in seconds, the process has been\nin its current state. For a slave SQL thread before MariaDB\n10.1, this is the time in seconds between the last\nreplicated event\'s timestamp and the slave machine\'s real\ntime. | | \n \nSTATE | See Thread States. | | \n \nINFO | The statement being executed. | | \n \nPROGRESS | The total progress of the process (0-100%) (see\nProgress Reporting). | MariaDB 5.3 | \n \nSee TIME_MS column in information_schema.PROCESSLIST for\ndifferences in the TIME column between MariaDB and MySQL.\n \nThe information_schema.PROCESSLIST table contains the\nfollowing additional columns:\n \nName | Description | Introduced | \n \nTIME_MS | The amount of time, in milliseconds, the process\nhas been in its current state. | MariaDB 5.1 | \n \nSTAGE | The stage the process is currently in. |\nMariaDB 5.3 | \n \nMAX_STAGE | The maximum number of stages. | MariaDB 5.3 | \n \nPROGRESS | The progress of the process within the current\nstage (0-100%). | MariaDB 5.3 | \n \nMEMORY_USED | The amount of memory used by the process. |\nMariaDB 10.0.1 | \n \nEXAMINED_ROWS | The number of rows the process has examined.\n| MariaDB 10.0.1 | \n \nQUERY_ID | Query ID. | MariaDB 10.0.5 | \n \nNote that the PROGRESS field from the information schema,\nand the PROGRESS field from SHOW PROCESSLIST display\ndifferent results. SHOW PROCESSLIST shows the total\nprogress, while the information schema shows the progress\nfor the current stage only.\n \nThreads can be killed using their thread_id, or, since\nMariaDB 10.0.5, their query_id, with the KILL statement.\n \nSince queries on this table are locking, if the\nperformance_schema is enabled, you may want to query the\nTHREADS table instead.\n \nExamples\n-------- \nFrom MariaDB 5.1.x\n \nSHOW FULL PROCESSLIST;\n+---------+-------+-----------+------+---------+------+-------+-----------------------+\n| Id | User | Host | db | Command | Time | State | Info |\n+---------+-------+-----------+------+---------+------+-------+-----------------------+\n| 1988880 | dbart | localhost | NULL | Query | 0 | NULL |\nSHOW FULL PROCESSLIST |\n+---------+-------+-----------+------+---------+------+-------+-----------------------+\n \nSELECT * FROM information_schema.processlist;\n+---------+-------+-----------+------+---------+------+-----------+----------------------------------------------+---------+\n| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |\nTIME_MS |\n+---------+-------+-----------+------+---------+------+-----------+----------------------------------------------+---------+\n| 1988880 | dbart | localhost | NULL | Query | 0 | executing\n| SELECT * FROM information_schema.processlist | 0.444 |\n+---------+-------+-----------+------+---------+------+-----------+----------------------------------------------+---------+\n \nFrom MariaDB 5.5.x\n \nSHOW FULL PROCESSLIST;\n+-----+------+-----------+------+---------+------+-------+-----------------------+----------+\n| Id | User | Host | db | Command | Time | State | Info |\nProgress |\n+-----+------+-----------+------+---------+------+-------+-----------------------+----------+\n| 126 | root | localhost | NULL | Query | 0 | NULL | SHOW\nFULL PROCESSLIST | 0.000 |\n+-----+------+-----------+------+---------+------+-------+-----------------------+----------+\n \nSELECT * FROM information_schema.processlist;\n+-----+--------+-----------+------+---------+------+-----------+----------------------------------------------+---------+-------+-----------+----------+\n| ID | USER | HOST | DB | COMMAND | TIME | STATE | INFO |\nTIME_MS | STAGE | MAX_STAGE | PROGRESS |\n+-----+--------+-----------+------+---------+------+-----------+----------------------------------------------+---------+-------+-----------+----------+\n| 126 | root | localhost | NULL | Query | 0 | executing |\nSELECT * FROM information_schema.processlist | 344.718 | 0 |\n0 | 0.000 |\n+-----+--------+-----------+------+---------+------+-----------+----------------------------------------------+---------+-------+-----------+----------+\n \nFrom MariaDB 10.0.x\n \nSHOW PROCESSLIST;\n+----+-----------------+-----------+------+---------+------+------------------------+------------------+----------+\n| Id | User | Host | db | Command | Time | State | Info |\nProgress |\n+----+-----------------+-----------+------+---------+------+------------------------+------------------+----------+\n| 2 | event_scheduler | localhost | NULL | Daemon | 2693 |\nWaiting on empty queue | NULL | 0.000 |\n| 4 | root | localhost | NULL | Query | 0 | Table lock |\nSHOW PROCESSLIST | 0.000 |\n+----+-----------------+-----------+------+---------+------+------------------------+------------------+----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-processlist/','','https://mariadb.com/kb/en/library/show-processlist/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (390,26,'SHOW PROFILE','Syntax\n------ \nSHOW PROFILE [type [, type] ... ]\n [FOR QUERY n]\n [LIMIT row_count [OFFSET offset]]\n \ntype:\n ALL\n | BLOCK IO\n | CONTEXT SWITCHES\n | CPU\n | IPC\n | MEMORY\n | PAGE FAULTS\n | SOURCE\n | SWAPS\n \nDescription\n----------- \nThe SHOW PROFILE and \nSHOW PROFILES statements display profiling\ninformation that indicates resource usage for statements\nexecuted during the\ncourse of the current session.\n \nProfiling is controlled by the profiling session variable,\nwhich has a default value of 0 (OFF). Profiling is enabled\nby setting profiling to 1 or ON:\n \nSET profiling = 1;\n \nSHOW PROFILES displays a list of the most recent statements\nsent to the master. The size of the list is controlled by\nthe\nprofiling_history_size session variable, which has a default\nvalue of 15. The maximum value is 100. Setting the value to\n0 has the practical effect of disabling profiling.\n \nAll statements are profiled except SHOW PROFILES and \nSHOW PROFILE, so you will find neither of those statements\nin the profile list. Malformed statements are profiled. For\nexample, \n SHOW PROFILING is an illegal statement, and a syntax error\noccurs if you try to execute it, but it will show up in the\nprofiling list.\n \n SHOW PROFILE displays detailed information about a single\nstatement. Without the FOR QUERY n clause, the output\npertains to the most recently executed statement. If \n FOR QUERY n is included,\n SHOW PROFILE displays information for statement n. The\nvalues of n correspond to\nthe Query_ID values displayed by SHOW PROFILES.\n \nThe LIMIT row_count clause may be given to limit the\noutput to row_count rows. If LIMIT is given, \n OFFSET offset may be added to begin the output offset\nrows into the full set of rows.\n \nBy default, SHOW PROFILE displays Status and Duration\ncolumns. The Status values are like the State values\ndisplayed by \nSHOW PROCESSLIST,\nalthough there might be some minor differences in\ninterpretation for\nthe two statements for some status values (see\nhttp://dev.mysql.com/doc/refman/5.6/en/thread-information.html).\n \nOptional type values may be specified to display specific\nadditional\ntypes of information:\nALL displays all information\nBLOCK IO displays counts for block input and output\noperations\nCONTEXT SWITCHES displays counts for voluntary and\ninvoluntary context switches\nCPU displays user and system CPU usage times\nIPC displays counts for messages sent and received\nMEMORY is not currently implemented\nPAGE FAULTS displays counts for major and minor page faults\nSOURCE displays the names of functions from the source code,\ntogether with the name and line number of the file in which\nthe function occurs\nSWAPS displays swap counts\n \nProfiling is enabled per session. When a session ends, its\nprofiling information is lost.\n \nThe information_schema.PROFILING table contains similar\ninformation.\n \nExamples\n-------- \nSELECT @@profiling;\n+-------------+\n| @@profiling |\n+-------------+\n| 0 |\n+-------------+\n \nSET profiling = 1;\n \nUSE test;\n \nDROP TABLE IF EXISTS t1;\n \nCREATE TABLE T1 (id INT);\n \nSHOW PROFILES;\n+----------+------------+--------------------------+\n| Query_ID | Duration | Query |\n+----------+------------+--------------------------+\n| 1 | 0.00009200 | SELECT DATABASE() |\n| 2 | 0.00023800 | show databases |\n| 3 | 0.00018900 | show tables |\n| 4 | 0.00014700 | DROP TABLE IF EXISTS t1 |\n| 5 | 0.24476900 | CREATE TABLE T1 (id INT) |\n+----------+------------+--------------------------+\n \nSHOW PROFILE;\n+----------------------+----------+\n| Status | Duration |\n+----------------------+----------+\n| starting | 0.000042 |\n| checking permissions | 0.000044 |\n| creating table | 0.244645 |\n| After create | 0.000013 |\n| query end | 0.000003 |\n| freeing items | 0.000016 |\n| logging slow query | 0.000003 |\n| cleaning up | 0.000003 |\n+----------------------+----------+\n \nSHOW PROFILE FOR QUERY 4;\n+--------------------+----------+\n| Status | Duration |\n+--------------------+----------+\n| starting | 0.000126 |\n| query end | 0.000004 |\n| freeing items | 0.000012 |\n| logging slow query | 0.000003 |\n| cleaning up | 0.000002 |\n+--------------------+----------+\n \nSHOW PROFILE CPU FOR QUERY 5;\n+----------------------+----------+----------+------------+\n| Status | Duration | CPU_user | CPU_system |\n+----------------------+----------+----------+------------+\n| starting | 0.000042 | 0.000000 | 0.000000 |\n| checking permissions | 0.000044 | 0.000000 | 0.000000 |\n| creating table | 0.244645 | 0.000000 | 0.000000 |\n| After create | 0.000013 | 0.000000 | 0.000000 |\n| query end | 0.000003 | 0.000000 | 0.000000 |\n| freeing items | 0.000016 | 0.000000 | 0.000000 |\n| logging slow query | 0.000003 | 0.000000 | 0.000000 |\n| cleaning up | 0.000003 | 0.000000 | 0.000000 |\n+----------------------+----------+----------+------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-profile/','','https://mariadb.com/kb/en/library/show-profile/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (391,26,'SHOW PROFILES','Syntax\n------ \nSHOW PROFILES\n \nDescription\n----------- \nThe SHOW PROFILES statement displays profiling information\nthat indicates resource usage for statements executed during\nthe course of the\ncurrent session. It is used together with \nSHOW PROFILE.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-profiles/','','https://mariadb.com/kb/en/library/show-profiles/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (392,26,'SHOW QUERY_RESPONSE_TIME','SHOW QUERY_RESPONSE_TIME was introduced in MariaDB 10.1.1.\n \nStarting with MariaDB 10.1.1, which introduced the\nInformation Schema plugin extension, it is possible to use\nSHOW QUERY_RESPONSE_TIME as an alternative for retrieving\ninformation from the QUERY_RESPONSE_TIME plugin.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/show-query_response_time/','','https://mariadb.com/kb/en/library/show-query_response_time/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (393,26,'SHOW RELAYLOG EVENTS','Syntax\n------ \nSHOW RELAYLOG [\'connection_name\'] EVENTS\n [IN \'log_name\'] [FROM pos] [LIMIT [offset,] row_count]\n \nDescription\n----------- \nOn replication slaves this command shows the events in the\nrelay log. If \'log_name\' is not specified, the first relay\nlog is shown.\n \nSyntax for the LIMIT clause is the same as for SELECT ...\nLIMIT.\n \nUsing the LIMIT clause is highly recommended because the\nSHOW RELAYLOG EVENTS command returns the complete contents\nof the relay log, which can be quite large.\n \nThis command does not return events related to setting user\nand system variables. If you need those, use mysqlbinlog.\n \nOn the replication master, this command does nothing.\n \nconnection_name\n \nconnection_name was added as part of multi-source\nreplication added in MariaDB 10.0.1\n \nIf there is only one nameless master, or the default master\n(as specified by the default_master_connection system\nvariable) is intended, connection_name can be omitted. If\nprovided, the SHOW RELAYLOG statement will apply to the\nspecified master. connection_name is case-insensitive.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-relaylog-events/','','https://mariadb.com/kb/en/library/show-relaylog-events/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (394,26,'SHOW SLAVE HOSTS','Syntax\n------ \nSHOW SLAVE HOSTS\n \nDescription\n----------- \nThis command is run on the master and displays a list of\nreplication slaves that are currently registered with it.\nOnly slaves started with the --report-host=host_name option\nare visible in this list.\n \nThe list is displayed on any server (not just the master\nserver). The output\nlooks like this:\n \nSHOW SLAVE HOSTS;\n+------------+-----------+------+-----------+\n| Server_id | Host | Port | Master_id |\n+------------+-----------+------+-----------+\n| 192168010 | iconnect2 | 3306 | 192168011 |\n| 1921680101 | athena | 3306 | 192168011 |\n+------------+-----------+------+-----------+\nServer_id: The unique server ID of the slave server, as\nconfigured in the server\'s option file, or on the command\nline with --server-id=value.\nHost: The host name of the slave server, as configured in\nthe server\'s option file, or on the command line with\n--report-host=host_name. Note that this can differ from the\nmachine name as configured in the operating system.\nPort: The port the slave server is listening on.\nMaster_id: The unique server ID of the master server that\nthe slave server is replicating from.\n \nSome MariaDB and MySQL versions report another variable,\nrpl_recovery_rank. This\nvariable was never used, and was eventually removed in\nMariaDB 10.1.2 and MySQL 5.6.\n \n\n\nURL: https://mariadb.com/kb/en/library/show-slave-hosts/','','https://mariadb.com/kb/en/library/show-slave-hosts/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (395,26,'SHOW SLAVE STATUS','Syntax\n------ \nSHOW SLAVE [\"connection_name\"] STATUS\n \nor\n \nSHOW ALL SLAVES STATUS\n \nDescription\n----------- \nThis statement is to be run on a slave and provides status\ninformation on essential parameters of the replication slave\nthreads.\n \nThis statement requires the SUPER or the REPLICATION_CLIENT\nprivilege.\n \nMulti-source\n \nMariaDB 10.0 introduced the FULL and \"connection_name\"\noptions to\nallow you to connect to many masters at the same time.\n \nALL SLAVES gives you a list of all connections to the\nmaster.\n \nThe rows will be sorted according to Connection_name.\n \nIf you specify a connection_name, you only get the\ninformation about that\nconnection. If connection_name is not used, then the name\nset by default_master_connection is used. If the connection\nname doesn\'t exist you will get an error:\nThere is no master connection for \'xxx\'.\n \nColumn descriptions\n \nName | Description | Added | \n \nConnection_name | Name of the master connection. Returned\nwith SHOW ALL SLAVES STATUS only. | MariaDB 10.0 | \n \nSlave_SQL_State | State of SQL thread. Returned with SHOW\nALL SLAVES STATUS only. See Slave SQL Thread States. |\nMariaDB 10.0 | \n \nSlave_IO_State | State of I/O thread. See Slave I/O Thread\nStates. | MariaDB 10.0 | \n \nMaster_host | Master host that the slave is connected to. | \n| \n \nMaster_user | Account user name being used to connect to the\nmaster. | | \n \nMaster_port | The port being used to connect to the master.\n| | \n \nConnect_Retry | Time in seconds between retries to connect.\nThe default is 60. The CHANGE MASTER TO statement can set\nthis. The master-retry-count option determines the maximum\nnumber of reconnection attempts. | | \n \nMaster_Log_File | Name of the master binary log file that\nthe I/O thread is currently reading from. | | \n \nRead_Master_Log_Pos | Position up to which the I/O thread\nhas read in the current master binary log file. | | \n \nRelay_Log_File | Name of the relay log file that the SQL\nthread is currently processing. | | \n \nRelay_Log_Pos | Position up to which the SQL thread has\nfinished processing in the current relay log file. | | \n \nRelay_Master_Log_File | Name of the master binary log file\nthat contains the most recent event executed by the SQL\nthread. | | \n \nSlave_IO_Running | Whether the slave I/O thread is running\nand connected (Yes), running but not connected to a master\n(Connecting) or not running (No). | | \n \nSlave_SQL_Running | Whether or not the SQL thread is\nrunning. | | \n \nReplicate_Do_DB | Databases specified for replicating with\nthe replicate_do_db option. | | \n \nReplicate_Ignore_DB | Databases specified for ignoring with\nthe replicate_ignore_db option. | | \n \nReplicate_Do_Table | Tables specified for replicating with\nthe replicate_do_table option. | | \n \nReplicate_Ignore_Table | Tables specified for ignoring with\nthe replicate_ignore_table option. | | \n \nReplicate_Wild_Do_Table | Tables specified for replicating\nwith the replicate_wild_do_table option. | | \n \nReplicate_Wild_Ignore_Table | Tables specified for ignoring\nwith the replicate_wild_ignore_table option. | | \n \nLast_Errno | Alias for Last_SQL_Errno (see below) | | \n \nLast Error | Alias for Last_SQL_Error (see below) | | \n \nSkip_Counter | Number of events that a slave skips from the\nmaster, as recorded in the sql_slave_skip_counter system\nvariable. | | \n \nExec_Master_Log_Pos | Position up to which the SQL thread\nhas processed in the current master binary log file. Can be\nused to start a new slave from a current slave with the\nCHANGE MASTER TO ... MASTER_LOG_POS option. | | \n \nRelay_Log_Space | Total size of all relay log files\ncombined. | | \n \nUntil_Condition | | | \n \nUntil_Log_File | The MASTER_LOG_FILE value of the START\nSLAVE UNTIL condition. | | \n \nUntil_Log_Pos | The MASTER_LOG_POS value of the START SLAVE\nUNTIL condition. | | \n \nMaster_SSL_Allowed | Whether an SSL connection is permitted\n(Yes), not permitted (No) or permitted but without the slave\nhaving SSL support enabled (Ignored) | | \n \nMaster_SSL_CA_File | The MASTER_SSL_CA option of the CHANGE\nMASTER TO statement. | | \n \nMaster_SSL_CA_Path | The MASTER_SSL_CAPATH option of the\nCHANGE MASTER TO statement. | | \n \nMaster_SSL_Cert | The MASTER_SSL_CERT option of the CHANGE\nMASTER TO statement. | | \n \nMaster_SSL_Cipher | The MASTER_SSL_CIPHER option of the\nCHANGE MASTER TO statement. | | \n \nMaster_SSL_Key | The MASTER_SSL_KEY option of the CHANGE\nMASTER TO statement. | | \n \nSeconds_Behind_Master | Difference between the timestamp\nlogged on the master for the event that the slave is\ncurrently processing, and the current timestamp on the\nslave. Zero if the slave is not currently processing an\nevent. From MariaDB 10.0.23 and MariaDB 10.1.9, with\nparallel replication, seconds_behind_master is updated only\nafter transactions commit. | | \n \nMaster_SSL_Verify_Server_Cert | The\nMASTER_SSL_VERIFY_SERVER_CERT option of the CHANGE MASTER TO\nstatement. | | \n \nLast_IO_Errno | Error code of the most recent error that\ncaused the I/O thread to stop (also recorded in the slave\'s\nerror log). 0 means no error. RESET SLAVE or RESET MASTER\nwill reset this value. | | \n \nLast_IO_Error | Error message of the most recent error that\ncaused the I/O thread to stop (also recorded in the slave\'s\nerror log). An empty string means no error. RESET SLAVE or\nRESET MASTER will reset this value. | | \n \nLast_SQL_Errno | Error code of the most recent error that\ncaused the SQL thread to stop (also recorded in the slave\'s\nerror log). 0 means no error. RESET SLAVE or RESET MASTER\nwill reset this value. | | \n \nLast_SQL_Error | Error message of the most recent error that\ncaused the SQL thread to stop (also recorded in the slave\'s\nerror log). An empty string means no error. RESET SLAVE or\nRESET MASTER will reset this value. | | \n \nReplicate_Ignore_Server_Ids | List of server_ids that are\ncurrently being ignored for replication purposes, or an\nempty string for none, as specified in the IGNORE_SERVER_IDS\noption of the CHANGE MASTER TO statement. | | \n \nMaster_Server_Id | The master\'s server_id value. | | \n \nMaster_SSL_Crl | The MASTER_SSL_CRL option of the CHANGE\nMASTER TO statement. | MariaDB 10.0 | \n \nMaster_SSL_Crlpath | The MASTER_SSL_CRLPATH option of the\nCHANGE MASTER TO statement. | MariaDB 10.0 | \n \nUsing_Gtid | Whether or not global transaction ID\'s are\nbeing used for replication (can be No, Slave_Pos, or\nCurrent_Pos). | MariaDB 10.0.2 | \n \nGtid_IO_Pos | Current global transaction ID value. | MariaDB\n10.0.2 | \n \nRetried_transactions | Number of retried transactions for\nthis connection. Returned with SHOW ALL SLAVES STATUS only.\n| MariaDB 10.0 | \n \nMax_relay_log_size | Max relay log size for this connection.\nReturned with SHOW ALL SLAVES STATUS only. | MariaDB 10.0 | \n \nExecuted_log_entries | How many log entries the slave has\nexecuted. Returned with SHOW ALL SLAVES STATUS only. |\nMariaDB 10.0 | \n \nSlave_received_heartbeats | How many heartbeats we have got\nfrom the master. Returned with SHOW ALL SLAVES STATUS only.\n| MariaDB 10.0 | \n \nSlave_heartbeat_period | How often to request a heartbeat\npacket from the master (in seconds). Returned with SHOW ALL\nSLAVES STATUS only. | MariaDB 10.0 | \n \nGtid_Slave_Pos | GTID of the last event group replicated on\na slave server, for each replication domain, as stored in\nthe gtid_slave_pos system variable. Returned with SHOW ALL\nSLAVES STATUS only. | MariaDB 10.0 | \n \nSQL_Delay | Value specified by MASTER_DELAY in CHANGE MASTER\n(or 0 if none). | MariaDB 10.2.3 | \n \nSQL_Remaining_Delay | When the slave is delaying the\nexecution of an event due to MASTER_DELAY, this is the\nnumber of seconds of delay remaining before the event will\nbe applied. Otherwise, the value is NULL. | MariaDB 10.2.3 |\n\n \nSlave_SQL_Running_State | The state of the SQL driver\nthreads, same as in SHOW PROCESSLIST. When the slave is\ndelaying the execution of an event due to MASTER_DELAY, this\nfield displays: \"Waiting until MASTER_DELAY seconds after\nmaster executed event\". | MariaDB 10.2.3 | \n \nExamples\n-------- \nIf you issue this statement using the mysql client,\nyou can use a \\G statement terminator rather than a\nsemicolon to\nobtain a more readable vertical layout.\n \nSHOW SLAVE STATUS\\G\n*************************** 1. row\n***************************\n Slave_IO_State: Waiting for master to send event\n Master_Host: db01.example.com\n Master_User: replicant\n Master_Port: 3306\n Connect_Retry: 60\n Master_Log_File: mariadb-bin.000010\n Read_Master_Log_Pos: 548\n Relay_Log_File: relay-bin.000004\n Relay_Log_Pos: 837\n Relay_Master_Log_File: mariadb-bin.000010\n Slave_IO_Running: Yes\n Slave_SQL_Running: Yes\n Replicate_Do_DB: \n Replicate_Ignore_DB: \n Replicate_Do_Table: \n Replicate_Ignore_Table: \n Replicate_Wild_Do_Table: \n Replicate_Wild_Ignore_Table: \n Last_Errno: 0\n Last_Error: \n Skip_Counter: 0\n Exec_Master_Log_Pos: 548\n Relay_Log_Space: 1497\n Until_Condition: None\n Until_Log_File: \n Until_Log_Pos: 0\n Master_SSL_Allowed: No\n Master_SSL_CA_File: \n Master_SSL_CA_Path: \n Master_SSL_Cert: \n Master_SSL_Cipher: \n Master_SSL_Key: \n Seconds_Behind_Master: 0\nMaster_SSL_Verify_Server_Cert: No\n Last_IO_Errno: 0\n Last_IO_Error: \n Last_SQL_Errno: 0\n Last_SQL_Error: \n Replicate_Ignore_Server_Ids: \n Master_Server_Id: 101\n Master_SSL_Crl: \n Master_SSL_Crlpath: \n Using_Gtid: No\n Gtid_IO_Pos: \n \nMariaDB [(none)]> SHOW ALL SLAVES STATUS\\G\n*************************** 1. row\n***************************\n Connection_name: \n Slave_SQL_State: Slave has read all relay log; waiting for\nthe slave I/O thread to update it\n Slave_IO_State: Waiting for master to send event\n Master_Host: db01.example.com\n Master_User: replicant\n Master_Port: 3306\n Connect_Retry: 60\n Master_Log_File: mariadb-bin.000010\n Read_Master_Log_Pos: 3608\n Relay_Log_File: relay-bin.000004\n Relay_Log_Pos: 3897\n Relay_Master_Log_File: mariadb-bin.000010\n Slave_IO_Running: Yes\n Slave_SQL_Running: Yes\n Replicate_Do_DB: \n Replicate_Ignore_DB: \n Replicate_Do_Table: \n Replicate_Ignore_Table: \n Replicate_Wild_Do_Table: \n Replicate_Wild_Ignore_Table: \n Last_Errno: 0\n Last_Error: \n Skip_Counter: 0\n Exec_Master_Log_Pos: 3608\n Relay_Log_Space: 4557\n Until_Condition: None\n Until_Log_File: \n Until_Log_Pos: 0\n Master_SSL_Allowed: No\n Master_SSL_CA_File: \n Master_SSL_CA_Path: \n Master_SSL_Cert: \n Master_SSL_Cipher: \n Master_SSL_Key: \n Seconds_Behind_Master: 0\nMaster_SSL_Verify_Server_Cert: No\n Last_IO_Errno: 0\n Last_IO_Error: \n Last_SQL_Errno: 0\n Last_SQL_Error: \n Replicate_Ignore_Server_Ids: \n Master_Server_Id: 101\n Master_SSL_Crl: \n Master_SSL_Crlpath: \n Using_Gtid: No\n Gtid_IO_Pos:\n Retried_transactions: 0\n Max_relay_log_size: 104857600\n Executed_log_entries: 40\n Slave_received_heartbeats: 11\n Slave_heartbeat_period: 1800.000\n Gtid_Slave_Pos: 0-101-2320\n \nYou can also access some of the variables directly from\nstatus variables:\n \nSET @@default_master_connection=\"test\" ;\nshow status like \"%slave%\"\n \nVariable_name Value\nCom_show_slave_hosts 0\nCom_show_slave_status 0\nCom_start_all_slaves 0\nCom_start_slave 0\nCom_stop_all_slaves 0\nCom_stop_slave 0\nRpl_semi_sync_slave_status OFF\nSlave_connections 0\nSlave_heartbeat_period 1800.000\nSlave_open_temp_tables 0\nSlave_received_heartbeats 0\nSlave_retried_transactions 0\nSlave_running OFF\nSlaves_connected 0\nSlaves_running 1\n \n\n\nURL: https://mariadb.com/kb/en/library/show-slave-status/','','https://mariadb.com/kb/en/library/show-slave-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (396,26,'SHOW STATUS','Syntax\n------ \nSHOW [GLOBAL | SESSION] STATUS\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nSHOW STATUS provides server status information. This\ninformation also can be obtained using the mysqladmin\nextended-status command, or by querying the Information\nSchema GLOBAL_STATUS and SESSION_STATUS tables.\nThe LIKE clause, if present, indicates which variable names\nto match. The WHERE clause can be given to select rows using\nmore general conditions.\n \nWith the GLOBAL modifier, SHOW STATUS\ndisplays the status values for all connections to MariaDB.\nWith\nSESSION, it displays the status values\nfor the current connection. If no modifier is present, the\ndefault is\n SESSION. LOCAL is a synonym for\n SESSION. If you see a lot of 0 values, the reason is\nprobably that you have used SHOW STATUS with a new\nconnection instead of SHOW GLOBAL STATUS.\n \nSome status variables have only a global value. For these,\nyou get the\nsame value for both GLOBAL and SESSION.\n \nSee Server Status Variables for a full list, scope and\ndescription of the variables that can be viewed with SHOW\nSTATUS.\n \nThe LIKE clause, if present on its own, indicates which\nvariable name to match.\n \nThe WHERE and LIKE clauses can be given to select rows using\nmore general conditions, as discussed in Extended SHOW.\n \nExamples\n-------- \nFull output from MariaDB 10.1.17:\n \nSHOW GLOBAL STATUS;\n \n+--------------------------------------------------------------+----------------------------------------+\n| Variable_name | Value |\n+--------------------------------------------------------------+----------------------------------------+\n| Aborted_clients | 0 |\n| Aborted_connects | 0 |\n| Access_denied_errors | 0 |\n| Acl_column_grants | 0 |\n| Acl_database_grants | 2 |\n| Acl_function_grants | 0 |\n| Acl_procedure_grants | 0 |\n| Acl_proxy_users | 2 |\n| Acl_role_grants | 0 |\n| Acl_roles | 0 |\n| Acl_table_grants | 0 |\n| Acl_users | 6 |\n| Aria_pagecache_blocks_not_flushed | 0 |\n| Aria_pagecache_blocks_unused | 15706 |\n| Aria_pagecache_blocks_used | 0 |\n| Aria_pagecache_read_requests | 0 |\n| Aria_pagecache_reads | 0 |\n| Aria_pagecache_write_requests | 0 |\n| Aria_pagecache_writes | 0 |\n| Aria_transaction_log_syncs | 0 |\n| Binlog_commits | 0 |\n| Binlog_group_commits | 0 |\n| Binlog_group_commit_trigger_count | 0 |\n| Binlog_group_commit_trigger_lock_wait | 0 |\n| Binlog_group_commit_trigger_timeout | 0 |\n| Binlog_snapshot_file | |\n| Binlog_snapshot_position | 0 |\n| Binlog_bytes_written | 0 |\n| Binlog_cache_disk_use | 0 |\n| Binlog_cache_use | 0 |\n| Binlog_stmt_cache_disk_use | 0 |\n| Binlog_stmt_cache_use | 0 |\n| Busy_time | 0.000000 |\n| Bytes_received | 432 |\n| Bytes_sent | 15183 |\n| Com_admin_commands | 1 |\n| Com_alter_db | 0 |\n| Com_alter_db_upgrade | 0 |\n| Com_alter_event | 0 |\n| Com_alter_function | 0 |\n| Com_alter_procedure | 0 |\n| Com_alter_server | 0 |\n| Com_alter_table | 0 |\n| Com_alter_tablespace | 0 |\n| Com_analyze | 0 |\n| Com_assign_to_keycache | 0 |\n| Com_begin | 0 |\n| Com_binlog | 0 |\n| Com_call_procedure | 0 |\n| Com_change_db | 0 |\n| Com_change_master | 0 |\n| Com_check | 0 |\n| Com_checksum | 0 |\n| Com_commit | 0 |\n| Com_compound_sql | 0 |\n| Com_create_db | 0 |\n| Com_create_event | 0 |\n| Com_create_function | 0 |\n| Com_create_index | 0 |\n| Com_create_procedure | 0 |\n| Com_create_role | 0 |\n| Com_create_server | 0 |\n| Com_create_table | 0 |\n| Com_create_temporary_table | 0 |\n| Com_create_trigger | 0 |\n| Com_create_udf | 0 |\n| Com_create_user | 0 |\n| Com_create_view | 0 |\n| Com_dealloc_sql | 0 |\n| Com_delete | 0 |\n| Com_delete_multi | 0 |\n| Com_do | 0 |\n| Com_drop_db | 0 |\n| Com_drop_event | 0 |\n| Com_drop_function | 0 |\n| Com_drop_index | 0 |\n| Com_drop_procedure | 0 |\n| Com_drop_role | 0 |\n| Com_drop_server | 0 |\n| Com_drop_table | 0 |\n| Com_drop_temporary_table | 0 |\n| Com_drop_trigger | 0 |\n| Com_drop_user | 0 |\n| Com_drop_view | 0 |\n| Com_empty_query | 0 |\n| Com_execute_sql | 0 |\n| Com_flush | 0 |\n| Com_get_diagnostics | 0 |\n| Com_grant | 0 |\n| Com_grant_role | 0 |\n| Com_ha_close | 0 |\n| Com_ha_open | 0 |\n| Com_ha_read | 0 |\n| Com_help | 0 |\n| Com_insert | 0 |\n| Com_insert_select | 0 |\n| Com_install_plugin | 0 |\n| Com_kill | 0 |\n| Com_load | 0 |\n| Com_lock_tables | 0 |\n| Com_optimize | 0 |\n| Com_preload_keys | 0 |\n| Com_prepare_sql | 0 |\n| Com_purge | 0 |\n| Com_purge_before_date | 0 |\n| Com_release_savepoint | 0 |\n| Com_rename_table | 0 |\n| Com_rename_user | 0 |\n| Com_repair | 0 |\n| Com_replace | 0 |\n| Com_replace_select | 0 |\n| Com_reset | 0 |\n| Com_resignal | 0 |\n| Com_revoke | 0 |\n| Com_revoke_all | 0 |\n| Com_revoke_role | 0 |\n| Com_rollback | 0 |\n| Com_rollback_to_savepoint | 0 |\n| Com_savepoint | 0 |\n| Com_select | 1 |\n| Com_set_option | 0 |\n| Com_show_authors | 0 |\n| Com_show_binlog_events | 0 |\n| Com_show_binlogs | 0 |\n| Com_show_charsets | 0 |\n| Com_show_collations | 0 |\n| Com_show_contributors | 0 |\n| Com_show_create_db | 0 |\n| Com_show_create_event | 0 |\n| Com_show_create_func | 0 |\n| Com_show_create_proc | 0 |\n| Com_show_create_table | 0 |\n| Com_show_create_trigger | 0 |\n| Com_show_databases | 0 |\n| Com_show_engine_logs | 0 |\n| Com_show_engine_mutex | 0 |\n| Com_show_engine_status | 0 |\n| Com_show_errors | 0 |\n| Com_show_events | 0 |\n| Com_show_explain | 0 |\n| Com_show_fields | 0 |\n| Com_show_function_status | 0 |\n| Com_show_generic | 0 |\n| Com_show_grants | 0 |\n| Com_show_keys | 0 |\n| Com_show_master_status | 0 |\n| Com_show_open_tables | 0 |\n| Com_show_plugins | 0 |\n| Com_show_privileges | 0 |\n| Com_show_procedure_status | 0 |\n| Com_show_processlist | 0 |\n| Com_show_profile | 0 |\n| Com_show_profiles | 0 |\n| Com_show_relaylog_events | 0 |\n| Com_show_slave_hosts | 0 |\n| Com_show_slave_status | 0 |\n| Com_show_status | 2 |\n| Com_show_storage_engines | 0 |\n| Com_show_table_status | 0 |\n| Com_show_tables | 0 |\n| Com_show_triggers | 0 |\n| Com_show_variables | 0 |\n| Com_show_warnings | 0 |\n| Com_shutdown | 0 |\n| Com_signal | 0 |\n| Com_start_all_slaves | 0 |\n| Com_start_slave | 0 |\n| Com_stmt_close | 0 |\n| Com_stmt_execute | 0 |\n| Com_stmt_fetch | 0 |\n| Com_stmt_prepare | 0 |\n| Com_stmt_reprepare | 0 |\n| Com_stmt_reset | 0 |\n| Com_stmt_send_long_data | 0 |\n| Com_stop_all_slaves | 0 |\n| Com_stop_slave | 0 |\n| Com_truncate | 0 |\n| Com_uninstall_plugin | 0 |\n| Com_unlock_tables | 0 |\n| Com_update | 0 |\n| Com_update_multi | 0 |\n| Com_xa_commit | 0 |\n| Com_xa_end | 0 |\n| Com_xa_prepare | 0 |\n| Com_xa_recover | 0 |\n| Com_xa_rollback | 0 |\n| Com_xa_start | 0 |\n| Compression | OFF |\n| Connection_errors_accept | 0 |\n| Connection_errors_internal | 0 |\n| Connection_errors_max_connections | 0 |\n| Connection_errors_peer_address | 0 |\n| Connection_errors_select | 0 |\n| Connection_errors_tcpwrap | 0 |\n| Connections | 4 |\n| Cpu_time | 0.000000 |\n| Created_tmp_disk_tables | 0 |\n| Created_tmp_files | 6 |\n| Created_tmp_tables | 2 |\n| Delayed_errors | 0 |\n| Delayed_insert_threads | 0 |\n| Delayed_writes | 0 |\n| Delete_scan | 0 |\n| Empty_queries | 0 |\n| Executed_events | 0 |\n| Executed_triggers | 0 |\n| Feature_delay_key_write | 0 |\n| Feature_dynamic_columns | 0 |\n| Feature_fulltext | 0 |\n| Feature_gis | 0 |\n| Feature_locale | 0 |\n| Feature_subquery | 0 |\n| Feature_timezone | 0 |\n| Feature_trigger | 0 |\n| Feature_xml | 0 |\n| Flush_commands | 1 |\n| Handler_commit | 1 |\n| Handler_delete | 0 |\n| Handler_discover | 0 |\n| Handler_external_lock | 0 |\n| Handler_icp_attempts | 0 |\n| Handler_icp_match | 0 |\n| Handler_mrr_init | 0 |\n| Handler_mrr_key_refills | 0 |\n| Handler_mrr_rowid_refills | 0 |\n| Handler_prepare | 0 |\n| Handler_read_first | 3 |\n| Handler_read_key | 0 |\n| Handler_read_last | 0 |\n| Handler_read_next | 0 |\n| Handler_read_prev | 0 |\n| Handler_read_retry | 0 |\n| Handler_read_rnd | 0 |\n| Handler_read_rnd_deleted | 0 |\n| Handler_read_rnd_next | 537 |\n| Handler_rollback | 0 |\n| Handler_savepoint | 0 |\n| Handler_savepoint_rollback | 0 |\n| Handler_tmp_update | 0 |\n| Handler_tmp_write | 516 |\n| Handler_update | 0 |\n| Handler_write | 0 |\n| Innodb_available_undo_logs | 128 |\n| Innodb_background_log_sync | 222 |\n| Innodb_buffer_pool_bytes_data | 2523136 |\n| Innodb_buffer_pool_bytes_dirty | 0 |\n| Innodb_buffer_pool_dump_status | Dumping buffer pool(s)\nnot yet started |\n| Innodb_buffer_pool_load_status | Loading buffer pool(s)\nnot yet started |\n| Innodb_buffer_pool_pages_data | 154 |\n| Innodb_buffer_pool_pages_dirty | 0 |\n| Innodb_buffer_pool_pages_flushed | 1 |\n| Innodb_buffer_pool_pages_free | 8037 |\n| Innodb_buffer_pool_pages_lru_flushed | 0 |\n| Innodb_buffer_pool_pages_made_not_young | 0 |\n| Innodb_buffer_pool_pages_made_young | 0 |\n| Innodb_buffer_pool_pages_misc | 0 |\n| Innodb_buffer_pool_pages_old | 0 |\n| Innodb_buffer_pool_pages_total | 8191 |\n| Innodb_buffer_pool_read_ahead | 0 |\n| Innodb_buffer_pool_read_ahead_evicted | 0 |\n| Innodb_buffer_pool_read_ahead_rnd | 0 |\n| Innodb_buffer_pool_read_requests | 558 |\n| Innodb_buffer_pool_reads | 155 |\n| Innodb_buffer_pool_wait_free | 0 |\n| Innodb_buffer_pool_write_requests | 1 |\n| Innodb_checkpoint_age | 0 |\n| Innodb_checkpoint_max_age | 80826164 |\n| Innodb_data_fsyncs | 5 |\n| Innodb_data_pending_fsyncs | 0 |\n| Innodb_data_pending_reads | 0 |\n| Innodb_data_pending_writes | 0 |\n| Innodb_data_read | 2609664 |\n| Innodb_data_reads | 172 |\n| Innodb_data_writes | 5 |\n| Innodb_data_written | 34304 |\n| Innodb_dblwr_pages_written | 1 |\n| Innodb_dblwr_writes | 1 |\n| Innodb_deadlocks | 0 |\n| Innodb_have_atomic_builtins | ON |\n| Innodb_history_list_length | 0 |\n| Innodb_ibuf_discarded_delete_marks | 0 |\n| Innodb_ibuf_discarded_deletes | 0 |\n| Innodb_ibuf_discarded_inserts | 0 |\n| Innodb_ibuf_free_list | 0 |\n| Innodb_ibuf_merged_delete_marks | 0 |\n| Innodb_ibuf_merged_deletes | 0 |\n| Innodb_ibuf_merged_inserts | 0 |\n| Innodb_ibuf_merges | 0 |\n| Innodb_ibuf_segment_size | 2 |\n| Innodb_ibuf_size | 1 |\n| Innodb_log_waits | 0 |\n| Innodb_log_write_requests | 0 |\n| Innodb_log_writes | 1 |\n| Innodb_lsn_current | 1616829 |\n| Innodb_lsn_flushed | 1616829 |\n| Innodb_lsn_last_checkpoint | 1616829 |\n| Innodb_master_thread_active_loops | 0 |\n| Innodb_master_thread_idle_loops | 222 |\n| Innodb_max_trx_id | 2308 |\n| Innodb_mem_adaptive_hash | 2217568 |\n| Innodb_mem_dictionary | 630703 |\n| Innodb_mem_total | 140771328 |\n| Innodb_mutex_os_waits | 1 |\n| Innodb_mutex_spin_rounds | 30 |\n| Innodb_mutex_spin_waits | 1 |\n| Innodb_oldest_view_low_limit_trx_id | 0 |\n| Innodb_os_log_fsyncs | 3 |\n| Innodb_os_log_pending_fsyncs | 0 |\n| Innodb_os_log_pending_writes | 0 |\n| Innodb_os_log_written | 512 |\n| Innodb_page_size | 16384 |\n| Innodb_pages_created | 0 |\n| Innodb_pages_read | 154 |\n| Innodb_pages_written | 1 |\n| Innodb_purge_trx_id | 0 |\n| Innodb_purge_undo_no | 0 |\n| Innodb_read_views_memory | 88 |\n| Innodb_row_lock_current_waits | 0 |\n| Innodb_row_lock_time | 0 |\n| Innodb_row_lock_time_avg | 0 |\n| Innodb_row_lock_time_max | 0 |\n| Innodb_row_lock_waits | 0 |\n| Innodb_rows_deleted | 0 |\n| Innodb_rows_inserted | 0 |\n| Innodb_rows_read | 0 |\n| Innodb_rows_updated | 0 |\n| Innodb_system_rows_deleted | 0 |\n| Innodb_system_rows_inserted | 0 |\n| Innodb_system_rows_read | 0 |\n| Innodb_system_rows_updated | 0 |\n| Innodb_s_lock_os_waits | 2 |\n| Innodb_s_lock_spin_rounds | 60 |\n| Innodb_s_lock_spin_waits | 2 |\n| Innodb_truncated_status_writes | 0 |\n| Innodb_x_lock_os_waits | 0 |\n| Innodb_x_lock_spin_rounds | 0 |\n| Innodb_x_lock_spin_waits | 0 |\n| Innodb_page_compression_saved | 0 |\n| Innodb_page_compression_trim_sect512 | 0 |\n| Innodb_page_compression_trim_sect1024 | 0 |\n| Innodb_page_compression_trim_sect2048 | 0 |\n| Innodb_page_compression_trim_sect4096 | 0 |\n| Innodb_page_compression_trim_sect8192 | 0 |\n| Innodb_page_compression_trim_sect16384 | 0 |\n| Innodb_page_compression_trim_sect32768 | 0 |\n| Innodb_num_index_pages_written | 0 |\n| Innodb_num_non_index_pages_written | 5 |\n| Innodb_num_pages_page_compressed | 0 |\n| Innodb_num_page_compressed_trim_op | 0 |\n| Innodb_num_page_compressed_trim_op_saved | 0 |\n| Innodb_num_pages_page_decompressed | 0 |\n| Innodb_num_pages_page_compression_error | 0 |\n| Innodb_num_pages_encrypted | 0 |\n| Innodb_num_pages_decrypted | 0 |\n| Innodb_have_lz4 | OFF |\n| Innodb_have_lzo | OFF |\n| Innodb_have_lzma | OFF |\n| Innodb_have_bzip2 | OFF |\n| Innodb_have_snappy | OFF |\n| Innodb_defragment_compression_failures | 0 |\n| Innodb_defragment_failures | 0 |\n| Innodb_defragment_count | 0 |\n| Innodb_onlineddl_rowlog_rows | 0 |\n| Innodb_onlineddl_rowlog_pct_used | 0 |\n| Innodb_onlineddl_pct_progress | 0 |\n| Innodb_secondary_index_triggered_cluster_reads | 0 |\n| Innodb_secondary_index_triggered_cluster_reads_avoided | 0\n|\n| Innodb_encryption_rotation_pages_read_from_cache | 0 |\n| Innodb_encryption_rotation_pages_read_from_disk | 0 |\n| Innodb_encryption_rotation_pages_modified | 0 |\n| Innodb_encryption_rotation_pages_flushed | 0 |\n| Innodb_encryption_rotation_estimated_iops | 0 |\n| Innodb_scrub_background_page_reorganizations | 0 |\n| Innodb_scrub_background_page_splits | 0 |\n| Innodb_scrub_background_page_split_failures_underflow | 0\n|\n|\nInnodb_scrub_background_page_split_failures_out_of_filespace\n| 0 |\n| Innodb_scrub_background_page_split_failures_missing_index\n| 0 |\n| Innodb_scrub_background_page_split_failures_unknown | 0 |\n| Key_blocks_not_flushed | 0 |\n| Key_blocks_unused | 107163 |\n| Key_blocks_used | 0 |\n| Key_blocks_warm | 0 |\n| Key_read_requests | 0 |\n| Key_reads | 0 |\n| Key_write_requests | 0 |\n| Key_writes | 0 |\n| Last_query_cost | 0.000000 |\n| Master_gtid_wait_count | 0 |\n| Master_gtid_wait_time | 0 |\n| Master_gtid_wait_timeouts | 0 |\n| Max_statement_time_exceeded | 0 |\n| Max_used_connections | 1 |\n| Memory_used | 273614696 |\n| Not_flushed_delayed_rows | 0 |\n| Open_files | 25 |\n| Open_streams | 0 |\n| Open_table_definitions | 18 |\n| Open_tables | 11 |\n| Opened_files | 77 |\n| Opened_plugin_libraries | 0 |\n| Opened_table_definitions | 18 |\n| Opened_tables | 18 |\n| Opened_views | 0 |\n| Performance_schema_accounts_lost | 0 |\n| Performance_schema_cond_classes_lost | 0 |\n| Performance_schema_cond_instances_lost | 0 |\n| Performance_schema_digest_lost | 0 |\n| Performance_schema_file_classes_lost | 0 |\n| Performance_schema_file_handles_lost | 0 |\n| Performance_schema_file_instances_lost | 0 |\n| Performance_schema_hosts_lost | 0 |\n| Performance_schema_locker_lost | 0 |\n| Performance_schema_mutex_classes_lost | 0 |\n| Performance_schema_mutex_instances_lost | 0 |\n| Performance_schema_rwlock_classes_lost | 0 |\n| Performance_schema_rwlock_instances_lost | 0 |\n| Performance_schema_session_connect_attrs_lost | 0 |\n| Performance_schema_socket_classes_lost | 0 |\n| Performance_schema_socket_instances_lost | 0 |\n| Performance_schema_stage_classes_lost | 0 |\n| Performance_schema_statement_classes_lost | 0 |\n| Performance_schema_table_handles_lost | 0 |\n| Performance_schema_table_instances_lost | 0 |\n| Performance_schema_thread_classes_lost | 0 |\n| Performance_schema_thread_instances_lost | 0 |\n| Performance_schema_users_lost | 0 |\n| Prepared_stmt_count | 0 |\n| Qcache_free_blocks | 1 |\n| Qcache_free_memory | 1031336 |\n| Qcache_hits | 0 |\n| Qcache_inserts | 0 |\n| Qcache_lowmem_prunes | 0 |\n| Qcache_not_cached | 0 |\n| Qcache_queries_in_cache | 0 |\n| Qcache_total_blocks | 1 |\n| Queries | 4 |\n| Questions | 4 |\n| Rows_read | 10 |\n| Rows_sent | 517 |\n| Rows_tmp_read | 516 |\n| Rpl_status | AUTH_MASTER |\n| Select_full_join | 0 |\n| Select_full_range_join | 0 |\n| Select_range | 0 |\n| Select_range_check | 0 |\n| Select_scan | 2 |\n| Slave_connections | 0 |\n| Slave_heartbeat_period | 0.000 |\n| Slave_open_temp_tables | 0 |\n| Slave_received_heartbeats | 0 |\n| Slave_retried_transactions | 0 |\n| Slave_running | OFF |\n| Slave_skipped_errors | 0 |\n| Slaves_connected | 0 |\n| Slaves_running | 0 |\n| Slow_launch_threads | 0 |\n| Slow_queries | 0 |\n| Sort_merge_passes | 0 |\n| Sort_priority_queue_sorts | 0 |\n| Sort_range | 0 |\n| Sort_rows | 0 |\n| Sort_scan | 0 |\n| Ssl_accept_renegotiates | 0 |\n| Ssl_accepts | 0 |\n| Ssl_callback_cache_hits | 0 |\n| Ssl_cipher | |\n| Ssl_cipher_list | |\n| Ssl_client_connects | 0 |\n| Ssl_connect_renegotiates | 0 |\n| Ssl_ctx_verify_depth | 0 |\n| Ssl_ctx_verify_mode | 0 |\n| Ssl_default_timeout | 0 |\n| Ssl_finished_accepts | 0 |\n| Ssl_finished_connects | 0 |\n| Ssl_server_not_after | |\n| Ssl_server_not_before | |\n| Ssl_session_cache_hits | 0 |\n| Ssl_session_cache_misses | 0 |\n| Ssl_session_cache_mode | NONE |\n| Ssl_session_cache_overflows | 0 |\n| Ssl_session_cache_size | 0 |\n| Ssl_session_cache_timeouts | 0 |\n| Ssl_sessions_reused | 0 |\n| Ssl_used_session_cache_entries | 0 |\n| Ssl_verify_depth | 0 |\n| Ssl_verify_mode | 0 |\n| Ssl_version | |\n| Subquery_cache_hit | 0 |\n| Subquery_cache_miss | 0 |\n| Syncs | 2 |\n| Table_locks_immediate | 21 |\n| Table_locks_waited | 0 |\n| Tc_log_max_pages_used | 0 |\n| Tc_log_page_size | 4096 |\n| Tc_log_page_waits | 0 |\n| Threadpool_idle_threads | 0 |\n| Threadpool_threads | 0 |\n| Threads_cached | 0 |\n| Threads_connected | 1 |\n| Threads_created | 2 |\n| Threads_running | 1 |\n| Update_scan | 0 |\n| Uptime | 223 |\n| Uptime_since_flush_status | 223 |\n| wsrep_cluster_conf_id | 18446744073709551615 |\n| wsrep_cluster_size | 0 |\n| wsrep_cluster_state_uuid | |\n| wsrep_cluster_status | Disconnected |\n| wsrep_connected | OFF |\n| wsrep_local_bf_aborts | 0 |\n| wsrep_local_index | 18446744073709551615 |\n| wsrep_provider_name | |\n| wsrep_provider_vendor | |\n| wsrep_provider_version | |\n| wsrep_ready | OFF |\n| wsrep_thread_count | 0 |\n+--------------------------------------------------------------+----------------------------------------+\n516 rows in set (0.00 sec)\n \nExample of filtered output:\n \nSHOW STATUS LIKE \'Key%\';\n \n+------------------------+--------+\n| Variable_name | Value |\n+------------------------+--------+\n| Key_blocks_not_flushed | 0 |\n| Key_blocks_unused | 107163 |\n| Key_blocks_used | 0 |\n| Key_blocks_warm | 0 |\n| Key_read_requests | 0 |\n| Key_reads | 0 |\n| Key_write_requests | 0 |\n| Key_writes | 0 |\n+------------------------+--------+\n8 rows in set (0.00 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-status/','','https://mariadb.com/kb/en/library/show-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (397,26,'SHOW TABLE STATUS','Syntax\n------ \nSHOW TABLE STATUS [{FROM | IN} db_name]\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \n SHOW TABLE STATUS works like \n SHOW TABLES, but provides more extensive information about\neach non-TEMPORARY table.\n \nThe LIKE clause, if present on its own, indicates which\ntable names to\nmatch. The WHERE and LIKE clauses can be given to select\nrows using more general conditions, as discussed in Extended\nSHOW.\n \nThe following information is returned:\n \nColumn | Description | \n \nName | Table name. | \n \nEngine | Table storage engine. | \n \nVersion | Version number from the table\'s .frm file. | \n \nRow_format | Row format (see InnoDB, Aria and MyISAM row\nformats). | \n \nRows | Number of rows in the table. Some engines, such as\nXtraDB and InnoDB may store an estimate. | \n \nAvg_row_length | Average row length in the table. | \n \nData_length | For InnoDB/XtraDB, the index size, in pages,\nmultiplied by the page size. For Aria and MyISAM, length of\nthe data file, in bytes. For MEMORY, the approximate\nallocated memory. | \n \nMax_data_length | Maximum length of the data file, ie the\ntotal number of bytes that could be stored in the table. Not\nused in XtraDB and InnoDB. | \n \nIndex_length | Length of the index file. | \n \nData_free | Bytes allocated but unused. For InnoDB tables in\na shared tablespace, the free space of the shared tablespace\nwith small safety margin. An estimate in the case of\npartitioned tables - see the PARTITIONS table. | \n \nAuto_increment | Next AUTO_INCREMENT value. | \n \nCreate_time | Time the table was created. | \n \nUpdate_time | Time the table was last updated. On Windows,\nthe timestamp is not updated on update, so MyISAM values\nwill be inaccurate. In InnoDB, if shared tablespaces are\nused, will be NULL, while buffering can also delay the\nupdate, so the value will differ from the actual time of the\nlast UPDATE, INSERT or DELETE. | \n \nCheck_time | Time the table was last checked. Not kept by\nall storage engines, in which case will be NULL. | \n \nCollation | Character set and collation. | \n \nChecksum | Live checksum value, if any. | \n \nCreate_options | Extra CREATE TABLE options. | \n \nComment | Table comment provided when MariaDB created the\ntable. | \n \nSimilar information can be found in the\ninformation_schema.TABLES table as well as by using\nmysqlshow:\n \nmysqlshow --status db_name\n \nExample\n \nshow table status\\G\n*************************** 1. row\n***************************\n Name: bus_routes\n Engine: InnoDB\n Version: 10\n Row_format: Dynamic\n Rows: 5\n Avg_row_length: 3276\n Data_length: 16384\nMax_data_length: 0\n Index_length: 0\n Data_free: 0\n Auto_increment: NULL\n Create_time: 2017-05-24 11:17:46\n Update_time: NULL\n Check_time: NULL\n Collation: latin1_swedish_ci\n Checksum: NULL\n Create_options: \n Comment:\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-table-status/','','https://mariadb.com/kb/en/library/show-table-status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (398,26,'SHOW TABLES','Syntax\n------ \nSHOW [FULL] TABLES [FROM db_name]\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nSHOW TABLES lists the non-TEMPORARY tables, sequences and\nviews in a given database. \n \nThe LIKE clause, if present on its own, indicates which\ntable names to match. The WHERE and LIKE clauses can be\ngiven to select rows using more general conditions, as\ndiscussed in Extended SHOW. For example, when searching for\ntables in the test database, the column name for use in the\nWHERE and LIKE clauses will be Tables_in_test\n \nThe FULL modifier is supported such that SHOW FULL TABLES\ndisplays a second output column. Values for the second\ncolumn. Table_type, are BASE TABLE for a table, VIEW for a\nview and SEQUENCE for a sequence.\n \nYou can also get this information using:\n \nmysqlshow db_name\n \nSee mysqlshow for more details.\n \nIf you have no privileges for a base table or view, it does\nnot show up in the output from SHOW TABLES or mysqlshow\ndb_name.\n \nThe information_schema.TABLES table, as well as the SHOW\nTABLE STATUS statement, provide extended information about\ntables.\n \nExamples\n-------- \nSHOW TABLES;\n+----------------------+\n| Tables_in_test |\n+----------------------+\n| animal_count |\n| animals |\n| are_the_mooses_loose |\n| aria_test2 |\n| t1 |\n| view1 |\n+----------------------+\n \nShowing the tables beginning with a only.\n \nSHOW TABLES WHERE Tables_in_test LIKE \'a%\';\n+----------------------+\n| Tables_in_test |\n+----------------------+\n| animal_count |\n| animals |\n| are_the_mooses_loose |\n| aria_test2 |\n+----------------------+\n \nShowing tables and table types:\n \nSHOW FULL TABLES;\n+----------------+------------+\n| Tables_in_test | Table_type |\n+----------------+------------+\n| s1 | SEQUENCE |\n| student | BASE TABLE |\n| v1 | VIEW |\n+----------------+------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/show-tables/','','https://mariadb.com/kb/en/library/show-tables/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (399,26,'SHOW TABLE_STATISTICS','MariaDB 5.2 introduced the User Statistics feature.\n \nSyntax\n------ \nSHOW TABLE_STATISTICS\n \nDescription\n----------- \nThe SHOW TABLE_STATISTICS statement was introduced in\nMariaDB 5.2 as part of the User Statistics feature. It was\nremoved as a separate statement in MariaDB 10.1.1, but\neffectively replaced by the generic SHOW\ninformation_schema_table statement. The\ninformation_schema.TABLE_STATISTICS table shows statistics\non table usage\n \nThe userstat system variable must be set to 1 to activate\nthis feature. See the User Statistics and\ninformation_schema.TABLE_STATISTICS articles for more\ninformation.\n \nExample\n \nFrom MariaDB 10.0\n \nSHOW TABLE_STATISTICS\\G\n*************************** 1. row\n***************************\n Table_schema: mysql\n Table_name: proxies_priv\n Rows_read: 2\n Rows_changed: 0\nRows_changed_x_#indexes: 0\n*************************** 2. row\n***************************\n Table_schema: test\n Table_name: employees_example\n Rows_read: 7\n Rows_changed: 0\nRows_changed_x_#indexes: 0\n*************************** 3. row\n***************************\n Table_schema: mysql\n Table_name: user\n Rows_read: 16\n Rows_changed: 0\nRows_changed_x_#indexes: 0\n*************************** 4. row\n***************************\n Table_schema: mysql\n Table_name: db\n Rows_read: 2\n Rows_changed: 0\nRows_changed_x_#indexes: 0\n \n\n \n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/show-table-statistics/','','https://mariadb.com/kb/en/library/show-table-statistics/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (400,26,'SHOW TRIGGERS','Syntax\n------ \nSHOW TRIGGERS [FROM db_name]\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \n SHOW TRIGGERS lists the triggers currently defined for\ntables in a database (the default database unless a FROM\nclause is given). This statement requires the\nTRIGGER privilege (prior to MySQL\n5.1.22, it required the SUPER privilege). \n \nThe LIKE clause, if present on its own, indicates which\ntable names to\nmatch and causes the statement to display triggers for those\ntables. The WHERE and LIKE clauses can be given to select\nrows using more general conditions, as discussed in Extended\nSHOW.\n \nSimilar information is stored in the\ninformation_schema.TRIGGERS table.\n \nIf there are multiple triggers for the same action, then the\ntriggers are shown in action order.\n \nExamples\n-------- \nFor the trigger defined at Trigger Overview:\n \nSHOW triggers Like \'animals\' \\G\n*************************** 1. row\n***************************\n Trigger: the_mooses_are_loose\n Event: INSERT\n Table: animals\n Statement: BEGIN\n IF NEW.name = \'Moose\' THEN\n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+100;\n ELSE \n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+1;\n END IF;\nEND\n Timing: AFTER\n Created: 2016-09-29 13:53:34.35\n sql_mode: \n Definer: root@localhost\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \nListing all triggers associated with a certain table:\n \nSHOW TRIGGERS FROM test WHERE `Table` = \'user\' \\G\n*************************** 1. row\n***************************\n Trigger: user_ai\n Event: INSERT\n Table: user\n Statement: BEGIN END\n Timing: AFTER\n Created: 2016-09-29 13:53:34.35\n sql_mode: \n Definer: root@%\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\n \nSHOW triggers WHERE Event Like \'Insert\' \\G\n*************************** 1. row\n***************************\n Trigger: the_mooses_are_loose\n Event: INSERT\n Table: animals\n Statement: BEGIN\n IF NEW.name = \'Moose\' THEN\n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+100;\n ELSE \n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+1;\n END IF;\nEND\n Timing: AFTER\n Created: 2016-09-29 13:53:34.35\n sql_mode: \n Definer: root@localhost\ncharacter_set_client: utf8\ncollation_connection: utf8_general_ci\n Database Collation: latin1_swedish_ci\ncharacter_set_client is the session value of the\ncharacter_set_client system variable when the trigger was\ncreated. \ncollation_connection is the session value of the\ncollation_connection system variable when the trigger was\n created. \nDatabase Collation is the collation of the database \n with which the trigger is associated.\n \nThese columns were added in MariaDB/MySQL 5.1.21.\n \nOld triggers created before MySQL 5.7 and MariaDB 10.2.3 has\nNULL in the Created column.\n \n\n\nURL: https://mariadb.com/kb/en/library/show-triggers/','','https://mariadb.com/kb/en/library/show-triggers/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (401,26,'SHOW USER_STATISTICS','MariaDB 5.2 introduced the User Statistics feature.\n \nSyntax\n------ \nSHOW USER_STATISTICS\n \nDescription\n----------- \nThe SHOW USER_STATISTICS statement was introduced in MariaDB\n5.2 as part of the User Statistics feature. It was removed\nas a separate statement in MariaDB 10.1.1, but effectively\nreplaced by the generic SHOW information_schema_table\nstatement. The information_schema.USER_STATISTICS table\nholds statistics about user activity. You can use this table\nto find out such things as which user is causing the most\nload and which users are being abusive. You can also use\nthis table to measure how close to capacity the server may\nbe.\n \nThe userstat system variable must be set to 1 to activate\nthis feature. See the User Statistics and\ninformation_schema.USER_STATISTICS table for more\ninformation.\n \nExample\n \nFrom MariaDB 10.0:\n \nSHOW USER_STATISTICS\\G\n*************************** 1. row\n***************************\n User: root\n Total_connections: 1\nConcurrent_connections: 0\n Connected_time: 3297\n Busy_time: 0.14113400000000006\n Cpu_time: 0.017637000000000003\n Bytes_received: 969\n Bytes_sent: 22355\n Binlog_bytes_written: 0\n Rows_read: 10\n Rows_sent: 67\n Rows_deleted: 0\n Rows_inserted: 0\n Rows_updated: 0\n Select_commands: 7\n Update_commands: 0\n Other_commands: 0\n Commit_transactions: 1\n Rollback_transactions: 0\n Denied_connections: 0\n Lost_connections: 0\n Access_denied: 0\n Empty_queries: 7\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-user-statistics/','','https://mariadb.com/kb/en/library/show-user-statistics/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (402,26,'SHOW VARIABLES','Syntax\n------ \nSHOW [GLOBAL | SESSION] VARIABLES\n [LIKE \'pattern\' | WHERE expr]\n \nDescription\n----------- \nSHOW VARIABLES shows the values of MariaDB system variables.\nThis\ninformation also can be obtained using the mysqladmin\nvariables\ncommand. The LIKE clause, if present, indicates which\nvariable names\nto match. The WHERE clause can be given to select rows using\nmore\ngeneral conditions.\n \nWith the GLOBAL modifier, SHOW VARIABLES displays the values\nthat are\nused for new connections to MariaDB. With SESSION, it\ndisplays the\nvalues that are in effect for the current connection. If no\nmodifier\nis present, the default is SESSION. LOCAL is a synonym for\nSESSION.\nWith a LIKE clause, the statement displays only rows for\nthose\nvariables with names that match the pattern. To obtain the\nrow for a\nspecific variable, use a LIKE clause as shown:\n \nSHOW VARIABLES LIKE \'maria_group_commit\';\n \nSHOW SESSION VARIABLES LIKE \'maria_group_commit\';\n \nTo get a list of variables whose name match a pattern, use\nthe \"%\"\nwildcard character in a LIKE clause:\n \nSHOW VARIABLES LIKE \'%maria%\';\n \nSHOW GLOBAL VARIABLES LIKE \'%maria%\';\n \nWildcard characters can be used in any position within the\npattern to\nbe matched. Strictly speaking, because \"_\" is a wildcard\nthat matches\nany single character, you should escape it as \"\\_\" to\nmatch it\nliterally. In practice, this is rarely necessary.\n \nThe WHERE and LIKE clauses can be given to select rows using\nmore general conditions, as discussed in Extended SHOW.\n \nSee SET for information on setting server system variables.\n \nSee Server System Variables for a list of all the variables\nthat can be set.\n \nYou can also see the server variables by querying the\nInformation Schema GLOBAL_VARIABLES and SESSION_VARIABLES\ntables.\n \nExamples\n-------- \nSHOW VARIABLES LIKE \'aria%\';\n \n+------------------------------------------+---------------------+\n| Variable_name | Value |\n+------------------------------------------+---------------------+\n| aria_block_size | 8192 |\n| aria_checkpoint_interval | 30 |\n| aria_checkpoint_log_activity | 1048576 |\n| aria_force_start_after_recovery_failures | 0 |\n| aria_group_commit | none |\n| aria_group_commit_interval | 0 |\n| aria_log_file_size | 1073741824 |\n| aria_log_purge_type | immediate |\n| aria_max_sort_file_size | 9223372036853727232 |\n| aria_page_checksum | ON |\n| aria_pagecache_age_threshold | 300 |\n| aria_pagecache_buffer_size | 134217728 |\n| aria_pagecache_division_limit | 100 |\n| aria_recover | NORMAL |\n| aria_repair_threads | 1 |\n| aria_sort_buffer_size | 134217728 |\n| aria_stats_method | nulls_unequal |\n| aria_sync_log_dir | NEWFILE |\n| aria_used_for_temp_tables | ON |\n+------------------------------------------+---------------------+\n \nSELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM\n INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE\n VARIABLE_NAME LIKE \'max_error_count\' OR\n VARIABLE_NAME LIKE \'innodb_sync_spin_loops\';\n \n+---------------------------+---------------+--------------+\n| VARIABLE_NAME | SESSION_VALUE | GLOBAL_VALUE |\n+---------------------------+---------------+--------------+\n| MAX_ERROR_COUNT | 64 | 64 |\n| INNODB_SYNC_SPIN_LOOPS | NULL | 30 |\n+---------------------------+---------------+--------------+\n \nSET GLOBAL max_error_count=128;\n \nSELECT VARIABLE_NAME, SESSION_VALUE, GLOBAL_VALUE FROM\n INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE\n VARIABLE_NAME LIKE \'max_error_count\' OR\n VARIABLE_NAME LIKE \'innodb_sync_spin_loops\';\n \n+---------------------------+---------------+--------------+\n| VARIABLE_NAME | SESSION_VALUE | GLOBAL_VALUE |\n+---------------------------+---------------+--------------+\n| MAX_ERROR_COUNT | 64 | 128 |\n| INNODB_SYNC_SPIN_LOOPS | NULL | 30 |\n+---------------------------+---------------+--------------+\n \nSET GLOBAL max_error_count=128;\n \nSHOW VARIABLES LIKE \'max_error_count\';\n \n+-----------------+-------+\n| Variable_name | Value |\n+-----------------+-------+\n| max_error_count | 64 |\n+-----------------+-------+\n \nSHOW GLOBAL VARIABLES LIKE \'max_error_count\';\n \n+-----------------+-------+\n| Variable_name | Value |\n+-----------------+-------+\n| max_error_count | 128 |\n+-----------------+-------+\n \nBecause the following variable only has a global scope, the\nglobal value is returned even when specifying SESSION (in\nthis case by default):\n \nSHOW VARIABLES LIKE \'innodb_sync_spin_loops\';\n \n+------------------------+-------+\n| Variable_name | Value |\n+------------------------+-------+\n| innodb_sync_spin_loops | 30 |\n+------------------------+-------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-variables/','','https://mariadb.com/kb/en/library/show-variables/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (403,26,'SHOW WARNINGS','Syntax\n------ \nSHOW WARNINGS [LIMIT [offset,] row_count]\nSHOW ERRORS [LIMIT row_count OFFSET offset]\nSHOW COUNT(*) WARNINGS\n \nDescription\n----------- \n SHOW WARNINGS shows the error, warning, and note messages\nthat resulted from the last statement that generated\nmessages in the\ncurrent session. It shows nothing if the last statement used\na table\nand generated no messages. (That is, a statement that uses a\ntable but\ngenerates no messages clears the message list.) Statements\nthat do not\nuse tables and do not generate messages have no effect on\nthe message\nlist.\n \nA note is different to a warning in that it only appears if\nthe sql_notes variable is set to 1 (the default), and is not\nconverted to an error if strict mode is enabled.\n \nA related statement, SHOW ERRORS, shows only the errors.\n \nThe SHOW COUNT(*) WARNINGS statement displays the total\nnumber of errors, warnings, and notes. You can also retrieve\nthis number from\nthe warning_count variable:\n \nSHOW COUNT(*) WARNINGS;\nSELECT @@warning_count;\n \nThe value of warning_count might be greater than the number\nof messages displayed by SHOW WARNINGS if the\nmax_error_count system variable is set so low that not all\nmessages are stored.\n \nThe LIMIT clause has the same syntax as for the\n SELECT statement.\n \nSHOW WARNINGS can be used after EXPLAIN EXTENDED to see how\na query is internally rewritten by MariaDB.\n \nIf the sql_notes server variable is set to 1, Notes are\nincluded in the output of SHOW WARNINGS; if it is set to 0,\nthis statement will not show (or count) Notes.\n \nThe results of SHOW WARNINGS and SHOW COUNT(*) WARNINGS are\ndirectly sent to the client. If you need to access those\ninformation in a stored program, you can use the GET\nDIAGNOSTICS statement instead.\n \nFor a list of MariaDB error codes, see MariaDB Error Codes.\n \nThe mysql client also has a number of options related to\nwarnings. The \\W command will show warnings after every\nstatement, while \\w will disable this. Starting the client\nwith the --show-warnings option will show warnings after\nevery statement.\n \nMariaDB 10.3.1 implements a stored routine error stack\ntrace. SHOW WARNINGS can also be used to show more\ninformation. See the example below.\n \nExamples\n-------- \nSELECT 1/0;\n+------+\n| 1/0 |\n+------+\n| NULL |\n+------+\n \nSHOW COUNT(*) WARNINGS;\n+-------------------------+\n| @@session.warning_count |\n+-------------------------+\n| 1 |\n+-------------------------+\n \nSHOW WARNINGS;\n+---------+------+---------------+\n| Level | Code | Message |\n+---------+------+---------------+\n| Warning | 1365 | Division by 0 |\n+---------+------+---------------+\n \nStack Trace\n \nFrom MariaDB 10.3.1, displaying a stack trace:\n \nDELIMITER $$\nCREATE OR REPLACE PROCEDURE p1()\n BEGIN\n DECLARE c CURSOR FOR SELECT * FROM not_existing;\n OPEN c;\n CLOSE c;\n END;\n$$\nCREATE OR REPLACE PROCEDURE p2()\n BEGIN\n CALL p1;\n END;\n$$\nDELIMITER ;\nCALL p2;\nERROR 1146 (42S02): Table \'test.not_existing\' doesn\'t\nexist\n \nSHOW WARNINGS;\n+-------+------+-----------------------------------------+\n| Level | Code | Message |\n+-------+------+-----------------------------------------+\n| Error | 1146 | Table \'test.not_existing\' doesn\'t exist\n|\n| Note | 4091 | At line 6 in test.p1 |\n| Note | 4091 | At line 4 in test.p2 |\n+-------+------+-----------------------------------------+\n \nSHOW WARNINGS displays a stack trace, showing where the\nerror actually happened:\nLine 4 in test.p1 is the OPEN command which actually raised\nthe error\nLine 3 in test.p2 is the CALL statement, calling p1 from p2.\n \n\n\nURL: https://mariadb.com/kb/en/library/show-warnings/','','https://mariadb.com/kb/en/library/show-warnings/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (404,26,'SHOW WSREP_MEMBERSHIP','MariaDB 10.1.2\n \nSHOW WSREP_MEMBERSHIP was introduced with the WSREP_INFO\nplugin in MariaDB 10.1.2.\n \nSyntax\n------ \nSHOW WSREP_MEMBERSHIP\n \nDescription\n----------- \nThe SHOW WSREP_MEMBERSHIP statement returns Galera node\ncluster membership information. It returns the same\ninformation as found in the\ninformation_schema.WSREP_MEMBERSHIP table. Only users with\nthe SUPER privilege can access this information.\n \nExamples\n-------- \nSHOW WSREP_MEMBERSHIP;\n+-------+--------------------------------------+----------+-----------------+\n| Index | Uuid | Name | Address |\n+-------+--------------------------------------+----------+-----------------+\n| 0 | 19058073-8940-11e4-8570-16af7bf8fced | my_node1 |\n10.0.2.15:16001 |\n| 1 | 19f2b0e0-8942-11e4-9cb8-b39e8ee0b5dd | my_node3 |\n10.0.2.15:16003 |\n| 2 | d85e62db-8941-11e4-b1ef-4bc9980e476d | my_node2 |\n10.0.2.15:16002 |\n+-------+--------------------------------------+----------+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/show-wsrep_membership/','','https://mariadb.com/kb/en/library/show-wsrep_membership/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (405,26,'SHOW WSREP_STATUS','MariaDB 10.1.2\n \nSHOW WSREP_STATUS was introduced with the WSREP_INFO plugin\nin MariaDB 10.1.2.\n \nSyntax\n------ \nSHOW WSREP_STATUS\n \nDescription\n----------- \nThe SHOW WSREP_STATUS statement returns Galera node and\ncluster status information. It returns the same information\nas found in the information_schema.WSREP_STATUS table. Only\nusers with the SUPER privilege can access this information.\n \nExamples\n-------- \nSHOW WSREP_STATUS;\n+------------+-------------+----------------+--------------+\n| Node_Index | Node_Status | Cluster_Status | Cluster_Size |\n+------------+-------------+----------------+--------------+\n| 0 | Synced | Primary | 3 |\n+------------+-------------+----------------+--------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/show-wsrep_status/','','https://mariadb.com/kb/en/library/show-wsrep_status/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (406,27,'CALL','Syntax\n------ \nCALL sp_name([parameter[,...]])\nCALL sp_name[()]\n \nDescription\n----------- \nThe CALL statement invokes a stored procedure that was\ndefined previously with CREATE PROCEDURE. \n \nStored procedure names can be specified as\ndatabase_name.procedure_name. Procedure names and database\nnames can be quoted with backticks (). This is necessary if\nthey are reserved words, or contain special characters. See\nidentifier qualifiers for details.\n \nBefore MySQL 5.1.13, stored procedures that take no\narguments required parentheses. In current releases of\nMariaDB, CALL p() and CALL p are equivalent.\n \nIf parentheses are used, any number of spaces, tab\ncharacters and new line characters is allowed between the\nprocedure\'s name and the open parenthesis.\n \nCALL can pass back values to its caller using parameters\nthat are declared as OUT or INOUT\nparameters. If no value is assigned to an OUT parameter,\nNULL is assigned (and its former value is lost). To pass\nsuch values from another stored program you can use\nuser-defined variables, local variables or routine\'s\nparameters; in other contexts, you can only use user-defined\nvariables. \n \nCALL can also be executed as a prepared statement.\nPlaceholders can be used for IN parameters in all versions\nof MariaDB; for OUT and INOUT parameters, placeholders can\nbe used since MariaDB 5.5.\n \nWhen the procedure returns, a client program can also obtain\nthe\nnumber of rows affected for the final statement executed\nwithin the routine: At\nthe SQL level, call the ROW_COUNT() function; from the C\nAPI, call the mysql_affected_rows() function.\n \nIf the CLIENT_MULTI_RESULTS API flag is set, CALL can return\nany number of resultsets and the called stored procedure can\nexecute prepared statements. If it is not set, at most one\nresultset can be returned and prepared statements cannot be\nused within procedures.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/call/','','https://mariadb.com/kb/en/library/call/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (407,27,'Concurrent Inserts','The MyISAM storage engine supports concurrent inserts. This\nfeature allows SELECT statements to be executed during\nINSERT operations, reducing contention.\n \nWhether concurrent inserts can be used or not depends on the\nvalue of the concurrent_insert server system variable:\nNEVER (0) disables concurrent inserts.\nAUTO (1) allows concurrent inserts only when the target\ntable has no free blocks (no data in the middle of the table\nhas been deleted after the last OPTIMIZE TABLE). This is the\ndefault.\nALWAYS (2) always enables concurrent inserts.\n \nIf the binary log is used, CREATE TABLE ... SELECT and\nINSERT ... SELECT statements cannot use concurrent inserts.\nThese statements acquire a read lock on the table, so\nconcurrent inserts will need to wait. This way the log can\nbe safely used to restore data.\n \nConcurrent inserts is not used by slaves with the row based\nreplication (see binary log formats).\n \nIf an INSERT statement contain the HIGH_PRIORITY clause,\nconcurrent inserts cannot be used. INSERT ... DELAYED is\nusually unneeded if concurrent inserts are enabled.\n \nLOAD DATA INFILE uses concurrent inserts if the CONCURRENT\nkeyword is specified and concurrent_insert is not NEVER.\nThis makes the statement slower (even if no other sessions\naccess the table) but reduces contention.\n \nLOCK TABLES allows non-conflicting concurrent inserts if a\nREAD LOCAL lock is used. Concurrent inserts are not allowed\nif the LOCAL keyword is omitted.\n \nNotes\n \nThe decision to enable concurrent insert for a table is done\nwhen the table is opened. If you change the value of\nconcurrent_insert it will only affect new opened tables. If\nyou want it to work for also for tables in use or cached,\nyou should do FLUSH TABLES after setting the variable.\n \n\n\nURL: https://mariadb.com/kb/en/library/concurrent-inserts/','','https://mariadb.com/kb/en/library/concurrent-inserts/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (408,27,'DELETE','Syntax\n------ \nSingle-table syntax:\n \nDELETE [LOW_PRIORITY] [QUICK] [IGNORE] \n FROM tbl_name [PARTITION (partition_list)]\n [WHERE where_condition]\n [ORDER BY ...]\n [LIMIT row_count]\n [RETURNING select_expr \n [, select_expr ...]]\n \nMultiple-table syntax:\n \nDELETE [LOW_PRIORITY] [QUICK] [IGNORE]\n tbl_name[.*] [, tbl_name[.*]] ...\n FROM table_references\n [WHERE where_condition]\n \nOr:\n \nDELETE [LOW_PRIORITY] [QUICK] [IGNORE]\n FROM tbl_name[.*] [, tbl_name[.*]] ...\n USING table_references\n [WHERE where_condition]\n \nTrimming history:\n \nDELETE HISTORY\n FROM tbl_name [PARTITION (partition_list)]\n [BEFORE SYSTEM_TIME [TIMESTAMP|TRANSACTION] expression]\n \nDescription\n----------- \nOption | Description | \n \nLOW_PRIORITY | Wait until all SELECT\'s are done before\nstarting the statement. Used with storage engines that uses\ntable locking (MyISAM, Aria etc). See HIGH_PRIORITY and\nLOW_PRIORITY clauses for details. | \n \nQUICK | Signal the storage engine that it should expect that\na lot of rows are deleted. The storage engine engine can do\nthings to speed up the DELETE like ignoring merging of data\nblocks until all rows are deleted from the block (instead of\nwhen a block is half full). This speeds up things at the\nexpanse of lost space in data blocks. At least MyISAM and\nAria support this feature. | \n \nIGNORE | Don\'t stop the query even if a not-critical error\noccurs (like data overflow). See How IGNORE works for a full\ndescription. | \n \nFor the single-table syntax, the DELETE statement deletes\nrows\nfrom tbl_name and returns a count of the number of deleted\nrows. This count can\nbe obtained by calling the ROW_COUNT() function. The\nWHERE clause, if given, specifies the conditions that\nidentify\nwhich rows to delete. With no WHERE clause, all rows are\ndeleted. If the ORDER BY clause is specified, the rows are\ndeleted in the order that is specified. The LIMIT clause\nplaces a limit on the number of rows that can be deleted.\n \nFor the multiple-table syntax, DELETE deletes from each\ntbl_name the rows that satisfy the conditions. In this case,\nORDER BY and LIMIT> cannot be used. A DELETE can also\nreference tables which are located in different databases;\nsee Identifier Qualifiers for the syntax.\n \nwhere_condition is an expression that evaluates to true for\neach row to be deleted. It is specified as described in\nSELECT.\n \nCurrently, you cannot delete from a table and select from\nthe same\ntable in a subquery.\n \nYou need the DELETE privilege on a table to delete rows from\nit. You need only the SELECT privilege for any columns that\nare only read, such as those named in the WHERE clause. See\nGRANT.\n \nThe PARTITION clause was introduced in MariaDB 10.0. See\nPartition Pruning and Selection for details.\n \nAs stated, a DELETE statement with no WHERE\nclause deletes all rows. A faster way to do this, when you\ndo not need to know\nthe number of deleted rows, is to use TRUNCATE TABLE.\nHowever,\nwithin a transaction or if you have a lock on the table, \nTRUNCATE TABLE cannot be used whereas DELETE\ncan. See TRUNCATE TABLE, and\nLOCK.\n \nFrom MariaDB 10.0.5, it is possible to return a resultset of\nthe deleted rows for a single table to the client by using\nthe syntax DELETE ... RETURNING select_expr [, select_expr2\n...]]\n \nAny of SQL expression that can be calculated from a single\nrow fields is allowed. Subqueries are allowed. The AS\nkeyword is allowed, so it is possible to use aliases.\n \nThe use of aggregate functions is not allowed. RETURNING\ncannot be used in multi-table DELETEs.\n \nSame Source and Target Table\n \nUntil MariaDB 10.3.1, deleting from a table with the same\nsource and target was not possible. From MariaDB 10.3.1,\nthis is now possible. For example:\n \nDELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE\nb.c2=0);\n \nOne can use DELETE HISTORY to delete historical information\nfrom System-versioned tables.\n \nExamples\n-------- \nHow to use the ORDER BY and LIMIT clauses:\n \nDELETE FROM page_hit ORDER BY timestamp LIMIT 1000000;\n \nHow to use the RETURNING clause:\n \nDELETE FROM t RETURNING f1;\n \n+------+\n| f1 |\n+------+\n| 5 |\n| 50 |\n| 500 |\n+------+ \n \nThe following statement joins two tables: one is only used\nto satisfy a WHERE condition, but no row is deleted from it;\nrows from the other table are deleted, instead.\n \nDELETE post FROM blog INNER JOIN post WHERE blog.id =\npost.blog_id;\n \nDeleting from the Same Source and Target\n \nCREATE TABLE t1 (c1 INT, c2 INT);\nDELETE FROM t1 WHERE c1 IN (SELECT b.c1 FROM t1 b WHERE\nb.c2=0);\n \nUntil MariaDB 10.3.1, this returned:\n \nERROR 1093 (HY000): Table \'t1\' is specified twice, both as\na target for \'DELETE\' \n and as a separate source for\n \nFrom MariaDB 10.3.1:\n \nQuery OK, 0 rows affected (0.00 sec)\n \n\n\nURL: https://mariadb.com/kb/en/library/delete/','','https://mariadb.com/kb/en/library/delete/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (409,27,'DO','Syntax\n------ \nDO expr [, expr] ...\n \nDescription\n----------- \n DO executes the expressions but does not return any\nresults. In most respects, DO is shorthand for\n SELECT expr, ..., but has the advantage that it is slightly\nfaster when you do not care about the result.\n \n DO is useful primarily with functions that have side\n effects, such as RELEASE_LOCK().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/do/','','https://mariadb.com/kb/en/library/do/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (410,27,'DUAL','Description\n----------- \nYou are allowed to specify DUAL as a dummy table name in\nsituations where no tables are referenced, such as the\nfollowing SELECT statement:\n \nSELECT 1 + 1 FROM DUAL;\n \n+-------+\n| 1 + 1 |\n+-------+\n| 2 |\n+-------+\n \n DUAL is purely for the convenience of people who require\n that all SELECT statements should have\n FROM and possibly other clauses. MariaDB ignores the\n clauses. MariaDB does not require FROM DUAL if no tables\n are referenced.\n \nFROM DUAL could be used when you only SELECT computed\nvalues, but require a WHERE clause, perhaps to test that a\nscript correctly handles empty resultsets:\n \nSELECT 1 FROM DUAL WHERE FALSE;\n \nEmpty set (0.00 sec)\n \n\n\nURL: https://mariadb.com/kb/en/library/dual/','','https://mariadb.com/kb/en/library/dual/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (411,27,'EXCEPT','EXCEPT was introduced in MariaDB 10.3.0.\n \nThe result of EXCEPT is all records of the left SELECT\nresult set except records which are in right SELECT result\nset, i.e. it is subtraction of two result sets.\n \nSyntax\n------ \nSELECT ...\n(INTERSECT | EXCEPT | UNION [ALL | DISTINCT]) SELECT ...\n[(INTERSECT | EXCEPT | UNION [ALL | DISTINCT]) SELECT ...]\n[ORDER BY [column [, column ...]]]\n[LIMIT {[offset,] row_count | row_count OFFSET offset}]\n \nPlease note:\nALL is not supported by EXCEPT (and it is difficult to make\nsense of ALL with EXCEPT).\nBrackets for explicit operation precedence are not\nsupported; use a subquery in the FROM clause as a\nworkaround).\n \nDescription\n----------- \nMariaDB has supported EXCEPT and INTERSECT in addition to\nUNION since MariaDB 10.3.\n \nAll behavior for naming columns, ORDER BY and LIMIT is the\nsame as for UNION.\n \nEXCEPT implicitly supposes a DISTINCT operation.\n \nThe result of EXCEPT is all records of the left SELECT\nresult except records which are in right SELECT result set,\ni.e. it is subtraction of two result sets.\n \nEXCEPT and UNION have the same operation precedence.\n \n\nParentheses\n \nFrom MariaDB 10.4.0, parentheses can be used to specify\nprecedence. Before this, a syntax error would be returned.\n \nExamples\n-------- \nShow customers which are not employees:\n \n(SELECT e_name AS name, email FROM customers)\nEXCEPT\n(SELECT c_name AS name, email FROM employees);\n \nDifference between UNION, EXCEPT and INTERSECT:\n \nCREATE TABLE seqs (i INT);\nINSERT INTO seqs VALUES (1),(2),(3),(4),(5),(6);\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n+------+\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 1 |\n| 2 |\n+------+\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 3 |\n+------+\n \nParentheses for specifying precedence, from MariaDB 10.4.0\n \nCREATE OR REPLACE TABLE t1 (a INT);\nCREATE OR REPLACE TABLE t2 (b INT);\nCREATE OR REPLACE TABLE t3 (c INT);\n \nINSERT INTO t1 VALUES (1),(2),(3),(4);\nINSERT INTO t2 VALUES (5),(6);\nINSERT INTO t3 VALUES (1),(6);\n \n((SELECT a FROM t1) UNION (SELECT b FROM t2)) EXCEPT (SELECT\nc FROM t3);\n+------+\n| a |\n+------+\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n+------+\n \n(SELECT a FROM t1) UNION ((SELECT b FROM t2) EXCEPT (SELECT\nc FROM t3));\n+------+\n| a |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/except/','','https://mariadb.com/kb/en/library/except/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (412,27,'FOR UPDATE','The FOR UPDATE clause of SELECT applies only when autocommit\nis set to 0 or the SELECT is enclosed in a transaction. A\nlock is acquired on the rows, and other transactions are\nprevented from writing the rows, acquire locks, and from\nreading them (unless their isolation level is READ\nUNCOMMITTED).\n \nIf autocommit is set to 1, the LOCK IN SHARE MODE and FOR\nUPDATE clauses have no effect.\n \nIf the isolation level is set to SERIALIZABLE, all plain\nSELECT statements are converted to SELECT ... LOCK IN SHARE\nMODE.\n \nExample\n \nSELECT * FROM trans WHERE period=2001 FOR UPDATE;\n \n\n\nURL: https://mariadb.com/kb/en/library/for-update/','','https://mariadb.com/kb/en/library/for-update/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (413,27,'GROUP BY','Use the GROUP BY clause in a SELECT statement to group rows\ntogether that have the same value in one or more column, or\nthe same computed value using expressions with any\nfunctions and operators except\ngrouping functions. When you\nuse a GROUP BY clause, you will get a single result row for\neach group of rows\nthat have the same value for the expression given in GROUP\nBY.\n \nWhen grouping rows, grouping values are compared as if by\nthe = operator.\nFor string values, the = operator ignores trailing\nwhitespace and may normalize\ncharacters and ignore case, depending on the collation in\nuse.\n \nYou can use any of the grouping functions in your select\nexpression. Their values will\nbe calculated based on all the rows that have been grouped\ntogether for each result\nrow. If you select a non-grouped column or a value computed\nfrom a non-grouped\ncolumn, it is undefined which row the returned value is\ntaken from. This is not permitted if the ONLY_FULL_GROUP_BY\nSQL_MODE is used.\n \nYou can use multiple expressions in the GROUP BY clause,\nseparated by commas.\nRows are grouped together if they match on each of the\nexpressions.\n \nYou can also use a single integer as the grouping\nexpression. If you use an integer n,\nthe results will be grouped by the nth column in the select\nexpression.\n \nThe WHERE clause is applied before the GROUP BY clause. It\nfilters non-aggregated\nrows before the rows are grouped together. To filter grouped\nrows based on aggregate values,\nuse the HAVING clause. The HAVING clause takes any\nexpression and evaluates it as\na boolean, just like the WHERE clause. You can use grouping\nfunctions in the HAVING\nclause. As with the select expression, if you reference\nnon-grouped columns in the HAVING\nclause, the behavior is undefined.\n \nBy default, if a GROUP BY clause is present, the rows in the\noutput will be sorted by the expressions used in the GROUP\nBY. You can also specify ASC or DESC (ascending, descending)\nafter those expressions, like in ORDER BY. The default is\nASC.\n \nIf you want the rows to be sorted by another field, you can\nadd an explicit ORDER BY. If you don\'t want the result to\nbe ordered, you can add ORDER BY NULL.\n \nWITH ROLLUP\n \nThe WITH ROLLUP modifer adds extra rows to the resultset\nthat represent super-aggregate summaries. For a full\ndescription with examples, see SELECT WITH ROLLUP.\n \nGROUP BY Examples\n \nConsider the following table that records how many times\neach user has played and won a game:\n \nCREATE TABLE plays (name VARCHAR(16), plays INT, wins INT);\nINSERT INTO plays VALUES \n (\"John\", 20, 5), \n (\"Robert\", 22, 8), \n (\"Wanda\", 32, 8), \n (\"Susan\", 17, 3);\n \nGet a list of win counts along with a count:\n \nSELECT wins, COUNT(*) FROM plays GROUP BY wins;\n \n+------+----------+\n| wins | COUNT(*) |\n+------+----------+\n| 3 | 1 |\n| 5 | 1 |\n| 8 | 2 |\n+------+----------+\n3 rows in set (0.00 sec)\n \nThe GROUP BY expression can be a computed value, and can\nrefer back to an identifer\nspecified with AS. Get a list of win averages along with a\ncount:\n \nSELECT (wins / plays) AS winavg, COUNT(*) FROM plays GROUP\nBY winavg;\n \n+--------+----------+\n| winavg | COUNT(*) |\n+--------+----------+\n| 0.1765 | 1 |\n| 0.2500 | 2 |\n| 0.3636 | 1 |\n+--------+----------+\n3 rows in set (0.00 sec)\n \nYou can use any grouping function\nin the select expression. For each win average as above, get\na list of the average play\ncount taken to get that average:\n \nSELECT (wins / plays) AS winavg, AVG(plays) FROM plays \n GROUP BY winavg;\n \n+--------+------------+\n| winavg | AVG(plays) |\n+--------+------------+\n| 0.1765 | 17.0000 |\n| 0.2500 | 26.0000 |\n| 0.3636 | 22.0000 |\n+--------+------------+\n3 rows in set (0.00 sec)\n \nYou can filter on aggregate information using the HAVING\nclause. The HAVING\nclause is applied after GROUP BY and allows you to filter on\naggregate data that is\nnot available to the WHERE clause. Restrict the above\nexample to results that involve\nan average number of plays over 20:\n \nSELECT (wins / plays) AS winavg, AVG(plays) FROM plays \n GROUP BY winavg HAVING AVG(plays) > 20;\n \n+--------+------------+\n| winavg | AVG(plays) |\n+--------+------------+\n| 0.2500 | 26.0000 |\n| 0.3636 | 22.0000 |\n+--------+------------+\n2 rows in set (0.00 sec)\n \nSee Also\n \nSELECT\nJoins and Subqueries\nLIMIT\nORDER BY\nCommon Table Expressions\nSELECT WITH ROLLUP\nSELECT INTO OUTFILE\nSELECT INTO DUMPFILE\nFOR UPDATE\nLOCK IN SHARE MODE\nOptimizer Hints\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/group-by/','','https://mariadb.com/kb/en/library/group-by/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (414,27,'HANDLER Commands','Syntax\n------ \nHANDLER tbl_name OPEN [ [AS] alias]\nHANDLER tbl_name READ index_name { = | >= | = | \n\nURL: https://mariadb.com/kb/en/library/handler-commands/','','https://mariadb.com/kb/en/library/handler-commands/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (415,27,'HIGH_PRIORITY and LOW_PRIORITY','The XtraDB/InnoDB storage engine uses row-level locking to\nensure data integrity. However some storage engines (such as\nMEMORY, MyISAM, Aria and MERGE) lock the whole table to\nprevent conflicts. These storage engines use two separate\nqueues to remember pending statements; one is for SELECTs\nand the other one is for write statements (INSERT, DELETE,\nUPDATE). By default, the latter has a higher priority.\n \nTo give write operations a lower priority, the\nlow_priority_updates server system variable can be set to\nON. The option is available on both the global and session\nlevels, and it can be set at startup or via the SET\nstatement.\n \nWhen too many table locks have been set by write statements,\nsome pending SELECTs are executed. The maximum number of\nwrite locks that can be acquired before this happens is\ndetermined by the max_write_lock_count server system\nvariable, which is dynamic.\n \nIf write statements have a higher priority (default), the\npriority of individual write statements (INSERT, REPLACE,\nUPDATE, DELETE) can be changed via the LOW_PRIORITY\nattribute, and the priority of a SELECT statement can be\nraised via the HIGH_PRIORITY attribute. Also, LOCK TABLES\nsupports a LOW_PRIORITY attribute for WRITE locks.\n \nIf read statements have a higher priority, the priority of\nan INSERT can be changed via the HIGH_PRIORITY attribute.\nHowever, the priority of other write statements cannot be\nraised individually.\n \nThe use of LOW_PRIORITY or HIGH_PRIORITY for an INSERT\nprevents Concurrent Inserts from being used.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/high_priority-and-low_priority/','','https://mariadb.com/kb/en/library/high_priority-and-low_priority/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (416,27,'IGNORE','The IGNORE option tells the server to ignore some common\nerrors.\n \nIGNORE can be used with the following statements:\nDELETE\nINSERT (see also INSERT IGNORE)\nLOAD DATA INFILE\nUPDATE\nALTER TABLE\nCREATE TABLE ... SELECT\nINSERT ... SELECT\n \nThe logic used:\nVariables out of ranges are replaced with the\nmaximum/minimum value.\n \nSQL_MODEs STRICT_TRANS_TABLES, STRICT_ALL_TABLES,\nNO_ZERO_IN_DATE, NO_ZERO_DATE are ignored.\n \nInserting NULL in a NOT NULL field will insert 0 ( in a\nnumerical\n field), 0000-00-00 ( in a date field) or an empty string (\nin a character\n field).\n \nRows that cause a duplicate key error or break a foreign key\nconstraint are\n not inserted, updated, or deleted.\n \nThe following errors are ignored:\n \nError number | Symbolic error name | Description | \n \n1022 | ER_DUP_KEY | Can\'t write; duplicate key in table\n\'%s\' | \n \n1048 | ER_BAD_NULL_ERROR | Column \'%s\' cannot be null | \n \n1062 | ER_DUP_ENTRY | Duplicate entry \'%s\' for key %d | \n \n1242 | ER_SUBQUERY_NO_1_ROW | Subquery returns more than 1\nrow | \n \n1264 | ER_WARN_DATA_OUT_OF_RANGE | Out of range value for\ncolumn \'%s\' at row %ld | \n \n1265 | WARN_DATA_TRUNCATED | Data truncated for column\n\'%s\' at row %ld | \n \n1292 | ER_TRUNCATED_WRONG_VALUE | Truncated incorrect %s\nvalue: \'%s\' | \n \n1366 | ER_TRUNCATED_WRONG_VALUE_FOR_FIELD | Incorrect\ninteger value | \n \n1369 | ER_VIEW_CHECK_FAILED | CHECK OPTION failed \'%s.%s\'\n| \n \n1451 | ER_ROW_IS_REFERENCED_2 | Cannot delete or update a\nparent row | \n \n1452 | ER_NO_REFERENCED_ROW_2 | Cannot add or update a child\nrow: a foreign key constraint fails (%s) | \n \n1526 | ER_NO_PARTITION_FOR_GIVEN_VALUE | Table has no\npartition for value %s | \n \n1586 | ER_DUP_ENTRY_WITH_KEY_NAME | Duplicate entry \'%s\'\nfor key \'%s\' | \n \n1591 | ER_NO_PARTITION_FOR_GIVEN_VALUE_SILENT | Table has no\npartition for some existing values | \n \n1748 | ER_ROW_DOES_NOT_MATCH_GIVEN_PARTITION_SET | Found a\nrow not matching the given partition set | \n \nIgnored errors normally generate a warning.\n \nA property of the IGNORE clause consists in causing\ntransactional engines and non-transactional engines (like\nXtraDB and Aria) to behave the same way. For example,\nnormally a multi-row insert which tries to violate a UNIQUE\ncontraint is completely rolled back on XtraDB/InnoDB, but\nmight be partially executed on Aria. With the IGNORE clause,\nthe statement will be partially executed in both engines.\n \nStarting from MariaDB 5.5.28 duplicate key errors also\ngenerate warnings. The OLD_MODE server variable can be used\nto prevent this.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/ignore/','','https://mariadb.com/kb/en/library/ignore/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (417,27,'INSERT','Syntax\n------ \nINSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]\n [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]\n {VALUES | VALUE} ({expr | DEFAULT},...),(...),...\n [ ON DUPLICATE KEY UPDATE\n col=expr\n [, col=expr] ... ]\n \nOr:\n \nINSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]\n [INTO] tbl_name [PARTITION (partition_list)]\n SET col={expr | DEFAULT}, ...\n [ ON DUPLICATE KEY UPDATE\n col=expr\n [, col=expr] ... ]\n \nOr:\n \nINSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]\n [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]\n SELECT ...\n [ ON DUPLICATE KEY UPDATE\n col=expr\n [, col=expr] ... ]\n \nThe INSERT statement is used to insert new rows into an\nexisting table. The INSERT ... VALUES\nand INSERT ... SET forms of the statement insert rows based\non explicitly specified values. The INSERT ... SELECT form\ninserts rows selected from another table or tables. INSERT\n... SELECT is discussed further in the INSERT ... SELECT\narticle.\n \nThe table name can be specified in the form db_name.tbl_name\nor, if a default database is selected, in the form tbl_name\n(see Identifier Qualifiers). This allows to use INSERT ...\nSELECT to copy rows between different databases.\n \nThe PARTITION clause was introduced in MariaDB 10.0. It can\nbe used in both the INSERT and the SELECT part. See\nPartition Pruning and Selection for details.\n \nThe columns list is optional. It specifies which values are\nexplicitly inserted, and in which order. If this clause is\nnot specified, all values must be explicitly specified, in\nthe same order they are listed in the table definition.\n \nThe list of value follow the VALUES or VALUE keyword (which\nare interchangeable, regardless how much values you want to\ninsert), and is wrapped by parenthesis. The values must be\nlisted in the same order as the columns list. It is possible\nto specify more than one list to insert more than one rows\nwith a single statement. If many rows are inserted, this is\na speed optimization.\n \nFor one-row statements, the SET clause may be more simple,\nbecause you don\'t need to remember the columns order. All\nvalues are specified in the form col = expr.\n \nValues can also be specified in the form of a SQL expression\nor subquery. However, the subquery cannot access the same\ntable that is named in the INTO clause.\n \nIf you use the LOW_PRIORITY keyword, execution of the INSERT\nis delayed until no other clients are reading from the\ntable. If you use the HIGH_PRIORITY keyword, the statement\nhas the same priority as SELECTs. This affects only storage\nengines that use only table-level locking (MyISAM, MEMORY,\nMERGE). However, if one of these keywords is specified,\nconcurrent inserts cannot be used. See HIGH_PRIORITY and\nLOW_PRIORITY clauses for details.\n \nINSERT DELAYED\n \nFor more details on the DELAYED option, see INSERT DELAYED.\n \nHIGH PRIORITY and LOW PRIORITY\n \nSee HIGH_PRIORITY and LOW_PRIORITY.\n \nDefaults and Duplicate Values\n \nSee INSERT - Default & Duplicate Values for details..\n \nINSERT IGNORE\n \nSee INSERT IGNORE.\n \nINSERT ON DUPLICATE KEY UPDATE\n \nSee INSERT ON DUPLICATE KEY UPDATE.\n \nExamples\n-------- \nSpecifying the column names:\n \nINSERT INTO person (first_name, last_name) VALUES (\'John\',\n\'Doe\');\n \nInserting more than 1 row at a time:\n \nINSERT INTO tbl_name VALUES (1, \"row 1\"), (2, \"row 2\");\n \nUsing the SET clause:\n \nINSERT INTO person SET first_name = \'John\', last_name =\n\'Doe\';\n \nSELECTing from another table:\n \nINSERT INTO contractor SELECT * FROM person WHERE status =\n\'c\';\n \nSee INSERT ON DUPLICATE KEY UPDATE and INSERT IGNORE for\nfurther examples.\n \n\n\nURL: https://mariadb.com/kb/en/library/insert/','','https://mariadb.com/kb/en/library/insert/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (418,27,'INSERT - Default & Duplicate Values','Default Values\n \nIf the SQL_MODE contains STRICT_TRANS_TABLES and you are\ninserting into a transactional table (like InnoDB), or if\nthe SQL_MODE contains STRICT_ALL_TABLES, all NOT NULL\ncolumns which does not have a DEFAULT value (and is not\nAUTO_INCREMENT) must be explicitly referenced in INSERT\nstatements. If not, an error like this is produced:\n \nERROR 1364 (HY000): Field \'col\' doesn\'t have a default\nvalue\n \nIn all other cases, if a NOT NULL column without a DEFAULT\nvalue is not referenced, an empty value will be inserted\n(for example, 0 for INTEGER columns and \'\' for CHAR\ncolumns). See NULL Values in MariaDB:Inserting for examples.\n \nIf a NOT NULL column having a DEFAULT value is not\nreferenced, NULL will be inserted.\n \nIf a NULL column having a DEFAULT value is not referenced,\nits default value will be inserted. It is also possible to\nexplicitly assign the default value using the DEFAULT\nkeyword or the DEFAULT() function.\n \nIf the DEFAULT keyword is used but the column does not have\na DEFAULT value, an error like this is produced:\n \nERROR 1364 (HY000): Field \'col\' doesn\'t have a default\nvalue\n \nDuplicate Values\n \nBy default, if you try to insert a duplicate row and there\nis a UNIQUE index, INSERT stops and an error like this is\nproduced:\n \nERROR 1062 (23000): Duplicate entry \'dup_value\' for key\n\'col\'\n \nTo handle duplicates you can use the IGNORE clause, INSERT\nON DUPLICATE KEY UPDATE or the REPLACE statement. Note that\nthe IGNORE and DELAYED options are ignored when you use ON\nDUPLICATE KEY UPDATE.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/insert-default-duplicate-values/','','https://mariadb.com/kb/en/library/insert-default-duplicate-values/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (419,27,'INSERT DELAYED','Syntax\n------ \nINSERT DELAYED ...\n \nDescription\n----------- \nThe DELAYED option for the INSERT\nstatement is a MariaDB/MySQL extension to standard SQL that\nis very useful if you have\nclients that cannot or need not wait for the INSERT to\ncomplete. This is a common situation when you use MariaDB\nfor logging and you\nalso periodically run SELECT and UPDATE\nstatements that take a long time to complete.\n \nWhen a client uses INSERT DELAYED, it gets an okay from the\nserver at once, and the row is queued to be inserted when\nthe table is not in\nuse by any other thread.\n \nAnother major benefit of using INSERT DELAYED is that\ninserts from many clients are bundled together and written\nin one block. This\nis much faster than performing many separate inserts.\n \nNote that INSERT DELAYED is slower than a normal\n INSERT if the table is not otherwise in use. There is also\nthe additional overhead for the server to handle a separate\nthread for each\ntable for which there are delayed rows. This means that you\nshould use\nINSERT DELAYED only when you are really sure that you need\nit.\n \nThe queued rows are held only in memory until they are\ninserted into the table.\nThis means that if you terminate mysqld forcibly (for\nexample, with kill -9) or\nif mysqld dies unexpectedly, any queued rows that have not\nbeen written to disk\nare lost.\n \nThe number of concurrent INSERT DELAYED threads is limited\nby the max_delayed_threads server system variables. If it is\nset to 0, INSERT DELAYED is disabled. The session value can\nbe equal to the global value, or 0 to disable this statement\nfor the current session. If this limit has been reached, the\nDELAYED clause will be silently ignore for subsequent\nstatements (no error will be produced).\n \nThere are some constraints on the use of DELAYED:\nINSERT DELAYED works only with MyISAM, MEMORY, ARCHIVE,\n and BLACKHOLE tables. If you execute INSERT DELAYED with\nanother storage engine, you will get an error like this:\nERROR 1616 (HY000): DELAYED option not supported for table\n\'tab_name\'\nFor MyISAM tables, if there are no free blocks in the middle\nof the data\n file, concurrent SELECT and INSERT statements are\nsupported. Under these\n circumstances, you very seldom need to use INSERT DELAYED\n with MyISAM.\nINSERT DELAYED should be used only for\n INSERT statements that specify value lists. The server\n ignores DELAYED for INSERT ... SELECT\n or INSERT ... ON DUPLICATE KEY UPDATE statements.\nBecause the INSERT DELAYED statement returns immediately,\n before the rows are inserted, you cannot use\n LAST_INSERT_ID() to get the\n AUTO_INCREMENT value that the statement might generate.\nDELAYED rows are not visible to SELECT\n statements until they actually have been inserted.\nAfter INSERT DELAYED, ROW_COUNT() returns the number of the\nrows you tried to insert, not the number of the successful\nwrites.\nDELAYED is ignored on slave replication servers, so that \n INSERT DELAYED is treated as a normal\n INSERT on slaves. This is because\n DELAYED could cause the slave to have different data than\n the master. INSERT DELAYED statements are not safe for\nreplication.\nPending INSERT DELAYED statements are lost if a table is\n write locked and ALTER TABLE is used to modify the table\nstructure.\nINSERT DELAYED is not supported for views. If you try, you\nwill get an error like this: ERROR 1347 (HY000):\n\'view_name\' is not BASE TABLE\nINSERT DELAYED is not supported for partitioned tables.\nINSERT DELAYED is not supported within stored programs.\n \n\n\nURL: https://mariadb.com/kb/en/library/insert-delayed/','','https://mariadb.com/kb/en/library/insert-delayed/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (420,27,'INSERT IGNORE','Ignoring Errors\n \nNormally INSERT stops and rolls back when it encounters an\nerror.\n \nBy using the IGNORE keyword all errors are converted to\nwarnings, which will not stop inserts of additional rows.\n \nThe IGNORE and DELAYED options are ignored when you use ON\nDUPLICATE KEY UPDATE.\n \nIncompatibilities\n \nMariaDB until 5.5.28\nMySQL and MariaDB before 5.5.28 didn\'t give warnings for\nduplicate key errors when using IGNORE.\nYou can get the old behaviour if you set OLD_MODE to\nNO_DUP_KEY_WARNINGS_WITH_IGNORE\n \nExamples\n-------- \nCREATE TABLE t1 (x INT UNIQUE);\n \nINSERT INTO t1 VALUES(1),(2);\n \nINSERT INTO t1 VALUES(2),(3);\nERROR 1062 (23000): Duplicate entry \'2\' for key \'x\'\nSELECT * FROM t1;\n \n+------+\n| x |\n+------+\n| 1 |\n| 2 |\n+------+\n2 rows in set (0.00 sec)\n \nINSERT IGNORE INTO t1 VALUES(2),(3);\nQuery OK, 1 row affected, 1 warning (0.04 sec)\n \nSHOW WARNINGS;\n \n+---------+------+---------------------------------+\n| Level | Code | Message |\n+---------+------+---------------------------------+\n| Warning | 1062 | Duplicate entry \'2\' for key \'x\' |\n+---------+------+---------------------------------+\n \nSELECT * FROM t1;\n \n+------+\n| x |\n+------+\n| 1 |\n| 2 |\n| 3 |\n+------+\n \nSee INSERT ON DUPLICATE KEY UPDATE for further examples\nusing that syntax.\n \n\n\nURL: https://mariadb.com/kb/en/library/insert-ignore/','','https://mariadb.com/kb/en/library/insert-ignore/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (421,27,'INSERT ON DUPLICATE KEY UPDATE','Syntax\n------ \nINSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]\n [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]\n {VALUES | VALUE} ({expr | DEFAULT},...),(...),...\n [ ON DUPLICATE KEY UPDATE\n col=expr\n [, col=expr] ... ]\n \nOr:\n \nINSERT [LOW_PRIORITY | DELAYED | HIGH_PRIORITY] [IGNORE]\n [INTO] tbl_name [PARTITION (partition_list)]\n SET col={expr | DEFAULT}, ...\n [ ON DUPLICATE KEY UPDATE\n col=expr\n [, col=expr] ... ]\n \nOr:\n \nINSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]\n [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]\n SELECT ...\n [ ON DUPLICATE KEY UPDATE\n col=expr\n [, col=expr] ... ]\n \nDescription\n----------- \nINSERT ... ON DUPLICATE KEY UPDATE is a MariaDB/MySQL\nextension to the INSERT statement that, if it finds a\nduplicate unique or primary key, will instead perform an\nUPDATE.\n \nThe row/s affected value is reported as 1 if a row is\ninserted, and 2 if a row is updated, unless the API\'s\nCLIENT_FOUND_ROWS flag is set.\n \nIf more than one unique index is matched, only the first is\nupdated. It is not recommended to use this statement on\ntables with more than one unique index.\n \nIf the table has an AUTO_INCREMENT primary key and the\nstatement inserts or updates a row, the LAST_INSERT_ID()\nfunction returns its AUTO_INCREMENT value.\n \nThe VALUES() function can only be used in a ON DUPLICATE KEY\nUPDATE clause and has no meaning in any other context. It\nreturns the column values from the INSERT portion of the\nstatement. This function is particularly useful for\nmulti-rows inserts.\n \nThe IGNORE and DELAYED options are ignored when you use ON\nDUPLICATE KEY UPDATE.\n \nThe PARTITION clause was introduced in MariaDB 10.0. See\nPartition Pruning and Selection for details.\n \nThis statement activates INSERT and UPDATE triggers. See\nTrigger Overview for details.\n \nSee also a similar statement, REPLACE.\n \nExamples\n-------- \nCREATE TABLE ins_duplicate (id INT PRIMARY KEY, animal\nVARCHAR(30));\nINSERT INTO ins_duplicate VALUES (1,\'Aardvark\'),\n(2,\'Cheetah\'), (3,\'Zebra\');\n \nIf there is no existing key, the statement runs as a regular\nINSERT:\n \nINSERT INTO ins_duplicate VALUES (4,\'Gorilla\') ON\nDUPLICATE KEY UPDATE animal=\'Gorilla\';\nQuery OK, 1 row affected (0.07 sec)\n \nSELECT * FROM ins_duplicate;\n+----+----------+\n| id | animal |\n+----+----------+\n| 1 | Aardvark |\n| 2 | Cheetah |\n| 3 | Zebra |\n| 4 | Gorilla |\n+----+----------+\n \nA regular INSERT with a primary key value of 1 will fail,\ndue to the existing key:\n \nINSERT INTO ins_duplicate VALUES (1,\'Antelope\');\nERROR 1062 (23000): Duplicate entry \'1\' for key\n\'PRIMARY\'\n \nHowever, we can use an INSERT ON DUPLICATE KEY UPDATE\ninstead:\n \nINSERT INTO ins_duplicate VALUES (1,\'Antelope\') ON\nDUPLICATE KEY UPDATE animal=\'Antelope\';\nQuery OK, 2 rows affected (0.09 sec)\n \nNote that there are two rows reported as affected, but this\nrefers only to the UPDATE.\n \nSELECT * FROM ins_duplicate;\n+----+----------+\n| id | animal |\n+----+----------+\n| 1 | Antelope |\n| 2 | Cheetah |\n| 3 | Zebra |\n| 4 | Gorilla |\n+----+----------+\n \nAdding a second unique column:\n \nALTER TABLE ins_duplicate ADD id2 INT;\nUPDATE ins_duplicate SET id2=id+10;\nALTER TABLE ins_duplicate ADD UNIQUE KEY(id2);\n \nWhere two rows match the unique keys match, only the first\nis updated. This can be unsafe and is not recommended unless\nyou are certain what you are doing. Note that the warning\nshown below appears in MariaDB 5.5 and before, but has been\nremoved in MariaDB 10.0, as MariaDB now assumes that the\nkeys are checked in order, as shown in SHOW CREATE TABLE.\n \nINSERT INTO ins_duplicate VALUES (2,\'Lion\',13) ON\nDUPLICATE KEY UPDATE animal=\'Lion\';\nQuery OK, 2 rows affected, 1 warning (0.06 sec)\n \nSHOW WARNINGS;\n+-------+------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Level | Code | Message |\n+-------+------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n| Note | 1592 | Unsafe statement written to the binary log\nusing statement format since BINLOG_FORMAT = STATEMENT.\nINSERT... ON DUPLICATE KEY UPDATE on a table with more than\none UNIQUE KEY is unsafe |\n+-------+------+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+\n \nSELECT * FROM ins_duplicate;\n+----+----------+------+\n| id | animal | id2 |\n+----+----------+------+\n| 1 | Antelope | 11 |\n| 2 | Lion | 12 |\n| 3 | Zebra | 13 |\n| 4 | Gorilla | 14 |\n+----+----------+------+\n \nAlthough the third row with an id of 3 has an id2 of 13,\nwhich also matched, it was not updated.\n \nChanging id to an auto_increment field. If a new row is\nadded, the auto_increment is moved forward. If the row is\nupdated, it remains the same.\n \nALTER TABLE `ins_duplicate` CHANGE `id` `id` INT( 11 ) NOT\nNULL AUTO_INCREMENT;\nALTER TABLE ins_duplicate DROP id2;\nSELECT Auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE\nTABLE_NAME=\'ins_duplicate\';\n+----------------+\n| Auto_increment |\n+----------------+\n| 5 |\n+----------------+\n \nINSERT INTO ins_duplicate VALUES (2,\'Leopard\') ON\nDUPLICATE KEY UPDATE animal=\'Leopard\';\nQuery OK, 2 rows affected (0.00 sec)\n \nSELECT Auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE\nTABLE_NAME=\'ins_duplicate\';\n+----------------+\n| Auto_increment |\n+----------------+\n| 5 |\n+----------------+\n \nINSERT INTO ins_duplicate VALUES (5,\'Wild Dog\') ON\nDUPLICATE KEY UPDATE animal=\'Wild Dog\';\nQuery OK, 1 row affected (0.09 sec)\n \nSELECT * FROM ins_duplicate;\n+----+----------+\n| id | animal |\n+----+----------+\n| 1 | Antelope |\n| 2 | Leopard |\n| 3 | Zebra |\n| 4 | Gorilla |\n| 5 | Wild Dog |\n+----+----------+\n \nSELECT Auto_increment FROM INFORMATION_SCHEMA.TABLES WHERE\nTABLE_NAME=\'ins_duplicate\';\n+----------------+\n| Auto_increment |\n+----------------+\n| 6 |\n+----------------+\n \nRefering to column values from the INSERT portion of the\nstatement: \n \nINSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6)\n ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);\n \nSee the VALUES() function for more.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/insert-on-duplicate-key-update/','','https://mariadb.com/kb/en/library/insert-on-duplicate-key-update/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (422,27,'INSERT SELECT','Syntax\n------ \nINSERT [LOW_PRIORITY | HIGH_PRIORITY] [IGNORE]\n [INTO] tbl_name [(col_name,...)]\n SELECT ...\n [ ON DUPLICATE KEY UPDATE col_name=expr, ... ]\n \nDescription\n----------- \nWith INSERT ... SELECT, you can quickly insert many rows\ninto a table from one or more other tables. For example:\n \nINSERT INTO tbl_temp2 (fld_id)\n SELECT tbl_temp1.fld_order_id\n FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;\n \ntbl_name can also be specified in the form db_name.tbl_name\n(see Identifier Qualifiers). This allows to copy rows\nbetween different databases.\n \nIf the new table has a primary key or UNIQUE indexes, you\ncan use IGNORE to handle duplicate key errors during the\nquery. The newer values will not be inserted if an identical\nvalue already exists.\n \nREPLACE can be used instead of INSERT to prevent duplicates\non UNIQUE indexes by deleting old values. In that case, ON\nDUPLICATE KEY UPDATE cannot be used.\n \nINSERT ... SELECT works for tables which already exist. To\ncreate a table for a given resultset, you can use CREATE\nTABLE ... SELECT.\n \n\n\nURL: https://mariadb.com/kb/en/library/insert-select/','','https://mariadb.com/kb/en/library/insert-select/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (423,27,'INTERSECT','INTERSECT was introduced in MariaDB 10.3.0.\n \nThe result of an intersect is the intersection of right and\nleft SELECT results, i.e. only records that are present in\nboth result sets will be included in the result of the\noperation.\n \nSyntax\n------ \nSELECT ...\n(INTERSECT | EXCEPT | UNION [ALL | DISTINCT]) SELECT ...\n[(INTERSECT | EXCEPT | UNION [ALL | DISTINCT]) SELECT ...]\n[ORDER BY [column [, column ...]]]\n[LIMIT {[offset,] row_count | row_count OFFSET offset}]\n \nPlease note:\nALL is not supported by INTERSECT (and it is difficult to\nmake sense of ALL with INTERSECT).\nBrackets for explicit operation precedence are not\nsupported; use a subquery in the FROM clause as a\nworkaround).\n \nDescription\n----------- \nMariaDB has supported INTERSECT (as well as EXCEPT) in\naddition to UNION since MariaDB 10.3.\n \nAll behavior for naming columns, ORDER BY and LIMIT is the\nsame as for UNION.\n \nINTERSECT implicitly supposes a DISTINCT operation.\n \nThe result of an intersect is the intersection of right and\nleft SELECT results, i.e. only records that are present in\nboth result sets will be included in the result of the\noperation.\n \nINTERSECT has higher precedence than UNION and EXCEPT. If\npossible it will be executed linearly but if not it will be\ntranslated to a subquery in the FROM clause:\n \n(select a,b from t1)\nunion\n(select c,d from t2)\nintersect\n(select e,f from t3)\nunion\n(select 4,4);\n \nwill be translated to:\n \n(select a,b from t1)\nunion\nselect c,d from\n ((select c,d from t2)\n intersect\n (select e,f from t3)) dummy_subselect\nunion\n(select 4,4)\n \n\n \nParentheses\n \nFrom MariaDB 10.4.0, parentheses can be used to specify\nprecedence. Before this, a syntax error would be returned.\n \nExamples\n-------- \nShow customers which are employees:\n \n(SELECT e_name AS name, email FROM employees)\nINTERSECT\n(SELECT c_name AS name, email FROM customers);\n \nDifference between UNION, EXCEPT and INTERSECT:\n \nCREATE TABLE seqs (i INT);\nINSERT INTO seqs VALUES (1),(2),(3),(4),(5),(6);\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n+------+\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 1 |\n| 2 |\n+------+\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 3 |\n+------+\n \nParentheses for specifying precedence, from MariaDB 10.4.0\n \nCREATE OR REPLACE TABLE t1 (a INT);\nCREATE OR REPLACE TABLE t2 (b INT);\nCREATE OR REPLACE TABLE t3 (c INT);\n \nINSERT INTO t1 VALUES (1),(2),(3),(4);\nINSERT INTO t2 VALUES (5),(6);\nINSERT INTO t3 VALUES (1),(6);\n \n((SELECT a FROM t1) UNION (SELECT b FROM t2)) INTERSECT\n(SELECT c FROM t3);\n+------+\n| a |\n+------+\n| 1 |\n| 6 |\n+------+\n \n(SELECT a FROM t1) UNION ((SELECT b FROM t2) INTERSECT\n(SELECT c FROM t3));\n+------+\n| a |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 6 |\n+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/intersect/','','https://mariadb.com/kb/en/library/intersect/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (424,27,'JOIN Syntax','Description\n----------- \nMariaDB supports the following JOIN syntaxes for\nthe table_references part of SELECT statements and\nmultiple-table DELETE and UPDATE statements:\n \ntable_references:\n table_reference [, table_reference] ...\n \ntable_reference:\n table_factor\n | join_table\n \ntable_factor:\n tbl_name [PARTITION (partition_list)]\n [query_system_time_period_specification] [[AS] alias]\n[index_hint_list]\n | table_subquery [query_system_time_period_specification]\n[AS] alias\n | ( table_references )\n | { ON table_reference LEFT OUTER JOIN table_reference\n ON conditional_expr }\n \njoin_table:\n table_reference [INNER | CROSS] JOIN table_factor\n[join_condition]\n | table_reference STRAIGHT_JOIN table_factor\n | table_reference STRAIGHT_JOIN table_factor ON\nconditional_expr\n | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference\njoin_condition\n | table_reference NATURAL [{LEFT|RIGHT} [OUTER]] JOIN\ntable_factor\n \njoin_condition:\n ON conditional_expr\n | USING (column_list)\n \nquery_system_time_period_specification:\n FOR SYSTEM_TIME AS OF point_in_time\n | FOR SYSTEM_TIME BETWEEN point_in_time AND point_in_time\n | FOR SYSTEM_TIME FROM point_in_time TO point_in_time\n | FOR SYSTEM_TIME ALL\n \npoint_in_time:\n [TIMESTAMP] expression\n | TRANSACTION expression\n \nindex_hint_list:\n index_hint [, index_hint] ...\n \nindex_hint:\n USE {INDEX|KEY}\n [{FOR {JOIN|ORDER BY|GROUP BY}] ([index_list])\n | IGNORE {INDEX|KEY}\n [{FOR {JOIN|ORDER BY|GROUP BY}] (index_list)\n | FORCE {INDEX|KEY}\n [{FOR {JOIN|ORDER BY|GROUP BY}] (index_list)\n \nindex_list:\n index_name [, index_name] ...\n \nA table reference is also known as a join expression.\n \nEach table can also be specified as db_name.tabl_name. This\nallows to write queries which involve multiple databases.\nSee Identifier Qualifiers for syntax details.\n \nThe syntax of table_factor is extended in comparison with\nthe\nSQL Standard. The latter accepts only table_reference, not a\nlist of them inside a pair of parentheses.\n \nThis is a conservative extension if we consider each comma\nin a list of\ntable_reference items as equivalent to an inner join. For\nexample:\n \nSELECT * FROM t1 LEFT JOIN (t2, t3, t4)\n ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)\n \nis equivalent to:\n \nSELECT * FROM t1 LEFT JOIN (t2 CROSS JOIN t3 CROSS JOIN t4)\n ON (t2.a=t1.a AND t3.b=t1.b AND t4.c=t1.c)\n \nIn MariaDB, CROSS JOIN is a syntactic equivalent to\nINNER JOIN (they can replace each other). In standard SQL,\nthey are not equivalent. INNER JOIN is used with an\nON clause, CROSS JOIN is used otherwise.\n \nIn general, parentheses can be ignored in join expressions\ncontaining only\ninner join operations. MariaDB also supports nested joins\n(see\nhttp://dev.mysql.com/doc/refman/5.1/en/nested-join-optimization.html).\n \nSee System-versioned tables for more information\nabout FOR SYSTEM_TIME syntax.\n \nIndex hints can be specified to affect how the MariaDB\noptimizer makes\nuse of indexes. For more information, see How to force query\nplans.\n \nExamples\n-------- \nSELECT left_tbl.*\n FROM left_tbl LEFT JOIN right_tbl ON left_tbl.id =\nright_tbl.id\n WHERE right_tbl.id IS NULL;\n \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/join-syntax/','','https://mariadb.com/kb/en/library/join-syntax/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (425,27,'LIMIT','Description\n----------- \nUse the LIMIT clause to restrict the number of returned\nrows. When you use a single\ninteger n with LIMIT, the first n rows will be returned. Use\nthe ORDER BY\nclause to control which rows come first. You can also select\na number of rows after an offset\nusing either of the following:\n \nLIMIT offset, row_count\nLIMIT row_count OFFSET offset\n \nWhen you provide an offset m with a limit n, the first m\nrows will be ignored, and the\nfollowing n rows will be returned.\n \nExecuting an UPDATE with the LIMIT clause is not safe for\nreplication.\n \nSince MariaDB 10.0.11, LIMIT 0 has been an exception to this\nrule (see MDEV-6170).\n \nBeginning in MariaDB 5.5.21, there is a LIMIT ROWS EXAMINED\noptimization which provides the\nmeans to terminate the execution of SELECT statements which\nexamine too\nmany rows, and thus use too many resources. See LIMIT ROWS\nEXAMINED.\n \nMulti-Table Updates\n \nUntil MariaDB 10.3.1, it was not possible to use LIMIT (or\nORDER BY) in a multi-table UPDATE statement. This\nrestriction was lifted in MariaDB 10.3.2.\n \nGROUP_CONCAT\n \nStarting from MariaDB 10.3.3, it is possible to use LIMIT\nwith GROUP_CONCAT().\n \nExamples\n-------- \nCREATE TABLE members (name VARCHAR(20));\nINSERT INTO members\nVALUES(\'Jagdish\'),(\'Kenny\'),(\'Rokurou\'),(\'Immaculada\');\n \nSELECT * FROM members;\n \n+------------+\n| name |\n+------------+\n| Jagdish |\n| Kenny |\n| Rokurou |\n| Immaculada |\n+------------+\n \nSelect the first two names (no ordering specified):\n \nSELECT * FROM members LIMIT 2;\n \n+---------+\n| name |\n+---------+\n| Jagdish |\n| Kenny |\n+---------+\n \nAll the names in alphabetical order:\n \nSELECT * FROM members ORDER BY name;\n \n+------------+\n| name |\n+------------+\n| Immaculada |\n| Jagdish |\n| Kenny |\n| Rokurou |\n+------------+\n \nThe first two names, ordered alphabetically:\n \nSELECT * FROM members ORDER BY name LIMIT 2;\n \n+------------+\n| name |\n+------------+\n| Immaculada |\n| Jagdish |\n+------------+\n \nThe third name, ordered alphabetically (the first name would\nbe offset zero, so the third is offset two):\n \nSELECT * FROM members ORDER BY name LIMIT 2,1;\n \n+-------+\n| name |\n+-------+\n| Kenny |\n+-------+\n \nFrom MariaDB 10.3.2, LIMIT can be used in a multi-table\nupdate:\n \nCREATE TABLE warehouse (product_id INT, qty INT);\nINSERT INTO warehouse VALUES\n(1,100),(2,100),(3,100),(4,100);\n \nCREATE TABLE store (product_id INT, qty INT);\nINSERT INTO store VALUES (1,5),(2,5),(3,5),(4,5);\n \nUPDATE warehouse,store SET warehouse.qty = warehouse.qty-2,\nstore.qty = store.qty+2 \n WHERE (warehouse.product_id = store.product_id AND\nstore.product_id >= 1) \n ORDER BY store.product_id DESC LIMIT 2;\n \nSELECT * FROM warehouse;\n \n+------------+------+\n| product_id | qty |\n+------------+------+\n| 1 | 100 |\n| 2 | 100 |\n| 3 | 98 |\n| 4 | 98 |\n+------------+------+\n \nSELECT * FROM store;\n \n+------------+------+\n| product_id | qty |\n+------------+------+\n| 1 | 5 |\n| 2 | 5 |\n| 3 | 7 |\n| 4 | 7 |\n+------------+------+\n \nFrom MariaDB 10.3.3, LIMIT can be used with GROUP_CONCAT,\nso, for example, given the following table:\n \nCREATE TABLE d (dd DATE, cc INT);\n \nINSERT INTO d VALUES (\'2017-01-01\',1);\nINSERT INTO d VALUES (\'2017-01-02\',2);\nINSERT INTO d VALUES (\'2017-01-04\',3);\n \nthe following query:\n \nSELECT SUBSTRING_INDEX(GROUP_CONCAT(CONCAT_WS(\":\",dd,cc)\nORDER BY cc DESC),\",\",1) FROM d;\n \n+----------------------------------------------------------------------------+\n| SUBSTRING_INDEX(GROUP_CONCAT(CONCAT_WS(\":\",dd,cc) ORDER\nBY cc DESC),\",\",1) |\n+----------------------------------------------------------------------------+\n| 2017-01-04:3 |\n+----------------------------------------------------------------------------+\n \ncan be more simply rewritten as:\n \nSELECT GROUP_CONCAT(CONCAT_WS(\":\",dd,cc) ORDER BY cc DESC\nLIMIT 1) FROM d;\n \n+-------------------------------------------------------------+\n| GROUP_CONCAT(CONCAT_WS(\":\",dd,cc) ORDER BY cc DESC LIMIT\n1) |\n+-------------------------------------------------------------+\n| 2017-01-04:3 |\n+-------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/limit/','','https://mariadb.com/kb/en/library/limit/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (426,27,'LOAD DATA INFILE','Syntax\n------ \nLOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE\n\'file_name\'\n [REPLACE | IGNORE]\n INTO TABLE tbl_name\n [CHARACTER SET charset_name]\n [{FIELDS | COLUMNS}\n [TERMINATED BY \'string\']\n [[OPTIONALLY] ENCLOSED BY \'char\']\n [ESCAPED BY \'char\']\n ]\n [LINES\n [STARTING BY \'string\']\n [TERMINATED BY \'string\']\n ]\n [IGNORE number LINES]\n [(col_name_or_user_var,...)]\n [SET col_name = expr,...]\n \nDescription\n----------- \nReads rows from a text file into the designated table on the\ndatabase at a very high speed. The file name must be given\nas a literal string. \n \nFiles are written to disk using the SELECT INTO OUTFILE\nstatement. You can then read the files back into a table\nusing the LOAD DATA INFILE statement. The FIELDS and LINES\nclauses are the same in both statements. These clauses are\noptional, but if both are specified then the FIELDS clause\nmust precede LINES.\n \nIn releases after MariaDB 5.5, LOAD DATA INFILE is unsafe\nfor statement-based replication.\n \nExecuting this statement activates INSERT triggers.\n \nREPLACE and IGNORE\n \nIn cases where you load data from a file into a table that\nalready contains data and has a Primary Key, you may\nencounter issues where the statement attempts to insert a\nrow with a Primary Key that already exists. When this\nhappens, the statement fails with Error 1064, protecting the\ndata already on the table. In cases where you want MariaDB\nto overwrite duplicates, use the REPLACE keyword.\n \nThe REPLACE keyword works like the REPLACE statement. Here,\nthe statement attempts to load the data from the file. If\nthe row does not exist, it adds it to the table. If the row\ncontains an existing Primary Key, it replaces the table\ndata. That is, in the event of a conflict, it assumes the\nfile contains the desired row. \n \nThis operation can cause a degradation in load speed by a\nfactor of 20 or more if the part that has already been\nloaded is larger than the capacity of the InnoDB Buffer\nPool. This happens because it causes a lot of turnaround in\nthe Buffer Pool.\n \nUse the IGNORE keyword when you want to skip any rows that\ncontain a conflicting Primary Key. Here, the statement\nattempts to load the data from the file. If the row does not\nexist, it adds it to the table. If the row contains an\nexisting Primary Key, it ignores the addition request and\nmoves on to the next. That is, in the event of a conflict,\nit assumes the table contains the desired row.\n \nLOCAL\n \nWhen you issue this statement, the Server attempts to read\nfiles from the host file system. Using the LOCAL keyword,\nthe statement instead attempts to read files from the\nclient. This allows you to insert files from the client\'s\nlocal file system into the database.\n \nIn the event that you don\'t want the server to permit this\noperation, (such as for security reasons), you can disable\nsupport using local_infile. When this system variable is set\nto 0, MariaDB rejects LOAD DATA LOCAL INFILE statements,\nfailing with an error message.\n \nCharacter-sets\n \nWhen the statement opens the file, it attempts to read the\ncontents using the default character-set, as defined by the\ncharacter_set_database system variable. \n \nIn the cases where the file was written using a\ncharacter-set other than the default, you can specify the\ncharacter-set to use with the CHARACTER SET clause in the\nstatement. It ignores character-sets specified by the SET\nNAMES statement and by the character_set_client system\nvariable. Setting the CHARACTER SET clause to a value of\nbinary indicates \"no conversion.\"\n \nThe statement interprets all fields in the file as having\nthe same character-set, regardless of the column data type.\nTo properly interpret file contents, you must ensure that it\nwas written with the correct character-set. If you write a\ndata file with mysqldump -T or with the SELECT INTO OUTFILE\nstatement with the mysql client, be sure to use the\n--default-character-set option, so that the output is\nwritten with the desired character-set.\n \nWhen using mixed character sets, use the CHARACTER SET\nclause in both SELECT INTO OUTFILE and LOAD DATA INFILE to\nensure that MariaDB correctly interprets the escape\nsequences.\n \nThe character_set_filesystem system variable controls the\ninterpretation of the filename.\n \nIt is currently not possible to load data files that use the\nucs2 character set.\n \nPriority and Concurrency\n \nIn loading data from a file, there\'s a risk that the\nstatement will attempt insertions concurrent with reads from\nanother client, which can result in the read serving a\nresult-set that contains only part of the update from the\nLOAD DATA INFILE statement.\n \nUsing the LOW_PRIORITY keyword, MariaDB delays insertions\nuntil no other clients are reading from the table.\nAlternatively, you can use the CONCURRENT keyword to perform\nconcurrent insertion.\n \nThe LOW_PRIORITY and CONCURRENT keywords are mutually\nexclusive. They cannot be used in the same statement.\n \nProgress Reporting\n \nSince MariaDB 5.3, the LOAD DATA INFILE statement supports\nprogress reporting. You may find this useful when dealing\nwith long-running operations. Using another client you can\nissue a SHOW PROCESSLIST query to check the progress of the\ndata load.\n \nUsing mysqlimport\n \nMariaDB ships with a separate utility for loading data from\nfiles: mysqlimport. It operates by sending LOAD DATA INFILE\nstatements to the server.\n \nUsing mysqlimport you can compress the file using the\n--compress option, to get better performance over slow\nnetworks, providing both the client and server support the\ncompressed protocol. Use the --local option to load from the\nlocal file system.\n \nIndexing\n \nIn cases where the storage engine supports ALTER TABLE...\nDISABLE KEYS statements, the LOAD DATA INFILE statement\nautomatically disables indexes during the execution.\n \n\n\nURL: https://mariadb.com/kb/en/library/load-data-infile/','','https://mariadb.com/kb/en/library/load-data-infile/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (427,27,'LOAD XML','Syntax\n------ \nLOAD XML [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE\n\'file_name\'\n [REPLACE | IGNORE]\n INTO TABLE [db_name.]tbl_name\n [CHARACTER SET charset_name]\n [ROWS IDENTIFIED BY \'\']\n [IGNORE number {LINES | ROWS}]\n [(column_or_user_var,...)]\n [SET col_name = expr,...]\n \nDescription\n----------- \nThe LOAD XML statement reads data from an XML file into a\ntable. The\nfile_name must be given as a literal string. The tagname in\nthe\noptional ROWS IDENTIFIED BY clause must also be given as a\nliteral\nstring, and must be surrounded by angle brackets (< and >).\n \nLOAD XML acts as the complement of running the mysql client\nin XML\noutput mode (that is, starting the client with the --xml\noption). To\nwrite data from a table to an XML file, use a command such\nas the\nfollowing one from the system shell:\n \nshell> mysql --xml -e \'SELECT * FROM mytable\' > file.xml\n \nTo read the file back into a table, use LOAD XML INFILE. By\ndefault,\nthe element is considered to be the equivalent of a\ndatabase\ntable row; this can be changed using the ROWS IDENTIFIED BY\nclause.\n \nThis statement supports three different XML formats:\nColumn names as attributes and column values as attribute\nvalues:\n \nColumn names as tags and column values as the content of\nthese tags:\n \n value1\n value2\n \nColumn names are the name attributes of tags, and values\nare\n the contents of these tags:\n \n value1\n value2\n \n This is the format used by other tools, such as mysqldump.\n \nAll 3 formats can be used in the same XML file; the import\nroutine\nautomatically detects the format for each row and interprets\nit\ncorrectly. Tags are matched based on the tag or attribute\nname and the\ncolumn name.\n \nThe following clauses work essentially the same way for LOAD\nXML as\nthey do for LOAD DATA:\nLOW_PRIORITY or CONCURRENT\nLOCAL\nREPLACE or IGNORE\nCHARACTER SET\n(column_or_user_var,...)\nSET\n \nSee LOAD DATA for more information about these clauses.\n \nThe IGNORE number LINES or IGNORE number ROWS clause causes\nthe first\nnumber rows in the XML file to be skipped. It is analogous\nto the LOAD\nDATA statement\'s IGNORE ... LINES clause.\n \nIf the LOW_PRIORITY keyword is used, insertions are delayed\nuntil no other clients are reading from the table. The\nCONCURRENT keyword allowes the use of concurrent inserts.\nThese clauses cannot be specified together.\n \nThis statement activates INSERT triggers.\n \n\n\nURL: https://mariadb.com/kb/en/library/load-xml/','','https://mariadb.com/kb/en/library/load-xml/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (428,27,'LOCK IN SHARE MODE','When LOCK IN SHARE MODE is specified in a SELECT statement,\nMariaDB will wait until all transactions that have modified\nthe rows are committed. Then, a write lock is acquired. All\ntransactions can read the rows, but if they want to modify\nthem, they have to wait until your transaction is committed.\n \nInnoDB/XtraDB supports row-level locking. selected rows can\nbe locked using LOCK IN SHARE MODE or FOR UPDATE. In both\ncases, a lock is acquired on the rows read by the query, and\nit will be released when the current transaction is\ncommitted.\n \nIf autocommit is set to 1, the LOCK IN SHARE MODE and FOR\nUPDATE clauses have no effect.\n \n\n\nURL: https://mariadb.com/kb/en/library/lock-in-share-mode/','','https://mariadb.com/kb/en/library/lock-in-share-mode/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (429,27,'Non-Recursive Common Table Expressions Overview','Common Table Expressions (CTEs) are a standard SQL feature,\nand are essentially temporary named result sets. There are\ntwo kinds of CTEs: Non-Recursive, which this article covers;\nand Recursive.\n \nCommon table expressions were introduced in MariaDB 10.2.1.\n \nNon-Recursive CTEs\n \nThe WITH keyword signifies a CTE. It is given a name,\nfollowed by a body (the main query) as follows:\n \nCTEs are similar to derived tables. For example\n \nWITH engineers AS \n ( SELECT * FROM employees\n WHERE dept = \'Engineering\' )\n \nSELECT * FROM engineers\nWHERE ...\n \nSELECT * FROM\n ( SELECT * FROM employees\n WHERE dept = \'Engineering\' ) AS engineers\nWHERE\n...\n \nA non-recursive CTE is basically a query-local VIEW. There\nare several advantages and caveats to them. The syntax is\nmore readable than nested FROM (SELECT ...).\nA CTE can refer to another and it can be referenced from\nmultiple places.\n \nA CTE referencing Another CTE\n \nUsing this format makes for a more readable SQL than a\nnested FROM(SELECT ...) clause. Below is an example of this:\n \nWITH engineers AS (\nSELECT * FROM employees\nWHERE dept IN(\'Development\',\'Support\') ),\neu_engineers AS ( SELECT * FROM engineers WHERE country\nIN(\'NL\',...) )\nSELECT\n...\nFROM eu_engineers;\n \nMultiple Uses of a CTE\n \nThis can be an \'anti-self join\', for example:\n \nWITH engineers AS (\nSELECT * FROM employees\nWHERE dept IN(\'Development\',\'Support\') )\n \nSELECT * FROM engineers E1\nWHERE NOT EXISTS\n (SELECT 1 FROM engineers E2\n WHERE E2.country=E1.country\n AND E2.name E1.name );\n \nOr, for year-over-year comparisons, for example:\n \nWITH sales_product_year AS (\nSELECT product, YEAR(ship_date) AS year,\nSUM(price) AS total_amt\nFROM item_sales\nGROUP BY product, year )\n \nSELECT *\nFROM sales_product_year CUR,\nsales_product_year PREV,\nWHERE CUR.product=PREV.product \nAND CUR.year=PREV.year + 1 \nAND CUR.total_amt > PREV.total_amt\n \nAnother use is to compare individuals against their group.\nBelow is an example of how this might be executed:\n \nWITH sales_product_year AS (\nSELECT product,\nYEAR(ship_date) AS year,\nSUM(price) AS total_amt\nFROM item_sales\nGROUP BY product, year\n)\n \nSELECT * \nFROM sales_product_year S1\nWHERE\ntotal_amt > \n (SELECT 0.1 * SUM(total_amt)\n FROM sales_product_year S2\n WHERE S2.year = S1.year)\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/non-recursive-common-table-expressions-overview/','','https://mariadb.com/kb/en/library/non-recursive-common-table-expressions-overview/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (430,27,'ORDER BY','Description\n----------- \nUse the ORDER BY clause to order a resultset, such as that\nare returned from a SELECT\nstatement. You can specify just a column or use any\nexpression with functions. If you are\nusing the GROUP BY clause, you can use grouping functions in\nORDER BY.\nOrdering is done after grouping.\n \nYou can use multiple ordering expressions, separated by\ncommas. Rows will be sorted by\nthe first expression, then by the second expression if they\nhave the same value for the\nfirst, and so on.\n \nYou can use the keywords ASC and DESC after each ordering\nexpression to\nforce that ordering to be ascending or descending,\nrespectively. Ordering is ascending\nby default.\n \nYou can also use a single integer as the ordering\nexpression. If you use an integer n,\nthe results will be ordered by the nth column in the select\nexpression.\n \nWhen string values are compared, they are compared as if by\nthe STRCMP\nfunction. STRCMP ignores trailing whitespace and may\nnormalize\ncharacters and ignore case, depending on the collation in\nuse.\n \nStarting from MariaDB 5.5.35 duplicated entries in the ORDER\nBY clause are removed. MySQL 5.6 also removes duplicated\nfields.\n \nORDER BY can also be used to order the activities of a\nDELETE or UPDATE statement (usually with the LIMIT clause). \n \nUntil MariaDB 10.3.1, it was not possible to use ORDER BY\n(or LIMIT) in a multi-table UPDATE statement. This\nrestriction was lifted in MariaDB 10.3.2.\n \nExamples\n-------- \nCREATE TABLE seq (i INT, x VARCHAR(1));\nINSERT INTO seq VALUES (1,\'a\'), (2,\'b\'), (3,\'b\'),\n(4,\'f\'), (5,\'e\');\n \nSELECT * FROM seq ORDER BY i;\n \n+------+------+\n| i | x |\n+------+------+\n| 1 | a |\n| 2 | b |\n| 3 | b |\n| 4 | f |\n| 5 | e |\n+------+------+\n \nSELECT * FROM seq ORDER BY i DESC;\n \n+------+------+\n| i | x |\n+------+------+\n| 5 | e |\n| 4 | f |\n| 3 | b |\n| 2 | b |\n| 1 | a |\n+------+------+\n \nSELECT * FROM seq ORDER BY x,i;\n \n+------+------+\n| i | x |\n+------+------+\n| 1 | a |\n| 2 | b |\n| 3 | b |\n| 5 | e |\n| 4 | f |\n+------+------+\n \nORDER BY in an UPDATE statement, in conjunction with LIMIT:\n \nUPDATE seq SET x=\'z\' WHERE x=\'b\' ORDER BY i DESC LIMIT\n1;\n \nSELECT * FROM seq;\n \n+------+------+\n| i | x |\n+------+------+\n| 1 | a |\n| 2 | b |\n| 3 | z |\n| 4 | f |\n| 5 | e |\n+------+------+\n \nFrom MariaDB 10.3.2, ORDER BY can be used in a multi-table\nupdate:\n \nCREATE TABLE warehouse (product_id INT, qty INT);\nINSERT INTO warehouse VALUES\n(1,100),(2,100),(3,100),(4,100);\n \nCREATE TABLE store (product_id INT, qty INT);\nINSERT INTO store VALUES (1,5),(2,5),(3,5),(4,5);\n \nUPDATE warehouse,store SET warehouse.qty = warehouse.qty-2,\nstore.qty = store.qty+2 \n WHERE (warehouse.product_id = store.product_id AND\nstore.product_id >= 1) \n ORDER BY store.product_id DESC LIMIT 2;\n \nSELECT * FROM warehouse;\n \n+------------+------+\n| product_id | qty |\n+------------+------+\n| 1 | 100 |\n| 2 | 100 |\n| 3 | 98 |\n| 4 | 98 |\n+------------+------+\n \nSELECT * FROM store;\n \n+------------+------+\n| product_id | qty |\n+------------+------+\n| 1 | 5 |\n| 2 | 5 |\n| 3 | 7 |\n| 4 | 7 |\n+------------+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/order-by/','','https://mariadb.com/kb/en/library/order-by/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (431,27,'PROCEDURE','The PROCEDURE clause of SELECT passes the whole result set\nto a Procedure which will process it. These Procedures are\nnot Stored Procedures, and can only be written in the C\nlanguage, so it is necessary to recompile the server.\n \nCurrently, the only available procedure is ANALYSE, which\nexamines the resultset and suggests the optimal datatypes\nfor each column. It is defined in the sql/sql_analyse.cc\nfile, and can be used as an example to create more\nProcedures.\n \nThis clause cannot be used in a view\'s definition.\n \n\n\nURL: https://mariadb.com/kb/en/library/procedure/','','https://mariadb.com/kb/en/library/procedure/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (432,27,'Recursive Common Table Expressions Overview','Recursive Common Table Expressions have been supported since\nMariaDB 10.2.2.\n \nCommon Table Expressions (CTEs) are a standard SQL feature,\nand are essentially temporary named result sets. CTEs first\nappeared in the SQL standard in 1999, and the first\nimplementations began appearing in 2007.\n \nThere are two kinds of CTEs:\nNon-recursive\nRecursive, which this article covers.\n \nSQL is generally poor at recursive structures.\n \nCTEs permit a query to reference itself. A recursive CTE\nwill repeatedly execute subsets of the data until it obtains\nthe complete result set. This makes it particularly useful\nfor handing hierarchical or tree-structured data.\n \nSyntax example\n \nWITH RECURSIVE signifies a recursive CTE. It is given a\nname, followed by a body (the main query) as follows:\n \n\nComputation\n \nGiven the following structure:\n \nFirst execute the anchor part of the query:\n \nNext, execute the recursive part of the query:\n \n\n \n\nSummary so far\n \nwith recursive R as (\n select anchor_data\n union [all]\n select recursive_part\n from R, ...\n)\nselect ...\nCompute anchor_data\nCompute recursive_part to get the new data\nif (new data is non-empty) goto 2;\n \nCAST to avoid truncating data\n \nAs currently implemented by MariaDB and by the SQL Standard,\ndata may be truncated if not correctly cast. It is necessary\nto CAST the column to the correct width if the CTE\'s\nrecursive part produces wider values for a column than the\nCTE\'s nonrecursive part. Some other DBMS give an error in\nthis situation, and MariaDB\'s behavior may change in future\n- see MDEV-12325. See the examples below.\n \nExamples\n-------- \nTransitive closure - determining bus destinations\n \nSample data:\n \nCREATE TABLE bus_routes (origin varchar(50), dst\nvarchar(50));\nINSERT INTO bus_routes VALUES \n (\'New York\', \'Boston\'), \n (\'Boston\', \'New York\'), \n (\'New York\', \'Washington\'), \n (\'Washington\', \'Boston\'), \n (\'Washington\', \'Raleigh\');\n \nNow, we want to return the bus destinations with New York as\nthe origin:\n \nWITH RECURSIVE bus_dst as ( \n SELECT origin as dst FROM bus_routes WHERE origin=\'New\nYork\' \n UNION\n SELECT bus_routes.dst FROM bus_routes, bus_dst WHERE\nbus_dst.dst= bus_routes.origin \n) \nSELECT * FROM bus_dst;\n \n+------------+\n| dst |\n+------------+\n| New York |\n| Boston |\n| Washington |\n| Raleigh |\n+------------+\n \nThe above example is computed as follows:\n \nFirst, the anchor data is calculated:\nStarting from New York\nBoston and Washington are added\n \nNext, the recursive part:\nStarting from Boston and then Washington\nRaleigh is added\nUNION excludes nodes that are already present.\n \nComputing paths - determining bus routes\n \nThis time, we are trying to get bus routes such as “New\nYork -> Washington -> Raleigh”.\n \nUsing the same sample data as the previous example:\n \nWITH RECURSIVE paths (cur_path, cur_dest) AS (\n SELECT origin, origin FROM bus_routes WHERE origin=\'New\nYork\' \n UNION\n SELECT CONCAT(paths.cur_path, \',\', bus_routes.dst),\nbus_routes.dst \n FROM paths, bus_routes \n WHERE paths.cur_dest = bus_routes.origin AND \n LOCATE(bus_routes.dst, paths.cur_path)=0 \n) \nSELECT * FROM paths;\n \n+-----------------------------+------------+\n| cur_path | cur_dest |\n+-----------------------------+------------+\n| New York | New York |\n| New York,Boston | Boston |\n| New York,Washington | Washington |\n| New York,Washington,Boston | Boston |\n| New York,Washington,Raleigh | Raleigh |\n+-----------------------------+------------+\n \nCAST to avoid data truncation\n \nIn the following example, data is truncated because the\nresults are not specifically cast to a wide enough type:\n \nWITH RECURSIVE tbl AS (\n SELECT NULL AS col\n UNION\n SELECT \"THIS NEVER SHOWS UP\" AS col FROM tbl\n)\n+------+\n| col |\n+------+\n| NULL |\n| |\n+------+\n \nExplicitly use CAST to overcome this:\n \nWITH RECURSIVE tbl AS (\n SELECT CAST(NULL AS CHAR(50)) AS col\n UNION SELECT \"THIS NEVER SHOWS UP\" AS col FROM tbl\n) \nSELECT * FROM tbl;\n \n+---------------------+\n| col |\n+---------------------+\n| NULL |\n| THIS NEVER SHOWS UP |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/recursive-common-table-expressions-overview/','','https://mariadb.com/kb/en/library/recursive-common-table-expressions-overview/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (433,27,'REPLACE','Syntax\n------ \nREPLACE [LOW_PRIORITY | DELAYED]\n [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]\n {VALUES | VALUE} ({expr | DEFAULT},...),(...),...\n \nOr:\n \nREPLACE [LOW_PRIORITY | DELAYED]\n [INTO] tbl_name [PARTITION (partition_list)]\n SET col={expr | DEFAULT}, ...\n \nOr:\n \nREPLACE [LOW_PRIORITY | DELAYED]\n [INTO] tbl_name [PARTITION (partition_list)] [(col,...)]\n SELECT ...\n \nDescription\n----------- \n REPLACE works exactly like\n INSERT, except that if an old row in the table\n has the same value as a new row for a PRIMARY KEY or a\n UNIQUE index, the old row is deleted before the new row is\n inserted. If the table has more than one UNIQUE keys, it is\npossible that the new row conflicts with more than one row.\nIn this case, all conflicting rows will be deleted.\n \nThe table name can be specified in the form db_name.tbl_name\nor, if a default database is selected, in the form tbl_name\n(see Identifier Qualifiers). This allows to use REPLACE ...\nSELECT to copy rows between different databases.\n \nBasically it works like this:\n \nBEGIN;\nSELECT 1 FROM t1 WHERE key=# FOR UPDATE;\nIF found-row\n DELETE FROM t1 WHERE key=# ;\n INSERT INTO t1 VALUES (...);\nENDIF\nEND;\n \nThe above can be replaced with:\n \nREPLACE INTO t1 VALUES (...)\n \n REPLACE is a MariaDB/MySQL extension to the SQL standard.\nIt\n either inserts, or deletes and inserts. For other\nMariaDB/MySQL extensions to\n standard SQL --- that also handle duplicate values --- see\nIGNORE and INSERT ON DUPLICATE KEY UPDATE.\n \nNote that unless the table has a PRIMARY KEY or\n UNIQUE index, using a REPLACE statement\nmakes no sense. It becomes equivalent to INSERT, because\nthere is no index to be used to determine whether a new row\nduplicates another.\n \nValues for all columns are taken from the values specified\nin the\n REPLACE statement. Any missing columns are set to their\ndefault values, just as happens for INSERT. You cannot refer\nto values from the current row and use them in the new row.\nIf you use an\nassignment such as \'SET col = col + 1\', the\nreference to the column name on the right hand side is\ntreated as\n DEFAULT(col), so the assignment is equivalent to\n \'SET col = DEFAULT(col) + 1\'.\n \nTo use REPLACE, you must have both the\n INSERT and DELETE privileges\nfor the table.\n \nThere are some gotchas you should be aware of, before using\nREPLACE:\nIf there is an AUTO_INCREMENT field, a new value will be\ngenerated.\nIf there are foreign keys, ON DELETE action will be\nactivated by REPLACE.\nTriggers on DELETE and INSERT will be activated by REPLACE.\n \nTo avoid some of these behaviors, you can use INSERT ... ON\nDUPLICATE KEY UPDATE.\n \nThe PARTITION clause was introduced in MariaDB 10.0. See\nPartition Pruning and Selection for details.\n \nThis statement activates INSERT and DELETE triggers. See\nTrigger Overview for details.\n \n\n\nURL: https://mariadb.com/kb/en/library/replace/','','https://mariadb.com/kb/en/library/replace/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (434,27,'SELECT','Syntax\n------ \nSELECT\n [ALL | DISTINCT | DISTINCTROW]\n [HIGH_PRIORITY]\n [STRAIGHT_JOIN]\n [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]\n [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]\n select_expr [, select_expr ...]\n [ FROM table_references\n [WHERE where_condition]\n [GROUP BY {col_name | expr | position} [ASC | DESC], ...\n[WITH ROLLUP]]\n [HAVING where_condition]\n [ORDER BY {col_name | expr | position} [ASC | DESC], ...]\n [LIMIT {[offset,] row_count | row_count OFFSET offset}]\n [PROCEDURE procedure_name(argument_list)]\n [INTO OUTFILE \'file_name\' [CHARACTER SET charset_name]\n[export_options]\n \nINTO DUMPFILE \'file_name\' | INTO var_name [, var_name] ] |\n\n \n [[FOR UPDATE | LOCK IN SHARE MODE] [WAIT n | NOWAIT] ] ]\n \nexport_options:\n [{FIELDS | COLUMNS}\n [TERMINATED BY \'string\']\n [[OPTIONALLY] ENCLOSED BY \'char\']\n [ESCAPED BY \'char\']\n ]\n [LINES\n [STARTING BY \'string\']\n [TERMINATED BY \'string\']\n ]\n \nDescription\n----------- \nSELECT is used to retrieve rows selected from one or more\ntables, and can include UNION statements and subqueries.\nEach select_expr expression indicates a column or data that\nyou want to retrieve. You\nmust have at least one select expression. See Select\nExpressions below.\n \nThe FROM clause indicates the table or tables from which to\nretrieve rows.\nUse either a single table name or a JOIN expression. See\nJOIN\nfor details. If no table is involved, FROM DUAL can be\nspecified.\n \nThe PARTITION clause was introduced in MariaDB 10.0. See\nPartition Pruning and Selection for details.\nEach table can also be specified as db_name.tabl_name. Each\ncolumn can also be specified as tbl_name.col_name or even\ndb_name.tbl_name.col_name. This allows to write queries\nwhich involve multiple databases. See Identifier Qualifiers\nfor syntax details.\n \nThe WHERE clause, if given, indicates the condition or\n conditions that rows must satisfy to be selected.\n where_condition is an expression that evaluates to true for\n each row to be selected. The statement selects all rows if\nthere is no WHERE\n clause.\nIn the WHERE clause, you can use any of the functions and\n operators that MariaDB supports, except for aggregate\n(summary) functions. See Functions and Operators and\nFunctions and Modifiers for use with GROUP BY (aggregate).\n \nUse the ORDER BY clause to order the results.\n \nUse the LIMIT clause allows you to restrict the results to\nonly\na certain number of rows, optionally with an offset.\n \nUse the GROUP BY and HAVING clauses to group\nrows together when they have columns or computed values in\ncommon.\n \nSELECT can also be used to retrieve rows computed without\nreference to\nany table.\n \nSelect Expressions\n \nA SELECT statement must contain one or more select\nexpressions, separated\nby commas. Each select expression can be one of the\nfollowing:\nThe name of a column.\nAny expression using functions and operators.\n* to select all columns from all tables in the FROM clause.\ntbl_name.* to select all columns from just the table\ntbl_name.\n \nWhen specifying a column, you can either use just the column\nname or qualify the column\nname with the name of the table using tbl_name.col_name. The\nqualified form is\nuseful if you are joining multiple tables in the FROM\nclause. If you do not qualify the\ncolumn names when selecting from multiple tables, MariaDB\nwill try to find the column in\neach table. It is an error if that column name exists in\nmultiple tables.\n \nYou can quote column names using backticks. If you are\nqualifying column names\nwith table names, quote each part separately as\n`tbl_name`.`col_name`.\n \nIf you use any grouping functions\nin any of the select expressions, all rows in your results\nwill be implicitly grouped, as if\nyou had used GROUP BY NULL.\n \nDISTINCT\n \nA query may produce some identical rows. By default, all\nrows are retrieved, even when their values are the same. To\nexplicitly specify that you want to retrieve identical rows,\nuse the ALL option. If you want duplicates to be removed\nfrom the resultset, use the DISTINCT option. DISTINCTROW is\na synonym for DISTINCT. See also COUNT DISTINCT and SELECT\nUNIQUE in Oracle mode.\n \nINTO\n \nThe INTO clause is used to specify that the query results\nshould be written to a file or variable.\nSELECT INTO OUTFILE - formatting and writing the result to\nan external file.\nSELECT INTO DUMPFILE - binary-safe writing of the\nunformatted results to an external file.\nSELECT INTO Variable - selecting and setting variables.\n \nThe reverse of SELECT INTO OUTFILE is LOAD DATA.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \n\nmax_statement_time clause\n \nBy using max_statement_time in conjunction with SET\nSTATEMENT, it is possible to limit the execution time of\nindividual queries. For example:\n \nSET STATEMENT max_statement_time=100 FOR \n SELECT field1 FROM table_name ORDER BY field1;\n \n\n\nURL: https://mariadb.com/kb/en/library/select/','','https://mariadb.com/kb/en/library/select/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (435,27,'SELECT INTO DUMPFILE','Syntax\n------ \nSELECT ... INTO DUMPFILE \'file_path\'\n \nDescription\n----------- \nSELECT ... INTO DUMPFILE is a SELECT clause which writes the\nresultset into a single unformatted row, without any\nseparators, in a file. The results will not be returned to\nthe client.\n \nfile_path can be an absolute path, or a relative path\nstarting from the data directory. It can only be specified\nas a string literal, not as a variable. However, the\nstatement can be dynamically composed and executed as a\nprepared statement to work around this limitation.\n \nThis statement is binary-safe and so is particularly useful\nfor writing BLOB values to file. It can be used, for\nexample, to copy an image or an audio document from the\ndatabase to a file. SELECT ... INTO FILE can be used to save\na text file.\n \nThe file must not exist. It cannot be overwritten. A user\nneeds the FILE privilege to run this statement. Also,\nMariaDB needs permission to write files in the specified\nlocation. If the secure_file_priv system variable is set to\na non-empty directory name, the file can only be written to\nthat directory.\n \nSince MariaDB 5.1, the character_set_filesystem system\nvariable has controlled interpretation of file names that\nare given as literal strings.\n \nExample\n \nSELECT _utf8\'Hello world!\' INTO DUMPFILE \'/tmp/world\';\n \nSELECT LOAD_FILE(\'/tmp/world\') AS world;\n \n+--------------+\n| world |\n+--------------+\n| Hello world! |\n+--------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/select-into-dumpfile/','','https://mariadb.com/kb/en/library/select-into-dumpfile/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (436,27,'SELECT INTO OUTFILE','Syntax\n------ \nSELECT ... INTO OUTFILE \'file_name\'\n [CHARACTER SET charset_name]\n [export_options]\n \nexport_options:\n [{FIELDS | COLUMNS}\n [TERMINATED BY \'string\']\n [[OPTIONALLY] ENCLOSED BY \'char\']\n [ESCAPED BY \'char\']\n ]\n [LINES\n [STARTING BY \'string\']\n [TERMINATED BY \'string\']\n ]\n \nDescription\n----------- \nSELECT INTO OUTFILE writes the resulting rows to a file, and\nallows the use of column and row terminators to specify a\nparticular output format. The default is to terminate fields\nwith tabs (\\t) and lines with newlines (\\n).\n \nThe file must not exist. It cannot be overwritten. A user\nneeds the FILE privilege to run this statement. Also,\nMariaDB needs permission to write files in the specified\nlocation. If the secure_file_priv system variable is set to\na non-empty directory name, the file can only be written to\nthat directory.\n \nThe LOAD DATA INFILE statement complements SELECT INTO\nOUTFILE.\n \nCharacter-sets\n \nThe CHARACTER SET clause specifies the character set in\nwhich the results are to be written. Without the clause, no\nconversion takes place (the binary character set). In this\ncase, if there are multiple character sets, the output will\ncontain these too, and may not easily be able to be\nreloaded.\n \nIn cases where you have two servers using different\ncharacter-sets, using SELECT INTO OUTFILE to transfer data\nfrom one to the other can have unexpected results. To ensure\nthat MariaDB correctly interprets the escape sequences, use\nthe CHARACTER SET clause on both the SELECT INTO OUTFILE\nstatement and the subsequent LOAD DATA INFILE statement.\n \nExample\n \nThe following example produces a file in the CSV format:\n \nSELECT customer_id, firstname, surname INTO OUTFILE\n\'/exportdata/customers.txt\'\n FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'\"\'\n LINES TERMINATED BY \'\\n\'\n FROM customers;\n \n\n\nURL: https://mariadb.com/kb/en/library/select-into-outfile/','','https://mariadb.com/kb/en/library/select-into-outfile/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (437,27,'SELECT WITH ROLLUP','Syntax\n------ \nSee SELECT for the full syntax.\n \nDescription\n----------- \nThe WITH ROLLUP modifier adds extra rows to the resultset\nthat represent super-aggregate summaries. The\nsuper-aggregated column is represented by a NULL value.\nMultiple aggregates over different columns will be added if\nthere are multiple GROUP BY columns.\n \nThe LIMIT clause can be used at the same time, and is\napplied after the WITH ROLLUP rows have been added.\n \nWITH ROLLUP cannot be used with ORDER BY. Some sorting is\nstill possible by using ASC or DESC clauses with the GROUP\nBY column, although the super-aggregate rows will always be\nadded last.\n \nExamples\n-------- \nThese examples use the following sample table\n \nCREATE TABLE booksales ( \n country VARCHAR(35), genre\nENUM(\'fiction\',\'non-fiction\'), year YEAR, sales INT);\n \nINSERT INTO booksales VALUES\n (\'Senegal\',\'fiction\',2014,12234),\n(\'Senegal\',\'fiction\',2015,15647),\n (\'Senegal\',\'non-fiction\',2014,64980),\n(\'Senegal\',\'non-fiction\',2015,78901),\n (\'Paraguay\',\'fiction\',2014,87970),\n(\'Paraguay\',\'fiction\',2015,76940),\n (\'Paraguay\',\'non-fiction\',2014,8760),\n(\'Paraguay\',\'non-fiction\',2015,9030);\n \nThe addition of the WITH ROLLUP modifier in this example\nadds an extra row that aggregates both years:\n \nSELECT year, SUM(sales) FROM booksales GROUP BY year;\n \n+------+------------+\n| year | SUM(sales) |\n+------+------------+\n| 2014 | 173944 |\n| 2015 | 180518 |\n+------+------------+\n2 rows in set (0.08 sec)\n \nSELECT year, SUM(sales) FROM booksales GROUP BY year WITH\nROLLUP;\n \n+------+------------+\n| year | SUM(sales) |\n+------+------------+\n| 2014 | 173944 |\n| 2015 | 180518 |\n| NULL | 354462 |\n+------+------------+\n \nIn the following example, each time the genre, the year or\nthe country change, another super-aggregate row is added:\n \nSELECT country, year, genre, SUM(sales) \n FROM booksales GROUP BY country, year, genre;\n \n+----------+------+-------------+------------+\n| country | year | genre | SUM(sales) |\n+----------+------+-------------+------------+\n| Paraguay | 2014 | fiction | 87970 |\n| Paraguay | 2014 | non-fiction | 8760 |\n| Paraguay | 2015 | fiction | 76940 |\n| Paraguay | 2015 | non-fiction | 9030 |\n| Senegal | 2014 | fiction | 12234 |\n| Senegal | 2014 | non-fiction | 64980 |\n| Senegal | 2015 | fiction | 15647 |\n| Senegal | 2015 | non-fiction | 78901 |\n+----------+------+-------------+------------+\n \nSELECT country, year, genre, SUM(sales) \n FROM booksales GROUP BY country, year, genre WITH ROLLUP;\n \n+----------+------+-------------+------------+\n| country | year | genre | SUM(sales) |\n+----------+------+-------------+------------+\n| Paraguay | 2014 | fiction | 87970 |\n| Paraguay | 2014 | non-fiction | 8760 |\n| Paraguay | 2014 | NULL | 96730 |\n| Paraguay | 2015 | fiction | 76940 |\n| Paraguay | 2015 | non-fiction | 9030 |\n| Paraguay | 2015 | NULL | 85970 |\n| Paraguay | NULL | NULL | 182700 |\n| Senegal | 2014 | fiction | 12234 |\n| Senegal | 2014 | non-fiction | 64980 |\n| Senegal | 2014 | NULL | 77214 |\n| Senegal | 2015 | fiction | 15647 |\n| Senegal | 2015 | non-fiction | 78901 |\n| Senegal | 2015 | NULL | 94548 |\n| Senegal | NULL | NULL | 171762 |\n| NULL | NULL | NULL | 354462 |\n+----------+------+-------------+------------+\n \nThe LIMIT clause, applied after WITH ROLLUP:\n \nSELECT country, year, genre, SUM(sales) \n FROM booksales GROUP BY country, year, genre WITH ROLLUP\nLIMIT 4;\n \n+----------+------+-------------+------------+\n| country | year | genre | SUM(sales) |\n+----------+------+-------------+------------+\n| Paraguay | 2014 | fiction | 87970 |\n| Paraguay | 2014 | non-fiction | 8760 |\n| Paraguay | 2014 | NULL | 96730 |\n| Paraguay | 2015 | fiction | 76940 |\n+----------+------+-------------+------------+\n \nSorting by year descending:\n \nSELECT country, year, genre, SUM(sales) \n FROM booksales GROUP BY country, year DESC, genre WITH\nROLLUP;\n \n+----------+------+-------------+------------+\n| country | year | genre | SUM(sales) |\n+----------+------+-------------+------------+\n| Paraguay | 2015 | fiction | 76940 |\n| Paraguay | 2015 | non-fiction | 9030 |\n| Paraguay | 2015 | NULL | 85970 |\n| Paraguay | 2014 | fiction | 87970 |\n| Paraguay | 2014 | non-fiction | 8760 |\n| Paraguay | 2014 | NULL | 96730 |\n| Paraguay | NULL | NULL | 182700 |\n| Senegal | 2015 | fiction | 15647 |\n| Senegal | 2015 | non-fiction | 78901 |\n| Senegal | 2015 | NULL | 94548 |\n| Senegal | 2014 | fiction | 12234 |\n| Senegal | 2014 | non-fiction | 64980 |\n| Senegal | 2014 | NULL | 77214 |\n| Senegal | NULL | NULL | 171762 |\n| NULL | NULL | NULL | 354462 |\n+----------+------+-------------+------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/select-with-rollup/','','https://mariadb.com/kb/en/library/select-with-rollup/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (438,27,'UNION','UNION is used to combine the results from multiple SELECT\nstatements into a single result set.\n \nSyntax\n------ \nSELECT ...\nUNION [ALL | DISTINCT] SELECT ...\n[UNION [ALL | DISTINCT] SELECT ...]\n[ORDER BY [column [, column ...]]]\n[LIMIT {[offset,] row_count | row_count OFFSET offset}]\n \nDescription\n----------- \nUNION is used to combine the results from multiple SELECT\nstatements into a single result set.\n \nThe column names from the first SELECT statement are used as\nthe column names for the results returned. Selected columns\nlisted in corresponding positions of each SELECT statement\nshould have the same data type. (For example, the first\ncolumn selected by the first statement should have the same\ntype as the first column selected by the other statements.)\n \nIf they don\'t, the type and length of the columns in the\nresult take into account the values returned by all of the\nSELECTs, so there is no need for explicit casting. Note that\ncurrently this is not the case for recursive CTEs - see\nMDEV-12325.\n \nTable names can be specified as db_name.tbl_name. This\npermits writing UNIONs which involve multiple databases. See\nIdentifier Qualifiers for syntax details.\n \nUNION queries cannot be used with aggregate functions.\n \nALL/DISTINCT\n \nThe ALL keyword causes duplicate rows to be preserved. The\nDISTINCT keyword (the default if the keyword is omitted)\ncauses duplicate rows to be removed by the results.\n \nUNION ALL and UNION DISTINCT can both be present in a query.\nIn this case, UNION DISTINCT will override any UNION ALLs to\nits left.\n \nUntil MariaDB 10.1.1, all UNION ALL statements required the\nserver to create a temporary table. Since MariaDB 10.1.1,\nthe server can in most cases execute UNION ALL without\ncreating a temporary table, improving performance (see\nMDEV-334).\n \nORDER BY and LIMIT\n \nIndividual SELECTs can contain their own ORDER BY and LIMIT\nclauses. In this case, the individual queries need to be\nwrapped between parentheses. However, this does not affect\nthe order of the UNION, so they only are useful to limit the\nrecord read by one SELECT.\n \nThe UNION can have global ORDER BY and LIMIT clauses, which\naffect the whole resultset. If the columns retrieved by\nindividual SELECT statements have an alias (AS), the ORDER\nBY must use that alias, not the real column names.\n \nHIGH_PRIORITY\n \nSpecifying a query as HIGH_PRIORITY will not work inside a\nUNION. If applied to the first SELECT, it will be ignored.\nApplying to a later SELECT results in a syntax error:\n \nERROR 1234 (42000): Incorrect usage/placement of\n\'HIGH_PRIORITY\'\n \nSELECT ... INTO ...\n \nIndividual SELECTs cannot be written INTO DUMPFILE or INTO\nOUTFILE. If the last SELECT statement specifies INTO\nDUMPFILE or INTO OUTFILE, the entire result of the UNION\nwill be written. Placing the clause after any other SELECT\nwill result in a syntax error.\n \nIf the result is a single row, SELECT ... INTO @var_name can\nalso be used.\n \n\nParentheses\n \nFrom MariaDB 10.4.0, parentheses can be used to specify\nprecedence. Before this, a syntax error would be returned.\n \nExamples\n-------- \nUNION between tables having different column names:\n \n(SELECT e_name AS name, email FROM employees)\nUNION\n(SELECT c_name AS name, email FROM customers);\n \nSpecifying the UNION\'s global order and limiting total\nrows:\n \n(SELECT name, email FROM employees)\nUNION\n(SELECT name, email FROM customers)\nORDER BY name LIMIT 10;\n \nAdding a constant row:\n \n(SELECT \'John Doe\' AS name, \'john.doe@example.net\' AS\nemail)\nUNION\n(SELECT name, email FROM customers);\n \nDiffering types:\n \nSELECT CAST(\'x\' AS CHAR(1)) UNION SELECT REPEAT(\'y\',4);\n+----------------------+\n| CAST(\'x\' AS CHAR(1)) |\n+----------------------+\n| x |\n| yyyy |\n+----------------------+\n \nReturning the results in order of each individual SELECT by\nuse of a sort column:\n \n(SELECT 1 AS sort_column, e_name AS name, email FROM\nemployees)\nUNION\n(SELECT 2, c_name AS name, email FROM customers) ORDER BY\nsort_column;\n \nDifference between UNION, EXCEPT and INTERSECT:\n \nCREATE TABLE seqs (i INT);\nINSERT INTO seqs VALUES (1),(2),(3),(4),(5),(6);\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 5 |\n| 6 |\n+------+\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 1 |\n| 2 |\n+------+\n \nSELECT i FROM seqs WHERE i =3;\n \n+------+\n| i |\n+------+\n| 3 |\n+------+\n \nParentheses for specifying precedence, from MariaDB 10.4.0\n \nCREATE OR REPLACE TABLE t1 (a INT);\nCREATE OR REPLACE TABLE t2 (b INT);\nCREATE OR REPLACE TABLE t3 (c INT);\n \nINSERT INTO t1 VALUES (1),(2),(3),(4);\nINSERT INTO t2 VALUES (5),(6);\nINSERT INTO t3 VALUES (1),(6);\n \n((SELECT a FROM t1) UNION (SELECT b FROM t2)) INTERSECT\n(SELECT c FROM t3);\n+------+\n| a |\n+------+\n| 1 |\n| 6 |\n+------+\n \n(SELECT a FROM t1) UNION ((SELECT b FROM t2) INTERSECT\n(SELECT c FROM t3));\n+------+\n| a |\n+------+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n| 6 |\n+------+\n \n\n\nURL: https://mariadb.com/kb/en/library/union/','','https://mariadb.com/kb/en/library/union/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (439,27,'UPDATE','Syntax\n------ \nSingle-table syntax:\n \nUPDATE [LOW_PRIORITY] [IGNORE] table_reference \n [PARTITION (partition_list)]\n SET col1={expr1|DEFAULT} [,col2={expr2|DEFAULT}] ...\n [WHERE where_condition]\n [ORDER BY ...]\n [LIMIT row_count]\n \nMultiple-table syntax:\n \nUPDATE [LOW_PRIORITY] [IGNORE] table_references\n SET col1={expr1|DEFAULT} [, col2={expr2|DEFAULT}] ...\n [WHERE where_condition]\n \nDescription\n----------- \nFor the single-table syntax, the UPDATE statement updates\ncolumns of existing rows in the named table with new values.\nThe\nSET clause indicates which columns to modify and the values\nthey should be given. Each value can be given as an\nexpression, or the keyword\nDEFAULT to set a column explicitly to its default value. The\nWHERE clause, if given, specifies the conditions that\nidentify\nwhich rows to update. With no WHERE clause, all rows are\nupdated. If the ORDER BY clause is specified, the rows are\nupdated in the order that is specified. The LIMIT clause\nplaces a limit on the number of rows that can be updated.\n \nThe PARTITION clause was introduced in MariaDB 10.0. See\nPartition Pruning and Selection for details.\n \nUntil MariaDB 10.3.2, for the multiple-table syntax, UPDATE\nupdates rows in each\ntable named in table_references that satisfy the conditions.\nIn this case,\nORDER BY and LIMIT cannot be used. This restriction was\nlifted in MariaDB 10.3.2 and both clauses can be used with\nmultiple-table updates. An UPDATE can also reference tables\nwhich are located in different databases; see Identifier\nQualifiers for the syntax.\n \nwhere_condition is an expression that evaluates to true for\neach row to be updated.\n \ntable_references and where_condition are as\nspecified as described in SELECT.\n \nAssignments are evaluated in left-to-right order, unless the\nSIMULTANEOUS_ASSIGNMENT sql_mode (available from MariaDB\n10.3.5) is set, in which case the UPDATE statement evaluates\nall assignments simultaneously. \n \nYou need the UPDATE privilege only for columns referenced in\nan UPDATE that are actually updated. You need only the\nSELECT privilege for any columns that are read but\nnot modified. See GRANT.\n \nThe UPDATE statement supports the following modifiers:\nIf you use the LOW_PRIORITY keyword, execution of\n the UPDATE is delayed until no other clients are reading\nfrom\n the table. This affects only storage engines that use only\ntable-level\n locking (MyISAM, MEMORY, MERGE). See HIGH_PRIORITY and\nLOW_PRIORITY clauses for details.\nIf you use the IGNORE keyword, the update statement does \n not abort even if errors occur during the update. Rows for\nwhich\n duplicate-key conflicts occur are not updated. Rows for\nwhich columns are\n updated to values that would cause data conversion errors\nare updated to the\n closest valid values instead.\n \nUPDATE Statements With the Same Source and Target\n \nFrom MariaDB 10.3.2, UPDATE statements may have the same\nsource and target.\n \nFor example, given the following table:\n \nDROP TABLE t1;\n \nCREATE TABLE t1 (c1 INT, c2 INT);\nINSERT INTO t1 VALUES (10,10), (20,20);\n \nUntil MariaDB 10.3.1, the following UPDATE statement would\nnot work:\n \nUPDATE t1 SET c1=c1+1 WHERE c2=(SELECT MAX(c2) FROM t1);\nERROR 1093 (HY000): Table \'t1\' is specified twice, \n both as a target for \'UPDATE\' and as a separate source\nfor data\n \nFrom MariaDB 10.3.2, the statement executes successfully:\n \nUPDATE t1 SET c1=c1+1 WHERE c2=(SELECT MAX(c2) FROM t1);\n \nSELECT * FROM t1;\n \n+------+------+\n| c1 | c2 |\n+------+------+\n| 10 | 10 |\n| 21 | 20 |\n+------+------+\n \nExample\n \nSingle-table syntax:\n \nUPDATE table_name SET column1 = value1, column2 = value2\nWHERE id=100;\n \nMultiple-table syntax:\n \nUPDATE tab1, tab2 SET tab1.column1 = value1, tab1.column2 =\nvalue2 WHERE tab1.id = tab2.id;\n \n\n\nURL: https://mariadb.com/kb/en/library/update/','','https://mariadb.com/kb/en/library/update/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (440,27,'WITH','The WITH keyword signifies a Common Table Expression (CTE).\nIt allows you to refer to a subquery expression many times\nin a query, as if having a temporary table that only exists\nfor the duration of a query.\n \nThere are two kinds of CTEs:\nNon-Recursive\nRecursive\n \nCommon Table Expression WITH was introduced in MariaDB\n10.2.1.\n \nRecursive WITH has been supported since MariaDB 10.2.2.\n \nSyntax\n------ \nWITH [RECURSIVE] table_reference as (SELECT ...)\n SELECT ...\n \nYou can use table_reference as any normal table in the\nexternal SELECT part. You can also use WITH in sub queries.\nWITH can also be used with EXPLAIN and SELECT.\n \nBelow is an example with the WITH at the top level:\n \nWITH t AS (SELECT a FROM t1 WHERE b >= \'c\') \n SELECT * FROM t2, t WHERE t2.c = t.a;\n \nThe example below uses WITH in a subquery:\n \nSELECT t1.a, t1.b FROM t1, t2\n WHERE t1.a > t2.c \n AND t2.c IN(WITH t AS (SELECT * FROM t1 WHERE t1.a \n\nURL: https://mariadb.com/kb/en/library/with/','','https://mariadb.com/kb/en/library/with/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (441,28,'DESCRIBE','Syntax\n------ \n{DESCRIBE | DESC} tbl_name [col_name | wild]\n \nDescription\n----------- \nDESCRIBE provides information about the columns in a table.\nIt is a shortcut for SHOW COLUMNS FROM.\nThese statements also display information for views.\n \ncol_name can be a column name, or a string containing the\nSQL \"%\" and \"_\" wildcard characters to\nobtain output only for the columns with names matching the\nstring. There is no\nneed to enclose the string within quotes unless it contains\nspaces or other\nspecial characters.\n \nDESCRIBE city;\n \n+------------+----------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+----------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| Name | char(35) | YES | | NULL | |\n| Country | char(3) | NO | UNI | | |\n| District | char(20) | YES | MUL | | |\n| Population | int(11) | YES | | NULL | |\n+------------+----------+------+-----+---------+----------------+\n \nThe description for SHOW COLUMNS provides\nmore information about the output columns.\n \n\n\nURL: https://mariadb.com/kb/en/library/describe/','','https://mariadb.com/kb/en/library/describe/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (442,28,'EXPLAIN','Syntax\n------ \nEXPLAIN tbl_name\n \nOr\n \nEXPLAIN [EXTENDED | PARTITIONS] \n {SELECT select_options | UPDATE update_options | DELETE\ndelete_options}\n \nDescription\n----------- \nThe EXPLAIN statement can be used either as a synonym for\nDESCRIBE or as a way to obtain information about how MariaDB\nexecutes a SELECT (as well as UPDATE and DELETE since\nMariaDB 10.0.5) statement:\n\'EXPLAIN tbl_name\' is synonymous with \n \'DESCRIBE tbl_name\' or \n \'SHOW COLUMNS FROM tbl_name\'.\nWhen you precede a SELECT statement (or, since MariaDB\n10.0.5, an UPDATE or a DELETE as well) with the keyword \n EXPLAIN, MariaDB displays information from the optimizer\n about the query execution plan. That is, MariaDB explains\nhow it would\n process the SELECT, UPDATE or DELETE, including information\nabout how tables\n are joined and in which order. EXPLAIN EXTENDED can be\n used to provide additional information.\nEXPLAIN PARTITIONS has been available since MySQL 5.1.5. It\nis useful only when examining queries involving partitioned\ntables. For details, see Partition pruning and selection.\nANALYZE statement, which performs the query as well as\nproducing EXPLAIN output, and provides actual as well as\nestimated statistics, has been available from MariaDB\n10.1.0.\nSince MariaDB 10.0.5, it has been possible to have EXPLAIN\noutput printed in the slow query log. See EXPLAIN in the\nSlow Query Log for details.\n \nSince MariaDB 10.0, SHOW EXPLAIN shows the output of a\nrunning statement. In some cases, its output can be closer\nto reality than EXPLAIN.\n \nSince MariaDB 10.1, the ANALYZE statement runs a statement\nand returns information about its execution plan. It also\nshows additional columns, to check how much the optimizer\'s\nestimation about filtering and found rows are close to\nreality.\n \nThere is an online EXPLAIN Analyzer that you can use to\nshare EXPLAIN and EXPLAIN EXTENDED output with others.\n \nEXPLAIN can acquire metadata locks in the same way that\nSELECT does, as it needs to know table metadata and,\nsometimes, data as well.\n \nThe columns in EXPLAIN ... SELECT\n \nColumn name | Description | \n \nid | Sequence number that shows in which order tables are\njoined. | \n \nselect_type | What kind of SELECT the table comes from. | \n \ntable | Alias name of table. Materialized temporary tables\nfor sub queries are named | \n \ntype | How rows are found from the table (join type). | \n \npossible_keys | keys in table that could be used to find\nrows in the table | \n \nkey | The name of the key that is used to retrieve rows.\nNULL is no key was used. | \n \nkey_len | How many bytes of the key that was used (shows if\nwe are using only parts of the multi-column key). | \n \nref | The reference that is used to as the key value. | \n \nrows | An estimate of how many rows we will find in the\ntable for each key lookup. | \n \nExtra | Extra information about this join. | \n \nHere are descriptions of the values for some of the more\ncomplex columns in EXPLAIN ... SELECT:\n \n\"select_type\" column\n \nThe select_type column can have the following values:\n \nValue | Description | \n \nDEPENDENT SUBQUERY | The SUBQUERY is DEPENDENT. | \n \nDEPENDENT UNION | The UNION is DEPENDENT. | \n \nDERIVED | The SELECT is DERIVED from the PRIMARY. | \n \nMATERIALIZED | The SUBQUERY is MATERIALIZED. | \n \nPRIMARY | The SELECT is a PRIMARY one. | \n \nSIMPLE | The SELECT is a SIMPLE one. | \n \nSUBQUERY | The SELECT is a SUBQUERY of the PRIMARY. | \n \nUNCACHEABLE SUBQUERY | The SUBQUERY is UNCACHEABLE. | \n \nUNCACHEABLE UNION | The UNION is UNCACHEABLE. | \n \nUNION | The SELECT is a UNION of the PRIMARY. | \n \nUNION RESULT | The result of the UNION. | \n \n\"Type\" column\n \nThis column contains information on how the table is\naccessed.\n \nValue | Description | \n \nALL | A full table scan is done for the table (all rows are\nread). This is bad if the table is large and the table is\njoined against a previous table! This happens when the\noptimizer could not find any usable index to access rows. | \n \nconst | There is only one possibly matching row in the\ntable. The row is read before the optimization phase and all\ncolumns in the table are treated as constants. | \n \neq_ref | A unique index is used to find the rows. This is\nthe best possible plan to find the row. | \n \nfulltext | A fulltext index is used to access the rows. | \n \nindex_merge | A \'range\' access is done for for several\nindex and the found rows are merged. The key column shows\nwhich keys are used. | \n \nindex_subquery | This is similar as ref, but used for sub\nqueries that are transformed to key lookups. | \n \nindex | A full scan over the used index. Better than ALL but\nstill bad if index is large and the table is joined against\na previous table. | \n \nrange | The table will be accessed with a key over one or\nmore value ranges. | \n \nref_or_null | Like \'ref\' but in addition another search\nfor the \'null\' value is done if the first value was not\nfound. This happens usually with sub queries. | \n \nref | A non unique index or prefix of an unique index is\nused to find the rows. Good if the prefix doesn\'t match\nmany rows. | \n \nsystem | The table has 0 or 1 rows. | \n \nunique_subquery | This is similar as eq_ref, but used for\nsub queries that are transformed to key lookups | \n \n\"Extra\" column\n \nThis column consists of one or more of the following values,\nseparated by \';\'\n \n Note that some of these values are detected after the\noptimization phase.\n \nThe optimization phase can do the following changes to the\nWHERE clause:\nAdd the expressions from the ON and USING clauses to the\nWHERE\n clause.\nConstant propagation: If there is column=constant, replace\nall column\n instances with this constant.\nReplace all columns from \'const\' tables with their values.\nRemove the used key columns from the WHERE (as this will be\ntested as\n part of the key lookup).\nRemove impossible constant sub expressions.\n For example WHERE \'(a=1 and a=2) OR b=1\' becomes \'b=1\'.\nReplace columns with other columns that has identical\nvalues:\n Example: WHERE a=b and a=c may be treated\n as \'WHERE a=b and a=c and b=c\'.\nAdd extra conditions to detect impossible row conditions\nearlier. This\n happens mainly with OUTER JOIN where we in some cases add\ndetection\n of NULL values in the WHERE (Part of \'Not exists\'\noptimization).\n This can cause an unexpected \'Using where\' in the Extra\ncolumn.\nFor each table level we remove expressions that have already\nbeen tested when\n we read the previous row. Example: When joining tables t1\nwith t2\n using the following WHERE \'t1.a=1 and t1.a=t2.b\', we\ndon\'t have to\n test \'t1.a=1\' when checking rows in t2 as we already know\nthat this\n expression is true. \n \nValue | Description | \n \nconst row not found | The table was a system table (a table\nwith should exactly one row), but no row was found. | \n \nDistinct | If distinct optimization (remove duplicates) was\nused. This is marked only for the last table in the SELECT.\n| \n \nFull scan on NULL key | The table is a part of the sub query\nand if the value that is used to match the sub query will be\nNULL, we will do a full table scan. | \n \nImpossible HAVING | The used HAVING clause is always false\nso the SELECT will return no rows. | \n \nImpossible WHERE noticed after reading const tables. | The\nused WHERE clause is always false so the SELECT will return\nno rows. This case was detected after we had read all\n\'const\' tables and used the column values as constant in\nthe WHERE clause. For example: WHERE const_column=5 and\nconst_column had a value of 4. | \n \nImpossible WHERE | The used WHERE clause is always false so\nthe SELECT will return no rows. For example: WHERE 1=2 | \n \nNo matching min/max row | During early optimization of\nMIN()/MAX() values it was detected that no row could match\nthe WHERE clause. The MIN()/MAX() function will return NULL.\n| \n \nno matching row in const table | The table was a const table\n(a table with only one possible matching row), but no row\nwas found. | \n \nNo tables used | The SELECT was a sub query that did not use\nany tables. For example a there was no FROM clause or a FROM\nDUAL clause. | \n \nNot exists | Stop searching after more row if we find one\nsingle matching row. This optimization is used with LEFT\nJOIN where one is explicitly searching for rows that\ndoesn\'t exists in the LEFT JOIN TABLE. Example: SELECT *\nFROM t1 LEFT JOIN t2 on (...) WHERE t2.not_null_column IS\nNULL. As t2.not_null_column can only be NULL if there was no\nmatching row for on condition, we can stop searching if we\nfind a single matching row. | \n \nOpen_frm_only | For information_schema tables. Only the frm\n(table definition file was opened) was opened for each\nmatching row. | \n \nOpen_full_table | For information_schema tables. A full\ntable open for each matching row is done to retrieve the\nrequested information. (Slow) | \n \nOpen_trigger_only | For information_schema tables. Only the\ntrigger file definition was opened for each matching row. | \n \nRange checked for each record (index map: ...) | This only\nhappens when there was no good default index to use but\nthere may some index that could be used when we can treat\nall columns from previous table as constants. For each row\ncombination the optimizer will decide which index to use (if\nany) to fetch a row from this table. This is not fast, but\nfaster than a full table scan that is the only other choice.\nThe index map is a bitmask that shows which index are\nconsidered for each row condition. | \n \nScanned 0/1/all databases | For information_schema tables.\nShows how many times we had to do a directory scan. | \n \nSelect tables optimized away | All tables in the join was\noptimized away. This happens when we are only using\nCOUNT(*), MIN() and MAX() functions in the SELECT and we\nwhere able to replace all of these with constants. | \n \nSkip_open_table | For information_schema tables. The queried\ntable didn\'t need to be opened. | \n \nunique row not found | The table was detected to be a const\ntable (a table with only one possible matching row) during\nthe early optimization phase, but no row was found. | \n \nUsing filesort | Filesort is needed to resolve the query.\nThis means an extra phase where we first collect all columns\nto sort, sort them with a disk based merge sort and then use\nthe sorted set to retrieve the rows in sorted order. If the\ncolumn set is small, we store all the columns in the sort\nfile to not have to go to the database to retrieve them\nagain. | \n \nUsing index | Only the index is used to retrieve the needed\ninformation from the table. There is no need to perform an\nextra seek to retrieve the actual record. | \n \nUsing index condition | Like \'Using where\' but the where\ncondition is pushed down to the table engine for internal\noptimization at the index level. | \n \nUsing index condition(BKA) | Like \'Using index condition\'\nbut in addition we use batch key access to retrieve rows. | \n \nUsing index for group-by | The index is being used to\nresolve a GROUP BY or DISTINCT query. The rows are not read.\nThis is very efficient if the table has a lot of identical\nindex entries as duplicates are quickly jumped over. | \n \nUsing intersect(...) | For index_merge joins. Shows which\nindex are part of the intersect. | \n \nUsing join buffer | We store previous row combinations in a\nrow buffer to be able to match each row against all of the\nrows combinations in the join buffer at one go. | \n \nUsing sort_union(...) | For index_merge joins. Shows which\nindex are part of the union. | \n \nUsing temporary | A temporary table is created to hold the\nresult. This typically happens if you are using GROUP BY,\nDISTINCT or ORDER BY. | \n \nUsing where | A WHERE expression (in additional to the\npossible key lookup) is used to check if the row should be\naccepted. If you don\'t have \'Using where\' together with a\njoin type of ALL, you are probably doing something wrong! | \n \nUsing where with pushed condition | Like \'Using where\' but\nthe where condition is pushed down to the table engine for\ninternal optimization at the row level. | \n \nUsing buffer | The UPDATE statement will first buffer the\nrows, and then run the updates, rather than do updates on\nthe fly. See Using Buffer UPDATE Algorithm for a detailed\nexplanation. | \n \nEXPLAIN EXTENDED\n \nThe EXTENDED keyword adds another column, filtered, to the\noutput. This is a percentage estimate of the table rows that\nwill be filtered by the condition.\n \nAn EXPLAIN EXTENDED will always throw a warning, as it adds\nextra Message information to a subsequent SHOW WARNINGS\nstatement. This includes what the SELECT query would look\nlike after optimizing and rewriting rules are applied and\nhow the optimizer qualifies columns and tables.\n \nExamples\n-------- \nAs synonym for DESCRIBE or SHOW COLUMNS FROM:\n \nDESCRIBE city;\n \n+------------+----------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+------------+----------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n| Name | char(35) | YES | | NULL | |\n| Country | char(3) | NO | UNI | | |\n| District | char(20) | YES | MUL | | |\n| Population | int(11) | YES | | NULL | |\n+------------+----------+------+-----+---------+----------------+\n \nA simple set of examples to see how EXPLAIN can identify\npoor index usage:\n \nCREATE TABLE IF NOT EXISTS `employees_example` (\n `id` int(11) NOT NULL AUTO_INCREMENT,\n `first_name` varchar(30) NOT NULL,\n `last_name` varchar(40) NOT NULL,\n `position` varchar(25) NOT NULL,\n `home_address` varchar(50) NOT NULL,\n `home_phone` varchar(12) NOT NULL,\n `employee_code` varchar(25) NOT NULL,\n PRIMARY KEY (`id`),\n UNIQUE KEY `employee_code` (`employee_code`),\n KEY `first_name` (`first_name`,`last_name`)\n) ENGINE=Aria;\n \nINSERT INTO `employees_example` (`first_name`, `last_name`,\n`position`, `home_address`, `home_phone`, `employee_code`)\n VALUES\n (\'Mustapha\', \'Mond\', \'Chief Executive Officer\', \'692\nPromiscuous Plaza\', \'326-555-3492\', \'MM1\'),\n (\'Henry\', \'Foster\', \'Store Manager\', \'314 Savage\nCircle\', \'326-555-3847\', \'HF1\'),\n (\'Bernard\', \'Marx\', \'Cashier\', \'1240 Ambient\nAvenue\', \'326-555-8456\', \'BM1\'),\n (\'Lenina\', \'Crowne\', \'Cashier\', \'281 Bumblepuppy\nBoulevard\', \'328-555-2349\', \'LC1\'),\n (\'Fanny\', \'Crowne\', \'Restocker\', \'1023 Bokanovsky\nLane\', \'326-555-6329\', \'FC1\'),\n (\'Helmholtz\', \'Watson\', \'Janitor\', \'944 Soma\nCourt\', \'329-555-2478\', \'HW1\');\n \nSHOW INDEXES FROM employees_example;\n \n+-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+\n| Table | Non_unique | Key_name | Seq_in_index | Column_name\n| Collation | Cardinality | Sub_part | Packed | Null |\nIndex_type | Comment | Index_comment |\n+-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+\n| employees_example | 0 | PRIMARY | 1 | id | A | 7 | NULL |\nNULL | | BTREE | | |\n| employees_example | 0 | employee_code | 1 | employee_code\n| A | 7 | NULL | NULL | | BTREE | | |\n| employees_example | 1 | first_name | 1 | first_name | A |\nNULL | NULL | NULL | | BTREE | | |\n| employees_example | 1 | first_name | 2 | last_name | A |\nNULL | NULL | NULL | | BTREE | | |\n+-------------------+------------+---------------+--------------+---------------+-----------+-------------+----------+--------+------+------------+---------+---------------+\n \nSELECT on a primary key:\n \nEXPLAIN SELECT * FROM employees_example WHERE id=1;\n \n+------+-------------+-------------------+-------+---------------+---------+---------+-------+------+-------+\n| id | select_type | table | type | possible_keys | key |\nkey_len | ref | rows | Extra |\n+------+-------------+-------------------+-------+---------------+---------+---------+-------+------+-------+\n| 1 | SIMPLE | employees_example | const | PRIMARY | PRIMARY\n| 4 | const | 1 | |\n+------+-------------+-------------------+-------+---------------+---------+---------+-------+------+-------+\n \nThe type is const, which means that only one possible result\ncould be returned. \nNow, returning the same record but searching by their phone\nnumber:\n \nEXPLAIN SELECT * FROM employees_example WHERE\nhome_phone=\'326-555-3492\';\n \n+------+-------------+-------------------+------+---------------+------+---------+------+------+-------------+\n| id | select_type | table | type | possible_keys | key |\nkey_len | ref | rows | Extra |\n+------+-------------+-------------------+------+---------------+------+---------+------+------+-------------+\n| 1 | SIMPLE | employees_example | ALL | NULL | NULL | NULL\n| NULL | 6 | Using where |\n+------+-------------+-------------------+------+---------------+------+---------+------+------+-------------+\n \nHere, the type is All, which means no index could be used.\nLooking at the rows count, a full table scan (all six rows)\nhad to be performed in order to retrieve the record. If\nit\'s a requirement to search by phone number, an index will\nhave to be created.\n \nSHOW EXPLAIN example:\n \nSHOW EXPLAIN FOR 1;\n \n+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+\n| id | select_type | table | type | possible_keys | key |\nkey_len | ref | rows | Extra |\n+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+\n| 1 | SIMPLE | tbl | index | NULL | a | 5 | NULL | 1000107 |\nUsing index |\n+------+-------------+-------+-------+---------------+------+---------+------+---------+-------------+\n1 row in set, 1 warning (0.00 sec)\n \nExample of ref_or_null optimization\n \nSELECT * FROM table_name\n WHERE key_column=expr OR key_column IS NULL;\n \nref_or_null is something that often happens when you use\nsubqueries with NOT IN as then one has to do an extra check\nfor NULL values if the first value didn\'t have a matching\nrow. \n \n\n\nURL: https://mariadb.com/kb/en/library/explain/','','https://mariadb.com/kb/en/library/explain/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (443,28,'EXPLAIN ANALYZE','The syntax for the EXPLAIN ANALYZE feature was changed to\nANALYZE statement, available since MariaDB 10.1.0. See\nANALYZE statement. \n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/explain-analyze/','','https://mariadb.com/kb/en/library/explain-analyze/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (444,28,'ANALYZE FORMAT=JSON','ANALYZE FORMAT=JSON is a mix of the EXPLAIN FORMAT=JSON and\nANALYZE statement features. ANALYZE FORMAT=JSON $statement\nwill execute $statement, and then print the output of\nEXPLAIN FORMAT=JSON, amended with the data from query\nexecution.\n \nBasic Execution Data\n \nYou can get the following also from tabular ANALYZE\nstatement form:\nr_rows is provided for any node that reads rows. It shows\nhow many rows were read, on average \nr_filtered is provided whenever there is a condition that is\nchecked. It shows the percentage of rows left after checking\nthe condition.\n \nAdvanced Execution Data\n \nThe most important data that is not available in tabula\nANALYZE statement are:\nr_loops field. This shows how many times the node was\nexecuted. Most query plan elements have this field.\nr_total_time_ms field. It shows how much time in total was\nspent executing this node. If the node has subnodes, their\nexecution time is included.\nr_buffer_size field. Query plan nodes that make use of\nbuffers report the size of buffer that was was used.\n \nData About Individual Query Plan Nodes\n \nfilesort node reports whether sorting was done with LIMIT n\nparameter, and how many rows were in the sort result. \nblock-nl-join node has r_loops field, which allows to tell\nwhether Using join buffer was efficient \nrange-checked-for-each-record reports counters that show the\nresult of the check. \nexpression-cache is used for subqueries, and it reports how\nmany times the cache was used, and what cache hit ratio was.\nunion_result node has r_rows so one can see how many rows\nwere produced after UNION operation\nand so forth\n \nUse Cases\n \nSee Examples of ANALYZE FORMAT=JSON.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/analyze-format-json/','','https://mariadb.com/kb/en/library/analyze-format-json/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (445,28,'ANALYZE FORMAT=JSON Examples','Example #1\n \nCustomers who have ordered more than 1M goods.\n \nANALYZE FORMAT=JSON\nSELECT CONT(*)\nFROM customer\nWHERE\n (SELECT SUM(o_totalprice) FROM orders WHERE\no_custkey=c_custkey) > 1000*1000;\n \nThe query takes 40 seconds over cold cache\n \nEXPLAIN: {\n \"query_block\": {\n \"select_id\": 1,\n \"r_loops\": 1,\n \"r_total_time_ms\": 39872,\n \"table\": {\n \"table_name\": \"customer\",\n \"access_type\": \"index\",\n \"key\": \"i_c_nationkey\",\n \"key_length\": \"5\",\n \"used_key_parts\": [\"c_nationkey\"],\n \"r_loops\": 1,\n \"rows\": 150303,\n \"r_rows\": 150000,\n \"r_total_time_ms\": 270.3,\n \"filtered\": 100,\n \"r_filtered\": 60.691,\n \"attached_condition\": \"((subquery#2) > ((1000 *\n1000)))\",\n \"using_index\": true\n },\n \"subqueries\": [\n {\n \"query_block\": {\n \"select_id\": 2,\n \"r_loops\": 150000,\n \"r_total_time_ms\": 39531,\n \"table\": {\n \"table_name\": \"orders\",\n \"access_type\": \"ref\",\n \"possible_keys\": [\"i_o_custkey\"],\n \"key\": \"i_o_custkey\",\n \"key_length\": \"5\",\n \"used_key_parts\": [\"o_custkey\"],\n \"ref\": [\"dbt3sf1.customer.c_custkey\"],\n \"r_loops\": 150000,\n \"rows\": 7,\n \"r_rows\": 10,\n \"r_total_time_ms\": 39208,\n \"filtered\": 100,\n \"r_filtered\": 100\n }\n }\n }\n ]\n }\n}\nANALYZE shows that 39.2 seconds were spent in the subquery,\nwhich was executed 150K times (for every row of outer\ntable).\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/analyze-formatjson-examples/','','https://mariadb.com/kb/en/library/analyze-formatjson-examples/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (446,30,'CONTAINS','Syntax\n------ \nContains(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether a geometry g1 completely\ncontains geometry g2. CONTAINS() is based on the original\nMySQL implementation and uses object bounding rectangles,\nwhile ST_CONTAINS() uses object shapes. \n \nThis tests the opposite relationship to Within().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/contains/','','https://mariadb.com/kb/en/library/contains/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (447,30,'CROSSES','Syntax\n------ \nCrosses(g1,g2)\n \nDescription\n----------- \nReturns 1 if g1 spatially crosses g2. Returns NULL if g1 is\na Polygon or a MultiPolygon, or if g2 is a\nPoint or a MultiPoint. Otherwise, returns 0.\n \nThe term spatially crosses denotes a spatial relation\nbetween two\ngiven geometries that has the following properties:\nThe two geometries intersect\nTheir intersection results in a geometry that has a\ndimension that is one\n less than the maximum dimension of the two given geometries\nTheir intersection is not equal to either of the two given\ngeometries\n \nCROSSES() is based on the original MySQL implementation, and\nuses object bounding rectangles, while ST_CROSSES() uses\nobject shapes.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/crosses/','','https://mariadb.com/kb/en/library/crosses/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (448,30,'DISJOINT','Syntax\n------ \nDisjoint(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether g1 is spatially disjoint\nfrom\n(does not intersect) g2.\n \nDISJOINT() tests the opposite relationship to INTERSECTS().\n \nDISJOINT() is based on the original MySQL implementation and\nuses object bounding rectangles, while ST_DISJOINT() uses\nobject shapes.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/disjoint/','','https://mariadb.com/kb/en/library/disjoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (449,30,'EQUALS','Syntax\n------ \nEquals(g1,g2)\n \nFrom MariaDB 10.2.3:\n \nMBREQUALS(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether g1 is spatially equal to\ng2.\n \nEQUALS() is based on the original MySQL implementation and\nuses object bounding rectangles, while ST_EQUALS() uses\nobject shapes.\n \nFrom MariaDB 10.2.3, MBREQUALS is a synonym for Equals.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/equals/','','https://mariadb.com/kb/en/library/equals/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (450,30,'INTERSECTS','Syntax\n------ \nINTERSECTS(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether geometry g1 spatially\nintersects geometry g2.\n \nINTERSECTS() is based on the original MySQL implementation\nand uses object bounding rectangles, while ST_INTERSECTS()\nuses object shapes.\n \nINTERSECTS() tests the opposite relationship to DISJOINT().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/intersects/','','https://mariadb.com/kb/en/library/intersects/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (451,30,'OVERLAPS','Syntax\n------ \nOVERLAPS(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether g1 spatially overlaps g2.\nThe term spatially overlaps is used if two geometries\nintersect and their\nintersection results in a geometry of the same dimension but\nnot equal to\neither of the given geometries.\n \nOVERLAPS() is based on the original MySQL implementation and\nuses object bounding rectangles, while ST_OVERLAPS() uses\nobject shapes.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/overlaps/','','https://mariadb.com/kb/en/library/overlaps/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (452,30,'ST_CONTAINS','Syntax\n------ \nST_CONTAINS(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether a geometry g1 completely\ncontains geometry g2.\n \nST_CONTAINS() uses object shapes, while CONTAINS(), based on\nthe original MySQL implementation, uses object bounding\nrectangles.\n \nST_CONTAINS tests the opposite relationship to ST_WITHIN().\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'POLYGON((175 150, 20 40, 50 60,\n125 100, 175 150))\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'POINT(174 149)\');\n \nSELECT ST_CONTAINS(@g1,@g2);\n+----------------------+\n| ST_CONTAINS(@g1,@g2) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSET @g2 = ST_GEOMFROMTEXT(\'POINT(175 151)\');\n \nSELECT ST_CONTAINS(@g1,@g2);\n+----------------------+\n| ST_CONTAINS(@g1,@g2) |\n+----------------------+\n| 0 |\n+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st-contains/','','https://mariadb.com/kb/en/library/st-contains/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (453,30,'ST_CROSSES','Syntax\n------ \nST_CROSSES(g1,g2)\n \nDescription\n----------- \nReturns 1 if geometry g1 spatially crosses geometry g2.\nReturns NULL if g1 is a Polygon or a MultiPolygon, or if g2\nis a\nPoint or a MultiPoint. Otherwise, returns 0.\n \nThe term spatially crosses denotes a spatial relation\nbetween two\ngiven geometries that has the following properties:\nThe two geometries intersect\nTheir intersection results in a geometry that has a\ndimension that is one\n less than the maximum dimension of the two given geometries\nTheir intersection is not equal to either of the two given\ngeometries\n \nST_CROSSES() uses object shapes, while CROSSES(), based on\nthe original MySQL implementation, uses object bounding\nrectangles.\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'LINESTRING(174 149, 176 151)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'POLYGON((175 150, 20 40, 50 60,\n125 100, 175 150))\');\n \nSELECT ST_CROSSES(@g1,@g2);\n+---------------------+\n| ST_CROSSES(@g1,@g2) |\n+---------------------+\n| 1 |\n+---------------------+\n \nSET @g1 = ST_GEOMFROMTEXT(\'LINESTRING(176 149, 176 151)\');\n \nSELECT ST_CROSSES(@g1,@g2);\n+---------------------+\n| ST_CROSSES(@g1,@g2) |\n+---------------------+\n| 0 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st-crosses/','','https://mariadb.com/kb/en/library/st-crosses/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (454,30,'ST_DIFFERENCE','Syntax\n------ \nST_DIFFERENCE(g1,g2)\n \nDescription\n----------- \nReturns a geometry representing the point set difference of\nthe given geometry values.\n \nExample\n \nSET @g1 = POINT(10,10), @g2 = POINT(20,20);\n \nSELECT ST_AsText(ST_Difference(@g1, @g2));\n+------------------------------------+\n| ST_AsText(ST_Difference(@g1, @g2)) |\n+------------------------------------+\n| POINT(10 10) |\n+------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_difference/','','https://mariadb.com/kb/en/library/st_difference/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (455,30,'ST_DISJOINT','Syntax\n------ \nST_DISJOINT(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether geometry g1 is spatially\ndisjoint from\n(does not intersect with) geometry g2.\n \nST_DISJOINT() uses object shapes, while DISJOINT(), based on\nthe original MySQL implementation, uses object bounding\nrectangles.\n \nST_DISJOINT() tests the opposite relationship to\nST_INTERSECTS().\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(0 0)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(2 0, 0 2)\');\n \nSELECT ST_DISJOINT(@g1,@g2);\n+----------------------+\n| ST_DISJOINT(@g1,@g2) |\n+----------------------+\n| 1 |\n+----------------------+\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(0 0, 0 2)\');\n \nSELECT ST_DISJOINT(@g1,@g2);\n+----------------------+\n| ST_DISJOINT(@g1,@g2) |\n+----------------------+\n| 0 |\n+----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_disjoint/','','https://mariadb.com/kb/en/library/st_disjoint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (456,30,'ST_DISTANCE','ST_DISTANCE() was introduced in MariaDB 5.3.3.\n \nSyntax\n------ \nST_DISTANCE(g1,g2)\n \nDescription\n----------- \nReturns the distance between two geometries, or null if not\ngiven valid inputs.\n \nExample\n \nSELECT ST_Distance(POINT(1,2),POINT(2,2));\n+------------------------------------+\n| ST_Distance(POINT(1,2),POINT(2,2)) |\n+------------------------------------+\n| 1 |\n+------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_distance/','','https://mariadb.com/kb/en/library/st_distance/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (457,30,'ST_EQUALS','Syntax\n------ \nST_EQUALS(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether geometry g1 is spatially\nequal to geometry g2.\n \nST_EQUALS() uses object shapes, while EQUALS(), based on the\noriginal MySQL implementation, uses object bounding\nrectangles.\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'LINESTRING(174 149, 176 151)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(176 151, 174 149)\');\n \nSELECT ST_EQUALS(@g1,@g2);\n+--------------------+\n| ST_EQUALS(@g1,@g2) |\n+--------------------+\n| 1 |\n+--------------------+\n \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(0 2)\');\n \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(2 0)\');\n \nSELECT ST_EQUALS(@g1,@g2);\n+--------------------+\n| ST_EQUALS(@g1,@g2) |\n+--------------------+\n| 0 |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st-equals/','','https://mariadb.com/kb/en/library/st-equals/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (458,30,'ST_INTERSECTS','Syntax\n------ \nST_INTERSECTS(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether geometry g1 spatially\nintersects geometry g2.\n \nST_INTERSECTS() uses object shapes, while INTERSECTS(),\nbased on the original MySQL implementation, uses object\nbounding rectangles.\n \nST_INTERSECTS() tests the opposite relationship to\nST_DISJOINT().\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(0 0)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(0 0, 0 2)\');\n \nSELECT ST_INTERSECTS(@g1,@g2);\n+------------------------+\n| ST_INTERSECTS(@g1,@g2) |\n+------------------------+\n| 1 |\n+------------------------+\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(2 0, 0 2)\');\n \nSELECT ST_INTERSECTS(@g1,@g2);\n+------------------------+\n| ST_INTERSECTS(@g1,@g2) |\n+------------------------+\n| 0 |\n+------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st-intersects/','','https://mariadb.com/kb/en/library/st-intersects/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (459,30,'ST_LENGTH','Syntax\n------ \nST_LENGTH(ls)\n \nDescription\n----------- \nReturns as a double-precision number the length of the\nLineString value ls in its associated spatial reference.\n \nExamples\n-------- \nSET @ls = \'LineString(1 1,2 2,3 3)\';\n \nSELECT ST_LENGTH(ST_GeomFromText(@ls));\n+---------------------------------+\n| ST_LENGTH(ST_GeomFromText(@ls)) |\n+---------------------------------+\n| 2.82842712474619 |\n+---------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_length/','','https://mariadb.com/kb/en/library/st_length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (460,30,'ST_OVERLAPS','Syntax\n------ \nST_OVERLAPS(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether geometry g1 spatially\noverlaps geometry g2.\n \nThe term spatially overlaps is used if two geometries\nintersect and their\nintersection results in a geometry of the same dimension but\nnot equal to\neither of the given geometries.\n \nST_OVERLAPS() uses object shapes, while OVERLAPS(), based on\nthe original MySQL implementation, uses object bounding\nrectangles.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st-overlaps/','','https://mariadb.com/kb/en/library/st-overlaps/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (461,30,'ST_TOUCHES','Syntax\n------ \nST_TOUCHES(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether geometry g1 spatially\ntouches geometry g2. Two geometries spatially touch if the\ninteriors of the geometries do not intersect,\nbut the boundary of one of the geometries intersects either\nthe boundary or the\ninterior of the other.\n \nST_TOUCHES() uses object shapes, while TOUCHES(), based on\nthe original MySQL implementation, uses object bounding\nrectangles.\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(2 0)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'LINESTRING(2 0, 0 2)\');\n \nSELECT ST_TOUCHES(@g1,@g2);\n+---------------------+\n| ST_TOUCHES(@g1,@g2) |\n+---------------------+\n| 1 |\n+---------------------+\n \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(2 1)\');\n \nSELECT ST_TOUCHES(@g1,@g2);\n+---------------------+\n| ST_TOUCHES(@g1,@g2) |\n+---------------------+\n| 0 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st-touches/','','https://mariadb.com/kb/en/library/st-touches/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (462,30,'ST_WITHIN','Syntax\n------ \nST_WITHIN(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether geometry g1 is spatially\nwithin geometry g2.\n \nThis tests the opposite relationship as ST_CONTAINS().\n \nST_WITHIN() uses object shapes, while WITHIN(), based on the\noriginal MySQL implementation, uses object bounding\nrectangles.\n \nExamples\n-------- \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(174 149)\');\n \nSET @g2 = ST_GEOMFROMTEXT(\'POLYGON((175 150, 20 40, 50 60,\n125 100, 175 150))\');\n \nSELECT ST_WITHIN(@g1,@g2);\n+--------------------+\n| ST_WITHIN(@g1,@g2) |\n+--------------------+\n| 1 |\n+--------------------+\n \nSET @g1 = ST_GEOMFROMTEXT(\'POINT(176 151)\');\n \nSELECT ST_WITHIN(@g1,@g2);\n+--------------------+\n| ST_WITHIN(@g1,@g2) |\n+--------------------+\n| 0 |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st-within/','','https://mariadb.com/kb/en/library/st-within/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (463,30,'TOUCHES','Syntax\n------ \nTouches(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether g1 spatially touches g2.\nTwo\ngeometries spatially touch if the interiors of the\ngeometries do not intersect,\nbut the boundary of one of the geometries intersects either\nthe boundary or the\ninterior of the other.\n \nTOUCHES() is based on the original MySQL implementation and\nuses object bounding rectangles, while ST_TOUCHES() uses\nobject shapes.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/touches/','','https://mariadb.com/kb/en/library/touches/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (464,30,'WITHIN','Syntax\n------ \nWithin(g1,g2)\n \nDescription\n----------- \nReturns 1 or 0 to indicate whether g1 is spatially within\ng2.\nThis tests the opposite relationship as Contains().\n \nWITHIN() is based on the original MySQL implementation, and\nuses object bounding rectangles, while ST_WITHIN() uses\nobject shapes.\n \nExamples\n-------- \nSET @g1 = GEOMFROMTEXT(\'POINT(174 149)\');\nSET @g2 = GEOMFROMTEXT(\'POINT(176 151)\');\nSET @g3 = GEOMFROMTEXT(\'POLYGON((175 150, 20 40, 50 60, 125\n100, 175 150))\');\n \nSELECT within(@g1,@g3);\n+-----------------+\n| within(@g1,@g3) |\n+-----------------+\n| 1 |\n+-----------------+\n \nSELECT within(@g2,@g3);\n+-----------------+\n| within(@g2,@g3) |\n+-----------------+\n| 0 |\n+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/within/','','https://mariadb.com/kb/en/library/within/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (465,31,'ADDDATE','Syntax\n------ \nADDDATE(date,INTERVAL expr unit), ADDDATE(expr,days)\n \nDescription\n----------- \nWhen invoked with the INTERVAL form of the second argument,\nADDDATE()\nis a synonym for DATE_ADD(). The related function\nSUBDATE() is a synonym for DATE_SUB(). For\ninformation on the INTERVAL unit argument, see the\ndiscussion for\nDATE_ADD().\n \nWhen invoked with the days form of the second argument,\nMariaDB treats it as an\ninteger number of days to be added to expr.\n \nExamples\n-------- \nSELECT DATE_ADD(\'2008-01-02\', INTERVAL 31 DAY);\n+-----------------------------------------+\n| DATE_ADD(\'2008-01-02\', INTERVAL 31 DAY) |\n+-----------------------------------------+\n| 2008-02-02 |\n+-----------------------------------------+\n \nSELECT ADDDATE(\'2008-01-02\', INTERVAL 31 DAY);\n+----------------------------------------+\n| ADDDATE(\'2008-01-02\', INTERVAL 31 DAY) |\n+----------------------------------------+\n| 2008-02-02 |\n+----------------------------------------+\n \nSELECT ADDDATE(\'2008-01-02\', 31);\n+---------------------------+\n| ADDDATE(\'2008-01-02\', 31) |\n+---------------------------+\n| 2008-02-02 |\n+---------------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT d, ADDDATE(d, 10) from t1;\n \n+---------------------+---------------------+\n| d | ADDDATE(d, 10) |\n+---------------------+---------------------+\n| 2007-01-30 21:31:07 | 2007-02-09 21:31:07 |\n| 1983-10-15 06:42:51 | 1983-10-25 06:42:51 |\n| 2011-04-21 12:34:56 | 2011-05-01 12:34:56 |\n| 2011-10-30 06:31:41 | 2011-11-09 06:31:41 |\n| 2011-01-30 14:03:25 | 2011-02-09 14:03:25 |\n| 2004-10-07 11:19:34 | 2004-10-17 11:19:34 |\n+---------------------+---------------------+\n \nSELECT d, ADDDATE(d, INTERVAL 10 HOUR) from t1;\n \n+---------------------+------------------------------+\n| d | ADDDATE(d, INTERVAL 10 HOUR) |\n+---------------------+------------------------------+\n| 2007-01-30 21:31:07 | 2007-01-31 07:31:07 |\n| 1983-10-15 06:42:51 | 1983-10-15 16:42:51 |\n| 2011-04-21 12:34:56 | 2011-04-21 22:34:56 |\n| 2011-10-30 06:31:41 | 2011-10-30 16:31:41 |\n| 2011-01-30 14:03:25 | 2011-01-31 00:03:25 |\n| 2004-10-07 11:19:34 | 2004-10-07 21:19:34 |\n+---------------------+------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/adddate/','','https://mariadb.com/kb/en/library/adddate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (466,31,'ADDTIME','Syntax\n------ \nADDTIME(expr1,expr2)\n \nDescription\n----------- \nADDTIME() adds expr2 to expr1 and returns the result. expr1\nis a time\nor datetime expression, and expr2 is a time expression.\n \nExamples\n-------- \nSELECT ADDTIME(\'2007-12-31 23:59:59.999999\', \'1\n1:1:1.000002\');\n+---------------------------------------------------------+\n| ADDTIME(\'2007-12-31 23:59:59.999999\', \'1\n1:1:1.000002\') |\n+---------------------------------------------------------+\n| 2008-01-02 01:01:01.000001 |\n+---------------------------------------------------------+\n \nSELECT ADDTIME(\'01:00:00.999999\', \'02:00:00.999998\');\n+-----------------------------------------------+\n| ADDTIME(\'01:00:00.999999\', \'02:00:00.999998\') |\n+-----------------------------------------------+\n| 03:00:01.999997 |\n+-----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/addtime/','','https://mariadb.com/kb/en/library/addtime/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (467,31,'CONVERT_TZ','Syntax\n------ \nCONVERT_TZ(dt,from_tz,to_tz)\n \nDescription\n----------- \nCONVERT_TZ() converts a datetime value dt from the time zone\ngiven by from_tz to the time zone given by to_tz and returns\nthe resulting value.\n \nIn order to use named time zones, such as GMT, MET or\nAfrica/Johannesburg, the time_zone tables must be loaded\n(see mysql_tzinfo_to_sql).\n \nNo conversion will take place if the value falls outside of\nthe supported TIMESTAMP range (\'1970-01-01 00:00:01\' to\n\'2038-01-19 05:14:07\' UTC) when converted from from_tz to\nUTC.\n \nThis function returns NULL if the arguments are invalid (or\nnamed time zones have not been loaded).\n \nSee time zones for more information.\n \nExamples\n-------- \nSELECT CONVERT_TZ(\'2016-01-01\n12:00:00\',\'+00:00\',\'+10:00\');\n+-----------------------------------------------------+\n| CONVERT_TZ(\'2016-01-01 12:00:00\',\'+00:00\',\'+10:00\')\n|\n+-----------------------------------------------------+\n| 2016-01-01 22:00:00 |\n+-----------------------------------------------------+\n \nUsing named time zones (with the time zone tables loaded):\n \nSELECT CONVERT_TZ(\'2016-01-01\n12:00:00\',\'GMT\',\'Africa/Johannesburg\');\n+---------------------------------------------------------------+\n| CONVERT_TZ(\'2016-01-01\n12:00:00\',\'GMT\',\'Africa/Johannesburg\') |\n+---------------------------------------------------------------+\n| 2016-01-01 14:00:00 |\n+---------------------------------------------------------------+\n \nThe value is out of the TIMESTAMP range, so no conversion\ntakes place:\n \nSELECT CONVERT_TZ(\'1969-12-31\n22:00:00\',\'+00:00\',\'+10:00\');\n+-----------------------------------------------------+\n| CONVERT_TZ(\'1969-12-31 22:00:00\',\'+00:00\',\'+10:00\')\n|\n+-----------------------------------------------------+\n| 1969-12-31 22:00:00 |\n+-----------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/convert_tz/','','https://mariadb.com/kb/en/library/convert_tz/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (468,31,'CURDATE','Syntax\n------ \nCURDATE()\n \nDescription\n----------- \nReturns the current date as a value in \'YYYY-MM-DD\' or\nYYYYMMDD\nformat, depending on whether the function is used in a\nstring or\nnumeric context.\n \nExamples\n-------- \nSELECT CURDATE();\n+------------+\n| CURDATE() |\n+------------+\n| 2019-03-05 |\n+------------+\n \nIn a numeric context (note this is not performing date\ncalculations):\n \nSELECT CURDATE() +0;\n \n+--------------+\n| CURDATE() +0 |\n+--------------+\n| 20190305 |\n+--------------+\n \nData calculation:\n \nSELECT CURDATE() - INTERVAL 5 DAY;\n \n+----------------------------+\n| CURDATE() - INTERVAL 5 DAY |\n+----------------------------+\n| 2019-02-28 |\n+----------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/curdate/','','https://mariadb.com/kb/en/library/curdate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (469,31,'CURRENT_DATE','Syntax\n------ \nCURRENT_DATE, CURRENT_DATE()\n \nDescription\n----------- \nCURRENT_DATE and CURRENT_DATE() are synonyms for CURDATE().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/current_date/','','https://mariadb.com/kb/en/library/current_date/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (470,31,'CURRENT_TIME','Syntax\n------ \nCURRENT_TIME\nCURRENT_TIME([precision])\n \nDescription\n----------- \nCURRENT_TIME and CURRENT_TIME() are synonyms for CURTIME().\n \n\n\nURL: https://mariadb.com/kb/en/library/current_time/','','https://mariadb.com/kb/en/library/current_time/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (471,31,'CURRENT_TIMESTAMP','Syntax\n------ \nCURRENT_TIMESTAMP\nCURRENT_TIMESTAMP([precision])\n \nDescription\n----------- \nCURRENT_TIMESTAMP and CURRENT_TIMESTAMP() are synonyms for\nNOW().\n \n\n\nURL: https://mariadb.com/kb/en/library/current_timestamp/','','https://mariadb.com/kb/en/library/current_timestamp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (472,31,'CURTIME','Syntax\n------ \nCURTIME([precision])\n \nDescription\n----------- \nReturns the current time as a value in \'HH:MM:SS\' or\nHHMMSS.uuuuuu format, depending on whether the function is\nused in a string or numeric context. The value is expressed\nin the current time zone.\n \nThe optional precision determines the microsecond precision.\nSee Microseconds in MariaDB.\n \nExamples\n-------- \nSELECT CURTIME();\n+-----------+\n| CURTIME() |\n+-----------+\n| 12:45:39 |\n+-----------+\n \nSELECT CURTIME() + 0;\n \n+---------------+\n| CURTIME() + 0 |\n+---------------+\n| 124545.000000 |\n+---------------+\n \nWith precision:\n \nSELECT CURTIME(2);\n+-------------+\n| CURTIME(2) |\n+-------------+\n| 09:49:08.09 |\n+-------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/curtime/','','https://mariadb.com/kb/en/library/curtime/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (473,31,'DATE FUNCTION','Syntax\n------ \nDATE(expr)\n \nDescription\n----------- \nExtracts the date part of the date or datetime expression\nexpr.\n \nExamples\n-------- \nSELECT DATE(\'2013-07-18 12:21:32\');\n+-----------------------------+\n| DATE(\'2013-07-18 12:21:32\') |\n+-----------------------------+\n| 2013-07-18 |\n+-----------------------------+\n \nError Handling\n \nUntil MariaDB 5.5.32, some versions of MariaDB returned\n0000-00-00 when passed an invalid date. From 5.5.32, NULL is\nreturned.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/date-function/','','https://mariadb.com/kb/en/library/date-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (474,31,'DATEDIFF','Syntax\n------ \nDATEDIFF(expr1,expr2)\n \nDescription\n----------- \nDATEDIFF() returns (expr1 – expr2) expressed\nas a value in days from one date to the other. expr1 and\nexpr2 are date\nor date-and-time expressions. Only the date parts of the\nvalues are used in the\ncalculation.\n \nExamples\n-------- \nSELECT DATEDIFF(\'2007-12-31 23:59:59\',\'2007-12-30\');\n+----------------------------------------------+\n| DATEDIFF(\'2007-12-31 23:59:59\',\'2007-12-30\') |\n+----------------------------------------------+\n| 1 |\n+----------------------------------------------+\n \nSELECT DATEDIFF(\'2010-11-30 23:59:59\',\'2010-12-31\');\n+----------------------------------------------+\n| DATEDIFF(\'2010-11-30 23:59:59\',\'2010-12-31\') |\n+----------------------------------------------+\n| -31 |\n+----------------------------------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT NOW();\n+---------------------+\n| NOW() |\n+---------------------+\n| 2011-05-23 10:56:05 |\n+---------------------+\n \nSELECT d, DATEDIFF(NOW(),d) FROM t1;\n \n+---------------------+-------------------+\n| d | DATEDIFF(NOW(),d) |\n+---------------------+-------------------+\n| 2007-01-30 21:31:07 | 1574 |\n| 1983-10-15 06:42:51 | 10082 |\n| 2011-04-21 12:34:56 | 32 |\n| 2011-10-30 06:31:41 | -160 |\n| 2011-01-30 14:03:25 | 113 |\n| 2004-10-07 11:19:34 | 2419 |\n+---------------------+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/datediff/','','https://mariadb.com/kb/en/library/datediff/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (475,31,'DATE_ADD','Syntax\n------ \nDATE_ADD(date,INTERVAL expr unit)\n \nDescription\n----------- \nPerforms date arithmetic. The date argument specifies the\nstarting date or datetime value. expr is an expression\nspecifying the\ninterval value to be added or subtracted from the starting\ndate. expr is a\nstring; it may start with a \"-\" for negative intervals.\nunit is a\nkeyword indicating the units in which the expression should\nbe interpreted. See Date and Time Units for a complete list\nof permitted units. \n \nSee also DATE_SUB().\n \nExamples\n-------- \nSELECT \'2008-12-31 23:59:59\' + INTERVAL 1 SECOND;\n \n+-------------------------------------------+\n| \'2008-12-31 23:59:59\' + INTERVAL 1 SECOND |\n+-------------------------------------------+\n| 2009-01-01 00:00:00 |\n+-------------------------------------------+\n \nSELECT INTERVAL 1 DAY + \'2008-12-31\';\n \n+-------------------------------+\n| INTERVAL 1 DAY + \'2008-12-31\' |\n+-------------------------------+\n| 2009-01-01 |\n+-------------------------------+\n \nSELECT \'2005-01-01\' - INTERVAL 1 SECOND;\n \n+----------------------------------+\n| \'2005-01-01\' - INTERVAL 1 SECOND |\n+----------------------------------+\n| 2004-12-31 23:59:59 |\n+----------------------------------+\n \nSELECT DATE_ADD(\'2000-12-31 23:59:59\', INTERVAL 1 SECOND);\n+----------------------------------------------------+\n| DATE_ADD(\'2000-12-31 23:59:59\', INTERVAL 1 SECOND) |\n+----------------------------------------------------+\n| 2001-01-01 00:00:00 |\n+----------------------------------------------------+\n \nSELECT DATE_ADD(\'2010-12-31 23:59:59\', INTERVAL 1 DAY);\n+-------------------------------------------------+\n| DATE_ADD(\'2010-12-31 23:59:59\', INTERVAL 1 DAY) |\n+-------------------------------------------------+\n| 2011-01-01 23:59:59 |\n+-------------------------------------------------+\n \nSELECT DATE_ADD(\'2100-12-31 23:59:59\', INTERVAL \'1:1\'\nMINUTE_SECOND);\n+---------------------------------------------------------------+\n| DATE_ADD(\'2100-12-31 23:59:59\', INTERVAL \'1:1\'\nMINUTE_SECOND) |\n+---------------------------------------------------------------+\n| 2101-01-01 00:01:00 |\n+---------------------------------------------------------------+\n \nSELECT DATE_ADD(\'1900-01-01 00:00:00\', INTERVAL \'-1 10\'\nDAY_HOUR);\n+------------------------------------------------------------+\n| DATE_ADD(\'1900-01-01 00:00:00\', INTERVAL \'-1 10\'\nDAY_HOUR) |\n+------------------------------------------------------------+\n| 1899-12-30 14:00:00 |\n+------------------------------------------------------------+\n \nSELECT DATE_ADD(\'1992-12-31 23:59:59.000002\', INTERVAL\n\'1.999999\' SECOND_MICROSECOND);\n+--------------------------------------------------------------------------------+\n| DATE_ADD(\'1992-12-31 23:59:59.000002\', INTERVAL\n\'1.999999\' SECOND_MICROSECOND) |\n+--------------------------------------------------------------------------------+\n| 1993-01-01 00:00:01.000001 |\n+--------------------------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/date_add/','','https://mariadb.com/kb/en/library/date_add/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (476,31,'DATE_FORMAT','Syntax\n------ \nDATE_FORMAT(date, format[, locale])\n \nDescription\n----------- \nFormats the date value according to the format string. \n \nThe language used for the names is controlled by the value\nof the lc_time_names system variable. See server locale for\nmore on the supported locales.\n \nThe options that can be used by DATE_FORMAT(), as well as\nits inverse STR_TO_DATE() and the FROM_UNIXTIME() function,\nare:\n \nOption | Description | \n \n%a | Short weekday name in current locale (Variable\nlc_time_names). | \n \n%b | Short form month name in current locale. For locale\nen_US this is one of:\nJan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov or Dec. | \n \n%c | Month with 1 or 2 digits. | \n \n%D | Day with English suffix \'th\', \'nd\', \'st\' or\n\'rd\'\'. (1st, 2nd, 3rd...). | \n \n%d | Day with 2 digits. | \n \n%e | Day with 1 or 2 digits. | \n \n%f | Sub seconds 6 digits. | \n \n%H | Hour with 2 digits between 00-23. | \n \n%h | Hour with 2 digits between 01-12. | \n \n%I | Hour with 2 digits between 01-12. | \n \n%i | Minute with 2 digits. | \n \n%j | Day of the year (001-366) | \n \n%k | Hour with 1 digits between 0-23. | \n \n%l | Hour with 1 digits between 1-12. | \n \n%M | Full month name in current locale (Variable\nlc_time_names). | \n \n%m | Month with 2 digits. | \n \n%p | AM/PM according to current locale (Variable\nlc_time_names). | \n \n%r | Time in 12 hour format, followed by AM/PM. Short for\n\'%I:%i:%S %p\'. | \n \n%S | Seconds with 2 digits. | \n \n%s | Seconds with 2 digits. | \n \n%T | Time in 24 hour format. Short for \'%H:%i:%S\'. | \n \n%U | Week number (00-53), when first day of the week is\nSunday. | \n \n%u | Week number (00-53), when first day of the week is\nMonday. | \n \n%V | Week number (01-53), when first day of the week is\nSunday. Used with %X. | \n \n%v | Week number (01-53), when first day of the week is\nMonday. Used with %x. | \n \n%W | Full weekday name in current locale (Variable\nlc_time_names). | \n \n%w | Day of the week. 0 = Sunday, 6 = Saturday. | \n \n%X | Year with 4 digits when first day of the week is\nSunday. Used with %V. | \n \n%x | Year with 4 digits when first day of the week is\nMonday. Used with %v. | \n \n%Y | Year with 4 digits. | \n \n%y | Year with 2 digits. | \n \n%# | For str_to_date(), skip all numbers. | \n \n%. | For str_to_date(), skip all punctation characters. | \n \n%@ | For str_to_date(), skip all alpha characters. | \n \n%% | A literal % character. | \n \nTo get a date in one of the standard formats, GET_FORMAT()\ncan be used.\n \nExamples\n-------- \nSELECT DATE_FORMAT(\'2009-10-04 22:23:00\', \'%W %M %Y\');\n+------------------------------------------------+\n| DATE_FORMAT(\'2009-10-04 22:23:00\', \'%W %M %Y\') |\n+------------------------------------------------+\n| Sunday October 2009 |\n+------------------------------------------------+\n \nSELECT DATE_FORMAT(\'2007-10-04 22:23:00\', \'%H:%i:%s\');\n+------------------------------------------------+\n| DATE_FORMAT(\'2007-10-04 22:23:00\', \'%H:%i:%s\') |\n+------------------------------------------------+\n| 22:23:00 |\n+------------------------------------------------+\n \nSELECT DATE_FORMAT(\'1900-10-04 22:23:00\', \'%D %y %a %d %m\n%b %j\');\n+------------------------------------------------------------+\n| DATE_FORMAT(\'1900-10-04 22:23:00\', \'%D %y %a %d %m %b\n%j\') |\n+------------------------------------------------------------+\n| 4th 00 Thu 04 10 Oct 277 |\n+------------------------------------------------------------+\n \nSELECT DATE_FORMAT(\'1997-10-04 22:23:00\', \'%H %k %I %r %T\n%S %w\');\n+------------------------------------------------------------+\n| DATE_FORMAT(\'1997-10-04 22:23:00\', \'%H %k %I %r %T %S\n%w\') |\n+------------------------------------------------------------+\n| 22 22 10 10:23:00 PM 22:23:00 00 6 |\n+------------------------------------------------------------+\n \nSELECT DATE_FORMAT(\'1999-01-01\', \'%X %V\');\n+------------------------------------+\n| DATE_FORMAT(\'1999-01-01\', \'%X %V\') |\n+------------------------------------+\n| 1998 52 |\n+------------------------------------+\n \nSELECT DATE_FORMAT(\'2006-06-00\', \'%d\');\n+---------------------------------+\n| DATE_FORMAT(\'2006-06-00\', \'%d\') |\n+---------------------------------+\n| 00 |\n+---------------------------------+\n \nOptionally, the locale can be explicitly specified as the\nthird DATE_FORMAT() argument. Doing so makes the function\nindependent from the session settings, and the three\nargument version of DATE_FORMAT() can be used in virtual\nindexed and persistent generated-columns:\n \nSELECT DATE_FORMAT(\'2006-01-01\', \'%W\', \'el_GR\');\n+------------------------------------------+\n| DATE_FORMAT(\'2006-01-01\', \'%W\', \'el_GR\') |\n+------------------------------------------+\n| Κυριακή |\n+------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/date_format/','','https://mariadb.com/kb/en/library/date_format/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (477,31,'DATE_SUB','Syntax\n------ \nDATE_SUB(date,INTERVAL expr unit)\n \nDescription\n----------- \nPerforms date arithmetic. The date argument specifies the\nstarting date or datetime value. expr is an expression\nspecifying the\ninterval value to be added or subtracted from the starting\ndate. expr is a\nstring; it may start with a \"-\" for negative intervals.\nunit is a\nkeyword indicating the units in which the expression should\nbe interpreted. See Date and Time Units for a complete list\nof permitted units. \n \nSee also DATE_ADD().\n \nExamples\n-------- \nSELECT DATE_SUB(\'1998-01-02\', INTERVAL 31 DAY);\n+-----------------------------------------+\n| DATE_SUB(\'1998-01-02\', INTERVAL 31 DAY) |\n+-----------------------------------------+\n| 1997-12-02 |\n+-----------------------------------------+\n \nSELECT DATE_SUB(\'2005-01-01 00:00:00\', INTERVAL \'1\n1:1:1\' DAY_SECOND);\n+----------------------------------------------------------------+\n| DATE_SUB(\'2005-01-01 00:00:00\', INTERVAL \'1 1:1:1\'\nDAY_SECOND) |\n+----------------------------------------------------------------+\n| 2004-12-30 22:58:59 |\n+----------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/date_sub/','','https://mariadb.com/kb/en/library/date_sub/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (478,31,'DAY','Syntax\n------ \nDAY(date)\n \nDescription\n----------- \nDAY() is a synonym for DAYOFMONTH().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/day/','','https://mariadb.com/kb/en/library/day/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (479,31,'DAYNAME','Syntax\n------ \nDAYNAME(date)\n \nDescription\n----------- \nReturns the name of the weekday for date. The language used\nfor the name is controlled by the value\nof the lc_time_names system variable. See server locale for\nmore on the supported locales.\n \nExamples\n-------- \nSELECT DAYNAME(\'2007-02-03\');\n+-----------------------+\n| DAYNAME(\'2007-02-03\') |\n+-----------------------+\n| Saturday |\n+-----------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT d, DAYNAME(d) FROM t1;\n \n+---------------------+------------+\n| d | DAYNAME(d) |\n+---------------------+------------+\n| 2007-01-30 21:31:07 | Tuesday |\n| 1983-10-15 06:42:51 | Saturday |\n| 2011-04-21 12:34:56 | Thursday |\n| 2011-10-30 06:31:41 | Sunday |\n| 2011-01-30 14:03:25 | Sunday |\n| 2004-10-07 11:19:34 | Thursday |\n+---------------------+------------+\n \nChanging the locale:\n \nSET lc_time_names = \'fr_CA\';\n \nSELECT DAYNAME(\'2013-04-01\');\n+-----------------------+\n| DAYNAME(\'2013-04-01\') |\n+-----------------------+\n| lundi |\n+-----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/dayname/','','https://mariadb.com/kb/en/library/dayname/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (480,31,'DAYOFMONTH','Syntax\n------ \nDAYOFMONTH(date)\n \nDescription\n----------- \nReturns the day of the month for date, in the range 1 to 31,\nor 0\nfor dates such as \'0000-00-00\' or \'2008-00-00\' which\nhave a zero day\npart.\n \nDAY() is a synonym.\n \nExamples\n-------- \nSELECT DAYOFMONTH(\'2007-02-03\');\n+--------------------------+\n| DAYOFMONTH(\'2007-02-03\') |\n+--------------------------+\n| 3 |\n+--------------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT d FROM t1 where DAYOFMONTH(d) = 30;\n \n+---------------------+\n| d |\n+---------------------+\n| 2007-01-30 21:31:07 |\n| 2011-10-30 06:31:41 |\n| 2011-01-30 14:03:25 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/dayofmonth/','','https://mariadb.com/kb/en/library/dayofmonth/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (481,31,'DAYOFWEEK','Syntax\n------ \nDAYOFWEEK(date)\n \nDescription\n----------- \nReturns the day of the week index for the date (1 = Sunday,\n2 = Monday, ..., 7 =\nSaturday). These index values correspond to the ODBC\nstandard.\n \nThis contrasts with WEEKDAY() which follows a different\nindex numbering\n(0 = Monday, 1 = Tuesday, ... 6 = Sunday).\n \nExamples\n-------- \nSELECT DAYOFWEEK(\'2007-02-03\');\n+-------------------------+\n| DAYOFWEEK(\'2007-02-03\') |\n+-------------------------+\n| 7 |\n+-------------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT d, DAYNAME(d), DAYOFWEEK(d), WEEKDAY(d) from t1;\n \n+---------------------+------------+--------------+------------+\n| d | DAYNAME(d) | DAYOFWEEK(d) | WEEKDAY(d) |\n+---------------------+------------+--------------+------------+\n| 2007-01-30 21:31:07 | Tuesday | 3 | 1 |\n| 1983-10-15 06:42:51 | Saturday | 7 | 5 |\n| 2011-04-21 12:34:56 | Thursday | 5 | 3 |\n| 2011-10-30 06:31:41 | Sunday | 1 | 6 |\n| 2011-01-30 14:03:25 | Sunday | 1 | 6 |\n| 2004-10-07 11:19:34 | Thursday | 5 | 3 |\n+---------------------+------------+--------------+------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/dayofweek/','','https://mariadb.com/kb/en/library/dayofweek/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (482,31,'DAYOFYEAR','Syntax\n------ \nDAYOFYEAR(date)\n \nDescription\n----------- \nReturns the day of the year for date, in the range 1 to 366.\n \nExamples\n-------- \nSELECT DAYOFYEAR(\'2018-02-16\');\n+-------------------------+\n| DAYOFYEAR(\'2018-02-16\') |\n+-------------------------+\n| 47 |\n+-------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/dayofyear/','','https://mariadb.com/kb/en/library/dayofyear/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (483,31,'EXTRACT','Syntax\n------ \nEXTRACT(unit FROM date)\n \nDescription\n----------- \nThe EXTRACT() function extracts the required unit from the\ndate. See Date and Time Units for a complete list of\npermitted units.\n \nIn MariaDB 10.0.7 and MariaDB 5.5.35, EXTRACT (HOUR FROM\n...) was changed to return a value from 0 to 23, adhering to\nthe SQL standard. Until MariaDB 10.0.6 and MariaDB 5.5.34,\nand in all versions of MySQL at least as of MySQL 5.7, it\ncould return a value > 23. HOUR() is not a standard\nfunction, so continues to adhere to the old behaviour\ninherited from MySQL.\n \nExamples\n-------- \nSELECT EXTRACT(YEAR FROM \'2009-07-02\');\n+---------------------------------+\n| EXTRACT(YEAR FROM \'2009-07-02\') |\n+---------------------------------+\n| 2009 |\n+---------------------------------+\n \nSELECT EXTRACT(YEAR_MONTH FROM \'2009-07-02 01:02:03\');\n+------------------------------------------------+\n| EXTRACT(YEAR_MONTH FROM \'2009-07-02 01:02:03\') |\n+------------------------------------------------+\n| 200907 |\n+------------------------------------------------+\n \nSELECT EXTRACT(DAY_MINUTE FROM \'2009-07-02 01:02:03\');\n+------------------------------------------------+\n| EXTRACT(DAY_MINUTE FROM \'2009-07-02 01:02:03\') |\n+------------------------------------------------+\n| 20102 |\n+------------------------------------------------+\n \nSELECT EXTRACT(MICROSECOND FROM \'2003-01-02\n10:30:00.000123\');\n+--------------------------------------------------------+\n| EXTRACT(MICROSECOND FROM \'2003-01-02 10:30:00.000123\') |\n+--------------------------------------------------------+\n| 123 |\n+--------------------------------------------------------+\n \nFrom MariaDB 10.0.7 and MariaDB 5.5.35, EXTRACT (HOUR\nFROM...) returns a value from 0 to 23, as per the SQL\nstandard. HOUR is not a standard function, so continues to\nadhere to the old behaviour inherited from MySQL.\n \nSELECT EXTRACT(HOUR FROM \'26:30:00\'), HOUR(\'26:30:00\');\n+-------------------------------+------------------+\n| EXTRACT(HOUR FROM \'26:30:00\') | HOUR(\'26:30:00\') |\n+-------------------------------+------------------+\n| 2 | 26 |\n+-------------------------------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/extract/','','https://mariadb.com/kb/en/library/extract/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (484,31,'FROM_DAYS','Syntax\n------ \nFROM_DAYS(N)\n \nDescription\n----------- \nGiven a day number N, returns a DATE value. The day count is\nbased on the number of days from the start of the standard\ncalendar (0000-00-00). \n \nThe function is not designed for use with dates before the\nadvent of the Gregorian calendar in October 1582. Results\nwill not be reliable since it doesn\'t account for the lost\ndays when the calendar changed from the Julian calendar.\n \nThis is the converse of the TO_DAYS() function.\n \nExamples\n-------- \nSELECT FROM_DAYS(730669);\n+-------------------+\n| FROM_DAYS(730669) |\n+-------------------+\n| 2000-07-03 |\n+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/from_days/','','https://mariadb.com/kb/en/library/from_days/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (485,31,'FROM_UNIXTIME','Syntax\n------ \nFROM_UNIXTIME(unix_timestamp),\nFROM_UNIXTIME(unix_timestamp,format)\n \nDescription\n----------- \nReturns a representation of the unix_timestamp argument as a\nvalue in\n\'YYYY-MM-DD HH:MM:SS\' or YYYYMMDDHHMMSS.uuuuuu format,\ndepending on\nwhether the function is used in a string or numeric context.\nThe value\nis expressed in the current time zone. unix_timestamp is an\ninternal\ntimestamp value such as is produced by the UNIX_TIMESTAMP()\nfunction.\n \nIf format is given, the result is formatted according to the\nformat\nstring, which is used the same way as listed in the entry\nfor the\nDATE_FORMAT() function.\n \nTimestamps in MariaDB have a maximum value of 2147483647,\nequivalent to 2038-01-19 05:14:07. This is due to the\nunderlying 32-bit limitation. Using the function on a\ntimestamp beyond this will result in NULL being returned.\nUse DATETIME as a storage type if you require dates beyond\nthis.\n \nThe options that can be used by FROM_UNIXTIME(), as well as\nDATE_FORMAT() and STR_TO_DATE(), are:\n \nOption | Description | \n \n%a | Short weekday name in current locale (Variable\nlc_time_names). | \n \n%b | Short form month name in current locale. For locale\nen_US this is one of:\nJan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov or Dec. | \n \n%c | Month with 1 or 2 digits. | \n \n%D | Day with English suffix \'th\', \'nd\', \'st\' or\n\'rd\'\'. (1st, 2nd, 3rd...). | \n \n%d | Day with 2 digits. | \n \n%e | Day with 1 or 2 digits. | \n \n%f | Sub seconds 6 digits. | \n \n%H | Hour with 2 digits between 00-23. | \n \n%h | Hour with 2 digits between 01-12. | \n \n%I | Hour with 2 digits between 01-12. | \n \n%i | Minute with 2 digits. | \n \n%j | Day of the year (001-366) | \n \n%k | Hour with 1 digits between 0-23. | \n \n%l | Hour with 1 digits between 1-12. | \n \n%M | Full month name in current locale (Variable\nlc_time_names). | \n \n%m | Month with 2 digits. | \n \n%p | AM/PM according to current locale (Variable\nlc_time_names). | \n \n%r | Time in 12 hour format, followed by AM/PM. Short for\n\'%I:%i:%S %p\'. | \n \n%S | Seconds with 2 digits. | \n \n%s | Seconds with 2 digits. | \n \n%T | Time in 24 hour format. Short for \'%H:%i:%S\'. | \n \n%U | Week number (00-53), when first day of the week is\nSunday. | \n \n%u | Week number (00-53), when first day of the week is\nMonday. | \n \n%V | Week number (01-53), when first day of the week is\nSunday. Used with %X. | \n \n%v | Week number (01-53), when first day of the week is\nMonday. Used with %x. | \n \n%W | Full weekday name in current locale (Variable\nlc_time_names). | \n \n%w | Day of the week. 0 = Sunday, 1 = Saturday. | \n \n%X | Year with 4 digits when first day of the week is\nSunday. Used with %V. | \n \n%x | Year with 4 digits when first day of the week is\nSunday. Used with %v. | \n \n%Y | Year with 4 digits. | \n \n%y | Year with 2 digits. | \n \n%# | For str_to_date(), skip all numbers. | \n \n%. | For str_to_date(), skip all punctation characters. | \n \n%@ | For str_to_date(), skip all alpha characters. | \n \n%% | A literal % character. | \n \nPerformance Considerations\n \nIf your session time zone is set to SYSTEM (the default),\nFROM_UNIXTIME() will call the OS function to convert the\ndata using the system time zone. At least on Linux, the\ncorresponding function (localtime_r) uses a global mutex\ninside glibc that can cause contention under high concurrent\nload.\n \nSet your time zone to a named time zone to avoid this issue.\nSee mysql time zone tables for details on how to do this.\n \nExamples\n-------- \nSELECT FROM_UNIXTIME(1196440219);\n+---------------------------+\n| FROM_UNIXTIME(1196440219) |\n+---------------------------+\n| 2007-11-30 11:30:19 |\n+---------------------------+\n \nSELECT FROM_UNIXTIME(1196440219) + 0;\n \n+-------------------------------+\n| FROM_UNIXTIME(1196440219) + 0 |\n+-------------------------------+\n| 20071130113019.000000 |\n+-------------------------------+\n \nSELECT FROM_UNIXTIME(UNIX_TIMESTAMP(), \'%Y %D %M %h:%i:%s\n%x\');\n+---------------------------------------------------------+\n| FROM_UNIXTIME(UNIX_TIMESTAMP(), \'%Y %D %M %h:%i:%s %x\')\n|\n+---------------------------------------------------------+\n| 2010 27th March 01:03:47 2010 |\n+---------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/from_unixtime/','','https://mariadb.com/kb/en/library/from_unixtime/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (486,31,'GET_FORMAT','Syntax\n------ \nGET_FORMAT({DATE|DATETIME|TIME},\n{\'EUR\'|\'USA\'|\'JIS\'|\'ISO\'|\'INTERNAL\'})\n \nDescription\n----------- \nReturns a format string. This function is useful in\ncombination with\nthe DATE_FORMAT() and the STR_TO_DATE() functions.\n \nPossible result formats are:\n \nFunction Call | Result Format | \n \nGET_FORMAT(DATE,\'EUR\') | \'%d.%m.%Y\' | \n \nGET_FORMAT(DATE,\'USA\') | \'%m.%d.%Y\' | \n \nGET_FORMAT(DATE,\'JIS\') | \'%Y-%m-%d\' | \n \nGET_FORMAT(DATE,\'ISO\') | \'%Y-%m-%d\' | \n \nGET_FORMAT(DATE,\'INTERNAL\') | \'%Y%m%d\' | \n \nGET_FORMAT(DATETIME,\'EUR\') | \'%Y-%m-%d %H.%i.%s\' | \n \nGET_FORMAT(DATETIME,\'USA\') | \'%Y-%m-%d %H.%i.%s\' | \n \nGET_FORMAT(DATETIME,\'JIS\') | \'%Y-%m-%d %H:%i:%s\' | \n \nGET_FORMAT(DATETIME,\'ISO\') | \'%Y-%m-%d %H:%i:%s\' | \n \nGET_FORMAT(DATETIME,\'INTERNAL\') | \'%Y%m%d%H%i%s\' | \n \nGET_FORMAT(TIME,\'EUR\') | \'%H.%i.%s\' | \n \nGET_FORMAT(TIME,\'USA\') | \'%h:%i:%s %p\' | \n \nGET_FORMAT(TIME,\'JIS\') | \'%H:%i:%s\' | \n \nGET_FORMAT(TIME,\'ISO\') | \'%H:%i:%s\' | \n \nGET_FORMAT(TIME,\'INTERNAL\') | \'%H%i%s\' | \n \nExamples\n-------- \nObtaining the string matching to the standard European date\nformat:\n \nSELECT GET_FORMAT(DATE, \'EUR\');\n+-------------------------+\n| GET_FORMAT(DATE, \'EUR\') |\n+-------------------------+\n| %d.%m.%Y |\n+-------------------------+\n \nUsing the same string to format a date:\n \nSELECT DATE_FORMAT(\'2003-10-03\',GET_FORMAT(DATE,\'EUR\'));\n+--------------------------------------------------+\n| DATE_FORMAT(\'2003-10-03\',GET_FORMAT(DATE,\'EUR\')) |\n+--------------------------------------------------+\n| 03.10.2003 |\n+--------------------------------------------------+\n \nSELECT STR_TO_DATE(\'10.31.2003\',GET_FORMAT(DATE,\'USA\'));\n+--------------------------------------------------+\n| STR_TO_DATE(\'10.31.2003\',GET_FORMAT(DATE,\'USA\')) |\n+--------------------------------------------------+\n| 2003-10-31 |\n+--------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/get_format/','','https://mariadb.com/kb/en/library/get_format/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (487,31,'HOUR','Syntax\n------ \nHOUR(time)\n \nDescription\n----------- \nReturns the hour for time. The range of the return value is\n0 to 23\nfor time-of-day values. However, the range of TIME values\nactually is\nmuch larger, so HOUR can return values greater than 23.\n \nThe return value is always positive, even if a negative TIME\nvalue is provided.\n \nExamples\n-------- \nSELECT HOUR(\'10:05:03\');\n+------------------+\n| HOUR(\'10:05:03\') |\n+------------------+\n| 10 |\n+------------------+\n \nSELECT HOUR(\'272:59:59\');\n+-------------------+\n| HOUR(\'272:59:59\') |\n+-------------------+\n| 272 |\n+-------------------+\n \nDifference between EXTRACT (HOUR FROM ...) (>= MariaDB\n10.0.7 and MariaDB 5.5.35) and HOUR:\n \nSELECT EXTRACT(HOUR FROM \'26:30:00\'), HOUR(\'26:30:00\');\n+-------------------------------+------------------+\n| EXTRACT(HOUR FROM \'26:30:00\') | HOUR(\'26:30:00\') |\n+-------------------------------+------------------+\n| 2 | 26 |\n+-------------------------------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/hour/','','https://mariadb.com/kb/en/library/hour/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (488,31,'LAST_DAY','Syntax\n------ \nLAST_DAY(date)\n \nDescription\n----------- \nTakes a date or datetime value and returns the corresponding\nvalue for\nthe last day of the month. Returns NULL if the argument is\ninvalid.\n \nExamples\n-------- \nSELECT LAST_DAY(\'2003-02-05\');\n+------------------------+\n| LAST_DAY(\'2003-02-05\') |\n+------------------------+\n| 2003-02-28 |\n+------------------------+\n \nSELECT LAST_DAY(\'2004-02-05\');\n+------------------------+\n| LAST_DAY(\'2004-02-05\') |\n+------------------------+\n| 2004-02-29 |\n+------------------------+\n \nSELECT LAST_DAY(\'2004-01-01 01:01:01\');\n+---------------------------------+\n| LAST_DAY(\'2004-01-01 01:01:01\') |\n+---------------------------------+\n| 2004-01-31 |\n+---------------------------------+\n \nSELECT LAST_DAY(\'2003-03-32\');\n+------------------------+\n| LAST_DAY(\'2003-03-32\') |\n+------------------------+\n| NULL |\n+------------------------+\n1 row in set, 1 warning (0.00 sec)\n \nWarning (Code 1292): Incorrect datetime value:\n\'2003-03-32\'\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/last_day/','','https://mariadb.com/kb/en/library/last_day/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (489,31,'LOCALTIME','Syntax\n------ \nLOCALTIME\nLOCALTIME([precision])\n \nDescription\n----------- \nLOCALTIME and LOCALTIME() are synonyms for NOW().\n \n\n\nURL: https://mariadb.com/kb/en/library/localtime/','','https://mariadb.com/kb/en/library/localtime/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (490,31,'LOCALTIMESTAMP','Syntax\n------ \nLOCALTIMESTAMP\nLOCALTIMESTAMP([precision])\n \nDescription\n----------- \nLOCALTIMESTAMP and LOCALTIMESTAMP() are synonyms for NOW().\n \n\n\nURL: https://mariadb.com/kb/en/library/localtimestamp/','','https://mariadb.com/kb/en/library/localtimestamp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (491,31,'MAKEDATE','Syntax\n------ \nMAKEDATE(year,dayofyear)\n \nDescription\n----------- \nReturns a date, given year and day-of-year values. dayofyear\nmust be\ngreater than 0 or the result is NULL.\n \nExamples\n-------- \nSELECT MAKEDATE(2011,31), MAKEDATE(2011,32);\n+-------------------+-------------------+\n| MAKEDATE(2011,31) | MAKEDATE(2011,32) |\n+-------------------+-------------------+\n| 2011-01-31 | 2011-02-01 |\n+-------------------+-------------------+\n \nSELECT MAKEDATE(2011,365), MAKEDATE(2014,365);\n+--------------------+--------------------+\n| MAKEDATE(2011,365) | MAKEDATE(2014,365) |\n+--------------------+--------------------+\n| 2011-12-31 | 2014-12-31 |\n+--------------------+--------------------+\n \nSELECT MAKEDATE(2011,0);\n+------------------+\n| MAKEDATE(2011,0) |\n+------------------+\n| NULL |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/makedate/','','https://mariadb.com/kb/en/library/makedate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (492,31,'MAKETIME','Syntax\n------ \nMAKETIME(hour,minute,second)\n \nDescription\n----------- \nReturns a time value calculated from the hour, minute, and\nsecond arguments.\n \nIf minute or second are out of the range 0 to 60, NULL is\nreturned. The hour can be in the range -838 to 838, outside\nof which the value is truncated with a warning.\n \nExamples\n-------- \nSELECT MAKETIME(13,57,33);\n+--------------------+\n| MAKETIME(13,57,33) |\n+--------------------+\n| 13:57:33 |\n+--------------------+\n \nSELECT MAKETIME(-13,57,33);\n+---------------------+\n| MAKETIME(-13,57,33) |\n+---------------------+\n| -13:57:33 |\n+---------------------+\n \nSELECT MAKETIME(13,67,33);\n+--------------------+\n| MAKETIME(13,67,33) |\n+--------------------+\n| NULL |\n+--------------------+\n \nSELECT MAKETIME(-1000,57,33);\n+-----------------------+\n| MAKETIME(-1000,57,33) |\n+-----------------------+\n| -838:59:59 |\n+-----------------------+\n1 row in set, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+---------+------+-----------------------------------------------+\n| Level | Code | Message |\n+---------+------+-----------------------------------------------+\n| Warning | 1292 | Truncated incorrect time value:\n\'-1000:57:33\' |\n+---------+------+-----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/maketime/','','https://mariadb.com/kb/en/library/maketime/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (493,31,'MICROSECOND','Syntax\n------ \nMICROSECOND(expr)\n \nDescription\n----------- \nReturns the microseconds from the time or datetime\nexpression expr as a number in the range from 0 to 999999.\n \nIf expr is a time with no microseconds, zero is returned,\nwhile if expr is a date with no time, zero with a warning is\nreturned.\n \nExamples\n-------- \nSELECT MICROSECOND(\'12:00:00.123456\');\n+--------------------------------+\n| MICROSECOND(\'12:00:00.123456\') |\n+--------------------------------+\n| 123456 |\n+--------------------------------+\n \nSELECT MICROSECOND(\'2009-12-31 23:59:59.000010\');\n+-------------------------------------------+\n| MICROSECOND(\'2009-12-31 23:59:59.000010\') |\n+-------------------------------------------+\n| 10 |\n+-------------------------------------------+\n \nSELECT MICROSECOND(\'2013-08-07 12:13:14\');\n+------------------------------------+\n| MICROSECOND(\'2013-08-07 12:13:14\') |\n+------------------------------------+\n| 0 |\n+------------------------------------+\n \nSELECT MICROSECOND(\'2013-08-07\');\n+---------------------------+\n| MICROSECOND(\'2013-08-07\') |\n+---------------------------+\n| 0 |\n+---------------------------+\n1 row in set, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+---------+------+----------------------------------------------+\n| Level | Code | Message |\n+---------+------+----------------------------------------------+\n| Warning | 1292 | Truncated incorrect time value:\n\'2013-08-07\' |\n+---------+------+----------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/microsecond/','','https://mariadb.com/kb/en/library/microsecond/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (494,31,'MINUTE','Syntax\n------ \nMINUTE(time)\n \nDescription\n----------- \nReturns the minute for time, in the range 0 to 59. \n \nExamples\n-------- \nSELECT MINUTE(\'2013-08-03 11:04:03\');\n+-------------------------------+\n| MINUTE(\'2013-08-03 11:04:03\') |\n+-------------------------------+\n| 4 |\n+-------------------------------+\n \n SELECT MINUTE (\'23:12:50\');\n+---------------------+\n| MINUTE (\'23:12:50\') |\n+---------------------+\n| 12 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/minute/','','https://mariadb.com/kb/en/library/minute/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (495,31,'MONTH','Syntax\n------ \nMONTH(date)\n \nDescription\n----------- \nReturns the month for date in the range 1 to 12 for January\nto\nDecember, or 0 for dates such as \'0000-00-00\' or\n\'2008-00-00\' that\nhave a zero month part.\n \nExamples\n-------- \nSELECT MONTH(\'2019-01-03\');\n+---------------------+\n| MONTH(\'2019-01-03\') |\n+---------------------+\n| 1 |\n+---------------------+\n \nSELECT MONTH(\'2019-00-03\');\n+---------------------+\n| MONTH(\'2019-00-03\') |\n+---------------------+\n| 0 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/month/','','https://mariadb.com/kb/en/library/month/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (496,31,'MONTHNAME','Syntax\n------ \nMONTHNAME(date)\n \nDescription\n----------- \nReturns the full name of the month for date. The language\nused for the name is controlled by the value of the\nlc_time_names system variable. See server locale for more on\nthe supported locales.\n \nExamples\n-------- \nSELECT MONTHNAME(\'2019-02-03\');\n+-------------------------+\n| MONTHNAME(\'2019-02-03\') |\n+-------------------------+\n| February |\n+-------------------------+\n \nChanging the locale:\n \nSET lc_time_names = \'fr_CA\';\n \nSELECT MONTHNAME(\'2019-05-21\');\n+-------------------------+\n| MONTHNAME(\'2019-05-21\') |\n+-------------------------+\n| mai |\n+-------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/monthname/','','https://mariadb.com/kb/en/library/monthname/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (497,31,'NOW','Syntax\n------ \nNOW([precision])\nCURRENT_TIMESTAMP\nCURRENT_TIMESTAMP([precision])\nLOCALTIME, LOCALTIME([precision])\nLOCALTIMESTAMP\nLOCALTIMESTAMP([precision])\n \nDescription\n----------- \nReturns the current date and time as a value in \'YYYY-MM-DD\nHH:MM:SS\'\nor YYYYMMDDHHMMSS.uuuuuu format, depending on whether the\nfunction is\nused in a string or numeric context. The value is expressed\nin the\ncurrent time zone.\n \nThe optional precision determines the microsecond precision.\nSee Microseconds in MariaDB.\n \nNOW() (or its synonyms) can be used as the default value for\nTIMESTAMP columns as well as, since MariaDB 10.0.1, DATETIME\ncolumns. Before MariaDB 10.0.1, it was only possible for a\nsingle TIMESTAMP column per table to contain the\nCURRENT_TIMESTAMP as its default.\n \nWhen displayed in the INFORMATION_SCHEMA.COLUMNS table, a\ndefault CURRENT TIMESTAMP is displayed as CURRENT_TIMESTAMP\nup until MariaDB 10.2.2, and as current_timestamp() from\nMariaDB 10.2.3, due to to MariaDB 10.2 accepting expressions\nin the DEFAULT clause.\n \nExamples\n-------- \nSELECT NOW();\n+---------------------+\n| NOW() |\n+---------------------+\n| 2010-03-27 13:13:25 |\n+---------------------+\n \nSELECT NOW() + 0;\n \n+-----------------------+\n| NOW() + 0 |\n+-----------------------+\n| 20100327131329.000000 |\n+-----------------------+\n \nWith precision:\n \nSELECT CURRENT_TIMESTAMP(2);\n+------------------------+\n| CURRENT_TIMESTAMP(2) |\n+------------------------+\n| 2018-07-10 09:47:26.24 |\n+------------------------+\n \nUsed as a default TIMESTAMP:\n \nCREATE TABLE t (createdTS TIMESTAMP NOT NULL DEFAULT\nCURRENT_TIMESTAMP);\n \nFrom MariaDB 10.2.2:\n \nSELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE\nTABLE_SCHEMA=\'test\'\n AND COLUMN_NAME LIKE \'%ts%\'\\G\n*************************** 1. row\n***************************\n TABLE_CATALOG: def\n TABLE_SCHEMA: test\n TABLE_NAME: t\n COLUMN_NAME: ts\n ORDINAL_POSITION: 1\n COLUMN_DEFAULT: current_timestamp()\n...\n \n\n\nURL: https://mariadb.com/kb/en/library/now/','','https://mariadb.com/kb/en/library/now/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (498,31,'PERIOD_ADD','Syntax\n------ \nPERIOD_ADD(P,N)\n \nDescription\n----------- \nAdds N months to period P. P is in the format YYMM or\nYYYYMM, and is not a date value. If P contains a two-digit\nyear, values from 00 to 69 are converted to from 2000 to\n2069, while values from 70 are converted to 1970 upwards.\n \nReturns a value in the format YYYYMM.\n \nExamples\n-------- \nSELECT PERIOD_ADD(200801,2);\n+----------------------+\n| PERIOD_ADD(200801,2) |\n+----------------------+\n| 200803 |\n+----------------------+\n \nSELECT PERIOD_ADD(6910,2);\n+--------------------+\n| PERIOD_ADD(6910,2) |\n+--------------------+\n| 206912 |\n+--------------------+\n \nSELECT PERIOD_ADD(7010,2);\n+--------------------+\n| PERIOD_ADD(7010,2) |\n+--------------------+\n| 197012 |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/period_add/','','https://mariadb.com/kb/en/library/period_add/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (499,31,'PERIOD_DIFF','Syntax\n------ \nPERIOD_DIFF(P1,P2)\n \nDescription\n----------- \nReturns the number of months between periods P1 and P2. P1\nand P2 \ncan be in the format YYMM or YYYYMM, and are not date\nvalues.\n \nIf P1 or P2 contains a two-digit year, values from 00 to 69\nare converted to from 2000 to 2069, while values from 70 are\nconverted to 1970 upwards.\n \nExamples\n-------- \nSELECT PERIOD_DIFF(200802,200703);\n+----------------------------+\n| PERIOD_DIFF(200802,200703) |\n+----------------------------+\n| 11 |\n+----------------------------+\n \nSELECT PERIOD_DIFF(6902,6803);\n+------------------------+\n| PERIOD_DIFF(6902,6803) |\n+------------------------+\n| 11 |\n+------------------------+\n \nSELECT PERIOD_DIFF(7002,6803);\n+------------------------+\n| PERIOD_DIFF(7002,6803) |\n+------------------------+\n| -1177 |\n+------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/period_diff/','','https://mariadb.com/kb/en/library/period_diff/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (500,31,'QUARTER','Syntax\n------ \nQUARTER(date)\n \nDescription\n----------- \nReturns the quarter of the year for date, in the range 1 to\n4. Returns 0 if month contains a zero value, or NULL if the\ngiven value is not otherwise a valid date (zero values are\naccepted).\n \nExamples\n-------- \nSELECT QUARTER(\'2008-04-01\');\n+-----------------------+\n| QUARTER(\'2008-04-01\') |\n+-----------------------+\n| 2 |\n+-----------------------+\n \nSELECT QUARTER(\'2019-00-01\');\n+-----------------------+\n| QUARTER(\'2019-00-01\') |\n+-----------------------+\n| 0 |\n+-----------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/quarter/','','https://mariadb.com/kb/en/library/quarter/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (501,31,'SECOND','Syntax\n------ \nSECOND(time)\n \nDescription\n----------- \nReturns the second for a given time (which can include\nmicroseconds), in the range 0 to 59, or NULL if not given a\nvalid time value.\n \nExamples\n-------- \nSELECT SECOND(\'10:05:03\');\n+--------------------+\n| SECOND(\'10:05:03\') |\n+--------------------+\n| 3 |\n+--------------------+\n \nSELECT SECOND(\'10:05:01.999999\');\n+---------------------------+\n| SECOND(\'10:05:01.999999\') |\n+---------------------------+\n| 1 |\n+---------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/second/','','https://mariadb.com/kb/en/library/second/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (502,31,'SEC_TO_TIME','Syntax\n------ \nSEC_TO_TIME(seconds)\n \nDescription\n----------- \nReturns the seconds argument, converted to hours, minutes,\nand\nseconds, as a TIME value. The range of the result is\nconstrained to\nthat of the TIME data type. A warning occurs if the argument\ncorresponds to a value outside that range.\n \nThe time will be returned in the format hh:mm:ss, or hhmmss\nif used in a numeric calculation.\n \nExamples\n-------- \nSELECT SEC_TO_TIME(12414);\n+--------------------+\n| SEC_TO_TIME(12414) |\n+--------------------+\n| 03:26:54 |\n+--------------------+\n \nSELECT SEC_TO_TIME(12414)+0;\n \n+----------------------+\n| SEC_TO_TIME(12414)+0 |\n+----------------------+\n| 32654 |\n+----------------------+\n \nSELECT SEC_TO_TIME(9999999);\n+----------------------+\n| SEC_TO_TIME(9999999) |\n+----------------------+\n| 838:59:59 |\n+----------------------+\n1 row in set, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+---------+------+-------------------------------------------+\n| Level | Code | Message |\n+---------+------+-------------------------------------------+\n| Warning | 1292 | Truncated incorrect time value:\n\'9999999\' |\n+---------+------+-------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/sec_to_time/','','https://mariadb.com/kb/en/library/sec_to_time/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (503,31,'STR_TO_DATE','Syntax\n------ \nSTR_TO_DATE(str,format)\n \nDescription\n----------- \nThis is the inverse of the DATE_FORMAT() function. It takes\na string str and a format string format. STR_TO_DATE()\nreturns a\nDATETIME value if the format string contains both date and\ntime parts, or a\nDATE or TIME value if the string contains only date or time\nparts.\n \nThe date, time, or datetime values contained in str should\nbe given in the format indicated by format. If str contains\nan illegal date, time, or datetime value, STR_TO_DATE()\nreturns NULL. An illegal value also produces a warning.\n \nThe options that can be used by STR_TO_DATE(), as well as\nits inverse DATE_FORMAT() and the FROM_UNIXTIME() function,\nare:\n \nOption | Description | \n \n%a | Short weekday name in current locale (Variable\nlc_time_names). | \n \n%b | Short form month name in current locale. For locale\nen_US this is one of:\nJan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov or Dec. | \n \n%c | Month with 1 or 2 digits. | \n \n%D | Day with English suffix \'th\', \'nd\', \'st\' or\n\'rd\'\'. (1st, 2nd, 3rd...). | \n \n%d | Day with 2 digits. | \n \n%e | Day with 1 or 2 digits. | \n \n%f | Sub seconds 6 digits. | \n \n%H | Hour with 2 digits between 00-23. | \n \n%h | Hour with 2 digits between 01-12. | \n \n%I | Hour with 2 digits between 01-12. | \n \n%i | Minute with 2 digits. | \n \n%j | Day of the year (001-366) | \n \n%k | Hour with 1 digits between 0-23. | \n \n%l | Hour with 1 digits between 1-12. | \n \n%M | Full month name in current locale (Variable\nlc_time_names). | \n \n%m | Month with 2 digits. | \n \n%p | AM/PM according to current locale (Variable\nlc_time_names). | \n \n%r | Time in 12 hour format, followed by AM/PM. Short for\n\'%I:%i:%S %p\'. | \n \n%S | Seconds with 2 digits. | \n \n%s | Seconds with 2 digits. | \n \n%T | Time in 24 hour format. Short for \'%H:%i:%S\'. | \n \n%U | Week number (00-53), when first day of the week is\nSunday. | \n \n%u | Week number (00-53), when first day of the week is\nMonday. | \n \n%V | Week number (01-53), when first day of the week is\nSunday. Used with %X. | \n \n%v | Week number (01-53), when first day of the week is\nMonday. Used with %x. | \n \n%W | Full weekday name in current locale (Variable\nlc_time_names). | \n \n%w | Day of the week. 0 = Sunday, 6 = Saturday. | \n \n%X | Year with 4 digits when first day of the week is\nSunday. Used with %V. | \n \n%x | Year with 4 digits when first day of the week is\nMonday. Used with %v. | \n \n%Y | Year with 4 digits. | \n \n%y | Year with 2 digits. | \n \n%# | For str_to_date(), skip all numbers. | \n \n%. | For str_to_date(), skip all punctation characters. | \n \n%@ | For str_to_date(), skip all alpha characters. | \n \n%% | A literal % character. | \n \nExamples\n-------- \nSELECT STR_TO_DATE(\'Wednesday, June 2, 2014\', \'%W, %M %e,\n%Y\');\n+---------------------------------------------------------+\n| STR_TO_DATE(\'Wednesday, June 2, 2014\', \'%W, %M %e,\n%Y\') |\n+---------------------------------------------------------+\n| 2014-06-02 |\n+---------------------------------------------------------+\n \nSELECT STR_TO_DATE(\'Wednesday23423, June 2, 2014\', \'%W,\n%M %e, %Y\');\n+--------------------------------------------------------------+\n| STR_TO_DATE(\'Wednesday23423, June 2, 2014\', \'%W, %M %e,\n%Y\') |\n+--------------------------------------------------------------+\n| NULL |\n+--------------------------------------------------------------+\n1 row in set, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+---------+------+-----------------------------------------------------------------------------------+\n| Level | Code | Message |\n+---------+------+-----------------------------------------------------------------------------------+\n| Warning | 1411 | Incorrect datetime value:\n\'Wednesday23423, June 2, 2014\' for function str_to_date |\n+---------+------+-----------------------------------------------------------------------------------+\n \nSELECT STR_TO_DATE(\'Wednesday23423, June 2, 2014\', \'%W%#,\n%M %e, %Y\');\n+----------------------------------------------------------------+\n| STR_TO_DATE(\'Wednesday23423, June 2, 2014\', \'%W%#, %M\n%e, %Y\') |\n+----------------------------------------------------------------+\n| 2014-06-02 |\n+----------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/str_to_date/','','https://mariadb.com/kb/en/library/str_to_date/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (504,31,'SUBDATE','Syntax\n------ \nSUBDATE(date,INTERVAL expr unit), SUBDATE(expr,days)\n \nDescription\n----------- \nWhen invoked with the INTERVAL form of the second argument,\nSUBDATE()\nis a synonym for DATE_SUB(). See Date and Time Units for a\ncomplete list of permitted units. \n \nThe second form allows the use of an integer value for days.\nIn such\ncases, it is interpreted as the number of days to be\nsubtracted from\nthe date or datetime expression expr.\n \nExamples\n-------- \nSELECT DATE_SUB(\'2008-01-02\', INTERVAL 31 DAY);\n+-----------------------------------------+\n| DATE_SUB(\'2008-01-02\', INTERVAL 31 DAY) |\n+-----------------------------------------+\n| 2007-12-02 |\n+-----------------------------------------+\n \nSELECT SUBDATE(\'2008-01-02\', INTERVAL 31 DAY);\n+----------------------------------------+\n| SUBDATE(\'2008-01-02\', INTERVAL 31 DAY) |\n+----------------------------------------+\n| 2007-12-02 |\n+----------------------------------------+\n \nSELECT SUBDATE(\'2008-01-02 12:00:00\', 31);\n+------------------------------------+\n| SUBDATE(\'2008-01-02 12:00:00\', 31) |\n+------------------------------------+\n| 2007-12-02 12:00:00 |\n+------------------------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT d, SUBDATE(d, 10) from t1;\n \n+---------------------+---------------------+\n| d | SUBDATE(d, 10) |\n+---------------------+---------------------+\n| 2007-01-30 21:31:07 | 2007-01-20 21:31:07 |\n| 1983-10-15 06:42:51 | 1983-10-05 06:42:51 |\n| 2011-04-21 12:34:56 | 2011-04-11 12:34:56 |\n| 2011-10-30 06:31:41 | 2011-10-20 06:31:41 |\n| 2011-01-30 14:03:25 | 2011-01-20 14:03:25 |\n| 2004-10-07 11:19:34 | 2004-09-27 11:19:34 |\n+---------------------+---------------------+\n \nSELECT d, SUBDATE(d, INTERVAL 10 MINUTE) from t1;\n \n+---------------------+--------------------------------+\n| d | SUBDATE(d, INTERVAL 10 MINUTE) |\n+---------------------+--------------------------------+\n| 2007-01-30 21:31:07 | 2007-01-30 21:21:07 |\n| 1983-10-15 06:42:51 | 1983-10-15 06:32:51 |\n| 2011-04-21 12:34:56 | 2011-04-21 12:24:56 |\n| 2011-10-30 06:31:41 | 2011-10-30 06:21:41 |\n| 2011-01-30 14:03:25 | 2011-01-30 13:53:25 |\n| 2004-10-07 11:19:34 | 2004-10-07 11:09:34 |\n+---------------------+--------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/subdate/','','https://mariadb.com/kb/en/library/subdate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (505,31,'SUBTIME','Syntax\n------ \nSUBTIME(expr1,expr2)\n \nDescription\n----------- \nSUBTIME() returns expr1 - expr2 expressed as a value in the\nsame\nformat as expr1. expr1 is a time or datetime expression, and\nexpr2 is\na time expression.\n \nExamples\n-------- \nSELECT SUBTIME(\'2007-12-31 23:59:59.999999\',\'1\n1:1:1.000002\');\n+--------------------------------------------------------+\n| SUBTIME(\'2007-12-31 23:59:59.999999\',\'1 1:1:1.000002\')\n|\n+--------------------------------------------------------+\n| 2007-12-30 22:58:58.999997 |\n+--------------------------------------------------------+\n \nSELECT SUBTIME(\'01:00:00.999999\', \'02:00:00.999998\');\n+-----------------------------------------------+\n| SUBTIME(\'01:00:00.999999\', \'02:00:00.999998\') |\n+-----------------------------------------------+\n| -00:59:59.999999 |\n+-----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/subtime/','','https://mariadb.com/kb/en/library/subtime/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (506,31,'SYSDATE','Syntax\n------ \nSYSDATE([precision])\n \nDescription\n----------- \nReturns the current date and time as a value in \'YYYY-MM-DD\nHH:MM:SS\'\nor YYYYMMDDHHMMSS.uuuuuu format, depending on whether the\nfunction is\nused in a string or numeric context.\n \nThe optional precision determines the microsecond precision.\nSee Microseconds in MariaDB.\n \nSYSDATE() returns the time at which it executes. This\ndiffers from the\nbehavior for NOW(), which returns a constant time that\nindicates the\ntime at which the statement began to execute. (Within a\nstored routine\nor trigger, NOW() returns the time at which the routine or\ntriggering\nstatement began to execute.)\n \nIn addition, changing the timestamp system variable with a\nSET timestamp statement affects the value returned by\nNOW() but not by SYSDATE(). This means that timestamp\nsettings in the\nbinary log have no effect on invocations of SYSDATE().\n \nBecause SYSDATE() can return different values even within\nthe same\nstatement, and is not affected by SET TIMESTAMP, it is\nnon-deterministic and therefore unsafe for replication if\nstatement-based binary logging is used. If that is a\nproblem, you can\nuse row-based logging, or start the server with the mysqld\noption --sysdate-is-now to cause SYSDATE() to be an alias\nfor NOW(). The non-deterministic nature of SYSDATE() also\nmeans that indexes cannot be used for evaluating expressions\nthat refer to it, and that statements using the SYSDATE()\nfunction are unsafe for statement-based replication.\n \nExamples\n-------- \nDifference between NOW() and SYSDATE():\n \nSELECT NOW(), SLEEP(2), NOW();\n+---------------------+----------+---------------------+\n| NOW() | SLEEP(2) | NOW() |\n+---------------------+----------+---------------------+\n| 2010-03-27 13:23:40 | 0 | 2010-03-27 13:23:40 |\n+---------------------+----------+---------------------+\n \nSELECT SYSDATE(), SLEEP(2), SYSDATE();\n+---------------------+----------+---------------------+\n| SYSDATE() | SLEEP(2) | SYSDATE() |\n+---------------------+----------+---------------------+\n| 2010-03-27 13:23:52 | 0 | 2010-03-27 13:23:54 |\n+---------------------+----------+---------------------+\n \nWith precision:\n \nSELECT SYSDATE(4);\n+--------------------------+\n| SYSDATE(4) |\n+--------------------------+\n| 2018-07-10 10:17:13.1689 |\n+--------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/sysdate/','','https://mariadb.com/kb/en/library/sysdate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (507,31,'TIME Function','Syntax\n------ \nTIME(expr)\n \nDescription\n----------- \nExtracts the time part of the time or datetime expression\nexpr and\nreturns it as a string.\n \nExamples\n-------- \nSELECT TIME(\'2003-12-31 01:02:03\');\n+-----------------------------+\n| TIME(\'2003-12-31 01:02:03\') |\n+-----------------------------+\n| 01:02:03 |\n+-----------------------------+\n \nSELECT TIME(\'2003-12-31 01:02:03.000123\');\n+------------------------------------+\n| TIME(\'2003-12-31 01:02:03.000123\') |\n+------------------------------------+\n| 01:02:03.000123 |\n+------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/time-function/','','https://mariadb.com/kb/en/library/time-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (508,31,'TIMEDIFF','Syntax\n------ \nTIMEDIFF(expr1,expr2)\n \nDescription\n----------- \nTIMEDIFF() returns expr1 - expr2 expressed as a time value.\nexpr1 and\nexpr2 are time or date-and-time expressions, but both must\nbe of the\nsame type.\n \nExamples\n-------- \nSELECT TIMEDIFF(\'2000:01:01 00:00:00\', \'2000:01:01\n00:00:00.000001\');\n+---------------------------------------------------------------+\n| TIMEDIFF(\'2000:01:01 00:00:00\', \'2000:01:01\n00:00:00.000001\') |\n+---------------------------------------------------------------+\n| -00:00:00.000001 |\n+---------------------------------------------------------------+\n \nSELECT TIMEDIFF(\'2008-12-31 23:59:59.000001\', \'2008-12-30\n01:01:01.000002\');\n+----------------------------------------------------------------------+\n| TIMEDIFF(\'2008-12-31 23:59:59.000001\', \'2008-12-30\n01:01:01.000002\') |\n+----------------------------------------------------------------------+\n| 46:58:57.999999 |\n+----------------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/timediff/','','https://mariadb.com/kb/en/library/timediff/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (509,31,'TIMESTAMP FUNCTION','Syntax\n------ \nTIMESTAMP(expr), TIMESTAMP(expr1,expr2)\n \nDescription\n----------- \nWith a single argument, this function returns the date or\ndatetime\nexpression expr as a datetime value. With two arguments, it\nadds the\ntime expression expr2 to the date or datetime expression\nexpr1 and\nreturns the result as a datetime value.\n \nExamples\n-------- \nSELECT TIMESTAMP(\'2003-12-31\');\n+-------------------------+\n| TIMESTAMP(\'2003-12-31\') |\n+-------------------------+\n| 2003-12-31 00:00:00 |\n+-------------------------+\n \nSELECT TIMESTAMP(\'2003-12-31 12:00:00\',\'6:30:00\');\n+--------------------------------------------+\n| TIMESTAMP(\'2003-12-31 12:00:00\',\'6:30:00\') |\n+--------------------------------------------+\n| 2003-12-31 18:30:00 |\n+--------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/timestamp-function/','','https://mariadb.com/kb/en/library/timestamp-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (510,31,'TIMESTAMPADD','Syntax\n------ \nTIMESTAMPADD(unit,interval,datetime_expr)\n \nDescription\n----------- \nAdds the integer expression interval to the date or datetime\nexpression datetime_expr. The unit for interval is given by\nthe unit\nargument, which should be one of the following values:\nMICROSECOND, SECOND, MINUTE, HOUR, DAY, WEEK, MONTH,\nQUARTER, or YEAR.\n \nThe unit value may be specified using one of keywords as\nshown, or\nwith a prefix of SQL_TSI_. For example, DAY and SQL_TSI_DAY\nboth are\nlegal.\n \nBefore MariaDB 5.5, FRAC_SECOND was permitted as a synonym\nfor MICROSECOND.\n \nExamples\n-------- \nSELECT TIMESTAMPADD(MINUTE,1,\'2003-01-02\');\n+-------------------------------------+\n| TIMESTAMPADD(MINUTE,1,\'2003-01-02\') |\n+-------------------------------------+\n| 2003-01-02 00:01:00 |\n+-------------------------------------+\n \nSELECT TIMESTAMPADD(WEEK,1,\'2003-01-02\');\n+-----------------------------------+\n| TIMESTAMPADD(WEEK,1,\'2003-01-02\') |\n+-----------------------------------+\n| 2003-01-09 |\n+-----------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/timestampadd/','','https://mariadb.com/kb/en/library/timestampadd/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (511,31,'TIMESTAMPDIFF','Syntax\n------ \nTIMESTAMPDIFF(unit,datetime_expr1,datetime_expr2)\n \nDescription\n----------- \nReturns datetime_expr2 - datetime_expr1, where\ndatetime_expr1 and\ndatetime_expr2 are date or datetime expressions. One\nexpression may be\na date and the other a datetime; a date value is treated as\na datetime\nhaving the time part \'00:00:00\' where necessary. The unit\nfor the\nresult (an integer) is given by the unit argument. The legal\nvalues\nfor unit are the same as those listed in the description of\nthe\nTIMESTAMPADD() function, i.e MICROSECOND, SECOND, MINUTE,\nHOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.\n \nTIMESTAMPDIFF can also be used to calculate age.\n \nExamples\n-------- \nSELECT TIMESTAMPDIFF(MONTH,\'2003-02-01\',\'2003-05-01\');\n+------------------------------------------------+\n| TIMESTAMPDIFF(MONTH,\'2003-02-01\',\'2003-05-01\') |\n+------------------------------------------------+\n| 3 |\n+------------------------------------------------+\n \nSELECT TIMESTAMPDIFF(YEAR,\'2002-05-01\',\'2001-01-01\');\n+-----------------------------------------------+\n| TIMESTAMPDIFF(YEAR,\'2002-05-01\',\'2001-01-01\') |\n+-----------------------------------------------+\n| -1 |\n+-----------------------------------------------+\n \nSELECT TIMESTAMPDIFF(MINUTE,\'2003-02-01\',\'2003-05-01\n12:05:55\');\n+----------------------------------------------------------+\n| TIMESTAMPDIFF(MINUTE,\'2003-02-01\',\'2003-05-01\n12:05:55\') |\n+----------------------------------------------------------+\n| 128885 |\n+----------------------------------------------------------+\n \nCalculating age:\n \nSELECT CURDATE();\n+------------+\n| CURDATE() |\n+------------+\n| 2019-05-27 |\n+------------+\n \nSELECT TIMESTAMPDIFF(YEAR, \'1971-06-06\', CURDATE()) AS\nage;\n \n+------+\n| age |\n+------+\n| 47 |\n+------+\n \nSELECT TIMESTAMPDIFF(YEAR, \'1971-05-06\', CURDATE()) AS\nage;\n \n+------+\n| age |\n+------+\n| 48 |\n+------+\n \nAge as of 2014-08-02:\n \nSELECT name, date_of_birth,\nTIMESTAMPDIFF(YEAR,date_of_birth,\'2014-08-02\') AS age \n FROM student_details;\n \n+---------+---------------+------+\n| name | date_of_birth | age |\n+---------+---------------+------+\n| Chun | 1993-12-31 | 20 |\n| Esben | 1946-01-01 | 68 |\n| Kaolin | 1996-07-16 | 18 |\n| Tatiana | 1988-04-13 | 26 |\n+---------+---------------+------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/timestampdiff/','','https://mariadb.com/kb/en/library/timestampdiff/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (512,31,'TIME_FORMAT','Syntax\n------ \nTIME_FORMAT(time,format)\n \nDescription\n----------- \nThis is used like the DATE_FORMAT() function, but the format\nstring\nmay contain format specifiers only for hours, minutes, and\nseconds.\nOther specifiers produce a NULL value or 0.\n \nExamples\n-------- \nSELECT TIME_FORMAT(\'100:00:00\', \'%H %k %h %I %l\');\n+--------------------------------------------+\n| TIME_FORMAT(\'100:00:00\', \'%H %k %h %I %l\') |\n+--------------------------------------------+\n| 100 100 04 04 4 |\n+--------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/time_format/','','https://mariadb.com/kb/en/library/time_format/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (513,31,'TIME_TO_SEC','Syntax\n------ \nTIME_TO_SEC(time)\n \nDescription\n----------- \nReturns the time argument, converted to seconds.\n \nThe value returned by TIME_TO_SEC is of type DOUBLE. Before\nMariaDB 5.3 (and MySQL 5.6), the type was INT. See\nMicroseconds in MariaDB.\n \nExamples\n-------- \nSELECT TIME_TO_SEC(\'22:23:00\');\n+-------------------------+\n| TIME_TO_SEC(\'22:23:00\') |\n+-------------------------+\n| 80580 |\n+-------------------------+\n \nSELECT TIME_TO_SEC(\'00:39:38\');\n+-------------------------+\n| TIME_TO_SEC(\'00:39:38\') |\n+-------------------------+\n| 2378 |\n+-------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/time_to_sec/','','https://mariadb.com/kb/en/library/time_to_sec/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (514,31,'TO_DAYS','Syntax\n------ \nTO_DAYS(date)\n \nDescription\n----------- \nGiven a date date, returns the number of days since the\nstart of the current calendar (0000-00-00).\n \nThe function is not designed for use with dates before the\nadvent of the Gregorian calendar in October 1582. Results\nwill not be reliable since it doesn\'t account for the lost\ndays when the calendar changed from the Julian calendar.\n \nThis is the converse of the FROM_DAYS() function.\n \nExamples\n-------- \nSELECT TO_DAYS(\'2007-10-07\');\n+-----------------------+\n| TO_DAYS(\'2007-10-07\') |\n+-----------------------+\n| 733321 |\n+-----------------------+\n \nSELECT TO_DAYS(\'0000-01-01\');\n+-----------------------+\n| TO_DAYS(\'0000-01-01\') |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nSELECT TO_DAYS(950501);\n+-----------------+\n| TO_DAYS(950501) |\n+-----------------+\n| 728779 |\n+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/to_days/','','https://mariadb.com/kb/en/library/to_days/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (515,31,'TO_SECONDS','Syntax\n------ \nTO_SECONDS(expr)\n \nDescription\n----------- \nReturns the number of seconds from year 0 till expr, or NULL\nif expr is not a valid date or datetime.\n \nExamples\n-------- \nSELECT TO_SECONDS(\'2013-06-13\');\n+--------------------------+\n| TO_SECONDS(\'2013-06-13\') |\n+--------------------------+\n| 63538300800 |\n+--------------------------+\n \nSELECT TO_SECONDS(\'2013-06-13 21:45:13\');\n+-----------------------------------+\n| TO_SECONDS(\'2013-06-13 21:45:13\') |\n+-----------------------------------+\n| 63538379113 |\n+-----------------------------------+\n \nSELECT TO_SECONDS(NOW());\n+-------------------+\n| TO_SECONDS(NOW()) |\n+-------------------+\n| 63543530875 |\n+-------------------+\n \nSELECT TO_SECONDS(20130513);\n+----------------------+\n| TO_SECONDS(20130513) |\n+----------------------+\n| 63535622400 |\n+----------------------+\n1 row in set (0.00 sec)\n \nSELECT TO_SECONDS(130513);\n+--------------------+\n| TO_SECONDS(130513) |\n+--------------------+\n| 63535622400 |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/to_seconds/','','https://mariadb.com/kb/en/library/to_seconds/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (516,31,'UNIX_TIMESTAMP','Syntax\n------ \nUNIX_TIMESTAMP()\nUNIX_TIMESTAMP(date)\n \nDescription\n----------- \nIf called with no argument, returns a Unix timestamp\n(seconds since\n\'1970-01-01 00:00:00\' UTC) as an unsigned integer. If\nUNIX_TIMESTAMP()\nis called with a date argument, it returns the value of the\nargument as seconds\nsince \'1970-01-01 00:00:00\' UTC. date may be a DATE\nstring, a\nDATETIME string, a TIMESTAMP, or a number in\nthe format YYMMDD or YYYYMMDD. The server interprets date as\na value in the\ncurrent time zone and converts it to an internal value in\nUTC. Clients can set\ntheir time zone as described in time zones.\n \nThe inverse function of UNIX_TIMESTAMP() is FROM_UNIXTIME()\n \nUNIX_TIMESTAMP() supports microseconds.\n \nTimestamps in MariaDB have a maximum value of 2147483647,\nequivalent to 2038-01-19 05:14:07. This is due to the\nunderlying 32-bit limitation. Using the function on a date\nbeyond this will result in NULL being returned. Use DATETIME\nas a storage type if you require dates beyond this.\n \nError Handling\n \nReturns NULL for wrong arguments to UNIX_TIMESTAMP(). In\nMySQL and MariaDB before 5.3 wrong arguments to\nUNIX_TIMESTAMP() returned 0. \n \nCompatibility\n \nAs you can see in the examples above,\nUNIX_TIMESTAMP(constant-date-string) returns a timestamp\nwith 6 decimals while MariaDB 5.2 and before returns it\nwithout decimals. This can cause a problem if you are using\nUNIX_TIMESTAMP() as a partitioning function. You can fix\nthis by using FLOOR(UNIX_TIMESTAMP(..)) or changing the date\nstring to a date number, like 20080101000000. \n \nExamples\n-------- \nSELECT UNIX_TIMESTAMP();\n+------------------+\n| UNIX_TIMESTAMP() |\n+------------------+\n| 1269711082 |\n+------------------+\n \nSELECT UNIX_TIMESTAMP(\'2007-11-30 10:30:19\');\n+---------------------------------------+\n| UNIX_TIMESTAMP(\'2007-11-30 10:30:19\') |\n+---------------------------------------+\n| 1196436619.000000 |\n+---------------------------------------+\n \nSELECT UNIX_TIMESTAMP(\"2007-11-30 10:30:19.123456\");\n+----------------------------------------------+\n| unix_timestamp(\"2007-11-30 10:30:19.123456\") |\n+----------------------------------------------+\n| 1196411419.123456 |\n+----------------------------------------------+\n \nSELECT FROM_UNIXTIME(UNIX_TIMESTAMP(\'2007-11-30\n10:30:19\'));\n+------------------------------------------------------+\n| FROM_UNIXTIME(UNIX_TIMESTAMP(\'2007-11-30 10:30:19\')) |\n+------------------------------------------------------+\n| 2007-11-30 10:30:19.000000 |\n+------------------------------------------------------+\n \nSELECT FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(\'2007-11-30\n10:30:19\')));\n+-------------------------------------------------------------+\n| FROM_UNIXTIME(FLOOR(UNIX_TIMESTAMP(\'2007-11-30\n10:30:19\'))) |\n+-------------------------------------------------------------+\n| 2007-11-30 10:30:19 |\n+-------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/unix_timestamp/','','https://mariadb.com/kb/en/library/unix_timestamp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (517,31,'UTC_DATE','Syntax\n------ \nUTC_DATE, UTC_DATE()\n \nDescription\n----------- \nReturns the current UTC date as a value in \'YYYY-MM-DD\' or\nYYYYMMDD\nformat, depending on whether the function is used in a\nstring or numeric context. \n \nExamples\n-------- \nSELECT UTC_DATE(), UTC_DATE() + 0;\n \n+------------+----------------+\n| UTC_DATE() | UTC_DATE() + 0 |\n+------------+----------------+\n| 2010-03-27 | 20100327 |\n+------------+----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/utc_date/','','https://mariadb.com/kb/en/library/utc_date/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (518,31,'UTC_TIME','Syntax\n------ \nUTC_TIME\nUTC_TIME([precision])\n \nDescription\n----------- \nReturns the current UTC time as a value in \'HH:MM:SS\' or\nHHMMSS.uuuuuu format, depending on whether the function is\nused in a string or numeric context. \n \nThe optional precision determines the microsecond precision.\nSee Microseconds in MariaDB.\n \nExamples\n-------- \nSELECT UTC_TIME(), UTC_TIME() + 0;\n \n+------------+----------------+\n| UTC_TIME() | UTC_TIME() + 0 |\n+------------+----------------+\n| 17:32:34 | 173234.000000 |\n+------------+----------------+\n \nWith precision:\n \nSELECT UTC_TIME(5);\n+----------------+\n| UTC_TIME(5) |\n+----------------+\n| 07:52:50.78369 |\n+----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/utc_time/','','https://mariadb.com/kb/en/library/utc_time/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (519,31,'UTC_TIMESTAMP','Syntax\n------ \nUTC_TIMESTAMP\nUTC_TIMESTAMP([precision])\n \nDescription\n----------- \nReturns the current UTC date and time as a value in\n\'YYYY-MM-DD\nHH:MM:SS\' or YYYYMMDDHHMMSS.uuuuuu format, depending on\nwhether the\nfunction is used in a string or numeric context.\n \nThe optional precision determines the microsecond precision.\nSee Microseconds in MariaDB.\n \nExamples\n-------- \nSELECT UTC_TIMESTAMP(), UTC_TIMESTAMP() + 0;\n \n+---------------------+-----------------------+\n| UTC_TIMESTAMP() | UTC_TIMESTAMP() + 0 |\n+---------------------+-----------------------+\n| 2010-03-27 17:33:16 | 20100327173316.000000 |\n+---------------------+-----------------------+\n \nWith precision:\n \nSELECT UTC_TIMESTAMP(4);\n+--------------------------+\n| UTC_TIMESTAMP(4) |\n+--------------------------+\n| 2018-07-10 07:51:09.1019 |\n+--------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/utc_timestamp/','','https://mariadb.com/kb/en/library/utc_timestamp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (520,31,'WEEK','Syntax\n------ \nWEEK(date[,mode])\n \nDescription\n----------- \nThis function returns the week number for date. The\ntwo-argument form of\nWEEK() allows you to specify whether the week starts on\nSunday or Monday\nand whether the return value should be in the range from 0\nto 53 or from 1 to\n53. If the mode argument is omitted, the value of the\ndefault_week_format system variable is used.\n \nModes\n \nMode | 1st day of week | Range | Week 1 is the 1st week with\n| \n \n0 | Sunday | 0-53 | a Sunday in this year | \n \n1 | Monday | 0-53 | more than 3 days this year | \n \n2 | Sunday | 1-53 | a Sunday in this year | \n \n3 | Monday | 1-53 | more than 3 days this year | \n \n4 | Sunday | 0-53 | more than 3 days this year | \n \n5 | Monday | 0-53 | a Monday in this year | \n \n6 | Sunday | 1-53 | more than 3 days this year | \n \n7 | Monday | 1-53 | a Monday in this year | \n \nExamples\n-------- \nSELECT WEEK(\'2008-02-20\');\n+--------------------+\n| WEEK(\'2008-02-20\') |\n+--------------------+\n| 7 |\n+--------------------+\n \nSELECT WEEK(\'2008-02-20\',0);\n+----------------------+\n| WEEK(\'2008-02-20\',0) |\n+----------------------+\n| 7 |\n+----------------------+\n \nSELECT WEEK(\'2008-02-20\',1);\n+----------------------+\n| WEEK(\'2008-02-20\',1) |\n+----------------------+\n| 8 |\n+----------------------+\n \nSELECT WEEK(\'2008-12-31\',0);\n+----------------------+\n| WEEK(\'2008-12-31\',0) |\n+----------------------+\n| 52 |\n+----------------------+\n \nSELECT WEEK(\'2008-12-31\',1);\n+----------------------+\n| WEEK(\'2008-12-31\',1) |\n+----------------------+\n| 53 |\n+----------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT d, WEEK(d,0), WEEK(d,1) from t1;\n \n+---------------------+-----------+-----------+\n| d | WEEK(d,0) | WEEK(d,1) |\n+---------------------+-----------+-----------+\n| 2007-01-30 21:31:07 | 4 | 5 |\n| 1983-10-15 06:42:51 | 41 | 41 |\n| 2011-04-21 12:34:56 | 16 | 16 |\n| 2011-10-30 06:31:41 | 44 | 43 |\n| 2011-01-30 14:03:25 | 5 | 4 |\n| 2004-10-07 11:19:34 | 40 | 41 |\n+---------------------+-----------+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/week/','','https://mariadb.com/kb/en/library/week/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (521,31,'WEEKDAY','Syntax\n------ \nWEEKDAY(date)\n \nDescription\n----------- \nReturns the weekday index for date \n(0 = Monday, 1 = Tuesday, ... 6 = Sunday).\n \nThis contrasts with DAYOFWEEK() which follows the ODBC\nstandard\n(1 = Sunday, 2 = Monday, ..., 7 = Saturday).\n \nExamples\n-------- \nSELECT WEEKDAY(\'2008-02-03 22:23:00\');\n+--------------------------------+\n| WEEKDAY(\'2008-02-03 22:23:00\') |\n+--------------------------------+\n| 6 |\n+--------------------------------+\n \nSELECT WEEKDAY(\'2007-11-06\');\n+-----------------------+\n| WEEKDAY(\'2007-11-06\') |\n+-----------------------+\n| 1 |\n+-----------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT d FROM t1 where WEEKDAY(d) = 6;\n \n+---------------------+\n| d |\n+---------------------+\n| 2011-10-30 06:31:41 |\n| 2011-01-30 14:03:25 |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/weekday/','','https://mariadb.com/kb/en/library/weekday/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (522,31,'WEEKOFYEAR','Syntax\n------ \nWEEKOFYEAR(date)\n \nDescription\n----------- \nReturns the calendar week of the date as a number in the\nrange from 1\nto 53. WEEKOFYEAR() is a compatibility function that is\nequivalent to\nWEEK(date,3).\n \nExamples\n-------- \nSELECT WEEKOFYEAR(\'2008-02-20\');\n+--------------------------+\n| WEEKOFYEAR(\'2008-02-20\') |\n+--------------------------+\n| 8 |\n+--------------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \n select * from t1;\n \n+---------------------+\n| d |\n+---------------------+\n| 2007-01-30 21:31:07 |\n| 1983-10-15 06:42:51 |\n| 2011-04-21 12:34:56 |\n| 2011-10-30 06:31:41 |\n| 2011-01-30 14:03:25 |\n| 2004-10-07 11:19:34 |\n+---------------------+\n \nSELECT d, WEEKOFYEAR(d), WEEK(d,3) from t1;\n \n+---------------------+---------------+-----------+\n| d | WEEKOFYEAR(d) | WEEK(d,3) |\n+---------------------+---------------+-----------+\n| 2007-01-30 21:31:07 | 5 | 5 |\n| 1983-10-15 06:42:51 | 41 | 41 |\n| 2011-04-21 12:34:56 | 16 | 16 |\n| 2011-10-30 06:31:41 | 43 | 43 |\n| 2011-01-30 14:03:25 | 4 | 4 |\n| 2004-10-07 11:19:34 | 41 | 41 |\n+---------------------+---------------+-----------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/weekofyear/','','https://mariadb.com/kb/en/library/weekofyear/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (523,31,'YEAR','Syntax\n------ \nYEAR(date)\n \nDescription\n----------- \nReturns the year for the given date, in the range 1000 to\n9999, or 0 for the\n\"zero\" date.\n \nExamples\n-------- \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT * FROM t1;\n \n+---------------------+\n| d |\n+---------------------+\n| 2007-01-30 21:31:07 |\n| 1983-10-15 06:42:51 |\n| 2011-04-21 12:34:56 |\n| 2011-10-30 06:31:41 |\n| 2011-01-30 14:03:25 |\n| 2004-10-07 11:19:34 |\n+---------------------+\n \nSELECT * FROM t1 WHERE YEAR(d) = 2011;\n \n+---------------------+\n| d |\n+---------------------+\n| 2011-04-21 12:34:56 |\n| 2011-10-30 06:31:41 |\n| 2011-01-30 14:03:25 |\n+---------------------+\n \nSELECT YEAR(\'1987-01-01\');\n+--------------------+\n| YEAR(\'1987-01-01\') |\n+--------------------+\n| 1987 |\n+--------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/year/','','https://mariadb.com/kb/en/library/year/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (524,31,'YEARWEEK','Syntax\n------ \nYEARWEEK(date), YEARWEEK(date,mode)\n \nDescription\n----------- \nReturns year and week for a date. The mode argument works\nexactly like the mode\nargument to WEEK(). The year in the result may be different\nfrom the\nyear in the date argument for the first and the last week of\nthe year.\n \nExamples\n-------- \nSELECT YEARWEEK(\'1987-01-01\');\n+------------------------+\n| YEARWEEK(\'1987-01-01\') |\n+------------------------+\n| 198652 |\n+------------------------+\n \nCREATE TABLE t1 (d DATETIME);\nINSERT INTO t1 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\n \nSELECT * FROM t1;\n \n+---------------------+\n| d |\n+---------------------+\n| 2007-01-30 21:31:07 |\n| 1983-10-15 06:42:51 |\n| 2011-04-21 12:34:56 |\n| 2011-10-30 06:31:41 |\n| 2011-01-30 14:03:25 |\n| 2004-10-07 11:19:34 |\n+---------------------+\n6 rows in set (0.02 sec)\n \nSELECT YEARWEEK(d) FROM t1 WHERE YEAR(d) = 2011;\n \n+-------------+\n| YEARWEEK(d) |\n+-------------+\n| 201116 |\n| 201144 |\n| 201105 |\n+-------------+\n3 rows in set (0.03 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/yearweek/','','https://mariadb.com/kb/en/library/yearweek/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (525,32,'Well-Known Binary (WKB) Format','WKB stands for Well-Known Binary, a format for representing\ngeographical and geometrical data.\n \nWKB uses 1-byte unsigned integers, 4-byte unsigned integers,\nand 8-byte double-precision numbers.\nThe first byte indicates the byte order. 00 for big endian,\nor 01 for little endian.\nThe next 4 bytes indicate the geometry type. Values from 1\nto 7 indicate whether the type is Point, LineString,\nPolygon, MultiPoint, MultiLineString, MultiPolygon, or\nGeometryCollection respectively. \nThe 8-byte floats represent the co-ordinates.\n \nTake the following example, a sequence of 21 bytes each\nrepresented by two hex digits:\n \n000000000140000000000000004010000000000000\nIt\'s big endian\n000000000140000000000000004010000000000000\n \nIt\'s a POINT\n000000000140000000000000004010000000000000\n \nThe X co-ordinate is 2.0\n000000000140000000000000004010000000000000\n \nThe Y-co-ordinate is 4.0\n000000000140000000000000004010000000000000\n \n\n \n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/well-known-binary-wkb-format/','','https://mariadb.com/kb/en/library/well-known-binary-wkb-format/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (526,32,'AsBinary','A synonym for ST_AsBinary().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkb-asbinary/','','https://mariadb.com/kb/en/library/wkb-asbinary/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (527,32,'AsWKB','A synonym for ST_AsBinary().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/aswkb/','','https://mariadb.com/kb/en/library/aswkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (528,32,'MLineFromWKB','Syntax\n------ \nMLineFromWKB(wkb[,srid])\nMultiLineStringFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a MULTILINESTRING value using its WKB\nrepresentation and SRID.\n \nMLineFromWKB() and MultiLineStringFromWKB() are synonyms.\n \nExamples\n-------- \nSET @g = ST_AsBinary(MLineFromText(\'MULTILINESTRING((10\n48,10 21,10 0),(16 0,16 23,16 48))\'));\n \nSELECT ST_AsText(MLineFromWKB(@g));\n+--------------------------------------------------------+\n| ST_AsText(MLineFromWKB(@g)) |\n+--------------------------------------------------------+\n| MULTILINESTRING((10 48,10 21,10 0),(16 0,16 23,16 48)) |\n+--------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mlinefromwkb/','','https://mariadb.com/kb/en/library/mlinefromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (529,32,'MPointFromWKB','Syntax\n------ \nMPointFromWKB(wkb[,srid])\nMultiPointFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a MULTIPOINT value using its WKB representation\nand SRID.\n \nMPointFromWKB() and MultiPointFromWKB() are synonyms.\n \nExamples\n-------- \nSET @g = ST_AsBinary(MPointFromText(\'MultiPoint( 1 1, 2 2,\n5 3, 7 2, 9 3, 8 4, 6 6, 6 9, 4 9, 1 5 )\'));\n \nSELECT ST_AsText(MPointFromWKB(@g));\n+-----------------------------------------------------+\n| ST_AsText(MPointFromWKB(@g)) |\n+-----------------------------------------------------+\n| MULTIPOINT(1 1,2 2,5 3,7 2,9 3,8 4,6 6,6 9,4 9,1 5) |\n+-----------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mpointfromwkb/','','https://mariadb.com/kb/en/library/mpointfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (530,32,'MPolyFromWKB','Syntax\n------ \nMPolyFromWKB(wkb[,srid])\nMultiPolygonFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a MULTIPOLYGON value using its WKB representation\nand SRID.\n \nMPolyFromWKB() and MultiPolygonFromWKB() are synonyms.\n \nExamples\n-------- \nSET @g = ST_AsBinary(MPointFromText(\'MULTIPOLYGON(((28\n26,28 0,84 0,84 42,28 26),(52 18,66 23,73 9,48 6,52\n18)),((59 18,67 18,67 13,59 13,59 18)))\'));\n \nSELECT ST_AsText(MPolyFromWKB(@g));\n+---------------------------------------------------------------------------------------------------------------+\n| ST_AsText(MPolyFromWKB(@g)) |\n+---------------------------------------------------------------------------------------------------------------+\n| MULTIPOLYGON(((28 26,28 0,84 0,84 42,28 26),(52 18,66\n23,73 9,48 6,52 18)),((59 18,67 18,67 13,59 13,59 18))) |\n+---------------------------------------------------------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mpolyfromwkb/','','https://mariadb.com/kb/en/library/mpolyfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (531,32,'GeomCollFromWKB','A synonym for ST_GeomCollFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkb-geomcollfromwkb/','','https://mariadb.com/kb/en/library/wkb-geomcollfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (532,32,'GeometryCollectionFromWKB','A synonym for ST_GeomCollFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometrycollectionfromwkb/','','https://mariadb.com/kb/en/library/geometrycollectionfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (533,32,'GeometryFromWKB','A synonym for ST_GeomFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/geometryfromwkb/','','https://mariadb.com/kb/en/library/geometryfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (534,32,'GeomFromWKB','A synonym for ST_GeomFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkb-geomfromwkb/','','https://mariadb.com/kb/en/library/wkb-geomfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (535,32,'LineFromWKB','A synonym for ST_LineFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkb-linefromwkb/','','https://mariadb.com/kb/en/library/wkb-linefromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (536,32,'LineStringFromWKB','A synonym for ST_LineFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/linestringfromwkb/','','https://mariadb.com/kb/en/library/linestringfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (537,32,'MultiLineStringFromWKB','A synonym for MLineFromWKB().\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/multilinestringfromwkb/','','https://mariadb.com/kb/en/library/multilinestringfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (538,32,'MultiPointFromWKB','A synonym for MPointFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/multipointfromwkb/','','https://mariadb.com/kb/en/library/multipointfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (539,32,'MultiPolygonFromWKB','Synonym for MPolyFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/multipolygonfromwkb/','','https://mariadb.com/kb/en/library/multipolygonfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (540,32,'PointFromWKB','A synonym for ST_PointFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkb-pointfromwkb/','','https://mariadb.com/kb/en/library/wkb-pointfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (541,32,'PolyFromWKB','A synonym for ST_PolyFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/wkb-polyfromwkb/','','https://mariadb.com/kb/en/library/wkb-polyfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (542,32,'PolygonFromWKB','A synonym for ST_PolyFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/polygonfromwkb/','','https://mariadb.com/kb/en/library/polygonfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (543,32,'ST_AsBinary','Syntax\n------ \nST_AsBinary(g)\nAsBinary(g)\nST_AsWKB(g)\nAsWKB(g)\n \nDescription\n----------- \nConverts a value in internal geometry format to its WKB\nrepresentation and returns the binary result.\n \nST_AsBinary(), AsBinary(), ST_AsWKB() and AsWKB() are\nsynonyms,\n \nExamples\n-------- \nSET @poly = ST_GeomFromText(\'POLYGON((0 0,0 1,1 1,1 0,0\n0))\');\nSELECT ST_AsBinary(@poly);\n \nSELECT ST_AsText(ST_GeomFromWKB(ST_AsWKB(@poly)));\n+--------------------------------------------+\n| ST_AsText(ST_GeomFromWKB(ST_AsWKB(@poly))) |\n+--------------------------------------------+\n| POLYGON((0 0,0 1,1 1,1 0,0 0)) |\n+--------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_asbinary/','','https://mariadb.com/kb/en/library/st_asbinary/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (544,32,'ST_AsWKB','A synonym for ST_AsBinary().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_aswkb/','','https://mariadb.com/kb/en/library/st_aswkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (545,32,'ST_GeomCollFromWKB','Syntax\n------ \nST_GeomCollFromWKB(wkb[,srid])\nST_GeometryCollectionFromWKB(wkb[,srid])\nGeomCollFromWKB(wkb[,srid])\nGeometryCollectionFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a GEOMETRYCOLLECTION value using its WKB\nrepresentation and SRID.\n \nST_GeomCollFromWKB(), ST_GeometryCollectionFromWKB(),\nGeomCollFromWKB() and GeometryCollectionFromWKB() are\nsynonyms.\n \nExamples\n-------- \nSET @g =\nST_AsBinary(ST_GeomFromText(\'GEOMETRYCOLLECTION(POLYGON((5\n5,10 5,10 10,5 5)),POINT(10 10))\'));\n \nSELECT ST_AsText(ST_GeomCollFromWKB(@g));\n+----------------------------------------------------------------+\n| ST_AsText(ST_GeomCollFromWKB(@g)) |\n+----------------------------------------------------------------+\n| GEOMETRYCOLLECTION(POLYGON((5 5,10 5,10 10,5 5)),POINT(10\n10)) |\n+----------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geomcollfromwkb/','','https://mariadb.com/kb/en/library/st_geomcollfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (546,32,'ST_GeometryCollectionFromWKB','A synonym for ST_GeomCollFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/st_geometrycollectionfromwkb/','','https://mariadb.com/kb/en/library/st_geometrycollectionfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (547,32,'ST_GeometryFromWKB','A synonym for ST_GeomFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geometryfromwkb/','','https://mariadb.com/kb/en/library/st_geometryfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (548,32,'ST_GeomFromWKB','Syntax\n------ \nST_GeomFromWKB(wkb[,srid])\nST_GeometryFromWKB(wkb[,srid])\nGeomFromWKB(wkb[,srid])\nGeometryFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a geometry value of any type using its WKB\nrepresentation and SRID.\n \nST_GeomFromWKB(), ST_GeometryFromWKB(), GeomFromWKB() and\nGeometryFromWKB() are synonyms.\n \nExamples\n-------- \nSET @g = ST_AsBinary(ST_LineFromText(\'LINESTRING(0 4, 4\n6)\'));\n \nSELECT ST_AsText(ST_GeomFromWKB(@g));\n+-------------------------------+\n| ST_AsText(ST_GeomFromWKB(@g)) |\n+-------------------------------+\n| LINESTRING(0 4,4 6) |\n+-------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geomfromwkb/','','https://mariadb.com/kb/en/library/st_geomfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (549,32,'ST_LineFromWKB','Syntax\n------ \nST_LineFromWKB(wkb[,srid])\nLineFromWKB(wkb[,srid])\nST_LineStringFromWKB(wkb[,srid])\nLineStringFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a LINESTRING value using its WKB representation\nand SRID.\n \nST_LineFromWKB(), LineFromWKB(), ST_LineStringFromWKB(), and\nLineStringFromWKB() are synonyms.\n \nExamples\n-------- \nSET @g = ST_AsBinary(ST_LineFromText(\'LineString(0 4,4\n6)\'));\n \nSELECT ST_AsText(ST_LineFromWKB(@g)) AS l;\n \n+---------------------+\n| l |\n+---------------------+\n| LINESTRING(0 4,4 6) |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_linefromwkb/','','https://mariadb.com/kb/en/library/st_linefromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (550,32,'ST_LineStringFromWKB','A synonym for ST_LineFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_linestringfromwkb/','','https://mariadb.com/kb/en/library/st_linestringfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (551,32,'ST_PointFromWKB','Syntax\n------ \nST_PointFromWKB(wkb[,srid])\nPointFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a POINT value using its WKB representation and\nSRID.\n \nST_PointFromWKB() and PointFromWKB() are synonyms.\n \nExamples\n-------- \nSET @g = ST_AsBinary(ST_PointFromText(\'POINT(0 4)\'));\n \nSELECT ST_AsText(ST_PointFromWKB(@g)) AS p;\n \n+------------+\n| p |\n+------------+\n| POINT(0 4) |\n+------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_pointfromwkb/','','https://mariadb.com/kb/en/library/st_pointfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (552,32,'ST_PolyFromWKB','Syntax\n------ \nST_PolyFromWKB(wkb[,srid])\nST_PolygonFromWKB(wkb[,srid])\nPolyFromWKB(wkb[,srid])\nPolygonFromWKB(wkb[,srid])\n \nDescription\n----------- \nConstructs a POLYGON value using its WKB representation and\nSRID.\n \nST_PolyFromWKB(), ST_PolygonFromWKB(), PolyFromWKB() and\nPolygonFromWKB() are synonyms.\n \nExamples\n-------- \nSET @g = ST_AsBinary(ST_PolyFromText(\'POLYGON((1 1,1 5,4\n9,6 9,9 3,7 2,1 1))\'));\n \nSELECT ST_AsText(ST_PolyFromWKB(@g)) AS p;\n \n+----------------------------------------+\n| p |\n+----------------------------------------+\n| POLYGON((1 1,1 5,4 9,6 9,9 3,7 2,1 1)) |\n+----------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_polyfromwkb/','','https://mariadb.com/kb/en/library/st_polyfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (553,32,'ST_PolygonFromWKB','A synonym for ST_PolyFromWKB.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_polygonfromwkb/','','https://mariadb.com/kb/en/library/st_polygonfromwkb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (554,36,'BOUNDARY','A synonym for ST_BOUNDARY.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-boundary/','','https://mariadb.com/kb/en/library/geometry-properties-boundary/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (555,36,'DIMENSION','A synonym for ST_DIMENSION.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/dimension/','','https://mariadb.com/kb/en/library/dimension/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (556,36,'ENVELOPE','A synonym for ST_ENVELOPE.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-envelope/','','https://mariadb.com/kb/en/library/geometry-properties-envelope/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (557,36,'GeometryN','A synonym for ST_GeometryN.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-geometryn/','','https://mariadb.com/kb/en/library/geometry-properties-geometryn/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (558,36,'GeometryType','A synonym for ST_GeometryType.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-geometrytype/','','https://mariadb.com/kb/en/library/geometry-properties-geometrytype/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (559,36,'IsClosed','A synonym for ST_IsClosed.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/isclosed/','','https://mariadb.com/kb/en/library/isclosed/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (560,36,'IsEmpty','A synonym for ST_IsEmpty.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-isempty/','','https://mariadb.com/kb/en/library/geometry-properties-isempty/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (561,36,'IsRing','A synonym for ST_IsRing.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/isring/','','https://mariadb.com/kb/en/library/isring/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (562,36,'IsSimple','A synonym for ST_IsSImple.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-issimple/','','https://mariadb.com/kb/en/library/geometry-properties-issimple/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (563,36,'NumGeometries','A synonym for ST_NumGeometries.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-numgeometries/','','https://mariadb.com/kb/en/library/geometry-properties-numgeometries/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (564,36,'SRID','A synonym for ST_SRID.\n \n\n \n \n \n \n \n \n \n\nURL:\nhttps://mariadb.com/kb/en/library/geometry-properties-srid/','','https://mariadb.com/kb/en/library/geometry-properties-srid/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (565,36,'ST_BOUNDARY','The ST_BOUNDARY function was introduced in MariaDB 10.1.2\n \nSyntax\n------ \nST_BOUNDARY(g)\nBOUNDARY(g)\n \nDescription\n----------- \nReturns a geometry that is the closure of the combinatorial\nboundary of the geometry value g.\n \nBOUNDARY() is a synonym.\n \nExamples\n-------- \nSELECT ST_AsText(ST_Boundary(ST_GeomFromText(\'LINESTRING(3\n3,0 0, -3 3)\')));\n+----------------------------------------------------------------------+\n| ST_AsText(ST_Boundary(ST_GeomFromText(\'LINESTRING(3 3,0\n0, -3 3)\'))) |\n+----------------------------------------------------------------------+\n| MULTIPOINT(3 3,-3 3) |\n+----------------------------------------------------------------------+\n \nSELECT ST_AsText(ST_Boundary(ST_GeomFromText(\'POLYGON((3\n3,0 0, -3 3, 3 3))\')));\n+--------------------------------------------------------------------------+\n| ST_AsText(ST_Boundary(ST_GeomFromText(\'POLYGON((3 3,0 0,\n-3 3, 3 3))\'))) |\n+--------------------------------------------------------------------------+\n| LINESTRING(3 3,0 0,-3 3,3 3) |\n+--------------------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_boundary/','','https://mariadb.com/kb/en/library/st_boundary/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (566,36,'ST_DIMENSION','Syntax\n------ \nST_Dimension(g)\nDimension(g)\n \nDescription\n----------- \nReturns the inherent dimension of the geometry value g. The\nresult can\nbe\n \nDimension | Definition | \n \n -1 | empty geometry | \n \n 0 | geometry with no length or area | \n \n 1 | geometry with no area but nonzero length | \n \n 2 | geometry with nonzero area | \n \nST_Dimension() and Dimension() are synonyms.\n \nExamples\n-------- \nSELECT Dimension(GeomFromText(\'LineString(1 1,2 2)\'));\n+------------------------------------------------+\n| Dimension(GeomFromText(\'LineString(1 1,2 2)\')) |\n+------------------------------------------------+\n| 1 |\n+------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_dimension/','','https://mariadb.com/kb/en/library/st_dimension/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (567,36,'ST_ENVELOPE','Syntax\n------ \nST_ENVELOPE(g)\nENVELOPE(g)\n \nDescription\n----------- \nReturns the Minimum Bounding Rectangle (MBR) for the\ngeometry value g. The result is returned as a Polygon value.\n \nThe polygon is defined by the corner points of the bounding\nbox:\n \nPOLYGON((MINX MINY, MAXX MINY, MAXX MAXY, MINX MAXY, MINX\nMINY))\n \nST_ENVELOPE() and ENVELOPE() are synonyms.\n \nExamples\n-------- \nSELECT AsText(ST_ENVELOPE(GeomFromText(\'LineString(1 1,4\n4)\')));\n+----------------------------------------------------------+\n| AsText(ST_ENVELOPE(GeomFromText(\'LineString(1 1,4 4)\')))\n|\n+----------------------------------------------------------+\n| POLYGON((1 1,4 1,4 4,1 4,1 1)) |\n+----------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_envelope/','','https://mariadb.com/kb/en/library/st_envelope/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (568,36,'ST_GEOMETRYN','Syntax\n------ \nST_GeometryN(gc,N)\nGeometryN(gc,N)\n \nDescription\n----------- \nReturns the N-th geometry in the GeometryCollection gc.\nGeometries are numbered beginning with 1.\n \nST_GeometryN() and GeometryN() are synonyms.\n \nExample\n \nSET @gc = \'GeometryCollection(Point(1 1),LineString(12 14,\n9 11))\';\n \nSELECT AsText(GeometryN(GeomFromText(@gc),1));\n+----------------------------------------+\n| AsText(GeometryN(GeomFromText(@gc),1)) |\n+----------------------------------------+\n| POINT(1 1) |\n+----------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geometryn/','','https://mariadb.com/kb/en/library/st_geometryn/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (569,36,'ST_GEOMETRYTYPE','Syntax\n------ \nST_GeometryType(g)\nGeometryType(g)\n \nDescription\n----------- \nReturns as a string the name of the geometry type of which\nthe\ngeometry instance g is a member. The name corresponds to one\nof the\ninstantiable Geometry subclasses.\n \nST_GeometryType() and GeometryType() are synonyms.\n \nExamples\n-------- \nSELECT GeometryType(GeomFromText(\'POINT(1 1)\'));\n+------------------------------------------+\n| GeometryType(GeomFromText(\'POINT(1 1)\')) |\n+------------------------------------------+\n| POINT |\n+------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_geometrytype/','','https://mariadb.com/kb/en/library/st_geometrytype/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (570,36,'ST_ISCLOSED','Syntax\n------ \nST_IsClosed(g)\nIsClosed(g)\n \nDescription\n----------- \nReturns 1 if a given LINESTRING\'s start and end points are\nthe same, or 0 if they are not the same. Before MariaDB\n10.1.5, returns NULL if not given a LINESTRING. After\nMariaDB 10.1.5, returns -1.\n \nST_IsClosed() and IsClosed() are synonyms.\n \nExamples\n-------- \nSET @ls = \'LineString(0 0, 0 4, 4 4, 0 0)\';\n \nSELECT ST_ISCLOSED(GEOMFROMTEXT(@ls));\n+--------------------------------+\n| ST_ISCLOSED(GEOMFROMTEXT(@ls)) |\n+--------------------------------+\n| 1 |\n+--------------------------------+\n \nSET @ls = \'LineString(0 0, 0 4, 4 4, 0 1)\';\n \nSELECT ST_ISCLOSED(GEOMFROMTEXT(@ls));\n+--------------------------------+\n| ST_ISCLOSED(GEOMFROMTEXT(@ls)) |\n+--------------------------------+\n| 0 |\n+--------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_isclosed/','','https://mariadb.com/kb/en/library/st_isclosed/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (571,36,'ST_ISEMPTY','Syntax\n------ \nST_IsEmpty(g)\nIsEmpty(g)\n \nDescription\n----------- \nIsEmpty is a function defined by the OpenGIS specification,\nbut is not fully implemented by MariaDB or MySQL. \n \nSince MariaDB and MySQL do not support GIS EMPTY values such\nas POINT EMPTY, as implemented it simply returns 1 if the\ngeometry value g is invalid, 0 if it is valid, and NULL if\nthe argument is NULL.\n \nST_IsEmpty() and IsEmpty() are synonyms.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_isempty/','','https://mariadb.com/kb/en/library/st_isempty/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (572,36,'ST_IsRing','The ST_IsRing function was introduced in MariaDB 10.1.2\n \nSyntax\n------ \nST_IsRing(g)\nIsRing(g)\n \nDescription\n----------- \nReturns true if a given LINESTRING is a ring, that is, both\nST_IsClosed and ST_IsSimple. A simple curve does not pass\nthrough the same point more than once. However, see\nMDEV-7510.\n \nSt_IsRing() and IsRing() are synonyms.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_isring/','','https://mariadb.com/kb/en/library/st_isring/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (573,36,'ST_IsSimple','Syntax\n------ \nST_IsSimple(g)\nIsSimple(g)\n \nDescription\n----------- \nReturns true if the given Geometry has no anomalous\ngeometric points, false if it does, or NULL if given a NULL\nvalue.\n \nST_IsSimple() and IsSimple() are synonyms.\n \nExamples\n-------- \nA POINT is always simple.\n \nSET @g = \'Point(1 2)\';\n \nSELECT ST_ISSIMPLE(GEOMFROMTEXT(@g));\n+-------------------------------+\n| ST_ISSIMPLE(GEOMFROMTEXT(@g)) |\n+-------------------------------+\n| 1 |\n+-------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_issimple/','','https://mariadb.com/kb/en/library/st_issimple/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (574,36,'ST_NUMGEOMETRIES','Syntax\n------ \nST_NumGeometries(gc)\nNumGeometries(gc)\n \nDescription\n----------- \nReturns the number of geometries in the GeometryCollection\ngc.\n \nST_NumGeometries() and NumGeometries() are synonyms.\n \nExample\n \nSET @gc = \'GeometryCollection(Point(1 1),LineString(2 2, 3\n3))\';\n \nSELECT NUMGEOMETRIES(GeomFromText(@gc));\n+----------------------------------+\n| NUMGEOMETRIES(GeomFromText(@gc)) |\n+----------------------------------+\n| 2 |\n+----------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_numgeometries/','','https://mariadb.com/kb/en/library/st_numgeometries/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (575,36,'ST_RELATE','The ST_RELATE() function was introduced in MariaDB 10.1.2\n \nSyntax\n------ \nST_Relate(g1, g2, i)\n \nDescription\n----------- \nReturns true if Geometry g1 is spatially related to\nGeometryg2 by testing for intersections between the\ninterior, boundary and exterior of the two geometries as\nspecified by the values in intersection matrix pattern i.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_relate/','','https://mariadb.com/kb/en/library/st_relate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (576,36,'ST_SRID','Syntax\n------ \nST_SRID(g)\nSRID(g)\n \nDescription\n----------- \nReturns an integer indicating the Spatial Reference System\nID for the\ngeometry value g.\n \nIn MariaDB, the SRID value is just an integer associated\nwith the\ngeometry value. All calculations are done assuming Euclidean\n(planar)\ngeometry.\n \nST_SRID() and SRID() are synonyms.\n \nExamples\n-------- \nSELECT SRID(GeomFromText(\'LineString(1 1,2 2)\',101));\n+-----------------------------------------------+\n| SRID(GeomFromText(\'LineString(1 1,2 2)\',101)) |\n+-----------------------------------------------+\n| 101 |\n+-----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/st_srid/','','https://mariadb.com/kb/en/library/st_srid/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (577,37,'ASCII','Syntax\n------ \nASCII(str)\n \nDescription\n----------- \nReturns the numeric ASCII value of the leftmost character of\nthe string argument. Returns 0 if the given string is empty\nand NULL if it is NULL.\n \nASCII() works for 8-bit characters.\n \nExamples\n-------- \nSELECT ASCII(9);\n+----------+\n| ASCII(9) |\n+----------+\n| 57 |\n+----------+\n \nSELECT ASCII(\'9\');\n+------------+\n| ASCII(\'9\') |\n+------------+\n| 57 |\n+------------+\n \nSELECT ASCII(\'abc\');\n+--------------+\n| ASCII(\'abc\') |\n+--------------+\n| 97 |\n+--------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/ascii/','','https://mariadb.com/kb/en/library/ascii/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (578,37,'BIN','Syntax\n------ \nBIN(N)\n \nDescription\n----------- \nReturns a string representation of the binary value of the\ngiven longlong (that is, BIGINT) number. This is equivalent\nto CONV(N,10,2). The argument should be positive. If it is a\nFLOAT, it will be truncated. Returns NULL if the argument is\nNULL.\n \nExamples\n-------- \nSELECT BIN(12);\n+---------+\n| BIN(12) |\n+---------+\n| 1100 |\n+---------+\n \n\n\nURL: https://mariadb.com/kb/en/library/bin/','','https://mariadb.com/kb/en/library/bin/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (579,37,'BINARY Operator','Syntax\n------ \nBINARY\n \nDescription\n----------- \nThe BINARY operator casts the string following it to a\nbinary string. This is an easy way to force a column\ncomparison to be done byte by byte rather than character by\ncharacter. This causes the comparison to be case sensitive\neven if the column isn\'t defined as BINARY or BLOB. \n \nBINARY also causes trailing spaces to be significant.\n \nExamples\n-------- \nSELECT \'a\' = \'A\';\n \n+-----------+\n| \'a\' = \'A\' |\n+-----------+\n| 1 |\n+-----------+\n \nSELECT BINARY \'a\' = \'A\';\n \n+------------------+\n| BINARY \'a\' = \'A\' |\n+------------------+\n| 0 |\n+------------------+\n \nSELECT \'a\' = \'a \';\n \n+------------+\n| \'a\' = \'a \' |\n+------------+\n| 1 |\n+------------+\n \nSELECT BINARY \'a\' = \'a \';\n \n+-------------------+\n| BINARY \'a\' = \'a \' |\n+-------------------+\n| 0 |\n+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/binary-operator/','','https://mariadb.com/kb/en/library/binary-operator/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (580,37,'BIT_LENGTH','Syntax\n------ \nBIT_LENGTH(str)\n \nDescription\n----------- \nReturns the length of the given string argument in bits. If\nthe argument is not a string, it will be converted to\nstring. If the argument is NULL, it returns NULL.\n \nExamples\n-------- \nSELECT BIT_LENGTH(\'text\');\n+--------------------+\n| BIT_LENGTH(\'text\') |\n+--------------------+\n| 32 |\n+--------------------+\n \nSELECT BIT_LENGTH(\'\');\n+----------------+\n| BIT_LENGTH(\'\') |\n+----------------+\n| 0 |\n+----------------+\n \nCompatibility\n \nPostgreSQL and Sybase support BIT_LENGTH().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/bit_length/','','https://mariadb.com/kb/en/library/bit_length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (581,37,'CAST','Syntax\n------ \nCAST(expr AS type)\n \nDescription\n----------- \nThe CAST() function takes a value of one type and produces a\nvalue of another type, similar to the CONVERT() function.\nFor more information, see the description of CONVERT(). \n \nThe main difference between the CAST() and CONVERT() is that\nCONVERT(expr,type) is ODBC syntax while CAST(expr as type)\nand CONVERT(... USING ...) are SQL92 syntax.\n \nIn MariaDB 10.4 and later, you can use the CAST() function\nwith the INTERVAL keyword.\n \nUntil MariaDB 5.5.31, X\'HHHH\', the standard SQL syntax for\nbinary string literals, erroneously worked in the same way\nas 0xHHHH. In 5.5.31 it was intentionally changed to behave\nas a string in all contexts (and never as a number).\n \nThis introduces an incompatibility with previous versions of\nMariaDB, and all versions of MySQL (see the example below). \n \nExamples\n-------- \nSimple casts:\n \nSELECT CAST(\"abc\" AS BINARY);\nSELECT CAST(\"1\" AS UNSIGNED INTEGER);\nSELECT CAST(123 AS CHAR CHARACTER SET utf8)\n \nNote that when one casts to CHAR without specifying the\ncharacter set, the collation_connection character set\ncollation will be used. When used with CHAR CHARACTER SET,\nthe default collation for that character set will be used.\n \nSELECT COLLATION(CAST(123 AS CHAR));\n+------------------------------+\n| COLLATION(CAST(123 AS CHAR)) |\n+------------------------------+\n| latin1_swedish_ci |\n+------------------------------+\n \nSELECT COLLATION(CAST(123 AS CHAR CHARACTER SET utf8));\n+-------------------------------------------------+\n| COLLATION(CAST(123 AS CHAR CHARACTER SET utf8)) |\n+-------------------------------------------------+\n| utf8_general_ci |\n+-------------------------------------------------+\n \nIf you also want to change the collation, you have to use\nthe COLLATE operator:\n \nSELECT COLLATION(CAST(123 AS CHAR CHARACTER SET utf8) \n COLLATE utf8_unicode_ci);\n+-------------------------------------------------------------------------+\n| COLLATION(CAST(123 AS CHAR CHARACTER SET utf8) COLLATE\nutf8_unicode_ci) |\n+-------------------------------------------------------------------------+\n| utf8_unicode_ci |\n+-------------------------------------------------------------------------+\n \nUsing CAST() to order an ENUM field as a CHAR rather than\nthe internal numerical value:\n \nCREATE TABLE enum_list (enum_field enum(\'c\',\'a\',\'b\'));\n \nINSERT INTO enum_list (enum_field) \nVALUES(\'c\'),(\'a\'),(\'c\'),(\'b\');\n \nSELECT * FROM enum_list \nORDER BY enum_field;\n \n+------------+\n| enum_field |\n+------------+\n| c |\n| c |\n| a |\n| b |\n+------------+\n \nSELECT * FROM enum_list \nORDER BY CAST(enum_field AS CHAR);\n+------------+\n| enum_field |\n+------------+\n| a |\n| b |\n| c |\n| c |\n+------------+\n \nFrom MariaDB 5.5.31, the following will trigger warnings,\nsince x\'aa\' and \'X\'aa\' no longer behave as a number.\nPreviously, and in all versions of MySQL, no warnings are\ntriggered since they did erroneously behave as a number:\n \nSELECT CAST(0xAA AS UNSIGNED), CAST(x\'aa\' AS UNSIGNED),\nCAST(X\'aa\' AS UNSIGNED);\n+------------------------+-------------------------+-------------------------+\n| CAST(0xAA AS UNSIGNED) | CAST(x\'aa\' AS UNSIGNED) |\nCAST(X\'aa\' AS UNSIGNED) |\n+------------------------+-------------------------+-------------------------+\n| 170 | 0 | 0 |\n+------------------------+-------------------------+-------------------------+\n1 row in set, 2 warnings (0.00 sec)\n \nWarning (Code 1292): Truncated incorrect INTEGER value:\n\'\\xAA\'\nWarning (Code 1292): Truncated incorrect INTEGER value:\n\'\\xAA\'\n \nCasting to intervals:\n \nSELECT CAST(2019-01-04 INTERVAL AS DAY_SECOND(2)) AS\n\"Cast\";\n \n+-------------+\n| Cast |\n+-------------+\n| 00:20:17.00 |\n+-------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/cast/','','https://mariadb.com/kb/en/library/cast/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (582,37,'CHAR Function','Syntax\n------ \nCHAR(N,... [USING charset_name])\n \nDescription\n----------- \nCHAR() interprets each argument as an INT and returns a\nstring consisting of the characters given by the code values\nof those integers. NULL values are skipped. By default,\nCHAR() returns a binary string. To produce a string in a\ngiven character set, use the optional USING clause:\n \nSELECT CHARSET(CHAR(0x65)), CHARSET(CHAR(0x65 USING utf8));\n+---------------------+--------------------------------+\n| CHARSET(CHAR(0x65)) | CHARSET(CHAR(0x65 USING utf8)) |\n+---------------------+--------------------------------+\n| binary | utf8 |\n+---------------------+--------------------------------+\n \nIf USING is given and the result string is illegal for the\ngiven character set, a warning is issued. Also, if strict\nSQL mode is enabled, the result from CHAR() becomes NULL.\n \nExamples\n-------- \nSELECT CHAR(77,97,114,\'105\',97,\'68\',66);\n+----------------------------------+\n| CHAR(77,97,114,\'105\',97,\'68\',66) |\n+----------------------------------+\n| MariaDB |\n+----------------------------------+\n \nSELECT CHAR(77,77.3,\'77.3\');\n+----------------------+\n| CHAR(77,77.3,\'77.3\') |\n+----------------------+\n| MMM |\n+----------------------+\n1 row in set, 1 warning (0.00 sec)\n \nWarning (Code 1292): Truncated incorrect INTEGER value:\n\'77.3\'\n \n\n\nURL: https://mariadb.com/kb/en/library/char-function/','','https://mariadb.com/kb/en/library/char-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (583,37,'CHARACTER_LENGTH','Syntax\n------ \nCHARACTER_LENGTH(str)\n \nDescription\n----------- \nCHARACTER_LENGTH() is a synonym for CHAR_LENGTH().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/character_length/','','https://mariadb.com/kb/en/library/character_length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (584,37,'CHAR_LENGTH','Syntax\n------ \nCHAR_LENGTH(str)\n \nDescription\n----------- \nReturns the length of the given string argument, measured in\ncharacters. A multi-byte character counts as a single\ncharacter. This means that for a string containing five\ntwo-byte characters, LENGTH() (or OCTET_LENGTH() in Oracle\nmode) returns 10, whereas CHAR_LENGTH() returns 5. If the\nargument is NULL, it returns NULL. \n \nIf the argument is not a string value, it is converted into\na string.\n \nIt is synonymous with the CHARACTER_LENGTH() function.\n \nUntil MariaDB 10.3.1, returns MYSQL_TYPE_LONGLONG, or\nbigint(10), in all cases. From MariaDB 10.3.1, returns\nMYSQL_TYPE_LONG, or int(10), when the result would fit\nwithin 32-bits.\n \nExamples\n-------- \nSELECT CHAR_LENGTH(\'MariaDB\');\n+------------------------+\n| CHAR_LENGTH(\'MariaDB\') |\n+------------------------+\n| 7 |\n+------------------------+\n \nSELECT CHAR_LENGTH(\'π\');\n+-------------------+\n| CHAR_LENGTH(\'π\') |\n+-------------------+\n| 1 |\n+-------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/char_length/','','https://mariadb.com/kb/en/library/char_length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (585,37,'CHR','The CHR() function was introduced in MariaDB 10.3.1 to\nprovide Oracle compatibility\n \nSyntax\n------ \nCHR(N)\n \nDescription\n----------- \nCHR() interprets each argument N as an integer and returns a\nVARCHAR(1) string consisting of the character given by the\ncode values of the integer. The character set and collation\nof the string are set according to the values of the\ncharacter_set_database and collation_database system\nvariables.\n \nCHR() is similar to the CHAR() function, but only accepts a\nsingle argument.\n \nCHR() is available in all sql_modes.\n \nExamples\n-------- \nSELECT CHR(67);\n+---------+\n| CHR(67) |\n+---------+\n| C |\n+---------+\n \nSELECT CHR(\'67\');\n+-----------+\n| CHR(\'67\') |\n+-----------+\n| C |\n+-----------+\n \nSELECT CHR(\'C\');\n+----------+\n| CHR(\'C\') |\n+----------+\n| |\n+----------+\n1 row in set, 1 warning (0.000 sec)\n \nSHOW WARNINGS;\n \n+---------+------+----------------------------------------+\n| Level | Code | Message |\n+---------+------+----------------------------------------+\n| Warning | 1292 | Truncated incorrect INTEGER value: \'C\'\n|\n+---------+------+----------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/chr/','','https://mariadb.com/kb/en/library/chr/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (586,37,'CONCAT','Syntax\n------ \nCONCAT(str1,str2,...)\n \nDescription\n----------- \nReturns the string that results from concatenating the\narguments. May have one or more arguments. If all arguments\nare non-binary strings, the result is a non-binary string.\nIf the arguments include any binary strings, the result is a\nbinary string. A numeric argument is converted to its\nequivalent binary string form; if you want to avoid that,\nyou can use an explicit type cast, as in this example:\n \nSELECT CONCAT(CAST(int_col AS CHAR), char_col);\n \nCONCAT() returns NULL if any argument is NULL.\n \nA NULL parameter hides all information contained in other\nparameters from the result. Sometimes this is not desirable;\nto avoid this, you can:\nUse the CONCAT_WS() function with an empty separator,\nbecause that function is NULL-safe.\nUse IFNULL() to turn NULLs into empty strings.\n \nOracle Mode\n \nIn Oracle mode from MariaDB 10.3, CONCAT ignores NULL.\n \nExamples\n-------- \nSELECT CONCAT(\'Ma\', \'ria\', \'DB\');\n+---------------------------+\n| CONCAT(\'Ma\', \'ria\', \'DB\') |\n+---------------------------+\n| MariaDB |\n+---------------------------+\n \nSELECT CONCAT(\'Ma\', \'ria\', NULL, \'DB\');\n+---------------------------------+\n| CONCAT(\'Ma\', \'ria\', NULL, \'DB\') |\n+---------------------------------+\n| NULL |\n+---------------------------------+\n \nSELECT CONCAT(42.0);\n+--------------+\n| CONCAT(42.0) |\n+--------------+\n| 42.0 |\n+--------------+\n \nUsing IFNULL() to handle NULLs:\n \nSELECT CONCAT(\'The value of @v is: \', IFNULL(@v, \'\'));\n+------------------------------------------------+\n| CONCAT(\'The value of @v is: \', IFNULL(@v, \'\')) |\n+------------------------------------------------+\n| The value of @v is: |\n+------------------------------------------------+\n \nIn Oracle mode, from MariaDB 10.3:\n \nSELECT CONCAT(\'Ma\', \'ria\', NULL, \'DB\');\n+---------------------------------+\n| CONCAT(\'Ma\', \'ria\', NULL, \'DB\') |\n+---------------------------------+\n| MariaDB |\n+---------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/concat/','','https://mariadb.com/kb/en/library/concat/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (587,37,'CONCAT_WS','Syntax\n------ \nCONCAT_WS(separator,str1,str2,...)\n \nDescription\n----------- \nCONCAT_WS() stands for Concatenate With Separator and is a\nspecial form of CONCAT(). The first argument is the\nseparator for the rest of the arguments. The separator is\nadded between the strings to be concatenated. The separator\ncan be a string, as can the rest of the arguments.\n \nIf the separator is NULL, the result is NULL; all other NULL\nvalues are skipped. This makes CONCAT_WS() suitable when you\nwant to concatenate some values and avoid losing all\ninformation if one of them is NULL.\n \nExamples\n-------- \nSELECT CONCAT_WS(\',\',\'First name\',\'Second name\',\'Last\nName\');\n+-------------------------------------------------------+\n| CONCAT_WS(\',\',\'First name\',\'Second name\',\'Last\nName\') |\n+-------------------------------------------------------+\n| First name,Second name,Last Name |\n+-------------------------------------------------------+\n \nSELECT CONCAT_WS(\'-\',\'Floor\',NULL,\'Room\');\n+------------------------------------+\n| CONCAT_WS(\'-\',\'Floor\',NULL,\'Room\') |\n+------------------------------------+\n| Floor-Room |\n+------------------------------------+\n \nIn some cases, remember to include a space in the separator\nstring:\n \nSET @a = \'gnu\', @b = \'penguin\', @c = \'sea lion\';\n \nQuery OK, 0 rows affected (0.00 sec)\n \nSELECT CONCAT_WS(\', \', @a, @b, @c);\n+-----------------------------+\n| CONCAT_WS(\', \', @a, @b, @c) |\n+-----------------------------+\n| gnu, penguin, sea lion |\n+-----------------------------+\n \nUsing CONCAT_WS() to handle NULLs:\n \nSET @a = \'a\', @b = NULL, @c = \'c\';\n \nSELECT CONCAT_WS(\'\', @a, @b, @c);\n+---------------------------+\n| CONCAT_WS(\'\', @a, @b, @c) |\n+---------------------------+\n| ac |\n+---------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/concat_ws/','','https://mariadb.com/kb/en/library/concat_ws/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (588,37,'CONVERT','Syntax\n------ \nCONVERT(expr,type), CONVERT(expr USING transcoding_name)\n \nDescription\n----------- \nThe CONVERT() and CAST() functions take a value of one type\nand produce a value of another type.\n \nThe type can be one of the following values:\nBINARY\nCHAR\nDATE\nDATETIME \nDECIMAL[(M[,D])]\nDOUBLE \nFLOAT — From MariaDB 10.4.5\nINTEGER \nShort for SIGNED INTEGER\n \nSIGNED [INTEGER]\nTIME \nUNSIGNED [INTEGER]\n \nNote that in MariaDB, INT and INTEGER are the same thing.\n \nBINARY produces a string with the BINARY data type. If the\noptional length is given, BINARY(N) causes the cast to use\nno more than N bytes of the argument. Values shorter than\nthe given number in bytes are padded with 0x00 bytes to make\nthem equal the length value.\n \nCHAR(N) causes the cast to use no more than the number of\ncharacters given in the argument.\n \nThe main difference between the CAST() and CONVERT() is that\nCONVERT(expr,type) is ODBC syntax while CAST(expr as type)\nand CONVERT(... USING ...) are SQL92 syntax.\n \nCONVERT() with USING is used to convert data between\ndifferent character sets. In MariaDB, transcoding names are\nthe same as the\ncorresponding character set names. For example, this\nstatement\nconverts the string \'abc\' in the default character set to\nthe\ncorresponding string in the utf8 character set:\n \nSELECT CONVERT(\'abc\' USING utf8);\n \nExamples\n-------- \nSELECT enum_col FROM tbl_name \nORDER BY CAST(enum_col AS CHAR);\n \nConverting a BINARY to string to permit the LOWER function\nto work:\n \nSET @x = \'AardVark\';\n \nSET @x = BINARY \'AardVark\';\n \nSELECT LOWER(@x), LOWER(CONVERT (@x USING latin1));\n+-----------+----------------------------------+\n| LOWER(@x) | LOWER(CONVERT (@x USING latin1)) |\n+-----------+----------------------------------+\n| AardVark | aardvark |\n+-----------+----------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/convert/','','https://mariadb.com/kb/en/library/convert/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (589,37,'ELT','Syntax\n------ \nELT(N, str1[, str2, str3,...])\n \nDescription\n----------- \nTakes a numeric argument and a series of string arguments.\nReturns the string that corresponds to the given numeric\nposition. For instance, it returns str1 if N is 1, str2 if N\nis 2, and so on. If the numeric argument is a FLOAT, MariaDB\nrounds it to the nearest INTEGER. If the numeric argument is\nless than 1, greater than the total number of arguments, or\nnot a number, ELT() returns NULL. It must have at least two\narguments.\n \nIt is complementary to the FIELD() function.\n \nExamples\n-------- \nSELECT ELT(1, \'ej\', \'Heja\', \'hej\', \'foo\');\n+------------------------------------+\n| ELT(1, \'ej\', \'Heja\', \'hej\', \'foo\') |\n+------------------------------------+\n| ej |\n+------------------------------------+\n \nSELECT ELT(4, \'ej\', \'Heja\', \'hej\', \'foo\');\n+------------------------------------+\n| ELT(4, \'ej\', \'Heja\', \'hej\', \'foo\') |\n+------------------------------------+\n| foo |\n+------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/elt/','','https://mariadb.com/kb/en/library/elt/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (590,37,'EXPORT_SET','Syntax\n------ \nEXPORT_SET(bits, on, off[, separator[, number_of_bits]])\n \nDescription\n----------- \nTakes a minimum of three arguments. Returns a string where\neach bit in the given bits argument is returned, with the\nstring values given for on and off. \n \nBits are examined from right to left, (from low-order to\nhigh-order bits). Strings are added to the result from left\nto right, separated by a separator string (defaults as\n\',\'). You can optionally limit the number of bits the\nEXPORT_SET() function examines using the number_of_bits\noption. \n \nIf any of the arguments are set as NULL, the function\nreturns NULL.\n \nExamples\n-------- \nSELECT EXPORT_SET(5,\'Y\',\'N\',\',\',4);\n+-----------------------------+\n| EXPORT_SET(5,\'Y\',\'N\',\',\',4) |\n+-----------------------------+\n| Y,N,Y,N |\n+-----------------------------+\n \nSELECT EXPORT_SET(6,\'1\',\'0\',\',\',10);\n+------------------------------+\n| EXPORT_SET(6,\'1\',\'0\',\',\',10) |\n+------------------------------+\n| 0,1,1,0,0,0,0,0,0,0 |\n+------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/export_set/','','https://mariadb.com/kb/en/library/export_set/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (591,37,'EXTRACTVALUE','Syntax\n------ \nEXTRACTVALUE(xml_frag, xpath_expr)\n \nDescription\n----------- \nThe EXTRACTVALUE() function takes two string arguments: a\nfragment of XML markup and an XPath expression, (also known\nas a locator). It returns the text (That is, CDDATA), of the\nfirst text node which is a child of the element or elements\nmatching the XPath expression. \n \nIn cases where a valid XPath expression does not match any\ntext nodes in a valid XML fragment, (including the implicit\n/text() expression), the EXTRACTVALUE() function returns an\nempty string.\n \nInvalid Arguments\n \nWhen either the XML fragment or the XPath expression is\nNULL, the EXTRACTVALUE() function returns NULL. When the XML\nfragment is invalid, it raises a warning Code 1525:\n \nWarning (Code 1525): Incorrect XML value: \'parse error at\nline 1 pos 11: unexpected END-OF-INPUT\'\n \nWhen the XPath value is invalid, it generates an Error 1105:\n \nERROR 1105 (HY000): XPATH syntax error: \')\'\n \nExplicit text() Expressions\n \nThis function is the equivalent of performing a match using\nthe XPath expression after appending /text(). In other\nwords:\n \nSELECT\n EXTRACTVALUE(\'example\', \'/cases/case\') AS \'Base\nExample\',\n EXTRACTVALUE(\'example\', \'/cases/case/text()\') AS\n\'text() Example\';\n \n+--------------+----------------+\n| Base Example | text() Example |\n+--------------+----------------+\n| example | example |\n+--------------+----------------+\n \nCount Matches\n \nWhen EXTRACTVALUE() returns multiple matches, it returns the\ncontent of the first child text node of each matching\nelement, in the matched order, as a single, space-delimited\nstring.\n \nBy design, the EXTRACTVALUE() function makes no distinction\nbetween a match on an empty element and no match at all. If\nyou need to determine whether no matching element was found\nin the XML fragment or if an element was found that\ncontained no child text nodes, use the XPath count()\nfunction. \n \nFor instance, when looking for a value that exists, but\ncontains no child text nodes, you would get a count of the\nnumber of matching instances:\n \nSELECT\n EXTRACTVALUE(\'\', \'/cases/case\') AS \'Empty Example\',\n EXTRACTVALUE(\'\', \'/cases/case/count()\') AS \'count()\nExample\';\n \n+---------------+-----------------+\n| Empty Example | count() Example |\n+---------------+-----------------+\n| | 1 |\n+---------------+-----------------+\n \nAlternatively, when looking for a value that doesn\'t exist,\ncount() returns 0.\n \nSELECT\n EXTRACTVALUE(\'\', \'/cases/person\') AS \'No Match\nExample\',\n EXTRACTVALUE(\'\', \'/cases/person/count()\') AS \'count()\nExample\';\n \n+------------------+-----------------+\n| No Match Example | count() Example |\n+------------------+-----------------+\n| | 0|\n+------------------+-----------------+\n \nMatches\n \nImportant: The EXTRACTVALUE() function only returns CDDATA.\nIt does not return tags that the element might contain or\nthe text that these child elements contain.\n \nSELECT EXTRACTVALUE(\'Personx@example.com\', \'/cases\') AS\nCase;\n \n+--------+\n| Case |\n+--------+\n| Person |\n+--------+\n \nNote, in the above example, while the XPath expression\nmatches to the parent instance, it does not return the\ncontained tag or its content.\n \nExamples\n-------- \nSELECT\n ExtractValue(\'cccddd\', \'/a\') AS val1,\n ExtractValue(\'cccddd\', \'/a/b\') AS val2,\n ExtractValue(\'cccddd\', \'//b\') AS val3,\n ExtractValue(\'cccddd\', \'/b\') AS val4,\n ExtractValue(\'cccdddeee\', \'//b\') AS val5;\n \n+------+------+------+------+---------+\n| val1 | val2 | val3 | val4 | val5 |\n+------+------+------+------+---------+\n| ccc | ddd | ddd | | ddd eee |\n+------+------+------+------+---------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/extractvalue/','','https://mariadb.com/kb/en/library/extractvalue/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (592,37,'FIELD','Syntax\n------ \nFIELD(pattern, str1[,str2,...])\n \nDescription\n----------- \nReturns the index position of the string or number matching\nthe given pattern. Returns 0 in the event that none of the\narguments match the pattern. Raises an Error 1582 if not\ngiven at least two arguments.\n \nWhen all arguments given to the FIELD() function are\nstrings, they are treated as case-insensitive. When all the\narguments are numbers, they are treated as numbers.\nOtherwise, they are treated as doubles. \n \nIf the given pattern occurs more than once, the FIELD()\nfunction only returns the index of the first instance. If\nthe given pattern is NULL, the function returns 0, as a NULL\npattern always fails to match.\n \nThis function is complementary to the ELT() function.\n \nExamples\n-------- \nSELECT FIELD(\'ej\', \'Hej\', \'ej\', \'Heja\', \'hej\',\n\'foo\') \n AS \'Field Results\';\n \n+---------------+\n| Field Results | \n+---------------+\n| 2 |\n+---------------+\n \nSELECT FIELD(\'fo\', \'Hej\', \'ej\', \'Heja\', \'hej\',\n\'foo\')\n AS \'Field Results\';\n \n+---------------+\n| Field Results | \n+---------------+\n| 0 |\n+---------------+\n \nSELECT FIELD(1, 2, 3, 4, 5, 1) AS \'Field Results\';\n \n+---------------+\n| Field Results |\n+---------------+\n| 5 |\n+---------------+\n \nSELECT FIELD(NULL, 2, 3) AS \'Field Results\';\n \n+---------------+\n| Field Results |\n+---------------+\n| 0 |\n+---------------+\n \nSELECT FIELD(\'fail\') AS \'Field Results\';\n \nError 1582 (42000): Incorrect parameter count in call\nto native function \'field\'\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/field/','','https://mariadb.com/kb/en/library/field/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (593,37,'FIND_IN_SET','Syntax\n------ \nFIND_IN_SET(pattern, strlist)\n \nDescription\n----------- \nReturns the index position where the given pattern occurs in\na string list. The first argument is the pattern you want to\nsearch for. The second argument is a string containing\ncomma-separated variables. If the second argument is of the\nSET data-type, the function is optimized to use bit\narithmetic.\n \nIf the pattern does not occur in the string list or if the\nstring list is an empty string, the function returns 0. If\neither argument is NULL, the function returns NULL. The\nfunction does not return the correct result if the pattern\ncontains a comma (\",\") character.\n \nExamples\n-------- \nSELECT FIND_IN_SET(\'b\',\'a,b,c,d\') AS \"Found Results\";\n \n+---------------+\n| Found Results |\n+---------------+\n| 2 |\n+---------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/find_in_set/','','https://mariadb.com/kb/en/library/find_in_set/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (594,37,'FORMAT','Syntax\n------ \nFORMAT(num, decimal_position[, locale])\n \nDescription\n----------- \nFormats the given number for display as a string, adding\nseparators to appropriate position and rounding the results\nto the given decimal position. For instance, it would format\n15233.345 to 15,233.35.\n \nIf the given decimal position is 0, it rounds to return no\ndecimal point or fractional part. You can optionally specify\na locale value to format numbers to the pattern appropriate\nfor the given region.\n \nExamples\n-------- \nSELECT FORMAT(1234567890.09876543210, 4) AS \'Format\';\n \n+--------------------+\n| Format |\n+--------------------+\n| 1,234,567,890.0988 |\n+--------------------+\n \nSELECT FORMAT(1234567.89, 4) AS \'Format\';\n \n+----------------+\n| Format |\n+----------------+\n| 1,234,567.8900 |\n+----------------+\n \nSELECT FORMAT(1234567.89, 0) AS \'Format\';\n \n+-----------+\n| Format |\n+-----------+\n| 1,234,568 |\n+-----------+\n \nSELECT FORMAT(123456789,2,\'rm_CH\') AS \'Format\';\n \n+----------------+\n| Format |\n+----------------+\n| 123\'456\'789,00 |\n+----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/format/','','https://mariadb.com/kb/en/library/format/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (595,37,'FROM_BASE64','The FROM_BASE64() function was introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nFROM_BASE64(str)\n \nDescription\n----------- \nDecodes the given base-64 encode string, returning the\nresult as a binary string. Returns NULL if the given string\nis NULL or if it\'s invalid.\n \nIt is the reverse of the TO_BASE64 function.\n \nThere are numerous methods to base-64 encode a string.\nMariaDB uses the following:\nIt encodes alphabet value 64 as \'+\'.\nIt encodes alphabet value 63 as \'/\'.\nIt codes output in groups of four printable characters. Each\nthree byte of data encoded uses four characters. If the\nfinal group is incomplete, it pads the difference with the\n\'=\' character.\nIt divides long output, adding a new line very 76\ncharacters.\nIn decoding, it recognizes and ignores newlines, carriage\nreturns, tabs and space whitespace characters.\n \nSELECT TO_BASE64(\'Maria\') AS \'Input\';\n \n+-----------+\n| Input |\n+-----------+\n| TWFyaWE= |\n+-----------+\n \nSELECT FROM_BASE64(\'TWFyaWE=\') AS \'Output\';\n \n+--------+\n| Output |\n+--------+\n| Maria |\n+--------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/from_base64/','','https://mariadb.com/kb/en/library/from_base64/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (596,37,'HEX','Syntax\n------ \nHEX(N_or_S)\n \nDescription\n----------- \nIf N_or_S is a number, returns a string representation of\nthe hexadecimal\nvalue of N, where N is a longlong (BIGINT) number. This is\nequivalent to CONV(N,10,16).\n \nIf N_or_S is a string, returns a hexadecimal string\nrepresentation of\nN_or_S where each byte of each character in N_or_S is\nconverted to two hexadecimal\ndigits. If N_or_S is NULL, returns NULL. The inverse of this\noperation is performed by the UNHEX()\nfunction.\n \nExamples\n-------- \nSELECT HEX(255);\n+----------+\n| HEX(255) |\n+----------+\n| FF |\n+----------+\n \nSELECT 0x4D617269614442;\n \n+------------------+\n| 0x4D617269614442 |\n+------------------+\n| MariaDB |\n+------------------+\n \nSELECT HEX(\'MariaDB\');\n+----------------+\n| HEX(\'MariaDB\') |\n+----------------+\n| 4D617269614442 |\n+----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/hex/','','https://mariadb.com/kb/en/library/hex/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (597,37,'INSERT Function','Syntax\n------ \nINSERT(str,pos,len,newstr)\n \nDescription\n----------- \nReturns the string str, with the substring beginning at\nposition pos\nand len characters long replaced by the string newstr.\nReturns the\noriginal string if pos is not within the length of the\nstring.\nReplaces the rest of the string from position pos if len is\nnot within\nthe length of the rest of the string. Returns NULL if any\nargument is\nNULL.\n \nExamples\n-------- \nSELECT INSERT(\'Quadratic\', 3, 4, \'What\');\n+-----------------------------------+\n| INSERT(\'Quadratic\', 3, 4, \'What\') |\n+-----------------------------------+\n| QuWhattic |\n+-----------------------------------+\n \nSELECT INSERT(\'Quadratic\', -1, 4, \'What\');\n+------------------------------------+\n| INSERT(\'Quadratic\', -1, 4, \'What\') |\n+------------------------------------+\n| Quadratic |\n+------------------------------------+\n \nSELECT INSERT(\'Quadratic\', 3, 100, \'What\');\n+-------------------------------------+\n| INSERT(\'Quadratic\', 3, 100, \'What\') |\n+-------------------------------------+\n| QuWhat |\n+-------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/insert-function/','','https://mariadb.com/kb/en/library/insert-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (598,37,'INSTR','Syntax\n------ \nINSTR(str,substr)\n \nDescription\n----------- \nReturns the position of the first occurrence of substring\nsubstr in\nstring str. This is the same as the two-argument form of\nLOCATE(),\nexcept that the order of the arguments is reversed.\n \nINSTR() performs a case-insensitive search.\n \nIf any argument is NULL, returns NULL.\n \nExamples\n-------- \nSELECT INSTR(\'foobarbar\', \'bar\');\n+---------------------------+\n| INSTR(\'foobarbar\', \'bar\') |\n+---------------------------+\n| 4 |\n+---------------------------+\n \nSELECT INSTR(\'My\', \'Maria\');\n+----------------------+\n| INSTR(\'My\', \'Maria\') |\n+----------------------+\n| 0 |\n+----------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/instr/','','https://mariadb.com/kb/en/library/instr/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (599,37,'LCASE','Syntax\n------ \nLCASE(str)\n \nDescription\n----------- \nLCASE() is a synonym for LOWER().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/lcase/','','https://mariadb.com/kb/en/library/lcase/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (600,37,'LEFT','Syntax\n------ \nLEFT(str,len)\n \nDescription\n----------- \nReturns the leftmost len characters from the string str, or\nNULL if\nany argument is NULL.\n \nExamples\n-------- \nSELECT LEFT(\'MariaDB\', 5);\n+--------------------+\n| LEFT(\'MariaDB\', 5) |\n+--------------------+\n| Maria |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/left/','','https://mariadb.com/kb/en/library/left/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (601,37,'LENGTH','Syntax\n------ \nLENGTH(str)\n \nDescription\n----------- \nReturns the length of the string str, measured in bytes. A\nmulti-byte\ncharacter counts as multiple bytes. This means that for a\nstring\ncontaining five two-byte characters, LENGTH() returns 10,\nwhereas\nCHAR_LENGTH() returns 5. \n \nIf str is not a string value, it is converted into a string.\nIf str is NULL, the function returns NULL.\n \nUntil MariaDB 10.3.1, returns MYSQL_TYPE_LONGLONG, or\nbigint(10), in all cases. From MariaDB 10.3.1, returns\nMYSQL_TYPE_LONG, or int(10), when the result would fit\nwithin 32-bits.\n \nOracle Mode\n \nWhen running Oracle mode from MariaDB 10.3, LENGTH() is a\nsynonym for CHAR_LENGTH().\n \nExamples\n-------- \nSELECT LENGTH(\'MariaDB\');\n+-------------------+\n| LENGTH(\'MariaDB\') |\n+-------------------+\n| 7 |\n+-------------------+\n \nSELECT LENGTH(\'π\');\n+--------------+\n| LENGTH(\'π\') |\n+--------------+\n| 2 |\n+--------------+\n \nIn Oracle mode from MariaDB 10.3:\n \nSELECT LENGTH(\'π\');\n+--------------+\n| LENGTH(\'π\') |\n+--------------+\n| 1 |\n+--------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/length/','','https://mariadb.com/kb/en/library/length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (602,37,'LENGTHB','Introduced in MariaDB 10.3.1 as part of the Oracle\ncompatibility enhancements.\n \nSyntax\n------ \nLENGTHB(str)\n \nDescription\n----------- \nLENGTHB() is a synonym for LENGTH().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/lengthb/','','https://mariadb.com/kb/en/library/lengthb/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (603,37,'LIKE','Syntax\n------ \nexpr LIKE pat [ESCAPE \'escape_char\']\nexpr NOT LIKE pat [ESCAPE \'escape_char\']\n \nDescription\n----------- \nTests whether expr matches the pattern pat. Returns either 1\n(TRUE) or 0 (FALSE).\nBoth expr and pat may be any valid expression and are\nevaluated to strings.\nPatterns may use the following wildcard characters:\n% matches any number of characters, including zero.\n_ matches any single character.\n \nUse NOT LIKE to test if a string does not match a pattern.\nThis is equivalent to using\nthe NOT operator on the entire LIKE expression.\n \nIf either the expression or the pattern is NULL, the result\nis NULL.\n \nLIKE performs case-insensitive substring matches if the\ncollation for the\nexpression and pattern is case-insensitive. For\ncase-sensitive matches, declare either argument\nto use a binary collation using COLLATE, or coerce either of\nthem to a BINARY\nstring using CAST. Use SHOW COLLATION to get a list of\navailable collations. Collations ending in _bin are\ncase-sensitive.\n \nNumeric arguments are coerced to binary strings.\n \nThe _ wildcard matches a single character, not byte. It will\nonly match a multi-byte character\nif it is valid in the expression\'s character set. For\nexample, _ will match _utf8\"€\", but it\nwill not match _latin1\"€\" because the Euro sign is not a\nvalid latin1 character. If necessary,\nuse CONVERT to use the expression in a different character\nset.\n \nIf you need to match the characters _ or %, you must escape\nthem. By default,\nyou can prefix the wildcard characters the backslash\ncharacter \\ to escape them.\nThe backslash is used both to encode special characters like\nnewlines when a string is\nparsed as well as to escape wildcards in a pattern after\nparsing. Thus, to match an\nactual backslash, you sometimes need to double-escape it as\n\"\\\\\\\\\".\n \nTo avoid difficulties with the backslash character, you can\nchange the wildcard escape\ncharacter using ESCAPE in a LIKE expression. The argument to\nESCAPE\nmust be a single-character string.\n \nExamples\n-------- \nSelect the days that begin with \"T\":\n \nCREATE TABLE t1 (d VARCHAR(16));\nINSERT INTO t1 VALUES (\"Monday\"), (\"Tuesday\"),\n(\"Wednesday\"), (\"Thursday\"), (\"Friday\"),\n(\"Saturday\"), (\"Sunday\");\nSELECT * FROM t1 WHERE d LIKE \"T%\";\n \nSELECT * FROM t1 WHERE d LIKE \"T%\";\n+----------+\n| d |\n+----------+\n| Tuesday |\n| Thursday |\n+----------+\n \nSelect the days that contain the substring \"es\":\n \nSELECT * FROM t1 WHERE d LIKE \"%es%\";\n \nSELECT * FROM t1 WHERE d LIKE \"%es%\";\n+-----------+\n| d |\n+-----------+\n| Tuesday |\n| Wednesday |\n+-----------+\n \nSelect the six-character day names:\n \nSELECT * FROM t1 WHERE d like \"___day\";\n \nSELECT * FROM t1 WHERE d like \"___day\";\n+---------+\n| d |\n+---------+\n| Monday |\n| Friday |\n| Sunday |\n+---------+\n \nWith the default collations, LIKE is case-insensitive:\n \nSELECT * FROM t1 where d like \"t%\";\n \nSELECT * FROM t1 where d like \"t%\";\n+----------+\n| d |\n+----------+\n| Tuesday |\n| Thursday |\n+----------+\n \nUse COLLATE to specify a binary collation, forcing\ncase-sensitive matches:\n \nSELECT * FROM t1 WHERE d like \"t%\" COLLATE latin1_bin;\n \nSELECT * FROM t1 WHERE d like \"t%\" COLLATE latin1_bin;\nEmpty set (0.00 sec)\n \nYou can include functions and operators in the expression to\nmatch. Select dates\nbased on their day name:\n \nCREATE TABLE t2 (d DATETIME);\nINSERT INTO t2 VALUES\n (\"2007-01-30 21:31:07\"),\n (\"1983-10-15 06:42:51\"),\n (\"2011-04-21 12:34:56\"),\n (\"2011-10-30 06:31:41\"),\n (\"2011-01-30 14:03:25\"),\n (\"2004-10-07 11:19:34\");\nSELECT * FROM t2 WHERE DAYNAME(d) LIKE \"T%\";\n \nSELECT * FROM t2 WHERE DAYNAME(d) LIKE \"T%\";\n+------------------+\n| d |\n+------------------+\n| 2007-01-30 21:31 |\n| 2011-04-21 12:34 |\n| 2004-10-07 11:19 |\n+------------------+\n3 rows in set, 7 warnings (0.00 sec)\n \nOptimizing LIKE\n \nMariaDB can use indexes for LIKE on string columns in the\ncase where the LIKE doesn\'t start with % or _.\nStarting from MariaDB 10.0, one can set the\noptimizer_use_condition_selectivity variable to 5. If this\nis done, then the optimizer will read\noptimizer_selectivity_sampling_limit rows to calculate the\nselectivity of the LIKE expression before starting to\ncalculate the query plan. This can help speed up some LIKE\nqueries by providing the optimizer with more information\nabout your data.\n \n\n\nURL: https://mariadb.com/kb/en/library/like/','','https://mariadb.com/kb/en/library/like/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (604,37,'LOAD_FILE','Syntax\n------ \nLOAD_FILE(file_name)\n \nDescription\n----------- \nReads the file and returns the file contents as a string. To\nuse this function, the file must be located on the server\nhost, you must specify the full path name to the file, and\nyou must have the FILE privilege. The file must be readable\nby all and it must be less than the size, in bytes, of the\nmax_allowed_packet system variable. If the secure_file_priv\nsystem variable is set to a non-empty directory name, the\nfile to be loaded must be located in that directory.\n \nIf the file does not exist or cannot be read because one of\nthe preceding conditions is not satisfied, the function\nreturns NULL.\n \nSince MariaDB 5.1, the character_set_filesystem system\nvariable has controlled interpretation of file names that\nare given as literal strings.\n \nStatements using the LOAD_FILE() function are not safe for\nstatement based replication. This is because the slave will\nexecute the LOAD_FILE() command itself. If the file doesn\'t\nexist on the slave, the function will return NULL.\n \nExamples\n-------- \nUPDATE t SET blob_col=LOAD_FILE(\'/tmp/picture\') WHERE\nid=1;\n \n\n\nURL: https://mariadb.com/kb/en/library/load_file/','','https://mariadb.com/kb/en/library/load_file/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (605,37,'LOCATE','Syntax\n------ \nLOCATE(substr,str), LOCATE(substr,str,pos)\n \nDescription\n----------- \nThe first syntax returns the position of the first\noccurrence of\nsubstring substr in string str. The second syntax returns\nthe position\nof the first occurrence of substring substr in string str,\nstarting at\nposition pos. Returns 0 if substr is not in str.\n \nLOCATE() performs a case-insensitive search.\n \nIf any argument is NULL, returns NULL.\n \nINSTR() is a synonym of LOCATE() without the third argument.\n \nExamples\n-------- \nSELECT LOCATE(\'bar\', \'foobarbar\');\n+----------------------------+\n| LOCATE(\'bar\', \'foobarbar\') |\n+----------------------------+\n| 4 |\n+----------------------------+\n \nSELECT LOCATE(\'My\', \'Maria\');\n+-----------------------+\n| LOCATE(\'My\', \'Maria\') |\n+-----------------------+\n| 0 |\n+-----------------------+\n \nSELECT LOCATE(\'bar\', \'foobarbar\', 5);\n+-------------------------------+\n| LOCATE(\'bar\', \'foobarbar\', 5) |\n+-------------------------------+\n| 7 |\n+-------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/locate/','','https://mariadb.com/kb/en/library/locate/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (606,37,'LOWER','Syntax\n------ \nLOWER(str)\n \nDescription\n----------- \nReturns the string str with all characters changed to\nlowercase\naccording to the current character set mapping. The default\nis latin1\n(cp1252 West European).\n \nExamples\n-------- \n SELECT LOWER(\'QUADRATICALLY\');\n+------------------------+\n| LOWER(\'QUADRATICALLY\') |\n+------------------------+\n| quadratically |\n+------------------------+\n \nLOWER() (and UPPER()) are ineffective when applied to binary\nstrings (BINARY, VARBINARY, BLOB). \nTo perform lettercase conversion, CONVERT the string to a\nnon-binary string:\n \nSET @str = BINARY \'North Carolina\';\n \nSELECT LOWER(@str), LOWER(CONVERT(@str USING latin1));\n+----------------+-----------------------------------+\n| LOWER(@str) | LOWER(CONVERT(@str USING latin1)) |\n+----------------+-----------------------------------+\n| North Carolina | north carolina |\n+----------------+-----------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/lower/','','https://mariadb.com/kb/en/library/lower/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (607,37,'LPAD','Syntax\n------ \nLPAD(str, len [,padstr])\n \nDescription\n----------- \nReturns the string str, left-padded with the string padstr\nto a length\nof len characters. If str is longer than len, the return\nvalue is\nshortened to len characters. If padstr is omitted, the LPAD\nfunction pads spaces.\n \nPrior to MariaDB 10.3.1, the padstr parameter was mandatory.\n \nReturns NULL if given a NULL argument. If the result is\nempty (zero length), returns either an empty string or, from\nMariaDB 10.3.6 with SQL_MODE=Oracle, NULL.\n \nThe Oracle mode version of the function can be accessed\noutside of Oracle mode by using LPAD_ORACLE as the function\nname.\n \nExamples\n-------- \nSELECT LPAD(\'hello\',10,\'.\');\n+----------------------+\n| LPAD(\'hello\',10,\'.\') |\n+----------------------+\n| .....hello |\n+----------------------+\n \nSELECT LPAD(\'hello\',2,\'.\');\n+---------------------+\n| LPAD(\'hello\',2,\'.\') |\n+---------------------+\n| he |\n+---------------------+\n \nFrom MariaDB 10.3.1, with the pad string defaulting to\nspace.\n \nSELECT LPAD(\'hello\',10);\n+------------------+\n| LPAD(\'hello\',10) |\n+------------------+\n| hello |\n+------------------+\n \nOracle mode version from MariaDB 10.3.6:\n \nSELECT LPAD(\'\',0),LPAD_ORACLE(\'\',0);\n+------------+-------------------+\n| LPAD(\'\',0) | LPAD_ORACLE(\'\',0) |\n+------------+-------------------+\n| | NULL |\n+------------+-------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/lpad/','','https://mariadb.com/kb/en/library/lpad/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (608,37,'LTRIM','Syntax\n------ \nLTRIM(str)\n \nDescription\n----------- \nReturns the string str with leading space characters\nremoved.\n \nReturns NULL if given a NULL argument. If the result is\nempty, returns either an empty string, or, from MariaDB\n10.3.6 with SQL_MODE=Oracle, NULL.\n \nThe Oracle mode version of the function can be accessed\noutside of Oracle mode by using LTRIM_ORACLE as the function\nname.\n \nExamples\n-------- \nSELECT QUOTE(LTRIM(\' MariaDB \'));\n+-------------------------------+\n| QUOTE(LTRIM(\' MariaDB \')) |\n+-------------------------------+\n| \'MariaDB \' |\n+-------------------------------+\n \nOracle mode version from MariaDB 10.3.6:\n \nSELECT LTRIM(\'\'),LTRIM_ORACLE(\'\');\n+-----------+------------------+\n| LTRIM(\'\') | LTRIM_ORACLE(\'\') |\n+-----------+------------------+\n| | NULL |\n+-----------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/ltrim/','','https://mariadb.com/kb/en/library/ltrim/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (609,37,'MAKE_SET','Syntax\n------ \nMAKE_SET(bits,str1,str2,...)\n \nDescription\n----------- \nReturns a set value (a string containing substrings\nseparated by \",\"\ncharacters) consisting of the strings that have the\ncorresponding bit\nin bits set. str1 corresponds to bit 0, str2 to bit 1, and\nso on. NULL\nvalues in str1, str2, ... are not appended to the result.\n \nExamples\n-------- \nSELECT MAKE_SET(1,\'a\',\'b\',\'c\');\n+-------------------------+\n| MAKE_SET(1,\'a\',\'b\',\'c\') |\n+-------------------------+\n| a |\n+-------------------------+\n \nSELECT MAKE_SET(1 | 4,\'hello\',\'nice\',\'world\');\n+----------------------------------------+\n| MAKE_SET(1 | 4,\'hello\',\'nice\',\'world\') |\n+----------------------------------------+\n| hello,world |\n+----------------------------------------+\n \nSELECT MAKE_SET(1 | 4,\'hello\',\'nice\',NULL,\'world\');\n+---------------------------------------------+\n| MAKE_SET(1 | 4,\'hello\',\'nice\',NULL,\'world\') |\n+---------------------------------------------+\n| hello |\n+---------------------------------------------+\n \nSELECT QUOTE(MAKE_SET(0,\'a\',\'b\',\'c\'));\n+--------------------------------+\n| QUOTE(MAKE_SET(0,\'a\',\'b\',\'c\')) |\n+--------------------------------+\n| \'\' |\n+--------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/make_set/','','https://mariadb.com/kb/en/library/make_set/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (610,37,'MATCH AGAINST','Syntax\n------ \nMATCH (col1,col2,...) AGAINST (expr [search_modifier])\n \nDescription\n----------- \nA special construct used to perform a fulltext search on a\nfulltext index.\n \nSee Fulltext Index Overview for a full description, and\nFull-text Indexes for more articles on the topic.\n \nExamples\n-------- \nCREATE TABLE ft_myisam(copy TEXT,FULLTEXT(copy))\nENGINE=MyISAM;\n \nINSERT INTO ft_myisam(copy) VALUES (\'Once upon a time\'),\n(\'There was a wicked witch\'), \n (\'Who ate everybody up\');\n \nSELECT * FROM ft_myisam WHERE MATCH(copy)\nAGAINST(\'wicked\');\n+--------------------------+\n| copy |\n+--------------------------+\n| There was a wicked witch |\n+--------------------------+\n \nSELECT id, body, MATCH (title,body) AGAINST\n (\'Security implications of running MySQL as root\'\n IN NATURAL LANGUAGE MODE) AS score\n FROM articles WHERE MATCH (title,body) AGAINST\n (\'Security implications of running MySQL as root\'\n IN NATURAL LANGUAGE MODE);\n+----+-------------------------------------+-----------------+\n| id | body | score |\n+----+-------------------------------------+-----------------+\n| 4 | 1. Never run mysqld as root. 2. ... | 1.5219271183014\n|\n| 6 | When configured properly, MySQL ... | 1.3114095926285\n|\n+----+-------------------------------------+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/match-against/','','https://mariadb.com/kb/en/library/match-against/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (611,37,'MID','Syntax\n------ \nMID(str,pos,len)\n \nDescription\n----------- \nMID(str,pos,len) is a synonym for SUBSTRING(str,pos,len).\n \nExamples\n-------- \nSELECT MID(\'abcd\',4,1);\n+-----------------+\n| MID(\'abcd\',4,1) |\n+-----------------+\n| d |\n+-----------------+\n \nSELECT MID(\'abcd\',2,2);\n+-----------------+\n| MID(\'abcd\',2,2) |\n+-----------------+\n| bc |\n+-----------------+\n \nA negative starting position:\n \nSELECT MID(\'abcd\',-2,4);\n+------------------+\n| MID(\'abcd\',-2,4) |\n+------------------+\n| cd |\n+------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/mid/','','https://mariadb.com/kb/en/library/mid/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (612,37,'NOT LIKE','Syntax\n------ \nexpr NOT LIKE pat [ESCAPE \'escape_char\']\n \nDescription\n----------- \nThis is the same as NOT (expr LIKE pat [ESCAPE\n\'escape_char\']).\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/not-like/','','https://mariadb.com/kb/en/library/not-like/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (613,37,'NOT REGEXP','Syntax\n------ \nexpr NOT REGEXP pat, expr NOT RLIKE pat\n \nDescription\n----------- \nThis is the same as NOT (expr REGEXP pat).\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/not-regexp/','','https://mariadb.com/kb/en/library/not-regexp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (614,37,'OCTET_LENGTH','Syntax\n------ \nOCTET_LENGTH(str)\n \nDescription\n----------- \nOCTET_LENGTH() is normally a synonym for LENGTH(). When\nrunning Oracle mode from MariaDB 10.3, they are not\nsynonyms, but OCTET_LENGTH() behaves as LENGTH() would when\nnot in Oracle mode.\n \n\n\nURL: https://mariadb.com/kb/en/library/octet_length/','','https://mariadb.com/kb/en/library/octet_length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (615,37,'ORD','Syntax\n------ \nORD(str)\n \nDescription\n----------- \nIf the leftmost character of the string str is a multi-byte\ncharacter,\nreturns the code for that character, calculated from the\nnumeric\nvalues of its constituent bytes using this formula:\n \n (1st byte code)\n+ (2nd byte code x 256)\n+ (3rd byte code x 256 x 256) ...\n \nIf the leftmost character is not a multi-byte character,\nORD() returns\nthe same value as the ASCII() function.\n \nExamples\n-------- \nSELECT ORD(\'2\');\n+----------+\n| ORD(\'2\') |\n+----------+\n| 50 |\n+----------+\n \n\n\nURL: https://mariadb.com/kb/en/library/ord/','','https://mariadb.com/kb/en/library/ord/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (616,37,'POSITION','Syntax\n------ \nPOSITION(substr IN str)\n \nDescription\n----------- \nPOSITION(substr IN str) is a synonym for LOCATE(substr,str).\n \nIt\'s part of ODBC 3.0.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/position/','','https://mariadb.com/kb/en/library/position/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (617,37,'QUOTE','Syntax\n------ \nQUOTE(str)\n \nDescription\n----------- \nQuotes a string to produce a result that can be used as a\nproperly escaped data\nvalue in an SQL statement. The string is returned enclosed\nby single quotes and\nwith each instance of single quote (\"\'\"), backslash\n(\"\\\"),\nASCII NUL, and Control-Z preceded by a backslash. If the\nargument\nis NULL, the return value is the word \"NULL\" without\nenclosing single\nquotes.\n \nExamples\n-------- \nSELECT QUOTE(\"Don\'t!\");\n+-----------------+\n| QUOTE(\"Don\'t!\") |\n+-----------------+\n| \'Don\\\'t!\' |\n+-----------------+\n \nSELECT QUOTE(NULL); \n+-------------+\n| QUOTE(NULL) |\n+-------------+\n| NULL |\n+-------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/quote/','','https://mariadb.com/kb/en/library/quote/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (618,37,'REGEXP_INSTR','REGEXP_INSTR was introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nREGEXP_INSTR(subject, pattern)\n \nReturns the position of the first occurrence of the regular\nexpression pattern in the string subject, or 0 if pattern\nwas not found.\n \nThe positions start with 1 and are measured in characters\n(i.e. not in bytes), which is important for multi-byte\ncharacter sets. You can cast a multi-byte character set to\nBINARY to get offsets in bytes.\n \nThe function follows the case sensitivity rules of the\neffective collation. Matching is performed case\ninsensitively for case insensitive collations, and case\nsensitively for case sensitive collations and for binary\ndata.\n \nThe collation case sensitivity can be overwritten using the\n(?i) and (?-i) PCRE flags.\n \nMariaDB 10.0.5 switched to the PCRE regular expression\nlibrary for enhanced regular expression performance, and\nREGEXP_INSTR was introduced as part of this enhancement.\n \nExamples\n-------- \nSELECT REGEXP_INSTR(\'abc\',\'b\');\n-> 2\n \nSELECT REGEXP_INSTR(\'abc\',\'x\');\n-> 0\n \nSELECT REGEXP_INSTR(\'BJÖRN\',\'N\');\n-> 5\n \nCasting a multi-byte character set as BINARY to get offsets\nin bytes:\n \nSELECT REGEXP_INSTR(BINARY \'BJÖRN\',\'N\') AS\ncast_utf8_to_binary;\n-> 6\n \nCase sensitivity:\n \nSELECT REGEXP_INSTR(\'ABC\',\'b\');\n-> 2\n \nSELECT REGEXP_INSTR(\'ABC\' COLLATE utf8_bin,\'b\');\n-> 0\n \nSELECT REGEXP_INSTR(BINARY\'ABC\',\'b\');\n-> 0\n \nSELECT REGEXP_INSTR(\'ABC\',\'(?-i)b\');\n-> 0\n \nSELECT REGEXP_INSTR(\'ABC\' COLLATE utf8_bin,\'(?i)b\');\n-> 2\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/regexp_instr/','','https://mariadb.com/kb/en/regexp_instr/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (619,37,'REGEXP_REPLACE','REGEXP_REPLACE was introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nREGEXP_REPLACE(subject, pattern, replace)\n \nDescription\n----------- \nREGEXP_REPLACE returns the string subject with all\noccurrences of the regular expression pattern replaced by\nthe string replace. If no occurrences are found, then\nsubject is returned as is.\n \nThe replace string can have backreferences to the\nsubexpressions in the form \\N, where N is a number from 1\nto 9.\n \nThe function follows the case sensitivity rules of the\neffective collation. Matching is performed case\ninsensitively for case insensitive collations, and case\nsensitively for case sensitive collations and for binary\ndata.\n \nThe collation case sensitivity can be overwritten using the\n(?i) and (?-i) PCRE flags.\n \nMariaDB 10.0.5 switched to the PCRE regular expression\nlibrary for enhanced regular expression performance, and\nREGEXP_REPLACE was introduced as part of this enhancement.\n \nMariaDB 10.0.11 introduced the default_regex_flags variable\nto address the remaining compatibilities between PCRE and\nthe old regex library. \n \nExamples\n-------- \nSELECT REGEXP_REPLACE(\'ab12cd\',\'[0-9]\',\'\') AS\nremove_digits;\n-> abcd\n \nSELECT REGEXP_REPLACE(\'titlebody\', \'\',\' \')\nAS strip_html;\n-> title body\n \nBackreferences to the subexpressions in the form \\N, where\nN is a number from 1 to 9:\n \nSELECT REGEXP_REPLACE(\'James Bond\',\'^(.*)\n(.*)$\',\'\\\\2, \\\\1\') AS reorder_name;\n-> Bond, James\n \nCase insensitive and case sensitive matches:\n \nSELECT REGEXP_REPLACE(\'ABC\',\'b\',\'-\') AS\ncase_insensitive;\n-> A-C\n \nSELECT REGEXP_REPLACE(\'ABC\' COLLATE utf8_bin,\'b\',\'-\')\nAS case_sensitive;\n-> ABC\n \nSELECT REGEXP_REPLACE(BINARY \'ABC\',\'b\',\'-\') AS\nbinary_data;\n-> ABC\n \nOverwriting the collation case sensitivity using the (?i)\nand (?-i) PCRE flags.\n \nSELECT REGEXP_REPLACE(\'ABC\',\'(?-i)b\',\'-\') AS\nforce_case_sensitive;\n-> ABC\n \nSELECT REGEXP_REPLACE(BINARY \'ABC\',\'(?i)b\',\'-\') AS\nforce_case_insensitive;\n-> A-C\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/regexp_replace/','','https://mariadb.com/kb/en/regexp_replace/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (620,37,'REGEXP_SUBSTR','REGEXP_SUBSTR was introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nREGEXP_SUBSTR(subject,pattern)\n \nDescription\n----------- \nReturns the part of the string subject that matches the\nregular expression pattern, or an empty string if pattern\nwas not found.\n \nThe function follows the case sensitivity rules of the\neffective collation. Matching is performed case\ninsensitively for case insensitive collations, and case\nsensitively for case sensitive collations and for binary\ndata.\n \nThe collation case sensitivity can be overwritten using the\n(?i) and (?-i) PCRE flags.\n \nMariaDB 10.0.5 switched to the PCRE regular expression\nlibrary for enhanced regular expression performance, and\nREGEXP_SUBSTR was introduced as part of this enhancement.\n \nMariaDB 10.0.11 introduced the default_regex_flags variable\nto address the remaining compatibilities between PCRE and\nthe old regex library. \n \nExamples\n-------- \nSELECT REGEXP_SUBSTR(\'ab12cd\',\'[0-9]+\');\n-> 12\n \nSELECT REGEXP_SUBSTR(\n \'See https://mariadb.org/en/foundation/ for details\',\n \'https?://[^/]*\');\n-> https://mariadb.org\n \nSELECT REGEXP_SUBSTR(\'ABC\',\'b\');\n-> B\n \nSELECT REGEXP_SUBSTR(\'ABC\' COLLATE utf8_bin,\'b\');\n->\n \nSELECT REGEXP_SUBSTR(BINARY\'ABC\',\'b\');\n->\n \nSELECT REGEXP_SUBSTR(\'ABC\',\'(?i)b\');\n-> B\n \nSELECT REGEXP_SUBSTR(\'ABC\' COLLATE utf8_bin,\'(?+i)b\');\n-> B\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/regexp_substr/','','https://mariadb.com/kb/en/regexp_substr/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (621,37,'REPEAT Function','Syntax\n------ \nREPEAT(str,count)\n \nDescription\n----------- \nReturns a string consisting of the string str repeated count\ntimes. If\ncount is less than 1, returns an empty string. Returns NULL\nif str or\ncount are NULL.\n \nExamples\n-------- \nSELECT QUOTE(REPEAT(\'MariaDB \',4));\n+------------------------------------+\n| QUOTE(REPEAT(\'MariaDB \',4)) |\n+------------------------------------+\n| \'MariaDB MariaDB MariaDB MariaDB \' |\n+------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/repeat-function/','','https://mariadb.com/kb/en/library/repeat-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (622,37,'REPLACE Function','Syntax\n------ \nREPLACE(str,from_str,to_str)\n \nDescription\n----------- \nReturns the string str with all occurrences of the string\nfrom_str\nreplaced by the string to_str. REPLACE() performs a\ncase-sensitive\nmatch when searching for from_str.\n \nExamples\n-------- \nSELECT REPLACE(\'www.mariadb.org\', \'w\', \'Ww\');\n+---------------------------------------+\n| REPLACE(\'www.mariadb.org\', \'w\', \'Ww\') |\n+---------------------------------------+\n| WwWwWw.mariadb.org |\n+---------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/replace-function/','','https://mariadb.com/kb/en/library/replace-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (623,37,'REVERSE','Syntax\n------ \nREVERSE(str)\n \nDescription\n----------- \nReturns the string str with the order of the characters\nreversed.\n \nExamples\n-------- \nSELECT REVERSE(\'desserts\');\n+---------------------+\n| REVERSE(\'desserts\') |\n+---------------------+\n| stressed |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/reverse/','','https://mariadb.com/kb/en/library/reverse/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (624,37,'RIGHT','Syntax\n------ \nRIGHT(str,len)\n \nDescription\n----------- \nReturns the rightmost len characters from the string str, or\nNULL if\nany argument is NULL.\n \nExamples\n-------- \nSELECT RIGHT(\'MariaDB\', 2);\n+---------------------+\n| RIGHT(\'MariaDB\', 2) |\n+---------------------+\n| DB |\n+---------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/right/','','https://mariadb.com/kb/en/library/right/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (625,37,'RPAD','Syntax\n------ \nRPAD(str, len [, padstr])\n \nDescription\n----------- \nReturns the string str, right-padded with the string padstr\nto a\nlength of len characters. If str is longer than len, the\nreturn value\nis shortened to len characters. If padstr is omitted, the\nRPAD function pads spaces.\n \nPrior to MariaDB 10.3.1, the padstr parameter was mandatory.\n \nReturns NULL if given a NULL argument. If the result is\nempty (a length of zero), returns either an empty string,\nor, from MariaDB 10.3.6 with SQL_MODE=Oracle, NULL.\n \nThe Oracle mode version of the function can be accessed\noutside of Oracle mode by using RPAD_ORACLE as the function\nname.\n \nExamples\n-------- \nSELECT RPAD(\'hello\',10,\'.\');\n+----------------------+\n| RPAD(\'hello\',10,\'.\') |\n+----------------------+\n| hello..... |\n+----------------------+\n \nSELECT RPAD(\'hello\',2,\'.\');\n+---------------------+\n| RPAD(\'hello\',2,\'.\') |\n+---------------------+\n| he |\n+---------------------+\n \nFrom MariaDB 10.3.1, with the pad string defaulting to\nspace.\n \nSELECT RPAD(\'hello\',30);\n+--------------------------------+\n| RPAD(\'hello\',30) |\n+--------------------------------+\n| hello |\n+--------------------------------+\n \nOracle mode version from MariaDB 10.3.6:\n \nSELECT RPAD(\'\',0),RPAD_ORACLE(\'\',0);\n+------------+-------------------+\n| RPAD(\'\',0) | RPAD_ORACLE(\'\',0) |\n+------------+-------------------+\n| | NULL |\n+------------+-------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/rpad/','','https://mariadb.com/kb/en/library/rpad/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (626,37,'RTRIM','Syntax\n------ \nRTRIM(str)\n \nDescription\n----------- \nReturns the string str with trailing space characters\nremoved.\n \nReturns NULL if given a NULL argument. If the result is\nempty, returns either an empty string, or, from MariaDB\n10.3.6 with SQL_MODE=Oracle, NULL.\n \nThe Oracle mode version of the function can be accessed\noutside of Oracle mode by using RTRIM_ORACLE as the function\nname.\n \nExamples\n-------- \nSELECT QUOTE(RTRIM(\'MariaDB \'));\n+-----------------------------+\n| QUOTE(RTRIM(\'MariaDB \')) |\n+-----------------------------+\n| \'MariaDB\' |\n+-----------------------------+\n \nOracle mode version from MariaDB 10.3.6:\n \nSELECT RTRIM(\'\'),RTRIM_ORACLE(\'\');\n+-----------+------------------+\n| RTRIM(\'\') | RTRIM_ORACLE(\'\') |\n+-----------+------------------+\n| | NULL |\n+-----------+------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/rtrim/','','https://mariadb.com/kb/en/library/rtrim/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (627,37,'SOUNDEX','Syntax\n------ \nSOUNDEX(str)\n \nDescription\n----------- \nReturns a soundex string from str. Two strings that sound\nalmost the\nsame should have identical soundex strings. A standard\nsoundex string is four\ncharacters long, but the SOUNDEX() function returns an\narbitrarily long\nstring. You can use SUBSTRING() on the result to get a\nstandard soundex\nstring. All non-alphabetic characters in str are ignored.\nAll\ninternational alphabetic characters outside the A-Z range\nare treated as\nvowels.\n \nImportant: When using SOUNDEX(), you should be aware of the\nfollowing limitations:\nThis function, as currently implemented, is intended to work\nwell with\n strings that are in the English language only. Strings in\nother languages may\n not produce reliable results.\n \nExamples\n-------- \nSOUNDEX(\'Hello\');\n+------------------+\n| SOUNDEX(\'Hello\') |\n+------------------+\n| H400 |\n+------------------+\n \nSELECT SOUNDEX(\'MariaDB\');\n+--------------------+\n| SOUNDEX(\'MariaDB\') |\n+--------------------+\n| M631 |\n+--------------------+\n \nSELECT SOUNDEX(\'Knowledgebase\');\n+--------------------------+\n| SOUNDEX(\'Knowledgebase\') |\n+--------------------------+\n| K543212 |\n+--------------------------+\n \nSELECT givenname, surname FROM users WHERE\nSOUNDEX(givenname) = SOUNDEX(\"robert\");\n+-----------+---------+\n| givenname | surname |\n+-----------+---------+\n| Roberto | Castro |\n+-----------+---------+\n \n\n\nURL: https://mariadb.com/kb/en/library/soundex/','','https://mariadb.com/kb/en/library/soundex/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (628,37,'SOUNDS LIKE','Syntax\n------ \nexpr1 SOUNDS LIKE expr2\n \nDescription\n----------- \nThis is the same as SOUNDEX(expr1) = SOUNDEX(expr2).\n \nExample\n \nSELECT givenname, surname FROM users WHERE givenname SOUNDS\nLIKE \"robert\";\n \n+-----------+---------+\n| givenname | surname |\n+-----------+---------+\n| Roberto | Castro |\n+-----------+---------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/sounds-like/','','https://mariadb.com/kb/en/library/sounds-like/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (629,37,'SPACE','Syntax\n------ \nSPACE(N)\n \nDescription\n----------- \nReturns a string consisting of N space characters. If N is\nNULL, returns NULL.\n \nExamples\n-------- \nSELECT QUOTE(SPACE(6));\n+-----------------+\n| QUOTE(SPACE(6)) |\n+-----------------+\n| \' \' |\n+-----------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/space/','','https://mariadb.com/kb/en/library/space/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (630,37,'STRCMP','Syntax\n------ \nSTRCMP(expr1,expr2)\n \nDescription\n----------- \nSTRCMP() returns 0 if the strings are the same, -1 if the\nfirst\nargument is smaller than the second according to the current\nsort order,\nand 1 otherwise.\n \nExamples\n-------- \nSELECT STRCMP(\'text\', \'text2\');\n+-------------------------+\n| STRCMP(\'text\', \'text2\') |\n+-------------------------+\n| -1 |\n+-------------------------+\n \nSELECT STRCMP(\'text2\', \'text\');\n+-------------------------+\n| STRCMP(\'text2\', \'text\') |\n+-------------------------+\n| 1 |\n+-------------------------+\n \nSELECT STRCMP(\'text\', \'text\');\n+------------------------+\n| STRCMP(\'text\', \'text\') |\n+------------------------+\n| 0 |\n+------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/strcmp/','','https://mariadb.com/kb/en/library/strcmp/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (631,37,'SUBSTR','Description\n----------- \nSUBSTR() is a synonym for SUBSTRING().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/substr/','','https://mariadb.com/kb/en/library/substr/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (632,37,'SUBSTRING','Syntax\n------ \nSUBSTRING(str,pos), \nSUBSTRING(str FROM pos), \nSUBSTRING(str,pos,len),\nSUBSTRING(str FROM pos FOR len)\n \nSUBSTR(str,pos), \nSUBSTR(str FROM pos), \nSUBSTR(str,pos,len),\nSUBSTR(str FROM pos FOR len)\n \nDescription\n----------- \nThe forms without a len argument return a substring from\nstring str starting at position pos.\n \nThe forms with a len argument return a substring len\ncharacters long from string str, starting at position pos.\n \nThe forms that use FROM are standard SQL syntax.\n \nIt is also possible to use a negative value for pos. In this\ncase, the beginning of the substring is pos characters from\nthe end of the string, rather than the beginning. A negative\nvalue may be used for pos in any of the forms of this\nfunction.\n \nBy default, the position of the first character in the\nstring from which the substring is to be extracted is\nreckoned as 1. For Oracle-compatibility, from MariaDB\n10.3.3, when sql_mode is set to \'oracle\', position zero is\ntreated as position 1 (although the first character is still\nreckoned as 1).\n \nIf any argument is NULL, returns NULL.\n \nExamples\n-------- \nSELECT SUBSTRING(\'Knowledgebase\',5);\n+------------------------------+\n| SUBSTRING(\'Knowledgebase\',5) |\n+------------------------------+\n| ledgebase |\n+------------------------------+\n \nSELECT SUBSTRING(\'MariaDB\' FROM 6);\n+-----------------------------+\n| SUBSTRING(\'MariaDB\' FROM 6) |\n+-----------------------------+\n| DB |\n+-----------------------------+\n \nSELECT SUBSTRING(\'Knowledgebase\',3,7);\n+--------------------------------+\n| SUBSTRING(\'Knowledgebase\',3,7) |\n+--------------------------------+\n| owledge |\n+--------------------------------+\n \nSELECT SUBSTRING(\'Knowledgebase\', -4);\n+--------------------------------+\n| SUBSTRING(\'Knowledgebase\', -4) |\n+--------------------------------+\n| base |\n+--------------------------------+\n \nSELECT SUBSTRING(\'Knowledgebase\', -8, 4);\n+-----------------------------------+\n| SUBSTRING(\'Knowledgebase\', -8, 4) |\n+-----------------------------------+\n| edge |\n+-----------------------------------+\n \nSELECT SUBSTRING(\'Knowledgebase\' FROM -8 FOR 4);\n+------------------------------------------+\n| SUBSTRING(\'Knowledgebase\' FROM -8 FOR 4) |\n+------------------------------------------+\n| edge |\n+------------------------------------------+\n \nOracle mode from MariaDB 10.3.3:\n \nSELECT SUBSTR(\'abc\',0,3);\n+-------------------+\n| SUBSTR(\'abc\',0,3) |\n+-------------------+\n| |\n+-------------------+\n \nSELECT SUBSTR(\'abc\',1,2);\n+-------------------+\n| SUBSTR(\'abc\',1,2) |\n+-------------------+\n| ab |\n+-------------------+\n \nSET sql_mode=\'oracle\';\n \nSELECT SUBSTR(\'abc\',0,3);\n+-------------------+\n| SUBSTR(\'abc\',0,3) |\n+-------------------+\n| abc |\n+-------------------+\n \nSELECT SUBSTR(\'abc\',1,2);\n+-------------------+\n| SUBSTR(\'abc\',1,2) |\n+-------------------+\n| ab |\n+-------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/substring/','','https://mariadb.com/kb/en/library/substring/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (633,37,'SUBSTRING_INDEX','Syntax\n------ \nSUBSTRING_INDEX(str,delim,count)\n \nDescription\n----------- \nReturns the substring from string str before count\noccurrences of the\ndelimiter delim. If count is positive, everything to the\nleft\nof the final delimiter (counting from the left) is returned.\nIf count\nis negative, everything to the right of the final delimiter\n(counting from the\nright) is returned. SUBSTRING_INDEX() performs a\ncase-sensitive match when\nsearching for delim.\n \nIf any argument is NULL, returns NULL.\n \nExamples\n-------- \nSELECT SUBSTRING_INDEX(\'www.mariadb.org\', \'.\', 2);\n+--------------------------------------------+\n| SUBSTRING_INDEX(\'www.mariadb.org\', \'.\', 2) |\n+--------------------------------------------+\n| www.mariadb |\n+--------------------------------------------+\n \nSELECT SUBSTRING_INDEX(\'www.mariadb.org\', \'.\', -2);\n+---------------------------------------------+\n| SUBSTRING_INDEX(\'www.mariadb.org\', \'.\', -2) |\n+---------------------------------------------+\n| mariadb.org |\n+---------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/substring_index/','','https://mariadb.com/kb/en/library/substring_index/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (634,37,'TO_BASE64','The TO_BASE64() function was introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nTO_BASE64(str)\n \nDescription\n----------- \nConverts the string argument str to its base-64 encoded\nform, returning the result as a character string in the\nconnection character set and collation.\n \nThe argument str will be converted to string first if it is\nnot a string. A NULL argument will return a NULL result.\n \nThe reverse function, FROM_BASE64(), decodes an encoded\nbase-64 string.\n \nThere are a numerous different methods to base-64 encode a\nstring. The following are used by MariaDB and MySQL:\nAlphabet value 64 is encoded as \'+\'.\nAlphabet value 63 is encoded as \'/\'.\nEncoding output is made up of groups of four printable\ncharacters, with each three bytes of data encoded using four\ncharacters. If the final group is not complete, it is padded\nwith \'=\' characters to make up a length of four.\nTo divide long output, a newline is added after every 76\ncharacters.\nDecoding will recognize and ignore newlines, carriage\nreturns, tabs, and spaces. \n \nExamples\n-------- \nSELECT TO_BASE64(\'Maria\');\n+--------------------+\n| TO_BASE64(\'Maria\') |\n+--------------------+\n| TWFyaWE= |\n+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/to_base64/','','https://mariadb.com/kb/en/library/to_base64/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (635,37,'TRIM','Syntax\n------ \nTRIM([{BOTH | LEADING | TRAILING} [remstr] FROM] str),\nTRIM([remstr FROM] str)\n \nDescription\n----------- \nReturns the string str with all remstr prefixes or suffixes\nremoved. If none of the specifiers BOTH, LEADING, or\nTRAILING is given, BOTH is assumed. remstr is optional and,\nif not specified, spaces are removed.\n \nReturns NULL if given a NULL argument. If the result is\nempty, returns either an empty string, or, from MariaDB\n10.3.6 with SQL_MODE=Oracle, NULL.\n \nThe Oracle mode version of the function can be accessed\noutside of Oracle mode by using TRIM_ORACLE as the function\nname.\n \nExamples\n-------- \nSELECT TRIM(\' bar \')\\G\n*************************** 1. row\n***************************\nTRIM(\' bar \'): bar\n \nSELECT TRIM(LEADING \'x\' FROM \'xxxbarxxx\')\\G\n*************************** 1. row\n***************************\nTRIM(LEADING \'x\' FROM \'xxxbarxxx\'): barxxx\n \nSELECT TRIM(BOTH \'x\' FROM \'xxxbarxxx\')\\G\n*************************** 1. row\n***************************\nTRIM(BOTH \'x\' FROM \'xxxbarxxx\'): bar\n \nSELECT TRIM(TRAILING \'xyz\' FROM \'barxxyz\')\\G\n*************************** 1. row\n***************************\nTRIM(TRAILING \'xyz\' FROM \'barxxyz\'): barx\n \nOracle mode version from MariaDB 10.3.6:\n \nSELECT TRIM(\'\'),TRIM_ORACLE(\'\');\n+----------+-----------------+\n| TRIM(\'\') | TRIM_ORACLE(\'\') |\n+----------+-----------------+\n| | NULL |\n+----------+-----------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/trim/','','https://mariadb.com/kb/en/library/trim/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (636,37,'UCASE','Syntax\n------ \nUCASE(str)\n \nDescription\n----------- \nUCASE() is a synonym for UPPER().\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/ucase/','','https://mariadb.com/kb/en/library/ucase/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (637,37,'UNHEX','Syntax\n------ \nUNHEX(str)\n \nDescription\n----------- \nPerforms the inverse operation of HEX(str). That is, it\ninterprets\neach pair of hexadecimal digits in the argument as a number\nand\nconverts it to the character represented by the number. The\nresulting\ncharacters are returned as a binary string.\n \nIf str is NULL, UNHEX() returns NULL.\n \nExamples\n-------- \nSELECT HEX(\'MariaDB\');\n+----------------+\n| HEX(\'MariaDB\') |\n+----------------+\n| 4D617269614442 |\n+----------------+\n \nSELECT UNHEX(\'4D617269614442\');\n+-------------------------+\n| UNHEX(\'4D617269614442\') |\n+-------------------------+\n| MariaDB |\n+-------------------------+\n \nSELECT 0x4D617269614442;\n \n+------------------+\n| 0x4D617269614442 |\n+------------------+\n| MariaDB |\n+------------------+\n \nSELECT UNHEX(HEX(\'string\'));\n+----------------------+\n| UNHEX(HEX(\'string\')) |\n+----------------------+\n| string |\n+----------------------+\n \nSELECT HEX(UNHEX(\'1267\'));\n+--------------------+\n| HEX(UNHEX(\'1267\')) |\n+--------------------+\n| 1267 |\n+--------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/unhex/','','https://mariadb.com/kb/en/library/unhex/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (638,37,'UPDATEXML','Syntax\n------ \nUpdateXML(xml_target, xpath_expr, new_xml)\n \nDescription\n----------- \nThis function replaces a single portion of a given fragment\nof XML markup\nxml_target with a new XML fragment new_xml, and then returns\nthe\nchanged XML. The portion of xml_target that is replaced\nmatches an XPath\nexpression xpath_expr supplied by the user. If no expression\nmatching\nxpath_expr is found, or if multiple matches are found, the\nfunction returns\nthe original xml_target XML fragment. All three arguments\nshould be\nstrings.\n \nExamples\n-------- \nSELECT\n UpdateXML(\'ccc\', \'/a\', \'fff\') AS val1,\n UpdateXML(\'ccc\', \'/b\', \'fff\') AS val2,\n UpdateXML(\'ccc\', \'//b\', \'fff\') AS val3,\n UpdateXML(\'ccc\', \'/a/d\', \'fff\') AS val4,\n UpdateXML(\'ccc\', \'/a/d\', \'fff\') AS val5\n \\G\n*************************** 1. row\n***************************\nval1: fff\nval2: ccc\nval3: fff\nval4: cccfff\nval5: ccc\n1 row in set (0.00 sec)\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/updatexml/','','https://mariadb.com/kb/en/library/updatexml/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (639,37,'UPPER','Syntax\n------ \nUPPER(str)\n \nDescription\n----------- \nReturns the string str with all characters changed to\nuppercase\naccording to the current character set mapping. The default\nis latin1\n(cp1252 West European).\n \nSELECT UPPER(surname), givenname FROM users ORDER BY\nsurname;\n \n+----------------+------------+\n| UPPER(surname) | givenname |\n+----------------+------------+\n| ABEL | Jacinto |\n| CASTRO | Robert |\n| COSTA | Phestos |\n| MOSCHELLA | Hippolytos |\n+----------------+------------+\n \nUPPER() is ineffective when applied to binary strings\n(BINARY,\nVARBINARY, BLOB). The description of \nLOWER() shows how to\nperform lettercase conversion of binary strings.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/upper/','','https://mariadb.com/kb/en/library/upper/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (640,37,'WEIGHT_STRING','The WEIGHT_STRING function was introduced in MariaDB 10.0.5.\n \nSyntax\n------ \nWEIGHT_STRING(str [AS {CHAR|BINARY}(N)] [LEVEL levels]\n[flags])\n levels: N [ASC|DESC|REVERSE] [, N [ASC|DESC|REVERSE]] ... \n \nDescription\n----------- \nReturns a binary string representing the string\'s sorting\nand comparison value. A string with a lower result means\nthat for sorting purposes the string appears before a string\nwith a higher result.\n \nWEIGHT_STRING() is particularly useful when adding new\ncollations, for testing purposes.\n \nIf str is a non-binary string (CHAR, VARCHAR or TEXT),\nWEIGHT_STRING returns the string\'s collation weight. If str\nis a binary string (BINARY, VARBINARY or BLOB), the return\nvalue is simply the input value, since the weight for each\nbyte in a binary string is the byte value.\n \nWEIGHT_STRING() returns NULL if given a NULL input. \n \nThe optional AS clause permits casting the input string to a\nbinary or non-binary string, as well as to a particular\nlength.\n \nAS BINARY(N) measures the length in bytes rather than\ncharacters, and right pads with 0x00 bytes to the desired\nlength. \n \nAS CHAR(N) measures the length in characters, and right pads\nwith spaces to the desired length.\n \nN has a minimum value of 1, and if it is less than the\nlength of the input string, the string is truncated without\nwarning.\n \nThe optional LEVEL clause specifies that the return value\nshould contain weights for specific collation levels. The\nlevels specifier can either be a single integer, a\ncomma-separated list of integers, or a range of integers\nseparated by a dash (whitespace is ignored). Integers can\nrange from 1 to a maximum of 6, dependent on the collation,\nand need to be listed in ascending order.\n \nIf the LEVEL clause is no provided, a default of 1 to the\nmaximum for the collation is assumed.\n \nIf the LEVEL is specified without using a range, an optional\nmodifier is permitted.\n \nASC, the default, returns the weights without any\nmodification.\n \nDESC returns bitwise-inverted weights.\n \nREVERSE returns the weights in reverse order.\n \nExamples\n-------- \nThe examples below use the HEX() function to represent\nnon-printable results in hexadecimal format.\n \nSELECT HEX(WEIGHT_STRING(\'x\'));\n+-------------------------+\n| HEX(WEIGHT_STRING(\'x\')) |\n+-------------------------+\n| 0058 |\n+-------------------------+\n \nSELECT HEX(WEIGHT_STRING(\'x\' AS BINARY(4)));\n+--------------------------------------+\n| HEX(WEIGHT_STRING(\'x\' AS BINARY(4))) |\n+--------------------------------------+\n| 78000000 |\n+--------------------------------------+\n \nSELECT HEX(WEIGHT_STRING(\'x\' AS CHAR(4)));\n+------------------------------------+\n| HEX(WEIGHT_STRING(\'x\' AS CHAR(4))) |\n+------------------------------------+\n| 0058002000200020 |\n+------------------------------------+\n \nSELECT HEX(WEIGHT_STRING(0xaa22ee LEVEL 1));\n+--------------------------------------+\n| HEX(WEIGHT_STRING(0xaa22ee LEVEL 1)) |\n+--------------------------------------+\n| AA22EE |\n+--------------------------------------+\n \nSELECT HEX(WEIGHT_STRING(0xaa22ee LEVEL 1 DESC));\n+-------------------------------------------+\n| HEX(WEIGHT_STRING(0xaa22ee LEVEL 1 DESC)) |\n+-------------------------------------------+\n| 55DD11 |\n+-------------------------------------------+\n \nSELECT HEX(WEIGHT_STRING(0xaa22ee LEVEL 1 REVERSE));\n+----------------------------------------------+\n| HEX(WEIGHT_STRING(0xaa22ee LEVEL 1 REVERSE)) |\n+----------------------------------------------+\n| EE22AA |\n+----------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/weight_string/','','https://mariadb.com/kb/en/library/weight_string/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (641,39,'ALTER DATABASE','Modifies a database, changing its overall characteristics.\n \nSyntax\n------ \nALTER {DATABASE | SCHEMA} [db_name]\n alter_specification ...\nALTER {DATABASE | SCHEMA} db_name\n UPGRADE DATA DIRECTORY NAME\n \nalter_specification:\n [DEFAULT] CHARACTER SET [=] charset_name\n | [DEFAULT] COLLATE [=] collation_name\n \nDescription\n----------- \nALTER DATABASE enables you to change the overall\ncharacteristics of a\ndatabase. These characteristics are stored in the db.opt\nfile in the\ndatabase directory. To use ALTER DATABASE, you need the\nALTER\nprivilege on the database. ALTER SCHEMA is a synonym for\nALTER\nDATABASE.\n \nThe CHARACTER SET clause changes the default database\ncharacter set.\nThe COLLATE clause changes the default database collation.\nSee Character Sets and Collations for more.\n \nYou can see what character sets and collations are available\nusing,\nrespectively, the SHOW CHARACTER SET and SHOW COLLATION\nstatements.\n \nChanging the default character set/collation of a database\ndoes not change the character set/collation of any stored\nprocedures or stored functions that were previously created,\nand relied on the defaults. These need to be dropped and\nrecreated in order to apply the character set/collation\nchanges.\n \nThe database name can be omitted from the first syntax, in\nwhich case\nthe statement applies to the default database.\n \nThe syntax that includes the UPGRADE DATA DIRECTORY NAME\nclause was\nadded in MySQL 5.1.23. It updates the name of the directory\nassociated\nwith the database to use the encoding implemented in MySQL\n5.1 for\nmapping database names to database directory names (see\nIdentifier to File Name Mapping). This\nclause is for use under these conditions:\nIt is intended when upgrading MySQL to 5.1 or later from\nolder versions.\nIt is intended to update a database directory name to the\ncurrent encoding format if the name contains special\ncharacters that need encoding.\nThe statement is used by mysqlcheck (as invoked by\nmysql_upgrade).\n \nFor example,if a database in MySQL 5.0 has a name of a-b-c,\nthe name\ncontains instance of the `-\' character. In 5.0, the\ndatabase directory\nis also named a-b-c, which is not necessarily safe for all\nfile\nsystems. In MySQL 5.1 and up, the same database name is\nencoded as\na@002db@002dc to produce a file system-neutral directory\nname.\n \nWhen a MySQL installation is upgraded to MySQL 5.1 or later\nfrom an\nolder version,the server displays a name such as a-b-c\n(which is in\nthe old format) as #mysql50#a-b-c, and you must refer to the\nname\nusing the #mysql50# prefix. Use UPGRADE DATA DIRECTORY NAME\nin this\ncase to explicitly tell the server to re-encode the database\ndirectory\nname to the current encoding format:\n \nALTER DATABASE `#mysql50#a-b-c` UPGRADE DATA DIRECTORY NAME;\n \nAfter executing this statement, you can refer to the\ndatabase as a-b-c\nwithout the special #mysql50# prefix.\n \nExamples\n-------- \nALTER DATABASE test CHARACTER SET = \'utf8\' COLLATE =\n\'utf8_bin\';\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-database/','','https://mariadb.com/kb/en/library/alter-database/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (642,39,'ALTER EVENT','Modifies one or more characteristics of an existing event.\n \nSyntax\n------ \nALTER\n [DEFINER = { user | CURRENT_USER }]\n EVENT event_name\n [ON SCHEDULE schedule]\n [ON COMPLETION [NOT] PRESERVE]\n [RENAME TO new_event_name]\n [ENABLE | DISABLE | DISABLE ON SLAVE]\n [COMMENT \'comment\']\n [DO sql_statement]\n \nDescription\n----------- \nThe ALTER EVENT statement is used to change one or more of\nthe\ncharacteristics of an existing event without the need to\ndrop and recreate it.\nThe syntax for each of the DEFINER, ON SCHEDULE, ON\nCOMPLETION,\nCOMMENT, ENABLE / DISABLE, and DO clauses is exactly the\nsame as when used with CREATE EVENT.\n \nThis statement requires the EVENT privilege.\nWhen a user executes a successful ALTER EVENT statement,\nthat user becomes\nthe definer for the affected event.\n \n(In MySQL 5.1.11 and earlier, an event could be altered only\nby its definer, or\nby a user having the SUPER privilege.)\n \nALTER EVENT works only with an existing event:\n \nALTER EVENT no_such_event ON SCHEDULE EVERY \'2:3\'\nDAY_HOUR;\nERROR 1539 (HY000): Unknown event \'no_such_event\'\n \nExamples\n-------- \nALTER EVENT myevent \n ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 2 HOUR \n DO \n UPDATE myschema.mytable SET mycol = mycol + 1;\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-event/','','https://mariadb.com/kb/en/library/alter-event/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (643,39,'ALTER FUNCTION','Syntax\n------ \nALTER FUNCTION func_name [characteristic ...]\n \ncharacteristic:\n { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL\nDATA }\n | SQL SECURITY { DEFINER | INVOKER }\n | COMMENT \'string\'\n \nDescription\n----------- \nThis statement can be used to change the characteristics of\na stored\nfunction. More than one change may be specified in an ALTER\nFUNCTION\nstatement. However, you cannot change the parameters or body\nof a\nstored function using this statement; to make such changes,\nyou must\ndrop and re-create the function using DROP FUNCTION and\nCREATE FUNCTION.\n \nYou must have the ALTER ROUTINE privilege for the function.\n(That\nprivilege is granted automatically to the function creator.)\nIf binary\nlogging is enabled, the ALTER FUNCTION statement might also\nrequire\nthe SUPER privilege, as described in Binary Logging of\nStored Routines.\n \nExample\n \nALTER FUNCTION hello SQL SECURITY INVOKER;\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-function/','','https://mariadb.com/kb/en/library/alter-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (644,39,'ALTER LOGFILE GROUP','Syntax\n------ \nALTER LOGFILE GROUP logfile_group\n ADD UNDOFILE \'file_name\'\n [INITIAL_SIZE [=] size]\n [WAIT]\n ENGINE [=] engine_name\n \nThe ALTER LOGFILE GROUP statement is not supported by\nMariaDB. It was originally inherited from MySQL NDB Cluster.\nSee MDEV-19295 for more information.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/alter-logfile-group/','','https://mariadb.com/kb/en/library/alter-logfile-group/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (645,39,'ALTER PROCEDURE','Syntax\n------ \nALTER PROCEDURE proc_name [characteristic ...]\n \ncharacteristic:\n { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL\nDATA }\n | SQL SECURITY { DEFINER | INVOKER }\n | COMMENT \'string\'\n \nDescription\n----------- \nThis statement can be used to change the characteristics of\na stored\nprocedure. More than one change may be specified in an ALTER\nPROCEDURE\nstatement. However, you cannot change the parameters or body\nof a\nstored procedure using this statement. To make such changes,\nyou must\ndrop and re-create the procedure using either CREATE OR\nREPLACE PROCEDURE (since MariaDB 10.1.3) or DROP PROCEDURE\nand CREATE PROCEDURE (MariaDB 10.1.2 and before).\n \nYou must have the ALTER ROUTINE privilege for the procedure.\nBy default, that privilege is granted automatically to the\nprocedure creator. See Stored Routine Privileges.\n \nExample\n \nALTER PROCEDURE simpleproc SQL SECURITY INVOKER;\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-procedure/','','https://mariadb.com/kb/en/library/alter-procedure/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (646,39,'ALTER SERVER','Syntax\n------ \nALTER SERVER server_name\n OPTIONS (option [, option] ...)\n \nDescription\n----------- \nAlters the server information for server_name, adjusting the\nspecified\noptions as per the CREATE SERVER command. The corresponding\nfields in the mysql.servers table are updated accordingly.\nThis statement requires the SUPER privilege.\n \nExamples\n-------- \nALTER SERVER s OPTIONS (USER \'sally\');\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-server/','','https://mariadb.com/kb/en/library/alter-server/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (647,39,'ALTER TABLE','Syntax\n------ \nALTER [ONLINE] [IGNORE] TABLE tbl_name\n [WAIT n | NOWAIT]\n alter_specification [, alter_specification] ...\n \nalter_specification:\n table_option ...\n | ADD [COLUMN] [IF NOT EXISTS] col_name column_definition\n [FIRST | AFTER col_name ]\n | ADD [COLUMN] [IF NOT EXISTS] (col_name\ncolumn_definition,...)\n | ADD {INDEX|KEY} [IF NOT EXISTS] [index_name]\n [index_type] (index_col_name,...) [index_option] ...\n | ADD [CONSTRAINT [symbol]] PRIMARY KEY\n [index_type] (index_col_name,...) [index_option] ...\n | ADD [CONSTRAINT [symbol]]\n UNIQUE [INDEX|KEY] [index_name]\n [index_type] (index_col_name,...) [index_option] ...\n | ADD FULLTEXT [INDEX|KEY] [index_name]\n (index_col_name,...) [index_option] ...\n | ADD SPATIAL [INDEX|KEY] [index_name]\n (index_col_name,...) [index_option] ...\n | ADD [CONSTRAINT [symbol]]\n FOREIGN KEY [IF NOT EXISTS] [index_name]\n(index_col_name,...)\n reference_definition\n | ADD PERIOD FOR SYSTEM_TIME (start_column_name,\nend_column_name)\n | ALTER [COLUMN] col_name SET DEFAULT literal\n| (expression)\n | ALTER [COLUMN] col_name DROP DEFAULT\n | CHANGE [COLUMN] [IF EXISTS] old_col_name new_col_name\ncolumn_definition\n [FIRST|AFTER col_name]\n | MODIFY [COLUMN] [IF EXISTS] col_name column_definition\n [FIRST | AFTER col_name]\n | DROP [COLUMN] [IF EXISTS] col_name [RESTRICT|CASCADE]\n | DROP PRIMARY KEY\n | DROP {INDEX|KEY} [IF EXISTS] index_name\n | DROP FOREIGN KEY [IF EXISTS] fk_symbol\n | DROP CONSTRAINT [IF EXISTS] constraint_name\n | DISABLE KEYS\n | ENABLE KEYS\n | RENAME [TO] new_tbl_name\n | ORDER BY col_name [, col_name] ...\n | CONVERT TO CHARACTER SET charset_name [COLLATE\ncollation_name]\n | [DEFAULT] CHARACTER SET [=] charset_name\n | [DEFAULT] COLLATE [=] collation_name\n | DISCARD TABLESPACE\n | IMPORT TABLESPACE\n | ALGORITHM [=] {DEFAULT|INPLACE|COPY|NOCOPY|INSTANT}\n | LOCK [=] {DEFAULT|NONE|SHARED|EXCLUSIVE}\n | FORCE\n | partition_options\n | ADD PARTITION (partition_definition)\n | DROP PARTITION partition_names\n | COALESCE PARTITION number\n | REORGANIZE PARTITION [partition_names INTO\n(partition_definitions)]\n | ANALYZE PARTITION partition_names\n | CHECK PARTITION partition_names\n | OPTIMIZE PARTITION partition_names\n | REBUILD PARTITION partition_names\n | REPAIR PARTITION partition_names\n | EXCHANGE PARTITION partition_name WITH TABLE tbl_name\n | REMOVE PARTITIONING\n | ADD SYSTEM VERSIONING\n | DROP SYSTEM VERSIONING\n \nindex_col_name:\n col_name [(length)] [ASC | DESC]\n \nindex_type:\n USING {BTREE | HASH | RTREE}\n \nindex_option:\n KEY_BLOCK_SIZE [=] value\n | index_type\n | WITH PARSER parser_name\n | COMMENT \'string\'\n | CLUSTERING={YES| NO}\n \ntable_options:\n table_option [[,] table_option] ...\nIn MariaDB 10.0.2 and later, IF EXISTS and IF NOT EXISTS\nclauses have been added for the following:\n \nADD COLUMN [IF NOT EXISTS]\nADD INDEX [IF NOT EXISTS]\nADD FOREIGN KEY [IF NOT EXISTS]\nADD PARTITION [IF NOT EXISTS]\nCREATE INDEX [IF NOT EXISTS]\n \nDROP COLUMN [IF EXISTS]\nDROP INDEX [IF EXISTS]\nDROP FOREIGN KEY [IF EXISTS]\nDROP PARTITION [IF EXISTS]\nCHANGE COLUMN [IF EXISTS]\nMODIFY COLUMN [IF EXISTS]\nDROP INDEX [IF EXISTS]\nWhen IF EXISTS and IF NOT EXISTS are used in clauses,\nqueries will not\nreport errors when the condition is triggered for that\nclause. A warning with\nthe same message text will be issued and the ALTER will move\non to the next\nclause in the statement (or end if finished).\n \nThis was done in MDEV-318.\n \nDescription\n----------- \nALTER TABLE enables you to change the structure of an\nexisting table.\nFor example, you can add or delete columns, create or\ndestroy indexes,\nchange the type of existing columns, or rename columns or\nthe table\nitself. You can also change the comment for the table and\nthe storage engine of the\ntable.\n \nIf another connection is using the table, a metadata lock is\nactive, and this statement will wait until the lock is\nreleased. This is also true for non-transactional tables.\n \nWhen adding a UNIQUE index on a column (or a set of columns)\nwhich have duplicated values, an error will be produced and\nthe statement will be stopped. To suppress the error and\nforce the creation of UNIQUE indexes, discarding duplicates,\nthe IGNORE option can be specified. This can be useful if a\ncolumn (or a set of columns) should be UNIQUE but it\ncontains duplicate values; however, this technique provides\nno control on which rows are preserved and which are\ndeleted. Also, note that IGNORE is accepted but ignored in\nALTER TABLE ... EXCHANGE PARTITION statements.\n \nThis statement can also be used to rename a table. For\ndetails see RENAME TABLE.\n \nWhen an index is created, the storage engine may use a\nconfigurable buffer in the process. Incrementing the buffer\nspeeds up the index creation. Aria and MyISAM allocate a\nbuffer whose size is defined by aria_sort_buffer_size or\nmyisam_sort_buffer_size, also used for REPAIR TABLE.\nInnoDB/XtraDB allocates three buffers whose size is defined\nby innodb_sort_buffer_size.\n \nPrivileges\n \nExecuting the ALTER TABLE statement generally requires at\nleast the ALTER privilege for the table or the database..\n \nIf you are renaming a table, then it also requires the DROP,\nCREATE and INSERT privileges for the table or the database\nas well.\n \nOnline DDL\n \nIn MariaDB 10.0 and later, online DDL is supported with the\nALGORITHM and LOCK clauses.\n \nSee InnoDB Online DDL Overview for more information on\nonline DDL with InnoDB.\n \nALTER ONLINE TABLE\n \nALTER ONLINE TABLE has also worked for partitioned tables\nsince MariaDB 10.0.11.\n \nOnline ALTER TABLE is available by executing the following:\n \nALTER ONLINE TABLE ...;\n \nThis statement has the following semantics:\n \nIn MariaDB 10.0.12 and later, this statement is equivalent\nto the following:\n \nALTER TABLE ... LOCK=NONE;\n \nSee the LOCK alter specification for more information.\n \nIn MariaDB 10.0.11, this statement is equivalent to the\nfollowing:\n \nALTER TABLE ... ALGORITHM=INPLACE;\n \nSee the ALGORITHM alter specification for more information.\n \nMariaDB until 10.0.10\n \nIn MariaDB 10.0.10 and before, this statement ensures that\nthe ALTER TABLE statement does not make a copy of the table.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \nColumn Definitions\n \nSee CREATE TABLE: Column Definitions for information about\ncolumn definitions.\n \nIndex Definitions\n \nSee CREATE TABLE: Index Definitions for information about\nindex definitions.\n \nThe CREATE INDEX and DROP INDEX statements can also be used\nto add or remove an index.\n \nCharacter Sets and Collations\n \nCONVERT TO CHARACTER SET charset_name [COLLATE\ncollation_name]\n[DEFAULT] CHARACTER SET [=] charset_name\n[DEFAULT] COLLATE [=] collation_name\nSee Setting Character Sets and Collations for details on\nsetting the character sets and collations.\n \nAlter Specifications\n \nTable Options\n \nSee CREATE TABLE: Table Options for information about table\noptions.\n \nADD COLUMN\n \n... ADD COLUMN [IF NOT EXISTS] (col_name\ncolumn_definition,...)\nAdds a column to the table. The syntax is the same as in\nCREATE TABLE.\nIf you are using IF NOT_EXISTS the column will not be added\nif it was not there already. This is very useful when doing\nscripts to modify tables.\n \nThe FIRST and AFTER clauses affect the physical order of\ncolumns in the datafile. Use FIRST to add a column in the\nfirst (leftmost) position, or AFTER followed by a column\nname to add the new column in any other position. Note that,\nnowadays, the physical position of a column is usually\nirrelevant.\n \nSee also Instant ADD COLUMN for InnoDB.\n \nDROP COLUMN\n \n... DROP COLUMN [IF EXISTS] col_name [CASCADE|RESTRICT]\nDrops the column from the table.\nIf you are using IF EXISTS you will not get an error if the\ncolumn didn\'t exist.\nIf the column is part of any index, the column will be\ndropped from them, except if you add a new column with\nidentical name at the same time. The index will be dropped\nif all columns from the index were dropped.\nIf the column was used in a view or trigger, you will get an\nerror next time the view or trigger is accessed.\n \nDropping a column that is part of a multi-column UNIQUE\nconstraint is not permitted. For example:\n \nCREATE TABLE a (\n a int,\n b int,\n primary key (a,b)\n);\n \nALTER TABLE x DROP COLUMN a;\n[42000][1072] Key column \'A\' doesn\'t exist in table\n \nThe reason is that dropping column a would result in the new\nconstraint that all values in column b be unique. In order\nto drop the column, an explicit DROP PRIMARY KEY and ADD\nPRIMARY KEY would be required. Up until MariaDB 10.2.7, the\ncolumn was dropped and the additional constraint applied,\nresulting in the following structure:\n \nALTER TABLE x DROP COLUMN a;\nQuery OK, 0 rows affected (0.46 sec)\n \nDESC x;\n+-------+---------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+-------+\n| b | int(11) | NO | PRI | NULL | |\n+-------+---------+------+-----+---------+-------+\n \nMariaDB 10.4.0 supports instant DROP COLUMN. DROP COLUMN of\nan indexed column would imply DROP INDEX (and in the case of\na non-UNIQUE multi-column index, possibly ADD INDEX). These\nwill not be allowed with ALGORITHM=INSTANT, but unlike\nbefore, they can be allowed with ALGORITHM=NOCOPY\n \nRESTRICT and CASCADE are allowed to make porting from other\ndatabase systems easier. In MariaDB, they do nothing.\n \nMODIFY COLUMN\n \nAllows you to modify the type of a column. The column will\nbe at the same place as the original column and all indexes\non the column will be kept. Note that when modifying column,\nyou should specify all attributes for the new column.\n \nCREATE TABLE t1 (a INT UNSIGNED AUTO_INCREMENT, PRIMARY\nKEY((a));\nALTER TABLE t1 MODIFY a BIGINT UNSIGNED AUTO_INCREMENT;\n \nCHANGE COLUMN\n \nWorks like MODIFY COLUMN except that you can also change the\nname of the column. The column will be at the same place as\nthe original column and all index on the column will be\nkept.\n \nCREATE TABLE t1 (a INT UNSIGNED AUTO_INCREMENT, PRIMARY\nKEY(a));\nALTER TABLE t1 CHANGE a b BIGINT UNSIGNED AUTO_INCREMENT;\n \nALTER COLUMN\n \nThis lets you change column options.\n \nCREATE TABLE t1 (a INT UNSIGNED AUTO_INCREMENT, b\nvarchar(50), PRIMARY KEY(a));\nALTER TABLE t1 ALTER b SET DEFAULT \'hello\';\n \nADD PRIMARY KEY\n \nAdd a primary key.\n \nFor PRIMARY KEY indexes, you can specify a name for the\nindex, but it is silently ignored, and the name of the index\nis always PRIMARY.\n \nSee Getting Started with Indexes: Primary Key for more\ninformation.\n \nDROP PRIMARY KEY\n \nDrop a primary key.\n \nFor PRIMARY KEY indexes, you can specify a name for the\nindex, but it is silently ignored, and the name of the index\nis always PRIMARY.\n \nSee Getting Started with Indexes: Primary Key for more\ninformation.\n \nADD FOREIGN KEY\n \nAdd a foreign key.\n \nFor FOREIGN KEY indexes, a reference definition must be\nprovided.\n \nFor FOREIGN KEY indexes, you can specify a name for the\nconstraint, using the CONSTRAINT keyword. That name will be\nused in error messages.\n \nFirst, you have to specify the name of the target (parent)\ntable and a column or a column list which must be indexed\nand whose values must match to the foreign key\'s values.\nThe MATCH clause is accepted to improve the compatibility\nwith other DBMS\'s, but has no meaning in MariaDB. The ON\nDELETE and ON UPDATE clauses specify what must be done when\na DELETE (or a REPLACE) statements attempts to delete a\nreferenced row from the parent table, and when an UPDATE\nstatement attempts to modify the referenced foreign key\ncolumns in a parent table row, respectively. The following\noptions are allowed:\nRESTRICT: The delete/update operation is not performed. The\nstatement terminates with a 1451 error (SQLSTATE \'2300\').\nNO ACTION: Synonym for RESTRICT.\nCASCADE: The delete/update operation is performed in both\ntables.\nSET NULL: The update or delete goes ahead in the parent\ntable, and the corresponding foreign key fields in the child\ntable are set to NULL. (They must not be defined as NOT NULL\nfor this to succeed).\n \nMariaDB until 5.3\nSET DEFAULT: This option is currently implemented only for\nthe PBXT storage engine, which is disabled by default and no\nlonger maintained. It sets the child table\'s foreign key\nfields to their DEFAULT values when the referenced parent\ntable key entries are updated or deleted.\n \nIf either clause is omitted, the default behavior for the\nomitted clause is RESTRICT.\n \nSee Foreign Keys for more information.\n \nDROP FOREIGN KEY\n \nDrop a foreign key.\n \nSee Foreign Keys for more information.\n \nADD INDEX\n \nAdd a plain index.\n \nPlain indexes are regular indexes that are not unique, and\nare not acting as a primary key or a foreign key. They are\nalso not the \"specialized\" FULLTEXT or SPATIAL indexes.\n \nSee Getting Started with Indexes: Plain Indexes for more\ninformation.\n \nDROP INDEX\n \nDrop a plain index.\n \nPlain indexes are regular indexes that are not unique, and\nare not acting as a primary key or a foreign key. They are\nalso not the \"specialized\" FULLTEXT or SPATIAL indexes.\n \nSee Getting Started with Indexes: Plain Indexes for more\ninformation.\n \nADD UNIQUE INDEX\n \nAdd a unique index.\n \nThe UNIQUE keyword means that the index will not accept\nduplicated values, except for NULLs. An error will raise if\nyou try to insert duplicate values in a UNIQUE index.\n \nFor UNIQUE indexes, you can specify a name for the\nconstraint, using the CONSTRAINT keyword. That name will be\nused in error messages.\n \nSee Getting Started with Indexes: Unique Index for more\ninformation.\n \nDROP UNIQUE INDEX\n \nDrop a unique index.\n \nThe UNIQUE keyword means that the index will not accept\nduplicated values, except for NULLs. An error will raise if\nyou try to insert duplicate values in a UNIQUE index.\n \nFor UNIQUE indexes, you can specify a name for the\nconstraint, using the CONSTRAINT keyword. That name will be\nused in error messages.\n \nSee Getting Started with Indexes: Unique Index for more\ninformation.\n \nADD FULLTEXT INDEX\n \nAdd a FULLTEXT index.\n \nSee Full-Text Indexes for more information.\n \nDROP FULLTEXT INDEX\n \nDrop a FULLTEXT index.\n \nSee Full-Text Indexes for more information.\n \nADD SPATIAL INDEX\n \nAdd a SPATIAL index.\n \nSee SPATIAL INDEX for more information.\n \nDROP SPATIAL INDEX\n \nDrop a SPATIAL index.\n \nSee SPATIAL INDEX for more information.\n \nENABLE/ DISABLE KEYS\n \nDISABLE KEYS will disable all non unique keys for the table\nfor storage engines that support this (at least MyISAM and\nAria). This can be used to speed up inserts into empty\ntables.\n \nENABLE KEYS will enable all disabled keys.\n \nRENAME TO\n \nRenames the table. See also RENAME TABLE.\n \nADD CONSTRAINT\n \nModifies the table adding a constraint on a particular\ncolumn or columns.\n \nMariaDB 10.2.1 introduced new ways to define a constraint.\n \nNote: Before MariaDB 10.2.1, constraint expressions were\naccepted in syntax, but ignored.\n \nALTER TABLE table_name \nADD CONSTRAINT [constraint_name] CHECK(expression);\nBefore a row is inserted or updated, all constraints are\nevaluated in the order they are defined. If any constraint\nfails, then the row will not be updated. One can use most\ndeterministic functions in a constraint, including UDF\'s.\n \nCREATE TABLE account_ledger (\n id INT PRIMARY KEY AUTO_INCREMENT,\n transaction_name VARCHAR(100),\n credit_account VARCHAR(100),\n credit_amount INT,\n debit_account VARCHAR(100),\n debit_amount INT);\n \nALTER TABLE account_ledger \nADD CONSTRAINT is_balanced \n CHECK((debit_amount + credit_amount) = 0);\n \nThe constraint_name is optional. If you don\'t provide one\nin the ALTER TABLE statement, MariaDB auto-generates a name\nfor you. This is done so that you can remove it later using\nDROP CONSTRAINT clause.\n \nYou can disable all constraint expression checks by setting\nthe variable check_constraint_checks to OFF. You may find\nthis useful when loading a table that violates some\nconstraints that you want to later find and fix in SQL.\n \nTo view constraints on a table, query\ninformation_schema.TABLE_CONSTRAINTS:\n \nSELECT CONSTRAINT_NAME, TABLE_NAME, CONSTRAINT_TYPE \nFROM information_schema.TABLE_CONSTRAINTS\nWHERE TABLE_NAME = \'account_ledger\';\n \n+-----------------+----------------+-----------------+\n| CONSTRAINT_NAME | TABLE_NAME | CONSTRAINT_TYPE |\n+-----------------+----------------+-----------------+\n| is_balanced | account_ledger | CHECK |\n+-----------------+----------------+-----------------+\n \nDROP CONSTRAINT\n \nDROP CONSTRAINT for UNIQUE and FOREIGN KEY constraints was\nintroduced in MariaDB 10.2.22 and MariaDB 10.3.13.\n \nDROP CONSTRAINT for CHECK constraints was introduced in\nMariaDB 10.2.1\n \nModifies the table, removing the given constraint.\n \nALTER TABLE table_name\nDROP CONSTRAINT constraint_name;\n \nWhen you add a constraint to a table, whether through a\nCREATE TABLE or ALTER TABLE...ADD CONSTRAINT statement, you\ncan either set a constraint_name yourself, or allow MariaDB\nto auto-generate one for you. To view constraints on a\ntable, query information_schema.TABLE_CONSTRAINTS. For\ninstance,\n \nCREATE TABLE t (\n a INT,\n b INT,\n c INT,\n CONSTRAINT CHECK(a > b),\n CONSTRAINT check_equals CHECK(a = c)); \n \nSELECT CONSTRAINT_NAME, TABLE_NAME, CONSTRAINT_TYPE \nFROM information_schema.TABLE_CONSTRAINTS\nWHERE TABLE_NAME = \'t\';\n \n+-----------------+----------------+-----------------+\n| CONSTRAINT_NAME | TABLE_NAME | CONSTRAINT_TYPE |\n+-----------------+----------------+-----------------+\n| check_equals | t | CHECK |\n| CONSTRAINT_1 | t | CHECK |\n+-----------------+----------------+-----------------+\n \nTo remove a constraint from the table, issue an ALTER\nTABLE...DROP CONSTRAINT statement. For example,\n \nALTER TABLE t DROP CONSTRAINT is_unique;\n \nADD SYSTEM VERSIONING\n \nSystem-versioned tables was added in MariaDB 10.3.4.\n \nAdd system versioning.\n \nDROP SYSTEM VERSIONING\n \nSystem-versioned tables was added in MariaDB 10.3.4.\n \nDrop system versioning.\n \nADD PERIOD FOR SYSTEM_TIME\n \nSystem-versioned tables was added in MariaDB 10.3.4.\n \nFORCE\n \nALTER TABLE ... FORCE can force MariaDB to re-build the\ntable.\n \nIn MariaDB 5.5 and before, this could only be done by\nsetting the ENGINE table option to its old value. For\nexample, for an InnoDB table, one could execute the\nfollowing:\n \nALTER TABLE tab_name ENGINE = InnoDB;\n \nIn MariaDB 10.0 and later, the FORCE option can be used\ninstead. For example, :\n \nALTER TABLE tab_name FORCE;\n \nWith InnoDB, the table rebuild will only reclaim unused\nspace (i.e. the space previously used for deleted rows) if\nthe innodb_file_per_table system variable is set to ON. If\nthe system variable is OFF, then the space will not be\nreclaimed, but it will be-re-used for new data that\'s later\nadded.\n \nEXCHANGE PARTITION\n \nALTER TABLE ... EXCHANGE PARTITION was introduced in MariaDB\n10.0.4\n \nThis is used to exchange the tablespace files between a\npartition and another table.\n \nSee copying InnoDB\'s transportable tablespaces for more\ninformation.\n \nDISCARD TABLESPACE\n \nThis is used to discard an InnoDB table\'s tablespace.\n \nSee copying I','','https://mariadb.com/kb/en/library/alter-table/'); +update help_topic set description = CONCAT(description, 'nnoDB\'s transportable tablespaces for more\ninformation.\n \nIMPORT TABLESPACE\n \nThis is used to import an InnoDB table\'s tablespace. The\ntablespace should have been copied from its original server\nafter executing FLUSH TABLES FOR EXPORT.\n \nSee copying InnoDB\'s transportable tablespaces for more\ninformation.\n \nALTER TABLE ... IMPORT only applies to InnoDB tables. Most\nother popular storage engines, such as Aria and MyISAM, will\nrecognize their data files as soon as they\'ve been placed\nin the proper directory under the datadir, and no special\nDDL is required to import them.\n \nALGORITHM\n \nIn MariaDB 5.5 and before, ALTER TABLE operations required\nmaking a temporary copy of the table, which can be slow for\nlarge tables.\n \nIn MariaDB 10.0 and later, the ALTER TABLE statement\nsupports the ALGORITHM clause. This clause is one of the\nclauses that is used to implement online DDL. ALTER TABLE\nsupports several different algorithms. An algorithm can be\nexplicitly chosen for an ALTER TABLE operation by setting\nthe ALGORITHM clause. The supported values are:\nALGORITHM=DEFAULT - This implies the default behavior for\nthe specific statement, such as if no ALGORITHM clause is\nspecified.\nALGORITHM=COPY\nALGORITHM=INPLACE\nALGORITHM=NOCOPY - This was added in MariaDB 10.3.7.\nALGORITHM=INSTANT - This was added in MariaDB 10.3.7.\n \nSee InnoDB Online DDL Overview: ALGORITHM for information on\nhow the ALGORITHM clause affects InnoDB.\n \nALGORITHM=DEFAULT\n \nThe default behavior, which occurs if ALGORITHM=DEFAULT is\nspecified, or if ALGORITHM is not specified at all, usually\nonly makes a copy if the operation doesn\'t support being\ndone in-place at all. In this case, the most efficient\navailable algorithm will usually be used.\n \nHowever, in MariaDB 10.3.6 and before, if the value of the\nold_alter_table system variable is set to ON, then the\ndefault behavior is to perform ALTER TABLE operations by\nmaking a copy of the table using the old algorithm.\n \nIn MariaDB 10.3.7 and later, the old_alter_table system\nvariable is deprecated. Instead, the alter_algorithm system\nvariable defines the default algorithm for ALTER TABLE\noperations.\n \nALGORITHM=COPY\n \nALGORITHM=COPY was introduced in MariaDB 10.0 as the name\nfor the original ALTER TABLE algorithm.\n \nWhen ALGORITHM=INPLACE is set, MariaDB essentially does the\nfollowing operations:\n \n-- Create a temporary table with the new definition\nCREATE TEMPORARY TABLE tmp_tab (\n...\n);\n \n-- Copy the data from the original table\nINSERT INTO tmp_tab\n SELECT * FROM original_tab;\n \n-- Drop the original table\nDROP TABLE original_tab;\n \n-- Rename the temporary table, so that it replaces the\noriginal one\nRENAME TABLE tmp_tab TO original_tab;\n \nThis algorithm is very inefficient, but it is generic, so it\nworks for all storage engines.\n \nIf ALGORITHM=COPY is specified, then the copy algorithm will\nbe used even if it is not necessary. This can result in a\nlengthy table copy. If multiple ALTER TABLE operations are\nrequired that each require the table to be rebuilt, then it\nis best to specify all operations in a single ALTER TABLE\nstatement, so that the table is only rebuilt once.\n \nALGORITHM=INPLACE\n \nALGORITHM=INPLACE was introduced in MariaDB 10.0.\n \nALGORITHM=COPY can be incredibly slow, because the whole\ntable has to be copied and rebuilt. ALGORITHM=INPLACE was\nintroduced as a way to avoid this by performing operations\nin-place and avoiding the table copy and rebuild, when\npossible.\n \nWhen ALGORITHM=INPLACE is set, the underlying storage engine\nuses optimizations to perform the operation while avoiding\nthe table copy and rebuild. However, INPLACE is a bit of a\nmisnomer, since some operations may still require the table\nto be rebuilt for some storage engines. Regardless, several\noperations can be performed without a full copy of the table\nfor some storage engines.\n \nA more accurate name would have been ALGORITHM=ENGINE, where\nENGINE refers to an \"engine-specific\" algorithm.\n \nIf an ALTER TABLE operation supports ALGORITHM=INPLACE, then\nit can be performed using optimizations by the underlying\nstorage engine, but it may rebuilt.\n \nSee InnoDB Online DDL Operations with ALGORITHM=INPLACE for\nmore.\n \nALGORITHM=NOCOPY\n \nALGORITHM=NOCOPY was introduced in MariaDB 10.3.7.\n \nALGORITHM=INPLACE can sometimes be surprisingly slow in\ninstances where it has to rebuild the clustered index,\nbecause when the clustered index has to be rebuilt, the\nwhole table has to be rebuilt. ALGORITHM=NOCOPY was\nintroduced as a way to avoid this. \n \nIf an ALTER TABLE operation supports ALGORITHM=NOCOPY, then\nit can be performed without rebuilding the clustered index.\n \nIf ALGORITHM=NOCOPY is specified for an ALTER TABLE\noperation that does not support ALGORITHM=NOCOPY, then an\nerror will be raised. In this case, raising an error is\npreferable, if the alternative is for the operation to\nrebuild the clustered index, and perform unexpectedly\nslowly.\n \nSee InnoDB Online DDL Operations with ALGORITHM=NOCOPY for\nmore.\n \nALGORITHM=INSTANT\n \nALGORITHM=INSTANT was introduced in MariaDB 10.3.7.\n \nALGORITHM=INPLACE can sometimes be surprisingly slow in\ninstances where it has to modify data files.\nALGORITHM=INSTANT was introduced as a way to avoid this.\n \nIf an ALTER TABLE operation supports ALGORITHM=INSTANT, then\nit can be performed without modifying any data files.\n \nIf ALGORITHM=INSTANT is specified for an ALTER TABLE\noperation that does not support ALGORITHM=INSTANT, then an\nerror will be raised. In this case, raising an error is\npreferable, if the alternative is for the operation to\nmodify data files, and perform unexpectedly slowly.\n \nSee InnoDB Online DDL Operations with ALGORITHM=INSTANT for\nmore.\n \nLOCK\n \nIn MariaDB 10.0 and later, the ALTER TABLE statement\nsupports the LOCK clause. This clause is one of the clauses\nthat is used to implement online DDL. ALTER TABLE supports\nseveral different locking strategies. A locking strategy can\nbe explicitly chosen for an ALTER TABLE operation by setting\nthe LOCK clause. The supported values are:\nDEFAULT: Acquire the least restrictive lock on the table\nthat is supported for the specific operation. Permit the\nmaximum amount of concurrency that is supported for the\nspecific operation.\nNONE: Acquire no lock on the table. Permit all concurrent\nDML. If this locking strategy is not permitted for an\noperation, then an error is raised.\nSHARED: Acquire a read lock on the table. Permit read-only\nconcurrent DML. If this locking strategy is not permitted\nfor an operation, then an error is raised.\nEXCLUSIVE: Acquire a write lock on the table. Do not permit\nconcurrent DML.\n \nDifferent storage engines support different locking\nstrategies for different operations. If a specific locking\nstrategy is chosen for an ALTER TABLE operation, and that\ntable\'s storage engine does not support that locking\nstrategy for that specific operation, then an error will be\nraised.\n \nIf the LOCK clause is not explicitly set, then the operation\nuses LOCK=DEFAULT.\n \nALTER ONLINE TABLE is equivalent to LOCK=NONE. Therefore,\nthe ALTER ONLINE TABLE statement can be used to ensure that\nyour ALTER TABLE operation allows all concurrent DML.\n \nSee InnoDB Online DDL Overview: LOCK for information on how\nthe LOCK clause affects InnoDB.\n \nProgress Reporting\n \nMariaDB provides progress reporting for ALTER TABLE\nstatement for clients\nthat support the new progress reporting protocol. For\nexample, if you were using the mysql client, then the\nprogress report might look like this::\n \nALTER TABLE test ENGINE=Aria;\nStage: 1 of 2 \'copy to tmp table\' 46% of stage\n \nThe progress report is also shown in the output of the SHOW\nPROCESSLIST statement and in the contents of the\ninformation_schema.PROCESSLIST table.\n \nSee Progress Reporting for more information.\n \nAborting ALTER TABLE Operations\n \nIf an ALTER TABLE operation is being performed and the\nconnection is killed, the changes will be rolled back in a\ncontrolled manner. The rollback can be a slow operation as\nthe time it takes is relative to how far the operation has\nprogressed.\n \nAborting ALTER TABLE ... ALGORITHM=COPY was made faster by\nremoving excessive undo logging (MDEV-11415). This\nsignificantly shortens the time it takes to abort a running\nALTER TABLE operation.\n \nExamples\n-------- \nAdding a new column:\n \nALTER TABLE t1 ADD x INT;\n \nDropping a column:\n \nALTER TABLE t1 DROP x;\n \nModifying the type of a column:\n \nALTER TABLE t1 MODIFY x bigint unsigned;\n \nChanging the name and type of a column:\n \nALTER TABLE t1 CHANGE a b bigint unsigned auto_increment;\n \nCombining multiple clauses in a single ALTER TABLE\nstatement, separated by commas:\n \nALTER TABLE t1 DROP x, ADD x2 INT, CHANGE y y2 INT;\n \nChanging the storage engine:\n \nALTER TABLE t1 ENGINE = InnoDB;\n \nRebuilding the table (the previous example will also rebuild\nthe table if it was already InnoDB):\n \nALTER TABLE t1 FORCE;\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-table/') WHERE help_topic_id = 647; +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (648,39,'ALTER TABLESPACE','The ALTER TABLESPACE statement is not supported by MariaDB.\nIt was originally inherited from MySQL NDB Cluster. In MySQL\n5.7 and later, the statement is also supported for InnoDB.\nHowever, MariaDB has chosen not to include that specific\nfeature. See MDEV-19294 for more information.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/alter-tablespace/','','https://mariadb.com/kb/en/library/alter-tablespace/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (649,39,'ALTER VIEW','Syntax\n------ \nALTER\n [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]\n [DEFINER = { user | CURRENT_USER }]\n [SQL SECURITY { DEFINER | INVOKER }]\n VIEW view_name [(column_list)]\n AS select_statement\n [WITH [CASCADED | LOCAL] CHECK OPTION]\n \nDescription\n----------- \nThis statement changes the definition of a view, which must\nexist. The\nsyntax is similar to that for CREATE VIEW and the effect is\nthe same\nas for CREATE OR REPLACE VIEW if the view exists. This\nstatement\nrequires the CREATE VIEW and DROP privileges for the view,\nand some\nprivilege for each column referred to in the SELECT\nstatement. As of\nMariaDB 5.1.23, ALTER VIEW is allowed only to the definer or\nusers with\nthe SUPER privilege.\n \nExample\n \nALTER VIEW v AS SELECT a, a*3 AS a2 FROM t;\n \n\n\nURL: https://mariadb.com/kb/en/library/alter-view/','','https://mariadb.com/kb/en/library/alter-view/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (650,39,'CONSTRAINT','MariaDB supports the implementation of constraints at the\ntable-level using either CREATE TABLE or ALTER TABLE\nstatements. A table constraint restricts the data you can\nadd to the table. If you attempt to insert invalid data on a\ncolumn, MariaDB throws an error. \n \nSyntax\n------ \n[CONSTRAINT [symbol]] constraint_expression\n \nconstraint_expression:\n | PRIMARY KEY [index_type] (index_col_name, ...)\n[index_option] ...\n | FOREIGN KEY [index_name] (index_col_name, ...) \n REFERENCES tbl_name (index_col_name, ...)\n [ON DELETE reference_option]\n [ON UPDATE reference_option]\n | UNIQUE [INDEX|KEY] [index_name]\n [index_type] (index_col_name, ...) [index_option] ...\n | CHECK (check_constraints)\n \nindex_type:\n USING {BTREE | HASH | RTREE}\n \nindex_col_name:\n col_name [(length)] [ASC | DESC]\n \nindex_option:\n | KEY_BLOCK_SIZE [=] value\n | index_type\n | WITH PARSER parser_name\n | COMMENT \'string\'\n | CLUSTERING={YES|NO}\n \nreference_option:\n RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT\n \nDescription\n----------- \nConstraints provide restrictions on the data you can add to\na table. This allows you to enforce data integrity from\nMariaDB, rather than through application logic. When a\nstatement violates a constraint, MariaDB throws an error.\n \nThere are four types of table constraints:\n \nConstraint | Description | \n \nPRIMARY KEY | Sets the column for referencing rows. Values\nmust be unique and not null. | \n \nFOREIGN KEY | Sets the column to reference the primary key\non another table. | \n \nUNIQUE | Requires values in column or columns only occur\nonce in the table. | \n \nCHECK | Checks whether the data meets the given condition. |\n\n \nFOREIGN KEY Constraints\n \nInnoDB supports foreign key constraints. The syntax for a\nforeign key\nconstraint definition in InnoDB looks like this:\n \n[CONSTRAINT [symbol]] FOREIGN KEY\n [index_name] (index_col_name, ...)\n REFERENCES tbl_name (index_col_name,...)\n [ON DELETE reference_option]\n [ON UPDATE reference_option]\n \nreference_option:\n RESTRICT | CASCADE | SET NULL | NO ACTION\n \nCHECK Constraints\n \nFrom MariaDB 10.2.1, constraints are enforced. Before\nMariaDB 10.2.1 constraint expressions were accepted in the\nsyntax but ignored.\n \nIn MariaDB 10.2.1 you can define constraints in 2 different\nways:\nCHECK(expression) given as part of a column definition.\nCONSTRAINT [constraint_name] CHECK (expression)\n \nBefore a row is inserted or updated, all constraints are\nevaluated in the order they are defined. If any constraint\nexpression returns false, then the row will not be inserted\nor updated.\nOne can use most deterministic functions in a constraint,\nincluding UDFs.\n \nCREATE TABLE t1 (a INT CHECK (a>2), b INT CHECK (b>2),\nCONSTRAINT a_greater CHECK (a>b));\n \nIf you use the second format and you don\'t give a name to\nthe constraint, then the constraint will get an\nautomatically generated name. This is done so that you can\nlater delete the constraint with ALTER TABLE DROP\nconstraint_name.\n \nOne can disable all constraint expression checks by setting\nthe check_constraint_checks variable to OFF. This is useful\nfor example when loading a table that violates some\nconstraints that you want to later find and fix in SQL.\n \nReplication\n \nIn row-based replication, only the master checks\nconstraints, and failed statements will not be replicated.\nIn statement-based replication, the slaves will also check\nconstraints. Constraints should therefore be identical, as\nwell as deterministic, in a replication environment.\n \nAuto_increment\n \nFrom MariaDB 10.2.6, auto_increment columns are no longer\npermitted in check constraints. Previously they were\npermitted, but would not work correctly. See MDEV-11117.\n \nExamples\n-------- \nCREATE TABLE product (category INT NOT NULL, id INT NOT\nNULL,\n price DECIMAL,\n PRIMARY KEY(category, id)) ENGINE=INNODB;\n \nCREATE TABLE customer (id INT NOT NULL,\n PRIMARY KEY (id)) ENGINE=INNODB;\n \nCREATE TABLE product_order (no INT NOT NULL AUTO_INCREMENT,\n product_category INT NOT NULL,\n product_id INT NOT NULL,\n customer_id INT NOT NULL,\n PRIMARY KEY(no),\n INDEX (product_category, product_id),\n FOREIGN KEY (product_category, product_id)\n REFERENCES product(category, id)\n ON UPDATE CASCADE ON DELETE RESTRICT,\n INDEX (customer_id),\n FOREIGN KEY (customer_id)\n REFERENCES customer(id)) ENGINE=INNODB;\n \nThe following examples will work from MariaDB 10.2.1\nonwards.\n \nNumeric constraints and comparisons:\n \nCREATE TABLE t1 (a INT CHECK (a>2), b INT CHECK (b>2),\nCONSTRAINT a_greater CHECK (a>b));\n \nINSERT INTO t1(a) VALUES (1);\nERROR 4022 (23000): CONSTRAINT `a` failed for `test`.`t1`\n \nINSERT INTO t1(a,b) VALUES (3,4);\nERROR 4022 (23000): CONSTRAINT `a_greater` failed for\n`test`.`t1`\n \nINSERT INTO t1(a,b) VALUES (4,3);\nQuery OK, 1 row affected (0.04 sec)\n \nDropping a constraint:\n \nALTER TABLE t1 DROP CONSTRAINT a_greater;\n \nAdding a constraint:\n \nALTER TABLE t1 ADD CONSTRAINT a_greater CHECK (a>b);\n \nDate comparisons and character length:\n \nCREATE TABLE t2 (name VARCHAR(30) CHECK\n(CHAR_LENGTH(name)>2), start_date DATE, \n end_date DATE CHECK (start_date IS NULL OR end_date IS NULL\nOR start_date2)), start_date DATE, \n end_date DATE CHECK (start_date IS NULL OR end_date IS NULL\nOR start_date2 is very different to CHAR_LENGTH(name>2) as\nthe latter mistakenly performs a numeric comparison on the\nname field, leading to unexpected results.\n \n\n\nURL: https://mariadb.com/kb/en/library/constraint/','','https://mariadb.com/kb/en/library/constraint/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (651,39,'CREATE DATABASE','Syntax\n------ \nCREATE [OR REPLACE] {DATABASE | SCHEMA} [IF NOT EXISTS]\ndb_name\n [create_specification] ...\n \ncreate_specification:\n [DEFAULT] CHARACTER SET [=] charset_name\n | [DEFAULT] COLLATE [=] collation_name\n \nDescription\n----------- \nCREATE DATABASE creates a database with the given name. To\nuse this statement, you need the CREATE privilege for the\ndatabase. CREATE SCHEMA is a synonym for CREATE DATABASE.\n \nFor valid identifiers to use as database names, see\nIdentifier Names.\n \nOR REPLACE\n \nThe OR REPLACE clause was added in MariaDB 10.1.3\n \nIf the optional OR REPLACE clause is used, it acts as a\nshortcut for:\n \nDROP DATABASE IF EXISTS db_name;\n \nCREATE DATABASE db_name ...;\n \nIF NOT EXISTS\n \nWhen the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the specified database\nalready exists.\n \nExamples\n-------- \nCREATE DATABASE db1;\n \nQuery OK, 1 row affected (0.18 sec)\n \nCREATE DATABASE db1;\n \nERROR 1007 (HY000): Can\'t create database \'db1\'; database\nexists\n \nCREATE OR REPLACE DATABASE db1;\nQuery OK, 2 rows affected (0.00 sec)\n \nCREATE DATABASE IF NOT EXISTS db1;\nQuery OK, 1 row affected, 1 warning (0.01 sec)\n \nSHOW WARNINGS;\n+-------+------+----------------------------------------------+\n| Level | Code | Message |\n+-------+------+----------------------------------------------+\n| Note | 1007 | Can\'t create database \'db1\';\n database exists |\n+-------+------+----------------------------------------------+\n \nSetting the character sets and collation. See Setting\nCharacter Sets and Collations for more details.\n \nCREATE DATABASE czech_slovak_names \n CHARACTER SET = \'keybcs2\'\n COLLATE = \'keybcs2_bin\';\n \n\n\nURL: https://mariadb.com/kb/en/library/create-database/','','https://mariadb.com/kb/en/library/create-database/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (652,39,'CREATE EVENT','Syntax\n------ \nCREATE [OR REPLACE]\n [DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]\n EVENT \n [IF NOT EXISTS]\n event_name \n ON SCHEDULE schedule\n [ON COMPLETION [NOT] PRESERVE]\n [ENABLE | DISABLE | DISABLE ON SLAVE]\n [COMMENT \'comment\']\n DO sql_statement;\n \nschedule:\n AT timestamp [+ INTERVAL interval] ...\n | EVERY interval \n [STARTS timestamp [+ INTERVAL interval] ...] \n [ENDS timestamp [+ INTERVAL interval] ...]\n \ninterval:\n quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |\n WEEK | SECOND | YEAR_MONTH | DAY_HOUR | DAY_MINUTE |\n DAY_SECOND | HOUR_MINUTE | HOUR_SECOND | MINUTE_SECOND}\n \nDescription\n----------- \nThis statement creates and schedules a new event. It\nrequires the\nEVENT privilege for the schema in which the event is to be\ncreated.\n \nThe minimum requirements for a valid CREATE EVENT statement\nare as\nfollows:\nThe keywords CREATE EVENT plus an event name, which uniquely\nidentifies\n the event in the current schema. (Prior to MySQL 5.1.12,\nthe event name\n needed to be unique only among events created by the same\nuser on a given\n database.)\nAn ON SCHEDULE clause, which determines when and how often\nthe event\n executes.\nA DO clause, which contains the SQL statement to be executed\nby an\n event.\n \nHere is an example of a minimal CREATE EVENT statement:\n \nCREATE EVENT myevent\n ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR\n DO\n UPDATE myschema.mytable SET mycol = mycol + 1;\n \nThe previous statement creates an event named myevent. This\nevent executes once\n— one hour following its creation\n— by running an SQL statement that increments the\nvalue of the myschema.mytable table\'s mycol column by 1.\n \nThe event_name must be a valid MariaDB identifier with a\nmaximum length\nof 64 characters. It may be delimited using back ticks, and\nmay be\nqualified with the name of a database schema. An event is\nassociated\nwith both a MariaDB user (the definer) and a schema, and its\nname must\nbe unique among names of events within that schema. In\ngeneral, the\nrules governing event names are the same as those for names\nof stored\nroutines. See Identifier Names.\n \nIf no schema is indicated as part of event_name, the default\n(current)\nschema is assumed.\n \nFor valid identifiers to use as event names, see Identifier\nNames.\n \nOR REPLACE\n \nThe OR REPLACE clause was included in MariaDB 10.1.4. If\nused and the event already exists, instead of an error being\nreturned, the existing event will be dropped and replaced by\nthe newly defined event.\n \nIF NOT EXISTS\n \nIf the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the event already exists.\nCannot be used together with OR REPLACE.\n \nON SCHEDULE\n \nThe ON SCHEDULE clause can be used to specify when the event\nmust be triggered.\n \nAT\n \nIf you want to execute the event only once (one time event),\nyou can use the AT keyword, followed by a timestamp. If you\nuse CURRENT_TIMESTAMP, the event acts as soon as it is\ncreated. As a convenience, you can add one or more intervals\nto that timestamp. You can also specify a timestamp in the\npast, so that the event is stored but not triggered, until\nyou modify it via ALTER EVENT.\n \nThe following example shows how to create an event that will\nbe triggered tomorrow at a certain time:\n \nCREATE EVENT example\nON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY + INTERVAL\n3 HOUR\nDO something;\n \nYou can also specify that an event must be triggered at a\nregular interval (recurring event). In such cases, use the\nEVERY clause followed by the interval.\n \nIf an event is recurring, you can specify when the first\nexecution must happen via the STARTS clause and a maximum\ntime for the last execution via the ENDS clause. STARTS and\nENDS clauses are followed by a timestamp and, optionally,\none or more intervals. The ENDS clause can specify a\ntimestamp in the past, so that the event is stored but not\nexecuted until you modify it via ALTER EVENT.\n \nIn the following example, next month a recurring event will\nbe triggered hourly for a week:\n \nCREATE EVENT example\nON SCHEDULE EVERY 1 HOUR\nSTARTS CURRENT_TIMESTAMP + INTERVAL 1 MONTH\nENDS CURRENT_TIMESTAMP + INTERVAL 1 MONTH + INTERVAL 1 WEEK\nDO some_task;\n \nIntervals consist of a quantity and a time unit. The time\nunits are the same used for other staments and time\nfunctions, except that you can\'t use microseconds for\nevents. For simple time units, like HOUR or MINUTE, the\nquantity is an integer number, for example \'10 MINUTE\'.\nFor composite time units, like HOUR_MINUTE or HOUR_SECOND,\nthe quantity must be a string with all involved simple\nvalues and their separators, for example \'2:30\' or\n\'2:30:30\'.\n \nON COMPLETION [NOT] PRESERVE\n \nThe ON COMPLETION clause can be used to specify if the event\nmust be deleted after its last execution (that is, after its\nAT or ENDS timestamp is past). By default, events are\ndropped when they are expired. To explicitly state that this\nis the desired behaviour, you can use ON COMPLETION NOT\nPRESERVE. Instead, if you want the event to be preserved,\nyou can use ON COMPLETION PRESERVE.\n \nIn you specify ON COMPLETION NOT PRESERVE, and you specify a\ntimestamp in the past for AT or ENDS clause, the event will\nbe immediatly dropped. In such cases, you will get a Note\n1558: \"Event execution time is in the past and ON\nCOMPLETION NOT PRESERVE is set. The event was dropped\nimmediately after creation\".\n \nENABLE/DISABLE/DISABLE ON SLAVE\n \nEvents are ENABLEd by default. If you want to stop MariaDB\nfrom executing\nan event, you may specify DISABLE. When it is ready to be\nactivated, you\nmay enable it using ALTER EVENT. Another option is\nDISABLE ON SLAVE, which indicates that an event was created\non a master and has been replicated to the slave, which is\nprevented from executing the event. If DISABLE ON SLAVE is\nspecifically set, the event will not be executed.\n \nCOMMENT\n \nThe COMMENT clause may be used to set a comment for the\nevent. Maximum\nlength for comments is 64 characters. The comment is a\nstring, so it must be\nquoted. To see events comments, you can query the\nINFORMATION_SCHEMA.EVENTS table (the column is named\nEVENT_COMMENT).\n \nExamples\n-------- \nMinimal CREATE EVENT statement:\n \nCREATE EVENT myevent\n ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR\n DO\n UPDATE myschema.mytable SET mycol = mycol + 1;\n \nAn event that will be triggered tomorrow at a certain time:\n \nCREATE EVENT example\nON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 DAY + INTERVAL\n3 HOUR\nDO something;\n \nNext month a recurring event will be triggered hourly for a\nweek:\n \nCREATE EVENT example\nON SCHEDULE EVERY 1 HOUR\nSTARTS CURRENT_TIMESTAMP + INTERVAL 1 MONTH\nENDS CURRENT_TIMESTAMP + INTERVAL 1 MONTH + INTERVAL 1 WEEK\nDO some_task;\n \nOR REPLACE and IF NOT EXISTS:\n \nCREATE EVENT myevent\n ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR\n DO\n UPDATE myschema.mytable SET mycol = mycol + 1;\n \nERROR 1537 (HY000): Event \'myevent\' already exists\n \nCREATE OR REPLACE EVENT myevent\n ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR\n DO\n UPDATE myschema.mytable SET mycol = mycol + 1;;\nQuery OK, 0 rows affected (0.00 sec)\n \nCREATE EVENT IF NOT EXISTS myevent\n ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 HOUR\n DO\n UPDATE myschema.mytable SET mycol = mycol + 1;\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \n SHOW WARNINGS;\n \n+-------+------+--------------------------------+\n| Level | Code | Message |\n+-------+------+--------------------------------+\n| Note | 1537 | Event \'myevent\' already exists |\n+-------+------+--------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/create-event/','','https://mariadb.com/kb/en/library/create-event/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (653,39,'CREATE FUNCTION','Syntax\n------ \nCREATE [OR REPLACE]\n [DEFINER = {user | CURRENT_USER | role | CURRENT_ROLE }]\n [AGGREGATE] FUNCTION [IF NOT EXISTS] func_name\n([func_parameter[,...]])\n RETURNS type\n [characteristic ...]\n RETURN func_body\n \nfunc_parameter:\n param_name type\n \ntype:\n Any valid MariaDB data type\n \ncharacteristic:\n LANGUAGE SQL\n | [NOT] DETERMINISTIC\n | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL\nDATA }\n | SQL SECURITY { DEFINER | INVOKER }\n | COMMENT \'string\'\n \nfunc_body:\n Valid SQL procedure statement\n \nDescription\n----------- \nUse the CREATE FUNCTION statement to create a new stored\nfunction. You must have\nthe CREATE ROUTINE database privilege to use CREATE\nFUNCTION.\nA function takes any number of arguments and returns a value\nfrom the function body. The\nfunction body can be any valid SQL expression as you would\nuse, for example, in any select\nexpression. If you have the appropriate privileges, you can\ncall the function exactly as you\nwould any built-in function. See Security below for details\non privileges.\n \nYou can also use a variant of the CREATE FUNCTION statement\nto install a user-defined\nfunction (UDF) defined by a plugin. See CREATE FUNCTION\n(UDF)\nfor details.\n \nYou can use a SELECT statement for the function body by\nenclosing it in\nparentheses, exactly as you would to use a subselect for any\nother expression. The SELECT\nstatement must return a single value. If more than one\ncolumn is returned when the function is called,\nerror 1241 results. If more than one row is returned when\nthe function is called, error 1242\nresults. Use a LIMIT clause to ensure only one row is\nreturned.\n \nYou can also replace the RETURN clause with a BEGIN...END\ncompound\nstatement. The compound statement must contain a RETURN\nstatement. When the function is\ncalled, the RETURN statement immediately returns its result,\nand any statements after RETURN\nare effectively ignored.\n \nBy default, a function is associated with the default\ndatabase. To associate the function explicitly\nwith a given database, specify the fully-qualified name as\ndb_name.func_name\nwhen you create it. If the function name is the same as the\nname of a built-in function, you must\nuse the fully qualified name when you call it.\n \nThe parameter list enclosed within parentheses must always\nbe present.\nIf there are no parameters, an empty parameter list of ()\nshould be\nused. Parameter names are not case sensitive.\n \nEach parameter can be declared to use any valid data type,\nexcept that\nthe COLLATE attribute cannot be used.\n \nFor valid identifiers to use as function names, see\nIdentifier Names.\n \nAGGREGATE\n \nFrom MariaDB 10.3.3, it is possible to create stored\naggregate functions as well. See Stored Aggregate Functions\nfor details.\n \nRETURNS\n \nThe RETURNS clause specifies the return type of the\nfunction. NULL values are permitted with all return types.\n \nWhat happens if the RETURN clause returns a value of a\ndifferent type? It depends on the SQL_MODE in effect at the\nmoment of the function creation.\n \nIf the SQL_MODE is strict (STRICT_ALL_TABLES or\nSTRICT_TRANS_TABLES flags are specified), a 1366 error will\nbe produced.\n \nOtherwise, the value is coerced to the proper type. For\nexample, if a function\nspecifies an ENUM or SET value in the RETURNS clause, but\nthe RETURN\nclause returns an integer, the value returned from the\nfunction is the string for the corresponding ENUM\nmember of set of SET members.\n \nMariaDB stores the SQL_MODE system variable setting that is\nin effect at the\ntime a routine is created, and always executes the routine\nwith this setting in\nforce, regardless of the server SQL mode in effect when the\nroutine is invoked.\n \nLANGUAGE SQL\n \nLANGUAGE SQL is a standard SQL clause, and it can be used in\nMariaDB for portability. However that clause has no meaning,\nbecause SQL is the only supported language for stored\nfunctions.\n \nA function is deterministic if it can produce only one\nresult for a given list of parameters. If the result may be\naffected by stored data, server variables, random numbers or\nany value that is not explicitly passed, then the function\nis not deterministic. Also, a function is non-deterministic\nif it uses non-deterministic functions like NOW() or\nCURRENT_TIMESTAMP(). The optimizer may choose a faster\nexecution plan if it known that the function is\ndeterministic. In such cases, you should declare the routine\nusing the DETERMINISTIC keyword. If you want to explicitly\nstate that the function is not deterministic (which is the\ndefault) you can use the NOT DETERMINISTIC keywords.\n \nIf you declare a non-deterministic function as\nDETERMINISTIC, you may get incorrect results. If you declare\na deterministic function as NOT DETERMINISTIC, in some cases\nthe queries will be slower.\n \nOR REPLACE\n \nIf the optional OR REPLACE clause is used, it acts as a\nshortcut for:\n \nDROP FUNCTION IF EXISTS function_name;\n \nCREATE FUNCTION function_name ...;\n \nwith the exception that any existing privileges for the\nfunction are not dropped.\n \nIF NOT EXISTS\n \nIf the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the function already exists.\nCannot be used together with OR REPLACE.\n \n[NOT] DETERMINISTIC\n \nThe [NOT] DETERMINISTIC clause also affects binary logging,\nbecause the STATEMENT format can not be used to store or\nreplicate non-deterministic statements.\n \nCONTAINS SQL, NO SQL, READS SQL DATA, and MODIFIES SQL DATA\nare informative clauses that tell the server what the\nfunction does. MariaDB does not check in any way whether the\nspecified clause is correct. If none of these clauses are\nspecified, CONTAINS SQL is used by default.\n \nMODIFIES SQL DATA\n \nMODIFIES SQL DATA means that the function contains\nstatements that may modify data stored in databases. This\nhappens if the function contains statements like DELETE,\nUPDATE, INSERT, REPLACE or DDL.\n \nREADS SQL DATA\n \nREADS SQL DATA means that the function reads data stored in\ndatabases, but does not modify any data. This happens if\nSELECT statements are used, but there no write operations\nare executed.\n \nCONTAINS SQL\n \nCONTAINS SQL means that the function contains at least one\nSQL statement, but it does not read or write any data stored\nin a database. Examples include SET or DO.\n \nNO SQL\n \nNO SQL means nothing, because MariaDB does not currently\nsupport any language other than SQL.\n \nOracle Mode\n \nFrom MariaDB 10.3, a subset of Oracle\'s PL/SQL language has\nbeen supported in addition to the traditional SQL/PSM-based\nMariaDB syntax. See Oracle mode from MariaDB 10.3 for\ndetails on changes when running Oracle mode.\n \nSecurity\n \nYou must have the EXECUTE privilege on a function to call\nit.\nMariaDB automatically grants the EXECUTE and ALTER ROUTINE\nprivileges to the\naccount that called CREATE FUNCTION, even if the DEFINER\nclause was used.\n \nEach function has an account associated as the definer. By\ndefault, the definer is the account\nthat created the function. Use the DEFINER clause to specify\na different account as the\ndefiner. You must have the SUPER privilege to use the\nDEFINER\nclause. See Account Names for details on specifying\naccounts.\n \nThe SQL SECURITY clause specifies what privileges are used\nwhen a function is called.\nIf SQL SECURITY is INVOKER, the function body will be\nevaluated using the privileges\nof the user calling the function. If SQL SECURITY is\nDEFINER, the function body is\nalways evaluated using the privileges of the definer\naccount. DEFINER is the default.\n \nThis allows you to create functions that grant limited\naccess to certain data. For example, say\nyou have a table that stores some employee information, and\nthat you\'ve granted SELECT\nprivileges only on certain columns to the user account\nroger.\n \nCREATE TABLE employees (name TINYTEXT, dept TINYTEXT, salary\nINT);\nGRANT SELECT (name, dept) ON employees TO roger;\n \nTo allow the user the get the maximum salary for a\ndepartment, define a function and grant\nthe EXECUTE privilege:\n \nCREATE FUNCTION max_salary (dept TINYTEXT) RETURNS INT\nRETURN\n (SELECT MAX(salary) FROM employees WHERE employees.dept =\ndept);\nGRANT EXECUTE ON FUNCTION max_salary TO roger;\n \nSince SQL SECURITY defaults to DEFINER, whenever the user\nroger calls\nthis function, the subselect will execute with your\nprivileges. As long as you have privileges to\nselect the salary of each employee, the caller of the\nfunction will be able to get the maximum\nsalary for each department without being able to see\nindividual salaries.\n \nCharacter sets and collations\n \nFunction return types can be declared to use any valid\ncharacter set and collation. If used, the COLLATE attribute\nneeds to be preceded by a CHARACTER SET attribute.\n \nIf the character set and collation are not specifically set\nin the statement, the database defaults at the time of\ncreation will be used. If the database defaults change at a\nlater stage, the stored function character set/collation\nwill not be changed at the same time; the stored function\nneeds to be dropped and recreated to ensure the same\ncharacter set/collation as the database is used.\n \nExamples\n-------- \nThe following example function takes a parameter, performs\nan operation using\nan SQL function, and returns the result.\n \nCREATE FUNCTION hello (s CHAR(20))\n RETURNS CHAR(50) DETERMINISTIC\n RETURN CONCAT(\'Hello, \',s,\'!\');\n \nSELECT hello(\'world\');\n+----------------+\n| hello(\'world\') |\n+----------------+\n| Hello, world! |\n+----------------+\n \nYou can use a compound statement in a function to manipulate\ndata with statements\nlike INSERT and UPDATE. The following example creates a\ncounter function\nthat uses a temporary table to store the current value.\nBecause the compound statement\ncontains statements terminated with semicolons, you have to\nfirst change the statement\ndelimiter with the DELIMITER statement to allow the\nsemicolon to be used in the\nfunction body. See Delimiters in the mysql client for more.\n \nCREATE TEMPORARY TABLE counter (c INT);\nINSERT INTO counter VALUES (0);\nDELIMITER //\nCREATE FUNCTION counter () RETURNS INT\n BEGIN\n UPDATE counter SET c = c + 1;\n \n RETURN (SELECT c FROM counter LIMIT 1);\n END //\nDELIMITER ;\n \nCharacter set and collation:\n \nCREATE FUNCTION hello2 (s CHAR(20))\n RETURNS CHAR(50) CHARACTER SET \'utf8\' COLLATE\n\'utf8_bin\' DETERMINISTIC\n RETURN CONCAT(\'Hello, \',s,\'!\');\n \n\n\nURL: https://mariadb.com/kb/en/library/create-function/','','https://mariadb.com/kb/en/library/create-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (654,39,'CREATE INDEX','Syntax\n------ \nCREATE [OR REPLACE] [UNIQUE|FULLTEXT|SPATIAL] INDEX \n [IF NOT EXISTS] index_name\n [index_type]\n ON tbl_name (index_col_name,...)\n [WAIT n | NOWAIT]\n [index_option]\n [algorithm_option | lock_option] ...\n \nindex_col_name:\n col_name [(length)] [ASC | DESC]\n \nindex_type:\n USING {BTREE | HASH | RTREE}\n \nindex_option:\n KEY_BLOCK_SIZE [=] value\n | index_type\n | WITH PARSER parser_name\n | COMMENT \'string\'\n \nalgorithm_option:\n ALGORITHM [=] {DEFAULT|INPLACE|COPY|NOCOPY|INSTANT}\n \nlock_option:\n LOCK [=] {DEFAULT|NONE|SHARED|EXCLUSIVE}\n \nDescription\n----------- \nCREATE INDEX is mapped to an ALTER TABLE statement to create\nindexes.\nSee ALTER TABLE. CREATE INDEX cannot be used to create a\nPRIMARY KEY; use ALTER TABLE instead.\n \nIf another connection is using the table, a metadata lock is\nactive, and this statement will wait until the lock is\nreleased. This is also true for non-transactional tables.\n \nAnother shortcut, DROP INDEX, allows the removal of an\nindex.\n \nFor valid identifiers to use as index names, see Identifier\nNames.\n \nNote that KEY_BLOCK_SIZE is currently ignored in CREATE\nINDEX, although it is included in the output of SHOW CREATE\nTABLE.\n \nPrivileges\n \nExecuting the CREATE INDEX statement requires the INDEX\nprivilege for the table or the database.\n \nOnline DDL\n \nIn MariaDB 10.0 and later, online DDL is supported with the\nALGORITHM and LOCK clauses.\n \nSee InnoDB Online DDL Overview for more information on\nonline DDL with InnoDB.\n \nCREATE OR REPLACE INDEX ...\n \nThe OR REPLACE clause was added in MariaDB 10.1.4.\n \nIf the OR REPLACE clause is used and if the index already\nexists, then instead of returning an error, the server will\ndrop the existing index and replace it with the newly\ndefined index.\n \nCREATE INDEX IF NOT EXISTS ...\n \nIf the IF NOT EXISTS clause is used, then the index will\nonly be created if an index with the same name does not\nalready exist. If the index already exists, then a warning\nwill be triggered by default.\n \nIndex Definitions\n \nSee CREATE TABLE: Index Definitions for information about\nindex definitions.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \nALGORITHM\n \nSee ALTER TABLE: ALGORITHM for more information.\n \nLOCK\n \nSee ALTER TABLE: LOCK for more information.\n \nProgress Reporting\n \nMariaDB provides progress reporting for CREATE INDEX\nstatement for clients\nthat support the new progress reporting protocol. For\nexample, if you were using the mysql client, then the\nprogress report might look like this::\n \nCREATE INDEX ON tab (num);;\nStage: 1 of 2 \'copy to tmp table\' 46% of stage\n \nThe progress report is also shown in the output of the SHOW\nPROCESSLIST statement and in the contents of the\ninformation_schema.PROCESSLIST table.\n \nSee Progress Reporting for more information.\n \nExamples\n-------- \nCreating a unique index:\n \nCREATE UNIQUE INDEX HomePhone ON Employees(Home_Phone);\n \nOR REPLACE and IF NOT EXISTS:\n \nCREATE INDEX xi ON xx5 (x);\nQuery OK, 0 rows affected (0.03 sec)\n \nCREATE INDEX xi ON xx5 (x);\nERROR 1061 (42000): Duplicate key name \'xi\'\n \nCREATE OR REPLACE INDEX xi ON xx5 (x);\nQuery OK, 0 rows affected (0.03 sec)\n \nCREATE INDEX IF NOT EXISTS xi ON xx5 (x);\nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+-------------------------+\n| Level | Code | Message |\n+-------+------+-------------------------+\n| Note | 1061 | Duplicate key name \'xi\' |\n+-------+------+-------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/create-index/','','https://mariadb.com/kb/en/library/create-index/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (655,39,'CREATE PACKAGE','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nCREATE\n [ OR REPLACE]\n [DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]\n PACKAGE [ IF NOT EXISTS ]\n [ db_name . ] package_name\n [ package_characteristic ... ]\n{ AS | IS }\n [ package_specification_element ... ]\nEND [ package_name ]\n \npackage_characteristic:\n COMMENT \'string\'\n | SQL SECURITY { DEFINER | INVOKER }\n \npackage_specification_element:\n FUNCTION_SYM package_specification_function ;\n | PROCEDURE_SYM package_specification_procedure ;\n \npackage_specification_function:\n func_name [ ( func_param [, func_param]... ) ]\n RETURNS func_return_type\n [ package_routine_characteristic... ]\n \npackage_specification_procedure:\n proc_name [ ( proc_param [, proc_param]... ) ]\n [ package_routine_characteristic... ]\n \nfunc_return_type:\n type\n \nfunc_param:\n param_name type\n \nproc_param:\n param_name { IN | OUT | INOUT | IN OUT } type\n \ntype:\n Any valid MariaDB explicit or anchored data type\n \npackage_routine_characteristic:\n COMMENT \'string\'\n | LANGUAGE SQL\n | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL\nDATA }\n | SQL SECURITY { DEFINER | INVOKER }\n \nDescription\n----------- \nThe CREATE PACKAGE statement can be used when Oracle\nSQL_MODE is set.\n \nThe CREATE PACKAGE creates the specification for a stored\npackage (a collection of logically related stored objects).\nA stored package specification declares public routines\n(procedures and functions) of the package, but does not\nimplement these routines.\n \nA package whose specification was created by the CREATE\nPACKAGE statement, should later be implemented using the\nCREATE PACKAGE BODY statement.\n \nExamples\n-------- \nSET sql_mode=ORACLE;\nDELIMITER $$\nCREATE OR REPLACE PACKAGE employee_tools AS\n FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2);\n PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2));\n PROCEDURE raiseSalaryStd(eid INT);\n PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2));\nEND;\n$$\nDELIMITER ;\n \n\n\nURL: https://mariadb.com/kb/en/library/create-package/','','https://mariadb.com/kb/en/library/create-package/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (656,39,'CREATE PACKAGE BODY','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nCREATE [ OR REPLACE ]\n [DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]\n PACKAGE BODY\n [ IF NOT EXISTS ]\n [ db_name . ] package_name\n [ package_characteristic... ]\n{ AS | IS }\n package_implementation_declare_section\n package_implementation_executable_section\nEND [ package_name]\n \npackage_implementation_declare_section:\n package_implementation_item_declaration\n [ package_implementation_item_declaration... ]\n [ package_implementation_routine_definition... ]\n | package_implementation_routine_definition\n [ package_implementation_routine_definition...]\n \npackage_implementation_item_declaration:\n variable_declaration ;\n \nvariable_declaration:\n variable_name[,...] type [:= expr ]\n \npackage_implementation_routine_definition:\n FUNCTION package_specification_function\n [ package_implementation_function_body ] ;\n | PROCEDURE package_specification_procedure\n [ package_implementation_procedure_body ] ;\n \npackage_implementation_function_body:\n { AS | IS } package_routine_body [func_name]\n \npackage_implementation_procedure_body:\n { AS | IS } package_routine_body [proc_name]\n \npackage_routine_body:\n [ package_routine_declarations ]\n BEGIN\n statements [ EXCEPTION exception_handlers ]\n END\n \npackage_routine_declarations:\n package_routine_declaration \';\'\n[package_routine_declaration \';\']...\n \npackage_routine_declaration:\n variable_declaration\n | condition_name CONDITION FOR condition_value\n | user_exception_name EXCEPTION\n | CURSOR_SYM cursor_name\n [ ( cursor_formal_parameters ) ]\n IS select_statement\n ;\n \npackage_implementation_executable_section:\n END\n | BEGIN\n statement ; [statement ; ]...\n [EXCEPTION exception_handlers]\n END\n \nexception_handlers:\n exception_handler [exception_handler...]\n \nexception_handler:\n WHEN_SYM condition_value [, condition_value]...\n THEN_SYM statement ; [statement ;]...\n \ncondition_value:\n condition_name\n | user_exception_name\n | SQLWARNING\n | SQLEXCEPTION\n | NOT FOUND\n | OTHERS_SYM\n | SQLSTATE [VALUE] sqlstate_value\n | mariadb_error_code\n \n\nDescription\n----------- \nThe CREATE PACKAGE BODY statement can be used when Oracle\nSQL_MODE is set.\n \nThe CREATE PACKAGE BODY statement creates the package body\nfor a stored package. The package specification must be\npreviously created using the CREATE PACKAGE statement.\n \nA package body provides implementations of the package\npublic routines and can optionally have:\npackage-wide private variables\npackage private routines\nforward declarations for private routines\nan executable initialization section\n \nExamples\n-------- \nSET sql_mode=ORACLE;\nDELIMITER $$\nCREATE OR REPLACE PACKAGE employee_tools AS\n FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2);\n PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2));\n PROCEDURE raiseSalaryStd(eid INT);\n PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2));\nEND;\n$$\nCREATE PACKAGE BODY employee_tools AS\n -- package body variables\n stdRaiseAmount DECIMAL(10,2):=500;\n \n -- private routines\n PROCEDURE log (eid INT, ecmnt TEXT) AS\n BEGIN\n INSERT INTO employee_log (id, cmnt) VALUES (eid, ecmnt);\n END;\n \n -- public routines\n PROCEDURE hire(ename TEXT, esalary DECIMAL(10,2)) AS\n eid INT;\n BEGIN\n INSERT INTO employee (name, salary) VALUES (ename,\nesalary);\n eid:= last_insert_id();\n log(eid, \'hire \' || ename);\n END;\n \n FUNCTION getSalary(eid INT) RETURN DECIMAL(10,2) AS\n nSalary DECIMAL(10,2);\n BEGIN\n SELECT salary INTO nSalary FROM employee WHERE id=eid;\n log(eid, \'getSalary id=\' || eid || \' salary=\' ||\nnSalary);\n RETURN nSalary;\n END;\n \n PROCEDURE raiseSalary(eid INT, amount DECIMAL(10,2)) AS\n BEGIN\n UPDATE employee SET salary=salary+amount WHERE id=eid;\n log(eid, \'raiseSalary id=\' || eid || \' amount=\' ||\namount);\n END;\n \n PROCEDURE raiseSalaryStd(eid INT) AS\n BEGIN\n raiseSalary(eid, stdRaiseAmount);\n log(eid, \'raiseSalaryStd id=\' || eid);\n END;\n \nBEGIN\n -- This code is executed when the current session\n -- accesses any of the package routines for the first time\n log(0, \'Session \' || connection_id() || \' \' ||\ncurrent_user || \' started\');\nEND;\n$$\n \nDELIMITER ;\n \n\n\nURL: https://mariadb.com/kb/en/library/create-package-body/','','https://mariadb.com/kb/en/library/create-package-body/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (657,39,'CREATE PROCEDURE','Syntax\n------ \nCREATE\n [OR REPLACE]\n [DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]\n PROCEDURE sp_name ([proc_parameter[,...]])\n [characteristic ...] routine_body\n \nproc_parameter:\n [ IN | OUT | INOUT ] param_name type\n \ntype:\n Any valid MariaDB data type\n \ncharacteristic:\n LANGUAGE SQL\n | [NOT] DETERMINISTIC\n | { CONTAINS SQL | NO SQL | READS SQL DATA | MODIFIES SQL\nDATA }\n | SQL SECURITY { DEFINER | INVOKER }\n | COMMENT \'string\'\n \nroutine_body:\n Valid SQL procedure statement\n \nDescription\n----------- \nCreates a stored procedure. By default, a routine is\nassociated with the default database. To associate the\nroutine\nexplicitly with a given database, specify the name as\ndb_name.sp_name\nwhen you create it.\n \nWhen the routine is invoked, an implicit USE db_name is\nperformed (and\nundone when the routine terminates). The causes the routine\nto have\nthe given default database while it executes. USE statements\nwithin\nstored routines are disallowed.\n \nWhen a stored procedure has been created, you invoke it by\nusing the CALL statement (see CALL).\n \nTo execute the CREATE PROCEDURE statement, it is\nnecessary to have the CREATE ROUTINE privilege. By default,\nMariaDB\nautomatically grants the ALTER ROUTINE and EXECUTE\nprivileges to the\nroutine creator. See also Stored Routine Privileges.\n \nThe DEFINER and SQL SECURITY clauses specify the security\ncontext to\nbe used when checking access privileges at routine execution\ntime, as\ndescribed later.\n \nIf the routine name is the same as the name of a built-in\nSQL\nfunction, you must use a space between the name and the\nfollowing\nparenthesis when defining the routine, or a syntax error\noccurs. This\nis also true when you invoke the routine later. For this\nreason, we\nsuggest that it is better to avoid re-using the names of\nexisting SQL\nfunctions for your own stored routines.\n \nThe IGNORE_SPACE SQL mode applies to built-in functions, not\nto stored\nroutines. It is always allowable to have spaces after a\nroutine name,\nregardless of whether IGNORE_SPACE is enabled.\n \nThe parameter list enclosed within parentheses must always\nbe present.\nIf there are no parameters, an empty parameter list of ()\nshould be\nused. Parameter names are not case sensitive.\n \nEach parameter can be declared to use any valid data type,\nexcept that\nthe COLLATE attribute cannot be used.\n \nFor valid identifiers to use as procedure names, see\nIdentifier Names.\n \nIN/OUT/INOUT\n \nEach parameter is an IN parameter by default. To specify\notherwise for\na parameter, use the keyword OUT or INOUT before the\nparameter name.\n \nAn IN parameter passes a value into a procedure. The\nprocedure might\nmodify the value, but the modification is not visible to the\ncaller\nwhen the procedure returns. An OUT parameter passes a value\nfrom the\nprocedure back to the caller. Its initial value is NULL\nwithin the\nprocedure, and its value is visible to the caller when the\nprocedure\nreturns. An INOUT parameter is initialized by the caller,\ncan be\nmodified by the procedure, and any change made by the\nprocedure is\nvisible to the caller when the procedure returns.\n \nFor each OUT or INOUT parameter, pass a user-defined\nvariable in the\nCALL statement that invokes the procedure so that you can\nobtain its\nvalue when the procedure returns. If you are calling the\nprocedure\nfrom within another stored procedure or function, you can\nalso pass a\nroutine parameter or local routine variable as an IN or\nINOUT\nparameter.\n \nDETERMINISTIC/NOT DETERMINISTIC\n \nDETERMINISTIC and NOT DETERMINISTIC apply only to functions.\nSpecifying DETERMINISTC or NON-DETERMINISTIC in procedures\nhas no effect. The default value is NOT DETERMINISTIC.\nFunctions are DETERMINISTIC when they always return the same\nvalue for the same input. For example, a truncate or\nsubstring function. Any function involving data, therefore,\nis always NOT DETERMINISTIC.\n \nCONTAINS SQL/NO SQL/READS SQL DATA/MODIFIES SQL DATA\n \nCONTAINS SQL, NO SQL, READS SQL DATA, and MODIFIES SQL DATA\nare informative clauses that tell the server what the\nfunction does. MariaDB does not check in any way whether the\nspecified clause is correct. If none of these clauses are\nspecified, CONTAINS SQL is used by default.\n \nMODIFIES SQL DATA means that the function contains\nstatements that may modify data stored in databases. This\nhappens if the function contains statements like DELETE,\nUPDATE, INSERT, REPLACE or DDL.\n \nREADS SQL DATA means that the function reads data stored in\ndatabases, but does not modify any data. This happens if\nSELECT statements are used, but there no write operations\nare executed.\n \nCONTAINS SQL means that the function contains at least one\nSQL statement, but it does not read or write any data stored\nin a database. Examples include SET or DO.\n \nNO SQL means nothing, because MariaDB does not currently\nsupport any language other than SQL.\n \nThe routine_body consists of a valid SQL procedure\nstatement. This can\nbe a simple statement such as SELECT or INSERT, or it can be\na\ncompound statement written using BEGIN and END. Compound\nstatements\ncan contain declarations, loops, and other control structure\nstatements. See Programmatic and Compound Statements for\nsyntax details.\n \nMariaDB allows routines to contain DDL statements, such as\nCREATE and\nDROP. MariaDB also allows stored procedures (but not stored\nfunctions)\nto contain SQL transaction statements such as COMMIT.\n \nFor additional information about statements that are not\nallowed in\nstored routines, see Stored Routine Limitations.\n \nInvoking stored procedure from within programs\n \nFor information about invoking stored procedures from within\nprograms written in a language that has a MariaDB/MySQL\ninterface, see CALL.\n \nOR REPLACE\n \nIf the optional OR REPLACE clause is used, it acts as a\nshortcut for:\n \nDROP PROCEDURE IF EXISTS name;\n \nCREATE PROCEDURE name ...;\n \nwith the exception that any existing privileges for the\nprocedure are not dropped.\n \nsql_mode\n \nMariaDB stores the sql_mode system variable setting that is\nin effect at the time a routine is created, and always\nexecutes the routine with this setting in force, regardless\nof the server SQL mode in effect when the routine is\ninvoked.\n \nCharacter Sets and Collations\n \nProcedure parameters can be declared with any character\nset/collation. If the character set and collation are not\nspecifically set, the database defaults at the time of\ncreation will be used. If the database defaults change at a\nlater stage, the stored procedure character set/collation\nwill not be changed at the same time; the stored procedure\nneeds to be dropped and recreated to ensure the same\ncharacter set/collation as the database is used.\n \nOracle Mode\n \nFrom MariaDB 10.3, a subset of Oracle\'s PL/SQL language has\nbeen supported in addition to the traditional SQL/PSM-based\nMariaDB syntax. See Oracle mode from MariaDB 10.3 for\ndetails on changes when running Oracle mode.\n \nExamples\n-------- \nThe following example shows a simple stored procedure that\nuses an OUT\nparameter. It uses the DELIMITER command to set a new\ndelimiter for the duration of the process — see Delimiters\nin the mysql client.\n \nDELIMITER //\n \nCREATE PROCEDURE simpleproc (OUT param1 INT)\n BEGIN\n SELECT COUNT(*) INTO param1 FROM t;\n END;\n//\n \nDELIMITER ;\n \nCALL simpleproc(@a);\n \nSELECT @a;\n+------+\n| @a |\n+------+\n| 1 |\n+------+\n \nCharacter set and collation:\n \nDELIMITER //\n \nCREATE PROCEDURE simpleproc2 (\n OUT param1 CHAR(10) CHARACTER SET \'utf8\' COLLATE\n\'utf8_bin\'\n)\n BEGIN\n SELECT CONCAT(\'a\'),f1 INTO param1 FROM t;\n END;\n//\n \nDELIMITER ;\n \nCREATE OR REPLACE:\n \nDELIMITER //\n \nCREATE PROCEDURE simpleproc2 (\n OUT param1 CHAR(10) CHARACTER SET \'utf8\' COLLATE\n\'utf8_bin\'\n)\n BEGIN\n SELECT CONCAT(\'a\'),f1 INTO param1 FROM t;\n \n END;\n \n//\nERROR 1304 (42000): PROCEDURE simpleproc2 already exists\n \nDELIMITER ;\n \nDELIMITER //\n \nCREATE OR REPLACE PROCEDURE simpleproc2 (\n OUT param1 CHAR(10) CHARACTER SET \'utf8\' COLLATE\n\'utf8_bin\'\n)\n BEGIN\n SELECT CONCAT(\'a\'),f1 INTO param1 FROM t;\n \n END;\n \n//\nERROR 1304 (42000): PROCEDURE simpleproc2 already exists\n \nDELIMITER ;\n \nQuery OK, 0 rows affected (0.03 sec)\n \n\n\nURL: https://mariadb.com/kb/en/library/create-procedure/','','https://mariadb.com/kb/en/library/create-procedure/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (658,39,'CREATE SEQUENCE','CREATE SEQUENCE was introduced in MariaDB 10.3.\n \nSyntax\n------ \nCREATE [OR REPLACE] [TEMPORARY] SEQUENCE [IF NOT EXISTS]\nsequence_name\n[ INCREMENT [ BY | = ] increment ]\n[ MINVALUE [=] minvalue | NO MINVALUE | NOMINVALUE ]\n[ MAXVALUE [=] maxvalue | NO MAXVALUE | NOMAXVALUE ]\n[ START [ WITH | = ] start ] \n[ CACHE [=] cache | NOCACHE ] [ CYCLE | NOCYCLE] \n[table_options]\n \nThe options for CREATE SEQUENCE can be given in any order,\noptionally followed by table_options.\n \ntable_options can be any of the normal table options in\nCREATE TABLE but the most usable ones are ENGINE=... and\nCOMMENT=.\n \nNOMAXVALUE and NOMINVALUE are there to allow one to create\nSEQUENCEs using the Oracle syntax.\n \nDescription\n----------- \nCREATE SEQUENCE will create a sequence that generates new\nvalues when called with NEXT VALUE FOR sequence_name. It\'s\nan alternative to AUTO INCREMENT when one wants to have more\ncontrol of how the numbers are generated. As the SEQUENCE\ncaches values (up to CACHE) it can in some cases be much\nfaster than AUTO INCREMENT. Another benefit is that one can\naccess the last value generated by all used sequences, which\nsolves one of the limitations with LAST_INSERT_ID().\n \nCREATE SEQUENCE requires the CREATE privilege.\n \nDROP SEQUENCE can be used to drop a sequence, and ALTER\nSEQUENCE to change it.\n \nArguments to Create\n \nThe following options may be used:\n \nOption | Default value | Description | \n \nINCREMENT | 1 | Increment to use for values. May be\nnegative. Setting an increment of 0 causes the sequence to\nuse the value of the auto_increment_increment system\nvariable at the time of creation, which is always a positive\nnumber. (see MDEV-16035). | \n \nMINVALUE | 1 if INCREMENT > 0 and -9223372036854775807 if\nINCREMENT < 0 | Minimum value for the sequence | \n \nMAXVALUE | 9223372036854775806 if INCREMENT > 0 and -1 if\nINCREMENT < 0 | Max value for sequence | \n \nSTART | MINVALUE if INCREMENT > 0 and MAX_VALUE if\nINCREMENT< 0 | First value that the sequence will generate |\n\n \nCACHE | 1000 | Number of values that should be cached. 0\nif no CACHE. The underlying table will be updated first time\na new sequence number is generated and each time the cache\nruns out. | \n \nIf CYCLE is used then the sequence should start again from\nMINVALUE after it has run out of values. Default value is\nNOCYCLE.\n \nConstraints on Create Arguments\n \nTo be able to create a legal sequence, the following must\nhold:\nMAXVALUE >= start\nMAXVALUE > MINVALUE\nSTART >= MINVALUE\nMAXVALUE = -9223372036854775807 (LONGLONG_MIN+1)\n \nNote that sequences can\'t generate the maximum/minimum 64\nbit number because of the constraint of\nMINVALUE and MAXVALUE. \n \nExamples\n-------- \nCREATE SEQUENCE s START WITH 100 INCREMENT BY 10;\n \nCREATE SEQUENCE s2 START WITH -100 INCREMENT BY -10;\n \nThe following statement fails, as the increment conflicts\nwith the defaults\n \nCREATE SEQUENCE s3 START WITH -100 INCREMENT BY 10;\n \nERROR 4082 (HY000): Sequence \'test.s3\' values are\nconflicting\n \nThe sequence can be created by specifying workable minimum\nand maximum values:\n \nCREATE SEQUENCE s3 START WITH -100 INCREMENT BY 10\nMINVALUE=-100 MAXVALUE=1000;\n \n\n\nURL: https://mariadb.com/kb/en/library/create-sequence/','','https://mariadb.com/kb/en/library/create-sequence/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (659,39,'CREATE SERVER','Syntax\n------ \nCREATE [OR REPLACE] SERVER [IF NOT EXISTS] server_name\n FOREIGN DATA WRAPPER wrapper_name\n OPTIONS (option [, option] ...)\n \noption:\n { HOST character-literal\n | DATABASE character-literal\n | USER character-literal\n | PASSWORD character-literal\n | SOCKET character-literal\n | OWNER character-literal\n | PORT numeric-literal }\n \nDescription\n----------- \nThis statement creates the definition of a server for use\nwith the Spider,\nFEDERATED or FederatedX storage\nengine. The CREATE SERVER statement creates a new row within\nthe\nservers table within the mysql database. This statement\nrequires the SUPER privilege.\n \nThe server_name should be a unique reference to the server.\nServer definitions\nare global within the scope of the server, it is not\npossible to qualify the\nserver definition to a specific database. server_name has a\nmaximum length of\n64 characters (names longer than 64 characters are silently\ntruncated), and is\ncase insensitive. You may specify the name as a quoted\nstring.\n \nThe wrapper_name should be mysql, and may be quoted with\nsingle quotes.\nOther values for wrapper_name are not currently supported.\n \nFor each option you must specify either a character literal\nor numeric literal.\nCharacter literals are UTF-8, support a maximum length of 64\ncharacters and\ndefault to a blank (empty) string. String literals are\nsilently truncated to 64\ncharacters. Numeric literals must be a number between 0 and\n9999, default value\nis 0.\n \nNote: The OWNER option is currently not applied, and has no\neffect on\nthe ownership or operation of the server connection that is\ncreated.\n \nThe CREATE SERVER statement creates an entry in the\nmysql.servers table that can later be used with the\nCREATE TABLE statement when creating a Spider, FederatedX or\nFEDERATED table. The options that you specify will\nbe used to populate the columns in the mysql.servers table.\nThe table columns\nare Server_name, Host, Db, Username, Password, Port and\nSocket.\n \n DROP SERVER removes a previously created server definition.\n\n \nCREATE SERVER is not written to the binary log, irrespective\nof\nthe binary log format being used.\n \nFor valid identifiers to use as server names, see Identifier\nNames.\n \nOR REPLACE\n \nIf the optional OR REPLACE clause is used, it acts as a\nshortcut for:\n \nDROP SERVER IF EXISTS name;\n \nCREATE SERVER server_name ...;\n \nIF NOT EXISTS\n \nIf the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the server already exists.\nCannot be used together with OR REPLACE.\n \nExamples\n-------- \nCREATE SERVER s\nFOREIGN DATA WRAPPER mysql\nOPTIONS (USER \'Remote\', HOST \'192.168.1.106\', DATABASE\n\'test\');\n \nOR REPLACE and IF NOT EXISTS:\n \nCREATE SERVER s \nFOREIGN DATA WRAPPER mysql \nOPTIONS (USER \'Remote\', HOST \'192.168.1.106\', DATABASE\n\'test\');\nERROR 1476 (HY000): The foreign server, s, you are trying to\ncreate already exists\n \nCREATE OR REPLACE SERVER s \nFOREIGN DATA WRAPPER mysql \nOPTIONS (USER \'Remote\', HOST \'192.168.1.106\', DATABASE\n\'test\');\nQuery OK, 0 rows affected (0.00 sec)\n \nCREATE SERVER IF NOT EXISTS s \nFOREIGN DATA WRAPPER mysql \nOPTIONS (USER \'Remote\', HOST \'192.168.1.106\', DATABASE\n\'test\');\nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+----------------------------------------------------------------+\n| Level | Code | Message |\n+-------+------+----------------------------------------------------------------+\n| Note | 1476 | The foreign server, s, you are trying to\ncreate already exists |\n+-------+------+----------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/create-server/','','https://mariadb.com/kb/en/library/create-server/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (660,39,'CREATE TABLE','Syntax\n------ \nCREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]\ntbl_name\n (create_definition,...) [table_options ]...\n[partition_options]\nCREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]\ntbl_name\n [(create_definition,...)] [table_options ]...\n[partition_options]\n select_statement\nCREATE [OR REPLACE] [TEMPORARY] TABLE [IF NOT EXISTS]\ntbl_name\n { LIKE old_table_name | (LIKE old_table_name) }\n \nselect_statement:\n [IGNORE | REPLACE] [AS] SELECT ... (Some legal select\nstatement)\n \nDescription\n----------- \nUse the CREATE TABLE statement to create a table with the\ngiven name.\n \nIn its most basic form, the CREATE TABLE statement provides\na table name\nfollowed by a list of columns, indexes, and constraints. By\ndefault, the table\nis created in the default database. Specify a database with\ndb_name.tbl_name.\nIf you quote the table name, you must quote the database\nname and table name\nseparately as `db_name`.`tbl_name`. This is particularly\nuseful for CREATE TABLE ... SELECT, because it allows to\ncreate a table into a database, which contains data from\nother databases. See Identifier Qualifiers.\n \nIf a table with the same name exists, error 1050 results.\nUse IF NOT EXISTS\nto suppress this error and issue a note instead. Use SHOW\nWARNINGS\nto see notes.\n \nThe CREATE TABLE statement automatically commits the current\ntransaction,\nexcept when using the TEMPORARY keyword.\n \nFor valid identifiers to use as table names, see Identifier\nNames.\n \nNote: if the default_storage_engine is set to ColumnStore\nthen it needs setting on all UMs. Otherwise when the tables\nusing the default engine are replicated across UMs they will\nuse the wrong engine. You should therefore not use this\noption as a session variable with ColumnStore.\n \nMicrosecond precision can be between 0-6. If no precision is\nspecified it is assumed to be 0, for backward compatibility\nreasons.\n \nPrivileges\n \nExecuting the CREATE TABLE statement requires the CREATE\nprivilege for the table or the database.\n \nCREATE OR REPLACE TABLE ...\n \nThe OR REPLACE clause was added in MariaDB 10.0.8.\n \nIf the OR REPLACE clause is used and if the table already\nexists, then instead of returning an error, the server will\ndrop the existing table and replace it with the newly\ndefined table.\n \nThis syntax was originally added to make replication more\nrobust if it has to rollback and repeat statements such as\nCREATE ... SELECT on slaves.\n \nCREATE OR REPLACE TABLE table_name (a int);\n \nis basically the same as:\n \nDROP TABLE IF EXISTS table_name;\nCREATE TABLE table_name (a int);\n \nwith the following exceptions:\nIf table_name was locked with LOCK TABLES it will continue\nto be locked after the statement.\nTemporary tables are only dropped if the TEMPORARY keyword\nwas used. (With DROP TABLE, temporary tables are preferred\nto be dropped before normal tables).\n \nThings to be Aware of With CREATE OR REPLACE\n \nThe table is dropped first (if it existed), after that the\nCREATE is done. Because of this, if the CREATE fails, then\nthe table will not exist anymore after the statement. If the\ntable was used with LOCK TABLES it will be unlocked.\nOne can\'t use OR REPLACE together with IF EXISTS.\nSlaves in replication will by default use CREATE OR REPLACE\nwhen replicating CREATE statements that don\'\'t use IF\nEXISTS. This can be changed by setting the variable\nslave-ddl-exec-mode to STRICT.\n \nCREATE TABLE IF NOT EXISTS ...\n \nIf the IF NOT EXISTS clause is used, then the index will\nonly be created if an index with the same name does not\nalready exist. If the index already exists, then a warning\nwill be triggered by default.\n \nCREATE TEMPORARY TABLE ...\n \nUse the TEMPORARY keyword to create a temporary table that\nis only available to your current session. Temporary tables\nare dropped when the your session ends. Temporary table\nnames are specific to your session. They will not conflict\nwith other temporary tables from other session even if they\nshare the same name. They will shadow names of non-temporary\ntables or views, if they are identical. A temporary table\ncan have the same name as a non-temporary table which is\nlocated in the same database. In that case, their name will\nreference the temporary table when used in SQL statements.\nYou must have the CREATE TEMPORARY TABLES privilege on the\ndatabase to create temporary tables. If no storage engine is\nspecified, the default_tmp_storage_engine setting will\ndetermine the engine.\n \nCREATE TABLE ... LIKE\n \nUse the LIKE clause instead of a full table definition to\ncreate a table with the same definition as another table,\nincluding columns, indexes, and table options. Foreign key\ndefinitions, as well as any DATA DIRECTORY or INDEX\nDIRECTORY table options specified on the original table,\nwill not be created.\n \nCREATE TABLE ... SELECT\n \nYou can create a table containing data from other tables\nusing the CREATE ... SELECT statement. Columns will be\ncreated in the table for each field returned by the SELECT\nquery.\n \nYou can also define some columns normally and add other\ncolumns from a SELECT. You can also create columns in the\nnormal way and assign them some values using the query, this\nis done to force a certain type or other field\ncharacteristics. The columns that are not named in the query\nwill be placed before the others. For example:\n \nCREATE TABLE test (a INT NOT NULL, b CHAR(10)) ENGINE=MyISAM\n SELECT 5 AS b, c, d FROM another_table;\n \nRemember that the query just returns data. If you want to\nuse the same indexes, or the same columns attributes ([NOT]\nNULL, DEFAULT, AUTO_INCREMENT) in the new table, you need to\nspecify them manually. Types and sizes are not automatically\npreserved if no data returned by the SELECT requires the\nfull size, and VARCHAR could be converted into CHAR. The\nCAST() function can be used to forcee the new table to use\ncertain types.\n \nAliases (AS) are taken into account, and they should always\nbe used when you SELECT an expression (function,\narithmetical operation, etc).\n \nIf an error occurs during the query, the table will not be\ncreated at all.\n \nIf the new table has a primary key or UNIQUE indexes, you\ncan use the IGNORE or REPLACE keywords to handle duplicate\nkey errors during the query. IGNORE means that the newer\nvalues must not be inserted an identical value exists in the\nindex. REPLACE means that older values must be overwritten.\n \nIf the columns in the new table are more than the rows\nreturned by the query, the columns populated by the query\nwill be placed after other columns. Note that if the strict\nSQL_MODE is on, and the columns that are not names in the\nquery do not have a DEFAULT value, an error will raise and\nno rows will be copied.\n \nConcurrent inserts are not used during the execution of a\nCREATE ... SELECT.\n \nIf the table already exists, an error similar to the\nfollowing will be returned:\n \nERROR 1050 (42S01): Table \'t\' already exists\n \nIf the IF NOT EXISTS clause is used and the table exists, a\nnote will be produced instead of an error.\n \nTo insert rows from a query into an existing table, INSERT\n... SELECT can be used.\n \nColumn Definitions\n \ncreate_definition:\n { col_name column_definition | index_definition |\nperiod_definition | CHECK (expr) }\n \ncolumn_definition:\n data_type\n [NOT NULL | NULL] [DEFAULT default_value | (expression)]\n [AUTO_INCREMENT] [ZEROFILL] [UNIQUE [KEY] | [PRIMARY] KEY]\n [INVISIBLE] [{WITH|WITHOUT} SYSTEM VERSIONING]\n [COMMENT \'string\']\n [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]\n [reference_definition]\n | data_type [GENERATED ALWAYS] AS { { ROW {START|END} } | {\n(expression) [VIRTUAL | PERSISTENT | STORED] } }\n [UNIQUE [KEY]] [COMMENT \'string\']\n \nconstraint_definition:\n CONSTRAINT [constraint_name] CHECK (expression)\nNote: MariaDB accepts the REFERENCES clause in ALTER TABLE\nand CREATE TABLE column definitions, but that syntax does\nnothing. MariaDB simply parses it without returning any\nerror or warning, for compatibility with other DBMS\'s.\nBefore MariaDB 10.2.1 this was also true for CHECK\nconstraints. Only the syntax for indexes described below\ncreates foreign keys.\n \nEach definition either creates a column in the table or\nspecifies and index or\nconstraint on one or more columns. See Indexes below for\ndetails\non creating indexes.\n \nCreate a column by specifying a column name and a data type,\noptionally\nfollowed by column options. See Data Types for a full list\nof data types allowed in MariaDB.\n \nNULL and NOT NULL\n \nUse the NULL or NOT NULL options to specify that values in\nthe column\nmay or may not be NULL, respectively. By default, values may\nbe NULL. See also NULL Values in MariaDB.\n \nDEFAULT Column Option\n \nThe DEFAULT clause was enhanced in MariaDB 10.2.1. Some\nenhancements include\nBLOB and TEXT columns now support DEFAULT.\nThe DEFAULT clause can now be used with an expression or\nfunction.\n \nSpecify a default value using the DEFAULT clause. If you\ndon\'t specify DEFAULT then the following rules apply:\nIf the column is not defined with NOT NULL, AUTO_INCREMENT\nor TIMESTAMP, an explicit DEFAULT NULL will be added.\nNote that in MySQL and in MariaDB before 10.1.6, you may get\nan explicit DEFAULT for primary key parts, if not specified\nwith NOT NULL.\n \nThe default value will be used if you INSERT a row without\nspecifying a value for that column, or if you specify\nDEFAULT for that column.\nBefore MariaDB 10.2.1 you couldn\'t usually provide an\nexpression or function to evaluate at\ninsertion time. You had to provide a constant default value\ninstead. The one\nexception is that you may use CURRENT_TIMESTAMP as\nthe default value for a TIMESTAMP column to use the current\ntimestamp at insertion time.\n \nCURRENT_TIMESTAMP may also be used as\nthe default value for a DATETIME\n \nFrom MariaDB 10.2.1 you can use most functions in DEFAULT.\nExpressions should have parentheses around them. If you use\na non deterministic function in DEFAULT then all inserts to\nthe table will be replicated in row mode. You can even refer\nto earlier columns in the DEFAULT expression:\n \nCREATE TABLE t1 (a int DEFAULT (1+1), b int DEFAULT (a+1));\nCREATE TABLE t2 (a bigint primary key DEFAULT UUID_SHORT());\n \nThe DEFAULT clause cannot contain any stored functions or\nsubqueries, and a column used in the clause must already\nhave been defined earlier in the statement.\n \nSince MariaDB 10.2.1, it is possible to assign BLOB or TEXT\ncolumns a DEFAULT value. In earlier versions, assigning a\ndefault to these columns was not possible.\n \nStarting from 10.3.3 you can also use DEFAULT (NEXT VALUE\nFOR sequence)\n \nAUTO_INCREMENT Column Option\n \nUse AUTO_INCREMENT to create a column whose value can\ncan be set automatically from a simple counter. You can only\nuse AUTO_INCREMENT\non a column with an integer type. The column must be a key,\nand there can only be\none AUTO_INCREMENT column in a table. If you insert a row\nwithout specifying\na value for that column (or if you specify 0, NULL, or\nDEFAULT\nas the value), the actual value will be taken from the\ncounter, with each insertion\nincrementing the counter by one. You can still insert a\nvalue explicitly. If you\ninsert a value that is greater than the current counter\nvalue, the counter is\nset based on the new value. An AUTO_INCREMENT column is\nimplicitly NOT NULL.\nUse LAST_INSERT_ID to get the AUTO_INCREMENT value\nmost recently used by an INSERT statement.\n \nZEROFILL Column Option\n \nIf the ZEROFILL column option is specified for a column\nusing a numeric data type, then the column will be set to\nUNSIGNED and the spaces used by default to pad the field are\nreplaced with zeros. ZEROFILL is ignored in expressions or\nas part of a UNION. ZEROFILL is a non-standard MySQL and\nMariaDB enhancement.\n \nPRIMARY KEY Column Option\n \nUse PRIMARY KEY (or just KEY) to make a column a primary\nkey. A primary key is a special type of a unique key. There\ncan be at most one primary key per table, and it is\nimplicitly NOT NULL.\n \nSpecifying a column as a unique key creates a unique index\non that column. See the Index Definitions section below for\nmore information.\n \nUNIQUE KEY Column Option\n \nUse UNIQUE KEY (or just UNIQUE) to specify that all values\nin the column\nmust be distinct from each other. Unless the column is NOT\nNULL, there may be\nmultiple rows with NULL in the column. \n \nSpecifying a column as a unique key creates a unique index\non that column. See the Index Definitions section below for\nmore information.\n \nCOMMENT Column Option\n \nYou can provide a comment for each column using the COMMENT\nclause. The maximum length is 1024 characters (it was 255\ncharacters before MariaDB 5.5). Use\nthe SHOW FULL COLUMNS statement to see column comments.\n \nGenerated Columns\n \nA generated column is a column in a table that cannot\nexplicitly be set to a specific value in a DML query.\nInstead, its value is automatically generated based on an\nexpression. This expression might generate the value based\non the values of other columns in the table, or it might\ngenerate the value by calling built-in functions or\nuser-defined functions (UDFs).\n \nThere are two types of generated columns:\nPERSISTENT or STORED: This type\'s value is actually stored\nin the table.\nVIRTUAL: This type\'s value is not stored at all. Instead,\nthe value is generated dynamically when the table is\nqueried. This type is the default.\n \nGenerated columns are also sometimes called computed columns\nor virtual columns.\n \nFor a complete description about generated columns and their\nlimitations, see Generated (Virtual and Persistent/Stored)\nColumns.\n \nCOLUMN_FORMAT\n \nCOLUMN_FORMAT is only used by MySQL Cluster, and is silently\nignored in MariaDB.\n \nCOMPRESSED\n \nCertain columns may be compressed. See Storage-Engine\nIndependent Column Compression.\n \nINVISIBLE\n \nColumns may be made invisible, and hidden in certain\ncontexts. See Invisible Columns.\n \nWITH SYSTEM VERSIONING Column Option\n \nColumns may be explicitly marked as included from system\nversioning. See System-versioned tables for details.\n \nWITHOUT SYSTEM VERSIONING Column Option\n \nColumns may be explicitly marked as excluded from system\nversioning. See System-versioned tables for details.\n \nIndex Definitions\n \nindex_definition:\n {INDEX|KEY} [index_name] [index_type] (index_col_name,...)\n[index_option] ...\n | {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name]\n(index_col_name,...) [index_option] ...\n | [CONSTRAINT [symbol]] PRIMARY KEY [index_type]\n(index_col_name,...) [index_option] ...\n | [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name]\n[index_type] (index_col_name,...) [index_option] ...\n | [CONSTRAINT [symbol]] FOREIGN KEY [index_name]\n(index_col_name,...) reference_definition\n \nindex_col_name:\n col_name [(length)] [ASC | DESC]\n \nindex_type:\n USING {BTREE | HASH | RTREE}\n \nindex_option:\n KEY_BLOCK_SIZE [=] value\n | index_type\n | WITH PARSER parser_name\n | COMMENT \'string\'\n | CLUSTERING={YES| NO}\n \nreference_definition:\n REFERENCES tbl_name (index_col_name,...)\n [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE]\n [ON DELETE reference_option]\n [ON UPDATE reference_option]\n \nreference_option:\n RESTRICT | CASCADE | SET NULL | NO ACTION\nINDEX and KEY are synonyms. \n \nIndex names are optional, if not specified an automatic name\nwill be assigned. Index name are needed to drop indexes and\nappear in error messages when a constraint is violated.\n \nIndex Categories\n \nPlain Indexes\n \nPlain indexes are regular indexes that are not unique, and\nare not acting as a primary key or a foreign key. They are\nalso not the \"specialized\" FULLTEXT or SPATIAL indexes.\n \nSee Getting Started with Indexes: Plain Indexes for more\ninformation.\n \nPRIMARY KEY\n \nFor PRIMARY KEY indexes, you can specify a name for the\nindex, but it is silently ignored, and the name of the index\nis always PRIMARY.\n \nSee Getting Started with Indexes: Primary Key for more\ninformation.\n \nUNIQUE\n \nThe UNIQUE keyword means that the index will not accept\nduplicated values, except for NULLs. An error will raise if\nyou try to insert duplicate values in a UNIQUE index.\n \nFor UNIQUE indexes, you can specify a name for the\nconstraint, using the CONSTRAINT keyword. That name will be\nused in error messages.\n \nSee Getting Started with Indexes: Unique Index for more\ninformation.\n \nFOREIGN KEY\n \nFor FOREIGN KEY indexes, a reference definition must be\nprovided.\n \nFor FOREIGN KEY indexes, you can specify a name for the\nconstraint, using the CONSTRAINT keyword. That name will be\nused in error messages.\n \nFirst, you have to specify the name of the target (parent)\ntable and a column or a column list which must be indexed\nand whose values must match to the foreign key\'s values.\nThe MATCH clause is accepted to improve the compatibility\nwith other DBMS\'s, but has no meaning in MariaDB. The ON\nDELETE and ON UPDATE clauses specify what must be done when\na DELETE (or a REPLACE) statements attempts to delete a\nreferenced row from the parent table, and when an UPDATE\nstatement attempts to modify the referenced foreign key\ncolumns in a parent table row, respectively. The following\noptions are allowed:\nRESTRICT: The delete/update operation is not performed. The\nstatement terminates with a 1451 error (SQLSTATE \'2300\').\nNO ACTION: Synonym for RESTRICT.\nCASCADE: The delete/update operation is performed in both\ntables.\nSET NULL: The update or delete goes ahead in the parent\ntable, and the corresponding foreign key fields in the child\ntable are set to NULL. (They must not be defined as NOT NULL\nfor this to succeed).\nSET DEFAULT: This option is currently implemented only for\nthe PBXT storage engine, which is disabled by default and no\nlonger maintained. It sets the child table\'s foreign key\nfields to their DEFAULT values when the referenced parent\ntable key entries are updated or deleted.\n \nIf either clause is omitted, the default behavior for the\nomitted clause is RESTRICT.\n \nSee Foreign Keys for more information.\n \nFULLTEXT\n \nUse the FULLTEXT keyword to create full-text indexes.\n \nSee Full-Text Indexes for more information.\n \nSPATIAL\n \nUse the SPATIAL keyword to create geometric indexes.\n \nSee SPATIAL INDEX for more information.\n \nIndex Options\n \nKEY_BLOCK_SIZE Index Option\n \nThe KEY_BLOCK_SIZE index option is similar to the\nKEY_BLOCK_SIZE table option.\n \nWith the InnoDB storage engine, if you specify a non-zero\nvalue for the KEY_BLOCK_SIZE table option for the whole\ntable, then the table will implicitly be created with the\nROW_FORMAT table option set to COMPRESSED. However, this\ndoes not happen if you just set the KEY_BLOCK_SIZE index\noption for one or more indexes in the table. The InnoDB\nstorage engine ignores the KEY_BLOCK_SIZE index option.\nHowever, the SHOW CREATE TABLE statement may still report it\nfor the index.\n \nFor information about the KEY_BLOCK_SIZE index option, see\nthe KEY_BLOCK_SIZE table option below.\n \nIndex Types\n \nEach storage engine supports some or all index types. See\nStorage Engine Index Types for details on permitted index\ntypes for each storage engine.\n \nDifferent index types are optimized for different kind of\noperations:\nBTREE is the default type, a','','https://mariadb.com/kb/en/library/create-table/'); +update help_topic set description = CONCAT(description, 'nd normally is the best choice.\nIt is supported by all storage engines. It can be used to\ncompare a column\'s value with a value using the =, >, >=,\n0) ,b int check (b> 0), constraint abc check (a>b));\n \nIf you use the second format and you don\'t give a name to\nthe constraint, then the constraint will get a auto\ngenerated name. This is done so that you can later delete\nthe constraint with ALTER TABLE DROP constraint_name.\n \nOne can disable all constraint expression checks by setting\nthe variable check_constraint_checks to OFF. This is useful\nfor example when loading a table that violates some\nconstraints that you want to later find and fix in SQL.\n \nSee CONSTRAINT for more information.\n \nTable Options\n \nFor each individual table you create (or alter), you can set\nsome table options. The general syntax for setting options\nis:\n \n = , [ = ...]\n \nThe equal sign is optional.\n \nSome options are supported by the server and can be used for\nall tables, no matter what storage engine they use; other\noptions can be specified for all storage engines, but have a\nmeaning only for some engines. Also, engines can extend\nCREATE TABLE with new options.\n \nIf the IGNORE_BAD_TABLE_OPTIONS SQL_MODE is enabled, wrong\ntable options generate a warning; otherwise, they generate\nan error.\n \ntable_option: \n [STORAGE] ENGINE [=] engine_name\n | AUTO_INCREMENT [=] value\n | AVG_ROW_LENGTH [=] value\n | [DEFAULT] CHARACTER SET [=] charset_name\n | CHECKSUM [=] {0 | 1}\n | [DEFAULT] COLLATE [=] collation_name\n | COMMENT [=] \'string\'\n | CONNECTION [=] \'connect_string\'\n | DATA DIRECTORY [=] \'absolute path to directory\'\n | DELAY_KEY_WRITE [=] {0 | 1}\n | ENCRYPTED [=] {YES | NO}\n | ENCRYPTION_KEY_ID [=] value\n | IETF_QUOTES [=] {YES | NO}\n | INDEX DIRECTORY [=] \'absolute path to directory\'\n | INSERT_METHOD [=] { NO | FIRST | LAST }\n | KEY_BLOCK_SIZE [=] value\n | MAX_ROWS [=] value\n | MIN_ROWS [=] value\n | PACK_KEYS [=] {0 | 1 | DEFAULT}\n | PAGE_CHECKSUM [=] {0 | 1}\n | PAGE_COMPRESSED [=] {0 | 1}\n | PAGE_COMPRESSION_LEVEL [=] {0 .. 9}\n | PASSWORD [=] \'string\'\n | ROW_FORMAT [=]\n{DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT|PAGE}\n | SEQUENCE [=] {0|1}\n | STATS_AUTO_RECALC [=] {DEFAULT|0|1}\n | STATS_PERSISTENT [=] {DEFAULT|0|1}\n | STATS_SAMPLE_PAGES [=] {DEFAULT|value}\n | TABLESPACE tablespace_name\n | TRANSACTIONAL [=] {0 | 1}\n | UNION [=] (tbl_name[,tbl_name]...)\n | WITH SYSTEM VERSIONING\n \n[STORAGE] ENGINE\n \n[STORAGE] ENGINE specifies a storage engine for the table.\nIf this option is not used, the default storage engine is\nused instead. That is, the default_storage_engine session option\nvalue if it is set, or the value specified for the\n--default-storage-engine mysqld startup options, or InnoDB.\nIf the specified storage engine is not installed and active,\nthe default value will be used, unless the\nNO_ENGINE_SUBSTITUTION SQL MODE is set (default since\nMariaDB 10.0). This is only true for CREATE TABLE, not for\nALTER TABLE. For a list of storage engines that are present\nin your server, issue a SHOW ENGINES.\n \nAUTO_INCREMENT\n \nAUTO_INCREMENT specifies the initial value for the\nAUTO_INCREMENT primary key. This works for MyISAM, Aria,\nInnoDB/XtraDB, MEMORY, and ARCHIVE tables. You can change\nthis option with ALTER TABLE, but in that case the new value\nmust be higher than the highest value which is present in\nthe AUTO_INCREMENT column. If the storage engine does not\nsupport this option, you can insert (and then delete) a row\nhaving the wanted value - 1 in the AUTO_INCREMENT column.\n \nAVG_ROW_LENGTH\n \nAVG_ROW_LENGTH is the average rows size. It only applies to\ntables using MyISAM and Aria storage engines that have the\nROW_FORMAT table option set to FIXED format.\n \nMyISAM uses MAX_ROWS and AVG_ROW_LENGTH to decide the\nmaximum size of a table (default: 256TB, or the maximum file\nsize allowed by the system).\n \n[DEFAULT] CHARACTER SET/CHARSET\n \n[DEFAULT] CHARACTER SET (or [DEFAULT] CHARSET) is used to\nset a default character set for the table. This is the\ncharacter set used for all columns where an explicit\ncharacter set is not specified. If this option is omitted or\nDEFAULT is specified, database\'s default character set will\nbe used. See Setting Character Sets and Collations for\ndetails on setting the character sets.\n \nCHECKSUM/TABLE_CHECKSUM\n \nCHECKSUM (or TABLE_CHECKSUM) can be set to 1 to maintain a\nlive checksum for all table\'s rows. This makes write\noperations slower, but CHECKSUM TABLE will be very fast.\nThis option is only supported for MyISAM and Aria tables.\n \n[DEFAULT] COLLATE\n \n[DEFAULT] COLLATE is used to set a default collation for the\ntable. This is the collation used for all columns where an\nexplicit character set is not specified. If this option is\nomitted or DEFAULT is specified, database\'s default option\nwill be used. See Setting Character Sets and Collations for\ndetails on setting the collations\n \nCOMMENT\n \nCOMMENT is a comment for the table. Maximum length is 2048\ncharacters (before mariaDB 5.5 it was 60 characters). Also\nused to define table parameters when creating a Spider\ntable.\n \nCONNECTION\n \nCONNECTION is used to specify a server name or a connection\nstring for a Spider, CONNECT, Federated or FederatedX table.\n \nDATA DIRECTORY/INDEX DIRECTORY\n \nDATA DIRECTORY and INDEX DIRECTORY were only supported for\nMyISAM and Aria, before MariaDB 5.5. Since 5.5, DATA\nDIRECTORY has also been supported by InnoDB if the\ninnodb_file_per_table server system variable is enabled, but\nonly in CREATE TABLE, not in ALTER TABLE. So, carefully\nchoose a path for InnoDB tables at creation time, because it\ncannot be changed without dropping and re-creating the\ntable. These options specify the paths for data files and\nindex files, respectively. If these options are omitted, the\ndatabase\'s directory will be used to store data files and\nindex files. Note that these table options do not work for\npartitioned tables (use the partition options instead), or\nif the server has been invoked with the\n--skip-symbolic-links startup option. To avoid the\noverwriting of old files with the same name that could be\npresent in the directories, you can use the\n--keep_files_on_create option (an error will be issued if\nfiles already exist). These options are ignored if the\nNO_DIR_IN_CREATE SQL_MODE is enabled (useful for replication\nslaves). Also note that symbolic links cannot be used for\nInnoDB tables.\n \nDATA DIRECTORY works by creating symlinks from where the\ntable would normally have been (inside the datadir) to where\nthe option specifies. For security reasons, to avoid\nbypassing the privilege system, the server does not permit\nsymlinks inside the datadir. Therefore, DATA DIRECTORY\ncannot be used to specify a location inside the datadir. An\nattempt to do so will result in an error 1210 (HY000)\nIncorrect arguments to DATA DIRECTORY.\n \nDELAY_KEY_WRITE\n \nDELAY_KEY_WRITE is supported by MyISAM and Aria, and can be\nset to 1 to speed up write operations. In that case, when\ndata are modified, the indexes are not updated until the\ntable is closed. Writing the changes to the index file\naltogether can be much faster. However, note that this\noption is applied only if the delay_key_write server\nvariable is set to \'ON\'. If it is \'OFF\' the delayed\nindex writes are always disabled, and if it is \'ALL\' the\ndelayed index writes are always used, disregarding the value\nof DELAY_KEY_WRITE.\n \nENCRYPTED\n \nThe ENCRYPTED table option was added in MariaDB 10.1.4\n \nThe ENCRYPTED table option can be used to manually set the\nencryption status of an InnoDB table. See InnoDB / XtraDB\nEncryption for more information.\n \nAria does not currently support the ENCRYPTED table option.\nSee MDEV-18049 about that.\n \nSee Data-at-Rest Encryption for more information.\n \nENCRYPTION_KEY_ID\n \nThe ENCRYPTION_KEY_ID table option was added in MariaDB\n10.1.4\n \nThe ENCRYPTION_KEY_ID table option can be used to manually\nset the encryption key of an InnoDB table. See InnoDB /\nXtraDB Encryption for more information.\n \nAria does not currently support the ENCRYPTION_KEY_ID table\noption. See MDEV-18049 about that.\n \nSee Data-at-Rest Encryption for more information.\n \nIETF_QUOTES\n \nThe IETF_QUOTES option was added in MariaDB 10.1.8\n \nFor the CSV storage engine, the IETF_QUOTES option, when set\nto YES, enables IETF-compatible parsing of embedded quote\nand comma characters. Enabling this option for a table\nimproves compatibility with other tools that use CSV, but is\nnot compatible with MySQL CSV tables, or MariaDB CSV tables\ncreated without this option. Disabled by default.\n \nINSERT_METHOD\n \nINSERT_METHOD is only used with MERGE tables. This option\ndetermines in which underlying table the new rows should be\ninserted. If you set it to \'NO\' (which is the default) no\nnew rows can be added to the table (but you will still be\nable to perform INSERTs directly against the underlying\ntables). FIRST means that the rows are inserted into the\nfirst table, and LAST means that thet are inserted into the\nlast table.\n \nKEY_BLOCK_SIZE\n \nKEY_BLOCK_SIZE is used to determine the size of key blocks,\nin bytes or kilobytes. However, this value is just a hint,\nand the storage engine could modify or ignore it. If\nKEY_BLOCK_SIZE is set to 0, the storage engine\'s default\nvalue will be used.\n \nWith the InnoDB storage engine, if you specify a non-zero\nvalue for the KEY_BLOCK_SIZE table option for the whole\ntable, then the table will implicitly be created with the\nROW_FORMAT table option set to COMPRESSED.\n \nMIN_ROWS/MAX_ROWS\n \nMIN_ROWS and MAX_ROWS let the storage engine know how many\nrows you are planning to store as a minimum and as a\nmaximum. These values will not be used as real limits, but\nthey help the storage engine to optimize the table. MIN_ROWS\nis only used by MEMORY storage engine to decide the minimum\nmemory that is always allocated. MAX_ROWS is used to decide\nthe minimum size for indexes.\n \nPACK_KEYS\n \nPACK_KEYS can be used to determine whether the indexes will\nbe compressed. Set it to 1 to compress all keys. With a\nvalue of 0, compression will not be used. With the DEFAULT\nvalue, only long strings will be compressed. Uncompressed\nkeys are faster.\n \nPAGE_CHECKSUM\n \nPAGE_CHECKSUM is only applicable to Aria tables, and\ndetermines whether indexes and data should use page\nchecksums for extra safety. \n \nPAGE_COMPRESSED\n \nPAGE_COMPRESSED is used to enable InnoDB page compression\nfor InnoDB tables.\n \nPAGE_COMPRESSION_LEVEL\n \nPAGE_COMPRESSION_LEVEL is used to set the compression level\nfor InnoDB page compression for InnoDB tables. The table\nmust also have the PAGE_COMPRESSED table option set to 1.\n \nValid values for PAGE_COMPRESSION_LEVEL are 1 (the best\nspeed) through 9 (the best compression), .\n \nPASSWORD\n \nPASSWORD is unused.\n \nRAID_TYPE\n \nRAID_TYPE is an obsolete option, as the raid support has\nbeen disabled since MySQL 5.0.\n \nROW_FORMAT\n \nThe ROW_FORMAT table option specifies the row format for the\ndata file. Possible values are engine-dependent.\n \nSupported MyISAM Row Formats\n \nFor MyISAM, the supported row formats are: \nFIXED\nDYNAMIC\nCOMPRESSED\n \nThe COMPRESSED row format can only be set by the myisampack\ncommand line tool.\n \nSee MyISAM Storage Formats for more information.\n \nSupported Aria Row Formats\n \nFor Aria, the supported row formats are:\nPAGE\nFIXED\nDYNAMIC.\n \nSee Aria Storage Formats for more information.\n \nSupported InnoDB Row Formats\n \nFor InnoDB/XtraDB, the supported row formats are:\nCOMPACT\nREDUNDANT\nCOMPRESSED\nDYNAMIC.\n \nIf the ROW_FORMAT table option is set to FIXED for an InnoDB\ntable, then the server will either return an error or a\nwarning depending on the value of the innodb_strict_mode\nsystem variable. If the innodb_strict_mode system variable\nis set to OFF, then a warning is issued, and MariaDB will\ncreate the table using the default row format for the\nspecific MariaDB server version. If the innodb_strict_mode\nsystem variable is set to ON, then an error will be raised.\n \nSee XtraDB/InnoDB Storage Formats for more information.\n \nOther Storage Engines and ROW_FORMAT\n \nOther storage engines do not support the ROW_FORMAT table\noption.\n \nSEQUENCE\n \nIf the table is a sequence, then it will have the SEQUENCE\nset to 1.\n \nSTATS_AUTO_RECALC\n \nSTATS_AUTO_RECALC is available only in MariaDB 10.0+. It\nindicates whether to automatically recalculate persistent\nstatistics (see STATS_PERSISTENT, below) for an InnoDB\ntable.\nIf set to 1, statistics will be recalculated when more than\n10% of the data has changed. When set to 0, stats will be\nrecalculated only when an ANALYZE TABLE is run. If set to\nDEFAULT, or left out, the value set by the\ninnodb_stats_auto_recalc system variable applies. See InnoDB\nPersistent Statistics.\n \nSTATS_PERSISTENT\n \nSTATS_PERSISTENT is available only in MariaDB 10.0+. It\nindicates whether the InnoDB statistics created by ANALYZE\nTABLE will remain on disk or not. It can be set to 1 (on\ndisk), 0 (not on disk, the pre-MariaDB 10 behavior), or\nDEFAULT (the same as leaving out the option), in which case\nthe value set by the innodb_stats_persistent system variable\nwill apply. Persistent statistics stored on disk allow the\nstatistics to survive server restarts, and provide better\nquery plan stability. See InnoDB Persistent Statistics.\n \nSTATS_SAMPLE_PAGES\n \nSTATS_SAMPLE_PAGES is available only in MariaDB 10.0+. It\nindicates how many pages are used to sample index\nstatistics. If 0 or DEFAULT, the default value, the\ninnodb_stats_sample_pages value is used. See InnoDB\nPersistent Statistics.\n \nTRANSACTIONAL\n \nTRANSACTIONAL is only applicable for Aria tables. In future\nAria tables created with this option will be fully\ntransactional, but currently this provides a form of crash\nprotection. See Aria Storage Engine for more details.\n \nUNION\n \nUNION must be specified when you create a MERGE table. This\noption contains a comma-separated list of MyISAM tables\nwhich are accessed by the new table. The list is enclosed\nbetween parenthesis. Example: UNION = (t1,t2)\n \nWITH SYSTEM VERSIONING\n \nWITH SYSTEM VERSIONING is used for creating System-versioned\ntables.\n \nPartitions\n \npartition_options:\n PARTITION BY\n { [LINEAR] HASH(expr)\n | [LINEAR] KEY(column_list)\n | RANGE(expr)\n | LIST(expr)\n | SYSTEM_TIME [INTERVAL time_quantity time_unit] [LIMIT\nnum] }\n [PARTITIONS num]\n [SUBPARTITION BY\n { [LINEAR] HASH(expr)\n | [LINEAR] KEY(column_list) }\n [SUBPARTITIONS num]\n ]\n [(partition_definition [, partition_definition] ...)]\n \npartition_definition:\n PARTITION partition_name\n [VALUES {LESS THAN {(expr) | MAXVALUE} | IN (value_list)}]\n [[STORAGE] ENGINE [=] engine_name]\n [COMMENT [=] \'comment_text\' ]\n [DATA DIRECTORY [=] \'data_dir\']\n [INDEX DIRECTORY [=] \'index_dir\']\n [MAX_ROWS [=] max_number_of_rows]\n [MIN_ROWS [=] min_number_of_rows]\n [TABLESPACE [=] tablespace_name]\n [NODEGROUP [=] node_group_id]\n [(subpartition_definition [, subpartition_definition] ...)]\n \nsubpartition_definition:\n SUBPARTITION logical_name\n [[STORAGE] ENGINE [=] engine_name]\n [COMMENT [=] \'comment_text\' ]\n [DATA DIRECTORY [=] \'data_dir\']\n [INDEX DIRECTORY [=] \'index_dir\']\n [MAX_ROWS [=] max_number_of_rows]\n [MIN_ROWS [=] min_number_of_rows]\n [TABLESPACE [=] tablespace_name]\n [NODEGROUP [=] node_group_id]\nIf the PARTITION BY clause is used, the table will be\npartitioned. A partition method must be explicitly indicated\nfor partitions and subpartitions. Partition methods are:\n[LINEAR] HASH creates a hash key which will be used to read\nand write rows. The partition function can be any valid SQL\nexpression which returns an INTEGER number. Thus, it is\npossible to use the HASH method on an integer column, or on\nfunctions which accept integer columns as an argument.\nHowever, VALUES LESS THAN and VALUES IN clauses can not be\nused with HASH. An example:\n \nCREATE TABLE t1 (a INT, b CHAR(5), c DATETIME)\n PARTITION BY HASH ( YEAR(c) );\n \n [LINEAR] HASH can be used for subpartitions, too.\n[LINEAR] KEY is similar to HASH, but the index has an even\ndistribution of data. Also, the expression can only be a\ncolumn or a list of columns. VALUES LESS THAN and VALUES IN\nclauses can not be used with KEY.\nRANGE partitions the rows using on a range of values, using\nthe VALUES LESS THAN operator. VALUES IN is not allowed with\nRANGE. The partition function can be any valid SQL\nexpression which returns a single value.\nLIST assignes partitions based on a table\'s column with a\nrestricted set of possible values. It is similar to RANGE,\nbut VALUES IN must be used for at least 1 columns, and\nVALUES LESS THAN is disallowed.\nSYSTEM_TIME partitioning is used for System-versioned tables\nto store historical data separately from current data.\n \nOnly HASH and KEY can be used for subpartitions, and they\ncan be [LINEAR].\n \nIt is possible to define up to 1024 partitions and\nsubpartitions.\n \nThe number of defined partitions can be optionally specified\nas PARTITION count. This can be done to avoid specifying all\npartitions individually. But you can also declare each\nindividual partition and, additionally, specify a PARTITIONS\ncount clause; in the case, the number of PARTITIONs must\nequal count.\n \nAlso see Partitioning Types Overview.\n \nSequences\n \nCREATE TABLE can also be used to create a SEQUENCE. See\nCREATE SEQUENCE and Sequence Overview.\n \nExamples\n-------- \ncreate table if not exists test (\na bigint auto_increment primary key,\nname varchar(128) charset utf8,\nkey name (name(32))\n) engine=InnoDB default charset latin1;\n \nThis example shows a couple of things:\nUsage of IF NOT EXISTS; If the table already existed, it\nwill not be created. There will not be any error for the\nclient, just a warning.\nHow to create a PRIMARY KEY that is automatically generated.\nHow to specify a table-specific character set and another\nfor a column.\nHow to create an index (name) that is only partly indexed\n(to save space).\n \nThe following clauses will work from MariaDB 10.2.1 only.\n \nCREATE TABLE t1(\n a int DEFAULT (1+1),\n b int DEFAULT (a+1),\n expires DATETIME DEFAULT(NOW() + INTERVAL 1 YEAR),\n x BLOB DEFAULT USER()\n);\n \n\n\nURL: https://mariadb.com/kb/en/library/create-table/') WHERE help_topic_id = 660; +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (661,39,'CREATE TABLESPACE','The CREATE TABLESPACE statement is not supported by MariaDB.\nIt was originally inherited from MySQL NDB Cluster. In MySQL\n5.7 and later, the statement is also supported for InnoDB.\nHowever, MariaDB has chosen not to include that specific\nfeature. See MDEV-19294 for more information.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/create-tablespace/','','https://mariadb.com/kb/en/library/create-tablespace/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (662,39,'CREATE TRIGGER','Syntax\n------ \nCREATE [OR REPLACE]\n [DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]\n TRIGGER [IF NOT EXISTS] trigger_name trigger_time\ntrigger_event\n ON tbl_name FOR EACH ROW\n [{ FOLLOWS | PRECEDES } other_trigger_name ]\n trigger_stmt\n \nDescription\n----------- \nThis statement creates a new trigger. A trigger is a named\ndatabase\nobject that is associated with a table, and that activates\nwhen a\nparticular event occurs for the table. The trigger becomes\nassociated\nwith the table named tbl_name, which must refer to a\npermanent table.\nYou cannot associate a trigger with a TEMPORARY table or a\nview.\n \nCREATE TRIGGER requires the TRIGGER privilege for the table\nassociated\nwith the trigger. (Before MySQL 5.1.6, this statement\nrequires the\nSUPER privilege.)\n \nYou can have multiple triggers for the same trigger_time and\ntrigger_event.\n \nFor valid identifiers to use as trigger names, see\nIdentifier Names.\n \nOR REPLACE\n \nIf used and the trigger already exists, instead of an error\nbeing returned, the existing trigger will be dropped and\nreplaced by the newly defined trigger.\n \nDEFINER\n \nThe DEFINER clause determines the security context to be\nused when\nchecking access privileges at trigger activation time.\n \nIF NOT EXISTS\n \nIf the IF NOT EXISTS clause is used, the trigger will only\nbe created if a trigger of the same name does not exist. If\nthe trigger already exists, by default a warning will be\nreturned.\n \ntrigger_time\n \ntrigger_time is the trigger action time. It can be BEFORE or\nAFTER to\nindicate that the trigger activates before or after each row\nto be\nmodified.\n \ntrigger_event\n \ntrigger_event indicates the kind of statement that activates\nthe\ntrigger. The trigger_event can be one of the following:\nINSERT: The trigger is activated whenever a new row is\ninserted into the table; for example, through INSERT, LOAD\nDATA, and REPLACE statements.\nUPDATE: The trigger is activated whenever a row is modified;\nfor example, through UPDATE statements.\nDELETE: The trigger is activated whenever a row is deleted\nfrom the table; for example, through DELETE and REPLACE\nstatements. However, DROP TABLE and TRUNCATE statements on\nthe table do not activate this trigger, because they do not\nuse DELETE. Dropping a partition does not activate DELETE\ntriggers, either.\n \nFOLLOWS/PRECEDES other_trigger_name\n \nThe FOLLOWS other_trigger_name and PRECEDES\nother_trigger_name options were added in MariaDB 10.2.3 as\npart of supporting multiple triggers per action time.\nThis is the same syntax used by MySQL 5.7, although MySQL\n5.7 does not have multi-trigger support.\n \nFOLLOWS adds the new trigger after another trigger while\nPRECEDES adds the new trigger before another trigger. If\nneither option is used, the new trigger is added last for\nthe given action and time.\n \nFOLLOWS and PRECEDES are not stored in the trigger\ndefinition. However the trigger order is guaranteed to not\nchange over time. mysqldump and other backup methods will\nnot change trigger order.\nYou can verify the trigger order from the ACTION_ORDER\ncolumn in INFORMATION_SCHEMA.TRIGGERS table.\n \nSELECT trigger_name, action_order FROM\ninformation_schema.triggers \n WHERE event_object_table=\'t1\';\n \nExamples\n-------- \nCREATE DEFINER=`root`@`localhost` TRIGGER increment_animal\n AFTER INSERT ON animals FOR EACH ROW \n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+1;\n \nOR REPLACE and IF NOT EXISTS\n \nCREATE DEFINER=`root`@`localhost` TRIGGER increment_animal\n AFTER INSERT ON animals FOR EACH ROW\n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+1;\n \nERROR 1359 (HY000): Trigger already exists\n \nCREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER\nincrement_animal\n AFTER INSERT ON animals FOR EACH ROW\n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+1;\n \nQuery OK, 0 rows affected (0.12 sec)\n \nCREATE DEFINER=`root`@`localhost` TRIGGER IF NOT EXISTS\nincrement_animal\n AFTER INSERT ON animals FOR EACH ROW\n UPDATE animal_count SET animal_count.animals =\nanimal_count.animals+1;\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+------------------------+\n| Level | Code | Message |\n+-------+------+------------------------+\n| Note | 1359 | Trigger already exists |\n+-------+------+------------------------+\n1 row in set (0.00 sec)\n \n\n\nURL: https://mariadb.com/kb/en/library/create-trigger/','','https://mariadb.com/kb/en/library/create-trigger/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (663,39,'CREATE VIEW','Syntax\n------ \nCREATE\n [OR REPLACE]\n [ALGORITHM = {UNDEFINED | MERGE | TEMPTABLE}]\n [DEFINER = { user | CURRENT_USER | role | CURRENT_ROLE }]\n [SQL SECURITY { DEFINER | INVOKER }]\n VIEW [IF NOT EXISTS] view_name [(column_list)]\n AS select_statement\n [WITH [CASCADED | LOCAL] CHECK OPTION]\n \nDescription\n----------- \nThe CREATE VIEW statement creates a new view, or replaces an\nexisting\none if the OR REPLACE clause is given. If the view does not\nexist, CREATE OR\nREPLACE VIEW is the same as CREATE VIEW. If the view does\nexist, CREATE OR\nREPLACE VIEW is the same as ALTER VIEW.\n \nThe select_statement is a SELECT statement that provides the\ndefinition of\nthe view. (When you select from the view, you select in\neffect using the SELECT\nstatement.) select_statement can select from base tables or\nother views.\n \nThe view definition is \"frozen\" at creation time, so\nchanges to the underlying\ntables afterwards do not affect the view definition. For\nexample, if a view is\ndefined as SELECT * on a table, new columns added to the\ntable later do not\nbecome part of the view. A SHOW CREATE VIEW shows that\nsuch queries are rewritten and column names are included in\nthe view\ndefinition.\n \nThe view definition must be a query that does not return\nerrors at view\ncreation times. However, the base tables used by the views\nmight be altered\nlater and the query may not be valid anymore. In this case,\nquerying the view\nwill result in an error. CHECK TABLE helps in finding this\nkind\nof problems.\n \nThe ALGORITHM clause affects how MariaDB processes the\nview. The DEFINER and SQL SECURITY clauses specify the\nsecurity context to be\nused when checking access privileges at view invocation\ntime. The WITH CHECK\nOPTION clause can be given to constrain inserts or updates\nto rows in tables\nreferenced by the view. These clauses are described later in\nthis section.\n \nThe CREATE VIEW statement requires the CREATE VIEW privilege\nfor the\nview, and some privilege for each column selected by the\nSELECT\nstatement. For columns used elsewhere in the SELECT\nstatement you must\nhave the SELECT privilege. If the OR REPLACE clause is\npresent, you\nmust also have the DROP privilege for the view.\n \nA view belongs to a database. By default, a new view is\ncreated in the\ndefault database. To create the view explicitly in a given\ndatabase,\nspecify the name as db_name.view_name when you create it.\n \nCREATE VIEW test.v AS SELECT * FROM t;\n \nBase tables and views share the same namespace within a\ndatabase, so a\ndatabase cannot contain a base table and a view that have\nthe same\nname.\n \nViews must have unique column names with no duplicates, just\nlike base\ntables. By default, the names of the columns retrieved by\nthe SELECT\nstatement are used for the view column names. To define\nexplicit names\nfor the view columns, the optional column_list clause can be\ngiven as\na list of comma-separated identifiers. The number of names\nin\ncolumn_list must be the same as the number of columns\nretrieved by the\nSELECT statement.\n \nMySQL until 5.1.28\n \nPrior to MySQL 5.1.29, When you modify an existing view, the\ncurrent view definition is backed up and saved. It is stored\nin that\ntable\'s database directory, in a subdirectory named arc.\nThe backup\nfile for a view v is named v.frm-00001. If you alter the\nview again,\nthe next backup is named v.frm-00002. The three latest view\nbackup\ndefinitions are stored. Backed up view definitions are not\npreserved\nby mysqldump, or any other such programs, but you can retain\nthem\nusing a file copy operation. However, they are not needed\nfor anything\nbut to provide you with a backup of your previous view\ndefinition. It\nis safe to remove these backup definitions, but only while\nmysqld is\nnot running. If you delete the arc subdirectory or its files\nwhile\nmysqld is running, you will receive an error the next time\nyou try to\nalter the view: \n \nMariaDB [test]> ALTER VIEW v AS SELECT * FROM t; \nERROR 6 (HY000): Error on delete of\n\'.\\test\\arc/v.frm-0004\' (Errcode: 2)\n \nColumns retrieved by the SELECT statement can be simple\nreferences to\ntable columns. They can also be expressions that use\nfunctions,\nconstant values, operators, and so forth.\n \nUnqualified table or view names in the SELECT statement are\ninterpreted with respect to the default database. A view can\nrefer to\ntables or views in other databases by qualifying the table\nor view\nname with the proper database name.\n \nA view can be created from many kinds of SELECT statements.\nIt can\nrefer to base tables or other views. It can use joins,\nUNION, and\nsubqueries. The SELECT need not even refer to any tables.\nThe\nfollowing example defines a view that selects two columns\nfrom another\ntable, as well as an expression calculated from those\ncolumns:\n \nCREATE TABLE t (qty INT, price INT);\n \nINSERT INTO t VALUES(3, 50);\n \nCREATE VIEW v AS SELECT qty, price, qty*price AS value FROM\nt;\n \nSELECT * FROM v;\n+------+-------+-------+\n| qty | price | value |\n+------+-------+-------+\n| 3 | 50 | 150 |\n+------+-------+-------+\n \nA view definition is subject to the following restrictions:\nThe SELECT statement cannot contain a subquery in the FROM\nclause.\nThe SELECT statement cannot refer to system or user\nvariables.\nWithin a stored program, the definition cannot refer to\nprogram parameters or local variables.\nThe SELECT statement cannot refer to prepared statement\nparameters.\nAny table or view referred to in the definition must exist.\nHowever, after a view has been created, it is possible to\ndrop a table or view that the definition refers to. In this\ncase, use of the view results in an error. To check a view\ndefinition for problems of this kind, use the CHECK TABLE\nstatement.\nThe definition cannot refer to a TEMPORARY table, and you\ncannot create a TEMPORARY view.\nAny tables named in the view definition must exist at\ndefinition time.\nYou cannot associate a trigger with a view.\nFor valid identifiers to use as view names, see Identifier\nNames.\n \nORDER BY is allowed in a view definition, but it is ignored\nif you\nselect from a view using a statement that has its own ORDER\nBY.\n \nFor other options or clauses in the definition, they are\nadded to the\noptions or clauses of the statement that references the\nview, but the\neffect is undefined. For example, if a view definition\nincludes a\nLIMIT clause, and you select from the view using a statement\nthat has\nits own LIMIT clause, it is undefined which limit applies.\nThis same\nprinciple applies to options such as ALL, DISTINCT, or\nSQL_SMALL_RESULT that follow the SELECT keyword, and to\nclauses such\nas INTO, FOR UPDATE, and LOCK IN SHARE MODE.\n \nThe PROCEDURE clause cannot be used in a view definition,\nand it cannot be used if a view is referenced in the FROM\nclause.\n \nIf you create a view and then change the query processing\nenvironment\nby changing system variables, that may affect the results\nthat you get\nfrom the view:\n \nCREATE VIEW v (mycol) AS SELECT \'abc\';\n \nSET sql_mode = \'\';\n \nSELECT \"mycol\" FROM v;\n+-------+\n| mycol |\n+-------+\n| mycol | \n+-------+\n \nSET sql_mode = \'ANSI_QUOTES\';\n \nSELECT \"mycol\" FROM v;\n+-------+\n| mycol |\n+-------+\n| abc | \n+-------+\n \nThe DEFINER and SQL SECURITY clauses determine which MariaDB\naccount to\nuse when checking access privileges for the view when a\nstatement is\nexecuted that references the view. They were added in MySQL\n5.1.2.\nThe legal SQL SECURITY characteristic values are DEFINER and\nINVOKER.\nThese indicate that the required privileges must be held by\nthe user\nwho defined or invoked the view, respectively. The default\nSQL\nSECURITY value is DEFINER.\n \nIf a user value is given for the DEFINER clause, it should\nbe a MariaDB\naccount in \'user_name\'@\'host_name\' format (the same\nformat used in the\nGRANT statement). The user_name and host_name values both\nare\nrequired. The definer can also be given as CURRENT_USER or\nCURRENT_USER(). The default DEFINER value is the user who\nexecutes the\nCREATE VIEW statement. This is the same as specifying\nDEFINER =\nCURRENT_USER explicitly.\n \nIf you specify the DEFINER clause, these rules determine the\nlegal\nDEFINER user values:\nIf you do not have the SUPER privilege, the only legal user\nvalue is your own account, either specified literally or by\nusing CURRENT_USER. You cannot set the definer to some other\naccount.\nIf you have the SUPER privilege, you can specify any\nsyntactically legal account name. If the account does not\nactually exist, a warning is generated.\nIf the SQL SECURITY value is DEFINER but the definer account\ndoes not exist when the view is referenced, an error occurs.\n \nWithin a view definition, CURRENT_USER returns the view\'s\nDEFINER\nvalue by default. Before MySQL 5.1.12, and for views\ndefined with the SQL SECURITY INVOKER characteristic,\nCURRENT_USER\nreturns the account for the view\'s invoker. For information\nabout user\nauditing within views, see\nhttp://dev.mysql.com/doc/refman/5.1/en/account-activity-auditing.html.\n \nWithin a stored routine that is defined with the SQL\nSECURITY DEFINER\ncharacteristic, CURRENT_USER returns the routine\'s DEFINER\nvalue. This\nalso affects a view defined within such a program, if the\nview\ndefinition contains a DEFINER value of CURRENT_USER.\n \nView privileges are checked like this:\nAt view definition time, the view creator must have the\nprivileges needed to use the top-level objects accessed by\nthe view. For example, if the view definition refers to\ntable columns, the creator must have privileges for the\ncolumns, as described previously. If the definition refers\nto a stored function, only the privileges needed to invoke\nthe function can be checked. The privileges required when\nthe function runs can be checked only as it executes: For\ndifferent invocations of the function, different execution\npaths within the function might be taken.\nWhen a view is referenced, privileges for objects accessed\nby the view are checked against the privileges held by the\nview creator or invoker, depending on whether the SQL\nSECURITY characteristic is DEFINER or INVOKER, respectively.\nIf reference to a view causes execution of a stored\nfunction, privilege checking for statements executed within\nthe function depend on whether the function is defined with\na SQL SECURITY characteristic of DEFINER or INVOKER. If the\nsecurity characteristic is DEFINER, the function runs with\nthe privileges of its creator. If the characteristic is\nINVOKER, the function runs with the privileges determined by\nthe view\'s SQL SECURITY characteristic.\n \nMySQL until 5.1.1\n \nPrior to MySQL 5.1.2 (before the DEFINER and SQL SECURITY\nclauses were\nimplemented), privileges required for objects used in a view\nare\nchecked at view creation time.\n \nExample: A view might depend on a stored function, and that\nfunction\nmight invoke other stored routines. For example, the\nfollowing view\ninvokes a stored function f():\n \nCREATE VIEW v AS SELECT * FROM t WHERE t.id = f(t.name);\n \nSuppose that f() contains a statement such as this:\n \nIF name IS NULL then\n CALL p1();\nELSE\n CALL p2();\nEND IF;\n \nThe privileges required for executing statements within f()\nneed to be\nchecked when f() executes. This might mean that privileges\nare needed\nfor p1() or p2(), depending on the execution path within\nf(). Those\nprivileges must be checked at runtime, and the user who must\npossess\nthe privileges is determined by the SQL SECURITY values of\nthe view v\nand the function f().\n \nThe DEFINER and SQL SECURITY clauses for views are\nextensions to\nstandard SQL. In standard SQL, views are handled using the\nrules for\nSQL SECURITY INVOKER.\n \nIf you invoke a view that was created before MySQL 5.1.2, it\nis\ntreated as though it was created with a SQL SECURITY DEFINER\nclause\nand with a DEFINER value that is the same as your account.\nHowever,\nbecause the actual definer is unknown, MySQL issues a\nwarning. To make\nthe warning go away, it is sufficient to re-create the view\nso that\nthe view definition includes a DEFINER clause.\n \nThe optional ALGORITHM clause is an extension to standard\nSQL. It\naffects how MariaDB processes the view. ALGORITHM takes\nthree values:\nMERGE, TEMPTABLE, or UNDEFINED. The default algorithm is\nUNDEFINED if\nno ALGORITHM clause is present. See View Algorithms for more\ninformation.\n \nSome views are updatable. That is, you can use them in\nstatements such\nas UPDATE, DELETE, or INSERT to update the contents of the\nunderlying\ntable. For a view to be updatable, there must be a\none-to-one\nrelationship between the rows in the view and the rows in\nthe\nunderlying table. There are also certain other constructs\nthat make a\nview non-updatable. See Inserting and Updating with Views.\n \nWITH CHECK OPTION\n \nThe WITH CHECK OPTION clause can be given for an updatable\nview to\nprevent inserts or updates to rows except those for which\nthe WHERE\nclause in the select_statement is true.\n \nIn a WITH CHECK OPTION clause for an updatable view, the\nLOCAL and\nCASCADED keywords determine the scope of check testing when\nthe view\nis defined in terms of another view. The LOCAL keyword\nrestricts the\nCHECK OPTION only to the view being defined. CASCADED causes\nthe\nchecks for underlying views to be evaluated as well. When\nneither\nkeyword is given, the default is CASCADED.\n \nFor more information about updatable views and the WITH\nCHECK OPTION\nclause, see\nInserting and Updating with Views.\n \nIF NOT EXISTS\n \nThe IF NOT EXISTS clause was added in MariaDB 10.1.3\n \nWhen the IF NOT EXISTS clause is used, MariaDB will return a\nwarning instead of an error if the specified view already\nexists. Cannot be used together with the OR REPLACE clause.\n \nExamples\n-------- \nCREATE TABLE t (a INT, b INT) ENGINE = InnoDB;\n \nINSERT INTO t VALUES (1,1), (2,2), (3,3);\n \nCREATE VIEW v AS SELECT a, a*2 AS a2 FROM t;\n \nSELECT * FROM v;\n \n+------+------+\n| a | a2 |\n+------+------+\n| 1 | 2 |\n| 2 | 4 |\n| 3 | 6 |\n+------+------+\n \nOR REPLACE and IF NOT EXISTS:\n \nCREATE VIEW v AS SELECT a, a*2 AS a2 FROM t;\n \nERROR 1050 (42S01): Table \'v\' already exists\n \nCREATE OR REPLACE VIEW v AS SELECT a, a*2 AS a2 FROM t;\n \nQuery OK, 0 rows affected (0.04 sec)\n \nCREATE VIEW IF NOT EXISTS v AS SELECT a, a*2 AS a2 FROM t;\n \nQuery OK, 0 rows affected, 1 warning (0.01 sec)\n \nSHOW WARNINGS;\n \n+-------+------+--------------------------+\n| Level | Code | Message |\n+-------+------+--------------------------+\n| Note | 1050 | Table \'v\' already exists |\n+-------+------+--------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/create-view/','','https://mariadb.com/kb/en/library/create-view/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (664,39,'DROP DATABASE','Syntax\n------ \nDROP {DATABASE | SCHEMA} [IF EXISTS] db_name\n \nDescription\n----------- \nDROP DATABASE drops all tables in the database and deletes\nthe database. Be very careful with this statement! To use\nDROP DATABASE,\nyou need the DROP privilege on the database. DROP SCHEMA is\na synonym for DROP DATABASE.\n \nImportant: When a database is dropped, user privileges on\nthe database are not automatically dropped. See GRANT.\n \nIF EXISTS\n \nUse IF EXISTS to prevent an error from occurring for\ndatabases that do not exist. A NOTE is generated for each\nnon-existent database when using IF EXISTS. See SHOW\nWARNINGS.\n \nExamples\n-------- \nDROP DATABASE bufg;\n \nQuery OK, 0 rows affected (0.39 sec)\n \nDROP DATABASE bufg;\n \nERROR 1008 (HY000): Can\'t drop database \'bufg\'; database\ndoesn\'t exist\n \n \\W\nShow warnings enabled.\n \nDROP DATABASE IF EXISTS bufg;\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\nNote (Code 1008): Can\'t drop database \'bufg\'; database\ndoesn\'t exist\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-database/','','https://mariadb.com/kb/en/library/drop-database/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (665,39,'DROP EVENT','Syntax\n------ \nDROP EVENT [IF EXISTS] event_name\n \nDescription\n----------- \nThis statement drops the event named event_name. The event\nimmediately\nceases being active, and is deleted completely from the\nserver.\n \nIf the event does not exist, the error\nERROR 1517 (HY000): Unknown event \'event_name\'\nresults. You can override this and cause the\nstatement to generate a NOTE for non-existent events instead\nby using\nIF EXISTS. See SHOW WARNINGS.\n \nThis statement requires the EVENT privilege. In MySQL 5.1.11\nand earlier, an event could be dropped only\nby its definer, or by a user having the SUPER privilege.\n \nExamples\n-------- \nDROP EVENT myevent3;\n \nUsing the IF EXISTS clause:\n \nDROP EVENT IF EXISTS myevent3;\n \nQuery OK, 0 rows affected, 1 warning (0.01 sec)\n \nSHOW WARNINGS;\n \n+-------+------+-------------------------------+\n| Level | Code | Message |\n+-------+------+-------------------------------+\n| Note | 1305 | Event myevent3 does not exist |\n+-------+------+-------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-event/','','https://mariadb.com/kb/en/library/drop-event/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (666,39,'DROP FUNCTION','Syntax\n------ \nDROP FUNCTION [IF EXISTS] f_name\n \nDescription\n----------- \nThe DROP FUNCTION statement is used to drop a stored\nfunction or a user-defined function (UDF). That is, the\nspecified routine is removed from the server, along with all\nprivileges specific to the function. You must have the ALTER\nROUTINE privilege for the routine in order to drop it. If\nthe automatic_sp_privileges server system variable is set,\nboth the ALTER ROUTINE and EXECUTE privileges are granted\nautomatically to the routine creator - see Stored Routine\nPrivileges.\n \nIF EXISTS\n \nThe IF EXISTS clause is a MySQL/MariaDB extension. It\nprevents an error from occurring if the function does not\nexist. A\nNOTE is produced that can be viewed with SHOW WARNINGS.\n \nFor dropping a user-defined functions (UDF), see DROP\nFUNCTION UDF.\n \nExamples\n-------- \nDROP FUNCTION hello;\n \nQuery OK, 0 rows affected (0.042 sec)\n \nDROP FUNCTION hello;\n \nERROR 1305 (42000): FUNCTION test.hello does not exist\n \nDROP FUNCTION IF EXISTS hello;\n \nQuery OK, 0 rows affected, 1 warning (0.000 sec)\n \nSHOW WARNINGS;\n \n+-------+------+------------------------------------+\n| Level | Code | Message |\n+-------+------+------------------------------------+\n| Note | 1305 | FUNCTION test.hello does not exist |\n+-------+------+------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-function/','','https://mariadb.com/kb/en/library/drop-function/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (667,39,'DROP INDEX','Syntax\n------ \nDROP INDEX [IF EXISTS] index_name ON tbl_name \n [WAIT n |NOWAIT]\n [algorithm_option | lock_option] ...\n \nalgorithm_option:\n ALGORITHM [=] {DEFAULT|INPLACE|COPY|NOCOPY|INSTANT}\n \nlock_option:\n LOCK [=] {DEFAULT|NONE|SHARED|EXCLUSIVE}\n \nDescription\n----------- \nDROP INDEX drops the index named index_name from the table\ntbl_name.\nThis statement is mapped to an ALTER TABLE statement to drop\nthe\nindex.\n \nIf another connection is using the table, a metadata lock is\nactive, and this statement will wait until the lock is\nreleased. This is also true for non-transactional tables.\n \nSee ALTER TABLE.\n \nAnother shortcut, CREATE INDEX, allows the creation of an\nindex.\n \nTo remove the primary key, `PRIMARY` must be specified as\nindex_name. Note that the quotes are necessary, because\nPRIMARY is a keyword.\n \nPrivileges\n \nExecuting the DROP INDEX statement requires the INDEX\nprivilege for the table or the database.\n \nOnline DDL\n \nIn MariaDB 10.0 and later, online DDL is supported with the\nALGORITHM and LOCK clauses.\n \nSee InnoDB Online DDL Overview for more information on\nonline DDL with InnoDB.\n \nDROP INDEX IF EXISTS ...\n \nThe IF EXISTS clause was added in MariaDB 10.1.4.\n \nIf the IF EXISTS clause is used, then MariaDB will return a\nwarning instead of an error if the index does not exist.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \nALGORITHM\n \nSee ALTER TABLE: ALGORITHM for more information.\n \nLOCK\n \nSee ALTER TABLE: LOCK for more information.\n \nProgress Reporting\n \nMariaDB provides progress reporting for DROP INDEX statement\nfor clients\nthat support the new progress reporting protocol. For\nexample, if you were using the mysql client, then the\nprogress report might look like this::\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-index/','','https://mariadb.com/kb/en/library/drop-index/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (668,39,'DROP PACKAGE','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nDROP PACKAGE [IF EXISTS] [ db_name . ] package_name\n \nDescription\n----------- \nThe DROP PACKAGE statement can be used when Oracle SQL_MODE\nis set.\n \nThe DROP PACKAGE statement drops a stored package entirely:\nDrops the package specification (earlier created using the\nCREATE PACKAGE statement).\nDrops the package implementation, if the implementation was\nalready created using the CREATE PACKAGE BODY statement.\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-package/','','https://mariadb.com/kb/en/library/drop-package/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (669,39,'DROP PACKAGE BODY','Oracle-style packages were introduced in MariaDB 10.3.5.\n \nSyntax\n------ \nDROP PACKAGE BODY [IF EXISTS] [ db_name . ] package_name\n \nDescription\n----------- \nThe DROP PACKAGE BODY statement can be used when Oracle\nSQL_MODE is set.\n \nThe DROP PACKAGE BODY statement drops the package body (i.e\nthe implementation), previously created using the CREATE\nPACKAGE BODY statement.\n \nNote, DROP PACKAGE BODY drops only the package\nimplementation, but does not drop the package specification.\nUse DROP PACKAGE to drop the package entirely (i.e. both\nimplementation and specification).\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-package-body/','','https://mariadb.com/kb/en/library/drop-package-body/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (670,39,'DROP PROCEDURE','Syntax\n------ \nDROP PROCEDURE [IF EXISTS] sp_name\n \nDescription\n----------- \nThis statement is used to drop a stored procedure. That is,\nthe\nspecified routine is removed from the server along with all\nprivileges specific to the procedure. You must have the\nALTER ROUTINE privilege for the routine. If the\nautomatic_sp_privileges server system variable is set, that\nprivilege and EXECUTE are granted automatically to the\nroutine creator - see Stored Routine Privileges.\n \nThe IF EXISTS clause is a MySQL/MariaDB extension. It\nprevents an error from occurring if the procedure or\nfunction does not exist. A\nNOTE is produced that can be viewed with SHOW WARNINGS.\n \nWhile this statement takes effect immediately, threads which\nare executing a procedure can continue execution.\n \nExamples\n-------- \nDROP PROCEDURE simpleproc;\n \nIF EXISTS:\n \nDROP PROCEDURE simpleproc;\n \nERROR 1305 (42000): PROCEDURE test.simpleproc does not exist\n \nDROP PROCEDURE IF EXISTS simpleproc;\n \nQuery OK, 0 rows affected, 1 warning (0.00 sec)\n \nSHOW WARNINGS;\n \n+-------+------+------------------------------------------+\n| Level | Code | Message |\n+-------+------+------------------------------------------+\n| Note | 1305 | PROCEDURE test.simpleproc does not exist |\n+-------+------+------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-procedure/','','https://mariadb.com/kb/en/library/drop-procedure/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (671,39,'DROP SEQUENCE','DROP SEQUENCE was introduced in MariaDB 10.3.\n \nSyntax\n------ \nDROP [TEMPORARY] SEQUENCE [IF EXISTS] [/*COMMENT TO SAVE*/]\n sequence_name [, sequence_name] ...\n \nDescription\n----------- \nDROP SEQUENCE removes one or more sequences created with\nCREATE SEQUENCE. You must have the DROP privilege for each\nsequence. MariaDB returns an error indicating by name which\nnon-existing tables it was unable to drop, but it also drops\nall of the tables in the list that do exist.\n \nImportant: When a table is dropped, user privileges on the\ntable are not automatically dropped. See GRANT.\n \nIf another connection is using the sequence, a metadata lock\nis active, and this statement will wait until the lock is\nreleased. This is also true for non-transactional tables.\n \nFor each referenced sequence, DROP SEQUENCE drops a\ntemporary sequence with that name, if it exists. If it does\nnot exist, and the TEMPORARY keyword is not used, it drops a\nnon-temporary sequence with the same name, if it exists. The\nTEMPORARY keyword ensures that a non-temporary sequence will\nnot accidentally be dropped.\n \nUse IF EXISTS to prevent an error from occurring for\nsequences that do not exist. A NOTE is generated for each\nnon-existent sequence when using IF EXISTS. See SHOW\nWARNINGS.\n \nDROP SEQUENCE requires the DROP privilege.\n \nNotes\n \nDROP SEQUENCE only removes sequences, not tables. However,\nDROP TABLE can remove both sequences and tables.\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-sequence/','','https://mariadb.com/kb/en/library/drop-sequence/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (672,39,'DROP SERVER','Syntax\n------ \nDROP SERVER [ IF EXISTS ] server_name\n \nDescription\n----------- \nDrops the server definition for the server named\nserver_name. The\ncorresponding row within the mysql.servers table will be\ndeleted. This\nstatement requires the SUPER privilege. \n \nDropping a server for a table does not affect any\nFederatedX, FEDERATED or Spider tables that used this\nconnection information when they were created. \n \nIF EXISTS\n \nIf the IF EXISTS clause is used, MariaDB will not return an\nerror if the server does not exist. Unlike all other\nstatements, DROP SERVER IF EXISTS does not issue a note if\nthe server does not exist. See MDEV-9400.\n \nExamples\n-------- \nDROP SERVER s;\n \nIF EXISTS:\n \nDROP SERVER s;\n \nERROR 1477 (HY000): The foreign server name you are trying\nto reference \n does not exist. Data source error: s\n \nDROP SERVER IF EXISTS s;\n \nQuery OK, 0 rows affected (0.00 sec)\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-server/','','https://mariadb.com/kb/en/library/drop-server/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (673,39,'DROP TABLE','Syntax\n------ \nDROP [TEMPORARY] TABLE [IF EXISTS] [/*COMMENT TO SAVE*/]\n tbl_name [, tbl_name] ...\n [WAIT n|NOWAIT]\n [RESTRICT | CASCADE]\n \nDescription\n----------- \nDROP TABLE removes one or more tables. You must have the\nDROP privilege\nfor each table. All table data and the table definition are\nremoved, as well as triggers associated to the table, so be\ncareful with this statement! If any of the tables named in\nthe argument list do\nnot exist, MariaDB returns an error indicating by name which\nnon-existing tables\nit was unable to drop, but it also drops all of the tables\nin the list that do\nexist.\n \nImportant: When a table is dropped, user privileges on the\ntable are not\nautomatically dropped. See GRANT.\n \nIf another connection is using the table, a metadata lock is\nactive, and this statement will wait until the lock is\nreleased. This is also true for non-transactional tables.\n \nNote that for a partitioned table, DROP TABLE permanently\nremoves the table\ndefinition, all of its partitions, and all of the data which\nwas stored in\nthose partitions. It also removes the partitioning\ndefinition (.par) file\nassociated with the dropped table.\n \nFor each referenced table, DROP TABLE drops a temporary\ntable with that name, if it exists. If it does not exist,\nand the TEMPORARY keyword is not used, it drops a\nnon-temporary table with the same name, if it exists. The\nTEMPORARY keyword ensures that a non-temporary table will\nnot accidentally be dropped.\n \nUse IF EXISTS to prevent an error from occurring for tables\nthat do not\nexist. A NOTE is generated for each non-existent table when\nusing\nIF EXISTS. See SHOW WARNINGS.\n \nIf a foreign key references this table, the table cannot be\ndropped. In this case, it is necessary to drop the foreign\nkey first.\n \nRESTRICT and CASCADE are allowed to make porting from other\ndatabase systems easier. In MariaDB, they do nothing.\n \nSince MariaDB 5.5.27, the comment before the tablenames\n(that /*COMMENT TO SAVE*/) is stored in the binary log. That\nfeature can be used by replication tools to send their\ninternal messages.\n \nIt is possible to specify table names as db_name.tab_name.\nThis is useful to delete tables from multiple databases with\none statement. See Identifier Qualifiers for details.\n \nThe DROP privilege is required to use DROP TABLE on\nnon-temporary tables. For temporary tables, no privilege is\nrequired, because such tables are only visible for the\ncurrent session.\n \nNote: DROP TABLE automatically commits the current active\ntransaction,\nunless you use the TEMPORARY keyword.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \nDROP TABLE in replication\n \nDROP TABLE has the following characteristics in replication:\nDROP TABLE IF EXISTS are always logged.\nDROP TABLE without IF EXISTS for tables that don\'t exist\nare not written to the binary log.\nDropping of TEMPORARY tables are prefixed in the log with\nTEMPORARY. These drops are only logged when running\nstatement or mixed mode replication.\nOne DROP TABLE statement can be logged with up to 3\ndifferent DROP statements:\nDROP TEMPORARY TABLE\nlist_of_non_transactional_temporary_tables\nDROP TEMPORARY TABLE list_of_transactional_temporary_tables\nDROP TABLE list_of_normal_tables\n \nStarting from MariaDB 10.0.8, DROP TABLE on the master is\ntreated on the slave as DROP TABLE IF EXISTS. You can change\nthat by setting slave-ddl-exec-mode to STRICT.\n \nDropping an Internal #sql-... Table\n \nIf the mysqld process is killed during an ALTER TABLE you\nmay find a table named #sql-... in your data directory. In\nMariaDB 10.3, InnoDB tables with this prefix will de deleted\nautomatically during startup.\nIn MariaDB 10.4 we will ensure that these temporary tables\nwill always be deleted automatically.\n \nIf you want to delete one of these tables explicitly you can\ndo so by using the following syntax:\n \nDROP TABLE `#mysql50##sql-...`;\n \nWhen running an ALTER TABLE…ALGORITHM=INPLACE that\nrebuilds the table, InnoDB will create an internal #sql-ib\ntable. For these tables, the .frm file will be called\nsomething else. In order to drop such a table after a server\ncrash, you must rename the #sql*.frm file to match the\n#sql-ib*.ibd file.\n \nExamples\n-------- \nDROP TABLE Employees, Customers;\n \nNotes\n \nBeware that DROP TABLE can drop both tables and sequences.\nThis is mainly done to allow old tools like mysqldump to\nwork with sequences.\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-table/','','https://mariadb.com/kb/en/library/drop-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (674,39,'DROP TABLESPACE','The DROP TABLESPACE statement is not supported by MariaDB.\nIt was originally inherited from MySQL NDB Cluster. In MySQL\n5.7 and later, the statement is also supported for InnoDB.\nHowever, MariaDB has chosen not to include that specific\nfeature. See MDEV-19294 for more information.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/drop-tablespace/','','https://mariadb.com/kb/en/library/drop-tablespace/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (675,39,'DROP TRIGGER','Syntax\n------ \nDROP TRIGGER [IF EXISTS] [schema_name.]trigger_name\n \nDescription\n----------- \nThis statement drops a trigger. The schema (database) name\nis optional. If the\nschema is omitted, the trigger is dropped from the default\nschema.\nIts use requires the TRIGGER privilege for the table\nassociated with the trigger.\n \nUse IF EXISTS to prevent an error from occurring for a\ntrigger that does not exist. A NOTE is generated for a\nnon-existent trigger\nwhen using IF EXISTS. See SHOW WARNINGS.\n \nNote: Triggers for a table are also dropped if you drop the\ntable.\n \nExamples\n-------- \nDROP TRIGGER test.example_trigger;\n \nUsing the IF EXISTS clause:\n \nDROP TRIGGER IF EXISTS test.example_trigger;\n \nQuery OK, 0 rows affected, 1 warning (0.01 sec)\n \nSHOW WARNINGS;\n \n+-------+------+------------------------+\n| Level | Code | Message |\n+-------+------+------------------------+\n| Note | 1360 | Trigger does not exist |\n+-------+------+------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-trigger/','','https://mariadb.com/kb/en/library/drop-trigger/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (676,39,'DROP VIEW','Syntax\n------ \nDROP VIEW [IF EXISTS]\n view_name [, view_name] ...\n [RESTRICT | CASCADE]\n \nDescription\n----------- \nDROP VIEW removes one or more views. You must have the DROP\nprivilege for\neach view. If any of the views named in the argument list do\nnot exist, MariaDB\nreturns an error indicating by name which non-existing views\nit was unable to\ndrop, but it also drops all of the views in the list that do\nexist.\n \nThe IF EXISTS clause prevents an error from occurring for\nviews that don\'t\nexist. When this clause is given, a NOTE is generated for\neach non-existent\nview. See SHOW WARNINGS.\n \nRESTRICT and CASCADE, if given, are parsed and ignored.\n \nIt is possible to specify view names as db_name.view_name.\nThis is useful to delete views from multiple databases with\none statement. See Identifier Qualifiers for details.\n \nThe DROP privilege is required to use DROP TABLE on\nnon-temporary tables. For temporary tables, no privilege is\nrequired, because such tables are only visible for the\ncurrent session.\n \nIf a view references another view, it will be possible to\ndrop the referenced view. However, the other view will\nreference a view which does not exist any more. Thus,\nquerying it will produce an error similar to the following:\n \nERROR 1356 (HY000): View \'db_name.view_name\' references\ninvalid table(s) or \ncolumn(s) or function(s) or definer/invoker of view lack\nrights to use them\n \nThis problem is reported in the output of CHECK TABLE.\n \nNote that it is not necessary to use DROP VIEW to replace an\nexisting view, because CREATE VIEW has an OR REPLACE clause.\n \nExamples\n-------- \nDROP VIEW v,v2;\n \nGiven views v and v2, but no view v3\n \nDROP VIEW v,v2,v3;\nERROR 1051 (42S02): Unknown table \'v3\'\n \nDROP VIEW IF EXISTS v,v2,v3;\nQuery OK, 0 rows affected, 1 warning (0.01 sec)\n \nSHOW WARNINGS;\n+-------+------+-------------------------+\n| Level | Code | Message |\n+-------+------+-------------------------+\n| Note | 1051 | Unknown table \'test.v3\' |\n+-------+------+-------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/drop-view/','','https://mariadb.com/kb/en/library/drop-view/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (677,39,'MERGE','Description\n----------- \nThe MERGE storage engine, also known as the MRG_MyISAM\nengine, is a\ncollection of identical MyISAM tables that can be used as\none.\n\"Identical\" means that all tables have identical column\nand index\ninformation. You cannot merge MyISAM tables in which the\ncolumns are\nlisted in a different order, do not have exactly the same\ncolumns, or\nhave the indexes in different order. However, any or all of\nthe MyISAM\ntables can be compressed with myisampack. Columns names and\nindexes names can be different, as long as data types and\nNULL/NOT NULL clauses are the same. Differences in\ntable options such as AVG_ROW_LENGTH, MAX_ROWS, or PACK_KEYS\ndo not\nmatter.\n \nEach index in a MERGE table must match an index in\nunderlying MyISAM tables, but the opposite is not true.\nAlso, a MERGE table cannot have a PRIMARY KEY or UNIQUE\nindexes, because it cannot enforce uniqueness over all\nunderlying tables.\n \nThe following options are meaningful for MERGE tables:\nUNION. This option specifies the list of the underlying\nMyISAM tables. The list is enclosed between parentheses and\nseparated with commas.\nINSERT_METHOD. This options specifies whether, and how,\nINSERTs are allowed for the table. Allowed values are: NO\n(INSERTs are not allowed), FIRST (new rows will be written\ninto the first table specified in the UNION list), LAST (new\nrows will be written into the last table specified in the\nUNION list). The default value is NO.\n \nIf you define a MERGE table with a definition which is\ndifferent from the underlying MyISAM tables, or one of the\nunderlying tables is not MyISAM, the CREATE TABLE statement\nwill not return any error. But any statement which involves\nthe table will produce an error like the following:\n \nERROR 1168 (HY000): Unable to open underlying table which is\ndifferently defined \n or of non-MyISAM type or doesn\'t exist\n \nA CHECK TABLE will show more information about the problem.\n \nThe error is also produced if the table is properly define,\nbut an underlying table\'s definition changes at some point\nin time.\n \nIf you try to insert a new row into a MERGE table with\nINSERT_METHOD=NO, you will get an error like the following:\n \nERROR 1036 (HY000): Table \'tbl_name\' is read only\n \nIt is possible to build a MERGE table on MyISAM tables which\nhave one or more virtual columns. MERGE itself does not\nsupport virtual columns, thus such columns will be seen as\nregular columns. The data types and sizes will still need to\nbe identical, and they cannot be NOT NULL.\n \nExamples\n-------- \nCREATE TABLE t1 (\n a INT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n message CHAR(20)) ENGINE=MyISAM;\n \nCREATE TABLE t2 (\n a INT NOT NULL AUTO_INCREMENT PRIMARY KEY,\n message CHAR(20)) ENGINE=MyISAM;\n \nINSERT INTO t1 (message) VALUES\n(\'Testing\'),(\'table\'),(\'t1\');\n \nINSERT INTO t2 (message) VALUES\n(\'Testing\'),(\'table\'),(\'t2\');\n \nCREATE TABLE total (\n a INT NOT NULL AUTO_INCREMENT,\n message CHAR(20), INDEX(a))\n ENGINE=MERGE UNION=(t1,t2) INSERT_METHOD=LAST;\n \nSELECT * FROM total;\n \n+---+---------+\n| a | message |\n+---+---------+\n| 1 | Testing |\n| 2 | table |\n| 3 | t1 |\n| 1 | Testing |\n| 2 | table |\n| 3 | t2 |\n+---+---------+\n \nIn the following example, we\'ll create three MyISAM tables,\nand then a MERGE table on them. However, one of them uses a\ndifferent data type for the column b, so a SELECT will\nproduce an error:\n \nCREATE TABLE t1 (\n a INT,\n b INT\n) ENGINE = MyISAM;\n \nCREATE TABLE t2 (\n a INT,\n b INT\n) ENGINE = MyISAM;\n \nCREATE TABLE t3 (\n a INT,\n b TINYINT\n) ENGINE = MyISAM;\n \nCREATE TABLE t_mrg (\n a INT,\n b INT\n) ENGINE = MERGE,UNION=(t1,t2,t3);\n \nSELECT * FROM t_mrg;\n \nERROR 1168 (HY000): Unable to open underlying table which is\ndifferently defined\n or of non-MyISAM type or doesn\'t exist\n \nTo find out what\'s wrong, we\'ll use a CHECK TABLE:\n \nCHECK TABLE t_mrg;\n \n+------------+-------+----------+-----------------------------------------------------------------------------------------------------+\n| Table | Op | Msg_type | Msg_text |\n+------------+-------+----------+-----------------------------------------------------------------------------------------------------+\n| test.t_mrg | check | Error | Table \'test.t3\' is\ndifferently defined or of non-MyISAM type or doesn\'t exist\n|\n| test.t_mrg | check | Error | Unable to open underlying\ntable which is differently defined or of non-MyISAM type or\ndoesn\'t exist |\n| test.t_mrg | check | error | Corrupt |\n+------------+-------+----------+-----------------------------------------------------------------------------------------------------+\n \nNow, we know that the problem is in t3\'s definition.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/merge/','','https://mariadb.com/kb/en/library/merge/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (678,39,'RENAME TABLE','Syntax\n------ \nRENAME TABLE tbl_name \n [WAIT n | NOWAIT]\n TO new_tbl_name\n [, tbl_name2 TO new_tbl_name2] ...\n \nDescription\n----------- \nThis statement renames one or more tables or views, but not\nthe privileges associated to them.\n \nThe rename operation is done atomically, which means that no\nother session can\naccess any of the tables while the rename is running. For\nexample, if you have\nan existing table old_table, you can create another table\nnew_table that has the same structure but is empty, and then\nreplace the existing table with the empty one as follows\n(assuming that\nbackup_table does not already exist):\n \nCREATE TABLE new_table (...);\nRENAME TABLE old_table TO backup_table, new_table TO\nold_table;\n \ntbl_name can optionally be specified as db_name.tbl_name.\nSee Identifier Qualifiers. This allows to use RENAME to move\na table from a database to another (as long as they are on\nthe same filesystem):\n \nRENAME TABLE db1.t TO db2.t;\n \nNote that moving a table to another database is not possible\nif it has some triggers. Trying to do so produces the\nfollowing error:\n \nERROR 1435 (HY000): Trigger in wrong schema\n \nAlso, views cannot be moved to another database:\n \nERROR 1450 (HY000): Changing schema from \'old_db\' to\n\'new_db\' is not allowed.\n \nIf a RENAME TABLE renames more than one table and one\nrenaming fails, all renames executed by the same statement\nare rolled back.\n \nRenames are always executed in the specified order. Knowing\nthis, it is also possible to swap two tables\' names:\n \nRENAME TABLE t1 TO tmp_table,\n t2 TO t1,\n tmp_table TO t2;\n \nPrivileges\n \nExecuting the RENAME TABLE statement requires the DROP,\nCREATE and INSERT privileges for the table or the database.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/rename-table/','','https://mariadb.com/kb/en/library/rename-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (679,39,'TRUNCATE TABLE','Syntax\n------ \nTRUNCATE [TABLE] tbl_name\n [WAIT n | NOWAIT]\n \nDescription\n----------- \nTRUNCATE TABLE empties a table completely. It requires the\nDROP privilege. See GRANT.\n \ntbl_name can also be specified in the form db_name.tbl_name\n(see Identifier Qualifiers).\n \nLogically, TRUNCATE TABLE is equivalent to a DELETE\nstatement that deletes all rows, but there are practical\ndifferences under some circumstances.\n \nTRUNCATE TABLE will fail for an InnoDB table if any FOREIGN\nKEY constraints from other tables reference the table,\nreturning the error:\n \nERROR 1701 (42000): Cannot truncate a table referenced in a\nforeign key constraint\n \nForeign Key constraints between columns in the same table\nare permitted.\n \nFor an InnoDB table, if there are no FOREIGN KEY\nconstraints, InnoDB performs fast truncation by dropping the\noriginal table and creating an empty one with the same\ndefinition, which is much faster than deleting rows one by\none. The AUTO_INCREMENT counter is reset by TRUNCATE TABLE,\nregardless of whether there is a FOREIGN KEY constraint.\n \nThe count of rows affected by TRUNCATE TABLE is accurate\nonly\nwhen it is mapped to a DELETE statement.\n \nFor other storage engines, TRUNCATE TABLE differs from\nDELETE in the following ways:\nTruncate operations drop and re-create the table, which is\nmuch\n faster than deleting rows one by one, particularly for\nlarge tables.\nTruncate operations cause an implicit commit.\nTruncation operations cannot be performed if the session\nholds an\n active table lock.\nTruncation operations do not return a meaningful value for\nthe number\n of deleted rows. The usual result is \"0 rows affected,\"\nwhich should\n be interpreted as \"no information.\"\nAs long as the table format file tbl_name.frm is valid, the\n table can be re-created as an empty table\n with TRUNCATE TABLE, even if the data or index files have\nbecome\n corrupted.\nThe table handler does not remember the last\n used AUTO_INCREMENT value, but starts counting\n from the beginning. This is true even for MyISAM and\nInnoDB, which normally\n do not reuse sequence values.\nWhen used with partitioned tables, TRUNCATE TABLE preserves\n the partitioning; that is, the data and index files are\ndropped and\n re-created, while the partition definitions (.par) file is\n unaffected.\nSince truncation of a table does not make any use of DELETE,\n the TRUNCATE statement does not invoke ON DELETE triggers.\nTRUNCATE TABLE will only reset the values in the Performance\nSchema summary tables to zero or null, and will not remove\nthe rows.\n \nFor the purposes of binary logging and replication, TRUNCATE\nTABLE is treated as DROP TABLE followed by CREATE TABLE (DDL\nrather than DML).\n \nTRUNCATE TABLE does not work on views. Currently, TRUNCATE\nTABLE drops all historical records from a system-versioned\ntable.\n \nWAIT/NOWAIT\n \nSet the lock wait timeout. See WAIT and NOWAIT.\n \nOracle-mode\n \nOracle-mode from MariaDB 10.3 permits the optional keywords\nREUSE STORAGE or DROP STORAGE to be used.\n \nTRUNCATE [TABLE] tbl_name [{DROP | REUSE} STORAGE]\n \nThese have no effect on the operation.\n \nPerformance\n \nTRUNCATE TABLE is faster than DELETE, because it drops and\nre-creates a table.\n \nWith XtraDB/InnoDB, TRUNCATE TABLE is slower if\ninnodb_file_per_table=ON is set (the default since MariaDB\n5.5). This is because TRUNCATE TABLE unlinks the underlying\ntablespace file, which can be an expensive operation. See\nMDEV-8069 for more details.\n \nThe performance issues with innodb_file_per_table=ON can be\nexacerbated in cases where the InnoDB buffer pool is very\nlarge and innodb_adaptive_hash_index=ON is set. In that\ncase, using DROP TABLE followed by CREATE TABLE instead of\nTRUNCATE TABLE may perform better. Setting\ninnodb_adaptive_hash_index=OFF can also help. In MariaDB\n10.2.19 and later, this performance can also be improved by\nsetting innodb_safe_truncate=OFF. See MDEV-9459 for more\ndetails.\n \nSetting innodb_adaptive_hash_index=OFF can also improve\nTRUNCATE TABLE performance in general. See MDEV-16796 for\nmore details.\n \n\n\nURL: https://mariadb.com/kb/en/library/truncate-table/','','https://mariadb.com/kb/en/library/truncate-table/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (680,40,'LASTVAL','LASTVAL is a synonym for PREVIOUS VALUE for sequence_name.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/lastval/','','https://mariadb.com/kb/en/library/lastval/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (681,40,'NEXT VALUE for sequence_name','SEQUENCEs were introduced in MariaDB 10.3\n \nSyntax\n------ \nNEXT VALUE FOR sequence\n \nor\n \nNEXTVAL(sequence_name)\n \nor in Oracle mode (SQL_MODE=ORACLE)\n \nsequence_name.nextval\n \nNEXT VALUE FOR is ANSI SQL syntax while NEXTVAL() is\nPostgreSQL syntax.\n \nDescription\n----------- \nGenerate next value for a SEQUENCE.\nYou can greatly speed up NEXT VALUE by creating the sequence\nwith the CACHE option. If not, every NEXT VALUE usage will\ncause changes in the stored SEQUENCE table.\nWhen using NEXT VALUE the value will be reserved at once and\nwill not be reused, except if the SEQUENCE was created with\nCYCLE. This means that when you are using SEQUENCEs you have\nto expect gaps in the generated sequence numbers.\nIf one updates the SEQUENCE with SETVAL() or ALTER SEQUENCE\n... RESTART, NEXT VALUE FOR will notice this and start from\nthe next requested value.\nFLUSH TABLES will close the sequence and the next sequence\nnumber generated will be according to what\'s stored in the\nSEQUENCE object. In effect, this will discard the cached\nvalues.\nNEXT VALUE requires the INSERT privilege.\n \nYou can also use NEXT VALUE FOR sequence for column DEFAULT.\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/next-value-for-sequence_name/','','https://mariadb.com/kb/en/library/next-value-for-sequence_name/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (682,40,'NEXTVAL','NEXTVAL is a synonym for NEXT VALUE for sequence_name.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/library/nextval/','','https://mariadb.com/kb/en/library/nextval/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (683,40,'PREVIOUS VALUE FOR sequence_name','SEQUENCEs were introduced in MariaDB 10.3.\n \nSyntax\n------ \nPREVIOUS VALUE FOR sequence_name\n \nor\n \nLASTVAL(sequence_name)\n \nor in Oracle mode (SQL_MODE=ORACLE)\n \nsequence_name.currval\n \nPREVIOUS VALUE FOR is IBM DB2 syntax while LASTVAL() is\nPostgreSQL syntax.\n \nDescription\n----------- \nGet last value in the current connection generated from a\nsequence.\nIf the sequence has not yet been used by the connection,\nPREVIOUS VALUE FOR returns NULL\nIf a SEQUENCE has been dropped and re-created then it\'s\ntreated as a new SEQUENCE and PREVIOUS VALUE FOR will return\nNULL.\nFLUSH TABLES has no effect on PREVIOUS VALUE FOR.\nPrevious values for all used sequences are stored per\nconnection until connection ends.\n \nPREVIOUS VALUE FOR requires the SELECT privilege.\n \nExample\n \nSELECT PREVIOUS VALUE FOR s;\n \n+----------------------+\n| PREVIOUS VALUE FOR s |\n+----------------------+\n| 100 |\n+----------------------+\n \n\n\nURL:\nhttps://mariadb.com/kb/en/library/previous-value-for-sequence_name/','','https://mariadb.com/kb/en/library/previous-value-for-sequence_name/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (684,40,'Sequence Overview','Sequences were introduced in MariaDB 10.3.\n \nIntroduction\n \nA sequence is an object that generates a sequence of numeric\nvalues, as specified by the CREATE SEQUENCE statement. \n \nCREATE SEQUENCE will create a sequence that generates new\nvalues when called with NEXT VALUE FOR sequence_name. It\'s\nan alternative to AUTO INCREMENT when one wants to have more\ncontrol of how the numbers are generated. As the SEQUENCE\ncaches values (up to the CACHE value in the CREATE SEQUENCE\nstatement, by default 1000) it can in some cases be much\nfaster than AUTO INCREMENT. Another benefit is that one can\naccess the last value generated by all used sequences, which\nsolves one of the limitations with LAST_INSERT_ID().\n \nCreating a Sequence\n \nThe CREATE SEQUENCE statement is used to create a sequence.\nHere is an example of a sequence starting at 100,\nincrementing by 10 each time:\n \nCREATE SEQUENCE s START WITH 100 INCREMENT BY 10;\n \nThe CREATE SEQUENCE statement, along with defaults, can be\nviewd with the SHOW CREATE SEQUENCE STATEMENT, for example:\n \nSHOW CREATE SEQUENCE s\\G\n*************************** 1. row\n***************************\n Table: s\nCreate Table: CREATE SEQUENCE `s` start with 100 minvalue 1\nmaxvalue 9223372036854775806 \n increment by 10 cache 1000 nocycle ENGINE=InnoDB\n \nUsing Sequence Objects\n \nTo get the next value from a sequence, use\n \nNEXT VALUE FOR sequence_name\n \nor\n \nNEXTVAL(sequence_name)\n \nor in Oracle mode (SQL_MODE=ORACLE)\n \nsequence_name.nextval\n \nFor retrieving the last value used by the current connection\nfrom a sequence\nuse:\n \nPREVIOUS VALUE FOR sequence_name\n \nor\n \nLASTVAL(sequence_name)\n \nor in Oracle mode (SQL_MODE=ORACLE)\n \nsequence_name.currval\n \nFor example:\n \nSELECT NEXTVAL(s);\n+------------+\n| NEXTVAL(s) |\n+------------+\n| 100 |\n+------------+\n \nSELECT NEXTVAL(s);\n+------------+\n| NEXTVAL(s) |\n+------------+\n| 110 |\n+------------+\n \nSELECT LASTVAL(s);\n+------------+\n| LASTVAL(s) |\n+------------+\n| 110 |\n+------------+\n \nUsing Sequences in DEFAULT\n \nStarting from 10.3.3 you can use Sequences in DEFAULT:\n \ncreate sequence s1;\n \ncreate table t1 (a int primary key default (next value for\ns1), b int);\ninsert into t1 (b) values (1),(2);\nselect * from t1;\n \n+---+------+\n| a | b |\n+---+------+\n| 1 | 1 |\n| 2 | 2 |\n+---+------+\n \nChanging a Sequence\n \nThe ALTER SEQUENCE statement is used for changing sequences.\nFor example, to restart the sequence at another value:\n \nALTER SEQUENCE s RESTART 50;\n \nSELECT NEXTVAL(s);\n+------------+\n| NEXTVAL(s) |\n+------------+\n| 50 |\n+------------+\n \nThe SETVAL function can also be used to set the next value\nto be returned for a SEQUENCE, for example:\n \nSELECT SETVAL(s, 100);\n+----------------+\n| SETVAL(s, 100) |\n+----------------+\n| 100 |\n+----------------+\n \nSETVAL can only be used to increase the sequence value.\nAttempting to set a lower value will fail, returning NULL:\n \nSELECT SETVAL(s, 50);\n+---------------+\n| SETVAL(s, 50) |\n+---------------+\n| NULL |\n+---------------+\n \nDropping a Sequence\n \nThe DROP SEQUENCE statement is used to drop a sequence, for\nexample:\n \nDROP SEQUENCE s;\n \nReplication\n \nIf one wants to use Sequences in a master-master setup or\nwith Galera one\nshould use INCREMENT=0. This will tell the Sequence to use\nauto_increment_increment and auto_increment_offset to\ngenerate unique values for each server.\n \nStandards Compliance\n \nMariaDB 10.3 supports both ANSI SQL and Oracle syntax for\nsequences.\n \nHowever as SEQUENCE is implemented as a special kind of\ntable, it uses the same namespace as tables. The benefits\nare that sequences show up in SHOW TABLES, and one can also\ncreate a sequence with CREATE TABLE and drop it with DROP\nTABLE. One can SELECT from it as from any other table. This\nensures that all old tools that work with tables should work\nwith sequences.\n \nSince sequence objects act as regular tables in many\ncontexts, they will be affected by LOCK TABLES. This is not\nthe case in other DBMS, such as Oracle, where LOCK TABLE\ndoes not affect sequences.\n \nNotes\n \nOne of the goals with the Sequence implementation is that\nall old\ntools, such as mysqldump, should work unchanged, while still\nkeeping the\nnormal usage of sequence standard compatibly.\n \nTo make this possible, sequence is currently implemented as\na table with a few exclusive properties.\n \nThe special properties for sequence tables are:\nA sequence table has always one row.\nWhen one creates a sequence, either with CREATE TABLE or\nCREATE SEQUENCE, one row will be inserted.\nIf one tries to insert into a sequence table, the single row\nwill be updated. This allows mysqldump to work but also\ngives the additional benefit that one can change all\nproperties of a sequence with a single insert. New\napplications should of course also use ALTER SEQUENCE.\nUPDATE or DELETE can\'t be performed on Sequence objects.\nDoing a select on the sequence shows the current state of\nthe sequence, except the values that are reserved in the\ncache. The next_value column shows the next value not\nreserved by the cache.\nFLUSH TABLES will close the sequence and the next sequence\nnumber generated will be according to what\'s stored in the\nSequence object. In effect, this will discard the cached\nvalues.\nA number of normal table operations work on Sequence tables.\nSee next section.\n \nTable Operations that Work with Sequences\n \nSHOW CREATE TABLE sequence_name. This shows the table\nstructure that is behind the SEQUENCE including the field\nnames that can be used with SELECT or even CREATE TABLE.\nCREATE TABLE sequence-structure ... SEQUENCE=1\nALTER TABLE sequence RENAME TO sequence2\nRENAME TABLE sequence_name TO new_sequence_name\nDROP TABLE sequence_name. This is allowed mainly to get old\ntools like mysqldump to work with sequence tables.\nSHOW TABLES\n \nImplementation\n \nInternally, sequence tables are created as a normal table\nwithout\nrollback (the InnoDB, Aria and MySAM engines support this),\nwrapped by a\nsequence engine object. This allowed us to create sequences\nwith\nalmost no performance impact for normal tables. (The cost is\none \'if\'\nper insert if the binary log is enabled).\n \nUnderlying Table Structure\n \nThe following example shows the table structure of sequences\nand how it\ncan be used as a table.\n(Output of results are slightly edited to make them easier\nto read)\n \ncreate sequence t1;\nshow create sequence t1\\G\n***** 1. row *****\n CREATE SEQUENCE `t1` start with 1 minvalue 1 maxvalue\n9223372036854775806\n increment by 1 cache 1000 nocycle ENGINE=InnoDB\n \nshow create table t1\\G\n***** 1. row *****\nCreate Table: CREATE TABLE `t1` (\n `next_not_cached_value` bigint(21) NOT NULL,\n `minimum_value` bigint(21) NOT NULL,\n `maximum_value` bigint(21) NOT NULL,\n `start_value` bigint(21) NOT NULL COMMENT \'start value\nwhen sequences is created or value if RESTART is used\',\n `increment` bigint(21) NOT NULL COMMENT \'increment\nvalue\',\n `cache_size` bigint(21) unsigned NOT NULL,\n `cycle_option` tinyint(1) unsigned NOT NULL COMMENT \'0 if\nno cycles are allowed, 1 if the sequence should begin a new\ncycle when maximum_value is passed\',\n `cycle_count` bigint(21) NOT NULL COMMENT \'How many cycles\nhave been done\'\n) ENGINE=InnoDB SEQUENCE=1\n \nselect * from t1\\G\nnext_not_cached_value: 1\n minimum_value: 1\n maximum_value: 9223372036854775806\n start_value: 1\n increment: 1\n cache_size: 1000\n cycle_option: 0\n cycle_count: 0\nThe cycle_count column is incremented every time the\nsequence wraps around.\n \nCredits\n \nThanks to Jianwe Zhao from Aliyun for his work on SEQUENCE\nin AliSQL, which gave ideas and inspiration for this work.\nThanks to Peter Gulutzan,who helped test and gave useful\ncomments about the implementation.\n \n\n\nURL: https://mariadb.com/kb/en/library/sequence-overview/','','https://mariadb.com/kb/en/library/sequence-overview/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (685,40,'SETVAL()','SEQUENCEs were introduced in MariaDB 10.3.\n \nSyntax\n------ \nSETVAL(sequence_name, next_value, [is_used, [round]])\n \nDescription\n----------- \nSet the next value to be returned for a SEQUENCE.\n \nThis function is compatible with PostgreSQL syntax, extended\nwith the round argument.\n \nIf the is_used argument is not given or is 1 or true, then\nthe next used value will\none after the given value. If is_used is 0 or false then the\nnext generated value\nwill be the given value.\n \nIf round is used then it will set the round value (or the\ninternal cycle count, starting at zero) for the sequence.\nIf round is not used, it\'s assumed to be 0.\n \nnext_value must be an integer literal.\n \nFor SEQUENCE tables defined with CYCLE (see CREATE SEQUENCE)\none should use both next_value and round to define the next\nvalue. In this case the\ncurrent sequence value is defined to be round, next_value.\n \nThe result returned by SETVAL() is next_value or NULL if the\ngiven next_value and round is smaller than the current\nvalue.\n \nSETVAL() will not set the SEQUENCE value to a something that\nis less than\nits current value. This is needed to ensure that SETVAL()\nis replication safe. If you want to set the SEQUENCE to a\nsmaller number\nuse ALTER SEQUENCE.\n \nIf CYCLE is used, first round and then next_value are\ncompared\nto see if the value is bigger than the current value.\n \nInternally, in the MariaDB server, SETVAL() is used to\ninform\nslaves that a SEQUENCE has changed value. The slave may get\nSETVAL() statements out of order, but this is ok as only the\nbiggest one will have an effect.\n \nSETVAL requires the INSERT privilege.\n \nExamples\n-------- \nSELECT setval(foo, 42); -- Next nextval will return 43\nSELECT setval(foo, 42, true); -- Same as above\nSELECT setval(foo, 42, false); -- Next nextval will return\n42\n \nSETVAL setting higher and lower values on a sequence with an\nincrement of 10:\n \nSELECT NEXTVAL(s);\n+------------+\n| NEXTVAL(s) |\n+------------+\n| 50 |\n+------------+\n \nSELECT SETVAL(s, 100);\n+----------------+\n| SETVAL(s, 100) |\n+----------------+\n| 100 |\n+----------------+\n \nSELECT NEXTVAL(s);\n+------------+\n| NEXTVAL(s) |\n+------------+\n| 110 |\n+------------+\n \nSELECT SETVAL(s, 50);\n+---------------+\n| SETVAL(s, 50) |\n+---------------+\n| NULL |\n+---------------+\n \nSELECT NEXTVAL(s);\n+------------+\n| NEXTVAL(s) |\n+------------+\n| 120 |\n+------------+\n \nExample demonstrating round:\n \nCREATE OR REPLACE SEQUENCE s1\n START WITH 1\n MINVALUE 1\n MAXVALUE 99\n INCREMENT BY 1 \n CACHE 20 \n CYCLE;\n \nSELECT SETVAL(s1, 99, 1, 0);\n+----------------------+\n| SETVAL(s1, 99, 1, 0) |\n+----------------------+\n| 99 |\n+----------------------+\n \nSELECT NEXTVAL(s1);\n+-------------+\n| NEXTVAL(s1) |\n+-------------+\n| 1 |\n+-------------+\n \nThe following statement returns NULL, as the given\nnext_value and round is smaller than the current value.\n \nSELECT SETVAL(s1, 99, 1, 0);\n+----------------------+\n| SETVAL(s1, 99, 1, 0) |\n+----------------------+\n| NULL |\n+----------------------+\n \nSELECT NEXTVAL(s1);\n+-------------+\n| NEXTVAL(s1) |\n+-------------+\n| 2 |\n+-------------+\n \nIncreasing the round from zero to 1 will allow next_value to\nbe returned.\n \nSELECT SETVAL(s1, 99, 1, 1);\n+----------------------+\n| SETVAL(s1, 99, 1, 1) |\n+----------------------+\n| 99 |\n+----------------------+\n \nSELECT NEXTVAL(s1);\n+-------------+\n| NEXTVAL(s1) |\n+-------------+\n| 1 |\n+-------------+\n \n\n\nURL: https://mariadb.com/kb/en/library/setval/','','https://mariadb.com/kb/en/library/setval/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (686,41,'JSON_ARRAY','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_ARRAY([value[, value2] ...])\n \nDescription\n----------- \nReturns a JSON array containing the listed values. The list\ncan be empty.\n \nExample\n \nSELECT Json_Array(56, 3.1416, \'My name is \"Foo\"\', NULL);\n+--------------------------------------------------+\n| Json_Array(56, 3.1416, \'My name is \"Foo\"\', NULL) |\n+--------------------------------------------------+\n| [56, 3.1416, \"My name is \\\"Foo\\\"\", null] |\n+--------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_array/','','https://mariadb.com/kb/en/json_array/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (687,41,'JSON_ARRAY_APPEND','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_ARRAY_APPEND(json_doc, path, value[, path, value] ...)\n \nDescription\n----------- \nAppends values to the end of the specified arrays within a\nJSON document, returning the result, or NULL if any of the\narguments are NULL.\n \nEvaluation is performed from left to right, with the\nresulting document from the previous pair becoming the new\nvalue against which the next pair is evaluated.\n \nIf the json_doc is not a valid JSON document, or if any of\nthe paths are not valid, or contain a * or ** wildcard, an\nerror is returned.\n \nExamples\n-------- \nSET @json = \'[1, 2, [3, 4]]\';\n \nSELECT JSON_ARRAY_APPEND(@json, \'$[0]\', 5)\n+-------------------------------------+\n| JSON_ARRAY_APPEND(@json, \'$[0]\', 5) |\n+-------------------------------------+\n| [[1, 5], 2, [3, 4]] |\n+-------------------------------------+\n \nSELECT JSON_ARRAY_APPEND(@json, \'$[1]\', 6);\n+-------------------------------------+\n| JSON_ARRAY_APPEND(@json, \'$[1]\', 6) |\n+-------------------------------------+\n| [1, [2, 6], [3, 4]] |\n+-------------------------------------+\n \nSELECT JSON_ARRAY_APPEND(@json, \'$[1]\', 6, \'$[2]\', 7);\n+------------------------------------------------+\n| JSON_ARRAY_APPEND(@json, \'$[1]\', 6, \'$[2]\', 7) |\n+------------------------------------------------+\n| [1, [2, 6], [3, 4, 7]] |\n+------------------------------------------------+\n \nSELECT JSON_ARRAY_APPEND(@json, \'$\', 5);\n+----------------------------------+\n| JSON_ARRAY_APPEND(@json, \'$\', 5) |\n+----------------------------------+\n| [1, 2, [3, 4], 5] |\n+----------------------------------+\n \nSET @json = \'{\"A\": 1, \"B\": [2], \"C\": [3, 4]}\';\n \nSELECT JSON_ARRAY_APPEND(@json, \'$.B\', 5);\n+------------------------------------+\n| JSON_ARRAY_APPEND(@json, \'$.B\', 5) |\n+------------------------------------+\n| {\"A\": 1, \"B\": [2, 5], \"C\": [3, 4]} |\n+------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_array_append/','','https://mariadb.com/kb/en/json_array_append/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (688,41,'JSON_ARRAY_INSERT','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_ARRAY_INSERT(json_doc, path, value[, path, value] ...)\n \nDescription\n----------- \nInserts a value into a JSON document, returning the modified\ndocument, or NULL if any of the arguments are NULL.\n \nEvaluation is performed from left to right, with the\nresulting document from the previous pair becoming the new\nvalue against which the next pair is evaluated.\n \nIf the json_doc is not a valid JSON document, or if any of\nthe paths are not valid, or contain a * or ** wildcard, an\nerror is returned.\n \nExamples\n-------- \nSET @json = \'[1, 2, [3, 4]]\';\n \nSELECT JSON_ARRAY_INSERT(@json, \'$[0]\', 5);\n+-------------------------------------+\n| JSON_ARRAY_INSERT(@json, \'$[0]\', 5) |\n+-------------------------------------+\n| [5, 1, 2, [3, 4]] |\n+-------------------------------------+\n \nSELECT JSON_ARRAY_INSERT(@json, \'$[1]\', 6);\n+-------------------------------------+\n| JSON_ARRAY_INSERT(@json, \'$[1]\', 6) |\n+-------------------------------------+\n| [1, 6, 2, [3, 4]] |\n+-------------------------------------+\n \nSELECT JSON_ARRAY_INSERT(@json, \'$[1]\', 6, \'$[2]\', 7);\n+------------------------------------------------+\n| JSON_ARRAY_INSERT(@json, \'$[1]\', 6, \'$[2]\', 7) |\n+------------------------------------------------+\n| [1, 6, 7, 2, [3, 4]] |\n+------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_array_insert/','','https://mariadb.com/kb/en/json_array_insert/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (689,41,'JSON_COMPACT','This function was added in MariaDB 10.2.4.\n \nSyntax\n------ \nJSON_COMPACT(json_doc)\n \nDescription\n----------- \nRemoves all unnecessary spaces so the json document is as\nshort as possible.\n \nExample\n \nSET @j = \'{ \"A\": 1, \"B\": [2, 3]}\';\n \nSELECT JSON_COMPACT(@j), @j;\n+-------------------+------------------------+\n| JSON_COMPACT(@j) | @j |\n+-------------------+------------------------+\n| {\"A\":1,\"B\":[2,3]} | { \"A\": 1, \"B\": [2, 3]} |\n+-------------------+------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_compact/','','https://mariadb.com/kb/en/json_compact/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (690,41,'JSON_CONTAINS','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_CONTAINS(json_doc, val[, path])\n \nDescription\n----------- \nReturns whether or not the specified value is found in the\ngiven JSON document or, optionally, at the specified path\nwithin the document. Returns 1 if it does, 0 if not and NULL\nif any of the arguments are null. An error occurs if the\ndocument or path is not valid, or contains the * or **\nwildcards.\n \nExamples\n-------- \nSET @json = \'{\"A\": 0, \"B\": {\"C\": 1}, \"D\": 2}\';\n \nSELECT JSON_CONTAINS(@json, \'2\', \'$.A\');\n+----------------------------------+\n| JSON_CONTAINS(@json, \'2\', \'$.A\') |\n+----------------------------------+\n| 0 |\n+----------------------------------+\n \nSELECT JSON_CONTAINS(@json, \'2\', \'$.D\');\n+----------------------------------+\n| JSON_CONTAINS(@json, \'2\', \'$.D\') |\n+----------------------------------+\n| 1 |\n+----------------------------------+\n \nSELECT JSON_CONTAINS(@json, \'{\"C\": 1}\', \'$.A\');\n+-----------------------------------------+\n| JSON_CONTAINS(@json, \'{\"C\": 1}\', \'$.A\') |\n+-----------------------------------------+\n| 0 |\n+-----------------------------------------+\n \nSELECT JSON_CONTAINS(@json, \'{\"C\": 1}\', \'$.B\');\n+-----------------------------------------+\n| JSON_CONTAINS(@json, \'{\"C\": 1}\', \'$.B\') |\n+-----------------------------------------+\n| 1 |\n+-----------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_contains/','','https://mariadb.com/kb/en/json_contains/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (691,41,'JSON_CONTAINS_PATH','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_CONTAINS_PATH(json_doc, return_arg, path[, path] ...)\n \nDescription\n----------- \nIndicates whether the given JSON document contains data at\nthe specified path or paths. Returns 1 if it does, 0 if not\nand NULL if any of the arguments are null.\n \nThe return_arg can be one or all:\none - Returns 1 if at least one path exists within the JSON\ndocument. \nall - Returns 1 only if all paths exist within the JSON\ndocument.\n \nExamples\n-------- \nSET @json = \'{\"A\": 1, \"B\": [2], \"C\": [3, 4]}\';\n \nSELECT JSON_CONTAINS_PATH(@json, \'one\', \'$.A\', \'$.D\');\n+------------------------------------------------+\n| JSON_CONTAINS_PATH(@json, \'one\', \'$.A\', \'$.D\') |\n+------------------------------------------------+\n| 1 |\n+------------------------------------------------+\n1 row in set (0.00 sec)\n \nSELECT JSON_CONTAINS_PATH(@json, \'all\', \'$.A\', \'$.D\');\n+------------------------------------------------+\n| JSON_CONTAINS_PATH(@json, \'all\', \'$.A\', \'$.D\') |\n+------------------------------------------------+\n| 0 |\n+------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_contains_path/','','https://mariadb.com/kb/en/json_contains_path/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (692,41,'JSON_DEPTH','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_DEPTH(json_doc)\n \nDescription\n----------- \nReturns the maximum depth of the given JSON document, or\nNULL if the argument is null. An error will occur if the\nargument is an invalid JSON document.\nScalar values or empty arrays or objects have a depth of 1.\nArrays or objects that are not empty but contain only\nelements or member values of depth 1 will have a depth of 2.\nIn other cases, the depth will be greater than 2.\n \nExamples\n-------- \nSELECT JSON_DEPTH(\'[]\'), JSON_DEPTH(\'true\'),\nJSON_DEPTH(\'{}\');\n+------------------+--------------------+------------------+\n| JSON_DEPTH(\'[]\') | JSON_DEPTH(\'true\') |\nJSON_DEPTH(\'{}\') |\n+------------------+--------------------+------------------+\n| 1 | 1 | 1 |\n+------------------+--------------------+------------------+\n \nSELECT JSON_DEPTH(\'[1, 2, 3]\'), JSON_DEPTH(\'[[], {},\n[]]\');\n+-------------------------+----------------------------+\n| JSON_DEPTH(\'[1, 2, 3]\') | JSON_DEPTH(\'[[], {}, []]\') |\n+-------------------------+----------------------------+\n| 2 | 2 |\n+-------------------------+----------------------------+\n \nSELECT JSON_DEPTH(\'[1, 2, [3, 4, 5, 6], 7]\');\n+---------------------------------------+\n| JSON_DEPTH(\'[1, 2, [3, 4, 5, 6], 7]\') |\n+---------------------------------------+\n| 3 |\n+---------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_depth/','','https://mariadb.com/kb/en/json_depth/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (693,41,'JSON_DETAILED','This function was added in MariaDB 10.2.4.\n \nSyntax\n------ \nJSON_DETAILED(json_doc[, tab_size])\n \nDescription\n----------- \nRepresents JSON in the most understandable way emphasizing\nnested structures.\n \nExample\n \nSET @j = \'{ \"A\":1,\"B\":[2,3]}\';\n \nSELECT @j;\n+--------------------+\n| @j |\n+--------------------+\n| { \"A\":1,\"B\":[2,3]} |\n+--------------------+\n \nSELECT JSON_DETAILED(@j);\n+------------------------------------------------------------+\n| JSON_DETAILED(@j) |\n+------------------------------------------------------------+\n| {\n \"A\": 1,\n \"B\": \n [\n 2,\n 3\n ]\n} |\n+------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_detailed/','','https://mariadb.com/kb/en/json_detailed/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (694,41,'JSON_EXISTS','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nDescription\n----------- \nDetermines whether a specified JSON value exists in the\ngiven data. Returns 1 if found, 0 if not, or NULL if any of\nthe inputs were NULL.\n \nExamples\n-------- \nSELECT JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2,\n3]}\', \"$.key2\");\n+------------------------------------------------------------+\n| JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2, 3]}\',\n\"$.key2\") |\n+------------------------------------------------------------+\n| 1 |\n+------------------------------------------------------------+\n \nSELECT JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2,\n3]}\', \"$.key3\");\n+------------------------------------------------------------+\n| JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2, 3]}\',\n\"$.key3\") |\n+------------------------------------------------------------+\n| 0 |\n+------------------------------------------------------------+\n \nSELECT JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2,\n3]}\', \"$.key2[1]\");\n+---------------------------------------------------------------+\n| JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2, 3]}\',\n\"$.key2[1]\") |\n+---------------------------------------------------------------+\n| 1 |\n+---------------------------------------------------------------+\n \nSELECT JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2,\n3]}\', \"$.key2[10]\");\n+----------------------------------------------------------------+\n| JSON_EXISTS(\'{\"key1\":\"xxxx\", \"key2\":[1, 2, 3]}\',\n\"$.key2[10]\") |\n+----------------------------------------------------------------+\n| 0 |\n+----------------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_exists/','','https://mariadb.com/kb/en/json_exists/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (695,41,'JSON_EXTRACT','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_EXTRACT(json_doc, path[, path] ...)\n \nDescription\n----------- \nExtracts data from a JSON document. The extracted data is\nselected from the parts matching the path arguments. Returns\nall matched values; either as a single matched value, or, if\nthe arguments could return multiple values, a result\nautowrapped as an array in the matching order.\n \nReturns NULL if no paths match or if any of the arguments\nare NULL. \n \nAn error will occur if any path argument is not a valid\npath, or if the json_doc argument is not a valid JSON\ndocument.\n \nExamples\n-------- \nSET @json = \'[1, 2, [3, 4]]\';\n \nSELECT JSON_EXTRACT(@json, \'$[1]\');\n+-----------------------------+\n| JSON_EXTRACT(@json, \'$[1]\') |\n+-----------------------------+\n| 2 |\n+-----------------------------+\n \nSELECT JSON_EXTRACT(@json, \'$[2]\');\n+-----------------------------+\n| JSON_EXTRACT(@json, \'$[2]\') |\n+-----------------------------+\n| [3, 4] |\n+-----------------------------+\n \nSELECT JSON_EXTRACT(@json, \'$[2][1]\');\n+--------------------------------+\n| JSON_EXTRACT(@json, \'$[2][1]\') |\n+--------------------------------+\n| 4 |\n+--------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_extract/','','https://mariadb.com/kb/en/json_extract/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (696,41,'JSON_INSERT','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_INSERT(json_doc, path, val[, path, val] ...)\n \nDescription\n----------- \nInserts data into a JSON document, returning the resulting\ndocument or NULL if any argument is null. \n \nAn error will occur if the JSON document is not invalid, or\nif any of the paths are invalid or contain a * or **\nwildcard.\n \nJSON_INSERT can only insert data while JSON_REPLACE can only\nupdate. JSON_SET can update or insert data. \n \nExamples\n-------- \nSET @json = \'{ \"A\": 0, \"B\": [1, 2]}\';\n \nSELECT JSON_INSERT(@json, \'$.C\', \'[3, 4]\');\n+--------------------------------------+\n| JSON_INSERT(@json, \'$.C\', \'[3, 4]\') |\n+--------------------------------------+\n| { \"A\": 0, \"B\": [1, 2], \"C\":\"[3, 4]\"} |\n+--------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_insert/','','https://mariadb.com/kb/en/json_insert/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (697,41,'JSON_KEYS','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_KEYS(json_doc[, path])\n \nDescription\n----------- \nReturns the keys as a JSON array from the top-level value of\na JSON object or, if the optional path argument is provided,\nthe top-level keys from the path. \n \nExcludes keys from nested sub-objects in the top level\nvalue. The resulting array will be empty if the selected\nobject is empty.\n \nReturns NULL if any of the arguments are null, a given path\ndoes not locate an object, or if the json_doc argument is\nnot an object.\n \nAn error will occur if JSON document is invalid, the path is\ninvalid or if the path contains a * or ** wildcard.\n \nExamples\n-------- \nSELECT JSON_KEYS(\'{\"A\": 1, \"B\": {\"C\": 2}}\');\n+--------------------------------------+\n| JSON_KEYS(\'{\"A\": 1, \"B\": {\"C\": 2}}\') |\n+--------------------------------------+\n| [\"A\", \"B\"] |\n+--------------------------------------+\n \nSELECT JSON_KEYS(\'{\"A\": 1, \"B\": 2, \"C\": {\"D\":\n3}}\', \'$.C\');\n+-----------------------------------------------------+\n| JSON_KEYS(\'{\"A\": 1, \"B\": 2, \"C\": {\"D\": 3}}\',\n\'$.C\') |\n+-----------------------------------------------------+\n| [\"D\"] |\n+-----------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_keys/','','https://mariadb.com/kb/en/json_keys/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (698,41,'JSON_LENGTH','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_LENGTH(json_doc[, path])\n \nDescription\n----------- \nReturns the length of a JSON document, or, if the optional\npath argument is given, the length of the value within the\ndocument specified by the path. \n \nReturns NULL if any of the arguments argument are null or\nthe path argument does not identify a value in the document.\n\n \nAn error will occur if the JSON document is invalid, the\npath is invalid or if the path contains a * or ** wildcard.\n \nLength will be determined as follow:\nA scalar\'s length is always 1.\nIf an array, the number of elements in the array.\nIf an object, the number of members in the object.\n \nThe length of nested arrays or objects are not counted.\n \nExamples\n-------- \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_length/','','https://mariadb.com/kb/en/json_length/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (699,41,'JSON_LOOSE','This function was added in MariaDB 10.2.4.\n \nSyntax\n------ \nJSON_LOOSE(json_doc)\n \nDescription\n----------- \nAdds spaces to a JSON document to make it look more\nreadable.\n \nExample\n \nSET @j = \'{ \"A\":1,\"B\":[2,3]}\';\n \nSELECT JSON_LOOSE(@j), @j;\n+-----------------------+--------------------+\n| JSON_LOOSE(@j) | @j |\n+-----------------------+--------------------+\n| {\"A\": 1, \"B\": [2, 3]} | { \"A\":1,\"B\":[2,3]} |\n+-----------------------+--------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_loose/','','https://mariadb.com/kb/en/json_loose/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (700,41,'JSON_MERGE','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_MERGE(json_doc, json_doc[, json_doc] ...)\n \nDescription\n----------- \nMerges the given JSON documents.\n \nReturns the merged result,or NULL if any argument is NULL.\n \nAn error occurs if any of the arguments are not valid JSON\ndocuments.\n \nExample\n \nSET @json1 = \'[1, 2]\';\n \nSET @json2 = \'[3, 4]\';\n \nSELECT JSON_MERGE(@json1,@json2);\n+---------------------------+\n| JSON_MERGE(@json1,@json2) |\n+---------------------------+\n| [1, 2, 3, 4] |\n+---------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_merge/','','https://mariadb.com/kb/en/json_merge/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (701,41,'JSON_OBJECT','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_OBJECT([key, value[, key, value] ...])\n \nDescription\n----------- \nReturns a JSON object containing the given key/value pairs.\nThe key/value list can be empty.\n \nAn error will occur if there are an odd number of arguments,\nor any key name is NULL.\n \nExample\n \nSELECT JSON_OBJECT(\"id\", 1, \"name\", \"Monty\");\n+---------------------------------------+\n| JSON_OBJECT(\"id\", 1, \"name\", \"Monty\") |\n+---------------------------------------+\n| {\"id\": 1, \"name\": \"Monty\"} |\n+---------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_object/','','https://mariadb.com/kb/en/json_object/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (702,41,'JSON_QUERY','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_QUERY(json_doc, path)\n \nDescription\n----------- \nGiven a JSON document, returns an object or array specified\nby the path. Returns NULL if not given a valid JSON\ndocument, or if there is no match.\n \nExamples\n-------- \nselect json_query(\'{\"key1\":{\"a\":1, \"b\":[1,2]}}\',\n\'$.key1\');\n+-----------------------------------------------------+\n| json_query(\'{\"key1\":{\"a\":1, \"b\":[1,2]}}\',\n\'$.key1\') |\n+-----------------------------------------------------+\n| {\"a\":1, \"b\":[1,2]} |\n+-----------------------------------------------------+\n \nselect json_query(\'{\"key1\":123, \"key1\": [1,2,3]}\',\n\'$.key1\');\n+-------------------------------------------------------+\n| json_query(\'{\"key1\":123, \"key1\": [1,2,3]}\',\n\'$.key1\') |\n+-------------------------------------------------------+\n| [1,2,3] |\n+-------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_query/','','https://mariadb.com/kb/en/json_query/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (703,41,'JSON_QUOTE','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_QUOTE(json_value)\n \nDescription\n----------- \nQuotes a string as a JSON value, usually for producing valid\nJSON string literals for inclusion in JSON documents. Wraps\nthe string with double quote characters and escapes interior\nquotes and other special characters, returning a utf8mb4\nstring. \n \nReturns NULL if the argument is NULL.\n \nExamples\n-------- \nSELECT JSON_QUOTE(\'A\'), JSON_QUOTE(\"B\"),\nJSON_QUOTE(\'\"C\"\');\n+-----------------+-----------------+-------------------+\n| JSON_QUOTE(\'A\') | JSON_QUOTE(\"B\") |\nJSON_QUOTE(\'\"C\"\') |\n+-----------------+-----------------+-------------------+\n| \"A\" | \"B\" | \"\\\"C\\\"\" |\n+-----------------+-----------------+-------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_quote/','','https://mariadb.com/kb/en/json_quote/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (704,41,'JSON_REMOVE','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_REMOVE(json_doc, path[, path] ...)\n \nDescription\n----------- \nRemoves data from a JSON document returning the result, or\nNULL if any of the arguments are null. If the element does\nnot exist in the document, no changes are made.\n \nAn error will occur if JSON document is invalid, the path is\ninvalid or if the path contains a * or ** wildcard.\n \nPath arguments are evaluated from left to right, with the\nresult from the earlier evaluation being used as the value\nfor the next.\n \nExamples\n-------- \nSELECT JSON_REMOVE(\'{\"A\": 1, \"B\": 2, \"C\": {\"D\":\n3}}\', \'$.C\');\n+-------------------------------------------------------+\n| JSON_REMOVE(\'{\"A\": 1, \"B\": 2, \"C\": {\"D\": 3}}\',\n\'$.C\') |\n+-------------------------------------------------------+\n| {\"A\": 1, \"B\": 2} |\n+-------------------------------------------------------+\n \nSELECT JSON_REMOVE(\'[\"A\", \"B\", [\"C\", \"D\"],\n\"E\"]\', \'$[1]\');\n+----------------------------------------------------+\n| JSON_REMOVE(\'[\"A\", \"B\", [\"C\", \"D\"], \"E\"]\',\n\'$[1]\') |\n+----------------------------------------------------+\n| [\"A\", [\"C\", \"D\"], \"E\"] |\n+----------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_remove/','','https://mariadb.com/kb/en/json_remove/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (705,41,'JSON_REPLACE','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_REPLACE(json_doc, path, val[, path, val] ...)\n \nDescription\n----------- \nReplaces existing values in a JSON document, returning the\nresult, or NULL if any of the arguments are NULL. \n \nAn error will occur if the JSON document is invalid, the\npath is invalid or if the path contains a * or ** wildcard.\n \nPaths and values are evaluated from left to right, with the\nresult from the earlier evaluation being used as the value\nfor the next.\n \nJSON_REPLACE can only update data, while JSON_INSERT can\nonly insert. JSON_SET can update or insert data. \n \nExamples\n-------- \nSELECT JSON_REPLACE(\'{ \"A\": 1, \"B\": [2, 3]}\',\n\'$.B[1]\', 4);\n+-----------------------------------------------------+\n| JSON_REPLACE(\'{ \"A\": 1, \"B\": [2, 3]}\', \'$.B[1]\',\n4) |\n+-----------------------------------------------------+\n| { \"A\": 1, \"B\": [2, 4]} |\n+-----------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_replace/','','https://mariadb.com/kb/en/json_replace/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (706,41,'JSON_SEARCH','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_SEARCH(json_doc, return_arg, search_str[, escape_char[,\npath] ...])\n \nDescription\n----------- \nReturns the path to the given string within a JSON document,\nor NULL if any of json_doc, search_str or a path argument is\nNULL; if the search string is not found, or if no path\nexists within the document. \n \nA warning will occur if the JSON document is not valid, any\nof the path arguments are not valid, if return_arg is\nneither one nor all, or if the escape character is not a\nconstant. NULL will be returned.\n \nreturn_arg can be one of two values:\n\'one: Terminates after finding the first match, so will\nreturn one path string. If there is more than one match, it\nis undefined which is considered first.\nall: Returns all matching path strings, without duplicates.\nMultiple strings are autowrapped as an array. The order is\nundefined.\n \nExamples\n-------- \nSET @json = \'[\"A\", [{\"B\": \"1\"}], {\"C\":\"AB\"},\n{\"D\":\"BC\"}]\';\n \nSELECT JSON_SEARCH(@json, \'one\', \'AB\');\n+---------------------------------+\n| JSON_SEARCH(@json, \'one\', \'AB\') |\n+---------------------------------+\n| \"$[2].C\" |\n+---------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_search/','','https://mariadb.com/kb/en/json_search/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (707,41,'JSON_SET','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_SET(json_doc, path, val[, path, val] ...)\n \nDescription\n----------- \nUpdates or inserts data into a JSON document, returning the\nresult, or NULL if any of the arguments are NULL or the\noptional path fails to find an object.\n \nAn error will occur if the JSON document is invalid, the\npath is invalid or if the path contains a * or wildcard.\n \nJSON_SET can update or insert data, while JSON_REPLACE can\nonly update, and JSON_INSERT only insert. \n \nExamples\n-------- \n\n \n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_set/','','https://mariadb.com/kb/en/json_set/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (708,41,'JSON_TYPE','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_TYPE(json_val)\n \nDescription\n----------- \nReturns the type of a JSON value, or NULL if the argument is\nnull.\n \nAn error will occur if the argument is an invalid JSON\nvalue.\n \nThe following is a complete list of the possible return\ntypes:\n \nReturn type | Value | \n \nARRAY | JSON array | \n \nBIT | MariaDB BIT scalar | \n \nBLOB | MariaDB binary types (BINARY, VARBINARY or BLOB) | \n \nBOOLEAN | JSON true/false literals | \n \nDATE | MariaDB DATE scalar | \n \nDATETIME | MariaDB DATETIME or TIMESTAMP scalar | \n \nDECIMAL | MariaDB DECIMAL or NUMERIC scalar | \n \nDOUBLE | MariaDB DOUBLE FLOAT scalar | \n \nINTEGER | MariaDB integer types (TINYINT, SMALLINT,\nMEDIUMINT, INT or BIGINT) | \n \nNULL | JSON null literal or NULL argument | \n \nOBJECT | JSON object | \n \nOPAQUE | Any valid JSON value that is not one of the other\ntypes. | \n \nSTRING | MariaDB character types (CHAR, VARCHAR, TEXT, ENUM\nor SET) | \n \nTIME | MariaDB TIME scalar | \n \nExamples\n-------- \nSELECT JSON_TYPE(\'{\"A\": 1, \"B\": 2, \"C\": 3}\');\n+---------------------------------------+\n| JSON_TYPE(\'{\"A\": 1, \"B\": 2, \"C\": 3}\') |\n+---------------------------------------+\n| OBJECT |\n+---------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_type/','','https://mariadb.com/kb/en/json_type/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (709,41,'JSON_UNQUOTE','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_UNQUOTE(val)\n \nDescription\n----------- \nUnquotes a JSON value, returning a string, or NULL if the\nargument is null. \n \nAn error will occur if the given value begins and ends with\ndouble quotes and is an invalid JSON string literal.\n \nCertain character sequences have special meanings within a\nstring. Usually, a backspace is ignored, but the escape\nsequences in the table below are recognised by MariaDB,\nunless the SQL Mode is set to NO_BACKSLASH_ESCAPES SQL.\n \nEscape sequence | Character | \n \n\\\" | Double quote (\") | \n \n\\b | Backspace | \n \n\\f | Formfeed | \n \n\\n | Newline (linefeed) | \n \n\\r | Carriage return | \n \n\\t | Tab | \n \n\\\\ | Backslash (\\) | \n \n\\uXXXX | UTF-8 bytes for Unicode value XXXX | \n \nExamples\n-------- \nSELECT JSON_UNQUOTE(\'\"Monty\"\');\n+-------------------------+\n| JSON_UNQUOTE(\'\"Monty\"\') |\n+-------------------------+\n| Monty |\n+-------------------------+\n \nWith the default SQL Mode:\n \nSELECT JSON_UNQUOTE(\'Si\\bng\\ting\');\n+-----------------------------+\n| JSON_UNQUOTE(\'Si\\bng\\ting\') |\n+-----------------------------+\n| Sng ing |\n+-----------------------------+\n \nSetting NO_BACKSLASH_ESCAPES:\n \nSET @@sql_mode = \'NO_BACKSLASH_ESCAPES\';\n \nSELECT JSON_UNQUOTE(\'Si\\bng\\ting\');\n+-----------------------------+\n| JSON_UNQUOTE(\'Si\\bng\\ting\') |\n+-----------------------------+\n| Si\\bng\\ting |\n+-----------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_unquote/','','https://mariadb.com/kb/en/json_unquote/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (710,41,'JSON_VALID','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_VALID(value)\n \nDescription\n----------- \nIndicates whether the given value is a valid JSON document\nor not. Returns 1 if valid, 0 if not, and NULL if the\nargument is NULL.\n \nFrom MariaDB 10.4.3, the JSON_VALID function is\nautomatically used as a CHECK constraint for the JSON data\ntype alias in order to ensure that a valid json document is\ninserted. \n \nExamples\n-------- \nSELECT JSON_VALID(\'{\"id\": 1, \"name\": \"Monty\"}\');\n+------------------------------------------+\n| JSON_VALID(\'{\"id\": 1, \"name\": \"Monty\"}\') |\n+------------------------------------------+\n| 1 |\n+------------------------------------------+\n \nSELECT JSON_VALID(\'{\"id\": 1, \"name\": \"Monty\",\n\"oddfield\"}\');\n+------------------------------------------------------+\n| JSON_VALID(\'{\"id\": 1, \"name\": \"Monty\",\n\"oddfield\"}\') |\n+------------------------------------------------------+\n| 0 |\n+------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_valid/','','https://mariadb.com/kb/en/json_valid/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (711,41,'JSON_VALUE','JSON functions were added in MariaDB 10.2.3.\n \nSyntax\n------ \nJSON_VALUE(json_doc, path)\n \nDescription\n----------- \nGiven a JSON document, returns the scalar specified by the\npath. Returns NULL if not given a valid JSON document, or if\nthere is no match.\n \nExamples\n-------- \nselect json_value(\'{\"key1\":123}\', \'$.key1\');\n+--------------------------------------+\n| json_value(\'{\"key1\":123}\', \'$.key1\') |\n+--------------------------------------+\n| 123 |\n+--------------------------------------+\n \nselect json_value(\'{\"key1\": [1,2,3], \"key1\":123}\',\n\'$.key1\');\n+-------------------------------------------------------+\n| json_value(\'{\"key1\": [1,2,3], \"key1\":123}\',\n\'$.key1\') |\n+-------------------------------------------------------+\n| 123 |\n+-------------------------------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/json_value/','','https://mariadb.com/kb/en/json_value/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (712,42,'CUME_DIST','The CUME_DIST() function was first introduced with window\nfunctions in MariaDB 10.2.0.\n \nSyntax\n------ \nCUME_DIST() OVER ( \n [ PARTITION BY partition_expression ] \n [ ORDER BY order_list ]\n)\n \nDescription\n----------- \nCUME_DIST() is a window function that returns the cumulative\ndistribution of a given row. The following formula is used\nto calculate the value:\n \n(number of rows \n\nURL: https://mariadb.com/kb/en/cume_dist/','','https://mariadb.com/kb/en/cume_dist/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (713,42,'DENSE_RANK','The DENSE_RANK() function was first introduced with window\nfunctions in MariaDB 10.2.0.\n \nSyntax\n------ \nDENSE_RANK() OVER (\n [ PARTITION BY partition_expression ]\n [ ORDER BY order_list ]\n) \n \nDescription\n----------- \nDENSE_RANK() is a window function that displays the number\nof a given row, starting at one and following the ORDER BY\nsequence of the window function, with identical values\nreceiving the same result. Unlike the RANK() function, there\nare no skipped values if the preceding results are\nidentical. It is also similar to the ROW_NUMBER() function\nexcept that in that function, identical values will receive\na different row number for each result.\n \nExamples\n-------- \nThe distinction between DENSE_RANK(), RANK() and\nROW_NUMBER():\n \nCREATE TABLE student(course VARCHAR(10), mark int, name\nvarchar(10));\n \nINSERT INTO student VALUES \n (\'Maths\', 60, \'Thulile\'),\n (\'Maths\', 60, \'Pritha\'),\n (\'Maths\', 70, \'Voitto\'),\n (\'Maths\', 55, \'Chun\'),\n (\'Biology\', 60, \'Bilal\'),\n (\'Biology\', 70, \'Roger\');\n \nSELECT \n RANK() OVER (PARTITION BY course ORDER BY mark DESC) AS\nrank, \n DENSE_RANK() OVER (PARTITION BY course ORDER BY mark DESC)\nAS dense_rank, \n ROW_NUMBER() OVER (PARTITION BY course ORDER BY mark DESC)\nAS row_num, \n course, mark, name \nFROM student ORDER BY course, mark DESC;\n \n+------+------------+---------+---------+------+---------+\n| rank | dense_rank | row_num | course | mark | name |\n+------+------------+---------+---------+------+---------+\n| 1 | 1 | 1 | Biology | 70 | Roger |\n| 2 | 2 | 2 | Biology | 60 | Bilal |\n| 1 | 1 | 1 | Maths | 70 | Voitto |\n| 2 | 2 | 2 | Maths | 60 | Thulile |\n| 2 | 2 | 3 | Maths | 60 | Pritha |\n| 4 | 3 | 4 | Maths | 55 | Chun |\n+------+------------+---------+---------+------+---------+\n \n\n\nURL: https://mariadb.com/kb/en/dense_rank/','','https://mariadb.com/kb/en/dense_rank/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (714,42,'FIRST_VALUE','The FIRST_VALUE() function was first introduced with other\nwindow functions in MariaDB 10.2.\n \nSyntax\n------ \nFIRST_VALUE(expr) OVER (\n [ PARTITION BY partition_expression ]\n [ ORDER BY order_list ]\n) \n \nDescription\n----------- \nFIRST_VALUE returns the first result from an ordered set, or\nNULL if no such result exists.\n \nExamples\n-------- \nCREATE TABLE t1 (\n pk int primary key,\n a int,\n b int,\n c char(10),\n d decimal(10, 3),\n e real\n);\n \nINSERT INTO t1 VALUES\n( 1, 0, 1, \'one\', 0.1, 0.001),\n( 2, 0, 2, \'two\', 0.2, 0.002),\n( 3, 0, 3, \'three\', 0.3, 0.003),\n( 4, 1, 2, \'three\', 0.4, 0.004),\n( 5, 1, 1, \'two\', 0.5, 0.005),\n( 6, 1, 1, \'one\', 0.6, 0.006),\n( 7, 2, NULL, \'n_one\', 0.5, 0.007),\n( 8, 2, 1, \'n_two\', NULL, 0.008),\n( 9, 2, 2, NULL, 0.7, 0.009),\n(10, 2, 0, \'n_four\', 0.8, 0.010),\n(11, 2, 10, NULL, 0.9, NULL);\n \nSELECT pk, FIRST_VALUE(pk) OVER (ORDER BY pk) AS first_asc,\n LAST_VALUE(pk) OVER (ORDER BY pk) AS last_asc,\n FIRST_VALUE(pk) OVER (ORDER BY pk DESC) AS first_desc,\n LAST_VALUE(pk) OVER (ORDER BY pk DESC) AS last_desc\nFROM t1\nORDER BY pk DESC;\n \n+----+-----------+----------+------------+-----------+\n| pk | first_asc | last_asc | first_desc | last_desc |\n+----+-----------+----------+------------+-----------+\n| 11 | 1 | 11 | 11 | 11 |\n| 10 | 1 | 10 | 11 | 10 |\n| 9 | 1 | 9 | 11 | 9 |\n| 8 | 1 | 8 | 11 | 8 |\n| 7 | 1 | 7 | 11 | 7 |\n| 6 | 1 | 6 | 11 | 6 |\n| 5 | 1 | 5 | 11 | 5 |\n| 4 | 1 | 4 | 11 | 4 |\n| 3 | 1 | 3 | 11 | 3 |\n| 2 | 1 | 2 | 11 | 2 |\n| 1 | 1 | 1 | 11 | 1 |\n+----+-----------+----------+------------+-----------+\n \nCREATE OR REPLACE TABLE t1 (i int);\nINSERT INTO t1 VALUES\n(1),(2),(3),(4),(5),(6),(7),(8),(9),(10);\n \nSELECT i,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW\nand 1 FOLLOWING) AS f_1f,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN CURRENT ROW and\n1 FOLLOWING) AS l_1f,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 PRECEDING\nAND 1 FOLLOWING) AS f_1p1f,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 PRECEDING AND\n1 FOLLOWING) AS f_1p1f,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 2 PRECEDING\nAND 1 PRECEDING) AS f_2p1p,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 2 PRECEDING AND\n1 PRECEDING) AS f_2p1p,\n FIRST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 FOLLOWING\nAND 2 FOLLOWING) AS f_1f2f,\n LAST_VALUE(i) OVER (ORDER BY i ROWS BETWEEN 1 FOLLOWING AND\n2 FOLLOWING) AS f_1f2f\nFROM t1;\n \n+------+------+------+--------+--------+--------+--------+--------+--------+\n| i | f_1f | l_1f | f_1p1f | f_1p1f | f_2p1p | f_2p1p |\nf_1f2f | f_1f2f |\n+------+------+------+--------+--------+--------+--------+--------+--------+\n| 1 | 1 | 2 | 1 | 2 | NULL | NULL | 2 | 3 |\n| 2 | 2 | 3 | 1 | 3 | 1 | 1 | 3 | 4 |\n| 3 | 3 | 4 | 2 | 4 | 1 | 2 | 4 | 5 |\n| 4 | 4 | 5 | 3 | 5 | 2 | 3 | 5 | 6 |\n| 5 | 5 | 6 | 4 | 6 | 3 | 4 | 6 | 7 |\n| 6 | 6 | 7 | 5 | 7 | 4 | 5 | 7 | 8 |\n| 7 | 7 | 8 | 6 | 8 | 5 | 6 | 8 | 9 |\n| 8 | 8 | 9 | 7 | 9 | 6 | 7 | 9 | 10 |\n| 9 | 9 | 10 | 8 | 10 | 7 | 8 | 10 | 10 |\n| 10 | 10 | 10 | 9 | 10 | 8 | 9 | NULL | NULL |\n+------+------+------+--------+--------+--------+--------+--------+--------+\n \n\n\nURL: https://mariadb.com/kb/en/first_value/','','https://mariadb.com/kb/en/first_value/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (715,42,'LAG','The LAG() function was first introduced with other window\nfunctions in MariaDB 10.2.\n \nSyntax\n------ \nLAG (expr[, offset]) OVER ( \n [ PARTITION BY partition_expression ] \n < ORDER BY order_list >\n)\n \nDescription\n----------- \nThe LAG function accesses data from a previous row according\nto the ORDER BY clause without the need for a self-join. The\nspecific row is determined by the offset (default 1), which\nspecifies the number of rows behind the current row to use.\nAn offset of 0 is the current row.\n \nExamples\n-------- \nCREATE TABLE t1 (pk int primary key, a int, b int, c\nchar(10), d decimal(10, 3), e real);\n \nINSERT INTO t1 VALUES\n ( 1, 0, 1, \'one\', 0.1, 0.001),\n ( 2, 0, 2, \'two\', 0.2, 0.002),\n ( 3, 0, 3, \'three\', 0.3, 0.003),\n ( 4, 1, 2, \'three\', 0.4, 0.004),\n ( 5, 1, 1, \'two\', 0.5, 0.005),\n ( 6, 1, 1, \'one\', 0.6, 0.006),\n ( 7, 2, NULL, \'n_one\', 0.5, 0.007),\n ( 8, 2, 1, \'n_two\', NULL, 0.008),\n ( 9, 2, 2, NULL, 0.7, 0.009),\n (10, 2, 0, \'n_four\', 0.8, 0.010),\n (11, 2, 10, NULL, 0.9, NULL);\n \nSELECT pk, LAG(pk) OVER (ORDER BY pk) AS l,\n LAG(pk,1) OVER (ORDER BY pk) AS l1,\n LAG(pk,2) OVER (ORDER BY pk) AS l2,\n LAG(pk,0) OVER (ORDER BY pk) AS l0,\n LAG(pk,-1) OVER (ORDER BY pk) AS lm1,\n LAG(pk,-2) OVER (ORDER BY pk) AS lm2 \nFROM t1;\n \n+----+------+------+------+------+------+------+\n| pk | l | l1 | l2 | l0 | lm1 | lm2 |\n+----+------+------+------+------+------+------+\n| 1 | NULL | NULL | NULL | 1 | 2 | 3 |\n| 2 | 1 | 1 | NULL | 2 | 3 | 4 |\n| 3 | 2 | 2 | 1 | 3 | 4 | 5 |\n| 4 | 3 | 3 | 2 | 4 | 5 | 6 |\n| 5 | 4 | 4 | 3 | 5 | 6 | 7 |\n| 6 | 5 | 5 | 4 | 6 | 7 | 8 |\n| 7 | 6 | 6 | 5 | 7 | 8 | 9 |\n| 8 | 7 | 7 | 6 | 8 | 9 | 10 |\n| 9 | 8 | 8 | 7 | 9 | 10 | 11 |\n| 10 | 9 | 9 | 8 | 10 | 11 | NULL |\n| 11 | 10 | 10 | 9 | 11 | NULL | NULL |\n+----+------+------+------+------+------+------+\n \n\n\nURL: https://mariadb.com/kb/en/lag/','','https://mariadb.com/kb/en/lag/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (717,42,'MEDIAN','The MEDIAN() window function was first introduced with in\nMariaDB 10.3.3.\n \nSyntax\n------ \nMEDIAN(median expression) OVER (\n [ PARTITION BY partition_expression ] \n)\n \nDescription\n----------- \nMEDIAN() is a window function that returns the median value\nof a range of values.\n \nIt is a specific case of PERCENTILE_CONT, with an argument\nof 0.5 and the ORDER BY column the one in MEDIAN\'s\nargument. \n \nMEDIAN() OVER ( [ PARTITION BY partition_expression] )\n \nIs equivalent to:\n \nPERCENTILE_CONT(0.5) WITHIN \n GROUP (ORDER BY ) OVER ( [ PARTITION BY\npartition_expression ])\n \nExamples\n-------- \nCREATE TABLE book_rating (name CHAR(30), star_rating\nTINYINT);\n \nINSERT INTO book_rating VALUES (\'Lord of the Ladybirds\',\n5);\nINSERT INTO book_rating VALUES (\'Lord of the Ladybirds\',\n3);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 1);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 2);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 5);\n \nSELECT name, median(star_rating) OVER (PARTITION BY name)\nFROM book_rating;\n \n+-----------------------+----------------------------------------------+\n| name | median(star_rating) OVER (PARTITION BY name) |\n+-----------------------+----------------------------------------------+\n| Lord of the Ladybirds | 4.0000000000 |\n| Lord of the Ladybirds | 4.0000000000 |\n| Lady of the Flies | 2.0000000000 |\n| Lady of the Flies | 2.0000000000 |\n| Lady of the Flies | 2.0000000000 |\n+-----------------------+----------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/median/','','https://mariadb.com/kb/en/median/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (718,42,'NTH_VALUE','The NTH_VALUE() function was first introduced with other\nwindow functions in MariaDB 10.2.\n \nSyntax\n------ \nNTH_VALUE (expr[, num_row]) OVER ( \n [ PARTITION BY partition_expression ] \n [ ORDER BY order_list ]\n)\n \nDescription\n----------- \nThe NTH_VALUE function returns the value evaluated at row\nnumber num_row of the window frame, starting from 1, or NULL\nif the row does not exist.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/nth_value/','','https://mariadb.com/kb/en/nth_value/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (719,42,'NTILE','The NTILE() function was first introduced with window\nfunctions in MariaDB 10.2.0.\n \nSyntax\n------ \nNTILE (expr) OVER ( \n [ PARTITION BY partition_expression ] \n [ ORDER BY order_list ]\n)\n \nDescription\n----------- \nNTILE() is a window function that returns an integer\nindicating which group a given row falls into. The number of\ngroups is specified in the argument (expr), starting at one.\nOrdered rows in the partition are divided into the specified\nnumber of groups with as equal a size as possible. \n \nExamples\n-------- \ncreate table t1 (\n pk int primary key,\n a int,\n b int\n );\n \ninsert into t1 values\n (11 , 0, 10),\n (12 , 0, 10),\n (13 , 1, 10),\n (14 , 1, 10),\n (18 , 2, 10),\n (15 , 2, 20),\n (16 , 2, 20),\n (17 , 2, 20),\n (19 , 4, 20),\n (20 , 4, 20);\n \nselect pk, a, b,\n ntile(1) over (order by pk)\n from t1;\n \n+----+------+------+-----------------------------+\n| pk | a | b | ntile(1) over (order by pk) |\n+----+------+------+-----------------------------+\n| 11 | 0 | 10 | 1 |\n| 12 | 0 | 10 | 1 |\n| 13 | 1 | 10 | 1 |\n| 14 | 1 | 10 | 1 |\n| 15 | 2 | 20 | 1 |\n| 16 | 2 | 20 | 1 |\n| 17 | 2 | 20 | 1 |\n| 18 | 2 | 10 | 1 |\n| 19 | 4 | 20 | 1 |\n| 20 | 4 | 20 | 1 |\n+----+------+------+-----------------------------+\n \nselect pk, a, b,\n ntile(4) over (order by pk)\n from t1;\n \n+----+------+------+-----------------------------+\n| pk | a | b | ntile(4) over (order by pk) |\n+----+------+------+-----------------------------+\n| 11 | 0 | 10 | 1 |\n| 12 | 0 | 10 | 1 |\n| 13 | 1 | 10 | 1 |\n| 14 | 1 | 10 | 2 |\n| 15 | 2 | 20 | 2 |\n| 16 | 2 | 20 | 2 |\n| 17 | 2 | 20 | 3 |\n| 18 | 2 | 10 | 3 |\n| 19 | 4 | 20 | 4 |\n| 20 | 4 | 20 | 4 |\n+----+------+------+-----------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/ntile/','','https://mariadb.com/kb/en/ntile/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (720,42,'PERCENT_RANK','The PERCENT_RANK() function was first introduced with window\nfunctions in MariaDB 10.2.0.\n \nSyntax\n------ \nPERCENT_RANK() OVER (\n [ PARTITION BY partition_expression ] \n [ ORDER BY order_list ]\n)\n \nDescription\n----------- \nPERCENT_RANK() is a window function that returns the\nrelative percent rank of a given row. The following formula\nis used to calculate the percent rank:\n \n(rank - 1) / (number of rows in the window or partition - 1)\n \nExamples\n-------- \ncreate table t1 (\n pk int primary key,\n a int,\n b int\n);\n \ninsert into t1 values\n( 1 , 0, 10),\n( 2 , 0, 10),\n( 3 , 1, 10),\n( 4 , 1, 10),\n( 8 , 2, 10),\n( 5 , 2, 20),\n( 6 , 2, 20),\n( 7 , 2, 20),\n( 9 , 4, 20),\n(10 , 4, 20);\n \nselect pk, a, b,\n rank() over (order by a) as rank,\n percent_rank() over (order by a) as pct_rank,\n cume_dist() over (order by a) as cume_dist\nfrom t1;\n \n+----+------+------+------+--------------+--------------+\n| pk | a | b | rank | pct_rank | cume_dist |\n+----+------+------+------+--------------+--------------+\n| 1 | 0 | 10 | 1 | 0.0000000000 | 0.2000000000 |\n| 2 | 0 | 10 | 1 | 0.0000000000 | 0.2000000000 |\n| 3 | 1 | 10 | 3 | 0.2222222222 | 0.4000000000 |\n| 4 | 1 | 10 | 3 | 0.2222222222 | 0.4000000000 |\n| 5 | 2 | 20 | 5 | 0.4444444444 | 0.8000000000 |\n| 6 | 2 | 20 | 5 | 0.4444444444 | 0.8000000000 |\n| 7 | 2 | 20 | 5 | 0.4444444444 | 0.8000000000 |\n| 8 | 2 | 10 | 5 | 0.4444444444 | 0.8000000000 |\n| 9 | 4 | 20 | 9 | 0.8888888889 | 1.0000000000 |\n| 10 | 4 | 20 | 9 | 0.8888888889 | 1.0000000000 |\n+----+------+------+------+--------------+--------------+\n \nselect pk, a, b,\n percent_rank() over (order by pk) as pct_rank,\n cume_dist() over (order by pk) as cume_dist\nfrom t1 order by pk;\n \n+----+------+------+--------------+--------------+\n| pk | a | b | pct_rank | cume_dist |\n+----+------+------+--------------+--------------+\n| 1 | 0 | 10 | 0.0000000000 | 0.1000000000 |\n| 2 | 0 | 10 | 0.1111111111 | 0.2000000000 |\n| 3 | 1 | 10 | 0.2222222222 | 0.3000000000 |\n| 4 | 1 | 10 | 0.3333333333 | 0.4000000000 |\n| 5 | 2 | 20 | 0.4444444444 | 0.5000000000 |\n| 6 | 2 | 20 | 0.5555555556 | 0.6000000000 |\n| 7 | 2 | 20 | 0.6666666667 | 0.7000000000 |\n| 8 | 2 | 10 | 0.7777777778 | 0.8000000000 |\n| 9 | 4 | 20 | 0.8888888889 | 0.9000000000 |\n| 10 | 4 | 20 | 1.0000000000 | 1.0000000000 |\n+----+------+------+--------------+--------------+\n \nselect pk, a, b,\n percent_rank() over (partition by a order by a) as\npct_rank,\n cume_dist() over (partition by a order by a) as cume_dist\nfrom t1;\n \n+----+------+------+--------------+--------------+\n| pk | a | b | pct_rank | cume_dist |\n+----+------+------+--------------+--------------+\n| 1 | 0 | 10 | 0.0000000000 | 1.0000000000 |\n| 2 | 0 | 10 | 0.0000000000 | 1.0000000000 |\n| 3 | 1 | 10 | 0.0000000000 | 1.0000000000 |\n| 4 | 1 | 10 | 0.0000000000 | 1.0000000000 |\n| 5 | 2 | 20 | 0.0000000000 | 1.0000000000 |\n| 6 | 2 | 20 | 0.0000000000 | 1.0000000000 |\n| 7 | 2 | 20 | 0.0000000000 | 1.0000000000 |\n| 8 | 2 | 10 | 0.0000000000 | 1.0000000000 |\n| 9 | 4 | 20 | 0.0000000000 | 1.0000000000 |\n| 10 | 4 | 20 | 0.0000000000 | 1.0000000000 |\n+----+------+------+--------------+--------------+\n \n\n\nURL: https://mariadb.com/kb/en/percent_rank/','','https://mariadb.com/kb/en/percent_rank/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (721,42,'PERCENTILE_CONT','The PERCENTILE_CONT() window function was first introduced\nwith in MariaDB 10.3.3.\n \nSyntax\n------ \nDescription\n----------- \nPERCENTILE_CONT() (standing for continuous percentile) is a\nwindow function which returns a value which corresponds to\nthe given fraction in the sort order. If required, it will\ninterpolate between adjacent input items.\n \nEssentially, the following process is followed to find the\nvalue to return:\nGet the number of rows in the partition, denoted by N\nRN = p*(N-1), where p denotes the argument to the\nPERCENTILE_CONT function\ncalculate the FRN(floor row number) and CRN(column row\nnumber for the group( FRN= floor(RN) and CRN = ceil(RN))\nlook up rows FRN and CRN\nIf (CRN = FRN = RN) then the result is (value of expression\nfrom row at RN)\nOtherwise the result is\n(CRN - RN) * (value of expression for row at FRN) +\n(RN - FRN) * (value of expression for row at CRN)\n \nThe MEDIAN function is a specific case of PERCENTILE_CONT,\nequivalent to PERCENTILE_CONT(0.5).\n \nExamples\n-------- \nCREATE TABLE book_rating (name CHAR(30), star_rating\nTINYINT);\n \nINSERT INTO book_rating VALUES (\'Lord of the Ladybirds\',\n5);\nINSERT INTO book_rating VALUES (\'Lord of the Ladybirds\',\n3);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 1);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 2);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 5);\n \nSELECT name, PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY\nstar_rating) \n OVER (PARTITION BY name) AS pc \n FROM book_rating;\n \n+-----------------------+--------------+\n| name | pc |\n+-----------------------+--------------+\n| Lord of the Ladybirds | 4.0000000000 |\n| Lord of the Ladybirds | 4.0000000000 |\n| Lady of the Flies | 2.0000000000 |\n| Lady of the Flies | 2.0000000000 |\n| Lady of the Flies | 2.0000000000 |\n+-----------------------+--------------+\n \nSELECT name, PERCENTILE_CONT(1) WITHIN GROUP (ORDER BY\nstar_rating) \n OVER (PARTITION BY name) AS pc \n FROM book_rating;\n \n+-----------------------+--------------+\n| name | pc |\n+-----------------------+--------------+\n| Lord of the Ladybirds | 5.0000000000 |\n| Lord of the Ladybirds | 5.0000000000 |\n| Lady of the Flies | 5.0000000000 |\n| Lady of the Flies | 5.0000000000 |\n| Lady of the Flies | 5.0000000000 |\n+-----------------------+--------------+\n \nSELECT name, PERCENTILE_CONT(0) WITHIN GROUP (ORDER BY\nstar_rating) \n OVER (PARTITION BY name) AS pc \n FROM book_rating;\n \n+-----------------------+--------------+\n| name | pc |\n+-----------------------+--------------+\n| Lord of the Ladybirds | 3.0000000000 |\n| Lord of the Ladybirds | 3.0000000000 |\n| Lady of the Flies | 1.0000000000 |\n| Lady of the Flies | 1.0000000000 |\n| Lady of the Flies | 1.0000000000 |\n+-----------------------+--------------+\n \nSELECT name, PERCENTILE_CONT(0.6) WITHIN GROUP (ORDER BY\nstar_rating) \n OVER (PARTITION BY name) AS pc \n FROM book_rating;\n \n+-----------------------+--------------+\n| name | pc |\n+-----------------------+--------------+\n| Lord of the Ladybirds | 4.2000000000 |\n| Lord of the Ladybirds | 4.2000000000 |\n| Lady of the Flies | 2.6000000000 |\n| Lady of the Flies | 2.6000000000 |\n| Lady of the Flies | 2.6000000000 |\n+-----------------------+--------------+\n \n\n\nURL: https://mariadb.com/kb/en/percentile_cont/','','https://mariadb.com/kb/en/percentile_cont/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (722,42,'PERCENTILE_DISC','The PERCENTILE_DISC() window function was first introduced\nwith in MariaDB 10.3.3.\n \nSyntax\n------ \n\nDescription\n----------- \nPERCENTILE_DISC() (standing for discrete percentile) is a\nwindow function which returns the first value in the set\nwhose ordered position is the same or more than the\nspecified fraction.\n \nEssentially, the following process is followed to find the\nvalue to return:\nGet the number of rows in the partition.\nWalk through the partition, in order, until finding the the\nfirst row with CUME_DIST() > function_argument.\n \nExamples\n-------- \nCREATE TABLE book_rating (name CHAR(30), star_rating\nTINYINT);\n \nINSERT INTO book_rating VALUES (\'Lord of the Ladybirds\',\n5);\nINSERT INTO book_rating VALUES (\'Lord of the Ladybirds\',\n3);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 1);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 2);\nINSERT INTO book_rating VALUES (\'Lady of the Flies\', 5);\n \nSELECT name, PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY\nstar_rating)\n OVER (PARTITION BY name) AS pc FROM book_rating;\n \n+-----------------------+------+\n| name | pc |\n+-----------------------+------+\n| Lord of the Ladybirds | 3 |\n| Lord of the Ladybirds | 3 |\n| Lady of the Flies | 2 |\n| Lady of the Flies | 2 |\n| Lady of the Flies | 2 |\n+-----------------------+------+\n5 rows in set (0.000 sec)\n \nSELECT name, PERCENTILE_DISC(0) WITHIN GROUP (ORDER BY\nstar_rating) \n OVER (PARTITION BY name) AS pc FROM book_rating;\n \n+-----------------------+------+\n| name | pc |\n+-----------------------+------+\n| Lord of the Ladybirds | 3 |\n| Lord of the Ladybirds | 3 |\n| Lady of the Flies | 1 |\n| Lady of the Flies | 1 |\n| Lady of the Flies | 1 |\n+-----------------------+------+\n5 rows in set (0.000 sec)\n \nSELECT name, PERCENTILE_DISC(1) WITHIN GROUP (ORDER BY\nstar_rating) \n OVER (PARTITION BY name) AS pc FROM book_rating;\n \n+-----------------------+------+\n| name | pc |\n+-----------------------+------+\n| Lord of the Ladybirds | 5 |\n| Lord of the Ladybirds | 5 |\n| Lady of the Flies | 5 |\n| Lady of the Flies | 5 |\n| Lady of the Flies | 5 |\n+-----------------------+------+\n5 rows in set (0.000 sec)\n \nSELECT name, PERCENTILE_DISC(0.6) WITHIN GROUP (ORDER BY\nstar_rating) \n OVER (PARTITION BY name) AS pc FROM book_rating;\n \n+-----------------------+------+\n| name | pc |\n+-----------------------+------+\n| Lord of the Ladybirds | 5 |\n| Lord of the Ladybirds | 5 |\n| Lady of the Flies | 2 |\n| Lady of the Flies | 2 |\n| Lady of the Flies | 2 |\n+-----------------------+------\n \n\n\nURL: https://mariadb.com/kb/en/percentile_disc/','','https://mariadb.com/kb/en/percentile_disc/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (723,42,'RANK','The RANK() function was first introduced with window\nfunctions in MariaDB 10.2.0.\n \nSyntax\n------ \nRANK() OVER (\n [ PARTITION BY partition_expression ]\n [ ORDER BY order_list ]\n) \n \nDescription\n----------- \nRANK() is a window function that displays the number of a\ngiven row, starting at one and following the ORDER BY\nsequence of the window function, with identical values\nreceiving the same result. It is similar to the ROW_NUMBER()\nfunction except that in that function, identical values will\nreceive a different row number for each result.\n \nExamples\n-------- \nThe distinction between DENSE_RANK(), RANK() and\nROW_NUMBER():\n \nCREATE TABLE student(course VARCHAR(10), mark int, name\nvarchar(10));\n \nINSERT INTO student VALUES \n (\'Maths\', 60, \'Thulile\'),\n (\'Maths\', 60, \'Pritha\'),\n (\'Maths\', 70, \'Voitto\'),\n (\'Maths\', 55, \'Chun\'),\n (\'Biology\', 60, \'Bilal\'),\n (\'Biology\', 70, \'Roger\');\n \nSELECT \n RANK() OVER (PARTITION BY course ORDER BY mark DESC) AS\nrank, \n DENSE_RANK() OVER (PARTITION BY course ORDER BY mark DESC)\nAS dense_rank, \n ROW_NUMBER() OVER (PARTITION BY course ORDER BY mark DESC)\nAS row_num, \n course, mark, name \nFROM student ORDER BY course, mark DESC;\n \n+------+------------+---------+---------+------+---------+\n| rank | dense_rank | row_num | course | mark | name |\n+------+------------+---------+---------+------+---------+\n| 1 | 1 | 1 | Biology | 70 | Roger |\n| 2 | 2 | 2 | Biology | 60 | Bilal |\n| 1 | 1 | 1 | Maths | 70 | Voitto |\n| 2 | 2 | 2 | Maths | 60 | Thulile |\n| 2 | 2 | 3 | Maths | 60 | Pritha |\n| 4 | 3 | 4 | Maths | 55 | Chun |\n+------+------------+---------+---------+------+---------+\n \n\n\nURL: https://mariadb.com/kb/en/rank/','','https://mariadb.com/kb/en/rank/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (724,42,'ROW_NUMBER','ROW_NUMBER() was first introduced with window functions in\nMariaDB 10.2.0.\n \nSyntax\n------ \nROW_NUMBER() OVER (\n [ PARTITION BY partition_expression ]\n [ ORDER BY order_list ]\n) \n \nDescription\n----------- \nROW_NUMBER() is a window function that displays the number\nof a given row, starting at one and following the ORDER BY\nsequence of the window function, with identical values\nreceiving different row numbers. It is similar to the RANK()\nand DENSE_RANK() functions except that in that function,\nidentical values will receive the same rank for each result.\n \nExamples\n-------- \nThe distinction between DENSE_RANK(), RANK() and\nROW_NUMBER():\n \nCREATE TABLE student(course VARCHAR(10), mark int, name\nvarchar(10));\n \nINSERT INTO student VALUES \n (\'Maths\', 60, \'Thulile\'),\n (\'Maths\', 60, \'Pritha\'),\n (\'Maths\', 70, \'Voitto\'),\n (\'Maths\', 55, \'Chun\'),\n (\'Biology\', 60, \'Bilal\'),\n (\'Biology\', 70, \'Roger\');\n \nSELECT \n RANK() OVER (PARTITION BY course ORDER BY mark DESC) AS\nrank, \n DENSE_RANK() OVER (PARTITION BY course ORDER BY mark DESC)\nAS dense_rank, \n ROW_NUMBER() OVER (PARTITION BY course ORDER BY mark DESC)\nAS row_num, \n course, mark, name \nFROM student ORDER BY course, mark DESC;\n \n+------+------------+---------+---------+------+---------+\n| rank | dense_rank | row_num | course | mark | name |\n+------+------------+---------+---------+------+---------+\n| 1 | 1 | 1 | Biology | 70 | Roger |\n| 2 | 2 | 2 | Biology | 60 | Bilal |\n| 1 | 1 | 1 | Maths | 70 | Voitto |\n| 2 | 2 | 2 | Maths | 60 | Thulile |\n| 2 | 2 | 3 | Maths | 60 | Pritha |\n| 4 | 3 | 4 | Maths | 55 | Chun |\n+------+------------+---------+---------+------+---------+\n \n\n\nURL: https://mariadb.com/kb/en/row_number/','','https://mariadb.com/kb/en/row_number/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (725,43,'SPIDER_BG_DIRECT_SQL','Syntax\n------ \nSPIDER_BG_DIRECT_SQL(\'sql\', \'tmp_table_list\',\n\'parameters\')\n \nDescription\n----------- \nExecutes the given SQL statement in the background on the\nremote server, as defined in the parameters listing. If the\nquery returns a result-set, it sttores the results in the\ngiven temporary table. When the given SQL statement executes\nsuccessfully, this function returns the number of called\nUDF\'s. It returns 0 when the given SQL statement fails.\n \nThis function is a UDF installed with the Spider storage\nengine.\n \nExamples\n-------- \nSELECT SPIDER_BG_DIRECT_SQL(\'SELECT * FROM example_table\',\n\'\', \n \'srv \"node1\", port \"8607\"\') AS \"Direct Query\";\n+--------------+\n| Direct Query | \n+--------------+\n| 1 |\n+--------------+\n \nParameters\n \nerror_rw_mode\n \nDescription: Returns empty results on network error.\n0 : Return error on getting network error.\n1: Return 0 records on getting network error.\n \nDefault Table Value: 0\nDSN Parameter Name: erwm\n \n\n\nURL: https://mariadb.com/kb/en/spider_bg_direct_sql/','','https://mariadb.com/kb/en/spider_bg_direct_sql/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (726,43,'SPIDER_COPY_TABLES','Syntax\n------ \nSPIDER_COPY_TABLES(spider_table_name, \n source_link_id, destination_link_id_list [,parameters])\n \nDescription\n----------- \nA UDF installed with the Spider Storage Engine, this\nfunction copies table data from source_link_id to\ndestination_link_id_list. The service does not need to be\nstopped in order to copy.\n \nIf the Spider table is partitioned, the name must be of the\nformat table_name#P#partition_name. The partition name can\nbe viewed in the mysql.spider_tables table, for example:\n \nSELECT table_name FROM mysql.spider_tables;\n+-------------+\n| table_name |\n+-------------+\n| spt_a#P#pt1 |\n| spt_a#P#pt2 |\n| spt_a#P#pt3 |\n+-------------+\n \nReturns 1 if the data was copied successfully, or 0 if\ncopying the data failed.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/spider_copy_tables/','','https://mariadb.com/kb/en/spider_copy_tables/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (727,43,'SPIDER_DIRECT_SQL','Syntax\n------ \nSPIDER_DIRECT_SQL(\'sql\', \'tmp_table_list\',\n\'parameters\')\n \nDescription\n----------- \nA UDF installed with the Spider Storage Engine, this\nfunction is used to execute the SQL string sql on the remote\nserver, as defined in parameters. If any resultsets are\nreturned, they are stored in the tmp_table_list.\n \nThe function returns 1 if the SQL executes successfully, or\n0 if it fails.\n \nExamples\n-------- \nSELECT SPIDER_DIRECT_SQL(\'SELECT * FROM s\', \'\', \'srv\n\"node1\", port \"8607\"\');\n+----------------------------------------------------------------------+\n| SPIDER_DIRECT_SQL(\'SELECT * FROM s\', \'\', \'srv\n\"node1\", port \"8607\"\') |\n+----------------------------------------------------------------------+\n| 1 |\n+----------------------------------------------------------------------+\n \n\n\nURL: https://mariadb.com/kb/en/spider_direct_sql/','','https://mariadb.com/kb/en/spider_direct_sql/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (728,43,'SPIDER_FLUSH_TABLE_MON_CACHE','Syntax\n------ \nSPIDER_FLUSH_TABLE_MON_CACHE()\n \nDescription\n----------- \nA UDF installed with the Spider Storage Engine, this\nfunction is used for refreshing monitoring server\ninformation. It returns a value of 1.\n \nExamples\n-------- \nSELECT SPIDER_FLUSH_TABLE_MON_CACHE();\n+--------------------------------+\n| SPIDER_FLUSH_TABLE_MON_CACHE() |\n+--------------------------------+\n| 1 |\n+--------------------------------+\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/spider_flush_table_mon_cache/','','https://mariadb.com/kb/en/spider_flush_table_mon_cache/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (729,44,'COLUMN_ADD','The Dynamic columns feature was introduced in MariaDB 5.3.\n \nSyntax\n------ \nCOLUMN_ADD(dyncol_blob, column_nr, value [as type],\n[column_nr, value [as type]]...);\nCOLUMN_ADD(dyncol_blob, column_name, value [as type],\n[column_name, value [as type]]...);\n \nDescription\n----------- \nAdds or updates dynamic columns.\ndyncol_blob must be either a valid dynamic columns blob (for\nexample, COLUMN_CREATE returns such blob), or an empty\nstring.\ncolumn_name specifies the name of the column to be added. If\ndyncol_blob already has a column with this name, it will be\noverwritten.\nvalue specifies the new value for the column. Passing a NULL\nvalue will cause the column to be deleted.\nas type is optional. See #datatypes section for a discussion\nabout types.\n \nThe return value is a dynamic column blob after the\nmodifications.\n \nExamples\n-------- \n-- MariaDB 5.3+:\nUPDATE tbl SET dyncol_blob=COLUMN_ADD(dyncol_blob, 1\n/*column id*/, \"value\") WHERE id=1;\n \n-- MariaDB 10.0.1+:\nUPDATE t1 SET dyncol_blob=COLUMN_ADD(dyncol_blob,\n\"column_name\", \"value\") WHERE id=1;\n \nNote: COLUMN_ADD() is a regular function (just like\nCONCAT()), hence, in order to update the value in the table\nyou have to use the UPDATE ... SET\ndynamic_col=COLUMN_ADD(dynamic_col,\n....) pattern.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_add/','','https://mariadb.com/kb/en/column_add/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (730,44,'COLUMN_CHECK','The COLUMN_CHECK function was added in MariaDB 10.0.1.\n \nSyntax\n------ \nCOLUMN_CHECK(dyncol_blob);\n \nDescription\n----------- \nCheck if dyncol_blob is a valid packed dynamic columns blob.\nReturn value of 1 means the blob is valid, return value of 0\nmeans it is not.\n \nRationale:\nNormally, one works with valid dynamic column blobs.\nFunctions like COLUMN_CREATE, COLUMN_ADD, COLUMN_DELETE\nalways return valid dynamic column blobs. However, if a\ndynamic column blob is accidentally truncated, or transcoded\nfrom one character set to another, it will be corrupted.\nThis function can be used to check if a value in a blob\nfield is a valid dynamic column blob.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_check/','','https://mariadb.com/kb/en/column_check/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (731,44,'COLUMN_CREATE','The Dynamic columns feature was introduced in MariaDB 5.3.\n \nSyntax\n------ \nCOLUMN_CREATE(column_nr, value [as type], [column_nr, value\n[as type]]...);\nCOLUMN_CREATE(column_name, value [as type], [column_name,\nvalue [as type]]...);\n \nDescription\n----------- \nReturns a dynamic columns blob that stores the specified\ncolumns with values.\n \nThe return value is suitable for \nstoring in a table\nfurther modification with other dynamic columns functions\n \nThe as type part allows one to specify the value type. In\nmost cases,\nthis is redundant because MariaDB will be able to deduce the\ntype of the\nvalue. Explicit type specification may be needed when the\ntype of the value is\nnot apparent. For example, a literal \'2012-12-01\' has a\nCHAR type by\ndefault, one will need to specify \'2012-12-01\' AS DATE to\nhave it stored as\na date. See Dynamic Columns:Datatypes for further details.\n \nExamples\n-------- \n-- MariaDB 5.3+:\nINSERT INTO tbl SET dyncol_blob=COLUMN_CREATE(1 /*column\nid*/, \"value\");\n-- MariaDB 10.0.1+:\nINSERT INTO tbl SET\ndyncol_blob=COLUMN_CREATE(\"column_name\", \"value\");\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_create/','','https://mariadb.com/kb/en/column_create/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (732,44,'COLUMN_DELETE','The Dynamic columns feature was introduced in MariaDB 5.3.\n \nSyntax\n------ \nCOLUMN_DELETE(dyncol_blob, column_nr, column_nr...);\nCOLUMN_DELETE(dyncol_blob, column_name, column_name...);\n \nDescription\n----------- \nDeletes a dynamic column with the specified name. Multiple\nnames can be given. The return value is a dynamic column\nblob after the modification.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_delete/','','https://mariadb.com/kb/en/column_delete/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (733,44,'COLUMN_EXISTS','The Dynamic columns feature was introduced in MariaDB 5.3.\n \nSyntax\n------ \nCOLUMN_EXISTS(dyncol_blob, column_nr);\nCOLUMN_EXISTS(dyncol_blob, column_name);\n \nDescription\n----------- \nChecks if a column with name column_name exists in\ndyncol_blob. If yes, return 1, otherwise return 0. See\ndynamic columns for more information.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_exists/','','https://mariadb.com/kb/en/column_exists/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (734,44,'COLUMN_GET','The Dynamic columns feature was introduced in MariaDB 5.3.\n \nSyntax\n------ \nCOLUMN_GET(dyncol_blob, column_nr as type);\nCOLUMN_GET(dyncol_blob, column_name as type);\n \nDescription\n----------- \nGets the value of a dynamic column by its name. If no column\nwith the given name exists, NULL will be returned.\n \ncolumn_name as type requires that one specify the datatype\nof the dynamic column they are reading. \n \nThis may seem counter-intuitive: why would one need to\nspecify which datatype they\'re retrieving? Can\'t the\ndynamic columns system figure the datatype from the data\nbeing stored?\n \nThe answer is: SQL is a statically-typed language. The SQL\ninterpreter needs to know the datatypes of all expressions\nbefore the query is run (for example, when one is using\nprepared statements and runs \"select COLUMN_GET(...)\", the\nprepared statement API requires the server to inform the\nclient about the datatype of the column being read before\nthe query is executed and the server can see what datatype\nthe column actually has).\n \nA note about lengths\n \nIf you\'re running queries like:\n \nSELECT COLUMN_GET(blob, \'colname\' as CHAR) ...\n \nwithout specifying a maximum length (i.e. using #as CHAR#,\nnot as CHAR(n)), MariaDB will report the maximum length of\nthe resultset column to be 53,6870,911 for MariaDB\n5.3-10.0.0 and 16,777,216 for MariaDB 10.0.1+. This may\ncause excessive memory usage in some client libraries,\nbecause they try to pre-allocate a buffer of maximum\nresultset width. To avoid this problem, use CHAR(n) whenever\nyou\'re using COLUMN_GET in the select list.\n \nSee Dynamic Columns:Datatypes for more information about\ndatatypes.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_get/','','https://mariadb.com/kb/en/column_get/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (735,44,'COLUMN_JSON','COLUMN_JSON was introduced in MariaDB 10.0.1\n \nSyntax\n------ \nCOLUMN_JSON(dyncol_blob)\n \nDescription\n----------- \nReturns a JSON representation of data in dyncol_blob. Can\nalso be used to display nested columns. See dynamic columns\nfor more information.\n \nExample\n \nselect item_name, COLUMN_JSON(dynamic_cols) from assets;\n+-----------------+----------------------------------------+\n| item_name | COLUMN_JSON(dynamic_cols) |\n+-----------------+----------------------------------------+\n| MariaDB T-shirt | {\"size\":\"XL\",\"color\":\"blue\"} |\n| Thinkpad Laptop | {\"color\":\"black\",\"warranty\":\"3\nyears\"} |\n+-----------------+----------------------------------------+\n \nLimitation: COLUMN_JSON will decode nested dynamic columns\nat a nesting level of not more than 10 levels deep. Dynamic\ncolumns that are nested deeper than 10 levels will be shown\nas BINARY string, without encoding.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_json/','','https://mariadb.com/kb/en/column_json/'); +insert into help_topic (help_topic_id,help_category_id,name,description,example,url) values (736,44,'COLUMN_LIST','The Dynamic columns feature was introduced in MariaDB 5.3.\n \nSyntax\n------ \nCOLUMN_LIST(dyncol_blob);\n \nDescription\n----------- \nSince MariaDB 10.0.1, this function returns a\ncomma-separated list of column names. The names are quoted\nwith backticks.\n \nBefore MariaDB 10.0.1, it returned a comma-separated list of\ncolumn numbers, not names.\n \nSee dynamic columns for more information.\n \n\n \n \n \n \n \n \n \n\nURL: https://mariadb.com/kb/en/column_list/','','https://mariadb.com/kb/en/column_list/'); +insert into help_keyword values (1,'master_ssl_verify_cert'); +insert into help_keyword values (2,'drop prepare'); +insert into help_keyword values (3,'work'); +insert into help_keyword values (4,'drop'); +insert into help_keyword values (5,'returns'); +insert into help_keyword values (6,'value'); +insert into help_keyword values (7,'nchar'); +insert into help_keyword values (8,'repeat'); +insert into help_keyword values (9,'columns'); +insert into help_keyword values (10,'sql_big_result'); +insert into help_keyword values (11,'escape'); +insert into help_keyword values (12,'mode'); +insert into help_keyword values (13,'schedule'); +insert into help_keyword values (14,'starts'); +insert into help_keyword values (15,'host'); +insert into help_keyword values (16,'row_format'); +insert into help_relation values (95,1); +insert into help_relation values (97,2); +insert into help_relation values (110,3); +insert into help_relation values (120,4); +insert into help_relation values (128,4); +insert into help_relation values (258,5); +insert into help_relation values (259,4); +insert into help_relation values (264,6); +insert into help_relation values (271,7); +insert into help_relation values (316,8); +insert into help_relation values (317,6); +insert into help_relation values (320,6); +insert into help_relation values (355,9); +insert into help_relation values (417,6); +insert into help_relation values (433,6); +insert into help_relation values (434,10); +insert into help_relation values (603,11); +insert into help_relation values (610,12); +insert into help_relation values (621,8); +insert into help_relation values (642,13); +insert into help_relation values (647,4); +insert into help_relation values (652,14); +insert into help_relation values (659,15); +insert into help_relation values (660,16); +insert into help_relation values (664,4); +insert into help_relation values (665,4); +insert into help_relation values (666,4); +insert into help_relation values (667,4); +insert into help_relation values (668,4); +insert into help_relation values (669,4); +insert into help_relation values (670,4); +insert into help_relation values (671,4); +insert into help_relation values (672,4); +insert into help_relation values (673,4); +insert into help_relation values (675,4); +insert into help_relation values (676,4); +unlock tables; diff --git a/scripts/galera_new_cluster.sh b/scripts/galera_new_cluster.sh new file mode 100755 index 00000000..e0763ed5 --- /dev/null +++ b/scripts/galera_new_cluster.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation; either version 2.1 of the License, or +# (at your option) any later version. + +if [ "${1}" = "-h" ] || [ "${1}" = "--help" ]; then + cat <<EOF + +Usage: ${0} + + The script galera_new_cluster is used to bootstrap new Galera Cluster, + when all the nodes are down. Run galera_new_cluster on the first node only. + On the remaining nodes simply run 'service @DAEMON_NAME@ start'. + + For more information on Galera Cluster configuration and usage see: + https://mariadb.com/kb/en/mariadb/getting-started-with-mariadb-galera-cluster/ + +EOF + exit 0 +fi + +systemctl set-environment _WSREP_NEW_CLUSTER='--wsrep-new-cluster' && \ + systemctl start ${1:-mariadb} + +extcode=$? + +systemctl set-environment _WSREP_NEW_CLUSTER='' + +exit $extcode diff --git a/scripts/galera_recovery.sh b/scripts/galera_recovery.sh new file mode 100644 index 00000000..8df2abc3 --- /dev/null +++ b/scripts/galera_recovery.sh @@ -0,0 +1,117 @@ +#!/bin/sh + +# Copyright (c) 2016 MariaDB Corporation +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA */ + + +# This script is intended to be executed by systemd. It starts mysqld with +# --wsrep-recover to recover from a non-graceful shutdown, determines the +# last stored global transaction ID and echoes it in --wsrep-start-position=XX +# format. The output is then captured and used by systemd to start mysqld. +# If the server was configured to start without wsrep, nothing is echoed. + +cmdline_args=$@ +user="@MYSQLD_USER@" +print_defaults="@bindir@/my_print_defaults" +log_file=$(mktemp /tmp/wsrep_recovery.XXXXXX) +euid=$(id -u) +recovered_pos="" +skipped="" +start_pos="" +start_pos_opt="" +ret=0 +wsrep_on=0 + +log () +{ + local msg="$1" + # Print all messages to stderr as we reserve stdout for printing + # --wsrep-start-position=XXXX. + echo "$msg" >&2 +} + +finish() +{ + rm -f "$log_file" +} + +trap finish EXIT + +parse_arguments() { + for arg do + val=`echo "$arg" | sed -e "s;--[^=]*=;;"` + case "$arg" in + --wsrep[-_]on) wsrep_on=1 ;; + --skip[-_]wsrep[-_]on) wsrep_on=0 ;; + --wsrep[-_]on=*) + if echo $val | grep -iq '\(ON\|1\)'; then + wsrep_on=1 + else + wsrep_on=0 + fi + ;; + esac + done +} + +wsrep_recover_position() { + # Redirect server's error log to the log file. + eval @sbindir@/mysqld $cmdline_args --user=$user --wsrep_recover \ + --disable-log-error 2> "$log_file" + ret=$? + if [ $ret -ne 0 ]; then + # Something went wrong, let us also print the error log so that it + # shows up in systemctl status output as a hint to the user. + log "WSREP: Failed to start mysqld for wsrep recovery: '`cat $log_file`'" + exit 1 + fi + + # Parse server's error log for recovered position. The server prints + # "..skipping position recovery.." if started without wsrep. + + recovered_pos="$(grep 'WSREP: Recovered position:' $log_file)" + + if [ -z "$recovered_pos" ]; then + skipped="$(grep WSREP $log_file | grep 'skipping position recovery')" + if [ -z "$skipped" ]; then + log "WSREP: Failed to recover position: '`cat $log_file`'" + exit 1 + else + log "WSREP: Position recovery skipped." + fi + else + start_pos="$(echo $recovered_pos | sed 's/.*WSREP\:\ Recovered\ position://' \ + | sed 's/^[ \t]*//')" + log "WSREP: Recovered position $start_pos" + start_pos_opt="--wsrep_start_position=$start_pos" + fi +} + +# Safety checks +if [ -n "$log_file" -a -f "$log_file" ]; then + chmod 600 $log_file +else + log "WSREP: mktemp failed" +fi + +parse_arguments `$print_defaults $cmdline_args --loose-verbose --mysqld` + +# Perform wsrep position recovery if wsrep_on=1, skip otherwise. +if [ "$wsrep_on" -eq 1 ]; then + wsrep_recover_position +fi + +echo "$start_pos_opt" + diff --git a/scripts/maria_add_gis_sp.sql.in b/scripts/maria_add_gis_sp.sql.in new file mode 100644 index 00000000..682cf52d --- /dev/null +++ b/scripts/maria_add_gis_sp.sql.in @@ -0,0 +1,37 @@ +-- Copyright (C) 2014 MariaDB Ab. +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; version 2 of the License. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +# This part creates stored procedures required by the OpenGIS standards. +# script is prepared to be run with the --bootstrap server option + +SET sql_mode=''; + +@ADD_GIS_SP_SET_DELIMITER@ + +DROP PROCEDURE IF EXISTS AddGeometryColumn; +DROP PROCEDURE IF EXISTS DropGeometryColumn; + +CREATE DEFINER=`mariadb.sys`@`localhost` PROCEDURE AddGeometryColumn(catalog varchar(64), t_schema varchar(64), + t_name varchar(64), geometry_column varchar(64), t_srid int) SQL SECURITY INVOKER +begin + set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' ADD ', geometry_column,' GEOMETRY REF_SYSTEM_ID=', t_srid); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end @ADD_GIS_SP_EOL@ + +CREATE DEFINER=`mariadb.sys`@`localhost` PROCEDURE DropGeometryColumn(catalog varchar(64), t_schema varchar(64), + t_name varchar(64), geometry_column varchar(64)) SQL SECURITY INVOKER +begin + set @qwe= concat('ALTER TABLE ', t_schema, '.', t_name, ' DROP ', geometry_column); PREPARE ls from @qwe; execute ls; deallocate prepare ls; end @ADD_GIS_SP_EOL@ + +@ADD_GIS_SP_RESET_DELIMITER@ + diff --git a/scripts/mariadb-service-convert b/scripts/mariadb-service-convert new file mode 100755 index 00000000..38043733 --- /dev/null +++ b/scripts/mariadb-service-convert @@ -0,0 +1,82 @@ +#!/bin/bash +# Copyright (c) 2015, Daniel Black. 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 +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA +# +# PURPOSE: +# +# Used to generate a mariadb.service file based on the current mysql/mariadb settings +# +# This is to assist distro maintainers in migrating to systemd service definations from +# a user mysqld_safe settings in the my.cnf files. +# +# Redirect output to user directory like /etc/systemd/system/mariadb.service.d/migrated-from-my.cnf-settings.conf + +tz_old=$TZ + +. /usr/bin/mysqld_safe --dry-run + +echo "# converted using $0" +echo "#" +echo + +echo '[Service]' + +echo + + +if [[ ( "$user" != "root" && "$user" != "mysql" ) || "${SET_USER}" == 1 ]]; then + echo User=$user +fi + + +[ -n "${open_files}" ] && echo LimitNOFILE=$open_files +[ -n "${core_file_size}" ] && echo LimitCORE=$core_file_size +[[ "${niceness}" -gt 0 ]] && echo Nice=$niceness +[ "${TZ}" != "${tz_old}" ] && echo Environment=\"TZ=${TZ}\" + +if [ -n "$mysqld_ld_preload" ]; then + new_text="$mysqld_ld_preload" + [ -n "$LD_PRELOAD" ] && new_text="$new_text $LD_PRELOAD" + echo Environment=\"LD_PRELOAD=`shell_quote_string "$new_text"`\" +fi + +if [ -n "$mysqld_ld_library_path" ]; then + new_text="$mysqld_ld_library_path" + [ -n "$LD_LIBRARY_PATH" ] && new_text="$new_text:$LD_LIBRARY_PATH" + echo Environment=\"LD_LIBRARY_PATH=`shell_quote_string "$new_text"`\" +fi + +if [[ $want_syslog -eq 1 ]]; then + echo StandardOutput=syslog + echo StandardError=syslog + echo SyslogFacility=daemon + echo SyslogLevel=err + echo SyslogIdentifier=${syslog_tag_mysqld} +fi + +if [[ "${flush_caches}" -gt 0 ]]; then + echo ExecStartPre=/usr/bin/sync + echo ExecStartPre=/usr/sbin/sysctl -q -w vm.drop_caches=3 +fi + +if [[ "${numa_interleave}" -gt 0 ]]; then + echo + echo ExecStart=/usr/bin/numactl --interleave=all ${cmd} '${MYSQLD_OPTS}' + echo +fi + +if [ -n "${CRASH_SCRIPT}" ]; then + echo FailureAction=${CRASH_SCRIPT} +fi diff --git a/scripts/msql2mysql.sh b/scripts/msql2mysql.sh new file mode 100644 index 00000000..72a609fa --- /dev/null +++ b/scripts/msql2mysql.sh @@ -0,0 +1,19 @@ +#!/bin/sh +# Copyright (C) 1979-2007 MySQL AB +# Use is subject to license terms +# +# 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; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston +# MA 02110-1335 USA. + +@bindir@/replace msqlConnect mysql_connect msqlListDBs mysql_list_dbs msqlNumRows mysql_num_rows msqlFetchRow mysql_fetch_row msqlFetchField mysql_fetch_field msqlFreeResult mysql_free_result msqlListFields mysql_list_fields msqlListTables mysql_list_tables msqlErrMsg 'mysql_error(mysql)' msqlStoreResult mysql_store_result msqlQuery mysql_query msqlField mysql_field msqlSelect mysql_select msqlSelectDB mysql_select_db msqlNumFields mysql_num_fields msqlClose mysql_close msqlDataSeek mysql_data_seek m_field MYSQL_FIELD m_result MYSQL_RES m_row MYSQL_ROW msql mysql mSQL mySQL MSQL MYSQL msqlCreateDB mysql_create_db msqlDropDB mysql_drop_db msqlFieldSeek mysql_field_seek -- $* diff --git a/scripts/mysql_config.pl.in b/scripts/mysql_config.pl.in new file mode 100644 index 00000000..e161d4a1 --- /dev/null +++ b/scripts/mysql_config.pl.in @@ -0,0 +1,284 @@ +#!@PERL_PATH@ +# -*- cperl -*- +# +# Copyright (c) 2007, 2017, 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 +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +############################################################################## +# +# This script reports various configuration settings that may be needed +# when using the MySQL client library. +# +# This script try to match the shell script version as close as possible, +# but in addition being compatible with ActiveState Perl on Windows. +# +# All unrecognized arguments to this script are passed to mysqld. +# +# NOTE: This script will only be used on Windows until solved how to +# handle @LIBS@ and other strings inserted that might contain +# several arguments, possibly with spaces in them. +# +# NOTE: This script was deliberately written to be as close to the shell +# script as possible, to make the maintenance of both in parallel +# easier. +# +############################################################################## + +use File::Basename; +use Getopt::Long; +use Cwd; +use strict; + +my @exclude_cflags = + qw/DDBUG_OFF DSAFE_MUTEX DUNIV_MUST_NOT_INLINE DFORCE_INIT_OF_VARS + DEXTRA_DEBUG DHAVE_valgrind O O[0-9] xO[0-9] W[-A-Za-z]* + Xa xstrconst xc99=none + unroll2 ip mp restrict/; + +my @exclude_libs = qw/lmtmalloc static-libcxa i-static static-intel/; + +my $cwd = cwd(); +my $basedir; + +my $socket = '@MYSQL_UNIX_ADDR@'; +my $version = '@VERSION@'; + +sub which +{ + my $file = shift; + + my $IFS = $^O eq "MSWin32" ? ";" : ":"; + + foreach my $dir ( split($IFS, $ENV{PATH}) ) + { + if ( -f "$dir/$file" or -f "$dir/$file.exe" ) + { + return "$dir/$file"; + } + } + print STDERR "which: no $file in ($ENV{PATH})\n"; + exit 1; +} + +# ---------------------------------------------------------------------- +# If we can find the given directory relatively to where mysql_config is +# we should use this instead of the incompiled one. +# This is to ensure that this script also works with the binary MySQL +# version +# ---------------------------------------------------------------------- + +sub fix_path +{ + my $default = shift; + my @dirs = @_; + + foreach my $dirname ( @dirs ) + { + my $path = "$basedir/$dirname"; + if ( -d $path ) + { + return $path; + } + } + return $default; +} + +sub get_full_path +{ + my $file = shift; + + # if the file is a symlink, try to resolve it + if ( $^O ne "MSWin32" and -l $file ) + { + $file = readlink($file); + } + + if ( $file =~ m,^/, ) + { + # Do nothing, absolute path + } + elsif ( $file =~ m,/, ) + { + # Make absolute, and remove "/./" in path + $file = "$cwd/$file"; + $file =~ s,/\./,/,g; + } + else + { + # Find in PATH + $file = which($file); + } + + return $file; +} + +############################################################################## +# +# Form a command line that can handle spaces in paths and arguments +# +############################################################################## + +sub quote_options { + my @cmd; + foreach my $opt ( @_ ) + { + next unless $opt; # If undefined or empty, just skip + push(@cmd, "\"$opt\""); # Quote argument + } + return join(" ", @cmd); +} + +############################################################################## +# +# Main program +# +############################################################################## + +my $me = get_full_path($0); +$basedir = dirname(dirname($me)); # Remove "/bin/mysql_config" part + +my $ldata = '@localstatedir@'; +my $execdir = '@libexecdir@'; +my $bindir = '@bindir@'; + +# ---------------------------------------------------------------------- +# If installed, search for the compiled in directory first (might be "lib64") +# ---------------------------------------------------------------------- + +my $pkglibdir = fix_path('@pkglibdir@',"libmysql/relwithdebinfo", + "libmysql/release","libmysql/debug","lib/mysql","lib"); + +my $pkgincludedir = fix_path('@pkgincludedir@', "include/mysql", "include"); + +# Assume no argument with space in it +my @ldflags = split(" ",'@LDFLAGS@'); + +my $port; +if ( '@MYSQL_TCP_PORT_DEFAULT@' == 0 ) { + $port = 0; +} else { + $port = '@MYSQL_TCP_PORT@'; +} + +# ---------------------------------------------------------------------- +# Create options +# We intentionally add a space to the beginning and end of lib strings, simplifies replace later +# ---------------------------------------------------------------------- + +my (@lib_opts,@lib_r_opts,@lib_e_opts); +if ( $^O eq "MSWin32" ) +{ + my $linkpath = "$pkglibdir"; + # user32 is only needed for debug or embedded + my @winlibs = ("wsock32.lib","advapi32.lib","user32.lib"); + @lib_opts = ("$linkpath/mysqlclient.lib",@winlibs); + @lib_r_opts = @lib_opts; + @lib_e_opts = ("$linkpath/mysqlserver.lib",@winlibs); +} +else +{ + my $linkpath = "-L$pkglibdir @RPATH_OPTION@"; + @lib_opts = ($linkpath,"-lmysqlclient"); + @lib_r_opts = ($linkpath,"-lmysqlclient_r"); + @lib_e_opts = ($linkpath,"-lmysqld"); +} + +my $flags; +$flags->{libs} = + [@ldflags,@lib_opts,'@ZLIB_DEPS@','@NON_THREADED_LIBS@','@openssl_libs@','@STATIC_NSS_FLAGS@']; +$flags->{libs_r} = + [@ldflags,@lib_r_opts,'@ZLIB_DEPS@','@LIBS@','@openssl_libs@']; +$flags->{embedded_libs} = + [@ldflags,@lib_e_opts,'@CMAKE_DL_LIBS@','@ZLIB_DEPS@','@LIBS@','@WRAPLIBS@','@openssl_libs@']; + +$flags->{include} = ["-I$pkgincludedir"]; +$flags->{cflags} = [@{$flags->{include}},split(" ",'@CFLAGS@')]; + +# ---------------------------------------------------------------------- +# Remove some options that a client doesn't have to care about +# FIXME until we have a --cxxflags, we need to remove -Xa +# and -xstrconst to make --cflags usable for Sun Forte C++ +# ---------------------------------------------------------------------- + +my $filter = join("|", @exclude_cflags); +my @tmp = @{$flags->{cflags}}; # Copy the flag list +$flags->{cflags} = []; # Clear it +foreach my $cflag ( @tmp ) +{ + push(@{$flags->{cflags}}, $cflag) unless $cflag =~ m/^($filter)$/o; +} + +# Same for --libs(_r) +$filter = join("|", @exclude_libs); +foreach my $lib_type ( "libs","libs_r","embedded_libs" ) +{ + my @tmp = @{$flags->{$lib_type}}; # Copy the flag list + $flags->{$lib_type} = []; # Clear it + foreach my $lib ( @tmp ) + { + push(@{$flags->{$lib_type}}, $lib) unless $lib =~ m/^($filter)$/o; + } +} + +my $include = quote_options(@{$flags->{include}}); +my $cflags = quote_options(@{$flags->{cflags}}); +my $libs = quote_options(@{$flags->{libs}}); +my $libs_r = quote_options(@{$flags->{libs_r}}); +my $embedded_libs = quote_options(@{$flags->{embedded_libs}}); + +############################################################################## +# +# Usage information, output if no option is given +# +############################################################################## + +sub usage +{ + print <<EOF; +Usage: $0 [OPTIONS] +Options: + --cflags [$cflags] + --include [$include] + --libs [$libs] + --libs_r [$libs_r] + --socket [$socket] + --port [$port] + --version [$version] + --libmysqld-libs [$embedded_libs] +EOF + exit 0; +} + +@ARGV or usage(); + +############################################################################## +# +# Get options and output the values +# +############################################################################## + +GetOptions( + "cflags" => sub { print "$cflags\n" }, + "include" => sub { print "$include\n" }, + "libs" => sub { print "$libs\n" }, + "libs_r" => sub { print "$libs_r\n" }, + "socket" => sub { print "$socket\n" }, + "port" => sub { print "$port\n" }, + "version" => sub { print "$version\n" }, + "embedded-libs|embedded|libmysqld-libs" => + sub { print "$embedded_libs\n" }, + ) or usage(); + +exit 0 diff --git a/scripts/mysql_config.sh b/scripts/mysql_config.sh new file mode 100644 index 00000000..8f78beee --- /dev/null +++ b/scripts/mysql_config.sh @@ -0,0 +1,169 @@ +#!/bin/sh +# Copyright (c) 2000, 2014, 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 +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +# This script reports various configuration settings that may be needed +# when using the MariaDB client library. + +# +# If we can find the given directory relatively to where mysql_config is +# we should use this instead of the incompiled one. +# This is to ensure that this script also works with the binary MariaDB +# version + +fix_path () +{ + var=$1 + shift + for filename + do + path=$basedir/$filename + if [ -d "$path" ] ; + then + eval "$var"=$path + return + fi + done +} + +get_full_path () +{ + file=$1 + + # if the file is a symlink, try to resolve it + if [ -h $file ]; + then + file=`ls -l $file | awk '{ print $NF }'` + fi + + case $file in + /*) echo "$file";; + */*) tmp=`pwd`/$file; echo $tmp | sed -e 's;/\./;/;' ;; + *) command -v $file ;; + esac +} + +me=`get_full_path $0` + +# Script might have been renamed but assume mysql_<something>config<something> +basedir=`echo $me | sed -e 's;/bin/mysql_.*config.*;;'` + +ldata='@localstatedir@' +execdir='@libexecdir@' +bindir='@bindir@' + +# If installed, search for the compiled in directory first (might be "lib64") +pkglibdir='@pkglibdir@' +pkglibdir_rel=`echo $pkglibdir | sed -e "s;^$basedir/;;"` +fix_path pkglibdir $pkglibdir_rel @libsubdir@/mysql @libsubdir@ + +plugindir='@pkgplugindir@' +plugindir_rel=`echo $plugindir | sed -e "s;^$basedir/;;"` +fix_path plugindir $plugindir_rel @libsubdir@/mysql/plugin @libsubdir@/plugin + +pkgincludedir='@pkgincludedir@' +fix_path pkgincludedir include/mysql + +version='@VERSION@' +socket='@MYSQL_UNIX_ADDR@' + +if [ @MYSQL_TCP_PORT_DEFAULT@ -eq 0 ]; then + port=0 +else + port=@MYSQL_TCP_PORT@ +fi + +# Create options +libs="-L$pkglibdir @RPATH_OPTION@ @LIBS_FOR_CLIENTS@" +embedded_libs="-L$pkglibdir @RPATH_OPTION@ @EMB_LIBS_FOR_CLIENTS@" + +include="-I$pkgincludedir" +if [ "$basedir" != "/usr" ]; then + include="$include -I$pkgincludedir/.." +fi +cflags="$include @CFLAGS_FOR_CLIENTS@" + +mariadb_config="$basedir/bin/mariadb_config" +if test -x "$basedir/bin/mariadb_config"; then + cflags=`"$mariadb_config" --cflags` + include=`"$mariadb_config" --include` + libs=`"$mariadb_config" --libs` + plugindir=`"$mariadb_config" --plugindir` + socket=`"$mariadb_config" --socket` + port=`"$mariadb_config" --port` + version=`"$mariadb_config" --version` +fi + +usage () { + cat <<EOF +Usage: $0 [OPTIONS] +Options: + --cflags [$cflags] + --include [$include] + --libs [$libs] + --libs_r [$libs] + --plugindir [$plugindir] + --socket [$socket] + --port [$port] + --version [$version] + --libmysqld-libs [$embedded_libs] + --variable=VAR VAR is one of: + pkgincludedir [$pkgincludedir] + pkglibdir [$pkglibdir] + plugindir [$plugindir] +EOF + exit $1 +} + +if test $# -le 0; then usage 0 ; fi + +while test $# -gt 0; do + case $1 in + --cflags) echo "$cflags" ;; + --include) echo "$include" ;; + --libs) echo "$libs" ;; + --libs_r) echo "$libs" ;; + --plugindir) echo "$plugindir" ;; + --socket) echo "$socket" ;; + --port) echo "$port" ;; + --version) echo "$version" ;; + --embedded-libs | --embedded | --libmysqld-libs) echo "$embedded_libs" ;; + --variable=*) + var=`echo "$1" | sed 's,^[^=]*=,,'` + case "$var" in + pkgincludedir) echo "$pkgincludedir" ;; + pkglibdir) echo "$pkglibdir" ;; + plugindir) echo "$plugindir" ;; + *) usage 1 >&2 ;; + esac + ;; + *) usage 1 >&2 ;; + esac + + shift +done + +#echo "ldata: '"$ldata"'" +#echo "execdir: '"$execdir"'" +#echo "bindir: '"$bindir"'" +#echo "pkglibdir: '"$pkglibdir"'" +#echo "pkgincludedir: '"$pkgincludedir"'" +#echo "version: '"$version"'" +#echo "socket: '"$socket"'" +#echo "port: '"$port"'" +#echo "ldflags: '"$ldflags"'" +#echo "client_libs: '"$client_libs"'" + +exit 0 diff --git a/scripts/mysql_convert_table_format.sh b/scripts/mysql_convert_table_format.sh new file mode 100644 index 00000000..6b4d758a --- /dev/null +++ b/scripts/mysql_convert_table_format.sh @@ -0,0 +1,167 @@ +#!@PERL_PATH@ +# Copyright (c) 2000, 2017, 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 +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +# Convert given tables in a database to MYISAM + +use DBI; +use Getopt::Long; + +$opt_help=$opt_version=$opt_verbose=$opt_force=0; +$opt_user=$opt_database=$opt_password=undef; +$opt_host="localhost"; +$opt_socket=""; +$opt_engine="MYISAM"; +$opt_port=0; +$exit_status=0; + +GetOptions( + "e|engine|type=s" => \$opt_engine, + "f|force" => \$opt_force, + "help|?" => \$opt_help, + "h|host=s" => \$opt_host, + "p|password=s" => \$opt_password, + "u|user=s" => \$opt_user, + "v|verbose" => \$opt_verbose, + "V|version" => \$opt_version, + "S|socket=s" => \$opt_socket, + "P|port=i" => \$opt_port +) || usage(0); + +usage($opt_version) if ($#ARGV < 0 || $opt_help || $opt_version); + +$opt_database=shift(@ARGV); + +if (grep { /^$opt_engine$/i } qw(HEAP MEMORY BLACKHOLE)) +{ + print "Converting to '$opt_engine' would delete your data; aborting\n"; + exit(1); +} + +$connect_opt=""; +if ($opt_port) +{ + $connect_opt.= ";port=$opt_port"; +} +if (length($opt_socket)) +{ + $connect_opt.=";mariadb_socket=$opt_socket"; +} + +$dbh = DBI->connect("DBI:MariaDB:$opt_database:${opt_host}$connect_opt", + $opt_user, + $opt_password, + { PrintError => 0}) + || die "Can't connect to database $opt_database: $DBI::errstr\n"; + +my @tables; + +push(@ARGV, "%") if(!@ARGV); + +foreach $pattern (@ARGV) +{ + my ($sth,$row); + $sth=$dbh->prepare("SHOW TABLES LIKE ?"); + $rv= $sth->execute($pattern); + if(!int($rv)) + { + warn "Can't get tables matching '$pattern' from $opt_database; $DBI::errstr\n"; + exit(1) unless $opt_force; + } + while (($row = $sth->fetchrow_arrayref)) + { + push(@tables, $row->[0]); + } + $sth->finish; +} + +print "Converting tables:\n" if ($opt_verbose); +foreach $table (@tables) +{ + my ($sth,$row); + + # Check if table is already converted + $sth=$dbh->prepare("show table status like '$table'"); + if ($sth->execute && ($row = $sth->fetchrow_arrayref)) + { + if (uc($row->[1]) eq uc($opt_engine)) + { + print "$table already uses the '$opt_engine' engine; Ignored\n"; + next; + } + } + print "converting $table\n" if ($opt_verbose); + $table=~ s/`/``/g; + if (!$dbh->do("ALTER TABLE `$table` ENGINE=$opt_engine")) + { + print STDERR "Can't convert $table: Error $DBI::errstr\n"; + exit(1) if (!$opt_force); + $exit_status=1; + } +} + +$dbh->disconnect; +exit($exit_status); + + +sub usage +{ + my($version)=shift; + print "$0 version 1.1\n"; + exit(0) if ($version); + + print <<EOF; + +Conversion of a MariaDB tables to other storage engines + + Usage: $0 database [table[ table ...]] + If no tables has been specifed, all tables in the database will be converted. + You can also use wildcards, ie "my%" + + The following options are available: + +-f, --force + Continue even if there is some error. + +-?, --help + Shows this help + +-e, --engine=ENGINE + Converts tables to the given storage engine (Default: $opt_engine) + +-h, --host=HOST + Host name where the database server is located. (Default: $opt_host) + +-p, --password=PASSWORD + Password for the current user. + +-P, --port=PORT + TCP/IP port to connect to if host is not "localhost". + +-S, --socket=SOCKET + Socket to connect with. + +-u, --user=USER + User name to log into the SQL server. + +-v, --verbose + This is a test specific option that is only used when debugging a test. + Print more information about what is going on. + +-V, --version + Shows the version of this program. +EOF + exit(1); +} diff --git a/scripts/mysql_find_rows.sh b/scripts/mysql_find_rows.sh new file mode 100644 index 00000000..09bcc227 --- /dev/null +++ b/scripts/mysql_find_rows.sh @@ -0,0 +1,159 @@ +#!@PERL_PATH@ +# Copyright (c) 2000, 2017, 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 +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +$version="1.02"; + +use Getopt::Long; + +$opt_help=$opt_Information=$opt_skip_use_db=0; +$opt_regexp=$opt_dbregexp=".*"; +$opt_start_row=1; $opt_rows=9999999999; + +GetOptions("Information","help","regexp=s","start_row=i","rows=i", + "dbregexp=s", "skip-use-db") + || usage(); +usage() if ($opt_help || $opt_Information); + +$query=$search=$database=$set=""; $eoq=0; +while (<>) +{ + next if (length($query) == 0 && /^\#/); # Skip comments + $query.=search($_); + if ($eoq) + { + if ($query =~ /^use /i || $query =~ /^SET / || + ($query =~ /$opt_regexp/o && $database =~ /$opt_dbregexp/o)) + { + if ($opt_skip_use_db && $query =~ /^use /i) + { + $query=""; + next; + } + if ($opt_start_row <= 1) + { + if ($database) + { + print $database, $set; + $database=$set=""; + } + print $query; + last if (--$opt_rows == 0); + } + else + { + $opt_start_row--; + if ($query =~ /^use /) + { + $database=$query; + $set=""; + } + elsif ($query =~ /^SET/) + { + $set=$query; + } + else + { + $set=""; + } + } + } + $query=""; $search=""; $eoq=0; + } +} + +exit 0; + +sub search +{ + my($row)=shift; + my($i); + + for ($i=0 ; $i < length($row) ; $i++) + { + if (length($search)) + { + if (length($search) > 1) + { # Comment + next if (substr($row,$i,length($search)) ne $search); + $i+=length($search)-1; + $search=""; + } + elsif (substr($row,$i,1) eq '\\') # Escaped char in string + { + $i++; + } + elsif (substr($row,$i,1) eq $search) + { + if (substr($row,$i+1,1) eq $search) # Double " or ' + { + $i++; + } + else + { + $search=""; + } + } + next; + } + if (substr($row,$i,2) eq '/*') # Comment + { + $search="*/"; + $i++; + } + elsif (substr($row,$i,1) eq "'" || substr($row,$i,1) eq '"') + { + $search=substr($row,$i,1); + } + } + $eoq=1 if (!length($search) && $row =~ /;\s*$/); + return $row; +} + + +sub usage +{ + print <<EOF; +$0 Ver $version + +Prints all SQL queries that matches a regexp or contains a 'use +database' or 'set ..' command to stdout. A SQL query may contain +newlines. This is useful to find things in a MariaDB update log. + +$0 takes the following options: + +--help or --Information + Shows this help + +--regexp=# + Print queries that matches this. + +--start_row=# + Start output from this row (first row = 1) + +--skip-use-db + Don\'t include \'use database\' commands in the output. + +--rows=# + Quit after this many rows. + +Example: + +$0 --regexp "problem_table" < update.log + +$0 --regexp "problem_table" update-log.1 update-log.2 +EOF + exit(0); +} diff --git a/scripts/mysql_fix_extensions.sh b/scripts/mysql_fix_extensions.sh new file mode 100644 index 00000000..c0de813e --- /dev/null +++ b/scripts/mysql_fix_extensions.sh @@ -0,0 +1,34 @@ +#!@PERL_PATH@ + +# Copyright (c) 2001, 2017, 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 Library 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 +# Library General Public License for more details. +# +# You should have received a copy of the GNU Library General Public +# License along with this library; if not, write to the Free +# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +# MA 02110-1335 USA + +# This is a utility for MariaDB. It is not needed by any standard part +# of MariaDB. + +# Usage: mysql_fix_extensions datadir +# does not work with RAID, with InnoDB or BDB tables +# makes .frm lowercase and .MYI/MYD/ISM/ISD uppercase +# useful when datafiles are copied from windows + +die "Usage: $0 datadir\n" unless -d $ARGV[0]; + +for $a (<$ARGV[0]/*/*.*>) { $_=$a; + s/\.frm$/.frm/i; + s/\.(is[md]|my[id])$/\U$&/i; + rename ($a, $_) || warn "Cannot rename $a => $_ : $!"; +} diff --git a/scripts/mysql_install_db.sh b/scripts/mysql_install_db.sh new file mode 100644 index 00000000..14ef6840 --- /dev/null +++ b/scripts/mysql_install_db.sh @@ -0,0 +1,658 @@ +#!/bin/sh +# Copyright (c) 2000, 2013, Oracle and/or its affiliates. +# Copyright (c) 2009, 2013, Monty Program Ab +# +# This program is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +# This scripts creates the MariaDB Server system tables +# +# All unrecognized arguments to this script are passed to mysqld. + +basedir="" +builddir="" +ldata="@localstatedir@" +langdir="" +srcdir="" +log_error="" + +args="" +defaults="" +defaults_group_suffix="" +mysqld_opt="" +user="" +silent_startup="--silent-startup" + +force=0 +in_rpm=0 +ip_only=0 +cross_bootstrap=0 +auth_root_authentication_method=socket +auth_root_socket_user="" +skip_test_db=0 + +dirname0=`dirname $0 2>/dev/null` +dirname0=`dirname $dirname0 2>/dev/null` + +usage() +{ + cat <<EOF +Usage: $0 [OPTIONS] + --auth-root-authentication-method=normal|socket + Chooses the authentication method for the created + initial root user. The historical behavior is 'normal' + to creates a root user that can login without password, + which can be insecure. The default behavior 'socket' + sets an invalid root password but allows the system root + user to login as MariaDB root without a password. + --auth-root-socket-user=user + Used with --auth-root-authentication-method=socket. It + specifies the name of the second MariaDB root account, + as well as of the system account allowed to access it. + Defaults to the value of --user. + --basedir=path The path to the MariaDB installation directory. + --builddir=path If using --srcdir with out-of-directory builds, you + will need to set this to the location of the build + directory where built files reside. + --cross-bootstrap For internal use. Used when building the MariaDB system + tables on a different host than the target. + --datadir=path The path to the MariaDB data directory. + --no-defaults Don't read default options from any option file. + --defaults-extra-file=name + Read this file after the global files are read. + --defaults-file=name Only read default options from the given file name. + --defaults-group-suffix=name + In addition to the given groups, read also groups with + this suffix + --force Causes mysql_install_db to run even if DNS does not + work. In that case, grant table entries that + normally use hostnames will use IP addresses. + --help Display this help and exit. + --ldata=path The path to the MariaDB data directory. Same as + --datadir. + --rpm For internal use. This option is used by RPM files + during the MariaDB installation process. + --skip-name-resolve Use IP addresses rather than hostnames when creating + grant table entries. This option can be useful if + your DNS does not work. + --skip-test-db Don't install a test database. + --srcdir=path The path to the MariaDB source directory. This option + uses the compiled binaries and support files within the + source tree, useful for if you don't want to install + MariaDB yet and just want to create the system tables. + --user=user_name The login username to use for running mysqld. Files + and directories created by mysqld will be owned by this + user. You must be root to use this option. By default + mysqld runs using your current login name and files and + directories that it creates will be owned by you. + +All other options are passed to the mysqld program + +EOF + exit 1 +} + +s_echo() +{ + if test "$in_rpm" -eq 0 -a "$cross_bootstrap" -eq 0 + then + echo "$1" + fi +} + +link_to_help() +{ + echo + echo "The latest information about mysql_install_db is available at" + echo "https://mariadb.com/kb/en/installing-system-tables-mysql_install_db" +} + +parse_arg() +{ + echo "$1" | sed -e 's/^[^=]*=//' +} + +parse_arguments() +{ + # We only need to pass arguments through to the server if we don't + # handle them here. So, we collect unrecognized options (passed on + # the command line) into the args variable. + pick_args= + if test "$1" = PICK-ARGS-FROM-ARGV + then + pick_args=1 + shift + fi + + for arg + do + case "$arg" in + --force) force=1 ;; + --basedir=*) basedir=`parse_arg "$arg"` ;; + --builddir=*) builddir=`parse_arg "$arg"` ;; + --srcdir=*) srcdir=`parse_arg "$arg"` ;; + --ldata=*|--datadir=*|--data=*) ldata=`parse_arg "$arg"` ;; + --log-error=*) + log_error=`parse_arg "$arg"` ;; + --user=*) + # Note that the user will be passed to mysqld so that it runs + # as 'user' (crucial e.g. if log-bin=/some_other_path/ + # where a chown of datadir won't help) + user=`parse_arg "$arg"` ;; + --skip-name-resolve) ip_only=1 ;; + --verbose) verbose=1 ; silent_startup="" ;; + --rpm) in_rpm=1 ;; + --help) usage ;; + --no-defaults|--defaults-file=*|--defaults-extra-file=*) + defaults="$arg" ;; + --defaults-group-suffix=*) + defaults_group_suffix="$arg" ;; + + --cross-bootstrap|--windows) + # Used when building the MariaDB system tables on a different host than + # the target. The platform-independent files that are created in + # --datadir on the host can be copied to the target system. + # + # The most common use for this feature is in the Windows installer + # which will take the files from datadir and include them as part of + # the install package. See top-level 'dist-hook' make target. + # + # --windows is a deprecated alias + cross_bootstrap=1 ;; + --auth-root-authentication-method=normal) + auth_root_authentication_method=normal ;; + --auth-root-authentication-method=socket) + auth_root_authentication_method=socket ;; + --auth-root-authentication-method=*) + usage ;; + --auth-root-socket-user=*) + auth_root_socket_user="$(parse_arg "$arg")" ;; + --skip-test-db) skip_test_db=1 ;; + + *) + if test -n "$pick_args" + then + # This sed command makes sure that any special chars are quoted, + # so the arg gets passed exactly to the server. + # XXX: This is broken; true fix requires using eval and proper + # quoting of every single arg ($basedir, $ldata, etc.) + #args="$args "`echo "$arg" | sed -e 's,\([^a-zA-Z0-9_.-]\),\\\\\1,g'` + args="$args $arg" + fi + ;; + esac + done +} + +# Try to find a specific file within --basedir which can either be a binary +# release or installed source directory and return the path. +find_in_dirs() +{ + case "$1" in + --dir) + return_dir=1; shift + ;; + esac + + file=$1; shift + + for dir in "$@" + do + if test -f "$dir/$file" + then + if test -n "$return_dir" + then + echo "$dir" + else + echo "$dir/$file" + fi + break + fi + done +} + +cannot_find_file() +{ + echo + echo "FATAL ERROR: Could not find $1" + + shift + if test $# -ne 0 + then + echo + echo "The following directories were searched:" + echo + for dir in "$@" + do + echo " $dir" + done + fi + + echo + echo "If you compiled from source, you need to either run 'make install' to" + echo "copy the software into the correct location ready for operation." + echo "If you don't want to do a full install, you can use the --srcdir" + echo "option to only install the mysql database and privilege tables." + echo + echo "If you are using a binary release, you must either be at the top" + echo "level of the extracted archive, or pass the --basedir option" + echo "pointing to that location." + link_to_help +} + +# Ok, let's go. We first need to parse arguments which are required by +# my_print_defaults so that we can execute it first, then later re-parse +# the command line to add any extra bits that we need. +parse_arguments "$@" + +# +# We can now find my_print_defaults. This script supports: +# +# --srcdir=path pointing to compiled source tree +# --basedir=path pointing to installed binary location +# +# or default to compiled-in locations. +# +if test -n "$srcdir" && test -n "$basedir" +then + echo "ERROR: Specify either --basedir or --srcdir, not both." + link_to_help + exit 1 +fi +if test -n "$srcdir" +then + # In an out-of-source build, builddir is not srcdir. Try to guess where + # builddir is by looking for my_print_defaults. + if test -z "$builddir" + then + if test -x "$dirname0/extra/my_print_defaults" + then + builddir="$dirname0" + else + builddir="$srcdir" + fi + fi + print_defaults="$builddir/extra/my_print_defaults" +elif test -n "$basedir" +then + print_defaults=`find_in_dirs my_print_defaults $basedir/bin $basedir/extra` + if test -z "$print_defaults" + then + cannot_find_file my_print_defaults $basedir/bin $basedir/extra + exit 1 + fi +elif test -n "$dirname0" -a -x "$dirname0/@bindir@/my_print_defaults" +then + print_defaults="$dirname0/@bindir@/my_print_defaults" +elif test -x "./extra/my_print_defaults" +then + srcdir="." + builddir="." + print_defaults="./extra/my_print_defaults" +else + print_defaults="@bindir@/my_print_defaults" +fi + +if test ! -x "$print_defaults" +then + cannot_find_file "$print_defaults" + exit 1 +fi + +# Now we can get arguments from the groups [mysqld] and [mysql_install_db] +# in the my.cfg file, then re-run to merge with command line arguments. +parse_arguments `"$print_defaults" $defaults $defaults_group_suffix --mysqld mysql_install_db mariadb-install-db` + +parse_arguments PICK-ARGS-FROM-ARGV "$@" + +rel_mysqld="$dirname0/@INSTALL_SBINDIR@/mysqld" + +# Configure paths to support files +if test -n "$srcdir" +then + basedir="$builddir" + bindir="$basedir/client" + resolveip="$basedir/extra/resolveip" + mysqld="$basedir/sql/mysqld" + langdir="$basedir/sql/share/english" + srcpkgdatadir="$srcdir/scripts" + buildpkgdatadir="$builddir/scripts" + plugindir="$builddir/plugin/auth_socket" + pamtooldir="$builddir/plugin/auth_pam" +elif test -n "$basedir" +then + bindir="$basedir/bin" # only used in the help text + resolveip=`find_in_dirs resolveip @resolveip_locations@` + if test -z "$resolveip" + then + cannot_find_file resolveip @resolveip_locations@ + exit 1 + fi + mysqld=`find_in_dirs mysqld @mysqld_locations@` + if test -z "$mysqld" + then + cannot_find_file mysqld @mysqld_locations@ + exit 1 + fi + langdir=`find_in_dirs --dir errmsg.sys @errmsg_locations@` + if test -z "$langdir" + then + cannot_find_file errmsg.sys @errmsg_locations@ + exit 1 + fi + srcpkgdatadir=`find_in_dirs --dir fill_help_tables.sql @pkgdata_locations@` + buildpkgdatadir=$srcpkgdatadir + if test -z "$srcpkgdatadir" + then + cannot_find_file fill_help_tables.sql @pkgdata_locations@ + exit 1 + fi + plugindir=`find_in_dirs --dir auth_pam.so $basedir/lib*/plugin $basedir/lib*/mysql/plugin $basedir/lib/*/mariadb19/plugin` + pamtooldir=$plugindir +# relative from where the script was run for a relocatable install +elif test -n "$dirname0" -a -x "$rel_mysqld" -a ! "$rel_mysqld" -ef "@sbindir@/mysqld" +then + basedir="$dirname0" + bindir="$basedir/@INSTALL_BINDIR@" + resolveip="$bindir/resolveip" + mysqld="$rel_mysqld" + srcpkgdatadir="$basedir/@INSTALL_MYSQLSHAREDIR@" + buildpkgdatadir="$basedir/@INSTALL_MYSQLSHAREDIR@" + plugindir="$basedir/@INSTALL_PLUGINDIR@" + pamtooldir=$plugindir +else + basedir="@prefix@" + bindir="@bindir@" + resolveip="$bindir/resolveip" + mysqld="@sbindir@/mysqld" + srcpkgdatadir="@pkgdatadir@" + buildpkgdatadir="@pkgdatadir@" + plugindir="@pkgplugindir@" + pamtooldir="@pkgplugindir@" +fi + +# Set up paths to SQL scripts required for bootstrap +fill_help_tables="$srcpkgdatadir/fill_help_tables.sql" +create_system_tables="$srcpkgdatadir/mysql_system_tables.sql" +create_system_tables2="$srcpkgdatadir/mysql_performance_tables.sql" +fill_system_tables="$srcpkgdatadir/mysql_system_tables_data.sql" +maria_add_gis_sp="$buildpkgdatadir/maria_add_gis_sp_bootstrap.sql" +mysql_test_db="$srcpkgdatadir/mysql_test_db.sql" + +for f in "$fill_help_tables" "$create_system_tables" "$create_system_tables2" "$fill_system_tables" "$maria_add_gis_sp" "$mysql_test_db" +do + if test ! -f "$f" + then + cannot_find_file "$f" + exit 1 + fi +done + +if test ! -x "$mysqld" +then + cannot_find_file "$mysqld" + exit 1 +fi + +if test -n "$langdir" +then + if test ! -f "$langdir/errmsg.sys" + then + cannot_find_file "$langdir/errmsg.sys" + exit 1 + fi + mysqld_opt="--lc-messages-dir=$langdir/.." +else + mysqld_opt="--lc-messages=en_US" +fi + + +# Try to determine the hostname +hostname=`@HOSTNAME@` + +# Check if hostname is valid +if test "$cross_bootstrap" -eq 0 -a "$in_rpm" -eq 0 -a "$force" -eq 0 +then + resolved=`"$resolveip" $hostname 2>&1` + if test $? -ne 0 + then + resolved=`"$resolveip" localhost 2>&1` + if test $? -ne 0 + then + echo "Neither host '$hostname' nor 'localhost' could be looked up with" + echo "'$resolveip'" + echo "Please configure the 'hostname' command to return a correct" + echo "hostname." + echo "If you want to solve this at a later stage, restart this script" + echo "with the --force option" + link_to_help + exit 1 + fi + echo "WARNING: The host '$hostname' could not be looked up with $resolveip." + echo "This probably means that your libc libraries are not 100 % compatible" + echo "with this binary MariaDB version. The MariaDB daemon, mysqld, should work" + echo "normally with the exception that host name resolving will not work." + echo "This means that you should use IP addresses instead of hostnames" + echo "when specifying MariaDB privileges !" + fi +fi + +if test "$ip_only" -eq 1 +then + hostname=`echo "$resolved" | awk '/ /{print $6}'` +fi + +# Create database directories +for dir in "$ldata" +do + if test ! -d "$dir" + then + if ! `mkdir -p "$dir"` + then + echo "Fatal error Can't create database directory '$dir'" + link_to_help + exit 1 + fi + chmod 700 "$dir" + fi + if test -n "$user" + then + chown $user "$dir" + if test $? -ne 0 + then + echo "Cannot change ownership of the database directories to the '$user'" + echo "user. Check that you have the necessary permissions and try again." + exit 1 + fi + fi +done + +if test -n "$user" +then + if test -z "$srcdir" -a "$in_rpm" -eq 0 + then + chown 0 "$pamtooldir/auth_pam_tool_dir/auth_pam_tool" && \ + chmod 04755 "$pamtooldir/auth_pam_tool_dir/auth_pam_tool" + if test $? -ne 0 + then + echo "Couldn't set an owner to '$pamtooldir/auth_pam_tool_dir/auth_pam_tool'." + echo "It must be root, the PAM authentication plugin doesn't work otherwise.." + echo + fi + chown $user "$pamtooldir/auth_pam_tool_dir" && \ + chmod 0700 "$pamtooldir/auth_pam_tool_dir" + if test $? -ne 0 + then + echo "Cannot change ownership of the '$pamtooldir/auth_pam_tool_dir' directory" + echo "to the '$user' user. Check that you have the necessary permissions and try again." + echo + fi + fi + args="$args --user=$user" +fi + +if test -f "$ldata/mysql/user.frm" +then + echo "mysql.user table already exists!" + echo "Run mysql_upgrade, not mysql_install_db" + exit 0 +fi + +# When doing a "cross bootstrap" install, no reference to the current +# host should be added to the system tables. So we filter out any +# lines which contain the current host name. +if test $cross_bootstrap -eq 1 +then + filter_cmd_line="sed -e '/@current_hostname/d'" +else + filter_cmd_line="cat" +fi + +# Configure mysqld command line +mysqld_bootstrap="${MYSQLD_BOOTSTRAP-$mysqld}" +mysqld_install_cmd_line() +{ + "$mysqld_bootstrap" $defaults $defaults_group_suffix "$mysqld_opt" --bootstrap $silent_startup\ + "--basedir=$basedir" "--datadir=$ldata" --log-warnings=0 --enforce-storage-engine="" \ + "--plugin-dir=${plugindir}" \ + $args --max_allowed_packet=8M \ + --net_buffer_length=16K +} + +# Use $auth_root_socket_user if explicitly specified. +# Otherwise use the owner of datadir - ${user:-$USER} +# Use 'root' as a fallback +auth_root_socket_user=${auth_root_socket_user:-${user:-${USER:-root}}} + +cat_sql() +{ + echo "create database if not exists mysql;" + echo "use mysql;" + + case "$auth_root_authentication_method" in + normal) + echo "SET @auth_root_socket=NULL;" + ;; + socket) + echo "SET @auth_root_socket='$auth_root_socket_user';" + ;; + esac + + cat "$create_system_tables" "$create_system_tables2" "$fill_system_tables" "$fill_help_tables" "$maria_add_gis_sp" + if test "$skip_test_db" -eq 0 + then + cat "$mysql_test_db" + fi +} + +# Create the system and help tables by passing them to "mysqld --bootstrap" +s_echo "Installing MariaDB/MySQL system tables in '$ldata' ..." +if cat_sql | eval "$filter_cmd_line" | mysqld_install_cmd_line > /dev/null +then + s_echo "OK" +else + log_file_place=$ldata + if test -n "$log_error" + then + log_file_place="$log_error or $log_file_place" + fi + echo + echo "Installation of system tables failed! Examine the logs in" + echo "$log_file_place for more information." + echo + echo "The problem could be conflicting information in an external" + echo "my.cnf files. You can ignore these by doing:" + echo + echo " shell> $0 --defaults-file=~/.my.cnf" + echo + echo "You can also try to start the mysqld daemon with:" + echo + echo " shell> $mysqld --skip-grant-tables --general-log &" + echo + echo "and use the command line tool $bindir/mysql" + echo "to connect to the mysql database and look at the grant tables:" + echo + echo " shell> $bindir/mysql -u root mysql" + echo " mysql> show tables;" + echo + echo "Try 'mysqld --help' if you have problems with paths. Using" + echo "--general-log gives you a log in $ldata that may be helpful." + link_to_help + echo "You can find the latest source at https://downloads.mariadb.org and" + echo "the maria-discuss email list at https://launchpad.net/~maria-discuss" + echo + echo "Please check all of the above before submitting a bug report" + echo "at https://mariadb.org/jira" + echo + exit 1 +fi + +# Don't output verbose information if running inside bootstrap or using +# --srcdir for testing. In such cases, there's no end user looking at +# the screen. +if test "$cross_bootstrap" -eq 0 && test -z "$srcdir" +then + s_echo + s_echo "To start mysqld at boot time you have to copy" + s_echo "support-files/mysql.server to the right place for your system" + + if test "$auth_root_authentication_method" = normal + then + echo + echo + echo "PLEASE REMEMBER TO SET A PASSWORD FOR THE MariaDB root USER !" + echo "To do so, start the server, then issue the following command:" + echo + echo "'$bindir/mysql_secure_installation'" + echo + echo "which will also give you the option of removing the test" + echo "databases and anonymous user created by default. This is" + echo "strongly recommended for production servers." + else + echo + echo + echo "Two all-privilege accounts were created." + echo "One is root@localhost, it has no password, but you need to" + echo "be system 'root' user to connect. Use, for example, sudo mysql" + echo "The second is $auth_root_socket_user@localhost, it has no password either, but" + echo "you need to be the system '$auth_root_socket_user' user to connect." + echo "After connecting you can set the password, if you would need to be" + echo "able to connect as any of these users with a password and without sudo" + fi + + echo + echo "See the MariaDB Knowledgebase at https://mariadb.com/kb or the" + echo "MySQL manual for more instructions." + + if test "$in_rpm" -eq 0 + then + echo + echo "You can start the MariaDB daemon with:" + echo "cd '$basedir' ; $bindir/mysqld_safe --datadir='$ldata'" + echo + echo "You can test the MariaDB daemon with mysql-test-run.pl" + echo "cd '$basedir/mysql-test' ; perl mysql-test-run.pl" + fi + + echo + echo "Please report any problems at https://mariadb.org/jira" + echo + echo "The latest information about MariaDB is available at https://mariadb.org/." + echo "You can find additional information about the MySQL part at:" + echo "https://dev.mysql.com" + echo "Consider joining MariaDB's strong and vibrant community:" + echo "https://mariadb.org/get-involved/" + echo +fi + +exit 0 diff --git a/scripts/mysql_performance_tables.sql b/scripts/mysql_performance_tables.sql new file mode 100644 index 00000000..30616035 --- /dev/null +++ b/scripts/mysql_performance_tables.sql @@ -0,0 +1,55 @@ +-- +-- PERFORMANCE SCHEMA INSTALLATION +-- Note that this script is also reused by mysql_upgrade, +-- so we have to be very careful here to not destroy any +-- existing database named 'performance_schema' if it +-- can contain user data. +-- In case of downgrade, it's ok to drop unknown tables +-- from a future version, as long as they belong to the +-- performance schema engine. +-- + +set @have_old_pfs= (select count(*) from information_schema.schemata where schema_name='performance_schema'); + +SET @cmd="SET @broken_tables = (select count(*) from information_schema.tables where engine != 'PERFORMANCE_SCHEMA' and table_schema='performance_schema')"; + +-- Work around for bug#49542 +SET @str = IF(@have_old_pfs = 1, @cmd, 'SET @broken_tables = 0'); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +SET @cmd="SET @broken_views = (select count(*) from information_schema.views where table_schema='performance_schema')"; + +-- Work around for bug#49542 +SET @str = IF(@have_old_pfs = 1, @cmd, 'SET @broken_views = 0'); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +SET @broken_routines = (select count(*) from mysql.proc where db='performance_schema'); + +SET @broken_events = (select count(*) from mysql.event where db='performance_schema'); + +SET @broken_pfs= (select @broken_tables + @broken_views + @broken_routines + @broken_events); + +-- +-- The performance schema database. +-- Only drop and create the database if this is safe (no broken_pfs). +-- This database is created, even in --without-perfschema builds, +-- so that the database name is always reserved by the MySQL implementation. +-- + +SET @cmd= "DROP DATABASE IF EXISTS performance_schema"; + +SET @str = IF(@broken_pfs = 0, @cmd, 'SET @dummy = 0'); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +SET @cmd= "CREATE DATABASE performance_schema character set utf8"; + +SET @str = IF(@broken_pfs = 0, @cmd, 'SET @dummy = 0'); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; diff --git a/scripts/mysql_secure_installation.sh b/scripts/mysql_secure_installation.sh new file mode 100644 index 00000000..b2a9edf4 --- /dev/null +++ b/scripts/mysql_secure_installation.sh @@ -0,0 +1,577 @@ +#!/bin/sh + +# Copyright (c) 2002, 2016, 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 +# the Free Software Foundation; version 2 of the License. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +config=".my.cnf.$$" +command=".mysql.$$" +output=".my.output.$$" + +trap "interrupt" 1 2 3 6 15 + +rootpass="" +echo_n= +echo_c= +basedir= +defaults_file= +defaults_extra_file= +no_defaults= + +parse_arg() +{ + echo "$1" | sed -e 's/^[^=]*=//' +} + +parse_arguments() +{ + # We only need to pass arguments through to the server if we don't + # handle them here. So, we collect unrecognized options (passed on + # the command line) into the args variable. + pick_args= + if test "$1" = PICK-ARGS-FROM-ARGV + then + pick_args=1 + shift + fi + + for arg + do + case "$arg" in + --basedir=*) basedir=`parse_arg "$arg"` ;; + --defaults-file=*) defaults_file="$arg" ;; + --defaults-extra-file=*) defaults_extra_file="$arg" ;; + --no-defaults) no_defaults="$arg" ;; + *) + if test -n "$pick_args" + then + # This sed command makes sure that any special chars are quoted, + # so the arg gets passed exactly to the server. + # XXX: This is broken; true fix requires using eval and proper + # quoting of every single arg ($basedir, $ldata, etc.) + #args="$args "`echo "$arg" | sed -e 's,\([^a-zA-Z0-9_.-]\),\\\\\1,g'` + args="$args $arg" + fi + ;; + esac + done +} + +# Try to find a specific file within --basedir which can either be a binary +# release or installed source directory and return the path. +find_in_basedir() +{ + return_dir=0 + found=0 + case "$1" in + --dir) + return_dir=1; shift + ;; + esac + + file=$1; shift + + for dir in "$@" + do + if test -f "$basedir/$dir/$file" + then + found=1 + if test $return_dir -eq 1 + then + echo "$basedir/$dir" + else + echo "$basedir/$dir/$file" + fi + break + fi + done + + if test $found -eq 0 + then + # Test if command is in PATH + $file --no-defaults --version > /dev/null 2>&1 + status=$? + if test $status -eq 0 + then + echo $file + fi + fi +} + +cannot_find_file() +{ + echo + echo "FATAL ERROR: Could not find $1" + + shift + if test $# -ne 0 + then + echo + echo "The following directories were searched:" + echo + for dir in "$@" + do + echo " $dir" + done + fi + + echo + echo "If you compiled from source, you need to run 'make install' to" + echo "copy the software into the correct location ready for operation." + echo + echo "If you are using a binary release, you must either be at the top" + echo "level of the extracted archive, or pass the --basedir option" + echo "pointing to that location." + echo +} + +# Ok, let's go. We first need to parse arguments which are required by +# my_print_defaults so that we can execute it first, then later re-parse +# the command line to add any extra bits that we need. +parse_arguments PICK-ARGS-FROM-ARGV "$@" + +# +# We can now find my_print_defaults. This script supports: +# +# --srcdir=path pointing to compiled source tree +# --basedir=path pointing to installed binary location +# +# or default to compiled-in locations. +# + +if test -n "$basedir" +then + print_defaults=`find_in_basedir my_print_defaults bin extra` + echo "print: $print_defaults" + if test -z "$print_defaults" + then + cannot_find_file my_print_defaults $basedir/bin $basedir/extra + exit 1 + fi + mysql_command=`find_in_basedir mysql bin` + if test -z "$mysql_command" + then + cannot_find_file mysql $basedir/bin + exit 1 + fi +else + print_defaults="@bindir@/my_print_defaults" + mysql_command="@bindir@/mysql" +fi + +if test ! -x "$print_defaults" +then + cannot_find_file "$print_defaults" + exit 1 +fi + +if test ! -x "$mysql_command" +then + cannot_find_file "$mysql_command" + exit 1 +fi + +# Now we can get arguments from the group [client] and [client-server] +# in the my.cfg file, then re-run to merge with command line arguments. +parse_arguments `$print_defaults $defaults_file $defaults_extra_file $no_defaults client client-server client-mariadb` +parse_arguments PICK-ARGS-FROM-ARGV "$@" + +set_echo_compat() { + case `echo "testing\c"`,`echo -n testing` in + *c*,-n*) echo_n= echo_c= ;; + *c*,*) echo_n=-n echo_c= ;; + *) echo_n= echo_c='\c' ;; + esac +} + +validate_reply () { + ret=0 + if [ -z "$1" ]; then + reply=y + return $ret + fi + case $1 in + y|Y|yes|Yes|YES) reply=y ;; + n|N|no|No|NO) reply=n ;; + *) ret=1 ;; + esac + return $ret +} + +prepare() { + touch $config $command + chmod 600 $config $command +} + +do_query() { + echo "$1" >$command + #sed 's,^,> ,' < $command # Debugging + $mysql_command --defaults-file=$config $defaults_extra_file $no_defaults $args <$command >$output + return $? +} + +# Simple escape mechanism (\-escape any ' and \), suitable for two contexts: +# - single-quoted SQL strings +# - single-quoted option values on the right hand side of = in my.cnf +# +# These two contexts don't handle escapes identically. SQL strings allow +# quoting any character (\C => C, for any C), but my.cnf parsing allows +# quoting only \, ' or ". For example, password='a\b' quotes a 3-character +# string in my.cnf, but a 2-character string in SQL. +# +# This simple escape works correctly in both places. +basic_single_escape () { + # The quoting on this sed command is a bit complex. Single-quoted strings + # don't allow *any* escape mechanism, so they cannot contain a single + # quote. The string sed gets (as argv[1]) is: s/\(['\]\)/\\\1/g + # + # Inside a character class, \ and ' are not special, so the ['\] character + # class is balanced and contains two characters. + echo "$1" | sed 's/\(['"'"'\]\)/\\\1/g' +} + +# +# create a simple my.cnf file to be able to pass the root password to the mysql +# client without putting it on the command line +# +make_config() { + echo "# mysql_secure_installation config file" >$config + echo "[mysql]" >>$config + echo "user=root" >>$config + esc_pass=`basic_single_escape "$rootpass"` + echo "password='$esc_pass'" >>$config + #sed 's,^,> ,' < $config # Debugging + + if test -n "$defaults_file" + then + dfile=`parse_arg "$defaults_file"` + cat "$dfile" >>$config + fi +} + +get_root_password() { + status=1 + while [ $status -eq 1 ]; do + stty -echo + echo $echo_n "Enter current password for root (enter for none): $echo_c" + read password + echo + stty echo + if [ "x$password" = "x" ]; then + emptypass=1 + else + emptypass=0 + fi + rootpass=$password + make_config + do_query "show create user root@localhost" + status=$? + done + if grep -q unix_socket $output; then + emptypass=0 + fi + echo "OK, successfully used password, moving on..." + echo +} + +set_root_password() { + stty -echo + echo $echo_n "New password: $echo_c" + read password1 + echo + echo $echo_n "Re-enter new password: $echo_c" + read password2 + echo + stty echo + + if [ "$password1" != "$password2" ]; then + echo "Sorry, passwords do not match." + echo + return 1 + fi + + if [ "$password1" = "" ]; then + echo "Sorry, you can't use an empty password here." + echo + return 1 + fi + + esc_pass=`basic_single_escape "$password1"` + do_query "UPDATE mysql.global_priv SET priv=json_set(priv, '$.plugin', 'mysql_native_password', '$.authentication_string', PASSWORD('$esc_pass')) WHERE User='root';" + if [ $? -eq 0 ]; then + echo "Password updated successfully!" + echo "Reloading privilege tables.." + reload_privilege_tables + if [ $? -eq 1 ]; then + clean_and_exit + fi + echo + rootpass=$password1 + make_config + else + echo "Password update failed!" + clean_and_exit + fi + + return 0 +} + +remove_anonymous_users() { + do_query "DELETE FROM mysql.global_priv WHERE User='';" + if [ $? -eq 0 ]; then + echo " ... Success!" + else + echo " ... Failed!" + clean_and_exit + fi + + return 0 +} + +remove_remote_root() { + do_query "DELETE FROM mysql.global_priv WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');" + if [ $? -eq 0 ]; then + echo " ... Success!" + else + echo " ... Failed!" + fi +} + +remove_test_database() { + echo " - Dropping test database..." + do_query "DROP DATABASE IF EXISTS test;" + if [ $? -eq 0 ]; then + echo " ... Success!" + else + echo " ... Failed! Not critical, keep moving..." + fi + + echo " - Removing privileges on test database..." + do_query "DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'" + if [ $? -eq 0 ]; then + echo " ... Success!" + else + echo " ... Failed! Not critical, keep moving..." + fi + + return 0 +} + +reload_privilege_tables() { + do_query "FLUSH PRIVILEGES;" + if [ $? -eq 0 ]; then + echo " ... Success!" + return 0 + else + echo " ... Failed!" + return 1 + fi +} + +interrupt() { + echo + echo "Aborting!" + echo + cleanup + stty echo + exit 1 +} + +cleanup() { + echo "Cleaning up..." + rm -f $config $command $output +} + +# Remove the files before exiting. +clean_and_exit() { + cleanup + exit 1 +} + +# The actual script starts here + +prepare +set_echo_compat + +echo +echo "NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB" +echo " SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!" +echo +echo "In order to log into MariaDB to secure it, we'll need the current" +echo "password for the root user. If you've just installed MariaDB, and" +echo "haven't set the root password yet, you should just press enter here." +echo + +get_root_password + + +# +# Set the root password +# + +echo "Setting the root password or using the unix_socket ensures that nobody" +echo "can log into the MariaDB root user without the proper authorisation." +echo + +while true ; do + if [ $emptypass -eq 1 ]; then + echo $echo_n "Enable unix_socket authentication? [Y/n] $echo_c" + else + echo "You already have your root account protected, so you can safely answer 'n'." + echo + echo $echo_n "Switch to unix_socket authentication [Y/n] $echo_c" + fi + read reply + validate_reply $reply && break +done + +if [ "$reply" = "n" ]; then + echo " ... skipping." +else + emptypass=0 + do_query "UPDATE mysql.global_priv SET priv=json_set(priv, '$.password_last_changed', UNIX_TIMESTAMP(), '$.plugin', 'mysql_native_password', '$.authentication_string', 'invalid', '$.auth_or', json_array(json_object(), json_object('plugin', 'unix_socket'))) WHERE User='root';" + if [ $? -eq 0 ]; then + echo "Enabled successfully!" + echo "Reloading privilege tables.." + reload_privilege_tables + if [ $? -eq 1 ]; then + clean_and_exit + fi + echo + else + echo "Failed!" + clean_and_exit + fi +fi +echo + +while true ; do + if [ $emptypass -eq 1 ]; then + echo $echo_n "Set root password? [Y/n] $echo_c" + else + echo "You already have your root account protected, so you can safely answer 'n'." + echo + echo $echo_n "Change the root password? [Y/n] $echo_c" + fi + read reply + validate_reply $reply && break +done + +if [ "$reply" = "n" ]; then + echo " ... skipping." +else + status=1 + while [ $status -eq 1 ]; do + set_root_password + status=$? + done +fi +echo + + +# +# Remove anonymous users +# + +echo "By default, a MariaDB installation has an anonymous user, allowing anyone" +echo "to log into MariaDB without having to have a user account created for" +echo "them. This is intended only for testing, and to make the installation" +echo "go a bit smoother. You should remove them before moving into a" +echo "production environment." +echo + +while true ; do + echo $echo_n "Remove anonymous users? [Y/n] $echo_c" + read reply + validate_reply $reply && break +done +if [ "$reply" = "n" ]; then + echo " ... skipping." +else + remove_anonymous_users +fi +echo + + +# +# Disallow remote root login +# + +echo "Normally, root should only be allowed to connect from 'localhost'. This" +echo "ensures that someone cannot guess at the root password from the network." +echo +while true ; do + echo $echo_n "Disallow root login remotely? [Y/n] $echo_c" + read reply + validate_reply $reply && break +done +if [ "$reply" = "n" ]; then + echo " ... skipping." +else + remove_remote_root +fi +echo + + +# +# Remove test database +# + +echo "By default, MariaDB comes with a database named 'test' that anyone can" +echo "access. This is also intended only for testing, and should be removed" +echo "before moving into a production environment." +echo + +while true ; do + echo $echo_n "Remove test database and access to it? [Y/n] $echo_c" + read reply + validate_reply $reply && break +done + +if [ "$reply" = "n" ]; then + echo " ... skipping." +else + remove_test_database +fi +echo + + +# +# Reload privilege tables +# + +echo "Reloading the privilege tables will ensure that all changes made so far" +echo "will take effect immediately." +echo + +while true ; do + echo $echo_n "Reload privilege tables now? [Y/n] $echo_c" + read reply + validate_reply $reply && break +done + +if [ "$reply" = "n" ]; then + echo " ... skipping." +else + reload_privilege_tables +fi +echo + +cleanup + +echo +echo "All done! If you've completed all of the above steps, your MariaDB" +echo "installation should now be secure." +echo +echo "Thanks for using MariaDB!" diff --git a/scripts/mysql_setpermission.sh b/scripts/mysql_setpermission.sh new file mode 100644 index 00000000..29311b9c --- /dev/null +++ b/scripts/mysql_setpermission.sh @@ -0,0 +1,703 @@ +#!@PERL_PATH@ +## Emacs, this is -*- perl -*- mode? :-) + +# Copyright (c) 2000, 2017, 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 Library 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 +# Library General Public License for more details. +# +# You should have received a copy of the GNU Library General Public +# License along with this library; if not, write to the Free +# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +# MA 02110-1335 USA + +## +## Permission setter for MySQL +## +## mady by Luuk de Boer (luuk@wxs.nl) 1998. +## it's made under GPL ...:-)) +## +## +############################################################################ +## History +## +## 1.0 first start of the program +## 1.1 some changes from monty and after that +## initial release in mysql 3.22.10 (nov 1998) +## 1.2 begin screen now in a loop + quit is using 0 instead of 9 +## after ideas of Paul DuBois. +## 1.2a Add Grant, References, Index and Alter privilege handling (Monty) +## 1.3 Applied patch provided by Martin Mokrejs <mmokrejs@natur.cuni.cz> +## (General code cleanup, use the GRANT statement instead of updating +## the privilege tables directly, added option to revoke privileges) +## 1.4 Remove option 6 which attempted to erroneously grant global privileges + +#### TODO +# +# empty ... suggestions ... mail them to me ... + + +$version="1.4"; + +use DBI; +use Getopt::Long; +use strict; +use vars qw($dbh $sth $hostname $opt_user $opt_password $opt_help $opt_host + $opt_socket $opt_port $host $version); + +my $sqlhost = ""; +my $user = ""; + +$dbh=$host=$opt_user= $opt_password= $opt_help= $opt_host= $opt_socket= ""; +$opt_port=3306; + +read_my_cnf(); # Read options from ~/.my.cnf + +GetOptions("user=s","password=s","help","host=s","socket=s","port=i"); + +usage() if ($opt_help); # the help function + +## User may have put the port with the host. + +if ($opt_host =~ s/:(\d+)$//) +{ + $opt_port = $1; +} + +if ($opt_host eq '') +{ + $sqlhost = "localhost"; +} +else +{ + $sqlhost = $opt_host; +} + +# ask for a password if no password is set already +if ($opt_password eq '') +{ + system "stty -echo"; + print "Password for user $opt_user to connect to MariaDB: "; + $opt_password = <STDIN>; + chomp($opt_password); + system "stty echo"; + print "\n"; +} + +## Socket takes precedence. +my $dsn; +my $prefix= 'mysql'; + +if (eval {DBI->install_driver("MariaDB")}) { + $dsn ="DBI:MariaDB:;"; + $prefix= 'mariadb'; +} +else { + $dsn = "DBI:mysql:;"; +} + +if ($opt_socket and -S $opt_socket) +{ + $dsn .= "${prefix}_socket=$opt_socket"; +} +else +{ + $dsn .= "host=$sqlhost;port=$opt_port"; +} + +# make the connection to MariaDB +$dbh= DBI->connect($dsn,$opt_user,$opt_password, { RaiseError => 1, PrintError => 0}) || + die("Can't make a connection to the MariaDB server.\n The error: $DBI::errstr"); + +# the start of the program +&q1(); +exit(0); # the end... + +##### +# below all subroutines of the program +##### + +### +# the beginning of the program +### +sub q1 { # first question ... + my ($answer,$end); + while (! $end) { + print "#"x70; + print "\n"; + print "## Welcome to the permission setter $version for MariaDB.\n"; + print "## made by Luuk de Boer\n"; + print "#"x70; + print "\n"; + print "What would you like to do:\n"; + print " 1. Set password for an existing user.\n"; + print " 2. Create a database + user privilege for that database\n"; + print " and host combination (user can only do SELECT)\n"; + print " 3. Create/append user privilege for an existing database\n"; + print " and host combination (user can only do SELECT)\n"; + print " 4. Create/append broader user privileges for an existing\n"; + print " database and host combination\n"; + print " (user can do SELECT,INSERT,UPDATE,DELETE)\n"; + print " 5. Create/append quite extended user privileges for an\n"; + print " existing database and host combination (user can do\n"; + print " SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,\n"; + print " LOCK TABLES,CREATE TEMPORARY TABLES)\n"; + print " 6. Create/append full privileges for an existing database\n"; + print " and host combination (user has FULL privilege)\n"; + print " 7. Remove all privileges for for an existing database and\n"; + print " host combination.\n"; + print " (user will have all permission fields set to N)\n"; + print " 0. exit this program\n"; + print "\nMake your choice [1,2,3,4,5,6,7,0]: "; + while (<STDIN>) { + $answer = $_; + chomp($answer); + if ($answer =~ /^[1234567]$/) { + if ($answer == 1) { + setpwd(); + } elsif ($answer =~ /^[234567]$/) { + addall($answer); + } else { + print "Sorry, something went wrong. With such option number you should not get here.\n\n"; + $end = 1; + } + } elsif ($answer == 0) { + print "We hope we can help you next time \n\n"; + $end = 1; + } else { + print "Your answer was $answer\n"; + print "and that's wrong .... Try again\n"; + } + last; + } + } +} + +### +# set a password for a user +### +sub setpwd +{ + my ($user,$pass,$host) = ""; + print "\n\nSetting a (new) password for a user.\n"; + + $user = user(); + $pass = newpass($user); + $host = hosts($user); + + print "#"x70; + print "\n\n"; + print "That was it ... here is an overview of what you gave to me:\n"; + print "The username : $user\n"; +# print "The password : $pass\n"; + print "The host : $host\n"; + print "#"x70; + print "\n\n"; + print "Are you pretty sure you would like to implement this [yes/no]: "; + my $no = <STDIN>; + chomp($no); + if ($no =~ /n/i) + { + print "Okay .. that was it then ... See ya\n\n"; + return(0); + } + else + { + print "Okay ... let's go then ...\n\n"; + } + $user = $dbh->quote($user); + $host = $dbh->quote($host); + if ($pass eq '') + { + $pass = "''"; + } + else + { + $pass = "PASSWORD(". $dbh->quote($pass) . ")"; + } + my $uh= "$user@$host"; + my $sth = $dbh->prepare("set password for $uh =$pass") || die $dbh->errstr; + $sth->execute || die $dbh->errstr; + $sth->finish; + print "The password is set for user $user.\n\n"; + +} + +### +# all things which will be added are done here +### +sub addall { + my ($todo) = @_; + my ($answer,$good,$db,$user,$pass,$host,$priv); + + if ($todo == 2) { + $db = newdatabase(); + } else { + $db = database(); + } + + $user = newuser(); + $pass = newpass("$user"); + $host = newhosts(); + + print "#"x70; + print "\n\n"; + print "That was it ... here is an overview of what you gave to me:\n"; + print "The database name : $db\n"; + print "The username : $user\n"; +# print "The password : $pass\n"; + print "The host(s) : $host\n"; + print "#"x70; + print "\n\n"; + print "Are you pretty sure you would like to implement this [yes/no]: "; + my $no = <STDIN>; + chomp($no); + if ($no =~ /n/i) { + print "Okay .. that was it then ... See ya\n\n"; + return(0); + } else { + print "Okay ... let's go then ...\n\n"; + } + + if ($todo == 2) { + # create the database + if ($db) { + my $sth = $dbh->do("CREATE DATABASE $db") || $dbh->errstr; + } else { + print STDERR "What do you want? You wanted to create new database and add new user, right?\n"; + die "But then specify databasename, please\n"; + } + } + + if ( ( !$todo ) or not ( $todo =~ m/^[2-7]$/ ) ) { + print STDERR "Sorry, select option $todo isn't known inside the program .. See ya\n"; + quit(); + } + + my @hosts = split(/,/,$host); + if (!$user) { + die "username not specified: $user\n"; + } + if (!$db) { + die "databasename is not specified nor *\n"; + } + foreach $host (@hosts) { + # user privileges: SELECT + if (($todo == 2) || ($todo == 3)) { + $sth = $dbh->do("GRANT SELECT ON $db.* TO \'$user\'@\'$host\' IDENTIFIED BY \'$pass\'") || die $dbh->errstr; + } elsif ($todo == 4) { + # user privileges: SELECT,INSERT,UPDATE,DELETE + $sth = $dbh->do("GRANT SELECT,INSERT,UPDATE,DELETE ON $db.* TO \'$user\'@\'$host\' IDENTIFIED BY \'$pass\'") || die $dbh->errstr; + } elsif ($todo == 5) { + # user privileges: SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,LOCK TABLES,CREATE TEMPORARY TABLES + $sth = $dbh->do("GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,LOCK TABLES,CREATE TEMPORARY TABLES ON $db.* TO \'$user\'@\'$host\' IDENTIFIED BY \'$pass\'") || die $dbh->errstr; + } elsif ($todo == 6) { + # all privileges + $sth = $dbh->do("GRANT ALL ON $db.* TO \'$user\'\@\'$host\' IDENTIFIED BY \'$pass\'") || die $dbh->errstr; + } elsif ($todo == 7) { + # all privileges set to N + $sth = $dbh->do("REVOKE ALL ON $db.* FROM \'$user\'\@\'$host\'") || die $dbh->errstr; + } + } + $dbh->do("FLUSH PRIVILEGES") || print STDERR "Can't flush privileges\n"; + print "Everything is inserted and mysql privileges have been reloaded.\n\n"; +} + +### +# ask for a new database name +### +sub newdatabase { + my ($answer,$good,$db); + print "\n\nWhich database would you like to add: "; + while (<STDIN>) { + $answer = $_; + $good = 0; + chomp($answer); + if ($answer) { + my $sth = $dbh->prepare("SHOW DATABASES") || die $dbh->errstr; + $sth->execute || die $dbh->errstr; + while (my @r = $sth->fetchrow_array) { + if ($r[0] eq $answer) { + print "\n\nSorry, this database name is already in use; try something else: "; + $good = 1; + } + } + } else { + print "You must type something ...\nTry again: "; + next; + } + last if ($good == 0); + } + $db = $answer; + print "The new database $db will be created\n"; + return($db); +} + +### +# select a database +### +sub database { + my ($answer,$good,$db); + print "\n\nWhich database from existing databases would you like to select: \n"; + print "You can choose from: \n"; + my $sth = $dbh->prepare("show databases") || die $dbh->errstr; + $sth->execute || die $dbh->errstr; + while (my @r = $sth->fetchrow_array) { + print " - $r[0] \n"; + } + print "Which database will it be (case sensitive). Type * for any: \n"; + while (<STDIN>) { + $answer = $_; + $good = 0; + chomp($answer); + if ($answer) { + if ($answer eq "*") { + print "OK, the user entry will NOT be limited to any database"; + return("*"); + } + my $sth = $dbh->prepare("show databases") || die $dbh->errstr; + $sth->execute || die $dbh->errstr; + while (my @r = $sth->fetchrow_array) { + if ($r[0] eq $answer) { + $good = 1; + $db = $r[0]; + last; + } + } + } else { + print "Type either database name or * meaning any databasename. That means"; + print " any of those above but also any which will be created in future!"; + print " This option gives a user chance to operate on databse mysql, which"; + print " contains privilege settings. That is really risky!\n"; + next; + } + if ($good == 1) { + last; + } else { + print "You must select one from the list.\nTry again: "; + next; + } + } + print "The database $db will be used.\n"; + return($db); +} + +### +# ask for a new username +### +sub newuser +{ + my $user = ""; + my $answer = ""; + + print "\nWhat username is to be created: "; + while(<STDIN>) + { + $answer = $_; + chomp($answer); + if ($answer) + { + $user = $answer; + } + else + { + print "You must type something ...\nTry again: "; + next; + } + last; + } + print "Username = $user\n"; + return($user); +} + +### +# ask for a user which is already in the user table +### +sub user +{ + my ($answer,$user); + + print "\nFor which user do you want to specify a password: "; + while(<STDIN>) + { + $answer = $_; + chomp($answer); + if ($answer) + { + my $sth = $dbh->prepare("select User from mysql.user where User = '$answer'") || die $dbh->errstr; + $sth->execute || die $dbh->errstr; + my @r = $sth->fetchrow_array; + if ($r[0]) + { + $user = $r[0]; + } + else + { + print "Sorry, user $answer isn't known in the user table.\nTry again: "; + next; + } + } + else + { + print "You must type something ...\nTry again: "; + next; + } + last; + } + print "Username = $user\n"; + return($user); +} + +### +# ask for a new password +### +sub newpass +{ + my ($user) = @_; + my ($pass,$answer,$good,$yes); + + print "Would you like to set a password for $user [y/n]: "; + $yes = <STDIN>; + chomp($yes); + if ($yes =~ /y/) + { + system "stty -echo"; + print "What password do you want to specify for $user: "; + while(<STDIN>) + { + $answer = $_; + chomp($answer); + system "stty echo"; + print "\n"; + if ($answer) + { + system "stty -echo"; + print "Type the password again: "; + my $second = <STDIN>; + chomp($second); + system "stty echo"; + print "\n"; + if ($answer ne $second) + { + print "Passwords aren't the same; we begin from scratch again.\n"; + system "stty -echo"; + print "Password please: "; + next; + } + else + { + $pass = $answer; + } + } + else + { + print "You must type something ...\nTry again: "; + next; + } + last; + } +# print "The password for $user is $pass.\n"; + } + else + { + print "We won't set a password so the user doesn't have to use it\n"; + $pass = ""; + } + return($pass); +} + +### +# ask for new hosts +### +sub newhosts +{ + my ($host,$answer,$good); + + print "We now need to know from what host(s) the user will connect.\n"; + print "Keep in mind that % means 'from any host' ...\n"; + print "The host please: "; + while(<STDIN>) + { + $answer = $_; + chomp($answer); + if ($answer) + { + $host .= ",$answer"; + print "Would you like to add another host [yes/no]: "; + my $yes = <STDIN>; + chomp($yes); + if ($yes =~ /y/i) + { + print "Okay, give us the host please: "; + next; + } + else + { + print "Okay we keep it with this ...\n"; + } + } + else + { + print "You must type something ...\nTry again: "; + next; + } + last; + } + $host =~ s/^,//; + print "The following host(s) will be used: $host.\n"; + return($host); +} + +### +# ask for a host which is already in the user table +### +sub hosts +{ + my ($user) = @_; + my ($answer,$good,$host); + + print "We now need to know which host for $user we have to change.\n"; + print "Choose from the following hosts: \n"; + $user = $dbh->quote($user); + my $sth = $dbh->prepare("select Host,User from mysql.user where User = $user") || die $dbh->errstr; + $sth->execute || die $dbh->errstr; + while (my @r = $sth->fetchrow_array) + { + print " - $r[0] \n"; + } + print "The host please (case sensitive): "; + while(<STDIN>) + { + $answer = $_; + chomp($answer); + if ($answer) + { + $sth = $dbh->prepare("select Host,User from mysql.user where Host = '$answer' and User = $user") || die $dbh->errstr; + $sth->execute || die $dbh->errstr; + my @r = $sth->fetchrow_array; + if ($r[0]) + { + $host = $answer; + last; + } + else + { + print "You have to select a host from the list ...\nTry again: "; + next; + } + } + else + { + print "You have to type something ...\nTry again: "; + next; + } + last; + } + print "The following host will be used: $host.\n"; + return($host); +} + +### +# a nice quit (first disconnect and then exit +### +sub quit +{ + $dbh->disconnect; + exit(0); +} + +### +# Read variables password, port and socket from .my.cnf under the client +# or perl groups +### + +sub read_my_cnf +{ + open(TMP,$ENV{'HOME'} . "/.my.cnf") || return 1; + while (<TMP>) + { + if (/^\[(client|perl)\]/i) + { + print "Options read from mycnf:\n"; + while ((defined($_=<TMP>)) && !/^\[\w+\]/) + { + next if /^\s*($|#)/; ## skip blanks and comments + print $_; + if (/^host\s*=\s*(\S+)/i) + { + $opt_host = $1; + } + elsif (/^user\s*=\s*(\S+)/i) + { + $opt_user = $1; + } + elsif (/^password\s*=\s*(\S+)/i) + { + $opt_password = $1; + } + elsif (/^port\s*=\s*(\S+)/i) + { + $opt_port = $1; + } + elsif (/^socket\s*=\s*(\S+)/i) + { + $opt_socket = $1; + } + } + print "------------------------\n"; + } + } + close(TMP); +} + +### +# the help text +### +sub usage +{ + print <<EOL; +---------------------------------------------------------------------- + The permission setter for MariaDB. + version: $version + + made by: Luuk de Boer <luuk\@wxs.nl> +---------------------------------------------------------------------- + +The permission setter is a little program which can help you add users +or databases or change passwords in MariaDB. Keep in mind that we don't +check permissions which already been set in MariaDB. So if you can't +connect to MariaDB using the permission you just added, take a look at +the permissions which have already been set in MariaDB. + +The permission setter first reads your .my.cnf file in your Home +directory if it exists. + +Options for the permission setter: + +--help : print this help message and exit. + +The options shown below are used for making the connection to the MariaDB +server. Keep in mind that the permissions for the user specified via +these options must be sufficient to add users / create databases / set +passwords. + +--user : is the username to connect with. +--password : the password of the username. +--host : the host to connect to. +--socket : the socket to connect to. +--port : the port number of the host to connect to. + +If you don't give a password and no password is set in your .my.cnf +file, then the permission setter will ask for a password. + + +EOL +exit(0); +} diff --git a/scripts/mysql_system_tables.sql b/scripts/mysql_system_tables.sql new file mode 100644 index 00000000..5e9d8424 --- /dev/null +++ b/scripts/mysql_system_tables.sql @@ -0,0 +1,342 @@ +-- Copyright (c) 2007, 2018, Oracle and/or its affiliates. +-- Copyright (c) 2008, 2019, MariaDB Corporation. +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; version 2 of the License. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +-- +-- The system tables of MySQL Server +-- + +set sql_mode=''; + +set @orig_storage_engine=@@default_storage_engine; +set default_storage_engine=Aria; + +set system_versioning_alter_history=keep; + +set @have_innodb= (select count(engine) from information_schema.engines where engine='INNODB' and support != 'NO'); +SET @innodb_or_aria=IF(@have_innodb <> 0, 'InnoDB', 'Aria'); + +CREATE TABLE IF NOT EXISTS db ( Host char(60) binary DEFAULT '' NOT NULL, Db char(64) binary DEFAULT '' NOT NULL, User char(80) binary DEFAULT '' NOT NULL, Select_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Insert_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Update_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Delete_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Create_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Drop_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Grant_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, References_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Index_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Alter_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Create_tmp_table_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Lock_tables_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Create_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Show_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Create_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Alter_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Execute_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Event_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Trigger_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, Delete_history_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, PRIMARY KEY /*Host */(Host,Db,User), KEY User (User) ) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='Database privileges'; + +-- Remember for later if db table already existed +set @had_db_table= @@warning_count != 0; + +CREATE TABLE IF NOT EXISTS global_priv (Host char(60) binary DEFAULT '', User char(80) binary DEFAULT '', Priv JSON NOT NULL DEFAULT '{}' CHECK(JSON_VALID(Priv)), PRIMARY KEY (Host,User)) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='Users and global privileges'; + +set @had_sys_user= 0 <> (select count(*) from mysql.global_priv where Host="localhost" and User="mariadb.sys"); + +set @exists_user_view= EXISTS (SELECT * FROM information_schema.VIEWS WHERE TABLE_CATALOG = 'def' and TABLE_SCHEMA = 'mysql' and TABLE_NAME='user'); + +set @exists_user_view_by_root= EXISTS (SELECT * FROM information_schema.VIEWS WHERE TABLE_CATALOG = 'def' and TABLE_SCHEMA = 'mysql' and TABLE_NAME='user' and DEFINER = 'mariadb.sys@localhost'); + +set @need_sys_user_creation= (NOT @had_sys_user) AND (( NOT @exists_user_view) OR @exists_user_view_by_root); + +CREATE TEMPORARY TABLE tmp_user_sys LIKE global_priv; +INSERT INTO tmp_user_sys (Host,User,Priv) VALUES ('localhost','mariadb.sys','{"access":0,"plugin":"mysql_native_password","authentication_string":"","account_locked":true,"password_last_changed":0}'); +INSERT INTO global_priv SELECT * FROM tmp_user_sys WHERE 0 <> @need_sys_user_creation; +DROP TABLE tmp_user_sys; + + +CREATE DEFINER='mariadb.sys'@'localhost' SQL SECURITY DEFINER VIEW IF NOT EXISTS user AS SELECT + Host, + User, + IF(JSON_VALUE(Priv, '$.plugin') IN ('mysql_native_password', 'mysql_old_password'), IFNULL(JSON_VALUE(Priv, '$.authentication_string'), ''), '') AS Password, + IF(JSON_VALUE(Priv, '$.access') & 1, 'Y', 'N') AS Select_priv, + IF(JSON_VALUE(Priv, '$.access') & 2, 'Y', 'N') AS Insert_priv, + IF(JSON_VALUE(Priv, '$.access') & 4, 'Y', 'N') AS Update_priv, + IF(JSON_VALUE(Priv, '$.access') & 8, 'Y', 'N') AS Delete_priv, + IF(JSON_VALUE(Priv, '$.access') & 16, 'Y', 'N') AS Create_priv, + IF(JSON_VALUE(Priv, '$.access') & 32, 'Y', 'N') AS Drop_priv, + IF(JSON_VALUE(Priv, '$.access') & 64, 'Y', 'N') AS Reload_priv, + IF(JSON_VALUE(Priv, '$.access') & 128, 'Y', 'N') AS Shutdown_priv, + IF(JSON_VALUE(Priv, '$.access') & 256, 'Y', 'N') AS Process_priv, + IF(JSON_VALUE(Priv, '$.access') & 512, 'Y', 'N') AS File_priv, + IF(JSON_VALUE(Priv, '$.access') & 1024, 'Y', 'N') AS Grant_priv, + IF(JSON_VALUE(Priv, '$.access') & 2048, 'Y', 'N') AS References_priv, + IF(JSON_VALUE(Priv, '$.access') & 4096, 'Y', 'N') AS Index_priv, + IF(JSON_VALUE(Priv, '$.access') & 8192, 'Y', 'N') AS Alter_priv, + IF(JSON_VALUE(Priv, '$.access') & 16384, 'Y', 'N') AS Show_db_priv, + IF(JSON_VALUE(Priv, '$.access') & 32768, 'Y', 'N') AS Super_priv, + IF(JSON_VALUE(Priv, '$.access') & 65536, 'Y', 'N') AS Create_tmp_table_priv, + IF(JSON_VALUE(Priv, '$.access') & 131072, 'Y', 'N') AS Lock_tables_priv, + IF(JSON_VALUE(Priv, '$.access') & 262144, 'Y', 'N') AS Execute_priv, + IF(JSON_VALUE(Priv, '$.access') & 524288, 'Y', 'N') AS Repl_slave_priv, + IF(JSON_VALUE(Priv, '$.access') & 1048576, 'Y', 'N') AS Repl_client_priv, + IF(JSON_VALUE(Priv, '$.access') & 2097152, 'Y', 'N') AS Create_view_priv, + IF(JSON_VALUE(Priv, '$.access') & 4194304, 'Y', 'N') AS Show_view_priv, + IF(JSON_VALUE(Priv, '$.access') & 8388608, 'Y', 'N') AS Create_routine_priv, + IF(JSON_VALUE(Priv, '$.access') & 16777216, 'Y', 'N') AS Alter_routine_priv, + IF(JSON_VALUE(Priv, '$.access') & 33554432, 'Y', 'N') AS Create_user_priv, + IF(JSON_VALUE(Priv, '$.access') & 67108864, 'Y', 'N') AS Event_priv, + IF(JSON_VALUE(Priv, '$.access') & 134217728, 'Y', 'N') AS Trigger_priv, + IF(JSON_VALUE(Priv, '$.access') & 268435456, 'Y', 'N') AS Create_tablespace_priv, + IF(JSON_VALUE(Priv, '$.access') & 536870912, 'Y', 'N') AS Delete_history_priv, + ELT(IFNULL(JSON_VALUE(Priv, '$.ssl_type'), 0) + 1, '', 'ANY','X509', 'SPECIFIED') AS ssl_type, + IFNULL(JSON_VALUE(Priv, '$.ssl_cipher'), '') AS ssl_cipher, + IFNULL(JSON_VALUE(Priv, '$.x509_issuer'), '') AS x509_issuer, + IFNULL(JSON_VALUE(Priv, '$.x509_subject'), '') AS x509_subject, + CAST(IFNULL(JSON_VALUE(Priv, '$.max_questions'), 0) AS UNSIGNED) AS max_questions, + CAST(IFNULL(JSON_VALUE(Priv, '$.max_updates'), 0) AS UNSIGNED) AS max_updates, + CAST(IFNULL(JSON_VALUE(Priv, '$.max_connections'), 0) AS UNSIGNED) AS max_connections, + CAST(IFNULL(JSON_VALUE(Priv, '$.max_user_connections'), 0) AS SIGNED) AS max_user_connections, + IFNULL(JSON_VALUE(Priv, '$.plugin'), '') AS plugin, + IFNULL(JSON_VALUE(Priv, '$.authentication_string'), '') AS authentication_string, + IF(IFNULL(JSON_VALUE(Priv, '$.password_last_changed'), 1) = 0, 'Y', 'N') AS password_expired, + ELT(IFNULL(JSON_VALUE(Priv, '$.is_role'), 0) + 1, 'N', 'Y') AS is_role, + IFNULL(JSON_VALUE(Priv, '$.default_role'), '') AS default_role, + CAST(IFNULL(JSON_VALUE(Priv, '$.max_statement_time'), 0.0) AS DECIMAL(12,6)) AS max_statement_time + FROM global_priv; + +-- Remember for later if user table already existed +set @had_user_table= @@warning_count != 0; + +CREATE TABLE IF NOT EXISTS roles_mapping ( Host char(60) binary DEFAULT '' NOT NULL, User char(80) binary DEFAULT '' NOT NULL, Role char(80) binary DEFAULT '' NOT NULL, Admin_option enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, UNIQUE (Host, User, Role)) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='Granted roles'; + +CREATE TABLE IF NOT EXISTS func ( name char(64) binary DEFAULT '' NOT NULL, ret tinyint(1) DEFAULT '0' NOT NULL, dl char(128) DEFAULT '' NOT NULL, type enum ('function','aggregate') COLLATE utf8_general_ci NOT NULL, PRIMARY KEY (name) ) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='User defined functions'; + + +CREATE TABLE IF NOT EXISTS plugin ( name varchar(64) DEFAULT '' NOT NULL, dl varchar(128) DEFAULT '' NOT NULL, PRIMARY KEY (name) ) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_general_ci comment='MySQL plugins'; + + +CREATE TABLE IF NOT EXISTS servers ( Server_name char(64) NOT NULL DEFAULT '', Host varchar(2048) NOT NULL DEFAULT '', Db char(64) NOT NULL DEFAULT '', Username char(80) NOT NULL DEFAULT '', Password char(64) NOT NULL DEFAULT '', Port INT(4) NOT NULL DEFAULT '0', Socket char(64) NOT NULL DEFAULT '', Wrapper char(64) NOT NULL DEFAULT '', Owner varchar(512) NOT NULL DEFAULT '', PRIMARY KEY (Server_name)) engine=Aria transactional=1 CHARACTER SET utf8 comment='MySQL Foreign Servers table'; + + +CREATE TABLE IF NOT EXISTS tables_priv ( Host char(60) binary DEFAULT '' NOT NULL, Db char(64) binary DEFAULT '' NOT NULL, User char(80) binary DEFAULT '' NOT NULL, Table_name char(64) binary DEFAULT '' NOT NULL, Grantor char(141) DEFAULT '' NOT NULL, Timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, Table_priv set('Select','Insert','Update','Delete','Create','Drop','Grant','References','Index','Alter','Create View','Show view','Trigger','Delete versioning rows') COLLATE utf8_general_ci DEFAULT '' NOT NULL, Column_priv set('Select','Insert','Update','References') COLLATE utf8_general_ci DEFAULT '' NOT NULL, PRIMARY KEY (Host,Db,User,Table_name), KEY Grantor (Grantor) ) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='Table privileges'; + +CREATE TEMPORARY TABLE tmp_user_sys LIKE tables_priv; +INSERT INTO tmp_user_sys (Host,Db,User,Table_name,Grantor,Timestamp,Table_priv) VALUES ('localhost','mysql','mariadb.sys','global_priv','root@localhost','0','Select,Delete'); +INSERT INTO tables_priv SELECT * FROM tmp_user_sys WHERE 0 <> @need_sys_user_creation; +DROP TABLE tmp_user_sys; + +CREATE TABLE IF NOT EXISTS columns_priv ( Host char(60) binary DEFAULT '' NOT NULL, Db char(64) binary DEFAULT '' NOT NULL, User char(80) binary DEFAULT '' NOT NULL, Table_name char(64) binary DEFAULT '' NOT NULL, Column_name char(64) binary DEFAULT '' NOT NULL, Timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, Column_priv set('Select','Insert','Update','References') COLLATE utf8_general_ci DEFAULT '' NOT NULL, PRIMARY KEY (Host,Db,User,Table_name,Column_name) ) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='Column privileges'; + + +CREATE TABLE IF NOT EXISTS help_topic ( help_topic_id int unsigned not null, name char(64) not null, help_category_id smallint unsigned not null, description text not null, example text not null, url text not null, primary key (help_topic_id), unique index (name) ) engine=Aria transactional=0 CHARACTER SET utf8 comment='help topics'; + + +CREATE TABLE IF NOT EXISTS help_category ( help_category_id smallint unsigned not null, name char(64) not null, parent_category_id smallint unsigned null, url text not null, primary key (help_category_id), unique index (name) ) engine=Aria transactional=0 CHARACTER SET utf8 comment='help categories'; + + +CREATE TABLE IF NOT EXISTS help_relation ( help_topic_id int unsigned not null references help_topic, help_keyword_id int unsigned not null references help_keyword, primary key (help_keyword_id, help_topic_id) ) engine=Aria transactional=0 CHARACTER SET utf8 comment='keyword-topic relation'; + + +CREATE TABLE IF NOT EXISTS help_keyword ( help_keyword_id int unsigned not null, name char(64) not null, primary key (help_keyword_id), unique index (name) ) engine=Aria transactional=0 CHARACTER SET utf8 comment='help keywords'; + + +CREATE TABLE IF NOT EXISTS time_zone_name ( Name char(64) NOT NULL, Time_zone_id int unsigned NOT NULL, PRIMARY KEY /*Name*/ (Name) ) engine=Aria transactional=1 CHARACTER SET utf8 comment='Time zone names'; + + +CREATE TABLE IF NOT EXISTS time_zone ( Time_zone_id int unsigned NOT NULL auto_increment, Use_leap_seconds enum('Y','N') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, PRIMARY KEY /*TzId*/ (Time_zone_id) ) engine=Aria transactional=1 CHARACTER SET utf8 comment='Time zones'; + + +CREATE TABLE IF NOT EXISTS time_zone_transition ( Time_zone_id int unsigned NOT NULL, Transition_time bigint signed NOT NULL, Transition_type_id int unsigned NOT NULL, PRIMARY KEY /*TzIdTranTime*/ (Time_zone_id, Transition_time) ) engine=Aria transactional=1 CHARACTER SET utf8 comment='Time zone transitions'; + + +CREATE TABLE IF NOT EXISTS time_zone_transition_type ( Time_zone_id int unsigned NOT NULL, Transition_type_id int unsigned NOT NULL, Offset int signed DEFAULT 0 NOT NULL, Is_DST tinyint unsigned DEFAULT 0 NOT NULL, Abbreviation char(8) DEFAULT '' NOT NULL, PRIMARY KEY /*TzIdTrTId*/ (Time_zone_id, Transition_type_id) ) engine=Aria transactional=1 CHARACTER SET utf8 comment='Time zone transition types'; + + +CREATE TABLE IF NOT EXISTS time_zone_leap_second ( Transition_time bigint signed NOT NULL, Correction int signed NOT NULL, PRIMARY KEY /*TranTime*/ (Transition_time) ) engine=Aria transactional=1 CHARACTER SET utf8 comment='Leap seconds information for time zones'; + +CREATE TABLE IF NOT EXISTS proc (db char(64) collate utf8_bin DEFAULT '' NOT NULL, name char(64) DEFAULT '' NOT NULL, type enum('FUNCTION','PROCEDURE','PACKAGE','PACKAGE BODY') NOT NULL, specific_name char(64) DEFAULT '' NOT NULL, language enum('SQL') DEFAULT 'SQL' NOT NULL, sql_data_access enum( 'CONTAINS_SQL', 'NO_SQL', 'READS_SQL_DATA', 'MODIFIES_SQL_DATA') DEFAULT 'CONTAINS_SQL' NOT NULL, is_deterministic enum('YES','NO') DEFAULT 'NO' NOT NULL, security_type enum('INVOKER','DEFINER') DEFAULT 'DEFINER' NOT NULL, param_list blob NOT NULL, returns longblob NOT NULL, body longblob NOT NULL, definer char(141) collate utf8_bin DEFAULT '' NOT NULL, created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, modified timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', sql_mode set( 'REAL_AS_FLOAT', 'PIPES_AS_CONCAT', 'ANSI_QUOTES', 'IGNORE_SPACE', 'IGNORE_BAD_TABLE_OPTIONS', 'ONLY_FULL_GROUP_BY', 'NO_UNSIGNED_SUBTRACTION', 'NO_DIR_IN_CREATE', 'POSTGRESQL', 'ORACLE', 'MSSQL', 'DB2', 'MAXDB', 'NO_KEY_OPTIONS', 'NO_TABLE_OPTIONS', 'NO_FIELD_OPTIONS', 'MYSQL323', 'MYSQL40', 'ANSI', 'NO_AUTO_VALUE_ON_ZERO', 'NO_BACKSLASH_ESCAPES', 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'NO_ZERO_IN_DATE', 'NO_ZERO_DATE', 'INVALID_DATES', 'ERROR_FOR_DIVISION_BY_ZERO', 'TRADITIONAL', 'NO_AUTO_CREATE_USER', 'HIGH_NOT_PRECEDENCE', 'NO_ENGINE_SUBSTITUTION', 'PAD_CHAR_TO_FULL_LENGTH', 'EMPTY_STRING_IS_NULL', 'SIMULTANEOUS_ASSIGNMENT', 'TIME_ROUND_FRACTIONAL') DEFAULT '' NOT NULL, comment text collate utf8_bin NOT NULL, character_set_client char(32) collate utf8_bin, collation_connection char(32) collate utf8_bin, db_collation char(32) collate utf8_bin, body_utf8 longblob, aggregate enum('NONE', 'GROUP') DEFAULT 'NONE' NOT NULL, PRIMARY KEY (db,name,type)) engine=Aria transactional=1 character set utf8 comment='Stored Procedures'; + +CREATE TABLE IF NOT EXISTS procs_priv ( Host char(60) binary DEFAULT '' NOT NULL, Db char(64) binary DEFAULT '' NOT NULL, User char(80) binary DEFAULT '' NOT NULL, Routine_name char(64) COLLATE utf8_general_ci DEFAULT '' NOT NULL, Routine_type enum('FUNCTION','PROCEDURE','PACKAGE','PACKAGE BODY') NOT NULL, Grantor char(141) DEFAULT '' NOT NULL, Proc_priv set('Execute','Alter Routine','Grant') COLLATE utf8_general_ci DEFAULT '' NOT NULL, Timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (Host,Db,User,Routine_name,Routine_type), KEY Grantor (Grantor) ) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='Procedure privileges'; + + +-- Create general_log if CSV is enabled. +SET @have_csv = (SELECT support FROM information_schema.engines WHERE engine = 'CSV'); +SET @str = IF (@have_csv = 'YES', 'CREATE TABLE IF NOT EXISTS general_log (event_time TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, user_host MEDIUMTEXT NOT NULL, thread_id BIGINT(21) UNSIGNED NOT NULL, server_id INTEGER UNSIGNED NOT NULL, command_type VARCHAR(64) NOT NULL, argument MEDIUMTEXT NOT NULL) engine=CSV CHARACTER SET utf8 comment="General log"', 'SET @dummy = 0'); + +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +-- Create slow_log if CSV is enabled. + +SET @str = IF (@have_csv = 'YES', 'CREATE TABLE IF NOT EXISTS slow_log (start_time TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, user_host MEDIUMTEXT NOT NULL, query_time TIME(6) NOT NULL, lock_time TIME(6) NOT NULL, rows_sent INTEGER NOT NULL, rows_examined INTEGER NOT NULL, db VARCHAR(512) NOT NULL, last_insert_id INTEGER NOT NULL, insert_id INTEGER NOT NULL, server_id INTEGER UNSIGNED NOT NULL, sql_text MEDIUMTEXT NOT NULL, thread_id BIGINT(21) UNSIGNED NOT NULL, rows_affected INTEGER NOT NULL) engine=CSV CHARACTER SET utf8 comment="Slow log"', 'SET @dummy = 0'); + +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +CREATE TABLE IF NOT EXISTS event ( db char(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL default '', name char(64) CHARACTER SET utf8 NOT NULL default '', body longblob NOT NULL, definer char(141) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL default '', execute_at DATETIME default NULL, interval_value int(11) default NULL, interval_field ENUM('YEAR','QUARTER','MONTH','DAY','HOUR','MINUTE','WEEK','SECOND','MICROSECOND','YEAR_MONTH','DAY_HOUR','DAY_MINUTE','DAY_SECOND','HOUR_MINUTE','HOUR_SECOND','MINUTE_SECOND','DAY_MICROSECOND','HOUR_MICROSECOND','MINUTE_MICROSECOND','SECOND_MICROSECOND') default NULL, created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, modified TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', last_executed DATETIME default NULL, starts DATETIME default NULL, ends DATETIME default NULL, status ENUM('ENABLED','DISABLED','SLAVESIDE_DISABLED') NOT NULL default 'ENABLED', on_completion ENUM('DROP','PRESERVE') NOT NULL default 'DROP', sql_mode set('REAL_AS_FLOAT','PIPES_AS_CONCAT','ANSI_QUOTES','IGNORE_SPACE','IGNORE_BAD_TABLE_OPTIONS','ONLY_FULL_GROUP_BY','NO_UNSIGNED_SUBTRACTION','NO_DIR_IN_CREATE','POSTGRESQL','ORACLE','MSSQL','DB2','MAXDB','NO_KEY_OPTIONS','NO_TABLE_OPTIONS','NO_FIELD_OPTIONS','MYSQL323','MYSQL40','ANSI','NO_AUTO_VALUE_ON_ZERO','NO_BACKSLASH_ESCAPES','STRICT_TRANS_TABLES','STRICT_ALL_TABLES','NO_ZERO_IN_DATE','NO_ZERO_DATE','INVALID_DATES','ERROR_FOR_DIVISION_BY_ZERO','TRADITIONAL','NO_AUTO_CREATE_USER','HIGH_NOT_PRECEDENCE','NO_ENGINE_SUBSTITUTION','PAD_CHAR_TO_FULL_LENGTH','EMPTY_STRING_IS_NULL','SIMULTANEOUS_ASSIGNMENT','TIME_ROUND_FRACTIONAL') DEFAULT '' NOT NULL, comment char(64) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL default '', originator INTEGER UNSIGNED NOT NULL, time_zone char(64) CHARACTER SET latin1 NOT NULL DEFAULT 'SYSTEM', character_set_client char(32) collate utf8_bin, collation_connection char(32) collate utf8_bin, db_collation char(32) collate utf8_bin, body_utf8 longblob, PRIMARY KEY (db, name) ) engine=Aria transactional=1 DEFAULT CHARSET=utf8 COMMENT 'Events'; + +SET @create_innodb_table_stats="CREATE TABLE IF NOT EXISTS innodb_table_stats ( + database_name VARCHAR(64) NOT NULL, + table_name VARCHAR(199) NOT NULL, + last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + n_rows BIGINT UNSIGNED NOT NULL, + clustered_index_size BIGINT UNSIGNED NOT NULL, + sum_of_other_index_sizes BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (database_name, table_name) +) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0"; + +SET @create_innodb_index_stats="CREATE TABLE IF NOT EXISTS innodb_index_stats ( + database_name VARCHAR(64) NOT NULL, + table_name VARCHAR(199) NOT NULL, + index_name VARCHAR(64) NOT NULL, + last_update TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + /* there are at least: + stat_name='size' + stat_name='n_leaf_pages' + stat_name='n_diff_pfx%' */ + stat_name VARCHAR(64) NOT NULL, + stat_value BIGINT UNSIGNED NOT NULL, + sample_size BIGINT UNSIGNED, + stat_description VARCHAR(1024) NOT NULL, + PRIMARY KEY (database_name, table_name, index_name, stat_name) +) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0"; + +SET @create_transaction_registry="CREATE TABLE IF NOT EXISTS transaction_registry ( + transaction_id BIGINT UNSIGNED NOT NULL, + commit_id BIGINT UNSIGNED NOT NULL, + begin_timestamp TIMESTAMP(6) NOT NULL DEFAULT '0000-00-00 00:00:00.000000', + commit_timestamp TIMESTAMP(6) NOT NULL DEFAULT '0000-00-00 00:00:00.000000', + isolation_level ENUM('READ-UNCOMMITTED', 'READ-COMMITTED', + 'REPEATABLE-READ', 'SERIALIZABLE') NOT NULL, + PRIMARY KEY (transaction_id), + UNIQUE KEY (commit_id), + INDEX (begin_timestamp), + INDEX (commit_timestamp, transaction_id) +) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_bin STATS_PERSISTENT=0"; + +SET @str=IF(@have_innodb <> 0, @create_innodb_table_stats, "SET @dummy = 0"); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +SET @str=IF(@have_innodb <> 0, @create_innodb_index_stats, "SET @dummy = 0"); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +SET @str=IF(@have_innodb <> 0, @create_transaction_registry, "SET @dummy = 0"); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +SET @cmd="CREATE TABLE IF NOT EXISTS slave_relay_log_info ( + Number_of_lines INTEGER UNSIGNED NOT NULL COMMENT 'Number of lines in the file or rows in the table. Used to version table definitions.', + Relay_log_name TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the current relay log file.', + Relay_log_pos BIGINT UNSIGNED NOT NULL COMMENT 'The relay log position of the last executed event.', + Master_log_name TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the master binary log file from which the events in the relay log file were read.', + Master_log_pos BIGINT UNSIGNED NOT NULL COMMENT 'The master log position of the last executed event.', + Sql_delay INTEGER NOT NULL COMMENT 'The number of seconds that the slave must lag behind the master.', + Number_of_workers INTEGER UNSIGNED NOT NULL, + Id INTEGER UNSIGNED NOT NULL COMMENT 'Internal Id that uniquely identifies this record.', + PRIMARY KEY(Id)) DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT 'Relay Log Information'"; + +SET @str=CONCAT(@cmd, ' ENGINE=', @innodb_or_aria); +-- Don't create the table; MariaDB will have another implementation +#PREPARE stmt FROM @str; +#EXECUTE stmt; +#DROP PREPARE stmt; + +SET @cmd= "CREATE TABLE IF NOT EXISTS slave_master_info ( + Number_of_lines INTEGER UNSIGNED NOT NULL COMMENT 'Number of lines in the file.', + Master_log_name TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL COMMENT 'The name of the master binary log currently being read from the master.', + Master_log_pos BIGINT UNSIGNED NOT NULL COMMENT 'The master log position of the last read event.', + Host CHAR(64) CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The host name of the master.', + User_name TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The user name used to connect to the master.', + User_password TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The password used to connect to the master.', + Port INTEGER UNSIGNED NOT NULL COMMENT 'The network port used to connect to the master.', + Connect_retry INTEGER UNSIGNED NOT NULL COMMENT 'The period (in seconds) that the slave will wait before trying to reconnect to the master.', + Enabled_ssl BOOLEAN NOT NULL COMMENT 'Indicates whether the server supports SSL connections.', + Ssl_ca TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The file used for the Certificate Authority (CA) certificate.', + Ssl_capath TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The path to the Certificate Authority (CA) certificates.', + Ssl_cert TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the SSL certificate file.', + Ssl_cipher TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the cipher in use for the SSL connection.', + Ssl_key TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The name of the SSL key file.', + Ssl_verify_server_cert BOOLEAN NOT NULL COMMENT 'Whether to verify the server certificate.', + Heartbeat FLOAT NOT NULL COMMENT '', + Bind TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'Displays which interface is employed when connecting to the MySQL server', + Ignored_server_ids TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The number of server IDs to be ignored, followed by the actual server IDs', + Uuid TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The master server uuid.', + Retry_count BIGINT UNSIGNED NOT NULL COMMENT 'Number of reconnect attempts, to the master, before giving up.', + Ssl_crl TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The file used for the Certificate Revocation List (CRL)', + Ssl_crlpath TEXT CHARACTER SET utf8 COLLATE utf8_bin COMMENT 'The path used for Certificate Revocation List (CRL) files', + Enabled_auto_position BOOLEAN NOT NULL COMMENT 'Indicates whether GTIDs will be used to retrieve events from the master.', + PRIMARY KEY(Host, Port)) DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT 'Master Information'"; + +SET @str=CONCAT(@cmd, ' ENGINE=', @innodb_or_aria); +-- Don't create the table; MariaDB will have another implementation +#PREPARE stmt FROM @str; +#EXECUTE stmt; +#DROP PREPARE stmt; + +SET @cmd= "CREATE TABLE IF NOT EXISTS slave_worker_info ( + Id INTEGER UNSIGNED NOT NULL, + Relay_log_name TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, + Relay_log_pos BIGINT UNSIGNED NOT NULL, + Master_log_name TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, + Master_log_pos BIGINT UNSIGNED NOT NULL, + Checkpoint_relay_log_name TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, + Checkpoint_relay_log_pos BIGINT UNSIGNED NOT NULL, + Checkpoint_master_log_name TEXT CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, + Checkpoint_master_log_pos BIGINT UNSIGNED NOT NULL, + Checkpoint_seqno INT UNSIGNED NOT NULL, + Checkpoint_group_size INTEGER UNSIGNED NOT NULL, + Checkpoint_group_bitmap BLOB NOT NULL, + PRIMARY KEY(Id)) DEFAULT CHARSET=utf8 STATS_PERSISTENT=0 COMMENT 'Worker Information'"; + +SET @str=CONCAT(@cmd, ' ENGINE=', @innodb_or_aria); +-- Don't create the table; MariaDB will have another implementation +#PREPARE stmt FROM @str; +#EXECUTE stmt; +#DROP PREPARE stmt; + +CREATE TABLE IF NOT EXISTS proxies_priv (Host char(60) binary DEFAULT '' NOT NULL, User char(80) binary DEFAULT '' NOT NULL, Proxied_host char(60) binary DEFAULT '' NOT NULL, Proxied_user char(80) binary DEFAULT '' NOT NULL, With_grant BOOL DEFAULT 0 NOT NULL, Grantor char(141) DEFAULT '' NOT NULL, Timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY /*Host*/ (Host,User,Proxied_host,Proxied_user), KEY Grantor (Grantor) ) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='User proxy privileges'; + +-- Remember for later if proxies_priv table already existed +set @had_proxies_priv_table= @@warning_count != 0; + +-- The following needs to be done both for new installations +-- and for upgrades +CREATE TEMPORARY TABLE tmp_proxies_priv LIKE proxies_priv; +INSERT INTO tmp_proxies_priv VALUES ('localhost', 'root', '', '', TRUE, '', now()); +INSERT INTO proxies_priv SELECT * FROM tmp_proxies_priv WHERE @had_proxies_priv_table=0; +DROP TABLE tmp_proxies_priv; + +-- +-- Tables unique for MariaDB +-- + +CREATE TABLE IF NOT EXISTS table_stats (db_name varchar(64) NOT NULL, table_name varchar(64) NOT NULL, cardinality bigint(21) unsigned DEFAULT NULL, PRIMARY KEY (db_name,table_name) ) engine=Aria transactional=0 CHARACTER SET utf8 COLLATE utf8_bin comment='Statistics on Tables'; + +CREATE TABLE IF NOT EXISTS column_stats (db_name varchar(64) NOT NULL, table_name varchar(64) NOT NULL, column_name varchar(64) NOT NULL, min_value varbinary(255) DEFAULT NULL, max_value varbinary(255) DEFAULT NULL, nulls_ratio decimal(12,4) DEFAULT NULL, avg_length decimal(12,4) DEFAULT NULL, avg_frequency decimal(12,4) DEFAULT NULL, hist_size tinyint unsigned, hist_type enum('SINGLE_PREC_HB','DOUBLE_PREC_HB'), histogram varbinary(255), PRIMARY KEY (db_name,table_name,column_name) ) engine=Aria transactional=0 CHARACTER SET utf8 COLLATE utf8_bin comment='Statistics on Columns'; + +CREATE TABLE IF NOT EXISTS index_stats (db_name varchar(64) NOT NULL, table_name varchar(64) NOT NULL, index_name varchar(64) NOT NULL, prefix_arity int(11) unsigned NOT NULL, avg_frequency decimal(12,4) DEFAULT NULL, PRIMARY KEY (db_name,table_name,index_name,prefix_arity) ) engine=Aria transactional=0 CHARACTER SET utf8 COLLATE utf8_bin comment='Statistics on Indexes'; + +-- Note: This definition must be kept in sync with the one used in +-- build_gtid_pos_create_query() in sql/slave.cc +SET @cmd= "CREATE TABLE IF NOT EXISTS gtid_slave_pos ( + domain_id INT UNSIGNED NOT NULL, + sub_id BIGINT UNSIGNED NOT NULL, + server_id INT UNSIGNED NOT NULL, + seq_no BIGINT UNSIGNED NOT NULL, + PRIMARY KEY (domain_id, sub_id)) CHARSET=latin1 +COMMENT='Replication slave GTID position'"; +SET @str=CONCAT(@cmd, ' ENGINE=', @innodb_or_aria); +PREPARE stmt FROM @str; +EXECUTE stmt; +DROP PREPARE stmt; + +set default_storage_engine=@orig_storage_engine; + +-- +-- Drop some tables not used anymore in MariaDB +-- + +drop table if exists mysql.ndb_binlog_index; +drop table if exists mysql.host; diff --git a/scripts/mysql_system_tables_data.sql b/scripts/mysql_system_tables_data.sql new file mode 100644 index 00000000..ab3dd704 --- /dev/null +++ b/scripts/mysql_system_tables_data.sql @@ -0,0 +1,55 @@ +-- Copyright (c) 2007, 2013, Oracle and/or its affiliates. +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; version 2 of the License. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +-- +-- The initial data for system tables of MySQL Server +-- + +-- When setting up a "cross bootstrap" database (e.g., creating data on a Unix +-- host which will later be included in a Windows zip file), any lines +-- containing "@current_hostname" are filtered out by mysql_install_db. + +-- Get the hostname, if the hostname has any wildcard character like "_" or "%" +-- add escape character in front of wildcard character to convert "_" or "%" to +-- a plain character +SELECT LOWER( REPLACE((SELECT REPLACE(@@hostname,'_','\_')),'%','\%') )INTO @current_hostname; +SELECT '{"access":18446744073709551615}' INTO @all_privileges; +SELECT '{"access":18446744073709551615,"plugin":"mysql_native_password","authentication_string":"invalid","auth_or":[{},{"plugin":"unix_socket"}]}' into @all_with_auth; + + +-- Fill "global_priv" table with default users allowing root access +-- from local machine if "global_priv" table didn't exist before +CREATE TEMPORARY TABLE tmp_user_nopasswd LIKE global_priv; +CREATE TEMPORARY TABLE tmp_user_socket LIKE global_priv; +-- Classic passwordless root account. +INSERT INTO tmp_user_nopasswd VALUES ('localhost','root',@all_privileges); +REPLACE INTO tmp_user_nopasswd SELECT @current_hostname,'root',@all_privileges FROM dual WHERE @current_hostname != 'localhost'; +REPLACE INTO tmp_user_nopasswd VALUES ('127.0.0.1','root',@all_privileges); +REPLACE INTO tmp_user_nopasswd VALUES ('::1','root',@all_privileges); +-- More secure root account using unix socket auth. +INSERT INTO tmp_user_socket VALUES ('localhost', 'root',@all_with_auth); +REPLACE INTO tmp_user_socket VALUES ('localhost',IFNULL(@auth_root_socket, 'root'),@all_with_auth); +IF @auth_root_socket is not null THEN + IF not exists(select 1 from information_schema.plugins where plugin_name='unix_socket') THEN + INSTALL SONAME 'auth_socket'; END IF; END IF; + +INSERT INTO global_priv SELECT * FROM tmp_user_nopasswd WHERE @had_user_table=0 AND @auth_root_socket IS NULL; +INSERT INTO global_priv SELECT * FROM tmp_user_socket WHERE @had_user_table=0 AND @auth_root_socket IS NOT NULL; +DROP TABLE tmp_user_nopasswd, tmp_user_socket; + +CREATE TEMPORARY TABLE tmp_proxies_priv LIKE proxies_priv; +INSERT INTO tmp_proxies_priv SELECT @current_hostname, 'root', '', '', TRUE, '', now() FROM DUAL WHERE @current_hostname != 'localhost'; +INSERT INTO proxies_priv SELECT * FROM tmp_proxies_priv WHERE @had_proxies_priv_table=0; +DROP TABLE tmp_proxies_priv; diff --git a/scripts/mysql_system_tables_fix.sql b/scripts/mysql_system_tables_fix.sql new file mode 100644 index 00000000..2352f801 --- /dev/null +++ b/scripts/mysql_system_tables_fix.sql @@ -0,0 +1,831 @@ +-- Copyright (C) 2003, 2013 Oracle and/or its affiliates. +-- Copyright (C) 2010, 2018 MariaDB Corporation +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; version 2 of the License. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1335 USA + +# This part converts any old privilege tables to privilege tables suitable +# for current version of MySQL + +# You can safely ignore all 'Duplicate column' and 'Unknown column' errors +# because these just mean that your tables are already up to date. +# This script is safe to run even if your tables are already up to date! + +# Warning message(s) produced for a statement can be printed by explicitly +# adding a 'SHOW WARNINGS' after the statement. + +set sql_mode=''; +set default_storage_engine=Aria; +set enforce_storage_engine=NULL; +set alter_algorithm=DEFAULT; + +set @have_innodb= (select count(engine) from information_schema.engines where engine='INNODB' and support != 'NO'); + +ALTER TABLE user add File_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL; + +# Detect whether or not we had the Grant_priv column +SET @hadGrantPriv:=0; +SELECT @hadGrantPriv:=1 FROM user WHERE Grant_priv IS NOT NULL; + +ALTER TABLE user add Grant_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + add References_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + add Index_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + add Alter_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL; +ALTER TABLE db add Grant_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + add References_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + add Index_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + add Alter_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL; + +# Fix privileges for old tables +UPDATE user SET Grant_priv=File_priv,References_priv=Create_priv,Index_priv=Create_priv,Alter_priv=Create_priv WHERE @hadGrantPriv = 0; +UPDATE db SET References_priv=Create_priv,Index_priv=Create_priv,Alter_priv=Create_priv WHERE @hadGrantPriv = 0; +# +# The second alter changes ssl_type to new 4.0.2 format +# Adding columns needed by GRANT .. REQUIRE (openssl) + +ALTER TABLE user +ADD ssl_type enum('','ANY','X509', 'SPECIFIED') DEFAULT '' NOT NULL, +ADD ssl_cipher BLOB NOT NULL, +ADD x509_issuer BLOB NOT NULL, +ADD x509_subject BLOB NOT NULL; +ALTER TABLE user MODIFY ssl_type enum('','ANY','X509', 'SPECIFIED') DEFAULT '' NOT NULL; + +# +# tables_priv +# +ALTER TABLE tables_priv + ADD KEY Grantor (Grantor); + +ALTER TABLE tables_priv + MODIFY Host char(60) NOT NULL default '', + MODIFY Db char(64) NOT NULL default '', + MODIFY User char(80) binary NOT NULL default '', + MODIFY Table_name char(64) NOT NULL default '', + MODIFY Grantor char(141) COLLATE utf8_bin NOT NULL default '', + ENGINE=Aria, + CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; + +ALTER TABLE tables_priv + MODIFY Column_priv set('Select','Insert','Update','References') + COLLATE utf8_general_ci DEFAULT '' NOT NULL, + MODIFY Table_priv set('Select','Insert','Update','Delete','Create', + 'Drop','Grant','References','Index','Alter', + 'Create View','Show view','Trigger','Delete versioning rows') + COLLATE utf8_general_ci DEFAULT '' NOT NULL, + COMMENT='Table privileges'; + +# +# columns_priv +# +# +# Name change of Type -> Column_priv from MySQL 3.22.12 +# +ALTER TABLE columns_priv + CHANGE Type Column_priv set('Select','Insert','Update','References') + COLLATE utf8_general_ci DEFAULT '' NOT NULL; + +ALTER TABLE columns_priv + MODIFY Host char(60) NOT NULL default '', + MODIFY Db char(64) NOT NULL default '', + MODIFY User char(80) binary NOT NULL default '', + MODIFY Table_name char(64) NOT NULL default '', + MODIFY Column_name char(64) NOT NULL default '', + ENGINE=Aria, + CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin, + COMMENT='Column privileges'; + +ALTER TABLE columns_priv + MODIFY Column_priv set('Select','Insert','Update','References') + COLLATE utf8_general_ci DEFAULT '' NOT NULL; + +# +# Add the new 'type' column to the func table. +# + +ALTER TABLE func add type enum ('function','aggregate') COLLATE utf8_general_ci NOT NULL; + +# +# Change the user,db and host tables to current format +# + +# Detect whether we had Show_db_priv +SET @hadShowDbPriv:=0; +SELECT @hadShowDbPriv:=1 FROM user WHERE Show_db_priv IS NOT NULL; + +ALTER TABLE user +ADD Show_db_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Alter_priv, +ADD Super_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Show_db_priv, +ADD Create_tmp_table_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Super_priv, +ADD Lock_tables_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_tmp_table_priv, +ADD Execute_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Lock_tables_priv, +ADD Repl_slave_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Execute_priv, +ADD Repl_client_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Repl_slave_priv; + +# Convert privileges so that users have similar privileges as before + +UPDATE user SET Show_db_priv= Select_priv, Super_priv=Process_priv, Execute_priv=Process_priv, Create_tmp_table_priv='Y', Lock_tables_priv='Y', Repl_slave_priv=file_priv, Repl_client_priv=File_priv where user<>"" AND @hadShowDbPriv = 0; + + +# Add fields that can be used to limit number of questions and connections +# for some users. + +ALTER TABLE user +ADD max_questions int(11) NOT NULL DEFAULT 0 AFTER x509_subject, +ADD max_updates int(11) unsigned NOT NULL DEFAULT 0 AFTER max_questions, +ADD max_connections int(11) unsigned NOT NULL DEFAULT 0 AFTER max_updates; + + +# +# Add Create_tmp_table_priv and Lock_tables_priv to db and host +# + +ALTER TABLE db +ADD Create_tmp_table_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, +ADD Lock_tables_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL; + +alter table user change max_questions max_questions int(11) unsigned DEFAULT 0 NOT NULL; + + +alter table db comment='Database privileges'; +alter table user comment='Users and global privileges'; +alter table func comment='User defined functions'; + +# Convert all tables to UTF-8 with binary collation +# and reset all char columns to correct width +ALTER TABLE user + MODIFY Host char(60) NOT NULL default '', + MODIFY User char(80) binary NOT NULL default '', + ENGINE=Aria, CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; + +# In MySQL 5.7.6 the Password column is removed. Recreate it to preserve the number +# of columns MariaDB expects in the user table. +ALTER TABLE user + ADD Password char(41) character set latin1 collate latin1_bin NOT NULL default '' AFTER User; + +# In MySQL the Unix socket authentication plugin has a different name. Thus the +# references to it need to be renamed in the user table. Thanks to the WHERE +# clauses this applies only to MySQL->MariaDB upgrades and nothing else. +UPDATE user + SET plugin='unix_socket' WHERE plugin='auth_socket'; +DELETE FROM plugin + WHERE name='auth_socket'; + +ALTER TABLE user + MODIFY Password char(41) character set latin1 collate latin1_bin NOT NULL default '', + MODIFY Select_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Insert_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Update_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Delete_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Create_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Drop_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Reload_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Shutdown_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Process_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY File_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Grant_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY References_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Index_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Alter_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Show_db_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Super_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Create_tmp_table_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Lock_tables_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Execute_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Repl_slave_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Repl_client_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY ssl_type enum('','ANY','X509', 'SPECIFIED') COLLATE utf8_general_ci DEFAULT '' NOT NULL; + +ALTER TABLE db + MODIFY Host char(60) NOT NULL default '', + MODIFY Db char(64) NOT NULL default '', + MODIFY User char(80) binary NOT NULL default '', + ENGINE=Aria, CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; +ALTER TABLE db + MODIFY Select_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Insert_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Update_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Delete_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Create_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Drop_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Grant_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY References_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Index_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Alter_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Create_tmp_table_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL, + MODIFY Lock_tables_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL; + + +ALTER TABLE func + ENGINE=Aria, CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; +ALTER TABLE func + MODIFY type enum ('function','aggregate') COLLATE utf8_general_ci NOT NULL; + +# +# Modify log tables. +# + +SET @old_log_state = @@global.general_log; +SET GLOBAL general_log = 'OFF'; +ALTER TABLE general_log + MODIFY event_time TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + MODIFY user_host MEDIUMTEXT NOT NULL, + MODIFY thread_id INTEGER NOT NULL, + MODIFY server_id INTEGER UNSIGNED NOT NULL, + MODIFY command_type VARCHAR(64) NOT NULL, + MODIFY argument MEDIUMTEXT NOT NULL, + MODIFY thread_id BIGINT(21) UNSIGNED NOT NULL; +SET GLOBAL general_log = @old_log_state; + +SET @old_log_state = @@global.slow_query_log; +SET GLOBAL slow_query_log = 'OFF'; +ALTER TABLE slow_log + ADD COLUMN thread_id BIGINT(21) UNSIGNED NOT NULL AFTER sql_text; +ALTER TABLE slow_log + ADD COLUMN rows_affected INTEGER NOT NULL AFTER thread_id; +ALTER TABLE slow_log + MODIFY start_time TIMESTAMP(6) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + MODIFY user_host MEDIUMTEXT NOT NULL, + MODIFY query_time TIME(6) NOT NULL, + MODIFY lock_time TIME(6) NOT NULL, + MODIFY rows_sent INTEGER NOT NULL, + MODIFY rows_examined INTEGER NOT NULL, + MODIFY db VARCHAR(512) NOT NULL, + MODIFY last_insert_id INTEGER NOT NULL, + MODIFY insert_id INTEGER NOT NULL, + MODIFY server_id INTEGER UNSIGNED NOT NULL, + MODIFY sql_text MEDIUMTEXT NOT NULL, + MODIFY thread_id BIGINT(21) UNSIGNED NOT NULL; +SET GLOBAL slow_query_log = @old_log_state; + +ALTER TABLE plugin + MODIFY name varchar(64) COLLATE utf8_general_ci NOT NULL DEFAULT '', + MODIFY dl varchar(128) COLLATE utf8_general_ci NOT NULL DEFAULT '', + CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; + +# +# Detect whether we had Create_view_priv +# +SET @hadCreateViewPriv:=0; +SELECT @hadCreateViewPriv:=1 FROM user WHERE Create_view_priv IS NOT NULL; + +# +# Create VIEWs privileges (v5.0) +# +ALTER TABLE db ADD Create_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Lock_tables_priv; +ALTER TABLE db MODIFY Create_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Lock_tables_priv; + + +ALTER TABLE user ADD Create_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Repl_client_priv; +ALTER TABLE user MODIFY Create_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Repl_client_priv; + +# +# Show VIEWs privileges (v5.0) +# +ALTER TABLE db ADD Show_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_view_priv; +ALTER TABLE db MODIFY Show_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_view_priv; + +ALTER TABLE user ADD Show_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_view_priv; +ALTER TABLE user MODIFY Show_view_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_view_priv; + +# +# Assign create/show view privileges to people who have create provileges +# +UPDATE user SET Create_view_priv=Create_priv, Show_view_priv=Create_priv where user<>"" AND @hadCreateViewPriv = 0; + +# +# +# +SET @hadCreateRoutinePriv:=0; +SELECT @hadCreateRoutinePriv:=1 FROM user WHERE Create_routine_priv IS NOT NULL; + +# +# Create PROCEDUREs privileges (v5.0) +# +ALTER TABLE db ADD Create_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Show_view_priv; +ALTER TABLE db MODIFY Create_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Show_view_priv; + +ALTER TABLE user ADD Create_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Show_view_priv; +ALTER TABLE user MODIFY Create_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Show_view_priv; + +# +# Alter PROCEDUREs privileges (v5.0) +# +ALTER TABLE db ADD Alter_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_routine_priv; +ALTER TABLE db MODIFY Alter_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_routine_priv; + +ALTER TABLE user ADD Alter_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_routine_priv; +ALTER TABLE user MODIFY Alter_routine_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Create_routine_priv; + +ALTER TABLE db ADD Execute_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Alter_routine_priv; +ALTER TABLE db MODIFY Execute_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Alter_routine_priv; + +# +# Assign create/alter routine privileges to people who have create privileges +# +UPDATE user SET Create_routine_priv=Create_priv, Alter_routine_priv=Alter_priv where user<>"" AND @hadCreateRoutinePriv = 0; +UPDATE db SET Create_routine_priv=Create_priv, Alter_routine_priv=Alter_priv, Execute_priv=Select_priv where user<>"" AND @hadCreateRoutinePriv = 0; + +# +# Add max_user_connections resource limit +# this is signed in MariaDB so that if one sets it's to -1 then the user +# can't connect anymore. +# +ALTER TABLE user ADD max_user_connections int(11) DEFAULT '0' NOT NULL AFTER max_connections; +ALTER TABLE user MODIFY max_user_connections int(11) DEFAULT '0' NOT NULL AFTER max_connections; + +# +# user.Create_user_priv +# + +SET @hadCreateUserPriv:=0; +SELECT @hadCreateUserPriv:=1 FROM user WHERE Create_user_priv IS NOT NULL; + +ALTER TABLE user ADD Create_user_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Alter_routine_priv; +ALTER TABLE user MODIFY Create_user_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Alter_routine_priv; +UPDATE user LEFT JOIN db USING (Host,User) SET Create_user_priv='Y' + WHERE @hadCreateUserPriv = 0 AND + (user.Grant_priv = 'Y' OR db.Grant_priv = 'Y'); + +# +# procs_priv +# + +ALTER TABLE procs_priv + ENGINE=Aria, + CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin; + +ALTER TABLE procs_priv + MODIFY Proc_priv set('Execute','Alter Routine','Grant') + COLLATE utf8_general_ci DEFAULT '' NOT NULL; + +ALTER IGNORE TABLE procs_priv + MODIFY Routine_name char(64) + COLLATE utf8_general_ci DEFAULT '' NOT NULL; + +ALTER TABLE procs_priv + ADD Routine_type enum('FUNCTION','PROCEDURE') + COLLATE utf8_general_ci NOT NULL AFTER Routine_name; + +ALTER TABLE procs_priv + MODIFY Timestamp timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER Proc_priv; + +# +# proc +# + +# Correct the name fields to not binary, and expand sql_data_access +ALTER TABLE proc MODIFY name char(64) DEFAULT '' NOT NULL, + MODIFY specific_name char(64) DEFAULT '' NOT NULL, + MODIFY sql_data_access + enum('CONTAINS_SQL', + 'NO_SQL', + 'READS_SQL_DATA', + 'MODIFIES_SQL_DATA' + ) DEFAULT 'CONTAINS_SQL' NOT NULL, + MODIFY body longblob NOT NULL, + MODIFY returns longblob NOT NULL, + MODIFY sql_mode + set('REAL_AS_FLOAT', + 'PIPES_AS_CONCAT', + 'ANSI_QUOTES', + 'IGNORE_SPACE', + 'IGNORE_BAD_TABLE_OPTIONS', + 'ONLY_FULL_GROUP_BY', + 'NO_UNSIGNED_SUBTRACTION', + 'NO_DIR_IN_CREATE', + 'POSTGRESQL', + 'ORACLE', + 'MSSQL', + 'DB2', + 'MAXDB', + 'NO_KEY_OPTIONS', + 'NO_TABLE_OPTIONS', + 'NO_FIELD_OPTIONS', + 'MYSQL323', + 'MYSQL40', + 'ANSI', + 'NO_AUTO_VALUE_ON_ZERO', + 'NO_BACKSLASH_ESCAPES', + 'STRICT_TRANS_TABLES', + 'STRICT_ALL_TABLES', + 'NO_ZERO_IN_DATE', + 'NO_ZERO_DATE', + 'INVALID_DATES', + 'ERROR_FOR_DIVISION_BY_ZERO', + 'TRADITIONAL', + 'NO_AUTO_CREATE_USER', + 'HIGH_NOT_PRECEDENCE', + 'NO_ENGINE_SUBSTITUTION', + 'PAD_CHAR_TO_FULL_LENGTH', + 'EMPTY_STRING_IS_NULL', + 'SIMULTANEOUS_ASSIGNMENT', + 'TIME_ROUND_FRACTIONAL' + ) DEFAULT '' NOT NULL, + DEFAULT CHARACTER SET utf8; + +# Correct the character set and collation +# Reset some fields after the conversion +ALTER TABLE proc CONVERT TO CHARACTER SET utf8, + MODIFY db char(64) binary DEFAULT '' NOT NULL, + MODIFY definer char(141) binary DEFAULT '' NOT NULL, + MODIFY comment text binary NOT NULL; + +ALTER TABLE proc ADD character_set_client + char(32) collate utf8_bin DEFAULT NULL + AFTER comment; +ALTER TABLE proc MODIFY character_set_client + char(32) collate utf8_bin DEFAULT NULL; + +ALTER TABLE proc MODIFY type enum('FUNCTION', + 'PROCEDURE', + 'PACKAGE', + 'PACKAGE BODY') NOT NULL; + +ALTER TABLE procs_priv MODIFY Routine_type enum('FUNCTION', + 'PROCEDURE', + 'PACKAGE', + 'PACKAGE BODY') NOT NULL; + +SELECT CASE WHEN COUNT(*) > 0 THEN +CONCAT ("WARNING: NULL values of the 'character_set_client' column ('mysql.proc' table) have been updated with a default value (", @@character_set_client, "). Please verify if necessary.") +ELSE NULL +END +AS value FROM proc WHERE character_set_client IS NULL; + +UPDATE proc SET character_set_client = @@character_set_client + WHERE character_set_client IS NULL; + +ALTER TABLE proc ADD collation_connection + char(32) collate utf8_bin DEFAULT NULL + AFTER character_set_client; +ALTER TABLE proc MODIFY collation_connection + char(32) collate utf8_bin DEFAULT NULL; + +SELECT CASE WHEN COUNT(*) > 0 THEN +CONCAT ("WARNING: NULL values of the 'collation_connection' column ('mysql.proc' table) have been updated with a default value (", @@collation_connection, "). Please verify if necessary.") +ELSE NULL +END +AS value FROM proc WHERE collation_connection IS NULL; + +UPDATE proc SET collation_connection = @@collation_connection + WHERE collation_connection IS NULL; + +ALTER TABLE proc ADD db_collation + char(32) collate utf8_bin DEFAULT NULL + AFTER collation_connection; +ALTER TABLE proc MODIFY db_collation + char(32) collate utf8_bin DEFAULT NULL; + +SELECT CASE WHEN COUNT(*) > 0 THEN +CONCAT ("WARNING: NULL values of the 'db_collation' column ('mysql.proc' table) have been updated with default values. Please verify if necessary.") +ELSE NULL +END +AS value FROM proc WHERE db_collation IS NULL; + +UPDATE proc AS p SET db_collation = + ( SELECT DEFAULT_COLLATION_NAME + FROM INFORMATION_SCHEMA.SCHEMATA + WHERE SCHEMA_NAME = p.db) + WHERE db_collation IS NULL; + +ALTER TABLE proc ADD body_utf8 longblob DEFAULT NULL + AFTER db_collation; +ALTER TABLE proc MODIFY body_utf8 longblob DEFAULT NULL; + +# Change comment from char(64) to text +ALTER TABLE proc MODIFY comment + text collate utf8_bin NOT NULL; + +# MDEV-7773: Stored Aggregate Functions +ALTER TABLE proc ADD aggregate enum('NONE', 'GROUP') DEFAULT 'NONE' NOT NULL + AFTER body_utf8; + +# +# EVENT privilege +# +SET @hadEventPriv := 0; +SELECT @hadEventPriv :=1 FROM user WHERE Event_priv IS NOT NULL; + +ALTER TABLE user ADD Event_priv enum('N','Y') character set utf8 DEFAULT 'N' NOT NULL AFTER Create_user_priv; +ALTER TABLE user MODIFY Event_priv enum('N','Y') character set utf8 DEFAULT 'N' NOT NULL AFTER Create_user_priv; + +UPDATE user SET Event_priv=Super_priv WHERE @hadEventPriv = 0; + +ALTER TABLE db ADD Event_priv enum('N','Y') character set utf8 DEFAULT 'N' NOT NULL; +ALTER TABLE db MODIFY Event_priv enum('N','Y') character set utf8 DEFAULT 'N' NOT NULL; + +# +# EVENT table +# +ALTER TABLE event DROP PRIMARY KEY, ADD PRIMARY KEY(db, name); +# Add sql_mode column just in case. +ALTER TABLE event ADD sql_mode set ('IGNORE_BAD_TABLE_OPTIONS') AFTER on_completion; +# Update list of sql_mode values. +ALTER TABLE event MODIFY sql_mode + set('REAL_AS_FLOAT', + 'PIPES_AS_CONCAT', + 'ANSI_QUOTES', + 'IGNORE_SPACE', + 'IGNORE_BAD_TABLE_OPTIONS', + 'ONLY_FULL_GROUP_BY', + 'NO_UNSIGNED_SUBTRACTION', + 'NO_DIR_IN_CREATE', + 'POSTGRESQL', + 'ORACLE', + 'MSSQL', + 'DB2', + 'MAXDB', + 'NO_KEY_OPTIONS', + 'NO_TABLE_OPTIONS', + 'NO_FIELD_OPTIONS', + 'MYSQL323', + 'MYSQL40', + 'ANSI', + 'NO_AUTO_VALUE_ON_ZERO', + 'NO_BACKSLASH_ESCAPES', + 'STRICT_TRANS_TABLES', + 'STRICT_ALL_TABLES', + 'NO_ZERO_IN_DATE', + 'NO_ZERO_DATE', + 'INVALID_DATES', + 'ERROR_FOR_DIVISION_BY_ZERO', + 'TRADITIONAL', + 'NO_AUTO_CREATE_USER', + 'HIGH_NOT_PRECEDENCE', + 'NO_ENGINE_SUBSTITUTION', + 'PAD_CHAR_TO_FULL_LENGTH', + 'EMPTY_STRING_IS_NULL', + 'SIMULTANEOUS_ASSIGNMENT', + 'TIME_ROUND_FRACTIONAL' + ) DEFAULT '' NOT NULL AFTER on_completion; +ALTER TABLE event MODIFY name char(64) CHARACTER SET utf8 NOT NULL default ''; + +ALTER TABLE event ADD COLUMN originator INT UNSIGNED NOT NULL AFTER comment; +ALTER TABLE event MODIFY COLUMN originator INT UNSIGNED NOT NULL; + +ALTER TABLE event MODIFY COLUMN status ENUM('ENABLED','DISABLED','SLAVESIDE_DISABLED') NOT NULL default 'ENABLED'; + +ALTER TABLE event ADD COLUMN time_zone char(64) CHARACTER SET latin1 + NOT NULL DEFAULT 'SYSTEM' AFTER originator; + +ALTER TABLE event ADD character_set_client + char(32) collate utf8_bin DEFAULT NULL + AFTER time_zone; +ALTER TABLE event MODIFY character_set_client + char(32) collate utf8_bin DEFAULT NULL; + +ALTER TABLE event ADD collation_connection + char(32) collate utf8_bin DEFAULT NULL + AFTER character_set_client; +ALTER TABLE event MODIFY collation_connection + char(32) collate utf8_bin DEFAULT NULL; + +ALTER TABLE event ADD db_collation + char(32) collate utf8_bin DEFAULT NULL + AFTER collation_connection; +ALTER TABLE event MODIFY db_collation + char(32) collate utf8_bin DEFAULT NULL; + +ALTER TABLE event ADD body_utf8 longblob DEFAULT NULL + AFTER db_collation; +ALTER TABLE event MODIFY body_utf8 longblob DEFAULT NULL; + +# Enable event scheduler if the event table was not up to date before. +set global event_scheduler=original; + +# +# TRIGGER privilege +# + +SET @hadTriggerPriv := 0; +SELECT @hadTriggerPriv :=1 FROM user WHERE Trigger_priv IS NOT NULL; + +ALTER TABLE user ADD Trigger_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Event_priv; +ALTER TABLE user MODIFY Trigger_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Event_priv; + +ALTER TABLE db ADD Trigger_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL; +ALTER TABLE db MODIFY Trigger_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL; + +UPDATE user SET Trigger_priv=Super_priv WHERE @hadTriggerPriv = 0; + +# +# user.Create_tablespace_priv +# + +SET @hadCreateTablespacePriv := 0; +SELECT @hadCreateTablespacePriv :=1 FROM user WHERE Create_tablespace_priv IS NOT NULL; + +ALTER TABLE user ADD Create_tablespace_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Trigger_priv; +ALTER TABLE user MODIFY Create_tablespace_priv enum('N','Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER Trigger_priv; + +UPDATE user SET Create_tablespace_priv = Super_priv WHERE @hadCreateTablespacePriv = 0; + +# +# System versioning +# + +ALTER TABLE user change Truncate_versioning_priv Delete_history_priv enum('N','Y') COLLATE utf8_general_ci NOT NULL DEFAULT 'N'; +ALTER TABLE db change Truncate_versioning_priv Delete_history_priv enum('N','Y') COLLATE utf8_general_ci NOT NULL DEFAULT 'N'; + +SET @had_user_delete_history_priv := 0; +SELECT @had_user_delete_history_priv :=1 FROM user WHERE Delete_history_priv IS NOT NULL; + +ALTER TABLE user add Delete_history_priv enum('N','Y') COLLATE utf8_general_ci NOT NULL DEFAULT 'N' after Create_tablespace_priv; +ALTER TABLE user modify Delete_history_priv enum('N','Y') COLLATE utf8_general_ci NOT NULL DEFAULT 'N'; +ALTER TABLE db add Delete_history_priv enum('N','Y') COLLATE utf8_general_ci NOT NULL DEFAULT 'N' after Trigger_priv; +ALTER TABLE db modify Delete_history_priv enum('N','Y') COLLATE utf8_general_ci NOT NULL DEFAULT 'N'; + +UPDATE user SET Delete_history_priv = Super_priv WHERE @had_user_delete_history_priv = 0; + +ALTER TABLE user ADD plugin char(64) CHARACTER SET latin1 DEFAULT '' NOT NULL AFTER max_user_connections, + ADD authentication_string TEXT NOT NULL AFTER plugin; +ALTER TABLE user CHANGE auth_string authentication_string TEXT NOT NULL; + +ALTER TABLE user ADD password_expired ENUM('N', 'Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER authentication_string; +ALTER TABLE user ADD password_last_changed timestamp DEFAULT CURRENT_TIMESTAMP NOT NULL after password_expired; +ALTER TABLE user ADD password_lifetime smallint unsigned DEFAULT NULL after password_last_changed; +ALTER TABLE user ADD account_locked enum('N', 'Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL after password_lifetime; +ALTER TABLE user ADD is_role enum('N', 'Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER account_locked; +ALTER TABLE user ADD default_role char(80) binary DEFAULT '' NOT NULL AFTER is_role; +ALTER TABLE user ADD max_statement_time decimal(12,6) DEFAULT 0 NOT NULL AFTER default_role; + +-- Somewhere above, we ran ALTER TABLE user .... CONVERT TO CHARACTER SET utf8 COLLATE utf8_bin. +-- we want password_expired column to have collation utf8_general_ci. +-- Order columns correctly that were not ordered until MDEV-23201 (ff8ffef3e1915d7a9caa07d9461cd8d47c4baf98) + +ALTER TABLE user MODIFY plugin char(64) CHARACTER SET latin1 DEFAULT '' NOT NULL AFTER max_user_connections, + MODIFY authentication_string TEXT NOT NULL AFTER plugin, + MODIFY password_expired ENUM('N', 'Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER authentication_string, + MODIFY is_role enum('N', 'Y') COLLATE utf8_general_ci DEFAULT 'N' NOT NULL AFTER password_expired, + MODIFY default_role char(80) binary DEFAULT '' NOT NULL AFTER is_role, + MODIFY max_statement_time decimal(12,6) DEFAULT 0 NOT NULL AFTER default_role, +-- MDEV-24122 formerly mysql5.7 users may have the following columns password_last_changed, +-- password_lifetime and account_locked. Ensure they are beyond the end of the user columns +-- used by MariaDB. MariaDB-10.4 will use these in the creation of mysql.global_priv. +-- password_last_changed has a DEFAULT/ON UPDATE of CURRENT_TIMESTAMP to keep track of +-- time until 10.4 added. + MODIFY IF EXISTS password_last_changed timestamp DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER max_statement_time, + MODIFY IF EXISTS password_lifetime smallint unsigned DEFAULT NULL AFTER password_last_changed, + MODIFY IF EXISTS account_locked enum('N', 'Y') CHARACTER SET utf8 DEFAULT 'N' NOT NULL after password_lifetime; + +-- Checking for any duplicate hostname and username combination are exists. +-- If exits we will throw error. +DELIMITER // +BEGIN NOT ATOMIC + SET @duplicate_hosts=(SELECT count(*) FROM mysql.user GROUP BY user, lower(host) HAVING count(*) > 1 LIMIT 1); + IF @duplicate_hosts > 1 THEN + SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Multiple accounts exist for @user_name, @host_name that differ only in Host lettercase; remove all except one of them'; + END IF; +END // +DELIMITER ; +-- Get warnings (if any) +SHOW WARNINGS; + +# Convering the host name to lower case for existing users +UPDATE user SET host=LOWER( host ) WHERE LOWER( host ) <> host; + +DELIMITER // +if @have_innodb then + # fix bad data when upgrading from unfixed InnoDB (MDEV-13360) + delete from innodb_index_stats where length(table_name) > 64; + delete from innodb_table_stats where length(table_name) > 64; + + # update table_name and timestamp fields in the innodb stat tables + alter table innodb_index_stats modify last_update timestamp not null default current_timestamp on update current_timestamp, modify table_name varchar(199); + alter table innodb_table_stats modify last_update timestamp not null default current_timestamp on update current_timestamp, modify table_name varchar(199); + + alter table innodb_index_stats drop foreign key if exists innodb_index_stats_ibfk_1; +end if // +DELIMITER ; + +# MDEV-4332 longer user names +alter table user modify User char(80) binary not null default ''; +alter table db modify User char(80) binary not null default ''; +alter table tables_priv modify User char(80) binary not null default ''; +alter table columns_priv modify User char(80) binary not null default ''; +alter table procs_priv modify User char(80) binary not null default ''; +alter table proc modify definer char(141) collate utf8_bin not null default ''; +alter table event modify definer char(141) collate utf8_bin not null default ''; +alter table proxies_priv modify User char(80) COLLATE utf8_bin not null default ''; +alter table proxies_priv modify Proxied_user char(80) COLLATE utf8_bin not null default ''; +alter table proxies_priv modify Grantor char(141) COLLATE utf8_bin not null default ''; +alter table servers modify Username char(80) not null default ''; +alter table procs_priv modify Grantor char(141) COLLATE utf8_bin not null default ''; +alter table tables_priv modify Grantor char(141) COLLATE utf8_bin not null default ''; + +# Activate the new, possible modified privilege tables +# This should not be needed, but gives us some extra testing that the above +# changes was correct + +flush privileges; + +-- +-- Upgrade help tables +-- + +ALTER TABLE help_category MODIFY url TEXT NOT NULL; +ALTER TABLE help_topic MODIFY url TEXT NOT NULL; + +# MDEV-7383 - varbinary on mix/max of column_stats +alter table column_stats modify min_value varbinary(255) DEFAULT NULL, modify max_value varbinary(255) DEFAULT NULL; + +-- +-- Ensure that all tables are of type Aria and transactional +-- + +ALTER TABLE user ENGINE=Aria transactional=1; +ALTER TABLE db ENGINE=Aria transactional=1; +ALTER TABLE func ENGINE=Aria transactional=1; +ALTER TABLE procs_priv ENGINE=Aria transactional=1; +ALTER TABLE tables_priv ENGINE=Aria transactional=1; +ALTER TABLE columns_priv ENGINE=Aria transactional=1; +ALTER TABLE roles_mapping ENGINE=Aria transactional=1; +ALTER TABLE plugin ENGINE=Aria transactional=1; +ALTER TABLE servers ENGINE=Aria transactional=1; +ALTER TABLE time_zone_name ENGINE=Aria transactional=1; +ALTER TABLE time_zone ENGINE=Aria transactional=1; +ALTER TABLE time_zone_transition ENGINE=Aria transactional=1; +ALTER TABLE time_zone_transition_type ENGINE=Aria transactional=1; +ALTER TABLE time_zone_leap_second ENGINE=Aria transactional=1; +ALTER TABLE proc ENGINE=Aria transactional=1; +ALTER TABLE event ENGINE=Aria transactional=1; +ALTER TABLE proxies_priv ENGINE=Aria transactional=1; + +-- The following tables doesn't have to be transactional +ALTER TABLE help_topic ENGINE=Aria transactional=0; +ALTER TABLE help_category ENGINE=Aria transactional=0; +ALTER TABLE help_relation ENGINE=Aria transactional=0; +ALTER TABLE help_keyword ENGINE=Aria transactional=0; +ALTER TABLE table_stats ENGINE=Aria transactional=0; +ALTER TABLE column_stats ENGINE=Aria transactional=0; +ALTER TABLE index_stats ENGINE=Aria transactional=0; + +DELIMITER // +IF 'BASE TABLE' = (select table_type from information_schema.tables where table_schema=database() and table_name='user') THEN + CREATE TABLE IF NOT EXISTS global_priv (Host char(60) binary DEFAULT '', User char(80) binary DEFAULT '', Priv JSON NOT NULL DEFAULT '{}' CHECK(JSON_VALID(Priv)), PRIMARY KEY Host (Host,User)) engine=Aria transactional=1 CHARACTER SET utf8 COLLATE utf8_bin comment='Users and global privileges' + SELECT Host, User, JSON_COMPACT(JSON_OBJECT('access', + 1*('Y'=Select_priv)+ + 2*('Y'=Insert_priv)+ + 4*('Y'=Update_priv)+ + 8*('Y'=Delete_priv)+ + 16*('Y'=Create_priv)+ + 32*('Y'=Drop_priv)+ + 64*('Y'=Reload_priv)+ + 128*('Y'=Shutdown_priv)+ + 256*('Y'=Process_priv)+ + 512*('Y'=File_priv)+ + 1024*('Y'=Grant_priv)+ + 2048*('Y'=References_priv)+ + 4096*('Y'=Index_priv)+ + 8192*('Y'=Alter_priv)+ + 16384*('Y'=Show_db_priv)+ + 32768*('Y'=Super_priv)+ + 65536*('Y'=Create_tmp_table_priv)+ + 131072*('Y'=Lock_tables_priv)+ + 262144*('Y'=Execute_priv)+ + 524288*('Y'=Repl_slave_priv)+ + 1048576*('Y'=Repl_client_priv)+ + 2097152*('Y'=Create_view_priv)+ + 4194304*('Y'=Show_view_priv)+ + 8388608*('Y'=Create_routine_priv)+ + 16777216*('Y'=Alter_routine_priv)+ + 33554432*('Y'=Create_user_priv)+ + 67108864*('Y'=Event_priv)+ + 134217728*('Y'=Trigger_priv)+ + 268435456*('Y'=Create_tablespace_priv)+ + 536870912*('Y'=Delete_history_priv), + 'ssl_type', ssl_type-1, + 'ssl_cipher', ssl_cipher, + 'x509_issuer', x509_issuer, + 'x509_subject', x509_subject, + 'max_questions', max_questions, + 'max_updates', max_updates, + 'max_connections', max_connections, + 'max_user_connections', max_user_connections, + 'max_statement_time', max_statement_time, + 'plugin', if(plugin>'',plugin,if(length(password)=16,'mysql_old_password','mysql_native_password')), + 'authentication_string', if(plugin>'' and authentication_string>'',authentication_string,password), + 'password_last_changed', if(password_expired='Y', 0, UNIX_TIMESTAMP(password_last_changed)), + 'password_lifetime', ifnull(password_lifetime, -1), + 'account_locked', 'Y'=account_locked, + 'default_role', default_role, + 'is_role', 'Y'=is_role)) as Priv + FROM user; + DROP TABLE user; +END IF// + +IF 1 = (SELECT count(*) FROM information_schema.VIEWS WHERE TABLE_CATALOG = 'def' and TABLE_SCHEMA = 'mysql' and TABLE_NAME='user' and (DEFINER = 'root@localhost' or (DEFINER = 'mariadb.sys@localhost' and VIEW_DEFINITION LIKE "%'N' AS `password_expired`%"))) THEN + DROP VIEW IF EXISTS mysql.user; +END IF// + +DELIMITER ; diff --git a/scripts/mysql_test_data_timezone.sql b/scripts/mysql_test_data_timezone.sql new file mode 100644 index 00000000..b4902c35 --- /dev/null +++ b/scripts/mysql_test_data_timezone.sql @@ -0,0 +1,21 @@ +-- Copyright (C) 2007 MySQL AB +-- Use is subject to license terms +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; version 2 of the License. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335 USA + +INSERT INTO time_zone_name (Name, Time_Zone_id) VALUES ('MET', 1), ('UTC', 2), ('Universal', 2), ('Europe/Moscow',3), ('leap/Europe/Moscow',4), ('Japan', 5); +INSERT INTO time_zone (Time_zone_id, Use_leap_seconds) VALUES (1,'N'), (2,'N'), (3,'N'), (4,'Y'), (5,'N'); +INSERT INTO time_zone_transition (Time_zone_id, Transition_time, Transition_type_id) VALUES (1, -1693706400, 0) ,(1, -1680483600, 1) ,(1, -1663455600, 2) ,(1, -1650150000, 3) ,(1, -1632006000, 2) ,(1, -1618700400, 3) ,(1, -938905200, 2) ,(1, -857257200, 3) ,(1, -844556400, 2) ,(1, -828226800, 3) ,(1, -812502000, 2) ,(1, -796777200, 3) ,(1, 228877200, 2) ,(1, 243997200, 3) ,(1, 260326800, 2) ,(1, 276051600, 3) ,(1, 291776400, 2) ,(1, 307501200, 3) ,(1, 323830800, 2) ,(1, 338950800, 3) ,(1, 354675600, 2) ,(1, 370400400, 3) ,(1, 386125200, 2) ,(1, 401850000, 3) ,(1, 417574800, 2) ,(1, 433299600, 3) ,(1, 449024400, 2) ,(1, 465354000, 3) ,(1, 481078800, 2) ,(1, 496803600, 3) ,(1, 512528400, 2) ,(1, 528253200, 3) ,(1, 543978000, 2) ,(1, 559702800, 3) ,(1, 575427600, 2) ,(1, 591152400, 3) ,(1, 606877200, 2) ,(1, 622602000, 3) ,(1, 638326800, 2) ,(1, 654656400, 3) ,(1, 670381200, 2) ,(1, 686106000, 3) ,(1, 701830800, 2) ,(1, 717555600, 3) ,(1, 733280400, 2) ,(1, 749005200, 3) ,(1, 764730000, 2) ,(1, 780454800, 3) ,(1, 796179600, 2) ,(1, 811904400, 3) ,(1, 828234000, 2) ,(1, 846378000, 3) ,(1, 859683600, 2) ,(1, 877827600, 3) ,(1, 891133200, 2) ,(1, 909277200, 3) ,(1, 922582800, 2) ,(1, 941331600, 3) ,(1, 954032400, 2) ,(1, 972781200, 3) ,(1, 985482000, 2) ,(1, 1004230800, 3) ,(1, 1017536400, 2) ,(1, 1035680400, 3) ,(1, 1048986000, 2) ,(1, 1067130000, 3) ,(1, 1080435600, 2) ,(1, 1099184400, 3) ,(1, 1111885200, 2) ,(1, 1130634000, 3) ,(1, 1143334800, 2) ,(1, 1162083600, 3) ,(1, 1174784400, 2) ,(1, 1193533200, 3) ,(1, 1206838800, 2) ,(1, 1224982800, 3) ,(1, 1238288400, 2) ,(1, 1256432400, 3) ,(1, 1269738000, 2) ,(1, 1288486800, 3) ,(1, 1301187600, 2) ,(1, 1319936400, 3) ,(1, 1332637200, 2) ,(1, 1351386000, 3) ,(1, 1364691600, 2) ,(1, 1382835600, 3) ,(1, 1396141200, 2) ,(1, 1414285200, 3) ,(1, 1427590800, 2) ,(1, 1445734800, 3) ,(1, 1459040400, 2) ,(1, 1477789200, 3) ,(1, 1490490000, 2) ,(1, 1509238800, 3) ,(1, 1521939600, 2) ,(1, 1540688400, 3) ,(1, 1553994000, 2) ,(1, 1572138000, 3) ,(1, 1585443600, 2) ,(1, 1603587600, 3) ,(1, 1616893200, 2) ,(1, 1635642000, 3) ,(1, 1648342800, 2) ,(1, 1667091600, 3) ,(1, 1679792400, 2) ,(1, 1698541200, 3) ,(1, 1711846800, 2) ,(1, 1729990800, 3) ,(1, 1743296400, 2) ,(1, 1761440400, 3) ,(1, 1774746000, 2) ,(1, 1792890000, 3) ,(1, 1806195600, 2) ,(1, 1824944400, 3) ,(1, 1837645200, 2) ,(1, 1856394000, 3) ,(1, 1869094800, 2) ,(1, 1887843600, 3) ,(1, 1901149200, 2) ,(1, 1919293200, 3) ,(1, 1932598800, 2) ,(1, 1950742800, 3) ,(1, 1964048400, 2) ,(1, 1982797200, 3) ,(1, 1995498000, 2) ,(1, 2014246800, 3) ,(1, 2026947600, 2) ,(1, 2045696400, 3) ,(1, 2058397200, 2) ,(1, 2077146000, 3) ,(1, 2090451600, 2) ,(1, 2108595600, 3) ,(1, 2121901200, 2) ,(1, 2140045200, 3) ,(3, -1688265000, 2) ,(3, -1656819048, 1) ,(3, -1641353448, 2) ,(3, -1627965048, 3) ,(3, -1618716648, 1) ,(3, -1596429048, 3) ,(3, -1593829848, 5) ,(3, -1589860800, 4) ,(3, -1542427200, 5) ,(3, -1539493200, 6) ,(3, -1525323600, 5) ,(3, -1522728000, 4) ,(3, -1491188400, 7) ,(3, -1247536800, 4) ,(3, 354920400, 5) ,(3, 370728000, 4) ,(3, 386456400, 5) ,(3, 402264000, 4) ,(3, 417992400, 5) ,(3, 433800000, 4) ,(3, 449614800, 5) ,(3, 465346800, 8) ,(3, 481071600, 9) ,(3, 496796400, 8) ,(3, 512521200, 9) ,(3, 528246000, 8) ,(3, 543970800, 9) ,(3, 559695600, 8) ,(3, 575420400, 9) ,(3, 591145200, 8) ,(3, 606870000, 9) ,(3, 622594800, 8) ,(3, 638319600, 9) ,(3, 654649200, 8) ,(3, 670374000, 10) ,(3, 686102400, 11) ,(3, 695779200, 8) ,(3, 701812800, 5) ,(3, 717534000, 4) ,(3, 733273200, 9) ,(3, 748998000, 8) ,(3, 764722800, 9) ,(3, 780447600, 8) ,(3, 796172400, 9) ,(3, 811897200, 8) ,(3, 828226800, 9) ,(3, 846370800, 8) ,(3, 859676400, 9) ,(3, 877820400, 8) ,(3, 891126000, 9) ,(3, 909270000, 8) ,(3, 922575600, 9) ,(3, 941324400, 8) ,(3, 954025200, 9) ,(3, 972774000, 8) ,(3, 985474800, 9) ,(3, 1004223600, 8) ,(3, 1017529200, 9) ,(3, 1035673200, 8) ,(3, 1048978800, 9) ,(3, 1067122800, 8) ,(3, 1080428400, 9) ,(3, 1099177200, 8) ,(3, 1111878000, 9) ,(3, 1130626800, 8) ,(3, 1143327600, 9) ,(3, 1162076400, 8) ,(3, 1174777200, 9) ,(3, 1193526000, 8) ,(3, 1206831600, 9) ,(3, 1224975600, 8) ,(3, 1238281200, 9) ,(3, 1256425200, 8) ,(3, 1269730800, 9) ,(3, 1288479600, 8) ,(3, 1301180400, 9) ,(3, 1319929200, 8) ,(3, 1332630000, 9) ,(3, 1351378800, 8) ,(3, 1364684400, 9) ,(3, 1382828400, 8) ,(3, 1396134000, 9) ,(3, 1414278000, 8) ,(3, 1427583600, 9) ,(3, 1445727600, 8) ,(3, 1459033200, 9) ,(3, 1477782000, 8) ,(3, 1490482800, 9) ,(3, 1509231600, 8) ,(3, 1521932400, 9) ,(3, 1540681200, 8) ,(3, 1553986800, 9) ,(3, 1572130800, 8) ,(3, 1585436400, 9) ,(3, 1603580400, 8) ,(3, 1616886000, 9) ,(3, 1635634800, 8) ,(3, 1648335600, 9) ,(3, 1667084400, 8) ,(3, 1679785200, 9) ,(3, 1698534000, 8) ,(3, 1711839600, 9) ,(3, 1729983600, 8) ,(3, 1743289200, 9) ,(3, 1761433200, 8) ,(3, 1774738800, 9) ,(3, 1792882800, 8) ,(3, 1806188400, 9) ,(3, 1824937200, 8) ,(3, 1837638000, 9) ,(3, 1856386800, 8) ,(3, 1869087600, 9) ,(3, 1887836400, 8) ,(3, 1901142000, 9) ,(3, 1919286000, 8) ,(3, 1932591600, 9) ,(3, 1950735600, 8) ,(3, 1964041200, 9) ,(3, 1982790000, 8) ,(3, 1995490800, 9) ,(3, 2014239600, 8) ,(3, 2026940400, 9) ,(3, 2045689200, 8) ,(3, 2058390000, 9) ,(3, 2077138800, 8) ,(3, 2090444400, 9) ,(3, 2108588400, 8) ,(3, 2121894000, 9) ,(3, 2140038000, 8) ,(4, -1688265000, 2) ,(4, -1656819048, 1) ,(4, -1641353448, 2) ,(4, -1627965048, 3) ,(4, -1618716648, 1) ,(4, -1596429048, 3) ,(4, -1593829848, 5) ,(4, -1589860800, 4) ,(4, -1542427200, 5) ,(4, -1539493200, 6) ,(4, -1525323600, 5) ,(4, -1522728000, 4) ,(4, -1491188400, 7) ,(4, -1247536800, 4) ,(4, 354920409, 5) ,(4, 370728010, 4) ,(4, 386456410, 5) ,(4, 402264011, 4) ,(4, 417992411, 5) ,(4, 433800012, 4) ,(4, 449614812, 5) ,(4, 465346812, 8) ,(4, 481071612, 9) ,(4, 496796413, 8) ,(4, 512521213, 9) ,(4, 528246013, 8) ,(4, 543970813, 9) ,(4, 559695613, 8) ,(4, 575420414, 9) ,(4, 591145214, 8) ,(4, 606870014, 9) ,(4, 622594814, 8) ,(4, 638319615, 9) ,(4, 654649215, 8) ,(4, 670374016, 10) ,(4, 686102416, 11) ,(4, 695779216, 8) ,(4, 701812816, 5) ,(4, 717534017, 4) ,(4, 733273217, 9) ,(4, 748998018, 8) ,(4, 764722818, 9) ,(4, 780447619, 8) ,(4, 796172419, 9) ,(4, 811897219, 8) ,(4, 828226820, 9) ,(4, 846370820, 8) ,(4, 859676420, 9) ,(4, 877820421, 8) ,(4, 891126021, 9) ,(4, 909270021, 8) ,(4, 922575622, 9) ,(4, 941324422, 8) ,(4, 954025222, 9) ,(4, 972774022, 8) ,(4, 985474822, 9) ,(4, 1004223622, 8) ,(4, 1017529222, 9) ,(4, 1035673222, 8) ,(4, 1048978822, 9) ,(4, 1067122822, 8) ,(4, 1080428422, 9) ,(4, 1099177222, 8) ,(4, 1111878022, 9) ,(4, 1130626822, 8) ,(4, 1143327622, 9) ,(4, 1162076422, 8) ,(4, 1174777222, 9) ,(4, 1193526022, 8) ,(4, 1206831622, 9) ,(4, 1224975622, 8) ,(4, 1238281222, 9) ,(4, 1256425222, 8) ,(4, 1269730822, 9) ,(4, 1288479622, 8) ,(4, 1301180422, 9) ,(4, 1319929222, 8) ,(4, 1332630022, 9) ,(4, 1351378822, 8) ,(4, 1364684422, 9) ,(4, 1382828422, 8) ,(4, 1396134022, 9) ,(4, 1414278022, 8) ,(4, 1427583622, 9) ,(4, 1445727622, 8) ,(4, 1459033222, 9) ,(4, 1477782022, 8) ,(4, 1490482822, 9) ,(4, 1509231622, 8) ,(4, 1521932422, 9) ,(4, 1540681222, 8) ,(4, 1553986822, 9) ,(4, 1572130822, 8) ,(4, 1585436422, 9) ,(4, 1603580422, 8) ,(4, 1616886022, 9) ,(4, 1635634822, 8) ,(4, 1648335622, 9) ,(4, 1667084422, 8) ,(4, 1679785222, 9) ,(4, 1698534022, 8) ,(4, 1711839622, 9) ,(4, 1729983622, 8) ,(4, 1743289222, 9) ,(4, 1761433222, 8) ,(4, 1774738822, 9) ,(4, 1792882822, 8) ,(4, 1806188422, 9) ,(4, 1824937222, 8) ,(4, 1837638022, 9) ,(4, 1856386822, 8) ,(4, 1869087622, 9) ,(4, 1887836422, 8) ,(4, 1901142022, 9) ,(4, 1919286022, 8) ,(4, 1932591622, 9) ,(4, 1950735622, 8) ,(4, 1964041222, 9) ,(4, 1982790022, 8) ,(4, 1995490822, 9) ,(4, 2014239622, 8) ,(4, 2026940422, 9) ,(4, 2045689222, 8) ,(4, 2058390022, 9) ,(4, 2077138822, 8) ,(4, 2090444422, 9) ,(4, 2108588422, 8) ,(4, 2121894022, 9) ,(4, 2140038022, 8) ,(5, -1009875600, 1); +INSERT INTO time_zone_transition_type (Time_zone_id, Transition_type_id, Offset, Is_DST, Abbreviation) VALUES (1, 0, 7200, 1, 'MEST') ,(1, 1, 3600, 0, 'MET') ,(1, 2, 7200, 1, 'MEST') ,(1, 3, 3600, 0, 'MET') ,(2, 0, 0, 0, 'UTC') ,(3, 0, 9000, 0, 'MMT') ,(3, 1, 12648, 1, 'MST') ,(3, 2, 9048, 0, 'MMT') ,(3, 3, 16248, 1, 'MDST') ,(3, 4, 10800, 0, 'MSK') ,(3, 5, 14400, 1, 'MSD') ,(3, 6, 18000, 1, 'MSD') ,(3, 7, 7200, 0, 'EET') ,(3, 8, 10800, 0, 'MSK') ,(3, 9, 14400, 1, 'MSD') ,(3, 10, 10800, 1, 'EEST') ,(3, 11, 7200, 0, 'EET') ,(4, 0, 9000, 0, 'MMT') ,(4, 1, 12648, 1, 'MST') ,(4, 2, 9048, 0, 'MMT') ,(4, 3, 16248, 1, 'MDST') ,(4, 4, 10800, 0, 'MSK') ,(4, 5, 14400, 1, 'MSD') ,(4, 6, 18000, 1, 'MSD') ,(4, 7, 7200, 0, 'EET') ,(4, 8, 10800, 0, 'MSK') ,(4, 9, 14400, 1, 'MSD') ,(4, 10, 10800, 1, 'EEST') ,(4, 11, 7200, 0, 'EET') ,(5, 0, 32400, 0, 'CJT') ,(5, 1, 32400, 0, 'JST'); +INSERT INTO time_zone_leap_second (Transition_time, Correction) VALUES (78796800, 1) ,(94694401, 2) ,(126230402, 3) ,(157766403, 4) ,(189302404, 5) ,(220924805, 6) ,(252460806, 7) ,(283996807, 8) ,(315532808, 9) ,(362793609, 10) ,(394329610, 11) ,(425865611, 12) ,(489024012, 13) ,(567993613, 14) ,(631152014, 15) ,(662688015, 16) ,(709948816, 17) ,(741484817, 18) ,(773020818, 19) ,(820454419, 20) ,(867715220, 21) ,(915148821, 22); diff --git a/scripts/mysql_test_db.sql b/scripts/mysql_test_db.sql new file mode 100644 index 00000000..9f8a0cf6 --- /dev/null +++ b/scripts/mysql_test_db.sql @@ -0,0 +1,31 @@ +-- Copyright (c) 2018 MariaDB Foundation +-- +-- This program is free software; you can redistribute it and/or modify +-- it under the terms of the GNU General Public License as published by +-- the Free Software Foundation; version 2 of the License. +-- +-- This program is distributed in the hope that it will be useful, +-- but WITHOUT ANY WARRANTY; without even the implied warranty of +-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +-- GNU General Public License for more details. +-- +-- You should have received a copy of the GNU General Public License +-- along with this program; if not, write to the Free Software +-- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA + +CREATE DATABASE IF NOT EXISTS test CHARACTER SET latin1 COLLATE latin1_swedish_ci; + +-- Fill "db" table with default grants for anyone to +-- access database 'test' and 'test_%' if "db" table didn't exist +CREATE TEMPORARY TABLE tmp_db LIKE db; +INSERT INTO tmp_db VALUES ('%','test','','Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','Y','Y','Y','Y','N','N','Y','Y','Y'); +INSERT INTO tmp_db VALUES ('%','test\_%','','Y','Y','Y','Y','Y','Y','N','Y','Y','Y','Y','Y','Y','Y','Y','N','N','Y','Y','Y'); +INSERT INTO db SELECT * FROM tmp_db WHERE @had_db_table=0; +DROP TABLE tmp_db; + +-- Anonymous user with no privileges. +CREATE TEMPORARY TABLE tmp_user_anonymous LIKE global_priv; +INSERT INTO tmp_user_anonymous (host,user) VALUES ('localhost',''); +INSERT INTO tmp_user_anonymous (host,user) SELECT @current_hostname,'' FROM dual WHERE @current_hostname != 'localhost'; +INSERT INTO global_priv SELECT * FROM tmp_user_anonymous WHERE @had_user_table=0; +DROP TABLE tmp_user_anonymous; diff --git a/scripts/mysqlaccess.conf b/scripts/mysqlaccess.conf new file mode 100644 index 00000000..faf47da5 --- /dev/null +++ b/scripts/mysqlaccess.conf @@ -0,0 +1,45 @@ +# ------------------------------------------------------------------------- # +# MySQLaccess version 2.0p2 # +# (c) Yves.Carlier@rug.ac.be, 1997 # +# # +# *** Configuration file *** # +# # +# -Default values read by mysqlaccess during initialisation. # +# This file is looked for in # +# 1) the current directory # +# 2) /etc/ # +# -Options given on the command-line override the values given in here # +# -Given options can't be overruled by empty/blanc options!! # +# ------------------------------------------------------------------------- # + + +# ----------------# +# Global settings # +# --------------- # + #$Param{'host'} = ''; + $Param{'user'} = 'nobody'; + $Param{'db'} = 'test'; + $Param{'password'} = 'foobar'; + $Param{'debug'} = 0; + +# --------------------------# +# Settings for Command-line # +# ------------------------- # +if ($CMD) { + $Param{'superuser'} = 'root'; + $Param{'rhost'} = 'localhost'; + $Param{'spassword'} = ''; + $Param{'brief'} = 1; +} + +# ---------------------# +# Settings for CGI-BIN # +# -------------------- # +if ($CGI) { + $Param{'superuser'} = 'root'; + $Param{'rhost'} = 'localhost'; + $Param{'spassword'} = ''; + $Param{'table'} = 1; +} + +1; #to make require happy diff --git a/scripts/mysqlaccess.sh b/scripts/mysqlaccess.sh new file mode 100644 index 00000000..aaf711b0 --- /dev/null +++ b/scripts/mysqlaccess.sh @@ -0,0 +1,3265 @@ +#!@PERL_PATH@ + +# Copyright (c) 2000, 2017, 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 Library 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 +# Library General Public License for more details. +# +# You should have received a copy of the GNU Library General Public +# License along with this library; if not, write to the Free +# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +# MA 02110-1335 USA + +# **************************** +package MySQLaccess; +#use strict; +use File::Temp qw(tempfile tmpnam); +use Fcntl; + +BEGIN { + # **************************** + # static information... + $VERSION = "2.10, 13 Sep 2019"; + $0 =~ m%/([^/]+)$%o; + $script = $1; + $script = 'MySQLAccess' unless $script; + $script_conf = "$script.conf"; + $script_log = $ENV{'HOME'}."/$script.log"; + + # **************************** + # information on MariaDB + $MYSQL = '@bindir@/mysql'; # path to mysql executable + $SERVER = '3.21'; + $MYSQL_OPT = ' --batch --unbuffered'; + $ACCESS_DB = 'mysql'; # name of DB with grant-tables + $ACCESS_H = 'host'; # + $ACCESS_U = 'user'; # + $ACCESS_D = 'db'; # + # Add/Edit privileges + $ACCESS_H_TMP = 'host_tmp'; + $ACCESS_U_TMP = 'user_tmp'; + $ACCESS_D_TMP = 'db_tmp'; + $ACCESS_H_BCK = 'host_backup'; + $ACCESS_U_BCK = 'user_backup'; + $ACCESS_D_BCK = 'db_backup'; + $DIFF = '/usr/bin/diff'; + $MYSQLDUMP = '@bindir@/mysqldump'; + #path to mysqldump executable + + $MYSQLADMIN= 'http://foobar.com/MySQLadmin'; + #URL of CGI for manipulating + #the temporary grant-tables +} + +END { + unlink $MYSQL_CNF if defined $MYSQL_CNF and not $DEBUG; +} + +$INFO = <<"_INFO"; +-------------------------------------------------------------------------- + mysqlaccess (Version $VERSION) + ~~~~~~~~~~~ + Copyright (C) 1997,1998 Yves.Carlier\@rug.ac.be + University of Ghent (RUG), Belgium + Administratieve Informatieverwerking (AIV) + + report the access-privileges for a USER from a HOST to a DB + + Many thanks go to <monty\@mysql.com> and <psmith\@BayNetworks.COM> + for their suggestions, debugging and patches. + + use `$script -?' to get more information on available options. + + From version 2.0x, $script can also be used through a WEB-browser + if it is ran as a CGI-script. (See the release-notes) + +-------------------------------------------------------------------------- +_INFO + +$OPTIONS = <<_OPTIONS; + +Usage: $script [host [user [db]]] OPTIONS + + -?, --help display this helpscreen and exit + -v, --version print information on the program `$script' + + -u, --user=# username for logging in to the db + -p, --password=# validate password for user + -h, --host=# name or IP-number of the host + -d, --db=# name of the database + + -U, --superuser=# connect as superuser + -P, --spassword=# password for superuser + -H, --rhost=# remote MariaDB-server to connect to + --old_server connect to old MariaDB-server (before v3.21) which + does not yet know how to handle full where clauses. + + -b, --brief single-line tabular report + -t, --table report in table-format + + --relnotes print release-notes + --plan print suggestions/ideas for future releases + --howto some examples of how to run `$script' + --debug=N enter debuglevel N (0..3) + + --copy reload temporary grant-tables from original ones + --preview show differences in privileges after making + changes in (temporary) grant-tables + --commit copy grant-rules from temporary tables to grant-tables + (!don't forget to do an mysqladmin reload) + --rollback undo the last changes to the grant-tables. + + Note: + At least the user and the db must be given (even with wildcards) + If no host is given, `localhost' is assumed + Wilcards (*,?,%,_) are allowed for host, user and db, but be sure + to escape them from your shell!! (ie type \\* or '*') +_OPTIONS + +$RELEASE = <<'_RELEASE'; + +Release Notes: +------------- + 0.1-beta1: internal + - first trial. + + 0.1-beta2: (1997-02-27) + - complete rewrite of the granting-rules, based on the documentation + found in de FAQ. + - IP-number and name for a host are equiv. + + 0.1-beta3: (1997-03-10) + - more information + - 'localhost' and the name/ip of the local machine are now equiv. + + 0.1-beta4: (1997-03-11) + - inform the user if he has not enough priv. to read the mysql db + + 1.0-beta1: (1997-03-12) + suggestions by Monty: + - connect as superuser with superpassword. + - mysqlaccess could also notice if all tables are empty. This means + that all user have full access! + - It would be nice if one could optionally start mysqlaccess without + any options just the arguments 'user db' or 'host user db', where + host is 'localhost' if one uses only two arguments. + + 1.0-beta2: (1997-03-14) + - bugfix: translation to reg.expr of \_ and \%. + - bugfix: error in matching regular expression and string given + by user which resulted in + 'test_123' being matched with 'test' + + 1.0-beta3: (1997-03-14) + - bugfix: the user-field should not be treated as a sql-regexpr, + but as a plain string. + - bugfix: the host-table should not be used if the host isn't empty in db + or if the host isn't emty in user + (Monty) + + 1.0-beta4: (1997-03-14) + - bugfix: in an expression "$i = $j or $k", the '=' binds tighter than the or + which results in problems... + (by Monty) + - running mysqlaccess with "perl -w" gives less warnings... ;-) + + 1.0-beta5: (1997-04-04) + - bugfix: The table sorting was only being applied to the "user" table; all + the tables need to be sorted. Rewrote the sort algorithm, and + the table walk algorithm (no temp file anymore), and various + other cleanups. I believe the access calculation is 100% correct. + (by Paul D. Smith <psmith\@baynetworks.com>) + - Allow the debug level to be set on the cmd line with --debug=N. + (by Paul D. Smith <psmith\@baynetworks.com>) + - More -w cleanups; should be totally -w-clean. + (by Paul D. Smith <psmith\@baynetworks.com>) + + 1.1-beta1: (1997-04-xx) + 1.1-beta2: (1997-04-11) + - new options: + --all_users : report access-rights for all possible users + --all_dbs : report access-rights for all possible dbs + --all_hosts : report access-rights for all possible hosts + --brief : as brief as possible, don't mention notes,warnings and rules + --password : validate password for user + - layout: long messages are wrapped on the report. + - functionality: + more descriptive notes and warnings + wildcards (*,?) are allowed in the user,host and db options + setting xxxx=* is equiv to using option --all_xxxx + note: make sure you escape your wildcards, so they don't get + interpreted by the shell. use \* or '*' + - bugfix: Fieldnames which should be skipped on the output can now have + a first capital letter. + - bugfix: any option with a '.' (eg ip-number) was interpreted as + a wildcard-expression. + - bugfix: When no entry was found in the db-table, the default accessrights are + N, instead of the faulty Y in a previous version. + + 1.1-beta-3 : (1997-04-xx) + 1.1-beta-4 : (1997-04-xx) + 1.1-beta-5 : (1997-04-xx) + 1.1 : (1997-04-28) + - new options: + --rhost : name of mysql-server to connect to + --plan : print suggestions/ideas for future releases + --relnotes : display release-notes + --howto : display examples on how to use mysqlaccess + --brief : single-line tabular output + - functionality/bugfix: + * removed options --all_users,--all_dbs,--all_hosts, which + were redundant with the wildcard-expressions for the corresponding + options. They made the processing of the commandline too painful + and confusing ;-) + (suggested by psmith) + * redefined the option --brief, which now gives a single-line + tabular output + * Now we check if the right version of the mysql-client is used, + since we might use an option not yet implemented in an + older version (--unbuffered, since 3.0.18) + Also the error-messages the mysql-client reports are + better interpreted ;-) + * Wildcards can now be given following the SQL-expression + (%,_) and the Regular-expression (*,?) syntax. + - speed: we now open a bidirectional pipe to the mysql-client, and keep + it open throughout the whole run. Queries are written to, + and the answers read from the pipe. + (suggested by monty) + - bugfixes: + * the Rules were not properly reset over iterations + * when in different tables the field-names were not identical, + eg. Select_priv and select_priv, they were considered as + definitions of 2 different access-rights. + * the IP-number of a host with a name containing wildcards should + not be searched for in Name2IP and IP2Name. + * various other small things, pointed out by <monty> and <psmith> + + 1.2 : (1997-05-13) + - bugfix: + * Fixed bug in acl with anonymous user: Now if one gets accepted by the + user table as a empty user name, the user name is set to '' when + checking against the 'db' and 'host' tables. (Bug fixed in MySQL3.20.19) + + 1.2-1 : (1997-xx-xx) + - bugfix: + * hashes should be initialized with () instead of {} <psmith> + * "my" variable $name masks earlier declaration in same scope, + using perl 5.004 <????> + + 1.2-2 : (1997-06-10) + + 2.0p1-3 : (1997-10-xx) + - new + * packages + * log-file for debug-output : /tmp/mysqlaccess.log + * default values are read from a configuration file $script.conf + first this file is looked for in the current directory; if not + found it is looked for in @sysconfdir@ + Note that when default-values are given, these can't get overridden + by empty (blanc) values! + * CGI-BIN version with HTML and forms interface. Simply place the + script in an ScriptAliased directory, make the configuration file + available in the that directory or in @sysconfdir@, and point your browser + to the right URL. + * copy the grant-rules to temporary tables, where you are safe to + play with them. + * preview changes in privileges after changing grant-rules, + before taking them into production + * copy the new grant-rules from the temporary tables back to the + grant-tables. + * Undo all changes made in the grant-tables (1-level undo). + -new options: + * --table : as opposite of the --brief option. + * --copy : (re)load temporary grant-tables from original ones. + * --preview : preview changes in privileges after changing + some or more entries in the grant-tables. + * --commit : copy grant-rules from temporary tables to grant-tables + (!don't forget to do an mysqladmin reload) + * --rollback: undo the last changes to the grant-tables. + + - bugfix: + * if the table db is empty, mysqlaccess freezed + (by X Zhu <X.Zhu@Bradford.ac.uk>) + + 2.0 : (1997-10-09) + - fixed some "-w" warnings. + - complain when certain programs and paths can't be found. + + 2.01 : (1997-12-12) + - bugfix: + * rules for db-table where not calculated and reported correctly. + 2.02 : (1998-01-xx) + - bugfix: + * Privileges of the user-table were not AND-ed properly with the + other privileges. (reported by monty) + - new option: + * --old_server: mysqlaccess will now use a full where clause when + retrieving information from the MySQL-server. If + you are connecting to an old server (before v3.21) + then use the option --old_server. + 2.03 : (1998-02-27) + - bugfix: + * in Host::MatchTemplate: incorrect match if host-field was left empty. + + 2.04-alpha1 : (2000-02-11) + Closes vulnerability due to former implementation requiring passwords + to be passed on the command line. + - functionality + Option values for --password -p -spassword -P may now be omitted from + command line, in which case the values will be prompted for. + (fix supplied by Steve Harvey <sgh@vex.net>) + + 2.05: (2000-02-17) Monty + Moved the log file from /tmp to ~ + + 2.06: Don't print '+++USING FULL WHERE CLAUSE+++' + +_RELEASE + +$TODO = <<_TODO; + + Plans: + ----- + -a full where clause is use now. How can we handle older servers? + -add some more functionality for DNS. + -select the warnings more carefuly. + >> I think that the warnings should either be enhanced to _really_ + >> understand and report real problems accurately, or restricted to + >> only printing things that it knows with 100% certainty. <psmith) + >> Why do I have both '%' and 'any_other_host' in there? Isn't that + >> the same thing? I think it's because I have an actual host '%' in + >> one of my tables. Probably the script should catch that and not + >> duplicate output. <psmith> + +_TODO + +# From the FAQ: the Grant-algorithm +# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +# The host table is mainly to maintain a list of "secure" servers. +# At TCX hosts contain a list of all machines on local network. These are granted +# all privileges. +# Technically the user grant is calculated by: +# +# 1.First sort all entries by host by putting host without wildcards first, +# after this host with wildcards and entries with host = ". +# Under each host sort user by the same criterias. +# 2.Get grant for user from the "db" table. +# 3.If hostname is "empty" for the found entry, AND the privileges with +# the privileges for the host in "host" table. +# (Remove all which is not "Y" in both) +# 4.OR (add) the privileges for the user from the "user" table. +# (add all privileges which is "Y" in "user") +# +# When matching, use the first found match. +# +# ----------------------------------------------------------------------------------- + +$HOWTO = <<_HOWTO; + +Examples of how to call $script: +~~~~~~~~ +1)Calling $script with 2 arguments: + + \$ $script root mysql + ->report rights of user root logged on at the local host in db mysql + + Access-rights + for USER 'root', from HOST 'localhost', to DB 'mysql' + +-----------------+---+ +-----------------+---+ + | select_priv | Y | | drop_priv | Y | + | insert_priv | Y | | reload_priv | Y | + | update_priv | Y | | shutdown_priv | Y | + | delete_priv | Y | | process_priv | Y | + | create_priv | Y | | file_priv | Y | + +-----------------+---+ +-----------------+---+ + BEWARE: Everybody can access your DB as user 'root' + : WITHOUT supplying a password. Be very careful about it!! + + The following rules are used: + db : 'No matching rule' + host : 'Not processed: host-field is not empty in db-table.' + user : 'localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y' + +2)Calling $script with 3 arguments: + + \$ $script foo.bar nobody Foo + ->report rights of user root logged in at machine foobar to db Foo + + Access-rights + for USER 'nobody', from HOST 'foo.bar', to DB 'Foo' + +-----------------+---+ +-----------------+---+ + | select_priv | Y | | drop_priv | N | + | insert_priv | Y | | reload_priv | N | + | update_priv | Y | | shutdown_priv | N | + | delete_priv | Y | | process_priv | N | + | create_priv | N | | file_priv | N | + +-----------------+---+ +-----------------+---+ + BEWARE: Everybody can access your DB as user 'nobody' + : WITHOUT supplying a password. Be very careful about it!! + + The following rules are used: + db : 'foo.bar','Foo','nobody','Y','Y','Y','N','N','N' + host : 'Not processed: host-field is not empty in db-table.' + user : 'foo.bar','nobody','','N','N','N','Y','N','N','N','N','N','N' + +3)Using wildcards: + + \$ $script \\* nobody Foo --brief + ->report access-rights of user nobody from all machines to db Foo, + and use a matrix-report. + + Sel Ins Upd Del Crea Drop Reld Shut Proc File Host,User,DB + ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- -------------------- + Y Y Y Y N N N N N N localhost,nobody,Foo + N N N N N N N N N N %,nobody,Foo + N N N N N N N N N N any_other_host,nobody,Foo + +_HOWTO + + +# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # +# START OF THE PROGRAM # +# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ # + +use Getopt::Long; +use Sys::Hostname; +use IPC::Open3; + + +# **************************** +# debugging flag +# can be set to 0,1,2,3 +# a higher value gives more info +# ! this can also be set on the command-line + $DEBUG = 0; + +# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>8 +# Normally nothing should be changed beneeth this line + + +# **************************** +# no caching on STDOUT + $|=1; + + $MYSQL_CNF = tmpnam(); + %MYSQL_CNF = (client => { }, + mysql => { }, + mysqldump => { }, + ); + + + +$NEW_USER = 'ANY_NEW_USER'; +$NEW_DB = 'ANY_NEW_DB' ; + + +# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # +# mysqlaccess: # +# ~~~~~~~~~~~ # +# Lets get to it, # +# and start the program by processing the parameters # +# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # + +($CMD,$CGI) = GetMode(); + +# **************************** +# the copyright message should +# always be printed (once) +MySQLaccess::Report::Print_Header(); + +# ***************************** +# Read configuration-file + MySQLaccess::Debug::Print(1, "Reading configuration file..."); + if (-f "@sysconfdir@/$script_conf") { + print "Configuration file '$script_conf' is found in '@sysconfdir@/'\n"; + require "@sysconfdir@/$script_conf"; + } + elsif (-f "@prefix@/$script_conf") { + print "Configuration file '$script_conf' is found in '@prefix@/'\n"; + require "@prefix@/$script_conf"; + } + elsif (-f "./$script_conf") { + print "\nERROR! Configuration file '$script_conf' is found in the current "; + print "directory.\nThe permissible locations for this file are either "; + print "@sysconfdir@/ or @prefix@/\n"; + print "Please move it to one of these locations and retry.\n\n"; + exit 0; + } + + +# **************************** +# Read in all parameters +if ($MySQLaccess::CMD) { #command-line version + # ---------------------------- + # Get options from commandline + $Getopt::Long::ignorecase=0; #case sensitive options + if ( grep(/\-\?/,@ARGV) ) { MySQLaccess::Report::Print_Usage(); exit 0; } + GetOptions("help" => \$Param{'help'} + ,"host|h=s" => \$Param{'host'} + ,"user|u=s" => \$Param{'user'} + ,"password|p:s" => \$Param{'password'} + ,"db|d=s" => \$Param{'db'} + ,"superuser|U=s" => \$Param{'superuser'} + ,"spassword|P:s" => \$Param{'spassword'} + ,"rhost|H=s" => \$Param{'rhost'} + ,"old_server" => \$Param{'old_server'} + ,"debug=i" => \$Param{'DEBUG'} + ,"brief|b" => \$Param{'brief'} + ,"table|t" => \$Param{'table'} + ,"relnotes" => \$Param{'relnotes'} + ,"plan" => \$Param{'plan'} + ,"howto" => \$Param{'howto'} + ,"version|v" => \$Param{'version'} + ,"preview" => \$Param{'preview'} + ,"copy" => \$Param{'copy'} + ,"commit" => \$Param{'commit'} + ,'rollback' => \$Param{'rollback'} + ); + + # ----------------------------- + # set DEBUG + $DEBUG = $Param{'DEBUG'} if ($Param{'DEBUG'}>=$DEBUG); + + # ----------------------------- + # check for things which aren't + # declared as options: + # 2 arguments: (user,db) -> ('localhost','user','db') + if ($#ARGV == 1) { + MySQLaccess::Debug::Print(2,"$script called with 2 arguments:"); + $Param{'host'} = $Param{'host'} || 'localhost'; + $Param{'user'} = $ARGV[0] || $Param{'user'}; + $Param{'db'} = $ARGV[1] || $Param{'db'}; + } + # 3 arguments: (host,user,db) + if ($#ARGV == 2) { + MySQLaccess::Debug::Print(2,"$script called with 3 arguments:"); + $Param{'host'} = $ARGV[0] || $Param{'host'}; + $Param{'user'} = $ARGV[1] || $Param{'user'}; + $Param{'db'} = $ARGV[2] || $Param{'db'}; + } + + # ------------------------------------- + # prompt for user password if requested + if ( defined($Param{'password'}) && length($Param{'password'}) == 0 ) { + $Param{'password'} = PromptPass( + "Password for MySQL user $Param{'user'}: "); + } +} +if ($MySQLaccess::CGI) { #CGI-version + require CGI; + $Q = new CGI; + $Param{'help'} = $Q->param('help') ; + $Param{'host'} = $Q->param('host') || $Q->param('h') || $Param{'host'}; + $Param{'user'} = $Q->param('user') || $Q->param('u') || $Param{'user'}; + $Param{'db'} = $Q->param('db') || $Q->param('d') || $Param{'db'}; + $Param{'password'} = $Q->param('password') || $Q->param('p') || $Param{'password'}; + $Param{'superuser'} = $Q->param('superuser') || $Q->param('U') || $Param{'superuser'}; + $Param{'spassword'} = $Q->param('spassword') || $Q->param('P') || $Param{'spassword'}; + $Param{'rhost'} = $Q->param('rhost') || $Q->param('H') || $Param{'rhost'}; + $Param{'old_server'}= $Q->param('old_server')|| $Param{'old_server'}; + $Param{'debug'} = $Q->param('debug') || $Param{'debug'}; + $Param{'brief'} = $Q->param('brief') || $Param{'brief'}; + $Param{'table'} = $Q->param('table') || $Param{'table'}; + $Param{'relnotes'} = $Q->param('relnotes'); + $Param{'plan'} = $Q->param('plan'); + $Param{'howto'} = $Q->param('howto'); + $Param{'version'} = $Q->param('version') ? $Q->param('version') : $Q->param('v'); + $Param{'edit'} = $Q->param('edit'); + $Param{'preview'} = $Q->param('preview'); + $Param{'copy'} = $Q->param('copy'); + $Param{'commit'} = $Q->param('commit'); + $Param{'rollback'} = $Q->param('rollback'); + # ----------------------------- + # set DEBUG + $DEBUG = $Q->param('debug') if ($Q->param('debug')>=$DEBUG); +} + +# ---------------------- +# brief and table-format +# exclude each-other +# table-format is prefered +if (defined($Param{'table'})) { undef($Param{'brief'}); } +if (defined($Param{'preview'}) or + defined($Param{'copy'}) or + defined($Param{'commit'}) or + defined($Param{'rollback'}) ) { $Param{'edit'}='on'; } + + +# ---------------------- +# if no host is given +# assume we mean 'localhost' +if (!defined($Param{'host'})) { $Param{'host'}='localhost'; } + +# ---------------------- +# perform some checks +# -> eliminate 'broken pipe' error +push(@MySQLaccess::Grant::Error,'not_found_mysql') if !(-x $MYSQL); +push(@MySQLaccess::Grant::Error,'not_found_diff') if !(-x $DIFF); +push(@MySQLaccess::Grant::Error,'not_found_mysqldump') if !(-x $MYSQLDUMP); +if (@MySQLaccess::Grant::Error) { + MySQLaccess::Report::Print_Error_Messages() ; + exit 0; +} + +#----------------------- +# get info/help if necc. +$print_usage=1; +if ( defined($Param{'version'}) ) { + MySQLaccess::Report::Print_Version(); + $print_usage=0; + MySQLaccess::Report::Print_Footer(); + MySQLaccess::DB::CloseConnection(); + exit 0; +# exit 0; +} +if ( defined($Param{'relnotes'}) ) { + MySQLaccess::Report::Print_Relnotes(); + $print_usage=0; + MySQLaccess::Report::Print_Footer(); + MySQLaccess::DB::CloseConnection(); + exit 0; +# exit 0; +} +if ( defined($Param{'plan'}) ) { + MySQLaccess::Report::Print_Plans(); + $print_usage=0; + MySQLaccess::Report::Print_Footer(); + MySQLaccess::DB::CloseConnection(); + exit 0; +# exit 0; +} +if ( defined($Param{'howto'}) ) { + MySQLaccess::Report::Print_HowTo(); + $print_usage=0; + MySQLaccess::Report::Print_Footer(); + MySQLaccess::DB::CloseConnection(); + exit 0; +# exit 0; +} + +# ----------------------------- +# generate a help-screen in CMD-mode +# or a blanc form in CGI-mode +if ( defined($Param{'help'}) + or !defined($Param{'user'}) + or !defined($Param{'host'}) + or !defined($Param{'db'}) + ) { + push(@MySQLaccess::Grant::Error,'user_required') unless defined($Param{'user'}); + push(@MySQLaccess::Grant::Error,'db_required') unless defined($Param{'db'}); + push(@MySQLaccess::Grant::Error,'host_required') unless defined($Param{'host'}); + MySQLaccess::Report::Print_Usage() if $print_usage; + exit 0; +} + + +# ---------------------------- +# get hostname and local-ip +# for localhost +$localhost = MySQLaccess::Host::LocalHost(); +$local_ip = MySQLaccess::Host::Name2IP($localhost); +$MySQLaccess::Host::localhost = MySQLaccess::Host::LocalHost(); +$MySQLaccess::Host::local_ip = MySQLaccess::Host::Name2IP($localhost); +MySQLaccess::Debug::Print(3, "localhost name=$localhost, ip=$local_ip"); + +#----------------------------------- +# version of MySQL-server to connect +# to determine use of full where clause +$MySQLaccess::Host::SERVER = $Param{'old_server'} ? '3.20' : $SERVER; + +#--------------------------------- +# create the config file for mysql and mysqldump +# to avoid passing authentication info on the command line +# +MergeConfigFiles(); +die "Unsafe config file found: $unsafeConfig\n" if $unsafeConfig; +if (defined($Param{'superuser'})) { + $MYSQL_CNF{'mysql'}{'user'} = $Param{'superuser'}; + $MYSQL_CNF{'mysqldump'}{'user'} = $Param{'superuser'}; +} +if (defined($Param{'spassword'})) { + if ( $CMD && length($Param{'spassword'}) == 0 ) { + $Param{'spassword'} = + PromptPass("Password for MySQL superuser $Param{'superuser'}: "); + } + if ( length($Param{'spassword'}) > 0 ) { + $MYSQL_CNF{'mysql'}{'password'} = $Param{'spassword'}; + $MYSQL_CNF{'mysqldump'}{'password'} = $Param{'spassword'}; + } +} +WriteTempConfigFile(); + +#--------------------------------- +# Inform user if he has not enough +# privileges to read the access-db +if ( $nerror=MySQLaccess::DB::OpenConnection() ) { + MySQLaccess::Report::Print_Error_Access($nerror); + exit 0; +} + +# ----------------------- +# Read MySQL ACL-files +if ($nerror=MySQLaccess::Grant::ReadTables()) { + MySQLaccess::Report::Print_Error_Access($nerror); + exit 0; +}; +if ($Param{'edit'} and $nerror=MySQLaccess::Grant::ReadTables('tmp')) { + MySQLaccess::Report::Print_Error_Access($nerror); + exit 0; +} + +#--------------------------------- +# reload temporay grant-tables +# with data from original ones +if ( defined($Param{'copy'}) ) { + $nerror=MySQLaccess::DB::LoadTmpTables(); + if ($nerror) { + MySQLaccess::Report::Print_Error_Access($nerror); + exit 0; + } + my $msg = "The grant-rules are copied from the grant-tables to\n" + . "the temporary tables."; + MySQLaccess::Report::Print_Message([$msg]); +# MySQLaccess::Report::Print_Footer(); +# MySQLaccess::DB::CloseConnection(); +# exit 0; +} + + +#--------------------------------- +# preview result of changes in the +# grant-tables +if ( defined($Param{'preview'}) ) { + $aref=MySQLaccess::Grant::Diff_Privileges(); + MySQLaccess::Report::Print_Diff_ACL($aref); +# MySQLaccess::Report::Print_Footer(); +# MySQLaccess::DB::CloseConnection(); +# exit 0; +} + + +#--------------------------------- +# reload grant-tables +# with data from temporary tables +if ( defined($Param{'commit'}) ) { + if ($nerror = MySQLaccess::DB::CommitGrantTables()) { + MySQLaccess::Report::Print_Error_Access($nerror); + exit 0; + } + my $msg = "The grant-rules have been copied from the temporary tables\n" + . "to the grant-tables."; + my $msg1= "Don't forget to do an 'mysqladmin reload' before these\n" + . "changes take effect."; + my $msg2= "A backup-version of your original grant-rules are saved in the\n" + . "backup-tables, so you can always perform a 1-level rollback."; + MySQLaccess::Report::Print_Message([$msg,$msg1,$msg2]); +# MySQLaccess::Report::Print_Footer(); +# MySQLaccess::DB::CloseConnection(); +# exit 0; +} + +#--------------------------------- +# restore previous grant-rules +# with data from backup tables +if ( defined($Param{'rollback'}) ) { + if ($nerror = MySQLaccess::DB::RollbackGrantTables()) { + MySQLaccess::Report::Print_Error_Access($nerror); + exit 0; + } + my $msg = "The old grant-rules have been copied back from the backup tables\n" + . "to the grant-tables."; + my $msg1= "Don't forget to do an 'mysqladmin reload' before these\n" + . "changes take effect."; + MySQLaccess::Report::Print_Message([$msg,$msg1]); +# MySQLaccess::Report::Print_Footer(); +# MySQLaccess::DB::CloseConnection(); +# exit 0; +} +#---------------------------------- +# show edit-taskbar +if ( defined($Param{'edit'})) { + if ($MySQLaccess::CGI ) { + MySQLaccess::Report::Print_Edit(); + $print_usage=0; + MySQLaccess::Report::Print_Footer(); + MySQLaccess::DB::CloseConnection(); + exit 0; + } + else { + MySQLaccess::Report::Print_Edit(); + $print_usage=0; + MySQLaccess::Report::Print_Footer(); + MySQLaccess::DB::CloseConnection(); + exit 0; + } +} + + +# ----------------------------- +# Build list of users,dbs,hosts +# to process... +@all_dbs = @{MySQLaccess::DB::Get_All_dbs($Param{'db'})}; +@all_users = @{MySQLaccess::DB::Get_All_users($Param{'user'})}; +@all_hosts = @{MySQLaccess::DB::Get_All_hosts($Param{'host'})}; +#if EDIT-mode +#@all_dbs_tmp = @{MySQLaccess::DB::Get_All_dbs($Param{'db'},'tmp')}; +#@all_users_tmp = @{MySQLaccess::DB::Get_All_users($Param{'user'},'tmp')}; +#@all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts($Param{'host'},'tmp')}; + +# ----------------------------- +# Report access-rights for each +# tuple (host,user,db) +#$headers=0; +my %Access = (); +foreach $host (@all_hosts) { + foreach $user (@all_users) { + foreach $db (@all_dbs) { + MySQLaccess::Grant::Initialize(); + %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db); + MySQLaccess::Report::Print_Access_rights($host,$user,$db,\%Access); + } + } +} + +# ----------------------------- +# End script +MySQLaccess::Report::Print_Footer(); +MySQLaccess::DB::CloseConnection(); +exit 0; + +############################################################# +# FUNCTIONS # +############### +sub GetMode { + my $cmd=0; + my $cgi=0; + if (defined($ENV{'HTTP_HOST'})) { $cmd=0; $cgi=1; } + else { $cmd=1; $cgi=0; } + return ($cmd,$cgi); +} + +# ================================ +# sub PromptPass +# prompt tty for a password +# ================================ +sub PromptPass { + my ($prompt) = @_; + my $password; + $ENV{PATH} = "/bin:/usr/bin"; + $ENV{IFS} = " \t\n"; + $ENV{SHELL} = "/bin/sh"; + system "stty -echo"; + print $prompt; + chomp($password = <STDIN>); + print "\n"; + system "stty echo"; + $password; +} + +# ================================= +# sub CheckUnsafeFile +# tell if a config file containing a password is unsafe +# ================================= +sub CheckUnsafeFile { + my ($fname) = @_; + my ($dev, $ino, $mode, $nlink, + $uid, $gid, $rdev, $size, + $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname); + + if ( $uid != $< ) { # unsafe if owned by other than current user + return 1; + } + if ( $mode & 066 ) { # unsafe if accessible by other + return 1; + } + $fname =~ s#/[^/]+$##; + if ( (length $fname) > 0 ) { + return CheckUnsafeDir($fname); + } + return 0; +} + +# ================================= +# sub CheckUnsafeDir +# tell if a directory is unsafe +# ================================= +sub CheckUnsafeDir { + my ($fname) = @_; + my ($dev, $ino, $mode, $nlink, + $uid, $gid, $rdev, $size, + $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname); + + # not owned by me or root + if ( ($uid != $<) && ($uid != 0) ) { + return 1; + } + if ( $mode & 022 ) { # unsafe if writable by other + return 1 unless $mode & 01000; # but sticky bit ok + } + $fname =~ s#/[^/]+$##; + if ( (length $fname) > 0 ) { + return CheckUnsafeDir($fname); + } + return 0; +} + +# ================================= +# sub MergeConfigFile +# merge data from .cnf file +# ================================= +sub MergeConfigFile { + my ($fname) = @_; + my ($group, $item, $value); + if ( open CNF, $fname ) { + while (<CNF>) { + s/^\s+//; + next if /^[#;]/; + if ( /\[\s*(\w+)\s*]/ ) { + $group = $1; + $group =~ tr/A-Z/a-z/; + if ( !exists $MYSQL_CNF{$group} ) { + undef $group; + } + } elsif ( defined $group ) { + ($item, $value) = /((?:\w|-)+)\s*=\s*(\S+)/; + # don't unquote backslashes as we just write it back out + if ( defined $item ) { + if ( $item =~ /^password$/ ) { + if ( CheckUnsafeFile($fname) ) { + $unsafeConfig = $fname; + } + } + if ( $group eq 'client' || $group eq "client-server") { + $MYSQL_CNF{'mysql'}{$item} = $value; + $MYSQL_CNF{'mysqldump'}{$item} = $value; + } else { + $MYSQL_CNF{$group}{$item} = $value; + } + } + } + } + close(CNF); + } +} + +# ================================= +# sub MergeConfigFiles +# merge options from config files +# NOTE: really should do two separate merges for each +# client to exactly duplicate order of resulting argument lists +# ================================= +sub MergeConfigFiles { + my ($name,$pass,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) = getpwuid $<; + MergeConfigFile("@prefix@/my.cnf"); + MergeConfigFile("@sysconfdir@/my.cnf"); + MergeConfigFile("$dir/.my.cnf"); +} + +# ================================= +# sub WriteTempConfigFile +# write +# ================================= +sub WriteTempConfigFile { + sysopen CNFFILE, $MYSQL_CNF, O_RDWR|O_CREAT|O_EXCL, 0700 + or die "sysopen $MYSQL_CNF: $!"; + + # groups may be in any order, generic groups such as [client] assumed + # here to be empty + foreach $group (keys %MYSQL_CNF) { + print CNFFILE "[$group]\n"; + foreach $item (keys %{$MYSQL_CNF{$group}}) { + if ( defined $MYSQL_CNF{$group}{$item} ) { + print CNFFILE "$item=$MYSQL_CNF{$group}{$item}\n"; + } else { + print CNFFILE "$item\n"; + } + } + print CNFFILE "\n"; + } + close(CNFFILE); +} + +###################################################################### +package MySQLaccess::DB; +########### +BEGIN { + $DEBUG = 2; + $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG); + # Error-messages from the MySQL client + %ACCESS_ERR= ('Access_denied' => 'Access denied' + ,'Dbaccess_denied' => 'Access to database denied' + ,'Unrecognized_option' => 'unrecognized option' + ,'Unknown_table' => "Can't find file:" + ,'unknown_error' => '^ERROR:' + ); +} +# ###################################### +# Connecting to the MYSQL DB +# ====================================== +# sub OpenConnection +# Open an connection to the mysql-db +# questions to MYSQL_Q +# answers from MYSQL_A +# ====================================== +sub OpenConnection { + my $pid; + MySQLaccess::Debug::Print(2,"OpenConnection:"); + + # check path to mysql-client executable + if (! -f $MySQLaccess::MYSQL) { + if ($MySQLaccess::CMD) { die "Could not find MySQL-client '$MySQLaccess::MYSQL'"; } + if ($MySQLaccess::CGI) { + print "<center>\n<font color=Red>\n"; + print "ERROR: Could not find MySQL-client '$MySQLaccess::MYSQL'"; + print "</center>\n</font>\n"; + exit 0; + } + } + + # path to mysql executable + my $connect = "$MySQLaccess::MYSQL --defaults-file=$MySQLaccess::MYSQL_CNF"; + $connect .= " $MySQLaccess::MYSQL_OPT"; + # superuser, spassword transmitted via defaults-file + if (defined($MySQLaccess::Param{'rhost'})) { $connect .= " --host=$MySQLaccess::Param{'rhost'}"; } + # other options?? + + # grant-database + $connect .= " $MySQLaccess::ACCESS_DB"; + + # open connection (not using /bin/sh -c) + MySQLaccess::Debug::Print(2,"Connecting to: $connect"); + $pid=IPC::Open3::open3(\*MYSQL_Q,\*MYSQL_A,"",split /\s+/,$connect); + MySQLaccess::Debug::Print(2,"PID of open pipe: $pid"); + + # check connection + print MYSQL_Q "select 'ok';\n"; + $answer = <MYSQL_A>; #answer from mysql + MySQLaccess::Debug::Print(2,"Answer: $answer\n"); + foreach $nerror (sort(keys(%ACCESS_ERR))) { + MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}"); + if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { + MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]"); + return $nerror; + } + } + +if (0) { + # check server-version + print MYSQL_Q "select 'ok';\n"; + $answer = <MYSQL_A>; #answer from mysql + MySQLaccess::Debug::Print(2,"Answer: $answer\n"); + foreach $nerror (sort(keys(%ACCESS_ERR))) { + MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}"); + if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { + MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]"); + return $nerror; + } + } +} + + my $skip=<MYSQL_A>; + return 0; +} + +# ====================================== +# sub CloseConnection +# Close the connection to the mysql-db +# ====================================== +sub CloseConnection { + close MYSQL_Q; + close MYSQL_A; +} + +# =========================================================== +# sub CreateTable($table) +# Create temporary/backup table +# =========================================================== +sub CreateTable { + my $pid; + my ($table,$force) = @_; + my %tables = ( $MySQLaccess::ACCESS_U_TMP => $MySQLaccess::ACCESS_U, + $MySQLaccess::ACCESS_H_TMP => $MySQLaccess::ACCESS_H, + $MySQLaccess::ACCESS_D_TMP => $MySQLaccess::ACCESS_D, + $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U, + $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H, + $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D, + $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK, + $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK, + $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK, + ); + my $tbl; + my $query=""; + my $delim; + my $skip; + my $create; + my @known_tables=(); + +# print STDERR "CreateTable($table)\n"; + MySQLaccess::Debug::Print(1,"CreateTable($table):"); + + ## error-handling + return 'Unknown_table' unless defined($tables{$table}); + + ## build list of known/existing tables; + ## if 'force' existing table is dropped first + if (defined($force) and $force) { + @known_tables = Show_Tables(); + if (grep(/^$table$/,@known_tables)) { + $query = "DROP TABLE $table;"; + } + } + + ## path to mysqldump executable + my $connect = $MySQLaccess::MYSQLDUMP; + $connect .= " --defaults-file=$MySQLaccess::MYSQL_CNF --no-data"; + # superuser, spassword transmitted via defaults-file + if (defined($MySQLaccess::Param{'rhost'})) { $connect .= " --host=$MySQLaccess::Param{'rhost'}"; } + $connect .= " $MySQLaccess::ACCESS_DB"; + $connect .= " $tables{$table}"; + + + ## get creation-data for original table + $create = ''; + my $mysqldump = $connect; + $mysqldump =~ s/ \$TABLE / $tbl /; + + # open connection (not using /bin/sh -c) + MySQLaccess::Debug::Print(2,"Connecting to: $connect"); + $pid=IPC::Open3::open3(\*DONTCARE,\*CREATE,"",split /\s+/,$mysqldump); + MySQLaccess::Debug::Print(2,"PID of open pipe: $pid"); + #open(CREATE,"$mysqldump"); + @create = <CREATE>; + $create = "@create"; + foreach $nerror (sort(keys(%ACCESS_ERR))) { + MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}"); + if (grep(/$ACCESS_ERR{$nerror}/i,$create)) { + MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]"); + return $nerror; + } + } + close(CREATE); + close(DONTCARE); + + ## manipulate result for creation-data for temporary table + $create =~ s/CREATE TABLE $tables{$table} \(/CREATE TABLE $table \(/; + + ## recreate temporary table + $query .= "$create\n"; + $query .= "select 'ok';"; + + ## execute query + print MYSQL_Q "$query\n"; +# print STDERR $query; + + $answer = <MYSQL_A>; #answer from mysql +# print STDERR "A>",$answer; + MySQLaccess::Debug::Print(2,"Answer: $answer\n"); + foreach $nerror (sort(keys(%ACCESS_ERR))) { +# print STDERR "->$nerror?"; + MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}"); + if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { +# print STDERR "Yes!"; + MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]"); + return $nerror; + } + } + + $delim = <MYSQL_A>; # read header + if ($delim ne "ok\n") { + while (($line=<MYSQL_A>) ne "ok\n") + { MySQLaccess::Debug::Print(3," A> $line"); } + $skip = <MYSQL_A>; # skip result 'ok' + } +# print STDERR "CreateTable done\n"; + return 0; +} + + +# =========================================================== +# sub CopyTable() +# Copy the structure and the data of a table to another table +# =========================================================== +sub CopyTable { + my ($from,$to,$force) = @_; + my @known_tables = Show_Tables(); + my $query = ""; + my $nerror= 0; + my $skip; + +# print STDERR "CopyTable($from,$to)\n"; + MySQLaccess::Debug::Print(1,"MySQLaccess::DB::CopyTable($from,$to)"); + + ## error-handling + if (!grep(/^$from$/,@known_tables)) { return 'Unknown_table'; } + + ## copy structure + ## if forced + if (defined($force) and $force) { + return $nerror if ($nerror=CreateTable($to,$force)); +# print STDERR "Structure copied\n"; + } + + ## copy data + $query .= "DELETE FROM $to;"; + $query .= "INSERT INTO $to SELECT * FROM $from;"; + $query .= "SELECT 'ok';\n"; + MySQLaccess::Debug::Print(2,"Query: $query"); + + ## execute query + print MYSQL_Q "$query\n"; +# print STDERR $query; + + ## check for errors... + my $answer = <MYSQL_A>; #answer from mysql +# print STDERR $answer; + MySQLaccess::Debug::Print(2,"Answer: $answer\n"); + foreach $nerror (sort(keys(%ACCESS_ERR))) { + MySQLaccess::Debug::Print(3,"check answer for error $ACCESS_ERR{$nerror}"); + if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { + MySQLaccess::Debug::Print(2,"Answer contain error [$nerror]"); + return $nerror; + } + } + + my $delim = <MYSQL_A>; # read header +# print STDERR $delim; + if ($delim ne "ok\n") { + while (($line=<MYSQL_A>) ne "ok\n") + { MySQLaccess::Debug::Print(3," A> $line"); } + $skip = <MYSQL_A>; # skip result 'ok' + } + + return 0; +} + +# =========================================================== +# sub LoadTmpTables() +# (Re)load temporary tables with entries of ACL-tables +# =========================================================== +sub LoadTmpTables { + my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP, + $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP, + $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP, + ); + my $tbl; + my $nerror; + +# print STDERR "LoadTmpTables:\n"; + MySQLaccess::Debug::Print(1,"LoadTmpTables():"); + foreach $tbl (keys(%tables)) { +# print STDERR "$tbl -> $tables{$tbl}\n"; + MySQLaccess::Debug::Print(2,"Loading table $tbl -> $tables{$tbl}."); + return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force')); + } + return 0; +} + +# =========================================================== +# sub BackupGrantTables() +# Make a backup of the original grant-tables +# =========================================================== +sub BackupGrantTables { + my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK, + $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK, + $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK, + ); + my $tbl; + my $nerror; + +# print STDERR "BackupGrantTables:\n"; + MySQLaccess::Debug::Print(1,"BackupGrantTables():"); + foreach $tbl (keys(%tables)) { +# print STDERR "$tbl -> $tables{$tbl}\n"; + MySQLaccess::Debug::Print(2,"Backup table $tbl -> $tables{$tbl}."); + return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force')); + } + return 0; +} + +# =========================================================== +# sub RollbackGrantTables() +# Rollback the backup of the grant-tables +# =========================================================== +sub RollbackGrantTables { + my %tables = ( $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U, + $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H, + $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D, + ); + my $tbl; + my $nerror; + +# print STDERR "RollbackGrantTables:\n"; + MySQLaccess::Debug::Print(1,"RollbackGrantTables():"); + foreach $tbl (keys(%tables)) { +# print STDERR "$tbl -> $tables{$tbl}\n"; + MySQLaccess::Debug::Print(2,"Rollback table $tbl -> $tables{$tbl}."); + return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force')); + } + return 0; +} + + +# =========================================================== +# sub CommitGrantTables() +# Copy grant-rules from temporary tables to the ACL-tables +# =========================================================== +sub CommitGrantTables { + my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP, + $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP, + $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP, + ); + my $tbl; + my $query; + my $delim; + my $skip; + my $create; + + print STDERR "CommitGrantTables()\n"; + MySQLaccess::Debug::Print(1,"CommitGrantTables():"); + + ## Make backup of original grant-tables + MySQLaccess::Debug::Print(2,"Making backup of original grant-tables..."); + BackupGrantTables(); + + ## Copy data from temporay tables to grant-tables + foreach $tbl (keys(%tables)) { + print STDERR "$tbl -> $tables{$tbl}\n"; + MySQLaccess::Debug::Print(2,"Loading data $tables{$tbl} -> $tbl."); + return $nerror if ($nerror=CopyTable($tables{$tbl},$tbl)); + } + return 0; +} + + +# =========================================================== +# sub Show_Fields($table): +# return (a reference to) a hash which holds the names +# of all relevant grant-fields, with their index in the record, +# and (a reference to) an array which holds the fieldnames. +# =========================================================== +sub Show_Fields { + my ($table) = @_; + my %skip = ('host' => [0,1] + ,'user' => [0,1,2] + ,'db' => [0,1,2] + ); + my %Struct = (); + my @Struct = (); + my $query = "show fields from $table;select 'ok';\n"; + my $i=0; + my $line; + +#print STDERR $query; + MySQLaccess::Debug::Print(1,"Show_Fields($table):"); + MySQLaccess::Debug::Print(2,"SQL: $query"); + + print MYSQL_Q "$query"; + my $skip = <MYSQL_A>; #skip header + while (($line=<MYSQL_A>) ne "ok\n") + { +#print STDERR ">",$line; + chop($line); + MySQLaccess::Debug::Print(2," $table>: $line"); + my ($field,$type,$null,$key,$default,$extra) = split(' ',$line); + $field = ucfirst($field); + MySQLaccess::Debug::Print(3, " <split: $field - $type - $null - $key - $default - $extra"); + if (! grep(/$i/,@{$skip{$table}}) ){ + $Struct{$field} = $i; #hash + push(@Struct,$field); #array + MySQLaccess::Debug::Print(3," ==> added column[$i]: $field ($Struct{$field})"); + } + else { + MySQLaccess::Debug::Print(3," ==> skipped column[$i], value=[$field]"); + } + $i++; + } + + $skip=<MYSQL_A>; # Get ok row (found already ok header) + + MySQLaccess::Debug::Print(2, "Array:"); + foreach $field (@Struct) { MySQLaccess::Debug::Print(2,"+ $field"); } + MySQLaccess::Debug::Print(2,"Hash:"); + foreach $field (keys(%Struct)) { MySQLaccess::Debug::Print(2,"+ $field -> $Struct{$field}"); } + + return (\%Struct,\@Struct); +} + +# =========================================================== +# sub Show_Tables(): +# return (a reference to) an array which holds all +# known tables. +# =========================================================== +sub Show_Tables { + my @Tables = (); + my $query = "show tables;select 'ok';\n"; + my $i=0; + my $line; + + MySQLaccess::Debug::Print(1,"Show_Tables():"); + MySQLaccess::Debug::Print(2,"SQL: $query"); + + print MYSQL_Q "$query"; + my $skip = <MYSQL_A>; #skip header + while (($line=<MYSQL_A>) ne "ok\n") + { + chop($line); + push(@Tables,$line); #array + MySQLaccess::Debug::Print(3," ==> added table: $line"); + } + + $skip=<MYSQL_A>; # Get ok row (found already ok header) + + MySQLaccess::Debug::Print(2, "Array:"); + foreach $tbl (@Tables) { MySQLaccess::Debug::Print(2,"+ $tbl"); } + + return @Tables; +} + +# ====================================== +# sub Validate_Password($passwd,$host,$user,$encpw) +# Validate the given password +# for user '$user' +# connecting from host '$host' +# ====================================== +sub Validate_Password { + my ($password,$host,$user,$encpw) = @_; + my $valid=0; + + MySQLaccess::Debug::Print(1,"Validate_Password($password,$host,$user,$encpw)"); + my $sql = "select host,user,password from user having " + ."host='$host' and user='$user' and password='$encpw' " + ."and password=PASSWORD('$password');\n"; + $sql .= "select 'ok';\n"; + MySQLaccess::Debug::Print(2,"SQL = $sql"); + print MYSQL_Q "$sql"; + + # if password is valid, at least 1 row returns before we read 'ok' + while ( ($line=<MYSQL_A>) ne "ok\n") { + MySQLaccess::Debug::Print(2," A> $line"); + $valid = defined($line); + } + my $skip = <MYSQL_A>; # read 'ok' + + return $valid; +} + + +# ========================================================== +# sub Sort_fields: (rewritten by psmith) +# Build the query for an ordered list of entries +# ========================================================== +sub Sort_fields { + my ($start, $end, $sofar, $this, @rest) = (@_); + my @where = ("((FIELD not like '\\%') AND (FIELD <> ''))", + "((FIELD like '%\\%%') OR (FIELD like '%\\_%'))", + "(FIELD = '')"); + my $res = ''; + + $this or return ("$start $sofar $end"); + + $sofar .= ' AND ' if $sofar; + + foreach $w (@where) { + my $f = $w; + $f =~ s/FIELD/$this/g; + + $res .= Sort_fields($start, $end, "$sofar$f", @rest); + } + + return ($res); +} + +# =========================================================== +# sub Sort_table: (rewritten by psmith) +# return all entries in the given table, +# in an ordered fashion +# =========================================================== +sub Sort_table { + my ($tbl, @order) = @_; + my @res=(); + + # as long as there's no full where clause (Distrib 3.20)... + # use having :-( + # NOTE: this clause WILL NOT work on 3.21, because of the + # order of 'ORDER BY' and 'HAVING' + my $start = "SELECT *,UCASE(host) as ucase_host FROM $tbl "; + $start .= 'ORDER BY ' . join(',', @order) ." HAVING "; + my $end = ";\n"; + + # server version 3.21 has a full where clause :-) + if ($MySQLaccess::Host::SERVER >= '3.21') { + # print "+++USING FULL WHERE CLAUSE+++\n"; + $start = "SELECT *,UCASE(host) as ucase_host FROM $tbl WHERE "; + $end = ' ORDER BY ' . join(',', @order) . ";\n"; + } + + MySQLaccess::Debug::Print(1,"Sort_table():"); + MySQLaccess::Debug::Print(2,"Sorting table $tbl by `@order'"); + + my $tmp; + foreach $tmp (@order) + { + $tmp="UCASE(host)" if ($tmp eq "ucase_host"); + } + my $query = Sort_fields($start, $end, '', @order); + $query .= "select 'ok';\n"; + MySQLaccess::Debug::Print(2,"Query: $query"); + + print MYSQL_Q "$query\n"; + + my $delim = <MYSQL_A>; # read header + MySQLaccess::Debug::Print(3," A> $delim"); + if ($delim ne "ok\n") { + if ($delim =~ /^ERROR/) { + push(@MySQLaccess::Grant::Error,'use_old_server'); + MySQLaccess::Report::Print_Error_Messages() ; + exit 1; + } + while (($line=<MYSQL_A>) ne "ok\n") + { + MySQLaccess::Debug::Print(3," A> $line"); + push(@res,$line); + } + } + my $skip = <MYSQL_A>; # skip result 'ok' + + # remove columnheaders from output + @res = grep(!/^\Q$delim\E$/, @res); + # remove trailing \n from each returned record + chomp(@res); + # each record has 1 field to much : ucase_host + @res = grep { /(.*)\t.*$/; $_ = $1; } @res; + + MySQLaccess::Debug::Print(2,"Result of sorted table $tbl:"); + foreach $line (@res) { MySQLaccess::Debug::Print(2," >>$line"); } + return @res; +} + +# =========================================================== +# sub Get_All_db(template): +# return all db the grant-tables are working on, +# which conform to the template +# =========================================================== +sub Get_All_dbs { + my ($template,$tmp) = @_; + my @db=(); + my $aref; + + # working with temporary tables or production tables + if (defined($tmp) and $tmp) { + $aref = \@MySQLaccess::Grant::sorted_db_tmp_table ; + } + else { + $aref = \@MySQLaccess::Grant::sorted_db_table; + } + + MySQLaccess::Debug::Print(1," template=[$template]"); + + # get all db for which access-rights can be calculated, + # which conform to the template. + # !! these db's don't have to exist yet, so it's not + # enough to look which db already exist on the system + $reg_expr = $template; + if ($template =~ /[\*\?]/) { + $reg_expr =~ tr/*?/%_/; + #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template); + } + $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr"); + + if ( ! ($template =~ /[\*\?%_]/) ) { + push(@db,$template); + return \@db; + } + + MySQLaccess::Debug::Print(2,"#Reading db-table..."); + foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_db_table) { + my @record=split(/\t/,$record); + my $db = $record[1]; + MySQLaccess::Debug::Print(2,"> $db "); + if ( (!grep(/$db/i,@db)) and ($db =~/$reg_expr/i) ) { + push(@db,$db); + MySQLaccess::Debug::Print(2,"added"); + } + else { + MySQLaccess::Debug::Print(2,"skipped"); + } + } + # if no rule is found for a certain db in the db-table, + # the rights of the user are used, so we should inform + # the user for + if (!grep(/^%$/,@db)) { push(@db,"$MySQLaccess::NEW_DB"); } + return \@db; +} + +# =========================================================== +# sub Get_All_users(template): +# return all users the grant-tables are working on, +# which conform to the template +# =========================================================== +sub Get_All_users { + ($template,$tmp) = @_; # nog verder uitwerken!!! + my @user=(); + my $aref; + + # working with temporary tables or production tables + if (defined($tmp) and $tmp) { + $aref = \@MySQLaccess::Grant::sorted_user_tmp_table ; + } + else { + $aref = \@MySQLaccess::Grant::sorted_user_table; + } + + MySQLaccess::Debug::Print(1,"Debug Get_All_users:"); + # get all db for which access-rights can be calculated. + # !! these db's don't have to exist yet, so it's not + # enough to look which db already exist on the system + $reg_expr = $template; + if ($template =~ /[\*\?]/) { + $reg_expr =~ tr/*?/%_/; + #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template); + } + $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr"); + + if ( ! ($template =~ /[\*\?%_]/) ) { + push(@user,$template); + return \@user; + } + + MySQLaccess::Debug::Print(2,"#Reading user-table..."); + foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_user_table) { + my @record=split(/\t/,$record); + my $user = $record[1]; + MySQLaccess::Debug::Print(2,"> $user "); + if ( (!grep(/$user/,@user)) and ($user=~/$reg_expr/)) { + push(@user,$user); + MySQLaccess::Debug::Print(2, "added"); + } + else { + MySQLaccess::Debug::Print(2, "skipped"); + } + } + # Any user means also: + # - the 'empty' user, ie without supplying a username + # - any user still to be defined/created + #push(@user,''); #without_suplying_a_username + push(@user,"$MySQLaccess::NEW_USER"); + #push(@Warnings,'minimum_priv'); + return \@user; +} + +# =========================================================== +# sub Get_All_hosts(template): +# return all hosts the grant-tables are working on, +# which conform to the template +# =========================================================== +sub Get_All_hosts { + my ($template,$tmp) = @_; + my @host=(); + my $aref; + my $aref1; + + # working with temporary tables or production tables + if (defined($tmp) and $tmp) { + $aref = \@MySQLaccess::Grant::sorted_host_tmp_table ; + $aref1= \@MySQLaccess::Grant::sorted_db_tmp_table ; + } + else { + $aref = \@MySQLaccess::Grant::sorted_host_table; + $aref1= \@MySQLaccess::Grant::sorted_db_table ; + } + + MySQLaccess::Debug::Print(1, "Debug Get_All_hosts:"); + # get all db for which access-rights can be calculated. + # !! these db's don't have to exist yet, so it's not + # enough to look which db already exist on the system + $reg_expr = $template; + if ($template =~ /[\*\?]/) { + $reg_expr =~ tr/*?/%_/; + #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template); + } + $reg_expr = MySQLaccess::Wildcards::SQL2Reg("$reg_expr"); + + if ( ! ($template =~ /[\*\?%_]/) ) { + push(@host,$template); + return \@host; + } + + MySQLaccess::Debug::Print(1, "#Reading db-table..."); + foreach $record (@{$aref1}) { #MySQLaccess::Grant::sorted_db_table) { + my @record=split(/\t/,$record); + my $host = $record[0]; + MySQLaccess::Debug::Print(2, "> $host "); + if (! grep(/$host/i,@host)) { + push(@host,$host); + MySQLaccess::Debug::Print(2, "added"); + } + else { + MySQLaccess::Debug::Print(2, "skipped"); + } + } + MySQLaccess::Debug::Print(1, "#Reading host-table..."); + foreach $record (@{$aref}) { + my @record=split(/\t/,$record); + my $host = $record[0]; + MySQLaccess::Debug::Print(2, "> $host "); + if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) { + push(@host,$host); + MySQLaccess::Debug::Print(2, "added"); + } + else { + MySQLaccess::Debug::Print(2, "skipped"); + } + } + # DOUBT: + #print "#Reading user-table...\n" if ($DEBUG>1); + #foreach $record (@MySQLaccess::Grant::sorted_user_table) { + # my @record=split(/\t/,$record); + # my $host = $record[0]; + # print "> $host " if ($DEBUG>2); + # if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) { + # push(@host,$host); + # print "added\n" if ($DEBUG>2); + # } + # else { + # print "skipped\n" if ($DEBUG>2); + # } + #} + # Any host also means: + # - any host still to be defined/created + #push(@host,"any_other_host"); + + @host = sort(@host); + return \@host; +} + + +########################################################################## +package MySQLaccess::Grant; +############## +BEGIN { + $DEBUG = 0; + $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG); +} + + + +# =========================================================== +# sub Diff_Privileges() +# Calculate diff between temporary and original grant-tables +# =========================================================== +sub Diff_Privileges { + my @before=(); + my @after =(); + my @diffs =(); + + # ----------------------------- + # Build list of users,dbs,hosts + # to process... + my @all_dbs = @{MySQLaccess::DB::Get_All_dbs('*')}; + my @all_users = @{MySQLaccess::DB::Get_All_users('*')}; + my @all_hosts = @{MySQLaccess::DB::Get_All_hosts('*')}; + #if EDIT-mode + my @all_dbs_tmp = @{MySQLaccess::DB::Get_All_dbs('*','tmp')}; + my @all_users_tmp = @{MySQLaccess::DB::Get_All_users('*','tmp')}; + my @all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts('*','tmp')}; + + + my %Access; + # ------------------------------------ + # Build list of priv. for grant-tables + foreach $host (@all_hosts) { + foreach $user (@all_users) { + foreach $db (@all_dbs) { + MySQLaccess::Grant::Initialize(); + %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db); + push(@before,MySQLaccess::Report::Raw_Report($host,$user,$db,\%Access)); + } + } + } + + # ---------------------------------- + # Build list of priv. for tmp-tables + foreach $host (@all_hosts_tmp) { + foreach $user (@all_users_tmp) { + foreach $db (@all_dbs_tmp) { + MySQLaccess::Grant::Initialize('tmp'); + %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db,'tmp'); + push(@after,MySQLaccess::Report::Raw_Report($host,$user,$db,\%Access)); + } + } + } + + # ---------------------------------- + # Write results to temp-file to make + # DIFF + @before = sort(@before); + @after = sort(@after); + + ($hb, $before) = tempfile("$MySQLaccess::script.XXXXXX") or + push(@MySQLaccess::Report::Errors,"Can't create temporary file: $!"); + ($ha, $after) = tempfile("$MySQLaccess::script.XXXXXX") or + push(@MySQLaccess::Report::Errors,"Can't create temporary file: $!"); + + print $hb join("\n",@before); + print $ha join("\n",@after); + close $hb; + close $ha; + + # ---------------------------------- + # compute difference + my $cmd="$MySQLaccess::DIFF $before $after |"; + open(DIFF,"$cmd"); + @diffs = <DIFF>; + @diffs = grep(/[<>]/,@diffs); + chomp(@diffs); + close(DIFF); + + # ---------------------------------- + # cleanup temp. files + unlink($before); + unlink($after); + + return \@diffs; +} + +# =========================================================== +# sub Initialize() +# +# =========================================================== +sub Initialize { + %MySQLaccess::Grant::Access = %{Default_Access_Rights()}; + @MySQLaccess::Grant::Errors = (); + @MySQLaccess::Grant::Warnings = (); + @MySQLaccess::Grant::Notes = (); + # ----- + # rules + $MySQLaccess::Grant::Rules{'user'} = 'no_rule_found'; + $MySQLaccess::Grant::Rules{'db'} = 'no_rule_found'; + $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host'; + $MySQLaccess::Grant::full_access = 1; + + $MySQLaccess::Grant::process_host_table = 0; + return 1; +} + +# =========================================================== +# sub ReadTables() +# +# =========================================================== +sub ReadTables { + my ($tmp) = @_; + my ($HOST,$DB,$USER); + my @tables; + + # build list of available tables + @tables = MySQLaccess::DB::Show_Tables(); + + # reading production grant-tables or temporary tables? + $tmp = (defined($tmp) and $tmp) ? 1 : 0; + if ($tmp) { #reading temporary tables + $HOST=$MySQLaccess::ACCESS_H_TMP; + $DB =$MySQLaccess::ACCESS_D_TMP; + $USER=$MySQLaccess::ACCESS_U_TMP; + + # ---------------------------- + # do tables exist? + if (!grep(/$HOST/,@tables)) { MySQLaccess::DB::CreateTable($HOST); } + if (!grep(/$USER/,@tables)) { MySQLaccess::DB::CreateTable($USER); } + if (!grep(/$DB/,@tables)) { MySQLaccess::DB::CreateTable($DB); } + + MySQLaccess::Debug::Print(1,"Finding fields in tmp-ACL files:"); + # ----------------------------- + # Get record-layout + my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST); + my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB); + my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER); + %MySQLaccess::Grant::H_tmp = %{$h1}; @MySQLaccess::Grant::H_tmp = @{$h2}; + %MySQLaccess::Grant::D_tmp = %{$d1}; @MySQLaccess::Grant::D_tmp = @{$d2}; + %MySQLaccess::Grant::U_tmp = %{$u1}; @MySQLaccess::Grant::U_tmp = @{$u2}; + +# @MySQLaccess::Grant::Privileges_tmp=@{Make_Privlist()}; +# + MySQLaccess::Debug::Print(1, "Reading sorted temp-tables:"); + @MySQLaccess::Grant::sorted_db_tmp_table = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db'); + @MySQLaccess::Grant::sorted_host_tmp_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db'); + @MySQLaccess::Grant::sorted_user_tmp_table= defined($MySQLaccess::Param{'password'}) ? + MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'): + MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user'); + } + else { #reading production grant-tables + $HOST=$MySQLaccess::ACCESS_H; + $DB =$MySQLaccess::ACCESS_D; + $USER=$MySQLaccess::ACCESS_U; + + MySQLaccess::Debug::Print(1,"Finding fields in ACL files:"); + # ----------------------------- + # Get record-layout + my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST); + my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB); + my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER); + %MySQLaccess::Grant::H = %{$h1}; @MySQLaccess::Grant::H = @{$h2}; + %MySQLaccess::Grant::D = %{$d1}; @MySQLaccess::Grant::D = @{$d2}; + %MySQLaccess::Grant::U = %{$u1}; @MySQLaccess::Grant::U = @{$u2}; + + @MySQLaccess::Grant::Privileges=@{Make_Privlist()}; + + MySQLaccess::Debug::Print(1, "Reading sorted tables:"); + @MySQLaccess::Grant::sorted_db_table = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db'); + @MySQLaccess::Grant::sorted_host_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db'); + @MySQLaccess::Grant::sorted_user_table= defined($MySQLaccess::Param{'password'}) ? + MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'): + MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user'); + } + + return 0; +} + +# =========================================================== +# sub Get_Access_Rights(host,user,db) +# report the access_rights for the tuple ($host,$user,$db). +# =========================================================== +sub Get_Access_Rights { + local ($host,$user,$db,$tmp) = @_; + + my $aref_user; + my $aref_host; + my $aref_db; + # working with temporary tables or production tables + if (defined($tmp) and $tmp) { + $aref_user = \@MySQLaccess::Grant::sorted_user_tmp_table; + $aref_host = \@MySQLaccess::Grant::sorted_host_tmp_table; + $aref_db = \@MySQLaccess::Grant::sorted_db_tmp_table; + } + else { + $aref_user = \@MySQLaccess::Grant::sorted_user_table; + $aref_host = \@MySQLaccess::Grant::sorted_host_table; + $aref_db = \@MySQLaccess::Grant::sorted_db_table; + } + + + my ($refrecord,$refgrant); + my ($_host_,$_user_,$encpw_); + my %_Access_; + + MySQLaccess::Debug::Print(1, "for ($host,$user,$db):"); + + # ****************************************************************************** + # Create default access-rights + # default access-rights are no access at all!! + + + # ****************************************************************************** + # get hostname for IP-address + # get IP-address for hostname + local $host_name = MySQLaccess::Host::IP2Name($host); + local $host_ip = MySQLaccess::Host::Name2IP($host); + + MySQLaccess::Debug::Print(3,"host=$host, hostname=$host_name, host-ip =$host_ip"); + MySQLaccess::Debug::Print(3,"user=$user"); + MySQLaccess::Debug::Print(3,"db =$db"); + + # *********************************************************************** + # retrieve information on USER + # check all records in mysql::user for matches with the tuple (host,user) + # *********************************************************************** + # 4.OR (add) the privileges for the user from the "user" table. + # (add all privileges which is "Y" in "user") + ($refrecord,$refgrant) = Get_grant_from_user($host,$user,$aref_user); + ($_host_,$_user_,$encpw_) = @{$refrecord}; + %_access_ = %{$refgrant}; + + foreach $field (keys(%U)) { ##only priv. set in user-table + $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field}); + } + + if ($_user_ eq $MySQLaccess::NEW_USER) { + push(@Warnings,'minimum_priv'); + } + if ($_user_ ne $user) { + $user=$_user_; + push(@Warnings,'anonymous_access'); + } + + # ******************************************************* + # Validate password if this has been asked to do + # ******************************************************* + if (defined($password)) { + $valid = Validate_Password($password,$_host_,$_user_,$_encpw_,$aref_user); + if (!$valid) { push(@Errors,'invalid_password'); } + else { push(@Notes,'valid_password'); } + } + + # ****************************************************************************** + # retrieve information on DB + # check all records in mysql::db for matches with the triple (host,db,user) + # first match is used. + # ****************************************************************************** + # 2.Get grant for user from the "db" table. + + ($refrecord,$refgrant)=Get_grant_from_db($host,$db,$user,$aref_db); #set process_host_table + ($_host_,$_user_,$encpw_) = @{$refrecord}; + %_access_ = %{$refgrant}; + + foreach $field (keys(%D)) { ##only priv. set in db-table + $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field}); + } + + # *********************************************************************** + # retrieve information on HOST + # check all records in mysql::host for matches with the tuple (host,db) + # + # ' The host table is mainly to maintain a list of "secure" servers. ' + # *********************************************************************** + # 3.If hostname is "empty" for the found entry, AND the privileges with + # the privileges for the host in "host" table. + # (Remove all which is not "Y" in both) + + if ($MySQLaccess::Grant::process_host_table) { + ($refrecord,$refgrant)=Get_grant_from_host($host,$db,$aref_host); + ($_host_,$_user_,$encpw_) = @{$refrecord}; + %_access_ = %{$refgrant}; + + foreach $field (keys(%H)) { ##only priv. set in host-table + $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} and $_access_{$field}); + } + } + + MySQLaccess::Debug::Print(1,"done for ($host,$user,$db)"); + return %MySQLaccess::Grant::Access; +} + +# #################################### +# FINDING THE RIGHT GRANT-RULE +# ========================================================== +# sub Get_grant_from_user: +# ========================================================== +sub Get_grant_from_user { + my ($host,$user,$aref) = @_; + + MySQLaccess::Debug::Print(1, ""); + MySQLaccess::Debug::Print(1, "(host=$host,user=$user)"); + + my %Access_user = %{Default_Access_Rights()}; + + my $rule_found=0; + my @record = (); + my $record; + + foreach $record (@{$aref}) { + $MySQLaccess::Grant::full_access=0; + MySQLaccess::Debug::Print(3, "Record= $record"); + @record=split(/\t/,$record); + + # check host and db + # with possible wildcards in field + # replace mysql-wildcards by reg-wildcards + my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]); + my $user_tpl = $record[1]; #user field isn't pattern-matched!! + my $passwd = $record[2]; + + MySQLaccess::Debug::Print(3, "=>host_tpl : read=$record[0] -> converted=$host_tpl"); + MySQLaccess::Debug::Print(3, "=>user_tpl : read=$record[1] -> $user_tpl"); + MySQLaccess::Debug::Print(3, "=>password : read=$record[2] -> $passwd"); + + + if ( MySQLaccess::Host::MatchTemplate($host,$host_tpl) and + MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user) + ) + { + MySQLaccess::Debug::Print(2, "FOUND!!"); + if ($passwd eq '') { push(@Warnings,'insecure_user'); } + else { push(@Notes,'password_required'); } + + foreach $field (keys(%U)) { + $Access_user{$field} = $MySQLaccess::Report::Answer{$record[$U{$field}]}; + } + #print "\n" if $DEBUG; + $MySQLaccess::Grant::Rules{'user'} = $record; + $rule_found=1; + last; + } + } + + # ------------------------------- + # setting privileges to user-priv + MySQLaccess::Debug::Print(2, "Rights after parsing user-table..:"); + if (! $rule_found ) { + @record=(); + MySQLaccess::Debug::Print(2, "NO record found in the user-table!!"); + } + else { + MySQLaccess::Debug::Print(2, "Selected record=@record"); + MySQLaccess::Debug::Print(2, "<=?=> $record"); + } + + MySQLaccess::Debug::Print(1, "returning @record"); + + return (\@record,\%Access_user); #matching record in user-table +} + +# ========================================================== +# sub Get_grant_from_db: +# ========================================================== +sub Get_grant_from_db { + my ($host,$db,$user,$aref) = @_; + + MySQLaccess::Debug::Print(1, "(host=$host,user=$user,db=$db)"); + + my %Access_db = %{Default_Access_Rights()}; + my $rule_found=0; + + foreach $record (@{$aref}) { + $full_access=0; + MySQLaccess::Debug::Print(2, "Read db: $record"); + @record=split(/\t/,$record); + + # check host and db + # with possible wildcards in field + # replace mysql-wildcards by reg-wildcards + my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]); + my $db_tpl = MySQLaccess::Wildcards::SQL2Reg($record[1]); + my $user_tpl = $record[2]; #user field isn't pattern matched!! + MySQLaccess::Debug::Print(3, "=>host_tpl : read=$record[0] -> converted=$host_tpl"); + MySQLaccess::Debug::Print(3, "=>db_tpl : read=$record[1] -> $db_tpl"); + MySQLaccess::Debug::Print(3, "=>user_tpl : read=$record[2] -> $user_tpl"); + + if ( ( MySQLaccess::Host::Is_localhost($host_tpl) + or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name) + or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) ) + and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) ) + and ( MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user) ) ) { + + $MySQLaccess::Grant::process_host_table = ($record[0] eq ''); + + if ($user_tpl eq '') { push(@Warnings,'public_database'); } + + foreach $field (keys(%D)) { + $Access_db{$field} = $MySQLaccess::Report::Answer{$record[$D{$field}]}; + } + $rule_found=1; + $MySQLaccess::Grant::Rules{'db'} = $record; + last; + } + } + + # ------------------------------- + # setting privileges to db-priv + MySQLaccess::Debug::Print(2, "Rights after parsing db-table..:"); + if (! $rule_found ) { + MySQLaccess::Debug::Print(2, "NO rule found in db-table => no access granted!!"); + } + + return (\@record,\%Access_db); +} + +# ========================================================== +# sub Get_grant_from_host: +# ========================================================== +sub Get_grant_from_host { + my ($host,$db,$aref) = @_; + + MySQLaccess::Debug::Print(1, "Get_grant_from_host()"); + + my %Access_host = %{Default_Access_Rights()}; + + # the host-table doesn't have to be processed if the host-field + # in the db-table isn't empty + if (!$MySQLaccess::Grant::process_host_table) { + MySQLaccess::Debug::Print(2, ">> Host-table doesn't have to be processed!!"); + $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host'; + return ([],\%Access_host); + } + + my $rule_found=0; + my @record = (); + + foreach $record (@{$aref}) { + $full_access=0; + MySQLaccess::Debug::Print(2, "host: $record"); + @record=split(/\t/,$record); + + # check host and db + # with possible wildcards in field + # replace mysql-wildcards by reg-wildcards + my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]); + my $db_tpl = MySQLaccess::Wildcards::SQL2Reg($record[1]); + MySQLaccess::Debug::Print(3, "=>host_tpl : $record[0] -> $host_tpl"); + MySQLaccess::Debug::Print(3, "=>db_tpl : $record[1] -> $db_tpl"); + + if ( ( MySQLaccess::Host::Is_localhost($host_tpl) + or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name) + or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) ) + and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) ) ) { + + $MySQLaccess::Grant::Rules{'host'} = $record; + $rule_found=1; + foreach $field (keys(%H)) { + $Access_host{$field} = $MySQLaccess::Report::Answer{$record[$H{$field}]}; + } + last; + } + } + + # ------------------------------- + # setting privileges to host-priv + MySQLaccess::Debug::Print(2, "Rights after parsing host-table..:"); + if (! $rule_found ) { + @record=(); + MySQLaccess::Debug::Print(2, "NO restrictions found in the host-table!!"); + } + + # -------------------------------- + # debugging access-rights in db + + return (\@record,\%Access_host); #matching record in host-table +} + + + +# =========================================================== +# sub Default_Access_Rights(): +# return (a reference to) a hash which holds all default +# priviliges currently defined in the grant-tables. +# =========================================================== +sub Default_Access_Rights { + my %right = (); + + MySQLaccess::Debug::Print(2, "Debug Default_Access_Rights():"); + # add entry for all fields in the HOST-table + foreach $field (keys(%MySQLaccess::Grant::H)) { + $right{$field}='0' unless (defined($right{$field})); + } + # add entry for all fields in the DB-table + foreach $field (keys(%MySQLaccess::Grant::D)) { + $right{$field}='0' unless (defined($right{$field})); + } + # add entry for all fields in the USER-table + foreach $field (keys(%MySQLaccess::Grant::U)) { + $right{$field}='0' unless (defined($right{$field})); + } + # -------------- + # debugging info + foreach $field (keys(%right)) { MySQLaccess::Debug::Print(3, sprintf("> %15s : %1s",$field,$right{$field})); } + + return \%right; +} + +# ====================================== +# sub Make_Privlist +# Make an ordered list of the privileges +# that should be reported +# ====================================== +sub Make_Privlist { + # layout: + #'select_priv', 'create_priv', + #'insert_priv', 'drop_priv', + #'update_priv', 'reload_priv', + #'delete_priv', 'process_priv', + #'file_priv', 'shutdown_priv'); + my $right; + my @privlist=(); + foreach $right (@U) { + if (! grep(/$right/,@privlist)) { push(@privlist,$right); } + }; + foreach $right (@D) { + if (! grep(/$right/,@privlist)) { push(@privlist,$right); } + }; + foreach $right (@H) { + if (! grep(/$right/,@privlist)) { push(@privlist,$right); } + }; +# print "Privileges:\n"; +# foreach $field (@privlist) { print " > $field\n"; } + return \@privlist; +} + + + +######################################################################## +package MySQLaccess::Report; +use Exporter (); +@EXPORT = qw(&Print_Header()); +BEGIN { + $FORM = $ENV{'SCRIPT_NAME'}; + $DEBUG = 0; + $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG); + + # translation-table for poss. answers + %Answer = ('Y' => 1 , 'N' => 0 + , 1 => 'Y', 0 => 'N' + ,'?' => '?', '' => '?' + ); + $headers = 0; + $separator = 0; + +# **************************** +# Notes and warnings +%MESSAGES = ( + 'insecure_user' + => "Everybody can access your DB as user `\$user' from host `\$host'\n" + ."WITHOUT supplying a password.\n" + ."Be very careful about it!!" + ,'password_required' + => "A password is required for user `\$user' :-(" + ,'invalid_password' + => "The password '\$password' for user `\$user' is invalid :-P" + , 'valid_password' + => "You supplied the right password for user `\$user' :-)" + ,'public_database' + => "Any user with the appropriate permissions has access to your DB!\n" + ."Check your users!" + ,'full_access' + => "All grant-tables are empty, which gives full access to ALL users !!" + ,'no_rule_found' + => "No matching rule" + ,'no_equiv_host' + => "Not processed: host-field is not empty in db-table." + ,'least_priv' + => "If the final priveliges of the user are more then you gave the user,\n" + ."check the priveliges in the db-table `\$db'." + ,'minimum_priv' + => "The privileges for any new user are AT LEAST\n" + ."the ones shown in the table above,\n" + ."since these are the privileges of the db `\$db'.\n" + ,'not_found_mysql' + => "The MySQL client program <$MySQLaccess::MYSQL> could not be found.\n" + ."+ Check your path, or\n" + ."+ edit the source of this script to point \$MYSQL to the mysql client.\n" + ,'not_found_mysqldump' + => "The MySQL dump program <$MySQLaccess::MYSQLDUMP> could not be found.\n" + ."+ Check your path, or\n" + ."+ edit the source of this script to point \$MYSQLDUMP to the mysqldump program.\n" + ,'not_found_diff' + => "The diff program <$MySQLaccess::DIFF> could not be found.\n" + ."+ Check your path, or\n" + ."+ edit the source of this script to point \$DIFF to the diff program.\n" + ,'Unrecognized_option' + => "Sorry,\n" + ."You are using an old version of the mysql-program,\n" + ."which does not yet implement a neccessary option.\n" + ."\n" + ."You need at least Version 6.2 of the mysql-client,\n" + ."which was build in MySQL v3.0.18, to use this version\n" + ."of `$MySQLaccess::script'." + ,'Access_denied' + => "Sorry,\n" + ."An error occurred when trying to connect to the database\n" + ."with the grant-tables:\n" + ."* Maybe YOU do not have READ-access to this database?\n" + ."* If you used the -U option, you may have supplied an invalid username?\n" + ." for the superuser?\n" + ."* If you used the -U option, it may be possible you have to supply\n" + ." a superuser-password to, with the -P option?\n" + ."* If you used the -P option, you may have supplied an invalid password?\n" + ,'Dbaccess_denied' + => "Sorry,\n" + ."An error occurred when trying to connect to the database\n" + ."with the grant-tables. (dbaccess denied)\n" + ,'Unknown_tmp_table' + => "Sorry,\n" + ."An error occurred when trying to work with the temporary tables in the database\n" + ."with the grant-tables. (One of the temporary tables does not exist)\n" + ,'Unknown_table' + => "Sorry,\n" + ."An error occurred when trying to work with some tables in the database\n" + ."with the grant-tables. (table does not exist)\n" + ,'use_old_server' + => "Sorry,\n" + ."An error occurred when executing an SQL statement.\n" + ."You might consider altering the use of the parameter `--old_server' when \n" + ."calling `$MySQLaccess::script'." + ,'unknown_error' + => "Sorry,\n" + ."An error occurred when trying to connect to the database\n" + ."with the grant-tables. (unknown error)\n" + ,'anonymous_access' + => "Accessing the db as an anonymous user.\n" + ."Your username has no relevance\n" + ,'user_required' + => "You have to supply a userid." + ,'db_required' + => "You have to supply the name of a database." + ,'host_required' + => "You have to supply the name of a host." + ); + + +} +# ===================================== +# sub Print_Header: +# print header info +# ===================================== +sub Print_Header { + if ($MySQLaccess::CMD) { #command-line mode + print "$MySQLaccess::script Version $MySQLaccess::VERSION\n" + ."By RUG-AIV, by Yves Carlier (Yves.Carlier\@rug.ac.be)\n" + ."Changes by Steve Harvey (sgh\@vex.net)\n" + ."This software comes with ABSOLUTELY NO WARRANTY.\n"; + } + if ($MySQLaccess::CGI) { #CGI-BIN mode + print "content-type: text/html\n\n" + . "<HTML>\n" + ."<HEAD>\n" + ."<TITLE>MySQLaccess</TITLE>\n" + ."</HEAD>\n" + ."<BODY>\n" + ."<H1>$MySQLaccess::script Version $MySQLaccess::VERSION</H1>\n" + ."<CENTER>\n<ADDRESS>\n" + ."By RUG-AIV, by Yves Carlier (<a href=mailto:Yves.Carlier\@rug.ac.be>Yves.Carlier\@rug.ac.be</a>)<BR>\n" + ."Changes by Steve Harvey (<a href=mailto:sgh\@vex.net>sgh\@vex.net</a>)<BR>\n" + ."This software comes with ABSOLUTELY NO WARRANTY.<BR>\n" + ."</ADDRESS>\n</CENTER>\n" + ."<HR>\n"; + Print_Taskbar(); + print "<HR>\n"; + } + return 1; +} + +# ===================================== +# sub Print_Footer: +# print footer info +# ===================================== +sub Print_Footer { + if ($MySQLaccess::CMD) { #command-line mode + print "\n" + ."BUGs can be reported at https://jira.mariadb.org\n"; + } + if ($MySQLaccess::CGI) { #CGI-BIN mode + if ($MySQLaccess::Param{'brief'}) { + print "</table>\n"; #close table in brief-output + } + print "<HR>\n" + ."<ADDRESS>\n" + ."BUGs can be reported at <a href=\"https://jira.mariadb.org\">MariaDB JIRA</a><BR>\n" +# ."Don't forget to mention the version $VERSION!<BR>\n" + ."</ADDRESS>\n" + ."</BODY>\n" + ."</HTML>\n"; + } + return 1; +} + +# ===================================== +# sub Print_Taskbar: +# print taskbar on STDOUT +# ===================================== +sub Print_Taskbar { + print "<CENTER>\n" + ."[<a href=$FORM?relnotes=on>Release Notes</a>] \n" + ."[<a href=$FORM?version=on>Version</a>] \n" + ."[<a href=$FORM?plan=on>Future Plans</a>] \n" + ."[<a href=$FORM?howto=on>Examples</a>] \n" + ."[<a href=$FORM?help=on>New check</a>] \n" + ."[<a href=$FORM?edit=on>Change/edit ACL</a>] \n" + ."</CENTER>\n"; + return 1; +} + +# ===================================== +# sub Print_Form: +# print CGI-form +# ===================================== +sub Print_Form { +print <<EOForm; +<center> +<!-- Quering --> +<FORM method=POST action=$FORM> + +<table border width="100%" > +<tr> + <th>MySQL server</th> + <th>User information</th> + <th>Reports</th> + </tr> + +<tr> + <td valign=top> + <table> + <tr> + <td halign=right><b>Host</b><br><font size=-2>(Host on which MySQL-server resides.)</font></td> + <td valign=top><INPUT name=rhost type=text size=15 maxlength=15 value="$MySQLaccess::Param{'rhost'}"></td> + </tr> + <tr> + <td halign=right><b>Superuser</b><br><font size=-2>(User which has <font color="Red">read-access</font> to grant-tables.)</font></td> + <td valign=top><INPUT name=superuser type=text size=15 maxlength=15 value="$MySQLaccess::Param{'superuser'}"></td> + </tr> + <tr> + <td halign=right><b>Password</b><br><font size=-2>(of Superuser.)</font></td> + <td valign=top><INPUT name=spassword type=password size=15 maxlength=15 value="$MySQLaccess::Param{'spassword'}"></td> + </tr> + </table> + </td> + + <td valign=top> + <table> + <tr> + <td halign=right><b><font color=Red>User</font></b><br><font size=-2>(Userid used to connect to MySQL-database.)</font></td> + <td halign=top><INPUT name=user type=text size=15 maxlength=15 value="$MySQLaccess::Param{'user'}"></td> + </tr> + <tr> + <td halign=right><b>Password</b><br><font size=-2>(Password user has to give to get access to MySQL-database.)</font></td> + <td valign=top><INPUT name=password type=password size=15 maxlength=15 value="$MySQLaccess::Param{'password'}"></td> + </tr> + <tr> + <td halign=right><b><font color=Red>Database</font></b><br><font size=-2>(Name of MySQL-database user tries to connect to.</font><br><font size=-2>Wildcards <font color="Green">(*,?,%,_)</font> are allowed.)</font></td> + <td valign=top><INPUT name=db type=text size=15 maxlength=15 value="$MySQLaccess::Param{'db'}"></td> + </tr> + <tr> + <td halign=right><b>Host</b><br><font size=-2>(Host from where the user is trying to connect to MySQL-database.</font><br><font size=-2>Wildcards <font color="Green">(*,?,%,_)</font> are allowed.)</font></td> + <td valign=top><INPUT name=host type=text size=15 maxlength=15 value="$MySQLaccess::Param{'host'}"></td> + </tr> + </table> + </td> + + <td valign=center> + <table cellspacing=5 cellpadding=2 cols=1 height="100%"> + <tr align=center> + <td halign=right><INPUT type=submit name=brief value="Brief"><br> + <INPUT type=submit name=table value="Tabular"></td> + </tr> + <tr align=center> + <td></td> + </tr> + <tr align=center> + <td halign=right><INPUT type=reset value="Clear"></td> + </tr> + </table> + </td> + </tr> + +</table> +</form> + + +</BODY> +</HTML> +EOForm + return 1; +} + +# ===================================== +# sub Print_Usage: +# print some information on STDOUT +# ===================================== +sub Print_Usage { + Print_Error_Messages(); + if ($MySQLaccess::CMD) { #command-line mode + Print_Options(); + } + if ($MySQLaccess::CGI) { #CGI-BIN mode + Print_Form(); + } + return 1; +} + +# ====================================== +# sub Print_Version: +# ====================================== +sub Print_Version { + if ($MySQLaccess::CMD) { + print $MySQLaccess::INFO; + } + if ($MySQLaccess::CGI) { + print "<PRE>\n"; + print $MySQLaccess::INFO; + print "</PRE>\n"; + } + return 1; +} + +# ====================================== +# sub Print_Relnotes: +# ====================================== +sub Print_Relnotes { + if ($MySQLaccess::CMD) { + print $MySQLaccess::RELEASE; + } + if ($MySQLaccess::CGI) { + print "<PRE>\n"; + print $MySQLaccess::RELEASE; + print "</PRE>\n"; + } + return 1; +} + +# ====================================== +# sub Print_Plans: +# ====================================== +sub Print_Plans { + if ($MySQLaccess::CMD) { + print $MySQLaccess::TODO; + } + if ($MySQLaccess::CGI) { + print "<PRE>\n"; + print $MySQLaccess::TODO; + print "</PRE>\n"; + } + return 1; +} + +# ====================================== +# sub Print_HowTo: +# ====================================== +sub Print_HowTo { + if ($MySQLaccess::CMD) { + print $MySQLaccess::HOWTO; + } + if ($MySQLaccess::CGI) { + print "<PRE>\n"; + print $MySQLaccess::HOWTO; + print "</PRE>\n"; + } + return 1; +} + +# ====================================== +# sub Print_Options: +# ====================================== +sub Print_Options { + if ($MySQLaccess::CGI) { print "<PRE>\n"; } + print $MySQLaccess::OPTIONS; + if ($MySQLaccess::CGI) { print "</PRE>\n"; } + return 1; +} + +# ====================================== +# sub Print_Error_Access: +# ====================================== +sub Print_Error_Access { + my ($error) = @_; + print "\n"; + if ($MySQLaccess::CGI) { print "<font color=Red>\n<PRE>\n"; } + print $MESSAGES{$error}; + if ($MySQLaccess::CGI) { print "</PRE>\n</font>\n"; } + print "\n"; + return 1; +} + +# ====================================== +# sub Print_Error_Messages: +# ====================================== +sub Print_Error_Messages { +# my ($error) = @_; + print "\n"; + if ($MySQLaccess::CGI) { print "<font color=Red>\n<center>\n"; } + foreach $error (@MySQLaccess::Grant::Error) { + print $MESSAGES{$error}; + print $MySQLaccess::CGI ? "<br>\n" : "\n"; + } + if ($MySQLaccess::CGI) { print "</center>\n</font>\n"; } + print "\n"; + return 1; +} + +# ====================================== +# sub Print_Message: +# ====================================== +sub Print_Message { + my ($aref) = @_; + my @messages = @{$aref}; + print "\n"; + if ($MySQLaccess::CGI) { print "<font color=DarkGreen>\n<center>\n"; } + foreach $msg (@messages) { + print $msg; + print $MySQLaccess::CGI ? "<br>\n" : "\n"; + } + if ($MySQLaccess::CGI) { print "</center>\n</font>\n"; } + print "\n"; + return 1; +} + +# ====================================== +# sub Print_Edit: +# ====================================== +sub Print_Edit { + print "\n"; + if (!$MySQLaccess::CGI) { + print "Note: Editing the temporary tables is NOT supported in CMD-line mode!\n"; + return 0; + } + print "<CENTER>\n" + ."<form action=$FORM method=GET>\n" + ."<table width=90% border>\n" + ."<tr>\n" + ." <td><input type=checkbox name=copy value=on> Copy grant-rules to temporary tables<br></td>\n" + ." <td rowspan=5 align=center valign=center><input type=submit value=Go></td>\n" + ."</tr>\n" + ."<tr>\n" + ." <td> Edit temporary tables with external application:<br>" + ." <a href=\"$MySQLaccess::MYSQLADMIN\">$MySQLaccess::MYSQLADMIN</a></td>\n" + ."</tr>\n" + ."<tr>\n" + ." <td><input type=checkbox name=preview value=on> Preview changes made in temporary tables</td>\n" + ."</tr>\n" + ."<tr>\n" + ." <td><input type=checkbox name=commit value=on> Make changes permanent</td>\n" + ."</tr>\n" + ."<tr>\n" + ." <td><input type=checkbox name=rollback value=on> Restore previous grand-rules</td>\n" + ."</tr>\n" + ."<tr>\n" + ." <td colspan=2 align=center><font size=-2 color=Red>You need write,delete and drop-privileges to perform the above actions</font></td>\n" + ."</tr>\n" + ."</table>\n" + ."</form>\n" + ."</CENTER>\n"; + + return 1; +} + + +# ====================================== +# sub Print_Access_rights: +# print the access-rights on STDOUT +# ====================================== +sub Print_Access_rights { + my ($host,$user,$db,$refhash) = @_; + + if (defined($MySQLaccess::Param{'brief'})) { +# if ($MySQLaccess::CGI) { print "<PRE>\n"; } + Matrix_Report($host,$user,$db,$refhash); +# if ($MySQLaccess::CGI) { print "</PRE>\n"; } + } + else { + Tabular_Report($host,$user,$db,$refhash); + $MySQLaccess::Report::separator = $MySQLaccess::CGI ? "<hr>" : "-"x80; + } + return 1; +} + +# ====================================== +# sub Print_Diff_ACL: +# print the diff. in the grants before and after +# ====================================== +sub Print_Diff_ACL { + my ($aref) = @_; + my @diffs = @{$aref}; + my %block = ( '<' => 'Before', + '>' => 'After', + ); + my %color = ( '<' => 'Green', + '>' => 'Red', + ); + my $curblock = ''; + + # ----------------------------- + # create column-headers + foreach $field (@MySQLaccess::Grant::Privileges) { + push(@headers,substr($field,0,4)); + } + + if ($MySQLaccess::CMD) { + print "\n"; + print "Differences in access-rights BEFORE and AFTER changes in grant-tables\n"; +# print "---------------------------------------------------------------------\n"; + my $line1=""; + my $line2=""; + $line1 .= sprintf("| %-30s|",'Host,User,DB'); + $line2 .= sprintf("+-%-30s+",'-' x 30); + foreach $header (@headers) { + $line1 .= sprintf("%-4s|",$header); + $line2 .= sprintf("%s+",'----'); + } + print "$line2\n"; + print "$line1\n"; + print "$line2\n"; + + $format = "format STDOUT = \n" + . "^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< " . " @|||" x 10 ."\n" + . '$host_user_db,@priv' . "\n" + . ".\n"; +#print $format; + eval $format; + } + if ($MySQLaccess::CGI) { + print "<table border width=100%>\n"; + print "<tr>\n"; + print "<th colspan=11>"; + print "Differences in access-rights <font color=$color{'<'}>BEFORE</font> " + ."and <font color=$color{'>'}>AFTER</font> changes to grant-tables</font>\n"; + print "</th>"; + print "</tr>\n"; + print "<tr>\n"; + $line1 .= sprintf("<th>%-20s</th>",'Host, User, DB'); + foreach $header (@headers) { + $line1 .= sprintf("<th>%-4s</th>",$header); + } + print "$line1</tr>\n"; + } + + foreach $line (@diffs) { + $type = substr($line,0,1); + $line = substr($line,1); + ($host,$user,$db,@priv) = split(/,/,$line); + if ($MySQLaccess::CMD) { + if ($type ne $curblock) { + $curblock = $type; + print $block{$curblock},":\n"; + } + #print "$line\n"; + write; + } + if ($MySQLaccess::CGI) { + if ($type ne $curblock) { + $curblock = $type; + print "<tr><td><b>$block{$curblock}<b></td></tr>\n"; + } + $line1="<td><font color=$color{$type}>$host, $user, $db</font></td>"; + foreach $field (@priv) { + $line1 .= sprintf("<td align=center><font color=$color{$type}>%-4s</font></td>",$field); + } + print "<tr>$line1</tr>\n"; + } + } + print "\n"; + if ($MySQLaccess::CMD) { + print "---------------------------------------------------------------------\n"; + } + if ($MySQLaccess::CGI) { + print "</table><br>"; + } + + + return 1; +} + +# ====================================== +# sub Tabular_Report +# Tabular report, +# suitable for 1 triple (host,db,user) +# ====================================== +sub Tabular_Report { + my ($host,$user,$db,$a) = @_; + my $column=2; + + # ----------------------------- + # separator + if ($MySQLaccess::Report::separator) { print "$MySQLaccess::Report::separator\n"; } + + # ----------------------------- + # print table of access-rights + my $rows = int(@MySQLaccess::Grant::Privileges/2); #round up + my @table=(); + $j=0; + for $i (0 .. $rows-1) { + $table[$j]=$MySQLaccess::Grant::Privileges[$i]; + $j = $j+2; + } + $j=1; + for $i ($rows .. $#MySQLaccess::Grant::Privileges) { + $table[$j]=$MySQLaccess::Grant::Privileges[$i]; + $j = $j+2; + } + if ($MySQLaccess::CMD) { + print "\n"; + print "Access-rights\n"; + print "for USER '$user', from HOST '$host', to DB '$db'\n"; + } + if ($MySQLaccess::CGI) { + print "<table border width=100%>\n"; + print "<tr>\n"; + } + if ($MySQLaccess::CGI) { + print "<th colspan=5>"; + print "<font color=Red>Access-rights</font>\n"; + print "for USER '<font color=Green>$user</font>', from HOST '<font color=Green>$host</font>', to DB '<font color=Green>$db</font>'\n"; + print "</th>"; + print "</tr>\n"; + print "<tr>\n"; + } + if ($MySQLaccess::CMD) { + print "\t+-----------------+---+\t+-----------------+---+"; + } + foreach $field (@table) { + if ($MySQLaccess::CMD) { + if ($column==2) { print "\n\t"; $column=1;} + else { print "\t"; $column=2;} + printf "| %-15s | %s |",$field,$Answer{$a->{$field}}; + } + if ($MySQLaccess::CGI) { + if ($column==2) { print "</tr>\n<tr>\n"; $column=1;} + else { print "<td width=10%></td>"; $column=2;} + printf " <td width=35%><b>%-15s</b></td><td width=10%>%s</td>\n",$field,$Answer{$a->{$field}}; + } + } + print "\n"; + if ($MySQLaccess::CMD) { + print "\t+-----------------+---+\t+-----------------+---+\n"; + } + if ($MySQLaccess::CGI) { + print "</tr>\n</table><br>"; + } + + # --------------- + # print notes: + foreach $note (@MySQLaccess::Grant::Notes) { + my $message = $MESSAGES{$note}; + $message =~ s/\$user/$user/g; + $message =~ s/\$db/$db/g; + $message =~ s/\$host/$host/g; + $message =~ s/\$password/$password/g; + $PREFIX='NOTE'; + if ($MySQLaccess::CMD) { + my @lines = split(/\n/,$message); + foreach $line (@lines) { + print "$PREFIX:\t $line\n"; + $PREFIX=' '; + } + } + if ($MySQLaccess::CGI) { + print "<b>$PREFIX:</b> $message<br>\n"; + } + } + + # --------------- + # print warnings: + foreach $warning (@MySQLaccess::Grant::Warnings) { + my $message = $MESSAGES{$warning}; + $message =~ s/\$user/$user/g; + $message =~ s/\$db/$db/g; + $message =~ s/\$host/$host/g; + $message =~ s/\$password/$password/g; + $PREFIX='BEWARE'; + if ($MySQLaccess::CMD) { + my @lines = split(/\n/,$message); + foreach $line (@lines) { + print "$PREFIX:\t $line\n"; + $PREFIX=' '; + } + } + if ($MySQLaccess::CGI) { + print "<b>$PREFIX:</b> $message<br>\n"; + } + } + + # --------------- + # print errors: + foreach $error (@MySQLaccess::Grant::Errors) { + my $message = $MESSAGES{$error}; + $message =~ s/\$user/$user/g; + $message =~ s/\$db/$db/g; + $message =~ s/\$host/$host/g; + $message =~ s/\$password/$password/g; + $PREFIX='ERROR'; + if ($MySQLaccess::CMD) { + my @lines = split(/\n/,$message); + foreach $line (@lines) { + print "$PREFIX:\t $line\n"; + $PREFIX=' '; + } + } + if ($MySQLaccess::CGI) { + print "<b>$PREFIX:</b> $message<br>\n"; + } + } + + # --------------- + # inform if there are no rules ==> full access for everyone. + if ($MySQLaccess::Grant::full_access) { print "$MESSAGES{'full_access'}\n"; } + + # --------------- + # print the rules used + print "\n"; + if ($MySQLaccess::CMD) { + print "The following rules are used:\n"; + foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) { + my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field}); + $rule =~ s/\t/','/g; + printf " %-5s : '%s'\n",$field,$rule; + } + } + if ($MySQLaccess::CGI) { + print "<br>\n"; + print "<table border width=100%>\n"; + print "<tr><th colspan=2>The following rules are used:</th></tr>\n"; + foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) { + my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field}); + $rule =~ s/\t/','/g; + printf "<tr><th>%-5s</th><td>'%s'</td></tr>\n",$field,$rule; + } + print "</table>\n"; + } + + return 1; +} + +# ====================================== +# sub Matrix_Report: +# single-line output foreach triple, +# no notes,warnings,... +# ====================================== +sub Matrix_Report { + my ($host,$user,$db,$a) = @_; + my @headers = (); + + if (! $headers) { + # ----------------------------- + # create column-headers + foreach $field (@MySQLaccess::Grant::Privileges) { + push(@headers,substr($field,0,4)); + } + + # ----------------------------- + # print column-headers + print "\n"; + if ($MySQLaccess::CMD) { + my $line1=""; + my $line2=""; + foreach $header (@headers) { + $line1 .= sprintf("%-4s ",$header); + $line2 .= sprintf("%s ",'----'); + } + $line1 .= sprintf("| %-20s",'Host,User,DB'); + $line2 .= sprintf("+ %-20s",'-' x 20); + print "$line1\n"; + print "$line2\n"; + } + if ($MySQLaccess::CGI) { + print "<table width=100% border>\n"; + my $line1="<tr>"; + foreach $header (@headers) { + $line1 .= sprintf("<th>%-4s</th>",$header); + } + $line1 .= sprintf("<th>%-20s</th>",'Host, User, DB'); + print "$line1</tr>\n"; + } + + # ---------------------------- + # column-headers should only be + # printed once. + $MySQLaccess::Report::headers=1; + } + + # ------------------------ + # print access-information + if ($MySQLaccess::CMD) { + foreach $field (@MySQLaccess::Grant::Privileges) { + printf " %-2s ",$Answer{$a->{$field}}; + } + printf "| %-20s",join(',',$host,$user,$db); + print "\n"; + } + if ($MySQLaccess::CGI) { + print "<tr>"; + foreach $field (@MySQLaccess::Grant::Privileges) { + printf "<td align=center>%-2s</td>",$Answer{$a->{$field}}; + } + printf "<td><b>%-20s</b></td>",join(', ',$host,$user,$db); + print "</tr>\n"; + } + + return 1; +} + + +# ====================================== +# sub Raw_Report: +# single-line output foreach triple, +# no notes,warnings,... +# ====================================== +sub Raw_Report { + my ($host,$user,$db,$a) = @_; + my @headers = (); + my $string = ""; + + # ------------------------ + # print access-information + $string = "$host,$user,$db,"; + foreach $field (@MySQLaccess::Grant::Privileges) { + $string .= $Answer{$a->{$field}} . ","; + } + return $string; +} + + +####################################################################### +package MySQLaccess::Wildcards; +BEGIN { + $DEBUG = 0; + $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG); +} +# ############################################ +# SQL, WILDCARDS and REGULAR EXPRESSIONS +# ============================================ +# translage SQL-expressions to Reg-expressions +# ============================================ +sub SQL2Reg { + my ($expr) = @_; + my $expr_o = $expr; + $expr =~ s/\./\\./g; + $expr =~ s/\\%/\002/g; + $expr =~ s/%/.*/g; + $expr =~ s/\002/%/g; + $expr =~ s/\\_/\002/g; + $expr =~ s/_/.+/g; + $expr =~ s/\002/_/g; + MySQLaccess::Debug::Print(2,"$expr_o --> $expr"); + return $expr; +} + +# translage WILDcards to Reg-expressions +# ============================================ +sub Wild2Reg { + my ($expr) = @_; + my $expr_o = $expr; + $expr =~ s/\./\\./g; + $expr =~ s/\\\*/\002/g; + $expr =~ s/\*/.*/g; + $expr =~ s/\002/*/g; + $expr =~ s/\\\?/\002/g; + $expr =~ s/\?/.+/g; + $expr =~ s/\002/?/g; + MySQLaccess::Debug::Print(2,"$expr_o --> $expr"); + return $expr; +} + +# ============================================= +# match a given string with a template +# ============================================= +sub MatchTemplate { + my ($tpl,$string) = @_; + my $match=0; + if ($string=~ /^$tpl$/ or $tpl eq '') { $match=1; } + else { $match=0;} + MySQLaccess::Debug::Print(2,"($tpl,$string) --> $match"); + return $match; +} + +####################################################################### +package MySQLaccess::Host; +BEGIN { + $localhost = undef; + $DEBUG = 2; + $DEBUG = $MySQLaccess::DEBUG unless ($DEBUG); +} +# ====================================== +# sub IP2Name +# return the Name with the corr. IP-nmbr +# (no aliases yet!!) +# ====================================== +sub IP2Name { + my ($ip) = @_; + my $ip_o = $ip; + if ($ip !~ /([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/o) { + MySQLaccess::Debug::Print(3,"'$ip' is not an ip-number, returning IP=$ip"); + return $ip; + } + MySQLaccess::Debug::Print(4,"IP=$ip split up => $1.$2.$3.$4"); + $ip = pack "C4",$1,$2,$3,$4; + MySQLaccess::Debug::Print(4,"IP packed -> >>$ip<<\n"); + my ($name,$aliases,$addrtype,$length,@addrs) = gethostbyaddr($ip, AF_INET); + MySQLaccess::Debug::Print(3,"IP=$ip_o => hostname=$name"); + MySQLaccess::Debug::Print(4,"aliases=$aliases"); + MySQLaccess::Debug::Print(4,"addrtype=$addrtype - length=$length"); + return ($name || $ip); + #return ($name || undef); +} + +# ====================================== +# sub Name2IP +# return the IP-number of the host +# ====================================== +sub Name2IP { + my ($name) = @_; + if ($name =~ /[%_]/) { + MySQLaccess::Debug::Print(3,"'$name' contains SQL-wildcards, returning name=$name"); + return $name; + } + my ($_name,$aliases,$addrtype,$length,@addrs) = gethostbyname($name); + my ($a,$b,$c,$d) = unpack('C4',$addrs[0]); + my $ip = "$a.$b.$c.$d"; + MySQLaccess::Debug::Print(3,"hostname=$name => IP=$ip"); + MySQLaccess::Debug::Print(4,"aliases=$aliases"); + MySQLaccess::Debug::Print(4,"addrtype=$addrtype - length=$length"); + #if ($ip ne "") { return "$ip"; } + #else { return undef; } + return ($ip || $name); +} + +# ======================================== +# sub LocalHost +# some special action has to be taken for +# the localhost +# ======================================== +sub LocalHost { + if (!defined($MySQLaccess::Host::localhost)) { + $MySQLaccess::Host::localhost = Sys::Hostname::hostname(); + MySQLaccess::Debug::Print(3,"Setting package variable \$localhost=$MySQLaccess::Host::localhost"); + } + my $host = $localhost; + MySQLaccess::Debug::Print(3,"localhost = $host"); + return $host; +} + +# ======================================== +# check if the given hostname (or ip) +# corresponds with the localhost +# ======================================== +sub Is_localhost { + my ($host_tpl) = @_; + my $isit = 0; + if (($MySQLaccess::host_name eq $localhost) or ($MySQLaccess::host_ip eq $local_ip)) { + MySQLaccess::Debug::Print(2,"Checking for localhost"); + MySQLaccess::Debug::Print(3,"because ($MySQLaccess::host_name EQ $localhost) AND ($MySQLaccess::host_ip EQ $local_ip)"); + $isit = ( 'localhost' =~ /$host_tpl/ ) ? 1 : 0; + MySQLaccess::Debug::Print(3," 'localhost' =?= $host_tpl -> $isit"); + return $isit; + } + else { + MySQLaccess::Debug::Print(4,"Not checking for localhost"); + MySQLaccess::Debug::Print(4,"because ($MySQLaccess::host_name != $localhost) AND ($MySQLaccess::host_ip != $local_ip)"); + return 0; + } +} + + +# ========================================= +# check if host (IP or name) can be matched +# on the template. +# ========================================= +sub MatchTemplate { + my ($host,$tpl) = @_; + my $match = 0; + + MySQLaccess::Debug::Print(1, "($host) =?= ($tpl)"); + + my $host_name = IP2Name($host); + my $host_ip = Name2IP($host); + + MySQLaccess::Debug::Print(2, "name=$host_name ; ip=$host_ip"); + $match = (MySQLaccess::Wildcards::MatchTemplate($tpl,$host_name) or + MySQLaccess::Wildcards::MatchTemplate($tpl,$host_ip)); + + MySQLaccess::Debug::Print(2, "($host_name,$host_ip) =?= ($tpl): $ncount"); + + return $match; +} + +######################################################################## +package MySQLaccess::Debug; +BEGIN { + my $dbg_file = "$MySQLaccess::script_log"; + open(DEBUG,"> $dbg_file") or warn "Could not open outputfile $dbg_file for debugging-info\n"; + select DEBUG; + $| = 1; + select STDOUT; +} +# ========================================= +# Print debugging information on STDERR +# ========================================= +sub Print { + my ($level,$mesg) = @_; + my ($pack,$file,$line,$subname,$hasargs,$wantarray) = caller(1); + my ($PACK) = split('::',$subname); + my $DEBUG = ${$PACK."::DEBUG"} ? ${$PACK."::DEBUG"} : $MySQLaccess::DEBUG ; + my ($sec,$min,$hour) = localtime(); + print DEBUG "[$hour:$min:$sec $subname] $mesg\n" if ($DEBUG>=$level); +} + diff --git a/scripts/mysqld_multi.sh b/scripts/mysqld_multi.sh new file mode 100644 index 00000000..77ed3621 --- /dev/null +++ b/scripts/mysqld_multi.sh @@ -0,0 +1,869 @@ +#!@PERL_PATH@ + +# Copyright (c) 2000, 2017, Oracle and/or its affiliates. +# Copyright (c) 2010, 2017, MariaDB Corporation +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU Library 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 +# Library General Public License for more details. +# +# You should have received a copy of the GNU Library General Public +# License along with this library; if not, write to the Free +# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +# MA 02110-1335 USA + +use Getopt::Long; +use POSIX qw(strftime getcwd); + +$|=1; +$VER="2.20"; + +my @defaults_options; # Leading --no-defaults, --defaults-file, etc. + +$opt_example = 0; +$opt_help = 0; +$opt_log = undef(); +$opt_mysqladmin = "@bindir@/mysqladmin"; +$opt_mysqld = "@sbindir@/mysqld"; +$opt_no_log = 0; +$opt_password = undef(); +$opt_tcp_ip = 0; +$opt_user = "root"; +$opt_version = 0; +$opt_silent = 0; +$opt_verbose = 0; +$opt_wsrep_new_cluster = 0; + +my $my_print_defaults_exists= 1; +my $logdir= undef(); + +my ($mysqld, $mysqladmin, $groupids, $homedir, $my_progname); + +$homedir = $ENV{HOME}; +$my_progname = $0; +$my_progname =~ s/.*[\/]//; + + +if (defined($ENV{UMASK})) { + my $UMASK = $ENV{UMASK}; + my $m; + my $fmode = "0640"; + + if(($UMASK =~ m/[^0246]/) || ($UMASK =~ m/^[^0]/) || (length($UMASK) != 4)) { + printf("UMASK must be a 3-digit mode with an additional leading 0 to indicate octal.\n"); + printf("The first digit will be corrected to 6, the others may be 0, 2, 4, or 6.\n"); } + else { + $fmode= substr $UMASK, 2, 2; + $fmode= "06${fmode}"; } + + if($fmode != $UMASK) { + printf("UMASK corrected from $UMASK to $fmode ...\n"); } + + $fmode= oct($fmode); + + umask($fmode); +} + + +main(); + +#### +#### main sub routine +#### + +sub main +{ + my $flag_exit= 0; + + if (!defined(my_which(my_print_defaults))) + { + # We can't throw out yet, since --version, --help, or --example may + # have been given + print "WARNING: my_print_defaults command not found.\n"; + print "Please make sure you have this command available and\n"; + print "in your path. The command is available from the latest\n"; + print "MariaDB distribution.\n"; + $my_print_defaults_exists= 0; + } + + # Remove leading defaults options from @ARGV + while (@ARGV > 0) + { + last unless $ARGV[0] =~ + /^--(?:no-defaults$|(?:defaults-file|defaults-extra-file)=)/; + push @defaults_options, (shift @ARGV); + } + + foreach (@defaults_options) + { + $_ = quote_shell_word($_); + } + + # Add [mysqld_multi] options to front of @ARGV, ready for GetOptions() + unshift @ARGV, defaults_for_group('mysqld_multi'); + + # We've already handled --no-defaults, --defaults-file, etc. + if (!GetOptions("help", "example", "version", "mysqld=s", "mysqladmin=s", + "user=s", "password=s", "log=s", "no-log", + "tcp-ip", "silent", "verbose", "wsrep-new-cluster")) + { + $flag_exit= 1; + } + usage() if ($opt_help); + + if ($opt_verbose && $opt_silent) + { + print "Both --verbose and --silent have been given. Some of the warnings "; + print "will be disabled\nand some will be enabled.\n\n"; + } + + init_log() if (!defined($opt_log)); + $groupids = $ARGV[1]; + if ($opt_version) + { + print "$my_progname version $VER by Jani Tolonen\n"; + exit(0); + } + example() if ($opt_example); + if ($flag_exit) + { + print "Error with an option, see $my_progname --help for more info.\n"; + exit(1); + } + if (!defined(my_which(my_print_defaults))) + { + print "ABORT: Can't find command 'my_print_defaults'.\n"; + print "This command is available from the latest MariaDB\n"; + print "distribution. Please make sure you have the command\n"; + print "in your PATH.\n"; + exit(1); + } + usage() if (!defined($ARGV[0]) || + (!($ARGV[0] =~ m/^start$/i) && + !($ARGV[0] =~ m/^stop$/i) && + !($ARGV[0] =~ m/^report$/i))); + + if (!$opt_no_log) + { + w2log("$my_progname log file version $VER; run: ", + "$opt_log", 1, 0); + } + else + { + print "$my_progname log file version $VER; run: "; + print strftime "%a %b %e %H:%M:%S %Y", localtime; + print "\n"; + } + if ($ARGV[0] =~ m/^start$/i) + { + if (!defined(($mysqld= my_which($opt_mysqld))) && $opt_verbose) + { + print "WARNING: Couldn't find the default mysqld binary.\n"; + print "Tried: $opt_mysqld\n"; + print "This is OK, if you are using option \"mysqld=...\" in "; + print "groups [mysqldN] separately for each.\n\n"; + } + start_mysqlds(); + } + else + { + if (!defined(($mysqladmin= my_which($opt_mysqladmin))) && $opt_verbose) + { + print "WARNING: Couldn't find the default mysqladmin binary.\n"; + print "Tried: $opt_mysqladmin\n"; + print "This is OK, if you are using option \"mysqladmin=...\" in "; + print "groups [mysqldN] separately for each.\n\n"; + } + if ($ARGV[0] =~ m/^report$/i) + { + report_mysqlds(); + } + else + { + stop_mysqlds(); + } + } +} + +# +# Quote word for shell +# + +sub quote_shell_word +{ + my ($option)= @_; + + $option =~ s!([^\w=./-])!\\$1!g; + return $option; +} + +#### +#### get options for a group +#### + +sub defaults_for_group +{ + my ($group) = @_; + + return () unless $my_print_defaults_exists; + + my $com= join ' ', 'my_print_defaults', @defaults_options, $group; + my @defaults = `$com`; + chomp @defaults; + return @defaults; +} + +#### +#### Init log file. Check for appropriate place for log file, in the following +#### order: my_print_defaults mysqld datadir, @datadir@ +#### + +sub init_log +{ + foreach my $opt (defaults_for_group('--mysqld')) + { + if ($opt =~ m/^--datadir=(.*)/ && -d "$1" && -w "$1") + { + $logdir= $1; + } + } + if (!defined($logdir)) + { + $logdir= "@datadir@" if (-d "@datadir@" && -w "@datadir@"); + } + if (!defined($logdir)) + { + # Log file was not specified and we could not log to a standard place, + # so log file be disabled for now. + if (!$opt_silent) + { + print "WARNING: Log file disabled. Maybe directory or file isn't writable?\n"; + } + $opt_no_log= 1; + } + else + { + $opt_log= "$logdir/mysqld_multi.log"; + } +} + +#### +#### Report living and not running MariaDB servers +#### + +sub report_mysqlds +{ + my (@groups, $com, $i, @options, $pec); + + print "Reporting MariaDB servers\n"; + if (!$opt_no_log) + { + w2log("\nReporting MariaDB servers","$opt_log",0,0); + } + @groups = &find_groups($groupids); + for ($i = 0; defined($groups[$i]); $i++) + { + $com= get_mysqladmin_options($i, @groups); + $com.= " ping >> /dev/null 2>&1"; + system($com); + $pec = $? >> 8; + if ($pec) + { + print "MariaDB server from group: $groups[$i] is not running\n"; + if (!$opt_no_log) + { + w2log("MariaDB server from group: $groups[$i] is not running", + "$opt_log", 0, 0); + } + } + else + { + print "MariaDB server from group: $groups[$i] is running\n"; + if (!$opt_no_log) + { + w2log("MariaDB server from group: $groups[$i] is running", + "$opt_log", 0, 0); + } + } + } + if (!$i) + { + print "No groups to be reported (check your GNRs)\n"; + if (!$opt_no_log) + { + w2log("No groups to be reported (check your GNRs)", "$opt_log", 0, 0); + } + } +} + +#### +#### start multiple servers +#### + +sub start_mysqlds() +{ + my (@groups, $com, $tmp, $i, @options, $j, $mysqld_found, $suffix_found, $info_sent); + + $suffix_found= 0; + + if (!$opt_no_log) + { + w2log("\nStarting MariaDB servers\n","$opt_log",0,0); + } + else + { + print "\nStarting MariaDB servers\n"; + } + @groups = &find_groups($groupids); + for ($i = 0; defined($groups[$i]); $i++) + { + @options = defaults_for_group($groups[$i]); + + $basedir_found= 0; # The default + $mysqld_found= 1; # The default + $mysqld_found= 0 if (!length($mysqld)); + $com= "$mysqld"; + + for ($j = 0, $tmp= ""; defined($options[$j]); $j++) + { + if ("--mysqladmin=" eq substr($options[$j], 0, 13)) + { + # catch this and ignore + } + elsif ("--mysqld=" eq substr($options[$j], 0, 9)) + { + $options[$j]=~ s/\-\-mysqld\=//; + $com= $options[$j]; + $mysqld_found= 1; + } + elsif ("--basedir=" eq substr($options[$j], 0, 10)) + { + $basedir= $options[$j]; + $basedir =~ s/^--basedir=//; + $basedir_found= 1; + $options[$j]= quote_shell_word($options[$j]); + $tmp.= " $options[$j]"; + } + elsif ("--defaults-group-suffix=" eq substr($options[$j], 0, 24)) + { + $suffix_found= 1; + } + else + { + $options[$j]= quote_shell_word($options[$j]); + $tmp.= " $options[$j]"; + } + } + if ($opt_verbose && $com =~ m/\/(safe_mysqld|mysqld_safe)$/ && !$info_sent) + { + print "WARNING: $1 is being used to start mysqld. In this case you "; + print "may need to pass\n\"ledir=...\" under groups [mysqldN] to "; + print "$1 in order to find the actual mysqld binary.\n"; + print "ledir (library executable directory) should be the path to the "; + print "wanted mysqld binary.\n\n"; + $info_sent= 1; + } + + if (!$suffix_found) + { + $com.= " --defaults-group-suffix="; + $com.= substr($groups[$i],6); + } + + $com.= $tmp; + + if ($opt_wsrep_new_cluster) { + $com.= " --wsrep-new-cluster"; + } + + $com.= " >> $opt_log 2>&1" if (!$opt_no_log); + $com.= " &"; + if (!$mysqld_found) + { + print "\n"; + print "FATAL ERROR: Tried to start mysqld under group [$groups[$i]], "; + print "but no mysqld binary was found.\n"; + print "Please add \"mysqld=...\" in group [mysqld_multi], or add it to "; + print "group [$groups[$i]] separately.\n"; + exit(1); + } + if ($basedir_found) + { + $curdir=getcwd(); + chdir($basedir) or die "Can't change to datadir $basedir"; + } + system($com); + if ($basedir_found) + { + chdir($curdir) or die "Can't change back to original dir $curdir"; + } + } + if (!$i && !$opt_no_log) + { + w2log("No MariaDB servers to be started (check your GNRs)", + "$opt_log", 0, 0); + } +} + +#### +#### stop multiple servers +#### + +sub stop_mysqlds() +{ + my (@groups, $com, $i, @options); + + if (!$opt_no_log) + { + w2log("\nStopping MariaDB servers\n","$opt_log",0,0); + } + else + { + print "\nStopping MariaDB servers\n"; + } + @groups = &find_groups($groupids); + for ($i = 0; defined($groups[$i]); $i++) + { + $com= get_mysqladmin_options($i, @groups); + $com.= " shutdown"; + $com.= " >> $opt_log 2>&1" if (!$opt_no_log); + $com.= " &"; + system($com); + } + if (!$i && !$opt_no_log) + { + w2log("No MariaDB servers to be stopped (check your GNRs)", + "$opt_log", 0, 0); + } +} + +#### +#### Sub function for mysqladmin option parsing +#### + +sub get_mysqladmin_options +{ + my ($i, @groups)= @_; + my ($mysqladmin_found, $com, $tmp, $j); + + @options = defaults_for_group($groups[$i]); + + $mysqladmin_found= 1; # The default + $mysqladmin_found= 0 if (!length($mysqladmin)); + $com = "$mysqladmin"; + $tmp = " -u $opt_user"; + if (defined($opt_password)) { + my $pw= $opt_password; + # Protect single quotes in password + $pw =~ s/'/'"'"'/g; + $tmp.= " -p'$pw'"; + } + $tmp.= $opt_tcp_ip ? " -h 127.0.0.1" : ""; + for ($j = 0; defined($options[$j]); $j++) + { + if ("--mysqladmin=" eq substr($options[$j], 0, 13)) + { + $options[$j]=~ s/\-\-mysqladmin\=//; + $com= $options[$j]; + $mysqladmin_found= 1; + } + elsif ((($options[$j] =~ m/^(\-\-socket\=)(.*)$/) && !$opt_tcp_ip) || + ($options[$j] =~ m/^(\-\-port\=)(.*)$/)) + { + $tmp.= " $options[$j]"; + } + } + if (!$mysqladmin_found) + { + print "\n"; + print "FATAL ERROR: Tried to use mysqladmin in group [$groups[$i]], "; + print "but no mysqladmin binary was found.\n"; + print "Please add \"mysqladmin=...\" in group [mysqld_multi], or "; + print "in group [$groups[$i]].\n"; + exit(1); + } + $com.= $tmp; + return $com; +} + +# Return a list of option files which can be opened. Similar, but not +# identical, to behavior of my_search_option_files() +# TODO implement and use my_print_defaults --list-groups instead +sub list_defaults_files +{ + my %opt; + foreach (@defaults_options) + { + return () if /^--no-defaults$/; + $opt{$1} = $2 if /^--defaults-(extra-file|file)=(.*)$/; + } + + return ($opt{file}) if exists $opt{file}; + + my @dirs; + + # same rule as in mysys/my_default.c + if ('@sysconfdir@') { + push @dirs, '@sysconfdir@/my.cnf'; + } else { + push @dirs, '/etc/my.cnf', '/etc/mysql/my.cnf'; + } + push @dirs, "$ENV{MYSQL_HOME}/my.cnf" if $ENV{MYSQL_HOME}; + push @dirs, $opt{'extra-file'} if $opt{'extra-file'}; + push @dirs, "$ENV{HOME}/.my.cnf" if $ENV{HOME}; + + return @dirs; +} + + +# Takes a specification of GNRs (see --help), and returns a list of matching +# groups which actually are mentioned in a relevant config file +sub find_groups +{ + my ($raw_gids) = @_; + + my %gids; + my @groups; + + if (defined($raw_gids)) + { + # Make a hash of the wanted group ids + foreach my $raw_gid (split ',', $raw_gids) + { + # Match 123 or 123-456 + my ($start, $end) = ($raw_gid =~ /^\s*(\d+)(?:\s*-\s*(\d+))?\s*$/); + $end = $start if not defined $end; + if (not defined $start or $end < $start or $start < 0) + { + print "ABORT: Bad GNR: $raw_gid; see $my_progname --help\n"; + exit(1); + } + + foreach my $i ($start .. $end) + { + # Use $i + 0 to normalize numbers (002 + 0 -> 2) + $gids{$i + 0}= 1; + } + } + } + + my %seen; + my @defaults_files = list_defaults_files(); + while (@defaults_files) + { + my $file = shift @defaults_files; + next unless defined $file and not $seen{$file}++ and open CONF, '<', $file; + + while (<CONF>) + { + if (/^\s*\[\s*(mysqld)(\d+)\s*\]\s*$/) + { + #warn "Found a group: $1$2\n"; + # Use $2 + 0 to normalize numbers (002 + 0 -> 2) + if (not defined($raw_gids) or $gids{$2 + 0}) + { + push @groups, "$1$2"; + } + } + elsif (/^\s*!include\s+(\S.*?)\s*$/) + { + push @defaults_files, $1; + } + elsif (/^\s*!includedir\s+(\S.*?)\s*$/) + { + push @defaults_files, <$1/*.cnf>; + } + } + + close CONF; + } + return @groups; +} + +#### +#### w2log: Write to a logfile. +#### 1.arg: append to the log file (given string, or from a file. if a file, +#### file will be read from $opt_logdir) +#### 2.arg: logfile -name (w2log assumes that the logfile is in $opt_logdir). +#### 3.arg. 0 | 1, if true, print current date to the logfile. 3. arg will +#### be ignored, if 1. arg is a file. +#### 4.arg. 0 | 1, if true, first argument is a file, else a string +#### + +sub w2log +{ + my ($msg, $file, $date_flag, $is_file)= @_; + my (@data); + + open (LOGFILE, ">>$opt_log") + or die "FATAL: w2log: Couldn't open log file: $opt_log\n"; + + if ($is_file) + { + open (FROMFILE, "<$msg") && (@data=<FROMFILE>) && + close(FROMFILE) + or die "FATAL: w2log: Couldn't open file: $msg\n"; + foreach my $line (@data) + { + print LOGFILE "$line"; + } + } + else + { + print LOGFILE "$msg"; + print LOGFILE strftime "%a %b %e %H:%M:%S %Y", localtime if ($date_flag); + print LOGFILE "\n"; + } + close (LOGFILE); + return; +} + +#### +#### my_which is used, because we can't assume that every system has the +#### which -command. my_which can take only one argument at a time. +#### Return values: requested system command with the first found path, +#### or undefined, if not found. +#### + +sub my_which +{ + my ($command) = @_; + my (@paths, $path); + + # If the argument is not 'my_print_defaults' then it would be of the format + # <absolute_path>/<program> + return $command if ($command ne 'my_print_defaults' && -f $command && + -x $command); + + @paths = split(':', $ENV{'PATH'}); + foreach $path (@paths) + { + $path .= "/$command"; + return $path if (-f $path && -x $path); + } + return undef(); +} + + +#### +#### example +#### + +sub example +{ + print <<EOF; +# This is an example of a my.cnf file for $my_progname. +# Usually this file is located in home dir ~/.my.cnf or @sysconfdir@/my.cnf +# +# SOME IMPORTANT NOTES FOLLOW: +# +# 1.COMMON USER +# +# Make sure that the MariaDB user, who is stopping the mysqld services, has +# the same password to all MariaDB servers being accessed by $my_progname. +# This user needs to have the 'Shutdown_priv' -privilege, but for security +# reasons should have no other privileges. It is advised that you create a +# common 'multi_admin' user for all MariaDB servers being controlled by +# $my_progname. Here is an example how to do it: +# +# GRANT SHUTDOWN ON *.* TO multi_admin\@localhost IDENTIFIED BY 'password' +# +# You will need to apply the above to all MariaDB servers that are being +# controlled by $my_progname. 'multi_admin' will shutdown the servers +# using 'mysqladmin' -binary, when '$my_progname stop' is being called. +# +# 2.PID-FILE +# +# If you are using mysqld_safe to start mysqld, make sure that every +# MariaDB server has a separate pid-file. In order to use mysqld_safe +# via $my_progname, you need to use two options: +# +# mysqld=/path/to/mysqld_safe +# ledir=/path/to/mysqld-binary/ +# +# ledir (library executable directory), is an option that only mysqld_safe +# accepts, so you will get an error if you try to pass it to mysqld directly. +# For this reason you might want to use the above options within [mysqld#] +# group directly. +# +# 3.DATA DIRECTORY +# +# It is NOT advised to run many MariaDB servers within the same data directory. +# You can do so, but please make sure to understand and deal with the +# underlying caveats. In short they are: +# - Speed penalty +# - Risk of table/data corruption +# - Data synchronising problems between the running servers +# - Heavily media (disk) bound +# - Relies on the system (external) file locking +# - Is not applicable with all table types. (Such as InnoDB) +# Trying so will end up with undesirable results. +# +# 4.TCP/IP Port +# +# Every server requires one and it must be unique. +# +# 5.[mysqld#] Groups +# +# In the example below the first and the fifth mysqld group was +# intentionally left out. You may have 'gaps' in the config file. This +# gives you more flexibility. +# +# 6.MariaDB Server User +# +# You can pass the user=... option inside [mysqld#] groups. This +# can be very handy in some cases, but then you need to run $my_progname +# as UNIX root. +# +# 7.A Start-up Manage Script for $my_progname +# +# In the recent MariaDB distributions you can find a file called +# mysqld_multi.server.sh. It is a wrapper for $my_progname. This can +# be used to start and stop multiple servers during boot and shutdown. +# +# You can place the file in /etc/init.d/mysqld_multi.server.sh and +# make the needed symbolic links to it from various run levels +# (as per Linux/Unix standard). You may even replace the +# /etc/init.d/mysql.server script with it. +# +# Before using, you must create a my.cnf file either in @prefix@/my.cnf +# or /root/.my.cnf and add the [mysqld_multi] and [mysqld#] groups. +# +# The script can be found from support-files/mysqld_multi.server.sh +# in MariaDB distribution. (Verify the script before using) +# + +[mysqld_multi] +mysqld = @bindir@/mysqld_safe +mysqladmin = @bindir@/mysqladmin +user = multi_admin +password = my_password + +[mysqld2] +socket = /tmp/mysql.sock2 +port = 3307 +pid-file = @localstatedir@2/hostname.pid2 +datadir = @localstatedir@2 +language = @datadir@/mysql/english +user = unix_user1 + +[mysqld3] +mysqld = /path/to/mysqld_safe +ledir = /path/to/mysqld-binary/ +mysqladmin = /path/to/mysqladmin +socket = /tmp/mysql.sock3 +port = 3308 +pid-file = @localstatedir@3/hostname.pid3 +datadir = @localstatedir@3 +language = @datadir@/mysql/swedish +user = unix_user2 + +[mysqld4] +socket = /tmp/mysql.sock4 +port = 3309 +pid-file = @localstatedir@4/hostname.pid4 +datadir = @localstatedir@4 +language = @datadir@/mysql/estonia +user = unix_user3 + +[mysqld6] +socket = /tmp/mysql.sock6 +port = 3311 +pid-file = @localstatedir@6/hostname.pid6 +datadir = @localstatedir@6 +language = @datadir@/mysql/japanese +user = unix_user4 +EOF + exit(0); +} + +#### +#### usage +#### + +sub usage +{ + print <<EOF; +$my_progname version $VER by Jani Tolonen + +Description: +$my_progname can be used to start, or stop any number of separate +mysqld processes running in different TCP/IP ports and UNIX sockets. + +$my_progname can read group [mysqld_multi] from my.cnf file. You may +want to put options mysqld=... and mysqladmin=... there. Since +version 2.10 these options can also be given under groups [mysqld#], +which gives more control over different versions. One can have the +default mysqld and mysqladmin under group [mysqld_multi], but this is +not mandatory. Please note that if mysqld or mysqladmin is missing +from both [mysqld_multi] and [mysqld#], a group that is tried to be +used, $my_progname will abort with an error. + +$my_progname will search for groups named [mysqld#] from my.cnf (or +the given --defaults-extra-file=...), where '#' can be any positive +integer starting from 1. These groups should be the same as the regular +[mysqld] group, but with those port, socket and any other options +that are to be used with each separate mysqld process. The number +in the group name has another function; it can be used for starting, +stopping, or reporting any specific mysqld server. + +Usage: $my_progname [OPTIONS] {start|stop|report} [GNR,GNR,GNR...] +or $my_progname [OPTIONS] {start|stop|report} [GNR-GNR,GNR,GNR-GNR,...] + +The GNR means the group number. You can start, stop or report any GNR, +or several of them at the same time. (See --example) The GNRs list can +be comma separated or a dash combined. The latter means that all the +GNRs between GNR1-GNR2 will be affected. Without GNR argument all the +groups found will either be started, stopped, or reported. Note that +syntax for specifying GNRs must appear without spaces. + +Options: + +These options must be given before any others: +--no-defaults Do not read any defaults file +--defaults-file=... Read only this configuration file, do not read the + standard system-wide and user-specific files +--defaults-extra-file=... Read this configuration file in addition to the + standard system-wide and user-specific files +Using: @{[join ' ', @defaults_options]} + +--example Give an example of a config file with extra information. +--help Print this help and exit. +--log=... Log file. Full path to and the name for the log file. NOTE: + If the file exists, everything will be appended. + Using: $opt_log +--mysqladmin=... mysqladmin binary to be used for a server shutdown. + Since version 2.10 this can be given within groups [mysqld#] + Using: $mysqladmin +--mysqld=... mysqld binary to be used. Note that you can give mysqld_safe + to this option also. The options are passed to mysqld. Just + make sure you have mysqld in your PATH or fix mysqld_safe. + Using: $mysqld + Please note: Since mysqld_multi version 2.3 you can also + give this option inside groups [mysqld#] in ~/.my.cnf, + where '#' stands for an integer (number) of the group in + question. This will be recognised as a special option and + will not be passed to the mysqld. This will allow one to + start different mysqld versions with mysqld_multi. +--no-log Print to stdout instead of the log file. By default the log + file is turned on. +--password=... Password for mysqladmin user. +--silent Disable warnings. +--tcp-ip Connect to the MariaDB server(s) via the TCP/IP port instead + of the UNIX socket. This affects stopping and reporting. + If a socket file is missing, the server may still be + running, but can be accessed only via the TCP/IP port. + By default connecting is done via the UNIX socket. +--user=... mysqladmin user. Using: $opt_user +--verbose Be more verbose. +--version Print the version number and exit. +--wsrep-new-cluster Bootstrap a cluster. +EOF + exit(0); +} diff --git a/scripts/mysqld_safe.sh b/scripts/mysqld_safe.sh new file mode 100644 index 00000000..75a613b2 --- /dev/null +++ b/scripts/mysqld_safe.sh @@ -0,0 +1,1077 @@ +#!/bin/sh +# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB +# This file is public domain and comes with NO WARRANTY of any kind +# +# Script to start the MySQL daemon and restart it if it dies unexpectedly +# +# This should be executed in the MySQL base directory if you are using a +# binary installation that is not installed in its compile-time default +# location +# +# mysql.server works by first doing a cd to the base directory and from there +# executing mysqld_safe + +# Initialize script globals +KILL_MYSQLD=1; +MYSQLD= +niceness=0 +nowatch=0 +mysqld_ld_preload= +mysqld_ld_library_path= +flush_caches=0 +numa_interleave=0 +wsrep_on=0 +dry_run=0 +defaults_group_suffix= + +# Initial logging status: error log is not open, and not using syslog +logging=init +want_syslog=0 +syslog_tag= +user='@MYSQLD_USER@' +pid_file= +err_log= +err_log_base= +skip_err_log=0 + +syslog_tag_mysqld=mysqld +syslog_tag_mysqld_safe=mysqld_safe + +trap '' 1 2 3 15 # we shouldn't let anyone kill us + +# MySQL-specific environment variable. First off, it's not really a umask, +# it's the desired mode. Second, it follows umask(2), not umask(3) in that +# octal needs to be explicit. Our shell might be a proper sh without printf, +# multiple-base arithmetic, and binary arithmetic, so this will get ugly. +# We reject decimal values to keep things at least half-sane. +umask 007 # fallback +UMASK="${UMASK-0640}" +fmode=`echo "$UMASK" | sed -e 's/[^0246]//g'` +octalp=`echo "$fmode"|cut -c1` +fmlen=`echo "$fmode"|wc -c|sed -e 's/ //g'` +if [ "x$octalp" != "x0" -o "x$UMASK" != "x$fmode" -o "x$fmlen" != "x5" ] +then + fmode=0640 + echo "UMASK must be a 3-digit mode with an additional leading 0 to indicate octal." >&2 + echo "The first digit will be corrected to 6, the others may be 0, 2, 4, or 6." >&2 +fi +fmode=`echo "$fmode"|cut -c3-4` +fmode="6$fmode" +if [ "x$UMASK" != "x0$fmode" ] +then + echo "UMASK corrected from $UMASK to 0$fmode ..." +fi + +defaults= +case "$1" in + --no-defaults|--defaults-file=*|--defaults-extra-file=*) + defaults="$1"; shift + ;; +esac + +usage () { + cat <<EOF +Usage: $0 [OPTIONS] + --no-defaults Don't read the system defaults file + --defaults-file=FILE Use the specified defaults file + --defaults-extra-file=FILE Also use defaults from the specified file + --defaults-group-suffix=X Additionally read default groups with X appended + as a suffix + --ledir=DIRECTORY Look for mysqld in the specified directory + --open-files-limit=LIMIT Limit the number of open files + --crash-script=FILE Script to call when mysqld crashes + --core-file-size=LIMIT Limit core files to the specified size + --timezone=TZ Set the system timezone + --malloc-lib=LIB Preload shared library LIB if available + --mysqld=FILE Use the specified file as mysqld + --mysqld-version=VERSION Use "mysqld-VERSION" as mysqld + --dry-run Simulate the start to detect errors but don't start + --nice=NICE Set the scheduling priority of mysqld + --no-auto-restart Exit after starting mysqld + --nowatch Exit after starting mysqld + --plugin-dir=DIR Plugins are under DIR or DIR/VERSION, if + VERSION is given + --skip-kill-mysqld Don't try to kill stray mysqld processes + --syslog Log messages to syslog with 'logger' + --skip-syslog Log messages to error log (default) + --syslog-tag=TAG Pass -t "mysqld-TAG" to 'logger' + --flush-caches Flush and purge buffers/caches before + starting the server + --numa-interleave Run mysqld with its memory interleaved + on all NUMA nodes + +All other options are passed to the mysqld program. + +EOF + exit 1 +} + +find_in_bin() { + if test -x "$MY_BASEDIR_VERSION/bin/$1" + then + echo "$MY_BASEDIR_VERSION/bin/$1" + elif test -x "@bindir@/$1" + then + echo "@bindir@/$1" + else + echo "$1" + fi +} + +log_generic () { + [ $dry_run -eq 1 ] && return + priority="$1" + shift + + msg="`date +'%y%m%d %H:%M:%S'` mysqld_safe $*" + echo "$msg" + case $logging in + init) ;; # Just echo the message, don't save it anywhere + file) + if [ "$helper_exist" -eq "0" ]; then + echo "$msg" | "$helper" "$user" log "$err_log" + fi + ;; + syslog) logger -t "$syslog_tag_mysqld_safe" -p "$priority" "$*" ;; + *) + echo "Internal program error (non-fatal):" \ + " unknown logging method '$logging'" >&2 + ;; + esac +} + +log_error () { + log_generic daemon.error "$@" >&2 +} + +log_notice () { + log_generic daemon.notice "$@" +} + +eval_log_error () { + local cmd="$1" + case $logging in + file) + if [ "$helper_exist" -eq "0" ]; then + cmd="$cmd 2>&1 | "`shell_quote_string "$helper"`" $user log "`shell_quote_string "$err_log"` + fi + ;; + syslog) + # mysqld often prefixes its messages with a timestamp, which is + # redundant when logging to syslog (which adds its own timestamp) + # However, we don't strip the timestamp with sed here, because + # sed buffers output (only GNU sed supports a -u (unbuffered) option) + # which means that messages may not get sent to syslog until the + # mysqld process quits. + cmd="$cmd 2>&1 | logger -t '$syslog_tag_mysqld' -p daemon.error" + ;; + *) + echo "Internal program error (non-fatal):" \ + " unknown logging method '$logging'" >&2 + ;; + esac + + if test $nowatch -eq 1 + then + # We'd prefer to exec $cmd here, but SELinux needs to be fixed first + #/usr/bin/logger "Running mysqld: $cmd" + eval "$cmd &" + exit 0 + else + #echo "Running mysqld: [$cmd]" + eval "$cmd" + fi +} + +shell_quote_string() { + # This sed command makes sure that any special chars are quoted, + # so the arg gets passed exactly to the server. + echo "$1" | sed -e 's,\([^a-zA-Z0-9/_.=-]\),\\\1,g' +} + +wsrep_pick_url() { + [ $# -eq 0 ] && return 0 + + log_error "WSREP: 'wsrep_urls' is DEPRECATED! Use wsrep_cluster_address to specify multiple addresses instead." + + if ! command -v nc >/dev/null + then + log_error "ERROR: nc tool not found in PATH! Make sure you have it installed." + return 1 + fi + + local url + # Assuming URL in the form scheme://host:port + # If host and port are not NULL, the liveness of URL is assumed to be tested + # If port part is absent, the url is returned literally and unconditionally + # If every URL has port but none is reachable, nothing is returned + for url in `echo $@ | sed s/,/\ /g` 0; do + local host=`echo $url | cut -d \: -f 2 | sed s/^\\\/\\\///` + local port=`echo $url | cut -d \: -f 3` + [ -z "$port" ] && break + nc -z "$host" $port >/dev/null && break + done + + if [ "$url" == "0" ]; then + log_error "ERROR: none of the URLs in '$@' is reachable." + return 1 + fi + + echo $url +} + +# Run mysqld with --wsrep-recover and parse recovered position from log. +# Position will be stored in wsrep_start_position_opt global. +wsrep_start_position_opt="" +wsrep_recover_position() { + local mysqld_cmd="$@" + local euid=$(id -u) + local ret=0 + + local wr_logfile=$(mktemp /tmp/wsrep_recovery.XXXXXX) + + # safety checks + if [ -z $wr_logfile ]; then + log_error "WSREP: mktemp failed" + return 1 + fi + + if [ -f $wr_logfile ]; then + # NOTE! Do not change ownership of the temporary file, as on newer kernel + # versions fs.protected_regular is set to '2' and redirecting output with > + # as root to a file not owned by root will fail with "Permission denied" + chmod 600 $wr_logfile + else + log_error "WSREP: mktemp failed" + return 1 + fi + + local wr_pidfile="$DATADIR/"`@HOSTNAME@`"-recover.pid" + + local wr_options="--disable-log-error --pid-file='$wr_pidfile'" + + log_notice "WSREP: Running position recovery with $wr_options" + + eval "$mysqld_cmd --wsrep_recover $wr_options 2> $wr_logfile" + + if [ ! -s "$wr_logfile" ]; then + log_error "Log file $wr_logfile was empty, cannot proceed. Is system running fs.protected_regular?" + exit 1 + fi + + local rp="$(grep 'WSREP: Recovered position:' $wr_logfile)" + if [ -z "$rp" ]; then + local skipped="$(grep WSREP $wr_logfile | grep 'skipping position recovery')" + if [ -z "$skipped" ]; then + log_error "WSREP: Failed to recover position: '`cat $wr_logfile`'" + ret=1 + else + log_notice "WSREP: Position recovery skipped" + fi + else + local start_pos="$(echo $rp | sed 's/.*WSREP\:\ Recovered\ position://' \ + | sed 's/^[ \t]*//')" + log_notice "WSREP: Recovered position $start_pos" + wsrep_start_position_opt="--wsrep_start_position=$start_pos" + fi + + if [ $ret -eq 0 ] ; then + local wr_logfile_permanent="$DATADIR/wsrep_recovery.ok" + else + local wr_logfile_permanent="$DATADIR/wsrep_recovery.fail" + fi + touch $wr_logfile_permanent + [ "$euid" = "0" ] && chown $user $wr_logfile_permanent + chmod 600 $wr_logfile_permanent + cat "$wr_logfile" >> $wr_logfile_permanent + rm -f "$wr_logfile" + + return $ret +} + +parse_arguments() { + for arg do + val=`echo "$arg" | sed -e "s;--[^=]*=;;"` + case "$arg" in + # these get passed explicitly to mysqld + --basedir=*) MY_BASEDIR_VERSION="$val" ;; + --datadir=*|--data=*) DATADIR="$val" ;; + --pid[-_]file=*) pid_file="$val" ;; + --plugin[-_]dir=*) PLUGIN_DIR="$val" ;; + --user=*) user="$val"; SET_USER=1 ;; + --log[-_]basename=*|--hostname=*|--loose[-_]log[-_]basename=*) + pid_file="$val.pid"; + err_log_base="$val"; + ;; + + # these might have been set in a [mysqld_safe] section of my.cnf + # they are added to mysqld command line to override settings from my.cnf + --skip[-_]log[-_]error) + err_log=; + skip_err_log=1; + ;; + --log[-_]error=*) + err_log="$val"; + skip_err_log=0; + ;; + --port=*) mysql_tcp_port="$val" ;; + --socket=*) mysql_unix_port="$val" ;; + + # mysqld_safe-specific options - must be set in my.cnf ([mysqld_safe])! + --core[-_]file[-_]size=*) core_file_size="$val" ;; + --ledir=*) ledir="$val" ;; + --malloc[-_]lib=*) set_malloc_lib "$val" ;; + --crash[-_]script=*) crash_script="$val" ;; + --mysqld=*) MYSQLD="$val" ;; + --mysqld[-_]version=*) + if test -n "$val" + then + MYSQLD="mysqld-$val" + PLUGIN_VARIANT="/$val" + else + MYSQLD="mysqld" + fi + ;; + --dry[-_]run) dry_run=1 ;; + --nice=*) niceness="$val" ;; + --nowatch|--no[-_]watch|--no[-_]auto[-_]restart) nowatch=1 ;; + --open[-_]files[-_]limit=*) open_files="$val" ;; + --skip[-_]kill[-_]mysqld*) KILL_MYSQLD=0 ;; + --syslog) want_syslog=1 ;; + --skip[-_]syslog) want_syslog=0 ;; + --syslog[-_]tag=*) syslog_tag="$val" ;; + --timezone=*) TZ="$val"; export TZ; ;; + --flush[-_]caches) flush_caches=1 ;; + --numa[-_]interleave) numa_interleave=1 ;; + --wsrep[-_]on) + wsrep_on=1 + append_arg_to_args "$arg" + ;; + --skip[-_]wsrep[-_]on) + wsrep_on=0 + append_arg_to_args "$arg" + ;; + --wsrep[-_]on=*) + if echo $val | grep -iq '\(ON\|1\)'; then + wsrep_on=1 + else + wsrep_on=0 + fi + append_arg_to_args "$arg" + ;; + --wsrep[-_]urls=*) wsrep_urls="$val"; ;; + --wsrep[-_]provider=*) + if test -n "$val" && test "$val" != "none" + then + wsrep_restart=1 + fi + append_arg_to_args "$arg" + ;; + + --defaults-group-suffix=*) defaults_group_suffix="$arg" ;; + + --help) usage ;; + + *) + case "$unrecognized_handling" in + collect) append_arg_to_args "$arg" ;; + complain) log_error "unknown option '$arg'" ;; + esac + esac + done +} + + +# Add a single shared library to the list of libraries which will be added to +# LD_PRELOAD for mysqld +# +# Since LD_PRELOAD is a space-separated value (for historical reasons), if a +# shared lib's path contains spaces, that path will be prepended to +# LD_LIBRARY_PATH and stripped from the lib value. +add_mysqld_ld_preload() { + lib_to_add="$1" + log_notice "Adding '$lib_to_add' to LD_PRELOAD for mysqld" + + case "$lib_to_add" in + *' '*) + # Must strip path from lib, and add it to LD_LIBRARY_PATH + lib_file=`basename "$lib_to_add"` + case "$lib_file" in + *' '*) + # The lib file itself has a space in its name, and can't + # be used in LD_PRELOAD + log_error "library name '$lib_to_add' contains spaces and can not be used with LD_PRELOAD" + exit 1 + ;; + esac + lib_path=`dirname "$lib_to_add"` + lib_to_add="$lib_file" + [ -n "$mysqld_ld_library_path" ] && mysqld_ld_library_path="$mysqld_ld_library_path:" + mysqld_ld_library_path="$mysqld_ld_library_path$lib_path" + ;; + esac + + # LD_PRELOAD is a space-separated + [ -n "$mysqld_ld_preload" ] && mysqld_ld_preload="$mysqld_ld_preload " + mysqld_ld_preload="${mysqld_ld_preload}$lib_to_add" +} + + +# Returns LD_PRELOAD (and LD_LIBRARY_PATH, if needed) text, quoted to be +# suitable for use in the eval that calls mysqld. +# +# All values in mysqld_ld_preload are prepended to LD_PRELOAD. +mysqld_ld_preload_text() { + text= + + if [ -n "$mysqld_ld_preload" ]; then + new_text="$mysqld_ld_preload" + [ -n "$LD_PRELOAD" ] && new_text="$new_text $LD_PRELOAD" + text="${text}LD_PRELOAD="`shell_quote_string "$new_text"`' ' + fi + + if [ -n "$mysqld_ld_library_path" ]; then + new_text="$mysqld_ld_library_path" + [ -n "$LD_LIBRARY_PATH" ] && new_text="$new_text:$LD_LIBRARY_PATH" + text="${text}LD_LIBRARY_PATH="`shell_quote_string "$new_text"`' ' + fi + + echo "$text" +} + +# set_malloc_lib LIB +# - If LIB is empty, do nothing and return +# - If LIB starts with 'tcmalloc' or 'jemalloc', look for the shared library +# using `ldconfig`. +# tcmalloc is part of the Google perftools project. +# - If LIB is an absolute path, assume it is a malloc shared library +# +# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when +# running mysqld. See ld.so for details. +set_malloc_lib() { + malloc_lib="$1" + if expr "$malloc_lib" : "\(tcmalloc\|jemalloc\)" > /dev/null ; then + export PATH=$PATH:/sbin + if ! command -v ldconfig > /dev/null 2>&1 + then + log_error "ldconfig command not found, required for ldconfig -p" + exit 1 + fi + # format from ldconfig: + # "libjemalloc.so.1 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libjemalloc.so.1" + libmalloc_path="$(ldconfig -p | sed -n "/lib${malloc_lib}/p" | cut -d '>' -f2)" + + if [ -z "$libmalloc_path" ]; then + log_error "no shared library for lib$malloc_lib.so.[0-9] found." + exit 1 + fi + + for f in $libmalloc_path; do + if [ -f "$f" ]; then + malloc_lib=$f # get the first path if many + break + fi + done + fi + # Allow --malloc-lib='' to override other settings + [ -z "$malloc_lib" ] && return + + case "$malloc_lib" in + /*) + if [ ! -r "$malloc_lib" ]; then + log_error "--malloc-lib '$malloc_lib' can not be read and will not be used" + exit 1 + fi + ;; + *) + log_error "--malloc-lib must be an absolute path, 'tcmalloc' or " \ + "'jemalloc'; ignoring value '$malloc_lib'" + exit 1 + ;; + esac + add_mysqld_ld_preload "$malloc_lib" +} + + +# +# First, try to find BASEDIR and ledir (where mysqld is) +# + +MY_PWD=`dirname $0` +MY_PWD=`cd "$MY_PWD"/.. && pwd` +# Check for the directories we would expect from a binary release install +if test -n "$MY_BASEDIR_VERSION" -a -d "$MY_BASEDIR_VERSION" +then + # BASEDIR is already overridden on command line. Do not re-set. + + # Use BASEDIR to discover le. + if test -x "$MY_BASEDIR_VERSION/libexec/mariadbd" + then + ledir="$MY_BASEDIR_VERSION/libexec" + elif test -x "$MY_BASEDIR_VERSION/sbin/mariadbd" + then + ledir="$MY_BASEDIR_VERSION/sbin" + else + ledir="$MY_BASEDIR_VERSION/bin" + fi +elif test -x "$MY_PWD/bin/mariadbd" +then + MY_BASEDIR_VERSION="$MY_PWD" # Where bin, share and data are + ledir="$MY_PWD/bin" # Where mysqld is +# Check for the directories we would expect from a source install +elif test -x "$MY_PWD/libexec/mariadbd" +then + MY_BASEDIR_VERSION="$MY_PWD" # Where libexec, share and var are + ledir="$MY_PWD/libexec" # Where mysqld is +elif test -x "$MY_PWD/sbin/mariadbd" +then + MY_BASEDIR_VERSION="$MY_PWD" # Where sbin, share and var are + ledir="$MY_PWD/sbin" # Where mysqld is +# Since we didn't find anything, used the compiled-in defaults +else + MY_BASEDIR_VERSION='@prefix@' + ledir='@libexecdir@' +fi + +helper=`find_in_bin mysqld_safe_helper` +print_defaults=`find_in_bin my_print_defaults` +# Check if helper exists +command -v $helper --help >/dev/null 2>&1 +helper_exist=$? +# +# Second, try to find the data directory +# + +# Try where the binary installs put it +if test -d $MY_BASEDIR_VERSION/data/mysql +then + DATADIR=$MY_BASEDIR_VERSION/data +# Next try where the source installs put it +elif test -d $MY_BASEDIR_VERSION/var/mysql +then + DATADIR=$MY_BASEDIR_VERSION/var +# Or just give up and use our compiled-in default +else + DATADIR=@localstatedir@ +fi + +if test -z "$MYSQL_HOME" +then + if test -r "$DATADIR/my.cnf" + then + log_error "WARNING: Found $DATADIR/my.cnf +The data directory is not a valid location for my.cnf, please move it to +$MY_BASEDIR_VERSION/my.cnf" + fi + MYSQL_HOME=$MY_BASEDIR_VERSION +fi +export MYSQL_HOME + +append_arg_to_args () { + args="$args "`shell_quote_string "$1"` +} + +args= + +# Get first arguments from the my.cnf file, groups [mysqld] and [server] +# (and related) and then merge with the command line arguments + +SET_USER=2 +parse_arguments `$print_defaults $defaults --loose-verbose --mysqld` +if test $SET_USER -eq 2 +then + SET_USER=0 +fi + +# If arguments come from [mysqld_safe] section of my.cnf +# we complain about unrecognized options +unrecognized_handling=complain +parse_arguments `$print_defaults $defaults --loose-verbose mysqld_safe safe_mysqld mariadb_safe mariadbd-safe` + +# We only need to pass arguments through to the server if we don't +# handle them here. So, we collect unrecognized options (passed on +# the command line) into the args variable. +unrecognized_handling=collect +parse_arguments "$@" + + +# +# Try to find the plugin directory +# + +# Use user-supplied argument +if [ -n "${PLUGIN_DIR}" ]; then + plugin_dir="${PLUGIN_DIR}" +else + # Try to find plugin dir relative to basedir + for dir in lib64/mysql/plugin lib64/plugin lib/mysql/plugin lib/plugin + do + if [ -d "${MY_BASEDIR_VERSION}/${dir}" ]; then + plugin_dir="${MY_BASEDIR_VERSION}/${dir}" + break + fi + done + # Give up and use compiled-in default + if [ -z "${plugin_dir}" ]; then + plugin_dir='@pkgplugindir@' + fi +fi +plugin_dir="${plugin_dir}${PLUGIN_VARIANT}" + +# Determine what logging facility to use + +# Ensure that 'logger' exists, if it's requested +if [ $want_syslog -eq 1 ] +then + if ! command -v logger > /dev/null + then + log_error "--syslog requested, but no 'logger' program found. Please ensure that 'logger' is in your PATH, or do not specify the --syslog option to mysqld_safe." + exit 1 + fi +fi + +if [ $skip_err_log -eq 1 ] +then + append_arg_to_args "--skip-log-error" +fi + +if [ -n "$err_log" -o $want_syslog -eq 0 ] +then + if [ -n "$err_log" ] + then + # mysqld adds ".err" if there is no extension on the --log-error + # argument; must match that here, or mysqld_safe will write to a + # different log file than mysqld + + # mysqld does not add ".err" to "--log-error=foo."; it considers a + # trailing "." as an extension + + if expr "$err_log" : '.*\.[^/]*$' > /dev/null + then + : + else + err_log="$err_log".err + fi + + case "$err_log" in + /* ) ;; + * ) err_log="$DATADIR/$err_log" ;; + esac + else + if [ -n "$err_log_base" ] + then + err_log=$err_log_base.err + case "$err_log" in + /* ) ;; + * ) err_log="$DATADIR/$err_log" ;; + esac + else + err_log=$DATADIR/`@HOSTNAME@`.err + fi + fi + + append_arg_to_args "--log-error=$err_log" + + if [ $want_syslog -eq 1 ] + then + # User explicitly asked for syslog, so warn that it isn't used + log_error "Can't log to error log and syslog at the same time. Remove all --log-error configuration options for --syslog to take effect." + want_syslog=0 + fi + + # Log to err_log file + log_notice "Logging to '$err_log'." + logging=file + +else + if [ -n "$syslog_tag" ] + then + # Sanitize the syslog tag + syslog_tag=`echo "$syslog_tag" | sed -e 's/[^a-zA-Z0-9_-]/_/g'` + syslog_tag_mysqld_safe="${syslog_tag_mysqld_safe}-$syslog_tag" + syslog_tag_mysqld="${syslog_tag_mysqld}-$syslog_tag" + fi + log_notice "Logging to syslog." + logging=syslog +fi + +USER_OPTION="" +if test -w / -o "$USER" = "root" +then + if test "$user" != "root" -o $SET_USER = 1 + then + USER_OPTION="--user=$user" + fi + if test -n "$open_files" + then + ulimit -n $open_files + fi +fi + +if test -n "$open_files" +then + append_arg_to_args "--open-files-limit=$open_files" +fi + +safe_mysql_unix_port=${mysql_unix_port:-${MYSQL_UNIX_PORT:-@MYSQL_UNIX_ADDR@}} +# Make sure that directory for $safe_mysql_unix_port exists +mysql_unix_port_dir=`dirname $safe_mysql_unix_port` +if [ ! -d $mysql_unix_port_dir -a $dry_run -eq 0 ] +then + if ! mkdir -p $mysql_unix_port_dir + then + log_error "Fatal error Can't create database directory '$mysql_unix_port'" + exit 1 + fi + chown $user $mysql_unix_port_dir + chmod 755 $mysql_unix_port_dir +fi + +# If the user doesn't specify a binary, we assume name "mariadbd" +if test -z "$MYSQLD" +then + MYSQLD=mariadbd +fi + +if test ! -x "$ledir/$MYSQLD" +then + log_error "The file $ledir/$MYSQLD +does not exist or is not executable. Please cd to the mysql installation +directory and restart this script from there as follows: +./bin/mysqld_safe& +See https://mariadb.com/kb/en/mysqld_safe for more information" + exit 1 +fi + +if test -z "$pid_file" +then + pid_file="`@HOSTNAME@`.pid" +fi +# MariaDB wants pid file without datadir +append_arg_to_args "--pid-file=$pid_file" +case "$pid_file" in + /* ) ;; + * ) pid_file="$DATADIR/$pid_file" ;; +esac + +if test -n "$mysql_unix_port" +then + append_arg_to_args "--socket=$mysql_unix_port" +fi +if test -n "$mysql_tcp_port" +then + append_arg_to_args "--port=$mysql_tcp_port" +fi + +if test $niceness -eq 0 +then + NOHUP_NICENESS="nohup" +else + NOHUP_NICENESS="nohup nice -$niceness" +fi + +# Using nice with no args to get the niceness level is GNU-specific. +# This check could be extended for other operating systems (e.g., +# BSD could use "nohup sh -c 'ps -o nice -p $$' | tail -1"). +# But, it also seems that GNU nohup is the only one which messes +# with the priority, so this is okay. +if nohup nice > /dev/null 2>&1 +then + normal_niceness=`nice` + nohup_niceness=`nohup nice 2>/dev/null` + + numeric_nice_values=1 + for val in $normal_niceness $nohup_niceness + do + case "$val" in + -[0-9] | -[0-9][0-9] | -[0-9][0-9][0-9] | \ + [0-9] | [0-9][0-9] | [0-9][0-9][0-9] ) + ;; + * ) + numeric_nice_values=0 ;; + esac + done + + if test $numeric_nice_values -eq 1 + then + nice_value_diff=`expr $nohup_niceness - $normal_niceness` + if test $? -eq 0 && test $nice_value_diff -gt 0 && \ + nice --$nice_value_diff echo testing > /dev/null 2>&1 + then + # nohup increases the priority (bad), and we are permitted + # to lower the priority with respect to the value the user + # might have been given + niceness=`expr $niceness - $nice_value_diff` + NOHUP_NICENESS="nice -$niceness nohup" + fi + fi +else + if nohup echo testing > /dev/null 2>&1 + then + : + else + # nohup doesn't work on this system + NOHUP_NICENESS="" + fi +fi + +# Try to set the core file size (even if we aren't root) because many systems +# don't specify a hard limit on core file size. +if test -n "$core_file_size" +then + ulimit -c $core_file_size +fi + +# +# If there exists an old pid file, check if the daemon is already running +# Note: The switches to 'ps' may depend on your operating system +if test -f "$pid_file" && [ $dry_run -eq 0 ] +then + PID=`cat "$pid_file"` + if @CHECK_PID@ + then + if @FIND_PROC@ + then # The pid contains a mysqld process + log_error "A mysqld process already exists" + exit 1 + fi + fi + rm -f "$pid_file" + if test -f "$pid_file" + then + log_error "Fatal error: Can't remove the pid file: +$pid_file +Please remove it manually and start $0 again; +mysqld daemon not started" + exit 1 + fi +fi + +# +# Flush and purge buffers/caches. +# + +if @TARGET_LINUX@ && test $flush_caches -eq 1 +then + # Locate sync, ensure it exists. + if ! command -v sync > /dev/null + then + log_error "sync command not found, required for --flush-caches" + exit 1 + # Flush file system buffers. + elif ! sync + then + # Huh, the sync() function is always successful... + log_error "sync failed, check if sync is properly installed" + fi + + # Locate sysctl, ensure it exists. + if ! command -v sysctl > /dev/null + then + log_error "sysctl command not found, required for --flush-caches" + exit 1 + # Purge page cache, dentries and inodes. + elif ! sysctl -q -w vm.drop_caches=3 + then + log_error "sysctl failed, check the error message for details" + exit 1 + fi +elif test $flush_caches -eq 1 +then + log_error "--flush-caches is not supported on this platform" + exit 1 +fi + +# +# Uncomment the following lines if you want all tables to be automatically +# checked and repaired during startup. You should add sensible key_buffer +# and sort_buffer values to my.cnf to improve check performance or require +# less disk space. +# Alternatively, you can start mysqld with the "myisam-recover" option. See +# the manual for details. +# +# echo "Checking tables in $DATADIR" +# $MY_BASEDIR_VERSION/bin/myisamchk --silent --force --fast --medium-check $DATADIR/*/*.MYI +# $MY_BASEDIR_VERSION/bin/isamchk --silent --force $DATADIR/*/*.ISM + +# Does this work on all systems? +#if type ulimit | grep "shell builtin" > /dev/null +#then +# ulimit -n 256 > /dev/null 2>&1 # Fix for BSD and FreeBSD systems +#fi + +cmd="`mysqld_ld_preload_text`$NOHUP_NICENESS" +[ $dry_run -eq 1 ] && cmd='' + +# +# Set mysqld's memory interleave policy. +# + +if @TARGET_LINUX@ && test $numa_interleave -eq 1 +then + # Locate numactl, ensure it exists. + if ! command -v numactl > /dev/null + then + log_error "numactl command not found, required for --numa-interleave" + exit 1 + # Attempt to run a command, ensure it works. + elif ! numactl --interleave=all true + then + log_error "numactl failed, check if numactl is properly installed" + fi + + # Launch mysqld with numactl. + [ $dry_run -eq 0 ] && cmd="$cmd numactl --interleave=all" +elif test $numa_interleave -eq 1 +then + log_error "--numa-interleave is not supported on this platform" + exit 1 +fi + +for i in "$ledir/$MYSQLD" "$defaults_group_suffix" "$defaults" "--basedir=$MY_BASEDIR_VERSION" \ + "--datadir=$DATADIR" "--plugin-dir=$plugin_dir" "$USER_OPTION" +do + cmd="$cmd "`shell_quote_string "$i"` +done +cmd="$cmd $args" + +if [ $dry_run -eq 1 ] +then + # RETURN or EXIT depending if the script is being sourced or not. + (return 2> /dev/null) && return || exit +fi + + +# Avoid 'nohup: ignoring input' warning +test -n "$NOHUP_NICENESS" && cmd="$cmd < /dev/null" +log_notice "Starting $MYSQLD daemon with databases from $DATADIR" + +# variable to track the current number of "fast" (a.k.a. subsecond) restarts +fast_restart=0 +# maximum number of restarts before trottling kicks in +max_fast_restarts=5 +# flag whether a usable sleep command exists +have_sleep=1 + +# close stdout and stderr, everything goes to $logging now +if expr "${-}" : '.*x' > /dev/null +then + : +else + exec 1>/dev/null + exec 2>/dev/null +fi + +# maximum number of wsrep restarts +max_wsrep_restarts=0 + +while true +do + rm -f "$pid_file" # Some extra safety + + start_time=`date +%M%S` + + # Perform wsrep position recovery if wsrep_on=1, skip otherwise. + if test $wsrep_on -eq 1 + then + # this sets wsrep_start_position_opt + wsrep_recover_position "$cmd" + + [ $? -ne 0 ] && exit 1 # + + [ -n "$wsrep_urls" ] && url=`wsrep_pick_url $wsrep_urls` # check connect address + + if [ -z "$url" ] + then + eval_log_error "$cmd $wsrep_start_position_opt" + else + eval_log_error "$cmd $wsrep_start_position_opt --wsrep_cluster_address=$url" + fi + else + eval_log_error "$cmd" + fi + end_time=`date +%M%S` + + if test ! -f "$pid_file" # This is removed if normal shutdown + then + break + fi + + + # sanity check if time reading is sane and there's sleep + if test $end_time -gt 0 -a $have_sleep -gt 0 + then + # throttle down the fast restarts + if test $end_time -eq $start_time + then + fast_restart=`expr $fast_restart + 1` + if test $fast_restart -ge $max_fast_restarts + then + log_notice "The server is respawning too fast. Sleeping for 1 second." + sleep 1 + sleep_state=$? + if test $sleep_state -gt 0 + then + log_notice "The server is respawning too fast and no working sleep command. Turning off trottling." + have_sleep=0 + fi + + fast_restart=0 + fi + else + fast_restart=0 + fi + fi + + if @TARGET_LINUX@ && test $KILL_MYSQLD -eq 1 + then + # Test if one process was hanging. + # This is only a fix for Linux (running as base 3 mysqld processes) + # but should work for the rest of the servers. + # The only thing is ps x => redhat 5 gives warnings when using ps -x. + # kill -9 is used or the process won't react on the kill. + numofproces=`ps xaww | grep -v "grep" | grep "$ledir/$MYSQLD\>" | grep -c "pid-file=$pid_file"` + + log_notice "Number of processes running now: $numofproces" + I=1 + while test "$I" -le "$numofproces" + do + PROC=`ps xaww | grep "$ledir/$MYSQLD\>" | grep -v "grep" | grep "pid-file=$pid_file" | sed -n '$p'` + + for T in $PROC + do + break + done + # echo "TEST $I - $T **" + if kill -9 $T + then + log_error "$MYSQLD process hanging, pid $T - killed" + else + break + fi + I=`expr $I + 1` + done + fi + + if [ -n "$wsrep_restart" ] + then + if [ $wsrep_restart -le $max_wsrep_restarts ] + then + wsrep_restart=`expr $wsrep_restart + 1` + log_notice "WSREP: sleeping 15 seconds before restart" + sleep 15 + else + log_notice "WSREP: not restarting wsrep node automatically" + break + fi + fi + + log_notice "mysqld restarted" + if test -n "$crash_script" + then + crash_script_output=`$crash_script 2>&1` + log_error "$crash_script_output" + fi +done + +log_notice "mysqld from pid file $pid_file ended" diff --git a/scripts/mysqldumpslow.sh b/scripts/mysqldumpslow.sh new file mode 100644 index 00000000..5c46587e --- /dev/null +++ b/scripts/mysqldumpslow.sh @@ -0,0 +1,236 @@ +#!@PERL_PATH@ + +# Copyright (c) 2000, 2017, 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 Library 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 +# Library General Public License for more details. +# +# You should have received a copy of the GNU Library General Public +# License along with this library; if not, write to the Free +# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +# MA 02110-1335 USA + +# mysqldumpslow - parse and summarize the MySQL slow query log + +# Original version by Tim Bunce, sometime in 2000. +# Further changes by Tim Bunce, 8th March 2001. +# Handling of strings with \ and double '' by Monty 11 Aug 2001. + +use strict; +use Getopt::Long; + +# t=time, l=lock time, r=rows, a=rows affected +# at, al, ar and aa are the corresponding averages + +my %opt = ( + s => 'at', + h => '*', +); + +GetOptions(\%opt, + 'v|verbose+',# verbose + 'help+', # write usage info + 'd|debug+', # debug + 's=s', # what to sort by (aa, ae, al, ar, at, a, c, e, l, r, t) + 'r!', # reverse the sort order (largest last instead of first) + 't=i', # just show the top n queries + 'a!', # don't abstract all numbers to N and strings to 'S' + 'n=i', # abstract numbers with at least n digits within names + 'g=s', # grep: only consider stmts that include this string + 'h=s', # hostname/basename of db server for *-slow.log filename (can be wildcard) + 'i=s', # name of server instance (if using mysql.server startup script) + 'l!', # don't subtract lock time from total time +) or usage("bad option"); + +$opt{'help'} and usage(); + +unless (@ARGV) { + my $defaults = `my_print_defaults --mysqld`; + + my $datadir = ($defaults =~ m/--datadir=(.*)/g)[-1]; + if (!$datadir or $opt{i}) { + # determine the datadir from the instances section of /etc/my.cnf, if any + my $instances = `my_print_defaults instances`; + die "Can't determine datadir from 'my_print_defaults instances' output: $defaults" + unless $instances; + my @instances = ($instances =~ m/^--(\w+)-/mg); + die "No -i 'instance_name' specified to select among known instances: @instances.\n" + unless $opt{i}; + die "Instance '$opt{i}' is unknown (known instances: @instances)\n" + unless grep { $_ eq $opt{i} } @instances; + $datadir = ($instances =~ m/--$opt{i}-datadir=(.*)/g)[-1] + or die "Can't determine --$opt{i}-datadir from 'my_print_defaults instances' output: $instances"; + warn "datadir=$datadir\n" if $opt{v}; + } + + my $slowlog = ($defaults =~ m/--log[-_]slow[-_]queries=(.*)/g)[-1]; + if (!$slowlog) + { + $slowlog = ($defaults =~ m/--slow[-_]query[-_]log[-_]file=(.*)/g)[-1]; + } + if ( $slowlog ) + { + @ARGV = ($slowlog); + die "Can't find '$slowlog'\n" unless @ARGV; + } + else + { + if (!$opt{h}) + { + $opt{h}= ($defaults =~ m/--log[-_]basename=(.*)/g)[-1]; + } + @ARGV = <$datadir/$opt{h}-slow.log>; + die "Can't find '$datadir/$opt{h}-slow.log'\n" unless @ARGV; + } +} + +warn "\nReading mysql slow query log from @ARGV\n"; + +my @pending; +my %stmt; +$/ = ";\n#"; # read entire statements using paragraph mode +while ( defined($_ = shift @pending) or defined($_ = <>) ) { + warn "[[$_]]\n" if $opt{d}; # show raw paragraph being read + + my @chunks = split /^\/.*Version.*started with[\000-\377]*?Time.*Id.*Command.*Argument.*\n/m; + if (@chunks > 1) { + unshift @pending, map { length($_) ? $_ : () } @chunks; + warn "<<".join(">>\n<<",@chunks).">>" if $opt{d}; + next; + } + + s/^#? Time: \d{6}\s+\d+:\d+:\d+.*\n//; + my ($user,$host) = s/^#? User\@Host:\s+(\S+)\s+\@\s+(\S+).*\n// ? ($1,$2) : ('',''); + + s/^# Thread_id: [0-9]+\s+Schema: .*\s+QC_hit:.*[^\n]+\n//; + s/^# Query_time: ([0-9.]+)\s+Lock_time: ([0-9.]+)\s+Rows_sent: ([0-9.]+)\s+Rows_examined: ([0-9.]+).*\n//; + my ($t, $l, $r, $e) = ($1, $2, $3, $4); + s/^# Rows_affected: ([0-9.]+).*\n//; + my ($a) = ($1); + + $t -= $l unless $opt{l}; + + # remove fluff that mysqld writes to log when it (re)starts: + s!^/.*Version.*started with:.*\n!!mg; + s!^Tcp port: \d+ Unix socket: \S+\n!!mg; + s!^Time.*Id.*Command.*Argument.*\n!!mg; + + # Remove optimizer info + s!^# QC_Hit: \S+\s+Full_scan: \S+\s+Full_join: \S+\s+Tmp_table: \S+\s+Tmp_table_on_disk: \S+[^\n]+\n!!mg; + s!^# Filesort: \S+\s+Filesort_on_disk: \S+[^\n]+\n!!mg; + s!^# Full_scan: \S+\s+Full_join: \S+[^\n]+\n!!mg; + + s/^use \w+;\n//; # not consistently added + s/^SET timestamp=\d+;\n//; + + s/^[ ]*\n//mg; # delete blank lines + s/^[ ]*/ /mg; # normalize leading whitespace + s/\s*;\s*(#\s*)?$//; # remove trailing semicolon(+newline-hash) + + next if $opt{g} and !m/$opt{g}/io; + + unless ($opt{a}) { + s/\b\d+\b/N/g; + s/\b0x[0-9A-Fa-f]+\b/N/g; + s/''/'S'/g; + s/""/"S"/g; + s/(\\')//g; + s/(\\")//g; + s/'[^']+'/'S'/g; + s/"[^"]+"/"S"/g; + # -n=8: turn log_20001231 into log_NNNNNNNN + s/([a-z_]+)(\d{$opt{n},})/$1.('N' x length($2))/ieg if $opt{n}; + # abbreviate massive "in (...)" statements and similar + s!(([NS],){100,})!sprintf("$2,{repeated %d times}",length($1)/2)!eg; + } + + my $s = $stmt{$_} ||= { users=>{}, hosts=>{} }; + $s->{c} += 1; + $s->{t} += $t; + $s->{l} += $l; + $s->{r} += $r; + $s->{e} += $e; + $s->{a} += $a; + $s->{users}->{$user}++ if $user; + $s->{hosts}->{$host}++ if $host; + + warn "{{$_}}\n\n" if $opt{d}; # show processed statement string +} + +foreach (keys %stmt) { + my $v = $stmt{$_} || die; + my ($c, $t, $l, $r, $e, $a) = @{ $v }{qw(c t l r e a)}; + $v->{at} = $t / $c; + $v->{al} = $l / $c; + $v->{ar} = $r / $c; + $v->{ae} = $e / $c; + $v->{aa} = $a / $c; +} + +my @sorted = sort { $stmt{$b}->{$opt{s}} <=> $stmt{$a}->{$opt{s}} } keys %stmt; +@sorted = @sorted[0 .. $opt{t}-1] if $opt{t}; +@sorted = reverse @sorted if $opt{r}; + +foreach (@sorted) { + my $v = $stmt{$_} || die; + my ($c, $t, $at, $l, $al, $r, $ar, $e, $ae, $a, $aa) = @{ $v }{qw(c t at l al r ar e ae a aa)}; + my @users = keys %{$v->{users}}; + my $user = (@users==1) ? $users[0] : sprintf "%dusers",scalar @users; + my @hosts = keys %{$v->{hosts}}; + my $host = (@hosts==1) ? $hosts[0] : sprintf "%dhosts",scalar @hosts; + printf "Count: %d Time=%.2fs (%ds) Lock=%.2fs (%ds) Rows_sent=%.1f (%d), Rows_examined=%.1f (%d), Rows_affected=%.1f (%d), $user\@$host\n%s\n\n", + $c, $at,$t, $al,$l, $ar,$r, $ae, $e, $aa, $a, $_; +} + +sub usage { + my $str= shift; + my $text= <<HERE; +Usage: mysqldumpslow [ OPTS... ] [ LOGS... ] + +Parse and summarize the MySQL slow query log. Options are + + --verbose verbose + --debug debug + --help write this text to standard output + + -v verbose + -d debug + -s ORDER what to sort by (aa, ae, al, ar, at, a, c, e, l, r, t), 'at' is default + aa: average rows affected + ae: aggregated rows examined + al: average lock time + ar: average rows sent + at: average query time + a: rows affected + c: count + e: rows examined + l: lock time + r: rows sent + t: query time + -r reverse the sort order (largest last instead of first) + -t NUM just show the top n queries + -a don't abstract all numbers to N and strings to 'S' + -n NUM abstract numbers with at least n digits within names + -g PATTERN grep: only consider stmts that include this string + -h HOSTNAME hostname of db server for *-slow.log filename (can be wildcard), + default is '*', i.e. match all + -i NAME name of server instance (if using mysql.server startup script) + -l don't subtract lock time from total time + +HERE + if ($str) { + print STDERR "ERROR: $str\n\n"; + print STDERR $text; + exit 1; + } else { + print $text; + exit 0; + } +} diff --git a/scripts/mysqlhotcopy.sh b/scripts/mysqlhotcopy.sh new file mode 100644 index 00000000..44abcfec --- /dev/null +++ b/scripts/mysqlhotcopy.sh @@ -0,0 +1,1161 @@ +#!@PERL_PATH@ + +# Copyright (c) 2000, 2017, Oracle and/or its affiliates. +# +# This program is free software; you can redistribute it and/or +# modify it under the terms of the GNU Library 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 +# Library General Public License for more details. +# +# You should have received a copy of the GNU Library General Public +# License along with this library; if not, write to the Free +# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, +# MA 02110-1335 USA + +use strict; +use Getopt::Long; +use Data::Dumper; +use File::Basename; +use File::Path; +use DBI; +use Sys::Hostname; +use File::Copy; +use File::Temp qw(tempfile); + +=head1 NAME + +mysqlhotcopy - fast on-line hot-backup utility for local MySQL databases and tables + +=head1 SYNOPSIS + + mysqlhotcopy db_name + + mysqlhotcopy --suffix=_copy db_name_1 ... db_name_n + + mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory + + mysqlhotcopy db_name./regex/ + + mysqlhotcopy db_name./^\(foo\|bar\)/ + + mysqlhotcopy db_name./~regex/ + + mysqlhotcopy db_name_1./regex_1/ db_name_1./regex_2/ ... db_name_n./regex_n/ /path/to/new_directory + + mysqlhotcopy --method='scp -Bq -i /usr/home/foo/.ssh/identity' --user=root --password=secretpassword \ + db_1./^nice_table/ user@some.system.dom:~/path/to/new_directory + +WARNING: THIS PROGRAM IS STILL IN BETA. Comments/patches welcome. + +=cut + +# Documentation continued at end of file + +# fix CORE::GLOBAL::die to return a predictable exit code +BEGIN { *CORE::GLOBAL::die= sub { warn @_; exit 1; }; } + +my $VERSION = "1.23"; + +my $opt_tmpdir = $ENV{TMPDIR} || "/tmp"; + +my $OPTIONS = <<"_OPTIONS"; + +$0 Ver $VERSION + +Usage: $0 db_name[./table_regex/] [new_db_name | directory] + + -?, --help display this help-screen and exit + -u, --user=# user for database login if not current user + -p, --password=# password to use when connecting to server (if not set + in my.cnf, which is recommended) + -h, --host=# hostname for local server when connecting over TCP/IP + -P, --port=# port to use when connecting to local server with TCP/IP + -S, --socket=# socket to use when connecting to local server + --old_server connect to old MySQL-server (before v5.5) which + doesn't have FLUSH TABLES WITH READ LOCK fully implemented. + + --allowold don\'t abort if target dir already exists (rename it _old) + --addtodest don\'t rename target dir if it exists, just add files to it + --keepold don\'t delete previous (now renamed) target when done + --noindices don\'t include full index files in copy + --method=# method for copy (only "cp" currently supported) + + -q, --quiet be silent except for errors + --debug enable debug + -n, --dryrun report actions without doing them + + --regexp=# copy all databases with names matching regexp + --suffix=# suffix for names of copied databases + --checkpoint=# insert checkpoint entry into specified db.table + --flushlog flush logs once all tables are locked + --resetmaster reset the binlog once all tables are locked + --resetslave reset the master.info once all tables are locked + --tmpdir=# temporary directory (instead of $opt_tmpdir) + --record_log_pos=# record slave and master status in specified db.table + --chroot=# base directory of chroot jail in which mysqld operates + + Try \'perldoc $0\' for more complete documentation +_OPTIONS + +sub usage { + die @_, $OPTIONS; +} + +# Do not initialize user or password options; that way, any user/password +# options specified in option files will be used. If no values are specified +# at all, the defaults will be used (login name, no password). + +my %opt = ( + noindices => 0, + allowold => 0, # for safety + keepold => 0, + method => "cp", + flushlog => 0, +); +Getopt::Long::Configure(qw(no_ignore_case)); # disambiguate -p and -P +GetOptions( \%opt, + "help", + "host|h=s", + "user|u=s", + "password|p=s", + "port|P=s", + "socket|S=s", + "old_server", + "allowold!", + "keepold!", + "addtodest!", + "noindices!", + "method=s", + "debug", + "quiet|q", + "mv!", + "regexp=s", + "suffix=s", + "checkpoint=s", + "record_log_pos=s", + "flushlog", + "resetmaster", + "resetslave", + "tmpdir|t=s", + "dryrun|n", + "chroot=s", +) or usage("Invalid option"); + +# @db_desc +# ========== +# a list of hash-refs containing: +# +# 'src' - name of the db to copy +# 't_regex' - regex describing tables in src +# 'target' - destination directory of the copy +# 'tables' - array-ref to list of tables in the db +# 'files' - array-ref to list of files to be copied +# 'index' - array-ref to list of indexes to be copied +# + +my @db_desc = (); +my $tgt_name = undef; + +usage("") if ($opt{help}); + +if ( $opt{regexp} || $opt{suffix} || @ARGV > 2 ) { + $tgt_name = pop @ARGV unless ( exists $opt{suffix} ); + @db_desc = map { s{^([^\.]+)\./(.+)/$}{$1}; { 'src' => $_, 't_regex' => ( $2 ? $2 : '.*' ) } } @ARGV; +} +else { + usage("Database name to hotcopy not specified") unless ( @ARGV ); + + $ARGV[0] =~ s{^([^\.]+)\./(.+)/$}{$1}; + @db_desc = ( { 'src' => $ARGV[0], 't_regex' => ( $2 ? $2 : '.*' ) } ); + + if ( @ARGV == 2 ) { + $tgt_name = $ARGV[1]; + } + else { + $opt{suffix} = "_copy"; + } +} + +my %mysqld_vars; +my $start_time = time; +$opt_tmpdir= $opt{tmpdir} if $opt{tmpdir}; +$0 = $1 if $0 =~ m:/([^/]+)$:; +$opt{quiet} = 0 if $opt{debug}; +$opt{allowold} = 1 if $opt{keepold}; + +# --- connect to the database --- +my $dsn; +$dsn = ";host=" . (defined($opt{host}) ? $opt{host} : "localhost"); +$dsn .= ";port=$opt{port}" if $opt{port}; +$dsn .= ";mariadb_socket=$opt{socket}" if $opt{socket}; + +# use mariadb_read_default_group=mysqlhotcopy so that [client] and +# [mysqlhotcopy] groups will be read from standard options files. + +my $dbh = DBI->connect("DBI:MariaDB:$dsn;mariadb_read_default_group=mysqlhotcopy", + $opt{user}, $opt{password}, +{ + RaiseError => 1, + PrintError => 0, + AutoCommit => 1, +}); + +# --- check that checkpoint table exists if specified --- +if ( $opt{checkpoint} ) { + $opt{checkpoint} = quote_names( $opt{checkpoint} ); + eval { $dbh->do( qq{ select time_stamp, src, dest, msg + from $opt{checkpoint} where 1 != 1} ); + }; + + die "Error accessing Checkpoint table ($opt{checkpoint}): $@" + if ( $@ ); +} + +# --- check that log_pos table exists if specified --- +if ( $opt{record_log_pos} ) { + $opt{record_log_pos} = quote_names( $opt{record_log_pos} ); + + eval { $dbh->do( qq{ select host, time_stamp, log_file, log_pos, master_host, master_log_file, master_log_pos + from $opt{record_log_pos} where 1 != 1} ); + }; + + die "Error accessing log_pos table ($opt{record_log_pos}): $@" + if ( $@ ); +} + +# --- get variables from database --- +my $sth_vars = $dbh->prepare("show variables like 'datadir'"); +$sth_vars->execute; +while ( my ($var,$value) = $sth_vars->fetchrow_array ) { + $mysqld_vars{ $var } = $value; +} +my $datadir = $mysqld_vars{'datadir'} + || die "datadir not in mysqld variables"; + $datadir= $opt{chroot}.$datadir if ($opt{chroot}); +$datadir =~ s:/$::; + + +# --- get target path --- +my ($tgt_dirname, $to_other_database); +$to_other_database=0; +if (defined($tgt_name) && $tgt_name =~ m:^\w+$: && @db_desc <= 1) +{ + $tgt_dirname = "$datadir/$tgt_name"; + $to_other_database=1; +} +elsif (defined($tgt_name) && ($tgt_name =~ m:/: || $tgt_name eq '.')) { + $tgt_dirname = $tgt_name; +} +elsif ( $opt{suffix} ) { + print "Using copy suffix '$opt{suffix}'\n" unless $opt{quiet}; +} +else +{ + $tgt_name="" if (!defined($tgt_name)); + die "Target '$tgt_name' doesn't look like a database name or directory path.\n"; +} + +# --- resolve database names from regexp --- +if ( defined $opt{regexp} ) { + my $t_regex = '.*'; + if ( $opt{regexp} =~ s{^/(.+)/\./(.+)/$}{$1} ) { + $t_regex = $2; + } + + my $sth_dbs = $dbh->prepare("show databases"); + $sth_dbs->execute; + while ( my ($db_name) = $sth_dbs->fetchrow_array ) { + next if $db_name =~ m/^information_schema$/i; + push @db_desc, { 'src' => $db_name, 't_regex' => $t_regex } if ( $db_name =~ m/$opt{regexp}/o ); + } +} + +# --- get list of tables and views to hotcopy --- + +my $hc_locks = ""; +my $hc_tables = ""; +my $hc_base_tables = ""; +my $hc_views = ""; +my $num_base_tables = 0; +my $num_views = 0; +my $num_tables = 0; +my $num_files = 0; + +foreach my $rdb ( @db_desc ) { + my $db = $rdb->{src}; + my @dbh_base_tables = get_list_of_tables( $db ); + my @dbh_views = get_list_of_views( $db ); + + ## filter out certain system non-lockable tables. + ## keep in sync with mysqldump. + if ($db =~ m/^mysql$/i) + { + @dbh_base_tables = grep + { !/^(apply_status|schema|general_log|slow_log|transaction_registry)$/ } @dbh_base_tables + } + + ## generate regex for tables/files + my $t_regex; + my $negated; + if ($rdb->{t_regex}) { + $t_regex = $rdb->{t_regex}; ## assign temporary regex + $negated = $t_regex =~ s/^~//; ## note and remove negation operator + + $t_regex = qr/$t_regex/; ## make regex string from + ## user regex + + ## filter (out) tables specified in t_regex + print "Filtering tables with '$t_regex'\n" if $opt{debug}; + @dbh_base_tables = ( $negated + ? grep { $_ !~ $t_regex } @dbh_base_tables + : grep { $_ =~ $t_regex } @dbh_base_tables ); + + ## filter (out) views specified in t_regex + print "Filtering tables with '$t_regex'\n" if $opt{debug}; + @dbh_views = ( $negated + ? grep { $_ !~ $t_regex } @dbh_views + : grep { $_ =~ $t_regex } @dbh_views ); + } + + ## Now concatenate the base table and view arrays. + my @dbh_tables = (@dbh_base_tables, @dbh_views); + + ## get list of files to copy + my $db_dir = "$datadir/$db"; + opendir(DBDIR, $db_dir ) + or die "Cannot open dir '$db_dir': $!"; + + my %db_files; + + while ( defined( my $name = readdir DBDIR ) ) { + $db_files{$name} = $1 if ( $name =~ /(.+)\.\w+$/ ); + } + closedir( DBDIR ); + + unless( keys %db_files ) { + warn "'$db' is an empty database\n"; + } + + ## filter (out) files specified in t_regex + my @db_files; + if ($rdb->{t_regex}) { + @db_files = ($negated + ? grep { $db_files{$_} !~ $t_regex } keys %db_files + : grep { $db_files{$_} =~ $t_regex } keys %db_files ); + } + else { + @db_files = keys %db_files; + } + + @db_files = sort @db_files; + + my @index_files=(); + + ## remove indices unless we're told to keep them + if ($opt{noindices}) { + @index_files= grep { /\.(ISM|MYI)$/ } @db_files; + @db_files = grep { not /\.(ISM|MYI)$/ } @db_files; + } + + $rdb->{files} = [ @db_files ]; + $rdb->{index} = [ @index_files ]; + my @hc_base_tables = map { quote_names("$db.$_") } @dbh_base_tables; + my @hc_views = map { quote_names("$db.$_") } @dbh_views; + + my @hc_tables = (@hc_base_tables, @hc_views); + $rdb->{tables} = [ @hc_tables ]; + + $hc_locks .= ", " if ( length $hc_locks && @hc_tables ); + $hc_locks .= join ", ", map { "$_ READ" } @hc_tables; + + $hc_base_tables .= ", " if ( length $hc_base_tables && @hc_base_tables ); + $hc_base_tables .= join ", ", @hc_base_tables; + $hc_views .= ", " if ( length $hc_views && @hc_views ); + $hc_views .= join " READ, ", @hc_views; + + @hc_tables = (@hc_base_tables, @hc_views); + + $num_base_tables += scalar @hc_base_tables; + $num_views += scalar @hc_views; + $num_tables += $num_base_tables + $num_views; + $num_files += scalar @{$rdb->{files}}; +} + +# --- resolve targets for copies --- + +if (defined($tgt_name) && length $tgt_name ) { + # explicit destination directory specified + + # GNU `cp -r` error message + die "copying multiple databases, but last argument ($tgt_dirname) is not a directory\n" + if ( @db_desc > 1 && !(-e $tgt_dirname && -d $tgt_dirname ) ); + + if ($to_other_database) + { + foreach my $rdb ( @db_desc ) { + $rdb->{target} = "$tgt_dirname"; + } + } + elsif ($opt{method} =~ /^scp\b/) + { # we have to trust scp to hit the target + foreach my $rdb ( @db_desc ) { + $rdb->{target} = "$tgt_dirname/$rdb->{src}"; + } + } + else + { + die "Last argument ($tgt_dirname) is not a directory\n" + if (!(-e $tgt_dirname && -d $tgt_dirname ) ); + foreach my $rdb ( @db_desc ) { + $rdb->{target} = "$tgt_dirname/$rdb->{src}"; + } + } + } +else { + die "Error: expected \$opt{suffix} to exist" unless ( exists $opt{suffix} ); + + foreach my $rdb ( @db_desc ) { + $rdb->{target} = "$datadir/$rdb->{src}$opt{suffix}"; + } +} + +print Dumper( \@db_desc ) if ( $opt{debug} ); + +# --- bail out if all specified databases are empty --- + +die "No tables to hot-copy" unless ( length $hc_locks ); + +# --- create target directories if we are using 'cp' --- + +my @existing = (); + +if ($opt{method} =~ /^cp\b/) +{ + foreach my $rdb ( @db_desc ) { + push @existing, $rdb->{target} if ( -d $rdb->{target} ); + } + + if ( @existing && !($opt{allowold} || $opt{addtodest}) ) + { + $dbh->disconnect(); + die "Can't hotcopy to '", join( "','", @existing ), "' because directory\nalready exist and the --allowold or --addtodest options were not given.\n" + } +} + +retire_directory( @existing ) if @existing && !$opt{addtodest}; + +foreach my $rdb ( @db_desc ) { + my $tgt_dirpath = "$rdb->{target}"; + # Remove trailing slashes (needed for Mac OS X) + substr($tgt_dirpath, 1) =~ s|/+$||; + if ( $opt{dryrun} ) { + print "mkdir $tgt_dirpath, 0750\n"; + } + elsif ($opt{method} =~ /^scp\b/) { + ## assume it's there? + ## ... + } + else { + mkdir($tgt_dirpath, 0750) or die "Can't create '$tgt_dirpath': $!\n" + unless -d $tgt_dirpath; + my @f_info= stat "$datadir/$rdb->{src}"; + chown $f_info[4], $f_info[5], $tgt_dirpath; + } +} + +############################## +# --- PERFORM THE HOT-COPY --- +# +# Note that we try to keep the time between the LOCK and the UNLOCK +# as short as possible, and only start when we know that we should +# be able to complete without error. + +# read lock all the tables we'll be copying +# in order to get a consistent snapshot of the database + +if ( $opt{checkpoint} || $opt{record_log_pos} ) { + # convert existing READ lock on checkpoint and/or log_pos table into WRITE lock + foreach my $table ( grep { defined } ( $opt{checkpoint}, $opt{record_log_pos} ) ) { + $hc_locks .= ", $table WRITE" + unless ( $hc_locks =~ s/$table\s+READ/$table WRITE/ ); + } +} + +my $hc_started = time; # count from time lock is granted + +if ( $opt{dryrun} ) { + if ( $opt{old_server} ) { + print "LOCK TABLES $hc_locks\n"; + print "FLUSH TABLES /*!32323 $hc_tables */\n"; + } + else { + # Lock base tables and views separately. + print "FLUSH TABLES $hc_base_tables WITH READ LOCK\n" + if ( $hc_base_tables ); + print "LOCK TABLES $hc_views READ\n" if ( $hc_views ); + } + + print "FLUSH LOGS\n" if ( $opt{flushlog} ); + print "RESET MASTER\n" if ( $opt{resetmaster} ); + print "RESET SLAVE\n" if ( $opt{resetslave} ); +} +else { + my $start = time; + if ( $opt{old_server} ) { + $dbh->do("LOCK TABLES $hc_locks"); + printf "Locked $num_tables tables in %d seconds.\n", time-$start unless $opt{quiet}; + $hc_started = time; # count from time lock is granted + + # flush tables to make on-disk copy up to date + $start = time; + $dbh->do("FLUSH TABLES /*!32323 $hc_tables */"); + printf "Flushed tables ($hc_tables) in %d seconds.\n", time-$start unless $opt{quiet}; + } + else { + # Lock base tables and views separately, as 'FLUSH TABLES <tbl_name> + # ... WITH READ LOCK' (introduced in 5.5) would fail for views. + # Also, flush tables to make on-disk copy up to date + $dbh->do("FLUSH TABLES $hc_base_tables WITH READ LOCK") + if ( $hc_base_tables ); + printf "Flushed $num_base_tables tables with read lock ($hc_base_tables) in %d seconds.\n", + time-$start unless $opt{quiet}; + + $start = time; + $dbh->do("LOCK TABLES $hc_views READ") if ( $hc_views ); + printf "Locked $num_views views ($hc_views) in %d seconds.\n", + time-$start unless $opt{quiet}; + + $hc_started = time; # count from time lock is granted + } + $dbh->do( "FLUSH LOGS" ) if ( $opt{flushlog} ); + $dbh->do( "RESET MASTER" ) if ( $opt{resetmaster} ); + $dbh->do( "RESET SLAVE" ) if ( $opt{resetslave} ); + + if ( $opt{record_log_pos} ) { + record_log_pos( $dbh, $opt{record_log_pos} ); + $dbh->do("FLUSH TABLES /*!32323 $hc_tables */"); + } +} + +my @failed = (); + +foreach my $rdb ( @db_desc ) +{ + my @files = map { "$datadir/$rdb->{src}/$_" } @{$rdb->{files}}; + next unless @files; + + eval { copy_files($opt{method}, \@files, $rdb->{target}); }; + push @failed, "$rdb->{src} -> $rdb->{target} failed: $@" + if ( $@ ); + + @files = @{$rdb->{index}}; + if ($rdb->{index}) + { + copy_index($opt{method}, \@files, + "$datadir/$rdb->{src}", $rdb->{target} ); + } + + if ( $opt{checkpoint} ) { + my $msg = ( $@ ) ? "Failed: $@" : "Succeeded"; + + eval { + $dbh->do( qq{ insert into $opt{checkpoint} (src, dest, msg) + VALUES ( '$rdb->{src}', '$rdb->{target}', '$msg' ) + } ); + }; + + if ( $@ ) { + warn "Failed to update checkpoint table: $@\n"; + } + } +} + +if ( $opt{dryrun} ) { + print "UNLOCK TABLES\n"; + if ( @existing && !$opt{keepold} ) { + my @oldies = map { $_ . '_old' } @existing; + print "rm -rf @oldies\n" + } + $dbh->disconnect(); + exit(0); +} +else { + $dbh->do("UNLOCK TABLES"); +} + +my $hc_dur = time - $hc_started; +printf "Unlocked tables.\n" unless $opt{quiet}; + +# +# --- HOT-COPY COMPLETE --- +########################### + +$dbh->disconnect; + +if ( @failed ) { + # hotcopy failed - cleanup + # delete any @targets + # rename _old copy back to original + + my @targets = (); + foreach my $rdb ( @db_desc ) { + push @targets, $rdb->{target} if ( -d $rdb->{target} ); + } + print "Deleting @targets \n" if $opt{debug}; + + print "Deleting @targets \n" if $opt{debug}; + rmtree([@targets]); + if (@existing) { + print "Restoring @existing from back-up\n" if $opt{debug}; + foreach my $dir ( @existing ) { + rename("${dir}_old", $dir ) + or warn "Can't rename ${dir}_old to $dir: $!\n"; + } + } + + die join( "\n", @failed ); +} +else { + # hotcopy worked + # delete _old unless $opt{keepold} + + if ( @existing && !$opt{keepold} ) { + my @oldies = map { $_ . '_old' } @existing; + print "Deleting previous copy in @oldies\n" if $opt{debug}; + rmtree([@oldies]); + } + + printf "$0 copied %d tables (%d files) in %d second%s (%d seconds overall).\n", + $num_tables, $num_files, + $hc_dur, ($hc_dur==1)?"":"s", time - $start_time + unless $opt{quiet}; +} + +exit 0; + + +# --- + +sub copy_files { + my ($method, $files, $target) = @_; + my @cmd; + print "Copying ".@$files." files...\n" unless $opt{quiet}; + + if ($method =~ /^s?cp\b/) # cp or scp with optional flags + { + my $cp = $method; + # add option to preserve mod time etc of copied files + # not critical, but nice to have + $cp.= " -p" if $^O =~ m/^(solaris|linux|freebsd|darwin)$/; + + # add recursive option for scp + $cp.= " -r" if $^O =~ /m^(solaris|linux|freebsd|darwin)$/ && $method =~ /^scp\b/; + + # perform the actual copy + safe_system( $cp, (map { "'$_'" } @$files), "'$target'" ); + } + else + { + die "Can't use unsupported method '$method'\n"; + } +} + +# +# Copy only the header of the index file +# + +sub copy_index +{ + my ($method, $files, $source, $target) = @_; + + print "Copying indices for ".@$files." files...\n" unless $opt{quiet}; + foreach my $file (@$files) + { + my $from="$source/$file"; + my $to="$target/$file"; + my $buff; + open(INPUT, "<$from") || die "Can't open file $from: $!\n"; + binmode(INPUT, ":raw"); + my $length=read INPUT, $buff, 2048; + die "Can't read index header from $from\n" if ($length < 1024); + close INPUT; + + if ( $opt{dryrun} ) + { + print "$opt{method}-header $from $to\n"; + } + elsif ($opt{method} eq 'cp') + { + open(OUTPUT,">$to") || die "Can\'t create file $to: $!\n"; + if (syswrite(OUTPUT,$buff) != length($buff)) + { + die "Error when writing data to $to: $!\n"; + } + close OUTPUT || die "Error on close of $to: $!\n"; + } + elsif ($opt{method} =~ /^scp\b/) + { + my ($fh, $tmp)= tempfile('mysqlhotcopy-XXXXXX', DIR => $opt_tmpdir) or + die "Can\'t create/open file in $opt_tmpdir\n"; + if (syswrite($fh,$buff) != length($buff)) + { + die "Error when writing data to $tmp: $!\n"; + } + close $fh || die "Error on close of $tmp: $!\n"; + safe_system("$opt{method} $tmp $to"); + unlink $tmp; + } + else + { + die "Can't use unsupported method '$opt{method}'\n"; + } + } +} + + +sub safe_system { + my @sources= @_; + my $method= shift @sources; + my $target= pop @sources; + ## @sources = list of source file names + + ## We have to deal with very long command lines, otherwise they may generate + ## "Argument list too long". + ## With 10000 tables the command line can be around 1MB, much more than 128kB + ## which is the common limit on Linux (can be read from + ## /usr/src/linux/include/linux/binfmts.h + ## see http://www.linuxjournal.com/article.php?sid=6060). + + my $chunk_limit= 100 * 1024; # 100 kB + my @chunk= (); + my $chunk_length= 0; + foreach (@sources) { + push @chunk, $_; + $chunk_length+= length($_); + if ($chunk_length > $chunk_limit) { + safe_simple_system($method, @chunk, $target); + @chunk=(); + $chunk_length= 0; + } + } + if ($chunk_length > 0) { # do not forget last small chunk + safe_simple_system($method, @chunk, $target); + } +} + +sub safe_simple_system { + my @cmd= @_; + + if ( $opt{dryrun} ) { + print "@cmd\n"; + } + else { + ## for some reason system fails but backticks works ok for scp... + print "Executing '@cmd'\n" if $opt{debug}; + my $cp_status = system "@cmd > /dev/null"; + if ($cp_status != 0) { + warn "Executing command failed ($cp_status). Trying backtick execution...\n"; + ## try something else + `@cmd` || die "Error: @cmd failed ($?) while copying files.\n"; + } + } +} + +sub retire_directory { + my ( @dir ) = @_; + + foreach my $dir ( @dir ) { + my $tgt_oldpath = $dir . '_old'; + if ( $opt{dryrun} ) { + print "rmtree $tgt_oldpath\n" if ( -d $tgt_oldpath ); + print "rename $dir, $tgt_oldpath\n"; + next; + } + + if ( -d $tgt_oldpath ) { + print "Deleting previous 'old' hotcopy directory ('$tgt_oldpath')\n" unless $opt{quiet}; + rmtree([$tgt_oldpath],0,1); + } + rename($dir, $tgt_oldpath) + or die "Can't rename $dir=>$tgt_oldpath: $!\n"; + print "Existing hotcopy directory renamed to '$tgt_oldpath'\n" unless $opt{quiet}; + } +} + +sub record_log_pos { + my ( $dbh, $table_name ) = @_; + + eval { + my ($file,$position) = get_row( $dbh, "show master status" ); + die "master status is undefined" if !defined $file || !defined $position; + + my $row_hash = get_row_hash( $dbh, "show slave status" ); + my ($master_host, $log_file, $log_pos ); + if ( $dbh->{mariadb_serverinfo} =~ /^3\.23/ ) { + ($master_host, $log_file, $log_pos ) + = @{$row_hash}{ qw / Master_Host Log_File Pos / }; + } else { + ($master_host, $log_file, $log_pos ) + = @{$row_hash}{ qw / Master_Host Relay_Master_Log_File Exec_Master_Log_Pos / }; + } + my $hostname = hostname(); + + $dbh->do( qq{ replace into $table_name + set host=?, log_file=?, log_pos=?, + master_host=?, master_log_file=?, master_log_pos=? }, + undef, + $hostname, $file, $position, + $master_host, $log_file, $log_pos ); + + }; + + if ( $@ ) { + warn "Failed to store master position: $@\n"; + } +} + +sub get_row { + my ( $dbh, $sql ) = @_; + + my $sth = $dbh->prepare($sql); + $sth->execute; + return $sth->fetchrow_array(); +} + +sub get_row_hash { + my ( $dbh, $sql ) = @_; + + my $sth = $dbh->prepare($sql); + $sth->execute; + return $sth->fetchrow_hashref(); +} + +sub get_list_of_tables { + my ( $db ) = @_; + + my $tables = + eval { + $dbh->selectall_arrayref('SHOW FULL TABLES FROM ' . + $dbh->quote_identifier($db) . + ' WHERE Table_type = \'BASE TABLE\'') + } || []; + warn "Unable to retrieve list of tables in $db: $@" if $@; + + return (map { $_->[0] } @$tables); +} + +sub get_list_of_views { + my ( $db ) = @_; + + my $views = + eval { + $dbh->selectall_arrayref('SHOW FULL TABLES FROM ' . + $dbh->quote_identifier($db) . + ' WHERE Table_type = \'VIEW\'') + } || []; + warn "Unable to retrieve list of views in $db: $@" if $@; + + return (map { $_->[0] } @$views); +} + +sub quote_names { + my ( $name ) = @_; + # given a db.table name, add quotes + + my ($db, $table, @cruft) = split( /\./, $name ); + die "Invalid db.table name '$name'" if (@cruft || !defined $db || !defined $table ); + + # Earlier versions of DBD return table name non-quoted, + # such as DBD-2.1012 and the newer ones, such as DBD-2.9002 + # returns it quoted. Let's have a support for both. + $table=~ s/\`//g; + return "`$db`.`$table`"; +} + +__END__ + +=head1 DESCRIPTION + +mysqlhotcopy is designed to make stable copies of live MySQL databases. + +Here "live" means that the database server is running and the database +may be in active use. And "stable" means that the copy will not have +any corruptions that could occur if the table files were simply copied +without first being locked and flushed from within the server. + +=head1 OPTIONS + +=over 4 + +=item --checkpoint checkpoint-table + +As each database is copied, an entry is written to the specified +checkpoint-table. This has the happy side-effect of updating the +MySQL update-log (if it is switched on) giving a good indication of +where roll-forward should begin for backup+rollforward schemes. + +The name of the checkpoint table should be supplied in database.table format. +The checkpoint-table must contain at least the following fields: + +=over 4 + + time_stamp timestamp not null + src varchar(32) + dest varchar(60) + msg varchar(255) + +=back + +=item --record_log_pos log-pos-table + +Just before the database files are copied, update the record in the +log-pos-table from the values returned from "show master status" and +"show slave status". The master status values are stored in the +log_file and log_pos columns, and establish the position in the binary +logs that any slaves of this host should adopt if initialised from +this dump. The slave status values are stored in master_host, +master_log_file, and master_log_pos, corresponding to the coordinates +of the next to the last event the slave has executed. The slave or its +siblings can connect to the master next time and request replication +starting from the recorded values. + +The name of the log-pos table should be supplied in database.table format. +A sample log-pos table definition: + +=over 4 + +CREATE TABLE log_pos ( + host varchar(60) NOT null, + time_stamp timestamp NOT NULL, + log_file varchar(32) default NULL, + log_pos int(11) default NULL, + master_host varchar(60) NULL, + master_log_file varchar(32) NULL, + master_log_pos int NULL, + + PRIMARY KEY (host) +); + +=back + + +=item --suffix suffix + +Each database is copied back into the originating datadir under +a new name. The new name is the original name with the suffix +appended. + +If only a single db_name is supplied and the --suffix flag is not +supplied, then "--suffix=_copy" is assumed. + +=item --allowold + +Move any existing version of the destination to a backup directory for +the duration of the copy. If the copy successfully completes, the backup +directory is deleted - unless the --keepold flag is set. If the copy fails, +the backup directory is restored. + +The backup directory name is the original name with "_old" appended. +Any existing versions of the backup directory are deleted. + +=item --keepold + +Behaves as for the --allowold, with the additional feature +of keeping the backup directory after the copy successfully completes. + +=item --addtodest + +Don't rename target directory if it already exists, just add the +copied files into it. + +This is most useful when backing up a database with many large +tables and you don't want to have all the tables locked for the +whole duration. + +In this situation, I<if> you are happy for groups of tables to be +backed up separately (and thus possibly not be logically consistent +with one another) then you can run mysqlhotcopy several times on +the same database each with different db_name./table_regex/. +All but the first should use the --addtodest option so the tables +all end up in the same directory. + +=item --flushlog + +Rotate the log files by executing "FLUSH LOGS" after all tables are +locked, and before they are copied. + +=item --resetmaster + +Reset the bin-log by executing "RESET MASTER" after all tables are +locked, and before they are copied. Useful if you are recovering a +slave in a replication setup. + +=item --resetslave + +Reset the master.info by executing "RESET SLAVE" after all tables are +locked, and before they are copied. Useful if you are recovering a +server in a mutual replication setup. + +=item --regexp pattern + +Copy all databases with names matching the pattern. + +=item --regexp /pattern1/./pattern2/ + +Copy all tables with names matching pattern2 from all databases with +names matching pattern1. For example, to select all tables which +names begin with 'bar' from all databases which names end with 'foo': + + mysqlhotcopy --indices --method=cp --regexp /foo$/./^bar/ + +=item db_name./pattern/ + +Copy only tables matching pattern. Shell metacharacters ( (, ), |, !, +etc.) have to be escaped (e.g., \). For example, to select all tables +in database db1 whose names begin with 'foo' or 'bar': + + mysqlhotcopy --indices --method=cp db1./^\(foo\|bar\)/ + +=item db_name./~pattern/ + +Copy only tables not matching pattern. For example, to copy tables +that do not begin with foo nor bar: + + mysqlhotcopy --indices --method=cp db1./~^\(foo\|bar\)/ + +=item -?, --help + +Display help-screen and exit. + +=item -u, --user=# + +User for database login if not current user. + +=item -p, --password=# + +Password to use when connecting to the server. Note that you are strongly +encouraged *not* to use this option as every user would be able to see the +password in the process list. Instead use the '[mysqlhotcopy]' section in +one of the config files, normally /etc/my.cnf or your personal ~/.my.cnf. +(See the chapter 'my.cnf Option Files' in the manual.) + +=item -h, -h, --host=# + +Hostname for local server when connecting over TCP/IP. By specifying this +different from 'localhost' will trigger mysqlhotcopy to use TCP/IP connection. + +=item -P, --port=# + +Port to use when connecting to MySQL server with TCP/IP. This is only used +when using the --host option. + +=item -S, --socket=# + +UNIX domain socket to use when connecting to local server. + +=item --old_server + +Use old server (pre v5.5) commands. + +=item --noindices + +Don\'t include index files in copy. Only up to the first 2048 bytes +are copied; You can restore the indexes with isamchk -r or myisamchk -r +on the backup. + +=item --method=# + +Method for copy (only "cp" currently supported). Alpha support for +"scp" was added in November 2000. Your experience with the scp method +will vary with your ability to understand how scp works. 'man scp' +and 'man ssh' are your friends. + +The destination directory _must exist_ on the target machine using the +scp method. --keepold and --allowold are meaningless with scp. +Liberal use of the --debug option will help you figure out what\'s +really going on when you do an scp. + +Note that using scp will lock your tables for a _long_ time unless +your network connection is _fast_. If this is unacceptable to you, +use the 'cp' method to copy the tables to some temporary area and then +scp or rsync the files at your leisure. + +=item -q, --quiet + +Be silent except for errors. + +=item --debug + +Debug messages are displayed. + +=item -n, --dryrun + +Display commands without actually doing them. + +=back + +=head1 WARRANTY + +This software is free and comes without warranty of any kind. You +should never trust backup software without studying the code yourself. +Study the code inside this script and only rely on it if I<you> believe +that it does the right thing for you. + +Patches adding bug fixes, documentation and new features are welcome. +Please send these to internals@lists.mysql.com. + +=head1 TO DO + +Extend the individual table copy to allow multiple subsets of tables +to be specified on the command line: + + mysqlhotcopy db newdb t1 t2 /^foo_/ : t3 /^bar_/ : + + +where ":" delimits the subsets, the /^foo_/ indicates all tables +with names beginning with "foo_" and the "+" indicates all tables +not copied by the previous subsets. + +'newdb' is either the name of the new database, or the full path name +of the new database file. The database should not already exist. + +Add option to lock each table in turn for people who don\'t need +cross-table integrity. + +Add option to FLUSH STATUS just before UNLOCK TABLES. + +Add support for other copy methods (e.g., tar to single file?). + +Add support for forthcoming MySQL ``RAID'' table subdirectory layouts. + +=head1 AUTHOR + +Tim Bunce + +Martin Waite - Added checkpoint, flushlog, regexp and dryrun options. + Fixed cleanup of targets when hotcopy fails. + Added --record_log_pos. + RAID tables are now copied (don't know if this works over scp). + +Ralph Corderoy - Added synonyms for commands. + +Scott Wiersdorf - Added table regex and scp support. + +Monty - Working --noindex (copy only first 2048 bytes of index file). + Fixes for --method=scp. + +Ask Bjoern Hansen - Cleanup code to fix a few bugs and enable -w again. + +Emil S. Hansen - Added resetslave and resetmaster. + +Jeremy D. Zawodny - Removed deprecated DBI calls. Fixed bug which +resulted in nothing being copied when a regexp was specified but no +database name(s). + +Martin Waite - Fix to handle database name that contains space. + +Paul DuBois - Remove end '/' from directory names. diff --git a/scripts/mytop.sh b/scripts/mytop.sh new file mode 100644 index 00000000..65bfb8c9 --- /dev/null +++ b/scripts/mytop.sh @@ -0,0 +1,2697 @@ +#!/usr/bin/env perl +# +# $Id: mytop,v 1.99-maria6 2019/10/22 14:53:51 jweisbuch Exp $ + +=pod + +=head1 NAME + +mytop - display MariaDB/MySQL server performance info like `top' + +=cut + +## most of the POD is at the bottom of the file + +use 5.005; +use strict; +use warnings; +use DBI; +use Getopt::Long; +use Socket; +use List::Util qw(min max); +use File::Basename; + +$main::VERSION = "1.99-maria6"; +my $path_for_script = dirname($0); + +$| = 1; +$0 = 'mytop'; + +my $WIN = ($^O eq 'MSWin32') ? 1 : 0; + +## Test for color support. + +eval { require Term::ANSIColor; }; + +my $HAS_COLOR = $@ ? 0 : 1; + +$HAS_COLOR = 0 if $WIN; + +## Test of Time::HiRes support + +eval { require Time::HiRes }; + +my $HAS_TIME = $@ ? 0 : 1; + +my $debug = 0; + +## Try to lower our priority (which, who, pri) + +setpriority(0,0,10) unless $WIN; + +## Prototypes + +sub Clear(); +sub GetData(); +sub GetQPS(); +sub FullQueryInfo($); +sub Explain($); +sub PrintTable(@); +sub PrintHelp(); +sub Sum(@); +sub commify($); +sub make_short($); +sub Hashes($); +sub Execute($); +sub StringOrRegex($); +sub GetInnoDBStatus(); +sub GetCmdSummary(); +sub GetShowVariables(); +sub GetShowStatus(); +sub cmd_s; +sub cmd_S; +sub cmd_q; + +## Default Config Values + +my %config = ( + batchmode => 0, + color => 1, + db => '', + database => '', + delay => 5, + filter_user => qr/.?/, + filter_db => qr/.?/, + filter_host => qr/.?/, + filter_state => qr/.?/, + header => 1, + help => 0, + host => 'localhost', + idle => 1, + long => 120, + long_nums => 0, + mode => 'top', + prompt => 0, + pass => '', + password => '', + port => 3306, + resolve => 0, + slow => 10, ## slow query time + socket => '', + sort => 1, ## default or reverse sort ("s") + user => 'root', + fullqueries => 0, ## shows untruncated queries + usercol_width => 8, ## User column width + dbcol_width => 9, ## DB column width + hide_progress => 0 ## hide the "%" column when available +); + +my %qcache = (); ## The query cache--used for full query info support. +my %ucache = (); ## The user cache--used for full killing by user +my %dbcache = (); ## The db cache. This should be merged at some point. +my %statcache = (); ## The show status cache for GetShowStatus() + +my (%STATUS, %OLD_STATUS); # header stuff. + +my $CLEAR = $WIN ? '': `clear`; + +## Term::ReadKey values + +my $RM_RESET = 0; +my $RM_NOBLKRD = 3; ## using 4 traps Ctrl-C :-( + +## Add options from .my.cnf first + +my $my_print_defaults; +if (!defined($my_print_defaults=my_which("my_print_defaults"))) +{ + print "Warning: Can't find my_print_defaults. Please add it to your PATH!\n"; + exit(1); +} + +unshift @ARGV, split "\n", `$my_print_defaults client mytop`; + +## Read the user's config file, if it exists. + +my $config = "$ENV{HOME}/.mytop"; + +if (-e $config) +{ + if (open CFG, "<$config") + { + while (<CFG>) + { + next if /^\s*($|#)/; ## skip blanks and comments + + chomp; + + if (/(\S+)\s*=\s*(.*\S)/) + { + $config{lc $1} = $2 if exists $config{lc $1}; + } + } + close CFG; + } + ## map database/password onto db/pass + ## short version gets precedence for historical reasons + $config{'db'} = $config{'database'} unless $config{'db'}; + $config{'pass'} = $config{'password'} unless $config{'pass'}; +} + +## Command-line args. + +use vars qw($opt_foo); + +Getopt::Long::Configure('no_ignore_case', 'bundling'); + +GetOptions( + "color!" => \$config{color}, + "user|u=s" => \$config{user}, + "pass|password|p=s" => \$config{pass}, + "database|db|d=s" => \$config{db}, + "host|h=s" => \$config{host}, + "port|P=i" => \$config{port}, + "socket|S=s" => \$config{socket}, + "delay|s=i" => \$config{delay}, + "batch|batchmode|b" => \$config{batchmode}, + "header!" => \$config{header}, + "idle|i!" => \$config{idle}, + "resolve|r!" => \$config{resolve}, + "prompt!" => \$config{prompt}, + "long=i" => \$config{long}, + "long_nums!" => \$config{long_nums}, + "mode|m=s" => \$config{mode}, + "slow=i" => \$config{slow}, + "sort=s" => \$config{sort}, + "fullqueries|L!" => \$config{fullqueries}, + "usercol_width=i" => \$config{usercol_width}, + "dbcol_width=i" => \$config{dbcol_width}, + "hide_progress|a!" => \$config{hide_progress} +); + +## User may have put the port with the host. + +if ($config{host} =~ s/:(\d+)$//) +{ + $config{port} = $1; +} + +## Don't use Term::ReadKey unless running interactively. + +if (not $config{batchmode}) +{ + require Term::ReadKey; + Term::ReadKey->import(); +} + +## User may want to disable color. + +if ($HAS_COLOR and not $config{color}) +{ + $HAS_COLOR = 0; +} + +if ($HAS_COLOR) +{ + import Term::ANSIColor ':constants'; +} +else +{ + *RESET = sub { }; + *YELLOW = sub { }; + *RED = sub { }; + *MAGENTA = sub { }; + *GREEN = sub { }; + *BLUE = sub { }; + *WHITE = sub { }; + *BOLD = sub { }; +} + +my $RESET = RESET() || ''; +my $YELLOW = YELLOW() || ''; +my $RED = RED() || ''; +my $MAGENTA = MAGENTA() || ''; +my $GREEN = GREEN() || ''; +my $BLUE = BLUE() || ''; +my $WHITE = WHITE() || ''; +my $BOLD = BOLD() || ''; + +## Connect + +my $dsn; + +## Socket takes precedence. +my $prefix= 'mysql'; +if (eval {DBI->install_driver("MariaDB")}) { + $dsn = "DBI:MariaDB:database=$config{db};mariadb_read_default_group=mytop;"; + $prefix= 'mariadb' +} else { + $dsn = "DBI:mysql:database=$config{db};mysql_read_default_group=mytop;"; +} + +if ($config{socket} and -S $config{socket}) +{ + $dsn .= "${prefix}_socket=$config{socket}"; +} +else +{ + $dsn .= "host=$config{host};port=$config{port}"; +} + +if ($config{prompt}) +{ + print "Password: "; + ReadMode(2); + chomp($config{pass} = <STDIN>); + ReadMode(0); + print "\n"; +} + +my $dbh = DBI->connect($dsn, $config{user}, $config{pass}, + { PrintError => 0 }); + +if (not ref $dbh) +{ + my $Error = <<EODIE +Cannot connect to MariaDB/MySQL server. Please check the: + + * database you specified "$config{db}" (default is "") + * username you specified "$config{user}" (default is "root") + * password you specified "$config{pass}" (default is "") + * hostname you specified "$config{host}" (default is "localhost") + * port you specified "$config{port}" (default is 3306) + * socket you specified "$config{socket}" (default is "") + +The options my be specified on the command-line or in a ~/.mytop or +~/.my.cnf config file. See the manual (perldoc mytop) for details. + +Here's the exact error from DBI. It might help you debug: + +$DBI::errstr + +EODIE +; + + die $Error; + +} + +ReadMode($RM_RESET) unless $config{batchmode}; + +## Get static data + +my $db_version; +my $db_release; +my $server = "MySQL"; +my $have_query_cache; + +my @variables = Hashes("SHOW VARIABLES"); + +foreach (@variables) +{ + if ($_->{Variable_name} eq "version") + { + $db_version = $_->{Value}; + $db_version =~ /^(\d+)/; + $db_release = $1; + $server = "MariaDB" if ($db_version =~ /maria/i); + # Get the version number only + $db_version = $1 if($db_version =~ m/(.*?)-/); + next; + } + if ($_->{Variable_name} eq "have_query_cache") + { + if ($_->{Value} ne 'NO') + { + $have_query_cache = 1; + } + else + { + $have_query_cache = 0; + } + next; + } +} + +my ($has_is_processlist, $has_time_ms, $has_progress); +$has_is_processlist = $has_time_ms = $has_progress = 0; + +## Check if the server has the INFORMATION_SCHEMA.PROCESSLIST table +## for backward compatibility +$has_is_processlist = Execute("SELECT /*mytop*/ 1 FROM INFORMATION_SCHEMA.TABLES + WHERE TABLE_SCHEMA = 'information_schema' AND + TABLE_NAME = 'PROCESSLIST';")->rows; +if ($has_is_processlist == 1) +{ + ## Check if the server has the TIME_MS column on the I_S.PROCESSLIST table + ## If it is the case, it will fetch the query time with decimal precision + ## for queries that has been running for less than 10k seconds + $has_time_ms = Execute("SELECT /*mytop*/ 1 FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = 'information_schema' AND + TABLE_NAME = 'PROCESSLIST' AND + COLUMN_NAME = 'TIME_MS';")->rows; + if ($has_time_ms == 1) + { + ## Check if the server has the STAGE column on the I_S.PROCESSLIST + ## table (MariaDB) to retreive query completion information + $has_progress = Execute("SELECT /*mytop*/ 1 FROM INFORMATION_SCHEMA.COLUMNS + WHERE TABLE_SCHEMA = 'information_schema' AND + TABLE_NAME = 'PROCESSLIST' AND + COLUMN_NAME = 'STAGE';")->rows; + } +} + +######################################################################### +## +## The main loop +## +######################################################################### + +ReadMode($RM_NOBLKRD) unless $config{batchmode}; + +while (1) +{ + my $key; + + if ($config{mode} eq 'qps') + { + GetQPS(); + $key = ReadKey(1); + + next unless $key; + + if ($key =~ /t/i) + { + $config{mode} = 'top'; + } + if ($key =~ /q/) + { + cmd_q(); + } + next; + } + if ($config{mode} eq 'top') + { + GetData(); + last if $config{batchmode}; + $key = ReadKey($config{delay}); + next unless $key; + } + elsif ($config{mode} eq 'cmd') + { + GetCmdSummary(); + last if $config{batchmode}; + $key = ReadKey($config{delay}); + next unless $key; + } + elsif ($config{mode} eq 'innodb') + { + GetInnoDBStatus(); + last if $config{batchmode}; + print "InnoDB Status [hit t to exit this mode or q to exit the application]\n"; + $key = ReadKey($config{delay}); + next unless $key; + } + elsif ($config{mode} eq 'status') + { + GetShowStatus(); + last if $config{batchmode}; + $key = ReadKey($config{delay}); + next unless $key; + } + + ## + ## keystroke command processing (if we get this far) + ## + + if ($key eq '!') + { + Execute("STOP /*mytop*/ SLAVE;"); + Execute("SET /*mytop*/ GLOBAL sql_slave_skip_counter=1"); + Execute("START /*mytop*/ SLAVE"); + } + + # t - top + + if ($key =~ /t/i) + { + $config{mode} = 'top'; + } + + ## q - quit + + if ($key eq 'q') + { + cmd_q(); + } + + if ($key eq 'D') + { + require Data::Dumper; + print Data::Dumper::Dumper([\%config]); + ReadKey(0); + } + + ## l - change long running hightling + + if ($key eq 'l') + { + cmd_l(); + next; + } + + ## m - mode switch to qps + + if ($key eq 'm') + { + $config{mode} = 'qps'; + Clear() unless $config{batchmode}; + print "Queries Per Second [hit t to exit this mode or q to exit the application]\n"; + next; + } + + ## c - mode switch to command summary + + if ($key eq 'c') + { + $config{mode} = 'cmd'; + Clear() unless $config{batchmode}; + print "Command Summary\n"; + next; + } + + ## C - change Color on and off + + if ($key eq 'C') + { + if ($HAS_COLOR) + { + $HAS_COLOR = 0; + } + else + { + $HAS_COLOR = 1; + } + } + + ## s - seconds of delay + + if ($key eq 's') + { + cmd_s(); + next; + } + + if ($key eq 'S') + { + cmd_S(); + next; + } + + ## R - resolve hostnames + if ($key eq 'R') + { + if ($config{resolve}) + { + $config{resolve} = 0; + } + else + { + $config{resolve} = 1; + } + } + + ## t - username based filter + + if ($key eq 't') + { + ReadMode($RM_RESET); + print RED(), "Which state (blank for all, /.../ for regex): ", RESET(); + $config{filter_state} = StringOrRegex(ReadLine(0)); + ReadMode($RM_NOBLKRD); + next; + } + + ## u - username based filter + + if ($key eq 'u') + { + ReadMode($RM_RESET); + print RED(), "Which user (blank for all, /.../ for regex): ", RESET(); + $config{filter_user} = StringOrRegex(ReadLine(0)); + ReadMode($RM_NOBLKRD); + next; + } + + ## d - database name based filter + + if ($key eq 'd') + { + ReadMode($RM_RESET); + print RED(), "Which database (blank for all, /.../ for regex): ", + RESET(); + $config{filter_db} = StringOrRegex(ReadLine(0)); + ReadMode($RM_NOBLKRD); + next; + } + + ## h - hostname based filter + + if ($key eq 'h') + { + ReadMode($RM_RESET); + print RED(), "Which hostname (blank for all, /.../ for regex): ", + RESET(); + $config{filter_host} = StringOrRegex(ReadLine(0)); + ReadMode($RM_NOBLKRD); + next; + } + + ## E - Show full Replication Error + + if ($key eq 'E') + { + my ($data) = Hashes('SHOW /*mytop*/ SLAVE STATUS'); + Clear(); + print "Error is: $data->{Last_Error}\n"; + print RED(), "-- paused. press any key to resume --", RESET(); + ReadKey(0); + next; + } + ## F - remove all filters + + if ($key eq 'F') + { + $config{filter_host} = qr/.?/; + $config{filter_db} = qr/.?/; + $config{filter_user} = qr/.?/; + $config{filter_state} = qr/.?/; + print RED(), "-- display unfiltered --", RESET(); + sleep 1; + next; + } + + ## p - pause + + if ($key eq 'p') + { + print RED(), "-- paused. press any key to resume --", RESET(); + ReadKey(0); + next; + } + + ## i - idle toggle + + if ($key =~ /i/) + { + if ($config{idle}) + { + $config{idle} = 0; + $config{sort} = 1; + print RED(), "-- idle (sleeping) processed filtered --", RESET(); + sleep 1; + } + else + { + $config{idle} = 1; + $config{sort} = 0; + print RED(), "-- idle (sleeping) processed unfiltered --", RESET(); + sleep 1; + } + } + + ## I - InnoDB status + + if ($key =~ 'I') + { + $config{mode} = 'innodb'; + Clear() unless $config{batchmode}; + print "InnoDB Status\n"; + next; + } + + ## o - sort order + + if ($key =~ /o/) + { + if ($config{sort}) + { + $config{sort} = 0; + print RED(), "-- sort order reversed --", RESET(); + sleep 1; + } + else + { + $config{sort} = 1; + print RED(), "-- sort order reversed --", RESET(); + sleep 1; + } + } + + ## ? - help + + if ($key eq '?') + { + Clear(); + PrintHelp(); + ReadKey(0); + next; + } + + ## k - kill + + if ($key eq 'k') + { + ReadMode($RM_RESET); + + print RED(), "Thread id to kill: ", RESET(); + my $id = ReadLine(0); + + $id =~ s/\s//g; + + if ($id =~ /^\d+$/) + { + Execute("KILL /*mytop*/ $id"); + } + else + { + print RED(), "-- invalid thread id --", RESET(); + sleep 1; + } + + ReadMode($RM_NOBLKRD); + next; + } + + ## K - kill based on a username + if ($key =~ /K/) + { + ReadMode($RM_RESET); + + print RED(), "User to kill: ", RESET(); + my $user = ReadLine(0); + + $user =~ s/\s//g; + + if ($user =~ /^\S+$/) + { + for my $pid (keys %ucache) + { + next unless $ucache{$pid} eq $user; + Execute("KILL /*mytop*/ $pid"); + select(undef, undef, undef, 0.2); + } + } + else + { + print RED(), "-- invalid thread id --", RESET(); + sleep 1; + } + + ReadMode($RM_NOBLKRD); + } + + ## f - full info + + if ($key =~ /f/) + { + ReadMode($RM_RESET); + print RED(), "Full query for which thread id: ", RESET(); + my $id = ReadLine(0); + chomp $id; + FullQueryInfo($id); + ReadMode($RM_NOBLKRD); + print RED(), "-- paused. press any key to resume or (e) to explain --", + RESET(); + my $key = ReadKey(0); + + if ($key eq 'e') + { + Explain($id); + print RED(), "-- paused. press any key to resume --", RESET(); + ReadKey(0); + } + + next; + } + + ## e - explain + + if ($key =~ /e/) + { + ReadMode($RM_RESET); + print RED(), "Explain which query (id): ", RESET(); + my $id = ReadLine(0); + chomp $id; + Explain($id); + ReadMode($RM_NOBLKRD); + print RED(), "-- paused. press any key to resume --", RESET(); + ReadKey(0); + next; + } + + ## r - reset status counters + + if ($key =~ /r/) + { + Execute("FLUSH /*mytop*/ STATUS"); + print RED(), "-- counters reset --", RESET(); + sleep 1; + next; + } + + ## H - header toggle + + if ($key eq 'H') + { + if ($config{header}) + { + $config{header} = 0; + } + else + { + $config{header}++; + } + } + + ## # - magic debug key + + if ($key eq '#') + { + $debug = 1; + } + + if ($key eq 'V') + { + GetShowVariables(); + print RED(), "-- paused. press any key to resume --", RESET(); + ReadKey(0); + } + + ## M - switch to SHOW STATUS mode + + if ($key eq 'M') + { + $config{mode} = 'status'; + } + + ## L - full queries toggle + + if ($key eq 'L') + { + if ($config{fullqueries}) + { + $config{fullqueries} = 0; + print RED(), "-- full queries OFF --", RESET(); + sleep 1; + } + else + { + $config{fullqueries} = 1; + print RED(), "-- full queries ON --", RESET(); + sleep 1; + } + } + + ## w - change columns width for the "User" and "Database" columns + + if ($key eq 'w') + { + ReadMode($RM_RESET); + print RED(), "Width for the 'User' column (the actual value is ". + $config{usercol_width}."): "; + my $readWidth = ReadLine(0); + chomp($readWidth); + if (defined($readWidth) && $readWidth ne "") + { + if ($readWidth > 4 && $readWidth < 60) + { + $config{usercol_width} = $readWidth; + } + else + { + print RED(), "-- Invalid value ($readWidth), the previous value". + "has been kept, press a key to resume --"; + ReadKey(0); + } + } + print RESET(), RED(), "Width for the 'DB' column (the actual value is ". + $config{dbcol_width}."): ", RESET(); + $readWidth = ReadLine(0); + chomp($readWidth); + if (defined($readWidth) && $readWidth ne "") + { + if ($readWidth > 2 && $readWidth < 60) + { + $config{dbcol_width} = $readWidth + } + else + { + print RED(), "-- Invalid value ($readWidth), the previous value". + "has been kept, press a key to resume --", RESET(); + ReadKey(0); + } + } + undef $readWidth; + ReadMode($RM_NOBLKRD); + next; + } + + ## a - progress column toggle (the column is only displayed + ## if progress information are available from the processlist) + + if ($key eq 'a') + { + if ($config{hide_progress}) + { + $config{hide_progress} = 0; + print RED(), "-- progress display ON --", RESET(); + sleep 1; + } + else + { + $config{hide_progress} = 1; + print RED(), "-- progress display OFF --", RESET(); + sleep 1; + } + } + +} + +ReadMode($RM_RESET) unless $config{batchmode}; + +exit; + +####################################################################### + +sub Clear() +{ + if (not $WIN) + { + print "$CLEAR" + } + else + { + print "\n" x 90; ## dumb hack for now. Anyone know how to + ## clear the screen in dos window on a Win32 + ## system?? + } +} + +my $last_time; + +sub GetData() +{ + ## Get terminal info + my $now_time; + %qcache = (); ## recycle memory + %dbcache = (); + + my ($width, $height, $wpx, $hpx, $lines_left); + + if (not $config{batchmode}) + { + ($width, $height, $wpx, $hpx) = GetTerminalSize(); + $lines_left = $height - 2; + } + else + { + $height = 999_999; ## I hope you don't have more than that! + $lines_left = 999_999; + $width = 80; + } + + ## + ## Header stuff. + ## + if ($config{header}) + { + my @recs = ""; + if ($db_release > 4) + { + @recs = Hashes("SHOW /*mytop*/ GLOBAL STATUS"); + } + else + { + @recs = Hashes("SHOW /*mytop*/ STATUS"); + } + + ## if the server died or we lost connectivity + if (not @recs) + { + ReadMode($RM_RESET); + exit 1; + } + + ## get high-res or low-res time + my ($t_delta); + + if ($HAS_TIME) + { + $now_time = Time::HiRes::gettimeofday(); + } + else + { + $now_time = time; + } + + if ($last_time and $last_time != $now_time) + { + $t_delta = $now_time - $last_time; + } + + %OLD_STATUS = %STATUS; + # Set some status that may not exist in all versions + $STATUS{Handler_tmp_write} = 0; + $STATUS{Handler_tmp_update} = 0; + $STATUS{Rows_tmp_read} = 0; + + foreach my $ref (@recs) + { + my $key = $ref->{Variable_name}; + my $val = $ref->{Value}; + + $STATUS{$key} = $val; + } + + ## Compute Key Cache Hit Stats + + $STATUS{Key_read_requests} ||= 1; ## can't divide by zero next + + my $cache_hits_percent = (100-($STATUS{Key_reads}/$STATUS{Key_read_requests}) * 100); + $cache_hits_percent = sprintf("%2.2f",$cache_hits_percent); + + ## Query Cache info for <= Ver. 4.1 + ## + ## mysql> show status like 'qcache%'; + ## +-------------------------+----------+ + ## | Variable_name | Value | + ## +-------------------------+----------+ + ## | Qcache_queries_in_cache | 81 | + ## | Qcache_inserts | 4961668 | + ## | Qcache_hits | 1374170 | + ## | Qcache_not_cached | 5656249 | + ## | Qcache_free_memory | 33164800 | + ## | Qcache_free_blocks | 2 | + ## | Qcache_total_blocks | 168 | + ## +-------------------------+----------+ + ## + ## Query Cache info for => Ver. 5.0 + ## + ## mysql> show status like 'qcache%'; + ## +-------------------------+------------+ + ## | Variable_name | Value | + ## +-------------------------+------------+ + ## | Qcache_free_blocks | 37652 | + ## | Qcache_free_memory | 110289712 | + ## | Qcache_hits | 1460617356 | + ## | Qcache_inserts | 390563495 | + ## | Qcache_lowmem_prunes | 6414172 | + ## | Qcache_not_cached | 93002420 | + ## | Qcache_queries_in_cache | 66558 | + ## | Qcache_total_blocks | 192031 | + ## +-------------------------+------------+ + + my $query_cache_hits = 0; + my $query_cache_hits_per_sec = 0; + my $now_query_cache_hits_per_sec = 0; + + if ($have_query_cache) + { + $query_cache_hits = $STATUS{Qcache_hits}; + $query_cache_hits_per_sec = $STATUS{Qcache_hits} / $STATUS{Uptime}; + + if (defined $last_time and $last_time != $now_time) + { + my $q_delta = $STATUS{Qcache_hits} - $OLD_STATUS{Qcache_hits}; + $now_query_cache_hits_per_sec = sprintf "%.2f", $q_delta / $t_delta; + } + } + + my $l; + if (-e "/proc/loadavg") + { + ## To avoid warnings if the OS is not Linux + open (my $fh, "<", "/proc/loadavg"); + ## Only the first 3 values are interresting + $l = join(" ", (split /\s+/, <$fh>)[0..2]); + close $fh; + } + + $last_time = $now_time; + + ## Server Uptime in meaningful terms... + + my $time = $STATUS{Uptime}; + my ($d,$h,$m,$s) = (0, 0, 0, 0); + + $d += int($time / (60*60*24)); $time -= $d * (60*60*24); + $h += int($time / (60*60)); $time -= $h * (60*60); + $m += int($time / (60)); $time -= $m * (60); + $s += int($time); + + my $uptime = sprintf("%d+%02d:%02d:%02d", $d, $h, $m, $s); + + ## Queries per second... + + my $avg_queries_per_sec = sprintf("%.2f", $STATUS{Questions} / $STATUS{Uptime}); + my $num_queries = $STATUS{Questions}; + + my @t = localtime(time); + + my $current_time = sprintf "[%02d:%02d:%02d]", $t[2], $t[1], $t[0]; + + my $host_width = length("$server $db_version on $config{host}"); + my $up_width = $width - $host_width - 1; + Clear() unless $config{batchmode}; + print RESET(); + + printf "%-.${host_width}s %${up_width}s\n", + "$server $db_version on $config{host}", + defined($l) ? "load ($l) up $uptime $current_time" : "up $uptime $current_time"; + $lines_left--; + + + printf " Queries: %-7s qps: %4.0f Slow: %7s Se/In/Up/De(%%): %02.0f/%02.0f/%02.0f/%02.0f\n", + make_short( $STATUS{Questions} ), # q total + $STATUS{Questions} / $STATUS{Uptime}, # qps, average + make_short( $STATUS{Slow_queries} ), # slow + + # hmm. a Qcache hit is really a select and should be counted. + 100 * ($STATUS{Com_select} + ($STATUS{Qcache_hits}||0) ) / $STATUS{Questions}, + 100 * ($STATUS{Com_insert} + $STATUS{Com_replace} ) / $STATUS{Questions}, + 100 * ($STATUS{Com_update} ) / $STATUS{Questions}, + 100 * $STATUS{Com_delete} / $STATUS{Questions}; + + $lines_left--; + + if ($t_delta) + { + my $q_diff = ( $STATUS{Questions} - $OLD_STATUS{Questions} ); +# print("q_diff: $STATUS{Questions} - $OLD_STATUS{Questions} / $t_delta = $q_diff\n"); + + printf(" Sorts: %6.0f qps now: %4.0f Slow qps: %3.1f Threads: %4.0f (%4.0f/%4.0f) %02.0f/%02.0f/%02.0f/%02.0f\n", + ( $STATUS{Sort_rows} - $OLD_STATUS{Sort_rows} ) / $t_delta, + + ( $STATUS{Questions} - $OLD_STATUS{Questions} ) / $t_delta, + ( # slow now (qps) + ($STATUS{Slow_queries} ) ? + ( $STATUS{Slow_queries} - $OLD_STATUS{Slow_queries} ) / $t_delta : + 0 + ), + $STATUS{Threads_connected}, + $STATUS{Threads_running}, + $STATUS{Threads_cached}, + + (100 * ($STATUS{Com_select} - $OLD_STATUS{Com_select} + + ($STATUS{Qcache_hits}||0) - ($OLD_STATUS{Qcache_hits}||0) + ) ) / ($q_diff ), + (100 * ($STATUS{Com_insert} - $OLD_STATUS{Com_insert} + + $STATUS{Com_replace} - $OLD_STATUS{Com_replace} + ) ) / ($q_diff ), + (100 * ($STATUS{Com_update} - $OLD_STATUS{Com_update}) ) / ($q_diff ), + (100 * ($STATUS{Com_delete} - $OLD_STATUS{Com_delete}) ) / ($q_diff ), + ); + } + else + { + print "\n"; + } + $lines_left--; + + if ($have_query_cache and $STATUS{Com_select} and $query_cache_hits) + { + printf(" Cache Hits: %-5s Hits/s: %4.1f Hits now: %5.1f Ratio: ", + make_short($STATUS{Qcache_hits}), # cache hits + $STATUS{Qcache_hits} / $STATUS{Uptime}, # hits / sec + ($t_delta) ? ($STATUS{Qcache_hits} - $OLD_STATUS{Qcache_hits}) / $t_delta : 0, # Hits Now + ); + + my ($Ratio) = 100 * ($STATUS{Qcache_hits}) / ($STATUS{Qcache_hits} + $STATUS{Com_select} ); + if ($HAS_COLOR) + { + print YELLOW() if ($Ratio < 80.0); + print RED() if ($Ratio < 50.0); + print MAGENTA() if ($Ratio < 20.0); + } + printf("%4.1f%% ",$Ratio); + if ($HAS_COLOR) + { + print RESET(); + } + + print " Ratio now: "; + my ($Ratio_now) = ($t_delta) ? # ratio now + 100 * ($STATUS{Qcache_hits} - $OLD_STATUS{Qcache_hits} ) / + ( ($STATUS{Com_select} + $STATUS{Qcache_hits} - + ($OLD_STATUS{Qcache_hits} + $OLD_STATUS{Com_select}) + ) || 1) : 0; + if ($HAS_COLOR) + { + print GREEN() if ($Ratio_now >= 80.0); + print YELLOW() if ($Ratio_now < 80.0); + print RED() if ($Ratio_now < 50.0); + print MAGENTA() if ($Ratio_now < 20.0); + } + printf("%4.1f%% \n",$Ratio_now); + if ($HAS_COLOR) + { + print RESET(); + } + $lines_left--; + } + + if ($t_delta) + { + my $rows_read; + if (defined($STATUS{Rows_read})) + { + $rows_read= $STATUS{Rows_read} - $OLD_STATUS{Rows_read}; + } + else + { + $rows_read= + ($STATUS{Handler_read_first} + $STATUS{Handler_read_key} + + $STATUS{Handler_read_next} + $STATUS{Handler_read_prev} + + $STATUS{Handler_read_rnd} + $STATUS{Handler_read_rnd_next} - + $OLD_STATUS{Handler_read_first} - $OLD_STATUS{Handler_read_key} - + $OLD_STATUS{Handler_read_next} - $OLD_STATUS{Handler_read_prev} - + $OLD_STATUS{Handler_read_rnd} - $OLD_STATUS{Handler_read_rnd_next}); + } + printf(" Handler: (R/W/U/D) %5d/%5d/%5d/%5d Tmp: R/W/U: %5d/%5d/%5d\n", + $rows_read/$t_delta, + ($STATUS{Handler_write} - $OLD_STATUS{Handler_write}) / + $t_delta, + ($STATUS{Handler_update} - $OLD_STATUS{Handler_update}) / + $t_delta, + ($STATUS{Handler_delete} - $OLD_STATUS{Handler_delete}) / + $t_delta, + ($STATUS{Rows_tmp_read} - $OLD_STATUS{Rows_tmp_read}) / + $t_delta, + ($STATUS{Handler_tmp_write} + -$OLD_STATUS{Handler_tmp_write})/$t_delta, + ($STATUS{Handler_tmp_update} - + $OLD_STATUS{Handler_tmp_update})/$t_delta); + } + else + { + print "\n"; + } + + $lines_left--; + + printf(" MyISAM Key Cache Efficiency: %2.1f%% Bps in/out: %5s/%5s ", + $cache_hits_percent, + make_short($STATUS{Bytes_received} / $STATUS{Uptime} ), + make_short($STATUS{Bytes_sent} / $STATUS{Uptime})); + printf("Now in/out: %5s/%5s", + make_short(($STATUS{Bytes_received} - $OLD_STATUS{Bytes_received}) / $t_delta ), + make_short(($STATUS{Bytes_sent} - $OLD_STATUS{Bytes_sent}) / $t_delta )) + if ($t_delta); + print "\n"; + + $lines_left--; + + my ($data) = Hashes('SHOW /*mytop*/ GLOBAL VARIABLES LIKE "read_only"'); + if ($data->{Value} ne "OFF") + { + print RED() if ($HAS_COLOR) ; + print " ReadOnly"; + RESET() if ($HAS_COLOR); + } + + ($data) = Hashes('SHOW /*mytop*/ SLAVE STATUS'); + if (defined($data->{Master_Host})) + { + if (defined($data->{Seconds_Behind_Master})) + { + if ($HAS_COLOR) + { + print GREEN(); + print YELLOW() if ($data->{Seconds_Behind_Master} > 60); + print MAGENTA() if ($data->{Seconds_Behind_Master} > 360); + } + } + print " Replication "; + print "IO:$data->{Slave_IO_Running} "; + print "SQL:$data->{Slave_SQL_Running} "; + print RESET() if ($HAS_COLOR); + + if (defined($data->{Seconds_Behind_Master})) + { + if ($HAS_COLOR) + { + print GREEN(); + print YELLOW() if ($data->{Seconds_Behind_Master} > 60); + print MAGENTA() if ($data->{Seconds_Behind_Master} > 360); + } + print "Delay: $data->{Seconds_Behind_Master} sec."; + } + else + { + my $free = $width - 45; + my $Err = substr $data->{Last_Error},0 ,$free; + printf(" ERR: %-${free}s", $Err) if ($Err ne ""); + } + print WHITE() if ($HAS_COLOR); + print "\n"; + $lines_left--; + } + print "\n"; + } + + if (not $config{batchmode} and not $config{header}) + { + Clear(); + print RESET(); + } + + ## + ## Threads + ## + + my $proc_cmd; ## Query used to fetch the processlist + my $time_format = "6d"; + + if ($has_is_processlist == 1) + { + if ($has_time_ms == 1) + { + $time_format = "6.6s"; + if ($has_progress == 1) + { + ## To have a computed value of "Progress" like the + ## "SHOW PROCESSLIST" one, the Progress column of the query + ## must be replaced by : + ## "CASE WHEN Max_Stage < 2 THEN Progress ELSE + ## (Stage-1)/Max_Stage*100+Progress/Max_Stage END AS Progress" + $proc_cmd = "SELECT /*mytop*/ Id, User, Host, db, Command, + CASE WHEN TIME > 10000 THEN Time ELSE + ROUND(TIME_MS/1000, 1) END AS Time, + State, Info, Progress, Stage, Max_Stage + FROM INFORMATION_SCHEMA.PROCESSLIST + WHERE ID != CONNECTION_ID();"; + } + else + { + $proc_cmd = "SELECT /*mytop*/ Id, User, Host, db, Command, + CASE WHEN TIME > 10000 THEN Time ELSE + ROUND(TIME_MS/1000, 1) END AS Time, + State, Info FROM INFORMATION_SCHEMA.PROCESSLIST + WHERE ID != CONNECTION_ID();"; + } + } + else + { + $proc_cmd = "SELECT /*mytop*/ Id, User, Host, db, Command, Time, + State, Info FROM INFORMATION_SCHEMA.PROCESSLIST + WHERE ID != CONNECTION_ID();"; + } + } + else + { + $proc_cmd = "SHOW /*mytop*/ FULL PROCESSLIST;"; + } + + ## Minimal width values for columns with a dynamic width + if ($config{usercol_width} < 4) { $config{usercol_width} = 4; } + if ($config{dbcol_width} < 2) { $config{dbcol_width} = 2; } + + my @sz = (9, $config{usercol_width}, 15, $config{dbcol_width}, 6, 6, 8); + if ($has_progress == 1 && !$config{hide_progress}) { push @sz, 5; }; + my $used = scalar(@sz) + Sum(@sz); + undef(@sz); + + ## If the terminal width <= 80, the state column will have a width of 6 + ## chars else it will be between 6 and 15 depending on the terminal width + my $state = $width <= 80 ? 6 : int(min(6+($width-80)/3, 15)); + ## $free = The number of chars between the beginning of the "Query" + ## column and the end of the line + my $free = $width - $used - ($state - 6); + my $format= "%9s %$config{usercol_width}s %15s %$config{dbcol_width}s %6s "; + if ($has_progress == 1 && !$config{hide_progress}) { $format .= "%5s "; } + $format .= "%6s %${state}s %-.${free}s\n"; + + my $format2 = "%9d %$config{usercol_width}.$config{usercol_width}s %15.15s %$config{dbcol_width}.$config{dbcol_width}s %${time_format} "; + if ($has_progress == 1 && !$config{hide_progress}) { $format2 .= "%5.1f "; } + $format2 .= "%6.6s %${state}.${state}s "; + if ($config{fullqueries}) + { + $format2 .= "%-${free}s\n"; + } + else + { + $format2 .= "%-${free}.${free}s\n"; + } + + print BOLD() if ($HAS_COLOR); + + if ($has_progress == 1 && !$config{hide_progress}) + { + printf $format, + 'Id','User','Host/IP','DB','Time', '%', 'Cmd', 'State', 'Query'; + } + else + { + printf $format, + 'Id','User','Host/IP','DB','Time', 'Cmd', 'State', 'Query'; + } + + print RESET() if ($HAS_COLOR); + + ## Id User Host DB + if ($has_progress == 1 && !$config{hide_progress}) + { + printf $format, + '--','----','-------','--','----', '-', '---', '-----', '----------'; + } + else + { + printf $format, + '--','----','-------','--','----', '---', '-----', '----------'; + } + + $lines_left -= 2; + + my @data = Hashes($proc_cmd); + + foreach my $thread (@data) + { + last if not $lines_left; + + ## Drop Domain Name, unless it looks like an IP address. If + ## it's an IP, we'll strip the port number because it's rarely + ## interesting. + + my $is_ip = 0; + + if ($thread->{Host} =~ /^(\d{1,3}\.){3}(\d{1,3})(:\d+)?$/) + { + $thread->{Host} =~ s/:.*$//; + $is_ip = 1; + } + else + { + $thread->{Host} =~ s/^([^.]+).*/$1/; + } + + ## Otherwise, look up the IP (if resolve is set) and strip the + ## name + if ($is_ip and $config{resolve}) + { + $thread->{Host} =~ s/:\d+$//; + my $host = gethostbyaddr(inet_aton($thread->{Host}), AF_INET); + if ($host) + { + ## Only the hostname part of the DNS is kept + $host =~ s/^([^.]+).*/$1/; + } + $thread->{Host} = $host; + } + + ## Fix possible undefs + + $thread->{db} ||= ''; + $thread->{Info} ||= ''; + $thread->{Time} ||= 0 ; + $thread->{Id} ||= 0 ; + $thread->{User} ||= ''; + $thread->{Command} ||= ''; + $thread->{Host} ||= ''; + $thread->{State} ||= ""; + $thread->{Progress} ||= 0; + + ## Alter double hyphen comments so they don't break + ## the query when newlines are removed - http://freshmeat.net/users/jerjones + $thread->{Info} =~ s~\s--(.*)$~ /* $1 */ ~mg; + + ## Normalize spaces -- mostly disabled for now. This can + ## break EXPLAIN if you try to explain a mangled query. It + ## may be re-enabled later as an option. + + ## Replace newlines and carriage returns with a space + $thread->{Info} =~ tr/\n\r/ /; + + ## Leading space removal + $thread->{Info} =~ s/^\s*//; + + ## Strip non printing control symbols + $thread->{Info} =~ tr/[[:cntrl:]]//; + + ## Collpase whitespace + $thread->{Info} =~ s/\s+/ /g; + + ## Trailing space removal + $thread->{Info} =~ s/\s$//; + + ## Put the first letter of the query uppercase for a better readability + ## with long State strings + $thread->{Info} = ucfirst $thread->{Info}; + + ## Stow it in the cache + $qcache{$thread->{Id}} = $thread->{Info}; + $dbcache{$thread->{Id}} = $thread->{db}; + $ucache{$thread->{Id}} = $thread->{User}; + + ## If Progress information is available and a multi-stage query is + ## running, the actual stage and the total number of stages of the + ## thread are shown at the beginning of the State column + if ($has_progress == 1 && $thread->{Max_Stage} && $thread->{Max_Stage} > 1) + { + $thread->{State} = $thread->{Stage}."/". + $thread->{Max_Stage}." ".$thread->{State}; + } + } + + ## Sort by idle time (closest thing to CPU usage I can think of). + + my @sorted; + + if (not $config{sort}) + { + @sorted = sort { $a->{Time} <=> $b->{Time} } @data + } + else + { + @sorted = sort { $b->{Time} <=> $a->{Time} } @data + } + + foreach my $thread (@sorted) + { + ## Check to see if we can skip out. + ## We skip out if we know the given line doesn't match. + + next if (($thread->{Command} eq "Sleep") + and + (not $config{idle})); + + next if (($thread->{Command} eq "Binlog Dump") + and + (not $config{idle})); + + next if (($thread->{Command} eq "Daemon") + and + (not $config{idle})); + + next if ($thread->{User} !~ $config{filter_user}); + next if ($thread->{db} !~ $config{filter_db}); + next if ($thread->{Host} !~ $config{filter_host}); + next if ($thread->{State} !~ $config{filter_state}); + + ## Otherwise, print. + + my $smInfo; + + if ($thread->{Info}) + { + if ($config{fullqueries}) + { + $smInfo = $thread->{Info}; + if (length($smInfo) > $free) + { + $lines_left -= int((length($smInfo) - $free)/$width) + 1; + } + } + else + { + $smInfo = substr $thread->{Info}, 0, $free; + } + } +# if ($thread->{State}) +# { +# $smInfo = substr $thread->{State}, 0, $free; +# } + else + { + $smInfo = ""; + } + + $lines_left--; + if ($lines_left < 0) + { + print WHITE(), "-- Truncated query list -- "; + last; + } + + if ($HAS_COLOR) + { + print YELLOW() if $thread->{Command} eq 'Query'; + print WHITE() if $thread->{Command} eq 'Sleep'; + print GREEN() if $thread->{Command} eq 'Connect'; + print BOLD() if $thread->{Time} > $config{slow}; + print MAGENTA() if $thread->{Time} > $config{long}; + } + + if ($has_progress == 1 && !$config{hide_progress}) + { + printf $format2, + $thread->{Id}, $thread->{User}, $thread->{Host}, $thread->{db}, + $thread->{Time}, $thread->{Progress}, $thread->{Command}, + $thread->{State}, $smInfo; + } + else + { + printf $format2, + $thread->{Id}, $thread->{User}, $thread->{Host}, $thread->{db}, + $thread->{Time}, $thread->{Command}, $thread->{State}, $smInfo; + } + + print RESET() if $HAS_COLOR; + } + +} + +########################################################################### + +my $questions; + +sub GetQPS() +{ + my ($data) = Hashes('SHOW /*mytop*/ STATUS LIKE "Questions"'); + my $num = $data->{Value}; + + if (not defined $questions) ## first time? + { + $questions = $num; + return; + } + + my $qps = $num - $questions; + $questions = $num; + print "$qps\n"; +} + +########################################################################### + +sub GetInnoDBStatus() +{ + if (not $config{pager}) + { + if (not $config{pager} = my_which('less')) + { + $config{pager} = my_which('more'); + } + } + + my @data = Hashes("SHOW /*mytop*/ ENGINE INNODB STATUS"); + + open P, "|$config{pager}" or die "$!"; + print keys %{$data[0]}; + print $data[0]->{Status},"\n"; + close P; +} + +########################################################################### + +my %prev_data; + +sub GetCmdSummary() +{ + my ($width, $height, $wpx, $hpx, $lines_left); + + if (not $config{batchmode}) + { + ($width, $height, $wpx, $hpx) = GetTerminalSize(); + + $lines_left = $height - 2; + } + else + { + $height = 999_999; ## I hope you don't have more than that! + $lines_left = 999_999; + $width = 80; + } + + ## Variable_name and Value pairs come back... + my @data = Hashes("SHOW /*mytop*/ STATUS LIKE 'Com\\_%'"); + my %cmd_data; + my %cmd_delta; + my %cmd_pct; + my %cmd_delta_pct; + my $total; + my $delta_total; + + for my $item (@data) + { + next unless $item->{Value}; + $item->{Variable_name} =~ s/^Com_//; + $item->{Variable_name} =~ s/_/ /g; + $cmd_data{$item->{Variable_name}} = $item->{Value}; + $total += $item->{Value}; + } + + ## Populate other stats + + for my $item (keys %cmd_data) + { + $cmd_delta{$item} = $cmd_data{$item} - + ($prev_data{$item} || $cmd_data{$item} - 1); + + $delta_total += $cmd_delta{$item}; + + $cmd_pct{$item} = int(($cmd_data{$item} / $total) * 100); + } + + for my $item (keys %cmd_data) + { + $cmd_delta_pct{$item} = int(($cmd_delta{$item} / $delta_total) * 100); + } + + + ## Display + + Clear() unless $config{batchmode}; + print RESET(); + printf "%18s %10s %4s | %5s %4s\n", 'Command', 'Total', 'Pct', 'Last', 'Pct'; + printf "%18s %10s %4s | %5s %4s\n", '-------', '-----', '---', '----', '---'; + $lines_left -= 2; + + for my $item (sort { $cmd_data{$b} <=> $cmd_data{$a} } keys %cmd_data) + { + printf "%18s %10d %4s | %5d %4s\n", + $item, + $cmd_data{$item}, + $cmd_pct{$item} . "%", + $cmd_delta{$item}, + $cmd_delta_pct{$item} . "%"; + + last if not $lines_left; + $lines_left -= 1; + } + + %prev_data = %cmd_data; +} + +########################################################################### + +sub GetShowVariables() +{ + if (not $config{pager}) + { + if (not $config{pager} = my_which('less')) + { + $config{pager} = my_which('more'); + } + } + + my @rows = Hashes("SHOW /*mytop*/ VARIABLES"); + + open P, "|$config{pager}" or die "$!"; + + for my $row (@rows) + { + my $name = $row->{Variable_name}; + my $value = $row->{Value}; + printf P "%32s: %s\n", $name, $value; + } + + close P; +} + +########################################################################### + +sub GetShowStatus() +{ + Clear() unless $config{batchmode}; + my @rows = Hashes("SHOW /*mytop*/ STATUS"); + + printf "%32s %10s %10s Toggle idle with 'i'\n", 'Counter', 'Total', 'Change'; + printf "%32s %10s %10s\n", '-------', '-----', '------'; + + for my $row (@rows) + { + my $name = $row->{Variable_name}; + my $value = $row->{Value}; + my $old = $statcache{$name}; + my $delta = 0; + + next if $name =~ m/^Com_/; ## skip Com_ stats + next if $value =~ m/^[^0-9]*$/; ## skip non-numeric + + ## TODO: if Qcache is off, we should skip Qcache_ values + + if ($HAS_COLOR and defined $old and $old =~ /^\d/) + { + if ($value > $old) + { + print YELLOW(); + $delta = $value - $old; + } + elsif ($value < $old) + { + print RED(); + $delta = $value - $old; + } + + if (not $config{idle} and $value == $old) + { + ## filter unchanging stats, maybe + print RESET(); + next; + } + } + + printf "%32s: %10s %10s\n", $name, $value, $delta; + print RESET() if $HAS_COLOR; + + $statcache{$name} = $value; + } + +} + +########################################################################### + +sub FullQueryInfo($) +{ + my $id = shift; + + if (not exists $qcache{$id} or not defined $qcache{$id}) + { + print "*** Invalid id. ***\n"; + return; + } + + my $sql = $qcache{$id}; + print $CLEAR; + print "Thread $id was executing following query:\n\n"; + print YELLOW(), $sql,"\n\n", RESET(); +} + +########################################################################### + +sub Explain($) +{ + my $id = shift; + + if (not exists $qcache{$id} or not defined $qcache{$id}) + { + print "*** Invalid id. ***\n"; + return; + } + + my $sql = $qcache{$id}; + my $db = $dbcache{$id}; + + Execute("USE /*mytop*/ $db"); + my @info = Hashes("EXPLAIN $sql"); + print $CLEAR; + print "EXPLAIN $sql:\n\n"; + PrintTable(@info); +} + +########################################################################### + +sub PrintTable(@) +{ + my $cnt = 1; + my @cols = qw(table type possible_keys key key_len ref rows Extra); + + for my $row (@_) + { + print "*** row $cnt ***\n"; + for my $key (@cols) + { + my $val = $row->{$key} || 'NULL'; + printf "%15s: %s\n", $key, $val; + } + $cnt++; + } +} + +########################################################################### + +sub StringOrRegex($) +{ + my $input = shift; + chomp $input; + if (defined $input) + { + ## regex, strip /.../ and use via qr// + if ($input =~ m{^/} and $input =~ m{/$}) + { + $input =~ s{^/}{} if $config{filter_user}; + $input =~ s{/$}{} if $config{filter_user}; + $input = qr/$input/; + } + + + ## reset to match anything + elsif ($input eq '') + { + $input = qr/.*/; + } + + ## string, build a simple regex + else + { + $input = '^' . $input . '$'; + $input = qr/$input/; + } + } + + ## reset to match anything + else + { + $input = qr/.*/; + } + return $input; +} + +########################################################################### + +sub cmd_l +{ + ReadMode($RM_RESET); + + print RED(), "Seconds for long queries: ", RESET(); + my $secs = ReadLine(0); + + if ($secs =~ /^\s*(\d+)/) + { + $config{long} = $1; + if ($config{long} < 1) + { + $config{long} = 1; + } + } + ReadMode($RM_NOBLKRD); +} + +sub cmd_s +{ + ReadMode($RM_RESET); + + print RED(), "Seconds of Delay: ", RESET(); + my $secs = ReadLine(0); + + if ($secs =~ /^\s*(\d+)/) + { + $config{delay} = $1; + if ($config{delay} < 1) + { + $config{delay} = 1; + } + } + ReadMode($RM_NOBLKRD); +} + +sub cmd_S +{ + ReadMode($RM_RESET); + + print RED(), "Seconds for Slow queries: ", RESET(); + my $secs = ReadLine(0); + + if ($secs =~ /^\s*(\d+)/) + { + $config{slow} = $1; + if ($config{slow} < 1) + { + $config{slow} = 1; + } + } + ReadMode($RM_NOBLKRD); +} + +sub cmd_q +{ + ReadMode($RM_RESET); + print "\n"; + exit; +} + +sub trim($) +{ + my $string = shift; + $string =~ s/^\s+//; + $string =~ s/\s+$//; + return $string; +} + +########################################################################### + +sub PrintHelp() +{ + my $help = qq[Help for mytop version $main::VERSION by Jeremy D. Zawodny <${YELLOW}Jeremy\@Zawodny.com${RESET}> + with updates by Mark Grennan <${YELLOW}mark\@grennan.com${RESET}> and Jean Weisbuch <${YELLOW}jean\@phpnet.org${RESET}> + + ? - display this screen + # - debug mode (toggle) + c - command summary view (based on Com_* counters) + C - turn color on and off + d - show only a specific database + e - explain the query that a thread is running + E - display current replication error + f - show full query info for a given thread + F - unfilter the display + h - show only a specifc host's connections + H - toggle the mytop header + i - toggle the display of idle (sleeping) threads + I - show innodb status + k - kill a thread + p - pause the display + l - change long running queries hightlighing + m - switch [mode] to qps (queries/sec) scrolling view + M - switch [mode] to status + o - reverse the sort order (toggle) + q - quit + r - reset the status counters (via FLUSH STATUS on your server) + R - change reverse IP lookup + s - change the delay between screen updates + S - change slow query hightlighting + t - switch to thread view (default) + u - show only a specific user + V - show variables + : - enter a command (not yet implemented) + ! - Skip an error that has stopped replications (at your own risk) + L - show full queries (do not strip to terminal width) + w - adjust the User and DB columns width + a - toggle the progress column + +Base version from ${GREEN}http://www.mysqlfanboy.com/mytop-3${RESET} +This version comes as part of the ${GREEN}MariaDB${RESET} distribution. +]; + + print $help; +} + +sub Sum(@) +{ + my $sum; + while (my $val = shift @_) { $sum += $val; } + return $sum; +} + +## A useful routine from perlfaq + +sub commify($) +{ + local $_ = shift; + return 0 unless defined $_; + 1 while s/^([-+]?\d+)(\d{3})/$1,$2/; + return $_; +} + +## Compact numeric representation (10,000 -> 10.0k) + +sub make_short($) +{ + my $number = shift; + return commify($number) if $config{long_nums}; + my $n = 0; + while ($number > 1_025) { $number /= 1024; $n++; }; + return sprintf "%.1f%s", $number, ('','k','M','G', 'T')[$n]; +} + + +## Run a query and return the records has an array of hashes. + +sub Hashes($) +{ + my $sql = shift; + my @records; + + if (my $sth = Execute($sql)) + { + while (my $ref = $sth->fetchrow_hashref) + { + print "record\n" if $debug; + push @records, $ref; + } + } + return @records; +} + +## Execute an SQL query and return the statement handle. + +sub Execute($) +{ + my $sql = shift; + + $sql =~ s/\n/ /sg; + + my $sth = $dbh->prepare($sql); + + if (not $sth) { ReadMode($RM_RESET); die $DBI::errstr; } + + my $ReturnCode = $sth->execute; + + if (not $ReturnCode) + { + if ($debug) + { + print "query failed\n"; + sleep 10; + } + return undef; + } + + return $sth; +} + +#### +#### my_which is used, because we can't assume that every system has the +#### which command. my_which can take only one argument at a time. +#### Return values: requested system command with the first found path, +#### or undefined, if not found. +#### + +sub my_which +{ + my ($command) = @_; + my (@paths, $path); + + return $command if (-f $command && -x $command); + + ## Check first if this is a source distribution, then if this binary distribution and last in the path + + push @paths, "./extra"; + push @paths, $path_for_script; + push @paths, split(':', $ENV{'PATH'}); + + foreach $path (@paths) + { + $path .= "/$command"; + return $path if (-f $path && -x $path); + } + return undef(); +} + +=pod + +=head1 SYNOPSIS + +B<mytop> [options] + +=head1 AVAILABILITY + +Base version from B<http://www.mysqlfanboy.com/mytop-3>. + +This version comes as part of the B<MariaDB> distribution. See B<https://mariadb.org/>. + +And older (the original) version B<mytop> is available from +http://www.mysqlfanboy.com/mytop-3/ it B<might> also be on CPAN as +well. + +=head1 REQUIREMENTS + +In order for B<mytop> to function properly, you must have the +following: + + * Perl 5.005 or newer + * Getopt::Long + * DBI and DBD::MariaDB or DBD::mysql + * Term::ReadKey from CPAN + +Most systems are likely to have all of those installed--except for +Term::ReadKey. You will need to pick that up from the CPAN. You can +pick up Term::ReadKey here: + + http://search.cpan.org/search?dist=TermReadKey + +And you obviously need access to a MariaDB server with the necessary +security to run the I<SHOW PROCESSLIST> and I<SHOW STATUS> commands. + +If you are a Windows user, using ActiveState's Perl, you can use PPM +(the Perl Package Manager) to install the MariaDB/MySQL and Term::ReadKey +modules. + +=head2 Optional Color Support + +In additon, if you want a color B<mytop> (recommended), install +Term::ANSIColor from the CPAN: + + http://search.cpan.org/search?dist=ANSIColor + +Once you do, B<mytop> will automatically use it. However, color is not +yet working on Windows. Patches welcome. :-) + +=head2 Optional Hi-Res Timing + +If you want B<mytop> to provide more accurate real-time +queries-per-second statistics, install the Time::HiRes module from +CPAN. B<mytop> will automatically notice that you have it and use it +rather than the standard timing mechanism. + +=head2 Platforms + +B<mytop> is known to work on: + + * Linux (2.2.x, 2.4.x) + * FreeBSD (2.2, 3.x, 4.x) + * Mac OS X + * BSDI 4.x + * Solaris 2.x + * Windows NT 4.x (ActivePerl) + +If you find that it works on another platform, please let me +know. Given that it is all Perl code, I expect it to be rather +portable to Unix and Unix-like systems. Heck, it I<might> even work on +Win32 systems. + +=head1 DESCRIPTION + +Help is always welcome in improving this software. Feel free to +contact the author (see L<"AUTHOR"> below) with bug reports, fixes, +suggestions, and comments. Additionally L<"BUGS"> will provide a list +of things this software is not able to do yet. + +Having said that, here are the details on how it works and what you can +do with it. + +=head2 The Basics + +B<mytop> was inspired by the system monitoring tool B<top>. I +routinely use B<top> on Linux, FreeBSD, and Solaris. You are likely to +notice features from each of them here. + +B<mytop> will connect to a MariaDB server and periodically run the +I<SHOW PROCESSLIST> and I<SHOW STATUS> commands and attempt to +summarize the information from them in a useful format. + +=head2 The Display + +The B<mytop> display screen is really broken into two parts. The top 4 +lines (header) contain summary information about your MariaDB +server. For example, you might see something like: + +MariaDB 10.5.0 on localhost load (3.89 3.86 3.91) up 7+23:56:31 [16:33:01] + Queries: 353.4M qps: 531 Slow: 4.5k Se/In/Up/De(%): 87/02/02/00 + Sorts: 2390 qps now: 651 Slow qps: 0.0 Threads: 11 ( 1/ 13) 88/01/03/00 + Handler: (R/W/U/D) 82138/ 5884/ 20/ 1 Tmp: R/W/U: 13623/29501/ 79 + MyISAM Key Cache Efficiency: 99.9% Bps in/out: 157.4k/ 2.2M Now in/out: 554.8k/ 2.6M + +The first line identifies the hostname of the server (localhost) and +the version of MariaDB it is running. The right hand side shows the +uptime of the MariaDB server process in days+hours:minutes:seconds +format (much like FreeBSD's top) as well as the current time. + +The second line displays the total number of queries the server has +processed, the average number of queries per second, the number of +slow queries, and the percentage of Select, Insert, Update, and Delete +queries. + +The third real-time values. First is the number of queries per second, +then the number of slow queries, followed by query precentages (like +on the previous line). + +And the fourth line displays key buffer efficiency (how often keys are +read from the buffer rather than disk) and the number of bytes that +MariaDB has sent and received, both over all and in the last cycle. + +You can toggle the header by hitting B<H> when running B<mytop>. + +The second part of the display lists as many threads as can fit on +screen. By default they are sorted according to their idle time (least +idle first). The display looks like: + + Id User Host Dbase Time Cmd Query or State + -- ---- ---- ----- ---- --- -------------- + 61 jzawodn localhost music 0 Query show processlist + +As you can see, the thread id, username, host from which the user is +connecting, database to which the user is connected, number of seconds +of idle time, the command the thread is executing, and the query info +are all displayed. + +Often times the query info is what you are really interested in, so it +is good to run B<mytop> in an xterm that is wider than the normal 80 +columns if possible. + +The thread display color-codes the threads if you have installed color +support. The current color scheme only works well in a window with a +dark (like black) background. The colors are selected according to the +C<Command> column of the display: + + Query - Yellow + Sleep - White + Connect - Green + Slow - Bright + Long - Magenta + +Those are purely arbitrary and will be customizable in a future +release. If they annoy you just start B<mytop> with the B<--nocolor> +flag or adjust your config file appropriately. + +=head2 Arguments + +B<mytop> handles long and short command-line arguments. Not all +options have both long and short formats, however. The long arguments +have two dashes `--'. Short arguments only have one '-'. + +=over + +=item B<-u> or B<--user> username + +Username to use when logging in to the MariaDB server. Default: ``B<root>''. + +=item B<-p> or B<--pass> or B<--password> I<password> + +Password to use when logging in to the MariaDB server. Default: none. + +WARNING: This is insecure as the password is visible for anyone. +See B<--prompt> instead! + +=item B<-h> or B<--host> I<hostname>[B<:>I<port>] + +Hostname of the MariaDB server. The hostname may be followed by an +option port number. Note that the port is specified separate from the +host when using a config file. Default: ``B<localhost>''. + +=item B<--port> or B<-P> I<port> + +If you're running MariaDB on a non-standard port, use this to specify +the port number. Default: B<3306>. + +=item B<-s> or B<--delay> I<seconds> + +How long between display refreshes. Default: B<5> + +=item B<-d> or B<--db> or B<--database> I<database> + +Use if you'd like B<mytop> to connect to a specific database by +default. Default: none. + +=item B<-b> or B<--batch> or B<--batchmode> + +In batch mode, mytop runs only once, does not clear the screen, and +places no limit on the number of lines it will print. This is suitable +for running periodically (perhaps from B<cron>) to capture the +information into a file for later viewing. You might use batch mode in +a CGI script to occasionally display your MariaDB server status on the +web. + +Default: unset. + +=item B<-S> or B<--socket> I</path/to/socket> + +If you're running B<mytop> on the same host as MariaDB/MySQL, you may wish to +have it use the MariaDB/MySQL socket directly rather than a standard TCP/IP +connection. If you do,just specify one. + +Note that specifying a socket will make B<mytop> ignore any host +and/or port that you might have specified. If the socket does not +exist (or the file specified is not a socket), this option will be +ignored and B<mytop> will use the hostname and port number instead. + +Default: none. + +=item B<--header> or B<--noheader> + +Specify if you want the header to display or not. You can toggle this +with the B<h> key while B<mytop> is running. + +Default: header. + +=item B<--color> or B<--nocolor> + +Specify if you want a color display. This has no effect if you don't +have color support available. + +Default: If you have color support, B<mytop> will try color unless you +tell it not to. + +=item B<-i> or B<--idle> or B<--noi> or B<--noidle> + +Specify if you want idle (sleeping) threads to appear in the list. If +sleeping threads are omitted, the default sorting order is reversed so +that the longest running queries appear at the top of the list. + +Default: idle. + +=item B<--prompt> or B<--noprompt> + +Specify if you want to be prompted to type in your database password. +This provides a little bit more security since it not only prevents +the password from viewable in a process list, but also doesn't require +the password to be stored in plain text in your C<~/.mytop> config file. +You will B<only> be prompted if a password has not been specified in +your config file or through another command line option. + +Default: noprompt. + +=item B<--resolve> + +If you have skip-resolve set on MariaDB (to keep it from doing a reverse +DNS lookup on each inbound connection), mytop can replace IP addresses +with hostnames but toggling this option. + +Default: noresolve + +=item B<--long> or B<--nolong> + +For large numbers print all digits (e.g. 10.000) instead of using a more +compact approximation (e.g. 10.0k). + +Default: nolong. + +=item B<-m> or B<--mode> I<mode> + +Specify initial mode B<qps>(queries/second), B<top>(overview), +B<cmd>(command summary), B<innodb>(InnoDB status) or B<status>(). + +Default: B<top> + +=item B<--sort> or B<--nosort> + +Reverse sort order from ascending to descending using Idle time. + +Default: nosort. + + +=back + +Command-line arguments will always take precedence over config file +options. That happens because the config file is read I<BEFORE> the +command-line arguments are applied. + +=head2 Config File + +Instead of always using bulky command-line parameters, you can also +use a config files for the default value of your options. + +mytop will first read the [client] and [mytop] sections from your +my.cnf files. After that it will read the (C<~/.mytop>) file from your +home directory (if present). These are read I<before> any of your +command-line arguments are processed, so your command-line arguments +will override directives in the config file. + + +Here is a sample config file C<~/.mytop> which implements the defaults +described above. + + user=root + pass= + host=localhost + db=test + delay=5 + port=3306 + slow=10 + socket= + batchmode=0 + header=1 + color=1 + idle=1 + long=120 + +Using a config file will help to ensure that your database password +isn't visible to users on the command-line. Just make sure that the +permissions on C<~/.mytop> are such that others cannot read it (unless +you want them to, of course). + +You may have white space on either side of the C<=> in lines of the +config file. + +=head2 Shortcut Keys + +The following keys perform various actions while B<mytop> is +running. Those which have not been implemented are listed as +such. They are included to give the user idea of what is coming. + +=over + +=item B<?> + +Display help. + +=item B<c> + +Show "command counters" based on the Com_* values in SHOW STATUS. +This is a new feature. Feedback welcome. + +=item B<C> + +Turn display color on and off. Default is on. + +=item B<d> + +Show only threads connected to a particular database. + +=item B<f> + +Given a thread id, display the entire query that thread was (and still +may be) running. + +=item B<F> + +Disable all filtering (host, user, and db). + +=item B<h> + +Only show queries from a particular host. + +=item B<H> + +Toggle the header display. You can also specify either C<header=0> or +C<header=1> in your config file to set the default behavior. + +=item B<i> + +Toggle the display of idle (sleeping) threads. If sleeping threads are +filtered, the default sorting order is reversed so that the longest +running queries appear at the top of the list. + +=item B<I> + +Switch to InnoDB Status mode. The output of "SHOW ENGINE INNODB STATUS" will +be displayed every cycle. In a future version, this may actually +summarize that data rather than producing raw output. + +=item B<k> + +Kill a thread. + +=item B<m> + +Toggle modes. Currently this switches from `top' mode to `qps' +(Queries Per Second Mode). In this mode, mytop will write out one +integer per second. The number written reflects the number of queries +executed by the server in the previous one second interval. + +More modes may be added in the future. + +=item B<o> + +Reverse the default sort order. + +=item B<p> + +Pause display. + +=item B<q> + +Quit B<mytop> + +=item B<r> + +Reset the server's status counters via a I<FLUSH STATUS> command. + +=item B<R> + +Togle IP reverse lookup. Default is on. + +=item B<s> + +Change the sleep time (number of seconds between display refreshes). + +=item B<S> + +Set the number of seconds a query will need to run before it is +considered old and will be highlighted. + +=item B<u> + +Show only threads owned by a giver user. + +=back + +The B<s> key has a command-line counterpart: B<-s>. + +The B<h> key has two command-line counterparts: B<--header> and +B<--noheader>. + +=head1 BUGS + +This is more of a BUGS + WishList. + +Some performance information is not available when talking to a +version 3.22.x MySQL server. Additional information (about threads +mostly) was added to the output of I<SHOW STATUS> in MySQL 3.23.x and +B<mytop> makes use of it. If the information is not available, you +will simply see zeros where the real numbers should be. + +Simply running this program will increase your overall counters (such +as the number of queries run). But you may or may not view that as a +bug. + +B<mytop> consumes too much CPU time when running (verified on older +versions of Linux and FreeBSD). It's likely a problem related to +Term::ReadKey. I haven't had time to investigate yet, so B<mytop> now +automatically lowers its priority when you run it. You may also think +about running B<mytop> on another workstation instead of your database +server. However, C<mytop> on Solaris does B<not> have this problem. +Newer versions of Linux and FreeBSD seem to have fixed this. + +You can't specify the maximum number of threads to list. If you have +many threads and a tall xterm, B<mytop> will always try to display as +many as it can fit. + +The size of most of the columns in the display has a small maximum +width. If you have fairly long database/user/host names the display +may appear odd. I have no good idea as to how best to deal with that +yet. Suggestions are welcome. + +It'd be nice if you could just add B<mytop> configuration directives +in your C<my.cnf> file instead of having a separate config file. + +You should be able to specify the columns you'd like to see in the +display and the order in which they appear. If you only have one +username that connects to your database, it's probably not worth +having the User column appear, for example. + +=head1 AUTHOR + +mytop was developed and is maintained by Jeremy D. Zawodny +(Jeremy@Zawodny.com). + +If you wish to e-mail me regarding this software, B<PLEASE> subscribe +to the B<mytop> mailing list. See the B<mytop> homepage for details. + +=head1 DISCLAIMER + +While I use this software in my job at Yahoo!, I am solely responsible +for it. Yahoo! does not necessarily support this software in any +way. It is merely a personal idea which happened to be very useful in +my job. + +=head1 SEE ALSO + +Please check the MariaDB manual if you're not sure where some of the +output of B<mytop> is coming from. + +=head1 COPYRIGHT + +Copyright (C) 2000-2010, Jeremy D. Zawodny. + +=head1 CREDITS + +Fix a bug. Add a feature. See your name here! + +Many thanks go to these fine folks: + +=over + +=item Jean Weisbuch (jean@phpnet.org) + +Added --fullqueries and --sort options, dynamic user and database columns +width, reading of .my.cnf, state/progress column that can be disabled +dynamically (when available) and various small fixes. + +=item Michael "Monty" Widenius <monty@askmonty.org> + +Fixed a couple of minor bugs that gave warnings on startup. +Added support for MariaDB (show MariaDB at top and % done). +Cut long server version names to display width. +Made 'State' length dynamic. + +=item Mark Grennan (mark@grennan.com) www.linuxfangoy.com + +Added updates for MySQL 5.x. Added 'S' (slow) highlighting. +Added 'C' to turn on and off Color. Added 'l' command to change +color for long running queries. Fixed a few documentation issues. +Monitors Slave status. Added color to Queue hit ratio. +Added number of rows sorted per second. +Created release 1.7. + +=item Sami Ahlroos (sami@avis-net.de) + +Suggested the idle/noidle stuff. + +=item Jan Willamowius (jan@janhh.shnet.org) + +Minor bug report. Documentation fixes. + +=item Alex Osipov (alex@acky.net) + +Long command-line options, Unix socket support. + +=item Stephane Enten (tuf@grolier.fr) + +Suggested batch mode. + +=item Richard Ellerbrock (richarde@eskom.co.za) + +Bug reports and usability suggestions. + +=item William R. Mattil (wrm@newton.irngtx.tel.gte.com) + +Bug report about empty passwords not working. + +=item Benjamin Pflugmann (philemon@spin.de) + +Suggested -P command-line flag as well as other changes. + +=item Justin Mecham <justin@aspect.net> + +Suggested setting $0 to `mytop'. + +=item Thorsten Kunz <thorsten.kunz@de.tiscali.com> + +Provided a fix for cases when we try remove the domain name from the +display even if it is actually an IP address. + +=item Sasha Pachev <sasha@mysql.com> + +Provided the idea of real-time queries per second in the main display. + +=item Paul DuBois <paul@snake.net> + +Pointed out some option-handling bugs. + +=item Mike Wexler <mwexler@tias.com> + +Suggested that we don't mangle (normalize) whitespace in query info by +default. + +=item Mark Zweifel <markez@yahoo-inc.com> + +Make the --idle command-line argument negatable. + +=item Axel Schwenke <schwenke@jobpilot.de> + +Noticed the incorrect formula for query cache hit percentages in +version 1.2. + +=item Steven Roussey <sroussey@network54.com> + +Supplied a patch to help filter binary junk in queries so that +terminals don't freak out. + +=item Jon R. Luini <falcon@chime.com> + +Supplied a patch that formed the basis for C<--prompt> support. +Sean Leach <sleach@wiggum.com> submitted a similar patch. + +=item Yogish Baliga <baliga@yahoo-inc.com> + +Supplied a patch that formed the basis for C<--resolve> support. + +=item Per Andreas Buer <perbu@linpro.no> + +Supplied an excellent patch to tidy up the top display. This includes +showing most values in short form, such as 10k rather than 10000. + +=back + +See the Changes file on the B<mytop> distribution page for more +details on what has changed. + +=head1 LICENSE + +B<mytop> is licensed under the GNU General Public License version +2. For the full license information, please visit +http://www.gnu.org/copyleft/gpl.html + +=cut + +__END__ diff --git a/scripts/wsrep_sst_common.sh b/scripts/wsrep_sst_common.sh new file mode 100644 index 00000000..562f9dc3 --- /dev/null +++ b/scripts/wsrep_sst_common.sh @@ -0,0 +1,1279 @@ +# Copyright (C) 2017-2021 MariaDB +# Copyright (C) 2012-2015 Codership Oy +# +# 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; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston +# MA 02110-1335 USA. + +# This is a common command line parser to be sourced by other SST scripts + +set -u + +WSREP_SST_OPT_BYPASS=0 +WSREP_SST_OPT_BINLOG="" +WSREP_SST_OPT_BINLOG_INDEX="" +WSREP_SST_OPT_LOG_BASENAME="" +WSREP_SST_OPT_DATA="" +WSREP_SST_OPT_AUTH="${WSREP_SST_OPT_AUTH:-}" +WSREP_SST_OPT_USER="${WSREP_SST_OPT_USER:-}" +WSREP_SST_OPT_PSWD="${WSREP_SST_OPT_PSWD:-}" +WSREP_SST_OPT_REMOTE_AUTH="${WSREP_SST_OPT_REMOTE_AUTH:-}" +WSREP_SST_OPT_DEFAULT="" +WSREP_SST_OPT_DEFAULTS="" +WSREP_SST_OPT_EXTRA_DEFAULT="" +WSREP_SST_OPT_EXTRA_DEFAULTS="" +WSREP_SST_OPT_SUFFIX_DEFAULT="" +WSREP_SST_OPT_SUFFIX_VALUE="" +WSREP_SST_OPT_MYSQLD="" +WSREP_SST_OPT_PORT="" +WSREP_SST_OPT_ADDR="" +WSREP_SST_OPT_ADDR_PORT="" +WSREP_SST_OPT_HOST="" +WSREP_SST_OPT_HOST_UNESCAPED="" +WSREP_SST_OPT_HOST_ESCAPED="" +INNODB_DATA_HOME_DIR="${INNODB_DATA_HOME_DIR:-}" +INNODB_LOG_GROUP_HOME="${INNODB_LOG_GROUP_HOME:-}" +INNODB_UNDO_DIR="${INNODB_UNDO_DIR:-}" +INNOEXTRA="" + +while [ $# -gt 0 ]; do +case "$1" in + '--address') + WSREP_SST_OPT_ADDR="$2" + # + # Break address string into host:port/path parts + # + case "$WSREP_SST_OPT_ADDR" in + \[*) + # IPv6 + # Remove the starting and ending square brackets, if present: + addr_no_bracket="${WSREP_SST_OPT_ADDR#\[}" + # Some utilities and subsequent code require an address + # without square brackets: + readonly WSREP_SST_OPT_HOST_UNESCAPED="${addr_no_bracket%%\]*}" + # Square brackets are needed in most cases: + readonly WSREP_SST_OPT_HOST="[${WSREP_SST_OPT_HOST_UNESCAPED}]" + readonly WSREP_SST_OPT_HOST_ESCAPED="\\[${WSREP_SST_OPT_HOST_UNESCAPED}\\]" + # Mark this address as IPv6: + readonly WSREP_SST_OPT_HOST_IPv6=1 + ;; + *) + readonly WSREP_SST_OPT_HOST="${WSREP_SST_OPT_ADDR%%[:/]*}" + readonly WSREP_SST_OPT_HOST_UNESCAPED="$WSREP_SST_OPT_HOST" + readonly WSREP_SST_OPT_HOST_ESCAPED="$WSREP_SST_OPT_HOST" + readonly WSREP_SST_OPT_HOST_IPv6=0 + ;; + esac + # Let's remove the leading part that contains the host address: + remain="${WSREP_SST_OPT_ADDR#$WSREP_SST_OPT_HOST_ESCAPED}" + # Let's remove the ":" character that separates the port number + # from the hostname: + remain="${remain#:}" + # Extract the port number from the address - all characters + # up to "/" (if present): + WSREP_SST_OPT_ADDR_PORT="${remain%%/*}" + # If the "/" character is present, then the path is not empty: + if [ "${remain#*/}" != "$remain" ]; then + # This operation removes everything up to the "/" character, + # effectively removing the port number from the string: + readonly WSREP_SST_OPT_PATH="${remain#*/}" + else + readonly WSREP_SST_OPT_PATH="" + fi + # The rest of the string is the same as the path (for now): + remain="$WSREP_SST_OPT_PATH" + # If there is one more "/" in the string, then everything before + # it will be the module name, otherwise the module name is empty: + if [ "${remain%%/*}" != "$remain" ]; then + # This operation removes the tail after the very first + # occurrence of the "/" character (inclusively): + readonly WSREP_SST_OPT_MODULE="${remain%%/*}" + else + readonly WSREP_SST_OPT_MODULE="" + fi + # Remove the module name part from the string, which ends with "/": + remain="${WSREP_SST_OPT_PATH#*/}" + # If the rest of the string does not match the original, then there + # was something else besides the module name: + if [ "$remain" != "$WSREP_SST_OPT_PATH" ]; then + # Extract the part that matches the LSN by removing all + # characters starting from the very first "/": + readonly WSREP_SST_OPT_LSN="${remain%%/*}" + # Exctract everything after the first occurrence of + # the "/" character in the string: + remain="${remain#*/}" + # If the remainder does not match the original string, + # then there is something else (the version number in + # our case): + if [ "$remain" != "$WSREP_SST_OPT_LSN" ]; then + # Let's extract the version number by removing the tail + # after the very first occurence of the "/" character + # (inclusively): + readonly WSREP_SST_OPT_SST_VER="${remain%%/*}" + else + readonly WSREP_SST_OPT_SST_VER="" + fi + else + readonly WSREP_SST_OPT_LSN="" + readonly WSREP_SST_OPT_SST_VER="" + fi + shift + ;; + '--bypass') + WSREP_SST_OPT_BYPASS=1 + ;; + '--datadir') + # Let's remove the trailing slash: + readonly WSREP_SST_OPT_DATA="${2%/}" + shift + ;; + '--innodb-data-home-dir') + # Let's remove the trailing slash: + readonly INNODB_DATA_HOME_DIR="${2%/}" + shift + ;; + '--innodb-log-group-home-dir') + # Let's remove the trailing slash: + readonly INNODB_LOG_GROUP_HOME="${2%/}" + shift + ;; + '--innodb-undo-directory') + # Let's remove the trailing slash: + readonly INNODB_UNDO_DIR="${2%/}" + shift + ;; + '--defaults-file') + readonly WSREP_SST_OPT_DEFAULT="$1=$2" + readonly WSREP_SST_OPT_DEFAULTS="$1='$2'" + shift + ;; + '--defaults-extra-file') + readonly WSREP_SST_OPT_EXTRA_DEFAULT="$1=$2" + readonly WSREP_SST_OPT_EXTRA_DEFAULTS="$1='$2'" + shift + ;; + '--defaults-group-suffix') + readonly WSREP_SST_OPT_SUFFIX_DEFAULT="$1=$2" + readonly WSREP_SST_OPT_SUFFIX_VALUE="$2" + shift + ;; + '--host') + case "$2" in + \[*) + # IPv6 + # Remove the starting and ending square brackets, if present: + addr_no_bracket="${2#\[}" + # Some utilities and subsequent code require an address + # without square brackets: + readonly WSREP_SST_OPT_HOST_UNESCAPED="${addr_no_bracket%%\]*}" + # Square brackets are needed in most cases: + readonly WSREP_SST_OPT_HOST="[${WSREP_SST_OPT_HOST_UNESCAPED}]" + readonly WSREP_SST_OPT_HOST_ESCAPED="\\[${WSREP_SST_OPT_HOST_UNESCAPED}\\]" + # Mark this address as IPv6: + readonly WSREP_SST_OPT_HOST_IPv6=1 + ;; + *) + readonly WSREP_SST_OPT_HOST="$2" + readonly WSREP_SST_OPT_HOST_UNESCAPED="$2" + readonly WSREP_SST_OPT_HOST_ESCAPED="$2" + readonly WSREP_SST_OPT_HOST_IPv6=0 + ;; + esac + WSREP_SST_OPT_ADDR="$WSREP_SST_OPT_HOST" + shift + ;; + '--local-port') + readonly WSREP_SST_OPT_LPORT="$2" + shift + ;; + '--parent') + readonly WSREP_SST_OPT_PARENT="$2" + shift + ;; + '--password') + WSREP_SST_OPT_PSWD="$2" + shift + ;; + '--port') + readonly WSREP_SST_OPT_PORT="$2" + shift + ;; + '--role') + readonly WSREP_SST_OPT_ROLE="$2" + shift + ;; + '--socket') + readonly WSREP_SST_OPT_SOCKET="$2" + shift + ;; + '--user') + WSREP_SST_OPT_USER="$2" + shift + ;; + '--gtid') + readonly WSREP_SST_OPT_GTID="$2" + shift + ;; + '--binlog'|'--log-bin') + readonly WSREP_SST_OPT_BINLOG="$2" + shift + ;; + '--binlog-index'|'--log-bin-index') + readonly WSREP_SST_OPT_BINLOG_INDEX="$2" + shift + ;; + '--log-basename') + readonly WSREP_SST_OPT_LOG_BASENAME="$2" + shift + ;; + '--gtid-domain-id') + readonly WSREP_SST_OPT_GTID_DOMAIN_ID="$2" + shift + ;; + '--mysqld-args') + original_cmd="" + shift + while [ $# -gt 0 ]; do + lname="${1#--}" + # "--" is interpreted as the end of the list of options: + if [ -z "$lname" ]; then + shift + if [ $# -gt 0 ]; then + # copy "--" to the output string: + original_cmd="$original_cmd --" + # All other arguments must be copied unchanged: + while [ $# -gt 0 ]; do + original_cmd="$original_cmd '$1'" + shift + done + fi + break; + fi + # Make sure the argument does not start with "--", otherwise it + # is a long option, which is processed after this "if": + if [ "$lname" = "$1" ]; then + # Check if the argument is the short option or the short + # options list, starting with "-": + options="${1#-}" + if [ "$options" != "$1" -a -n "$options" ]; then + slist="" + while [ -n "$options" ]; do + # Let's separate the first character as the current + # option name: + if [ -n "$BASH_VERSION" ]; then + option="${options:0:1}" + else + # If it's not bash, then we need to use slow + # external utilities: + option=$(echo "$options" | cut -c1-1) + fi + # And the subsequent characters consider option value: + value="" + if [ ${#options} -gt 0 ]; then + value="${options#?}" + fi + # Check for options without argument: + if [ "$option" != '?' -a \ + "$option" != 'a' -a \ + "$option" != 's' -a \ + "$option" != 'v' ] + then + # If the option value is absent, then check + # the following argument: + if [ -z "$value" -a $# -gt 1 ]; then + # if the next argument does not start with + # the "-" character, then next argument is + # the current option value: + if [ "${2#-}" = "$2" ]; then + shift + value="$1" + fi + fi + if [ $option = 'h' ]; then + if [ -z "$WSREP_SST_OPT_DATA" ]; then + MYSQLD_OPT_DATADIR="${value%/}" + fi + elif [ $option != 'u' -a \ + $option != 'P' ] + then + if [ -z "$value" ]; then + slist="$slist$option" + elif [ -z "$slist" ]; then + slist="$option '$value'" + else + slist="$slist -$option '$value'" + fi + fi + break + + else + slist="$slist$option" + fi + options="$value" + done + if [ -n "$slist" ]; then + original_cmd="$original_cmd -$slist" + fi + elif [ -z "$options" ]; then + # We found an equal sign without any characters after it: + original_cmd="$original_cmd -" + else + # We found a value that does not start with a minus - + # it is a positional argument or the value of previous + # option. Copy it to output string (as is): + original_cmd="$original_cmd '$1'" + fi + shift + continue; + fi + # Now we are sure that we are working with an option + # that has a "long" name, so remove all characters after + # the first equal sign: + option="${1%%=*}" + # The "--loose-" prefix should not affect the recognition + # of the option name: + if [ "${option#--loose-}" != "$option" ]; then + option="--${option#--loose-}" + fi + # Some options just need to be removed from the list: + if [ "$option" != '--defaults-file' -a \ + "$option" != '--defaults-extra-file' -a \ + "$option" != '--defaults-group-suffix' -a \ + "$option" != '--user' -a \ + "$option" != '--port' -a \ + "$option" != '--socket' ]; then + value="${1#*=}" + if [ "$value" = "$1" ]; then + value="" + fi + # Let's fill in the variables containing important paths + # that might not have been passed through explicit parameters + # (+ removing the trailing slash in these paths). Many of these + # options are processed internally within scripts or passed + # explicitly to other programs, so we need to remove them + # from mysqld's argument list: + skip_mysqld_arg=0 + case "$option" in + '--innodb-data-home-dir') + if [ -z "$INNODB_DATA_HOME_DIR" ]; then + MYSQLD_OPT_INNODB_DATA_HOME_DIR="${value%/}" + fi + skip_mysqld_arg=1 + ;; + '--innodb-log-group-home-dir') + if [ -z "$INNODB_LOG_GROUP_HOME" ]; then + MYSQLD_OPT_INNODB_LOG_GROUP_HOME="${value%/}" + fi + skip_mysqld_arg=1 + ;; + '--innodb-undo-directory') + if [ -z "$INNODB_UNDO_DIR" ]; then + MYSQLD_OPT_INNODB_UNDO_DIR="${value%/}" + fi + skip_mysqld_arg=1 + ;; + '--log-bin') + if [ -z "$WSREP_SST_OPT_BINLOG" ]; then + MYSQLD_OPT_LOG_BIN="$value" + fi + skip_mysqld_arg=1 + ;; + '--log-bin-index') + if [ -z "$WSREP_SST_OPT_BINLOG_INDEX" ]; then + MYSQLD_OPT_LOG_BIN_INDEX="$value" + fi + skip_mysqld_arg=1 + ;; + '--log-basename') + if [ -z "$WSREP_SST_OPT_LOG_BASENAME" ]; then + MYSQLD_OPT_LOG_BASENAME="$value" + fi + skip_mysqld_arg=1 + ;; + '--datadir') + if [ -z "$WSREP_SST_OPT_DATA" ]; then + MYSQLD_OPT_DATADIR="${value%/}" + fi + skip_mysqld_arg=1 + ;; + esac + if [ $skip_mysqld_arg -eq 0 ]; then + original_cmd="$original_cmd '$1'" + fi + fi + shift + done + WSREP_SST_OPT_MYSQLD="${original_cmd# *}" + break + ;; + *) # Must be command usage + # exit 1 + ;; +esac +shift +done +readonly WSREP_SST_OPT_BYPASS + +# The same argument can be present on the command line several +# times, in this case we must take its last value: +if [ -n "${MYSQLD_OPT_INNODB_DATA_HOME_DIR:-}" -a \ + -z "$INNODB_DATA_HOME_DIR" ]; then + readonly INNODB_DATA_HOME_DIR="$MYSQLD_OPT_INNODB_DATA_HOME_DIR" +fi +if [ -n "${MYSQLD_OPT_INNODB_LOG_GROUP_HOME:-}" -a \ + -z "$INNODB_LOG_GROUP_HOME" ]; then + readonly INNODB_LOG_GROUP_HOME="$MYSQLD_OPT_INNODB_LOG_GROUP_HOME" +fi +if [ -n "${MYSQLD_OPT_INNODB_UNDO_DIR:-}" -a \ + -z "$INNODB_UNDO_DIR" ]; then + readonly INNODB_UNDO_DIR="$MYSQLD_OPT_INNODB_UNDO_DIR" +fi +if [ -n "${MYSQLD_OPT_LOG_BIN:-}" -a \ + -z "$WSREP_SST_OPT_BINLOG" ]; then + readonly WSREP_SST_OPT_BINLOG="$MYSQLD_OPT_LOG_BIN" +fi +if [ -n "${MYSQLD_OPT_LOG_BIN_INDEX:-}" -a \ + -z "$WSREP_SST_OPT_BINLOG_INDEX" ]; then + readonly WSREP_SST_OPT_BINLOG_INDEX="$MYSQLD_OPT_LOG_BIN_INDEX" +fi +if [ -n "${MYSQLD_OPT_DATADIR:-}" -a \ + -z "$WSREP_SST_OPT_DATA" ]; then + readonly WSREP_SST_OPT_DATA="$MYSQLD_OPT_DATADIR" +fi +if [ -n "${MYSQLD_OPT_LOG_BASENAME:-}" -a \ + -z "$WSREP_SST_OPT_LOG_BASENAME" ]; then + readonly WSREP_SST_OPT_LOG_BASENAME="$MYSQLD_OPT_LOG_BASENAME" +fi + +# If the --log-bin option is present without a value, then +# set WSREP_SST_OPT_BINLOG value using other arguments: +if [ -z "$WSREP_SST_OPT_BINLOG" -a -n "${MYSQLD_OPT_LOG_BIN+x}" ]; then + if [ -n "$WSREP_SST_OPT_LOG_BASENAME" ]; then + # If the WSREP_SST_OPT_BINLOG variable is not set, but + # --log-basename is present among the arguments to mysqld, + # then set WSREP_SST_OPT_BINLOG equal to the base name with + # the "-bin" suffix: + readonly WSREP_SST_OPT_BINLOG="$WSREP_SST_OPT_LOG_BASENAME-bin" + else + # Take the default name: + readonly WSREP_SST_OPT_BINLOG='mysql-bin' + fi +fi + +# Reconstructing the command line arguments that control the innodb +# and binlog options: +if [ -n "$WSREP_SST_OPT_LOG_BASENAME" ]; then + if [ -n "$WSREP_SST_OPT_MYSQLD" ]; then + WSREP_SST_OPT_MYSQLD="--log-basename='$WSREP_SST_OPT_LOG_BASENAME' $WSREP_SST_OPT_MYSQLD" + else + WSREP_SST_OPT_MYSQLD="--log-basename='$WSREP_SST_OPT_LOG_BASENAME'" + fi +fi +if [ -n "$INNODB_DATA_HOME_DIR" ]; then + INNOEXTRA="$INNOEXTRA --innodb-data-home-dir='$INNODB_DATA_HOME_DIR'" +fi +if [ -n "$INNODB_LOG_GROUP_HOME" ]; then + INNOEXTRA="$INNOEXTRA --innodb-log-group-home-dir='$INNODB_LOG_GROUP_HOME'" +fi +if [ -n "$INNODB_UNDO_DIR" ]; then + INNOEXTRA="$INNOEXTRA --innodb-undo-directory='$INNODB_UNDO_DIR'" +fi +if [ -n "$WSREP_SST_OPT_BINLOG" ]; then + INNOEXTRA="$INNOEXTRA --log-bin='$WSREP_SST_OPT_BINLOG'" + if [ -n "$WSREP_SST_OPT_BINLOG_INDEX" ]; then + if [ -n "$WSREP_SST_OPT_MYSQLD" ]; then + WSREP_SST_OPT_MYSQLD="--log-bin-index='$WSREP_SST_OPT_BINLOG_INDEX' $WSREP_SST_OPT_MYSQLD" + else + WSREP_SST_OPT_MYSQLD="--log-bin-index='$WSREP_SST_OPT_BINLOG_INDEX'" + fi + fi +fi + +readonly WSREP_SST_OPT_MYSQLD + +get_binlog() +{ + # if no command line argument and WSREP_SST_OPT_BINLOG is not set, + # try to get it from my.cnf: + if [ -z "$WSREP_SST_OPT_BINLOG" ]; then + WSREP_SST_OPT_BINLOG=$(parse_cnf '--mysqld' 'log-bin') + fi + # if no command line argument and WSREP_SST_OPT_BINLOG_INDEX is not set, + # try to get it from my.cnf: + if [ -z "$WSREP_SST_OPT_BINLOG_INDEX" ]; then + WSREP_SST_OPT_BINLOG_INDEX=$(parse_cnf '--mysqld' 'log-bin-index') + fi + # if no command line argument and WSREP_SST_OPT_LOG_BASENAME is not set, + # try to get it from my.cnf: + if [ -z "$WSREP_SST_OPT_LOG_BASENAME" ]; then + WSREP_SST_OPT_LOG_BASENAME=$(parse_cnf '--mysqld' 'log-basename') + fi + if [ -z "$WSREP_SST_OPT_BINLOG" ]; then + # If the --log-bin option is specified without a parameter, + # then we need to build the name of the index file according + # to the rules described in the server documentation: + if [ -n "${MYSQLD_OPT_LOG_BIN+x}" -o \ + $(in_config '--mysqld' 'log-bin') -eq 1 ] + then + if [ -n "$WSREP_SST_OPT_LOG_BASENAME" ]; then + # If the WSREP_SST_OPT_BINLOG variable is not set, but + # --log-basename is present among the arguments of mysqld, + # then set WSREP_SST_OPT_BINLOG equal to the base name with + # the "-bin" suffix: + readonly WSREP_SST_OPT_BINLOG="$WSREP_SST_OPT_LOG_BASENAME-bin" + else + # If the --log-bin option is present without a value, then + # we take the default name: + readonly WSREP_SST_OPT_BINLOG='mysql-bin' + fi + fi + fi + if [ -n "$WSREP_SST_OPT_BINLOG" ]; then + # If the name of the index file is not specified, then we will build + # it according to the specifications for the server: + if [ -z "$WSREP_SST_OPT_BINLOG_INDEX" ]; then + if [ -n "$WSREP_SST_OPT_LOG_BASENAME" ]; then + # If the WSREP_SST_OPT_BINLOG variable is not set, but + # --log-basename is present among the arguments of mysqld, + # then set WSREP_SST_OPT_BINLOG equal to the base name with + # the "-bin" suffix: + readonly WSREP_SST_OPT_BINLOG_INDEX="$WSREP_SST_OPT_LOG_BASENAME-bin.index" + else + # the default name (note that base of this name + # is already defined above): + readonly WSREP_SST_OPT_BINLOG_INDEX="$WSREP_SST_OPT_BINLOG.index" + fi + fi + fi +} + +# Check the presence of the port value and, if necessary, transfer +# the port number from the address to the WSREP_SST_OPT_PORT variable +# or vice versa, and also, if necessary, substitute the missing port +# value into the address value: +if [ -n "$WSREP_SST_OPT_ADDR_PORT" ]; then + if [ -n "$WSREP_SST_OPT_PORT" ]; then + if [ "$WSREP_SST_OPT_PORT" != "$WSREP_SST_OPT_ADDR_PORT" ]; then + echo "WSREP_SST: [ERROR] port in --port=$WSREP_SST_OPT_PORT differs from port in --address=$WSREP_SST_OPT_ADDR" >&2 + exit 2 + fi + else + # If the address contains a port number, assign it to + # the corresponding variable: + readonly WSREP_SST_OPT_PORT="$WSREP_SST_OPT_ADDR_PORT" + fi +elif [ -n "$WSREP_SST_OPT_ADDR" ]; then + # If the port is missing, take the default port: + if [ -z "$WSREP_SST_OPT_PORT" ]; then + readonly WSREP_SST_OPT_PORT=4444 + fi + WSREP_SST_OPT_ADDR_PORT="$WSREP_SST_OPT_PORT" + # Let's remove the leading part that contains the host address: + remain="${WSREP_SST_OPT_ADDR#$WSREP_SST_OPT_HOST_ESCAPED}" + # Let's remove the ":" character that separates the port number + # from the hostname: + remain="${remain#:}" + # Let's remove all characters upto first "/" character that + # separates the hostname with port number from the path: + remain="${remain#/}" + # Let's construct a new value for the address with the port: + WSREP_SST_OPT_ADDR="$WSREP_SST_OPT_HOST:$WSREP_SST_OPT_PORT" + if [ -n "$remain" ]; then + WSREP_SST_OPT_ADDR="$WSREP_SST_OPT_ADDR/$remain" + fi +fi + +readonly WSREP_SST_OPT_ADDR +readonly WSREP_SST_OPT_ADDR_PORT + +# try to use my_print_defaults, mysql and mysqldump that come with the sources +# (for MTR suite) +script_binary=$(dirname "$0") +SCRIPTS_DIR=$(cd "$script_binary"; pwd -P) +EXTRA_DIR="$SCRIPTS_DIR/../extra" +CLIENT_DIR="$SCRIPTS_DIR/../client" + +if [ -x "$CLIENT_DIR/mysql" ]; then + MYSQL_CLIENT="$CLIENT_DIR/mysql" +else + MYSQL_CLIENT="$(command -v mysql)" +fi + +if [ -x "$CLIENT_DIR/mysqldump" ]; then + MYSQLDUMP="$CLIENT_DIR/mysqldump" +else + MYSQLDUMP="$(command -v mysqldump)" +fi + +wsrep_log() +{ + # echo everything to stderr so that it gets into common error log + # deliberately made to look different from the rest of the log + local readonly tst="$(date +%Y%m%d\ %H:%M:%S.%N | cut -b -21)" + echo "WSREP_SST: $* ($tst)" >&2 +} + +wsrep_log_error() +{ + wsrep_log "[ERROR] $*" +} + +wsrep_log_warning() +{ + wsrep_log "[WARNING] $*" +} + +wsrep_log_info() +{ + wsrep_log "[INFO] $*" +} + +if [ -x "$SCRIPTS_DIR/my_print_defaults" ]; then + MY_PRINT_DEFAULTS="$SCRIPTS_DIR/my_print_defaults" +elif [ -x "$EXTRA_DIR/my_print_defaults" ]; then + MY_PRINT_DEFAULTS="$EXTRA_DIR/my_print_defaults" +else + MY_PRINT_DEFAULTS="$(command -v my_print_defaults)" + if [ -z "$MY_PRINT_DEFAULTS" ]; then + wsrep_log_error "my_print_defaults not found in path" + exit 2 + fi +fi + +readonly MY_PRINT_DEFAULTS + +wsrep_defaults="$WSREP_SST_OPT_DEFAULTS" +wsrep_defaults="$wsrep_defaults${wsrep_defaults:+ }$WSREP_SST_OPT_EXTRA_DEFAULTS" +wsrep_defaults="$wsrep_defaults${wsrep_defaults:+ }$WSREP_SST_OPT_SUFFIX_DEFAULT" + +readonly WSREP_SST_OPT_CONF="$wsrep_defaults" + +wsrep_defaults="$WSREP_SST_OPT_DEFAULT" +wsrep_defaults="$wsrep_defaults${wsrep_defaults:+ }$WSREP_SST_OPT_EXTRA_DEFAULT" +wsrep_defaults="$wsrep_defaults${wsrep_defaults:+ }$WSREP_SST_OPT_SUFFIX_DEFAULT" + +readonly WSREP_SST_OPT_CONF_UNQUOTED="$wsrep_defaults" + +# +# User can specify mariabackup specific settings that will be used during sst +# process like encryption, etc. Parse such configuration option. +# +# 1st parameter: group (config file section like sst) or +# my_print_defaults argument (like --mysqld) +# 2nd parameter: var : name of the variable in the section, e.g. server-id +# 3rd parameter: default value for the parameter +# +parse_cnf() +{ + local groups="$1" + local var="$2" + local reval="" + + # normalize the variable names specified in the .cnf file + # (user can use '_' or '-', for example, log-bin or log_bin), + # then search for the last instance of the desired variable + # and finally get the value of that variable (if the variable + # was specified several times - we use only its last instance): + + local pattern='BEGIN {OFS=FS="="} {sub(/^--loose/,"-",$0); gsub(/_/,"-",$1); if ($1=="--'"$var"'") lastval=substr($0,length($1)+2)} END {print lastval}' + + while [ -n "$groups" ]; do + # Remove the largest suffix starting with the '|' character: + local group="${groups%%\|*}" + # Remove the remainder (the group name) from the rest + # of the groups list (as if it were a prefix): + groups="${groups#$group}" + groups="${groups#\|}" + # If the group name is the same as the "mysqld" without "--" prefix, + # then try to use it together with the group suffix: + if [ "$group" = 'mysqld' -a -n "$WSREP_SST_OPT_SUFFIX_VALUE" ]; then + reval=$("$MY_PRINT_DEFAULTS" \ + ${WSREP_SST_OPT_DEFAULT:+"$WSREP_SST_OPT_DEFAULT"} \ + ${WSREP_SST_OPT_EXTRA_DEFAULT:+"$WSREP_SST_OPT_EXTRA_DEFAULT"} \ + ${WSREP_SST_OPT_SUFFIX_DEFAULT:+"$WSREP_SST_OPT_SUFFIX_DEFAULT"} \ + "mysqld$WSREP_SST_OPT_SUFFIX_VALUE" | awk "$pattern") + if [ -n "$reval" ]; then + break + fi + fi + # Let's try to use the group name as it is: + reval=$("$MY_PRINT_DEFAULTS" \ + ${WSREP_SST_OPT_DEFAULT:+"$WSREP_SST_OPT_DEFAULT"} \ + ${WSREP_SST_OPT_EXTRA_DEFAULT:+"$WSREP_SST_OPT_EXTRA_DEFAULT"} \ + ${WSREP_SST_OPT_SUFFIX_DEFAULT:+"$WSREP_SST_OPT_SUFFIX_DEFAULT"} \ + "$group" | awk "$pattern") + if [ -n "$reval" ]; then + break + fi + done + + # Use default if we haven't found a value: + if [ -z "$reval" ]; then + [ -n "${3:-}" ] && reval="$3" + fi + echo "$reval" +} + +# +# This function simply checks for the presence of the parameter +# in the config file, but does not return its value. It returns "1" +# (true) even if the parameter is present in the configuration file +# without a value: +# +in_config() +{ + local groups="$1" + local var="$2" + local found=0 + + # normalize the variable names specified in the .cnf file + # (user can use '_' or '-', for example, log-bin or log_bin), + # then search for the last instance(s) of the desired variable: + + local pattern='BEGIN {OFS=FS="="; found=0} {sub(/^--loose/,"-",$0); gsub(/_/,"-",$1); if ($1=="--'"$var"'") found=1} END {print found}' + + while [ -n "$groups" ]; do + # Remove the largest suffix starting with the '|' character: + local group="${groups%%\|*}" + # Remove the remainder (the group name) from the rest + # of the groups list (as if it were a prefix): + groups="${groups#$group}" + groups="${groups#\|}" + # If the group name is the same as the "mysqld" without "--" prefix, + # then try to use it together with the group suffix: + if [ "$group" = 'mysqld' -a -n "$WSREP_SST_OPT_SUFFIX_VALUE" ]; then + found=$("$MY_PRINT_DEFAULTS" \ + ${WSREP_SST_OPT_DEFAULT:+"$WSREP_SST_OPT_DEFAULT"} \ + ${WSREP_SST_OPT_EXTRA_DEFAULT:+"$WSREP_SST_OPT_EXTRA_DEFAULT"} \ + ${WSREP_SST_OPT_SUFFIX_DEFAULT:+"$WSREP_SST_OPT_SUFFIX_DEFAULT"} \ + "mysqld$WSREP_SST_OPT_SUFFIX_VALUE" | awk "$pattern") + if [ $found -ne 0 ]; then + break + fi + fi + # Let's try to use the group name as it is: + found=$($MY_PRINT_DEFAULTS \ + ${WSREP_SST_OPT_DEFAULT:+"$WSREP_SST_OPT_DEFAULT"} \ + ${WSREP_SST_OPT_EXTRA_DEFAULT:+"$WSREP_SST_OPT_EXTRA_DEFAULT"} \ + ${WSREP_SST_OPT_SUFFIX_DEFAULT:+"$WSREP_SST_OPT_SUFFIX_DEFAULT"} \ + "$group" | awk "$pattern") + if [ $found -ne 0 ]; then + break + fi + done + echo $found +} + +wsrep_auth_not_set() +{ + [ -z "$WSREP_SST_OPT_AUTH" ] +} + +# Get rid of incorrect values resulting from substitution +# in programs external to the script: +if [ "$WSREP_SST_OPT_USER" = '(null)' ]; then + WSREP_SST_OPT_USER="" +fi +if [ "$WSREP_SST_OPT_PSWD" = '(null)' ]; then + WSREP_SST_OPT_PSWD="" +fi +if [ "$WSREP_SST_OPT_AUTH" = '(null)' ]; then + WSREP_SST_OPT_AUTH="" +fi + +# Let's read the value of the authentication string from the +# configuration file so that it does not go to the command line +# and does not appear in the ps output: +if wsrep_auth_not_set; then + WSREP_SST_OPT_AUTH=$(parse_cnf 'sst' 'wsrep-sst-auth') +fi + +# Splitting WSREP_SST_OPT_AUTH as "user:password" pair: +if ! wsrep_auth_not_set +then + # Extract username as shortest prefix up to first ':' character: + WSREP_SST_OPT_AUTH_USER="${WSREP_SST_OPT_AUTH%%:*}" + if [ -z "$WSREP_SST_OPT_USER" ]; then + # if the username is not in the command line arguments, + # set the username and password using WSREP_SST_OPT_AUTH + # from the environment: + WSREP_SST_OPT_USER="$WSREP_SST_OPT_AUTH_USER" + WSREP_SST_OPT_PSWD="${WSREP_SST_OPT_AUTH#*:}" + elif [ "$WSREP_SST_OPT_USER" = "$WSREP_SST_OPT_AUTH_USER" ]; then + # If the username in the command line arguments and in + # the environment variable are the same, set the password + # if it was not specified in the command line: + if [ -z "$WSREP_SST_OPT_PSWD" ]; then + WSREP_SST_OPT_PSWD="${WSREP_SST_OPT_AUTH#*:}" + fi + else + # The username is passed through the command line and does + # not match the username in the environment variable - ignore + # the environment and rebuild the authentication parameters: + WSREP_SST_OPT_AUTH="$WSREP_SST_OPT_USER:$WSREP_SST_OPT_PSWD" + fi +fi + +readonly WSREP_SST_OPT_USER +readonly WSREP_SST_OPT_PSWD +readonly WSREP_SST_OPT_AUTH + +if [ -n "$WSREP_SST_OPT_REMOTE_AUTH" ] +then + # Split auth string at the last ':' + readonly WSREP_SST_OPT_REMOTE_USER="${WSREP_SST_OPT_REMOTE_AUTH%%:*}" + readonly WSREP_SST_OPT_REMOTE_PSWD="${WSREP_SST_OPT_REMOTE_AUTH#*:}" +else + readonly WSREP_SST_OPT_REMOTE_USER= + readonly WSREP_SST_OPT_REMOTE_PSWD= +fi + +readonly WSREP_SST_OPT_REMOTE_AUTH + +if [ -n "$WSREP_SST_OPT_DATA" ] +then + SST_PROGRESS_FILE="$WSREP_SST_OPT_DATA/sst_in_progress" +else + SST_PROGRESS_FILE="" +fi + +wsrep_cleanup_progress_file() +{ + [ -n "$SST_PROGRESS_FILE" -a \ + -f "$SST_PROGRESS_FILE" ] && rm -f "$SST_PROGRESS_FILE" 2>/dev/null || true +} + +wsrep_check_program() +{ + local prog="$1" + local cmd=$(command -v "$prog") + if [ -z "$cmd" ]; then + echo "'$prog' not found in PATH" + return 2 # no such file or directory + fi +} + +wsrep_check_programs() +{ + local ret=0 + + while [ $# -gt 0 ] + do + wsrep_check_program "$1" || ret=$? + shift + done + + return $ret +} + +wsrep_check_datadir() +{ + if [ -z "$WSREP_SST_OPT_DATA" ] + then + wsrep_log_error "The '--datadir' parameter must be passed to the SST script" + exit 2 + fi +} + +get_openssl() +{ + # If the OPENSSL_BINARY variable is already defined, just return: + if [ -n "${OPENSSL_BINARY+x}" ]; then + return + fi + # Let's look for openssl: + OPENSSL_BINARY="$(command -v openssl)" + if [ -z "$OPENSSL_BINARY" ]; then + OPENSSL_BINARY='/usr/bin/openssl' + if [ -z "$OPENSSL_BINARY" ]; then + OPENSSL_BINARY="" + fi + fi + readonly OPENSSL_BINARY +} + +# +# Generate a string equivalent to 16 random bytes +# +wsrep_gen_secret() +{ + get_openssl + if [ -n "$OPENSSL_BINARY" ] + then + echo $("$OPENSSL_BINARY" rand -hex 16) + else + printf "%04x%04x%04x%04x%04x%04x%04x%04x" \ + $RANDOM $RANDOM $RANDOM $RANDOM \ + $RANDOM $RANDOM $RANDOM $RANDOM + fi +} + +# +# Checking if the address passed to us is local. +# If the second parameter is nonzero, then this function +# does not check for matches with local domain names: +# +is_local_ip() +{ + # Rapid recognition of the most common cases: + [ "$1" = '127.0.0.1' -o \ + "$1" = '127.0.0.2' -o \ + "$1" = 'localhost' -o \ + "$1" = '[::1]' ] && return 0 + # If the address starts with "127." this is probably a local + # address, but we need to clarify what follows this prefix: + if [ "${1#127.}" != "$1" ]; then + # All 127.0.0.0/8 addresses are local: + if echo "$1" | grep -q -E '^127\.[0-9]+\.[0-9]+\.[0-9]+$'; then + return 0 + fi + fi + # If the second parameter is nonzero, then we will skip + # the domain name check: + if [ "${2:-0}" -eq 0 ]; then + # We consider all the names of a given host to be local addresses: + [ "$1" = "$(hostname -s)" -o \ + "$1" = "$(hostname -f)" -o \ + "$1" = "$(hostname -d)" ] && return 0 + fi + # Now let's check if the given address is assigned to + # one of the network cards: + local ip_util="$(command -v ip)" + if [ -n "$ip_util" ]; then + # ip address show ouput format is " inet[6] <address>/<mask>": + "$ip_util" address show \ + | grep -E "^[[:space:]]*inet.? [^[:space:]]+/" -o \ + | grep -F " $1/" >/dev/null && return 0 + else + local ifconfig_util="$(command -v ifconfig)" + if [ -n "$ifconfig_util" ]; then + # ifconfig output format is " inet[6] <address> ...": + "$ifconfig_util" \ + | grep -E "^[[:space:]]*inet.? [^[:space:]]+ " -o \ + | grep -F " $1 " >/dev/null && return 0 + fi + fi + return 1 +} + +check_sockets_utils() +{ + lsof_available=0 + sockstat_available=0 + ss_available=0 + + [ -n "$(command -v lsof)" ] && lsof_available=1 + [ -n "$(command -v sockstat)" ] && sockstat_available=1 + [ -n "$(command -v ss)" ] && ss_available=1 + + if [ $lsof_available -eq 0 -a \ + $sockstat_available -eq 0 -a \ + $ss_available -eq 0 ] + then + wsrep_log_error "Neither lsof, nor sockstat or ss tool was found in " \ + "the PATH. Make sure you have it installed." + exit 2 # ENOENT + fi +} + +# +# Check if the port is in the "listen" state. +# The first parameter is the PID of the process that should +# listen on the port - if it is not known, you can specify +# an empty string or zero. +# The second parameter is the port number. +# The third parameter is a list of the names of utilities +# (via "|") that can listen on this port during the state +# transfer. +# +check_port() +{ + local pid="$1" + local port="$2" + local utils="$3" + + [ -z "$pid" ] || [ $pid -eq 0 ] && pid='[0-9]+' + + local rc=1 + + if [ $lsof_available -ne 0 ]; then + lsof -Pnl -i ":$port" 2>/dev/null | \ + grep -q -E "^($utils)[^[:space:]]*[[:space:]]+$pid[[:space:]].*\\(LISTEN\\)" && rc=0 + elif [ $sockstat_available -ne 0 ]; then + sockstat -p "$port" 2>/dev/null | \ + grep -q -E "[[:space:]]+($utils)[^[:space:]]*[[:space:]]+$pid[[:space:]].*[[:space:]]LISTEN" && rc=0 + elif [ $ss_available -ne 0 ]; then + ss -nlpH "( sport = :$port )" 2>/dev/null | \ + grep -q -E "users:\\(.*\\(\"($utils)[^[:space:]]*\"[^)]*,pid=$pid(,[^)]*)?\\)" && rc=0 + else + wsrep_log_error "unknown sockets utility" + exit 2 # ENOENT + fi + + return $rc +} + +# +# If the ssl_dhparams variable is already set, uses that as a source +# of dh parameters for OpenSSL. Otherwise, looks for dhparams.pem in +# the datadir, and creates it there if it can't find the file. +# +check_for_dhparams() +{ + ssl_dhparams="$DATA/dhparams.pem" + if [ ! -r "$ssl_dhparams" ]; then + get_openssl + if [ -n "$OPENSSL_BINARY" ]; then + wsrep_log_info "Could not find dhparams file, creating $ssl_dhparams" + if ! "$OPENSSL_BINARY" dhparam -out "$ssl_dhparams" 2048 >/dev/null 2>&1 + then + wsrep_log_error "******** ERROR *****************************************" + wsrep_log_error "* Could not create the dhparams.pem file with OpenSSL. *" + wsrep_log_error "********************************************************" + ssl_dhparams="" + fi + else + # Rollback: if openssl is not installed, then use + # the default parameters: + ssl_dhparams="" + fi + fi +} + +# +# Verifies that the CA file verifies the certificate. +# Doing this here lets us generate better error messages. +# +# 1st param: path to the CA file. +# 2nd param: path to the certificate. +# +verify_ca_matches_cert() +{ + local ca_path="$1" + local cert_path="$2" + + # If the openssl utility is not installed, then + # we will not do this certificate check: + get_openssl + if [ -z "$OPENSSL_BINARY" ]; then + return + fi + + if ! "$OPENSSL_BINARY" verify -verbose -CAfile "$ca_path" "$cert_path" >/dev/null 2>&1 + then + wsrep_log_error "******** FATAL ERROR ********************************************" + wsrep_log_error "* The certifcate and CA (certificate authority) do not match. *" + wsrep_log_error "* It does not appear that the certificate was issued by the CA. *" + wsrep_log_error "* Please check your certificate and CA files. *" + wsrep_log_error "*****************************************************************" + exit 22 + fi +} + +# +# Verifies that the certificate matches the private key. +# Doing this will save us having to wait for a timeout that would +# otherwise occur. +# +# 1st param: path to the certificate. +# 2nd param: path to the private key. +# +verify_cert_matches_key() +{ + local cert_path="$1" + local key_path="$2" + + # If the diff utility is not installed, then + # we will not do this certificate check: + if [ -z "$(command -v diff)" ]; then + return + fi + + # If the openssl utility is not installed, then + # we will not do this certificate check: + get_openssl + if [ -z "$OPENSSL_BINARY" ]; then + return + fi + + # Generate the public key from the cert and the key. + # They should match (otherwise we can't create an SSL connection). + if ! diff <("$OPENSSL_BINARY" x509 -in "$cert_path" -pubkey -noout 2>/dev/null) \ + <("$OPENSSL_BINARY" pkey -in "$key_path" -pubout 2>/dev/null) >/dev/null 2>&1 + then + wsrep_log_error "******************* FATAL ERROR ****************" + wsrep_log_error "* The certifcate and private key do not match. *" + wsrep_log_error "* Please check your certificate and key files. *" + wsrep_log_error "************************************************" + exit 22 + fi +} + +# +# Compares two version strings. +# The first parameter is the version to be checked; +# The second parameter is the minimum version required; +# Returns 1 (failure) if $1 >= $2, 0 (success) otherwise. +# +check_for_version() +{ + y1="${1#*.}" + [ "$y1" = "$1" ] && y1="" + z1=${y1#*.} + [ "$z1" = "$y1" ] && z1="" + x1="${1%%.*}" + y1="${y1%%.*}" + z1="${z1%%.*}" + [ -z "$y1" ] && y1=0 + [ -z "$z1" ] && z1=0 + y2="${2#*.}" + [ "$y2" = "$2" ] && y2="" + z2="${y2#*.}" + [ "$z2" = "$y2" ] && z2="" + x2="${2%%.*}" + y2="${y2%%.*}" + z2="${z2%%.*}" + [ -z "$y2" ] && y2=0 + [ -z "$z2" ] && z2=0 + [ $x1 -lt $x2 ] && return 1 + [ $x1 -gt $x2 ] && return 0 + [ $y1 -lt $y2 ] && return 1 + [ $y1 -gt $y2 ] && return 0 + [ $z1 -lt $z2 ] && return 1 + return 0 +} + +trim_string() +{ + if [ -n "$BASH_VERSION" ]; then + local pattern="[![:space:]${2:-}]" + local x="${1#*$pattern}" + local z=${#1} + x=${#x} + if [ $x -ne $z ]; then + local y="${1%$pattern*}" + y=${#y} + x=$(( z-x-1 )) + y=$(( y-x+1 )) + printf '%s' "${1:$x:$y}" + else + printf '' + fi + else + local pattern="[[:space:]${2:-}]" + echo "$1" | sed -E "s/^$pattern+|$pattern+\$//g" + fi +} + +# +# Check whether process is still running. +# The first parameter contains the name of the PID file. +# The second parameter is the flag of the need to delete +# the PID file. +# If the second parameter is not zero and not empty, +# then if the process terminates, the corresponding +# PID file will be deleted. +# This function also sets the CHECK_PID variable to zero +# if the process has already exited, or writes the PID +# of the process there if it is still running. +# +check_pid() +{ + local pid_file="$1" + if [ -r "$pid_file" ]; then + local pid=$(cat "$pid_file" 2>/dev/null) + if [ -n "$pid" ]; then + if [ $pid -ne 0 ]; then + if ps -p "$pid" >/dev/null 2>&1; then + CHECK_PID=$pid + return 0 + fi + fi + fi + local remove=${2:-0} + if [ $remove -eq 1 ]; then + rm -f "$pid_file" + fi + fi + CHECK_PID=0 + return 1 +} + +# +# Checking that the process with the specified PID is still +# running and killing it in this case by sending SIGTERM +# (using the "kill" operation). +# The first parameter contains PID of the process. +# The second and third parameters (both optional) are the names +# of the PID and the configuration files, which should be removed +# after the process ends. +# If the first parameter (PID of the process) is zero, then +# the function immediately deletes the PID and the configuration +# files (if specified), without any additional checks. +# +cleanup_pid() +{ + local pid=$1 + local pid_file="${2:-}" + local config="${3:-}" + + if [ $pid -ne 0 ]; then + if ps -p $pid >/dev/null 2>&1; then + if kill $pid >/dev/null 2>&1; then + sleep 0.5 + local round=0 + local force=0 + while ps -p $pid >/dev/null 2>&1; do + sleep 1 + round=$(( round+1 )) + if [ $round -eq 16 ]; then + if [ $force -eq 0 ]; then + round=8 + force=1 + kill -9 $pid >/dev/null 2>&1 + sleep 0.5 + else + return 1 + fi + fi + done + elif ps -p $pid >/dev/null 2>&1; then + wsrep_log_warning "Unable to kill PID=$pid ($pid_file)" + return 1 + fi + fi + fi + + [ -n "$pid_file" ] && [ -f "$pid_file" ] && rm -f "$pid_file" + [ -n "$config" ] && [ -f "$config" ] && rm -f "$config" + + return 0 +} + +nproc="" + +get_proc() +{ + if [ -z "$nproc" ]; then + set +e + if [ "$OS" = 'Linux' ]; then + nproc=$(grep -c processor /proc/cpuinfo 2>/dev/null) + elif [ "$OS" = 'Darwin' -o "$OS" = 'FreeBSD' ]; then + nproc=$(sysctl -n hw.ncpu) + fi + if [ -z "$nproc" ] || [ $nproc -eq 0 ]; then + nproc=1 + fi + set -e + fi +} diff --git a/scripts/wsrep_sst_mariabackup.sh b/scripts/wsrep_sst_mariabackup.sh new file mode 100644 index 00000000..46804c9d --- /dev/null +++ b/scripts/wsrep_sst_mariabackup.sh @@ -0,0 +1,1326 @@ +#!/bin/bash -ue +# Copyright (C) 2017-2021 MariaDB +# Copyright (C) 2013 Percona 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; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston +# MA 02110-1335 USA. + +# Documentation: +# https://mariadb.com/kb/en/mariabackup-overview/ +# Make sure to read that before proceeding! + +. $(dirname "$0")/wsrep_sst_common +wsrep_check_datadir + +OS="$(uname)" +ealgo="" +eformat="" +ekey="" +ekeyfile="" +encrypt=0 +ecode=0 +ssyslog="" +ssystag="" +BACKUP_PID="" +tcert="" +tpem="" +tkey="" +tmode="DISABLED" +sockopt="" +progress="" +ttime=0 +totime=0 +lsn="" +ecmd="" +rlimit="" +# Initially +stagemsg="$WSREP_SST_OPT_ROLE" +cpat="" +speciald=1 +ib_home_dir="" +ib_log_dir="" +ib_undo_dir="" + +sfmt="" +strmcmd="" +tfmt="" +tcmd="" +payload=0 +pvformat="-F '%N => Rate:%r Avg:%a Elapsed:%t %e Bytes: %b %p'" +pvopts="-f -i 10 -N $WSREP_SST_OPT_ROLE" +STATDIR="" +uextra=0 +disver="" + +tmpopts="" +itmpdir="" +xtmpdir="" + +scomp="" +sdecomp="" + +ssl_dhparams="" + +compress='none' +compress_chunk="" +compress_threads="" + +backup_threads="" + +encrypt_threads="" +encrypt_chunk="" + +readonly SECRET_TAG="secret" + +# Required for backup locks +# For backup locks it is 1 sent by joiner +# 5.6.21 PXC and later can't donate to an older joiner +sst_ver=1 + +if [ -n "$(command -v pv)" ] && pv --help | grep -qw -- '-F'; then + pvopts="$pvopts $pvformat" +fi +pcmd="pv $pvopts" +declare -a RC + +BACKUP_BIN="$(command -v mariabackup)" +if [ ! -x "$BACKUP_BIN" ]; then + wsrep_log_error 'mariabackup binary not found in path' + exit 42 +fi + +DATA="$WSREP_SST_OPT_DATA" +INFO_FILE="xtrabackup_galera_info" +IST_FILE="xtrabackup_ist" +MAGIC_FILE="$DATA/$INFO_FILE" + +INNOAPPLYLOG="$DATA/mariabackup.prepare.log" +INNOMOVELOG="$DATA/mariabackup.move.log" +INNOBACKUPLOG="$DATA/mariabackup.backup.log" + +# Setting the path for ss and ip +export PATH="/usr/sbin:/sbin:$PATH" + +timeit() +{ + local stage="$1" + shift + local cmd="$@" + local x1 x2 took extcode + + if [ $ttime -eq 1 ]; then + x1=$(date +%s) + wsrep_log_info "Evaluating $cmd" + eval "$cmd" + extcode=$? + x2=$(date +%s) + took=$(( x2-x1 )) + wsrep_log_info "NOTE: $stage took $took seconds" + totime=$(( totime+took )) + else + wsrep_log_info "Evaluating $cmd" + eval "$cmd" + extcode=$? + fi + return $extcode +} + +get_keys() +{ + # $encrypt -eq 1 is for internal purposes only + if [ $encrypt -ge 2 -o $encrypt -eq -1 ]; then + return + fi + + if [ $encrypt -eq 0 ]; then + if [ -n "$ealgo" -o -n "$ekey" -o -n "$ekeyfile" ]; then + wsrep_log_error "Options for encryption are specified, " \ + "but encryption itself is disabled. SST may fail." + fi + return + fi + + if [ $sfmt = 'tar' ]; then + wsrep_log_info "NOTE: key-based encryption (encrypt=1) " \ + "cannot be enabled with tar format" + encrypt=-1 + return + fi + + wsrep_log_info "Key based encryption enabled in my.cnf" + + if [ -z "$ealgo" ]; then + wsrep_log_error "FATAL: Encryption algorithm empty from my.cnf, bailing out" + exit 3 + fi + + if [ -z "$ekey" -a ! -r "$ekeyfile" ]; then + wsrep_log_error "FATAL: Either key or keyfile must be readable" + exit 3 + fi + + if [ "$eformat" = 'openssl' ]; then + get_openssl + if [ -z "$OPENSSL_BINARY" ]; then + wsrep_log_error "If encryption using the openssl is enabled, " \ + "then you need to install openssl" + exit 2 + fi + ecmd="'$OPENSSL_BINARY' enc -$ealgo" + if "$OPENSSL_BINARY" enc -help 2>&1 | grep -qw -- '-pbkdf2'; then + ecmd="$ecmd -pbkdf2" + elif "$OPENSSL_BINARY" enc -help 2>&1 | grep -qw -- '-iter'; then + ecmd="$ecmd -iter 1" + elif "$OPENSSL_BINARY" enc -help 2>&1 | grep -qw -- '-md'; then + ecmd="$ecmd -md sha256" + fi + if [ -z "$ekey" ]; then + ecmd="$ecmd -kfile '$ekeyfile'" + else + ecmd="$ecmd -k '$ekey'" + fi + elif [ "$eformat" = 'xbcrypt' ]; then + if [ -z "$(command -v xbcrypt)" ]; then + wsrep_log_error "If encryption using the xbcrypt is enabled, " \ + "then you need to install xbcrypt" + exit 2 + fi + wsrep_log_info "NOTE: xbcrypt-based encryption, " \ + "supported only from Xtrabackup 2.1.4" + if [ -z "$ekey" ]; then + ecmd="xbcrypt --encrypt-algo='$ealgo' --encrypt-key-file='$ekeyfile'" + else + ecmd="xbcrypt --encrypt-algo='$ealgo' --encrypt-key='$ekey'" + fi + if [ -n "$encrypt_threads" ]; then + ecmd="$ecmd --encrypt-threads=$encrypt_threads" + fi + if [ -n "$encrypt_chunk" ]; then + ecmd="$ecmd --encrypt-chunk-size=$encrypt_chunk" + fi + else + wsrep_log_error "Unknown encryption format='$eformat'" + exit 2 + fi + + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + ecmd="$ecmd -d" + fi + + stagemsg="$stagemsg-XB-Encrypted" +} + +get_transfer() +{ + if [ $tfmt = 'nc' ]; then + wsrep_log_info "Using netcat as streamer" + wsrep_check_programs nc + tcmd="nc" + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + if nc -h 2>&1 | grep -q 'ncat'; then + wsrep_log_info "Using Ncat as streamer" + tcmd="$tcmd -l" + elif nc -h 2>&1 | grep -qw -- '-d'; then + wsrep_log_info "Using Debian netcat as streamer" + tcmd="$tcmd -dl" + if [ $WSREP_SST_OPT_HOST_IPv6 -eq 1 ]; then + # When host is not explicitly specified (when only the port + # is specified) netcat can only bind to an IPv4 address if + # the "-6" option is not explicitly specified: + tcmd="$tcmd -6" + fi + else + wsrep_log_info "Using traditional netcat as streamer" + tcmd="$tcmd -l -p" + fi + tcmd="$tcmd $SST_PORT" + else + # Check to see if netcat supports the '-N' flag. + # -N Shutdown the network socket after EOF on stdin + # If it supports the '-N' flag, then we need to use the '-N' + # flag, otherwise the transfer will stay open after the file + # transfer and cause the command to timeout. + # Older versions of netcat did not need this flag and will + # return an error if the flag is used. + if nc -h 2>&1 | grep -qw -- '-N'; then + tcmd="$tcmd -N" + wsrep_log_info "Using nc -N" + fi + # netcat doesn't understand [] around IPv6 address + if nc -h 2>&1 | grep -q ncat; then + wsrep_log_info "Using Ncat as streamer" + elif nc -h 2>&1 | grep -qw -- '-d'; then + wsrep_log_info "Using Debian netcat as streamer" + else + wsrep_log_info "Using traditional netcat as streamer" + tcmd="$tcmd -q0" + fi + tcmd="$tcmd $WSREP_SST_OPT_HOST_UNESCAPED $SST_PORT" + fi + else + tfmt='socat' + + wsrep_log_info "Using socat as streamer" + wsrep_check_programs socat + + if [ -n "$sockopt" ]; then + sockopt=$(trim_string "$sockopt" ',') + if [ -n "$sockopt" ]; then + sockopt=",$sockopt" + fi + fi + + # Add an option for ipv6 if needed: + if [ $WSREP_SST_OPT_HOST_IPv6 -eq 1 ]; then + # If sockopt contains 'pf=ip6' somewhere in the middle, + # this will not interfere with socat, but exclude the trivial + # cases when sockopt contains 'pf=ip6' as prefix or suffix: + if [ "$sockopt" = "${sockopt#,pf=ip6}" -a \ + "$sockopt" = "${sockopt%,pf=ip6}" ] + then + sockopt=",pf=ip6$sockopt" + fi + fi + + if [ $encrypt -lt 2 ]; then + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + tcmd="socat -u TCP-LISTEN:$SST_PORT,reuseaddr$sockopt stdio" + else + tcmd="socat -u stdio TCP:$REMOTEIP:$SST_PORT$sockopt" + fi + return + fi + + if ! socat -V | grep -q -F 'WITH_OPENSSL 1'; then + wsrep_log_error "******** FATAL ERROR ************************************************ " + wsrep_log_error "* Encryption requested, but socat is not OpenSSL enabled (encrypt=$encrypt) *" + wsrep_log_error "********************************************************************* " + exit 2 + fi + + local action='Decrypting' + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + tcmd="socat -u openssl-listen:$SST_PORT,reuseaddr" + else + tcmd="socat -u stdio openssl-connect:$REMOTEIP:$SST_PORT" + action='Encrypting' + fi + + if [ "${sockopt#*,dhparam=}" != "$sockopt" ]; then + if [ -z "$ssl_dhparams" ]; then + # Determine the socat version + SOCAT_VERSION=$(socat -V 2>&1 | grep -m1 -oe '[0-9]\.[0-9][\.0-9]*') + if [ -z "$SOCAT_VERSION" ]; then + wsrep_log_error "******** FATAL ERROR ******************" + wsrep_log_error "* Cannot determine the socat version. *" + wsrep_log_error "***************************************" + exit 2 + fi + if ! check_for_version "$SOCAT_VERSION" '1.7.3'; then + # socat versions < 1.7.3 will have 512-bit dhparams (too small) + # so create 2048-bit dhparams and send that as a parameter: + check_for_dhparams + fi + fi + if [ -n "$ssl_dhparams" ]; then + tcmd="$tcmd,dhparam='$ssl_dhparams'" + fi + fi + + if [ $encrypt -eq 2 ]; then + wsrep_log_info "Using openssl based encryption with socat: with crt and pem" + if [ -z "$tpem" -o -z "$tcert" ]; then + wsrep_log_error "Both PEM and CRT files required" + exit 22 + fi + if [ ! -r "$tpem" -o ! -r "$tcert" ]; then + wsrep_log_error "Both PEM and CRT files must be readable" + exit 22 + fi + verify_ca_matches_cert "$tcert" "$tpem" + tcmd="$tcmd,cert='$tpem',cafile='$tcert'$sockopt" + stagemsg="$stagemsg-OpenSSL-Encrypted-2" + wsrep_log_info "$action with cert=$tpem, cafile=$tcert" + elif [ $encrypt -eq 3 -o $encrypt -eq 4 ]; then + wsrep_log_info "Using openssl based encryption with socat: with key and crt" + if [ -z "$tpem" -o -z "$tkey" ]; then + wsrep_log_error "Both certificate and key files required" + exit 22 + fi + if [ ! -r "$tpem" -o ! -r "$tkey" ]; then + wsrep_log_error "Both certificate and key files must be readable" + exit 22 + fi + verify_cert_matches_key "$tpem" "$tkey" + stagemsg="$stagemsg-OpenSSL-Encrypted-3" + if [ -z "$tcert" ]; then + if [ $encrypt -eq 4 ]; then + wsrep_log_error "Peer certificate required if encrypt=4" + exit 22 + fi + # no verification + tcmd="$tcmd,cert='$tpem',key='$tkey',verify=0$sockopt" + wsrep_log_info "$action with cert=$tpem, key=$tkey, verify=0" + else + # CA verification + if [ ! -r "$tcert" ]; then + wsrep_log_error "Certificate file must be readable" + exit 22 + fi + verify_ca_matches_cert "$tcert" "$tpem" + if [ -n "$WSREP_SST_OPT_REMOTE_USER" ]; then + CN_option=",commonname='$WSREP_SST_OPT_REMOTE_USER'" + elif [ $encrypt -eq 4 ]; then + CN_option=",commonname=''" + elif is_local_ip "$WSREP_SST_OPT_HOST_UNESCAPED"; then + CN_option=',commonname=localhost' + else + CN_option=",commonname='$WSREP_SST_OPT_HOST_UNESCAPED'" + fi + tcmd="$tcmd,cert='$tpem',key='$tkey',cafile='$tcert'$CN_option$sockopt" + wsrep_log_info "$action with cert=$tpem, key=$tkey, cafile=$tcert" + fi + else + wsrep_log_info "Unknown encryption mode: encrypt=$encrypt" + exit 22 + fi + + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + tcmd="$tcmd stdio" + fi + fi +} + +get_footprint() +{ + pushd "$WSREP_SST_OPT_DATA" 1>/dev/null + payload=$(find . -regex '.*\.ibd$\|.*\.MYI$\|.*\.MYD$\|.*ibdata1$' -type f -print0 | du --files0-from=- --block-size=1 -c -s | awk 'END { print $1 }') + if [ "$compress" != 'none' ]; then + # QuickLZ has around 50% compression ratio + # When compression/compaction used, the progress is only an approximate. + payload=$(( payload*1/2 )) + fi + popd 1>/dev/null + pcmd="$pcmd -s $payload" + adjust_progress +} + +adjust_progress() +{ + if [ -z "$(command -v pv)" ]; then + wsrep_log_error "pv not found in path: $PATH" + wsrep_log_error "Disabling all progress/rate-limiting" + pcmd="" + rlimit="" + progress="" + return + fi + + if [ -n "$progress" -a "$progress" != '1' ]; then + if [ -e "$progress" ]; then + pcmd="$pcmd 2>>'$progress'" + else + pcmd="$pcmd 2>'$progress'" + fi + elif [ -z "$progress" -a -n "$rlimit" ]; then + # When rlimit is non-zero + pcmd="pv -q" + fi + + if [ -n "$rlimit" -a "$WSREP_SST_OPT_ROLE" = 'donor' ]; then + wsrep_log_info "Rate-limiting SST to $rlimit" + pcmd="$pcmd -L \$rlimit" + fi +} + +encgroups='--mysqld|sst|xtrabackup' + +check_server_ssl_config() +{ + tcert=$(parse_cnf "$encgroups" 'ssl-ca') + tpem=$(parse_cnf "$encgroups" 'ssl-cert') + tkey=$(parse_cnf "$encgroups" 'ssl-key') +} + +read_cnf() +{ + sfmt=$(parse_cnf sst streamfmt 'mbstream') + tfmt=$(parse_cnf sst transferfmt 'socat') + + encrypt=$(parse_cnf "$encgroups" 'encrypt' 0) + tmode=$(parse_cnf "$encgroups" 'ssl-mode' 'DISABLED' | tr [:lower:] [:upper:]) + + if [ $encrypt -eq 0 -o $encrypt -ge 2 ] + then + if [ "$tmode" != 'DISABLED' -o $encrypt -ge 2 ] + then + tcert=$(parse_cnf 'sst' 'tca') + tpem=$(parse_cnf 'sst' 'tcert') + tkey=$(parse_cnf 'sst' 'tkey') + fi + if [ "$tmode" != 'DISABLED' ]; then + # backward-incompatible behavior + if [ -z "$tpem" -a -z "$tkey" -a -z "$tcert" ]; then + # no old-style SSL config in [sst] + check_server_ssl_config + fi + if [ 0 -eq $encrypt -a -n "$tpem" -a -n "$tkey" ] + then + encrypt=3 # enable cert/key SSL encyption + + # avoid CA verification if not set explicitly: + # nodes may happen to have different CA if self-generated + # zeroing up tcert does the trick + [ "${tmode#VERIFY}" != "$tmode" ] || tcert="" + fi + fi + elif [ $encrypt -eq 1 ]; then + ealgo=$(parse_cnf "$encgroups" 'encrypt-algo') + eformat=$(parse_cnf "$encgroups" 'encrypt-format' 'openssl') + ekey=$(parse_cnf "$encgroups" 'encrypt-key') + ekeyfile=$(parse_cnf "$encgroups" 'encrypt-key-file') + fi + + wsrep_log_info "SSL configuration: CA='$tcert', CERT='$tpem'," \ + "KEY='$tkey', MODE='$tmode', encrypt='$encrypt'" + + sockopt=$(parse_cnf sst sockopt "") + progress=$(parse_cnf sst progress "") + ttime=$(parse_cnf sst time 0) + cpat='.*\.pem$\|.*galera\.cache$\|.*sst_in_progress$\|.*\.sst$\|.*gvwstate\.dat$\|.*grastate\.dat$\|.*\.err$\|.*\.log$\|.*RPM_UPGRADE_MARKER$\|.*RPM_UPGRADE_HISTORY$' + [ "$OS" = 'FreeBSD' ] && cpat=$(echo "$cpat" | sed 's/\\|/|/g') + cpat=$(parse_cnf sst cpat "$cpat") + scomp=$(parse_cnf sst compressor "") + sdecomp=$(parse_cnf sst decompressor "") + + rlimit=$(parse_cnf sst rlimit "") + uextra=$(parse_cnf sst use-extra 0) + speciald=$(parse_cnf sst sst-special-dirs 1) + iopts=$(parse_cnf sst inno-backup-opts "") + iapts=$(parse_cnf sst inno-apply-opts "") + impts=$(parse_cnf sst inno-move-opts "") + stimeout=$(parse_cnf sst sst-initial-timeout 300) + ssyslog=$(parse_cnf sst sst-syslog 0) + ssystag=$(parse_cnf mysqld_safe syslog-tag "${SST_SYSLOG_TAG:-}") + ssystag="$ssystag-" + sstlogarchive=$(parse_cnf sst sst-log-archive 1) + sstlogarchivedir=$(parse_cnf sst sst-log-archive-dir '/tmp/sst_log_archive') + + if [ $speciald -eq 0 ]; then + wsrep_log_error "sst-special-dirs equal to 0 is not supported, falling back to 1" + speciald=1 + fi + + if [ $ssyslog -ne -1 ]; then + ssyslog=$(in_config 'mysqld_safe' 'syslog') + fi + + if [ "$WSREP_SST_OPT_ROLE" = 'donor' ]; then + compress=$(parse_cnf "$encgroups" 'compress' 'none') + if [ "$compress" != 'none' ]; then + compress_chunk=$(parse_cnf "$encgroups" 'compress-chunk-size') + compress_threads=$(parse_cnf "$encgroups" 'compress-threads') + fi + fi + + backup_threads=$(parse_cnf "$encgroups" 'backup-threads') + + if [ "$eformat" = 'xbcrypt' ]; then + encrypt_threads=$(parse_cnf "$encgroups" 'encrypt-threads') + encrypt_chunk=$(parse_cnf "$encgroups" 'encrypt-chunk-size') + fi +} + +get_stream() +{ + if [ "$sfmt" = 'mbstream' -o "$sfmt" = 'xbstream' ]; then + sfmt='mbstream' + STREAM_BIN="$(command -v mbstream)" + if [ -z "$STREAM_BIN" ]; then + wsrep_log_error "Streaming with $sfmt, but $sfmt not found in path" + exit 42 + fi + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + strmcmd="'$STREAM_BIN' -x" + else + strmcmd="'$STREAM_BIN' -c '$INFO_FILE'" + fi + else + sfmt='tar' + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + strmcmd='tar xfi -' + else + strmcmd="tar cf - '$INFO_FILE'" + fi + fi + wsrep_log_info "Streaming with $sfmt" +} + +sig_joiner_cleanup() +{ + wsrep_log_error "Removing $MAGIC_FILE file due to signal" + [ -f "$MAGIC_FILE" ] && rm -f "$MAGIC_FILE" +} + +cleanup_at_exit() +{ + # Since this is invoked just after exit NNN + local estatus=$? + if [ $estatus -ne 0 ]; then + wsrep_log_error "Cleanup after exit with status:$estatus" + fi + + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + wsrep_log_info "Removing the sst_in_progress file" + wsrep_cleanup_progress_file + else + if [ -n "$BACKUP_PID" ]; then + if check_pid "$BACKUP_PID" 1; then + wsrep_log_error "mariabackup process is still running. Killing..." + cleanup_pid $CHECK_PID "$BACKUP_PID" + fi + fi + [ -f "$DATA/$IST_FILE" ] && rm -f "$DATA/$IST_FILE" + fi + + if [ -n "$progress" -a -p "$progress" ]; then + wsrep_log_info "Cleaning up fifo file $progress" + rm -f "$progress" || true + fi + + wsrep_log_info "Cleaning up temporary directories" + + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + if [ -n "$STATDIR" ]; then + [ -d "$STATDIR" ] && rm -rf "$STATDIR" + fi + else + [ -n "$xtmpdir" -a -d "$xtmpdir" ] && rm -rf "$xtmpdir" || true + [ -n "$itmpdir" -a -d "$itmpdir" ] && rm -rf "$itmpdir" || true + fi + + # Final cleanup + pgid=$(ps -o pgid= $$ | grep -o '[0-9]*') + + # This means no setsid done in mysqld. + # We don't want to kill mysqld here otherwise. + if [ $$ -eq $pgid ]; then + # This means a signal was delivered to the process. + # So, more cleanup. + if [ $estatus -ge 128 ]; then + kill -KILL -- -$$ || true + fi + fi + + exit $estatus +} + +setup_ports() +{ + SST_PORT="$WSREP_SST_OPT_PORT" + if [ "$WSREP_SST_OPT_ROLE" = 'donor' ]; then + REMOTEIP="$WSREP_SST_OPT_HOST" + lsn="$WSREP_SST_OPT_LSN" + sst_ver="$WSREP_SST_OPT_SST_VER" + fi +} + +# +# Waits ~30 seconds for socat or nc to open the port and +# then reports ready, regardless of timeout. +# +wait_for_listen() +{ + local PORT="$1" + local ADDR="$2" + local MODULE="$3" + for i in {1..150}; do + if check_port "" "$PORT" 'socat|nc'; then + break + fi + sleep 0.2 + done + echo "ready $ADDR/$MODULE//$sst_ver" +} + +check_extra() +{ + local use_socket=1 + if [ $uextra -eq 1 ]; then + local thread_handling=$(parse_cnf '--mysqld' 'thread-handling') + if [ "$thread_handling" = 'pool-of-threads' ]; then + local eport=$(parse_cnf '--mysqld' 'extra-port') + if [ -n "$eport" ]; then + # mariabackup works only locally. + # Hence, setting host to 127.0.0.1 unconditionally: + wsrep_log_info "SST through extra_port $eport" + INNOEXTRA="$INNOEXTRA --host=127.0.0.1 --port=$eport" + use_socket=0 + else + wsrep_log_error "Extra port $eport null, failing" + exit 1 + fi + else + wsrep_log_info "Thread pool not set, ignore the option use_extra" + fi + fi + if [ $use_socket -eq 1 -a -n "$WSREP_SST_OPT_SOCKET" ]; then + INNOEXTRA="$INNOEXTRA --socket='$WSREP_SST_OPT_SOCKET'" + fi +} + +recv_joiner() +{ + local dir="$1" + local msg="$2" + local tmt=$3 + local checkf=$4 + local wait=$5 + + if [ ! -d "$dir" ]; then + # This indicates that IST is in progress + return + fi + + local ltcmd="$tcmd" + if [ $tmt -gt 0 ]; then + if [ -n "$(command -v timeout)" ]; then + if timeout --help | grep -qw -- '-k'; then + ltcmd="timeout -k $(( tmt+10 )) $tmt $tcmd" + else + ltcmd="timeout -s9 $tmt $tcmd" + fi + fi + fi + + pushd "$dir" 1>/dev/null + set +e + + if [ $wait -ne 0 ]; then + wait_for_listen "$SST_PORT" "$ADDR" "$MODULE" & + fi + + timeit "$msg" "$ltcmd | $strmcmd; RC=( "\${PIPESTATUS[@]}" )" + + set -e + popd 1>/dev/null + + if [ ${RC[0]} -eq 124 ]; then + wsrep_log_error "Possible timeout in receiving first data from " \ + "donor in gtid stage: exit codes: ${RC[@]}" + exit 32 + fi + + for ecode in "${RC[@]}"; do + if [ $ecode -ne 0 ]; then + wsrep_log_error "Error while getting data from donor node: " \ + "exit codes: ${RC[@]}" + exit 32 + fi + done + + if [ $checkf -eq 1 ]; then + if [ ! -r "$MAGIC_FILE" ]; then + # this message should cause joiner to abort + wsrep_log_error "receiving process ended without creating " \ + "'$MAGIC_FILE'" + wsrep_log_info "Contents of datadir" + wsrep_log_info $(ls -l "$dir/"*) + exit 32 + fi + + # check donor supplied secret + SECRET=$(grep -F -- "$SECRET_TAG " "$MAGIC_FILE" 2>/dev/null | cut -d ' ' -f 2) + if [ "$SECRET" != "$MY_SECRET" ]; then + wsrep_log_error "Donor does not know my secret!" + wsrep_log_info "Donor:'$SECRET', my:'$MY_SECRET'" + exit 32 + fi + + # remove secret from the magic file + grep -v -F -- "$SECRET_TAG " "$MAGIC_FILE" > "$MAGIC_FILE.new" + mv "$MAGIC_FILE.new" "$MAGIC_FILE" + fi +} + +send_donor() +{ + local dir="$1" + local msg="$2" + + pushd "$dir" 1>/dev/null + set +e + timeit "$msg" "$strmcmd | $tcmd; RC=( "\${PIPESTATUS[@]}" )" + set -e + popd 1>/dev/null + + for ecode in "${RC[@]}"; do + if [ $ecode -ne 0 ]; then + wsrep_log_error "Error while sending data to joiner node: " \ + "exit codes: ${RC[@]}" + exit 32 + fi + done +} + +monitor_process() +{ + local sst_stream_pid=$1 + + while true ; do + if ! ps -p "$WSREP_SST_OPT_PARENT" >/dev/null 2>&1; then + wsrep_log_error "Parent mysqld process (PID: $WSREP_SST_OPT_PARENT) terminated unexpectedly." + kill -- -"$WSREP_SST_OPT_PARENT" + exit 32 + fi + if ! ps -p "$sst_stream_pid" >/dev/null 2>&1; then + break + fi + sleep 0.1 + done +} + +[ -f "$MAGIC_FILE" ] && rm -f "$MAGIC_FILE" + +if [ "$WSREP_SST_OPT_ROLE" != 'joiner' -a "$WSREP_SST_OPT_ROLE" != 'donor' ]; then + wsrep_log_error "Invalid role '$WSREP_SST_OPT_ROLE'" + exit 22 +fi + +read_cnf +setup_ports + +if "$BACKUP_BIN" --help 2>/dev/null | grep -qw -- '--version-check'; then + disver='--no-version-check' +fi + +# if no command line argument and INNODB_DATA_HOME_DIR environment variable +# is not set, try to get it from my.cnf: +if [ -z "$INNODB_DATA_HOME_DIR" ]; then + INNODB_DATA_HOME_DIR=$(parse_cnf '--mysqld' 'innodb-data-home-dir') +fi + +OLD_PWD="$(pwd)" + +cd "$WSREP_SST_OPT_DATA" +if [ -n "$INNODB_DATA_HOME_DIR" ]; then + # handle both relative and absolute paths + [ ! -d "$INNODB_DATA_HOME_DIR" ] && mkdir -p "$INNODB_DATA_HOME_DIR" + cd "$INNODB_DATA_HOME_DIR" +fi +INNODB_DATA_HOME_DIR=$(pwd -P) + +cd "$OLD_PWD" + +if [ $ssyslog -eq 1 ]; then + if [ -n "$(command -v logger)" ]; then + wsrep_log_info "Logging all stderr of SST/mariabackup to syslog" + + exec 2> >(logger -p daemon.err -t ${ssystag}wsrep-sst-$WSREP_SST_OPT_ROLE) + + wsrep_log_error() + { + logger -p daemon.err -t ${ssystag}wsrep-sst-$WSREP_SST_OPT_ROLE "$@" + } + + wsrep_log_info() + { + logger -p daemon.info -t ${ssystag}wsrep-sst-$WSREP_SST_OPT_ROLE "$@" + } + else + wsrep_log_error "logger not in path: $PATH. Ignoring" + fi + INNOAPPLY="2>&1 | logger -p daemon.err -t ${ssystag}innobackupex-apply" + INNOMOVE="2>&1 | logger -p daemon.err -t ${ssystag}innobackupex-move" + INNOBACKUP="2> >(logger -p daemon.err -t ${ssystag}innobackupex-backup)" +else + if [ $sstlogarchive -eq 1 ] + then + ARCHIVETIMESTAMP=$(date "+%Y.%m.%d-%H.%M.%S.%N") + + if [ -n "$sstlogarchivedir" ]; then + if [ ! -d "$sstlogarchivedir" ]; then + mkdir -p "$sstlogarchivedir" + fi + fi + + if [ -e "$INNOAPPLYLOG" ] + then + if [ -n "$sstlogarchivedir" ] + then + newfile=$(basename "$INNOAPPLYLOG") + newfile="$sstlogarchivedir/$newfile.$ARCHIVETIMESTAMP" + else + newfile="$INNOAPPLYLOG.$ARCHIVETIMESTAMP" + fi + wsrep_log_info "Moving '$INNOAPPLYLOG' to '$newfile'" + mv "$INNOAPPLYLOG" "$newfile" + gzip "$newfile" + fi + + if [ -e "$INNOMOVELOG" ] + then + if [ -n "$sstlogarchivedir" ] + then + newfile=$(basename "$INNOMOVELOG") + newfile="$sstlogarchivedir/$newfile.$ARCHIVETIMESTAMP" + else + newfile="$INNOMOVELOG.$ARCHIVETIMESTAMP" + fi + wsrep_log_info "Moving '$INNOMOVELOG' to '$newfile'" + mv "$INNOMOVELOG" "$newfile" + gzip "$newfile" + fi + + if [ -e "$INNOBACKUPLOG" ] + then + if [ -n "$sstlogarchivedir" ] + then + newfile=$(basename "$INNOBACKUPLOG") + newfile="$sstlogarchivedir/$newfile.$ARCHIVETIMESTAMP" + else + newfile="$INNOBACKUPLOG.$ARCHIVETIMESTAMP" + fi + wsrep_log_info "Moving '$INNOBACKUPLOG' to '$newfile'" + mv "$INNOBACKUPLOG" "$newfile" + gzip "$newfile" + fi + fi + INNOAPPLY="> '$INNOAPPLYLOG' 2>&1" + INNOMOVE="> '$INNOMOVELOG' 2>&1" + INNOBACKUP="2> '$INNOBACKUPLOG'" +fi + +setup_commands() +{ + local mysqld_args="" + if [ -n "$WSREP_SST_OPT_MYSQLD" ]; then + mysqld_args="--mysqld-args $WSREP_SST_OPT_MYSQLD" + fi + INNOAPPLY="$BACKUP_BIN --prepare $disver $iapts $INNOEXTRA --target-dir='$DATA' --datadir='$DATA' $mysqld_args $INNOAPPLY" + INNOMOVE="$BACKUP_BIN $WSREP_SST_OPT_CONF --move-back $disver $impts --force-non-empty-directories --target-dir='$DATA' --datadir='${TDATA:-$DATA}' $INNOMOVE" + INNOBACKUP="$BACKUP_BIN $WSREP_SST_OPT_CONF --backup $disver $iopts $tmpopts $INNOEXTRA --galera-info --stream=$sfmt --target-dir='$itmpdir' --datadir='$DATA' $mysqld_args $INNOBACKUP" +} + +get_stream +get_transfer + +if [ "$WSREP_SST_OPT_ROLE" = 'donor' ] +then + trap cleanup_at_exit EXIT + + if [ $WSREP_SST_OPT_BYPASS -eq 0 ] + then + if [ -z "$sst_ver" ]; then + wsrep_log_error "Upgrade joiner to 5.6.21 or higher for backup locks support" + wsrep_log_error "The joiner is not supported for this version of donor" + exit 93 + fi + + tmpdir=$(parse_cnf "$encgroups" 'tmpdir') + if [ -z "$tmpdir" ]; then + xtmpdir="$(mktemp -d)" + else + xtmpdir=$(mktemp '-d' "--tmpdir=$tmpdir") + fi + + wsrep_log_info "Using '$xtmpdir' as mariabackup temporary directory" + tmpopts="--tmpdir='$xtmpdir'" + + itmpdir="$(mktemp -d)" + wsrep_log_info "Using '$itmpdir' as mariabackup working directory" + + usrst=0 + if [ -n "$WSREP_SST_OPT_USER" ]; then + INNOEXTRA="$INNOEXTRA --user='$WSREP_SST_OPT_USER'" + usrst=1 + fi + + if [ -n "$WSREP_SST_OPT_PSWD" ]; then + export MYSQL_PWD="$WSREP_SST_OPT_PSWD" + elif [ $usrst -eq 1 ]; then + # Empty password, used for testing, debugging etc. + unset MYSQL_PWD + fi + + check_extra + + wsrep_log_info "Streaming GTID file before SST" + + # Store donor's wsrep GTID (state ID) and wsrep_gtid_domain_id + # (separated by a space). + echo "$WSREP_SST_OPT_GTID $WSREP_SST_OPT_GTID_DOMAIN_ID" > "$MAGIC_FILE" + + if [ -n "$WSREP_SST_OPT_REMOTE_PSWD" ]; then + # Let joiner know that we know its secret + echo "$SECRET_TAG $WSREP_SST_OPT_REMOTE_PSWD" >> "$MAGIC_FILE" + fi + + ttcmd="$tcmd" + + if [ -n "$scomp" ]; then + tcmd="$scomp | $tcmd" + fi + + get_keys + if [ $encrypt -eq 1 ]; then + tcmd="$ecmd | $tcmd" + fi + + send_donor "$DATA" "$stagemsg-gtid" + + # Restore the transport commmand to its original state + tcmd="$ttcmd" + + if [ -n "$progress" ]; then + get_footprint + tcmd="$pcmd | $tcmd" + elif [ -n "$rlimit" ]; then + adjust_progress + tcmd="$pcmd | $tcmd" + fi + + wsrep_log_info "Sleeping before data transfer for SST" + sleep 10 + + wsrep_log_info "Streaming the backup to joiner at $REMOTEIP:$SST_PORT" + + # Add compression to the head of the stream (if specified) + if [ -n "$scomp" ]; then + tcmd="$scomp | $tcmd" + fi + + # Add encryption to the head of the stream (if specified) + if [ $encrypt -eq 1 ]; then + tcmd="$ecmd | $tcmd" + fi + + iopts="--databases-exclude='lost+found' $iopts" + + if [ ${FORCE_FTWRL:-0} -eq 1 ]; then + wsrep_log_info "Forcing FTWRL due to environment variable FORCE_FTWRL equal to $FORCE_FTWRL" + iopts="--no-backup-locks $iopts" + fi + + # if compression is enabled for backup files, then add the + # appropriate options to the mariabackup command line: + if [ "$compress" != 'none' ]; then + iopts="--compress${compress:+=$compress} $iopts" + if [ -n "$compress_threads" ]; then + iopts="--compress-threads=$compress_threads $iopts" + fi + if [ -n "$compress_chunk" ]; then + iopts="--compress-chunk-size=$compress_chunk $iopts" + fi + fi + + if [ -n "$backup_threads" ]; then + iopts="--parallel=$backup_threads $iopts" + fi + + setup_commands + set +e + timeit "$stagemsg-SST" "$INNOBACKUP | $tcmd; RC=( "\${PIPESTATUS[@]}" )" + set -e + + if [ ${RC[0]} -ne 0 ]; then + wsrep_log_error "mariabackup finished with error: ${RC[0]}. " \ + "Check syslog or '$INNOBACKUPLOG' for details" + exit 22 + elif [ ${RC[$(( ${#RC[@]}-1 ))]} -eq 1 ]; then + wsrep_log_error "$tcmd finished with error: ${RC[1]}" + exit 22 + fi + + # mariabackup implicitly writes PID to fixed location in $xtmpdir + BACKUP_PID="$xtmpdir/xtrabackup_pid" + + else # BYPASS FOR IST + + wsrep_log_info "Bypassing the SST for IST" + echo "continue" # now server can resume updating data + + # Store donor's wsrep GTID (state ID) and wsrep_gtid_domain_id + # (separated by a space). + echo "$WSREP_SST_OPT_GTID $WSREP_SST_OPT_GTID_DOMAIN_ID" > "$MAGIC_FILE" + echo "1" > "$DATA/$IST_FILE" + + if [ -n "$scomp" ]; then + tcmd="$scomp | $tcmd" + fi + + get_keys + if [ $encrypt -eq 1 ]; then + tcmd="$ecmd | $tcmd" + fi + + strmcmd="$strmcmd '$IST_FILE'" + + send_donor "$DATA" "$stagemsg-IST" + + fi + + echo "done $WSREP_SST_OPT_GTID" + wsrep_log_info "Total time on donor: $totime seconds" + +elif [ "$WSREP_SST_OPT_ROLE" = 'joiner' ] +then + [ -e "$SST_PROGRESS_FILE" ] && wsrep_log_info "Stale sst_in_progress file: $SST_PROGRESS_FILE" + [ -n "$SST_PROGRESS_FILE" ] && touch "$SST_PROGRESS_FILE" + + ib_home_dir="$INNODB_DATA_HOME_DIR" + + # if no command line argument and INNODB_LOG_GROUP_HOME is not set, + # try to get it from my.cnf: + if [ -z "$INNODB_LOG_GROUP_HOME" ]; then + INNODB_LOG_GROUP_HOME=$(parse_cnf '--mysqld' 'innodb-log-group-home-dir') + fi + + ib_log_dir="$INNODB_LOG_GROUP_HOME" + + # if no command line argument then try to get it from my.cnf: + if [ -z "$INNODB_UNDO_DIR" ]; then + INNODB_UNDO_DIR=$(parse_cnf '--mysqld' 'innodb-undo-directory') + fi + + ib_undo_dir="$INNODB_UNDO_DIR" + + if [ -n "$backup_threads" ]; then + impts="--parallel=$backup_threads $impts" + fi + + stagemsg='Joiner-Recv' + + sencrypted=1 + nthreads=1 + + MODULE="xtrabackup_sst" + + [ -f "$DATA/$IST_FILE" ] && rm -f "$DATA/$IST_FILE" + + # May need xtrabackup_checkpoints later on + [ -f "$DATA/xtrabackup_binary" ] && rm -f "$DATA/xtrabackup_binary" + [ -f "$DATA/xtrabackup_galera_info" ] && rm -f "$DATA/xtrabackup_galera_info" + [ -f "$DATA/ib_logfile0" ] && rm -f "$DATA/ib_logfile0" + + ADDR="$WSREP_SST_OPT_ADDR" + + if [ "${tmode#VERIFY}" != "$tmode" ] + then # backward-incompatible behavior + CN="" + if [ -n "$tpem" ] + then + # find out my Common Name + get_openssl + if [ -z "$OPENSSL_BINARY" ]; then + wsrep_log_error 'openssl not found but it is required for authentication' + exit 42 + fi + CN=$("$OPENSSL_BINARY" x509 -noout -subject -in "$tpem" | \ + tr "," "\n" | grep -F 'CN =' | cut -d= -f2 | sed s/^\ // | \ + sed s/\ %//) + fi + MY_SECRET="$(wsrep_gen_secret)" + # Add authentication data to address + ADDR="$CN:$MY_SECRET@$ADDR" + else + MY_SECRET="" # for check down in recv_joiner() + fi + + trap sig_joiner_cleanup HUP PIPE INT TERM + trap cleanup_at_exit EXIT + + if [ -n "$progress" ]; then + adjust_progress + tcmd="$tcmd | $pcmd" + fi + + get_keys + if [ $encrypt -eq 1 -a $sencrypted -eq 1 ]; then + strmcmd="$ecmd | $strmcmd" + fi + + if [ -n "$sdecomp" ]; then + strmcmd="$sdecomp | $strmcmd" + fi + + check_sockets_utils + + STATDIR="$(mktemp -d)" + MAGIC_FILE="$STATDIR/$INFO_FILE" + + recv_joiner "$STATDIR" "$stagemsg-gtid" $stimeout 1 1 + + if ! ps -p "$WSREP_SST_OPT_PARENT" >/dev/null 2>&1 + then + wsrep_log_error "Parent mysqld process (PID: $WSREP_SST_OPT_PARENT) terminated unexpectedly." + exit 32 + fi + + if [ ! -r "$STATDIR/$IST_FILE" ] + then + + if [ -d "$DATA/.sst" ]; then + wsrep_log_info "WARNING: Stale temporary SST directory: '$DATA/.sst' from previous state transfer. Removing" + rm -rf "$DATA/.sst" + fi + mkdir -p "$DATA/.sst" + (recv_joiner "$DATA/.sst" "$stagemsg-SST" 0 0 0) & + jpid=$! + wsrep_log_info "Proceeding with SST" + + wsrep_log_info "Cleaning the existing datadir and innodb-data/log directories" + if [ "$OS" = 'FreeBSD' ]; then + find -E ${ib_home_dir:+"$ib_home_dir"} \ + ${ib_undo_dir:+"$ib_undo_dir"} \ + ${ib_log_dir:+"$ib_log_dir"} \ + "$DATA" -mindepth 1 -prune -regex "$cpat" -o -exec rm -rfv {} 1>&2 \+ + else + find ${ib_home_dir:+"$ib_home_dir"} \ + ${ib_undo_dir:+"$ib_undo_dir"} \ + ${ib_log_dir:+"$ib_log_dir"} \ + "$DATA" -mindepth 1 -prune -regex "$cpat" -o -exec rm -rfv {} 1>&2 \+ + fi + + get_binlog + + if [ -n "$WSREP_SST_OPT_BINLOG" ]; then + binlog_dir=$(dirname "$WSREP_SST_OPT_BINLOG") + cd "$binlog_dir" + wsrep_log_info "Cleaning the binlog directory $binlog_dir as well" + rm -fv "$WSREP_SST_OPT_BINLOG".[0-9]* 1>&2 \+ || true + binlog_index="${WSREP_SST_OPT_BINLOG_INDEX%.index}.index" + [ -f "$binlog_index" ] && rm -fv "$binlog_index" 1>&2 \+ || true + cd "$OLD_PWD" + fi + + TDATA="$DATA" + DATA="$DATA/.sst" + + MAGIC_FILE="$DATA/$INFO_FILE" + wsrep_log_info "Waiting for SST streaming to complete!" + monitor_process $jpid + + if [ ! -s "$DATA/xtrabackup_checkpoints" ]; then + wsrep_log_error "xtrabackup_checkpoints missing, failed mariabackup/SST on donor" + exit 2 + fi + + # Compact backups are not supported by mariabackup + if grep -q -F 'compact = 1' "$DATA/xtrabackup_checkpoints"; then + wsrep_log_info "Index compaction detected" + wsrel_log_error "Compact backups are not supported by mariabackup" + exit 2 + fi + + qpfiles=$(find "$DATA" -maxdepth 1 -type f -name '*.qp' -print -quit) + if [ -n "$qpfiles" ]; then + wsrep_log_info "Compressed qpress files found" + + if [ -z "$(command -v qpress)" ]; then + wsrep_log_error "qpress utility not found in the path" + exit 22 + fi + + get_proc + + dcmd="xargs -n 2 qpress -dT$nproc" + + if [ -n "$progress" ] && pv --help | grep -qw -- '--line-mode'; then + count=$(find "$DATA" -type f -name '*.qp' | wc -l) + count=$(( count*2 )) + pvopts="-f -s $count -l -N Decompression" + if pv --help | grep -qw -- '-F'; then + pvopts="$pvopts -F '%N => Rate:%r Elapsed:%t %e Progress: [%b/$count]'" + fi + pcmd="pv $pvopts" + adjust_progress + dcmd="$pcmd | $dcmd" + fi + + # Decompress the qpress files + wsrep_log_info "Decompression with $nproc threads" + timeit "Joiner-Decompression" "find '$DATA' -type f -name '*.qp' -printf '%p\n%h\n' | $dcmd" + extcode=$? + + if [ $extcode -eq 0 ]; then + wsrep_log_info "Removing qpress files after decompression" + find "$DATA" -type f -name '*.qp' -delete + if [ $? -ne 0 ]; then + wsrep_log_error "Something went wrong with deletion of qpress files. Investigate" + fi + else + wsrep_log_error "Decompression failed. Exit code: $extcode" + exit 22 + fi + fi + + if [ -n "$WSREP_SST_OPT_BINLOG" ]; then + + BINLOG_DIRNAME=$(dirname "$WSREP_SST_OPT_BINLOG") + BINLOG_FILENAME=$(basename "$WSREP_SST_OPT_BINLOG") + + # To avoid comparing data directory and BINLOG_DIRNAME + mv "$DATA/$BINLOG_FILENAME".* "$BINLOG_DIRNAME/" 2>/dev/null || true + + cd "$BINLOG_DIRNAME" + for bfile in $(ls -1 "$BINLOG_FILENAME".[0-9]*); do + echo "$BINLOG_DIRNAME/$bfile" >> "${WSREP_SST_OPT_BINLOG_INDEX%.index}.index" + done + cd "$OLD_PWD" + + fi + + wsrep_log_info "Preparing the backup at $DATA" + setup_commands + timeit "mariabackup prepare stage" "$INNOAPPLY" + + if [ $? -ne 0 ]; then + wsrep_log_error "mariabackup apply finished with errors. Check syslog or '$INNOAPPLYLOG' for details" + exit 22 + fi + + MAGIC_FILE="$TDATA/$INFO_FILE" + + wsrep_log_info "Moving the backup to $TDATA" + timeit "mariabackup move stage" "$INNOMOVE" + if [ $? -eq 0 ]; then + wsrep_log_info "Move successful, removing $DATA" + rm -rf "$DATA" + DATA="$TDATA" + else + wsrep_log_error "Move failed, keeping '$DATA' for further diagnosis" + wsrep_log_error "Check syslog or '$INNOMOVELOG' for details" + exit 22 + fi + + else + + wsrep_log_info "'$IST_FILE' received from donor: Running IST" + + fi + + if [ ! -r "$MAGIC_FILE" ]; then + wsrep_log_error "SST magic file '$MAGIC_FILE' not found/readable" + exit 2 + fi + + coords=$(cat "$MAGIC_FILE") + wsrep_log_info "Galera co-ords from recovery: $coords" + cat "$MAGIC_FILE" # Output : UUID:seqno wsrep_gtid_domain_id + + wsrep_log_info "Total time on joiner: $totime seconds" +fi + +exit 0 diff --git a/scripts/wsrep_sst_mysqldump.sh b/scripts/wsrep_sst_mysqldump.sh new file mode 100644 index 00000000..798bee1a --- /dev/null +++ b/scripts/wsrep_sst_mysqldump.sh @@ -0,0 +1,173 @@ +#!/bin/bash -ue +# Copyright (C) 2009-2015 Codership Oy +# Copyright (C) 2017-2021 MariaDB +# +# 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; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston +# MA 02110-1335 USA. + +# This is a reference script for mysqldump-based state snapshot tansfer + +. $(dirname "$0")/wsrep_sst_common +PATH=$PATH:/usr/sbin:/usr/bin:/sbin:/bin + +EINVAL=22 + +if test -z "$WSREP_SST_OPT_HOST"; then wsrep_log_error "HOST cannot be nil"; exit $EINVAL; fi +if test -z "$WSREP_SST_OPT_PORT"; then wsrep_log_error "PORT cannot be nil"; exit $EINVAL; fi +if test -z "$WSREP_SST_OPT_LPORT"; then wsrep_log_error "LPORT cannot be nil"; exit $EINVAL; fi +if test -z "$WSREP_SST_OPT_SOCKET";then wsrep_log_error "SOCKET cannot be nil";exit $EINVAL; fi +if test -z "$WSREP_SST_OPT_GTID"; then wsrep_log_error "GTID cannot be nil"; exit $EINVAL; fi + +if is_local_ip "$WSREP_SST_OPT_HOST_UNESCAPED" && \ + [ "$WSREP_SST_OPT_PORT" = "$WSREP_SST_OPT_LPORT" ] +then + wsrep_log_error \ + "destination address '$WSREP_SST_OPT_HOST:$WSREP_SST_OPT_PORT' matches source address." + exit $EINVAL +fi + +# Check client version +if ! $MYSQL_CLIENT --version | grep 'Distrib 10\.[1-9]' >/dev/null +then + $MYSQL_CLIENT --version >&2 + wsrep_log_error "this operation requires MySQL client version 10.1 or newer" + exit $EINVAL +fi + +AUTH="" +usrst=0 +if [ -n "$WSREP_SST_OPT_USER" ]; then + AUTH="-u$WSREP_SST_OPT_USER" + usrst=1 +fi + +# Refs https://github.com/codership/mysql-wsrep/issues/141 +# Passing password in MYSQL_PWD environment variable is considered +# "extremely insecure" by MySQL Guidelines for Password Security +# (https://dev.mysql.com/doc/refman/5.6/en/password-security-user.html) +# that is even less secure than passing it on a command line! It is doubtful: +# the whole command line is easily observable by any unprivileged user via ps, +# whereas (at least on Linux) unprivileged user can't see process environment +# that he does not own. So while it may be not secure in the NSA sense of the +# word, it is arguably more secure than passing password on the command line. +if [ -n "$WSREP_SST_OPT_PSWD" ]; then + export MYSQL_PWD="$WSREP_SST_OPT_PSWD" +elif [ $usrst -eq 1 ]; then + # Empty password, used for testing, debugging etc. + unset MYSQL_PWD +fi + +STOP_WSREP='SET wsrep_on=OFF;' + +# mysqldump cannot restore CSV tables, fix this issue +CSV_TABLES_FIX=" +set sql_mode=''; + +USE mysql; + +SET @cond = (SELECT (SUPPORT = 'YES' or SUPPORT = 'DEFAULT') FROM INFORMATION_SCHEMA.ENGINES WHERE ENGINE = 'csv'); + +SET @stmt = IF (@cond = '1', 'CREATE TABLE IF NOT EXISTS general_log ( event_time timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), user_host mediumtext NOT NULL, thread_id bigint(21) unsigned NOT NULL, server_id int(10) unsigned NOT NULL, command_type varchar(64) NOT NULL, argument mediumtext NOT NULL) ENGINE=CSV DEFAULT CHARSET=utf8mb3 COMMENT=\"General log\"', 'SET @dummy = 0'); + +PREPARE stmt FROM @stmt; +EXECUTE stmt; +DROP PREPARE stmt; + +SET @stmt = IF (@cond = '1', 'CREATE TABLE IF NOT EXISTS slow_log ( start_time timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6), user_host mediumtext NOT NULL, query_time time(6) NOT NULL, lock_time time(6) NOT NULL, rows_sent int(11) NOT NULL, rows_examined int(11) NOT NULL, db varchar(512) NOT NULL, last_insert_id int(11) NOT NULL, insert_id int(11) NOT NULL, server_id int(10) unsigned NOT NULL, sql_text mediumtext NOT NULL, thread_id bigint(21) unsigned NOT NULL) ENGINE=CSV DEFAULT CHARSET=utf8mb3 COMMENT=\"Slow log\"', 'SET @dummy = 0'); + +PREPARE stmt FROM @stmt; +EXECUTE stmt; +DROP PREPARE stmt;" + +SET_START_POSITION="SET GLOBAL wsrep_start_position='$WSREP_SST_OPT_GTID';" + +SET_WSREP_GTID_DOMAIN_ID="" +if [ -n $WSREP_SST_OPT_GTID_DOMAIN_ID ] +then + SET_WSREP_GTID_DOMAIN_ID=" + SET @val = (SELECT GLOBAL_VALUE FROM INFORMATION_SCHEMA.SYSTEM_VARIABLES WHERE VARIABLE_NAME = 'WSREP_GTID_STRICT_MODE' AND GLOBAL_VALUE > 0); + SET @stmt = IF (@val IS NOT NULL, 'SET GLOBAL WSREP_GTID_DOMAIN_ID=$WSREP_SST_OPT_GTID_DOMAIN_ID', 'SET @dummy = 0'); + PREPARE stmt FROM @stmt; + EXECUTE stmt; + DROP PREPARE stmt;" +fi + +MYSQL="$MYSQL_CLIENT $WSREP_SST_OPT_CONF_UNQUOTED "\ +"$AUTH -h$WSREP_SST_OPT_HOST_UNESCAPED "\ +"-P$WSREP_SST_OPT_PORT --disable-reconnect --connect_timeout=10" + +# Check if binary logging is enabled on the joiner node. +# Note: SELECT cannot be used at this point. +LOG_BIN=$(echo "set statement wsrep_sync_wait=0 for SHOW VARIABLES LIKE 'log_bin'" | $MYSQL | \ +tail -1 | awk -F ' ' '{ print $2 }') + +# Check the joiner node's server version. +SERVER_VERSION=$(echo "set statement wsrep_sync_wait=0 for SHOW VARIABLES LIKE 'version'" | $MYSQL | \ +tail -1 | awk -F ' ' '{ print $2 }') + +# Retrieve the donor's @@global.gtid_binlog_state. +GTID_BINLOG_STATE=$(echo "SHOW GLOBAL VARIABLES LIKE 'gtid_binlog_state'" | $MYSQL | \ +tail -1 | awk -F ' ' '{ print $2 }') + +RESET_MASTER="" +SET_GTID_BINLOG_STATE="" +SQL_LOG_BIN_OFF="" + +# Safety check +if [ ${SERVER_VERSION%%.*} -gt 5 ] +then + # If binary logging is enabled on the joiner node, we need to copy donor's + # gtid_binlog_state to joiner. In order to do that, a RESET MASTER must be + # executed to erase binary logs (if any). Binary logging should also be + # turned off for the session so that gtid state does not get altered while + # the dump gets replayed on joiner. + if [ "$LOG_BIN" = 'ON' ]; then + RESET_MASTER="SET GLOBAL wsrep_on=OFF; RESET MASTER; SET GLOBAL wsrep_on=ON;" + SET_GTID_BINLOG_STATE="SET GLOBAL wsrep_on=OFF; SET @@global.gtid_binlog_state='$GTID_BINLOG_STATE'; SET GLOBAL wsrep_on=ON;" + SQL_LOG_BIN_OFF="SET @@session.sql_log_bin=OFF;" + fi +fi + +# NOTE: we don't use --routines here because we're dumping mysql.proc table +MYSQLDUMP="$MYSQLDUMP $WSREP_SST_OPT_CONF_UNQUOTED $AUTH -S$WSREP_SST_OPT_SOCKET \ +--add-drop-database --add-drop-table --skip-add-locks --create-options \ +--disable-keys --extended-insert --skip-lock-tables --quick --set-charset \ +--skip-comments --flush-privileges --all-databases --events" + +if [ $WSREP_SST_OPT_BYPASS -eq 0 ] +then + # need to disable logging when loading the dump + # reason is that dump contains ALTER TABLE for log tables, and + # this causes an error if logging is enabled + GENERAL_LOG_OPT=$($MYSQL --skip-column-names -e "$STOP_WSREP SELECT @@GENERAL_LOG") + SLOW_LOG_OPT=$($MYSQL --skip-column-names -e "$STOP_WSREP SELECT @@SLOW_QUERY_LOG") + + LOG_OFF="SET GLOBAL GENERAL_LOG=OFF; SET GLOBAL SLOW_QUERY_LOG=OFF;" + + # commands to restore log settings + RESTORE_GENERAL_LOG="SET GLOBAL GENERAL_LOG=$GENERAL_LOG_OPT;" + RESTORE_SLOW_QUERY_LOG="SET GLOBAL SLOW_QUERY_LOG=$SLOW_LOG_OPT;" + + (echo "$STOP_WSREP" && echo "$LOG_OFF" && echo "$RESET_MASTER" && \ + echo "$SET_GTID_BINLOG_STATE" && echo "$SQL_LOG_BIN_OFF" && \ + echo "$STOP_WSREP" && $MYSQLDUMP && echo "$CSV_TABLES_FIX" && \ + echo "$RESTORE_GENERAL_LOG" && echo "$RESTORE_SLOW_QUERY_LOG" && \ + echo "$SET_START_POSITION" && echo "$SET_WSREP_GTID_DOMAIN_ID" \ + || echo "SST failed to complete;") | $MYSQL +else + wsrep_log_info "Bypassing state dump." + echo "$SET_START_POSITION" | $MYSQL +fi + +# diff --git a/scripts/wsrep_sst_rsync.sh b/scripts/wsrep_sst_rsync.sh new file mode 100644 index 00000000..fc9f5017 --- /dev/null +++ b/scripts/wsrep_sst_rsync.sh @@ -0,0 +1,771 @@ +#!/bin/bash -ue + +# Copyright (C) 2017-2021 MariaDB +# Copyright (C) 2010-2014 Codership Oy +# +# 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; see the file COPYING. If not, write to the +# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston +# MA 02110-1335 USA. + +# This is a reference script for rsync-based state snapshot tansfer + +RSYNC_REAL_PID=0 # rsync process id +STUNNEL_REAL_PID=0 # stunnel process id + +OS="$(uname)" +[ "$OS" = 'Darwin' ] && export -n LD_LIBRARY_PATH + +# Setting the path for lsof on CentOS +export PATH="/usr/sbin:/sbin:$PATH" + +. $(dirname "$0")/wsrep_sst_common +wsrep_check_datadir + +wsrep_check_programs rsync + +cleanup_joiner() +{ + local failure=0 + + wsrep_log_info "Joiner cleanup: rsync PID=$RSYNC_REAL_PID, stunnel PID=$STUNNEL_REAL_PID" + + if [ -n "$STUNNEL" ]; then + if cleanup_pid $STUNNEL_REAL_PID "$STUNNEL_PID" "$STUNNEL_CONF"; then + if [ $RSYNC_REAL_PID -eq 0 ]; then + if [ -r "$RSYNC_PID" ]; then + RSYNC_REAL_PID=$(cat "$RSYNC_PID" 2>/dev/null) + if [ -z "$RSYNC_REAL_PID" ]; then + RSYNC_REAL_PID=0 + fi + fi + fi + else + wsrep_log_warning "stunnel cleanup failed." + failure=1 + fi + fi + + if [ $failure -eq 0 ]; then + if cleanup_pid $RSYNC_REAL_PID "$RSYNC_PID" "$RSYNC_CONF"; then + [ -f "$MAGIC_FILE" ] && rm -f "$MAGIC_FILE" + else + wsrep_log_warning "rsync cleanup failed." + fi + fi + + wsrep_log_info "Joiner cleanup done." + + if [ "$WSREP_SST_OPT_ROLE" = 'joiner' ]; then + wsrep_cleanup_progress_file + fi + + [ -f "$SST_PID" ] && rm -f "$SST_PID" +} + +check_pid_and_port() +{ + local pid_file="$1" + local pid=$2 + local addr="$3" + local port="$4" + + local utils='rsync|stunnel' + + if ! check_port "$pid" "$port" "$utils"; then + local port_info + local busy=0 + + if [ $lsof_available -ne 0 ]; then + port_info=$(lsof -Pnl -i ":$port" 2>/dev/null | \ + grep -F '(LISTEN)') + echo "$port_info" | \ + grep -q -E "[[:space:]](\\*|\\[?::\\]?):$port[[:space:]]" && busy=1 + else + local filter='([^[:space:]]+[[:space:]]+){4}[^[:space:]]+' + if [ $sockstat_available -eq 1 ]; then + port_info=$(sockstat -p "$port" 2>/dev/null | \ + grep -E '[[:space:]]LISTEN' | grep -o -E "$filter") + else + port_info=$(ss -nlpH "( sport = :$port )" 2>/dev/null | \ + grep -F 'users:(' | grep -o -E "$filter") + fi + echo "$port_info" | \ + grep -q -E "[[:space:]](\\*|\\[?::\\]?):$port\$" && busy=1 + fi + + if [ $busy -eq 0 ]; then + if echo "$port_info" | grep -qw -F "[$addr]:$port" || \ + echo "$port_info" | grep -qw -F -- "$addr:$port" + then + busy=1 + fi + fi + + if [ $busy -eq 0 ]; then + return 1 + fi + + if ! check_port "$pid" "$port" "$utils"; then + wsrep_log_error "rsync or stunnel daemon port '$port' " \ + "has been taken by another program" + exit 16 # EBUSY + fi + fi + + check_pid "$pid_file" && [ $CHECK_PID -eq $pid ] +} + +STUNNEL_CONF="$WSREP_SST_OPT_DATA/stunnel.conf" +STUNNEL_PID="$WSREP_SST_OPT_DATA/stunnel.pid" + +MAGIC_FILE="$WSREP_SST_OPT_DATA/rsync_sst_complete" + +BINLOG_TAR_FILE="$WSREP_SST_OPT_DATA/wsrep_sst_binlog.tar" +BINLOG_N_FILES=1 + +get_binlog + +if [ -n "$WSREP_SST_OPT_BINLOG" ]; then + BINLOG_DIRNAME=$(dirname "$WSREP_SST_OPT_BINLOG") + BINLOG_FILENAME=$(basename "$WSREP_SST_OPT_BINLOG") +fi + +# if no command line argument and INNODB_LOG_GROUP_HOME is not set, +# try to get it from my.cnf: +if [ -z "$INNODB_LOG_GROUP_HOME" ]; then + INNODB_LOG_GROUP_HOME=$(parse_cnf '--mysqld' 'innodb-log-group-home-dir') +fi + +OLD_PWD="$(pwd)" + +WSREP_LOG_DIR="$INNODB_LOG_GROUP_HOME" + +cd "$WSREP_SST_OPT_DATA" +if [ -n "$WSREP_LOG_DIR" ]; then + # handle both relative and absolute paths + [ ! -d "$WSREP_LOG_DIR" ] && mkdir -p "$WSREP_LOG_DIR" + cd "$WSREP_LOG_DIR" +fi +WSREP_LOG_DIR=$(pwd -P) + +cd "$OLD_PWD" + +# if no command line argument and INNODB_DATA_HOME_DIR environment variable +# is not set, try to get it from my.cnf: +if [ -z "$INNODB_DATA_HOME_DIR" ]; then + INNODB_DATA_HOME_DIR=$(parse_cnf '--mysqld' 'innodb-data-home-dir') +fi + +cd "$WSREP_SST_OPT_DATA" +if [ -n "$INNODB_DATA_HOME_DIR" ]; then + # handle both relative and absolute paths + [ ! -d "$INNODB_DATA_HOME_DIR" ] && mkdir -p "$INNODB_DATA_HOME_DIR" + cd "$INNODB_DATA_HOME_DIR" +fi +INNODB_DATA_HOME_DIR=$(pwd -P) + +cd "$OLD_PWD" + +# if no command line argument then try to get it from my.cnf: +if [ -z "$INNODB_UNDO_DIR" ]; then + INNODB_UNDO_DIR=$(parse_cnf '--mysqld' 'innodb-undo-directory') +fi + +cd "$WSREP_SST_OPT_DATA" +if [ -n "$INNODB_UNDO_DIR" ]; then + # handle both relative and absolute paths + [ ! -d "$INNODB_UNDO_DIR" ] && mkdir -p "$INNODB_UNDO_DIR" + cd "$INNODB_UNDO_DIR" +fi +INNODB_UNDO_DIR=$(pwd -P) + +cd "$OLD_PWD" + +# Old filter - include everything except selected +# FILTER=(--exclude '*.err' --exclude '*.pid' --exclude '*.sock' \ +# --exclude '*.conf' --exclude core --exclude 'galera.*' \ +# --exclude grastate.txt --exclude '*.pem' \ +# --exclude '*.[0-9][0-9][0-9][0-9][0-9][0-9]' --exclude '*.index') + +# New filter - exclude everything except dirs (schemas) and innodb files +FILTER="-f '- /lost+found' + -f '- /.zfs' + -f '- /.fseventsd' + -f '- /.Trashes' + -f '- /.pid' + -f '- /.conf' + -f '+ /wsrep_sst_binlog.tar' + -f '- $INNODB_DATA_HOME_DIR/ib_lru_dump' + -f '- $INNODB_DATA_HOME_DIR/ibdata*' + -f '+ $INNODB_UNDO_DIR/undo*' + -f '+ /*/' + -f '- /*'" + +# old-style SSL config +SSTKEY=$(parse_cnf 'sst' 'tkey') +SSTCERT=$(parse_cnf 'sst' 'tcert') +SSTCA=$(parse_cnf 'sst' 'tca') + +SST_SECTIONS="--mysqld|sst" + +check_server_ssl_config() +{ + SSTKEY=$(parse_cnf "$SST_SECTIONS" 'ssl-key') + SSTCERT=$(parse_cnf "$SST_SECTIONS" 'ssl-cert') + SSTCA=$(parse_cnf "$SST_SECTIONS" 'ssl-ca') +} + +SSLMODE=$(parse_cnf "$SST_SECTIONS" 'ssl-mode' | tr [:lower:] [:upper:]) + +# no old-style SSL config in [sst], check for new one: +if [ -z "$SSTKEY" -a -z "$SSTCERT" -a -z "$SSTCA" ] +then + check_server_ssl_config +fi + +if [ -z "$SSLMODE" ]; then + # Implicit verification if CA is set and the SSL mode + # is not specified by user: + if [ -n "$SSTCA" ]; then + if [ -n "$(command -v stunnel)" ]; then + SSLMODE='VERIFY_CA' + fi + # Require SSL by default if SSL key and cert are present: + elif [ -n "$SSTKEY" -a -n "$SSTCERT" ]; then + SSLMODE='REQUIRED' + fi +fi + +if [ -n "$SSTCA" ] +then + CAFILE_OPT="CAfile = $SSTCA" +else + CAFILE_OPT="" +fi + +VERIFY_OPT="" +CHECK_OPT="" +CHECK_OPT_LOCAL="" +if [ "${SSLMODE#VERIFY}" != "$SSLMODE" ] +then + case "$SSLMODE" in + 'VERIFY_IDENTITY') + VERIFY_OPT='verifyPeer = yes' + ;; + 'VERIFY_CA') + VERIFY_OPT='verifyChain = yes' + if [ -n "$WSREP_SST_OPT_REMOTE_USER" ]; then + CHECK_OPT="checkHost = $WSREP_SST_OPT_REMOTE_USER" + else + # check if the address is an ip-address (v4 or v6): + if echo "$WSREP_SST_OPT_HOST_UNESCAPED" | \ + grep -q -E '^([0-9]+(\.[0-9]+){3}|[0-9a-fA-F]*(\:[0-9a-fA-F]*)+)$' + then + CHECK_OPT="checkIP = $WSREP_SST_OPT_HOST_UNESCAPED" + else + CHECK_OPT="checkHost = $WSREP_SST_OPT_HOST" + fi + if is_local_ip "$WSREP_SST_OPT_HOST_UNESCAPED"; then + CHECK_OPT_LOCAL="checkHost = localhost" + fi + fi + ;; + *) + wsrep_log_error "Unrecognized ssl-mode option: '$SSLMODE'" + exit 22 # EINVAL + ;; + esac + if [ -z "$CAFILE_OPT" ]; then + wsrep_log_error "Can't have ssl-mode='$SSLMODE' without CA file" + exit 22 # EINVAL + fi +fi + +STUNNEL="" +if [ -n "$SSLMODE" -a "$SSLMODE" != 'DISABLED' ]; then + STUNNEL_BIN="$(command -v stunnel)" + if [ -n "$STUNNEL_BIN" ]; then + wsrep_log_info "Using stunnel for SSL encryption: CAfile: '$SSTCA', ssl-mode='$SSLMODE'" + STUNNEL="$STUNNEL_BIN $STUNNEL_CONF" + fi +fi + +readonly SECRET_TAG="secret" + +if [ "$WSREP_SST_OPT_ROLE" = 'donor' ] +then + + [ -f "$MAGIC_FILE" ] && rm -f "$MAGIC_FILE" + [ -f "$BINLOG_TAR_FILE" ] && rm -f "$BINLOG_TAR_FILE" + [ -f "$STUNNEL_PID" ] && rm -f "$STUNNEL_PID" + + if [ -n "$STUNNEL" ] + then + cat << EOF > "$STUNNEL_CONF" +key = $SSTKEY +cert = $SSTCERT +${CAFILE_OPT} +foreground = yes +pid = $STUNNEL_PID +debug = warning +client = yes +connect = $WSREP_SST_OPT_HOST_UNESCAPED:$WSREP_SST_OPT_PORT +TIMEOUTclose = 0 +${VERIFY_OPT} +${CHECK_OPT} +${CHECK_OPT_LOCAL} +EOF + else + [ -f "$STUNNEL_CONF" ] && rm -f "$STUNNEL_CONF" + fi + + if [ $WSREP_SST_OPT_BYPASS -eq 0 ] + then + + FLUSHED="$WSREP_SST_OPT_DATA/tables_flushed" + ERROR="$WSREP_SST_OPT_DATA/sst_error" + + [ -f "$FLUSHED" ] && rm -f "$FLUSHED" + [ -f "$ERROR" ] && rm -f "$ERROR" + + echo "flush tables" + + # Wait for : + # (a) Tables to be flushed, AND + # (b) Cluster state ID & wsrep_gtid_domain_id to be written to the file, OR + # (c) ERROR file, in case flush tables operation failed. + + while [ ! -r "$FLUSHED" ] && ! grep -q -F ':' "$FLUSHED" >/dev/null 2>&1 + do + # Check whether ERROR file exists. + if [ -f "$ERROR" ] + then + # Flush tables operation failed. + rm -f "$ERROR" + exit 255 + fi + sleep 0.2 + done + + STATE=$(cat "$FLUSHED") + rm -f "$FLUSHED" + + sync + + if [ -n "$WSREP_SST_OPT_BINLOG" ] + then + # Prepare binlog files + cd "$BINLOG_DIRNAME" + + binlog_files_full=$(tail -n $BINLOG_N_FILES "${WSREP_SST_OPT_BINLOG_INDEX%.index}.index") + + binlog_files="" + for ii in $binlog_files_full + do + binlog_file=$(basename "$ii") + binlog_files="$binlog_files $binlog_file" + done + + if [ -n "$binlog_files" ] + then + wsrep_log_info "Preparing binlog files for transfer:" + tar -cvf "$BINLOG_TAR_FILE" $binlog_files >&2 + fi + + cd "$OLD_PWD" + fi + + # Use deltaxfer only for WAN + inv=$(basename "$0") + WHOLE_FILE_OPT="" + if [ "${inv%wsrep_sst_rsync_wan*}" != "$inv" ]; then + WHOLE_FILE_OPT="--whole-file" + fi + + # first, the normal directories, so that we can detect incompatible protocol + RC=0 + eval rsync ${STUNNEL:+"'--rsh=$STUNNEL'"} \ + --owner --group --perms --links --specials \ + --ignore-times --inplace --dirs --delete --quiet \ + $WHOLE_FILE_OPT $FILTER "'$WSREP_SST_OPT_DATA/'" \ + "'rsync://$WSREP_SST_OPT_ADDR'" >&2 || RC=$? + + if [ $RC -ne 0 ]; then + wsrep_log_error "rsync returned code $RC:" + case $RC in + 12) RC=71 # EPROTO + wsrep_log_error \ + "rsync server on the other end has incompatible protocol. " \ + "Make sure you have the same version of rsync on all nodes." + ;; + 22) RC=12 # ENOMEM + ;; + *) RC=255 # unknown error + ;; + esac + exit $RC + fi + + # Transfer InnoDB data files + rsync ${STUNNEL:+--rsh="$STUNNEL"} \ + --owner --group --perms --links --specials \ + --ignore-times --inplace --dirs --delete --quiet \ + $WHOLE_FILE_OPT -f '+ /ibdata*' -f '+ /ib_lru_dump' \ + -f '- **' "$INNODB_DATA_HOME_DIR/" \ + "rsync://$WSREP_SST_OPT_ADDR-data_dir" >&2 || RC=$? + + if [ $RC -ne 0 ]; then + wsrep_log_error "rsync innodb_data_home_dir returned code $RC:" + exit 255 # unknown error + fi + + # second, we transfer InnoDB and Aria log files + rsync ${STUNNEL:+--rsh="$STUNNEL"} \ + --owner --group --perms --links --specials \ + --ignore-times --inplace --dirs --delete --quiet \ + $WHOLE_FILE_OPT -f '+ /ib_logfile[0-9]*' -f '+ /aria_log.*' \ + -f '+ /aria_log_control' -f '- **' "$WSREP_LOG_DIR/" \ + "rsync://$WSREP_SST_OPT_ADDR-log_dir" >&2 || RC=$? + + if [ $RC -ne 0 ]; then + wsrep_log_error "rsync innodb_log_group_home_dir returned code $RC:" + exit 255 # unknown error + fi + + # then, we parallelize the transfer of database directories, + # use '.' so that path concatenation works: + + cd "$WSREP_SST_OPT_DATA" + + backup_threads=$(parse_cnf "--mysqld|sst" 'backup-threads') + if [ -z "$backup_threads" ]; then + get_proc + backup_threads=$nproc + fi + + find . -maxdepth 1 -mindepth 1 -type d -not -name 'lost+found' \ + -not -name '.zfs' -print0 | xargs -I{} -0 -P $backup_threads \ + rsync ${STUNNEL:+--rsh="$STUNNEL"} \ + --owner --group --perms --links --specials \ + --ignore-times --inplace --recursive --delete --quiet \ + $WHOLE_FILE_OPT --exclude '*/ib_logfile*' --exclude '*/aria_log.*' \ + --exclude '*/aria_log_control' "$WSREP_SST_OPT_DATA/{}/" \ + "rsync://$WSREP_SST_OPT_ADDR/{}" >&2 || RC=$? + + cd "$OLD_PWD" + + if [ $RC -ne 0 ]; then + wsrep_log_error "find/rsync returned code $RC:" + exit 255 # unknown error + fi + + else # BYPASS + + wsrep_log_info "Bypassing state dump." + + # Store donor's wsrep GTID (state ID) and wsrep_gtid_domain_id + # (separated by a space). + STATE="$WSREP_SST_OPT_GTID $WSREP_SST_OPT_GTID_DOMAIN_ID" + + fi + + echo 'continue' # now server can resume updating data + + echo "$STATE" > "$MAGIC_FILE" + + if [ -n "$WSREP_SST_OPT_REMOTE_PSWD" ]; then + # Let joiner know that we know its secret + echo "$SECRET_TAG $WSREP_SST_OPT_REMOTE_PSWD" >> "$MAGIC_FILE" + fi + + rsync ${STUNNEL:+--rsh="$STUNNEL"} \ + --archive --quiet --checksum "$MAGIC_FILE" "rsync://$WSREP_SST_OPT_ADDR" + + echo "done $STATE" + + if [ -n "$STUNNEL" ]; then + [ -f "$STUNNEL_CONF" ] && rm -f "$STUNNEL_CONF" + [ -f "$STUNNEL_PID" ] && rm -f "$STUNNEL_PID" + fi + +elif [ "$WSREP_SST_OPT_ROLE" = 'joiner' ] +then + check_sockets_utils + + SST_PID="$WSREP_SST_OPT_DATA/wsrep_rsync_sst.pid" + + # give some time for previous SST to complete: + check_round=0 + while check_pid "$SST_PID" 0 + do + wsrep_log_info "previous SST is not completed, waiting for it to exit" + check_round=$(( check_round + 1 )) + if [ $check_round -eq 10 ]; then + wsrep_log_error "previous SST script still running." + exit 114 # EALREADY + fi + sleep 1 + done + + # give some time for stunnel from the previous SST to complete: + check_round=0 + while check_pid "$STUNNEL_PID" 1 + do + wsrep_log_info "lingering stunnel daemon found at startup, waiting for it to exit" + check_round=$(( check_round + 1 )) + if [ $check_round -eq 10 ]; then + wsrep_log_error "stunnel daemon already running." + exit 114 # EALREADY + fi + sleep 1 + done + + MODULE="rsync_sst" + RSYNC_PID="$WSREP_SST_OPT_DATA/$MODULE.pid" + RSYNC_CONF="$WSREP_SST_OPT_DATA/$MODULE.conf" + + # give some time for rsync from the previous SST to complete: + check_round=0 + while check_pid "$RSYNC_PID" 1 + do + wsrep_log_info "lingering rsync daemon found at startup, waiting for it to exit" + check_round=$(( check_round + 1 )) + if [ $check_round -eq 10 ]; then + wsrep_log_error "rsync daemon already running." + exit 114 # EALREADY + fi + sleep 1 + done + + [ -f "$MAGIC_FILE" ] && rm -f "$MAGIC_FILE" + [ -f "$BINLOG_TAR_FILE" ] && rm -f "$BINLOG_TAR_FILE" + + if [ -z "$STUNNEL" ]; then + [ -f "$STUNNEL_CONF" ] && rm -f "$STUNNEL_CONF" + fi + + ADDR="$WSREP_SST_OPT_ADDR" + RSYNC_PORT="$WSREP_SST_OPT_PORT" + RSYNC_ADDR="$WSREP_SST_OPT_HOST" + RSYNC_ADDR_UNESCAPED="$WSREP_SST_OPT_HOST_UNESCAPED" + + trap "exit 32" HUP PIPE + trap "exit 3" INT TERM ABRT + trap cleanup_joiner EXIT + + touch "$SST_PROGRESS_FILE" + + if [ -n "${MYSQL_TMP_DIR:-}" ]; then + SILENT="log file = $MYSQL_TMP_DIR/rsyncd.log" + else + SILENT="" + fi + +cat << EOF > "$RSYNC_CONF" +pid file = $RSYNC_PID +use chroot = no +read only = no +timeout = 300 +$SILENT +[$MODULE] + path = $WSREP_SST_OPT_DATA + exclude = .zfs +[$MODULE-log_dir] + path = $WSREP_LOG_DIR +[$MODULE-data_dir] + path = $INNODB_DATA_HOME_DIR +EOF + +# rm -rf "$DATA/ib_logfile"* # we don't want old logs around + + # If the IP is local, listen only on it: + if is_local_ip "$RSYNC_ADDR_UNESCAPED" + then + RSYNC_EXTRA_ARGS="--address $RSYNC_ADDR_UNESCAPED" + STUNNEL_ACCEPT="$RSYNC_ADDR_UNESCAPED:$RSYNC_PORT" + else + # Not local, possibly a NAT, listen on all interfaces: + RSYNC_EXTRA_ARGS="" + STUNNEL_ACCEPT="$RSYNC_PORT" + # Overwrite address with all: + RSYNC_ADDR="*" + fi + + echo $$ > "$SST_PID" + + if [ -z "$STUNNEL" ] + then + rsync --daemon --no-detach --port "$RSYNC_PORT" --config "$RSYNC_CONF" $RSYNC_EXTRA_ARGS & + RSYNC_REAL_PID=$! + TRANSFER_REAL_PID=$RSYNC_REAL_PID + TRANSFER_PID="$RSYNC_PID" + else + # Let's check if the path to the config file contains a space? + if [ "${RSYNC_CONF#* }" = "$RSYNC_CONF" ]; then + cat << EOF > "$STUNNEL_CONF" +key = $SSTKEY +cert = $SSTCERT +${CAFILE_OPT} +foreground = yes +pid = $STUNNEL_PID +debug = warning +client = no +${VERIFY_OPT} +${CHECK_OPT} +${CHECK_OPT_LOCAL} +[rsync] +accept = $STUNNEL_ACCEPT +exec = $(command -v rsync) +execargs = rsync --server --daemon --config=$RSYNC_CONF . +EOF + else + # The path contains a space, so we will run it via + # shell with "eval" command: + export RSYNC_CMD="eval $(command -v rsync) --server --daemon --config='$RSYNC_CONF' ." + cat << EOF > "$STUNNEL_CONF" +key = $SSTKEY +cert = $SSTCERT +${CAFILE_OPT} +foreground = yes +pid = $STUNNEL_PID +debug = warning +client = no +${VERIFY_OPT} +${CHECK_OPT} +${CHECK_OPT_LOCAL} +[rsync] +accept = $STUNNEL_ACCEPT +exec = $SHELL +execargs = $SHELL -c \$RSYNC_CMD +EOF + fi + stunnel "$STUNNEL_CONF" & + STUNNEL_REAL_PID=$! + TRANSFER_REAL_PID=$STUNNEL_REAL_PID + TRANSFER_PID="$STUNNEL_PID" + fi + + if [ "${SSLMODE#VERIFY}" != "$SSLMODE" ] + then # backward-incompatible behavior + CN="" + if [ -n "$SSTCERT" ] + then + # find out my Common Name + get_openssl + if [ -z "$OPENSSL_BINARY" ]; then + wsrep_log_error 'openssl not found but it is required for authentication' + exit 42 + fi + CN=$("$OPENSSL_BINARY" x509 -noout -subject -in "$SSTCERT" | \ + tr "," "\n" | grep -F 'CN =' | cut -d= -f2 | sed s/^\ // | \ + sed s/\ %//) + fi + MY_SECRET="$(wsrep_gen_secret)" + # Add authentication data to address + ADDR="$CN:$MY_SECRET@$WSREP_SST_OPT_HOST" + else + MY_SECRET="" # for check down in recv_joiner() + ADDR="$WSREP_SST_OPT_HOST" + fi + + until check_pid_and_port "$TRANSFER_PID" $TRANSFER_REAL_PID "$RSYNC_ADDR_UNESCAPED" "$RSYNC_PORT" + do + sleep 0.2 + done + + echo "ready $ADDR:$RSYNC_PORT/$MODULE" + + MYSQLD_PID="$WSREP_SST_OPT_PARENT" + + # wait for SST to complete by monitoring magic file + while [ ! -r "$MAGIC_FILE" ] && check_pid "$TRANSFER_PID" && \ + ps -p $MYSQLD_PID >/dev/null 2>&1 + do + sleep 1 + done + + if ! ps -p $MYSQLD_PID >/dev/null 2>&1 + then + wsrep_log_error \ + "Parent mysqld process (PID: $MYSQLD_PID) terminated unexpectedly." + kill -- -$MYSQLD_PID + sleep 1 + exit 32 + fi + + if [ -n "$WSREP_SST_OPT_BINLOG" ]; then + if [ -f "$BINLOG_TAR_FILE" ]; then + cd "$BINLOG_DIRNAME" + + binlog_index="${WSREP_SST_OPT_BINLOG_INDEX%.index}.index" + + # Clean up old binlog files first + rm -f "$BINLOG_FILENAME".[0-9]* + [ -f "$binlog_index" ] && rm -f "$binlog_index" + + # Create a temporary file: + tmpdir=$(parse_cnf '--mysqld|sst' 'tmpdir') + if [ -z "$tmpdir" ]; then + tmpfile="$(mktemp)" + else + tmpfile=$(mktemp "--tmpdir=$tmpdir") + fi + + wsrep_log_info "Extracting binlog files:" + if ! tar -xvf "$BINLOG_TAR_FILE" > "$tmpfile"; then + wsrep_log_error "Error unpacking tar file with binlog files" + rm -f "$tmpfile" + exit 32 + fi + + # Rebuild binlog index: + while read bin_file; do + echo "$BINLOG_DIRNAME/$bin_file" >> "$binlog_index" + done < "$tmpfile" + rm -f "$tmpfile" + + cd "$OLD_PWD" + fi + fi + + if [ -r "$MAGIC_FILE" ]; then + if [ -n "$MY_SECRET" ]; then + # check donor supplied secret + SECRET=$(grep -F -- "$SECRET_TAG " "$MAGIC_FILE" 2>/dev/null | cut -d ' ' -f 2) + if [ "$SECRET" != "$MY_SECRET" ]; then + wsrep_log_error "Donor does not know my secret!" + wsrep_log_info "Donor:'$SECRET', my:'$MY_SECRET'" + exit 32 + fi + # remove secret from the magic file, and output + # the UUID:seqno & wsrep_gtid_domain_id: + grep -v -F -- "$SECRET_TAG " "$MAGIC_FILE" + else + # Output the UUID:seqno and wsrep_gtid_domain_id: + cat "$MAGIC_FILE" + fi + else + # this message should cause joiner to abort + echo "rsync process ended without creating '$MAGIC_FILE'" + fi + +# wsrep_cleanup_progress_file +# cleanup_joiner +else + wsrep_log_error "Unrecognized role: '$WSREP_SST_OPT_ROLE'" + exit 22 # EINVAL +fi + +[ -f "$BINLOG_TAR_FILE" ] && rm -f "$BINLOG_TAR_FILE" + +exit 0 |