From 48f40550f462e1a258682a5cc85f22ac8955f095 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 20 Jul 2001 19:01:23 +0300 Subject: [PATCH 01/51] dict0dict.ic Remove acquisition of the dictionary mutex: this may fix the hang observed by Peter Zaitsev os0file.c Use O_SYNC instead of O_DSYNC because in Linux there may be a bug innobase/os/os0file.c: Use O_SYNC instead of O_DSYNC because in Linux there may be a bug innobase/include/dict0dict.ic: Remove acquisition of the dictionary mutex: this may fix the hang observed by Peter Zaitsev --- innobase/include/dict0dict.ic | 4 ---- innobase/os/os0file.c | 7 +++++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/innobase/include/dict0dict.ic b/innobase/include/dict0dict.ic index 549a5763b44..9089ebe8edd 100644 --- a/innobase/include/dict0dict.ic +++ b/innobase/include/dict0dict.ic @@ -651,8 +651,6 @@ dict_table_get_index( char* name) /* in: index name */ { dict_index_t* index = NULL; - - mutex_enter(&(dict_sys->mutex)); index = dict_table_get_first_index(table); @@ -665,8 +663,6 @@ dict_table_get_index( index = dict_table_get_next_index(index); } - mutex_exit(&(dict_sys->mutex)); - return(index); } diff --git a/innobase/os/os0file.c b/innobase/os/os0file.c index 668d74d75b5..d3c6232031a 100644 --- a/innobase/os/os0file.c +++ b/innobase/os/os0file.c @@ -347,9 +347,12 @@ try_again: UT_NOT_USED(purpose); -#ifdef O_DSYNC + /* Currently use only O_SYNC because there may be a bug in + Linux O_DSYNC! */ + +#ifdef O_SYNC if (srv_unix_file_flush_method == SRV_UNIX_O_DSYNC) { - create_flag = create_flag | O_DSYNC; + create_flag = create_flag | O_SYNC; } #endif if (create_mode == OS_FILE_CREATE) { From e77d99c6af7d194afc9c295f5a8ad08cef162221 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 20 Jul 2001 20:58:58 +0300 Subject: [PATCH 02/51] row0sel.c Remove a possible cause of the Peter Zaitsev hang innobase/row/row0sel.c: Remove a possible cause of the Peter Zaitsev hang --- innobase/row/row0sel.c | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/innobase/row/row0sel.c b/innobase/row/row0sel.c index eef60c07af3..5a77fc5daaa 100644 --- a/innobase/row/row0sel.c +++ b/innobase/row/row0sel.c @@ -2537,10 +2537,7 @@ row_search_for_mysql( unique_search_from_clust_index = TRUE; - /* Disable this optimization (hence FALSE below) until - the hang of Peter Zaitsev has been tracked down */ - - if (FALSE && trx->mysql_n_tables_locked == 0 + if (trx->mysql_n_tables_locked == 0 && !prebuilt->sql_stat_start) { /* This is a SELECT query done as a consistent read, @@ -2576,6 +2573,12 @@ row_search_for_mysql( return(DB_RECORD_NOT_FOUND); } + + /* Commit the mini-transaction since it can + hold latches */ + + mtr_commit(&mtr); + mtr_start(&mtr); } } From 556bb5fb9c95c079696f273a96aa356c73b5564a Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 21 Jul 2001 13:51:40 -0300 Subject: [PATCH 03/51] Updated Translation English->Protuguese sql/share/portuguese/errmsg.txt: Updated the translation English->Portuguese. --- sql/share/portuguese/errmsg.txt | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/sql/share/portuguese/errmsg.txt b/sql/share/portuguese/errmsg.txt index b1cab63c0a0..8acb2365996 100644 --- a/sql/share/portuguese/errmsg.txt +++ b/sql/share/portuguese/errmsg.txt @@ -206,8 +206,8 @@ "Não conseguiu criar 'thread' de 'slave'. Verifique os recursos do sistema", "Usuário '%-.64s' já possui 'max_user_connections' conexões ativas", "Você pode usar apenas expressões de constante com SET", -"Lock wait timeout exceeded", -"The total number of locks exceeds the lock table size", -"Update locks cannot be acquired during a READ UNCOMMITTED transaction", -"DROP DATABASE not allowed while thread is holding global read lock", -"CREATE DATABASE not allowed while thread is holding global read lock", +"Excedido tempo de espera (timeout) do travamento", +"O número total de travamentos excede o tamanho de travamento da tabela", +"Travamentos de atualização não podem ser obtidos durante um READ UNCOMMITTED na transação", +"DROP DATABASE não permitido enquanto uma 'thread' está assegurando um travamento global de leitura", +"CREATE DATABASE não permitido enquanto uma 'thread' está assegurando um travamento global de leitura", From 0889a0055aa94180f598a99a59e56e9539e17a25 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 23 Jul 2001 13:02:45 -0500 Subject: [PATCH 04/51] Applied mysqldumslow patch to manual.texi. Docs/manual.texi: Applied mysqldumslow patch. --- Docs/manual.texi | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 551db373ae0..63562566dac 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -39006,7 +39006,10 @@ suffixed with @code{-slow.log}. If a filename is given, but doesn't contain a path, the file is written in the data directory. The slow query log can be used to find queries that take a long time to -execute and are thus candidates for optimization. +execute and are thus candidates for optimization. With a large log, that +can become a difficult task. You can pipe the slow query log through the +@code{mysqldumpslow} command to get a summary of the queries which +appear in the log. You are using @code{--log-long-format} then also queries that are not using indexes are printed. @xref{Command-line options}. From 10cae1f6706639d2ceb6db49a87579209c698507 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 23 Jul 2001 21:44:28 -0500 Subject: [PATCH 05/51] manual.texi bug was described incorrectly Docs/manual.texi: bug was described incorrectly --- Docs/manual.texi | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 63562566dac..4099de9a1d4 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -45748,8 +45748,9 @@ Fixed hard bug in BDB tables when using key parts. Fixed problem when using the @code{GRANT FILE ON database.* ...}; Previously we added the @code{DROP} privilege for the database. @item -Fixed that @code{DELETE FROM table_name ... LIMIT 0} and -@code{UPDATE FROM table_name ... LIMIT 0} doesn't delete/update anything. +Fixed @code{DELETE FROM table_name ... LIMIT 0} and +@code{UPDATE FROM table_name ... LIMIT 0} acted as though the @code{LIMIT} +clause was not present (they deleted or updated all selected rows). @item @code{CHECK TABLE} now checks if an auto_increment column contains the value 0. @item From 47fe7b4f16cca046cc345c7f1e20bda791827492 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 23 Jul 2001 21:53:41 -0500 Subject: [PATCH 06/51] manual.texi change note cleanups, other misc. typo fixes Docs/manual.texi: change note cleanups, other misc. typo fixes --- Docs/manual.texi | 35 ++++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 4099de9a1d4..bb158c60f97 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -6461,7 +6461,7 @@ With the option @code{--with-extra-charset=LIST} you can define which additional character sets should be incompiled in the server. Here @code{LIST} is either a list of character set separated with space, -@code{complex} to include all characters that can't be dynamicly loaded +@code{complex} to include all characters that can't be dynamically loaded or @code{all} to include all character sets into the binaries. @item @@ -12444,14 +12444,14 @@ mysql -u monty -p database_name Note that in the last example the password is @strong{NOT} 'database_name'. -If you want to use the -p option to supply a password you should do like this: +If you want to use the @code{-p} option to supply a password you should do like this: @example mysql -u monty -pguess database_name @end example On some system the library call that @strong{MySQL} uses to prompt for a -password will automaticly cut the password to 8 characters. Internally +password will automatically cut the password to 8 characters. Internally @strong{MySQL} doesn't have any limit for the length of the password. @node Connecting, Password security, User names, Privilege system @@ -19861,7 +19861,7 @@ still get strange errors from a table when @strong{MySQL} tries to update a row or find a row by key (this is VERY unlikely to happen if a normal check has succeeded!). -Some things reported by check table, can't be corrected automaticly: +Some things reported by check table, can't be corrected automatically: @itemize @bullet @item @@ -43560,7 +43560,7 @@ as well developers, to do regression tests on the @strong{MySQL} code. To address this problem, we have created a new test system that is included in the source and binary distributions starting in Version 3.23.29. -The current set of test cases doesn't test everything in MySQL but, it +The current set of test cases doesn't test everything in @strong{MySQL}, but it should catch most obvious bugs in the SQL processing code, OS/library issues, and is quite thorough in testing replication. Our eventual goal is to have the tests cover 100% of the code. We welcome contributions @@ -45605,30 +45605,30 @@ Our TODO section contains what we plan to have in 4.0. @xref{TODO MySQL 4.0}. @item Multi-table @code{DELETE}. @item -Don't anymore support old client protocols prior to @strong{MySQL} 3.21. +Don't support old client protocols prior to @strong{MySQL} 3.21 any more. @item Don't include the old C API functions @code{mysql_drop_db}, -@code{mysql_create_db} and @code{mysql_connect}, if not compiled with +@code{mysql_create_db} and @code{mysql_connect}, unless compiled with @code{USE_OLD_FUNCTIONS}. @item Renamed @code{safe_mysqld} to @code{mysqld_safe}. @item -Allow one to use @code{IN} instead of @code{FROM} in @code{SHOW} commands. +Allow @code{IN} as a synonym for @code{FROM} in @code{SHOW} commands. @item @code{SHOW INDEXES} is now a synonym for @code{SHOW INDEX}. @item Added support for symbolic links to @code{MyISAM} tables. Symlink handling is now enabled by default for Windows. @item -@code{LOAD DATA FROM MASTER} "auto-magically" sets up a slave. +@code{LOAD DATA FROM MASTER} ``auto-magically'' sets up a slave. @item A new @code{HANDLER} interface to @code{MyISAM} tables. @item @code{COUNT(DISTINCT)} is about 30% faster. @item -Creating full text indexes are now much faster. +@code{FULLTEXT} index creation now is much faster. @item -Searching on packed (@code{CHAR}/@code{VARCHAR}) keys are now much faster. +Searching on packed (@code{CHAR}/@code{VARCHAR}) keys now is much faster. @item Added @code{SQL_CALC_FOUND_ROWS} and @code{FOUND_ROWS()}. This makes it possible to know how many rows a query would have returned @@ -45737,13 +45737,13 @@ not yet 100% confident in this code. Fixed problem with @code{--low-priority-updates} and @code{INSERT}'s. @item Fixed bug in slave thread when under some rare circumstances it could -get 22 bytes ahead on the offset in the master +get 22 bytes ahead on the offset in the master. @item Added @code{slave_wait_timeout} for replication. @item -Fixed problem with @code{UPDATE} and BDB tables. +Fixed problem with @code{UPDATE} and @code{BDB} tables. @item -Fixed hard bug in BDB tables when using key parts. +Fixed hard bug in @code{BDB} tables when using key parts. @item Fixed problem when using the @code{GRANT FILE ON database.* ...}; Previously we added the @code{DROP} privilege for the database. @@ -45752,7 +45752,8 @@ Fixed @code{DELETE FROM table_name ... LIMIT 0} and @code{UPDATE FROM table_name ... LIMIT 0} acted as though the @code{LIMIT} clause was not present (they deleted or updated all selected rows). @item -@code{CHECK TABLE} now checks if an auto_increment column contains the value 0. +@code{CHECK TABLE} now checks if an @code{AUTO_INCREMENT} column contains +the value 0. @item Sending a @code{SIGHUP} to @code{mysqld} will now only flush the logs, not reset the replication. @@ -45767,11 +45768,11 @@ only prints the error @code{Aborted connection} if this option is used. Fixed problem with @code{SHOW CREATE TABLE} when you didn't have a @code{PRIMARY KEY}. @item -Fixed properly the rename of @code{innodb_unix_file_flush_method} to +Properly fixed the rename of @code{innodb_unix_file_flush_method} to @code{innodb_flush_method}. @item Fixed bug when converting @code{UNSIGNED BIGINT} to @code{DOUBLE}. This caused -a problem when doing comparisons with @code{BIGINT}'s outside of the +a problem when doing comparisons with @code{BIGINT} values outside of the signed range. @item Fixed bug in @code{BDB} tables when querying empty tables. From 710fb9998b7a37ece5fc5e84a5a7accc84bb1850 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 24 Jul 2001 12:00:23 -0400 Subject: [PATCH 07/51] ha_berkeley.cc Fix bug in remove_key(), when key != primary_key it would ha_berkeley.cc core dump if cursor was invalid. sql/ha_berkeley.cc: Fix bug in remove_key(), when key != primary_key it would core dump if cursor was invalid. --- sql/ha_berkeley.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sql/ha_berkeley.cc b/sql/ha_berkeley.cc index 6907da855b9..fedb7812c36 100644 --- a/sql/ha_berkeley.cc +++ b/sql/ha_berkeley.cc @@ -1207,7 +1207,7 @@ int ha_berkeley::remove_key(DB_TXN *trans, uint keynr, const byte *record, if (!(error=key_file[keynr]->cursor(key_file[keynr], trans, &tmp_cursor, 0))) { - if (!(error=cursor->c_get(tmp_cursor, + if (!(error=tmp_cursor->c_get(tmp_cursor, (keynr == primary_key ? prim_key : create_key(&key, keynr, key_buff2, record)), From 22a5241f2836c3c9217bd59d6658259486e7fd27 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 24 Jul 2001 12:23:17 -0400 Subject: [PATCH 08/51] Add test case for update/replace bug in bdb. Remove unused argument to ha_berkeley::remove_key(). mysql-test/r/bdb.result: Add test case for update/replace bug in bdb. BitKeeper/etc/ignore: Added .gdbinit .vimrc to the ignore list mysql-test/t/bdb.test: Add test case for update/replace bug in bdb. sql/ha_berkeley.cc: The packed_record argument to ha_berkeley::remove_key() was never used; remove it. sql/ha_berkeley.h: The packed_record argument to ha_berkeley::remove_key() was never used; remove it. --- .bzrignore | 2 ++ mysql-test/r/bdb.result | 2 ++ mysql-test/t/bdb.test | 7 +++++++ sql/ha_berkeley.cc | 21 +++++++-------------- sql/ha_berkeley.h | 3 +-- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/.bzrignore b/.bzrignore index 1683e4d7a22..e18c49af87c 100644 --- a/.bzrignore +++ b/.bzrignore @@ -289,3 +289,5 @@ tags tmp/* myisam/test1.MYD myisam/test1.MYI +.gdbinit +.vimrc diff --git a/mysql-test/r/bdb.result b/mysql-test/r/bdb.result index 89d9c56b3b0..39b4962ef58 100644 --- a/mysql-test/r/bdb.result +++ b/mysql-test/r/bdb.result @@ -139,6 +139,8 @@ t1 1 level 1 level A 3 NULL NULL gesuchnr benutzer_id 1 1 2 1 +id x +1 2 Table Op Msg_type Msg_text test.t1 optimize status OK a diff --git a/mysql-test/t/bdb.test b/mysql-test/t/bdb.test index ed167d8d005..7976b482100 100644 --- a/mysql-test/t/bdb.test +++ b/mysql-test/t/bdb.test @@ -65,6 +65,13 @@ replace into t1 (gesuchnr,benutzer_id) values (1,1); select * from t1; drop table t1; +# test for bug in replace with secondary key +create table t1 (id int not null primary key, x int not null, key (x)) type=bdb; +insert into t1 (id, x) values (1, 1); +replace into t1 (id, x) values (1, 2); +select * from t1; +drop table t1; + # # test delete using hidden_primary_key # diff --git a/sql/ha_berkeley.cc b/sql/ha_berkeley.cc index fedb7812c36..25f8148e52f 100644 --- a/sql/ha_berkeley.cc +++ b/sql/ha_berkeley.cc @@ -888,7 +888,7 @@ int ha_berkeley::write_row(byte * record) if (changed_keys & 1) { if ((new_error = remove_key(sub_trans, keynr, record, - (DBT*) 0, &prim_key))) + &prim_key))) break; /* purecov: inspected */ } } @@ -970,7 +970,7 @@ int ha_berkeley::update_primary_key(DB_TXN *trans, bool primary_key_changed, { // Primary key changed or we are updating a key that can have duplicates. // Delete the old row and add a new one - if (!(error=remove_key(trans, primary_key, old_row, (DBT *) 0, old_key))) + if (!(error=remove_key(trans, primary_key, old_row, old_key))) { if (!(error=pack_row(&row, new_row, 0))) { @@ -1034,7 +1034,7 @@ int ha_berkeley::restore_keys(DB_TXN *trans, key_map changed_keys, if (changed_keys & 1) { if (changed_keys != 1 && - (error = remove_key(trans, keynr, new_row, (DBT*) 0, new_key))) + (error = remove_key(trans, keynr, new_row, new_key))) break; /* purecov: inspected */ if ((error = key_file[keynr]->put(key_file[keynr], trans, create_key(&tmp_key, keynr, key_buff2, @@ -1105,8 +1105,7 @@ int ha_berkeley::update_row(const byte * old_row, byte * new_row) continue; if (key_cmp(keynr, old_row, new_row) || primary_key_changed) { - if ((error=remove_key(sub_trans, keynr, old_row, (DBT*) 0, - &old_prim_key))) + if ((error=remove_key(sub_trans, keynr, old_row, &old_prim_key))) { if (using_ignore && /* purecov: inspected */ (thd_options & OPTION_INTERNAL_SUBTRANSACTIONS)) @@ -1172,11 +1171,9 @@ int ha_berkeley::update_row(const byte * old_row, byte * new_row) Delete one key This uses key_buff2, when keynr != primary key, so it's important that a function that calls this doesn't use this buffer for anything else. - packed_record may be NULL if the key is unique */ int ha_berkeley::remove_key(DB_TXN *trans, uint keynr, const byte *record, - DBT *packed_record, DBT *prim_key) { int error; @@ -1208,12 +1205,8 @@ int ha_berkeley::remove_key(DB_TXN *trans, uint keynr, const byte *record, &tmp_cursor, 0))) { if (!(error=tmp_cursor->c_get(tmp_cursor, - (keynr == primary_key ? - prim_key : - create_key(&key, keynr, key_buff2, record)), - (keynr == primary_key ? - packed_record : prim_key), - DB_GET_BOTH | DB_RMW))) + create_key(&key, keynr, key_buff2, record), + prim_key, DB_GET_BOTH | DB_RMW))) { // This shouldn't happen error=tmp_cursor->c_del(tmp_cursor,0); } @@ -1236,7 +1229,7 @@ int ha_berkeley::remove_keys(DB_TXN *trans, const byte *record, { if (keys & 1) { - int new_error=remove_key(trans, keynr, record, new_record, prim_key); + int new_error=remove_key(trans, keynr, record, prim_key); if (new_error) { result=new_error; // Return last error /* purecov: inspected */ diff --git a/sql/ha_berkeley.h b/sql/ha_berkeley.h index 9e657d72da1..3eb793937ae 100644 --- a/sql/ha_berkeley.h +++ b/sql/ha_berkeley.h @@ -69,8 +69,7 @@ class ha_berkeley: public handler int key_length = MAX_KEY_LENGTH); DBT *pack_key(DBT *key, uint keynr, char *buff, const byte *key_ptr, uint key_length); - int remove_key(DB_TXN *trans, uint keynr, const byte *record, - DBT *packed_record, DBT *prim_key); + int remove_key(DB_TXN *trans, uint keynr, const byte *record, DBT *prim_key); int remove_keys(DB_TXN *trans,const byte *record, DBT *new_record, DBT *prim_key, key_map keys); int restore_keys(DB_TXN *trans, key_map changed_keys, uint primary_key, From 78c9ec6f95d614a1e9121ace9e73a58734f581b4 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 24 Jul 2001 14:09:33 -0400 Subject: [PATCH 09/51] Code cleanup in safe_mysqld. Fix --core-file-size so that the argument is parsed correctly. scripts/safe_mysqld.sh: Code cleanup. Fix --core-file-size so that the argument is parsed correctly. --- scripts/safe_mysqld.sh | 43 +++++++++++++++++++----------------------- 1 file changed, 19 insertions(+), 24 deletions(-) diff --git a/scripts/safe_mysqld.sh b/scripts/safe_mysqld.sh index 6eda1740ad6..59d7dcc5cfc 100644 --- a/scripts/safe_mysqld.sh +++ b/scripts/safe_mysqld.sh @@ -23,37 +23,32 @@ 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 + pick_args=$1; shift for arg do case "$arg" in # these get passed explicitly to mysqld - --basedir=*) MY_BASEDIR_VERSION=`echo "$arg" | sed -e "s;--basedir=;;"` ;; - --datadir=*) DATADIR=`echo "$arg" | sed -e "s;--datadir=;;"` ;; - --pid-file=*) pid_file=`echo "$arg" | sed -e "s;--pid-file=;;"` ;; - --user=*) user=`echo "$arg" | sed -e "s;--user=;;"` ;; + --basedir=*) MY_BASEDIR_VERSION=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --datadir=*) DATADIR=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --pid-file=*) pid_file=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --user=*) user=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; # these two might have been set in a [safe_mysqld] section of my.cnf # they get passed via environment variables to safe_mysqld - --socket=*) MYSQL_UNIX_PORT=`echo "$arg" | sed -e "s;--socket=;;"` ;; - --port=*) MYSQL_TCP_PORT=`echo "$arg" | sed -e "s;--port=;;"` ;; + --socket=*) MYSQL_UNIX_PORT=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --port=*) MYSQL_TCP_PORT=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; - # safe_mysqld-specific options - must be set in my.cnf ([safe_mysqld])! - --ledir=*) ledir=`echo "$arg" | sed -e "s;--ledir=;;"` ;; - --err-log=*) err_log=`echo "$arg" | sed -e "s;--err-log=;;"` ;; + # safe_mysqld-specific options + --ledir=*) ledir=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --err-log=*) err_log=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; # QQ The --open-files should be removed - --open-files=*) open_files=`echo "$arg" | sed -e "s;--open-files=;;"` ;; - --open-files-limit=*) open_files=`echo "$arg" | sed -e "s;--open-files-limit=;;"` ;; - --core-file-size=*) core_file_size=`echo "$arg" | sed -e "s;--core_file_size=;;"` ;; - --timezone=*) TZ=`echo "$arg" | sed -e "s;--timezone=;;"` ; export TZ; ;; - --mysqld=*) MYSQLD=`echo "$arg" | sed -e "s;--mysqld=;;"` ;; + --open-files=*) open_files=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --open-files-limit=*) open_files=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --core-file-size=*) core_file_size=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; + --timezone=*) TZ=`echo "$arg" | sed -e "s;--[^=]*=;;"` ; export TZ; ;; + --mysqld=*) MYSQLD=`echo "$arg" | sed -e "s;--[^=]*=;;"` ;; --mysqld-version=*) - tmp=`echo "$arg" | sed -e "s;--mysqld-version=;;"` + tmp=`echo "$arg" | sed -e "s;--[^=]*=;;"` if test -n "$tmp" then MYSQLD="mysqld-$tmp" @@ -62,7 +57,7 @@ parse_arguments() { fi ;; *) - if test -n "$pick_args" + if test $pick_args -eq 1 then # This sed command makes sure that any special chars are quoted, # so the arg gets passed exactly to the server. @@ -130,8 +125,8 @@ else fi args= -parse_arguments `$print_defaults $defaults mysqld server safe_mysqld` -parse_arguments PICK-ARGS-FROM-ARGV "$@" +parse_arguments 0 `$print_defaults $defaults mysqld server safe_mysqld` +parse_arguments 1 "$@" if test ! -x $ledir/$MYSQLD then From 29ef9455578c37f5581609171bb1abc7d0410162 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 25 Jul 2001 15:47:31 -0500 Subject: [PATCH 10/51] New Chapter 1 a la DocTOC. Sorry for such a big patch. :) --- Docs/manual.texi | 6509 +++++++++++++++++++++++----------------------- 1 file changed, 3295 insertions(+), 3214 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index bb158c60f97..8b5052aa19c 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -111,10 +111,7 @@ distribution for that version. @menu * Introduction:: General Information about @strong{MySQL} -* Questions:: @strong{MySQL} mailing lists and how to ask questions or report errors (bugs) -* Licensing and Support:: @strong{MySQL} licensing and support * Installing:: Installing @strong{MySQL} -* Compatibility:: How standards-compatible is @strong{MySQL}? * Privilege system:: The @strong{MySQL} access privilege system * Reference:: @strong{MySQL} language reference * Table types:: @strong{MySQL} table types @@ -134,7 +131,6 @@ distribution for that version. * Common problems:: Solving some common problems with @strong{MySQL} * Log files:: * Clients:: @strong{MySQL} client tools and APIs -* Comparisons:: How does @strong{MySQL} compare with other databases? * MySQL internals:: @strong{MySQL} internals * Environment variables:: @strong{MySQL} environment variables * Users:: Some @strong{MySQL} users @@ -142,8 +138,6 @@ distribution for that version. * Contrib:: Contributed programs * Credits:: Contributors to @strong{MySQL} * News:: @strong{MySQL} change history -* Bugs:: Known errors and design deficiencies in @strong{MySQL} -* TODO:: List of things we want to add to @strong{MySQL} in the future (The TODO) * Porting:: Comments on porting to other systems * Regexp:: Description of @strong{MySQL} regular expression syntax * Unireg:: What is Unireg? @@ -157,20 +151,31 @@ distribution for that version. General Information About MySQL +* MySQL and MySQL AB:: +* MySQL Information Sources:: +* Licensing and Support:: +* Compatibility:: +* Comparisons:: +* TODO:: + +MySQL, MySQL AB, and Open Source + * What-is:: What is @strong{MySQL}? -* What is MySQL AB:: +* What is MySQL AB:: What is @strong{MySQL AB}? * Manual-info:: About this manual +* Manual conventions:: Conventions used in this manual * History:: History of @strong{MySQL} -* MySQL-Books:: Books about MySQL * Features:: The main features of @strong{MySQL} * Stability:: How stable is @strong{MySQL}? +* Table size:: * Year 2000 compliance:: Year 2000 compliance -* General-SQL:: General SQL information and tutorials -* Useful Links:: Useful @strong{MySQL}-related links -About This Manual +MySQL Information Sources -* Manual conventions:: Conventions used in this manual +* MySQL-Books:: +* General-SQL:: +* Useful Links:: +* Questions:: MySQL Mailing Lists @@ -211,6 +216,61 @@ Types of Commercial Support * Telephone support:: Telephone support * Table handler support:: Support for other table handlers +How Standards-compatible Is MySQL? + +* Extensions to ANSI:: @strong{MySQL} extensions to ANSI SQL92 +* Differences from ANSI:: @strong{MySQL} differences compared to ANSI SQL92 +* ANSI mode:: Running @strong{MySQL} in ANSI mode +* Missing functions:: Functionality missing from @strong{MySQL} +* Standards:: What standards does @strong{MySQL} follow? +* Commit-rollback:: How to cope without @code{COMMIT}-@code{ROLLBACK} +* Bugs:: + +Functionality Missing from MySQL + +* Missing Sub-selects:: Sub-selects +* Missing SELECT INTO TABLE:: @code{SELECT INTO TABLE} +* Missing Transactions:: Transactions +* Missing Triggers:: Triggers +* Missing Foreign Keys:: Foreign Keys +* Broken Foreign KEY:: +* Missing Views:: Views +* Missing comments:: @samp{--} as the start of a comment + +Foreign Keys + +* Broken Foreign KEY:: Reasons NOT to use foreign keys constraints + +How MySQL Compares to Other Databases + +* Compare mSQL:: How @strong{MySQL} compares to @code{mSQL} +* Protocol differences:: +* Compare PostgreSQL:: How @strong{MySQL} compares with PostgreSQL +* MySQL-PostgreSQL features:: + +How MySQL Compares to @code{mSQL} + +* Using mSQL tools:: How to convert @code{mSQL} tools for @strong{MySQL} + +How @code{mSQL} and MySQL Client/Server Communications Protocols Differ + +* Syntax differences:: + +How MySQL Compares to PostgreSQL + +* MySQL-PostgreSQL goals:: MySQL and PostgreSQL development strategies + +Featurevise Comparison of MySQL and PostgreSQL + +* MySQL-PostgreSQL benchmarks:: + +MySQL and the future (The TODO) + +* TODO MySQL 4.0:: Things that should be in Version 4.0 +* TODO future:: Things that must be done in the near future +* TODO sometime:: Things that have to be done sometime +* TODO unplanned:: Some things we don't have any plans to do + Installing MySQL * Getting MySQL:: How to get @strong{MySQL} @@ -331,29 +391,6 @@ Upgrading/Downgrading MySQL * Upgrading-from-3.20:: Upgrading from a 3.20 version to 3.21 * Upgrading-to-arch:: Upgrading to another architecture -How Standards-compatible Is MySQL? - -* Extensions to ANSI:: @strong{MySQL} extensions to ANSI SQL92 -* ANSI mode:: Running @strong{MySQL} in ANSI mode -* Differences from ANSI:: @strong{MySQL} differences compared to ANSI SQL92 -* Missing functions:: Functionality missing from @strong{MySQL} -* Standards:: What standards does @strong{MySQL} follow? -* Commit-rollback:: How to cope without @code{COMMIT}-@code{ROLLBACK} - -Functionality Missing from MySQL - -* Missing Sub-selects:: Sub-selects -* Missing SELECT INTO TABLE:: @code{SELECT INTO TABLE} -* Missing Transactions:: Transactions -* Missing Triggers:: Triggers -* Missing Foreign Keys:: Foreign Keys -* Missing Views:: Views -* Missing comments:: @samp{--} as the start of a comment - -Foreign Keys - -* Broken Foreign KEY:: Reasons NOT to use foreign keys constraints - The MySQL Access Privilege System * General security:: General security @@ -619,7 +656,6 @@ Queries from Twin Project MySQL Server Functions * Languages:: What languages are supported by @strong{MySQL}? -* Table size:: How big @strong{MySQL} tables can be What Languages Are Supported by MySQL? @@ -919,23 +955,6 @@ MySQL PHP API * PHP problems:: Common problems with MySQL and PHP -How MySQL Compares to Other Databases - -* Compare mSQL:: How @strong{MySQL} compares to @code{mSQL} -* Compare PostgreSQL:: How @strong{MySQL} compares with PostgreSQL - -How MySQL Compares to @code{mSQL} - -* Using mSQL tools:: How to convert @code{mSQL} tools for @strong{MySQL} -* Protocol differences:: How @code{mSQL} and @strong{MySQL} client/server communications protocols differ -* Syntax differences:: How @code{mSQL} 2.0 SQL syntax differs from @strong{MySQL} - -How MySQL Compares to PostgreSQL - -* MySQL-PostgreSQL goals:: MySQL and PostgreSQL development strategies -* MySQL-PostgreSQL features:: Featurevise Comparison of MySQL and PostgreSQL -* MySQL-PostgreSQL benchmarks:: Benchmarking MySQL and PostgreSQL - MySQL Internals * MySQL threads:: MySQL threads @@ -1111,13 +1130,6 @@ Changes in release 3.19.x * News-3.19.4:: Changes in release 3.19.4 * News-3.19.3:: Changes in release 3.19.3 -MySQL and the future (The TODO) - -* TODO MySQL 4.0:: Things that should be in Version 4.0 -* TODO future:: Things that must be done in the near future -* TODO sometime:: Things that have to be done sometime -* TODO unplanned:: Some things we don't have any plans to do - Comments on porting to other systems * Debugging server:: Debugging a @strong{MySQL} server @@ -1144,22 +1156,9 @@ Debugging a MySQL server @cindex online location of manual @cindex manual, online location -@node Introduction, Questions, Top, Top +@node Introduction, Installing, Top, Top @chapter General Information About MySQL -@menu -* What-is:: What is @strong{MySQL}? -* What is MySQL AB:: -* Manual-info:: About this manual -* History:: History of @strong{MySQL} -* MySQL-Books:: Books about MySQL -* Features:: The main features of @strong{MySQL} -* Stability:: How stable is @strong{MySQL}? -* Year 2000 compliance:: Year 2000 compliance -* General-SQL:: General SQL information and tutorials -* Useful Links:: Useful @strong{MySQL}-related links -@end menu - This is the @strong{MySQL} reference manual; it documents @strong{MySQL} Version @value{mysql_version}. As @strong{MySQL} is work in progress, the manual gets updated frequently. There is a very good chance that @@ -1246,10 +1245,36 @@ or relational database concepts. If you want general information about SQL, see @ref{General-SQL}. For books that focus more specifically on @strong{MySQL}, see @ref{MySQL-Books}. + +@menu +* MySQL and MySQL AB:: +* MySQL Information Sources:: +* Licensing and Support:: +* Compatibility:: +* Comparisons:: +* TODO:: +@end menu + +@node MySQL and MySQL AB, MySQL Information Sources, Introduction, Introduction +@section MySQL, MySQL AB, and Open Source + +@menu +* What-is:: What is @strong{MySQL}? +* What is MySQL AB:: What is @strong{MySQL AB}? +* Manual-info:: About this manual +* Manual conventions:: Conventions used in this manual +* History:: History of @strong{MySQL} +* Features:: The main features of @strong{MySQL} +* Stability:: How stable is @strong{MySQL}? +* Table size:: +* Year 2000 compliance:: Year 2000 compliance +@end menu + +@node What-is, What is MySQL AB, MySQL and MySQL AB, MySQL and MySQL AB +@subsection What Is MySQL + @cindex MySQL, defined @cindex MySQL, introduction -@node What-is, What is MySQL AB, Introduction, Introduction -@section What Is MySQL @strong{MySQL}, the most popular Open Source SQL database, is provided by @strong{MySQL AB}. @strong{MySQL AB} is a commercial company that @@ -1335,9 +1360,10 @@ language already supports @strong{MySQL}. The official way to pronounce @strong{MySQL} is ``My Ess Que Ell'' (not MY-SEQUEL). But we try to avoid correcting people who say MY-SEQUEL. +@node What is MySQL AB, Manual-info, What-is, MySQL and MySQL AB +@subsection What Is MySQL AB + @cindex MySQL AB, defined -@node What is MySQL AB, Manual-info, What-is, Introduction -@section What Is MySQL AB @strong{MySQL AB} is the Swedish company owned and run by the @strong{MySQL} founders and main developers. We are dedicated to developing @strong{MySQL} @@ -1446,12 +1472,8 @@ Are a virtual company, networking with others. Work against software patents. @end itemize -@node Manual-info, History, What is MySQL AB, Introduction -@section About This Manual - -@menu -* Manual conventions:: Conventions used in this manual -@end menu +@node Manual-info, Manual conventions, What is MySQL AB, MySQL and MySQL AB +@subsection About This Manual This manual is currently available in Texinfo, plain text, Info, HTML, PostScript, and PDF versions. The primary document is the Texinfo file. @@ -1467,7 +1489,7 @@ This manual is written and maintained by David Axmark, Michael (Monty) Widenius, Jeremy Cole, and Paul DuBois. For other contributors, see @ref{Credits}. -@node Manual conventions, , Manual-info, Manual-info +@node Manual conventions, History, Manual-info, MySQL and MySQL AB @subsection Conventions Used in This Manual This manual uses certain typographical conventions: @@ -1591,12 +1613,13 @@ alternatives are listed within braces (@samp{@{} and @samp{@}}): @{DESCRIBE | DESC@} tbl_name @{col_name | wild@} @end example +@node History, Features, Manual conventions, MySQL and MySQL AB +@subsection History of MySQL + @cindex MySQL history @cindex history of MySQL @cindex MySQL name @cindex My, derivation -@node History, MySQL-Books, Manual-info, Introduction -@section History of MySQL We once started out with the intention of using @code{mSQL} to connect to our tables using our own fast low-level (ISAM) routines. However, after some @@ -1611,11 +1634,499 @@ directory and a large number of our libraries and tools have had the prefix is also named My. Which of the two gave its name to @strong{MySQL} is still a mystery, even for us. -@node MySQL-Books, Features, History, Introduction -@section Books About MySQL -@cindex books, about MySQL -@cindex manuals, about MySQL +@node Features, Stability, History, MySQL and MySQL AB +@subsection The Main Features of MySQL + +@cindex main features of MySQL +@cindex features of MySQL + +The following list describes some of the important characteristics +of @strong{MySQL}: + +@c This list is too technical and should be divided into one feature +@c list comparable to commercial competition and a very technical on +@c with max limits (from crash-me) and so on. +@itemize @bullet +@item +Fully multi-threaded using kernel threads. This means it can easily +use multiple CPUs if available. + +@item +C, C++, Eiffel, Java, Perl, PHP, Python and Tcl APIs. @xref{Clients}. + +@item +Works on many different platforms. @xref{Which OS}. + +@item +Many column types: signed/unsigned integers 1, 2, 3, 4, and 8 bytes +long, @code{FLOAT}, @code{DOUBLE}, @code{CHAR}, @code{VARCHAR}, +@code{TEXT}, @code{BLOB}, @code{DATE}, @code{TIME}, @code{DATETIME}, +@code{TIMESTAMP}, @code{YEAR}, @code{SET}, and @code{ENUM} types. +@xref{Column types}. + +@item +Very fast joins using an optimized one-sweep multi-join. + +@item +Full operator and function support in the @code{SELECT} and @code{WHERE} +parts of queries. For example: + +@example +mysql> SELECT CONCAT(first_name, " ", last_name) FROM tbl_name + WHERE income/dependents > 10000 AND age > 30; +@end example + +@item +SQL functions are implemented through a highly optimized class library and +should be as fast as possible! Usually there isn't any memory allocation +at all after query initialization. + +@item +Full support for SQL @code{GROUP BY} and @code{ORDER BY} clauses. Support +for group functions (@code{COUNT()}, @code{COUNT(DISTINCT ...)}, +@code{AVG()}, @code{STD()}, @code{SUM()}, @code{MAX()} and @code{MIN()}). + +@item +Support for @code{LEFT OUTER JOIN} and @code{RIGHT OUTER JOIN} with ANSI +SQL and ODBC syntax. + +@item +You can mix tables from different databases in the same query (as of +Version 3.22). + +@item +A privilege and password system that is very flexible and secure, and +allows host-based verification. Passwords are secure because all +password traffic is encrypted when you connect to a server. + +@item +ODBC (Open-DataBase-Connectivity) support for Win32 (with source). All +ODBC 2.5 functions and many others. For example, you can use MS Access to +connect to your @strong{MySQL} server. @xref{ODBC}. + +@item +Very fast B-tree disk tables with index compression. + +@item +Up to 32 indexes per table are allowed. Each index may consist of 1 to 16 +columns or parts of columns. The maximum index length is 500 bytes (this +may be changed when compiling @strong{MySQL}). An index may use a prefix +of a @code{CHAR} or @code{VARCHAR} field. + +@item +Fixed-length and variable-length records. + +@item +In-memory hash tables which are used as temporary tables. + +@item +Handles large databases. We are using @strong{MySQL} with some +databases that contain 50,000,000 records and we know of users that +uses @strong{MySQL} with 60,000 tables and about 5,000,000,000 rows + +@item +All columns have default values. You can use @code{INSERT} to insert a +subset of a table's columns; those columns that are not explicitly given +values are set to their default values. + +@item +Uses GNU Automake, Autoconf, and Libtool for portability. + +@item +Written in C and C++. Tested with a broad range of different compilers. + +@item +A very fast thread-based memory allocation system. + +@item +No memory leaks. @strong{MySQL} has been tested with Purify, a commercial +memory leakage detector. + +@item +Includes @code{myisamchk}, a very fast utility for table checking, +optimization, and repair. All of the functionality of @code{myisamchk} +is also available through the SQL interface as well. @xref{Maintenance}. + +@item +Full support for several different character sets, including +ISO-8859-1 (Latin1), big5, ujis, and more. For example, the +Scandinavian characters `@ringaccent{a}', `@"a' and `@"o' are allowed +in table and column names. + +@item +All data are saved in the chosen character set. All comparisons for normal +string columns are case insensitive. + +@item +Sorting is done according to the chosen character set (the Swedish +way by default). It is possible to change this when the @strong{MySQL} server +is started up. To see an example of very advanced sorting, look at the +Czech sorting code. @strong{MySQL} supports many different character sets +that can be specified at compile and run time. + +@item +Aliases on tables and columns are allowed as in the SQL92 standard. + +@item +@code{DELETE}, @code{INSERT}, @code{REPLACE}, and @code{UPDATE} return +the number of rows that were changed (affected). It is possible to return +the number of rows matched instead by setting a flag when connecting to the +server. + +@item +Function names do not clash with table or column names. For example, +@code{ABS} is a valid column name. The only restriction is that for a +function call, no spaces are allowed between the function name and the +@samp{(} that follows it. @xref{Reserved words}. + +@item +All @strong{MySQL} programs can be invoked with the @code{--help} or @code{-?} +options to obtain online assistance. + +@item +The server can provide error messages to clients in many languages. +@xref{Languages}. + +@item +Clients may connect to the @strong{MySQL} server using TCP/IP Sockets, +Unix Sockets (Unix), or Named Pipes (NT). + +@item +The @strong{MySQL}-specific @code{SHOW} command can be used to retrieve +information about databases, tables, and indexes. The @code{EXPLAIN} command +can be used to determine how the optimizer resolves a query. +@end itemize + +@cindex stability +@node Stability, Table size, Features, MySQL and MySQL AB +@subsection How Stable Is MySQL? + +This section addresses the questions ``How stable is @strong{MySQL}?'' and +``Can I depend on @strong{MySQL} in this project?'' We will try to clarify +some issues and to answer some of the more important questions that seem to +concern many people. This section has been put together from information +gathered from the mailing list (which is very active in reporting bugs). + +At TcX, @strong{MySQL} has worked without any problems in our projects since +mid-1996. When @strong{MySQL} was released to a wider public, we noticed that +there were some pieces of ``untested code'' that were quickly found by the +new users who made queries in a manner different than our own. Each new +release has had fewer portability problems than the previous one (even though +each has had many new features). + +Each release of @strong{MySQL} has been usable, and there have been problems +only when users start to use code from the ``gray zones.'' Naturally, outside +users don't know what the gray zones are; this section attempts to indicate +those that are currently known. The descriptions deal with Version 3.23 +of @strong{MySQL}. All known and reported bugs are fixed in the latest +version, with the exception of the bugs listed in the bugs section, which +are things that are design-related. @xref{Bugs}. + +@strong{MySQL} is written in multiple layers and different independent +modules. These modules are listed below with an indication of how +well-tested each of them is: + +@cindex modules, list of + +@table @strong +@item The ISAM table handler --- Stable +This manages storage and retrieval of all data in @strong{MySQL} Version 3.22 +and earlier. In all @strong{MySQL} releases there hasn't been a single +(reported) bug in this code. The only known way to get a corrupted table +is to kill the server in the middle of an update. Even that is unlikely +to destroy any data beyond rescue, because all data are flushed to disk +between each query. There hasn't been a single bug report about lost data +because of bugs in @strong{MySQL}. + +@cindex ISAM table handler +@cindex storing, data +@cindex retrieving, data +@cindex data, ISAM table handler + +@item The MyISAM table handler --- Stable +This is new in @strong{MySQL} Version 3.23. It's largely based on the ISAM +table code but has a lot of new and very useful features. + +@item The parser and lexical analyser --- Stable +There hasn't been a single reported bug in this system for a long time. + +@item The C client code --- Stable +No known problems. In early Version 3.20 releases, there were some limitations +in the send/receive buffer size. As of Version 3.21, the buffer size is now +dynamic up to a default of 16M. + +@item Standard client programs --- Stable +These include @code{mysql}, @code{mysqladmin}, @code{mysqlshow}, +@code{mysqldump}, and @code{mysqlimport}. + +@item Basic SQL --- Stable +The basic SQL function system and string classes and dynamic memory +handling. Not a single reported bug in this system. + +@item Query optimizer --- Stable + +@item Range optimizer --- Stable + +@item Join optimizer --- Stable + +@item Locking --- Gamma +This is very system-dependent. On some systems there are big problems +using standard OS locking (@code{fcntl()}). In these cases, you should run the +@strong{MySQL} daemon with the @code{--skip-locking} flag. Problems are known +to occur on some Linux systems, and on SunOS when using NFS-mounted file +systems. + +@item Linux threads --- Stable +The major problem found has been with the @code{fcntl()} call, which is +fixed by using the @w{@code{--skip-locking}} option to +@code{mysqld}. Some people have reported lockup problems with Version 0.5. +LinuxThreads will need to be recompiled if you plan to use +1000+ concurrent connections. Although it is possible to run that many +connections with the default LinuxThreads (however, you will never go +above 1021), the default stack spacing of 2 MB makes the application +unstable, and we have been able to reproduce a coredump after creating +1021 idle connections. @xref{Linux}. + +@item Solaris 2.5+ pthreads --- Stable +We use this for all our production work. + +@item MIT-pthreads (Other systems) --- Stable +There have been no reported bugs since Version 3.20.15 and no known bugs since +Version 3.20.16. On some systems, there is a ``misfeature'' where some +operations are quite slow (a 1/20 second sleep is done between each query). +Of course, MIT-pthreads may slow down everything a bit, but index-based +@code{SELECT} statements are usually done in one time frame so there shouldn't +be a mutex locking/thread juggling. + +@item Other thread implementions --- Beta - Gamma +The ports to other systems are still very new and may have bugs, possibly +in @strong{MySQL}, but most often in the thread implementation itself. + +@item @code{LOAD DATA ...}, @code{INSERT ... SELECT} --- Stable +Some people thought they had found bugs here, but these usually have +turned out to be misunderstandings. Please check the manual before reporting +problems! + +@item @code{ALTER TABLE} --- Stable +Small changes in Version 3.22.12. + +@item DBD --- Stable +Now maintained by Jochen Wiedmann +(@email{wiedmann@@neckar-alb.de}). Thanks! + +@item @code{mysqlaccess} --- Stable +Written and maintained by Yves Carlier +(@email{Yves.Carlier@@rug.ac.be}). Thanks! + +@item @code{GRANT} --- Stable +Big changes made in @strong{MySQL} Version 3.22.12. + +@item @strong{MyODBC} (uses ODBC SDK 2.5) --- Gamma +It seems to work well with some programs. + +@item Replication -- Beta / Gamma +We are still working on replication, so don't expect this to be rock +solid yet. On the other hand, some @strong{MySQL} users are already +using this with good results. + +@item BDB Tables -- Beta +The Berkeley DB code is very stable, but we are still improving the interface +between @strong{MySQL} and BDB tables, so it will take some time before this +is as tested as the other table types. + +@item InnoDB Tables -- Beta +This is a recent addition to @code{MySQL}. They appear to work good and +can be used after some initial testing. + +@item Automatic recovery of MyISAM tables - Beta +This only affects the new code that checks if the table was closed properly +on open and executes an automatic check/repair of the table if it wasn't. + +@item MERGE tables -- Beta / Gamma +The usage of keys on @code{MERGE} tables is still not that tested. The +other part of the @code{MERGE} code is quite well tested. + +@item FULLTEXT -- Beta +Text search seems to work, but is still not widely used. + +@end table + +@strong{MySQL AB} provides e-mail support for paying customers, but the +@strong{MySQL} mailing list usually provides answers to common questions. +Bugs are usually fixed right away with a patch; for serious bugs, there is +almost always a new release. + +@node Table size, Year 2000 compliance, Stability, MySQL and MySQL AB +@subsection How Big Can MySQL Tables Be? + +@cindex tables, maximum size +@cindex size of tables +@cindex operating systems, file size limits +@cindex limits, file size +@cindex files, size limits + +@strong{MySQL} Version 3.22 has a 4G limit on table size. With the new +@code{MyISAM} in @strong{MySQL} Version 3.23 the maximum table size is +pushed up to 8 million terabytes (2 ^ 63 bytes). + +Note, however, that operating systems have their own file size +limits. Here are some examples: + +@multitable @columnfractions .5 .5 +@item @strong{Operating System} @tab @strong{File Size Limit} +@item Linux-Intel 32 bit @tab 2G, 4G or more, depends on Linux version +@item Linux-Alpha @tab 8T (?) +@item Solaris 2.5.1 @tab 2G (possible 4G with patch) +@item Solaris 2.6 @tab 4G +@item Solaris 2.7 Intel @tab 4G +@item Solaris 2.7 ULTRA-SPARC @tab 8T (?) +@end multitable + +On Linux 2.2 you can get bigger tables than 2G by using the LFS patch for +the ext2 file system. On Linux 2.4 there exists also patches for ReiserFS +to get support for big files. + +This means that the table size for @strong{MySQL} is normally limited by +the operating system. + +By default, @strong{MySQL} tables have a maximum size of about 4G. You can +check the maximum table size for a table with the @code{SHOW TABLE STATUS} +command or with the @code{myisamchk -dv table_name}. +@xref{SHOW}. + +If you need bigger tables than 4G (and your operating system supports +this), you should set the @code{AVG_ROW_LENGTH} and @code{MAX_ROWS} +parameter when you create your table. @xref{CREATE TABLE}. You can +also set these later with @code{ALTER TABLE}. @xref{ALTER TABLE}. + +If your big table is going to be read-only, you could use +@code{myisampack} to merge and compress many tables to one. +@code{myisampack} usually compresses a table by at least 50%, so you can +have, in effect, much bigger tables. @xref{myisampack, , +@code{myisampack}}. + +You can go around the operating system file limit for @code{MyISAM} data +files by using the @code{RAID} option. @xref{CREATE TABLE}. + +Another solution can be the included MERGE library, which allows you to +handle a collection of identical tables as one. @xref{MERGE, MERGE +tables}. + +@node Year 2000 compliance, , Table size, MySQL and MySQL AB +@subsection Year 2000 Compliance + +@cindex Year 2000 compliance +@cindex compliance, Y2K +@cindex date functions, Y2K compliance + +@strong{MySQL} itself has no problems with Year 2000 (Y2K) compliance: + +@itemize @bullet +@item +@strong{MySQL} uses Unix time functions and has no problems with dates +until @code{2069}; all 2-digit years are regarded to be in the range +@code{1970} to @code{2069}, which means that if you store @code{01} in a +@code{year} column, @strong{MySQL} treats it as @code{2001}. + +@item +All @strong{MySQL} date functions are stored in one file @file{sql/time.cc} +and coded very carefully to be year 2000-safe. + +@item +In @strong{MySQL} Version 3.22 and later, the new @code{YEAR} column type +can store years @code{0} and @code{1901} to @code{2155} in 1 byte and display +them using 2 or 4 digits. +@end itemize + +You may run into problems with applications that use @strong{MySQL} in a +way that is not Y2K-safe. For example, many old applications store +or manipulate years using 2-digit values (which are ambiguous) rather than +4-digit values. This problem may be compounded by applications that use +values such as @code{00} or @code{99} as ``missing'' value indicators. + +Unfortunately, these problems may be difficult to fix, because different +applications may be written by different programmers, each of whom may +use a different set of conventions and date-handling functions. + +Here is a simple demonstration illustrating that @strong{MySQL} doesn't have +any problems with dates until the year 2030: + +@example +mysql> DROP TABLE IF EXISTS y2k; +Query OK, 0 rows affected (0.01 sec) + +mysql> CREATE TABLE y2k (date date, date_time datetime, time_stamp timestamp); +Query OK, 0 rows affected (0.00 sec) + +mysql> INSERT INTO y2k VALUES + -> ("1998-12-31","1998-12-31 23:59:59",19981231235959), + -> ("1999-01-01","1999-01-01 00:00:00",19990101000000), + -> ("1999-09-09","1999-09-09 23:59:59",19990909235959), + -> ("2000-01-01","2000-01-01 00:00:00",20000101000000), + -> ("2000-02-28","2000-02-28 00:00:00",20000228000000), + -> ("2000-02-29","2000-02-29 00:00:00",20000229000000), + -> ("2000-03-01","2000-03-01 00:00:00",20000301000000), + -> ("2000-12-31","2000-12-31 23:59:59",20001231235959), + -> ("2001-01-01","2001-01-01 00:00:00",20010101000000), + -> ("2004-12-31","2004-12-31 23:59:59",20041231235959), + -> ("2005-01-01","2005-01-01 00:00:00",20050101000000), + -> ("2030-01-01","2030-01-01 00:00:00",20300101000000), + -> ("2050-01-01","2050-01-01 00:00:00",20500101000000); +Query OK, 13 rows affected (0.01 sec) +Records: 13 Duplicates: 0 Warnings: 0 + +mysql> SELECT * FROM y2k; ++------------+---------------------+----------------+ +| date | date_time | time_stamp | ++------------+---------------------+----------------+ +| 1998-12-31 | 1998-12-31 23:59:59 | 19981231235959 | +| 1999-01-01 | 1999-01-01 00:00:00 | 19990101000000 | +| 1999-09-09 | 1999-09-09 23:59:59 | 19990909235959 | +| 2000-01-01 | 2000-01-01 00:00:00 | 20000101000000 | +| 2000-02-28 | 2000-02-28 00:00:00 | 20000228000000 | +| 2000-02-29 | 2000-02-29 00:00:00 | 20000229000000 | +| 2000-03-01 | 2000-03-01 00:00:00 | 20000301000000 | +| 2000-12-31 | 2000-12-31 23:59:59 | 20001231235959 | +| 2001-01-01 | 2001-01-01 00:00:00 | 20010101000000 | +| 2004-12-31 | 2004-12-31 23:59:59 | 20041231235959 | +| 2005-01-01 | 2005-01-01 00:00:00 | 20050101000000 | +| 2030-01-01 | 2030-01-01 00:00:00 | 20300101000000 | +| 2050-01-01 | 2050-01-01 00:00:00 | 00000000000000 | ++------------+---------------------+----------------+ +13 rows in set (0.00 sec) + +@end example + +This shows that the @code{DATE} and @code{DATETIME} types will not +give any problems with future dates (they handle dates until the year +9999). + +The @code{TIMESTAMP} type, which is used to store the current time, has a +range up to only @code{2030-01-01}. @code{TIMESTAMP} has a range of +@code{1970} to @code{2030} on 32-bit machines (signed value). On 64-bit +machines it handles times up to @code{2106} (unsigned value). + +Even though @strong{MySQL} is Y2K-compliant, it is your responsibility to +provide unambiguous input. See @ref{Y2K issues} for @strong{MySQL}'s rules +for dealing with ambiguous date input data (data containing 2-digit year +values). + +@node MySQL Information Sources, Licensing and Support, MySQL and MySQL AB, Introduction +@section MySQL Information Sources + +@cindex manuals, about @strong{MySQL} +@cindex books, about @strong{MySQL} + +@menu +* MySQL-Books:: +* General-SQL:: +* Useful Links:: +* Questions:: +@end menu + +@node MySQL-Books, General-SQL, MySQL Information Sources, MySQL Information Sources +@subsection Books About MySQL While this manual is still the right place for up to date technical information, its primary goal is to contain everything there is to know @@ -1966,432 +2477,8 @@ A complete reference to DBI. @end itemize @* -@node Features, Stability, MySQL-Books, Introduction -@section The Main Features of MySQL - -@cindex main features of MySQL -@cindex features of MySQL - -The following list describes some of the important characteristics -of @strong{MySQL}: - -@c This list is too technical and should be divided into one feature -@c list comparable to commercial competition and a very technical on -@c with max limits (from crash-me) and so on. -@itemize @bullet -@item -Fully multi-threaded using kernel threads. This means it can easily -use multiple CPUs if available. - -@item -C, C++, Eiffel, Java, Perl, PHP, Python and Tcl APIs. @xref{Clients}. - -@item -Works on many different platforms. @xref{Which OS}. - -@item -Many column types: signed/unsigned integers 1, 2, 3, 4, and 8 bytes -long, @code{FLOAT}, @code{DOUBLE}, @code{CHAR}, @code{VARCHAR}, -@code{TEXT}, @code{BLOB}, @code{DATE}, @code{TIME}, @code{DATETIME}, -@code{TIMESTAMP}, @code{YEAR}, @code{SET}, and @code{ENUM} types. -@xref{Column types}. - -@item -Very fast joins using an optimized one-sweep multi-join. - -@item -Full operator and function support in the @code{SELECT} and @code{WHERE} -parts of queries. For example: - -@example -mysql> SELECT CONCAT(first_name, " ", last_name) FROM tbl_name - WHERE income/dependents > 10000 AND age > 30; -@end example - -@item -SQL functions are implemented through a highly optimized class library and -should be as fast as possible! Usually there isn't any memory allocation -at all after query initialization. - -@item -Full support for SQL @code{GROUP BY} and @code{ORDER BY} clauses. Support -for group functions (@code{COUNT()}, @code{COUNT(DISTINCT ...)}, -@code{AVG()}, @code{STD()}, @code{SUM()}, @code{MAX()} and @code{MIN()}). - -@item -Support for @code{LEFT OUTER JOIN} and @code{RIGHT OUTER JOIN} with ANSI -SQL and ODBC syntax. - -@item -You can mix tables from different databases in the same query (as of -Version 3.22). - -@item -A privilege and password system that is very flexible and secure, and -allows host-based verification. Passwords are secure because all -password traffic is encrypted when you connect to a server. - -@item -ODBC (Open-DataBase-Connectivity) support for Win32 (with source). All -ODBC 2.5 functions and many others. For example, you can use MS Access to -connect to your @strong{MySQL} server. @xref{ODBC}. - -@item -Very fast B-tree disk tables with index compression. - -@item -Up to 32 indexes per table are allowed. Each index may consist of 1 to 16 -columns or parts of columns. The maximum index length is 500 bytes (this -may be changed when compiling @strong{MySQL}). An index may use a prefix -of a @code{CHAR} or @code{VARCHAR} field. - -@item -Fixed-length and variable-length records. - -@item -In-memory hash tables which are used as temporary tables. - -@item -Handles large databases. We are using @strong{MySQL} with some -databases that contain 50,000,000 records and we know of users that -uses @strong{MySQL} with 60,000 tables and about 5,000,000,000 rows - -@item -All columns have default values. You can use @code{INSERT} to insert a -subset of a table's columns; those columns that are not explicitly given -values are set to their default values. - -@item -Uses GNU Automake, Autoconf, and Libtool for portability. - -@item -Written in C and C++. Tested with a broad range of different compilers. - -@item -A very fast thread-based memory allocation system. - -@item -No memory leaks. @strong{MySQL} has been tested with Purify, a commercial -memory leakage detector. - -@item -Includes @code{myisamchk}, a very fast utility for table checking, -optimization, and repair. All of the functionality of @code{myisamchk} -is also available through the SQL interface as well. @xref{Maintenance}. - -@item -Full support for several different character sets, including -ISO-8859-1 (Latin1), big5, ujis, and more. For example, the -Scandinavian characters `@ringaccent{a}', `@"a' and `@"o' are allowed -in table and column names. - -@item -All data are saved in the chosen character set. All comparisons for normal -string columns are case insensitive. - -@item -Sorting is done according to the chosen character set (the Swedish -way by default). It is possible to change this when the @strong{MySQL} server -is started up. To see an example of very advanced sorting, look at the -Czech sorting code. @strong{MySQL} supports many different character sets -that can be specified at compile and run time. - -@item -Aliases on tables and columns are allowed as in the SQL92 standard. - -@item -@code{DELETE}, @code{INSERT}, @code{REPLACE}, and @code{UPDATE} return -the number of rows that were changed (affected). It is possible to return -the number of rows matched instead by setting a flag when connecting to the -server. - -@item -Function names do not clash with table or column names. For example, -@code{ABS} is a valid column name. The only restriction is that for a -function call, no spaces are allowed between the function name and the -@samp{(} that follows it. @xref{Reserved words}. - -@item -All @strong{MySQL} programs can be invoked with the @code{--help} or @code{-?} -options to obtain online assistance. - -@item -The server can provide error messages to clients in many languages. -@xref{Languages}. - -@item -Clients may connect to the @strong{MySQL} server using TCP/IP Sockets, -Unix Sockets (Unix), or Named Pipes (NT). - -@item -The @strong{MySQL}-specific @code{SHOW} command can be used to retrieve -information about databases, tables, and indexes. The @code{EXPLAIN} command -can be used to determine how the optimizer resolves a query. -@end itemize - -@cindex stability -@node Stability, Year 2000 compliance, Features, Introduction -@section How Stable Is MySQL? - -This section addresses the questions ``How stable is @strong{MySQL}?'' and -``Can I depend on @strong{MySQL} in this project?'' We will try to clarify -some issues and to answer some of the more important questions that seem to -concern many people. This section has been put together from information -gathered from the mailing list (which is very active in reporting bugs). - -At TcX, @strong{MySQL} has worked without any problems in our projects since -mid-1996. When @strong{MySQL} was released to a wider public, we noticed that -there were some pieces of ``untested code'' that were quickly found by the -new users who made queries in a manner different than our own. Each new -release has had fewer portability problems than the previous one (even though -each has had many new features). - -@c FIX We've been stable for quite a while now. :) (jcole) - -Each release of @strong{MySQL} has been usable, and there have been problems -only when users start to use code from the ``gray zones.'' Naturally, outside -users don't know what the gray zones are; this section attempts to indicate -those that are currently known. The descriptions deal with Version 3.23 -of @strong{MySQL}. All known and reported bugs are fixed in the latest -version, with the exception of the bugs listed in the bugs section, which -are things that are design-related. @xref{Bugs}. - -@strong{MySQL} is written in multiple layers and different independent -modules. These modules are listed below with an indication of how -well-tested each of them is: - -@cindex modules, list of - -@table @strong -@item The ISAM table handler --- Stable -This manages storage and retrieval of all data in @strong{MySQL} Version 3.22 -and earlier. In all @strong{MySQL} releases there hasn't been a single -(reported) bug in this code. The only known way to get a corrupted table -is to kill the server in the middle of an update. Even that is unlikely -to destroy any data beyond rescue, because all data are flushed to disk -between each query. There hasn't been a single bug report about lost data -because of bugs in @strong{MySQL}. - -@cindex ISAM table handler -@cindex storing, data -@cindex retrieving, data -@cindex data, ISAM table handler - -@item The MyISAM table handler --- Stable -This is new in @strong{MySQL} Version 3.23. It's largely based on the ISAM -table code but has a lot of new and very useful features. - -@item The parser and lexical analyser --- Stable -There hasn't been a single reported bug in this system for a long time. - -@item The C client code --- Stable -No known problems. In early Version 3.20 releases, there were some limitations -in the send/receive buffer size. As of Version 3.21, the buffer size is now -dynamic up to a default of 16M. - -@item Standard client programs --- Stable -These include @code{mysql}, @code{mysqladmin}, @code{mysqlshow}, -@code{mysqldump}, and @code{mysqlimport}. - -@item Basic SQL --- Stable -The basic SQL function system and string classes and dynamic memory -handling. Not a single reported bug in this system. - -@item Query optimizer --- Stable - -@item Range optimizer --- Stable - -@item Join optimizer --- Stable - -@item Locking --- Gamma -This is very system-dependent. On some systems there are big problems -using standard OS locking (@code{fcntl()}). In these cases, you should run the -@strong{MySQL} daemon with the @code{--skip-locking} flag. Problems are known -to occur on some Linux systems, and on SunOS when using NFS-mounted file -systems. - -@item Linux threads --- Stable -The major problem found has been with the @code{fcntl()} call, which is -fixed by using the @w{@code{--skip-locking}} option to -@code{mysqld}. Some people have reported lockup problems with Version 0.5. -LinuxThreads will need to be recompiled if you plan to use -1000+ concurrent connections. Although it is possible to run that many -connections with the default LinuxThreads (however, you will never go -above 1021), the default stack spacing of 2 MB makes the application -unstable, and we have been able to reproduce a coredump after creating -1021 idle connections. @xref{Linux}. - -@item Solaris 2.5+ pthreads --- Stable -We use this for all our production work. - -@item MIT-pthreads (Other systems) --- Stable -There have been no reported bugs since Version 3.20.15 and no known bugs since -Version 3.20.16. On some systems, there is a ``misfeature'' where some -operations are quite slow (a 1/20 second sleep is done between each query). -Of course, MIT-pthreads may slow down everything a bit, but index-based -@code{SELECT} statements are usually done in one time frame so there shouldn't -be a mutex locking/thread juggling. - -@item Other thread implementions --- Beta - Gamma -The ports to other systems are still very new and may have bugs, possibly -in @strong{MySQL}, but most often in the thread implementation itself. - -@item @code{LOAD DATA ...}, @code{INSERT ... SELECT} --- Stable -Some people thought they had found bugs here, but these usually have -turned out to be misunderstandings. Please check the manual before reporting -problems! - -@item @code{ALTER TABLE} --- Stable -Small changes in Version 3.22.12. - -@item DBD --- Stable -Now maintained by Jochen Wiedmann -(@email{wiedmann@@neckar-alb.de}). Thanks! - -@item @code{mysqlaccess} --- Stable -Written and maintained by Yves Carlier -(@email{Yves.Carlier@@rug.ac.be}). Thanks! - -@item @code{GRANT} --- Stable -Big changes made in @strong{MySQL} Version 3.22.12. - -@item @strong{MyODBC} (uses ODBC SDK 2.5) --- Gamma -It seems to work well with some programs. - -@item Replication -- Beta / Gamma -We are still working on replication, so don't expect this to be rock -solid yet. On the other hand, some @strong{MySQL} users are already -using this with good results. - -@item BDB Tables -- Beta -The Berkeley DB code is very stable, but we are still improving the interface -between @strong{MySQL} and BDB tables, so it will take some time before this -is as tested as the other table types. - -@item InnoDB Tables -- Beta -This is a recent addition to @code{MySQL}. They appear to work good and -can be used after some initial testing. - -@item Automatic recovery of MyISAM tables - Beta -This only affects the new code that checks if the table was closed properly -on open and executes an automatic check/repair of the table if it wasn't. - -@item MERGE tables -- Beta / Gamma -The usage of keys on @code{MERGE} tables is still not that tested. The -other part of the @code{MERGE} code is quite well tested. - -@item FULLTEXT -- Beta -Text search seems to work, but is still not widely used. - -@end table - -@strong{MySQL AB} provides e-mail support for paying customers, but the -@strong{MySQL} mailing list usually provides answers to common questions. -Bugs are usually fixed right away with a patch; for serious bugs, there is -almost always a new release. - -@cindex Year 2000 compliance -@cindex compliance, Y2K -@cindex date functions, Y2K compliance -@node Year 2000 compliance, General-SQL, Stability, Introduction -@section Year 2000 Compliance - -@strong{MySQL} itself has no problems with Year 2000 (Y2K) compliance: - -@itemize @bullet -@item -@strong{MySQL} uses Unix time functions and has no problems with dates -until @code{2069}; all 2-digit years are regarded to be in the range -@code{1970} to @code{2069}, which means that if you store @code{01} in a -@code{year} column, @strong{MySQL} treats it as @code{2001}. - -@item -All @strong{MySQL} date functions are stored in one file @file{sql/time.cc} -and coded very carefully to be year 2000-safe. - -@item -In @strong{MySQL} Version 3.22 and later, the new @code{YEAR} column type -can store years @code{0} and @code{1901} to @code{2155} in 1 byte and display -them using 2 or 4 digits. -@end itemize - -You may run into problems with applications that use @strong{MySQL} in a -way that is not Y2K-safe. For example, many old applications store -or manipulate years using 2-digit values (which are ambiguous) rather than -4-digit values. This problem may be compounded by applications that use -values such as @code{00} or @code{99} as ``missing'' value indicators. - -Unfortunately, these problems may be difficult to fix, because different -applications may be written by different programmers, each of whom may -use a different set of conventions and date-handling functions. - -Here is a simple demonstration illustrating that @strong{MySQL} doesn't have -any problems with dates until the year 2030: - -@example -mysql> DROP TABLE IF EXISTS y2k; -Query OK, 0 rows affected (0.01 sec) - -mysql> CREATE TABLE y2k (date date, date_time datetime, time_stamp timestamp); -Query OK, 0 rows affected (0.00 sec) - -mysql> INSERT INTO y2k VALUES - -> ("1998-12-31","1998-12-31 23:59:59",19981231235959), - -> ("1999-01-01","1999-01-01 00:00:00",19990101000000), - -> ("1999-09-09","1999-09-09 23:59:59",19990909235959), - -> ("2000-01-01","2000-01-01 00:00:00",20000101000000), - -> ("2000-02-28","2000-02-28 00:00:00",20000228000000), - -> ("2000-02-29","2000-02-29 00:00:00",20000229000000), - -> ("2000-03-01","2000-03-01 00:00:00",20000301000000), - -> ("2000-12-31","2000-12-31 23:59:59",20001231235959), - -> ("2001-01-01","2001-01-01 00:00:00",20010101000000), - -> ("2004-12-31","2004-12-31 23:59:59",20041231235959), - -> ("2005-01-01","2005-01-01 00:00:00",20050101000000), - -> ("2030-01-01","2030-01-01 00:00:00",20300101000000), - -> ("2050-01-01","2050-01-01 00:00:00",20500101000000); -Query OK, 13 rows affected (0.01 sec) -Records: 13 Duplicates: 0 Warnings: 0 - -mysql> SELECT * FROM y2k; -+------------+---------------------+----------------+ -| date | date_time | time_stamp | -+------------+---------------------+----------------+ -| 1998-12-31 | 1998-12-31 23:59:59 | 19981231235959 | -| 1999-01-01 | 1999-01-01 00:00:00 | 19990101000000 | -| 1999-09-09 | 1999-09-09 23:59:59 | 19990909235959 | -| 2000-01-01 | 2000-01-01 00:00:00 | 20000101000000 | -| 2000-02-28 | 2000-02-28 00:00:00 | 20000228000000 | -| 2000-02-29 | 2000-02-29 00:00:00 | 20000229000000 | -| 2000-03-01 | 2000-03-01 00:00:00 | 20000301000000 | -| 2000-12-31 | 2000-12-31 23:59:59 | 20001231235959 | -| 2001-01-01 | 2001-01-01 00:00:00 | 20010101000000 | -| 2004-12-31 | 2004-12-31 23:59:59 | 20041231235959 | -| 2005-01-01 | 2005-01-01 00:00:00 | 20050101000000 | -| 2030-01-01 | 2030-01-01 00:00:00 | 20300101000000 | -| 2050-01-01 | 2050-01-01 00:00:00 | 00000000000000 | -+------------+---------------------+----------------+ -13 rows in set (0.00 sec) - -@end example - -This shows that the @code{DATE} and @code{DATETIME} types will not -give any problems with future dates (they handle dates until the year -9999). - -The @code{TIMESTAMP} type, which is used to store the current time, has a -range up to only @code{2030-01-01}. @code{TIMESTAMP} has a range of -@code{1970} to @code{2030} on 32-bit machines (signed value). On 64-bit -machines it handles times up to @code{2106} (unsigned value). - -Even though @strong{MySQL} is Y2K-compliant, it is your responsibility to -provide unambiguous input. See @ref{Y2K issues} for @strong{MySQL}'s rules -for dealing with ambiguous date input data (data containing 2-digit year -values). - -@cindex manuals, about @strong{MySQL} -@cindex books, about @strong{MySQL} -@node General-SQL, Useful Links, Year 2000 compliance, Introduction -@section General SQL Information and Tutorials +@node General-SQL, Useful Links, MySQL-Books, MySQL Information Sources +@subsection General SQL Information and Tutorials The following book has been recommended by several people on the @strong{MySQL} mailing list: @@ -2419,8 +2506,8 @@ Alameda, CA USA A SQL tutorial is available on the net at http://w3.one.net/~jhoffman/sqltut.htm -@node Useful Links, , General-SQL, Introduction -@section Useful MySQL-related Links +@node Useful Links, Questions, General-SQL, MySQL Information Sources +@subsection Useful MySQL-related Links Apart from the following links, you can find and download a lot of @strong{MySQL} programs, tools and APIs from the @@ -3007,10 +3094,11 @@ require that you show a @strong{MySQL} logo somewhere if you wish your site to be added. It is okay to have it on a ``used tools'' page or something similar. +@node Questions, , Useful Links, MySQL Information Sources +@subsection MySQL Mailing Lists + @cindex reporting, errors @cindex MySQL mailing lists -@node Questions, Licensing and Support, Introduction, Top -@chapter MySQL Mailing Lists @menu * Mailing-list:: The @strong{MySQL} mailing lists @@ -3019,11 +3107,11 @@ something similar. * Answering questions:: Guidelines for answering questions on the mailing list @end menu -This chapter introduces you to the @strong{MySQL} mailing lists, and gives +This section introduces you to the @strong{MySQL} mailing lists, and gives some guidelines as to how to use them. @node Mailing-list, Asking questions, Questions, Questions -@section The MySQL Mailing Lists +@subsubsection The MySQL Mailing Lists @cindex mailing lists @cindex email lists @@ -3167,11 +3255,12 @@ Email @code{subscribe mysql-br your@@email.address} to this list. Email @code{subscribe mysql your@@email.address} to this list. @end table +@node Asking questions, Bug reports, Mailing-list, Questions +@subsubsection Asking Questions or Reporting Bugs + @cindex net etiquette @cindex mailing lists, archive location @cindex searching, MySQL webpages -@node Asking questions, Bug reports, Mailing-list, Questions -@section Asking Questions or Reporting Bugs Before posting a bug report or question, please do the following: @@ -3200,6 +3289,9 @@ local @strong{MySQL} expert. If you still can't find an answer to your question, go ahead and read the next section about how to send mail to @email{mysql@@lists.mysql.com}. +@node Bug reports, Answering questions, Asking questions, Questions +@subsubsection How to Report Bugs or Problems + @cindex bugs, reporting @cindex reporting, bugs @cindex problems, reporting @@ -3207,8 +3299,6 @@ question, go ahead and read the next section about how to send mail to @cindex @code{mysqlbug} script @cindex creating, bug reports @cindex scripts, @code{mysqlbug} -@node Bug reports, Answering questions, Asking questions, Questions -@section How to Report Bugs or Problems Writing a good bug report takes patience, but doing it right the first time saves time for us and for you. A good bug report containing a full @@ -3506,12 +3596,13 @@ it is considered good etiquette to summarize the answers and send the summary to the mailing list so that others may have the benefit of responses you received that helped you solve your problem! +@node Answering questions, , Bug reports, Questions +@subsubsection Guidelines for Answering Question on the Mailing List + @cindex net etiquette @cindex questions, answering @cindex answering questions, etiquette @cindex mailing lists, guidelines -@node Answering questions, , Bug reports, Questions -@section Guidelines for Answering Question on the Mailing List If you consider your answer to have broad interest, you may want to post it to the mailing list instead of replying directly to the individual who @@ -3525,10 +3616,11 @@ obliged to quote the entire original message. Please don't post mail messages from your browser with HTML mode turned on! Many users don't read mail with a browser! +@node Licensing and Support, Compatibility, MySQL Information Sources, Introduction +@section MySQL Licensing and Support + @cindex licensing terms @cindex support terms -@node Licensing and Support, Installing, Questions, Top -@chapter MySQL Licensing and Support @menu * Licensing policy:: @strong{MySQL} licensing policy @@ -3538,7 +3630,7 @@ Many users don't read mail with a browser! * Support:: Types of commercial support @end menu -This chapter describes @strong{MySQL} support and licensing +This section describes @strong{MySQL} support and licensing arrangements: @itemize @bullet @@ -3555,12 +3647,13 @@ arrangements: @item Commercial licensing costs @end itemize +@node Licensing policy, Copyright, Licensing and Support, Licensing and Support +@subsection MySQL Licensing Policy + @cindex licensing policy @cindex technical support, licensing @cindex support, licensing @cindex General Public License, MySQL -@node Licensing policy, Copyright, Licensing and Support, Licensing and Support -@section MySQL Licensing Policy The formal terms of the GPL license can be found at @ref{GPL license}. Basically, our licensing policy and interpretation of the GPL is as follows: @@ -3640,9 +3733,10 @@ is to use the license form on @strong{MySQL}'s secure server at @uref{https://order.mysql.com/}. Other forms of payment are discussed in @ref{Payment information}. -@cindex copyrights @node Copyright, Licensing examples, Licensing policy, Licensing and Support -@section Copyrights Used by MySQL +@subsection Copyrights Used by MySQL + +@cindex copyrights @menu * Copyright changes:: Possible future copyright changes @@ -3686,13 +3780,13 @@ want to help secure its development by purchasing licenses or a support contract. @xref{Support}. @node Copyright changes, , Copyright, Copyright -@subsection Copyright Changes +@subsubsection Copyright Changes Version 3.22 of @strong{MySQL} is still using a more strict license. See the documentation for that version for more information. @node Licensing examples, Cost, Copyright, Licensing and Support -@section Example Licensing Situations +@subsection Example Licensing Situations @menu * Products that use MySQL:: Selling products that use @strong{MySQL} @@ -3713,7 +3807,7 @@ Note that a single @strong{MySQL} license covers any number of CPUs and number of clients that connect to the server in any way. @node Products that use MySQL, ISP, Licensing examples, Licensing examples -@subsection Selling Products that use MySQL +@subsubsection Selling Products that use MySQL To determine whether or not you need a @strong{MySQL} license when selling your application, you should ask whether the proper functioning @@ -3757,7 +3851,7 @@ don't need a license. @end itemize @node ISP, Web server, Products that use MySQL, Licensing examples -@subsection ISP MySQL Services +@subsubsection ISP MySQL Services @cindex ISP services @cindex services, ISP @@ -3782,10 +3876,11 @@ it should give its customers at least read access to the source of the @strong{MySQL} installation so that its customer can verify that it is patched correctly. +@node Web server, , ISP, Licensing examples +@subsubsection Running a Web Server Using MySQL + @cindex web server, running @cindex running, a web server -@node Web server, , ISP, Licensing examples -@subsection Running a Web Server Using MySQL If you use @strong{MySQL} in conjunction with a Web server on Unix, you don't have to pay for a license. @@ -3795,12 +3890,13 @@ This is true even if you run a commercial Web server that uses version yourself. However, in this case we would like you to purchase @strong{MySQL} support, because @strong{MySQL} is helping your enterprise. +@node Cost, Support, Licensing examples, Licensing and Support +@subsection MySQL Licensing and Support Costs + @cindex costs, licensing and support @cindex licensing costs @cindex support costs @cindex prices, licensing and support -@node Cost, Support, Licensing examples, Licensing and Support -@section MySQL Licensing and Support Costs @menu * Payment information:: Payment information @@ -3876,13 +3972,15 @@ Note that as our sales staff is very busy, it may take some time until your request is handled. Our support staff does however always answer promptly to support questions! -@cindex payment information @node Payment information, Contact information, Cost, Cost -@subsection Payment information +@subsubsection Payment information + +@cindex payment information Currently we can take SWIFT payments, checks, or credit cards. Payment should be made to: + @example Postgirot Bank AB 105 06 STOCKHOLM, SWEDEN @@ -3922,15 +4020,17 @@ us'' in the comment field. You can also mail a message to @email{sales@@mysql.com} (@strong{not} @code{mysql@@lists.mysql.com}!) with your company information and ask us to bill you. +@node Contact information, , Payment information, Cost +@subsubsection Contact Information + @cindex contact information @cindex licensing, contact information -@cindex partnering, with MySQL +@cindex advertising, contact information +@cindex employment, contact information +@cindex partnering with MySQL @cindex employment with MySQL @cindex jobs at MySQL -@node Contact information, , Payment information, Cost -@subsection Contact Information - For commercial licensing, please contact the @strong{MySQL} licensing team. The much preferred method is by e-mail to @email{licensing@@mysql.com}. Fax is also possible but handling of @@ -3962,11 +4062,12 @@ For general information inquires, please send e-mail to For questions or comments about the workings or content of the Web site, please send e-mail to @email{webmaster@@mysql.com}. +@node Support, , Cost, Licensing and Support +@subsection Types of Commercial Support + @cindex support, types @cindex types, of support @cindex commercial support, types -@node Support, , Cost, Licensing and Support -@section Types of Commercial Support @menu * Basic email support:: Basic email support @@ -3999,10 +4100,11 @@ if you have login support (2000 EURO), you can expect us to work up to 10 hours to help you with things like this. @end itemize +@node Basic email support, Extended email support, Support, Support +@subsubsection Basic E-mail Support + @cindex email, technical support @cindex technical support, by email -@node Basic email support, Extended email support, Support, Support -@subsection Basic E-mail Support Basic e-mail support is a very inexpensive support option and should be thought of more as a way to support our development of @strong{MySQL} @@ -4071,9 +4173,10 @@ If you want us to help optimize your system, you must upgrade to a higher level of support. @end itemize -@cindex extended email support @node Extended email support, Login support, Basic email support, Support -@subsection Extended E-mail Support +@subsubsection Extended E-mail Support + +@cindex extended email support Extended e-mail support includes everything in basic e-mail support with these additions: @@ -4117,9 +4220,10 @@ TODO List. @xref{TODO}. This will ensure that the features you really need will be implemented sooner than they might be otherwise. @end itemize -@cindex login support @node Login support, Extended login support, Extended email support, Support -@subsection Login Support +@subsubsection Login Support + +@cindex login support Login support includes everything in extended e-mail support with these additions: @@ -4160,7 +4264,7 @@ solving the problem. @end itemize @node Extended login support, Telephone support, Login support, Support -@subsection Extended Login Support +@subsubsection Extended Login Support Extended login support includes everything in login support with these additions: @@ -4197,7 +4301,7 @@ rate that is at least 20 % less than our standard rates. @end itemize @node Telephone support, Table handler support, Extended login support, Support -@subsection Telephone Support +@subsubsection Telephone Support Telephone support includes everything in extended login support with these additions: @@ -4212,10 +4316,11 @@ For non critical problem, you can request a @strong{MySQL} developer to phone back within 48 hours to discuss @code{MySQL} related issues. @end itemize +@node Table handler support, , Telephone support, Support +@subsubsection Support for other table handlers + @cindex support, BDB Tables @cindex support, InnoDB Tables -@node Table handler support, , Telephone support, Support -@subsection Support for other table handlers To get support for @code{BDB} tables, @code{InnoDB} tables you have to pay an additional 30% on the standard support price for each of @@ -4231,9 +4336,2629 @@ timely manner, we can't guarantee a quick solution for any problems you can get with the different table handlers. We will however do our best to help you get the problem solved. +@node Compatibility, Comparisons, Licensing and Support, Introduction +@section How Standards-compatible Is MySQL? -@node Installing, Compatibility, Licensing and Support, Top +@cindex compatibility, with ANSI SQL +@cindex standards compatibility +@cindex extensions, to ANSI SQL +@cindex ANSI SQL92, extensions to + +@menu +* Extensions to ANSI:: @strong{MySQL} extensions to ANSI SQL92 +* Differences from ANSI:: @strong{MySQL} differences compared to ANSI SQL92 +* ANSI mode:: Running @strong{MySQL} in ANSI mode +* Missing functions:: Functionality missing from @strong{MySQL} +* Standards:: What standards does @strong{MySQL} follow? +* Commit-rollback:: How to cope without @code{COMMIT}-@code{ROLLBACK} +* Bugs:: +@end menu + +This section describes how @strong{MySQL} relates to the ANSI SQL standards. +@strong{MySQL} has many extensions to the ANSI SQL standards, and here you +will find out what they are, and how to use them. You will also find +information about functionality missing from @strong{MySQL}, and how to work +around some differences. + +@node Extensions to ANSI, Differences from ANSI, Compatibility, Compatibility +@subsection MySQL Extensions to ANSI SQL92 + +@strong{MySQL} includes some extensions that you probably will not find in +other SQL databases. Be warned that if you use them, your code will not be +portable to other SQL servers. In some cases, you can write code that +includes @strong{MySQL} extensions, but is still portable, by using comments +of the form @code{/*! ... */}. In this case, @strong{MySQL} will parse and +execute the code within the comment as it would any other @strong{MySQL} +statement, but other SQL servers will ignore the extensions. For example: + +@example +SELECT /*! STRAIGHT_JOIN */ col_name FROM table1,table2 WHERE ... +@end example + +If you add a version number after the @code{'!'}, the syntax will only be +executed if the @strong{MySQL} version is equal to or newer than the used +version number: + +@example +CREATE /*!32302 TEMPORARY */ TABLE (a int); +@end example + +The above means that if you have Version 3.23.02 or newer, then @strong{MySQL} +will use the @code{TEMPORARY} keyword. + +@strong{MySQL} extensions are listed below: + +@itemize @bullet +@item +The field types @code{MEDIUMINT}, @code{SET}, @code{ENUM}, and the +different @code{BLOB} and @code{TEXT} types. + +@item +The field attributes @code{AUTO_INCREMENT}, @code{BINARY}, @code{NULL}, +@code{UNSIGNED}, and @code{ZEROFILL}. + +@item +All string comparisons are case insensitive by default, with sort +ordering determined by the current character set (ISO-8859-1 Latin1 by +default). If you don't like this, you should declare your columns with +the @code{BINARY} attribute or use the @code{BINARY} cast, which causes +comparisons to be done according to the ASCII order used on the +@strong{MySQL} server host. + +@item +@strong{MySQL} maps each database to a directory under the @strong{MySQL} +data directory, and tables within a database to filenames in the database +directory. + +This has a few implications: + +@cindex database names, case sensitivity +@cindex table names, case sensitivity +@cindex case sensitivity, of database names +@cindex case sensitivity, of table names + +@itemize @minus + +@item +Database names and table names are case sensitive in @strong{MySQL} on +operating systems that have case-sensitive filenames (like most Unix +systems). @xref{Name case sensitivity}. + +@item +Database, table, index, column, or alias names may begin with a digit +(but may not consist solely of digits). + +@item +You can use standard system commands to backup, rename, move, delete, and copy +tables. For example, to rename a table, rename the @file{.MYD}, @file{.MYI}, +and @file{.frm} files to which the table corresponds. +@end itemize + +@item +In SQL statements, you can access tables from different databases +with the @code{db_name.tbl_name} syntax. Some SQL servers provide +the same functionality but call this @code{User space}. +@strong{MySQL} doesn't support tablespaces as in: +@code{create table ralph.my_table...IN my_tablespace}. + +@item +@code{LIKE} is allowed on numeric columns. + +@item +Use of @code{INTO OUTFILE} and @code{STRAIGHT_JOIN} in a @code{SELECT} +statement. @xref{SELECT, , @code{SELECT}}. + +@item +The @code{SQL_SMALL_RESULT} option in a @code{SELECT} statement. + +@item +@code{EXPLAIN SELECT} to get a description on how tables are joined. + +@item +Use of index names, indexes on a prefix of a field, and use of +@code{INDEX} or @code{KEY} in a @code{CREATE TABLE} +statement. @xref{CREATE TABLE, , @code{CREATE TABLE}}. + +@item +Use of @code{TEMPORARY} or @code{IF NOT EXISTS} with @code{CREATE TABLE}. + +@item +Use of @code{COUNT(DISTINCT list)} where 'list' is more than one element. + +@item +Use of @code{CHANGE col_name}, @code{DROP col_name}, or @code{DROP +INDEX}, @code{IGNORE} or @code{RENAME} in an @code{ALTER TABLE} +statement. @xref{ALTER TABLE, , @code{ALTER TABLE}}. + +@item +Use of @code{RENAME TABLE}. @xref{RENAME TABLE, , @code{RENAME TABLE}}. + +@item +Use of multiple @code{ADD}, @code{ALTER}, @code{DROP}, or @code{CHANGE} +clauses in an @code{ALTER TABLE} statement. + +@item +Use of @code{DROP TABLE} with the keywords @code{IF EXISTS}. + +@item +You can drop multiple tables with a single @code{DROP TABLE} statement. + +@item +The @code{LIMIT} clause of the @code{DELETE} statement. + +@item +The @code{DELAYED} clause of the @code{INSERT} and @code{REPLACE} +statements. + +@item +The @code{LOW_PRIORITY} clause of the @code{INSERT}, @code{REPLACE}, +@code{DELETE}, and @code{UPDATE} statements. + +@cindex Oracle compatibility +@cindex compatibility, with Oracle +@item +Use of @code{LOAD DATA INFILE}. In many cases, this syntax is compatible with +Oracle's @code{LOAD DATA INFILE}. @xref{LOAD DATA, , @code{LOAD DATA}}. + +@item +The @code{ANALYZE TABLE}, @code{CHECK TABLE}, @code{OPTIMIZE TABLE}, and +@code{REPAIR TABLE} statements. + +@item +The @code{SHOW} statement. +@xref{SHOW, , @code{SHOW}}. + +@item +Strings may be enclosed by either @samp{"} or @samp{'}, not just by @samp{'}. + +@item +Use of the escape @samp{\} character. + +@item +The @code{SET OPTION} statement. @xref{SET OPTION, , @code{SET OPTION}}. + +@item +You don't need to name all selected columns in the @code{GROUP BY} part. +This gives better performance for some very specific, but quite normal +queries. +@xref{Group by functions}. + +@item +One can specify @code{ASC} and @code{DESC} with @code{GROUP BY}. + +@item +To make it easier for users who come from other SQL environments, +@strong{MySQL} supports aliases for many functions. For example, all +string functions support both ANSI SQL syntax and ODBC syntax. + +@item +@strong{MySQL} understands the @code{||} and @code{&&} operators to mean +logical OR and AND, as in the C programming language. In @strong{MySQL}, +@code{||} and @code{OR} are synonyms, as are @code{&&} and @code{AND}. +Because of this nice syntax, @strong{MySQL} doesn't support +the ANSI SQL @code{||} operator for string concatenation; use +@code{CONCAT()} instead. Because @code{CONCAT()} takes any number +of arguments, it's easy to convert use of the @code{||} operator to +@strong{MySQL}. + +@item +@code{CREATE DATABASE} or @code{DROP DATABASE}. +@xref{CREATE DATABASE, , @code{CREATE DATABASE}}. + +@cindex PostgreSQL compatibility +@cindex compatibility, with PostgreSQL +@item +The @code{%} operator is a synonym for @code{MOD()}. That is, +@code{N % M} is equivalent to @code{MOD(N,M)}. @code{%} is supported +for C programmers and for compatibility with PostgreSQL. + +@item +The @code{=}, @code{<>}, @code{<=} ,@code{<}, @code{>=},@code{>}, +@code{<<}, @code{>>}, @code{<=>}, @code{AND}, @code{OR}, or @code{LIKE} +operators may be used in column comparisons to the left of the +@code{FROM} in @code{SELECT} statements. For example: + +@example +mysql> SELECT col1=1 AND col2=2 FROM tbl_name; +@end example + +@item +The @code{LAST_INSERT_ID()} function. +@xref{mysql_insert_id, , @code{mysql_insert_id()}}. + +@item +The @code{REGEXP} and @code{NOT REGEXP} extended regular expression +operators. + +@item +@code{CONCAT()} or @code{CHAR()} with one argument or more than two +arguments. (In @strong{MySQL}, these functions can take any number of +arguments.) + +@item The @code{BIT_COUNT()}, @code{CASE}, @code{ELT()}, +@code{FROM_DAYS()}, @code{FORMAT()}, @code{IF()}, @code{PASSWORD()}, +@code{ENCRYPT()}, @code{md5()}, @code{ENCODE()}, @code{DECODE()}, +@code{PERIOD_ADD()}, @code{PERIOD_DIFF()}, @code{TO_DAYS()}, or +@code{WEEKDAY()} functions. + +@item +Use of @code{TRIM()} to trim substrings. ANSI SQL only supports removal +of single characters. + +@item +The @code{GROUP BY} functions @code{STD()}, @code{BIT_OR()}, and +@code{BIT_AND()}. + +@item +Use of @code{REPLACE} instead of @code{DELETE} + @code{INSERT}. +@xref{REPLACE, , @code{REPLACE}}. + +@item +The @code{FLUSH flush_option} statement. + +@item +The possibility to set variables in a statement with @code{:=}: +@example +SELECT @@a:=SUM(total),@@b=COUNT(*),@@a/@@b AS avg FROM test_table; +SELECT @@t1:=(@@t2:=1)+@@t3:=4,@@t1,@@t2,@@t3; +@end example + +@end itemize + +@node Differences from ANSI, ANSI mode, Extensions to ANSI, Compatibility +@subsection MySQL Differences Compared to ANSI SQL92 + +We try to make @strong{MySQL} follow the ANSI SQL standard and the +ODBC SQL standard, but in some cases @strong{MySQL} does some things +differently: + +@itemize @bullet +@item +@code{--} is only a comment if followed by a white space. @xref{Missing +comments}. +@item +For @code{VARCHAR} columns, trailing spaces are removed when the value is +stored. @xref{Bugs}. +@item +In some cases, @code{CHAR} columns are silently changed to @code{VARCHAR} +columns. @xref{Silent column changes}. +@item +Privileges for a table are not automatically revoked when you delete a +table. You must explicitly issue a @code{REVOKE} to revoke privileges for +a table. @xref{GRANT, , @code{GRANT}}. +@item +@code{NULL AND FALSE} will evaluate to @code{NULL} and not to @code{FALSE}. +This is because we don't think it's good to have to evaluate a lot of +extra conditions in this case. +@end itemize + +@node ANSI mode, Missing functions, Differences from ANSI, Compatibility +@subsection Running MySQL in ANSI Mode + +@cindex running, ANSI mode +@cindex ANSI mode, running + +If you start @code{mysqld} with the @code{--ansi} option, the following behavior +of @strong{MySQL} changes: + +@itemize @bullet +@item +@code{||} is string concatenation instead of @code{OR}. +@item +You can have any number of spaces between a function name and the @samp{(}. +This forces all function names to be treated as reserved words. +@item +@samp{"} will be an identifier quote character (like the @strong{MySQL} +@samp{`} quote character) and not a string quote character. +@item +@code{REAL} will be a synonym for @code{FLOAT} instead of a synonym of +@code{DOUBLE}. +@item +The default transaction isolation level is @code{SERIALIZABLE}. +@xref{SET TRANSACTION}. +@end itemize + +@node Missing functions, Standards, ANSI mode, Compatibility +@subsection Functionality Missing from MySQL + +@cindex missing functionality +@cindex functionality, missing + +The following functionality is missing in the current version of +@strong{MySQL}. For a prioritized list indicating when new extensions +may be added to @strong{MySQL}, you should consult +@uref{http://www.mysql.com/documentation/manual.php?section=TODO, the +online @strong{MySQL} TODO list}. That is the latest version of the TODO +list in this manual. @xref{TODO}. + +@menu +* Missing Sub-selects:: Sub-selects +* Missing SELECT INTO TABLE:: @code{SELECT INTO TABLE} +* Missing Transactions:: Transactions +* Missing Triggers:: Triggers +* Missing Foreign Keys:: Foreign Keys +* Broken Foreign KEY:: +* Missing Views:: Views +* Missing comments:: @samp{--} as the start of a comment +@end menu + +@node Missing Sub-selects, Missing SELECT INTO TABLE, Missing functions, Missing functions +@subsubsection Sub-selects + +@cindex sub-selects + +The following will not yet work in @strong{MySQL}: + +@example +SELECT * FROM table1 WHERE id IN (SELECT id FROM table2); +SELECT * FROM table1 WHERE id NOT IN (SELECT id FROM table2); +SELECT * FROM table1 WHERE NOT EXISTS (SELECT id FROM table2 where table1.id=table2.id); +@end example + +However, in many cases you can rewrite the query without a sub-select: + +@example +SELECT table1.* FROM table1,table2 WHERE table1.id=table2.id; +SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.id=table2.id where table2.id IS NULL +@end example + +For more complicated subqueries you can often create temporary tables +to hold the subquery. In some cases, however this option will not +work. The most frequently encountered of these cases arises with +@code{DELETE} statements, for which standard SQL does not support joins +(except in sub-selects). For this situation there are two options +available until subqueries are supported by @strong{MySQL}. + +The first option is to use a procedural programming language (such as +Perl or PHP) to submit a @code{SELECT} query to obtain the primary keys +for the records to be deleted, and then use these values to construct +the @code{DELETE} statement (@code{DELETE FROM ... WHERE ... IN (key1, +key2, ...)}). + +The second option is to use interactive SQL to contruct a set of +@code{DELETE} statements automatically, using the @strong{MySQL} +extension @code{CONCAT()} (in lieu of the standard @code{||} operator). +For example: + +@example +SELECT CONCAT('DELETE FROM tab1 WHERE pkid = ', tab1.pkid, ';') + FROM tab1, tab2 + WHERE tab1.col1 = tab2.col2; +@end example + +You can place this query in a script file and redirect input from it to +the @code{mysql} command-line interpreter, piping its output back to a +second instance of the interpreter: + +@example +prompt> mysql --skip-column-names mydb < myscript.sql | mysql mydb +@end example + +@strong{MySQL} only supports @code{INSERT ... SELECT ...} and +@code{REPLACE ... SELECT ...} Independent sub-selects will probably +be available in Version 4.0. You can now use the function @code{IN()} in +other contexts, however. + +@node Missing SELECT INTO TABLE, Missing Transactions, Missing Sub-selects, Missing functions +@subsubsection @code{SELECT INTO TABLE} + +@findex SELECT INTO TABLE + +@strong{MySQL} doesn't yet support the Oracle SQL extension: +@code{SELECT ... INTO TABLE ...}. @strong{MySQL} supports instead the +ANSI SQL syntax @code{INSERT INTO ... SELECT ...}, which is basically +the same thing. @xref{INSERT SELECT}. + +@example +INSERT INTO tblTemp2 (fldID) SELECT tblTemp1.fldOrder_ID FROM tblTemp1 WHERE +tblTemp1.fldOrder_ID > 100; +@end example + +Alternatively, you can use @code{SELECT INTO OUTFILE...} or @code{CREATE +TABLE ... SELECT} to solve your problem. + +@node Missing Transactions, Missing Triggers, Missing SELECT INTO TABLE, Missing functions +@subsubsection Transactions + +@cindex transactions, support + +As @strong{MySQL} does nowadays support transactions, the following +discussion is only valid if you are only using the non-transaction-safe +table types. @xref{COMMIT}. + +The question is often asked, by the curious and the critical, ``Why is +@strong{MySQL} not a transactional database?'' or ``Why does @strong{MySQL} +not support transactions?'' + +@strong{MySQL} has made a conscious decision to support another paradigm +for data integrity, ``atomic operations.'' It is our thinking and +experience that atomic operations offer equal or even better integrity +with much better performance. We, nonetheless, appreciate and understand +the transactional database paradigm and plan, within the next few releases, +to introduce transaction-safe tables on a per table basis. We will be +giving our users the possibility to decide if they need the speed of +atomic operations or if they need to use transactional features in their +applications. + +How does one use the features of @strong{MySQL} to maintain rigorous integrity +and how do these features compare with the transactional paradigm? + +First, in the transactional paradigm, if your applications are written +in a way that is dependent on the calling of ``rollback'' instead of +``commit'' in critical situations, then transactions are more +convenient. Moreover, transactions ensure that unfinished updates or +corrupting activities are not committed to the database; the server is +given the opportunity to do an automatic rollback and your database is +saved. + +@strong{MySQL}, in almost all cases, allows you to solve for potential +problems by including simple checks before updates and by running simple +scripts that check the databases for inconsistencies and automatically +repair or warn if such occurs. Note that just by using the +@strong{MySQL} log or even adding one extra log, one can normally fix +tables perfectly with no data integrity loss. + +Moreover, fatal transactional updates can be rewritten to be +atomic. In fact,we will go so far as to say that all integrity problems +that transactions solve can be done with @code{LOCK TABLES} or atomic updates, +ensuring that you never will get an automatic abort from the database, +which is a common problem with transactional databases. + +Not even transactions can prevent all loss if the server goes down. In +such cases even a transactional system can lose data. The difference +between different systems lies in just how small the time-lap is where +they could lose data. No system is 100% secure, only ``secure +enough.'' Even Oracle, reputed to be the safest of transactional +databases, is reported to sometimes lose data in such situations. + +To be safe with @strong{MySQL}, you only need to have backups and have +the update logging turned on. With this you can recover from any +situation that you could with any transactional database. It is, of +course, always good to have backups, independent of which database you +use. + +The transactional paradigm has its benefits and its drawbacks. Many +users and application developers depend on the ease with which they can +code around problems where an abort appears to be, or is necessary, and they +may have to do a little more work with @strong{MySQL} to either think +differently or write more. If you are new to the atomic operations +paradigm, or more familiar or more comfortable with transactions, do not +jump to the conclusion that @strong{MySQL} has not addressed these +issues. Reliability and integrity are foremost in our minds. Recent +estimates indicate that there are more than 1,000,000 @code{mysqld} servers +currently running, many of which are in production environments. We +hear very, very seldom from our users that they have lost any data, and +in almost all of those cases user error is involved. This is, in our +opinion, the best proof of @strong{MySQL}'s stability and reliability. + +Lastly, in situations where integrity is of highest importance, +@strong{MySQL}'s current features allow for transaction-level or better +reliability and integrity. If you lock tables with @code{LOCK TABLES}, all +updates will stall until any integrity checks are made. If you only obtain +a read lock (as opposed to a write lock), then reads and inserts are +still allowed to happen. The new inserted records will not be seen by +any of the clients that have a @code{READ} lock until they release their read +locks. With @code{INSERT DELAYED} you can queue inserts into a local queue, +until the locks are released, without having the client wait for the insert +to complete. @xref{INSERT DELAYED}. + +``Atomic,'' in the sense that we mean it, is nothing magical. It only means +that you can be sure that while each specific update is running, no other +user can interfere with it, and there will never be an automatic +rollback (which can happen on transaction based systems if you are not +very careful). @strong{MySQL} also guarantees that there will not be +any dirty reads. You can find some example of how to write atomic updates +in the commit-rollback section. @xref{Commit-rollback}. + +We have thought quite a bit about integrity and performance, and we +believe that our atomic operations paradigm allows for both high +reliability and extremely high performance, on the order of three to +five times the speed of the fastest and most optimally tuned of +transactional databases. We didn't leave out transactions because they +are hard to do. The main reason we went with atomic operations as +opposed to transactions is that by doing this we could apply many speed +optimizations that would not otherwise have been possible. + +Many of our users who have speed foremost in their minds are not at all +concerned about transactions. For them transactions are not an +issue. For those of our users who are concerned with or have wondered +about transactions vis-a-vis @strong{MySQL}, there is a ``@strong{MySQL} +way'' as we have outlined above. For those where safety is more +important than speed, we recommend them to use the @code{BDB}, +or @code{InnoDB} tables for all their critical data. @xref{Table types}. + +One final note: We are currently working on a safe replication schema +that we believe to be better than any commercial replication system we +know of. This system will work most reliably under the atomic +operations, non-transactional, paradigm. Stay tuned. + +@node Missing Triggers, Missing Foreign Keys, Missing Transactions, Missing functions +@subsubsection Stored Procedures and Triggers + +@cindex stored procedures and triggers, defined +@cindex procedures, stored +@cindex triggers, stored + + +A stored procedure is a set of SQL commands that can be compiled and stored +in the server. Once this has been done, clients don't need to keep reissuing +the entire query but can refer to the stored procedure. This provides better +performance because the query has to be parsed only once, and less information +needs to be sent between the server and the client. You can also raise the +conceptual level by having libraries of functions in the server. + +A trigger is a stored procedure that is invoked when a particular event +occurs. For example, you can install a stored procedure that is triggered +each time a record is deleted from a transaction table and that automatically +deletes the corresponding customer from a customer table when all his +transactions are deleted. + +The planned update language will be able to +handle stored procedures, but without triggers. Triggers usually slow +down everything, even queries for which they are not needed. + +To see when @strong{MySQL} might get stored procedures, see @ref{TODO}. + +@node Missing Foreign Keys, Broken Foreign KEY, Missing Triggers, Missing functions +@subsubsection Foreign Keys + +@cindex foreign keys +@cindex keys, foreign + +Note that foreign keys in SQL are not used to join tables, but are used +mostly for checking referential integrity (foreign key constraints). If +you want to get results from multiple tables from a @code{SELECT} +statement, you do this by joining tables: + +@example +SELECT * from table1,table2 where table1.id = table2.id; +@end example + +@xref{JOIN, , @code{JOIN}}. @xref{example-Foreign keys}. + +The @code{FOREIGN KEY} syntax in @strong{MySQL} exists only for compatibility +with other SQL vendors' @code{CREATE TABLE} commands; it doesn't do +anything. The @code{FOREIGN KEY} syntax without @code{ON DELETE ...} is +mostly used for documentation purposes. Some ODBC applications may use this +to produce automatic @code{WHERE} clauses, but this is usually easy to +override. @code{FOREIGN KEY} is sometimes used as a constraint check, but +this check is unnecessary in practice if rows are inserted into the tables in +the right order. @strong{MySQL} only supports these clauses because some +applications require them to exist (regardless of whether or not they +work). + +In @strong{MySQL}, you can work around the problem of @code{ON DELETE +...} not being implemented by adding the appropriate @code{DELETE} statement to +an application when you delete records from a table that has a foreign key. +In practice this is as quick (in some cases quicker) and much more portable +than using foreign keys. + +In the near future we will extend the @code{FOREIGN KEY} implementation so +that at least the information will be saved in the table specification file +and may be retrieved by @code{mysqldump} and ODBC. At a later stage we will +implement the foreign key constraints for application that can't easily be +coded to avoid them. + +@menu +* Broken Foreign KEY:: Reasons NOT to use foreign keys constraints +@end menu + +@node Broken Foreign KEY, Missing Views, Missing Foreign Keys, Missing functions +@subsubsection Reasons NOT to Use Foreign Keys constraints + +@cindex foreign keys, reasons not to use + +There are so many problems with foreign key constraints that we don't +know where to start: + +@itemize @bullet +@item +Foreign key constraints make life very complicated, because the foreign +key definitions must be stored in a database and implementing them would +destroy the whole ``nice approach'' of using files that can be moved, +copied, and removed. + +@item +The speed impact is terrible for @code{INSERT} and @code{UPDATE} +statements, and in this case almost all @code{FOREIGN KEY} constraint +checks are useless because you usually insert records in the right +tables in the right order, anyway. + +@item +There is also a need to hold locks on many more tables when updating one +table, because the side effects can cascade through the entire database. It's +MUCH faster to delete records from one table first and subsequently delete +them from the other tables. + +@item +You can no longer restore a table by doing a full delete from the table +and then restoring all records (from a new source or from a backup). + +@item +If you use foreign key constraints you can't dump and restore tables +unless you do so in a very specific order. + +@item +It's very easy to do ``allowed'' circular definitions that make the +tables impossible to re-create each table with a single create statement, +even if the definition works and is usable. + +@item +It's very easy to overlook @code{FOREIGN KEY ... ON DELETE} rules when +one codes an application. It's not unusual that one loses a lot of +important information just because a wrong or misused @code{ON DELETE} rule. +@end itemize + +The only nice aspect of @code{FOREIGN KEY} is that it gives ODBC and some +other client programs the ability to see how a table is connected and to use +this to show connection diagrams and to help in building applications. + +@strong{MySQL} will soon store @code{FOREIGN KEY} definitions so that a +client can ask for and receive an answer about how the original +connection was made. The current @file{.frm} file format does not have +any place for it. At a later stage we will implement the foreign key +constraints for application that can't easily be coded to avoid them. + +@node Missing Views, Missing comments, Broken Foreign KEY, Missing functions +@subsubsection Views + +@cindex views + +@strong{MySQL} doesn't yet support views, but we plan to implement these +to about 4.1. + +Views are mostly useful for letting users access a set of relations as one +table (in read-only mode). Many SQL databases don't allow one to update +any rows in a view, but you have to do the updates in the separate tables. + +As @strong{MySQL} is mostly used in applications and on web system where +the application writer has full control on the database usage, most of +our users haven't regarded views to be very important. (At least no one +has been interested enough in this to be prepared to finance the +implementation of views). + +One doesn't need views in @strong{MySQL} to restrict access to columns +as @strong{MySQL} has a very sophisticated privilege +system. @xref{Privilege system}. + +@node Missing comments, , Missing Views, Missing functions +@subsubsection @samp{--} as the Start of a Comment + +@cindex comments, starting +@cindex starting, comments + +Some other SQL databases use @samp{--} to start comments. @strong{MySQL} +has @samp{#} as the start comment character, even if the @code{mysql} +command-line tool removes all lines that start with @samp{--}. +You can also use the C comment style @code{/* this is a comment */} with +@strong{MySQL}. +@xref{Comments}. + +@strong{MySQL} Version 3.23.3 and above supports the @samp{--} comment style +only if the comment is followed by a space. This is because this +degenerate comment style has caused many problems with automatically +generated SQL queries that have used something like the following code, +where we automatically insert the value of the payment for +@code{!payment!}: + +@example +UPDATE tbl_name SET credit=credit-!payment! +@end example + +What do you think will happen when the value of @code{payment} is negative? + +Because @code{1--1} is legal in SQL, we think it is terrible that +@samp{--} means start comment. + +In @strong{MySQL} Version 3.23 you can, however, use: +@code{1-- This is a comment} + +The following discussion only concerns you if you are running a @strong{MySQL} +version earlier than Version 3.23: + +If you have a SQL program in a text file that contains @samp{--} comments +you should use: + +@example +shell> replace " --" " #" < text-file-with-funny-comments.sql \ + | mysql database +@end example + +instead of the usual: + +@example +shell> mysql database < text-file-with-funny-comments.sql +@end example + +You can also edit the command file ``in place'' to change the @samp{--} +comments to @samp{#} comments: + +@example +shell> replace " --" " #" -- text-file-with-funny-comments.sql +@end example + +Change them back with this command: + +@example +shell> replace " #" " --" -- text-file-with-funny-comments.sql +@end example + +@node Standards, Commit-rollback, Missing functions, Compatibility +@subsection What Standards Does MySQL Follow? + +Entry level SQL92. ODBC levels 0-2. + +@node Commit-rollback, Bugs, Standards, Compatibility +@subsection How to Cope Without @code{COMMIT}/@code{ROLLBACK} + +@findex COMMIT +@findex ROLLBACK +@cindex transaction-safe tables +@cindex tables, updating +@cindex updating, tables +@cindex @code{BDB} tables +@cindex @code{InnoDB} tables + +The following mostly applies only for @code{ISAM}, @code{MyISAM}, and +@code{HEAP} tables. If you only use transaction-safe tables (@code{BDB}, +or @code{InnoDB} tables) in an an update, you can do +@code{COMMIT} and @code{ROLLBACK} also with @strong{MySQL}. +@xref{COMMIT}. + +The problem with handling @code{COMMIT}-@code{ROLLBACK} efficiently with +the above table types would require a completely different table layout +than @strong{MySQL} uses today. The table type would also need extra +threads that do automatic cleanups on the tables, and the disk usage +would be much higher. This would make these table types about 2-4 times +slower than they are today. + +For the moment, we prefer implementing the SQL server language (something +like stored procedures). With this you would very seldom really need +@code{COMMIT}-@code{ROLLBACK.} This would also give much better performance. + +Loops that need transactions normally can be coded with the help of +@code{LOCK TABLES}, and you don't need cursors when you can update records +on the fly. + +We at TcX had a greater need for a real fast database than a 100% +general database. Whenever we find a way to implement these features without +any speed loss, we will probably do it. For the moment, there are many more +important things to do. Check the TODO for how we prioritize things at +the moment. (Customers with higher levels of support can alter this, so +things may be reprioritized.) + +The current problem is actually @code{ROLLBACK}. Without +@code{ROLLBACK}, you can do any kind of @code{COMMIT} action with +@code{LOCK TABLES}. To support @code{ROLLBACK} with the above table +types, @strong{MySQL} would have to be changed to store all old records +that were updated and revert everything back to the starting point if +@code{ROLLBACK} was issued. For simple cases, this isn't that hard to do +(the current @code{isamlog} could be used for this purpose), but it +would be much more difficult to implement @code{ROLLBACK} for +@code{ALTER/DROP/CREATE TABLE}. + +To avoid using @code{ROLLBACK}, you can use the following strategy: + +@enumerate +@item +Use @code{LOCK TABLES ...} to lock all the tables you want to access. +@item +Test conditions. +@item +Update if everything is okay. +@item +Use @code{UNLOCK TABLES} to release your locks. +@end enumerate + +This is usually a much faster method than using transactions with possible +@code{ROLLBACK}s, although not always. The only situation this solution +doesn't handle is when someone kills the threads in the middle of an +update. In this case, all locks will be released but some of the updates may +not have been executed. + +You can also use functions to update records in a single operation. +You can get a very efficient application by using the following techniques: + +@itemize @bullet +@item Modify fields relative to their current value. +@item Update only those fields that actually have changed. +@end itemize + +For example, when we are doing updates to some customer information, we +update only the customer data that has changed and test only that none of +the changed data, or data that depend on the changed data, has changed +compared to the original row. The test for changed data is done with the +@code{WHERE} clause in the @code{UPDATE} statement. If the record wasn't +updated, we give the client a message: "Some of the data you have changed +have been changed by another user". Then we show the old row versus the new +row in a window, so the user can decide which version of the customer record +he should use. + +This gives us something that is similar to column locking but is actually +even better, because we only update some of the columns, using values that +are relative to their current values. This means that typical @code{UPDATE} +statements look something like these: + +@example +UPDATE tablename SET pay_back=pay_back+'relative change'; + +UPDATE customer + SET + customer_date='current_date', + address='new address', + phone='new phone', + money_he_owes_us=money_he_owes_us+'new_money' + WHERE + customer_id=id AND address='old address' AND phone='old phone'; +@end example + +As you can see, this is very efficient and works even if another client has +changed the values in the @code{pay_back} or @code{money_he_owes_us} columns. + +@findex mysql_insert_id() +@findex LAST_INSERT_ID() +In many cases, users have wanted @code{ROLLBACK} and/or @code{LOCK +TABLES} for the purpose of managing unique identifiers for some tables. This +can be handled much more efficiently by using an @code{AUTO_INCREMENT} column +and either the SQL function @code{LAST_INSERT_ID()} or the C API function +@code{mysql_insert_id()}. @xref{mysql_insert_id, , @code{mysql_insert_id()}}. + +@cindex rows, locking +At @strong{MySQL AB}, we have never had any need for row-level locking +because we have always been able to code around it. Some cases really need +row locking, but they are very few. If you want row-level locking, you +can use a flag column in the table and do something like this: + +@example +UPDATE tbl_name SET row_flag=1 WHERE id=ID; +@end example + +@strong{MySQL} returns 1 for the number of affected rows if the row was +found and @code{row_flag} wasn't already 1 in the original row. + +You can think of it as @strong{MySQL} changed the above query to: + +@example +UPDATE tbl_name SET row_flag=1 WHERE id=ID and row_flag <> 1; +@end example + +@node Bugs, , Commit-rollback, Compatibility +@subsection Known errors and design deficiencies in MySQL + +@cindex bugs, known +@cindex errors, known +@cindex design, issues +@cindex known errors + +The following problems are known and have a very high priority to get +fixed: + +@itemize @bullet +@item +@code{ANALYZE TABLE} on a BDB table may in some case make the table +unusable until one has restarted @code{mysqld}. When this happens you will +see errors like the following in the @strong{MySQL} error file: + +@example +001207 22:07:56 bdb: log_flush: LSN past current end-of-log +@end example + +@item +Don't execute @code{ALTER TABLE} on a @code{BDB} table on which you are +running not completed multi-statement transactions. (The transaction +will probably be ignored). + +@item +@code{ANALYZE TABLE}, @code{OPTIMIZE TABLE} and @code{REPAIR TABLE} may +cause problems on tables for which you are using @code{INSERT DELAYED}. + +@item +Doing a @code{LOCK TABLE ..} and @code{FLUSH TABLES ..} doesn't +guarantee that there isn't a half-finished transaction in progress on the +table. + +@item +BDB tables are a bit slow to open. If you have many BDB tables in a +database, it will take a long time to use the @code{mysql} client on the +database if you are not using the @code{-A} option or if you are using +@code{rehash}. This is especially notable when you have a big table +cache. + +@item +Th current replication protocol cannot deal with @code{LOAD DATA INFILE} +and line terminator characters of more than 1 character. +@end itemize + +The following problems are known and will be fixed in due time: + +@itemize @bullet +@item +For the moment @code{MATCH} only works with @code{SELECT} statements. +@item +When using @code{SET CHARACTER SET}, one can't use translated +characters in database, table and column names. +@item +@code{DELETE FROM merge_table} used without a @code{WHERE} +will only clear the mapping for the table, not delete everything in the +mapped tables +@item +You cannot build in another directory when using +MIT-pthreads. Because this requires changes to MIT-pthreads, we are not +likely to fix this. +@item +@code{BLOB} values can't ``reliably'' be used in @code{GROUP BY} or +@code{ORDER BY} or @code{DISTINCT}. Only the first @code{max_sort_length} +bytes (default 1024) are used when comparing @code{BLOB}bs in these cases. +This can be changed with the @code{-O max_sort_length} option to +@code{mysqld}. A workaround for most cases is to use a substring: +@code{SELECT DISTINCT LEFT(blob,2048) FROM tbl_name}. +@item +Calculation is done with @code{BIGINT} or @code{DOUBLE} (both are +normally 64 bits long). It depends on the function which precision one +gets. The general rule is that bit functions are done with @code{BIGINT} +precision, @code{IF}, and @code{ELT()} with @code{BIGINT} or @code{DOUBLE} +precision and the rest with @code{DOUBLE} precision. One should try to +avoid using bigger unsigned long long values than 63 bits +(9223372036854775807) for anything else than bit fields! +@item +All string columns, except @code{BLOB} and @code{TEXT} columns, automatically +have all trailing spaces removed when retrieved. For @code{CHAR} types this +is okay, and may be regarded as a feature according to ANSI SQL92. The bug is +that in @strong{MySQL}, @code{VARCHAR} columns are treated the same way. +@item +You can only have up to 255 @code{ENUM} and @code{SET} columns in one table. +@item +@code{safe_mysqld} re-directs all messages from @code{mysqld} to the +@code{mysqld} log. One problem with this is that if you execute +@code{mysqladmin refresh} to close and reopen the log, +@code{stdout} and @code{stderr} are still redirected to the old log. +If you use @code{--log} extensively, you should edit @code{safe_mysqld} to +log to @file{'hostname'.err} instead of @file{'hostname'.log} so you can +easily reclaim the space for the old log by deleting the old one and +executing @code{mysqladmin refresh}. +@item +In the @code{UPDATE} statement, columns are updated from left to right. +If you refer to an updated column, you will get the updated value instead of the +original value. For example: +@example +mysql> UPDATE tbl_name SET KEY=KEY+1,KEY=KEY+1; +@end example +will update @code{KEY} with @code{2} instead of with @code{1}. +@item +You can't use temporary tables more than once in the same query. +For example, the following doesn't work. + +@example +select * from temporary_table, temporary_table as t2; +@end example + +@item +@code{RENAME} doesn't work with @code{TEMPORARY} tables. + +@item +The optimizer may handle @code{DISTINCT} differently if you are using +'hidden' columns in a join or not. In a join, hidden columns are +counted as part of the result (even if they are not shown) while in +normal queries hidden columns doesn't participate in the @code{DISTINCT} +comparison. We will probably change this in the future to never compare +the hidden columns when executing @code{DISTINCT} + +An example of this is: + +@example +SELECT DISTINCT mp3id FROM band_downloads WHERE userid = 9 ORDER BY id +DESC; + +and + +SELECT DISTINCT band_downloads.mp3id, FROM band_downloads,band_mp3 +WHERE band_downloads.userid = 9 AND band_mp3.id = band_downloads.mp3id +ORDER BY band_downloads.id DESC; +@end example + +In the second case you may in @strong{MySQL} 3.23.x get two identical rows +in the result set (because the hidden 'id' column may differ). + +Note that the this only happens for queries where you don't have the +ORDER BY columns in the result, something that is you are not allowed +to do in ANSI SQL. + +@item +Because @strong{MySQL} allows you to work with table types that doesn't +support transactions (and thus can't @code{rollback} data) some things +behaves a little different in @strong{MySQL} than in other SQL servers: +(This is just to ensure that @strong{MySQL} never need to do a rollback +for a SQL command). This may be a little awkward at times as column +Because @strong{MySQL} allows you to work with table types that don't +support transactions, and thus can't @code{rollback} data, some things +behave a little differently in @strong{MySQL} than in other SQL servers. +This is just to ensure that @strong{MySQL} never need to do a rollback +for a SQL command. This may be a little awkward at times as column +values must be checked in the application, but this will actually give +you a nice speed increase as it allows @strong{MySQL} to do some +optimizations that otherwise would be very hard to do. + +If you set a column to an incorrect value, @strong{MySQL} will, instead of +doing a rollback, store the @code{best possible value} in the column: + +@itemize @bullet +@item +If you try to store a value outside the range in a numerical column, +@strong{MySQL} will instead store the smallest or biggest possible value in +the column. +@item +If you try to store a string that doesn't start with a number into a +numerical column, @strong{MySQL} will store 0 into it. +@item +If you try to store @code{NULL} into a column that doesn't take +@code{NULL} values, @strong{MySQL} will store 0 or @code{''} (empty +string) in it instead. (This behavior can, however, be changed with the +-DDONT_USE_DEFAULT_FIELDS compile option). +@item +@strong{MySQL} allows you to store some wrong date values into +@code{DATE} and @code{DATETIME} columns. (Like 2000-02-31 or 2000-02-00). +If the date is totally wrong, @strong{MySQL} will store the special +0000-00-00 date value in the column. +@item +If you set an @code{enum} to an unsupported value, it will be set to +the error value 'empty string', with numeric value 0. +@end itemize + +@item +If you execute a @code{PROCEDURE} on a query that returns an empty set, +in some cases the @code{PROCEDURE} will not transform the columns. +@item +Creation of a table of type @code{MERGE} doesn't check if the underlying +tables are of compatible types. +@item +@strong{MySQL} can't yet handle @code{NaN}, @code{-Inf} and @code{Inf} +values in double. Using these will cause problems when trying to export +and import data. We should as an intermediate solution change @code{NaN} to +@code{NULL} (if possible) and @code{-Inf} and @code{Inf} to the +Minimum respective maximum possible @code{double} value. +@item +@code{LIMIT} on negative numbers are treated as big positive numbers. +@end itemize + +The following are known bugs in earlier versions of @strong{MySQL}: + +@itemize @bullet +@item +You can get a hung thread if you do a @code{DROP TABLE} on a table that is +one among many tables that is locked with @code{LOCK TABLES}. + +@item +In the following case you can get a core dump: +@enumerate +@item +Delayed insert handler has pending inserts to a table. +@item +@code{LOCK table} with @code{WRITE} +@item +@code{FLUSH TABLES} +@end enumerate + +@item +Before @strong{MySQL} Version 3.23.2 an @code{UPDATE} that updated a key with +a @code{WHERE} on the same key may have failed because the key was used to +search for records and the same row may have been found multiple times: + +@example +UPDATE tbl_name SET KEY=KEY+1 WHERE KEY > 100; +@end example + +A workaround is to use: + +@example +mysql> UPDATE tbl_name SET KEY=KEY+1 WHERE KEY+0 > 100; +@end example + +This will work because @strong{MySQL} will not use index on expressions in +the @code{WHERE} clause. +@item +Before @strong{MySQL} Version 3.23, all numeric types where treated as fixed-point +fields. That means you had to specify how many decimals a floating-point +field shall have. All results were returned with the correct number of +decimals. +@end itemize + +For platform-specific bugs, see the sections about compiling and porting. + +@node Comparisons, TODO, Compatibility, Introduction +@section How MySQL Compares to Other Databases + +@cindex databases, MySQL vs. others +@cindex comparisons, MySQL vs. others + +@menu +* Compare mSQL:: How @strong{MySQL} compares to @code{mSQL} +* Protocol differences:: +* Compare PostgreSQL:: How @strong{MySQL} compares with PostgreSQL +* MySQL-PostgreSQL features:: +@end menu + +This section compares @strong{MySQL} to other popular databases. + +This section has been written by the @strong{MySQL} developers, so it +should be read with that in mind. There are no factual errors contained +in this section that we know of. If you find something which you believe +to be an error, please contact us about it at @email{docs@@mysql.com}. + +For a list of all supported limits, functions, and types, see the +@code{crash-me} Web page at +@uref{http://www.mysql.com/information/crash-me.php}. + +@node Compare mSQL, Protocol differences, Comparisons, Comparisons +@subsection How MySQL Compares to @code{mSQL} + +@table @strong +@item Performance + +For a true comparison of speed, consult the growing @strong{MySQL} benchmark +suite. @xref{Benchmarks}. + +Because there is no thread creation overhead, a small parser, few features, and +simple security, @code{mSQL} should be quicker at: + +@itemize @bullet +@item +Tests that perform repeated connects and disconnects, running a very simple +query during each connection. +@item +@code{INSERT} operations into very simple tables with few columns and keys. +@item +@code{CREATE TABLE} and @code{DROP TABLE}. +@item +@code{SELECT} on something that isn't an index. (A table scan is very +easy.) +@end itemize + +Because these operations are so simple, it is hard to be better at them when +you have a higher startup overhead. After the connection is established, +@strong{MySQL} should perform much better. + +On the other hand, @strong{MySQL} is much faster than @code{mSQL} (and +most other SQL implementations) on the following: + +@itemize @bullet +@item +Complex @code{SELECT} operations. +@item +Retrieving large results (@strong{MySQL} has a better, faster, and safer +protocol). +@item +Tables with variable-length strings, because @strong{MySQL} has more efficient +handling and can have indexes on @code{VARCHAR} columns. +@item +Handling tables with many columns. +@item +Handling tables with large record lengths. +@item +@code{SELECT} with many expressions. +@item +@code{SELECT} on large tables. +@item +Handling many connections at the same time. @strong{MySQL} is fully +multi-threaded. Each connection has its own thread, which means that +no thread has to wait for another (unless a thread is modifying +a table another thread wants to access). In @code{mSQL}, once one connection +is established, all others must wait until the first has finished, regardless +of whether the connection is running a query that is short or long. When the +first connection terminates, the next can be served, while all the others wait +again, etc. +@item +Joins. +@code{mSQL} can become pathologically slow if you change the order of tables +in a @code{SELECT}. In the benchmark suite, a time more than 15000 times +slower than @strong{MySQL} was seen. This is due to @code{mSQL}'s lack of a +join optimizer to order tables in the optimal order. However, if you put the +tables in exactly the right order in @code{mSQL}2 and the @code{WHERE} is +simple and uses index columns, the join will be relatively fast! +@xref{Benchmarks}. +@item +@code{ORDER BY} and @code{GROUP BY}. +@item +@code{DISTINCT}. +@item +Using @code{TEXT} or @code{BLOB} columns. +@end itemize + +@item SQL Features + +@itemize @bullet +@item @code{GROUP BY} and @code{HAVING}. +@code{mSQL} does not support @code{GROUP BY} at all. +@strong{MySQL} supports a full @code{GROUP BY} with both @code{HAVING} and +the following functions: @code{COUNT()}, @code{AVG()}, @code{MIN()}, +@code{MAX()}, @code{SUM()}, and @code{STD()}. @code{COUNT(*)} is optimized to +return very quickly if the @code{SELECT} retrieves from one table, no other +columns are retrieved, and there is no @code{WHERE} clause. @code{MIN()} and +@code{MAX()} may take string arguments. + +@item @code{INSERT} and @code{UPDATE} with calculations. +@strong{MySQL} can do calculations in an @code{INSERT} or @code{UPDATE}. +For example: +@example +mysql> UPDATE SET x=x*10+y WHERE x<20; +@end example + +@item Aliasing. +@strong{MySQL} has column aliasing. + +@item Qualifying column names. +In @strong{MySQL}, if a column name is unique among the tables used in a +query, you do not have to use the full qualifier. + +@item @code{SELECT} with functions. +@strong{MySQL} has many functions (too many to list here; see @ref{Functions}). + +@end itemize + +@item Disk Space Efficiency +That is, how small can you make your tables? + +@strong{MySQL} has very precise types, so you can create tables that take +very little space. An example of a useful @strong{MySQL} datatype is the +@code{MEDIUMINT} that is 3 bytes long. If you have 100,000,000 records, +saving even one byte per record is very important. + +@code{mSQL2} has a more limited set of column types, so it is +more difficult to get small tables. +@item Stability +This is harder to judge objectively. For a discussion of @strong{MySQL} +stability, see @ref{Stability}. + +We have no experience with @code{mSQL} stability, so we cannot say +anything about that. + +@item Price +Another important issue is the license. @strong{MySQL} has a +more flexible license than @code{mSQL}, and is also less expensive than +@code{mSQL}. Whichever product you choose to use, remember to at least +consider paying for a license or e-mail support. (You are required to get +a license if you include @strong{MySQL} with a product that you sell, +of course.) + +@item Perl Interfaces +@strong{MySQL} has basically the same interfaces to Perl as @code{mSQL} with +some added features. + +@item JDBC (Java) +@strong{MySQL} currently has a lot of different JDBC drivers: +@itemize @bullet +@item +The mm driver: A type 4 JDBC driver by Mark Matthews +@email{mmatthew@@ecn.purdue.edu}. This is released under the LGPL. +@item +The Resin driver. This is a commercial JDBC driver released under open +source. @uref{http://www.caucho.com/projects/jdbc-mysql/index.xtp} +@item +The gwe driver: A Java interface by GWE technologies (not supported anymore). +@item +The jms driver: An improved gwe driver by Xiaokun Kelvin ZHU +@email{X.Zhu@@brad.ac.uk} (not supported anymore). +@item +The twz driver: A type 4 JDBC driver by Terrence W. Zellers +@email{zellert@@voicenet.com}. This is commercial but is free for private +and educational use (not supported anymore). +@end itemize + +The recommended driver is the mm driver. The Resin driver may also be +good (at least the benchmarks looks good), but we haven't received that much +information about this yet. + +We know that @code{mSQL} has a JDBC driver, but we have too little experience +with it to compare. + +@item Rate of Development +@strong{MySQL} has a very small team of developers, but we are quite +used to coding C and C++ very rapidly. Because threads, functions, +@code{GROUP BY}, and so on are still not implemented in @code{mSQL}, it +has a lot of catching up to do. To get some perspective on this, you +can view the @code{mSQL} @file{HISTORY} file for the last year and +compare it with the News section of the @strong{MySQL} Reference Manual +(@pxref{News}). It should be pretty obvious which one has developed +most rapidly. + +@item Utility Programs +Both @code{mSQL} and @strong{MySQL} have many interesting third-party +tools. Because it is very easy to port upward (from @code{mSQL} to +@strong{MySQL}), almost all the interesting applications that are available for +@code{mSQL} are also available for @strong{MySQL}. + +@strong{MySQL} comes with a simple @code{msql2mysql} program that fixes +differences in spelling between @code{mSQL} and @strong{MySQL} for the +most-used C API functions. +For example, it changes instances of @code{msqlConnect()} to +@code{mysql_connect()}. Converting a client program from @code{mSQL} to +@strong{MySQL} usually takes a couple of minutes. +@end table + +@menu +* Using mSQL tools:: How to convert @code{mSQL} tools for @strong{MySQL} +@end menu + +@node Using mSQL tools, , Compare mSQL, Compare mSQL +@subsubsection How to Convert @code{mSQL} Tools for MySQL + +@cindex MySQL tools, conversion +@cindex converting, tools +@cindex tools, converting + +According to our experience, it would just take a few hours to convert tools +such as @code{msql-tcl} and @code{msqljava} that use the +@code{mSQL} C API so that they work with the @strong{MySQL} C API. + +The conversion procedure is: + +@enumerate +@item +Run the shell script @code{msql2mysql} on the source. This requires the +@code{replace} program, which is distributed with @strong{MySQL}. +@item +Compile. +@item +Fix all compiler errors. +@end enumerate + +Differences between the @code{mSQL} C API and the @strong{MySQL} C API are: +@itemize @bullet +@item +@strong{MySQL} uses a @code{MYSQL} structure as a connection type (@code{mSQL} +uses an @code{int}). +@item +@code{mysql_connect()} takes a pointer to a @code{MYSQL} structure as a +parameter. It is easy to define one globally or to use @code{malloc()} to get +one. +@code{mysql_connect()} also takes two parameters for specifying the user and +password. You may set these to @code{NULL, NULL} for default use. +@item +@code{mysql_error()} takes the @code{MYSQL} structure as a parameter. Just add +the parameter to your old @code{msql_error()} code if you are porting old code. +@item +@strong{MySQL} returns an error number and a text error message for all +errors. @code{mSQL} returns only a text error message. +@item +Some incompatibilities exist as a result of @strong{MySQL} supporting +multiple connections to the server from the same process. +@end itemize + +@cindex communications protocols +@cindex mSQL vs. MySQL +@node Protocol differences, Compare PostgreSQL, Compare mSQL, Comparisons +@subsection How @code{mSQL} and MySQL Client/Server Communications Protocols Differ + +There are enough differences that it is impossible (or at least not easy) +to support both. + +The most significant ways in which the @strong{MySQL} protocol differs +from the @code{mSQL} protocol are listed below: + +@itemize @bullet +@item +A message buffer may contain many result rows. +@item +The message buffers are dynamically enlarged if the query or the +result is bigger than the current buffer, up to a configurable server and +client limit. +@item +All packets are numbered to catch duplicated or missing packets. +@item +All column values are sent in ASCII. The lengths of columns and rows are sent +in packed binary coding (1, 2, or 3 bytes). +@item +@strong{MySQL} can read in the result unbuffered (without having to store the +full set in the client). +@item +If a single read/write takes more than 30 seconds, the server closes +the connection. +@item +If a connection is idle for 8 hours, the server closes the connection. +@end itemize + +@menu +* Syntax differences:: +@end menu + +@node Syntax differences, , Protocol differences, Protocol differences +@subsubsection How @code{mSQL} 2.0 SQL Syntax Differs from MySQL + +@noindent +@strong{Column types} + +@table @code +@item @strong{MySQL} +Has the following additional types (among others; +@pxref{CREATE TABLE, , @code{CREATE TABLE}}): +@itemize @bullet +@item +@code{ENUM} type for one of a set of strings. +@item +@code{SET} type for many of a set of strings. +@item +@code{BIGINT} type for 64-bit integers. +@end itemize +@item +@strong{MySQL} also supports +the following additional type attributes: +@itemize @bullet +@item +@code{UNSIGNED} option for integer columns. +@item +@code{ZEROFILL} option for integer columns. +@item +@code{AUTO_INCREMENT} option for integer columns that are a +@code{PRIMARY KEY}. +@xref{mysql_insert_id, , @code{mysql_insert_id()}}. +@item +@code{DEFAULT} value for all columns. +@end itemize +@item mSQL2 +@code{mSQL} column types correspond to the @strong{MySQL} types shown below: +@multitable @columnfractions .15 .85 +@item @code{mSQL} @strong{type} @tab @strong{Corresponding @strong{MySQL} type} +@item @code{CHAR(len)} @tab @code{CHAR(len)} +@item @code{TEXT(len)} @tab @code{TEXT(len)}. @code{len} is the maximal length. +And @code{LIKE} works. +@item @code{INT} @tab @code{INT}. With many more options! +@item @code{REAL} @tab @code{REAL}. Or @code{FLOAT}. Both 4- and 8-byte versions are available. +@item @code{UINT} @tab @code{INT UNSIGNED} +@item @code{DATE} @tab @code{DATE}. Uses ANSI SQL format rather than @code{mSQL}'s own format. +@item @code{TIME} @tab @code{TIME} +@item @code{MONEY} @tab @code{DECIMAL(12,2)}. A fixed-point value with two decimals. +@end multitable +@end table + +@noindent +@strong{Index Creation} + +@table @code +@item @strong{MySQL} +Indexes may be specified at table creation time with the @code{CREATE TABLE} +statement. +@item mSQL +Indexes must be created after the table has been created, with separate +@code{CREATE INDEX} statements. +@end table + +@noindent +@strong{To Insert a Unique Identifier into a Table} + +@table @code +@item @strong{MySQL} +Use @code{AUTO_INCREMENT} as a column type +specifier. +@xref{mysql_insert_id, , @code{mysql_insert_id()}}. +@item mSQL +Create a @code{SEQUENCE} on a table and select the @code{_seq} column. +@end table + +@noindent +@strong{To Obtain a Unique Identifier for a Row} + +@table @code +@item @strong{MySQL} +Add a @code{PRIMARY KEY} or @code{UNIQUE} key to the table and use this. +New in Version 3.23.11: If the @code{PRIMARY} or @code{UNIQUE} key consists of only one +column and this is of type integer, one can also refer to it as +@code{_rowid}. +@item mSQL +Use the @code{_rowid} column. Observe that @code{_rowid} may change over time +depending on many factors. +@end table + +@noindent +@strong{To Get the Time a Column Was Last Modified} + +@table @code +@item @strong{MySQL} +Add a @code{TIMESTAMP} column to the table. This column is automatically set +to the current date and time for @code{INSERT} or @code{UPDATE} statements if +you don't give the column a value or if you give it a @code{NULL} value. + +@item mSQL +Use the @code{_timestamp} column. +@end table + +@noindent +@strong{@code{NULL} Value Comparisons} + +@table @code +@item @strong{MySQL} +@strong{MySQL} follows +ANSI SQL, and a comparison with @code{NULL} is always @code{NULL}. +@item mSQL +In @code{mSQL}, @code{NULL = NULL} is TRUE. You +must change @code{=NULL} to @code{IS NULL} and @code{<>NULL} to +@code{IS NOT NULL} when porting old code from @code{mSQL} to @strong{MySQL}. +@end table + +@noindent +@strong{String Comparisons} + +@table @code +@item @strong{MySQL} +Normally, string comparisons are performed in case-independent fashion with +the sort order determined by the current character set (ISO-8859-1 Latin1 by +default). If you don't like this, declare your columns with the +@code{BINARY} attribute, which causes comparisons to be done according to the +ASCII order used on the @strong{MySQL} server host. +@item mSQL +All string comparisons are performed in case-sensitive fashion with +sorting in ASCII order. +@end table + +@noindent +@strong{Case-insensitive Searching} + +@table @code +@item @strong{MySQL} +@code{LIKE} is a case-insensitive or case-sensitive operator, depending on +the columns involved. If possible, @strong{MySQL} uses indexes if the +@code{LIKE} argument doesn't start with a wild-card character. +@item mSQL +Use @code{CLIKE}. +@end table + +@noindent +@strong{Handling of Trailing Spaces} + +@table @code +@item @strong{MySQL} +Strips all spaces at the end of @code{CHAR} and @code{VARCHAR} +columns. Use a @code{TEXT} column if this behavior is not desired. +@item mSQL +Retains trailing space. +@end table + +@noindent +@strong{@code{WHERE} Clauses} + +@table @code +@item @strong{MySQL} +@strong{MySQL} correctly prioritizes everything (@code{AND} is evaluated +before @code{OR}). To get @code{mSQL} behavior in @strong{MySQL}, use +parentheses (as shown in an example below). +@item mSQL +Evaluates everything from left to right. This means that some logical +calculations with more than three arguments cannot be expressed in any +way. It also means you must change some queries when you upgrade to +@strong{MySQL}. You do this easily by adding parentheses. Suppose you +have the following @code{mSQL} query: +@example +mysql> SELECT * FROM table WHERE a=1 AND b=2 OR a=3 AND b=4; +@end example +To make @strong{MySQL} evaluate this the way that @code{mSQL} would, +you must add parentheses: +@example +mysql> SELECT * FROM table WHERE (a=1 AND (b=2 OR (a=3 AND (b=4)))); +@end example +@end table + +@noindent +@strong{Access Control} + +@table @code +@item @strong{MySQL} +Has tables to store grant (permission) options per user, host, and +database. @xref{Privileges}. +@item mSQL +Has a file @file{mSQL.acl} in which you can grant read/write privileges for +users. +@item +@end table + +@node Compare PostgreSQL, MySQL-PostgreSQL features, Protocol differences, Comparisons +@subsection How MySQL Compares to PostgreSQL + +@cindex PostgreSQL vs. MySQL, overview + +When reading the following, please note that both products are +continually evolving. We at @strong{MySQL AB} and the PostgreSQL +developers are both working on making our respective database as good as +possible, so we are both a serious choice to any commercial database. + +The following comparison is made by us at MySQL AB. We have tried to be +as accurate and fair as possible, but because we don't have a full +knowledge of all PostgreSQL features while we know MySQL througly, we +may have got some things wrong. We will however correct these when they +come to our attention. + +We would first like to note that @code{PostgreSQL} and @strong{MySQL} +are both widely used products, but with different design goals, even if +we are both striving to be ANSI SQL compatible. This means that for +some applications @strong{MySQL} is more suitable and for others +@code{PostgreSQL} is more suitable. When choosing which database to +use, you should first check if the database's feature set satisfies your +application. If you need speed, @strong{MySQL} is probably your best +choice. If you need some of the extra features that only @code{PostgreSQL} +can offer, you should use @code{PostgreSQL}. + +@cindex PostgreSQL/MySQL, strategies +@menu +* MySQL-PostgreSQL goals:: MySQL and PostgreSQL development strategies +@end menu + +@node MySQL-PostgreSQL goals, , Compare PostgreSQL, Compare PostgreSQL +@subsubsection MySQL and PostgreSQL development strategies + +When adding things to MySQL we take pride to do an optimal, definite +solution. The code should be so good that we shouldn't have any need to +change it in the foreseeable future. We also do not like to sacrifice +speed for features but instead will do our utmost to find a solution +that will give maximal throughput. This means that development will take +a little longer, but the end result will be well worth this. This kind +of development is only possible because all server code are checked by +one of a few (currently two) persons before it's included in the +@strong{MySQL} server. + +We at MySQL AB believe in frequent releases to be able to push out new +features quickly to our users. Because of this we do a new small release +about every 3 weeks, which a major branch every year. All releases are +throughly tested with our testing tools on a lot of different platforms. + +PostgreSQL is based on a kernel with lots of contributors. In this setup +it makes sense to prioritize adding a lot of new features, instead of +implementing them optimally, because one can always optimize things +later if there arises a need for this. + +Another big difference between @strong{MySQL} and PostgreSQL is that +nearly all of the code in the MySQL server are coded by developers that +are employed by MySQL AB and are still working on the server code. The +exceptions are the transaction engines and the regexp library. + +This is in sharp contrast to the PostgreSQL code where the majority of +the code is coded by a big group of people with different backgrounds. +It was only recently that the PostgreSQL developers announced that they +current developer group had finally had time to take a look at all +the code in the current PostgreSQL release. + +Both of the above development methods has it's own merits and drawbacks. +We here at @strong{MySQL AB} think of course that our model is better +because our model gives better code consistence, more optimal and +reusable code and, in our opinion, fewer bugs. Because we are the +authors of the @strong{MySQL} server code we are better able to +coordinate new features and releases. + +@cindex PostgreSQL/MySQL, features +@node MySQL-PostgreSQL features, , Compare PostgreSQL, Comparisons +@subsection Featurevise Comparison of MySQL and PostgreSQL + +On the @uref{http://www.mysql.com/information/crash-me.php, crash-me} +page you can find a list of those database constructs and limits that +one can detect automatically with a program. Note however that a lot of +the numerical limits may be changed with startup options for respective +database. The above web page is however extremely useful when you want to +ensure that your applications works with many different databases or +when you want to convert your application from one datbase to another. + +@strong{MySQL} offers the following advantages over PostgreSQL: + +@itemize @bullet +@item +@code{MySQL} is generally much faster than PostgreSQL. +@xref{MySQL-PostgreSQL benchmarks}. +@item +Because @strong{MySQL} has a much larger user base than PostgreSQL the +code is more tested and has historically been more stable than +PostgreSQL. @strong{MySQL} is the much more used in production +environments than PostgreSQL, mostly thanks to that @strong{MySQL AB}, +former TCX DataKonsult AB, has provided top quality commercial support +for @strong{MySQL} from the day it was released, whereas until recently +PostgreSQL was unsupported. +@item +@strong{MySQL} works on more platforms than PostgreSQL. @xref{Which OS}. +@item +@strong{MySQL} works better on Windows; @strong{MySQL} is running as a +native windows application (a service on NT/Win2000/WinXP), while +PostgreSQL is run under the cygwin emulation. We have heard that +PostgreSQL is not yet that stable on windows but we haven't been able to +verify this ourselves. +@item +@strong{MySQL} has more API to other languages and is supported by more +programs than PostgreSQL. @xref{Contrib}. +@item +@strong{MySQL} works on 24/7 heavy duty systems. In most circumstances +you never have to run any cleanups on @code{MySQL}. PostgreSQL doesn't +yet support 24/7 systems because you have have to run @code{vacuum()} +once in a while to reclaim space from @code{UPDATE} and @code{DELETE} +commands and to perform statistics analyzes that are critical to get +good performance with PostgreSQL. Vacuum is also needed after adding +a lot of new rows to a table. On a busy system with lots of changes +vacuum must be run very frequently, in the worst cases even many times a +day. During the @code{vacuum()} run, which may take hours if the +database is big, the database is from a production standpoint +practically dead. The PostgreSQL team has fixing this on their TODO, +but we assume that this is not an easy thing to fix permanently. +@item +A working, tested replication feature used by sites like +@uref{http://finance.yahoo.com, Yahoo finance}, +@uref{http://www.mobile.de/,mobile.de} and +@uref{http://www.slashdot.org,Slashdot}. +@item +Included in the @strong{MySQL} distribution is included two different +testing suits (@file{mysql-test-run} and +@uref{http://www.mysql.com/information/crash-me.php,crash-me}) and a +benchmark suite. The test system is actively updated with code to test +each new feature and almost all repeatable bugs that comes to our +attention. We test @strong{MySQL} with these on a lot of platforms +before every release. These tests are more sofisticated than anything +have seen from PostgreSQL and ensures that the @strong{MySQL} code keeps +at a high standard. +@item +There are far moore books in print on @strong{MySQL} than on PostgreSQL. +O'Reilly, Sams, Que, and New Riders are all major publishers with books +about MySQL. All @strong{MySQL} features is also documented in the +@strong{MySQL} on-line manual because when a feature is implemented, the +@strong{MySQL} developers are required to document it before it's +included in the source. +@item +@strong{MySQL} has supports more of the standard ODBC functions than +@code{PostgreSQL}. +@item +@strong{MySQL} has a much more sophisticated @code{ALTER TABLE}. +@item +@strong{MySQL} has support for tables without transactions for +applications that need all speed they can get. The tables may be memory +based,@code{HEAP} tables or disk based @code{MyISAM}. @xref{Table types}. +@item +@strong{MySQL} has support for 3 different table handles that support +transactions (@code{BDB} and @code{InnoDB}). Because +every transaction engine performs differently under different +conditions, this gives the application writer more options to find an +optimal solution for his/her setup. @xref{Table types}. +@item +@code{MERGE} tables gives you a unique way to instantly make a view over +a set of identical tables and use these as one. This is perfectly for +systems where you have log files that you order for example by month. +@xref{MERGE}. +@item +The option to compress read-only tables, but still have direct access to +the rows in the table, gives you better performance by minimizing disk +reads. This is very useful when you are archiving +things.@xref{myisampack}. +@item +@strong{MySQL} has internal support for text search. @xref{Fulltext Search}. +@item +You can access many databases from the same connection (depending of course +on your privileges). +@item +@strong{MySQL} is coded from the start with multi-threading while +PostgreSQL uses processes. Because context switching and access to +common storage areas is much faster between threads, than are separate +processes, this gives @strong{MySQL} a big speed advantage in multi-user +applications and also makes it easier for @strong{MySQL} to take full +advantage of symmetric multiprocessor systems (SMP). +@item +@strong{MySQL} has a much more sophisticated privilege system than +PostgreSQL. While PostgreSQL only supports @code{INSERT}, +@code{SELECT}, @code{update/delete} grants per user on a database or a +table @strong{MySQL} allows you to define a full set of different +privileges on database, table and columns level. @strong{MySQL} also allows +you to specify the privilege on host+user combinations. @xref{GRANT}. +@item +@strong{MySQL} supports a compressed server/client protocol which +improves performance over slow links. +@item +@strong{MySQL} employs the table handler concept and is the only +relational database we know of built around this concept. This allows +different low level table types to be swapped into the SQL engine, each +table type optimized for a different performance characteristics. +@item +All @code{MySQL} table types (except @strong{InnoDB}) are implemented as +files (ie: one table per file), which makes it really easy to backup, +move, delete and even symlink databases and tables when the server is +down. +@item +Tools to repair and optimize @strong{MyISAM} tables (the most common +@strong{MySQL} table type). A repair tool is only needed when a +physical corruption of a data file happens, usually from a hardware +failure. It allows a majority of the data to be recovered. +@item +Upgrading @strong{MySQL} is painless. When you are upgrading @strong{MySQL}, +you don't need to dump/restore your data, as you have to do with most +PostgreSQL upgrades. +@end itemize + +Drawbacks with @strong{MySQL} compared to PostgreSQL: + +@itemize @bullet +@item +The transaction support in @strong{MySQL} is not yet as well tested as +PostgreSQL's system. +@item +Because @strong{MySQL} uses threads, which are still a moving target on +many OS, one must either use binaries from +@uref{http://www.mysql.com/downloads} or carefully follow our +instructions on +@uref{http://www.mysql.com/doc/I/n/Installing_source.html} to get an +optimal binary that works in all cases. +@item +Table locking, as used by the non-transactional @code{MyISAM} tables, is +in many cases faster than page locks, row locks or versioning. The +drawback however is that if one doesn't take into account how table +locks works, a single long-running query can block a table for updates +for a long time. This can usable be avoided when designing the +application. If not, one can always switch the trouble table to use one +of the transactional table types. @xref{Table locking}. +@item +With UDF (user defined functions) one can extend @strong{MySQL} with +both normal SQL functions and aggregates, but this is not as easy or as +flexible as in PostgreSQL. @xref{Adding functions}. +@item +Updates and deletes that goes over multiple tables is harder to do in +@strong{MySQL}. (Will be fixed in @strong{MySQL} 4.0 with multi-table +@code{DELETE} and multi-table @code{UPDATE} and in @strong{MySQL} 4.1 +with @code{SUB-SELECT}) +@end itemize + +PostgreSQL offers currently the following advantages over @strong{MySQL}: + +Note that because we know the @strong{MySQL} road map, we have included +in the following table the version when @strong{MySQL} should support +this feature. Unfortunately we couldn't do this for previous comparison, +because we don't know the PostgreSQL roadmap. + +@multitable @columnfractions .70 .30 +@item @strong{Feature} @tab @strong{MySQL version} +@item Subselects @tab 4.1 +@item Foreign keys @tab 4.0 and 4.1 +@item Views. @tab 4.2 +@item Stored procedures in multiple languages @tab 4.1 +@item Extensible type system. @tab Not planed +@item Unions @tab 4.0. +@item Full join. @tab 4.0 or 4.1. +@item Triggers. @tab 4.1 +@item Constrainst @tab 4.1 +@item Cursors @tab 4.1 or 4.2 +@item Extensible index types like R-trees @tab R-trees are planned to 4.2 +@item Inherited tables @tab Not planned +@end multitable + +Other reasons to use PostgreSQL: + +@itemize @bullet +@item +Standard usage is in PostgreSQL closer to ANSI SQL in some cases. +@item +One can get speed up PostgreSQL by coding things as stored procedures. +@item +Bigger team of developers that contributes to the server. +@end itemize + +Drawbacks with PostgreSQL compared to @strong{MySQL}: + +@itemize @bullet +@item +@code{Vaccum()} makes PostgreSQL hard to use in a 24/7 environment. +@item +Only transactional tables. +@item +Much slower insert/delete/update. +@end itemize + +For a complete list of drawbacks, you should also examine the first table +in this section. + +@menu +* MySQL-PostgreSQL benchmarks:: +@end menu + +@node MySQL-PostgreSQL benchmarks, , MySQL-PostgreSQL features, MySQL-PostgreSQL features +@subsubsection Benchmarking MySQL and PostgreSQL + +@cindex PostgreSQL vs. MySQL, benchmarks + +The only open source benchmark, that we know of, that can be used to +benchmark @strong{MySQL} and PostgreSQL (and other databases) is our +own. It can be found at: +@uref{http://www.mysql.com/information/benchmarks.html}. + +We have many times asked the PostgreSQL developers and some PostgreSQL +users to help us extend this benchmark to make the definitive benchmark +for databases, but unfortunately we haven't got any feedback for this. + +We, the @strong{MySQL} developers, have because of this spent a lot of +hours to get maximum performance from PostgreSQL for the benchmarks, but +because we don't know PostgreSQL intimately we are sure that there are +things that we have missed. We have on the benchmark page documented +exactly how we did run the benchmark so that it should be easy for +anyone to repeat and verify our results. + +The benchmarks are usually run with and without the @code{--fast} +option. When run with @code{--fast} we are trying to use every trick +the server can do to get the code to execute as fast as possible. +The idea is that the normal run should show how the server would work in +a default setup and the @code{--fast} run shows how the server would do +if the application developer would use extensions in the server to make +his application run faster. + +When running with PostgreSQL and @code{--fast} we do a @code{vacuum()} +between after every major table update and drop table to make the database +in perfect shape for the following selects. The time for vacuum() is +measured separately. + +When running with PostgreSQL 7.1.1 we could however not run with +@code{--fast} because during the insert test, the postmaster (the +PostgreSQL deamon) died and the database was so corrupted that it was +impossible to restart postmaster. (The details about the machine we run +the benchmark can be found on the benchmark page). After this happened +twice, we decided to postpone the @code{--fast} test until next +PostgreSQL release. + +Before going to the other benchmarks we know of, We would like to give +some background to benchmarks: + +It's very easy to write a test that shows ANY database to be best +database in the world, by just restricting the test to something the +database is very good at and not test anything that the database is not +good at; If one after this publish the result with a single figure +things is even easier. + +This would be like we would measure the speed of @strong{MySQL} compared +to PostgreSQL by looking at the summary time of the MySQL benchmarks on +our web page. Based on this @strong{MySQL} would be more than 40 times +faster than PostgreSQL, something that is of course not true. We could +make things even worse by just taking the test where PostgreSQL performs +worst and claim that @strong{MySQL} is more than 2000 times faster than +PostgreSQL. + +The case is that @strong{MySQL} does a lot of optimizations that +PostgreSQL doesn't do and the other way around. An SQL optimizer is a +very complex thing and a company could spend years on just making the +optimizer faster and faster. + +When looking at the benchmark results you should look for things that +you do in your application and just use these results to decide which +database would be best suited for your application. The benchmark +results also shows things a particular database is not good at and should +give you a notion about things to avoid and what you may have to do in +other ways. + +We know of two benchmark tests that claims that PostgreSQL performers +better than @strong{MySQL}. These both where multi-user tests, a test +that we here at @strong{MySQL AB} haven't had time to write and include in +the benchmark suite, mainly because it's a big task to do this in a +manner that is fair against all databases. + +One is the benchmark paid for by +@uref{http://www.greatbridge.com/about/press.php?content_id=4,Great +Bridge}. + +This is the worst benchmark we have ever seen anyone ever conduct. This +was not only tuned to only test what PostgreSQL is absolutely best at, +it was also totally unfair against every other database involved in the +test. + +@strong{NOTE}: We know that not even some of the main PostgreSQL +developers did like the way Great Bridge conducted the benchmark, so we +don't blame them for the way the benchmark was made. + +This benchmark has been condemned in a lot of postings and newsgroups so +we will here just shortly repeat some things that where wrong with it. + +@itemize @bullet +@item +The tests where run with an expensive commercial tool, that makes it +impossible for an open source company like us to verify the benchmarks, +or even check how the benchmark where really done. The tool is not even +a true benchmark tool, but a application/setup testing tool. To refer +this as STANDARD benchmark tool is to stretch the truth a long way. +@item +Great Bridge admitted that they had optimized the PostgreSQL database +(with vacuum() before the test) and tuned the startup for the tests, +something they hadn't done for any of the other databases involved. To +say "This process optimizes indexes and frees up disk space a bit. The +optimized indexes boost performance by some margin". Our benchmarks +clearly indicates that the difference in running a lot of selects on a +database with and without vacuum() can easily differ by a factor of 10. +@item +The test results where also strange; The AS3AP test documentation +mentions that the test does: + +"selections, simple joins, projections, aggregates, one-tuple updates, +and bulk updates" + +PostgreSQL is good at doing selects and joins (especially after a +vacuum()), but doesn't perform as well on inserts/updates; The +benchmarks seem to indicate that only SELECTs where done (or very few +updates) . This could easily explain they good results for PostgreSQL in +this test. The bad results for MySQL will be obvious a bit down in this +document. +@item +They did run the so called benchmark from a Windows machine against a +Linux machine over ODBC, a setup that no normal database user would ever +do when running a heavy multi-user application. This tested more the +ODBC driver and the Windows protocol used between the clients than the +database itself. +@item +When running the database against Oracle and MS-SQL (Great Bridge has +indirectly indicated that the databases they used in the test), +they didn't use the native protocol but instead ODBC. Anyone that has +ever used Oracle, knows that all real application uses the native +interface instead of ODBC. Doing a test through ODBC and claiming that +the results had anything to do with using the database for real can't +be regarded as fair play. They should have done two tests with and +without ODBC to provide the right facts (after having got experts to tune +all involved databases of course). +@item +They refer to the TPC-C tests, but doesn't anywhere mention that the +tests they did where not a true TPC-C test and they where not even +allowed to call it a TPC-C test. A TPC-C test can only be conducted by +the rules approved by the @uref{http://www.tpc.org,TPC-council}. Great +Bridge didn't do that. By doing this they have both violated the TPC +trademark and miscredited their own benchmarks. The rules set by the +TPC-council are very strict to ensure that no one can produce false +results or make unprovable statements. Apparently Great Bridge wasn't +interested in doing this. +@item +After the first test, we contacted Great Bridge and mentioned to them +some of the obvious mistakes they had done with @strong{MySQL}; Running +with a debug version of our ODBC driver, running on a Linux system that +wasn't optimized for threads, using an old MySQL version when there was +a recommended newer one available, not starting @strong{MySQL} with the +right options for heavy multi-user use (the default installation of +MySQL is tuned for minimal resource use). Great Bridge did run a new +test, with our optimized ODBC driver and with better startup options for +MySQL, but refused to either use our updated glibc library or our +standard binary (used by 80% of our users), which was statically linked +with a fixed glibc library. + +According to what we know, Great Bridge did nothing to ensure that the +other databases where setup correctly to run good in their test +environment. We are sure however that they didn't contact Oracle or +Microsoft to ask for their advice in this matter ;) +@item +The benchmark was paid for by Great Bridge, and they decided to publish +only partial chosen results (instead of publishing it all). +@end itemize + +Tim Perdue, a long time PostgreSQL fan and a reluctant MySQL user +published a comparison on +@uref{http://www.phpbuilder.com/columns/tim20001112.php3,phpbuider}. + +When we got aware of the comparison, we phoned Tim Perdue about this +because there was a lot of strange things in his results. For example, +he claimed that MySQL had a problem with five users in his tests, when we +know that there are users with similar machines as his that are using +MySQL with 2000 simultaneous connections doing 400 queries per second (In +this case the limit was the web bandwidth, not the database). + +It sounded like he was using a Linux kernel that either had some +problems with many threads (Linux kernels before 2.4 had a problem with +this but we have documented how to fix this and Tim should be aware of +this problem). The other possible problem could have been an old glibc +library and that Tim didn't use a MySQL binary from our site, which is +linked with a corrected glibc library, but had compiled a version of his +own with. In any of the above cases, the symptom would have been exactly +what Tim had measured. + +We asked Tim if we could get access to his data so that we could repeat +the benchmark and if he could check the MySQL version on the machine to +find out what was wrong and he promised to come back to us about this. +He has not done that yet. + +Because of this we can't put any trust in this benchmark either :( + +Conclusion: + +The only benchmarks that exist today that anyone can download and run +against @strong{MySQL}and PostgreSQL is the MySQL benchmarks. We here +at @strong{MySQL} believe that open source databases should be tested +with open source tools! This is the only way to ensure that no one +does tests that nobody can reproduce and use this to claim that a +database is better than another. Without knowing all the facts it's +impossible to answer the claims of the tester. + +The thing we find strange is that every test we have seen about +PostgreSQL, that is impossible to reproduce, claims that PostgreSQL is +better in most cases while our tests, which anyone can reproduce, +clearly shows otherwise. With this we don't want to say that PostgreSQL +isn't good at many things (It is!) We would just like to see a fair test +where they are very good so that we could get some friendly competition +going! + +For more information about our benchmarks suite see @xref{MySQL +Benchmarks}. + +We are working on an even better benchmark suite, including much better +documentation of what the individual tests really do and how to add more +tests to the suite. + +@node TODO, , Comparisons, Introduction +@section MySQL and the future (The TODO) + +@cindex ToDo list for MySQL + +@menu +* TODO MySQL 4.0:: Things that should be in Version 4.0 +* TODO future:: Things that must be done in the near future +* TODO sometime:: Things that have to be done sometime +* TODO unplanned:: Some things we don't have any plans to do +@end menu + +This appendix lists the features that we plan to implement in @strong{MySQL}. + +Everything in this list is approximately in the order it will be done. If you +want to affect the priority order, please register a license or support us and +tell us what you want to have done more quickly. @xref{Licensing and Support}. + +The plan is that we in the future will support the full ANSI SQL99 +standard, but with a lot of useful extensions. The challenge is to do +this without sacrifying the speed or compromise the code. + +@node TODO MySQL 4.0, TODO future, TODO, TODO +@subsection Things that should be in 4.0 + +We plan to make @strong{MySQL} Version 4.0 a ``quick'' release where we only +add some new stuff to enable others to help us with developing new features +into Version 4.1. The @strong{MySQL} 4.0 version should only take us about +a month to make after which we want to stabilize it and start working on +Version 4.1. Version 4.0 should have the following new features: + +The news section for 4.0 includes a list of the features we have already +implemented in the 4.0 tree. @xref{News-4.0.x}. + +@itemize @bullet +@item +New table definition file format (@code{.frm} files) This will enable us +to not run out of bits when adding more table options. One will still +be able to use the old @code{.frm} file format with 4.0. All newly created +tables will, however, use the new format. + +The new file format will enable us to add new column types, more options +for keys and @code{FOREIGN KEY} support. +@item +@code{mysqld} as a library. This will have the same interface as the +standard @strong{MySQL} client (with an extra function to just set up +startup parameters) but will be faster (no TCP/IP or socket overhead), +smaller and much easier to use for embedded products. + +One will be able to define at link time if one wants to use the +client/server model or a stand-alone application just by defining which +library to link with. + +The @code{mysqld} will support all standard @strong{MySQL} features and +one can use it in a threaded client to run different queries in each +thread. +@item +Replication should work with @code{RAND()} and user variables @code{@@var}. +@item +Online backup with very low performance penalty. The online backup will +make it easy to add a new replication slave without taking down the +master. +@item +@code{DELETE FROM table_name} will return the number of deleted rows. For +fast execution one should use @code{TRUNCATE table_name}. +@item +Allow @code{DELETE} on @code{MyISAM} tables to use the record cache. +To do this, we need to update the threads record cache when we update +the @code{.MYD} file. +@item +Better replication. +@item +More functions for full-text search. +@xref{Fulltext Features to Appear in MySQL 4.0}. +@item +Character set casts and syntax for handling multiple character sets. +@item +Allow users to change startup options without taking down the server. +@item +Help for all commands from the client. +@item +Secure connections (with SSL). +@item +Extend the optimizer to be able to optimize some @code{ORDER BY key_name DESC} +queries. +@item +@code{SHOW COLUMNS FROM table_name} (used by @code{mysql} client to allow +expansions of column names) should not open the table, but only the +definition file. This will require less memory and be much faster. +@item +New key cache +@item +When using @code{SET CHARACTER SET} we should translate the whole query +at once and not only strings. This will enable users to use the translated +characters in database, table and column names. +@item +Add a portable interface over @code{gethostbyaddr_r()} so that we can change +@code{ip_to_hostname()} to not block other threads while doing DNS lookups. +@item +Add @code{record_in_range()} method to @code{MERGE} tables to be +able to choose the right index when there is many to choose from. We should +also extend the info interface to get the key distribution for each index, +of @code{analyze} is run on all sub tables. +@item +@code{SET SQL_DEFAULT_TABLE_TYPE=[MyISAM | INNODB | BDB | HEAP]}. +@end itemize + +@node TODO future, TODO sometime, TODO MySQL 4.0, TODO +@subsection Things that must be done in the real near future + +@itemize @bullet +@item +Fail safe replication. +@item +Subqueries. +@code{select id from t where grp in (select grp from g where u > 100)} +@item +Derived tables. +@example +select a.col1, b.col2 from (select max(col1) as col1 from root_table ) a, +other_table b where a.col1=b.col1 +@end example + +This could be done by automatically creating temporary tables for the +derived tables for the duration of the query. +@item +Add @code{PREPARE} of statements and sending of parameters to @code{mysqld}. +@item +Extend the server/client protocol to support warnings. +@item +Add options to the server/protocol protocol to get progress notes +for long running commands. +@item +Add database and real table name (in case of alias) to the MYSQL_FIELD +structure. +@item +Don't allow more than a defined number of threads to run MyISAM recover +at the same time. +@item +Change @code{INSERT ... SELECT} to optionally use concurrent inserts. +@item +Implement @code{RENAME DATABASE}. To make this safe for all table handlers, +it should work as follows: +@itemize @bullet +@item +Create the new database. +@item +For every table do a rename of the table to another database, as +we do with the @code{RENAME} command. +@item +Drop the old database. +@end itemize +@item +Return the original field types() when doing @code{SELECT MIN(column) +... GROUP BY}. +@item +Multiple result sets. +@item +Change the protocol to allow binary transfer of values. To do this +efficiently, we need to add an API to allow binding of variables. +@item +Make it possible to specify @code{long_query_time} with a granularity +in microseconds. +@item +Add a configurable prompt to the @code{mysql} command line client, with +options like database in use, time and date... +@item +Add range checking to @code{MERGE} tables. +@item +Link the @code{myisampack} code into the server. +@item +Port of @strong{MySQL} to BeOS. +@item +Port of the @strong{MySQL} clients to LynxOS. +@item +Add a temporary key buffer cache during @code{INSERT/DELETE/UPDATE} so that we +can gracefully recover if the index file gets full. +@item +If you perform an @code{ALTER TABLE} on a table that is symlinked to another +disk, create temporary tables on this disk. +@item +Implement a @code{DATE/DATETIME} type that handles time zone information +properly, so that dealing with dates in different time zones is easier. +@item +FreeBSD and MIT-pthreads; Do sleeping threads take CPU? +@item +Check if locked threads take any CPU. +@item +Fix configure so that one can compile all libraries (like @code{MyISAM}) +without threads. +@item +Add an option to periodically flush key pages for tables with delayed keys +if they haven't been used in a while. +@item +Allow join on key parts (optimization issue). +@item +@code{INSERT SQL_CONCURRENT} and @code{mysqld --concurrent-insert} to do +a concurrent insert at the end of the file if the file is read-locked. +@item +Remember @code{FOREIGN} key definitions in the @file{.frm} file. +@item +Cascading @code{DELETE} +@item +Server side cursors. +@item +Check if @code{lockd} works with modern Linux kernels; If not, we have +to fix @code{lockd}! To test this, start @code{mysqld} with +@code{--enable-locking} and run the different fork* test suits. They shouldn't +give any errors if @code{lockd} works. +@item +Allow SQL variables in @code{LIMIT}, like in @code{LIMIT @@a,@@b}. +@item +Allow update of variables in @code{UPDATE} statements. For example: +@code{UPDATE TABLE foo SET @@a=a+b,a=@@a, b=@@a+c} +@item +Change when user variables are updated so that one can use them with +@code{GROUP BY}, as in the following example: +@code{SELECT id, @@a:=count(*), sum(sum_col)/@@a FROM table_name GROUP BY id}. +@item +Don't add automatic @code{DEFAULT} values to columns. Give an error when using +an @code{INSERT} that doesn't contain a column that doesn't have a +@code{DEFAULT}. +@item +Caching of queries and results. This should be done as a separated +module that examines each query and if this is query is in the cache +the cached result should be returned. When one updates a table one +should remove as few queries as possible from the cache. +This should give a big speed bost on machines with much RAM where +queries are often repeated (like WWW applications). +One idea would be to only cache queries of type: +@code{SELECT CACHED ...} +@item +Fix @file{libmysql.c} to allow two @code{mysql_query()} commands in a row +without reading results or give a nice error message when one does this. +@item +Optimize @code{BIT} type to take 1 bit (now @code{BIT} takes 1 char). +@item +Check why MIT-pthreads @code{ctime()} doesn't work on some FreeBSD systems. +@item +Add an @code{IMAGE} option to @code{LOAD DATA INFILE} to not update +@code{TIMESTAMP} and @code{AUTO_INCREMENT} fields. +@item +Added @code{LOAD DATE INFILE.. UPDATE} syntax. +@itemize @bullet +@item +For tables with primary keys, if the data contains the primary key, +entries matching that primary key are updated from the remainder of the +columns. However, columns MISSING from the incoming data feed are not +touched. +@item +For tables tables with primary keys that are missing some part of the key +in the incoming data stream, or that have no primary key, the feed is +treated as a @code{LOAD DATA INFILE ... REPLACE INTO} is now. +@end itemize +@item +Make @code{LOAD DATA INFILE} understand syntax like: +@example +LOAD DATA INFILE 'file_name.txt' INTO TABLE tbl_name +TEXT_FIELDS (text_field1, text_field2, text_field3) +SET table_field1=concatenate(text_field1, text_field2), table_field3=23 +IGNORE text_field3 + +This can be used to skip over extra columns in the text file, or update columns +based on expressions of the read data... +@end example +@item +@code{LOAD DATA INFILE 'file_name' INTO TABLE 'table_name' ERRORS TO err_table_name} +This would cause any errors and warnings to be logged into the err_table_name +table. That table would have a structure like: + +@example +line_number - line number in data file +error_message - the error/warning message +and maybe +data_line - the line from the data file +@end example +@item +Add true @code{VARCHAR} support (There is already support for this in MyISAM). +@item +Automatic output from @code{mysql} to netscape. +@item +@code{LOCK DATABASES}. (with various options) +@item +Change sort to allocate memory in ``hunks'' to get better memory utilization. +@item +@code{DECIMAL} and @code{NUMERIC} types can't read exponential numbers; +@code{Field_decimal::store(const char *from,uint len)} must be recoded +to fix this. +@item +Fix @code{mysql.cc} to do fewer @code{malloc()} calls when hashing field +names. +@item +Functions: +ADD_TO_SET(value,set) and REMOVE_FROM_SET(value,set) +@item +Add use of @code{t1 JOIN t2 ON ...} and @code{t1 JOIN t2 USING ...} +Currently, you can only use this syntax with @code{LEFT JOIN}. +@item +Add full support for @code{unsigned long long} type. +@item +Many more variables for @code{show status}. Counts for: +@code{INSERT}/@code{DELETE}/@code{UPDATE} statements. Records reads and +updated. Selects on 1 table and selects with joins. Mean number of +tables in select. Number of @code{ORDER BY} and @code{GROUP BY} queries. +@item +If you abort @code{mysql} in the middle of a query, you should open +another connection and kill the old running query. +Alternatively, an attempt should be made to detect this in the server. +@item +Add a handler interface for table information so you can use it as a system +table. This would be a bit slow if you requested information about all tables, +but very flexible. @code{SHOW INFO FROM tbl_name} for basic table information +should be implemented. +@item +Add support for UNICODE. +@item +@code{NATURAL JOIN} and @code{UNION JOIN} +@item +Allow @code{select a from crash_me left join crash_me2 using (a)}; In this +case a is assumed to come from the crash_me table. +@item +Fix that @code{ON} and @code{USING} works with the @code{JOIN} and +@code{INNER JOIN} join types. +@item +Oracle like @code{CONNECT BY PRIOR ...} to search hierarchy structures. +@item +@code{RENAME DATABASE} +@item +@code{mysqladmin copy database new-database}. -- Requires COPY command to be +added to @code{mysqld} +@item +Processlist should show number of queries/thread. +@item +@code{SHOW HOSTS} for printing information about the hostname cache. +@item +@code{DELETE} and @code{REPLACE} options to the @code{UPDATE} statement +(this will delete rows when one gets a duplicate key error while updating). +@item +Change the format of @code{DATETIME} to store fractions of seconds. +@item +Add all missing ANSI92 and ODBC 3.0 types. +@item +Change table names from empty strings to @code{NULL} for calculated columns. +@item +Don't use 'Item_copy_string' on numerical values to avoid +number->string->number conversion in case of: +@code{SELECT COUNT(*)*(id+0) FROM table_name GROUP BY id} +@item +Make it possible to use the new GNU regexp library instead of the current +one (The GNU library should be much faster than the old one). +@item +Change that @code{ALTER TABLE} doesn't abort clients that executes +@code{INSERT DELAYED}. +@item +Fix that when columns referenced in an @code{UPDATE} clause contains the old +values before the update started. +@item +@code{myisamchk}, @code{REPAIR} and @code{OPTIMIZE TABLE} should be able +to handle cases where the data and/or index files are symbolic links. +@item +Add simulation of @code{pread()}/@code{pwrite()} on Windows to enable +concurrent inserts. +@item +A logfile analyzer that could parsed out information about which tables +are hit most often, how often multi-table joins are executed, etc. It +should help users identify areas or table design that could be optimized +to execute much more efficient queries. +@item +Add @code{SUM(DISTINCT)} +@item +Add @code{ANY()},@code{EVERY()} and @code{SOME()} group functions. In +ANSI SQL these only works on boolean columns, but we can extend these to +work on any columns/expressions by applying: value == 0 -> FALSE and +value <> 0 -> TRUE. +@item +Fix that the type for @code{MAX(column)} is the same as the column type. +@example +create table t1 (a DATE); +insert into t1 values (now()); +create table t2 select max(a) from t1; +show columns from t2; +@end example +@item +Come up with a nice syntax for a statement that will @code{UPDATE} the row +if it exists and @code{INSERT} a new row if the row didn't exist. +(Like @code{REPLACE} works with @code{INSERT} / @code{DELETE}) +@end itemize + +@node TODO sometime, TODO unplanned, TODO future, TODO +@subsection Things that have to be done sometime + +@itemize @bullet +@item +Implement function: @code{get_changed_tables(timeout,table1,table2,...)} +@item +Atomic multi-table updates, eg @code{update items,month set +items.price=month.price where items.id=month.id;}; +@item +Change reading through tables to use memmap when possible. Now only +compressed tables use memmap. +@item +Add a new privilege @strong{'Show_priv'} for @code{SHOW} commands. +@item +Make the automatic timestamp code nicer. Add timestamps to the update +log with @code{SET TIMESTAMP=#;} +@item +Use read/write mutex in some places to get more speed. +@item +Full foreign key support. One probably wants to implement a procedural +language first. +@item +Simple views (first on one table, later on any expression). +@item +Automatically close some tables if a table, temporary table or temporary files +gets error 23 (not enough open files). +@item +When one finds a field=#, change all occurrences of field to #. Now this +is only done for some simple cases. +@item +Change all const expressions with calculated expressions if possible. +@item +Optimize key = expression. At the moment only key = field or key = +constant are optimized. +@item +Join some of the copy functions for nicer code. +@item +Change @file{sql_yacc.yy} to an inline parser to reduce its size and get +better error messages (5 days). +@item +Change the parser to use only one rule per different number of arguments +in function. +@item +Use of full calculation names in the order part. (For ACCESS97) +@item +@code{UNION}, @code{MINUS}, @code{INTERSECT} and @code{FULL OUTER JOIN}. +(Currently only @code{LEFT OUTER JOIN} is supported) +@item +Allow @code{UNIQUE} on fields that can be @code{NULL}. +@item +@code{SQL_OPTION MAX_SELECT_TIME=#} to put a time limit on a query. +@item +Make the update log to a database. +@item +Negative @code{LIMIT} to retrieve data from the end. +@item +Alarm around client connect/read/write functions. +@item +Please note the changes to @code{safe_mysqld}: according to FSSTND (which +Debian tries to follow) PID files should go into @file{/var/run/.pid} +and log files into @file{/var/log}. It would be nice if you could put the +"DATADIR" in the first declaration of "pidfile" and "log", so the +placement of these files can be changed with a single statement. +@item +Allow a client to request logging. +@item +Add use of @code{zlib()} for @code{gzip}-ed files to @code{LOAD DATA INFILE}. +@item +Fix sorting and grouping of @code{BLOB} columns (partly solved now). +@item +Stored procedures. This is currently not regarded to be very +important as stored procedures are not very standardized yet. +Another problem is that true stored procedures make it much harder for +the optimizer and in many cases the result is slower than before +We will, on the other hand, add a simple (atomic) update language that +can be used to write loops and such in the @strong{MySQL} server. +@item +Change to use semaphores when counting threads. One should first implement +a semaphore library to MIT-pthreads. +@item +Don't assign a new @code{AUTO_INCREMENT} value when one sets a column to 0. +Use @code{NULL} instead. +@item +Add full support for @code{JOIN} with parentheses. +@item +As an alternative for one thread / connection manage a pool of threads +to handle the queries. +@item +Allow one to get more than one lock with @code{GET_LOCK}. When doing this, +one must also handle the possible deadlocks this change will introduce. +@end itemize + +Time is given according to amount of work, not real time. + +@node TODO unplanned, , TODO sometime, TODO +@subsection Some things we don't have any plans to do + +@itemize @bullet +@item +Nothing; In the long run we plan to be fully ANSI 92 / ANSI 99 compliant. +@end itemize + +@node Installing, Privilege system, Introduction, Top @chapter Installing MySQL + @cindex installing, overview @menu @@ -11116,879 +13841,8 @@ After you import the @code{mysql} database on the new machine, execute @code{mysqladmin flush-privileges} so that the server reloads the grant table information. -@cindex compatibility, with ANSI SQL -@cindex standards compatibility -@cindex extensions, to ANSI SQL -@cindex ANSI SQL92, extensions to -@node Compatibility, Privilege system, Installing, Top -@chapter How Standards-compatible Is MySQL? -@menu -* Extensions to ANSI:: @strong{MySQL} extensions to ANSI SQL92 -* ANSI mode:: Running @strong{MySQL} in ANSI mode -* Differences from ANSI:: @strong{MySQL} differences compared to ANSI SQL92 -* Missing functions:: Functionality missing from @strong{MySQL} -* Standards:: What standards does @strong{MySQL} follow? -* Commit-rollback:: How to cope without @code{COMMIT}-@code{ROLLBACK} -@end menu - -This chapter describes how @strong{MySQL} relates to the ANSI SQL standards. -@strong{MySQL} has many extensions to the ANSI SQL standards, and here you -will find out what they are, and how to use them. You will also find -information about functionality missing from @strong{MySQL}, and how to work -around some differences. - -@node Extensions to ANSI, ANSI mode, Compatibility, Compatibility -@section MySQL Extensions to ANSI SQL92 - -@strong{MySQL} includes some extensions that you probably will not find in -other SQL databases. Be warned that if you use them, your code will not be -portable to other SQL servers. In some cases, you can write code that -includes @strong{MySQL} extensions, but is still portable, by using comments -of the form @code{/*! ... */}. In this case, @strong{MySQL} will parse and -execute the code within the comment as it would any other @strong{MySQL} -statement, but other SQL servers will ignore the extensions. For example: - -@example -SELECT /*! STRAIGHT_JOIN */ col_name FROM table1,table2 WHERE ... -@end example - -If you add a version number after the @code{'!'}, the syntax will only be -executed if the @strong{MySQL} version is equal to or newer than the used -version number: - -@example -CREATE /*!32302 TEMPORARY */ TABLE (a int); -@end example - -The above means that if you have Version 3.23.02 or newer, then @strong{MySQL} -will use the @code{TEMPORARY} keyword. - -@strong{MySQL} extensions are listed below: - -@itemize @bullet -@item -The field types @code{MEDIUMINT}, @code{SET}, @code{ENUM}, and the -different @code{BLOB} and @code{TEXT} types. - -@item -The field attributes @code{AUTO_INCREMENT}, @code{BINARY}, @code{NULL}, -@code{UNSIGNED}, and @code{ZEROFILL}. - -@item -All string comparisons are case insensitive by default, with sort -ordering determined by the current character set (ISO-8859-1 Latin1 by -default). If you don't like this, you should declare your columns with -the @code{BINARY} attribute or use the @code{BINARY} cast, which causes -comparisons to be done according to the ASCII order used on the -@strong{MySQL} server host. - -@item -@strong{MySQL} maps each database to a directory under the @strong{MySQL} -data directory, and tables within a database to filenames in the database -directory. - -This has a few implications: - -@cindex database names, case sensitivity -@cindex table names, case sensitivity -@cindex case sensitivity, of database names -@cindex case sensitivity, of table names - -@itemize @minus - -@item -Database names and table names are case sensitive in @strong{MySQL} on -operating systems that have case-sensitive filenames (like most Unix -systems). @xref{Name case sensitivity}. - -@item -Database, table, index, column, or alias names may begin with a digit -(but may not consist solely of digits). - -@item -You can use standard system commands to backup, rename, move, delete, and copy -tables. For example, to rename a table, rename the @file{.MYD}, @file{.MYI}, -and @file{.frm} files to which the table corresponds. -@end itemize - -@item -In SQL statements, you can access tables from different databases -with the @code{db_name.tbl_name} syntax. Some SQL servers provide -the same functionality but call this @code{User space}. -@strong{MySQL} doesn't support tablespaces as in: -@code{create table ralph.my_table...IN my_tablespace}. - -@item -@code{LIKE} is allowed on numeric columns. - -@item -Use of @code{INTO OUTFILE} and @code{STRAIGHT_JOIN} in a @code{SELECT} -statement. @xref{SELECT, , @code{SELECT}}. - -@item -The @code{SQL_SMALL_RESULT} option in a @code{SELECT} statement. - -@item -@code{EXPLAIN SELECT} to get a description on how tables are joined. - -@item -Use of index names, indexes on a prefix of a field, and use of -@code{INDEX} or @code{KEY} in a @code{CREATE TABLE} -statement. @xref{CREATE TABLE, , @code{CREATE TABLE}}. - -@item -Use of @code{TEMPORARY} or @code{IF NOT EXISTS} with @code{CREATE TABLE}. - -@item -Use of @code{COUNT(DISTINCT list)} where 'list' is more than one element. - -@item -Use of @code{CHANGE col_name}, @code{DROP col_name}, or @code{DROP -INDEX}, @code{IGNORE} or @code{RENAME} in an @code{ALTER TABLE} -statement. @xref{ALTER TABLE, , @code{ALTER TABLE}}. - -@item -Use of @code{RENAME TABLE}. @xref{RENAME TABLE, , @code{RENAME TABLE}}. - -@item -Use of multiple @code{ADD}, @code{ALTER}, @code{DROP}, or @code{CHANGE} -clauses in an @code{ALTER TABLE} statement. - -@item -Use of @code{DROP TABLE} with the keywords @code{IF EXISTS}. - -@item -You can drop multiple tables with a single @code{DROP TABLE} statement. - -@item -The @code{LIMIT} clause of the @code{DELETE} statement. - -@item -The @code{DELAYED} clause of the @code{INSERT} and @code{REPLACE} -statements. - -@item -The @code{LOW_PRIORITY} clause of the @code{INSERT}, @code{REPLACE}, -@code{DELETE}, and @code{UPDATE} statements. - -@cindex Oracle compatibility -@cindex compatibility, with Oracle -@item -Use of @code{LOAD DATA INFILE}. In many cases, this syntax is compatible with -Oracle's @code{LOAD DATA INFILE}. @xref{LOAD DATA, , @code{LOAD DATA}}. - -@item -The @code{ANALYZE TABLE}, @code{CHECK TABLE}, @code{OPTIMIZE TABLE}, and -@code{REPAIR TABLE} statements. - -@item -The @code{SHOW} statement. -@xref{SHOW, , @code{SHOW}}. - -@item -Strings may be enclosed by either @samp{"} or @samp{'}, not just by @samp{'}. - -@item -Use of the escape @samp{\} character. - -@item -The @code{SET OPTION} statement. @xref{SET OPTION, , @code{SET OPTION}}. - -@item -You don't need to name all selected columns in the @code{GROUP BY} part. -This gives better performance for some very specific, but quite normal -queries. -@xref{Group by functions}. - -@item -One can specify @code{ASC} and @code{DESC} with @code{GROUP BY}. - -@item -To make it easier for users who come from other SQL environments, -@strong{MySQL} supports aliases for many functions. For example, all -string functions support both ANSI SQL syntax and ODBC syntax. - -@item -@strong{MySQL} understands the @code{||} and @code{&&} operators to mean -logical OR and AND, as in the C programming language. In @strong{MySQL}, -@code{||} and @code{OR} are synonyms, as are @code{&&} and @code{AND}. -Because of this nice syntax, @strong{MySQL} doesn't support -the ANSI SQL @code{||} operator for string concatenation; use -@code{CONCAT()} instead. Because @code{CONCAT()} takes any number -of arguments, it's easy to convert use of the @code{||} operator to -@strong{MySQL}. - -@item -@code{CREATE DATABASE} or @code{DROP DATABASE}. -@xref{CREATE DATABASE, , @code{CREATE DATABASE}}. - -@cindex PostgreSQL compatibility -@cindex compatibility, with PostgreSQL -@item -The @code{%} operator is a synonym for @code{MOD()}. That is, -@code{N % M} is equivalent to @code{MOD(N,M)}. @code{%} is supported -for C programmers and for compatibility with PostgreSQL. - -@item -The @code{=}, @code{<>}, @code{<=} ,@code{<}, @code{>=},@code{>}, -@code{<<}, @code{>>}, @code{<=>}, @code{AND}, @code{OR}, or @code{LIKE} -operators may be used in column comparisons to the left of the -@code{FROM} in @code{SELECT} statements. For example: - -@example -mysql> SELECT col1=1 AND col2=2 FROM tbl_name; -@end example - -@item -The @code{LAST_INSERT_ID()} function. -@xref{mysql_insert_id, , @code{mysql_insert_id()}}. - -@item -The @code{REGEXP} and @code{NOT REGEXP} extended regular expression -operators. - -@item -@code{CONCAT()} or @code{CHAR()} with one argument or more than two -arguments. (In @strong{MySQL}, these functions can take any number of -arguments.) - -@item The @code{BIT_COUNT()}, @code{CASE}, @code{ELT()}, -@code{FROM_DAYS()}, @code{FORMAT()}, @code{IF()}, @code{PASSWORD()}, -@code{ENCRYPT()}, @code{md5()}, @code{ENCODE()}, @code{DECODE()}, -@code{PERIOD_ADD()}, @code{PERIOD_DIFF()}, @code{TO_DAYS()}, or -@code{WEEKDAY()} functions. - -@item -Use of @code{TRIM()} to trim substrings. ANSI SQL only supports removal -of single characters. - -@item -The @code{GROUP BY} functions @code{STD()}, @code{BIT_OR()}, and -@code{BIT_AND()}. - -@item -Use of @code{REPLACE} instead of @code{DELETE} + @code{INSERT}. -@xref{REPLACE, , @code{REPLACE}}. - -@item -The @code{FLUSH flush_option} statement. - -@item -The possibility to set variables in a statement with @code{:=}: -@example -SELECT @@a:=SUM(total),@@b=COUNT(*),@@a/@@b AS avg FROM test_table; -SELECT @@t1:=(@@t2:=1)+@@t3:=4,@@t1,@@t2,@@t3; -@end example - -@end itemize - -@node ANSI mode, Differences from ANSI, Extensions to ANSI, Compatibility -@section Running MySQL in ANSI Mode -@cindex running, ANSI mode -@cindex ANSI mode, running - -If you start @code{mysqld} with the @code{--ansi} option, the following behavior -of @strong{MySQL} changes: - -@itemize @bullet -@item -@code{||} is string concatenation instead of @code{OR}. -@item -You can have any number of spaces between a function name and the @samp{(}. -This forces all function names to be treated as reserved words. -@item -@samp{"} will be an identifier quote character (like the @strong{MySQL} -@samp{`} quote character) and not a string quote character. -@item -@code{REAL} will be a synonym for @code{FLOAT} instead of a synonym of -@code{DOUBLE}. -@item -The default transaction isolation level is @code{SERIALIZABLE}. -@xref{SET TRANSACTION}. -@end itemize - -@node Differences from ANSI, Missing functions, ANSI mode, Compatibility -@section MySQL Differences Compared to ANSI SQL92 - -We try to make @strong{MySQL} follow the ANSI SQL standard and the -ODBC SQL standard, but in some cases @strong{MySQL} does some things -differently: - -@itemize @bullet -@item -@code{--} is only a comment if followed by a white space. @xref{Missing -comments}. -@item -For @code{VARCHAR} columns, trailing spaces are removed when the value is -stored. @xref{Bugs}. -@item -In some cases, @code{CHAR} columns are silently changed to @code{VARCHAR} -columns. @xref{Silent column changes}. -@item -Privileges for a table are not automatically revoked when you delete a -table. You must explicitly issue a @code{REVOKE} to revoke privileges for -a table. @xref{GRANT, , @code{GRANT}}. -@item -@code{NULL AND FALSE} will evaluate to @code{NULL} and not to @code{FALSE}. -This is because we don't think it's good to have to evaluate a lot of -extra conditions in this case. -@end itemize - -@node Missing functions, Standards, Differences from ANSI, Compatibility -@section Functionality Missing from MySQL -@cindex missing functionality -@cindex functionality, missing - -The following functionality is missing in the current version of -@strong{MySQL}. For a prioritized list indicating when new extensions -may be added to @strong{MySQL}, you should consult -@uref{http://www.mysql.com/documentation/manual.php?section=TODO, the -online @strong{MySQL} TODO list}. That is the latest version of the TODO -list in this manual. @xref{TODO}. - -@menu -* Missing Sub-selects:: Sub-selects -* Missing SELECT INTO TABLE:: @code{SELECT INTO TABLE} -* Missing Transactions:: Transactions -* Missing Triggers:: Triggers -* Missing Foreign Keys:: Foreign Keys -* Missing Views:: Views -* Missing comments:: @samp{--} as the start of a comment -@end menu - -@node Missing Sub-selects, Missing SELECT INTO TABLE, Missing functions, Missing functions -@subsection Sub-selects -@cindex sub-selects - -The following will not yet work in @strong{MySQL}: - -@example -SELECT * FROM table1 WHERE id IN (SELECT id FROM table2); -SELECT * FROM table1 WHERE id NOT IN (SELECT id FROM table2); -SELECT * FROM table1 WHERE NOT EXISTS (SELECT id FROM table2 where table1.id=table2.id); -@end example - -However, in many cases you can rewrite the query without a sub-select: - -@example -SELECT table1.* FROM table1,table2 WHERE table1.id=table2.id; -SELECT table1.* FROM table1 LEFT JOIN table2 ON table1.id=table2.id where table2.id IS NULL -@end example - -For more complicated subqueries you can often create temporary tables -to hold the subquery. In some cases, however this option will not -work. The most frequently encountered of these cases arises with -@code{DELETE} statements, for which standard SQL does not support joins -(except in sub-selects). For this situation there are two options -available until subqueries are supported by @strong{MySQL}. - -The first option is to use a procedural programming language (such as -Perl or PHP) to submit a @code{SELECT} query to obtain the primary keys -for the records to be deleted, and then use these values to construct -the @code{DELETE} statement (@code{DELETE FROM ... WHERE ... IN (key1, -key2, ...)}). - -The second option is to use interactive SQL to contruct a set of -@code{DELETE} statements automatically, using the @strong{MySQL} -extension @code{CONCAT()} (in lieu of the standard @code{||} operator). -For example: - -@example -SELECT CONCAT('DELETE FROM tab1 WHERE pkid = ', tab1.pkid, ';') - FROM tab1, tab2 - WHERE tab1.col1 = tab2.col2; -@end example - -You can place this query in a script file and redirect input from it to -the @code{mysql} command-line interpreter, piping its output back to a -second instance of the interpreter: - -@example -prompt> mysql --skip-column-names mydb < myscript.sql | mysql mydb -@end example - -@strong{MySQL} only supports @code{INSERT ... SELECT ...} and -@code{REPLACE ... SELECT ...} Independent sub-selects will probably -be available in Version 4.0. You can now use the function @code{IN()} in -other contexts, however. - -@node Missing SELECT INTO TABLE, Missing Transactions, Missing Sub-selects, Missing functions -@subsection @code{SELECT INTO TABLE} -@findex SELECT INTO TABLE - -@strong{MySQL} doesn't yet support the Oracle SQL extension: -@code{SELECT ... INTO TABLE ...}. @strong{MySQL} supports instead the -ANSI SQL syntax @code{INSERT INTO ... SELECT ...}, which is basically -the same thing. @xref{INSERT SELECT}. - -@example -INSERT INTO tblTemp2 (fldID) SELECT tblTemp1.fldOrder_ID FROM tblTemp1 WHERE -tblTemp1.fldOrder_ID > 100; -@end example - -Alternatively, you can use @code{SELECT INTO OUTFILE...} or @code{CREATE -TABLE ... SELECT} to solve your problem. - -@node Missing Transactions, Missing Triggers, Missing SELECT INTO TABLE, Missing functions -@subsection Transactions -@cindex transactions, support - -As @strong{MySQL} does nowadays support transactions, the following -discussion is only valid if you are only using the non-transaction-safe -table types. @xref{COMMIT}. - -The question is often asked, by the curious and the critical, ``Why is -@strong{MySQL} not a transactional database?'' or ``Why does @strong{MySQL} -not support transactions?'' - -@strong{MySQL} has made a conscious decision to support another paradigm -for data integrity, ``atomic operations.'' It is our thinking and -experience that atomic operations offer equal or even better integrity -with much better performance. We, nonetheless, appreciate and understand -the transactional database paradigm and plan, within the next few releases, -to introduce transaction-safe tables on a per table basis. We will be -giving our users the possibility to decide if they need the speed of -atomic operations or if they need to use transactional features in their -applications. - -How does one use the features of @strong{MySQL} to maintain rigorous integrity -and how do these features compare with the transactional paradigm? - -First, in the transactional paradigm, if your applications are written -in a way that is dependent on the calling of ``rollback'' instead of -``commit'' in critical situations, then transactions are more -convenient. Moreover, transactions ensure that unfinished updates or -corrupting activities are not committed to the database; the server is -given the opportunity to do an automatic rollback and your database is -saved. - -@strong{MySQL}, in almost all cases, allows you to solve for potential -problems by including simple checks before updates and by running simple -scripts that check the databases for inconsistencies and automatically -repair or warn if such occurs. Note that just by using the -@strong{MySQL} log or even adding one extra log, one can normally fix -tables perfectly with no data integrity loss. - -Moreover, fatal transactional updates can be rewritten to be -atomic. In fact,we will go so far as to say that all integrity problems -that transactions solve can be done with @code{LOCK TABLES} or atomic updates, -ensuring that you never will get an automatic abort from the database, -which is a common problem with transactional databases. - -Not even transactions can prevent all loss if the server goes down. In -such cases even a transactional system can lose data. The difference -between different systems lies in just how small the time-lap is where -they could lose data. No system is 100% secure, only ``secure -enough.'' Even Oracle, reputed to be the safest of transactional -databases, is reported to sometimes lose data in such situations. - -To be safe with @strong{MySQL}, you only need to have backups and have -the update logging turned on. With this you can recover from any -situation that you could with any transactional database. It is, of -course, always good to have backups, independent of which database you -use. - -The transactional paradigm has its benefits and its drawbacks. Many -users and application developers depend on the ease with which they can -code around problems where an abort appears to be, or is necessary, and they -may have to do a little more work with @strong{MySQL} to either think -differently or write more. If you are new to the atomic operations -paradigm, or more familiar or more comfortable with transactions, do not -jump to the conclusion that @strong{MySQL} has not addressed these -issues. Reliability and integrity are foremost in our minds. Recent -estimates indicate that there are more than 1,000,000 @code{mysqld} servers -currently running, many of which are in production environments. We -hear very, very seldom from our users that they have lost any data, and -in almost all of those cases user error is involved. This is, in our -opinion, the best proof of @strong{MySQL}'s stability and reliability. - -Lastly, in situations where integrity is of highest importance, -@strong{MySQL}'s current features allow for transaction-level or better -reliability and integrity. If you lock tables with @code{LOCK TABLES}, all -updates will stall until any integrity checks are made. If you only obtain -a read lock (as opposed to a write lock), then reads and inserts are -still allowed to happen. The new inserted records will not be seen by -any of the clients that have a @code{READ} lock until they release their read -locks. With @code{INSERT DELAYED} you can queue inserts into a local queue, -until the locks are released, without having the client wait for the insert -to complete. @xref{INSERT DELAYED}. - -``Atomic,'' in the sense that we mean it, is nothing magical. It only means -that you can be sure that while each specific update is running, no other -user can interfere with it, and there will never be an automatic -rollback (which can happen on transaction based systems if you are not -very careful). @strong{MySQL} also guarantees that there will not be -any dirty reads. You can find some example of how to write atomic updates -in the commit-rollback section. @xref{Commit-rollback}. - -We have thought quite a bit about integrity and performance, and we -believe that our atomic operations paradigm allows for both high -reliability and extremely high performance, on the order of three to -five times the speed of the fastest and most optimally tuned of -transactional databases. We didn't leave out transactions because they -are hard to do. The main reason we went with atomic operations as -opposed to transactions is that by doing this we could apply many speed -optimizations that would not otherwise have been possible. - -Many of our users who have speed foremost in their minds are not at all -concerned about transactions. For them transactions are not an -issue. For those of our users who are concerned with or have wondered -about transactions vis-a-vis @strong{MySQL}, there is a ``@strong{MySQL} -way'' as we have outlined above. For those where safety is more -important than speed, we recommend them to use the @code{BDB}, -or @code{InnoDB} tables for all their critical data. @xref{Table types}. - -One final note: We are currently working on a safe replication schema -that we believe to be better than any commercial replication system we -know of. This system will work most reliably under the atomic -operations, non-transactional, paradigm. Stay tuned. - -@node Missing Triggers, Missing Foreign Keys, Missing Transactions, Missing functions -@subsection Stored Procedures and Triggers -@cindex stored procedures and triggers, defined -@cindex procedures, stored -@cindex triggers, stored - - -A stored procedure is a set of SQL commands that can be compiled and stored -in the server. Once this has been done, clients don't need to keep reissuing -the entire query but can refer to the stored procedure. This provides better -performance because the query has to be parsed only once, and less information -needs to be sent between the server and the client. You can also raise the -conceptual level by having libraries of functions in the server. - -A trigger is a stored procedure that is invoked when a particular event -occurs. For example, you can install a stored procedure that is triggered -each time a record is deleted from a transaction table and that automatically -deletes the corresponding customer from a customer table when all his -transactions are deleted. - -The planned update language will be able to -handle stored procedures, but without triggers. Triggers usually slow -down everything, even queries for which they are not needed. - -To see when @strong{MySQL} might get stored procedures, see @ref{TODO}. - -@node Missing Foreign Keys, Missing Views, Missing Triggers, Missing functions -@subsection Foreign Keys -@cindex foreign keys -@cindex keys, foreign - -Note that foreign keys in SQL are not used to join tables, but are used -mostly for checking referential integrity (foreign key constraints). If -you want to get results from multiple tables from a @code{SELECT} -statement, you do this by joining tables: - -@example -SELECT * from table1,table2 where table1.id = table2.id; -@end example - -@xref{JOIN, , @code{JOIN}}. @xref{example-Foreign keys}. - -The @code{FOREIGN KEY} syntax in @strong{MySQL} exists only for compatibility -with other SQL vendors' @code{CREATE TABLE} commands; it doesn't do -anything. The @code{FOREIGN KEY} syntax without @code{ON DELETE ...} is -mostly used for documentation purposes. Some ODBC applications may use this -to produce automatic @code{WHERE} clauses, but this is usually easy to -override. @code{FOREIGN KEY} is sometimes used as a constraint check, but -this check is unnecessary in practice if rows are inserted into the tables in -the right order. @strong{MySQL} only supports these clauses because some -applications require them to exist (regardless of whether or not they -work). - -In @strong{MySQL}, you can work around the problem of @code{ON DELETE -...} not being implemented by adding the appropriate @code{DELETE} statement to -an application when you delete records from a table that has a foreign key. -In practice this is as quick (in some cases quicker) and much more portable -than using foreign keys. - -In the near future we will extend the @code{FOREIGN KEY} implementation so -that at least the information will be saved in the table specification file -and may be retrieved by @code{mysqldump} and ODBC. At a later stage we will -implement the foreign key constraints for application that can't easily be -coded to avoid them. - -@menu -* Broken Foreign KEY:: Reasons NOT to use foreign keys constraints -@end menu - -@node Broken Foreign KEY, , Missing Foreign Keys, Missing Foreign Keys -@subsubsection Reasons NOT to Use Foreign Keys constraints -@cindex foreign keys, reasons not to use - -There are so many problems with foreign key constraints that we don't -know where to start: - -@itemize @bullet -@item -Foreign key constraints make life very complicated, because the foreign -key definitions must be stored in a database and implementing them would -destroy the whole ``nice approach'' of using files that can be moved, -copied, and removed. - -@item -The speed impact is terrible for @code{INSERT} and @code{UPDATE} -statements, and in this case almost all @code{FOREIGN KEY} constraint -checks are useless because you usually insert records in the right -tables in the right order, anyway. - -@item -There is also a need to hold locks on many more tables when updating one -table, because the side effects can cascade through the entire database. It's -MUCH faster to delete records from one table first and subsequently delete -them from the other tables. - -@item -You can no longer restore a table by doing a full delete from the table -and then restoring all records (from a new source or from a backup). - -@item -If you use foreign key constraints you can't dump and restore tables -unless you do so in a very specific order. - -@item -It's very easy to do ``allowed'' circular definitions that make the -tables impossible to re-create each table with a single create statement, -even if the definition works and is usable. - -@item -It's very easy to overlook @code{FOREIGN KEY ... ON DELETE} rules when -one codes an application. It's not unusual that one loses a lot of -important information just because a wrong or misused @code{ON DELETE} rule. -@end itemize - -The only nice aspect of @code{FOREIGN KEY} is that it gives ODBC and some -other client programs the ability to see how a table is connected and to use -this to show connection diagrams and to help in building applications. - -@strong{MySQL} will soon store @code{FOREIGN KEY} definitions so that a -client can ask for and receive an answer about how the original -connection was made. The current @file{.frm} file format does not have -any place for it. At a later stage we will implement the foreign key -constraints for application that can't easily be coded to avoid them. - -@node Missing Views, Missing comments, Missing Foreign Keys, Missing functions -@subsection Views -@cindex views - -@strong{MySQL} doesn't yet support views, but we plan to implement these -to about 4.1. - -Views are mostly useful for letting users access a set of relations as one -table (in read-only mode). Many SQL databases don't allow one to update -any rows in a view, but you have to do the updates in the separate tables. - -As @strong{MySQL} is mostly used in applications and on web system where -the application writer has full control on the database usage, most of -our users haven't regarded views to be very important. (At least no one -has been interested enough in this to be prepared to finance the -implementation of views). - -One doesn't need views in @strong{MySQL} to restrict access to columns -as @strong{MySQL} has a very sophisticated privilege -system. @xref{Privilege system}. - -@node Missing comments, , Missing Views, Missing functions -@subsection @samp{--} as the Start of a Comment -@cindex comments, starting -@cindex starting, comments - -Some other SQL databases use @samp{--} to start comments. @strong{MySQL} -has @samp{#} as the start comment character, even if the @code{mysql} -command-line tool removes all lines that start with @samp{--}. -You can also use the C comment style @code{/* this is a comment */} with -@strong{MySQL}. -@xref{Comments}. - -@strong{MySQL} Version 3.23.3 and above supports the @samp{--} comment style -only if the comment is followed by a space. This is because this -degenerate comment style has caused many problems with automatically -generated SQL queries that have used something like the following code, -where we automatically insert the value of the payment for -@code{!payment!}: - -@example -UPDATE tbl_name SET credit=credit-!payment! -@end example - -What do you think will happen when the value of @code{payment} is negative? - -Because @code{1--1} is legal in SQL, we think it is terrible that -@samp{--} means start comment. - -In @strong{MySQL} Version 3.23 you can, however, use: -@code{1-- This is a comment} - -The following discussion only concerns you if you are running a @strong{MySQL} -version earlier than Version 3.23: - -If you have a SQL program in a text file that contains @samp{--} comments -you should use: - -@example -shell> replace " --" " #" < text-file-with-funny-comments.sql \ - | mysql database -@end example - -instead of the usual: - -@example -shell> mysql database < text-file-with-funny-comments.sql -@end example - -You can also edit the command file ``in place'' to change the @samp{--} -comments to @samp{#} comments: - -@example -shell> replace " --" " #" -- text-file-with-funny-comments.sql -@end example - -Change them back with this command: - -@example -shell> replace " #" " --" -- text-file-with-funny-comments.sql -@end example - -@node Standards, Commit-rollback, Missing functions, Compatibility -@section What Standards Does MySQL Follow? - -Entry level SQL92. ODBC levels 0-2. - -@node Commit-rollback, , Standards, Compatibility -@section How to Cope Without @code{COMMIT}/@code{ROLLBACK} -@findex COMMIT -@findex ROLLBACK -@cindex transaction-safe tables -@cindex tables, updating -@cindex updating, tables -@cindex @code{BDB} tables -@cindex @code{InnoDB} tables - -The following mostly applies only for @code{ISAM}, @code{MyISAM}, and -@code{HEAP} tables. If you only use transaction-safe tables (@code{BDB}, -or @code{InnoDB} tables) in an an update, you can do -@code{COMMIT} and @code{ROLLBACK} also with @strong{MySQL}. -@xref{COMMIT}. - -The problem with handling @code{COMMIT}-@code{ROLLBACK} efficiently with -the above table types would require a completely different table layout -than @strong{MySQL} uses today. The table type would also need extra -threads that do automatic cleanups on the tables, and the disk usage -would be much higher. This would make these table types about 2-4 times -slower than they are today. - -For the moment, we prefer implementing the SQL server language (something -like stored procedures). With this you would very seldom really need -@code{COMMIT}-@code{ROLLBACK.} This would also give much better performance. - -Loops that need transactions normally can be coded with the help of -@code{LOCK TABLES}, and you don't need cursors when you can update records -on the fly. - -We at TcX had a greater need for a real fast database than a 100% -general database. Whenever we find a way to implement these features without -any speed loss, we will probably do it. For the moment, there are many more -important things to do. Check the TODO for how we prioritize things at -the moment. (Customers with higher levels of support can alter this, so -things may be reprioritized.) - -The current problem is actually @code{ROLLBACK}. Without -@code{ROLLBACK}, you can do any kind of @code{COMMIT} action with -@code{LOCK TABLES}. To support @code{ROLLBACK} with the above table -types, @strong{MySQL} would have to be changed to store all old records -that were updated and revert everything back to the starting point if -@code{ROLLBACK} was issued. For simple cases, this isn't that hard to do -(the current @code{isamlog} could be used for this purpose), but it -would be much more difficult to implement @code{ROLLBACK} for -@code{ALTER/DROP/CREATE TABLE}. - -To avoid using @code{ROLLBACK}, you can use the following strategy: - -@enumerate -@item -Use @code{LOCK TABLES ...} to lock all the tables you want to access. -@item -Test conditions. -@item -Update if everything is okay. -@item -Use @code{UNLOCK TABLES} to release your locks. -@end enumerate - -This is usually a much faster method than using transactions with possible -@code{ROLLBACK}s, although not always. The only situation this solution -doesn't handle is when someone kills the threads in the middle of an -update. In this case, all locks will be released but some of the updates may -not have been executed. - -You can also use functions to update records in a single operation. -You can get a very efficient application by using the following techniques: - -@itemize @bullet -@item Modify fields relative to their current value. -@item Update only those fields that actually have changed. -@end itemize - -For example, when we are doing updates to some customer information, we -update only the customer data that has changed and test only that none of -the changed data, or data that depend on the changed data, has changed -compared to the original row. The test for changed data is done with the -@code{WHERE} clause in the @code{UPDATE} statement. If the record wasn't -updated, we give the client a message: "Some of the data you have changed -have been changed by another user". Then we show the old row versus the new -row in a window, so the user can decide which version of the customer record -he should use. - -This gives us something that is similar to column locking but is actually -even better, because we only update some of the columns, using values that -are relative to their current values. This means that typical @code{UPDATE} -statements look something like these: - -@example -UPDATE tablename SET pay_back=pay_back+'relative change'; - -UPDATE customer - SET - customer_date='current_date', - address='new address', - phone='new phone', - money_he_owes_us=money_he_owes_us+'new_money' - WHERE - customer_id=id AND address='old address' AND phone='old phone'; -@end example - -As you can see, this is very efficient and works even if another client has -changed the values in the @code{pay_back} or @code{money_he_owes_us} columns. - -@findex mysql_insert_id() -@findex LAST_INSERT_ID() -In many cases, users have wanted @code{ROLLBACK} and/or @code{LOCK -TABLES} for the purpose of managing unique identifiers for some tables. This -can be handled much more efficiently by using an @code{AUTO_INCREMENT} column -and either the SQL function @code{LAST_INSERT_ID()} or the C API function -@code{mysql_insert_id()}. @xref{mysql_insert_id, , @code{mysql_insert_id()}}. - -@cindex rows, locking -At @strong{MySQL AB}, we have never had any need for row-level locking -because we have always been able to code around it. Some cases really need -row locking, but they are very few. If you want row-level locking, you -can use a flag column in the table and do something like this: - -@example -UPDATE tbl_name SET row_flag=1 WHERE id=ID; -@end example - -@strong{MySQL} returns 1 for the number of affected rows if the row was -found and @code{row_flag} wasn't already 1 in the original row. - -You can think of it as @strong{MySQL} changed the above query to: - -@example -UPDATE tbl_name SET row_flag=1 WHERE id=ID and row_flag <> 1; -@end example - -@node Privilege system, Reference, Compatibility, Top +@node Privilege system, Reference, Installing, Top @chapter The MySQL Access Privilege System @cindex system, security @cindex access privileges @@ -25865,7 +27719,7 @@ Finland @cindex tables, @code{BDB} @cindex tables, @code{Berkeley DB} -@node BDB, , InnoDB, Table types +@node BDB, , InnoDB, Table types @section BDB or Berkeley_DB Tables @menu @@ -28536,7 +30390,6 @@ group by @menu * Languages:: What languages are supported by @strong{MySQL}? -* Table size:: How big @strong{MySQL} tables can be @end menu This chapter describes the languages @strong{MySQL} supports, how sorting @@ -28547,7 +30400,7 @@ You will also find information about maximum table sizes in this chapter. @cindex messages, languages @cindex files, error messages @cindex language support -@node Languages, Table size, Server, Server +@node Languages, , Server, Server @section What Languages Are Supported by MySQL? @code{mysqld} can issue error messages in the following languages: @@ -28861,60 +30714,6 @@ You must specify the @code{mbmaxlen_MYSET=N} value in the special comment at the top of the source file. @code{N} should be set to the size in bytes of the largest character in the set. -@cindex tables, maximum size -@cindex size of tables -@cindex operating systems, file size limits -@cindex limits, file size -@cindex files, size limits -@node Table size, , Languages, Server -@section How Big MySQL Tables Can Be - -@strong{MySQL} Version 3.22 has a 4G limit on table size. With the new -@code{MyISAM} in @strong{MySQL} Version 3.23 the maximum table size is -pushed up to 8 million terabytes (2 ^ 63 bytes). - -Note, however, that operating systems have their own file size -limits. Here are some examples: - -@multitable @columnfractions .5 .5 -@item @strong{Operating System} @tab @strong{File Size Limit} -@item Linux-Intel 32 bit @tab 2G, 4G or more, depends on Linux version -@item Linux-Alpha @tab 8T (?) -@item Solaris 2.5.1 @tab 2G (possible 4G with patch) -@item Solaris 2.6 @tab 4G -@item Solaris 2.7 Intel @tab 4G -@item Solaris 2.7 ULTRA-SPARC @tab 8T (?) -@end multitable - -On Linux 2.2 you can get bigger tables than 2G by using the LFS patch for -the ext2 file system. On Linux 2.4 there exists also patches for ReiserFS -to get support for big files. - -This means that the table size for @strong{MySQL} is normally limited by -the operating system. - -By default, @strong{MySQL} tables have a maximum size of about 4G. You can -check the maximum table size for a table with the @code{SHOW TABLE STATUS} -command or with the @code{myisamchk -dv table_name}. -@xref{SHOW}. - -If you need bigger tables than 4G (and your operating system supports -this), you should set the @code{AVG_ROW_LENGTH} and @code{MAX_ROWS} -parameter when you create your table. @xref{CREATE TABLE}. You can -also set these later with @code{ALTER TABLE}. @xref{ALTER TABLE}. - -If your big table is going to be read-only, you could use -@code{myisampack} to merge and compress many tables to one. -@code{myisampack} usually compresses a table by at least 50%, so you can -have, in effect, much bigger tables. @xref{myisampack, , -@code{myisampack}}. - -You can go around the operating system file limit for @code{MyISAM} data -files by using the @code{RAID} option. @xref{CREATE TABLE}. - -Another solution can be the included MERGE library, which allows you to -handle a collection of identical tables as one. @xref{MERGE, MERGE -tables}. @cindex replication @cindex increasing, speed @@ -39027,7 +40826,7 @@ to the master database. @xref{Log Replication}. @cindex @code{mysqlclient} library @cindex buffer sizes, client @cindex library, @code{mysqlclient} -@node Clients, Comparisons, Log files, Top +@node Clients, MySQL internals, Log files, Top @chapter MySQL APIs @menu @@ -42488,1000 +44287,11 @@ The @uref{http://www.mysql.com/Downloads/Contrib,Contrib directory} contains a Tcl interface that is based on msqltcl 1.50. -@cindex databases, MySQL vs. others -@cindex comparisons, MySQL vs. others -@node Comparisons, MySQL internals, Clients, Top -@chapter How MySQL Compares to Other Databases -@menu -* Compare mSQL:: How @strong{MySQL} compares to @code{mSQL} -* Compare PostgreSQL:: How @strong{MySQL} compares with PostgreSQL -@end menu - -This chapter compares @strong{MySQL} to other popular databases. - -This chapter has been written by the @strong{MySQL} developers, so it -should be read with that in mind. There are no factual errors contained -in this chapter that we know of. If you find something which you believe -to be an error, please contact us about it at @email{docs@@mysql.com}. - -For a list of all supported limits, functions, and types, see the -@code{crash-me} Web page at -@uref{http://www.mysql.com/information/crash-me.php}. - -@node Compare mSQL, Compare PostgreSQL, Comparisons, Comparisons -@section How MySQL Compares to @code{mSQL} - -@table @strong -@item Performance - -For a true comparison of speed, consult the growing @strong{MySQL} benchmark -suite. @xref{Benchmarks}. - -Because there is no thread creation overhead, a small parser, few features, and -simple security, @code{mSQL} should be quicker at: - -@itemize @bullet -@item -Tests that perform repeated connects and disconnects, running a very simple -query during each connection. -@item -@code{INSERT} operations into very simple tables with few columns and keys. -@item -@code{CREATE TABLE} and @code{DROP TABLE}. -@item -@code{SELECT} on something that isn't an index. (A table scan is very -easy.) -@end itemize - -Because these operations are so simple, it is hard to be better at them when -you have a higher startup overhead. After the connection is established, -@strong{MySQL} should perform much better. - -On the other hand, @strong{MySQL} is much faster than @code{mSQL} (and -most other SQL implementations) on the following: - -@itemize @bullet -@item -Complex @code{SELECT} operations. -@item -Retrieving large results (@strong{MySQL} has a better, faster, and safer -protocol). -@item -Tables with variable-length strings, because @strong{MySQL} has more efficient -handling and can have indexes on @code{VARCHAR} columns. -@item -Handling tables with many columns. -@item -Handling tables with large record lengths. -@item -@code{SELECT} with many expressions. -@item -@code{SELECT} on large tables. -@item -Handling many connections at the same time. @strong{MySQL} is fully -multi-threaded. Each connection has its own thread, which means that -no thread has to wait for another (unless a thread is modifying -a table another thread wants to access). In @code{mSQL}, once one connection -is established, all others must wait until the first has finished, regardless -of whether the connection is running a query that is short or long. When the -first connection terminates, the next can be served, while all the others wait -again, etc. -@item -Joins. -@code{mSQL} can become pathologically slow if you change the order of tables -in a @code{SELECT}. In the benchmark suite, a time more than 15000 times -slower than @strong{MySQL} was seen. This is due to @code{mSQL}'s lack of a -join optimizer to order tables in the optimal order. However, if you put the -tables in exactly the right order in @code{mSQL}2 and the @code{WHERE} is -simple and uses index columns, the join will be relatively fast! -@xref{Benchmarks}. -@item -@code{ORDER BY} and @code{GROUP BY}. -@item -@code{DISTINCT}. -@item -Using @code{TEXT} or @code{BLOB} columns. -@end itemize - -@item SQL Features - -@itemize @bullet -@item @code{GROUP BY} and @code{HAVING}. -@code{mSQL} does not support @code{GROUP BY} at all. -@strong{MySQL} supports a full @code{GROUP BY} with both @code{HAVING} and -the following functions: @code{COUNT()}, @code{AVG()}, @code{MIN()}, -@code{MAX()}, @code{SUM()}, and @code{STD()}. @code{COUNT(*)} is optimized to -return very quickly if the @code{SELECT} retrieves from one table, no other -columns are retrieved, and there is no @code{WHERE} clause. @code{MIN()} and -@code{MAX()} may take string arguments. - -@item @code{INSERT} and @code{UPDATE} with calculations. -@strong{MySQL} can do calculations in an @code{INSERT} or @code{UPDATE}. -For example: -@example -mysql> UPDATE SET x=x*10+y WHERE x<20; -@end example - -@item Aliasing. -@strong{MySQL} has column aliasing. - -@item Qualifying column names. -In @strong{MySQL}, if a column name is unique among the tables used in a -query, you do not have to use the full qualifier. - -@item @code{SELECT} with functions. -@strong{MySQL} has many functions (too many to list here; see @ref{Functions}). - -@end itemize - -@item Disk Space Efficiency -That is, how small can you make your tables? - -@strong{MySQL} has very precise types, so you can create tables that take -very little space. An example of a useful @strong{MySQL} datatype is the -@code{MEDIUMINT} that is 3 bytes long. If you have 100,000,000 records, -saving even one byte per record is very important. - -@code{mSQL2} has a more limited set of column types, so it is -more difficult to get small tables. -@item Stability -This is harder to judge objectively. For a discussion of @strong{MySQL} -stability, see @ref{Stability}. - -We have no experience with @code{mSQL} stability, so we cannot say -anything about that. - -@item Price -Another important issue is the license. @strong{MySQL} has a -more flexible license than @code{mSQL}, and is also less expensive than -@code{mSQL}. Whichever product you choose to use, remember to at least -consider paying for a license or e-mail support. (You are required to get -a license if you include @strong{MySQL} with a product that you sell, -of course.) - -@item Perl Interfaces -@strong{MySQL} has basically the same interfaces to Perl as @code{mSQL} with -some added features. - -@item JDBC (Java) -@strong{MySQL} currently has a lot of different JDBC drivers: -@itemize @bullet -@item -The mm driver: A type 4 JDBC driver by Mark Matthews -@email{mmatthew@@ecn.purdue.edu}. This is released under the LGPL. -@item -The Resin driver. This is a commercial JDBC driver released under open -source. @uref{http://www.caucho.com/projects/jdbc-mysql/index.xtp} -@item -The gwe driver: A Java interface by GWE technologies (not supported anymore). -@item -The jms driver: An improved gwe driver by Xiaokun Kelvin ZHU -@email{X.Zhu@@brad.ac.uk} (not supported anymore). -@item -The twz driver: A type 4 JDBC driver by Terrence W. Zellers -@email{zellert@@voicenet.com}. This is commercial but is free for private -and educational use (not supported anymore). -@end itemize - -The recommended driver is the mm driver. The Resin driver may also be -good (at least the benchmarks looks good), but we haven't received that much -information about this yet. - -We know that @code{mSQL} has a JDBC driver, but we have too little experience -with it to compare. - -@item Rate of Development -@strong{MySQL} has a very small team of developers, but we are quite -used to coding C and C++ very rapidly. Because threads, functions, -@code{GROUP BY}, and so on are still not implemented in @code{mSQL}, it -has a lot of catching up to do. To get some perspective on this, you -can view the @code{mSQL} @file{HISTORY} file for the last year and -compare it with the News section of the @strong{MySQL} Reference Manual -(@pxref{News}). It should be pretty obvious which one has developed -most rapidly. - -@item Utility Programs -Both @code{mSQL} and @strong{MySQL} have many interesting third-party -tools. Because it is very easy to port upward (from @code{mSQL} to -@strong{MySQL}), almost all the interesting applications that are available for -@code{mSQL} are also available for @strong{MySQL}. - -@strong{MySQL} comes with a simple @code{msql2mysql} program that fixes -differences in spelling between @code{mSQL} and @strong{MySQL} for the -most-used C API functions. -For example, it changes instances of @code{msqlConnect()} to -@code{mysql_connect()}. Converting a client program from @code{mSQL} to -@strong{MySQL} usually takes a couple of minutes. -@end table - -@menu -* Using mSQL tools:: How to convert @code{mSQL} tools for @strong{MySQL} -* Protocol differences:: How @code{mSQL} and @strong{MySQL} client/server communications protocols differ -* Syntax differences:: How @code{mSQL} 2.0 SQL syntax differs from @strong{MySQL} -@end menu - -@cindex MySQL tools, conversion -@cindex converting, tools -@cindex tools, converting -@node Using mSQL tools, Protocol differences, Compare mSQL, Compare mSQL -@subsection How to Convert @code{mSQL} Tools for MySQL - -According to our experience, it would just take a few hours to convert tools -such as @code{msql-tcl} and @code{msqljava} that use the -@code{mSQL} C API so that they work with the @strong{MySQL} C API. - -The conversion procedure is: - -@enumerate -@item -Run the shell script @code{msql2mysql} on the source. This requires the -@code{replace} program, which is distributed with @strong{MySQL}. -@item -Compile. -@item -Fix all compiler errors. -@end enumerate - -Differences between the @code{mSQL} C API and the @strong{MySQL} C API are: -@itemize @bullet -@item -@strong{MySQL} uses a @code{MYSQL} structure as a connection type (@code{mSQL} -uses an @code{int}). -@item -@code{mysql_connect()} takes a pointer to a @code{MYSQL} structure as a -parameter. It is easy to define one globally or to use @code{malloc()} to get -one. -@code{mysql_connect()} also takes two parameters for specifying the user and -password. You may set these to @code{NULL, NULL} for default use. -@item -@code{mysql_error()} takes the @code{MYSQL} structure as a parameter. Just add -the parameter to your old @code{msql_error()} code if you are porting old code. -@item -@strong{MySQL} returns an error number and a text error message for all -errors. @code{mSQL} returns only a text error message. -@item -Some incompatibilities exist as a result of @strong{MySQL} supporting -multiple connections to the server from the same process. -@end itemize - -@cindex communications protocols -@cindex mSQL vs. MySQL -@node Protocol differences, Syntax differences, Using mSQL tools, Compare mSQL -@subsection How @code{mSQL} and MySQL Client/Server Communications Protocols Differ - -There are enough differences that it is impossible (or at least not easy) -to support both. - -The most significant ways in which the @strong{MySQL} protocol differs -from the @code{mSQL} protocol are listed below: - -@itemize @bullet -@item -A message buffer may contain many result rows. -@item -The message buffers are dynamically enlarged if the query or the -result is bigger than the current buffer, up to a configurable server and -client limit. -@item -All packets are numbered to catch duplicated or missing packets. -@item -All column values are sent in ASCII. The lengths of columns and rows are sent -in packed binary coding (1, 2, or 3 bytes). -@item -@strong{MySQL} can read in the result unbuffered (without having to store the -full set in the client). -@item -If a single read/write takes more than 30 seconds, the server closes -the connection. -@item -If a connection is idle for 8 hours, the server closes the connection. -@end itemize - -@node Syntax differences, , Protocol differences, Compare mSQL -@subsection How @code{mSQL} 2.0 SQL Syntax Differs from MySQL - -@noindent -@strong{Column types} - -@table @code -@item @strong{MySQL} -Has the following additional types (among others; -@pxref{CREATE TABLE, , @code{CREATE TABLE}}): -@itemize @bullet -@item -@code{ENUM} type for one of a set of strings. -@item -@code{SET} type for many of a set of strings. -@item -@code{BIGINT} type for 64-bit integers. -@end itemize -@item -@strong{MySQL} also supports -the following additional type attributes: -@itemize @bullet -@item -@code{UNSIGNED} option for integer columns. -@item -@code{ZEROFILL} option for integer columns. -@item -@code{AUTO_INCREMENT} option for integer columns that are a -@code{PRIMARY KEY}. -@xref{mysql_insert_id, , @code{mysql_insert_id()}}. -@item -@code{DEFAULT} value for all columns. -@end itemize -@item mSQL2 -@code{mSQL} column types correspond to the @strong{MySQL} types shown below: -@multitable @columnfractions .15 .85 -@item @code{mSQL} @strong{type} @tab @strong{Corresponding @strong{MySQL} type} -@item @code{CHAR(len)} @tab @code{CHAR(len)} -@item @code{TEXT(len)} @tab @code{TEXT(len)}. @code{len} is the maximal length. -And @code{LIKE} works. -@item @code{INT} @tab @code{INT}. With many more options! -@item @code{REAL} @tab @code{REAL}. Or @code{FLOAT}. Both 4- and 8-byte versions are available. -@item @code{UINT} @tab @code{INT UNSIGNED} -@item @code{DATE} @tab @code{DATE}. Uses ANSI SQL format rather than @code{mSQL}'s own format. -@item @code{TIME} @tab @code{TIME} -@item @code{MONEY} @tab @code{DECIMAL(12,2)}. A fixed-point value with two decimals. -@end multitable -@end table - -@noindent -@strong{Index Creation} - -@table @code -@item @strong{MySQL} -Indexes may be specified at table creation time with the @code{CREATE TABLE} -statement. -@item mSQL -Indexes must be created after the table has been created, with separate -@code{CREATE INDEX} statements. -@end table - -@noindent -@strong{To Insert a Unique Identifier into a Table} - -@table @code -@item @strong{MySQL} -Use @code{AUTO_INCREMENT} as a column type -specifier. -@xref{mysql_insert_id, , @code{mysql_insert_id()}}. -@item mSQL -Create a @code{SEQUENCE} on a table and select the @code{_seq} column. -@end table - -@noindent -@strong{To Obtain a Unique Identifier for a Row} - -@table @code -@item @strong{MySQL} -Add a @code{PRIMARY KEY} or @code{UNIQUE} key to the table and use this. -New in Version 3.23.11: If the @code{PRIMARY} or @code{UNIQUE} key consists of only one -column and this is of type integer, one can also refer to it as -@code{_rowid}. -@item mSQL -Use the @code{_rowid} column. Observe that @code{_rowid} may change over time -depending on many factors. -@end table - -@noindent -@strong{To Get the Time a Column Was Last Modified} - -@table @code -@item @strong{MySQL} -Add a @code{TIMESTAMP} column to the table. This column is automatically set -to the current date and time for @code{INSERT} or @code{UPDATE} statements if -you don't give the column a value or if you give it a @code{NULL} value. - -@item mSQL -Use the @code{_timestamp} column. -@end table - -@noindent -@strong{@code{NULL} Value Comparisons} - -@table @code -@item @strong{MySQL} -@strong{MySQL} follows -ANSI SQL, and a comparison with @code{NULL} is always @code{NULL}. -@item mSQL -In @code{mSQL}, @code{NULL = NULL} is TRUE. You -must change @code{=NULL} to @code{IS NULL} and @code{<>NULL} to -@code{IS NOT NULL} when porting old code from @code{mSQL} to @strong{MySQL}. -@end table - -@noindent -@strong{String Comparisons} - -@table @code -@item @strong{MySQL} -Normally, string comparisons are performed in case-independent fashion with -the sort order determined by the current character set (ISO-8859-1 Latin1 by -default). If you don't like this, declare your columns with the -@code{BINARY} attribute, which causes comparisons to be done according to the -ASCII order used on the @strong{MySQL} server host. -@item mSQL -All string comparisons are performed in case-sensitive fashion with -sorting in ASCII order. -@end table - -@noindent -@strong{Case-insensitive Searching} - -@table @code -@item @strong{MySQL} -@code{LIKE} is a case-insensitive or case-sensitive operator, depending on -the columns involved. If possible, @strong{MySQL} uses indexes if the -@code{LIKE} argument doesn't start with a wild-card character. -@item mSQL -Use @code{CLIKE}. -@end table - -@noindent -@strong{Handling of Trailing Spaces} - -@table @code -@item @strong{MySQL} -Strips all spaces at the end of @code{CHAR} and @code{VARCHAR} -columns. Use a @code{TEXT} column if this behavior is not desired. -@item mSQL -Retains trailing space. -@end table - -@noindent -@strong{@code{WHERE} Clauses} - -@table @code -@item @strong{MySQL} -@strong{MySQL} correctly prioritizes everything (@code{AND} is evaluated -before @code{OR}). To get @code{mSQL} behavior in @strong{MySQL}, use -parentheses (as shown in an example below). -@item mSQL -Evaluates everything from left to right. This means that some logical -calculations with more than three arguments cannot be expressed in any -way. It also means you must change some queries when you upgrade to -@strong{MySQL}. You do this easily by adding parentheses. Suppose you -have the following @code{mSQL} query: -@example -mysql> SELECT * FROM table WHERE a=1 AND b=2 OR a=3 AND b=4; -@end example -To make @strong{MySQL} evaluate this the way that @code{mSQL} would, -you must add parentheses: -@example -mysql> SELECT * FROM table WHERE (a=1 AND (b=2 OR (a=3 AND (b=4)))); -@end example -@end table - -@noindent -@strong{Access Control} - -@table @code -@item @strong{MySQL} -Has tables to store grant (permission) options per user, host, and -database. @xref{Privileges}. -@item mSQL -Has a file @file{mSQL.acl} in which you can grant read/write privileges for -users. -@item -@end table - -@cindex PostgreSQL/MySQL, overview -@node Compare PostgreSQL, , Compare mSQL, Comparisons -@section How MySQL Compares to PostgreSQL - -When reading the following, please note that both products are -continually evolving. We at @strong{MySQL AB} and the PostgreSQL -developers are both working on making our respective database as good as -possible, so we are both a serious choice to any commercial database. - -The following comparison is made by us at MySQL AB. We have tried to be -as accurate and fair as possible, but because we don't have a full -knowledge of all PostgreSQL features while we know MySQL througly, we -may have got some things wrong. We will however correct these when they -come to our attention. - -We would first like to note that @code{PostgreSQL} and @strong{MySQL} -are both widely used products, but with different design goals, even if -we are both striving to be ANSI SQL compatible. This means that for -some applications @strong{MySQL} is more suitable and for others -@code{PostgreSQL} is more suitable. When choosing which database to -use, you should first check if the database's feature set satisfies your -application. If you need speed, @strong{MySQL} is probably your best -choice. If you need some of the extra features that only @code{PostgreSQL} -can offer, you should use @code{PostgreSQL}. - -@cindex PostgreSQL/MySQL, strategies -@menu -* MySQL-PostgreSQL goals:: MySQL and PostgreSQL development strategies -* MySQL-PostgreSQL features:: Featurevise Comparison of MySQL and PostgreSQL -* MySQL-PostgreSQL benchmarks:: Benchmarking MySQL and PostgreSQL -@end menu - -@node MySQL-PostgreSQL goals, MySQL-PostgreSQL features, Compare PostgreSQL, Compare PostgreSQL -@subsection MySQL and PostgreSQL development strategies - -When adding things to MySQL we take pride to do an optimal, definite -solution. The code should be so good that we shouldn't have any need to -change it in the foreseeable future. We also do not like to sacrifice -speed for features but instead will do our utmost to find a solution -that will give maximal throughput. This means that development will take -a little longer, but the end result will be well worth this. This kind -of development is only possible because all server code are checked by -one of a few (currently two) persons before it's included in the -@strong{MySQL} server. - -We at MySQL AB believe in frequent releases to be able to push out new -features quickly to our users. Because of this we do a new small release -about every 3 weeks, which a major branch every year. All releases are -throughly tested with our testing tools on a lot of different platforms. - -PostgreSQL is based on a kernel with lots of contributors. In this setup -it makes sense to prioritize adding a lot of new features, instead of -implementing them optimally, because one can always optimize things -later if there arises a need for this. - -Another big difference between @strong{MySQL} and PostgreSQL is that -nearly all of the code in the MySQL server are coded by developers that -are employed by MySQL AB and are still working on the server code. The -exceptions are the transaction engines and the regexp library. - -This is in sharp contrast to the PostgreSQL code where the majority of -the code is coded by a big group of people with different backgrounds. -It was only recently that the PostgreSQL developers announced that they -current developer group had finally had time to take a look at all -the code in the current PostgreSQL release. - -Both of the above development methods has it's own merits and drawbacks. -We here at @strong{MySQL AB} think of course that our model is better -because our model gives better code consistence, more optimal and -reusable code and, in our opinion, fewer bugs. Because we are the -authors of the @strong{MySQL} server code we are better able to -coordinate new features and releases. - -@cindex PostgreSQL/MySQL, features -@node MySQL-PostgreSQL features, MySQL-PostgreSQL benchmarks, MySQL-PostgreSQL goals, Compare PostgreSQL -@subsection Featurevise Comparison of MySQL and PostgreSQL - -On the @uref{http://www.mysql.com/information/crash-me.php, crash-me} -page you can find a list of those database constructs and limits that -one can detect automatically with a program. Note however that a lot of -the numerical limits may be changed with startup options for respective -database. The above web page is however extremely useful when you want to -ensure that your applications works with many different databases or -when you want to convert your application from one datbase to another. - -@strong{MySQL} offers the following advantages over PostgreSQL: - -@itemize @bullet -@item -@code{MySQL} is generally much faster than PostgreSQL. -@xref{MySQL-PostgreSQL benchmarks}. -@item -Because @strong{MySQL} has a much larger user base than PostgreSQL the -code is more tested and has historically been more stable than -PostgreSQL. @strong{MySQL} is the much more used in production -environments than PostgreSQL, mostly thanks to that @strong{MySQL AB}, -former TCX DataKonsult AB, has provided top quality commercial support -for @strong{MySQL} from the day it was released, whereas until recently -PostgreSQL was unsupported. -@item -@strong{MySQL} works on more platforms than PostgreSQL. @xref{Which OS}. -@item -@strong{MySQL} works better on Windows; @strong{MySQL} is running as a -native windows application (a service on NT/Win2000/WinXP), while -PostgreSQL is run under the cygwin emulation. We have heard that -PostgreSQL is not yet that stable on windows but we haven't been able to -verify this ourselves. -@item -@strong{MySQL} has more API to other languages and is supported by more -programs than PostgreSQL. @xref{Contrib}. -@item -@strong{MySQL} works on 24/7 heavy duty systems. In most circumstances -you never have to run any cleanups on @code{MySQL}. PostgreSQL doesn't -yet support 24/7 systems because you have have to run @code{vacuum()} -once in a while to reclaim space from @code{UPDATE} and @code{DELETE} -commands and to perform statistics analyzes that are critical to get -good performance with PostgreSQL. Vacuum is also needed after adding -a lot of new rows to a table. On a busy system with lots of changes -vacuum must be run very frequently, in the worst cases even many times a -day. During the @code{vacuum()} run, which may take hours if the -database is big, the database is from a production standpoint -practically dead. The PostgreSQL team has fixing this on their TODO, -but we assume that this is not an easy thing to fix permanently. -@item -A working, tested replication feature used by sites like -@uref{http://finance.yahoo.com, Yahoo finance}, -@uref{http://www.mobile.de/,mobile.de} and -@uref{http://www.slashdot.org,Slashdot}. -@item -Included in the @strong{MySQL} distribution is included two different -testing suits (@file{mysql-test-run} and -@uref{http://www.mysql.com/information/crash-me.php,crash-me}) and a -benchmark suite. The test system is actively updated with code to test -each new feature and almost all repeatable bugs that comes to our -attention. We test @strong{MySQL} with these on a lot of platforms -before every release. These tests are more sofisticated than anything -have seen from PostgreSQL and ensures that the @strong{MySQL} code keeps -at a high standard. -@item -There are far moore books in print on @strong{MySQL} than on PostgreSQL. -O'Reilly, Sams, Que, and New Riders are all major publishers with books -about MySQL. All @strong{MySQL} features is also documented in the -@strong{MySQL} on-line manual because when a feature is implemented, the -@strong{MySQL} developers are required to document it before it's -included in the source. -@item -@strong{MySQL} has supports more of the standard ODBC functions than -@code{PostgreSQL}. -@item -@strong{MySQL} has a much more sophisticated @code{ALTER TABLE}. -@item -@strong{MySQL} has support for tables without transactions for -applications that need all speed they can get. The tables may be memory -based,@code{HEAP} tables or disk based @code{MyISAM}. @xref{Table types}. -@item -@strong{MySQL} has support for 3 different table handles that support -transactions (@code{BDB} and @code{InnoDB}). Because -every transaction engine performs differently under different -conditions, this gives the application writer more options to find an -optimal solution for his/her setup. @xref{Table types}. -@item -@code{MERGE} tables gives you a unique way to instantly make a view over -a set of identical tables and use these as one. This is perfectly for -systems where you have log files that you order for example by month. -@xref{MERGE}. -@item -The option to compress read-only tables, but still have direct access to -the rows in the table, gives you better performance by minimizing disk -reads. This is very useful when you are archiving -things.@xref{myisampack}. -@item -@strong{MySQL} has internal support for text search. @xref{Fulltext Search}. -@item -You can access many databases from the same connection (depending of course -on your privileges). -@item -@strong{MySQL} is coded from the start with multi-threading while -PostgreSQL uses processes. Because context switching and access to -common storage areas is much faster between threads, than are separate -processes, this gives @strong{MySQL} a big speed advantage in multi-user -applications and also makes it easier for @strong{MySQL} to take full -advantage of symmetric multiprocessor systems (SMP). -@item -@strong{MySQL} has a much more sophisticated privilege system than -PostgreSQL. While PostgreSQL only supports @code{INSERT}, -@code{SELECT}, @code{update/delete} grants per user on a database or a -table @strong{MySQL} allows you to define a full set of different -privileges on database, table and columns level. @strong{MySQL} also allows -you to specify the privilege on host+user combinations. @xref{GRANT}. -@item -@strong{MySQL} supports a compressed server/client protocol which -improves performance over slow links. -@item -@strong{MySQL} employs the table handler concept and is the only -relational database we know of built around this concept. This allows -different low level table types to be swapped into the SQL engine, each -table type optimized for a different performance characteristics. -@item -All @code{MySQL} table types (except @strong{InnoDB}) are implemented as -files (ie: one table per file), which makes it really easy to backup, -move, delete and even symlink databases and tables when the server is -down. -@item -Tools to repair and optimize @strong{MyISAM} tables (the most common -@strong{MySQL} table type). A repair tool is only needed when a -physical corruption of a data file happens, usually from a hardware -failure. It allows a majority of the data to be recovered. -@item -Upgrading @strong{MySQL} is painless. When you are upgrading @strong{MySQL}, -you don't need to dump/restore your data, as you have to do with most -PostgreSQL upgrades. -@end itemize - -Drawbacks with @strong{MySQL} compared to PostgreSQL: - -@itemize @bullet -@item -The transaction support in @strong{MySQL} is not yet as well tested as -PostgreSQL's system. -@item -Because @strong{MySQL} uses threads, which are still a moving target on -many OS, one must either use binaries from -@uref{http://www.mysql.com/downloads} or carefully follow our -instructions on -@uref{http://www.mysql.com/doc/I/n/Installing_source.html} to get an -optimal binary that works in all cases. -@item -Table locking, as used by the non-transactional @code{MyISAM} tables, is -in many cases faster than page locks, row locks or versioning. The -drawback however is that if one doesn't take into account how table -locks works, a single long-running query can block a table for updates -for a long time. This can usable be avoided when designing the -application. If not, one can always switch the trouble table to use one -of the transactional table types. @xref{Table locking}. -@item -With UDF (user defined functions) one can extend @strong{MySQL} with -both normal SQL functions and aggregates, but this is not as easy or as -flexible as in PostgreSQL. @xref{Adding functions}. -@item -Updates and deletes that goes over multiple tables is harder to do in -@strong{MySQL}. (Will be fixed in @strong{MySQL} 4.0 with multi-table -@code{DELETE} and multi-table @code{UPDATE} and in @strong{MySQL} 4.1 -with @code{SUB-SELECT}) -@end itemize - -PostgreSQL offers currently the following advantages over @strong{MySQL}: - -Note that because we know the @strong{MySQL} road map, we have included -in the following table the version when @strong{MySQL} should support -this feature. Unfortunately we couldn't do this for previous comparison, -because we don't know the PostgreSQL roadmap. - -@multitable @columnfractions .70 .30 -@item @strong{Feature} @tab @strong{MySQL version} -@item Subselects @tab 4.1 -@item Foreign keys @tab 4.0 and 4.1 -@item Views. @tab 4.2 -@item Stored procedures in multiple languages @tab 4.1 -@item Extensible type system. @tab Not planed -@item Unions @tab 4.0. -@item Full join. @tab 4.0 or 4.1. -@item Triggers. @tab 4.1 -@item Constrainst @tab 4.1 -@item Cursors @tab 4.1 or 4.2 -@item Extensible index types like R-trees @tab R-trees are planned to 4.2 -@item Inherited tables @tab Not planned -@end multitable - -Other reasons to use PostgreSQL: - -@itemize @bullet -@item -Standard usage is in PostgreSQL closer to ANSI SQL in some cases. -@item -One can get speed up PostgreSQL by coding things as stored procedures. -@item -Bigger team of developers that contributes to the server. -@end itemize - -Drawbacks with PostgreSQL compared to @strong{MySQL}: - -@itemize @bullet -@item -@code{Vaccum()} makes PostgreSQL hard to use in a 24/7 environment. -@item -Only transactional tables. -@item -Much slower insert/delete/update. -@end itemize - -For a complete list of drawbacks, you should also examine the first table -in this section. - -@cindex PostgreSQL/MySQL, benchmarks -@node MySQL-PostgreSQL benchmarks, , MySQL-PostgreSQL features, Compare PostgreSQL -@subsection Benchmarking MySQL and PostgreSQL - -The only open source benchmark, that we know of, that can be used to -benchmark @strong{MySQL} and PostgreSQL (and other databases) is our -own. It can be found at: -@uref{http://www.mysql.com/information/benchmarks.html}. - -We have many times asked the PostgreSQL developers and some PostgreSQL -users to help us extend this benchmark to make the definitive benchmark -for databases, but unfortunately we haven't got any feedback for this. - -We, the @strong{MySQL} developers, have because of this spent a lot of -hours to get maximum performance from PostgreSQL for the benchmarks, but -because we don't know PostgreSQL intimately we are sure that there are -things that we have missed. We have on the benchmark page documented -exactly how we did run the benchmark so that it should be easy for -anyone to repeat and verify our results. - -The benchmarks are usually run with and without the @code{--fast} -option. When run with @code{--fast} we are trying to use every trick -the server can do to get the code to execute as fast as possible. -The idea is that the normal run should show how the server would work in -a default setup and the @code{--fast} run shows how the server would do -if the application developer would use extensions in the server to make -his application run faster. - -When running with PostgreSQL and @code{--fast} we do a @code{vacuum()} -between after every major table update and drop table to make the database -in perfect shape for the following selects. The time for vacuum() is -measured separately. - -When running with PostgreSQL 7.1.1 we could however not run with -@code{--fast} because during the insert test, the postmaster (the -PostgreSQL deamon) died and the database was so corrupted that it was -impossible to restart postmaster. (The details about the machine we run -the benchmark can be found on the benchmark page). After this happened -twice, we decided to postpone the @code{--fast} test until next -PostgreSQL release. - -Before going to the other benchmarks we know of, We would like to give -some background to benchmarks: - -It's very easy to write a test that shows ANY database to be best -database in the world, by just restricting the test to something the -database is very good at and not test anything that the database is not -good at; If one after this publish the result with a single figure -things is even easier. - -This would be like we would measure the speed of @strong{MySQL} compared -to PostgreSQL by looking at the summary time of the MySQL benchmarks on -our web page. Based on this @strong{MySQL} would be more than 40 times -faster than PostgreSQL, something that is of course not true. We could -make things even worse by just taking the test where PostgreSQL performs -worst and claim that @strong{MySQL} is more than 2000 times faster than -PostgreSQL. - -The case is that @strong{MySQL} does a lot of optimizations that -PostgreSQL doesn't do and the other way around. An SQL optimizer is a -very complex thing and a company could spend years on just making the -optimizer faster and faster. - -When looking at the benchmark results you should look for things that -you do in your application and just use these results to decide which -database would be best suited for your application. The benchmark -results also shows things a particular database is not good at and should -give you a notion about things to avoid and what you may have to do in -other ways. - -We know of two benchmark tests that claims that PostgreSQL performers -better than @strong{MySQL}. These both where multi-user tests, a test -that we here at @strong{MySQL AB} haven't had time to write and include in -the benchmark suite, mainly because it's a big task to do this in a -manner that is fair against all databases. - -One is the benchmark paid for by -@uref{http://www.greatbridge.com/about/press.php?content_id=4,Great -Bridge}. - -This is the worst benchmark we have ever seen anyone ever conduct. This -was not only tuned to only test what PostgreSQL is absolutely best at, -it was also totally unfair against every other database involved in the -test. - -@strong{NOTE}: We know that not even some of the main PostgreSQL -developers did like the way Great Bridge conducted the benchmark, so we -don't blame them for the way the benchmark was made. - -This benchmark has been condemned in a lot of postings and newsgroups so -we will here just shortly repeat some things that where wrong with it. - -@itemize @bullet -@item -The tests where run with an expensive commercial tool, that makes it -impossible for an open source company like us to verify the benchmarks, -or even check how the benchmark where really done. The tool is not even -a true benchmark tool, but a application/setup testing tool. To refer -this as STANDARD benchmark tool is to stretch the truth a long way. -@item -Great Bridge admitted that they had optimized the PostgreSQL database -(with vacuum() before the test) and tuned the startup for the tests, -something they hadn't done for any of the other databases involved. To -say "This process optimizes indexes and frees up disk space a bit. The -optimized indexes boost performance by some margin". Our benchmarks -clearly indicates that the difference in running a lot of selects on a -database with and without vacuum() can easily differ by a factor of 10. -@item -The test results where also strange; The AS3AP test documentation -mentions that the test does: - -"selections, simple joins, projections, aggregates, one-tuple updates, -and bulk updates" - -PostgreSQL is good at doing selects and joins (especially after a -vacuum()), but doesn't perform as well on inserts/updates; The -benchmarks seem to indicate that only SELECTs where done (or very few -updates) . This could easily explain they good results for PostgreSQL in -this test. The bad results for MySQL will be obvious a bit down in this -document. -@item -They did run the so called benchmark from a Windows machine against a -Linux machine over ODBC, a setup that no normal database user would ever -do when running a heavy multi-user application. This tested more the -ODBC driver and the Windows protocol used between the clients than the -database itself. -@item -When running the database against Oracle and MS-SQL (Great Bridge has -indirectly indicated that the databases they used in the test), -they didn't use the native protocol but instead ODBC. Anyone that has -ever used Oracle, knows that all real application uses the native -interface instead of ODBC. Doing a test through ODBC and claiming that -the results had anything to do with using the database for real can't -be regarded as fair play. They should have done two tests with and -without ODBC to provide the right facts (after having got experts to tune -all involved databases of course). -@item -They refer to the TPC-C tests, but doesn't anywhere mention that the -tests they did where not a true TPC-C test and they where not even -allowed to call it a TPC-C test. A TPC-C test can only be conducted by -the rules approved by the @uref{http://www.tpc.org,TPC-council}. Great -Bridge didn't do that. By doing this they have both violated the TPC -trademark and miscredited their own benchmarks. The rules set by the -TPC-council are very strict to ensure that no one can produce false -results or make unprovable statements. Apparently Great Bridge wasn't -interested in doing this. -@item -After the first test, we contacted Great Bridge and mentioned to them -some of the obvious mistakes they had done with @strong{MySQL}; Running -with a debug version of our ODBC driver, running on a Linux system that -wasn't optimized for threads, using an old MySQL version when there was -a recommended newer one available, not starting @strong{MySQL} with the -right options for heavy multi-user use (the default installation of -MySQL is tuned for minimal resource use). Great Bridge did run a new -test, with our optimized ODBC driver and with better startup options for -MySQL, but refused to either use our updated glibc library or our -standard binary (used by 80% of our users), which was statically linked -with a fixed glibc library. - -According to what we know, Great Bridge did nothing to ensure that the -other databases where setup correctly to run good in their test -environment. We are sure however that they didn't contact Oracle or -Microsoft to ask for their advice in this matter ;) -@item -The benchmark was paid for by Great Bridge, and they decided to publish -only partial chosen results (instead of publishing it all). -@end itemize - -Tim Perdue, a long time PostgreSQL fan and a reluctant MySQL user -published a comparison on -@uref{http://www.phpbuilder.com/columns/tim20001112.php3,phpbuider}. - -When we got aware of the comparison, we phoned Tim Perdue about this -because there was a lot of strange things in his results. For example, -he claimed that MySQL had a problem with five users in his tests, when we -know that there are users with similar machines as his that are using -MySQL with 2000 simultaneous connections doing 400 queries per second (In -this case the limit was the web bandwidth, not the database). - -It sounded like he was using a Linux kernel that either had some -problems with many threads (Linux kernels before 2.4 had a problem with -this but we have documented how to fix this and Tim should be aware of -this problem). The other possible problem could have been an old glibc -library and that Tim didn't use a MySQL binary from our site, which is -linked with a corrected glibc library, but had compiled a version of his -own with. In any of the above cases, the symptom would have been exactly -what Tim had measured. - -We asked Tim if we could get access to his data so that we could repeat -the benchmark and if he could check the MySQL version on the machine to -find out what was wrong and he promised to come back to us about this. -He has not done that yet. - -Because of this we can't put any trust in this benchmark either :( - -Conclusion: - -The only benchmarks that exist today that anyone can download and run -against @strong{MySQL}and PostgreSQL is the MySQL benchmarks. We here -at @strong{MySQL} believe that open source databases should be tested -with open source tools! This is the only way to ensure that no one -does tests that nobody can reproduce and use this to claim that a -database is better than another. Without knowing all the facts it's -impossible to answer the claims of the tester. - -The thing we find strange is that every test we have seen about -PostgreSQL, that is impossible to reproduce, claims that PostgreSQL is -better in most cases while our tests, which anyone can reproduce, -clearly shows otherwise. With this we don't want to say that PostgreSQL -isn't good at many things (It is!) We would just like to see a fair test -where they are very good so that we could get some friendly competition -going! - -For more information about our benchmarks suite see @xref{MySQL -Benchmarks}. - -We are working on an even better benchmark suite, including much better -documentation of what the individual tests really do and how to add more -tests to the suite. @cindex internals @cindex threads -@node MySQL internals, Environment variables, Comparisons, Top +@node MySQL internals, Environment variables, Clients, Top @chapter MySQL Internals This chapter describes a lot of things that you need to know when @@ -45565,7 +46375,7 @@ Development on the embedded @code{mysqld} version. @code{--skip-show-variables} @end table -@node News, Bugs, Credits, Top +@node News, Porting, Credits, Top @appendix MySQL change history This appendix lists the changes from version to version in the @strong{MySQL} @@ -50803,739 +51613,10 @@ fields, the @code{BLOB} was garbage on output. Fixed @code{DISTINCT} with calculated columns. @end itemize -@cindex bugs, known -@cindex errors, known -@cindex design, issues -@cindex known errors -@node Bugs, TODO, News, Top -@appendix Known errors and design deficiencies in MySQL -The following problems are known and have a very high priority to get -fixed: - -@itemize @bullet -@item -@code{ANALYZE TABLE} on a BDB table may in some case make the table -unusable until one has restarted @code{mysqld}. When this happens you will -see errors like the following in the @strong{MySQL} error file: - -@example -001207 22:07:56 bdb: log_flush: LSN past current end-of-log -@end example - -@item -Don't execute @code{ALTER TABLE} on a @code{BDB} table on which you are -running not completed multi-statement transactions. (The transaction -will probably be ignored). - -@item -@code{ANALYZE TABLE}, @code{OPTIMIZE TABLE} and @code{REPAIR TABLE} may -cause problems on tables for which you are using @code{INSERT DELAYED}. - -@item -Doing a @code{LOCK TABLE ..} and @code{FLUSH TABLES ..} doesn't -guarantee that there isn't a half-finished transaction in progress on the -table. - -@item -BDB tables are a bit slow to open. If you have many BDB tables in a -database, it will take a long time to use the @code{mysql} client on the -database if you are not using the @code{-A} option or if you are using -@code{rehash}. This is especially notable when you have a big table -cache. - -@item -Th current replication protocol cannot deal with @code{LOAD DATA INFILE} -and line terminator characters of more than 1 character. -@end itemize - -The following problems are known and will be fixed in due time: - -@itemize @bullet -@item -For the moment @code{MATCH} only works with @code{SELECT} statements. -@item -When using @code{SET CHARACTER SET}, one can't use translated -characters in database, table and column names. -@item -@code{DELETE FROM merge_table} used without a @code{WHERE} -will only clear the mapping for the table, not delete everything in the -mapped tables -@item -You cannot build in another directory when using -MIT-pthreads. Because this requires changes to MIT-pthreads, we are not -likely to fix this. -@item -@code{BLOB} values can't ``reliably'' be used in @code{GROUP BY} or -@code{ORDER BY} or @code{DISTINCT}. Only the first @code{max_sort_length} -bytes (default 1024) are used when comparing @code{BLOB}bs in these cases. -This can be changed with the @code{-O max_sort_length} option to -@code{mysqld}. A workaround for most cases is to use a substring: -@code{SELECT DISTINCT LEFT(blob,2048) FROM tbl_name}. -@item -Calculation is done with @code{BIGINT} or @code{DOUBLE} (both are -normally 64 bits long). It depends on the function which precision one -gets. The general rule is that bit functions are done with @code{BIGINT} -precision, @code{IF}, and @code{ELT()} with @code{BIGINT} or @code{DOUBLE} -precision and the rest with @code{DOUBLE} precision. One should try to -avoid using bigger unsigned long long values than 63 bits -(9223372036854775807) for anything else than bit fields! -@item -All string columns, except @code{BLOB} and @code{TEXT} columns, automatically -have all trailing spaces removed when retrieved. For @code{CHAR} types this -is okay, and may be regarded as a feature according to ANSI SQL92. The bug is -that in @strong{MySQL}, @code{VARCHAR} columns are treated the same way. -@item -You can only have up to 255 @code{ENUM} and @code{SET} columns in one table. -@item -@code{safe_mysqld} re-directs all messages from @code{mysqld} to the -@code{mysqld} log. One problem with this is that if you execute -@code{mysqladmin refresh} to close and reopen the log, -@code{stdout} and @code{stderr} are still redirected to the old log. -If you use @code{--log} extensively, you should edit @code{safe_mysqld} to -log to @file{'hostname'.err} instead of @file{'hostname'.log} so you can -easily reclaim the space for the old log by deleting the old one and -executing @code{mysqladmin refresh}. -@item -In the @code{UPDATE} statement, columns are updated from left to right. -If you refer to an updated column, you will get the updated value instead of the -original value. For example: -@example -mysql> UPDATE tbl_name SET KEY=KEY+1,KEY=KEY+1; -@end example -will update @code{KEY} with @code{2} instead of with @code{1}. -@item -You can't use temporary tables more than once in the same query. -For example, the following doesn't work. - -@example -select * from temporary_table, temporary_table as t2; -@end example - -@item -@code{RENAME} doesn't work with @code{TEMPORARY} tables. - -@item -The optimizer may handle @code{DISTINCT} differently if you are using -'hidden' columns in a join or not. In a join, hidden columns are -counted as part of the result (even if they are not shown) while in -normal queries hidden columns doesn't participate in the @code{DISTINCT} -comparison. We will probably change this in the future to never compare -the hidden columns when executing @code{DISTINCT} - -An example of this is: - -@example -SELECT DISTINCT mp3id FROM band_downloads WHERE userid = 9 ORDER BY id -DESC; - -and - -SELECT DISTINCT band_downloads.mp3id, FROM band_downloads,band_mp3 -WHERE band_downloads.userid = 9 AND band_mp3.id = band_downloads.mp3id -ORDER BY band_downloads.id DESC; -@end example - -In the second case you may in @strong{MySQL} 3.23.x get two identical rows -in the result set (because the hidden 'id' column may differ). - -Note that the this only happens for queries where you don't have the -ORDER BY columns in the result, something that is you are not allowed -to do in ANSI SQL. - -@item -Because @strong{MySQL} allows you to work with table types that doesn't -support transactions (and thus can't @code{rollback} data) some things -behaves a little different in @strong{MySQL} than in other SQL servers: -(This is just to ensure that @strong{MySQL} never need to do a rollback -for a SQL command). This may be a little awkward at times as column -Because @strong{MySQL} allows you to work with table types that don't -support transactions, and thus can't @code{rollback} data, some things -behave a little differently in @strong{MySQL} than in other SQL servers. -This is just to ensure that @strong{MySQL} never need to do a rollback -for a SQL command. This may be a little awkward at times as column -values must be checked in the application, but this will actually give -you a nice speed increase as it allows @strong{MySQL} to do some -optimizations that otherwise would be very hard to do. - -If you set a column to an incorrect value, @strong{MySQL} will, instead of -doing a rollback, store the @code{best possible value} in the column: - -@itemize @bullet -@item -If you try to store a value outside the range in a numerical column, -@strong{MySQL} will instead store the smallest or biggest possible value in -the column. -@item -If you try to store a string that doesn't start with a number into a -numerical column, @strong{MySQL} will store 0 into it. -@item -If you try to store @code{NULL} into a column that doesn't take -@code{NULL} values, @strong{MySQL} will store 0 or @code{''} (empty -string) in it instead. (This behavior can, however, be changed with the --DDONT_USE_DEFAULT_FIELDS compile option). -@item -@strong{MySQL} allows you to store some wrong date values into -@code{DATE} and @code{DATETIME} columns. (Like 2000-02-31 or 2000-02-00). -If the date is totally wrong, @strong{MySQL} will store the special -0000-00-00 date value in the column. -@item -If you set an @code{enum} to an unsupported value, it will be set to -the error value 'empty string', with numeric value 0. -@end itemize - -@item -If you execute a @code{PROCEDURE} on a query that returns an empty set, -in some cases the @code{PROCEDURE} will not transform the columns. -@item -Creation of a table of type @code{MERGE} doesn't check if the underlying -tables are of compatible types. -@item -@strong{MySQL} can't yet handle @code{NaN}, @code{-Inf} and @code{Inf} -values in double. Using these will cause problems when trying to export -and import data. We should as an intermediate solution change @code{NaN} to -@code{NULL} (if possible) and @code{-Inf} and @code{Inf} to the -Minimum respective maximum possible @code{double} value. -@item -@code{LIMIT} on negative numbers are treated as big positive numbers. -@end itemize - -The following are known bugs in earlier versions of @strong{MySQL}: - -@itemize @bullet -@item -You can get a hung thread if you do a @code{DROP TABLE} on a table that is -one among many tables that is locked with @code{LOCK TABLES}. - -@item -In the following case you can get a core dump: -@enumerate -@item -Delayed insert handler has pending inserts to a table. -@item -@code{LOCK table} with @code{WRITE} -@item -@code{FLUSH TABLES} -@end enumerate - -@item -Before @strong{MySQL} Version 3.23.2 an @code{UPDATE} that updated a key with -a @code{WHERE} on the same key may have failed because the key was used to -search for records and the same row may have been found multiple times: - -@example -UPDATE tbl_name SET KEY=KEY+1 WHERE KEY > 100; -@end example - -A workaround is to use: - -@example -mysql> UPDATE tbl_name SET KEY=KEY+1 WHERE KEY+0 > 100; -@end example - -This will work because @strong{MySQL} will not use index on expressions in -the @code{WHERE} clause. -@item -Before @strong{MySQL} Version 3.23, all numeric types where treated as fixed-point -fields. That means you had to specify how many decimals a floating-point -field shall have. All results were returned with the correct number of -decimals. -@end itemize - -For platform-specific bugs, see the sections about compiling and porting. - -@cindex ToDo list for MySQL -@node TODO, Porting, Bugs, Top -@appendix MySQL and the future (The TODO) - -@menu -* TODO MySQL 4.0:: Things that should be in Version 4.0 -* TODO future:: Things that must be done in the near future -* TODO sometime:: Things that have to be done sometime -* TODO unplanned:: Some things we don't have any plans to do -@end menu - -This appendix lists the features that we plan to implement in @strong{MySQL}. - -Everything in this list is approximately in the order it will be done. If you -want to affect the priority order, please register a license or support us and -tell us what you want to have done more quickly. @xref{Licensing and Support}. - -The plan is that we in the future will support the full ANSI SQL99 -standard, but with a lot of useful extensions. The challenge is to do -this without sacrifying the speed or compromise the code. - -@node TODO MySQL 4.0, TODO future, TODO, TODO -@appendixsec Things that should be in 4.0 - -We plan to make @strong{MySQL} Version 4.0 a ``quick'' release where we only -add some new stuff to enable others to help us with developing new features -into Version 4.1. The @strong{MySQL} 4.0 version should only take us about -a month to make after which we want to stabilize it and start working on -Version 4.1. Version 4.0 should have the following new features: - -The news section for 4.0 includes a list of the features we have already -implemented in the 4.0 tree. @xref{News-4.0.x}. - -@itemize @bullet -@item -New table definition file format (@code{.frm} files) This will enable us -to not run out of bits when adding more table options. One will still -be able to use the old @code{.frm} file format with 4.0. All newly created -tables will, however, use the new format. - -The new file format will enable us to add new column types, more options -for keys and @code{FOREIGN KEY} support. -@item -@code{mysqld} as a library. This will have the same interface as the -standard @strong{MySQL} client (with an extra function to just set up -startup parameters) but will be faster (no TCP/IP or socket overhead), -smaller and much easier to use for embedded products. - -One will be able to define at link time if one wants to use the -client/server model or a stand-alone application just by defining which -library to link with. - -The @code{mysqld} will support all standard @strong{MySQL} features and -one can use it in a threaded client to run different queries in each -thread. -@item -Replication should work with @code{RAND()} and user variables @code{@@var}. -@item -Online backup with very low performance penalty. The online backup will -make it easy to add a new replication slave without taking down the -master. -@item -@code{DELETE FROM table_name} will return the number of deleted rows. For -fast execution one should use @code{TRUNCATE table_name}. -@item -Allow @code{DELETE} on @code{MyISAM} tables to use the record cache. -To do this, we need to update the threads record cache when we update -the @code{.MYD} file. -@item -Better replication. -@item -More functions for full-text search. -@xref{Fulltext Features to Appear in MySQL 4.0}. -@item -Character set casts and syntax for handling multiple character sets. -@item -Allow users to change startup options without taking down the server. -@item -Help for all commands from the client. -@item -Secure connections (with SSL). -@item -Extend the optimizer to be able to optimize some @code{ORDER BY key_name DESC} -queries. -@item -@code{SHOW COLUMNS FROM table_name} (used by @code{mysql} client to allow -expansions of column names) should not open the table, but only the -definition file. This will require less memory and be much faster. -@item -New key cache -@item -When using @code{SET CHARACTER SET} we should translate the whole query -at once and not only strings. This will enable users to use the translated -characters in database, table and column names. -@item -Add a portable interface over @code{gethostbyaddr_r()} so that we can change -@code{ip_to_hostname()} to not block other threads while doing DNS lookups. -@item -Add @code{record_in_range()} method to @code{MERGE} tables to be -able to choose the right index when there is many to choose from. We should -also extend the info interface to get the key distribution for each index, -of @code{analyze} is run on all sub tables. -@item -@code{SET SQL_DEFAULT_TABLE_TYPE=[MyISAM | INNODB | BDB | HEAP]}. -@end itemize - -@node TODO future, TODO sometime, TODO MySQL 4.0, TODO -@appendixsec Things that must be done in the real near future - -@itemize @bullet -@item -Fail safe replication. -@item -Subqueries. -@code{select id from t where grp in (select grp from g where u > 100)} -@item -Derived tables. -@example -select a.col1, b.col2 from (select max(col1) as col1 from root_table ) a, -other_table b where a.col1=b.col1 -@end example - -This could be done by automatically creating temporary tables for the -derived tables for the duration of the query. -@item -Add @code{PREPARE} of statements and sending of parameters to @code{mysqld}. -@item -Extend the server/client protocol to support warnings. -@item -Add options to the server/protocol protocol to get progress notes -for long running commands. -@item -Add database and real table name (in case of alias) to the MYSQL_FIELD -structure. -@item -Don't allow more than a defined number of threads to run MyISAM recover -at the same time. -@item -Change @code{INSERT ... SELECT} to optionally use concurrent inserts. -@item -Implement @code{RENAME DATABASE}. To make this safe for all table handlers, -it should work as follows: -@itemize @bullet -@item -Create the new database. -@item -For every table do a rename of the table to another database, as -we do with the @code{RENAME} command. -@item -Drop the old database. -@end itemize -@item -Return the original field types() when doing @code{SELECT MIN(column) -... GROUP BY}. -@item -Multiple result sets. -@item -Change the protocol to allow binary transfer of values. To do this -efficiently, we need to add an API to allow binding of variables. -@item -Make it possible to specify @code{long_query_time} with a granularity -in microseconds. -@item -Add a configurable prompt to the @code{mysql} command line client, with -options like database in use, time and date... -@item -Add range checking to @code{MERGE} tables. -@item -Link the @code{myisampack} code into the server. -@item -Port of @strong{MySQL} to BeOS. -@item -Port of the @strong{MySQL} clients to LynxOS. -@item -Add a temporary key buffer cache during @code{INSERT/DELETE/UPDATE} so that we -can gracefully recover if the index file gets full. -@item -If you perform an @code{ALTER TABLE} on a table that is symlinked to another -disk, create temporary tables on this disk. -@item -Implement a @code{DATE/DATETIME} type that handles time zone information -properly, so that dealing with dates in different time zones is easier. -@item -FreeBSD and MIT-pthreads; Do sleeping threads take CPU? -@item -Check if locked threads take any CPU. -@item -Fix configure so that one can compile all libraries (like @code{MyISAM}) -without threads. -@item -Add an option to periodically flush key pages for tables with delayed keys -if they haven't been used in a while. -@item -Allow join on key parts (optimization issue). -@item -@code{INSERT SQL_CONCURRENT} and @code{mysqld --concurrent-insert} to do -a concurrent insert at the end of the file if the file is read-locked. -@item -Remember @code{FOREIGN} key definitions in the @file{.frm} file. -@item -Cascading @code{DELETE} -@item -Server side cursors. -@item -Check if @code{lockd} works with modern Linux kernels; If not, we have -to fix @code{lockd}! To test this, start @code{mysqld} with -@code{--enable-locking} and run the different fork* test suits. They shouldn't -give any errors if @code{lockd} works. -@item -Allow SQL variables in @code{LIMIT}, like in @code{LIMIT @@a,@@b}. -@item -Allow update of variables in @code{UPDATE} statements. For example: -@code{UPDATE TABLE foo SET @@a=a+b,a=@@a, b=@@a+c} -@item -Change when user variables are updated so that one can use them with -@code{GROUP BY}, as in the following example: -@code{SELECT id, @@a:=count(*), sum(sum_col)/@@a FROM table_name GROUP BY id}. -@item -Don't add automatic @code{DEFAULT} values to columns. Give an error when using -an @code{INSERT} that doesn't contain a column that doesn't have a -@code{DEFAULT}. -@item -Caching of queries and results. This should be done as a separated -module that examines each query and if this is query is in the cache -the cached result should be returned. When one updates a table one -should remove as few queries as possible from the cache. -This should give a big speed bost on machines with much RAM where -queries are often repeated (like WWW applications). -One idea would be to only cache queries of type: -@code{SELECT CACHED ...} -@item -Fix @file{libmysql.c} to allow two @code{mysql_query()} commands in a row -without reading results or give a nice error message when one does this. -@item -Optimize @code{BIT} type to take 1 bit (now @code{BIT} takes 1 char). -@item -Check why MIT-pthreads @code{ctime()} doesn't work on some FreeBSD systems. -@item -Add an @code{IMAGE} option to @code{LOAD DATA INFILE} to not update -@code{TIMESTAMP} and @code{AUTO_INCREMENT} fields. -@item -Added @code{LOAD DATE INFILE.. UPDATE} syntax. -@itemize @bullet -@item -For tables with primary keys, if the data contains the primary key, -entries matching that primary key are updated from the remainder of the -columns. However, columns MISSING from the incoming data feed are not -touched. -@item -For tables tables with primary keys that are missing some part of the key -in the incoming data stream, or that have no primary key, the feed is -treated as a @code{LOAD DATA INFILE ... REPLACE INTO} is now. -@end itemize -@item -Make @code{LOAD DATA INFILE} understand syntax like: -@example -LOAD DATA INFILE 'file_name.txt' INTO TABLE tbl_name -TEXT_FIELDS (text_field1, text_field2, text_field3) -SET table_field1=concatenate(text_field1, text_field2), table_field3=23 -IGNORE text_field3 - -This can be used to skip over extra columns in the text file, or update columns -based on expressions of the read data... -@end example -@item -@code{LOAD DATA INFILE 'file_name' INTO TABLE 'table_name' ERRORS TO err_table_name} -This would cause any errors and warnings to be logged into the err_table_name -table. That table would have a structure like: - -@example -line_number - line number in data file -error_message - the error/warning message -and maybe -data_line - the line from the data file -@end example -@item -Add true @code{VARCHAR} support (There is already support for this in MyISAM). -@item -Automatic output from @code{mysql} to netscape. -@item -@code{LOCK DATABASES}. (with various options) -@item -Change sort to allocate memory in ``hunks'' to get better memory utilization. -@item -@code{DECIMAL} and @code{NUMERIC} types can't read exponential numbers; -@code{Field_decimal::store(const char *from,uint len)} must be recoded -to fix this. -@item -Fix @code{mysql.cc} to do fewer @code{malloc()} calls when hashing field -names. -@item -Functions: -ADD_TO_SET(value,set) and REMOVE_FROM_SET(value,set) -@item -Add use of @code{t1 JOIN t2 ON ...} and @code{t1 JOIN t2 USING ...} -Currently, you can only use this syntax with @code{LEFT JOIN}. -@item -Add full support for @code{unsigned long long} type. -@item -Many more variables for @code{show status}. Counts for: -@code{INSERT}/@code{DELETE}/@code{UPDATE} statements. Records reads and -updated. Selects on 1 table and selects with joins. Mean number of -tables in select. Number of @code{ORDER BY} and @code{GROUP BY} queries. -@item -If you abort @code{mysql} in the middle of a query, you should open -another connection and kill the old running query. -Alternatively, an attempt should be made to detect this in the server. -@item -Add a handler interface for table information so you can use it as a system -table. This would be a bit slow if you requested information about all tables, -but very flexible. @code{SHOW INFO FROM tbl_name} for basic table information -should be implemented. -@item -Add support for UNICODE. -@item -@code{NATURAL JOIN} and @code{UNION JOIN} -@item -Allow @code{select a from crash_me left join crash_me2 using (a)}; In this -case a is assumed to come from the crash_me table. -@item -Fix that @code{ON} and @code{USING} works with the @code{JOIN} and -@code{INNER JOIN} join types. -@item -Oracle like @code{CONNECT BY PRIOR ...} to search hierarchy structures. -@item -@code{RENAME DATABASE} -@item -@code{mysqladmin copy database new-database}. -- Requires COPY command to be -added to @code{mysqld} -@item -Processlist should show number of queries/thread. -@item -@code{SHOW HOSTS} for printing information about the hostname cache. -@item -@code{DELETE} and @code{REPLACE} options to the @code{UPDATE} statement -(this will delete rows when one gets a duplicate key error while updating). -@item -Change the format of @code{DATETIME} to store fractions of seconds. -@item -Add all missing ANSI92 and ODBC 3.0 types. -@item -Change table names from empty strings to @code{NULL} for calculated columns. -@item -Don't use 'Item_copy_string' on numerical values to avoid -number->string->number conversion in case of: -@code{SELECT COUNT(*)*(id+0) FROM table_name GROUP BY id} -@item -Make it possible to use the new GNU regexp library instead of the current -one (The GNU library should be much faster than the old one). -@item -Change that @code{ALTER TABLE} doesn't abort clients that executes -@code{INSERT DELAYED}. -@item -Fix that when columns referenced in an @code{UPDATE} clause contains the old -values before the update started. -@item -@code{myisamchk}, @code{REPAIR} and @code{OPTIMIZE TABLE} should be able -to handle cases where the data and/or index files are symbolic links. -@item -Add simulation of @code{pread()}/@code{pwrite()} on Windows to enable -concurrent inserts. -@item -A logfile analyzer that could parsed out information about which tables -are hit most often, how often multi-table joins are executed, etc. It -should help users identify areas or table design that could be optimized -to execute much more efficient queries. -@item -Add @code{SUM(DISTINCT)} -@item -Add @code{ANY()},@code{EVERY()} and @code{SOME()} group functions. In -ANSI SQL these only works on boolean columns, but we can extend these to -work on any columns/expressions by applying: value == 0 -> FALSE and -value <> 0 -> TRUE. -@item -Fix that the type for @code{MAX(column)} is the same as the column type. -@example -create table t1 (a DATE); -insert into t1 values (now()); -create table t2 select max(a) from t1; -show columns from t2; -@end example -@item -Come up with a nice syntax for a statement that will @code{UPDATE} the row -if it exists and @code{INSERT} a new row if the row didn't exist. -(Like @code{REPLACE} works with @code{INSERT} / @code{DELETE}) -@end itemize - -@node TODO sometime, TODO unplanned, TODO future, TODO -@appendixsec Things that have to be done sometime - -@itemize @bullet -@item -Implement function: @code{get_changed_tables(timeout,table1,table2,...)} -@item -Atomic multi-table updates, eg @code{update items,month set -items.price=month.price where items.id=month.id;}; -@item -Change reading through tables to use memmap when possible. Now only -compressed tables use memmap. -@item -Add a new privilege @strong{'Show_priv'} for @code{SHOW} commands. -@item -Make the automatic timestamp code nicer. Add timestamps to the update -log with @code{SET TIMESTAMP=#;} -@item -Use read/write mutex in some places to get more speed. -@item -Full foreign key support. One probably wants to implement a procedural -language first. -@item -Simple views (first on one table, later on any expression). -@item -Automatically close some tables if a table, temporary table or temporary files -gets error 23 (not enough open files). -@item -When one finds a field=#, change all occurrences of field to #. Now this -is only done for some simple cases. -@item -Change all const expressions with calculated expressions if possible. -@item -Optimize key = expression. At the moment only key = field or key = -constant are optimized. -@item -Join some of the copy functions for nicer code. -@item -Change @file{sql_yacc.yy} to an inline parser to reduce its size and get -better error messages (5 days). -@item -Change the parser to use only one rule per different number of arguments -in function. -@item -Use of full calculation names in the order part. (For ACCESS97) -@item -@code{UNION}, @code{MINUS}, @code{INTERSECT} and @code{FULL OUTER JOIN}. -(Currently only @code{LEFT OUTER JOIN} is supported) -@item -Allow @code{UNIQUE} on fields that can be @code{NULL}. -@item -@code{SQL_OPTION MAX_SELECT_TIME=#} to put a time limit on a query. -@item -Make the update log to a database. -@item -Negative @code{LIMIT} to retrieve data from the end. -@item -Alarm around client connect/read/write functions. -@item -Please note the changes to @code{safe_mysqld}: according to FSSTND (which -Debian tries to follow) PID files should go into @file{/var/run/.pid} -and log files into @file{/var/log}. It would be nice if you could put the -"DATADIR" in the first declaration of "pidfile" and "log", so the -placement of these files can be changed with a single statement. -@item -Allow a client to request logging. -@item -Add use of @code{zlib()} for @code{gzip}-ed files to @code{LOAD DATA INFILE}. -@item -Fix sorting and grouping of @code{BLOB} columns (partly solved now). -@item -Stored procedures. This is currently not regarded to be very -important as stored procedures are not very standardized yet. -Another problem is that true stored procedures make it much harder for -the optimizer and in many cases the result is slower than before -We will, on the other hand, add a simple (atomic) update language that -can be used to write loops and such in the @strong{MySQL} server. -@item -Change to use semaphores when counting threads. One should first implement -a semaphore library to MIT-pthreads. -@item -Don't assign a new @code{AUTO_INCREMENT} value when one sets a column to 0. -Use @code{NULL} instead. -@item -Add full support for @code{JOIN} with parentheses. -@item -As an alternative for one thread / connection manage a pool of threads -to handle the queries. -@item -Allow one to get more than one lock with @code{GET_LOCK}. When doing this, -one must also handle the possible deadlocks this change will introduce. -@end itemize - -Time is given according to amount of work, not real time. - -@node TODO unplanned, , TODO sometime, TODO -@appendixsec Some things we don't have any plans to do - -@itemize @bullet -@item -Nothing; In the long run we plan to be fully ANSI 92 / ANSI 99 compliant. -@end itemize @cindex porting, to other systems -@node Porting, Regexp, TODO, Top +@node Porting, Regexp, News, Top @appendix Comments on porting to other systems A working Posix thread library is needed for the server. On Solaris 2.5 From e7eb74372cd792c52754068127981e0e2f604aa8 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 28 Jul 2001 13:29:20 +0300 Subject: [PATCH 11/51] Updated LOCK TABLES manual section Applied patch for mysqlhotcopy Fixed open-files-size option in safe_mysqld Docs/manual.texi: Updated LOCK TABLES section scripts/mysqlhotcopy.sh: Removed depricated DBI calls. Fixed bug which resulted in nothing being copied when a regexp was specified but no database name(s). Patch by Jeremy D. Zawodny scripts/safe_mysqld.sh: Fixed open-files-size option --- Docs/manual.texi | 67 ++++++++++++++++++++++++----------------- scripts/mysqlhotcopy.sh | 45 +++++++++++++++++++-------- scripts/safe_mysqld.sh | 4 +-- 3 files changed, 74 insertions(+), 42 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 551db373ae0..2ed7c45a014 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -7585,7 +7585,7 @@ You should also add /etc/my.cnf: @example [safe_mysqld] -open_files_limit=8192 +open-files-limit=8192 @end example The above should allow @strong{MySQL} to create up to 8192 connections/files. @@ -22952,17 +22952,9 @@ are locked by the current thread are automatically unlocked when the thread issues another @code{LOCK TABLES}, or when the connection to the server is closed. -The main reasons to use @code{LOCK TABLES} are: - -@itemize @bullet -@item -Emulate transactions with not transaction safe tables. -@item -To get more speed with @code{MyISAM} tables when inserting/updating data -over many statements. The main reason this gives more speed is that -@strong{MySQL} will not flush the key cache for the locked tables until -@code{UNLOCK TABLES} is called. -@end itemize +The main reasons to use @code{LOCK TABLES} are for emulating transactions +or getting more speed when updating tables. This is explained in more +detail later. If a thread obtains a @code{READ} lock on a table, that thread (and all other threads) can only read from the table. If a thread obtains a @code{WRITE} @@ -22975,8 +22967,10 @@ execute while the lock is held. This can't however be used if you are going to manipulate the database files outside @strong{MySQL} while you hold the lock. -Each thread waits (without timing out) until it obtains all the locks it has -requested. +When you use @code{LOCK TABLES}, you must lock all tables that you are +going to use and you must use the same alias that you are going to use +in your queries! If you are using a table multiple times in a query +(with aliases), you must get a lock for each alias! @code{WRITE} locks normally have higher priority than @code{READ} locks, to ensure that updates are processed as soon as possible. This means that if one @@ -22988,15 +22982,32 @@ locks while the thread is waiting for the @code{WRITE} lock. You should only use @code{LOW_PRIORITY WRITE} locks if you are sure that there will eventually be a time when no threads will have a @code{READ} lock. -@code{LOCK TABLES} and @code{UNLOCK TABLES} both commits any active -transactions. +@code{LOCK TABLES} works as follows: +@enumerate +@item +Sort all tables to be locked in a internally defined order (from the +user standpoint the order is undefined). +@item +If a table is locked with a read and a write lock, put the write lock +before the read lock. +@item +Lock one table at a time until the thread gets all locks. +@end enumerate -When you use @code{LOCK TABLES}, you must lock all tables that you are -going to use and you must use the same alias that you are going to use -in your queries! If you are using a table multiple times in a query -(with aliases), you must get a lock for each alias! This policy ensures -that table locking is deadlock free and makes the locking code smaller, -simpler and much faster. +This policy ensures that table locking is deadlock free. There is +however other things one needs to be aware of with this schema: + +If you are using a @code{LOW_PRIORITY_WRITE} lock for a table, this +means only that @strong{MySQL} will wait for this particlar lock until +there is no threads that wants a @code{READ} lock. When the thread has +got the @code{WRITE} lock and is waiting to get the lock for the next +table in the lock table list, all other threads will wait for the +@code{WRITE} lock to be released. If this becomes a serious problem +with your application, you should consider converting some of your +tables to transactions safe tables. + +You can safely kill a thread that is waiting for a table lock with +@code{KILL}. @xref{KILL}. Note that you should @strong{NOT} lock any tables that you are using with @code{INSERT DELAYED}. This is because that in this case the @code{INSERT} @@ -23013,6 +23024,12 @@ If you are going to run many operations on a bunch of tables, it's much faster to lock the tables you are going to use. The downside is, of course, that no other thread can update a @code{READ}-locked table and no other thread can read a @code{WRITE}-locked table. + +The reason some things are faster under @code{LOCK TABLES} is that +@strong{MySQL} will not flush the key cache for the locked tables until +@code{UNLOCK TABLES} is called (normally the key cache is flushed after +each SQL statement). This speeds up inserting/updateing/deletes on +@code{MyISAM} tables. @item If you are using a table handler in @strong{MySQL} that doesn't support transactions, you must use @code{LOCK TABLES} if you want to ensure that @@ -23044,7 +23061,7 @@ table in the server and implemented with @code{pthread_mutex_lock()} and See @ref{Internal locking}, for more information on locking policy. -You can also lock all tables in all databases with read locks with the +You can lock all tables in all databases with read locks with the @code{FLUSH TABLES WITH READ LOCK} command. @xref{FLUSH}. This is very convenient way to get backups if you have a file system, like Veritas, that can take snapshots in time. @@ -43898,8 +43915,6 @@ more than one way to compute} @item @uref{http://www.spylog.ru/, SpyLOG ; A very popular Web counter site} -@item @uref{http://www.tucows.com/, TuCows Network; Free Software archive} - @item @uref{http://www.jobvertise.com,Jobvertise: Post and search for jobs} @item @uref{http://www.musicdatabase.com, The Music Database} @@ -45486,8 +45501,6 @@ For making @code{mysqlaccess} more secure. @item Albert Chin-A-Young. Configure updates for Tru64, large file support and better TCP wrappers support. -@item Valueclick Inc. -For sponsoring the optimize section in this manual. @end table Other contributors, bugfinders, and testers: James H. Thompson, Maurizio diff --git a/scripts/mysqlhotcopy.sh b/scripts/mysqlhotcopy.sh index 1c26bf8e2d6..71359fa5612 100644 --- a/scripts/mysqlhotcopy.sh +++ b/scripts/mysqlhotcopy.sh @@ -223,18 +223,27 @@ foreach my $rdb ( @db_desc ) { my $db = $rdb->{src}; eval { $dbh->do( "use $db" ); }; die "Database '$db' not accessible: $@" if ( $@ ); - my @dbh_tables = $dbh->func( '_ListTables' ); + my @dbh_tables = $dbh->tables(); ## generate regex for tables/files - my $t_regex = $rdb->{t_regex}; ## assign temporary regex - my $negated = $t_regex =~ tr/~//d; ## remove and count negation operator: we don't allow ~ in table names - $t_regex = qr/$t_regex/; ## make regex string from user regex + my $t_regex; + my $negated; + if ($rdb->{t_regex}) { + $t_regex = $rdb->{t_regex}; ## assign temporary regex + $negated = $t_regex =~ tr/~//d; ## remove and count + ## negation operator: we + ## don't allow ~ in table + ## names - ## filter (out) tables specified in t_regex - print "Filtering tables with '$t_regex'\n" if $opt{debug}; - @dbh_tables = ( $negated - ? grep { $_ !~ $t_regex } @dbh_tables - : grep { $_ =~ $t_regex } @dbh_tables ); + $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_tables = ( $negated + ? grep { $_ !~ $t_regex } @dbh_tables + : grep { $_ =~ $t_regex } @dbh_tables ); + } ## get list of files to copy my $db_dir = "$datadir/$db"; @@ -249,10 +258,18 @@ foreach my $rdb ( @db_desc ) { closedir( DBDIR ); ## filter (out) files specified in t_regex - my @db_files = ( $negated - ? grep { $db_files{$_} !~ $t_regex } keys %db_files - : grep { $db_files{$_} =~ $t_regex } keys %db_files ); + 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 @@ -809,3 +826,7 @@ 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 depricated DBI calls. Fixed bug which +resulted in nothing being copied when a regexp was specified but no +database name(s). + diff --git a/scripts/safe_mysqld.sh b/scripts/safe_mysqld.sh index 6eda1740ad6..a9ffddab453 100644 --- a/scripts/safe_mysqld.sh +++ b/scripts/safe_mysqld.sh @@ -46,10 +46,8 @@ parse_arguments() { # safe_mysqld-specific options - must be set in my.cnf ([safe_mysqld])! --ledir=*) ledir=`echo "$arg" | sed -e "s;--ledir=;;"` ;; --err-log=*) err_log=`echo "$arg" | sed -e "s;--err-log=;;"` ;; - # QQ The --open-files should be removed - --open-files=*) open_files=`echo "$arg" | sed -e "s;--open-files=;;"` ;; --open-files-limit=*) open_files=`echo "$arg" | sed -e "s;--open-files-limit=;;"` ;; - --core-file-size=*) core_file_size=`echo "$arg" | sed -e "s;--core_file_size=;;"` ;; + --core-file-size=*) core_file_size=`echo "$arg" | sed -e "s;--core-file-size=;;"` ;; --timezone=*) TZ=`echo "$arg" | sed -e "s;--timezone=;;"` ; export TZ; ;; --mysqld=*) MYSQLD=`echo "$arg" | sed -e "s;--mysqld=;;"` ;; --mysqld-version=*) From a774d5614994e7fe5c73b87f411daba18cf6a8ab Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 28 Jul 2001 11:46:22 -0600 Subject: [PATCH 12/51] do not log stray error codes in Query_log_event sql/log_event.h: do not log stray error codes --- sql/log_event.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/sql/log_event.h b/sql/log_event.h index 41f847e8d92..8d8ac183f61 100644 --- a/sql/log_event.h +++ b/sql/log_event.h @@ -145,6 +145,9 @@ public: time(&end_time); exec_time = (ulong) (end_time - thd->start_time); db_len = (db) ? (uint32) strlen(db) : 0; + // do not log stray system errors such as EE_WRITE + if (error_code < ERRMOD) + error_code = 0; } #endif From 811532f56fc551a799ffad4ddf3aba5e96f4978d Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 30 Jul 2001 22:49:39 +0300 Subject: [PATCH 13/51] Fixed optimizer bug in ORDER BY where some ORDER BY parts where ignored. Extended default arguments to be up to 4095 characters Docs/manual.texi: Update lof LOCK TABLES mysql-test/r/order_by.result: Test for optimizer bug in ORDER BY mysql-test/t/order_by.test: Test for optimizer bug in ORDER BY mysys/default.c: Extended default arguments to be up to 4095 characters sql/sql_select.cc: Fixed optimizer bug in ORDER BY --- Docs/manual.texi | 1081 ++-------------------------------- mysql-test/r/order_by.result | 31 + mysql-test/t/order_by.test | 52 +- mysys/default.c | 2 +- sql/sql_select.cc | 12 +- 5 files changed, 136 insertions(+), 1042 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 8b5052aa19c..7602409709f 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -146,1009 +146,6 @@ distribution for that version. * Function Index:: SQL command, type and function index * Concept Index:: Concept Index -@detailmenu - --- The Detailed Node Listing --- - -General Information About MySQL - -* MySQL and MySQL AB:: -* MySQL Information Sources:: -* Licensing and Support:: -* Compatibility:: -* Comparisons:: -* TODO:: - -MySQL, MySQL AB, and Open Source - -* What-is:: What is @strong{MySQL}? -* What is MySQL AB:: What is @strong{MySQL AB}? -* Manual-info:: About this manual -* Manual conventions:: Conventions used in this manual -* History:: History of @strong{MySQL} -* Features:: The main features of @strong{MySQL} -* Stability:: How stable is @strong{MySQL}? -* Table size:: -* Year 2000 compliance:: Year 2000 compliance - -MySQL Information Sources - -* MySQL-Books:: -* General-SQL:: -* Useful Links:: -* Questions:: - -MySQL Mailing Lists - -* Mailing-list:: The @strong{MySQL} mailing lists -* Asking questions:: Asking questions or reporting bugs -* Bug reports:: How to report bugs or problems -* Answering questions:: Guidelines for answering questions on the mailing list - -MySQL Licensing and Support - -* Licensing policy:: @strong{MySQL} licensing policy -* Copyright:: Copyrights used by @strong{MySQL} -* Licensing examples:: Example licensing situations -* Cost:: @strong{MySQL} licensing and support costs -* Support:: Types of commercial support - -Copyrights Used by MySQL - -* Copyright changes:: Possible future copyright changes - -Example Licensing Situations - -* Products that use MySQL:: Selling products that use @strong{MySQL} -* ISP:: ISP @strong{MySQL} services -* Web server:: Running a web server using @strong{MySQL}. - -MySQL Licensing and Support Costs - -* Payment information:: Payment information -* Contact information:: Contact information - -Types of Commercial Support - -* Basic email support:: Basic email support -* Extended email support:: Extended email support -* Login support:: Login support -* Extended login support:: Extended login support -* Telephone support:: Telephone support -* Table handler support:: Support for other table handlers - -How Standards-compatible Is MySQL? - -* Extensions to ANSI:: @strong{MySQL} extensions to ANSI SQL92 -* Differences from ANSI:: @strong{MySQL} differences compared to ANSI SQL92 -* ANSI mode:: Running @strong{MySQL} in ANSI mode -* Missing functions:: Functionality missing from @strong{MySQL} -* Standards:: What standards does @strong{MySQL} follow? -* Commit-rollback:: How to cope without @code{COMMIT}-@code{ROLLBACK} -* Bugs:: - -Functionality Missing from MySQL - -* Missing Sub-selects:: Sub-selects -* Missing SELECT INTO TABLE:: @code{SELECT INTO TABLE} -* Missing Transactions:: Transactions -* Missing Triggers:: Triggers -* Missing Foreign Keys:: Foreign Keys -* Broken Foreign KEY:: -* Missing Views:: Views -* Missing comments:: @samp{--} as the start of a comment - -Foreign Keys - -* Broken Foreign KEY:: Reasons NOT to use foreign keys constraints - -How MySQL Compares to Other Databases - -* Compare mSQL:: How @strong{MySQL} compares to @code{mSQL} -* Protocol differences:: -* Compare PostgreSQL:: How @strong{MySQL} compares with PostgreSQL -* MySQL-PostgreSQL features:: - -How MySQL Compares to @code{mSQL} - -* Using mSQL tools:: How to convert @code{mSQL} tools for @strong{MySQL} - -How @code{mSQL} and MySQL Client/Server Communications Protocols Differ - -* Syntax differences:: - -How MySQL Compares to PostgreSQL - -* MySQL-PostgreSQL goals:: MySQL and PostgreSQL development strategies - -Featurevise Comparison of MySQL and PostgreSQL - -* MySQL-PostgreSQL benchmarks:: - -MySQL and the future (The TODO) - -* TODO MySQL 4.0:: Things that should be in Version 4.0 -* TODO future:: Things that must be done in the near future -* TODO sometime:: Things that have to be done sometime -* TODO unplanned:: Some things we don't have any plans to do - -Installing MySQL - -* Getting MySQL:: How to get @strong{MySQL} -* Which OS:: Operating systems supported by @strong{MySQL} -* Which version:: Which @strong{MySQL} version to use -* Many versions:: How and when updates are released -* Installation layouts:: Installation layouts -* Installing binary:: Installing a @strong{MySQL} binary distribution -* Installing source:: Installing a @strong{MySQL} source distribution -* Installing source tree:: Installing @strong{MySQL} from development source tree -* Compilation problems:: Problems compiling? -* MIT-pthreads:: MIT-pthreads notes -* Perl support:: Perl installation comments -* Source install system issues:: System-specific issues -* Windows:: Windows notes -* OS/2:: OS/2 notes -* MySQL binaries:: MySQL binaries -* Post-installation:: Post-installation setup and testing -* Installing many servers:: Installing many servers on the same machine -* Upgrade:: Upgrading/Downgrading MySQL - -Installing a MySQL Binary Distribution - -* Linux-RPM:: Linux RPM files -* Building clients:: Building client programs -* Binary install system issues:: System-specific issues - -System-specific Issues - -* Binary notes-Linux:: Linux notes for binary distribution -* Binary notes-HP-UX:: HP-UX notes for binary distribution - -Installing a MySQL Source Distribution - -* Quick install:: Quick installation overview -* Applying patches:: Applying patches -* configure options:: Typical @code{configure} options - -Perl Installation Comments - -* Perl installation:: Installing Perl on Unix -* ActiveState Perl:: Installing ActiveState Perl on Windows -* Windows Perl:: Installing the @strong{MySQL} Perl distribution on Windows -* Perl support problems:: Problems using the Perl @code{DBI}/@code{DBD} interface - -System-specific Issues - -* Solaris:: Solaris notes -* Solaris 2.7:: Solaris 2.7 / 2.8 notes -* Solaris x86:: Solaris x86 notes -* SunOS:: SunOS 4 notes -* Linux:: Linux notes (all Linux versions) -* Alpha-DEC-UNIX:: Alpha-DEC-UNIX notes -* Alpha-DEC-OSF1:: Alpha-DEC-OSF1 notes -* SGI-Irix:: SGI-Irix notes -* FreeBSD:: FreeBSD notes -* NetBSD:: NetBSD notes -* OpenBSD:: OpenBSD 2.5 notes -* BSDI:: BSD/OS notes -* SCO:: SCO notes -* SCO Unixware:: SCO Unixware 7.0 notes -* IBM-AIX:: IBM-AIX notes -* HP-UX 10.20:: HP-UX 10.20 notes -* HP-UX 11.x:: HP-UX 11.x notes -* Mac OS X:: Mac OS X notes -* BEOS:: BeOS Notes - -Linux Notes (All Linux Versions) - -* Linux-x86:: Linux-x86 notes -* Linux-RedHat50:: RedHat 5.0 notes -* Linux-RedHat51:: RedHat 5.1 notes -* Linux-SPARC:: Linux-SPARC notes -* Linux-Alpha:: Linux-Alpha notes -* MKLinux:: MkLinux notes -* Qube2:: Qube2 Linux notes -* Linux-Ia64:: Linux-Ia64 notes - -OpenBSD Notes - -* OpenBSD 2.5:: OpenBSD 2.5 Notes -* OpenBSD 2.8:: OpenBSD 2.8 Notes - -BSD/OS Notes - -* BSDI2:: BSD/OS 2.x notes -* BSDI3:: BSD/OS 3.x notes -* BSDI4:: BSD/OS 4.x notes - -Mac OS X Notes - -* Mac OS X Public Data:: -* Mac OS X Server:: - -Windows Notes - -* Windows installation:: Installing @strong{MySQL} on Windows -* Win95 start:: Starting @strong{MySQL} on Win95 / Win98 -* NT start:: Starting @strong{MySQL} on NT / Win2000 -* Windows running:: Running @strong{MySQL} on Windows -* Windows and SSH:: Connecting to a remote @strong{MySQL} from Windows with SSH -* Windows symbolic links:: Splitting data across different disks under Win32 -* Windows compiling:: Compiling MySQL clients on Windows. -* Windows vs Unix:: @strong{MySQL}-Windows compared to Unix @strong{MySQL} - -Post-installation Setup and Testing - -* mysql_install_db:: Problems running @code{mysql_install_db} -* Starting server:: Problems starting the @strong{MySQL} server -* Automatic start:: Starting and stopping @strong{MySQL} automatically -* Command-line options:: Command-line options -* Option files:: Option files - -Upgrading/Downgrading MySQL - -* Upgrading-from-3.22:: Upgrading from a 3.22 version to 3.23 -* Upgrading-from-3.21:: Upgrading from a 3.21 version to 3.22 -* Upgrading-from-3.20:: Upgrading from a 3.20 version to 3.21 -* Upgrading-to-arch:: Upgrading to another architecture - -The MySQL Access Privilege System - -* General security:: General security -* Security:: How to make @strong{MySQL} secure against crackers -* Privileges options:: -* What Privileges:: What the privilege system does -* User names:: @strong{MySQL} user names and passwords -* Connecting:: Connecting to the @strong{MySQL} server -* Password security:: Keeping your password secure -* Privileges provided:: Privileges provided by @strong{MySQL} -* Privileges:: How the privilege system works -* Connection access:: Access control, stage 1: Connection verification -* Request access:: Access control, stage 2: Request verification -* Privilege changes:: When privilege changes take effect -* Default privileges:: Setting up the initial @strong{MySQL} privileges -* Adding users:: Adding new users to @strong{MySQL} -* Passwords:: How to set up passwords -* Access denied:: Causes of @code{Access denied} errors - -MySQL Language Reference - -* Literals:: Literals: How to write strings and numbers -* Variables:: User variables -* Column types:: Column types -* Functions:: Functions -* CREATE DATABASE:: @code{CREATE DATABASE} syntax -* DROP DATABASE:: @code{DROP DATABASE} syntax -* CREATE TABLE:: @code{CREATE TABLE} syntax -* ALTER TABLE:: @code{ALTER TABLE} syntax -* RENAME TABLE:: @code{RENAME TABLE} syntax -* DROP TABLE:: @code{DROP TABLE} syntax -* OPTIMIZE TABLE:: @code{OPTIMIZE TABLE} syntax -* CHECK TABLE:: @code{CHECK TABLE} syntax -* BACKUP TABLE:: @code{BACKUP TABLE} syntax -* RESTORE TABLE:: @code{RESTORE TABLE} syntax -* ANALYZE TABLE:: @code{ANALYZE TABLE} syntax -* REPAIR TABLE:: @code{REPAIR TABLE} syntax -* DELETE:: @code{DELETE} syntax -* TRUNCATE:: @code{TRUNCATE} syntax -* SELECT:: @code{SELECT} syntax -* JOIN:: @code{JOIN} syntax -* INSERT:: @code{INSERT} syntax -* REPLACE:: @code{REPLACE} syntax -* LOAD DATA:: @code{LOAD DATA INFILE} syntax -* UPDATE:: @code{UPDATE} syntax -* USE:: @code{USE} syntax -* FLUSH:: @code{FLUSH} syntax (clearing caches) -* KILL:: @code{KILL} syntax -* SHOW:: @code{SHOW} syntax (Get information about tables, columns, ...) -* EXPLAIN:: @code{EXPLAIN} syntax (Get information about a @code{SELECT}) -* DESCRIBE:: @code{DESCRIBE} syntax (Get information about names of columns) -* COMMIT:: @code{BEGIN/COMMIT/ROLLBACK} syntax -* LOCK TABLES:: @code{LOCK TABLES/UNLOCK TABLES} syntax -* SET OPTION:: @code{SET OPTION} syntax -* SET TRANSACTION:: @code{SET TRANSACTION} syntax -* GRANT:: @code{GRANT} and @code{REVOKE} syntax -* CREATE INDEX:: @code{CREATE INDEX} syntax -* DROP INDEX:: @code{DROP INDEX} syntax -* Comments:: Comment syntax -* CREATE FUNCTION:: @code{CREATE FUNCTION} syntax -* Reserved words:: Is @strong{MySQL} picky about reserved words? - -Literals: How to Write Strings and Numbers - -* String syntax:: Strings -* Number syntax:: Numbers -* Hexadecimal values:: Hexadecimal values -* NULL values:: @code{NULL} values -* Legal names:: Database, Table, Index, Column, and Alias Names - -Database, Table, Index, Column, and Alias Names - -* Name case sensitivity:: Case sensitivity in names - -Column Types - -* Storage requirements:: Column type storage requirements -* Numeric types:: Numeric types -* Date and time types:: Date and time types -* String types:: String types -* Choosing types:: Choosing the right type for a column -* Indexes:: Column indexes -* Multiple-column indexes:: Multiple-column indexes -* Other-vendor column types:: Using column types from other database engines - -Date and Time Types - -* Y2K issues:: Y2K issues and date types -* DATETIME:: The @code{DATETIME}, @code{DATE} and @code{TIMESTAMP} types -* TIME:: The @code{TIME} type -* YEAR:: The @code{YEAR} type - -String Types - -* CHAR:: The @code{CHAR} and @code{VARCHAR} types -* BLOB:: The @code{BLOB} and @code{TEXT} types -* ENUM:: The @code{ENUM} type -* SET:: The @code{SET} type - -Functions for Use in @code{SELECT} and @code{WHERE} Clauses - -* Grouping functions:: Grouping functions -* Arithmetic functions:: Normal arithmetic operations -* Bit functions:: Bit functions -* Logical functions:: Logical operations -* Comparison functions:: Comparison operators -* String comparison functions:: String comparison functions -* Casts:: Cast operators -* Control flow functions:: Control flow functions -* Mathematical functions:: Mathematical functions -* String functions:: String functions -* Date and time functions:: Date and time functions -* Miscellaneous functions:: Miscellaneous functions -* Group by functions:: Functions for @code{GROUP BY} clause - -@code{CREATE TABLE} Syntax - -* Silent column changes:: Silent column changes - -@code{INSERT} Syntax - -* INSERT SELECT:: -* INSERT DELAYED:: - -@code{SHOW} Syntax - -* SHOW DATABASE INFO:: -* SHOW TABLE STATUS:: -* SHOW STATUS:: -* SHOW VARIABLES:: -* SHOW LOGS:: -* SHOW PROCESSLIST:: -* SHOW GRANTS:: -* SHOW CREATE TABLE:: - -MySQL Table Types - -* MyISAM:: MyISAM tables -* MERGE:: MERGE tables -* ISAM:: ISAM tables -* HEAP:: HEAP tables -* InnoDB:: InnoDB tables -* BDB:: BDB or Berkeley_db tables - -MyISAM Tables - -* Key space:: Space needed for keys -* MyISAM table formats:: MyISAM table formats -* MyISAM table problems:: - -MyISAM Table Formats - -* Static format:: Static (Fixed-length) table characteristics -* Dynamic format:: Dynamic table characteristics -* Compressed format:: Compressed table characteristics - -MyISAM table problems. - -* Corrupted MyISAM tables:: -* MyISAM table close:: - -InnoDB Tables - -* InnoDB overview:: InnoDB tables overview -* InnoDB start:: InnoDB startup options -* InnoDB init:: Creating InnoDB table space. -* Using InnoDB tables:: Creating InnoDB tables -* Adding and removing:: Adding and removing InnoDB data and log files -* Backing up:: Backing up and recovering an InnoDB database -* Moving:: Moving an InnoDB database to another machine -* InnoDB transaction model:: InnoDB transaction model. -* Implementation:: Implementation of multiversioning -* Table and index:: Table and index structures -* File space management:: File space management and disk i/o -* Error handling:: Error handling -* InnoDB restrictions:: Some restrictions on InnoDB tables -* InnoDB contact information:: InnoDB contact information. - -Creating InnoDB table space - -* Error creating InnoDB:: - -Backing up and recovering an InnoDB database - -* InnoDB checkpoints:: - -InnoDB transaction model - -* InnoDB consistent read:: -* InnoDB locking reads:: -* InnoDB Next-key locking:: -* InnoDB Locks set:: -* InnoDB Deadlock detection:: - -Table and index structures - -* InnoDB physical structure:: -* InnoDB Insert buffering:: -* InnoDB Adaptive hash:: -* InnoDB Physical record:: - -File space management and disk i/o - -* InnoDB Disk i/o:: -* InnoDB File space:: -* InnoDB File Defragmenting:: - -BDB or Berkeley_DB Tables - -* BDB overview:: Overview of BDB Tables -* BDB install:: Installing BDB -* BDB start:: BDB startup options -* BDB characteristic:: Some characteristic of @code{BDB} tables: -* BDB TODO:: Some things we need to fix for BDB in the near future: -* BDB portability:: Operating systems supported by @strong{BDB} -* BDB errors:: Errors You May Get When Using BDB Tables - -MySQL Tutorial - -* Connecting-disconnecting:: Connecting to and disconnecting from the server -* Entering queries:: Entering queries -* Database use:: Creating and using a database -* Getting information:: Getting information about databases and tables -* Examples:: Examples -* Batch mode:: Using @code{mysql} in batch mode -* Twin:: Queries from twin project - -Creating and Using a Database - -* Creating database:: Creating a database -* Creating tables:: Creating a table -* Loading tables:: Loading data into a table -* Retrieving data:: Retrieving information from a table - -Retrieving Information from a Table - -* Selecting all:: Selecting all data -* Selecting rows:: Selecting particular rows -* Selecting columns:: Selecting particular columns -* Sorting rows:: Sorting rows -* Date calculations:: Date calculations -* Working with NULL:: Working with @code{NULL} values -* Pattern matching:: Pattern matching -* Counting rows:: Counting rows -* Multiple tables:: - -Examples of Common Queries - -* example-Maximum-column:: The maximum value for a column -* example-Maximum-row:: The row holding the maximum of a certain column -* example-Maximum-column-group:: Maximum of column per group -* example-Maximum-column-group-row:: The rows holding the group-wise maximum of a certain field -* example-user-variables:: Using user variables -* example-Foreign keys:: Using foreign keys -* Searching on two keys:: -* Calculating days:: - -Queries from Twin Project - -* Twin pool:: Find all non-distributed twins -* Twin event:: Show a table on twin pair status - -MySQL Server Functions - -* Languages:: What languages are supported by @strong{MySQL}? - -What Languages Are Supported by MySQL? - -* Character sets:: The character set used for data and sorting -* Adding character set:: Adding a new character set -* Character arrays:: The character definition arrays -* String collating:: String collating support -* Multi-byte characters:: Multi-byte character support - -Replication in MySQL - -* Replication Intro:: Introduction -* Replication Implementation:: Replication Implementation Overview -* Replication HOWTO:: HOWTO -* Replication Features:: Replication Features -* Replication Options:: Replication Options in my.cnf -* Replication SQL:: SQL Commands related to replication -* Replication FAQ:: Frequently Asked Questions about replication -* Replication Problems:: Troubleshooting Replication. - -MySQL Full-text Search - -* Fulltext Fine-tuning:: -* Fulltext Features to Appear in MySQL 4.0:: -* Fulltext TODO:: - -Getting Maximum Performance from MySQL - -* Optimize Basics:: Optimization overview -* System:: System/Compile time and startup parameter tuning -* Data size:: Get your data as small as possible -* MySQL indexes:: How @strong{MySQL} uses indexes -* Query Speed:: Speed of queries that access or update data -* Tips:: Other optimization tips -* Benchmarks:: Using your own benchmarks -* Design:: Design choices -* Design Limitations:: MySQL design limitations/tradeoffs -* Portability:: Portability -* Internal use:: What have we used MySQL for? - -System/Compile Time and Startup Parameter Tuning - -* Compile and link options:: How compiling and linking affects the speed of MySQL -* Disk issues:: Disk issues -* Symbolic links:: Using Symbolic Links -* Server parameters:: Tuning server parameters -* Table cache:: How MySQL opens and closes tables -* Creating many tables:: Drawbacks of creating large numbers of tables in the same database -* Open tables:: Why so many open tables? -* Memory use:: How MySQL uses memory -* Internal locking:: How MySQL locks tables -* Table locking:: Table locking issues -* DNS:: - -Using Symbolic Links - -* Symbolic links to database:: -* Symbolic links to tables:: - -Speed of Queries that Access or Update Data - -* Estimating performance:: Estimating query performance -* SELECT speed:: Speed of @code{SELECT} queries -* Where optimizations:: How MySQL optimizes @code{WHERE} clauses -* DISTINCT optimization:: How MySQL Optimizes @code{DISTINCT} -* LEFT JOIN optimization:: How MySQL optimizes @code{LEFT JOIN} -* LIMIT optimization:: How MySQL optimizes @code{LIMIT} -* Insert speed:: Speed of @code{INSERT} queries -* Update speed:: Speed of @code{UPDATE} queries -* Delete speed:: Speed of @code{DELETE} queries - -MySQL Utilites - -* Programs:: What do the executables do? -* mysqld-max:: mysqld-max, An extended mysqld server -* safe_mysqld:: safe_mysqld, the wrapper around mysqld -* mysqld_multi:: Program for managing multiple @strong{MySQL} servers -* mysql:: The command line tool -* mysqladmin:: Administering a @strong{MySQL} server -* mysqldump:: Dumping the structure and data from @strong{MySQL} databases and tables -* mysqlhotcopy:: Copying @strong{MySQL} Databases and Tables -* mysqlimport:: Importing data from text files -* perror:: Displaying error messages -* mysqlshow:: Showing databases, tables and columns -* myisampack:: The @strong{MySQL} compressed read-only table generator - -Maintaining a MySQL Installation - -* Table maintenance:: Table maintenance and crash recovery -* Using mysqlcheck:: Using mysqlcheck for maintenance and recovery -* Maintenance regimen:: Setting up a table maintenance regimen -* Table-info:: Getting information about a table -* Crash recovery:: Using @code{myisamchk} for crash recovery -* Log file maintenance:: Log file maintenance - -Using @code{myisamchk} for Table Maintenance and Crash Recovery - -* myisamchk syntax:: @code{myisamchk} invocation syntax -* myisamchk memory:: @code{myisamchk} memory usage - -@code{myisamchk} Invocation Syntax - -* myisamchk general options:: -* myisamchk check options:: -* myisamchk repair options:: -* myisamchk other options:: - -Using @code{myisamchk} for Crash Recovery - -* Check:: How to check tables for errors -* Repair:: How to repair tables -* Optimization:: Table optimization - -Adding New Functions to MySQL - -* Adding UDF:: Adding a new user-definable function -* Adding native function:: Adding a new native function - -Adding a New User-definable Function - -* UDF calling sequences:: UDF calling sequences -* UDF arguments:: Argument processing -* UDF return values:: Return values and error handling -* UDF compiling:: Compiling and installing user-definable functions - -Adding New Procedures to MySQL - -* procedure analyse:: Procedure analyse -* Writing a procedure:: Writing a procedure. - -MySQL ODBC Support - -* Installing MyODBC:: How to install MyODBC -* ODBC administrator:: How to fill in the various fields in the ODBC administrator program -* MyODBC connect parameters:: -* ODBC Problems:: How to report problems with @strong{MySQL} ODBC -* MyODBC clients:: Programs known to work with @strong{MyODBC} -* ODBC and last_insert_id:: How to get the value of an @code{AUTO_INCREMENT} column in ODBC -* MyODBC bug report:: Reporting problems with MyODBC - -Using MySQL with Some Common Programs - -* Apache:: Using @strong{MySQL} with Apache -* Borland C++:: - -Problems and Common Errors - -* What is crashing:: How to determine what is causing problems -* Crashing:: What to do if @strong{MySQL} keeps crashing -* Link errors:: Problems when linking with the @strong{MySQL} client library -* Common errors:: Some common errors when using @strong{MySQL} -* Full disk:: How @strong{MySQL} handles a full disk -* Multiple sql commands:: How to run SQL commands from a text file -* Temporary files:: Where @strong{MySQL} stores temporary files -* Problems with mysql.sock:: How to protect @file{/tmp/mysql.sock} -* Changing MySQL user:: How to run @strong{MySQL} as a normal user -* Resetting permissions:: How to reset a forgotten password. -* File permissions :: Problems with file permissions -* Not enough file handles:: File not found -* Using DATE:: Problems using @code{DATE} columns -* Timezone problems:: Timezone problems -* Case sensitivity:: Case sensitivity in searches -* Problems with NULL:: Problems with @code{NULL} values -* Problems with alias:: Problems with @code{alias} -* Deleting from related tables:: Deleting rows from related tables -* No matching rows:: Solving problems with no matching rows -* ALTER TABLE problems:: Problems with @code{ALTER TABLE}. -* Change column order:: How to change the order of columns in a table -* Temporary table problems:: - -Some Common Errors When Using MySQL - -* Error Access denied:: @code{Access denied} Error -* Gone away:: @code{MySQL server has gone away} error -* Can not connect to server:: @code{Can't connect to [local] MySQL server} error -* Blocked host:: @code{Host '...' is blocked} error -* Too many connections:: @code{Too many connections} error -* Non-transactional tables:: @code{Some non-transactional changed tables couldn't be rolled back} Error -* Out of memory:: @code{Out of memory} error -* Packet too large:: @code{Packet too large} error -* Communication errors:: Communication errors / Aborted connection -* Full table:: @code{The table is full} error -* Cannot create:: @code{Can't create/write to file} Error -* Commands out of sync:: @code{Commands out of sync} error in client -* Ignoring user:: @code{Ignoring user} error -* Cannot find table:: @code{Table 'xxx' doesn't exist} error -* Cannot initialize character set:: - -Solving Some Common Problems with MySQL - -* Log Replication:: Database replication with update log -* Backup:: Database backups -* Multiple servers:: Running multiple @strong{MySQL} servers on the same machine - -The MySQL log files - -* Error log:: -* Query log:: -* Update log:: -* Binary log:: -* Slow query log:: - -MySQL APIs - -* C:: @strong{MySQL} C API -* Perl:: @strong{MySQL} Perl API -* Eiffel:: @strong{MySQL} Eiffel wrapper -* Java:: @strong{MySQL} Java connectivity (JDBC) -* PHP:: @strong{MySQL} PHP API -* Cplusplus:: @strong{MySQL} C++ APIs -* Python:: @strong{MySQL} Python APIs -* Tcl:: @strong{MySQL} Tcl APIs - -MySQL C API - -* C API datatypes:: C API Datatypes -* C API function overview:: C API Function Overview -* C API functions:: C API Function Descriptions -* C API problems:: -* Thread-safe clients:: - -C API Function Descriptions - -* mysql_affected_rows:: @code{mysql_affected_rows()} -* mysql_close:: @code{mysql_close()} -* mysql_connect:: @code{mysql_connect()} -* mysql_change_user:: @code{mysql_change_user()} -* mysql_character_set_name:: @code{mysql_character_set_name()} -* mysql_create_db:: @code{mysql_create_db()} -* mysql_data_seek:: @code{mysql_data_seek()} -* mysql_debug:: @code{mysql_debug()} -* mysql_drop_db:: @code{mysql_drop_db()} -* mysql_dump_debug_info:: @code{mysql_dump_debug_info()} -* mysql_eof:: @code{mysql_eof()} -* mysql_errno:: @code{mysql_errno()} -* mysql_error:: @code{mysql_error()} -* mysql_escape_string:: @code{mysql_escape_string()} -* mysql_fetch_field:: @code{mysql_fetch_field()} -* mysql_fetch_fields:: @code{mysql_fetch_fields()} -* mysql_fetch_field_direct:: @code{mysql_fetch_field_direct()} -* mysql_fetch_lengths:: @code{mysql_fetch_lengths()} -* mysql_fetch_row:: @code{mysql_fetch_row()} -* mysql_field_count:: @code{mysql_field_count()} -* mysql_field_seek:: @code{mysql_field_seek()} -* mysql_field_tell:: @code{mysql_field_tell()} -* mysql_free_result:: @code{mysql_free_result()} -* mysql_get_client_info:: @code{mysql_get_client_info()} -* mysql_get_host_info:: @code{mysql_get_host_info()} -* mysql_get_proto_info:: @code{mysql_get_proto_info()} -* mysql_get_server_info:: @code{mysql_get_server_info()} -* mysql_info:: @code{mysql_info()} -* mysql_init:: @code{mysql_init()} -* mysql_insert_id:: @code{mysql_insert_id()} -* mysql_kill:: @code{mysql_kill()} -* mysql_list_dbs:: @code{mysql_list_dbs()} -* mysql_list_fields:: @code{mysql_list_fields()} -* mysql_list_processes:: @code{mysql_list_processes()} -* mysql_list_tables:: @code{mysql_list_tables()} -* mysql_num_fields:: @code{mysql_num_fields()} -* mysql_num_rows:: @code{mysql_num_rows()} -* mysql_options:: @code{mysql_options()} -* mysql_ping:: @code{mysql_ping()} -* mysql_query:: @code{mysql_query()} -* mysql_real_connect:: @code{mysql_real_connect()} -* mysql_real_escape_string:: @code{mysql_real_escape_string()} -* mysql_real_query:: @code{mysql_real_query()} -* mysql_reload:: @code{mysql_reload()} -* mysql_row_seek:: @code{mysql_row_seek()} -* mysql_row_tell:: @code{mysql_row_tell()} -* mysql_select_db:: @code{mysql_select_db()} -* mysql_shutdown:: @code{mysql_shutdown()} -* mysql_stat:: @code{mysql_stat()} -* mysql_store_result:: @code{mysql_store_result()} -* mysql_thread_id:: @code{mysql_thread_id()} -* mysql_use_result:: @code{mysql_use_result()} - -Common questions and problems when using the C API - -* NULL mysql_store_result:: -* Query results:: -* Getting unique ID:: -* C API linking problems:: - -Why Is It that After @code{mysql_query()} Returns Success, @code{mysql_store_result()} Sometimes Returns @code{NULL?} - -* Query results:: -* Getting unique ID:: -* C API linking problems:: - -MySQL Perl API - -* DBI with DBD:: @code{DBI} with @code{DBD::mysql} -* Perl DBI Class:: The @code{DBI} interface -* DBI-info:: More @code{DBI}/@code{DBD} information - -MySQL PHP API - -* PHP problems:: Common problems with MySQL and PHP - -MySQL Internals - -* MySQL threads:: MySQL threads -* MySQL test suite:: MySQL test suite - -MySQL Test Suite - -* running mysqltest:: -* extending mysqltest:: -* Reporting mysqltest bugs:: - -Credits - -* Developers:: -* Contributors:: -* Supporters:: - -MySQL change history - -* News-4.0.x:: Changes in release 4.0.x (Development; Alpha) -* News-3.23.x:: Changes in release 3.23.x (Stable) -* News-3.22.x:: Changes in release 3.22.x (Older; Still supported) -* News-3.21.x:: Changes in release 3.21.x -* News-3.20.x:: Changes in release 3.20.x -* News-3.19.x:: Changes in release 3.19.x - -Changes in release 4.0.x (Development; Alpha) - -* News-4.0.0:: Changes in release 4.0.0 - -Changes in release 3.23.x (Stable) - -* News-3.23.40:: Changes in release 3.23.40 -* News-3.23.39:: Changes in release 3.23.39 -* News-3.23.38:: Changes in release 3.23.38 -* News-3.23.37:: Changes in release 3.23.37 -* News-3.23.36:: Changes in release 3.23.36 -* News-3.23.35:: Changes in release 3.23.35 -* News-3.23.34a:: Changes in release 3.23.34a -* News-3.23.34:: Changes in release 3.23.34 -* News-3.23.33:: Changes in release 3.23.33 -* News-3.23.32:: Changes in release 3.23.32 -* News-3.23.31:: Changes in release 3.23.31 -* News-3.23.30:: Changes in release 3.23.30 -* News-3.23.29:: Changes in release 3.23.29 -* News-3.23.28:: Changes in release 3.23.28 -* News-3.23.27:: Changes in release 3.23.27 -* News-3.23.26:: Changes in release 3.23.26 -* News-3.23.25:: Changes in release 3.23.25 -* News-3.23.24:: Changes in release 3.23.24 -* News-3.23.23:: Changes in release 3.23.23 -* News-3.23.22:: Changes in release 3.23.22 -* News-3.23.21:: Changes in release 3.23.21 -* News-3.23.20:: Changes in release 3.23.20 -* News-3.23.19:: Changes in release 3.23.19 -* News-3.23.18:: Changes in release 3.23.18 -* News-3.23.17:: Changes in release 3.23.17 -* News-3.23.16:: Changes in release 3.23.16 -* News-3.23.15:: Changes in release 3.23.15 -* News-3.23.14:: Changes in release 3.23.14 -* News-3.23.13:: Changes in release 3.23.13 -* News-3.23.12:: Changes in release 3.23.12 -* News-3.23.11:: Changes in release 3.23.11 -* News-3.23.10:: Changes in release 3.23.10 -* News-3.23.9:: Changes in release 3.23.9 -* News-3.23.8:: Changes in release 3.23.8 -* News-3.23.7:: Changes in release 3.23.7 -* News-3.23.6:: Changes in release 3.23.6 -* News-3.23.5:: Changes in release 3.23.5 -* News-3.23.4:: Changes in release 3.23.4 -* News-3.23.3:: Changes in release 3.23.3 -* News-3.23.2:: Changes in release 3.23.2 -* News-3.23.1:: Changes in release 3.23.1 -* News-3.23.0:: Changes in release 3.23.0 - -Changes in release 3.22.x (Older; Still supported) - -* News-3.22.35:: Changes in release 3.22.35 -* News-3.22.34:: Changes in release 3.22.34 -* News-3.22.33:: Changes in release 3.22.33 -* News-3.22.32:: Changes in release 3.22.32 -* News-3.22.31:: Changes in release 3.22.31 -* News-3.22.30:: Changes in release 3.22.30 -* News-3.22.29:: Changes in release 3.22.29 -* News-3.22.28:: Changes in release 3.22.28 -* News-3.22.27:: Changes in release 3.22.27 -* News-3.22.26:: Changes in release 3.22.26 -* News-3.22.25:: Changes in release 3.22.25 -* News-3.22.24:: Changes in release 3.22.24 -* News-3.22.23:: Changes in release 3.22.23 -* News-3.22.22:: Changes in release 3.22.22 -* News-3.22.21:: Changes in release 3.22.21 -* News-3.22.20:: Changes in release 3.22.20 -* News-3.22.19:: Changes in release 3.22.19 -* News-3.22.18:: Changes in release 3.22.18 -* News-3.22.17:: Changes in release 3.22.17 -* News-3.22.16:: Changes in release 3.22.16 -* News-3.22.15:: Changes in release 3.22.15 -* News-3.22.14:: Changes in release 3.22.14 -* News-3.22.13:: Changes in release 3.22.13 -* News-3.22.12:: Changes in release 3.22.12 -* News-3.22.11:: Changes in release 3.22.11 -* News-3.22.10:: Changes in release 3.22.10 -* News-3.22.9:: Changes in release 3.22.9 -* News-3.22.8:: Changes in release 3.22.8 -* News-3.22.7:: Changes in release 3.22.7 -* News-3.22.6:: Changes in release 3.22.6 -* News-3.22.5:: Changes in release 3.22.5 -* News-3.22.4:: Changes in release 3.22.4 -* News-3.22.3:: Changes in release 3.22.3 -* News-3.22.2:: Changes in release 3.22.2 -* News-3.22.1:: Changes in release 3.22.1 -* News-3.22.0:: Changes in release 3.22.0 - -Changes in release 3.21.x - -* News-3.21.33:: Changes in release 3.21.33 -* News-3.21.32:: Changes in release 3.21.32 -* News-3.21.31:: Changes in release 3.21.31 -* News-3.21.30:: Changes in release 3.21.30 -* News-3.21.29:: Changes in release 3.21.29 -* News-3.21.28:: Changes in release 3.21.28 -* News-3.21.27:: Changes in release 3.21.27 -* News-3.21.26:: Changes in release 3.21.26 -* News-3.21.25:: Changes in release 3.21.25 -* News-3.21.24:: Changes in release 3.21.24 -* News-3.21.23:: Changes in release 3.21.23 -* News-3.21.22:: Changes in release 3.21.22 -* News-3.21.21a:: Changes in release 3.21.21a -* News-3.21.21:: Changes in release 3.21.21 -* News-3.21.20:: Changes in release 3.21.20 -* News-3.21.19:: Changes in release 3.21.19 -* News-3.21.18:: Changes in release 3.21.18 -* News-3.21.17:: Changes in release 3.21.17 -* News-3.21.16:: Changes in release 3.21.16 -* News-3.21.15:: Changes in release 3.21.15 -* News-3.21.14b:: Changes in release 3.21.14b -* News-3.21.14a:: Changes in release 3.21.14a -* News-3.21.13:: Changes in release 3.21.13 -* News-3.21.12:: Changes in release 3.21.12 -* News-3.21.11:: Changes in release 3.21.11 -* News-3.21.10:: Changes in release 3.21.10 -* News-3.21.9:: Changes in release 3.21.9 -* News-3.21.8:: Changes in release 3.21.8 -* News-3.21.7:: Changes in release 3.21.7 -* News-3.21.6:: Changes in release 3.21.6 -* News-3.21.5:: Changes in release 3.21.5 -* News-3.21.4:: Changes in release 3.21.4 -* News-3.21.3:: Changes in release 3.21.3 -* News-3.21.2:: Changes in release 3.21.2 -* News-3.21.0:: Changes in release 3.21.0 - -Changes in release 3.20.x - -* News-3.20.18:: Changes in release 3.20.18 -* News-3.20.17:: Changes in release 3.20.17 -* News-3.20.16:: Changes in release 3.20.16 -* News-3.20.15:: Changes in release 3.20.15 -* News-3.20.14:: Changes in release 3.20.14 -* News-3.20.13:: Changes in release 3.20.13 -* News-3.20.11:: Changes in release 3.20.11 -* News-3.20.10:: Changes in release 3.20.10 -* News-3.20.9:: Changes in release 3.20.9 -* News-3.20.8:: Changes in release 3.20.8 -* News-3.20.7:: Changes in release 3.20.7 -* News-3.20.6:: Changes in release 3.20.6 -* News-3.20.3:: Changes in release 3.20.3 -* News-3.20.0:: Changes in releases 3.20.0 - -Changes in release 3.19.x - -* News-3.19.5:: Changes in release 3.19.5 -* News-3.19.4:: Changes in release 3.19.4 -* News-3.19.3:: Changes in release 3.19.3 - -Comments on porting to other systems - -* Debugging server:: Debugging a @strong{MySQL} server -* Debugging client:: Debugging a @strong{MySQL} client -* The DBUG package:: The DBUG package -* Locking methods:: Locking methods -* RTS-threads:: Comments about RTS threads -* Thread packages:: Differences between different thread packages - -Debugging a MySQL server - -* Compiling for debugging:: -* Making trace files:: -* Using gdb on mysqld:: -* Using stack trace:: -* Using log files:: -* Reproduceable test case:: - -@end detailmenu @end menu @cindex overview @@ -10310,10 +9307,10 @@ You should also add /etc/my.cnf: @example [safe_mysqld] -open_files_limit=8192 +open-files-limit=8192 @end example -The above should allow @strong{MySQL} to create up to 8192 connections/files. +The above should allow @strong{MySQL} to create up to 8192 connections + files. The @code{STACK_SIZE} constant in LinuxThreads controls the spacing of thread stacks in the address space. It needs to be large enough so that there will @@ -24806,17 +23803,9 @@ are locked by the current thread are automatically unlocked when the thread issues another @code{LOCK TABLES}, or when the connection to the server is closed. -The main reasons to use @code{LOCK TABLES} are: - -@itemize @bullet -@item -Emulate transactions with not transaction safe tables. -@item -To get more speed with @code{MyISAM} tables when inserting/updating data -over many statements. The main reason this gives more speed is that -@strong{MySQL} will not flush the key cache for the locked tables until -@code{UNLOCK TABLES} is called. -@end itemize +The main reasons to use @code{LOCK TABLES} are for emulating transactions +or getting more speed when updating tables. This is explained in more +detail later. If a thread obtains a @code{READ} lock on a table, that thread (and all other threads) can only read from the table. If a thread obtains a @code{WRITE} @@ -24829,8 +23818,10 @@ execute while the lock is held. This can't however be used if you are going to manipulate the database files outside @strong{MySQL} while you hold the lock. -Each thread waits (without timing out) until it obtains all the locks it has -requested. +When you use @code{LOCK TABLES}, you must lock all tables that you are +going to use and you must use the same alias that you are going to use +in your queries! If you are using a table multiple times in a query +(with aliases), you must get a lock for each alias! @code{WRITE} locks normally have higher priority than @code{READ} locks, to ensure that updates are processed as soon as possible. This means that if one @@ -24842,15 +23833,32 @@ locks while the thread is waiting for the @code{WRITE} lock. You should only use @code{LOW_PRIORITY WRITE} locks if you are sure that there will eventually be a time when no threads will have a @code{READ} lock. -@code{LOCK TABLES} and @code{UNLOCK TABLES} both commits any active -transactions. +@code{LOCK TABLES} works as follows: +@enumerate +@item +Sort all tables to be locked in a internally defined order (from the +user standpoint the order is undefined). +@item +If a table is locked with a read and a write lock, put the write lock +before the read lock. +@item +Lock one table at a time until the thread gets all locks. +@end enumerate -When you use @code{LOCK TABLES}, you must lock all tables that you are -going to use and you must use the same alias that you are going to use -in your queries! If you are using a table multiple times in a query -(with aliases), you must get a lock for each alias! This policy ensures -that table locking is deadlock free and makes the locking code smaller, -simpler and much faster. +This policy ensures that table locking is deadlock free. There is +however other things one needs to be aware of with this schema: + +If you are using a @code{LOW_PRIORITY_WRITE} lock for a table, this +means only that @strong{MySQL} will wait for this particlar lock until +there is no threads that wants a @code{READ} lock. When the thread has +got the @code{WRITE} lock and is waiting to get the lock for the next +table in the lock table list, all other threads will wait for the +@code{WRITE} lock to be released. If this becomes a serious problem +with your application, you should consider converting some of your +tables to transactions safe tables. + +You can safely kill a thread that is waiting for a table lock with +@code{KILL}. @xref{KILL}. Note that you should @strong{NOT} lock any tables that you are using with @code{INSERT DELAYED}. This is because that in this case the @code{INSERT} @@ -24867,6 +23875,12 @@ If you are going to run many operations on a bunch of tables, it's much faster to lock the tables you are going to use. The downside is, of course, that no other thread can update a @code{READ}-locked table and no other thread can read a @code{WRITE}-locked table. + +The reason some things are faster under @code{LOCK TABLES} is that +@strong{MySQL} will not flush the key cache for the locked tables until +@code{UNLOCK TABLES} is called (normally the key cache is flushed after +each SQL statement). This speeds up inserting/updateing/deletes on +@code{MyISAM} tables. @item If you are using a table handler in @strong{MySQL} that doesn't support transactions, you must use @code{LOCK TABLES} if you want to ensure that @@ -24898,7 +23912,7 @@ table in the server and implemented with @code{pthread_mutex_lock()} and See @ref{Internal locking}, for more information on locking policy. -You can also lock all tables in all databases with read locks with the +You can lock all tables in all databases with read locks with the @code{FLUSH TABLES WITH READ LOCK} command. @xref{FLUSH}. This is very convenient way to get backups if you have a file system, like Veritas, that can take snapshots in time. @@ -46299,8 +45313,6 @@ For making @code{mysqlaccess} more secure. @item Albert Chin-A-Young. Configure updates for Tru64, large file support and better TCP wrappers support. -@item Valueclick Inc. -For sponsoring the optimize section in this manual. @end table Other contributors, bugfinders, and testers: James H. Thompson, Maurizio @@ -46496,6 +45508,7 @@ users use this code as the rest of the code and because of this we are not yet 100% confident in this code. @menu +* News-3.23.41:: * News-3.23.40:: Changes in release 3.23.40 * News-3.23.39:: Changes in release 3.23.39 * News-3.23.38:: Changes in release 3.23.38 @@ -46540,7 +45553,15 @@ not yet 100% confident in this code. * News-3.23.0:: Changes in release 3.23.0 @end menu -@node News-3.23.40, News-3.23.39, News-3.23.x, News-3.23.x +@node News-3.23.41, News-3.23.40, News-3.23.x, News-3.23.x +@appendixsubsec Changes in release 3.23.41 +@itemize @bullet +@item +Fixed optimizing bug in @code{ORDER BY} where some @code{ORDER BY} parts +where wrongly removed. +@end itemize + +@node News-3.23.40, News-3.23.39, News-3.23.41, News-3.23.x @appendixsubsec Changes in release 3.23.40 @itemize @bullet @item diff --git a/mysql-test/r/order_by.result b/mysql-test/r/order_by.result index 74c8bd53af2..1a292b1203c 100644 --- a/mysql-test/r/order_by.result +++ b/mysql-test/r/order_by.result @@ -111,3 +111,34 @@ DateOfAction TransactionID member_id nickname voornaam 1 2 +gid sid uid +104620 5 15 +103867 5 27 +103962 5 27 +104619 5 75 +104505 5 117 +103853 5 250 +gid sid uid +104620 5 15 +103867 5 27 +103962 5 27 +104619 5 75 +104505 5 117 +103853 5 250 +table type possible_keys key key_len ref rows Extra +t1 index PRIMARY PRIMARY 4 NULL 6 Using index +t2 eq_ref PRIMARY,uid PRIMARY 4 t1.gid 1 +t3 eq_ref PRIMARY PRIMARY 2 t2.uid 1 where used; Using index +table type possible_keys key key_len ref rows Extra +t1 index PRIMARY PRIMARY 4 NULL 6 Using index +t3 eq_ref PRIMARY PRIMARY 2 t1.gid 1 where used +table type possible_keys key key_len ref rows Extra +t1 index PRIMARY PRIMARY 4 NULL 6 Using index; Using temporary; Using filesort +t2 eq_ref PRIMARY,uid PRIMARY 4 t1.gid 1 +t3 eq_ref PRIMARY PRIMARY 2 t2.uid 1 where used; Using index +table type possible_keys key key_len ref rows Extra +t1 index PRIMARY PRIMARY 4 NULL 6 Using index; Using temporary; Using filesort +t3 eq_ref PRIMARY PRIMARY 2 t1.gid 1 where used +table type possible_keys key key_len ref rows Extra +t1 ALL NULL NULL NULL NULL 6 Using temporary; Using filesort +t3 eq_ref PRIMARY PRIMARY 2 t1.skr 1 where used diff --git a/mysql-test/t/order_by.test b/mysql-test/t/order_by.test index 4e5cee0d0ff..16094206745 100644 --- a/mysql-test/t/order_by.test +++ b/mysql-test/t/order_by.test @@ -168,8 +168,8 @@ drop table t1,t2,t3; #bug reported by Wouter de Jong -drop table if exists members; -CREATE TABLE members ( +drop table if exists t1; +CREATE TABLE t1 ( member_id int(11) NOT NULL auto_increment, inschrijf_datum varchar(20) NOT NULL default '', lastchange_datum varchar(20) NOT NULL default '', @@ -200,8 +200,50 @@ CREATE TABLE members ( PRIMARY KEY (member_id) ) TYPE=MyISAM PACK_KEYS=1; -insert into members (member_id) values (1),(2),(3); -select member_id, nickname, voornaam FROM members +insert into t1 (member_id) values (1),(2),(3); +select member_id, nickname, voornaam FROM t1 ORDER by lastchange_datum DESC LIMIT 2; -drop table members; +drop table t1; +# +# Test optimizing bug with EQ_REF tables, where some ORDER BY parts where +# wrongly removed. + +CREATE TABLE t1 ( + gid int(10) unsigned NOT NULL auto_increment, + cid smallint(5) unsigned NOT NULL default '0', + PRIMARY KEY (gid), + KEY component_id (cid) +) TYPE=MyISAM; +INSERT INTO t1 VALUES (103853,108),(103867,108),(103962,108),(104505,108),(104619,108),(104620,108); +ALTER TABLE t1 add skr int(10) not null; + +CREATE TABLE t2 ( + gid int(10) unsigned NOT NULL default '0', + uid smallint(5) unsigned NOT NULL default '1', + sid tinyint(3) unsigned NOT NULL default '1', + PRIMARY KEY (gid), + KEY uid (uid), + KEY status_id (sid) +) TYPE=MyISAM; +INSERT INTO t2 VALUES (103853,250,5),(103867,27,5),(103962,27,5),(104505,117,5),(104619,75,5),(104620,15,5); + +CREATE TABLE t3 ( + uid smallint(6) NOT NULL auto_increment, + PRIMARY KEY (uid) +) TYPE=MyISAM; +INSERT INTO t3 VALUES (1),(15),(27),(75),(117),(250); +ALTER TABLE t3 add skr int(10) not null; + +select t1.gid, t2.sid, t3.uid from t2, t1, t3 where t2.gid = t1.gid and t2.uid = t3.uid order by t3.uid, t1.gid; +select t1.gid, t2.sid, t3.uid from t3, t2, t1 where t2.gid = t1.gid and t2.uid = t3.uid order by t3.uid, t1.gid; + +# The following ORDER BY can be optimimized +EXPLAIN select t1.gid, t2.sid, t3.uid from t3, t2, t1 where t2.gid = t1.gid and t2.uid = t3.uid order by t1.gid, t3.uid; +EXPLAIN SELECT t1.gid, t3.uid from t1, t3 where t1.gid = t3.uid order by t1.gid,t3.skr; + +# The following ORDER BY can't be optimimized +EXPLAIN SELECT t1.gid, t2.sid, t3.uid from t2, t1, t3 where t2.gid = t1.gid and t2.uid = t3.uid order by t3.uid, t1.gid; +EXPLAIN SELECT t1.gid, t3.uid from t1, t3 where t1.gid = t3.uid order by t3.skr,t1.gid; +EXPLAIN SELECT t1.gid, t3.uid from t1, t3 where t1.skr = t3.uid order by t1.gid,t3.skr; +drop table t1,t2,t3; diff --git a/mysys/default.c b/mysys/default.c index cb842da0f02..126c0270a17 100644 --- a/mysys/default.c +++ b/mysys/default.c @@ -222,7 +222,7 @@ static my_bool search_default_file(DYNAMIC_ARRAY *args, MEM_ROOT *alloc, const char *dir, const char *config_file, const char *ext, TYPELIB *group) { - char name[FN_REFLEN+10],buff[FN_REFLEN+1],*ptr,*end,*value,*tmp; + char name[FN_REFLEN+10],buff[4096],*ptr,*end,*value,*tmp; FILE *fp; uint line=0; my_bool read_values=0,found_group=0; diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 82b73e5a48f..d23a7edd37e 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -2649,12 +2649,12 @@ static void update_depend_map(JOIN *join) for (i=0 ; i < ref->key_parts ; i++,item++) depend_map|=(*item)->used_tables(); ref->depend_map=depend_map; - for (JOIN_TAB *join_tab2=join->join_tab; + for (JOIN_TAB **tab=join->map2table; depend_map ; - join_tab2++,depend_map>>=1 ) + tab++,depend_map>>=1 ) { if (depend_map & 1) - ref->depend_map|=join_tab2->ref.depend_map; + ref->depend_map|=(*tab)->ref.depend_map; } } } @@ -2671,12 +2671,12 @@ static void update_depend_map(JOIN *join, ORDER *order) order->depend_map=depend_map=order->item[0]->used_tables(); if (!(order->depend_map & RAND_TABLE_BIT)) // Not item_sum() or RAND() { - for (JOIN_TAB *join_tab=join->join_tab; + for (JOIN_TAB **tab=join->map2table; depend_map ; - join_tab++, depend_map>>=1) + tab++, depend_map>>=1) { if (depend_map & 1) - order->depend_map|=join_tab->ref.depend_map; + order->depend_map|=(*tab)->ref.depend_map; } } } From d078b8f817ba667bb1e36029c5c40864e4b48221 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 30 Jul 2001 17:43:58 -0600 Subject: [PATCH 14/51] added test case for fulltext join bug --- mysql-test/t/fulltext_join.test | 38 +++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 mysql-test/t/fulltext_join.test diff --git a/mysql-test/t/fulltext_join.test b/mysql-test/t/fulltext_join.test new file mode 100644 index 00000000000..c5e6037180a --- /dev/null +++ b/mysql-test/t/fulltext_join.test @@ -0,0 +1,38 @@ +DROP TABLE IF EXISTS stories; +CREATE TABLE stories ( + sid char(16) NOT NULL, + tid smallint UNSIGNED NOT NULL, + uid mediumint UNSIGNED NOT NULL, + title varchar(100) DEFAULT '' NOT NULL, + dept varchar(100), + time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, + hits mediumint UNSIGNED DEFAULT '0' NOT NULL, + section varchar(30) DEFAULT '' NOT NULL, + displaystatus tinyint DEFAULT '0' NOT NULL, + commentstatus tinyint, + discussion mediumint UNSIGNED, + submitter mediumint UNSIGNED NOT NULL, + flags set("delete_me","data_dirty") DEFAULT '' NOT NULL, + PRIMARY KEY (sid), + FOREIGN KEY (uid) REFERENCES users(uid), + FOREIGN KEY (tid) REFERENCES tid(topic), + FOREIGN KEY (section) REFERENCES sections(section), + KEY time (time), + KEY searchform (displaystatus,time) +) TYPE = myisam; +DROP TABLE IF EXISTS story_text; +CREATE TABLE story_text ( + sid char(16) NOT NULL, + introtext text, + bodytext text, + relatedtext text, + FOREIGN KEY (sid) REFERENCES stories(sid), + PRIMARY KEY (sid) +) TYPE = myisam; +ALTER TABLE stories add fulltext (title); +ALTER TABLE story_text add fulltext (introtext,bodytext); + +SELECT stories.sid,title, TRUNCATE((MATCH (title,introtext,bodytext) +AGAINST('install')), 1) as score FROM stories,story_text WHERE +stories.sid = story_text.sid AND MATCH (title,introtext,bodytext) +AGAINST ('install'); From d77fe435f49ba0dd7bc69ce7b624f3aed174ce21 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 31 Jul 2001 08:55:29 -0500 Subject: [PATCH 15/51] DocTOC Chapter 2 Complete! --- Docs/manual.texi | 7170 +++++++++++++++++++++++----------------------- 1 file changed, 3617 insertions(+), 3553 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 7602409709f..18a204069ca 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -143,6 +143,7 @@ distribution for that version. * Unireg:: What is Unireg? * GPL license:: GNU General Public License * LGPL license:: GNU Library General Public License +* Placeholder:: * Function Index:: SQL command, type and function index * Concept Index:: Concept Index @@ -5954,29 +5955,20 @@ Nothing; In the long run we plan to be fully ANSI 92 / ANSI 99 compliant. @end itemize @node Installing, Privilege system, Introduction, Top -@chapter Installing MySQL +@chapter MySQL Installation @cindex installing, overview @menu -* Getting MySQL:: How to get @strong{MySQL} -* Which OS:: Operating systems supported by @strong{MySQL} -* Which version:: Which @strong{MySQL} version to use +* Quick Standard Installation:: +* General Installation Issues:: * Many versions:: How and when updates are released -* Installation layouts:: Installation layouts -* Installing binary:: Installing a @strong{MySQL} binary distribution -* Installing source:: Installing a @strong{MySQL} source distribution -* Installing source tree:: Installing @strong{MySQL} from development source tree -* Compilation problems:: Problems compiling? -* MIT-pthreads:: MIT-pthreads notes -* Perl support:: Perl installation comments -* Source install system issues:: System-specific issues -* Windows:: Windows notes -* OS/2:: OS/2 notes * MySQL binaries:: MySQL binaries +* Installing source:: Installing a @strong{MySQL} source distribution +* Perl support:: Perl installation comments * Post-installation:: Post-installation setup and testing -* Installing many servers:: Installing many servers on the same machine * Upgrade:: Upgrading/Downgrading MySQL +* Operating System Specific Notes:: @end menu This chapter describes how to obtain and install @strong{MySQL}: @@ -6012,14 +6004,186 @@ procedures apply whether you install @strong{MySQL} using a binary or source distribution. @end itemize +@node Quick Standard Installation, General Installation Issues, Installing, Installing +@section Quick Standard Installation of MySQL + +@c This node name is special +@menu +* Linux-RPM:: +* Windows installation:: +@end menu + +@node Linux-RPM, Windows installation, Quick Standard Installation, Quick Standard Installation +@subsection Installing MySQL on Linux + +@cindex RPM file +@cindex RedHat Package Manager + +The recommended way to install @strong{MySQL} on Linux is by using an RPM +file. The @strong{MySQL} RPMs are currently being built on a RedHat Version +6.2 system but should work on other versions of Linux that support @code{rpm} +and use @code{glibc}. + +If you have problems with an RPM file, for example, if you receive the error +``@code{Sorry, the host 'xxxx' could not be looked up}'', see +@ref{Binary notes-Linux}. + +The RPM files you may want to use are: + +@itemize @bullet +@item @code{MySQL-VERSION.i386.rpm} + +The @strong{MySQL} server. You will need this unless you only want to +connect to a @strong{MySQL} server running on another machine. + +@item @code{MySQL-client-VERSION.i386.rpm} + +The standard @strong{MySQL} client programs. You probably always want to +install this package. + +@item @code{MySQL-bench-VERSION.i386.rpm} + +Tests and benchmarks. Requires Perl and msql-mysql-modules RPMs. + +@item @code{MySQL-devel-VERSION.i386.rpm} + +Libraries and include files needed if you want to compile other +@strong{MySQL} clients, such as the Perl modules. + +@item @code{MySQL-VERSION.src.rpm} + +This contains the source code for all of the above packages. It can also +be used to try to build RPMs for other architectures (for example, Alpha +or SPARC). +@end itemize + +To see all files in an RPM package, run: +@example +shell> rpm -qpl MySQL-VERSION.i386.rpm +@end example + +To perform a standard minimal installation, run: + +@example +shell> rpm -i MySQL-VERSION.i386.rpm MySQL-client-VERSION.i386.rpm +@end example + +To install just the client package, run: + +@example +shell> rpm -i MySQL-client-VERSION.i386.rpm +@end example + +The RPM places data in @file{/var/lib/mysql}. The RPM also creates the +appropriate entries in @file{/etc/rc.d/} to start the server automatically +at boot time. (This means that if you have performed a previous +installation, you may want to make a copy of your previously installed +@strong{MySQL} startup file if you made any changes to it, so you don't lose +your changes.) + +After installing the RPM file(s), the @code{mysqld} daemon should be running +and you should now be able to start using @strong{MySQL}. +@xref{Post-installation}. + +If something goes wrong, you can find more information in the binary +installation chapter. @xref{Installing binary}. + +@node Windows installation, , Linux-RPM, Quick Standard Installation +@subsection Installing MySQL on Windows + +The following instructions apply to precompiled binary distributions. +If you download a source distribution, you will have to compile and install +it yourself. + +If you don't have a copy of the @strong{MySQL} distribution, you should +first download one from @uref{http://www.mysql.com/downloads/mysql-3.23.html}. + +If you plan to connect to @strong{MySQL} from some other program, you will +probably also need the @strong{MyODBC} driver. You can find this at the +@strong{MyODBC} download page +(@uref{http://www.mysql.com/downloads/api-myodbc.html}). + +To install either distribution, unzip it in some empty directory and run the +@code{Setup.exe} program. + +By default, @strong{MySQL}-Windows is configured to be installed in +@file{C:\mysql}. If you want to install @strong{MySQL} elsewhere, +install it in @file{C:\mysql} first, then move the installation to +where you want it. If you do move @strong{MySQL}, you must indicate +where everything is located by supplying a @code{--basedir} option when +you start the server. For example, if you have moved the @strong{MySQL} +distribution to @file{D:\programs\mysql}, you must start @code{mysqld} +like this: + +@example +C:\> D:\programs\mysql\bin\mysqld --basedir D:\programs\mysql +@end example + +Use @code{mysqld --help} to display all the options that @code{mysqld} +understands! + +With all newer @strong{MySQL} versions, you can also create a +@file{C:\my.cnf} file that holds any default options for the +@strong{MySQL} server. Copy the file @file{\mysql\my-xxxxx.cnf} to +@file{C:\my.cnf} and edit it to suit your setup. Note that you should +specify all paths with @samp{/} instead of @samp{\}. If you use +@samp{\}, you need to specify it twice, because @samp{\} is the escape +character in @strong{MySQL}. @xref{Option files}. + +Starting with @strong{MySQL} 3.23.38, the Windows distribution includes +both the normal and the @strong{MySQL-Max} binaries. The main benefit +of using the normal @code{mysqld.exe} binary is that it's a little +faster and uses less resources. + +Here is a list of the different @strong{MySQL} servers you can use: + +@multitable @columnfractions .25 .75 +@item @code{mysqld} @tab +Compiled with full debugging and automatic memory allocation checking, +symbolic links, BDB and InnoDB tables. +@item @code{mysqld-opt} @tab +Optimized binary with no support for transactional tables. +@item @code{mysqld-nt} @tab +Optimized binary for NT with support for named pipes. You can run this +version on Win98, but in this case no named pipes are created and you must +have TCP/IP installed. +@item @code{mysqld-max} @tab +Optimized binary with support for symbolic links, BDB and InnoDB tables. +@item @code{mysqld-max-nt} @tab +Like @code{mysqld-max}, but compiled with support for named pipes. +@end multitable + +All of the above binaries are optimized for the Pentium Pro processor but +should work on any Intel processor >= i386. + +NOTE: If you want to use InnoDB tables, there are certain startup +options that must be specified in your @file{my.ini} file! @xref{InnoDB start}. + + +@node General Installation Issues, Many versions, Quick Standard Installation, Installing +@section General Installation Issues + +@c @node Methods of Installation, , , +@c @subsection Methods of Installation + +@c FIX: this needs to be written? + +@menu +* Getting MySQL:: +* Which OS:: +* Which version:: +* Installation layouts:: +@end menu + +@node Getting MySQL, Which OS, General Installation Issues, General Installation Issues +@subsection How to Get MySQL + @cindex downloading @cindex MySQL version @cindex version, latest @cindex getting MySQL @cindex mirror sites @cindex URLS for downloading MySQL -@node Getting MySQL, Which OS, Installing, Installing -@section How to Get MySQL Check the @uref{http://www.mysql.com/, @strong{MySQL} home page} for information about the current version and for downloading instructions. @@ -6787,13 +6951,14 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @c END_OF_MIRROR_LISTING +@node Which OS, Which version, Getting MySQL, General Installation Issues +@subsection Operating Systems Supported by MySQL + @cindex operating systems, supported @cindex native thread support @cindex thread support @cindex process support @cindex support, for operating systems -@node Which OS, Which version, Getting MySQL, Installing -@section Operating Systems Supported by MySQL We use GNU Autoconf, so it is possible to port @strong{MySQL} to all modern systems with working Posix threads and a C++ compiler. (To compile only the @@ -6920,13 +7085,14 @@ forth more effort into testing on and optimizing for that particular platform. We are just stating our observations to help you make a decision on which platform to use @strong{MySQL} on in your setup. +@node Which version, Installation layouts, Which OS, General Installation Issues +@subsection Which MySQL Version to Use + @cindex MySQL binary distribution @cindex MySQL source distribution @cindex release numbers @cindex version, choosing @cindex choosing, a MySQL version -@node Which version, Many versions, Which OS, Installing -@section Which MySQL Version to Use The first decision to make is whether you want to use the latest development release or the last stable release: @@ -7100,68 +7266,8 @@ Another test is that we use the newest @strong{MySQL} version in our internal production environment, on at least one machine. We have more than 100 gigabytes of data to work with. -@cindex releases, updating -@cindex updating, releases of MySQL -@node Many versions, Installation layouts, Which version, Installing -@section How and When Updates Are Released - -@strong{MySQL} is evolving quite rapidly here at @strong{MySQL AB} and we -want to share this with other @strong{MySQL} users. We try to make a release -when we have very useful features that others seem to have a need for. - -We also try to help out users who request features that are easy to -implement. We take note of what our licensed users want to have, and -we especially take note of what our extended e-mail supported customers -want and try to help them out. - -No one has to download a new release. The News section will tell you if -the new release has something you really want. @xref{News}. - -We use the following policy when updating @strong{MySQL}: - -@itemize @bullet -@item -For each minor update, the last number in the version string is incremented. -When there are major new features or minor incompatibilities with previous -versions, the second number in the version string is incremented. When the -file format changes, the first number is increased. - -@item -Stable tested releases are meant to appear about 1-2 times a year, but -if small bugs are found, a release with only bug fixes will be released. - -@item -Working releases are meant to appear about every 1-8 weeks. - -@item -Binary distributions for some platforms will be made by us for major releases. -Other people may make binary distributions for other systems but probably -less frequently. - -@item -We usually make patches available as soon as we have located and fixed -small bugs. - -@item -For non-critical but annoying bugs, we will make patches available if they -are sent to us. Otherwise we will combine many of them into a larger -patch. - -@item -If there is, by any chance, a fatal bug in a release we will make a new -release as soon as possible. We would like other companies to do this, -too. -@end itemize - -The current stable release is Version 3.23; We have already moved active -development to Version 4.0. Bugs will still be fixed in the stable version. -We don't believe in a complete freeze, as this also leaves out bug fixes -and things that ``must be done.'' ``Somewhat frozen'' means that we may -add small things that ``almost surely will not affect anything that's -already working.'' - -@node Installation layouts, Installing binary, Many versions, Installing -@section Installation Layouts +@node Installation layouts, , Which version, General Installation Issues +@subsection Installation Layouts @cindex installation layouts @cindex layout of installation @@ -7225,485 +7331,132 @@ The header file and library directories are @file{include/mysql} and You can create your own binary installation from a compiled source distribution by executing the script @file{scripts/make_binary_distribution}. -@cindex installing, binary distribution -@cindex binary distributions, installing -@node Installing binary, Installing source, Installation layouts, Installing -@section Installing a MySQL Binary Distribution +@node Many versions, MySQL binaries, General Installation Issues, Installing +@section How and When Updates Are Released -@menu -* Linux-RPM:: Linux RPM files -* Building clients:: Building client programs -* Binary install system issues:: System-specific issues -@end menu +@cindex releases, updating +@cindex updating, releases of MySQL -You need the following tools to install a @strong{MySQL} binary distribution: +@strong{MySQL} is evolving quite rapidly here at @strong{MySQL AB} and we +want to share this with other @strong{MySQL} users. We try to make a release +when we have very useful features that others seem to have a need for. + +We also try to help out users who request features that are easy to +implement. We take note of what our licensed users want to have, and +we especially take note of what our extended e-mail supported customers +want and try to help them out. + +No one has to download a new release. The News section will tell you if +the new release has something you really want. @xref{News}. + +We use the following policy when updating @strong{MySQL}: @itemize @bullet @item -GNU @code{gunzip} to uncompress the distribution. +For each minor update, the last number in the version string is incremented. +When there are major new features or minor incompatibilities with previous +versions, the second number in the version string is incremented. When the +file format changes, the first number is increased. @item -A reasonable @code{tar} to unpack the distribution. GNU @code{tar} is -known to work. Sun @code{tar} is known to have problems. +Stable tested releases are meant to appear about 1-2 times a year, but +if small bugs are found, a release with only bug fixes will be released. + +@item +Working releases are meant to appear about every 1-8 weeks. + +@item +Binary distributions for some platforms will be made by us for major releases. +Other people may make binary distributions for other systems but probably +less frequently. + +@item +We usually make patches available as soon as we have located and fixed +small bugs. + +@item +For non-critical but annoying bugs, we will make patches available if they +are sent to us. Otherwise we will combine many of them into a larger +patch. + +@item +If there is, by any chance, a fatal bug in a release we will make a new +release as soon as possible. We would like other companies to do this, +too. @end itemize -@cindex RPM, defined -@cindex RedHat Package Manager -An alternative installation method under Linux is to use RPM (RedHat Package -Manager) distributions. @xref{Linux-RPM}. +The current stable release is Version 3.23; We have already moved active +development to Version 4.0. Bugs will still be fixed in the stable version. +We don't believe in a complete freeze, as this also leaves out bug fixes +and things that ``must be done.'' ``Somewhat frozen'' means that we may +add small things that ``almost surely will not affect anything that's +already working.'' -@c texi2html fails to split chapters if I use strong for all of this. -If you run into problems, @strong{PLEASE ALWAYS USE} @code{mysqlbug} when -posting questions to @email{mysql@@lists.mysql.com}. Even if the problem -isn't a bug, @code{mysqlbug} gathers system information that will help others -solve your problem. By not using @code{mysqlbug}, you lessen the likelihood -of getting a solution to your problem! You will find @code{mysqlbug} in the -@file{bin} directory after you unpack the distribution. @xref{Bug reports}. +@node MySQL binaries, Installing source, Many versions, Installing +@section MySQL Binaries Compiled by MySQL AB -@cindex commands, for binary distribution -The basic commands you must execute to install and use a @strong{MySQL} -binary distribution are: +@cindex binary distributions -@example -shell> groupadd mysql -shell> useradd -g mysql mysql -shell> cd /usr/local -shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf - -shell> ln -s mysql-VERSION-OS mysql -shell> cd mysql -shell> scripts/mysql_install_db -shell> chown -R root /usr/local/mysql -shell> chown -R mysql /usr/local/mysql/data -shell> chgrp -R mysql /usr/local/mysql -shell> chown -R root /usr/local/mysql/bin -shell> bin/safe_mysqld --user=mysql & -@end example +As a service, we at @strong{MySQL AB} provide a set of binary distributions +of @strong{MySQL} that are compiled at our site or at sites where customers +kindly have given us access to their machines. -@cindex adding, new users -@cindex new users, adding -@cindex users, adding +These distributions are generated with @code{scripts/make_binary_distribution} +and are configured with the following compilers and options: -You can add new users using the @code{bin/mysql_setpermission} script if -you install the @code{DBI} and @code{Msql-Mysql-modules} Perl modules. +@table @asis +@item SunOS 4.1.4 2 sun4c with @code{gcc} 2.7.2.1 +@code{CC=gcc CXX=gcc CXXFLAGS="-O3 -felide-constructors" ./configure --prefix=/usr/local/mysql --disable-shared --with-extra-charsets=complex --enable-assembler} -A more detailed description follows. +@item SunOS 5.5.1 (and above) sun4u with @code{egcs} 1.0.3a or 2.90.27 or gcc 2.95.2 and newer +@code{CC=gcc CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex --enable-assembler} -To install a binary distribution, follow the steps below, then proceed -to @ref{Post-installation}, for post-installation setup and testing: +@item SunOS 5.6 i86pc with @code{gcc} 2.8.1 +@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex} -@enumerate -@item -Pick the directory under which you want to unpack the distribution, and move -into it. In the example below, we unpack the distribution under -@file{/usr/local} and create a directory @file{/usr/local/mysql} into which -@strong{MySQL} is installed. (The following instructions therefore assume -you have permission to create files in @file{/usr/local}. If that directory -is protected, you will need to perform the installation as @code{root}.) +@item Linux 2.0.33 i386 with @code{pgcc} 2.90.29 (@code{egcs} 1.0.3a) +@code{CFLAGS="-O3 -mpentium -mstack-align-double" CXX=gcc CXXFLAGS="-O3 -mpentium -mstack-align-double -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --with-extra-charsets=complex} -@item -Obtain a distribution file from one of the sites listed in -@ref{Getting MySQL, , Getting @strong{MySQL}}. +@item Linux 2.2.x with x686 with @code{gcc} 2.95.2 +@code{CFLAGS="-O3 -mpentiumpro" CXX=gcc CXXFLAGS="-O3 -mpentiumpro -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --disable-shared --with-extra-charset=complex} -@strong{MySQL} binary distributions are provided as compressed @code{tar} -archives and have names like @file{mysql-VERSION-OS.tar.gz}, where -@code{VERSION} is a number (for example, @code{3.21.15}), and @code{OS} -indicates the type of operating system for which the distribution is intended -(for example, @code{pc-linux-gnu-i586}). +@item SCO 3.2v5.0.4 i386 with @code{gcc} 2.7-95q4 +@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} -@item -If you see a binary distribution marked with the @code{-max} prefix, this -means that the binary has support for transaction-safe tables and other -features. @xref{mysqld-max, , @code{mysqld-max}}. Note that all binaries -are built from the same @strong{MySQL} source distribution. +@item AIX 2 4 with @code{gcc} 2.7.2.2 +@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} -@item -Add a user and group for @code{mysqld} to run as: +@item OSF1 V4.0 564 alpha with @code{gcc} 2.8.1 +@code{CC=gcc CFLAGS=-O CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex} -@example -shell> groupadd mysql -shell> useradd -g mysql mysql -@end example +@item Irix 6.3 IP32 with @code{gcc} 2.8.0 +@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} -These commands add the @code{mysql} group and the @code{mysql} user. The -syntax for @code{useradd} and @code{groupadd} may differ slightly on different -versions of Unix. They may also be called @code{adduser} and @code{addgroup}. -You may wish to call the user and group something else instead of @code{mysql}. +@item BSDI BSD/OS 3.1 i386 with @code{gcc} 2.7.2.1 +@code{CC=gcc CXX=gcc CXXFLAGS=-O ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} -@item -Change into the intended installation directory: - -@example -shell> cd /usr/local -@end example - -@item -Unpack the distribution and create the installation directory: - -@example -shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf - -shell> ln -s mysql-VERSION-OS mysql -@end example - -The first command creates a directory named @file{mysql-VERSION-OS}. The -second command makes a symbolic link to that directory. This lets you refer -more easily to the installation directory as @file{/usr/local/mysql}. - -@item -Change into the installation directory: - -@example -shell> cd mysql -@end example - -You will find several files and subdirectories in the @code{mysql} directory. -The most important for installation purposes are the @file{bin} and -@file{scripts} subdirectories. - -@table @file -@item bin -@tindex PATH environment variable -@tindex environment variable, PATH -This directory contains client programs and the server -You should add the full pathname of this directory to your -@code{PATH} environment variable so that your shell finds the @strong{MySQL} -programs properly. @xref{Environment variables}. - -@item scripts -This directory contains the @code{mysql_install_db} script used to initialize -the @code{mysql} database containing the grant tables that store the server -access permissions. +@item BSDI BSD/OS 2.1 i386 with @code{gcc} 2.7.2 +@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} @end table -@item -If you would like to use @code{mysqlaccess} and have the @strong{MySQL} -distribution in some non-standard place, you must change the location where -@code{mysqlaccess} expects to find the @code{mysql} client. Edit the -@file{bin/mysqlaccess} script at approximately line 18. Search for a line -that looks like this: +Anyone who has more optimal options for any of the configurations listed +above can always mail them to the developer's mailing list at +@email{internals@@lists.mysql.com}. -@example -$MYSQL = '/usr/local/bin/mysql'; # path to mysql executable -@end example +RPM distributions prior to @strong{MySQL} Version 3.22 are user-contributed. +Beginning with Version 3.22, the RPMs are generated by us at +@strong{MySQL AB}. -Change the path to reflect the location where @code{mysql} actually is -stored on your system. If you do not do this, you will get a @code{Broken -pipe} error when you run @code{mysqlaccess}. +If you want to compile a debug version of @strong{MySQL}, you should add +@code{--with-debug} or @code{--with-debug=full} to the above configure lines +and remove any @code{-fomit-frame-pointer} options. -@item -Create the @strong{MySQL} grant tables (necessary only if you haven't -installed @strong{MySQL} before): -@example -shell> scripts/mysql_install_db -@end example - -Note that @strong{MySQL} versions older than Version 3.22.10 started the -@strong{MySQL} server when you run @code{mysql_install_db}. This is no -longer true! - -@item -Change ownership of binaries to @code{root} and ownership of the data -directory to the user that you will run @code{mysqld} as: - -@example -shell> chown -R root /usr/local/mysql -shell> chown -R mysql /usr/local/mysql/data -shell> chgrp -R mysql /usr/local/mysql -@end example - -The first command changes the @code{owner} attribute of the files to the -@code{root} user, the second one changes the @code{owner} attribute of the -data directory to the @code{mysql} user, and the third one changes the -@code{group} attribute to the @code{mysql} group. - -@item -If you want to install support for the Perl @code{DBI}/@code{DBD} interface, -see @ref{Perl support}. - -@item -If you would like @strong{MySQL} to start automatically when you boot your -machine, you can copy @code{support-files/mysql.server} to the location where -your system has its startup files. More information can be found in the -@code{support-files/mysql.server} script itself and in -@ref{Automatic start}. - -@end enumerate - -After everything has been unpacked and installed, you should initialize -and test your distribution. - -You can start the @strong{MySQL} server with the following command: - -@example -shell> bin/safe_mysqld --user=mysql & -@end example - -@xref{safe_mysqld, , @code{safe_mysqld}}. - -@xref{Post-installation}. - -@cindex RPM file -@cindex RedHat Package Manager -@c This node name is special -@node Linux-RPM, Building clients, Installing binary, Installing binary -@subsection Linux RPM Notes - -The recommended way to install @strong{MySQL} on Linux is by using an RPM -file. The @strong{MySQL} RPMs are currently being built on a RedHat Version -6.2 system but should work on other versions of Linux that support @code{rpm} -and use @code{glibc}. - -If you have problems with an RPM file, for example, if you receive the error -``@code{Sorry, the host 'xxxx' could not be looked up}'', see -@ref{Binary notes-Linux}. - -The RPM files you may want to use are: - -@itemize @bullet -@item @code{MySQL-VERSION.i386.rpm} - -The @strong{MySQL} server. You will need this unless you only want to -connect to a @strong{MySQL} server running on another machine. - -@item @code{MySQL-client-VERSION.i386.rpm} - -The standard @strong{MySQL} client programs. You probably always want to -install this package. - -@item @code{MySQL-bench-VERSION.i386.rpm} - -Tests and benchmarks. Requires Perl and msql-mysql-modules RPMs. - -@item @code{MySQL-devel-VERSION.i386.rpm} - -Libraries and include files needed if you want to compile other -@strong{MySQL} clients, such as the Perl modules. - -@item @code{MySQL-VERSION.src.rpm} - -This contains the source code for all of the above packages. It can also -be used to try to build RPMs for other architectures (for example, Alpha -or SPARC). -@end itemize - -To see all files in an RPM package, run: -@example -shell> rpm -qpl MySQL-VERSION.i386.rpm -@end example - -To perform a standard minimal installation, run: - -@example -shell> rpm -i MySQL-VERSION.i386.rpm MySQL-client-VERSION.i386.rpm -@end example - -To install just the client package, run: - -@example -shell> rpm -i MySQL-client-VERSION.i386.rpm -@end example - -The RPM places data in @file{/var/lib/mysql}. The RPM also creates the -appropriate entries in @file{/etc/rc.d/} to start the server automatically -at boot time. (This means that if you have performed a previous -installation, you may want to make a copy of your previously installed -@strong{MySQL} startup file if you made any changes to it, so you don't lose -your changes.) - -After installing the RPM file(s), the @code{mysqld} daemon should be running -and you should now be able to start using @strong{MySQL}. -@xref{Post-installation}. - -If something goes wrong, you can find more information in the binary -installation chapter. @xref{Installing binary}. - -@cindex client programs, building -@cindex linking -@cindex building, client programs -@cindex programs, client -@node Building clients, Binary install system issues, Linux-RPM, Installing binary -@subsection Building Client Programs - -If you compile @strong{MySQL} clients that you've written yourself or that -you obtain from a third party, they must be linked using the -@code{-lmysqlclient -lz} option on the link command. You may also need to -specify a @code{-L} option to tell the linker where to find the library. For -example, if the library is installed in @file{/usr/local/mysql/lib}, use -@code{-L/usr/local/mysql/lib -lmysqlclient -lz} on the link command. - -For clients that use @strong{MySQL} header files, you may need to specify a -@code{-I} option when you compile them (for example, -@code{-I/usr/local/mysql/include}), so the compiler can find the header -files. - -@node Binary install system issues, , Building clients, Installing binary -@subsection System-specific Issues - -@menu -* Binary notes-Linux:: Linux notes for binary distribution -* Binary notes-HP-UX:: HP-UX notes for binary distribution -@end menu - -The following sections indicate some of the issues that have been observed -on particular systems when installing @strong{MySQL} from a binary -distribution or from RPM files. - -@cindex binary distributions, on Linux -@cindex Linux, binary distribution -@node Binary notes-Linux, Binary notes-HP-UX, Binary install system issues, Binary install system issues -@subsubsection Linux Notes for Binary Distributions - -@strong{MySQL} needs at least Linux Version 2.0. - -The binary release is linked with @code{-static}, which means you do not -normally need to worry about which version of the system libraries you -have. You need not install LinuxThreads, either. A program linked with -@code{-static} is slightly bigger than a dynamically linked program but -also slightly faster (3-5%). One problem, however, is that you can't use -user-definable functions (UDFs) with a statically linked program. If -you are going to write or use UDF functions (this is something only for -C or C++ programmers), you must compile @strong{MySQL} yourself, using -dynamic linking. - -If you are using a @code{libc}-based system (instead of a @code{glibc2} -system), you will probably get some problems with hostname resolving and -@code{getpwnam()} with the binary release. (This is because @code{glibc} -unfortunately depends on some external libraries to resolve hostnames -and @code{getpwent()}, even when compiled with @code{-static}). In this -case you probably get the following error message when you run -@code{mysql_install_db}: - -@example -Sorry, the host 'xxxx' could not be looked up -@end example - -or the following error when you try to run @code{mysqld} with the @code{--user} -option: - -@example -getpwnam: No such file or directory -@end example - -You can solve this problem in one of the following ways: - -@itemize @bullet -@item -Get a @strong{MySQL} source distribution (an RPM or the @code{tar.gz} -distribution) and install this instead. -@item -Execute @code{mysql_install_db --force}; This will not execute the -@code{resolveip} test in @code{mysql_install_db}. The downside is that -you can't use host names in the grant tables; you must use IP numbers -instead (except for @code{localhost}). If you are using an old @strong{MySQL} -release that doesn't support @code{--force}, you have to remove the -@code{resolveip} test in @code{mysql_install} with an editor. -@item -Start @code{mysqld} with @code{su} instead of using @code{--user}. -@end itemize - -The Linux-Intel binary and RPM releases of @strong{MySQL} are configured -for the highest possible speed. We are always trying to use the fastest -stable compiler available. - -@strong{MySQL} Perl support requires Version Perl 5.004_03 or newer. - -On some Linux 2.2 versions, you may get the error @code{Resource -temporarily unavailable} when you do a lot of new connections to a -@code{mysqld} server over TCP/IP. - -The problem is that Linux has a delay between when you close a TCP/IP -socket and until this is actually freed by the system. As there is only -room for a finite number of TCP/IP slots, you will get the above error if -you try to do too many new TCP/IP connections during a small time, like -when you run the @strong{MySQL} @file{test-connect} benchmark over -TCP/IP. - -We have mailed about this problem a couple of times to different Linux -mailing lists but have never been able to resolve this properly. - -The only known 'fix' to this problem is to use persistent connections in -your clients or use sockets, if you are running the database server -and clients on the same machine. We hope that the @code{Linux 2.4} -kernel will fix this problem in the future. - -@cindex HP-UX, binary distribution -@cindex binary distributions, on HP-UX -@node Binary notes-HP-UX, , Binary notes-Linux, Binary install system issues -@subsubsection HP-UX Notes for Binary Distributions - -Some of the binary distributions of @strong{MySQL} for HP-UX is -distributed as an HP depot file and as a tar file. To use the depot -file you must be running at least HP-UX 10.x to have access to HP's -software depot tools. - -The HP version of @strong{MySQL} was compiled on an HP 9000/8xx server -under HP-UX 10.20, and uses MIT-pthreads. It is known to work well under -this configuration. @strong{MySQL} Version 3.22.26 and newer can also be -built with HP's native thread package. - -Other configurations that may work: - -@itemize @bullet -@item -HP 9000/7xx running HP-UX 10.20+ -@item -HP 9000/8xx running HP-UX 10.30 -@end itemize - -The following configurations almost definitely won't work: - -@itemize @bullet -@item -HP 9000/7xx or 8xx running HP-UX 10.x where x < 2 -@item -HP 9000/7xx or 8xx running HP-UX 9.x -@end itemize - -To install the distribution, use one of the commands below, where -@code{/path/to/depot} is the full pathname of the depot file: - -@itemize @bullet -@item -To install everything, including the server, client and development tools: - -@example -shell> /usr/sbin/swinstall -s /path/to/depot mysql.full -@end example - -@item -To install only the server: - -@example -shell> /usr/sbin/swinstall -s /path/to/depot mysql.server -@end example - -@item -To install only the client package: - -@example -shell> /usr/sbin/swinstall -s /path/to/depot mysql.client -@end example - -@item -To install only the development tools: - -@example -shell> /usr/sbin/swinstall -s /path/to/depot mysql.developer -@end example -@end itemize - -The depot places binaries and libraries in @file{/opt/mysql} and data in -@file{/var/opt/mysql}. The depot also creates the appropriate entries in -@file{/etc/init.d} and @file{/etc/rc2.d} to start the server automatically -at boot time. Obviously, this entails being @code{root} to install. - -To install the HP-UX tar.gz distribution, you must have a copy of GNU -@code{tar}. +@node Installing source, Perl support, MySQL binaries, Installing +@section Installing a MySQL Source Distribution @cindex installing, source distribution @cindex source distribution, installing @cindex installation overview -@node Installing source, Installing source tree, Installing binary, Installing -@section Installing a MySQL Source Distribution Before you proceed with the source installation, check first to see if our binary is available for your platform and if it will work for you. We @@ -7767,6 +7520,9 @@ of getting a solution to your problem! You will find @code{mysqlbug} in the * Quick install:: Quick installation overview * Applying patches:: Applying patches * configure options:: Typical @code{configure} options +* Installing source tree:: +* Compilation problems:: +* MIT-pthreads:: @end menu @node Quick install, Applying patches, Installing source, Installing source @@ -7948,11 +7704,12 @@ running. @xref{Multiple servers}. @xref{Post-installation}. -@cindex patches, applying -@cindex applying, patches @node Applying patches, configure options, Quick install, Installing source @subsection Applying Patches +@cindex patches, applying +@cindex applying, patches + Sometimes patches appear on the mailing list or are placed in the @uref{http://www.mysql.com/Downloads/Patches, patches area} of the @strong{MySQL} Web site. @@ -7988,14 +7745,15 @@ You may need to bring down any currently running server before you run systems do not allow you to install a new version of a program if it replaces the version that is currently executing. +@node configure options, Installing source tree, Applying patches, Installing source +@subsection Typical @code{configure} Options + +@findex without-server option @cindex @code{configure} script @cindex options, configure @cindex configuration options -@findex without-server option @cindex log files @cindex files, log -@node configure options, , Applying patches, Installing source -@subsection Typical @code{configure} Options The @code{configure} script gives you a great deal of control over how you configure your @strong{MySQL} distribution. Typically you do this @@ -8205,12 +7963,12 @@ applications. @xref{Thread-safe clients}. @item Options that pertain to particular systems can be found in the -system-specific sections later in this chapter. @xref{Source install -system issues}. +system-specific section of this manual. +@xref{Operating System Specific Notes}. @end itemize -@node Installing source tree, Compilation problems, Installing source, Installing -@section Installing from the Development Source Tree +@node Installing source tree, Compilation problems, configure options, Installing source +@subsection Installing from the Development Source Tree @cindex development source tree @cindex BitKeeper tree @@ -8310,13 +8068,14 @@ a description. @end enumerate +@node Compilation problems, MIT-pthreads, Installing source tree, Installing source +@subsection Problems Compiling? + @cindex compiling, problems @cindex problems, compiling @cindex reconfiguring @cindex @code{config.cache} file @cindex files, @code{config.cache} -@node Compilation problems, MIT-pthreads, Installing source tree, Installing -@section Problems Compiling? All @strong{MySQL} programs compile cleanly for us with no warnings on Solaris using @code{gcc}. On other systems, warnings may occur due to @@ -8530,10 +8289,11 @@ If you need to debug @code{mysqld} or a @strong{MySQL} client, run link your clients with the new client library. @xref{Debugging client}. @end itemize +@node MIT-pthreads, , Compilation problems, Installing source +@subsection MIT-pthreads Notes + @cindex MIT-pthreads @cindex thread support, non-native -@node MIT-pthreads, Perl support, Compilation problems, Installing -@section MIT-pthreads Notes This section describes some of the issues involved in using MIT-pthreads. @@ -8622,7 +8382,7 @@ needed, but may be interesting for someone.) @cindex Perl, installing @cindex installing, Perl -@node Perl support, Source install system issues, MIT-pthreads, Installing +@node Perl support, Post-installation, Installing source, Installing @section Perl Installation Comments @menu @@ -8906,2496 +8666,18 @@ shell> make perl Finally, you should install this new Perl. Again, the output of @code{make perl} indicates the command to use. -@node Source install system issues, Windows, Perl support, Installing -@section System-specific Issues -The following sections indicate some of the issues that have been observed to -occur on particular systems when installing @strong{MySQL} from a source -distribution. - -@menu -* Solaris:: Solaris notes -* Solaris 2.7:: Solaris 2.7 / 2.8 notes -* Solaris x86:: Solaris x86 notes -* SunOS:: SunOS 4 notes -* Linux:: Linux notes (all Linux versions) -* Alpha-DEC-UNIX:: Alpha-DEC-UNIX notes -* Alpha-DEC-OSF1:: Alpha-DEC-OSF1 notes -* SGI-Irix:: SGI-Irix notes -* FreeBSD:: FreeBSD notes -* NetBSD:: NetBSD notes -* OpenBSD:: OpenBSD 2.5 notes -* BSDI:: BSD/OS notes -* SCO:: SCO notes -* SCO Unixware:: SCO Unixware 7.0 notes -* IBM-AIX:: IBM-AIX notes -* HP-UX 10.20:: HP-UX 10.20 notes -* HP-UX 11.x:: HP-UX 11.x notes -* Mac OS X:: Mac OS X notes -* BEOS:: BeOS Notes -@end menu - - -@cindex Solaris installation problems -@cindex problems, installing on Solaris -@cindex tar, problems on Solaris -@cindex errors, directory checksum -@cindex checksum errors -@node Solaris, Solaris 2.7, Source install system issues, Source install system issues -@subsection Solaris Notes - -On Solaris, you may run into trouble even before you get the @strong{MySQL} -distribution unpacked! Solaris @code{tar} can't handle long file names, so -you may see an error like this when you unpack @strong{MySQL}: - -@example -x mysql-3.22.12-beta/bench/Results/ATIS-mysql_odbc-NT_4.0-cmp-db2,informix,ms-sql,mysql,oracle,solid,sybase, 0 bytes, 0 tape blocks -tar: directory checksum error -@end example - -In this case, you must use GNU @code{tar} (@code{gtar}) to unpack the -distribution. You can find a precompiled copy for Solaris at -@uref{http://www.mysql.com/Downloads/}. - -Sun native threads work only on Solaris 2.5 and higher. For Version 2.4 and -earlier, @strong{MySQL} will automatically use MIT-pthreads. -@xref{MIT-pthreads}. - -If you get the following error from configure: - -@example -checking for restartable system calls... configure: error can not run test -programs while cross compiling -@end example - -This means that you have something wrong with your compiler installation! -In this case you should upgrade your compiler to a newer version. You may -also be able to solve this problem by inserting the following row into the -@file{config.cache} file: - -@example -ac_cv_sys_restartable_syscalls=$@{ac_cv_sys_restartable_syscalls='no'@} -@end example - -If you are using Solaris on a SPARC, the recommended compiler is -@code{gcc} 2.95.2. You can find this at @uref{http://gcc.gnu.org/}. -Note that @code{egcs} 1.1.1 and @code{gcc} 2.8.1 don't work reliably on -SPARC! - -The recommended @code{configure} line when using @code{gcc} 2.95.2 is: - -@example -CC=gcc CFLAGS="-O3" \ -CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti" \ -./configure --prefix=/usr/local/mysql --with-low-memory --enable-assembler -@end example - -If you have a ultra sparc, you can get 4 % more performance by adding -"-mcpu=v8 -Wa,-xarch=v8plusa" to CFLAGS and CXXFLAGS. - -If you have the Sun Workshop (SunPro) 4.2 (or newer) compiler, you can -run @code{configure} like this: - -@example -CC=cc CFLAGS="-Xa -fast -xO4 -native -xstrconst -mt" \ -CXX=CC CXXFLAGS="-noex -xO4 -mt" \ -./configure --prefix=/usr/local/mysql --enable-assembler -@end example - -You may also have to edit the @code{configure} script to change this line: - -@example -#if !defined(__STDC__) || __STDC__ != 1 -@end example - -to this: - -@example -#if !defined(__STDC__) -@end example - -If you turn on @code{__STDC__} with the @code{-Xc} option, the Sun compiler -can't compile with the Solaris @file{pthread.h} header file. This is a Sun -bug (broken compiler or broken include file). - -If @code{mysqld} issues the error message shown below when you run it, you have -tried to compile @strong{MySQL} with the Sun compiler without enabling the -multi-thread option (@code{-mt}): - -@example -libc internal error: _rmutex_unlock: rmutex not held -@end example - -Add @code{-mt} to @code{CFLAGS} and @code{CXXFLAGS} and try again. - -If you get the following error when compiling @strong{MySQL} with @code{gcc}, -it means that your @code{gcc} is not configured for your version of Solaris: - -@example -shell> gcc -O3 -g -O2 -DDBUG_OFF -o thr_alarm ... -./thr_alarm.c: In function `signal_hand': -./thr_alarm.c:556: too many arguments to function `sigwait' -@end example - -The proper thing to do in this case is to get the newest version of -@code{gcc} and compile it with your current @code{gcc} compiler! At -least for Solaris 2.5, almost all binary versions of @code{gcc} have -old, unusable include files that will break all programs that use -threads (and possibly other programs)! - -Solaris doesn't provide static versions of all system libraries -(@code{libpthreads} and @code{libdl}), so you can't compile @strong{MySQL} -with @code{--static}. If you try to do so, you will get the error: - -@example -ld: fatal: library -ldl: not found - -or - -undefined reference to `dlopen' -@end example - -If too many processes try to connect very rapidly to @code{mysqld}, you will -see this error in the @strong{MySQL} log: - -@example -Error in accept: Protocol error -@end example - -You might try starting the server with the @code{--set-variable back_log=50} -option as a workaround for this. @xref{Command-line options}. - -If you are linking your own @strong{MySQL} client, you might get the -following error when you try to execute it: - -@example -ld.so.1: ./my: fatal: libmysqlclient.so.#: open failed: No such file or directory -@end example - -The problem can be avoided by one of the following methods: - -@itemize @bullet -@item -Link the client with the following flag (instead of @code{-Lpath}): -@code{-Wl,r/full-path-to-libmysqlclient.so}. - -@item -Copy @file{libmysqclient.so} to @file{/usr/lib}. - -@tindex LD_RUN_PATH environment variable -@tindex Environment variable, LD_RUN_PATH -@item -Add the pathname of the directory where @file{libmysqlclient.so} is located -to the @code{LD_RUN_PATH} environment variable before running your client. -@end itemize - -When using the @code{--with-libwrap} configure option, you must also -include the libraries that @file{libwrap.a} needs: - -@example ---with-libwrap="/opt/NUtcpwrapper-7.6/lib/libwrap.a -lnsl -lsocket -@end example - -If you have problems with configure trying to link with @code{-lz} and -you don't have @code{zlib} installed, you have two options: - -@itemize @bullet -@item -If you want to be able to use the compressed communication protocol, -you need to get and install zlib from ftp.gnu.org. - -@item -Configure with @code{--with-named-z-libs=no}. -@end itemize - -If you are using gcc and have problems with loading @code{UDF} functions -into @strong{MySQL}, try adding @code{-lgcc} to the link line for the -@code{UDF} function. - -If you would like @strong{MySQL} to start automatically, you can copy -@file{support-files/mysql.server} to @file{/etc/init.d} and create a -symbolic link to it named @file{/etc/rc3.d/S99mysql.server}. - -@node Solaris 2.7, Solaris x86, Solaris, Source install system issues -@subsection Solaris 2.7/2.8 Notes - -You can normally use a Solaris 2.6 binary on Solaris 2.7 and 2.8. Most -of the Solaris 2.6 issues also apply for Solaris 2.7 and 2.8. - -Note that @strong{MySQL} Version 3.23.4 and above should be able to autodetect -new versions of Solaris and enable workarounds for the following problems! - -Solaris 2.7 / 2.8 has some bugs in the include files. You may see the -following error when you use @code{gcc}: - -@example -/usr/include/widec.h:42: warning: `getwc' redefined -/usr/include/wchar.h:326: warning: this is the location of the previous -definition -@end example - -If this occurs, you can do the following to fix the problem: - -Copy @code{/usr/include/widec.h} to -@code{.../lib/gcc-lib/os/gcc-version/include} and change line 41 from: - -@example -#if !defined(lint) && !defined(__lint) - -to - -#if !defined(lint) && !defined(__lint) && !defined(getwc) -@end example - -Alternatively, you can edit @file{/usr/include/widec.h} directly. Either -way, after you make the fix, you should remove @file{config.cache} and run -@code{configure} again! - -If you get errors like this when you run @code{make}, it's because -@code{configure} didn't detect the @file{curses.h} file (probably -because of the error in @file{/usr/include/widec.h}): - -@example -In file included from mysql.cc:50: -/usr/include/term.h:1060: syntax error before `,' -/usr/include/term.h:1081: syntax error before `;' -@end example - -The solution to this is to do one of the following: - -@itemize @bullet -@item -Configure with @code{CFLAGS=-DHAVE_CURSES_H CXXFLAGS=-DHAVE_CURSES_H ./configure}. - -@item -Edit @file{/usr/include/widec.h} as indicted above and rerun configure. - -@item -Remove the @code{#define HAVE_TERM} line from @file{config.h} file and -run @code{make} again. -@end itemize - -If you get a problem that your linker can't find @code{-lz} when linking -your client program, the problem is probably that your @file{libz.so} file is -installed in @file{/usr/local/lib}. You can fix this by one of the -following methods: - -@itemize @bullet -@item -Add @file{/usr/local/lib} to @code{LD_LIBRARY_PATH}. - -@item -Add a link to @file{libz.so} from @file{/lib}. - -@item -If you are using Solaris 8, you can install the optional zlib from your -Solaris 8 CD distribution. - -@item -Configure @strong{MySQL} with the @code{--with-named-z-libs=no} option. -@end itemize - -@node Solaris x86, SunOS, Solaris 2.7, Source install system issues -@subsection Solaris x86 Notes - -On Solaris 2.8 on x86, @strong{mysqld} will core dump if you run -'strip' in. - -If you are using @code{gcc} or @code{egcs} on Solaris x86 and you -experience problems with core dumps under load, you should use the -following @code{configure} command: - -@example -CC=gcc CFLAGS="-O3 -fomit-frame-pointer -DHAVE_CURSES_H" \ -CXX=gcc \ -CXXFLAGS="-O3 -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti -DHAVE_CURSES_H" \ -./configure --prefix=/usr/local/mysql -@end example - -This will avoid problems with the @code{libstdc++} library and with C++ -exceptions. - -If this doesn't help, you should compile a debug version and run -it with a trace file or under @code{gdb}. @xref{Using gdb on mysqld}. - -@node SunOS, Linux, Solaris x86, Source install system issues -@subsection SunOS 4 Notes - -On SunOS 4, MIT-pthreads is needed to compile @strong{MySQL}, which in turn -means you will need GNU @code{make}. - -Some SunOS 4 systems have problems with dynamic libraries and @code{libtool}. -You can use the following @code{configure} line to avoid this problem: - -@example -shell> ./configure --disable-shared --with-mysqld-ldflags=-all-static -@end example - -When compiling @code{readline}, you may get warnings about duplicate defines. -These may be ignored. - -When compiling @code{mysqld}, there will be some @code{implicit declaration -of function} warnings. These may be ignored. - -@node Linux, Alpha-DEC-UNIX, SunOS, Source install system issues -@subsection Linux Notes (All Linux Versions) - -The notes below regarding @strong{glibc} apply only to the situation -when you build @strong{MySQL} -yourself. If you are running Linux on an x86 machine, in most cases it is -much better for you to just use our binary. We link our binaries against -the best patched version of @strong{glibc} we can come up with and with the -best compiler options, in an attempt to make it suitable for a high-load -server. So if you read the text below, and are in doubt about -what you should do, try our binary first to see if it meets your needs, and -worry about your own build only after you have discovered that our binary is -not good enough. In that case, we would appreciate a note about it, so we -can build a better binary next time. For a typical user, even for setups with -a lot of concurrent connections and/or tables exceeding 2GB limit, our -binary in most cases is the best choice. - -@strong{MySQL} uses LinuxThreads on Linux. If you are using an old -Linux version that doesn't have @code{glibc2}, you must install -LinuxThreads before trying to compile @strong{MySQL}. You can get -LinuxThreads at @uref{http://www.mysql.com/Downloads/Linux}. - -@strong{NOTE:} We have seen some strange problems with Linux 2.2.14 and -@strong{MySQL} on SMP systems; If you have a SMP system, we recommend -you to upgrade to Linux 2.4 ASAP! Your system will be faster and more -stable by doing this! - -Note that @code{glibc} versions before and including Version 2.1.1 have -a fatal bug in @code{pthread_mutex_timedwait} handling, which is used -when you do @code{INSERT DELAYED}. We recommend you to not use -@code{INSERT DELAYED} before upgrading glibc. - -If you plan to have 1000+ concurrent connections, you will need to make -some changes to LinuxThreads, recompile it, and relink @strong{MySQL} against -the new @file{libpthread.a}. Increase @code{PTHREAD_THREADS_MAX} in -@file{sysdeps/unix/sysv/linux/bits/local_lim.h} to 4096 and decrease -@code{STACK_SIZE} in @file{linuxthreads/internals.h} to 256 KB. The paths are -relative to the root of @code{glibc} Note that @strong{MySQL} will not be -stable with around 600-1000 connections if @code{STACK_SIZE} is the default -of 2 MB. - -If you have a problem with that @strong{MySQL} can't open enough files, -or connections, it may be that you haven't configured Linux to handle -enough files. - -In Linux 2.2 and forwards, you can check the number of allocated -file handlers by doing: - -@example -cat /proc/sys/fs/file-max -cat /proc/sys/fs/dquot-max -cat /proc/sys/fs/super-max -@end example - -If you have more than 16M of memory, you should add something like the -following in your boot script (@file{/etc/rc/boot.local} on SuSE): - -@example -echo 65536 > /proc/sys/fs/file-max -echo 8192 > /proc/sys/fs/dquot-max -echo 1024 > /proc/sys/fs/super-max -@end example - -You can also run the above from the command line as root, but in this case -your old limits will be used next time your computer reboots. - -You should also add /etc/my.cnf: - -@example -[safe_mysqld] -open-files-limit=8192 -@end example - -The above should allow @strong{MySQL} to create up to 8192 connections + files. - -The @code{STACK_SIZE} constant in LinuxThreads controls the spacing of thread -stacks in the address space. It needs to be large enough so that there will -be plenty of room for the stack of each individual thread, but small enough -to keep the stack of some thread from running into the global @code{mysqld} -data. Unfortunately, the Linux implementation of @code{mmap()}, as we have -experimentally discovered, will successfully unmap an already mapped region -if you ask it to map out an address already in use, zeroing out the data -on the entire page, instead of returning an error. So, the safety of -@code{mysqld} or any other threaded application depends on the "gentleman" -behavior of the code that creates threads. The user must take measures to -make sure the number of running threads at any time is sufficiently low for -thread stacks to stay away from the global heap. With @code{mysqld}, you -should enforce this "gentleman" behavior by setting a reasonable value for -the @code{max_connections} variable. - -If you build @strong{MySQL} yourself and do not what to mess with patching -LinuxThreads, you should set @code{max_connections} to a value no higher -than 500. It should be even less if you have a large key buffer, large -heap tables, or some other things that make @strong{mysqld} allocate a lot -of memory or if you are running a 2.2 kernel with a 2GB patch. If you are -using our binary or RPM version 3.23.25 or later, you can safely set -@code{max_connections} at 1500, assuming no large key buffer or heap tables -with lots of data. The more you reduce @code{STACK_SIZE} in LinuxThreads -the more threads you can safely create. We recommend the values between -128K and 256K. - -If you use a lot of concurrent connections, you may suffer from a "feature" -in the 2.2 kernel that penalizes a process for forking or cloning a child -in an attempt to prevent a fork bomb attack. This will cause @strong{MySQL} -not to scale well as you increase the number of concurrent clients. On -single CPU systems, we have seen this manifested in a very slow thread -creation, which means it may take a long time to connect to @strong{MySQL} -(as long as 1 minute), and it may take just as long to shut it down. On -multiple CPU systems, we have observed a gradual drop in query speed as -the number of clients increases. In the process of trying to find a -solution, we have received a kernel patch from one of our users, who -claimed it made a lot of difference for his site. The patch is available here -(@uref{http://www.mysql.com/Downloads/Patches/linux-fork.patch}). We have -now done rather extensive testing of this patch on both development and -production systems. It has significantly -improved @code{MySQL} performance without causing any problems and we now -recommend it to our users who are still running high-load servers on -2.2 kernels. This issue has been fixed in the 2.4 kernel, so if you are not -satisfied with -the current performance of your system, rather than patching your 2.2 kernel, -it might be easier to just upgrade to 2.4, which will also give you a nice -SMP boost in addition to fixing this fairness bug. - -We have tested @strong{MySQL} on the 2.4 kernel on a 2 CPU machine and -found @strong{MySQL} scales MUCH better - there was virtually no slowdown -on query throughput all the way up -to 1000 clients, and @strong{MySQL} scaling factor ( computed as the ratio of -maximum throughput to the throughput with one client) was 180%. -We have observed similar results on a 4-CPU system - virtually no -slowdown as the number of -clients was increased up to 1000, and 300% scaling factor. So for a high-load -SMP server we would definitely recommend the 2.4 kernel at this point. We -have discovered that it is essential to run @code{mysqld} process with the -highest possible priority on the 2.4 kernel to achieve maximum performance. -This can be done by adding -@code{renice -20 $$} command to @code{safe_mysqld}. In our testing on a -4-CPU machine, increasing the priority gave 60% increase in throughput with -400 clients. - -We are currently also trying to collect -more info on how well @code{MySQL} performs on 2.4 kernel on 4-way and 8-way -systems. If you have access such a system and have done some benchmarks, -please send a mail to @email{docs@@mysql.com} with the results - we will -include them in the manual. - -There is another issue that greatly hurts @strong{MySQL} performance, -especially on SMP systems. The implementation of mutex in -LinuxThreads in @strong{glibc-2.1} is very bad for programs with many -threads that only -hold the mutex for a short time. On an SMP system, ironic as it is, if -you link @strong{MySQL} against unmodified @strong{LinuxThreads}, -removing processors from the machine improves @strong{MySQL} performance -in many cases. We have made a patch available for @strong{glibc 2.1.3}, -@uref{http://www.mysql.com/Downloads/Linux/linuxthreads-2.1-patch,linuxthreads-2.1-patch} -to correct this behavior. - -With @strong{glibc-2.2.2} -@strong{MySQL} version 3.23.36 will use the adaptive mutex, which is much -better than even the patched one in @strong{glibc-2.1.3}. Be warned, however, -that under some conditions, the current mutex code in @strong{glibc-2.2.2} -overspins, which hurts @strong{MySQL} performance. The chance of this -condition can be reduced by renicing @code{mysqld} process to the highest -priority. We have also been able to correct the overspin behavior with -a patch, available @uref{http://www.mysql.com/Downloads/Linux/linuxthreads-2.2.2.patch,here}. It combines the correction of overspin, maximum number of -threads, and stack spacing all in one. You will need to apply it in the -@code{linuxthreads} directory with -@code{patch -p0 cp support-files/mysql.server /etc/init.d/mysql.server -shell> /usr/sbin/update-rc.d mysql.server defaults 99 -@end example - -@code{mysql.server} can be found in the @file{share/mysql} directory -under the @strong{MySQL} installation directory or in the -@file{support-files} directory of the @strong{MySQL} source tree. - -If @code{mysqld} always core dumps when it starts up, the problem may be that -you have an old @file{/lib/libc.a}. Try renaming it, then remove -@file{sql/mysqld} and do a new @code{make install} and try again. This -problem has been reported on some Slackware installations. RedHat Version 5.0 -also has a similar problem with some new @code{glibc} versions. -@xref{Linux-RedHat50}. - -If you get the following error when linking @code{mysqld}, -it means that your @file{libg++.a} is not installed correctly: - -@example -/usr/lib/libc.a(putc.o): In function `_IO_putc': -putc.o(.text+0x0): multiple definition of `_IO_putc' -@end example - -You can avoid using @file{libg++.a} by running @code{configure} like this: - -@example -shell> CXX=gcc ./configure -@end example - -@node Linux-RedHat50, Linux-RedHat51, Linux-x86, Linux -@subsubsection RedHat Version 5.0 Notes - -If you have any problems with @strong{MySQL} on RedHat, you should start by -upgrading @code{glibc} to the newest possible version! - -If you install all the official RedHat patches (including -@code{glibc-2.0.7-19} and @code{glibc-devel-2.0.7-19}), both the -binary and source distributions of @strong{MySQL} should work without -any trouble! - -The updates are needed because there is a bug in @code{glibc} 2.0.5 in how -@code{pthread_key_create} variables are freed. With @code{glibc} 2.0.5, you -must use a statically linked @strong{MySQL} binary distribution. If you -want to compile from source, you must install the corrected version of -LinuxThreads from @uref{http://www.mysql.com/Downloads/Linux} or upgrade your -@code{glibc}. - -If you have an incorrect version of @code{glibc} or LinuxThreads, the symptom -is that @code{mysqld} crashes after each connection. For example, -@code{mysqladmin version} will crash @code{mysqld} when it finishes! - -Another symptom of incorrect libraries is that @code{mysqld} crashes at -once when it starts. On some Linux systems, this can be fixed by configuring -like this: - -@example -shell> ./configure --with-mysqld-ldflags=-all-static -@end example - -On Redhat Version 5.0, the easy way out is to install the @code{glibc} -2.0.7-19 RPM and run @code{configure} @strong{without} the -@code{--with-mysqld-ldflags=-all-static} option. - -For the source distribution of @code{glibc} 2.0.7, a patch that is easy to -apply and is tested with @strong{MySQL} may be found at: - -@example -@uref{http://www.mysql.com/Downloads/Linux/glibc-2.0.7-total-patch.tar.gz} -@end example - -If you experience crashes like these when you build @strong{MySQL}, you can -always download the newest binary version of @strong{MySQL}. This is -statically-linked to avoid library conflicts and should work on all Linux -systems! - -@strong{MySQL} comes with an internal debugger that can generate -trace files with a lot of information that can be used to find and solve a -wide range of different problems. -@xref{Debugging server}. - -@node Linux-RedHat51, Linux-SPARC, Linux-RedHat50, Linux -@subsubsection RedHat Version 5.1 notes - -The @code{glibc} of RedHat Version 5.1 (@code{glibc} 2.0.7-13) has a memory -leak, so to get a stable @strong{MySQL} version, you must upgrade @code{glibc}, -to 2.0.7-19, downgrade @code{glibc} or use a binary version of @code{mysqld}. -If you don't do this, you will encounter memory problems (out of memory, etc.). -The most common error in this case is: - -@example -Can't create a new thread (errno 11). If you are not out of available -memory, you can consult the manual for any possible OS dependent bug -@end example - -After you have upgraded to @code{glibc} 2.0.7-19, you can configure -@strong{MySQL} with dynamic linking (the default), but you @strong{cannot} -run @code{configure} with the @code{--with-mysqld-ldflags=-all-static} option -until you have installed @code{glibc} 2.0.7-19 from source! - -You can check which version of @code{glibc} you have with @code{rpm -q glibc}. - -Another reason for the above error is if you try to use more threads -than your Linux kernel is configured for. In this case you should raise -the limits in @file{include/linux/tasks.h} and recompile your kernel! - -@node Linux-SPARC, Linux-Alpha, Linux-RedHat51, Linux -@subsubsection Linux-SPARC Notes - -In some implementations, @code{readdir_r()} is broken. The symptom is that -@code{SHOW DATABASES} always returns an empty set. This can be fixed by -removing @code{HAVE_READDIR_R} from @file{config.h} after configuring and -before compiling. - -Some problems will require patching your Linux installation. The patch can -be found at -@uref{http://www.mysql.com/Downloads/patches/Linux-sparc-2.0.30.diff}. -This patch is against the Linux distribution @file{sparclinux-2.0.30.tar.gz} -that is available at @code{vger.rutgers.edu} (a version of Linux that was -never merged with the official 2.0.30). You must also install LinuxThreads -Version 0.6 or newer. - -@node Linux-Alpha, MKLinux, Linux-SPARC, Linux -@subsubsection Linux-Alpha Notes - -@strong{MySQL} Version 3.23.12 is the first @strong{MySQL} version that is -tested on Linux-Alpha. If you plan to use @strong{MySQL} on Linux-Alpha, -you should ensure that you have this version or newer. - -We have tested @strong{MySQL} on Alpha with our benchmarks and test suite, -and it appears to work nicely. The main thing we haven't yet had time to -test is how things works with many concurrent users. - -When we compiled the standard @strong{MySQL} binary we are using SuSE 6.4, -kernel 2.2.13-SMP, Compaq C compiler (V6.2-504) and Compaq C++ compiler -(V6.3-005) on a Comaq DS20 machine with an Alpha EV6 processor. - -You can find the above compilers at -@uref{http://www.support.compaq.com/alpha-tools}). By using these compilers, -instead of gcc, we get about 9-14 % better performance with @strong{MySQL}. - -Note that the configure line optimized the binary for the current CPU; This -means you can only use our binary if you have an Alpha EV6 processor. We also -compile statically to avoid library problems. - -@example -CC=ccc CFLAGS="-fast" CXX=cxx CXXFLAGS="-fast -noexceptions -nortti" ./configure --prefix=/usr/local/mysql --disable-shared --with-extra-charsets=complex --enable-thread-safe-client --with-mysqld-ldflags=-non_shared --with-client-ldflags=-non_shared -@end example - -If you want to use egcs the following configure line worked for us: - -@example -CFLAGS="-O3 -fomit-frame-pointer" CXX=gcc CXXFLAGS="-O3 -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --disable-shared -@end example - -Some known problems when running @strong{MySQL} on Linux-Alpha: - -@itemize @bullet -@item -Debugging threaded applications like @strong{MySQL} will not work with -@code{gdb 4.18}. You should download and use gdb 5.0 instead! - -@item -If you try linking @code{mysqld} statically when using @code{gcc}, the -resulting image will core dump at start. In other words, @strong{DON'T} -use @code{--with-mysqld-ldflags=-all-static} with @code{gcc}. -@end itemize - -@node MKLinux, Qube2, Linux-Alpha, Linux -@subsubsection MkLinux Notes - -@strong{MySQL} should work on MkLinux with the newest @code{glibc} package -(tested with @code{glibc} 2.0.7). - -@node Qube2, Linux-Ia64, MKLinux, Linux -@subsubsection Qube2 Linux Notes - -To get @strong{MySQL} to work on Qube2, (Linux Mips), you need the -newest @code{glibc} libraries (@code{glibc-2.0.7-29C2} is known to -work). You must also use the @code{egcs} C++ compiler -(@code{egcs-1.0.2-9}, @code{gcc 2.95.2} or newer). - -@node Linux-Ia64, , Qube2, Linux -@subsubsection Linux IA64 Notes - -To get @strong{MySQL} to compile on Linux Ia64, we had to do the following -(we assume that this will be easier when next gcc version for ia64 is -released). - -Using @code{gcc-2.9-final}: - -@example -CFLAGS="-O2" CXX=gcc CXXFLAGS="-O2 -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --disable-shared --with-extra-charsets=complex -@end example - -After @code{make} you will get an error that @code{sql/opt_range.cc} -will not compile (internal compiler error). To fix this, go to the sql -directory and type @code{make} again. Copy the compile line, but change --O2 to -O0. The file should now compile. - -Now you can do: - -@example -cd .. -make -make_install -@end example - -and @strong{mysqld} should be ready to run. - -@node Alpha-DEC-UNIX, Alpha-DEC-OSF1, Linux, Source install system issues -@subsection Alpha-DEC-UNIX Notes (Tru64) - -If you are using egcs 1.1.2 on Digital Unix, you should upgrade to gcc -2.95.2, as egcs on DEC has some serious bugs! - -When compiling threaded programs under Digital Unix, the documentation -recommends using the @code{-pthread} option for @code{cc} and @code{cxx} and -the libraries @code{-lmach -lexc} (in addition to @code{-lpthread}). You -should run @code{configure} something like this: - -@example -CC="cc -pthread" CXX="cxx -pthread -O" \ -./configure --with-named-thread-libs="-lpthread -lmach -lexc -lc" -@end example - -When compiling @code{mysqld}, you may see a couple of warnings like this: - -@example -mysqld.cc: In function void handle_connections()': -mysqld.cc:626: passing long unsigned int *' as argument 3 of -accept(int,sockadddr *, int *)' -@end example - -You can safely ignore these warnings. They occur because @code{configure} -can detect only errors, not warnings. - -If you start the server directly from the command line, you may have problems -with it dying when you log out. (When you log out, your outstanding processes -receive a @code{SIGHUP} signal.) If so, try starting the server like this: - -@example -shell> nohup mysqld [options] & -@end example - -@code{nohup} causes the command following it to ignore any @code{SIGHUP} -signal sent from the terminal. Alternatively, start the server by running -@code{safe_mysqld}, which invokes @code{mysqld} using @code{nohup} for you. -@xref{safe_mysqld, , @code{safe_mysqld}}. - -If you get a problem when compiling mysys/get_opt.c, just remove the -line #define _NO_PROTO from the start of that file! - -If you are using Compac's CC compiler, the following configure line should -work: - -@example -CC="cc -pthread" -CFLAGS="-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host" -CXX="cxx -pthread" -CXXFLAGS="-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host" -export CC CFLAGS CXX CXXFLAGS -./configure \ ---prefix=/usr/local/mysql \ ---with-low-memory \ ---enable-large-files \ ---enable-shared=yes \ ---with-named-thread-libs="-lpthread -lmach -lexc -lc" -gnumake -@end example - -If you get a problem with libtool, when compiling with shared libraries -as above, when linking @code{mysql}, you should be able to get around -this by issuing: - -@example -cd mysql -/bin/sh ../libtool --mode=link cxx -pthread -O3 -DDBUG_OFF \ --O4 -ansi_alias -ansi_args -fast -inline speed \ --speculate all \ -arch host -DUNDEF_HAVE_GETHOSTBYNAME_R \ --o mysql mysql.o readline.o sql_string.o completion_hash.o \ -../readline/libreadline.a -lcurses \ -../libmysql/.libs/libmysqlclient.so -lm -cd .. -gnumake -gnumake install -scripts/mysql_install_db -@end example - -@node Alpha-DEC-OSF1, SGI-Irix, Alpha-DEC-UNIX, Source install system issues -@subsection Alpha-DEC-OSF1 Notes - -If you have problems compiling and have DEC @code{CC} and @code{gcc} -installed, try running @code{configure} like this: - -@example -CC=cc CFLAGS=-O CXX=gcc CXXFLAGS=-O3 \ -./configure --prefix=/usr/local/mysql -@end example - -If you get problems with the @file{c_asm.h} file, you can create and use -a 'dummy' @file{c_asm.h} file with: - -@example -touch include/c_asm.h -CC=gcc CFLAGS=-I./include \ -CXX=gcc CXXFLAGS=-O3 \ -./configure --prefix=/usr/local/mysql -@end example - -Note that the following problems with the @code{ld} program can be fixed -by downloading the latest DEC (Compaq) patch kit from: -@uref{http://ftp.support.compaq.com/public/unix/}. - -On OSF1 V4.0D and compiler "DEC C V5.6-071 on Digital Unix V4.0 (Rev. 878)" -the compiler had some strange behavior (undefined @code{asm} symbols). -@code{/bin/ld} also appears to be broken (problems with @code{_exit -undefined} errors occuring while linking @code{mysqld}). On this system, we -have managed to compile @strong{MySQL} with the following @code{configure} -line, after replacing @code{/bin/ld} with the version from OSF 4.0C: - -@example -CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql -@end example - -With the Digital compiler "C++ V6.1-029", the following should work: - -@example -CC=cc -pthread -CFLAGS=-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host -CXX=cxx -pthread -CXXFLAGS=-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host -noexceptions -nortti -export CC CFLAGS CXX CXXFLAGS -./configure --prefix=/usr/mysql/mysql --with-mysqld-ldflags=-all-static --disable-shared --with-named-thread-libs="-lmach -lexc -lc" -@end example - -In some versions of OSF1, the @code{alloca()} function is broken. Fix -this by removing the line in @file{config.h} that defines @code{'HAVE_ALLOCA'}. - -The @code{alloca()} function also may have an incorrect prototype in -@code{/usr/include/alloca.h}. This warning resulting from this can be ignored. - -@code{configure} will use the following thread libraries automatically: -@code{--with-named-thread-libs="-lpthread -lmach -lexc -lc"}. - -When using @code{gcc}, you can also try running @code{configure} like this: - -@example -shell> CFLAGS=-D_PTHREAD_USE_D4 CXX=gcc CXXFLAGS=-O3 ./configure .... -@end example - -If you have problems with signals (@strong{MySQL} dies unexpectedly -under high load), you may have found an OS bug with threads and -signals. In this case you can tell @strong{MySQL} not to use signals by -configuring with: - -@example -shell> CFLAGS=-DDONT_USE_THR_ALARM \ - CXXFLAGS=-DDONT_USE_THR_ALARM \ - ./configure ... -@end example - -This doesn't affect the performance of @strong{MySQL}, but has the side -effect that you can't kill clients that are ``sleeping'' on a connection with -@code{mysqladmin kill} or @code{mysqladmin shutdown}. Instead, the client -will die when it issues its next command. - -With @code{gcc} 2.95.2, you will probably run into the following compile error: - -@example -sql_acl.cc:1456: Internal compiler error in `scan_region', at except.c:2566 -Please submit a full bug report. -@end example - -To fix this you should change to the @code{sql} directory and do a ``cut -and paste'' of the last @code{gcc} line, but change @code{-O3} to -@code{-O0} (or add @code{-O0} immediately after @code{gcc} if you don't -have any @code{-O} option on your compile line.) After this is done you -can just change back to the top-level directly and run @code{make} -again. - -@node SGI-Irix, FreeBSD, Alpha-DEC-OSF1, Source install system issues -@subsection SGI-Irix Notes - -If you are using Irix Version 6.5.3 or newer @code{mysqld} will only be able to -create threads if you run it as a user with @code{CAP_SCHED_MGT} -privileges (like @code{root}) or give the @code{mysqld} server this privilege -with the following shell command: - -@example -shell> chcap "CAP_SCHED_MGT+epi" /opt/mysql/libexec/mysqld -@end example - -You may have to undefine some things in @file{config.h} after running -@code{configure} and before compiling. - -In some Irix implementations, the @code{alloca()} function is broken. If the -@code{mysqld} server dies on some @code{SELECT} statements, remove the lines -from @file{config.h} that define @code{HAVE_ALLOC} and @code{HAVE_ALLOCA_H}. -If @code{mysqladmin create} doesn't work, remove the line from @file{config.h} -that defines @code{HAVE_READDIR_R}. You may have to remove the -@code{HAVE_TERM_H} line as well. - -SGI recommends that you install all of the patches on this page as a set: -http://support.sgi.com/surfzone/patches/patchset/6.2_indigo.rps.html - -At the very minimum, you should install the latest kernel rollup, the -latest @code{rld} rollup, and the latest @code{libc} rollup. - -You definitely need all the POSIX patches on this page, for pthreads support: - -@uref{http://support.sgi.com/surfzone/patches/patchset/6.2_posix.rps.html} - -If you get the something like the following error when compiling -@file{mysql.cc}: - -@example -"/usr/include/curses.h", line 82: error(1084): invalid combination of type -@end example - -Type the following in the top-level directory of your @strong{MySQL} source -tree: - -@example -shell> extra/replace bool curses_bool < /usr/include/curses.h > include/curses.h -shell> make -@end example - -There have also been reports of scheduling problems. If only one thread is -running, things go slow. Avoid this by starting another client. This may -lead to a 2-to-10-fold increase in execution speed thereafter for the other -thread. This is a poorly understood problem with Irix threads; you may have -to improvise to find solutions until this can be fixed. - -If you are compiling with @code{gcc}, you can use the following -@code{configure} command: - -@example -CC=gcc CXX=gcc CXXFLAGS=-O3 \ -./configure --prefix=/usr/local/mysql --with-thread-safe-client --with-named-thread-libs=-lpthread -@end example - -On Irix 6.5.11 with native Irix C and C++ compilers ver. 7.3.1.2, the -following is reported to work - -@example -CC=cc CXX=CC CFLAGS='-O3 -n32 -TARG:platform=IP22 -I/usr/local/include \ --L/usr/local/lib' CXXFLAGS='-O3 -n32 -TARG:platform=IP22 \ --I/usr/local/include -L/usr/local/lib' ./configure --prefix=/usr/local/mysql \ ---with-berkeley-db --with-innodb \ ---with-libwrap=/usr/local --with-named-curses-libs=/usr/local/lib/libncurses.a -@end example - -@node FreeBSD, NetBSD, SGI-Irix, Source install system issues -@subsection FreeBSD Notes - -FreeBSD 3.x is recommended for running @strong{MySQL} since the thread package -is much more integrated. - -The easiest and therefor the preferred way to install is to use the -mysql-server and mysql-client ports available on @uref{http://www.freebsd.org}. - -Using these gives you: -@itemize @bullet -@item -A working @strong{MySQL} with all optimizations known to work on your version -of FreeBSD enabled. - -@item -Automatic configuration and build. - -@item -Startup scripts installed in /usr/local/etc/rc.d. - -@item -Ability to see which files that are installed with pkg_info -L. And to -remove them all with pkg_delete if you no longer want @strong{MySQL} on that -machine. -@end itemize - -It is recommended you use MIT-pthreads on FreeBSD 2.x and native threads on -Versions 3 and up. It is possible to run with native threads on some late -2.2.x versions but you may encounter problems shutting down @code{mysqld}. - -The @strong{MYSQL} Makefiles require GNU make (@code{gmake}) to work. -If you want to compile @strong{MYSQL} you need to install GNU make -first. - -Be sure to have your name resolver setup correct. Otherwise you may -experience resolver delays or failures when connecting to @code{mysqld}. - -Make sure that the @code{localhost} entry in the @file{/etc/hosts} file is -correct (otherwise you will have problems connecting to the database). The -@file{/etc/hosts} file should start with a line: - -@example -127.0.0.1 localhost localhost.your.domain -@end example - -If you notice that @code{configure} will use MIT-pthreads, you should read -the MIT-pthreads notes. @xref{MIT-pthreads}. - -If you get an error from @code{make install} that it can't find -@file{/usr/include/pthreads}, @code{configure} didn't detect that you need -MIT-pthreads. This is fixed by executing these commands: - -@example -shell> rm config.cache -shell> ./configure --with-mit-threads -@end example - -FreeBSD is also known to have a very low default file handle limit. -@xref{Not enough file handles}. Uncomment the ulimit -n section in -safe_mysqld or raise the limits for the @code{mysqld} user in /etc/login.conf -(and rebuild it with cap_mkdb /etc/login.conf). Also be sure you set the -appropriate class for this user in the password file if you are not -using the default (use: chpass mysqld-user-name). @xref{safe_mysqld, , -@code{safe_mysqld}}. - -If you get problems with the current date in @strong{MySQL}, setting the -@code{TZ} variable will probably help. @xref{Environment variables}. - -To get a secure and stable system you should only use FreeBSD kernels -that are marked @code{-STABLE}. - -@node NetBSD, OpenBSD, FreeBSD, Source install system issues -@subsection NetBSD notes - -To compile on NetBSD you need GNU @code{make}. Otherwise the compile will -crash when @code{make} tries to run @code{lint} on C++ files. - -@node OpenBSD, BSDI, NetBSD, Source install system issues -@subsection OpenBSD Notes - -@menu -* OpenBSD 2.5:: OpenBSD 2.5 Notes -* OpenBSD 2.8:: OpenBSD 2.8 Notes -@end menu - -@node OpenBSD 2.5, OpenBSD 2.8, OpenBSD, OpenBSD -@subsubsection OpenBSD 2.5 Notes - -On OpenBSD Version 2.5, you can compile @strong{MySQL} with native threads -with the following options: - -@example -CFLAGS=-pthread CXXFLAGS=-pthread ./configure --with-mit-threads=no -@end example - -@node OpenBSD 2.8, , OpenBSD 2.5, OpenBSD -@subsubsection OpenBSD 2.8 Notes - -Our users have reported that OpenBSD 2.8 has a threading bug which causes -problems with @strong{MySQL}. The OpenBSD Developers have fixed the problem, -but as of January 25th, 2001, it's only available in the ``-current'' branch. -The symptoms of this threading bug are: slow response, high load, high CPU -usage, and crashes. - -@node BSDI, SCO, OpenBSD, Source install system issues -@subsection BSD/OS Notes - -@menu -* BSDI2:: BSD/OS 2.x notes -* BSDI3:: BSD/OS 3.x notes -* BSDI4:: BSD/OS 4.x notes -@end menu - -@node BSDI2, BSDI3, BSDI, BSDI -@subsubsection BSD/OS Version 2.x Notes - -If you get the following error when compiling @strong{MySQL}, your -@code{ulimit} value for virtual memory is too low: - -@example -item_func.h: In method `Item_func_ge::Item_func_ge(const Item_func_ge &)': -item_func.h:28: virtual memory exhausted -make[2]: *** [item_func.o] Error 1 -@end example - -Try using @code{ulimit -v 80000} and run @code{make} again. If this -doesn't work and you are using @code{bash}, try switching to @code{csh} -or @code{sh}; some BSDI users have reported problems with @code{bash} -and @code{ulimit}. - -If you are using @code{gcc}, you may also use have to use the -@code{--with-low-memory} flag for @code{configure} to be able to compile -@file{sql_yacc.cc}. - -If you get problems with the current date in @strong{MySQL}, setting the -@code{TZ} variable will probably help. @xref{Environment variables}. - -@node BSDI3, BSDI4, BSDI2, BSDI -@subsubsection BSD/OS Version 3.x Notes - -Upgrade to BSD/OS Version 3.1. If that is not possible, install -BSDIpatch M300-038. - -Use the following command when configuring @strong{MySQL}: - -@example -shell> env CXX=shlicc++ CC=shlicc2 \ - ./configure \ - --prefix=/usr/local/mysql \ - --localstatedir=/var/mysql \ - --without-perl \ - --with-unix-socket-path=/var/mysql/mysql.sock -@end example - -The following is also known to work: - -@example -shell> env CC=gcc CXX=gcc CXXFLAGS=-O3 \ - ./configure \ - --prefix=/usr/local/mysql \ - --with-unix-socket-path=/var/mysql/mysql.sock -@end example - -You can change the directory locations if you wish, or just use the -defaults by not specifying any locations. - -If you have problems with performance under heavy load, try using the -@code{--skip-thread-priority} option to @code{mysqld}! This will run -all threads with the same priority; on BSDI Version 3.1, this gives better -performance (at least until BSDI fixes their thread scheduler). - -If you get the error @code{virtual memory exhausted} while compiling, -you should try using @code{ulimit -v 80000} and run @code{make} again. -If this doesn't work and you are using @code{bash}, try switching to -@code{csh} or @code{sh}; some BSDI users have reported problems with -@code{bash} and @code{ulimit}. - -@node BSDI4, , BSDI3, BSDI -@subsubsection BSD/OS Version 4.x Notes - -BSDI Version 4.x has some thread-related bugs. If you want to use -@strong{MySQL} on this, you should install all thread-related patches. At -least M400-023 should be installed. - -On some BSDI Version 4.x systems, you may get problems with shared libraries. -The symptom is that you can't execute any client programs, for example, -@code{mysqladmin}. In this case you need to reconfigure not to use -shared libraries with the @code{--disable-shared} option to configure. - -Some customers have had problems on BSDI 4.0.1 that the @code{mysqld} -binary after a while can't open tables. This is because some -library/system related bug causes @code{mysqld} to change current -directory without asking for this! - -The fix is to either upgrade to 3.23.34 or after running @code{configure} -remove the line @code{#define HAVE_REALPATH} from @code{config.h} -before running make. - -Note that the above means that you can't symbolic link a database directories -to another database directory or symbolic link a table to another database -on BSDI! (Making a symbolic link to another disk is ok). - -@node SCO, SCO Unixware, BSDI, Source install system issues -@subsection SCO Notes - -The current port is tested only on a ``sco3.2v5.0.4'' and -``sco3.2v5.0.5'' system. There has also been a lot of progress on a -port to ``sco 3.2v4.2''. - -For the moment the recommended compiler on OpenServer is gcc 2.95.2. With this -you should be able to compile @strong{MySQL} with just: - -@example -CC=gcc CXX=gcc ./configure ... (options) -@end example - -@enumerate -@item -For OpenServer 5.0.X you need to use GDS in Skunkware 95 (95q4c). This -is necessary because GNU @code{gcc} 2.7.2 in Skunkware 97 does not have -GNU @code{as}. You can also use @code{egcs} 1.1.2 or newer -@uref{http://www.egcs.com/}. If you are using @code{egcs} 1.1.2 you have -to execute the following command: - -@example -shell> cp -p /usr/include/pthread/stdtypes.h /usr/local/lib/gcc-lib/i386-pc-sco3.2v5.0.5/egcs-2.91.66/include/pthread/ -@end example - -@item -You need the port of GCC 2.5.x for this product and the Development -system. They are required on this version of SCO Unix. You cannot -just use the GCC Dev system. - -@item -You should get the FSU Pthreads package and install it first. This can be -found at -@uref{http://www.cs.wustl.edu/~schmidt/ACE_wrappers/FSU-threads.tar.gz}. -You can also get a precompiled package from -@uref{http://www.mysql.com/Downloads/SCO/FSU-threads-3.5c.tar.gz}. - -@item -FSU Pthreads can be compiled with SCO Unix 4.2 with tcpip. Or -OpenServer 3.0 or Open Desktop 3.0 (OS 3.0 ODT 3.0), with the SCO -Development System installed using a good port of GCC 2.5.x ODT or OS -3.0 you will need a good port of GCC 2.5.x There are a lot of problems -without a good port. The port for this product requires the SCO Unix -Development system. Without it, you are missing the libraries and the -linker that is needed. - -@item -To build FSU Pthreads on your system, do the following: - -@enumerate a -@item -Run @code{./configure} in the @file{threads/src} directory and select -the SCO OpenServer option. This command copies @file{Makefile.SCO5} to -@file{Makefile}. - -@item -Run @code{make}. - -@item -To install in the default @file{/usr/include} directory, login as root, -then @code{cd} to the @file{thread/src} directory, and run @code{make -install}. -@end enumerate - -@item -Remember to use GNU @code{make} when making @strong{MySQL}. - -@item -If you don't start @code{safe_mysqld} as root, you probably will get only the -default 110 open files per process. @code{mysqld} will write a note about this -in the log file. - -@item -With SCO 3.2V5.0.5, you should use FSU Pthreads version 3.5c or newer. -You should also use gcc 2.95.2 or newer! - -The following @code{configure} command should work: - -@example -shell> ./configure --prefix=/usr/local/mysql --disable-shared -@end example - -@item -With SCO 3.2V4.2, you should use FSU Pthreads version 3.5c or newer. -The following @code{configure} command should work: - -@example -shell> CFLAGS="-D_XOPEN_XPG4" CXX=gcc CXXFLAGS="-D_XOPEN_XPG4" \ - ./configure \ - --prefix=/usr/local/mysql \ - --with-named-thread-libs="-lgthreads -lsocket -lgen -lgthreads" \ - --with-named-curses-libs="-lcurses" -@end example - -You may get some problems with some include files. In this case, you can -find new SCO-specific include files at -@uref{http://www.mysql.com/Downloads/SCO/SCO-3.2v4.2-includes.tar.gz}. -You should unpack this file in the @file{include} directory of your -@strong{MySQL} source tree. -@end enumerate - -SCO development notes: - -@itemize @bullet -@item -@strong{MySQL} should automatically detect FSU Pthreads and link @code{mysqld} -with @code{-lgthreads -lsocket -lgthreads}. - -@item -The SCO development libraries are re-entrant in FSU Pthreads. SCO claims -that its libraries' functions are re-entrant, so they must be reentrant with -FSU Pthreads. FSU Pthreads on OpenServer tries to use the SCO scheme to -make re-entrant libraries. - -@item -FSU Pthreads (at least the version at @uref{http://www.mysql.com/}) comes -linked with GNU @code{malloc}. If you encounter problems with memory usage, -make sure that @file{gmalloc.o} is included in @file{libgthreads.a} and -@file{libgthreads.so}. - -@item -In FSU Pthreads, the following system calls are pthreads-aware: @code{read()}, -@code{write()}, @code{getmsg()}, @code{connect()}, @code{accept()}, -@code{select()}, and @code{wait()}. -@end itemize - -If you want to install DBI on SCO, you have to edit the @file{Makefile} in -DBI-xxx and each subdirectory. - -Note that the following assumes gcc 2.95.2 or newer: - -@example -OLD: NEW: -CC = cc CC = gcc -CCCDLFLAGS = -KPIC -W1,-Bexport CCCDLFLAGS = -fpic -CCDLFLAGS = -wl,-Bexport CCDLFLAGS = - -LD = ld LD = gcc -G -fpic -LDDLFLAGS = -G -L/usr/local/lib LDDLFLAGS = -L/usr/local/lib -LDFLAGS = -belf -L/usr/local/lib LDFLAGS = -L/usr/local/lib - -LD = ld LD = gcc -G -fpic -OPTIMISE = -Od OPTIMISE = -O1 - -OLD: -CCCFLAGS = -belf -dy -w0 -U M_XENIX -DPERL_SCO5 -I/usr/local/include - -NEW: -CCFLAGS = -U M_XENIX -DPERL_SCO5 -I/usr/local/include -@end example - -This is because the Perl dynaloader will not load the @code{DBI} modules -if they were compiled with @code{icc} or @code{cc}. - -Perl works best when compiled with @code{cc}. - -@node SCO Unixware, IBM-AIX, SCO, Source install system issues -@subsection SCO Unixware Version 7.0 Notes - -You must use a version of @strong{MySQL} at least as recent as Version 3.22.13 -because that version fixes some portability problems under Unixware. - -We have been able to compile @strong{MySQL} with the following @code{configure} -command on Unixware Version 7.0.1: - -@example -CC=cc CXX=CC ./configure --prefix=/usr/local/mysql -@end example - -If you want to use @code{gcc}, you must use @code{gcc} 2.95.2 or newer. - -@node IBM-AIX, HP-UX 10.20, SCO Unixware, Source install system issues -@subsection IBM-AIX notes -@cindex problems, installing on IBM-AIX - -Automatic detection of @code{xlC} is missing from Autoconf, so a -@code{configure} command something like this is needed when compiling -@strong{MySQL} (This example uses the IBM compiler): - -@example -export CC="xlc_r -ma -O3 -qstrict -qoptimize=3 -qmaxmem=8192 " -export CXX="xlC_r -ma -O3 -qstrict -qoptimize=3 -qmaxmem=8192" -export CFLAGS="-I /usr/local/include" -export LDLFAGS="-L /usr/local/lib" -export CPPFLAGS=$CFLAGS -export CXXFLAGS=$CFLAGS - -./configure --prefix=/usr/local \ - --localstatedir=/var/mysql \ - --sysconfdir=/etc/mysql \ - --sbindir='/usr/local/bin' \ - --libexecdir='/usr/local/bin' \ - --enable-thread-safe-client \ - --enable-large-files -@end example - -Above are the options used to compile the @strong{MySQL} distribution that -can be found at @uref{http://www-frec.bull.com/}. - -If you change the @code{-O3} to @code{-O2} in the above configure line, -you must also remove the @code{-qstrict} option (this is a limitation in -the IBM C compiler). - -If you are using @code{gcc} or @code{egcs} to compile @strong{MySQL}, you -@strong{MUST} use the @code{-fno-exceptions} flag, as the exception -handling in @code{gcc}/@code{egcs} is not thread safe! (This is tested with -@code{egcs} 1.1.). There are also some known problems with IBM's assembler, -which may cause it to generate bad code when used with gcc. - -We recommend the following @code{configure} line with @code{egcs} and -@code{gcc 2.95} on AIX: - -@example -CC="gcc -pipe -mcpu=power -Wa,-many" \ -CXX="gcc -pipe -mcpu=power -Wa,-many" \ -CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti" \ -./configure --prefix=/usr/local/mysql --with-low-memory -@end example - -The @code{-Wa,-many} is necessary for the compile to be successful. IBM is -aware of this problem but is in to hurry to fix it because of the workaround -available. We don't know if the @code{-fno-exceptions} is required with -@code{gcc 2.95}, but as @strong{MySQL} doesn't use exceptions and the above -option generates faster code, we recommend that you should always use this -option with @code{egcs / gcc}. - -If you get a problem with assembler code try changing the -mcpu=xxx to -match your cpu. Typically power2, power, or powerpc may need to be used, -alternatively you might need to use 604 or 604e. I'm not positive but I -would think using "power" would likely be safe most of the time, even on -a power2 machine. - -If you don't know what your cpu is then do a "uname -m", this will give -you back a string that looks like "000514676700", with a format of -xxyyyyyymmss where xx and ss are always 0's, yyyyyy is a unique system -id and mm is the id of the CPU Planar. A chart of these values can be -found at -@uref{http://www.rs6000.ibm.com/doc_link/en_US/a_doc_lib/cmds/aixcmds5/uname.htm}. -This will give you a machine type and a machine model you can use to -determine what type of cpu you have. - -If you have problems with signals (@strong{MySQL} dies unexpectedly -under high load) you may have found an OS bug with threads and -signals. In this case you can tell @strong{MySQL} not to use signals by -configuring with: - -@example -shell> CFLAGS=-DDONT_USE_THR_ALARM CXX=gcc \ - CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti -DDONT_USE_THR_ALARM" \ - ./configure --prefix=/usr/local/mysql --with-debug --with-low-memory -@end example - -This doesn't affect the performance of @strong{MySQL}, but has the side -effect that you can't kill clients that are ``sleeping'' on a connection with -@code{mysqladmin kill} or @code{mysqladmin shutdown}. Instead, the client -will die when it issues its next command. - -On some versions of AIX, linking with @code{libbind.a} makes -@code{getservbyname} core dump. This is an AIX bug and should be reported -to IBM. - -For AIX 4.2.1 and gcc you have to do the following changes. - -After configuring, edit @file{config.h} and @file{include/my_config.h} -and change the line that says - -@example -#define HAVE_SNPRINTF 1 -@end example - -to - -@example -#undef HAVE_SNPRINTF -@end example - -And finally, in @file{mysqld.cc} you need to add a prototype for initgoups. - -@example -#ifdef _AIX41 -extern "C" int initgroups(const char *,int); -#endif -@end example - -@node HP-UX 10.20, HP-UX 11.x, IBM-AIX, Source install system issues -@subsection HP-UX Version 10.20 Notes - -There are a couple of small problems when compiling @strong{MySQL} on -HP-UX. We recommend that you use @code{gcc} instead of the HP-UX native -compiler, because @code{gcc} produces better code! - -We recommend using gcc 2.95 on HP-UX. Don't use high optimization -flags (like -O6) as this may not be safe on HP-UX. - -Note that MIT-pthreads can't be compiled with the HP-UX compiler -because it can't compile @code{.S} (assembler) files. - -The following configure line should work: - -@example -CFLAGS="-DHPUX -I/opt/dce/include" CXXFLAGS="-DHPUX -I/opt/dce/include -felide-constructors -fno-exceptions -fno-rtti" CXX=gcc ./configure --with-pthread --with-named-thread-libs='-ldce' --prefix=/usr/local/mysql --disable-shared -@end example - -If you are compiling @code{gcc} 2.95 yourself, you should NOT link it with -the DCE libraries (@code{libdce.a} or @code{libcma.a}) if you want to compile -@strong{MySQL} with MIT-pthreads. If you mix the DCE and MIT-pthreads -packages you will get a @code{mysqld} to which you cannot connect. Remove -the DCE libraries while you compile @code{gcc} 2.95! - -@node HP-UX 11.x, Mac OS X, HP-UX 10.20, Source install system issues -@subsection HP-UX Version 11.x Notes - -For HP-UX Version 11.x we recommend @strong{MySQL} Version 3.23.15 or later. - -Because of some critical bugs in the standard HP-UX libraries, you should -install the following patches before trying to run @strong{MySQL} on HP-UX 11.0: - -@example -PHKL_22840 Streams cumulative -PHNE_22397 ARPA cumulative -@end example - -This will solve a problem that one gets @code{EWOULDBLOCK} from @code{recv()} -and @code{EBADF} from @code{accept()} in threaded applications. - -If you are using @code{gcc} 2.95.1 on an unpatched HP-UX 11.x system, -you will get the error: - -@example -In file included from /usr/include/unistd.h:11, - from ../include/global.h:125, - from mysql_priv.h:15, - from item.cc:19: -/usr/include/sys/unistd.h:184: declaration of C function ... -/usr/include/sys/pthread.h:440: previous declaration ... -In file included from item.h:306, - from mysql_priv.h:158, - from item.cc:19: -@end example - -The problem is that HP-UX doesn't define @code{pthreads_atfork()} consistently. -It has conflicting prototypes in -@file{/usr/include/sys/unistd.h}:184 and -@file{/usr/include/sys/pthread.h}:440 (details below). - -One solution is to copy @file{/usr/include/sys/unistd.h} into -@file{mysql/include} and edit @file{unistd.h} and change it to match -the definition in @file{pthread.h}. Here's the diff: - -@example -183,184c183,184 -< extern int pthread_atfork(void (*prepare)(), void (*parent)(), -< void (*child)()); ---- -> extern int pthread_atfork(void (*prepare)(void), void (*parent)(void), -> void (*child)(void)); -@end example - -After this, the following configure line should work: - -@example -CFLAGS="-fomit-frame-pointer -O3 -fpic" CXX=gcc CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti -O3" ./configure --prefix=/usr/local/mysql --disable-shared -@end example - -Here is some information that a HP-UX Version 11.x user sent us about compiling -@strong{MySQL} with HP-UX:x compiler: - -@example - Environment: - proper compilers. - setenv CC cc - setenv CXX aCC - flags - setenv CFLAGS -D_REENTRANT - setenv CXXFLAGS -D_REENTRANT - setenv CPPFLAGS -D_REENTRANT - % aCC -V - aCC: HP ANSI C++ B3910B X.03.14.06 - % cc -V /tmp/empty.c - cpp.ansi: HP92453-01 A.11.02.00 HP C Preprocessor (ANSI) - ccom: HP92453-01 A.11.01.00 HP C Compiler - cc: "/tmp/empty.c", line 1: warning 501: Empty source file. - - configuration: - ./configure --with-pthread \ - --prefix=/source-control/mysql \ - --with-named-thread-libs=-lpthread \ - --with-low-memory - - added '#define _CTYPE_INCLUDED' to include/m_ctype.h. This - symbol is the one defined in HP's /usr/include/ctype.h: - - /* Don't include std ctype.h when this is included */ - #define _CTYPE_H - #define __CTYPE_INCLUDED - #define _CTYPE_INCLUDED - #define _CTYPE_USING /* Don't put names in global namespace. */ -@end example - -@itemize @bullet -@item -I had to use the compile-time flag @code{-D_REENTRANT} to get the compiler -to recognize the prototype for @code{localtime_r}. Alternatively I could have -supplied the prototype for @code{localtime_r}. But I wanted to catch other -bugs without needing to run into them. I wasn't sure where I needed it, so I -added it to all flags. -@item -The optimization flags used by @strong{MySQL} (-O3) are not recognized by HP's -compilers. I did not change the flags. -@end itemize - -If you get the following error from @code{configure} - -@example -checking for cc option to accept ANSI C... no -configure: error: MySQL requires a ANSI C compiler (and a C++ compiler). Try gcc. See the Installation chapter in the Reference Manual. -@end example - -Check that you don't have the path to the K&R compiler before the path -to the HP-UX C and C++ compiler. - -@node Mac OS X, BEOS, HP-UX 11.x, Source install system issues -@subsection Mac OS X Notes - -@menu -* Mac OS X Public Data:: -* Mac OS X Server:: -@end menu - -@node Mac OS X Public Data, Mac OS X Server, Mac OS X, Mac OS X -@subsubsection Mac OS X Public beta - -@strong{MySQL} should work without any problems on Mac OS X Public Beta -(Darwin). You don't need the pthread patches for this OS! - -@node Mac OS X Server, , Mac OS X Public Data, Mac OS X -@subsubsection Mac OS X Server - -Before trying to configure @strong{MySQL} on Mac OS X server you must -first install the pthread package from -@uref{http://www.prnet.de/RegEx/mysql.html}. - -Our binary for Mac OS X is compiled on Rhapsody 5.5 with the following -configure line: - -@example -CC=gcc CFLAGS="-O2 -fomit-frame-pointer" CXX=gcc CXXFLAGS="-O2 -fomit-frame-pointer" ./configure --prefix=/usr/local/mysql "--with-comment=Official MySQL binary" --with-extra-charsets=complex --disable-shared -@end example - -You might want to also add aliases to your shell's resource file to -access @code{mysql} and @code{mysqladmin} from the command line: - -@example -alias mysql '/usr/local/mysql/bin/mysql' -alias mysqladmin '/usr/local/mysql/bin/mysqladmin' -@end example - -@node BEOS, , Mac OS X, Source install system issues -@subsection BeOS Notes - -We are really interested in getting @strong{MySQL} to work on BeOS, but -unfortunately we don't have any person who knows BeOS or has time to do -a port. - -We are interested in finding someone to do a port, and we will help them -with any technical questions they may have while doing the port. - -We have previously talked with some BeOS developers that have said that -@strong{MySQL} is 80% ported to BeOS, but we haven't heard from them -in a while. - -@node Windows, OS/2, Source install system issues, Installing -@section Windows Notes - -This section describes installation and use of @strong{MySQL} on Windows. -This information is also provided in the @file{README} file that comes -with the @strong{MySQL} Windows distribution. - -@menu -* Windows installation:: Installing @strong{MySQL} on Windows -* Win95 start:: Starting @strong{MySQL} on Win95 / Win98 -* NT start:: Starting @strong{MySQL} on NT / Win2000 -* Windows running:: Running @strong{MySQL} on Windows -* Windows and SSH:: Connecting to a remote @strong{MySQL} from Windows with SSH -* Windows symbolic links:: Splitting data across different disks under Win32 -* Windows compiling:: Compiling MySQL clients on Windows. -* Windows vs Unix:: @strong{MySQL}-Windows compared to Unix @strong{MySQL} -@end menu - -@node Windows installation, Win95 start, Windows, Windows -@subsection Installing MySQL on Windows - -The following instructions apply to precompiled binary distributions. -If you download a source distribution, you will have to compile and install -it yourself. - -If you don't have a copy of the @strong{MySQL} distribution, you should -first download one from @uref{http://www.mysql.com/downloads/mysql-3.23.html}. - -If you plan to connect to @strong{MySQL} from some other program, you will -probably also need the @strong{MyODBC} driver. You can find this at the -@strong{MyODBC} download page -(@uref{http://www.mysql.com/downloads/api-myodbc.html}). - -To install either distribution, unzip it in some empty directory and run the -@code{Setup.exe} program. - -By default, @strong{MySQL}-Windows is configured to be installed in -@file{C:\mysql}. If you want to install @strong{MySQL} elsewhere, -install it in @file{C:\mysql} first, then move the installation to -where you want it. If you do move @strong{MySQL}, you must indicate -where everything is located by supplying a @code{--basedir} option when -you start the server. For example, if you have moved the @strong{MySQL} -distribution to @file{D:\programs\mysql}, you must start @code{mysqld} -like this: - -@example -C:\> D:\programs\mysql\bin\mysqld --basedir D:\programs\mysql -@end example - -Use @code{mysqld --help} to display all the options that @code{mysqld} -understands! - -With all newer @strong{MySQL} versions, you can also create a -@file{C:\my.cnf} file that holds any default options for the -@strong{MySQL} server. Copy the file @file{\mysql\my-xxxxx.cnf} to -@file{C:\my.cnf} and edit it to suit your setup. Note that you should -specify all paths with @samp{/} instead of @samp{\}. If you use -@samp{\}, you need to specify it twice, because @samp{\} is the escape -character in @strong{MySQL}. @xref{Option files}. - -Starting with @strong{MySQL} 3.23.38, the Windows distribution includes -both the normal and the @strong{MySQL-Max} binaries. The main benefit -of using the normal @code{mysqld.exe} binary is that it's a little -faster and uses less resources. - -Here is a list of the different @strong{MySQL} servers you can use: - -@multitable @columnfractions .25 .75 -@item @code{mysqld} @tab -Compiled with full debugging and automatic memory allocation checking, -symbolic links, BDB and InnoDB tables. -@item @code{mysqld-opt} @tab -Optimized binary with no support for transactional tables. -@item @code{mysqld-nt} @tab -Optimized binary for NT with support for named pipes. You can run this -version on Win98, but in this case no named pipes are created and you must -have TCP/IP installed. -@item @code{mysqld-max} @tab -Optimized binary with support for symbolic links, BDB and InnoDB tables. -@item @code{mysqld-max-nt} @tab -Like @code{mysqld-max}, but compiled with support for named pipes. -@end multitable - -All of the above binaries are optimized for the Pentium Pro processor but -should work on any Intel processor >= i386. - -NOTE: If you want to use InnoDB tables, there are certain startup -options that must be specified in your @file{my.ini} file! @xref{InnoDB start}. - -@node Win95 start, NT start, Windows installation, Windows -@subsection Starting MySQL on Windows 95 or Windows 98 - -@strong{MySQL} uses TCP/IP to connect a client to a server. (This will -allow any machine on your network to connect to your @strong{MySQL} -server.) Because of this, you must install TCP/IP on your machine before -starting @strong{MySQL}. You can find TCP/IP on your Windows CD-ROM. - -Note that if you are using an old Win95 release (for example OSR2), it's -likely that you have an old Winsock package! @strong{MySQL} requires -Winsock 2! You can get the newest Winsock from -@uref{http://www.microsoft.com/}. Win98 has the new Winsock 2 library, so -the above doesn't apply for Win98. - -To start the @code{mysqld} server, you should start an MS-DOS window and type: - -@example -C:\> C:\mysql\bin\mysqld -@end example - -This will start @code{mysqld} in the background without a window. - -You can kill the @strong{MySQL} server by executing: - -@example -C:\> C:\mysql\bin\mysqladmin -u root shutdown -@end example - -Note that Win95 and Win98 don't support creation of named pipes. -On Win95 and Win98, you can only use named pipes to connect to a -remote @strong{MySQL} server running on a Windows NT server host. -(The @strong{MySQL} server must also support named pipes, of -course. For example, using @code{mysqld-opt} under NT will not allow -named pipe connections. You should use either @code{mysqld-nt} or -@code{mysqld-max-nt}.) - -If @code{mysqld} doesn't start, please check the -@file{\mysql\data\mysql.err} file to see if the server wrote any message -there to indicate the cause of the problem. You can also try to start -the server with @code{mysqld --standalone}; In this case, you may get -some useful information on the screen that may help solve the problem. - -The last option is to start @code{mysqld} with @code{--standalone ---debug}. In this case @code{mysqld} will write a log file -@file{C:\mysqld.trace} that should contain the reason why @code{mysqld} -doesn't start. @xref{Making trace files}. - -@node NT start, Windows running, Win95 start, Windows -@subsection Starting MySQL on Windows NT or Windows 2000 - -The Win95/Win98 section also applies to @strong{MySQL} on NT/Win2000, with -the following differences: - -To get @strong{MySQL} to work with TCP/IP on NT, you must install -service pack 3 (or newer)! - -Note that everything in the following that applies for NT also applies -for Win2000! - -For NT/Win2000, the server name is @code{mysqld-nt}. Normally you -should install @strong{MySQL} as a service on NT/Win2000: - -@example -C:\> C:\mysql\bin\mysqld-nt --install -@end example - -or - -@example -C:\> C:\mysql\bin\mysqld-max-nt --install -@end example - -(Under Windows NT, you can actually install any of the server binaries -as a service, but only those having names that end with @code{-nt.exe} -provide support for named pipes.) - -You can start and stop the @strong{MySQL} service with these commands: - -@example -C:\> NET START mysql -C:\> NET STOP mysql -@end example - -Note that in this case you can't use any other options for @code{mysqld-nt}! - -You can also run @code{mysqld-nt} as a stand-alone program on NT if you need -to start @code{mysqld-nt} with any options! If you start @code{mysqld-nt} -without options on NT, @code{mysqld-nt} tries to start itself as a service -with the default service options. If you have stopped @code{mysqld-nt}, you -have to start it with @code{NET START mysql}. - -The service is installed with the name @code{MySQL}. Once installed, it must -be started using the Services Control Manager (SCM) Utility found in the -Control Panel, or by using the @code{NET START MySQL} command. If any options -are desired, they must be specified as ``Startup parameters'' in the SCM utility -before you start the @strong{MySQL} service. Once running, @code{mysqld-nt} -can be stopped using @code{mysqladmin}, or from the SCM utility or by using -the command @code{NET STOP MySQL}. If you use SCM to stop @code{mysqld-nt}, -there is a strange message from SCM about @code{mysqld shutdown normally}. -When run as a service, @code{mysqld-nt} has no access to a console and so no -messages can be seen. - -On NT you can get the following service error messages: - -@multitable @columnfractions .3 .7 -@item Permission Denied @tab Means that it cannot find @code{mysqld-nt.exe}. -@item Cannot Register @tab Means that the path is incorrect. -@item Failed to install service. @tab Means that the service is already installed or that the Service Control Manager is in bad state. -@end multitable - -If you have problems installing @code{mysqld-nt} as a service, try starting -it with the full path: - -@example -C:\> C:\mysql\bin\mysqld-nt --install -@end example - -If this doesn't work, you can get @code{mysqld-nt} to start properly by fixing -the path in the registry! - -If you don't want to start @code{mysqld-nt} as a service, you can start it as -follows: - -@example -C:\> C:\mysql\bin\mysqld-nt --standalone -@end example - -or - -@example -C:\> C:\mysql\bin\mysqld --standalone --debug -@end example - -The last version gives you a debug trace in @file{C:\mysqld.trace}. -@xref{Making trace files}. - -@node Windows running, Windows and SSH, NT start, Windows -@subsection Running MySQL on Windows - -@cindex TCP/IP -@cindex named pipes - -@strong{MySQL} supports TCP/IP on all Windows platforms and named pipes on NT. -The default is to use named pipes for local connections on NT and TCP/IP for -all other cases if the client has TCP/IP installed. The host name specifies -which protocol is used: - -@multitable @columnfractions .3 .7 -@strong{Host name} @tab @strong{Protocol} -@item NULL (none) @tab On NT, try named pipes first; if that doesn't work, use TCP/IP. On Win95/Win98, TCP/IP is used. -@item . @tab Named pipes -@item localhost @tab TCP/IP to current host -@item hostname @tab TCP/IP -@end multitable - -You can force a @strong{MySQL} client to use named pipes by specifying the -@code{--pipe} option or by specifying @code{.} as the host name. Use the -@code{--socket} option to specify the name of the pipe. - -You can test whether or not @strong{MySQL} is working by executing the -following commands: - -@example -C:\> C:\mysql\bin\mysqlshow -C:\> C:\mysql\bin\mysqlshow -u root mysql -C:\> C:\mysql\bin\mysqladmin version status proc -C:\> C:\mysql\bin\mysql test -@end example - -If @code{mysqld} is slow to answer to connections on Win95/Win98, there is -probably a problem with your DNS. In this case, start @code{mysqld} with -@code{--skip-name-resolve} and use only @code{localhost} and IP numbers in -the @strong{MySQL} grant tables. You can also avoid DNS when connecting to a -@code{mysqld-nt} @strong{MySQL} server running on NT by using the -@code{--pipe} argument to specify use of named pipes. This works for most -@strong{MySQL} clients. - -There are two versions of the @strong{MySQL} command-line tool: -@multitable @columnfractions .25 .75 -@item @code{mysql} @tab Compiled on native Windows, which offers very limited text editing capabilities. -@item @code{mysqlc} @tab Compiled with the Cygnus GNU compiler and libraries, which offers @code{readline} editing. -@end multitable - -If you want to use @code{mysqlc.exe}, you must copy -@file{C:\mysql\lib\cygwinb19.dll} to your Windows system directory -(@file{\windows\system} or similar place). - -The default privileges on Windows give all local users full privileges -to all databases without specifying a password. To make @strong{MySQL} -more secure, you should set a password for all users and remove the row in -the @code{mysql.user} table that has @code{Host='localhost'} and -@code{User=''}. - -You should also add a password for the @code{root} user. The following -example starts by removing the anonymous user that can be used by anyone -to access the @code{test} database, then sets a @code{root} user password: - -@example -C:\> C:\mysql\bin\mysql mysql -mysql> DELETE FROM user WHERE Host='localhost' AND User=''; -mysql> QUIT -C:\> C:\mysql\bin\mysqladmin reload -C:\> C:\mysql\bin\mysqladmin -u root password your_password -@end example - -After you've set the password, if you want to take down the @code{mysqld} -server, you can do so using this command: - -@example -C:\> mysqladmin --user=root --password=your_password shutdown -@end example - -If you are using the old shareware version of @strong{MySQL} Version -3.21 under Windows, the above command will fail with an error: -@code{parse error near 'SET OPTION password'}. The fix is in to upgrade -to the current @strong{MySQL} version, which is freely available. - -With the current @strong{MySQL} versions you can easily add new users -and change privileges with @code{GRANT} and @code{REVOKE} commands. -@xref{GRANT}. - -@c FIX this is ugly, real ugly. -@cindex SSH -@cindex connecting, remotely with SSH -@node Windows and SSH, Windows symbolic links, Windows running, Windows -@subsection Connecting to a Remote MySQL from Windows with SSH - -Here is a note about how to connect to get a secure connection to remote -@strong{MySQL} server with SSH (by David Carlson @email{dcarlson@@mplcomm.com}): - -@itemize @bullet -@item -Install an SSH client on your Windows machine. As a user, the best non-free -one I've found is from @code{SecureCRT} from @uref{http://www.vandyke.com/}. -Another option is @code{f-secure} from @uref{http://www.f-secure.com/}. You -can also find some free ones on @strong{Google} at -@uref{http://directory.google.com/Top/Computers/Security/Products_and_Tools/Cryptography/SSH/Clients/Windows/}. - -@item -Start your Windows SSH client. -Set @code{Host_Name = yourmysqlserver_URL_or_IP}. -Set @code{userid=your_userid} to log in to your server (probably not the same -as your @strong{MySQL} login/password. - -@item -Set up port forwarding. Either do a remote forward (Set @code{local_port: 3306}, @code{remote_host: yourmysqlservername_or_ip}, @code{remote_port: 3306} ) -or a local forward (Set @code{port: 3306}, @code{host: localhost}, @code{remote port: 3306}). - -@item -Save everything, otherwise you'll have to redo it the next time. - -@item -Log in to your server with SSH session you just created. - -@item -On your Windows machine, start some ODBC application (such as Access). - -@item -Create a new file in Windows and link to @strong{MySQL} using the ODBC -driver the same way you normally do, EXCEPT type in @code{localhost} -for the @strong{MySQL} host server --- not @code{yourmysqlservername}. -@end itemize - -You should now have an ODBC connection to @strong{MySQL}, encrypted using SSH. - -@cindex symbolic links -@cindex using multiple disks to start data -@cindex disks, splitting data across -@node Windows symbolic links, Windows compiling, Windows and SSH, Windows -@subsection Splitting Data Across Different Disks on Windows - -Beginning with @strong{MySQL} Version 3.23.16, the @code{mysqld-max} -and @code{mysql-max-nt} servers in the @strong{MySQL} distribution are -compiled with the @code{-DUSE_SYMDIR} option. This allows you to put a -database on different disk by adding a symbolic link to it -(in a manner similar to the way that symbolic links work on Unix). - -On Windows, you make a symbolic link to a database by creating a file -that contains the path to the destination directory and saving this in -the @file{mysql_data} directory under the filename @file{database.sym}. -Note that the symbolic link will be used only if the directory -@file{mysql_data_dir\database} doesn't exist. - -For example, if the @strong{MySQL} data directory is @file{C:\mysql\data} -and you want to have database @code{foo} located at @file{D:\data\foo}, you -should create the file @file{C:\mysql\data\foo.sym} that contains the -text @code{D:\data\foo\}. After that, all tables created in the database -@code{foo} will be created in @file{D:\data\foo}. - -Note that because of the speed penalty you get when opening every table, -we have not enabled this by default even if you have compiled -@strong{MySQL} with support for this. To enable symlinks you should put -in your @code{my.cnf} or @code{my.ini} file the following entry: - -@example -[mysqld] -use-symbolic-links -@end example - -In @strong{MySQL} 4.0 we will enable symlinks by default. Then you -should instead use the @code{skip-symlink} option if you want to -disable this. - -@cindex compiling, on Windows -@cindex Windows, compiling on -@node Windows compiling, Windows vs Unix, Windows symbolic links, Windows -@subsection Compiling MySQL Clients on Windows - -In your source files, you should include @file{windows.h} before you include -@file{mysql.h}: - -@example -#if defined(_WIN32) || defined(_WIN64) -#include -#endif -#include -@end example - -You can either link your code with the dynamic @file{libmysql.lib} library, -which is just a wrapper to load in @file{libmysql.dll} on demand, or link -with the static @file{mysqlclient.lib} library. - -Note that as the mysqlclient libraries are compiled as threaded libraries, -you should also compile your code to be multi-threaded! - -@cindex Windows, versus Unix -@cindex operating systems, Windows versus Unix -@node Windows vs Unix, , Windows compiling, Windows -@subsection MySQL-Windows Compared to Unix MySQL - -@strong{MySQL}-Windows has by now proven itself to be very stable. This version -of @strong{MySQL} has the same features as the corresponding Unix version -with the following exceptions: - -@table @strong -@item Win95 and threads -Win95 leaks about 200 bytes of main memory for each thread creation. -Each connection in @strong{MySQL} creates a new thread, so you shouldn't -run @code{mysqld} for an extended time on Win95 if your server handles -many connections! WinNT and Win98 don't suffer from this bug. - -@item Concurrent reads -@strong{MySQL} depends on the @code{pread()} and @code{pwrite()} calls to be -able to mix @code{INSERT} and @code{SELECT}. Currently we use mutexes -to emulate @code{pread()}/@code{pwrite()}. We will, in the long run, -replace the file level interface with a virtual interface so that we can -use the @code{readfile()}/@code{writefile()} interface on NT to get more speed. -The current implementation limits the number of open files @strong{MySQL} -can use to 1024, which means that you will not be able to run as many -concurrent threads on NT as on Unix. - -@item Blocking read -@strong{MySQL} uses a blocking read for each connection. -This means that: - -@itemize @bullet -@item -A connection will not be disconnected automatically after 8 hours, as happens -with the Unix version of @strong{MySQL}. - -@item -If a connection hangs, it's impossible to break it without killing -@strong{MySQL}. - -@item -@code{mysqladmin kill} will not work on a sleeping connection. - -@item -@code{mysqladmin shutdown} can't abort as long as there are sleeping -connections. -@end itemize - -We plan to fix this problem when our Windows developers have figured out a -nice workaround. - -@item UDF functions -For the moment, @strong{MySQL}-Windows does not support user-definable -functions. - -@item @code{DROP DATABASE} -You can't drop a database that is in use by some thread. - -@item Killing @strong{MySQL} from the task manager -You can't kill @strong{MySQL} from the task manager or with the shutdown -utility in Win95. You must take it down with @code{mysqladmin shutdown}. - -@item Case-insensitive names -Filenames are case insensitive on Windows, so database and table names -are also case insensitive in @strong{MySQL} for Windows. The only -restriction is that database and table names must be specified using the same -case throughout a given statement. @xref{Name case sensitivity}. - -@item The @samp{\} directory character -Pathname components in Win95 are separated by the @samp{\} character, which is -also the escape character in @strong{MySQL}. If you are using @code{LOAD -DATA INFILE} or @code{SELECT ... INTO OUTFILE}, you must double the @samp{\} -character: - -@example -mysql> LOAD DATA INFILE "C:\\tmp\\skr.txt" INTO TABLE skr; -mysql> SELECT * INTO OUTFILE 'C:\\tmp\\skr.txt' FROM skr; -@end example - -Alternatively, use Unix style filenames with @samp{/} characters: - -@example -mysql> LOAD DATA INFILE "C:/tmp/skr.txt" INTO TABLE skr; -mysql> SELECT * INTO OUTFILE 'C:/tmp/skr.txt' FROM skr; -@end example - -@item @code{Can't open named pipe} error -If you use a @strong{MySQL} 3.22 version on NT with the newest mysql-clients -you will get the following error: - -@example -error 2017: can't open named pipe to host: . pipe... -@end example - -@tindex .my.cnf file -This is because the release version of @strong{MySQL} uses named pipes on NT -by default. You can avoid this error by using the @code{--host=localhost} -option to the new @strong{MySQL} clients or create an option file -@file{C:\my.cnf} that contains the following information: - -@example -[client] -host = localhost -@end example - -@item @code{Access denied for user} error -If you get the error @code{Access denied for user: 'some-user@@unknown' -to database 'mysql'} when accessing a @strong{MySQL} server on the same -machine, this means that @strong{MySQL} can't resolve your host name -properly. - -To fix this, you should create a file @file{\windows\hosts} with the -following information: - -@example -127.0.0.1 localhost -@end example - -@item @code{ALTER TABLE} -While you are executing an @code{ALTER TABLE} statement, the table is locked -from usage by other threads. This has to do with the fact that on Windows, -you can't delete a file that is in use by another threads. (In the future, -we may find some way to work around this problem.) - -@item @code{DROP TABLE} on a table that is in use by a @code{MERGE} table will not work -The @code{MERGE} handler does its table mapping hidden from @strong{MySQL}. -Because Windows doesn't allow you to drop files that are open, you first -must flush all @code{MERGE} tables (with @code{FLUSH TABLES}) or drop the -@code{MERGE} table before dropping the table. We will fix this at the same -time we introduce @code{VIEW}s. -@end table - -Here are some open issues for anyone who might want to help us with the Windows -release: - -@cindex Windows, open issues - -@itemize @bullet -@item -Make a single-user @code{MYSQL.DLL} server. This should include everything in -a standard @strong{MySQL} server, except thread creation. This will make -@strong{MySQL} much easier to use in applications that don't need a true -client/server and don't need to access the server from other hosts. - -@item -Add some nice start and shutdown icons to the @strong{MySQL} installation. - -@item -Create a tool to manage registry entries for the @strong{MySQL} startup -options. The registry entry reading is already coded into @file{mysqld.cc}, -but it should be recoded to be more parameter oriented. The tool should -also be able to update the @file{C:\my.cnf} option file if the user prefers -to use that instead of the registry. - -@item -When registering @code{mysqld} as a service with @code{--install} (on NT) -it would be nice if you could also add default options on the command line. -For the moment, the workaround is to list the parameters in the -@file{C:\my.cnf} file instead. - -@item -It would be real nice to be able to kill @code{mysqld} from the task manager. -For the moment, you must use @code{mysqladmin shutdown}. - -@item -Port @code{readline} to Windows for use in the @code{mysql} command line tool. - -@item -GUI versions of the standard @strong{MySQL} clients (@code{mysql}, -@code{mysqlshow}, @code{mysqladmin}, and @code{mysqldump}) would be nice. - -@item -It would be nice if the socket read and write functions in @file{net.c} were -interruptible. This would make it possible to kill open threads with -@code{mysqladmin kill} on Windows. - -@item -@code{mysqld} always starts in the "C" locale and not in the default locale. -We would like to have @code{mysqld} use the current locale for the sort order. - -@item -Implement UDF functions with @code{.DLL}s. - -@item -Add macros to use the faster thread-safe increment/decrement methods -provided by Windows. - -@end itemize - -Other Windows-specific issues are described in the @file{README} file that -comes with the @strong{MySQL}-Windows distribution. - -@node OS/2, MySQL binaries, Windows, Installing -@section OS/2 Notes - -@strong{MySQL} uses quite a few open files. Because of this, you should add -something like the following to your @file{CONFIG.SYS} file: - -@example -SET EMXOPT=-c -n -h1024 -@end example - -If you don't do this, you will probably run into the following error: - -@example -File 'xxxx' not found (Errcode: 24) -@end example - -When using @strong{MySQL} with OS/2 Warp 3, FixPack 29 or above is -required. With OS/2 Warp 4, FixPack 4 or above is required. This is a -requirement of the Pthreads library. @strong{MySQL} must be installed -in a partition that supports long filenames such as HPFS, FAT32, etc. - -The @file{INSTALL.CMD} script must be run from OS/2's own @file{CMD.EXE} -and may not work with replacement shells such as @file{4OS2.EXE}. - -The @file{scripts/mysql-install-db} script has been renamed. It is now called -@file{install.cmd} and is a REXX script, which will set up the default -@strong{MySQL} security settings and create the WorkPlace Shell icons -for @strong{MySQL}. - -Dynamic module support is compiled in but not fully tested. Dynamic -modules should be compiled using the Pthreads run-time library. - -@example -gcc -Zdll -Zmt -Zcrtdll=pthrdrtl -I../include -I../regex -I.. \ - -o example udf_example.cc -L../lib -lmysqlclient udf_example.def -mv example.dll example.udf -@end example - -@strong{Note:} Due to limitations in OS/2, UDF module name stems must not -exceed 8 characters. Modules are stored in the @file{/mysql2/udf} -directory; the @code{safe-mysqld.cmd} script will put this directory in -the @code{BEGINLIBPATH} environment variable. When using UDF modules, -specified extensions are ignored --- it is assumed to be @file{.udf}. -For example, in Unix, the shared module might be named @file{example.so} -and you would load a function from it like this: - -@example -mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "example.so"; -@end example - -Is OS/2, the module would be named @file{example.udf}, but you would not -specify the module extension: - -@example -mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "example"; -@end example - -@cindex binary distributions -@node MySQL binaries, Post-installation, OS/2, Installing -@section MySQL Binaries - -As a service, we at @strong{MySQL AB} provide a set of binary distributions -of @strong{MySQL} that are compiled at our site or at sites where customers -kindly have given us access to their machines. - -These distributions are generated with @code{scripts/make_binary_distribution} -and are configured with the following compilers and options: - -@table @asis -@item SunOS 4.1.4 2 sun4c with @code{gcc} 2.7.2.1 -@code{CC=gcc CXX=gcc CXXFLAGS="-O3 -felide-constructors" ./configure --prefix=/usr/local/mysql --disable-shared --with-extra-charsets=complex --enable-assembler} - -@item SunOS 5.5.1 (and above) sun4u with @code{egcs} 1.0.3a or 2.90.27 or gcc 2.95.2 and newer -@code{CC=gcc CFLAGS="-O3" CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex --enable-assembler} - -@item SunOS 5.6 i86pc with @code{gcc} 2.8.1 -@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex} - -@item Linux 2.0.33 i386 with @code{pgcc} 2.90.29 (@code{egcs} 1.0.3a) -@code{CFLAGS="-O3 -mpentium -mstack-align-double" CXX=gcc CXXFLAGS="-O3 -mpentium -mstack-align-double -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --with-extra-charsets=complex} - -@item Linux 2.2.x with x686 with @code{gcc} 2.95.2 -@code{CFLAGS="-O3 -mpentiumpro" CXX=gcc CXXFLAGS="-O3 -mpentiumpro -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --disable-shared --with-extra-charset=complex} - -@item SCO 3.2v5.0.4 i386 with @code{gcc} 2.7-95q4 -@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} - -@item AIX 2 4 with @code{gcc} 2.7.2.2 -@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} - -@item OSF1 V4.0 564 alpha with @code{gcc} 2.8.1 -@code{CC=gcc CFLAGS=-O CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-low-memory --with-extra-charsets=complex} - -@item Irix 6.3 IP32 with @code{gcc} 2.8.0 -@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} - -@item BSDI BSD/OS 3.1 i386 with @code{gcc} 2.7.2.1 -@code{CC=gcc CXX=gcc CXXFLAGS=-O ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} - -@item BSDI BSD/OS 2.1 i386 with @code{gcc} 2.7.2 -@code{CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql --with-extra-charsets=complex} -@end table - -Anyone who has more optimal options for any of the configurations listed -above can always mail them to the developer's mailing list at -@email{internals@@lists.mysql.com}. - -RPM distributions prior to @strong{MySQL} Version 3.22 are user-contributed. -Beginning with Version 3.22, the RPMs are generated by us at -@strong{MySQL AB}. - -If you want to compile a debug version of @strong{MySQL}, you should add -@code{--with-debug} or @code{--with-debug=full} to the above configure lines -and remove any @code{-fomit-frame-pointer} options. +@node Post-installation, Upgrade, Perl support, Installing +@section Post-installation Setup and Testing @cindex post-installation, setup and testing @cindex testing, post-installation @cindex setup, post-installation -@node Post-installation, Installing many servers, MySQL binaries, Installing -@section Post-installation Setup and Testing @menu * mysql_install_db:: Problems running @code{mysql_install_db} * Starting server:: Problems starting the @strong{MySQL} server * Automatic start:: Starting and stopping @strong{MySQL} automatically -* Command-line options:: Command-line options -* Option files:: Option files @end menu Once you've installed @strong{MySQL} (from either a binary or source @@ -11929,7 +9211,7 @@ options. @xref{InnoDB start}. If you are using BDB (Berkeley DB) tables, you should familiarize yourself with the different BDB specific startup options. @xref{BDB start}. -@node Automatic start, Command-line options, Starting server, Post-installation +@node Automatic start, , Starting server, Post-installation @subsection Starting and Stopping MySQL Automatically @cindex starting, the server automatically @cindex stopping, the server @@ -12004,512 +9286,9 @@ read from option files: @xref{Option files}. -@findex command-line options -@cindex options, command-line -@cindex mysqld options -@node Command-line options, Option files, Automatic start, Post-installation -@subsection mysqld Command-line Options - -@code{mysqld} accepts the following command-line options: - -@table @code -@item --ansi -Use ANSI SQL syntax instead of MySQL syntax. @xref{ANSI mode}. - -@item -b, --basedir=path -Path to installation directory. All paths are usually resolved relative to -this. - -@item --big-tables -Allow big result sets by saving all temporary sets on file. It solves -most 'table full' errors, but also slows down the queries where -in-memory tables would suffice. Since Version 3.23.2, @strong{MySQL} is -able to solve it automatically by using memory for small temporary -tables and switching to disk tables where necessary. - -@item --bind-address=IP -IP address to bind to. - -@item --character-sets-dir=path -Directory where character sets are. @xref{Character sets}. - -@item --chroot=path -Chroot @code{mysqld} daemon during startup. Recommended security measure. It will -somewhat limit @code{LOAD DATA INFILE} and @code{SELECT ... INTO OUTFILE} -though. - -@item --core-file -Write a core file if @code{mysqld} dies. For some systems you must also -specify @code{--core-file-size} to @code{safe_mysqld}. @xref{safe_mysqld, , -@code{safe_mysqld}}. - -@item -h, --datadir=path -Path to the database root. - -@item --default-character-set=charset -Set the default character set. @xref{Character sets}. - -@item --default-table-type=type -Set the default table type for tables. @xref{Table types}. - -@item --debug[...]= -If @strong{MySQL} is configured with @code{--with-debug}, you can use this -option to get a trace file of what @code{mysqld} is doing. -@xref{Making trace files}. - -@item --delay-key-write-for-all-tables -Don't flush key buffers between writes for any @code{MyISAM} table. -@xref{Server parameters}. - -@item --enable-locking -Enable system locking. Note that if you use this option on a system -which a not fully working lockd() (as on Linux) you will easily get -mysqld to deadlock. - -@item -T, --exit-info -This is a bit mask of different flags one can use for debugging the -mysqld server; One should not use this option if one doesn't know -exactly what it does! - -@item --flush -Flush all changes to disk after each SQL command. Normally @strong{MySQL} -only does a write of all changes to disk after each SQL command and lets -the operating system handle the syncing to disk. -@xref{Crashing}. - -@item -?, --help -Display short help and exit. - -@item --init-file=file -Read SQL commands from this file at startup. - -@item -L, --language=... -Client error messages in given language. May be given as a full path. -@xref{Languages}. - -@item -l, --log[=file] -Log connections and queries to file. @xref{Query log}. - -@item --log-isam[=file] -Log all ISAM/MyISAM changes to file (only used when debugging ISAM/MyISAM). - -@item --log-slow-queries[=file] -Log all queries that have taken more than @code{long_query_time} seconds to -execute to file. @xref{Slow query log}. - -@item --log-update[=file] -Log updates to @code{file.#} where @code{#} is a unique number if not given. -@xref{Update log}. - -@item --log-long-format -Log some extra information to update log. If you are using -@code{--log-slow-queries} then queries that are not using indexes are logged -to the slow query log. - -@item --low-priority-updates -Table-modifying operations (@code{INSERT}/@code{DELETE}/@code{UPDATE}) -will have lower priority than selects. It can also be done via -@code{@{INSERT | REPLACE | UPDATE | DELETE@} LOW_PRIORITY ...} to lower -the priority of only one query, or by -@code{SET OPTION SQL_LOW_PRIORITY_UPDATES=1} to change the priority in one -thread. @xref{Table locking}. - -@item --memlock -Lock the @code{mysqld} process in memory. This works only if your -system supports the @code{mlockall()} system call (like Solaris). This -may help if you have a problem where the operating system is causing -@code{mysqld} to swap on disk. - -@item --myisam-recover [=option[,option...]]] where option is one of DEFAULT, BACKUP, FORCE or QUICK. -If this option is used, @code{mysqld} will on open check if the table is -marked as crashed or if if the table wasn't closed properly. (The last -option only works if you are running with @code{--skip-locking}). If this -is the case @code{mysqld} will run check on the table. If the table was corrupted, -@code{mysqld} will attempt to repair it. - -The following options affects how the repair works. - -@multitable @columnfractions .3 .7 -@item DEFAULT @tab The same as not giving any option to - @code{--myisam-recover}. -@item BACKUP @tab If the data table was changed during recover, save a - backup of the @file{table_name.MYD} data file as - @file{table_name-datetime.BAK}. -@item FORCE @tab Run recover even if we will loose more than one row - from the .MYD file. -@item QUICK @tab Don't check the rows in the table if there isn't any - delete blocks. -@end multitable - -Before a table is automatically repaired, @strong{MySQL} will add a note -about this in the error log. If you want to be able to recover from most -things without user intervention, you should use the options -@code{BACKUP,FORCE}. This will force a repair of a table even if some rows -would be deleted, but it will keep the old data file as a backup so that -you can later examine what happened. - -@item --pid-file=path -Path to pid file used by @code{safe_mysqld}. - -@item -P, --port=... -Port number to listen for TCP/IP connections. - -@item -o, --old-protocol -Use the 3.20 protocol for compatibility with some very old clients. -@xref{Upgrading-from-3.20}. - -@item --one-thread -Only use one thread (for debugging under Linux). @xref{Debugging server}. - -@item -O, --set-variable var=option -Give a variable a value. @code{--help} lists variables. You can find a full -description for all variables in the @code{SHOW VARIABLES} section in this -manual. @xref{SHOW VARIABLES}. The tuning server parameters section includes -information of how to optimize these. @xref{Server parameters}. - -@item --safe-mode -Skip some optimize stages. Implies @code{--skip-delay-key-write}. - -@item --safe-show-database -Don't show databases for which the user doesn't have any privileges. - -@item --secure -IP numbers returned by the @code{gethostbyname()} system call are -checked to make sure they resolve back to the original hostname. This -makes it harder for someone on the outside to get access by pretending -to be another host. This option also adds some sanity checks of -hostnames. The option is turned off by default in @strong{MySQL} Version 3.21 -because sometimes it takes a long time to perform backward resolutions. -@strong{MySQL} Version 3.22 caches hostnames (unless @code{--skip-host-cache} -is used) and has this option enabled by default. - -@item --skip-concurrent-insert -Turn off the ability to select and insert at the same time on @code{MyISAM} -tables. (This is only to be used if you think you have found a bug in this -feature). - -@item --skip-delay-key-write -Ignore the @code{delay_key_write} option for all tables. -@xref{Server parameters}. - -@item --skip-grant-tables -This option causes the server not to use the privilege system at all. This -gives everyone @emph{full access} to all databases! (You can tell a running -server to start using the grant tables again by executing @code{mysqladmin -flush-privileges} or @code{mysqladmin reload}.) - -@item --skip-host-cache -Never use host name cache for faster name-ip resolution, but query DNS server -on every connect instead. @xref{DNS}. - -@item --skip-locking -Don't use system locking. To use @code{isamchk} or @code{myisamchk} you must -shut down the server. @xref{Stability}. Note that in @strong{MySQL} Version -3.23 you can use @code{REPAIR} and @code{CHECK} to repair/check @code{MyISAM} -tables. - -@item --skip-name-resolve -Hostnames are not resolved. All @code{Host} column values in the grant tables -must be IP numbers or @code{localhost}. @xref{DNS}. - -@item --skip-networking -Don't listen for TCP/IP connections at all. All interaction with -@code{mysqld} must be made via Unix sockets. This option is highly -recommended for systems where only local requests are allowed. @xref{DNS}. - -@item --skip-new -Don't use new, possible wrong routines. Implies @code{--skip-delay-key-write}. -This will also set default table type to @code{ISAM}. @xref{ISAM}. - -@item --skip-symlink -Don't delete or rename files that a symlinked file in the data directory -points to. - -@item --skip-safemalloc -If @strong{MySQL} is configured with @code{--with-debug=full}, all programs -will check the memory for overruns for every memory allocation and memory -freeing. As this checking is very slow, you can avoid this, when you don't -need memory checking, by using this option. - -@item --skip-show-database -Don't allow 'SHOW DATABASE' commands, unless the user has @strong{process} -privilege. - -@item --skip-stack-trace -Don't write stack traces. This option is useful when you are running -@code{mysqld} under a debugger. @xref{Debugging server}. - -@item --skip-thread-priority -Disable using thread priorities for faster response time. - -@item --socket=path -Socket file to use for local connections instead of default -@code{/tmp/mysql.sock}. - -@item transaction-isolation= @{ READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE @} -Sets the default transaction isolation level. @xref{SET TRANSACTION}. - -@item -t, --tmpdir=path -Path for temporary files. It may be useful if your default @code{/tmp} -directory resides on a partition too small to hold temporary tables. - -@item -u, --user=user_name -Run @code{mysqld} daemon as user @code{user_name}. This option is -@emph{mandatory} when starting @code{mysqld} as root. - -@item -V, --version -Output version information and exit. - -@item -W, --warnings -Print out warnings like @code{Aborted connection...} to the @code{.err} file. -@xref{Communication errors}. -@end table - -@cindex default options -@cindex option files -@cindex creating, default startup options -@cindex startup options, default -@node Option files, , Command-line options, Post-installation -@subsection Option Files - -@strong{MySQL} can, since Version 3.22, read default startup options for the -server and for clients from option files. - -@strong{MySQL} reads default options from the following files on Unix: - -@tindex .my.cnf file -@multitable @columnfractions .3 .7 -@item @strong{Filename} @tab @strong{Purpose} -@item @code{/etc/my.cnf} @tab Global options -@item @code{DATADIR/my.cnf} @tab Server-specific options -@item @code{defaults-extra-file} @tab The file specified with --defaults-extra-file=# -@item @code{~/.my.cnf} @tab User-specific options -@end multitable - -@code{DATADIR} is the @strong{MySQL} data directory (typically -@file{/usr/local/mysql/data} for a binary installation or -@file{/usr/local/var} for a source installation). Note that this is the -directory that was specified at configuration time, not the one specified -with @code{--datadir} when @code{mysqld} starts up! (@code{--datadir} has no -effect on where the server looks for option files, because it looks for them -before it processes any command-line arguments.) - -@strong{MySQL} reads default options from the following files on Windows: - -@multitable @columnfractions .3 .7 -@item @strong{Filename} @tab @strong{Purpose} -@item @code{windows-system-directory\my.ini} @tab Global options -@item @code{C:\my.cnf} @tab Global options -@item @code{C:\mysql\data\my.cnf} @tab Server-specific options -@end multitable - -Note that on Windows, you should specify all paths with @code{/} instead of -@code{\}. If you use @code{\}, you need to specify this twice, as -@code{\} is the escape character in @strong{MySQL}. - -@cindex Environment variables -@strong{MySQL} tries to read option files in the order listed above. If -multiple option files exist, an option specified in a file read later takes -precedence over the same option specified in a file read earlier. Options -specified on the command line take precedence over options specified in any -option file. Some options can be specified using environment variables. -Options specified on the command line or in option files take precedence over -environment variable values. @xref{Environment variables}. - -The following programs support option files: @code{mysql}, -@code{mysqladmin}, @code{mysqld}, @code{mysqldump}, @code{mysqlimport}, -@code{mysql.server}, @code{myisamchk}, and @code{myisampack}. - -You can use option files to specify any long option that a program supports! -Run the program with @code{--help} to get a list of available options. - -An option file can contain lines of the following forms: - -@table @code -@item #comment -Comment lines start with @samp{#} or @samp{;}. Empty lines are ignored. - -@item [group] -@code{group} is the name of the program or group for which you want to set -options. After a group line, any @code{option} or @code{set-variable} lines -apply to the named group until the end of the option file or another group -line is given. - -@item option -This is equivalent to @code{--option} on the command line. - -@item option=value -This is equivalent to @code{--option=value} on the command line. - -@item set-variable = variable=value -This is equivalent to @code{--set-variable variable=value} on the command line. -This syntax must be used to set a @code{mysqld} variable. -@end table - -The @code{client} group allows you to specify options that apply to all -@strong{MySQL} clients (not @code{mysqld}). This is the perfect group to use -to specify the password you use to connect to the server. (But make -sure the option file is readable and writable only by yourself.) - -Note that for options and values, all leading and trailing blanks are -automatically deleted. You may use the escape sequences @samp{\b}, -@samp{\t}, @samp{\n}, @samp{\r}, @samp{\\}, and @samp{\s} in your value string -(@samp{\s} == blank). - -Here is a typical global option file: - -@example -[client] -port=3306 -socket=/tmp/mysql.sock - -[mysqld] -port=3306 -socket=/tmp/mysql.sock -set-variable = key_buffer_size=16M -set-variable = max_allowed_packet=1M - -[mysqldump] -quick -@end example - -Here is typical user option file: - -@example -[client] -# The following password will be sent to all standard MySQL clients -password=my_password - -[mysql] -no-auto-rehash -set-variable = connect_timeout=2 - -[mysqlhotcopy] -interactive-timeout - -@end example - -@tindex .my.cnf file -If you have a source distribution, you will find sample configuration -files named @file{my-xxxx.cnf} in the @file{support-files} directory. -If you have a binary distribution, look in the @file{DIR/support-files} -directory, where @code{DIR} is the pathname to the @strong{MySQL} -installation directory (typically @file{/usr/local/mysql}). Currently -there are sample configuration files for small, medium, large, and very -large systems. You can copy @file{my-xxxx.cnf} to your home directory -(rename the copy to @file{.my.cnf}) to experiment with this. - -All @strong{MySQL} clients that support option files support the -following options: - -@multitable @columnfractions .40 .60 -@item --no-defaults @tab Don't read any option files. -@item --print-defaults @tab Print the program name and all options that it will get. -@item --defaults-file=full-path-to-default-file @tab Only use the given configuration file. -@item --defaults-extra-file=full-path-to-default-file @tab Read this configuration file after the global configuration file but before the user configuration file. -@end multitable - -Note that the above options must be first on the command line to work! -@code{--print-defaults} may however be used directly after the -@code{--defaults-xxx-file} commands. - -Note for developers: Option file handling is implemented simply by -processing all matching options (that is, options in the appropriate group) -before any command-line arguments. This works nicely for programs that use -the last instance of an option that is specified multiple times. If you have -an old program that handles multiply-specified options this way but doesn't -read option files, you need add only two lines to give it that capability. -Check the source code of any of the standard @strong{MySQL} clients to see -how to do this. - -In shell scripts you can use the @file{my_print_defaults} command to parse the -config files: - -@example - -shell> my_print_defaults client mysql ---port=3306 ---socket=/tmp/mysql.sock ---no-auto-rehash -@end example - -The above output contains all options for the groups 'client' and 'mysql'. - -@node Installing many servers, Upgrade, Post-installation, Installing -@section Installing Many Servers on the Same Machine -@cindex post-install, many servers -@cindex Installing many servers -@cindex Starting many servers - -In some cases you may want to have many different @code{mysqld} daemons -(servers) running on the same machine. You may for example want to run -a new version of @strong{MySQL} for testing together with an old version -that is in production. Another case is when you want to give different -users access to different @code{mysqld} servers that they manage themselves. - -One way to get a new server running is by starting it with a different -socket and port as follows: - -@tindex MYSQL_UNIX_PORT environment variable -@tindex MYSQL_TCP_PORT environment variable -@tindex Environment variable, MYSQL_UNIX_PORT -@tindex Environment variable, MYSQL_TCP_PORT -@example -shell> MYSQL_UNIX_PORT=/tmp/mysqld-new.sock -shell> MYSQL_TCP_PORT=3307 -shell> export MYSQL_UNIX_PORT MYSQL_TCP_PORT -shell> scripts/mysql_install_db -shell> bin/safe_mysqld & -@end example - -The environment variables appendix includes a list of other environment -variables you can use to affect @code{mysqld}. @xref{Environment variables}. - -The above is the quick and dirty way that one commonly uses for testing. -The nice thing with this is that all connections you do in the above shell -will automatically be directed to the new running server! - -If you need to do this more permanently, you should create an option -file for each server. @xref{Option files}. In your startup script that -is executed at boot time (mysql.server?) you should specify for both -servers: - -@code{safe_mysqld --default-file=path-to-option-file} - -At least the following options should be different per server: - -@table @code -@item port=# -@item socket=path -@item pid-file=path -@end table - -The following options should be different, if they are used: - -@table @code -@item log=path -@item log-bin=path -@item log-update=path -@item log-isam=path -@item bdb-logdir=path -@end table - -If you want more performance, you can also specify the following differently: - -@table @code -@item tmpdir=path -@item bdb-tmpdir=path -@end table - -@xref{Command-line options}. - -If you are installing binary @strong{MySQL} versions (.tar files) and -start them with @code{./bin/safe_mysqld} then in most cases the only -option you need to add/change is the @code{socket} and @code{port} -argument to @code{safe_mysqld}. - -@node Upgrade, , Installing many servers, Installing +@node Upgrade, Operating System Specific Notes, Post-installation, Installing @section Upgrading/Downgrading MySQL + @cindex upgrading @cindex downgrading @@ -12553,11 +9332,12 @@ dumping core after you upgrade @strong{MySQL}. * Upgrading-to-arch:: Upgrading to another architecture @end menu -@cindex compatibility, between MySQL versions -@cindex upgrading, 3.22 to 3.23 @node Upgrading-from-3.22, Upgrading-from-3.21, Upgrade, Upgrade @subsection Upgrading From Version 3.22 to Version 3.23 +@cindex compatibility, between MySQL versions +@cindex upgrading, 3.22 to 3.23 + @strong{MySQL} Version 3.23 supports tables of the new @code{MyISAM} type and the old @code{ISAM} type. You don't have to convert your old tables to use these with Version 3.23. By default, all new tables will be created with @@ -12576,78 +9356,111 @@ Version 3.23: @item All tables that uses the @code{tis620} character set must be fixed with @code{myisamchk -r} or @code{REPAIR TABLE}. + @item If you do a @code{DROP DATABASE} on a symbolic linked database, both the link and the original database is deleted. (This didn't happen in 3.22 because configure didn't detect the @code{readlink} system call). + @item @code{OPTIMIZE TABLE} now only works for @strong{MyISAM} tables. For other table types, you can use @code{ALTER TABLE} to optimize the table. During @code{OPTIMIZE TABLE} the table is now locked from other threads. + @item The @strong{MySQL} client @code{mysql} is now by default started with the option @code{--no-named-commands (-g)}. This option can be disabled with @code{--enable-named-commands (-G)}. This may cause incompatibility problems in some cases, for example in SQL scripts that use named commands without a semicolon! Long format commands still work from the first line. + @item If you are using the @code{german} character sort order, you must repair all your tables with @code{isamchk -r}, as we have made some changes in the sort order! -@item The default return type of @code{IF} will now depend on both arguments + +@item +The default return type of @code{IF} will now depend on both arguments and not only the first argument. -@item @code{AUTO_INCREMENT} will not work with negative numbers. The reason + +@item +@code{AUTO_INCREMENT} will not work with negative numbers. The reason for this is that negative numbers caused problems when wrapping from -1 to 0. @code{AUTO_INCREMENT} is now for MyISAM tables handled at a lower level and is much faster than before. For MyISAM tables old numbers are also not reused anymore, even if you delete some rows from the table. -@item @code{CASE}, @code{DELAYED}, @code{ELSE}, @code{END}, @code{FULLTEXT}, @code{INNER}, @code{RIGHT}, @code{THEN} and @code{WHEN} are now reserved words. -@item @code{FLOAT(X)} is now a true floating-point type and not a value with -a fixed number of decimals. -@item When declaring @code{DECIMAL(length,dec)} the length argument no -longer includes a place for the sign or the decimal point. -@item A @code{TIME} string must now be of one of the following formats: + +@item +@code{CASE}, @code{DELAYED}, @code{ELSE}, @code{END}, @code{FULLTEXT}, +@code{INNER}, @code{RIGHT}, @code{THEN} and @code{WHEN} are now reserved words. + +@item +@code{FLOAT(X)} is now a true floating-point type and not a value with a +fixed number of decimals. + +@item +When declaring @code{DECIMAL(length,dec)} the length argument no longer +includes a place for the sign or the decimal point. + +@item +A @code{TIME} string must now be of one of the following formats: @code{[[[DAYS] [H]H:]MM:]SS[.fraction]} or @code{[[[[[H]H]H]H]MM]SS[.fraction]} -@item @code{LIKE} now compares strings using the same character -comparison rules as @code{'='}. If you require the old behavior, you -can compile @strong{MySQL} with the @code{CXXFLAGS=-DLIKE_CMP_TOUPPER} -flag. -@item @code{REGEXP} is now case insensitive for normal (not binary) strings. -@item When you check/repair tables you should use @code{CHECK TABLE} + +@item +@code{LIKE} now compares strings using the same character comparison rules +as @code{'='}. If you require the old behavior, you can compile +@strong{MySQL} with the @code{CXXFLAGS=-DLIKE_CMP_TOUPPER} flag. + +@item +@code{REGEXP} is now case insensitive for normal (not binary) strings. + +@item +When you check/repair tables you should use @code{CHECK TABLE} or @code{myisamchk} for @code{MyISAM} tables (@code{.MYI}) and @code{isamchk} for ISAM (@code{.ISM}) tables. -@item If you want your @code{mysqldump} files to be compatible between + +@item +If you want your @code{mysqldump} files to be compatible between @strong{MySQL} Version 3.22 and Version 3.23, you should not use the @code{--opt} or @code{--full} option to @code{mysqldump}. -@item Check all your calls to @code{DATE_FORMAT()} to make sure there is a + +@item +Check all your calls to @code{DATE_FORMAT()} to make sure there is a @samp{%} before each format character. (Later @strong{MySQL} Version 3.22 did allow this syntax.) + @item @code{mysql_fetch_fields_direct} is now a function (it was a macro) and it returns a pointer to a @code{MYSQL_FIELD} instead of a @code{MYSQL_FIELD}. + @item @code{mysql_num_fields()} can no longer be used on a @code{MYSQL*} object (it's now a function that takes @code{MYSQL_RES*} as an argument. You should now use @code{mysql_field_count()} instead. + @item In @strong{MySQL} Version 3.22, the output of @code{SELECT DISTINCT ...} was almost always sorted. In Version 3.23, you must use @code{GROUP BY} or @code{ORDER BY} to obtain sorted output. + @item @code{SUM()} now returns @code{NULL}, instead of 0, if there is no matching rows. This is according to ANSI SQL. -@item An @code{AND} or @code{OR} with @code{NULL} values will now return + +@item +An @code{AND} or @code{OR} with @code{NULL} values will now return @code{NULL} instead of 0. This mostly affects queries that use @code{NOT} on an @code{AND/OR} expression as @code{NOT NULL} = @code{NULL}. @code{LPAD()} and @code{RPAD()} will shorten the result string if it's longer than the length argument. @end itemize -@cindex compatibility, between MySQL versions @node Upgrading-from-3.21, Upgrading-from-3.20, Upgrading-from-3.22, Upgrade @subsection Upgrading from Version 3.21 to Version 3.22 + +@cindex compatibility, between MySQL versions @cindex upgrading, 3.21 to 3.22 Nothing that affects compatibility has changed between Version 3.21 and 3.22. @@ -12744,10 +9557,11 @@ There are some new reserved words. The most notable are @code{DATE}, @code{TIME}, and @code{TIMESTAMP}. @end itemize -@cindex upgrading, different architecture @node Upgrading-to-arch, , Upgrading-from-3.20, Upgrade @subsection Upgrading to Another Architecture +@cindex upgrading, different architecture + If you are using @strong{MySQL} Version 3.23, you can copy the @code{.frm}, @code{.MYI}, and @code{.MYD} files between different architectures that support the same floating-point format. (@strong{MySQL} takes care of any @@ -12838,9 +9652,2499 @@ After you import the @code{mysql} database on the new machine, execute @code{mysqladmin flush-privileges} so that the server reloads the grant table information. +@node Operating System Specific Notes, , Upgrade, Installing +@section Operating System Specific Notes + +@menu +* Linux:: +* Windows:: +* Solaris:: +* Solaris 2.7:: +* Solaris x86:: +* BSD Notes:: +* Mac OS X:: +* Other Unix Notes:: +* SCO Unixware:: +* BeOS:: +* Novell Netware:: +@end menu + +@node Linux, Windows, Operating System Specific Notes, Operating System Specific Notes +@subsection Linux Notes (All Linux Versions) + +@menu +* Binary notes-Linux:: +* Linux-x86:: Linux-x86 notes +* Linux-SPARC:: Linux-SPARC notes +* Linux-Alpha:: Linux-Alpha notes +* Linux-PowerPC:: +* Linux-MIPS:: +* Linux-IA64:: Linux-Ia64 notes +@end menu + +The notes below regarding @strong{glibc} apply only to the situation +when you build @strong{MySQL} +yourself. If you are running Linux on an x86 machine, in most cases it is +much better for you to just use our binary. We link our binaries against +the best patched version of @strong{glibc} we can come up with and with the +best compiler options, in an attempt to make it suitable for a high-load +server. So if you read the text below, and are in doubt about +what you should do, try our binary first to see if it meets your needs, and +worry about your own build only after you have discovered that our binary is +not good enough. In that case, we would appreciate a note about it, so we +can build a better binary next time. For a typical user, even for setups with +a lot of concurrent connections and/or tables exceeding 2GB limit, our +binary in most cases is the best choice. + +@strong{MySQL} uses LinuxThreads on Linux. If you are using an old +Linux version that doesn't have @code{glibc2}, you must install +LinuxThreads before trying to compile @strong{MySQL}. You can get +LinuxThreads at @uref{http://www.mysql.com/Downloads/Linux}. + +@strong{NOTE:} We have seen some strange problems with Linux 2.2.14 and +@strong{MySQL} on SMP systems; If you have a SMP system, we recommend +you to upgrade to Linux 2.4 ASAP! Your system will be faster and more +stable by doing this! + +Note that @code{glibc} versions before and including Version 2.1.1 have +a fatal bug in @code{pthread_mutex_timedwait} handling, which is used +when you do @code{INSERT DELAYED}. We recommend you to not use +@code{INSERT DELAYED} before upgrading glibc. + +If you plan to have 1000+ concurrent connections, you will need to make +some changes to LinuxThreads, recompile it, and relink @strong{MySQL} against +the new @file{libpthread.a}. Increase @code{PTHREAD_THREADS_MAX} in +@file{sysdeps/unix/sysv/linux/bits/local_lim.h} to 4096 and decrease +@code{STACK_SIZE} in @file{linuxthreads/internals.h} to 256 KB. The paths are +relative to the root of @code{glibc} Note that @strong{MySQL} will not be +stable with around 600-1000 connections if @code{STACK_SIZE} is the default +of 2 MB. + +If you have a problem with that @strong{MySQL} can't open enough files, +or connections, it may be that you haven't configured Linux to handle +enough files. + +In Linux 2.2 and forwards, you can check the number of allocated +file handlers by doing: + +@example +cat /proc/sys/fs/file-max +cat /proc/sys/fs/dquot-max +cat /proc/sys/fs/super-max +@end example + +If you have more than 16M of memory, you should add something like the +following in your boot script (@file{/etc/rc/boot.local} on SuSE): + +@example +echo 65536 > /proc/sys/fs/file-max +echo 8192 > /proc/sys/fs/dquot-max +echo 1024 > /proc/sys/fs/super-max +@end example + +You can also run the above from the command line as root, but in this case +your old limits will be used next time your computer reboots. + +You should also add /etc/my.cnf: + +@example +[safe_mysqld] +open-files-limit=8192 +@end example + +The above should allow @strong{MySQL} to create up to 8192 connections + files. + +The @code{STACK_SIZE} constant in LinuxThreads controls the spacing of thread +stacks in the address space. It needs to be large enough so that there will +be plenty of room for the stack of each individual thread, but small enough +to keep the stack of some thread from running into the global @code{mysqld} +data. Unfortunately, the Linux implementation of @code{mmap()}, as we have +experimentally discovered, will successfully unmap an already mapped region +if you ask it to map out an address already in use, zeroing out the data +on the entire page, instead of returning an error. So, the safety of +@code{mysqld} or any other threaded application depends on the "gentleman" +behavior of the code that creates threads. The user must take measures to +make sure the number of running threads at any time is sufficiently low for +thread stacks to stay away from the global heap. With @code{mysqld}, you +should enforce this "gentleman" behavior by setting a reasonable value for +the @code{max_connections} variable. + +If you build @strong{MySQL} yourself and do not what to mess with patching +LinuxThreads, you should set @code{max_connections} to a value no higher +than 500. It should be even less if you have a large key buffer, large +heap tables, or some other things that make @strong{mysqld} allocate a lot +of memory or if you are running a 2.2 kernel with a 2GB patch. If you are +using our binary or RPM version 3.23.25 or later, you can safely set +@code{max_connections} at 1500, assuming no large key buffer or heap tables +with lots of data. The more you reduce @code{STACK_SIZE} in LinuxThreads +the more threads you can safely create. We recommend the values between +128K and 256K. + +If you use a lot of concurrent connections, you may suffer from a "feature" +in the 2.2 kernel that penalizes a process for forking or cloning a child +in an attempt to prevent a fork bomb attack. This will cause @strong{MySQL} +not to scale well as you increase the number of concurrent clients. On +single CPU systems, we have seen this manifested in a very slow thread +creation, which means it may take a long time to connect to @strong{MySQL} +(as long as 1 minute), and it may take just as long to shut it down. On +multiple CPU systems, we have observed a gradual drop in query speed as +the number of clients increases. In the process of trying to find a +solution, we have received a kernel patch from one of our users, who +claimed it made a lot of difference for his site. The patch is available here +(@uref{http://www.mysql.com/Downloads/Patches/linux-fork.patch}). We have +now done rather extensive testing of this patch on both development and +production systems. It has significantly +improved @code{MySQL} performance without causing any problems and we now +recommend it to our users who are still running high-load servers on +2.2 kernels. This issue has been fixed in the 2.4 kernel, so if you are not +satisfied with +the current performance of your system, rather than patching your 2.2 kernel, +it might be easier to just upgrade to 2.4, which will also give you a nice +SMP boost in addition to fixing this fairness bug. + +We have tested @strong{MySQL} on the 2.4 kernel on a 2 CPU machine and +found @strong{MySQL} scales MUCH better - there was virtually no slowdown +on query throughput all the way up +to 1000 clients, and @strong{MySQL} scaling factor ( computed as the ratio of +maximum throughput to the throughput with one client) was 180%. +We have observed similar results on a 4-CPU system - virtually no +slowdown as the number of +clients was increased up to 1000, and 300% scaling factor. So for a high-load +SMP server we would definitely recommend the 2.4 kernel at this point. We +have discovered that it is essential to run @code{mysqld} process with the +highest possible priority on the 2.4 kernel to achieve maximum performance. +This can be done by adding +@code{renice -20 $$} command to @code{safe_mysqld}. In our testing on a +4-CPU machine, increasing the priority gave 60% increase in throughput with +400 clients. + +We are currently also trying to collect +more info on how well @code{MySQL} performs on 2.4 kernel on 4-way and 8-way +systems. If you have access such a system and have done some benchmarks, +please send a mail to @email{docs@@mysql.com} with the results - we will +include them in the manual. + +There is another issue that greatly hurts @strong{MySQL} performance, +especially on SMP systems. The implementation of mutex in +LinuxThreads in @strong{glibc-2.1} is very bad for programs with many +threads that only +hold the mutex for a short time. On an SMP system, ironic as it is, if +you link @strong{MySQL} against unmodified @strong{LinuxThreads}, +removing processors from the machine improves @strong{MySQL} performance +in many cases. We have made a patch available for @strong{glibc 2.1.3}, +@uref{http://www.mysql.com/Downloads/Linux/linuxthreads-2.1-patch,linuxthreads-2.1-patch} +to correct this behavior. + +With @strong{glibc-2.2.2} +@strong{MySQL} version 3.23.36 will use the adaptive mutex, which is much +better than even the patched one in @strong{glibc-2.1.3}. Be warned, however, +that under some conditions, the current mutex code in @strong{glibc-2.2.2} +overspins, which hurts @strong{MySQL} performance. The chance of this +condition can be reduced by renicing @code{mysqld} process to the highest +priority. We have also been able to correct the overspin behavior with +a patch, available @uref{http://www.mysql.com/Downloads/Linux/linuxthreads-2.2.2.patch,here}. It combines the correction of overspin, maximum number of +threads, and stack spacing all in one. You will need to apply it in the +@code{linuxthreads} directory with +@code{patch -p0 cp support-files/mysql.server /etc/init.d/mysql.server +shell> /usr/sbin/update-rc.d mysql.server defaults 99 +@end example + +@code{mysql.server} can be found in the @file{share/mysql} directory +under the @strong{MySQL} installation directory or in the +@file{support-files} directory of the @strong{MySQL} source tree. + +If @code{mysqld} always core dumps when it starts up, the problem may be that +you have an old @file{/lib/libc.a}. Try renaming it, then remove +@file{sql/mysqld} and do a new @code{make install} and try again. This +problem has been reported on some Slackware installations. + +If you get the following error when linking @code{mysqld}, +it means that your @file{libg++.a} is not installed correctly: + +@example +/usr/lib/libc.a(putc.o): In function `_IO_putc': +putc.o(.text+0x0): multiple definition of `_IO_putc' +@end example + +You can avoid using @file{libg++.a} by running @code{configure} like this: + +@example +shell> CXX=gcc ./configure +@end example + +@node Linux-SPARC, Linux-Alpha, Linux-x86, Linux +@subsubsection Linux SPARC Notes + +In some implementations, @code{readdir_r()} is broken. The symptom is that +@code{SHOW DATABASES} always returns an empty set. This can be fixed by +removing @code{HAVE_READDIR_R} from @file{config.h} after configuring and +before compiling. + +Some problems will require patching your Linux installation. The patch can +be found at +@uref{http://www.mysql.com/Downloads/patches/Linux-sparc-2.0.30.diff}. +This patch is against the Linux distribution @file{sparclinux-2.0.30.tar.gz} +that is available at @code{vger.rutgers.edu} (a version of Linux that was +never merged with the official 2.0.30). You must also install LinuxThreads +Version 0.6 or newer. + +@node Linux-Alpha, Linux-PowerPC, Linux-SPARC, Linux +@subsubsection Linux Alpha Notes + +@strong{MySQL} Version 3.23.12 is the first @strong{MySQL} version that is +tested on Linux-Alpha. If you plan to use @strong{MySQL} on Linux-Alpha, +you should ensure that you have this version or newer. + +We have tested @strong{MySQL} on Alpha with our benchmarks and test suite, +and it appears to work nicely. The main thing we haven't yet had time to +test is how things works with many concurrent users. + +When we compiled the standard @strong{MySQL} binary we are using SuSE 6.4, +kernel 2.2.13-SMP, Compaq C compiler (V6.2-504) and Compaq C++ compiler +(V6.3-005) on a Comaq DS20 machine with an Alpha EV6 processor. + +You can find the above compilers at +@uref{http://www.support.compaq.com/alpha-tools}). By using these compilers, +instead of gcc, we get about 9-14 % better performance with @strong{MySQL}. + +Note that the configure line optimized the binary for the current CPU; This +means you can only use our binary if you have an Alpha EV6 processor. We also +compile statically to avoid library problems. + +@example +CC=ccc CFLAGS="-fast" CXX=cxx CXXFLAGS="-fast -noexceptions -nortti" ./configure --prefix=/usr/local/mysql --disable-shared --with-extra-charsets=complex --enable-thread-safe-client --with-mysqld-ldflags=-non_shared --with-client-ldflags=-non_shared +@end example + +If you want to use egcs the following configure line worked for us: + +@example +CFLAGS="-O3 -fomit-frame-pointer" CXX=gcc CXXFLAGS="-O3 -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --disable-shared +@end example + +Some known problems when running @strong{MySQL} on Linux-Alpha: + +@itemize @bullet +@item +Debugging threaded applications like @strong{MySQL} will not work with +@code{gdb 4.18}. You should download and use gdb 5.0 instead! + +@item +If you try linking @code{mysqld} statically when using @code{gcc}, the +resulting image will core dump at start. In other words, @strong{DON'T} +use @code{--with-mysqld-ldflags=-all-static} with @code{gcc}. +@end itemize + +@node Linux-PowerPC, Linux-MIPS, Linux-Alpha, Linux +@subsubsection Linux PowerPC Notes + +@strong{MySQL} should work on MkLinux with the newest @code{glibc} package +(tested with @code{glibc} 2.0.7). + +@node Linux-MIPS, Linux-IA64, Linux-PowerPC, Linux +@subsubsection Linux MIPS Notes + +To get @strong{MySQL} to work on Qube2, (Linux Mips), you need the +newest @code{glibc} libraries (@code{glibc-2.0.7-29C2} is known to +work). You must also use the @code{egcs} C++ compiler +(@code{egcs-1.0.2-9}, @code{gcc 2.95.2} or newer). + +@node Linux-IA64, , Linux-MIPS, Linux +@subsubsection Linux IA64 Notes + +To get @strong{MySQL} to compile on Linux Ia64, we had to do the following +(we assume that this will be easier when next gcc version for ia64 is +released). + +Using @code{gcc-2.9-final}: + +@example +CFLAGS="-O2" CXX=gcc CXXFLAGS="-O2 -felide-constructors -fno-exceptions -fno-rtti" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --disable-shared --with-extra-charsets=complex +@end example + +After @code{make} you will get an error that @code{sql/opt_range.cc} +will not compile (internal compiler error). To fix this, go to the sql +directory and type @code{make} again. Copy the compile line, but change +-O2 to -O0. The file should now compile. + +Now you can do: + +@example +cd .. +make +make_install +@end example + +and @strong{mysqld} should be ready to run. + + +@node Windows, Solaris, Linux, Operating System Specific Notes +@subsection Windows Notes + +This section describes installation and use of @strong{MySQL} on Windows. +This information is also provided in the @file{README} file that comes +with the @strong{MySQL} Windows distribution. + +@menu +* Win95 start:: Starting @strong{MySQL} on Win95 / Win98 +* NT start:: Starting @strong{MySQL} on NT / Win2000 +* Windows running:: Running @strong{MySQL} on Windows +* Windows and SSH:: Connecting to a remote @strong{MySQL} from Windows with SSH +* Windows symbolic links:: Splitting data across different disks under Win32 +* Windows compiling:: Compiling MySQL clients on Windows. +* Windows vs Unix:: @strong{MySQL}-Windows compared to Unix @strong{MySQL} +@end menu + +@node Win95 start, NT start, Windows, Windows +@subsubsection Starting MySQL on Windows 95 or Windows 98 + +@strong{MySQL} uses TCP/IP to connect a client to a server. (This will +allow any machine on your network to connect to your @strong{MySQL} +server.) Because of this, you must install TCP/IP on your machine before +starting @strong{MySQL}. You can find TCP/IP on your Windows CD-ROM. + +Note that if you are using an old Win95 release (for example OSR2), it's +likely that you have an old Winsock package! @strong{MySQL} requires +Winsock 2! You can get the newest Winsock from +@uref{http://www.microsoft.com/}. Win98 has the new Winsock 2 library, so +the above doesn't apply for Win98. + +To start the @code{mysqld} server, you should start an MS-DOS window and type: + +@example +C:\> C:\mysql\bin\mysqld +@end example + +This will start @code{mysqld} in the background without a window. + +You can kill the @strong{MySQL} server by executing: + +@example +C:\> C:\mysql\bin\mysqladmin -u root shutdown +@end example + +Note that Win95 and Win98 don't support creation of named pipes. +On Win95 and Win98, you can only use named pipes to connect to a +remote @strong{MySQL} server running on a Windows NT server host. +(The @strong{MySQL} server must also support named pipes, of +course. For example, using @code{mysqld-opt} under NT will not allow +named pipe connections. You should use either @code{mysqld-nt} or +@code{mysqld-max-nt}.) + +If @code{mysqld} doesn't start, please check the +@file{\mysql\data\mysql.err} file to see if the server wrote any message +there to indicate the cause of the problem. You can also try to start +the server with @code{mysqld --standalone}; In this case, you may get +some useful information on the screen that may help solve the problem. + +The last option is to start @code{mysqld} with @code{--standalone +--debug}. In this case @code{mysqld} will write a log file +@file{C:\mysqld.trace} that should contain the reason why @code{mysqld} +doesn't start. @xref{Making trace files}. + +@node NT start, Windows running, Win95 start, Windows +@subsubsection Starting MySQL on Windows NT or Windows 2000 + +The Win95/Win98 section also applies to @strong{MySQL} on NT/Win2000, with +the following differences: + +To get @strong{MySQL} to work with TCP/IP on NT, you must install +service pack 3 (or newer)! + +Note that everything in the following that applies for NT also applies +for Win2000! + +For NT/Win2000, the server name is @code{mysqld-nt}. Normally you +should install @strong{MySQL} as a service on NT/Win2000: + +@example +C:\> C:\mysql\bin\mysqld-nt --install +@end example + +or + +@example +C:\> C:\mysql\bin\mysqld-max-nt --install +@end example + +(Under Windows NT, you can actually install any of the server binaries +as a service, but only those having names that end with @code{-nt.exe} +provide support for named pipes.) + +You can start and stop the @strong{MySQL} service with these commands: + +@example +C:\> NET START mysql +C:\> NET STOP mysql +@end example + +Note that in this case you can't use any other options for @code{mysqld-nt}! + +You can also run @code{mysqld-nt} as a stand-alone program on NT if you need +to start @code{mysqld-nt} with any options! If you start @code{mysqld-nt} +without options on NT, @code{mysqld-nt} tries to start itself as a service +with the default service options. If you have stopped @code{mysqld-nt}, you +have to start it with @code{NET START mysql}. + +The service is installed with the name @code{MySQL}. Once installed, it must +be started using the Services Control Manager (SCM) Utility found in the +Control Panel, or by using the @code{NET START MySQL} command. If any options +are desired, they must be specified as ``Startup parameters'' in the SCM utility +before you start the @strong{MySQL} service. Once running, @code{mysqld-nt} +can be stopped using @code{mysqladmin}, or from the SCM utility or by using +the command @code{NET STOP MySQL}. If you use SCM to stop @code{mysqld-nt}, +there is a strange message from SCM about @code{mysqld shutdown normally}. +When run as a service, @code{mysqld-nt} has no access to a console and so no +messages can be seen. + +On NT you can get the following service error messages: + +@multitable @columnfractions .3 .7 +@item Permission Denied @tab Means that it cannot find @code{mysqld-nt.exe}. +@item Cannot Register @tab Means that the path is incorrect. +@item Failed to install service. @tab Means that the service is already installed or that the Service Control Manager is in bad state. +@end multitable + +If you have problems installing @code{mysqld-nt} as a service, try starting +it with the full path: + +@example +C:\> C:\mysql\bin\mysqld-nt --install +@end example + +If this doesn't work, you can get @code{mysqld-nt} to start properly by fixing +the path in the registry! + +If you don't want to start @code{mysqld-nt} as a service, you can start it as +follows: + +@example +C:\> C:\mysql\bin\mysqld-nt --standalone +@end example + +or + +@example +C:\> C:\mysql\bin\mysqld --standalone --debug +@end example + +The last version gives you a debug trace in @file{C:\mysqld.trace}. +@xref{Making trace files}. + +@node Windows running, Windows and SSH, NT start, Windows +@subsubsection Running MySQL on Windows + +@cindex TCP/IP +@cindex named pipes + +@strong{MySQL} supports TCP/IP on all Windows platforms and named pipes on NT. +The default is to use named pipes for local connections on NT and TCP/IP for +all other cases if the client has TCP/IP installed. The host name specifies +which protocol is used: + +@multitable @columnfractions .3 .7 +@strong{Host name} @tab @strong{Protocol} +@item NULL (none) @tab On NT, try named pipes first; if that doesn't work, use TCP/IP. On Win95/Win98, TCP/IP is used. +@item . @tab Named pipes +@item localhost @tab TCP/IP to current host +@item hostname @tab TCP/IP +@end multitable + +You can force a @strong{MySQL} client to use named pipes by specifying the +@code{--pipe} option or by specifying @code{.} as the host name. Use the +@code{--socket} option to specify the name of the pipe. + +You can test whether or not @strong{MySQL} is working by executing the +following commands: + +@example +C:\> C:\mysql\bin\mysqlshow +C:\> C:\mysql\bin\mysqlshow -u root mysql +C:\> C:\mysql\bin\mysqladmin version status proc +C:\> C:\mysql\bin\mysql test +@end example + +If @code{mysqld} is slow to answer to connections on Win95/Win98, there is +probably a problem with your DNS. In this case, start @code{mysqld} with +@code{--skip-name-resolve} and use only @code{localhost} and IP numbers in +the @strong{MySQL} grant tables. You can also avoid DNS when connecting to a +@code{mysqld-nt} @strong{MySQL} server running on NT by using the +@code{--pipe} argument to specify use of named pipes. This works for most +@strong{MySQL} clients. + +There are two versions of the @strong{MySQL} command-line tool: +@multitable @columnfractions .25 .75 +@item @code{mysql} @tab Compiled on native Windows, which offers very limited text editing capabilities. +@item @code{mysqlc} @tab Compiled with the Cygnus GNU compiler and libraries, which offers @code{readline} editing. +@end multitable + +If you want to use @code{mysqlc.exe}, you must copy +@file{C:\mysql\lib\cygwinb19.dll} to your Windows system directory +(@file{\windows\system} or similar place). + +The default privileges on Windows give all local users full privileges +to all databases without specifying a password. To make @strong{MySQL} +more secure, you should set a password for all users and remove the row in +the @code{mysql.user} table that has @code{Host='localhost'} and +@code{User=''}. + +You should also add a password for the @code{root} user. The following +example starts by removing the anonymous user that can be used by anyone +to access the @code{test} database, then sets a @code{root} user password: + +@example +C:\> C:\mysql\bin\mysql mysql +mysql> DELETE FROM user WHERE Host='localhost' AND User=''; +mysql> QUIT +C:\> C:\mysql\bin\mysqladmin reload +C:\> C:\mysql\bin\mysqladmin -u root password your_password +@end example + +After you've set the password, if you want to take down the @code{mysqld} +server, you can do so using this command: + +@example +C:\> mysqladmin --user=root --password=your_password shutdown +@end example + +If you are using the old shareware version of @strong{MySQL} Version +3.21 under Windows, the above command will fail with an error: +@code{parse error near 'SET OPTION password'}. The fix is in to upgrade +to the current @strong{MySQL} version, which is freely available. + +With the current @strong{MySQL} versions you can easily add new users +and change privileges with @code{GRANT} and @code{REVOKE} commands. +@xref{GRANT}. + +@c FIX this is ugly, real ugly. +@node Windows and SSH, Windows symbolic links, Windows running, Windows +@subsubsection Connecting to a Remote MySQL from Windows with SSH + +@cindex SSH +@cindex connecting, remotely with SSH + +Here is a note about how to connect to get a secure connection to remote +@strong{MySQL} server with SSH (by David Carlson @email{dcarlson@@mplcomm.com}): + +@itemize @bullet +@item +Install an SSH client on your Windows machine. As a user, the best non-free +one I've found is from @code{SecureCRT} from @uref{http://www.vandyke.com/}. +Another option is @code{f-secure} from @uref{http://www.f-secure.com/}. You +can also find some free ones on @strong{Google} at +@uref{http://directory.google.com/Top/Computers/Security/Products_and_Tools/Cryptography/SSH/Clients/Windows/}. + +@item +Start your Windows SSH client. +Set @code{Host_Name = yourmysqlserver_URL_or_IP}. +Set @code{userid=your_userid} to log in to your server (probably not the same +as your @strong{MySQL} login/password. + +@item +Set up port forwarding. Either do a remote forward (Set @code{local_port: 3306}, @code{remote_host: yourmysqlservername_or_ip}, @code{remote_port: 3306} ) +or a local forward (Set @code{port: 3306}, @code{host: localhost}, @code{remote port: 3306}). + +@item +Save everything, otherwise you'll have to redo it the next time. + +@item +Log in to your server with SSH session you just created. + +@item +On your Windows machine, start some ODBC application (such as Access). + +@item +Create a new file in Windows and link to @strong{MySQL} using the ODBC +driver the same way you normally do, EXCEPT type in @code{localhost} +for the @strong{MySQL} host server --- not @code{yourmysqlservername}. +@end itemize + +You should now have an ODBC connection to @strong{MySQL}, encrypted using SSH. + +@node Windows symbolic links, Windows compiling, Windows and SSH, Windows +@subsubsection Splitting Data Across Different Disks on Windows + +@cindex symbolic links +@cindex using multiple disks to start data +@cindex disks, splitting data across + +Beginning with @strong{MySQL} Version 3.23.16, the @code{mysqld-max} +and @code{mysql-max-nt} servers in the @strong{MySQL} distribution are +compiled with the @code{-DUSE_SYMDIR} option. This allows you to put a +database on different disk by adding a symbolic link to it +(in a manner similar to the way that symbolic links work on Unix). + +On Windows, you make a symbolic link to a database by creating a file +that contains the path to the destination directory and saving this in +the @file{mysql_data} directory under the filename @file{database.sym}. +Note that the symbolic link will be used only if the directory +@file{mysql_data_dir\database} doesn't exist. + +For example, if the @strong{MySQL} data directory is @file{C:\mysql\data} +and you want to have database @code{foo} located at @file{D:\data\foo}, you +should create the file @file{C:\mysql\data\foo.sym} that contains the +text @code{D:\data\foo\}. After that, all tables created in the database +@code{foo} will be created in @file{D:\data\foo}. + +Note that because of the speed penalty you get when opening every table, +we have not enabled this by default even if you have compiled +@strong{MySQL} with support for this. To enable symlinks you should put +in your @code{my.cnf} or @code{my.ini} file the following entry: + +@example +[mysqld] +use-symbolic-links +@end example + +In @strong{MySQL} 4.0 we will enable symlinks by default. Then you +should instead use the @code{skip-symlink} option if you want to +disable this. + +@node Windows compiling, Windows vs Unix, Windows symbolic links, Windows +@subsubsection Compiling MySQL Clients on Windows + +@cindex compiling, on Windows +@cindex Windows, compiling on + +In your source files, you should include @file{windows.h} before you include +@file{mysql.h}: + +@example +#if defined(_WIN32) || defined(_WIN64) +#include +#endif +#include +@end example + +You can either link your code with the dynamic @file{libmysql.lib} library, +which is just a wrapper to load in @file{libmysql.dll} on demand, or link +with the static @file{mysqlclient.lib} library. + +Note that as the mysqlclient libraries are compiled as threaded libraries, +you should also compile your code to be multi-threaded! + +@node Windows vs Unix, , Windows compiling, Windows +@subsubsection MySQL-Windows Compared to Unix MySQL + +@cindex Windows, versus Unix +@cindex operating systems, Windows versus Unix + +@strong{MySQL}-Windows has by now proven itself to be very stable. This version +of @strong{MySQL} has the same features as the corresponding Unix version +with the following exceptions: + +@table @strong +@item Win95 and threads +Win95 leaks about 200 bytes of main memory for each thread creation. +Each connection in @strong{MySQL} creates a new thread, so you shouldn't +run @code{mysqld} for an extended time on Win95 if your server handles +many connections! WinNT and Win98 don't suffer from this bug. + +@item Concurrent reads +@strong{MySQL} depends on the @code{pread()} and @code{pwrite()} calls to be +able to mix @code{INSERT} and @code{SELECT}. Currently we use mutexes +to emulate @code{pread()}/@code{pwrite()}. We will, in the long run, +replace the file level interface with a virtual interface so that we can +use the @code{readfile()}/@code{writefile()} interface on NT to get more speed. +The current implementation limits the number of open files @strong{MySQL} +can use to 1024, which means that you will not be able to run as many +concurrent threads on NT as on Unix. + +@item Blocking read +@strong{MySQL} uses a blocking read for each connection. +This means that: + +@itemize @bullet +@item +A connection will not be disconnected automatically after 8 hours, as happens +with the Unix version of @strong{MySQL}. + +@item +If a connection hangs, it's impossible to break it without killing +@strong{MySQL}. + +@item +@code{mysqladmin kill} will not work on a sleeping connection. + +@item +@code{mysqladmin shutdown} can't abort as long as there are sleeping +connections. +@end itemize + +We plan to fix this problem when our Windows developers have figured out a +nice workaround. + +@item UDF functions +For the moment, @strong{MySQL}-Windows does not support user-definable +functions. + +@item @code{DROP DATABASE} +You can't drop a database that is in use by some thread. + +@item Killing @strong{MySQL} from the task manager +You can't kill @strong{MySQL} from the task manager or with the shutdown +utility in Win95. You must take it down with @code{mysqladmin shutdown}. + +@item Case-insensitive names +Filenames are case insensitive on Windows, so database and table names +are also case insensitive in @strong{MySQL} for Windows. The only +restriction is that database and table names must be specified using the same +case throughout a given statement. @xref{Name case sensitivity}. + +@item The @samp{\} directory character +Pathname components in Win95 are separated by the @samp{\} character, which is +also the escape character in @strong{MySQL}. If you are using @code{LOAD +DATA INFILE} or @code{SELECT ... INTO OUTFILE}, you must double the @samp{\} +character: + +@example +mysql> LOAD DATA INFILE "C:\\tmp\\skr.txt" INTO TABLE skr; +mysql> SELECT * INTO OUTFILE 'C:\\tmp\\skr.txt' FROM skr; +@end example + +Alternatively, use Unix style filenames with @samp{/} characters: + +@example +mysql> LOAD DATA INFILE "C:/tmp/skr.txt" INTO TABLE skr; +mysql> SELECT * INTO OUTFILE 'C:/tmp/skr.txt' FROM skr; +@end example + +@item @code{Can't open named pipe} error +If you use a @strong{MySQL} 3.22 version on NT with the newest mysql-clients +you will get the following error: + +@example +error 2017: can't open named pipe to host: . pipe... +@end example + +@tindex .my.cnf file +This is because the release version of @strong{MySQL} uses named pipes on NT +by default. You can avoid this error by using the @code{--host=localhost} +option to the new @strong{MySQL} clients or create an option file +@file{C:\my.cnf} that contains the following information: + +@example +[client] +host = localhost +@end example + +@item @code{Access denied for user} error +If you get the error @code{Access denied for user: 'some-user@@unknown' +to database 'mysql'} when accessing a @strong{MySQL} server on the same +machine, this means that @strong{MySQL} can't resolve your host name +properly. + +To fix this, you should create a file @file{\windows\hosts} with the +following information: + +@example +127.0.0.1 localhost +@end example + +@item @code{ALTER TABLE} +While you are executing an @code{ALTER TABLE} statement, the table is locked +from usage by other threads. This has to do with the fact that on Windows, +you can't delete a file that is in use by another threads. (In the future, +we may find some way to work around this problem.) + +@item @code{DROP TABLE} on a table that is in use by a @code{MERGE} table will not work +The @code{MERGE} handler does its table mapping hidden from @strong{MySQL}. +Because Windows doesn't allow you to drop files that are open, you first +must flush all @code{MERGE} tables (with @code{FLUSH TABLES}) or drop the +@code{MERGE} table before dropping the table. We will fix this at the same +time we introduce @code{VIEW}s. +@end table + +Here are some open issues for anyone who might want to help us with the Windows +release: + +@cindex Windows, open issues + +@itemize @bullet +@item +Make a single-user @code{MYSQL.DLL} server. This should include everything in +a standard @strong{MySQL} server, except thread creation. This will make +@strong{MySQL} much easier to use in applications that don't need a true +client/server and don't need to access the server from other hosts. + +@item +Add some nice start and shutdown icons to the @strong{MySQL} installation. + +@item +Create a tool to manage registry entries for the @strong{MySQL} startup +options. The registry entry reading is already coded into @file{mysqld.cc}, +but it should be recoded to be more parameter oriented. The tool should +also be able to update the @file{C:\my.cnf} option file if the user prefers +to use that instead of the registry. + +@item +When registering @code{mysqld} as a service with @code{--install} (on NT) +it would be nice if you could also add default options on the command line. +For the moment, the workaround is to list the parameters in the +@file{C:\my.cnf} file instead. + +@item +It would be real nice to be able to kill @code{mysqld} from the task manager. +For the moment, you must use @code{mysqladmin shutdown}. + +@item +Port @code{readline} to Windows for use in the @code{mysql} command line tool. + +@item +GUI versions of the standard @strong{MySQL} clients (@code{mysql}, +@code{mysqlshow}, @code{mysqladmin}, and @code{mysqldump}) would be nice. + +@item +It would be nice if the socket read and write functions in @file{net.c} were +interruptible. This would make it possible to kill open threads with +@code{mysqladmin kill} on Windows. + +@item +@code{mysqld} always starts in the "C" locale and not in the default locale. +We would like to have @code{mysqld} use the current locale for the sort order. + +@item +Implement UDF functions with @code{.DLL}s. + +@item +Add macros to use the faster thread-safe increment/decrement methods +provided by Windows. + +@end itemize + +Other Windows-specific issues are described in the @file{README} file that +comes with the @strong{MySQL}-Windows distribution. + + +@node Solaris, Solaris 2.7, Windows, Operating System Specific Notes +@subsection Solaris Notes + +@cindex Solaris installation problems +@cindex problems, installing on Solaris +@cindex tar, problems on Solaris +@cindex errors, directory checksum +@cindex checksum errors + +On Solaris, you may run into trouble even before you get the @strong{MySQL} +distribution unpacked! Solaris @code{tar} can't handle long file names, so +you may see an error like this when you unpack @strong{MySQL}: + +@example +x mysql-3.22.12-beta/bench/Results/ATIS-mysql_odbc-NT_4.0-cmp-db2,informix,ms-sql,mysql,oracle,solid,sybase, 0 bytes, 0 tape blocks +tar: directory checksum error +@end example + +In this case, you must use GNU @code{tar} (@code{gtar}) to unpack the +distribution. You can find a precompiled copy for Solaris at +@uref{http://www.mysql.com/Downloads/}. + +Sun native threads work only on Solaris 2.5 and higher. For Version 2.4 and +earlier, @strong{MySQL} will automatically use MIT-pthreads. +@xref{MIT-pthreads}. + +If you get the following error from configure: + +@example +checking for restartable system calls... configure: error can not run test +programs while cross compiling +@end example + +This means that you have something wrong with your compiler installation! +In this case you should upgrade your compiler to a newer version. You may +also be able to solve this problem by inserting the following row into the +@file{config.cache} file: + +@example +ac_cv_sys_restartable_syscalls=$@{ac_cv_sys_restartable_syscalls='no'@} +@end example + +If you are using Solaris on a SPARC, the recommended compiler is +@code{gcc} 2.95.2. You can find this at @uref{http://gcc.gnu.org/}. +Note that @code{egcs} 1.1.1 and @code{gcc} 2.8.1 don't work reliably on +SPARC! + +The recommended @code{configure} line when using @code{gcc} 2.95.2 is: + +@example +CC=gcc CFLAGS="-O3" \ +CXX=gcc CXXFLAGS="-O3 -felide-constructors -fno-exceptions -fno-rtti" \ +./configure --prefix=/usr/local/mysql --with-low-memory --enable-assembler +@end example + +If you have a ultra sparc, you can get 4 % more performance by adding +"-mcpu=v8 -Wa,-xarch=v8plusa" to CFLAGS and CXXFLAGS. + +If you have the Sun Workshop (SunPro) 4.2 (or newer) compiler, you can +run @code{configure} like this: + +@example +CC=cc CFLAGS="-Xa -fast -xO4 -native -xstrconst -mt" \ +CXX=CC CXXFLAGS="-noex -xO4 -mt" \ +./configure --prefix=/usr/local/mysql --enable-assembler +@end example + +You may also have to edit the @code{configure} script to change this line: + +@example +#if !defined(__STDC__) || __STDC__ != 1 +@end example + +to this: + +@example +#if !defined(__STDC__) +@end example + +If you turn on @code{__STDC__} with the @code{-Xc} option, the Sun compiler +can't compile with the Solaris @file{pthread.h} header file. This is a Sun +bug (broken compiler or broken include file). + +If @code{mysqld} issues the error message shown below when you run it, you have +tried to compile @strong{MySQL} with the Sun compiler without enabling the +multi-thread option (@code{-mt}): + +@example +libc internal error: _rmutex_unlock: rmutex not held +@end example + +Add @code{-mt} to @code{CFLAGS} and @code{CXXFLAGS} and try again. + +If you get the following error when compiling @strong{MySQL} with @code{gcc}, +it means that your @code{gcc} is not configured for your version of Solaris: + +@example +shell> gcc -O3 -g -O2 -DDBUG_OFF -o thr_alarm ... +./thr_alarm.c: In function `signal_hand': +./thr_alarm.c:556: too many arguments to function `sigwait' +@end example + +The proper thing to do in this case is to get the newest version of +@code{gcc} and compile it with your current @code{gcc} compiler! At +least for Solaris 2.5, almost all binary versions of @code{gcc} have +old, unusable include files that will break all programs that use +threads (and possibly other programs)! + +Solaris doesn't provide static versions of all system libraries +(@code{libpthreads} and @code{libdl}), so you can't compile @strong{MySQL} +with @code{--static}. If you try to do so, you will get the error: + +@example +ld: fatal: library -ldl: not found + +or + +undefined reference to `dlopen' +@end example + +If too many processes try to connect very rapidly to @code{mysqld}, you will +see this error in the @strong{MySQL} log: + +@example +Error in accept: Protocol error +@end example + +You might try starting the server with the @code{--set-variable back_log=50} +option as a workaround for this. @xref{Command-line options}. + +If you are linking your own @strong{MySQL} client, you might get the +following error when you try to execute it: + +@example +ld.so.1: ./my: fatal: libmysqlclient.so.#: open failed: No such file or directory +@end example + +The problem can be avoided by one of the following methods: + +@itemize @bullet +@item +Link the client with the following flag (instead of @code{-Lpath}): +@code{-Wl,r/full-path-to-libmysqlclient.so}. + +@item +Copy @file{libmysqclient.so} to @file{/usr/lib}. + +@tindex LD_RUN_PATH environment variable +@tindex Environment variable, LD_RUN_PATH +@item +Add the pathname of the directory where @file{libmysqlclient.so} is located +to the @code{LD_RUN_PATH} environment variable before running your client. +@end itemize + +When using the @code{--with-libwrap} configure option, you must also +include the libraries that @file{libwrap.a} needs: + +@example +--with-libwrap="/opt/NUtcpwrapper-7.6/lib/libwrap.a -lnsl -lsocket +@end example + +If you have problems with configure trying to link with @code{-lz} and +you don't have @code{zlib} installed, you have two options: + +@itemize @bullet +@item +If you want to be able to use the compressed communication protocol, +you need to get and install zlib from ftp.gnu.org. + +@item +Configure with @code{--with-named-z-libs=no}. +@end itemize + +If you are using gcc and have problems with loading @code{UDF} functions +into @strong{MySQL}, try adding @code{-lgcc} to the link line for the +@code{UDF} function. + +If you would like @strong{MySQL} to start automatically, you can copy +@file{support-files/mysql.server} to @file{/etc/init.d} and create a +symbolic link to it named @file{/etc/rc3.d/S99mysql.server}. + + +@node Solaris 2.7, Solaris x86, Solaris, Operating System Specific Notes +@subsection Solaris 2.7/2.8 Notes + +You can normally use a Solaris 2.6 binary on Solaris 2.7 and 2.8. Most +of the Solaris 2.6 issues also apply for Solaris 2.7 and 2.8. + +Note that @strong{MySQL} Version 3.23.4 and above should be able to autodetect +new versions of Solaris and enable workarounds for the following problems! + +Solaris 2.7 / 2.8 has some bugs in the include files. You may see the +following error when you use @code{gcc}: + +@example +/usr/include/widec.h:42: warning: `getwc' redefined +/usr/include/wchar.h:326: warning: this is the location of the previous +definition +@end example + +If this occurs, you can do the following to fix the problem: + +Copy @code{/usr/include/widec.h} to +@code{.../lib/gcc-lib/os/gcc-version/include} and change line 41 from: + +@example +#if !defined(lint) && !defined(__lint) + +to + +#if !defined(lint) && !defined(__lint) && !defined(getwc) +@end example + +Alternatively, you can edit @file{/usr/include/widec.h} directly. Either +way, after you make the fix, you should remove @file{config.cache} and run +@code{configure} again! + +If you get errors like this when you run @code{make}, it's because +@code{configure} didn't detect the @file{curses.h} file (probably +because of the error in @file{/usr/include/widec.h}): + +@example +In file included from mysql.cc:50: +/usr/include/term.h:1060: syntax error before `,' +/usr/include/term.h:1081: syntax error before `;' +@end example + +The solution to this is to do one of the following: + +@itemize @bullet +@item +Configure with @code{CFLAGS=-DHAVE_CURSES_H CXXFLAGS=-DHAVE_CURSES_H ./configure}. + +@item +Edit @file{/usr/include/widec.h} as indicted above and rerun configure. + +@item +Remove the @code{#define HAVE_TERM} line from @file{config.h} file and +run @code{make} again. +@end itemize + +If you get a problem that your linker can't find @code{-lz} when linking +your client program, the problem is probably that your @file{libz.so} file is +installed in @file{/usr/local/lib}. You can fix this by one of the +following methods: + +@itemize @bullet +@item +Add @file{/usr/local/lib} to @code{LD_LIBRARY_PATH}. + +@item +Add a link to @file{libz.so} from @file{/lib}. + +@item +If you are using Solaris 8, you can install the optional zlib from your +Solaris 8 CD distribution. + +@item +Configure @strong{MySQL} with the @code{--with-named-z-libs=no} option. +@end itemize + + +@node Solaris x86, BSD Notes, Solaris 2.7, Operating System Specific Notes +@subsection Solaris x86 Notes + +On Solaris 2.8 on x86, @strong{mysqld} will core dump if you run +'strip' in. + +If you are using @code{gcc} or @code{egcs} on Solaris x86 and you +experience problems with core dumps under load, you should use the +following @code{configure} command: + +@example +CC=gcc CFLAGS="-O3 -fomit-frame-pointer -DHAVE_CURSES_H" \ +CXX=gcc \ +CXXFLAGS="-O3 -fomit-frame-pointer -felide-constructors -fno-exceptions -fno-rtti -DHAVE_CURSES_H" \ +./configure --prefix=/usr/local/mysql +@end example + +This will avoid problems with the @code{libstdc++} library and with C++ +exceptions. + +If this doesn't help, you should compile a debug version and run +it with a trace file or under @code{gdb}. @xref{Using gdb on mysqld}. + + +@node BSD Notes, Mac OS X, Solaris x86, Operating System Specific Notes +@subsection BSD Notes + +@menu +* FreeBSD:: +* NetBSD:: +* OpenBSD:: +* OpenBSD 2.5:: +* OpenBSD 2.8:: +* BSDI:: +* BSDI2:: +* BSDI3:: +* BSDI4:: +@end menu + + +@node FreeBSD, NetBSD, BSD Notes, BSD Notes +@subsubsection FreeBSD Notes + +FreeBSD 3.x is recommended for running @strong{MySQL} since the thread package +is much more integrated. + +The easiest and therefor the preferred way to install is to use the +mysql-server and mysql-client ports available on @uref{http://www.freebsd.org}. + +Using these gives you: +@itemize @bullet +@item +A working @strong{MySQL} with all optimizations known to work on your version +of FreeBSD enabled. + +@item +Automatic configuration and build. + +@item +Startup scripts installed in /usr/local/etc/rc.d. + +@item +Ability to see which files that are installed with pkg_info -L. And to +remove them all with pkg_delete if you no longer want @strong{MySQL} on that +machine. +@end itemize + +It is recommended you use MIT-pthreads on FreeBSD 2.x and native threads on +Versions 3 and up. It is possible to run with native threads on some late +2.2.x versions but you may encounter problems shutting down @code{mysqld}. + +The @strong{MYSQL} Makefiles require GNU make (@code{gmake}) to work. +If you want to compile @strong{MYSQL} you need to install GNU make +first. + +Be sure to have your name resolver setup correct. Otherwise you may +experience resolver delays or failures when connecting to @code{mysqld}. + +Make sure that the @code{localhost} entry in the @file{/etc/hosts} file is +correct (otherwise you will have problems connecting to the database). The +@file{/etc/hosts} file should start with a line: + +@example +127.0.0.1 localhost localhost.your.domain +@end example + +If you notice that @code{configure} will use MIT-pthreads, you should read +the MIT-pthreads notes. @xref{MIT-pthreads}. + +If you get an error from @code{make install} that it can't find +@file{/usr/include/pthreads}, @code{configure} didn't detect that you need +MIT-pthreads. This is fixed by executing these commands: + +@example +shell> rm config.cache +shell> ./configure --with-mit-threads +@end example + +FreeBSD is also known to have a very low default file handle limit. +@xref{Not enough file handles}. Uncomment the ulimit -n section in +safe_mysqld or raise the limits for the @code{mysqld} user in /etc/login.conf +(and rebuild it with cap_mkdb /etc/login.conf). Also be sure you set the +appropriate class for this user in the password file if you are not +using the default (use: chpass mysqld-user-name). @xref{safe_mysqld, , +@code{safe_mysqld}}. + +If you get problems with the current date in @strong{MySQL}, setting the +@code{TZ} variable will probably help. @xref{Environment variables}. + +To get a secure and stable system you should only use FreeBSD kernels +that are marked @code{-STABLE}. + + +@node NetBSD, OpenBSD, FreeBSD, BSD Notes +@subsubsection NetBSD notes + +To compile on NetBSD you need GNU @code{make}. Otherwise the compile will +crash when @code{make} tries to run @code{lint} on C++ files. + + +@node OpenBSD, OpenBSD 2.5, NetBSD, BSD Notes +@subsubsection OpenBSD Notes + +@menu +* OpenBSD 2.5:: OpenBSD 2.5 Notes +* OpenBSD 2.8:: OpenBSD 2.8 Notes +@end menu + +@node OpenBSD 2.5, OpenBSD 2.8, OpenBSD, BSD Notes +@subsubsection OpenBSD 2.5 Notes + +On OpenBSD Version 2.5, you can compile @strong{MySQL} with native threads +with the following options: + +@example +CFLAGS=-pthread CXXFLAGS=-pthread ./configure --with-mit-threads=no +@end example + +@node OpenBSD 2.8, BSDI, OpenBSD 2.5, BSD Notes +@subsubsection OpenBSD 2.8 Notes + +Our users have reported that OpenBSD 2.8 has a threading bug which causes +problems with @strong{MySQL}. The OpenBSD Developers have fixed the problem, +but as of January 25th, 2001, it's only available in the ``-current'' branch. +The symptoms of this threading bug are: slow response, high load, high CPU +usage, and crashes. + + +@node BSDI, BSDI2, OpenBSD 2.8, BSD Notes +@subsubsection BSD/OS Notes + +@menu +* BSDI2:: BSD/OS 2.x notes +* BSDI3:: BSD/OS 3.x notes +* BSDI4:: BSD/OS 4.x notes +@end menu + +@node BSDI2, BSDI3, BSDI, BSD Notes +@subsubsection BSD/OS Version 2.x Notes + +If you get the following error when compiling @strong{MySQL}, your +@code{ulimit} value for virtual memory is too low: + +@example +item_func.h: In method `Item_func_ge::Item_func_ge(const Item_func_ge &)': +item_func.h:28: virtual memory exhausted +make[2]: *** [item_func.o] Error 1 +@end example + +Try using @code{ulimit -v 80000} and run @code{make} again. If this +doesn't work and you are using @code{bash}, try switching to @code{csh} +or @code{sh}; some BSDI users have reported problems with @code{bash} +and @code{ulimit}. + +If you are using @code{gcc}, you may also use have to use the +@code{--with-low-memory} flag for @code{configure} to be able to compile +@file{sql_yacc.cc}. + +If you get problems with the current date in @strong{MySQL}, setting the +@code{TZ} variable will probably help. @xref{Environment variables}. + +@node BSDI3, BSDI4, BSDI2, BSD Notes +@subsubsection BSD/OS Version 3.x Notes + +Upgrade to BSD/OS Version 3.1. If that is not possible, install +BSDIpatch M300-038. + +Use the following command when configuring @strong{MySQL}: + +@example +shell> env CXX=shlicc++ CC=shlicc2 \ + ./configure \ + --prefix=/usr/local/mysql \ + --localstatedir=/var/mysql \ + --without-perl \ + --with-unix-socket-path=/var/mysql/mysql.sock +@end example + +The following is also known to work: + +@example +shell> env CC=gcc CXX=gcc CXXFLAGS=-O3 \ + ./configure \ + --prefix=/usr/local/mysql \ + --with-unix-socket-path=/var/mysql/mysql.sock +@end example + +You can change the directory locations if you wish, or just use the +defaults by not specifying any locations. + +If you have problems with performance under heavy load, try using the +@code{--skip-thread-priority} option to @code{mysqld}! This will run +all threads with the same priority; on BSDI Version 3.1, this gives better +performance (at least until BSDI fixes their thread scheduler). + +If you get the error @code{virtual memory exhausted} while compiling, +you should try using @code{ulimit -v 80000} and run @code{make} again. +If this doesn't work and you are using @code{bash}, try switching to +@code{csh} or @code{sh}; some BSDI users have reported problems with +@code{bash} and @code{ulimit}. + +@node BSDI4, , BSDI3, BSD Notes +@subsubsection BSD/OS Version 4.x Notes + +BSDI Version 4.x has some thread-related bugs. If you want to use +@strong{MySQL} on this, you should install all thread-related patches. At +least M400-023 should be installed. + +On some BSDI Version 4.x systems, you may get problems with shared libraries. +The symptom is that you can't execute any client programs, for example, +@code{mysqladmin}. In this case you need to reconfigure not to use +shared libraries with the @code{--disable-shared} option to configure. + +Some customers have had problems on BSDI 4.0.1 that the @code{mysqld} +binary after a while can't open tables. This is because some +library/system related bug causes @code{mysqld} to change current +directory without asking for this! + +The fix is to either upgrade to 3.23.34 or after running @code{configure} +remove the line @code{#define HAVE_REALPATH} from @code{config.h} +before running make. + +Note that the above means that you can't symbolic link a database directories +to another database directory or symbolic link a table to another database +on BSDI! (Making a symbolic link to another disk is ok). + + +@node Mac OS X, Other Unix Notes, BSD Notes, Operating System Specific Notes +@subsection Mac OS X Notes + +@menu +* Mac OS X Public Beta:: +* Mac OS X Server:: +@end menu + + +@node Mac OS X Public Beta, Mac OS X Server, Mac OS X, Mac OS X +@subsubsection Mac OS X Public Beta + +@strong{MySQL} should work without any problems on Mac OS X Public Beta +(Darwin). You don't need the pthread patches for this OS! + + +@node Mac OS X Server, , Mac OS X Public Beta, Mac OS X +@subsubsection Mac OS X Server + +Before trying to configure @strong{MySQL} on Mac OS X server you must +first install the pthread package from +@uref{http://www.prnet.de/RegEx/mysql.html}. + +Our binary for Mac OS X is compiled on Rhapsody 5.5 with the following +configure line: + +@example +CC=gcc CFLAGS="-O2 -fomit-frame-pointer" CXX=gcc CXXFLAGS="-O2 -fomit-frame-pointer" ./configure --prefix=/usr/local/mysql "--with-comment=Official MySQL binary" --with-extra-charsets=complex --disable-shared +@end example + +You might want to also add aliases to your shell's resource file to +access @code{mysql} and @code{mysqladmin} from the command line: + +@example +alias mysql '/usr/local/mysql/bin/mysql' +alias mysqladmin '/usr/local/mysql/bin/mysqladmin' +@end example + + +@node Other Unix Notes, SCO Unixware, Mac OS X, Operating System Specific Notes +@subsection Other Unix Notes + +@menu +* Binary notes-HP-UX:: +* HP-UX 10.20:: +* HP-UX 11.x:: +* IBM-AIX:: +* SunOS:: +* Alpha-DEC-UNIX:: +* Alpha-DEC-OSF1:: +* SGI-Irix:: +* SCO:: +@end menu + + +@node Binary notes-HP-UX, HP-UX 10.20, Other Unix Notes, Other Unix Notes +@subsubsection HP-UX Notes for Binary Distributions + +@cindex HP-UX, binary distribution +@cindex binary distributions, on HP-UX + +Some of the binary distributions of @strong{MySQL} for HP-UX is +distributed as an HP depot file and as a tar file. To use the depot +file you must be running at least HP-UX 10.x to have access to HP's +software depot tools. + +The HP version of @strong{MySQL} was compiled on an HP 9000/8xx server +under HP-UX 10.20, and uses MIT-pthreads. It is known to work well under +this configuration. @strong{MySQL} Version 3.22.26 and newer can also be +built with HP's native thread package. + +Other configurations that may work: + +@itemize @bullet +@item +HP 9000/7xx running HP-UX 10.20+ +@item +HP 9000/8xx running HP-UX 10.30 +@end itemize + +The following configurations almost definitely won't work: + +@itemize @bullet +@item +HP 9000/7xx or 8xx running HP-UX 10.x where x < 2 +@item +HP 9000/7xx or 8xx running HP-UX 9.x +@end itemize + +To install the distribution, use one of the commands below, where +@code{/path/to/depot} is the full pathname of the depot file: + +@itemize @bullet +@item +To install everything, including the server, client and development tools: + +@example +shell> /usr/sbin/swinstall -s /path/to/depot mysql.full +@end example + +@item +To install only the server: + +@example +shell> /usr/sbin/swinstall -s /path/to/depot mysql.server +@end example + +@item +To install only the client package: + +@example +shell> /usr/sbin/swinstall -s /path/to/depot mysql.client +@end example + +@item +To install only the development tools: + +@example +shell> /usr/sbin/swinstall -s /path/to/depot mysql.developer +@end example +@end itemize + +The depot places binaries and libraries in @file{/opt/mysql} and data in +@file{/var/opt/mysql}. The depot also creates the appropriate entries in +@file{/etc/init.d} and @file{/etc/rc2.d} to start the server automatically +at boot time. Obviously, this entails being @code{root} to install. + +To install the HP-UX tar.gz distribution, you must have a copy of GNU +@code{tar}. + + +@node HP-UX 10.20, HP-UX 11.x, Binary notes-HP-UX, Other Unix Notes +@subsubsection HP-UX Version 10.20 Notes + +There are a couple of small problems when compiling @strong{MySQL} on +HP-UX. We recommend that you use @code{gcc} instead of the HP-UX native +compiler, because @code{gcc} produces better code! + +We recommend using gcc 2.95 on HP-UX. Don't use high optimization +flags (like -O6) as this may not be safe on HP-UX. + +Note that MIT-pthreads can't be compiled with the HP-UX compiler +because it can't compile @code{.S} (assembler) files. + +The following configure line should work: + +@example +CFLAGS="-DHPUX -I/opt/dce/include" CXXFLAGS="-DHPUX -I/opt/dce/include -felide-constructors -fno-exceptions -fno-rtti" CXX=gcc ./configure --with-pthread --with-named-thread-libs='-ldce' --prefix=/usr/local/mysql --disable-shared +@end example + +If you are compiling @code{gcc} 2.95 yourself, you should NOT link it with +the DCE libraries (@code{libdce.a} or @code{libcma.a}) if you want to compile +@strong{MySQL} with MIT-pthreads. If you mix the DCE and MIT-pthreads +packages you will get a @code{mysqld} to which you cannot connect. Remove +the DCE libraries while you compile @code{gcc} 2.95! + + +@node HP-UX 11.x, IBM-AIX, HP-UX 10.20, Other Unix Notes +@subsubsection HP-UX Version 11.x Notes + +For HP-UX Version 11.x we recommend @strong{MySQL} Version 3.23.15 or later. + +Because of some critical bugs in the standard HP-UX libraries, you should +install the following patches before trying to run @strong{MySQL} on HP-UX 11.0: + +@example +PHKL_22840 Streams cumulative +PHNE_22397 ARPA cumulative +@end example + +This will solve a problem that one gets @code{EWOULDBLOCK} from @code{recv()} +and @code{EBADF} from @code{accept()} in threaded applications. + +If you are using @code{gcc} 2.95.1 on an unpatched HP-UX 11.x system, +you will get the error: + +@example +In file included from /usr/include/unistd.h:11, + from ../include/global.h:125, + from mysql_priv.h:15, + from item.cc:19: +/usr/include/sys/unistd.h:184: declaration of C function ... +/usr/include/sys/pthread.h:440: previous declaration ... +In file included from item.h:306, + from mysql_priv.h:158, + from item.cc:19: +@end example + +The problem is that HP-UX doesn't define @code{pthreads_atfork()} consistently. +It has conflicting prototypes in +@file{/usr/include/sys/unistd.h}:184 and +@file{/usr/include/sys/pthread.h}:440 (details below). + +One solution is to copy @file{/usr/include/sys/unistd.h} into +@file{mysql/include} and edit @file{unistd.h} and change it to match +the definition in @file{pthread.h}. Here's the diff: + +@example +183,184c183,184 +< extern int pthread_atfork(void (*prepare)(), void (*parent)(), +< void (*child)()); +--- +> extern int pthread_atfork(void (*prepare)(void), void (*parent)(void), +> void (*child)(void)); +@end example + +After this, the following configure line should work: + +@example +CFLAGS="-fomit-frame-pointer -O3 -fpic" CXX=gcc CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti -O3" ./configure --prefix=/usr/local/mysql --disable-shared +@end example + +Here is some information that a HP-UX Version 11.x user sent us about compiling +@strong{MySQL} with HP-UX:x compiler: + +@example + Environment: + proper compilers. + setenv CC cc + setenv CXX aCC + flags + setenv CFLAGS -D_REENTRANT + setenv CXXFLAGS -D_REENTRANT + setenv CPPFLAGS -D_REENTRANT + % aCC -V + aCC: HP ANSI C++ B3910B X.03.14.06 + % cc -V /tmp/empty.c + cpp.ansi: HP92453-01 A.11.02.00 HP C Preprocessor (ANSI) + ccom: HP92453-01 A.11.01.00 HP C Compiler + cc: "/tmp/empty.c", line 1: warning 501: Empty source file. + + configuration: + ./configure --with-pthread \ + --prefix=/source-control/mysql \ + --with-named-thread-libs=-lpthread \ + --with-low-memory + + added '#define _CTYPE_INCLUDED' to include/m_ctype.h. This + symbol is the one defined in HP's /usr/include/ctype.h: + + /* Don't include std ctype.h when this is included */ + #define _CTYPE_H + #define __CTYPE_INCLUDED + #define _CTYPE_INCLUDED + #define _CTYPE_USING /* Don't put names in global namespace. */ +@end example + +@itemize @bullet +@item +I had to use the compile-time flag @code{-D_REENTRANT} to get the compiler +to recognize the prototype for @code{localtime_r}. Alternatively I could have +supplied the prototype for @code{localtime_r}. But I wanted to catch other +bugs without needing to run into them. I wasn't sure where I needed it, so I +added it to all flags. +@item +The optimization flags used by @strong{MySQL} (-O3) are not recognized by HP's +compilers. I did not change the flags. +@end itemize + +If you get the following error from @code{configure} + +@example +checking for cc option to accept ANSI C... no +configure: error: MySQL requires a ANSI C compiler (and a C++ compiler). Try gcc. See the Installation chapter in the Reference Manual. +@end example + +Check that you don't have the path to the K&R compiler before the path +to the HP-UX C and C++ compiler. + + +@node IBM-AIX, SunOS, HP-UX 11.x, Other Unix Notes +@subsubsection IBM-AIX notes + +@cindex problems, installing on IBM-AIX + +Automatic detection of @code{xlC} is missing from Autoconf, so a +@code{configure} command something like this is needed when compiling +@strong{MySQL} (This example uses the IBM compiler): + +@example +export CC="xlc_r -ma -O3 -qstrict -qoptimize=3 -qmaxmem=8192 " +export CXX="xlC_r -ma -O3 -qstrict -qoptimize=3 -qmaxmem=8192" +export CFLAGS="-I /usr/local/include" +export LDLFAGS="-L /usr/local/lib" +export CPPFLAGS=$CFLAGS +export CXXFLAGS=$CFLAGS + +./configure --prefix=/usr/local \ + --localstatedir=/var/mysql \ + --sysconfdir=/etc/mysql \ + --sbindir='/usr/local/bin' \ + --libexecdir='/usr/local/bin' \ + --enable-thread-safe-client \ + --enable-large-files +@end example + +Above are the options used to compile the @strong{MySQL} distribution that +can be found at @uref{http://www-frec.bull.com/}. + +If you change the @code{-O3} to @code{-O2} in the above configure line, +you must also remove the @code{-qstrict} option (this is a limitation in +the IBM C compiler). + +If you are using @code{gcc} or @code{egcs} to compile @strong{MySQL}, you +@strong{MUST} use the @code{-fno-exceptions} flag, as the exception +handling in @code{gcc}/@code{egcs} is not thread safe! (This is tested with +@code{egcs} 1.1.). There are also some known problems with IBM's assembler, +which may cause it to generate bad code when used with gcc. + +We recommend the following @code{configure} line with @code{egcs} and +@code{gcc 2.95} on AIX: + +@example +CC="gcc -pipe -mcpu=power -Wa,-many" \ +CXX="gcc -pipe -mcpu=power -Wa,-many" \ +CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti" \ +./configure --prefix=/usr/local/mysql --with-low-memory +@end example + +The @code{-Wa,-many} is necessary for the compile to be successful. IBM is +aware of this problem but is in to hurry to fix it because of the workaround +available. We don't know if the @code{-fno-exceptions} is required with +@code{gcc 2.95}, but as @strong{MySQL} doesn't use exceptions and the above +option generates faster code, we recommend that you should always use this +option with @code{egcs / gcc}. + +If you get a problem with assembler code try changing the -mcpu=xxx to +match your cpu. Typically power2, power, or powerpc may need to be used, +alternatively you might need to use 604 or 604e. I'm not positive but I +would think using "power" would likely be safe most of the time, even on +a power2 machine. + +If you don't know what your cpu is then do a "uname -m", this will give +you back a string that looks like "000514676700", with a format of +xxyyyyyymmss where xx and ss are always 0's, yyyyyy is a unique system +id and mm is the id of the CPU Planar. A chart of these values can be +found at +@uref{http://www.rs6000.ibm.com/doc_link/en_US/a_doc_lib/cmds/aixcmds5/uname.htm}. +This will give you a machine type and a machine model you can use to +determine what type of cpu you have. + +If you have problems with signals (@strong{MySQL} dies unexpectedly +under high load) you may have found an OS bug with threads and +signals. In this case you can tell @strong{MySQL} not to use signals by +configuring with: + +@example +shell> CFLAGS=-DDONT_USE_THR_ALARM CXX=gcc \ + CXXFLAGS="-felide-constructors -fno-exceptions -fno-rtti -DDONT_USE_THR_ALARM" \ + ./configure --prefix=/usr/local/mysql --with-debug --with-low-memory +@end example + +This doesn't affect the performance of @strong{MySQL}, but has the side +effect that you can't kill clients that are ``sleeping'' on a connection with +@code{mysqladmin kill} or @code{mysqladmin shutdown}. Instead, the client +will die when it issues its next command. + +On some versions of AIX, linking with @code{libbind.a} makes +@code{getservbyname} core dump. This is an AIX bug and should be reported +to IBM. + +For AIX 4.2.1 and gcc you have to do the following changes. + +After configuring, edit @file{config.h} and @file{include/my_config.h} +and change the line that says + +@example +#define HAVE_SNPRINTF 1 +@end example + +to + +@example +#undef HAVE_SNPRINTF +@end example + +And finally, in @file{mysqld.cc} you need to add a prototype for initgoups. + +@example +#ifdef _AIX41 +extern "C" int initgroups(const char *,int); +#endif +@end example + + +@node SunOS, Alpha-DEC-UNIX, IBM-AIX, Other Unix Notes +@subsubsection SunOS 4 Notes + +On SunOS 4, MIT-pthreads is needed to compile @strong{MySQL}, which in turn +means you will need GNU @code{make}. + +Some SunOS 4 systems have problems with dynamic libraries and @code{libtool}. +You can use the following @code{configure} line to avoid this problem: + +@example +shell> ./configure --disable-shared --with-mysqld-ldflags=-all-static +@end example + +When compiling @code{readline}, you may get warnings about duplicate defines. +These may be ignored. + +When compiling @code{mysqld}, there will be some @code{implicit declaration +of function} warnings. These may be ignored. + + +@node Alpha-DEC-UNIX, Alpha-DEC-OSF1, SunOS, Other Unix Notes +@subsubsection Alpha-DEC-UNIX Notes (Tru64) + +If you are using egcs 1.1.2 on Digital Unix, you should upgrade to gcc +2.95.2, as egcs on DEC has some serious bugs! + +When compiling threaded programs under Digital Unix, the documentation +recommends using the @code{-pthread} option for @code{cc} and @code{cxx} and +the libraries @code{-lmach -lexc} (in addition to @code{-lpthread}). You +should run @code{configure} something like this: + +@example +CC="cc -pthread" CXX="cxx -pthread -O" \ +./configure --with-named-thread-libs="-lpthread -lmach -lexc -lc" +@end example + +When compiling @code{mysqld}, you may see a couple of warnings like this: + +@example +mysqld.cc: In function void handle_connections()': +mysqld.cc:626: passing long unsigned int *' as argument 3 of +accept(int,sockadddr *, int *)' +@end example + +You can safely ignore these warnings. They occur because @code{configure} +can detect only errors, not warnings. + +If you start the server directly from the command line, you may have problems +with it dying when you log out. (When you log out, your outstanding processes +receive a @code{SIGHUP} signal.) If so, try starting the server like this: + +@example +shell> nohup mysqld [options] & +@end example + +@code{nohup} causes the command following it to ignore any @code{SIGHUP} +signal sent from the terminal. Alternatively, start the server by running +@code{safe_mysqld}, which invokes @code{mysqld} using @code{nohup} for you. +@xref{safe_mysqld, , @code{safe_mysqld}}. + +If you get a problem when compiling mysys/get_opt.c, just remove the +line #define _NO_PROTO from the start of that file! + +If you are using Compac's CC compiler, the following configure line should +work: + +@example +CC="cc -pthread" +CFLAGS="-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host" +CXX="cxx -pthread" +CXXFLAGS="-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host" +export CC CFLAGS CXX CXXFLAGS +./configure \ +--prefix=/usr/local/mysql \ +--with-low-memory \ +--enable-large-files \ +--enable-shared=yes \ +--with-named-thread-libs="-lpthread -lmach -lexc -lc" +gnumake +@end example + +If you get a problem with libtool, when compiling with shared libraries +as above, when linking @code{mysql}, you should be able to get around +this by issuing: + +@example +cd mysql +/bin/sh ../libtool --mode=link cxx -pthread -O3 -DDBUG_OFF \ +-O4 -ansi_alias -ansi_args -fast -inline speed \ +-speculate all \ -arch host -DUNDEF_HAVE_GETHOSTBYNAME_R \ +-o mysql mysql.o readline.o sql_string.o completion_hash.o \ +../readline/libreadline.a -lcurses \ +../libmysql/.libs/libmysqlclient.so -lm +cd .. +gnumake +gnumake install +scripts/mysql_install_db +@end example + + +@node Alpha-DEC-OSF1, SGI-Irix, Alpha-DEC-UNIX, Other Unix Notes +@subsubsection Alpha-DEC-OSF1 Notes + +If you have problems compiling and have DEC @code{CC} and @code{gcc} +installed, try running @code{configure} like this: + +@example +CC=cc CFLAGS=-O CXX=gcc CXXFLAGS=-O3 \ +./configure --prefix=/usr/local/mysql +@end example + +If you get problems with the @file{c_asm.h} file, you can create and use +a 'dummy' @file{c_asm.h} file with: + +@example +touch include/c_asm.h +CC=gcc CFLAGS=-I./include \ +CXX=gcc CXXFLAGS=-O3 \ +./configure --prefix=/usr/local/mysql +@end example + +Note that the following problems with the @code{ld} program can be fixed +by downloading the latest DEC (Compaq) patch kit from: +@uref{http://ftp.support.compaq.com/public/unix/}. + +On OSF1 V4.0D and compiler "DEC C V5.6-071 on Digital Unix V4.0 (Rev. 878)" +the compiler had some strange behavior (undefined @code{asm} symbols). +@code{/bin/ld} also appears to be broken (problems with @code{_exit +undefined} errors occuring while linking @code{mysqld}). On this system, we +have managed to compile @strong{MySQL} with the following @code{configure} +line, after replacing @code{/bin/ld} with the version from OSF 4.0C: + +@example +CC=gcc CXX=gcc CXXFLAGS=-O3 ./configure --prefix=/usr/local/mysql +@end example + +With the Digital compiler "C++ V6.1-029", the following should work: + +@example +CC=cc -pthread +CFLAGS=-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host +CXX=cxx -pthread +CXXFLAGS=-O4 -ansi_alias -ansi_args -fast -inline speed -speculate all -arch host -noexceptions -nortti +export CC CFLAGS CXX CXXFLAGS +./configure --prefix=/usr/mysql/mysql --with-mysqld-ldflags=-all-static --disable-shared --with-named-thread-libs="-lmach -lexc -lc" +@end example + +In some versions of OSF1, the @code{alloca()} function is broken. Fix +this by removing the line in @file{config.h} that defines @code{'HAVE_ALLOCA'}. + +The @code{alloca()} function also may have an incorrect prototype in +@code{/usr/include/alloca.h}. This warning resulting from this can be ignored. + +@code{configure} will use the following thread libraries automatically: +@code{--with-named-thread-libs="-lpthread -lmach -lexc -lc"}. + +When using @code{gcc}, you can also try running @code{configure} like this: + +@example +shell> CFLAGS=-D_PTHREAD_USE_D4 CXX=gcc CXXFLAGS=-O3 ./configure .... +@end example + +If you have problems with signals (@strong{MySQL} dies unexpectedly +under high load), you may have found an OS bug with threads and +signals. In this case you can tell @strong{MySQL} not to use signals by +configuring with: + +@example +shell> CFLAGS=-DDONT_USE_THR_ALARM \ + CXXFLAGS=-DDONT_USE_THR_ALARM \ + ./configure ... +@end example + +This doesn't affect the performance of @strong{MySQL}, but has the side +effect that you can't kill clients that are ``sleeping'' on a connection with +@code{mysqladmin kill} or @code{mysqladmin shutdown}. Instead, the client +will die when it issues its next command. + +With @code{gcc} 2.95.2, you will probably run into the following compile error: + +@example +sql_acl.cc:1456: Internal compiler error in `scan_region', at except.c:2566 +Please submit a full bug report. +@end example + +To fix this you should change to the @code{sql} directory and do a ``cut +and paste'' of the last @code{gcc} line, but change @code{-O3} to +@code{-O0} (or add @code{-O0} immediately after @code{gcc} if you don't +have any @code{-O} option on your compile line.) After this is done you +can just change back to the top-level directly and run @code{make} +again. + + +@node SGI-Irix, SCO, Alpha-DEC-OSF1, Other Unix Notes +@subsubsection SGI Irix Notes + +If you are using Irix Version 6.5.3 or newer @code{mysqld} will only be able to +create threads if you run it as a user with @code{CAP_SCHED_MGT} +privileges (like @code{root}) or give the @code{mysqld} server this privilege +with the following shell command: + +@example +shell> chcap "CAP_SCHED_MGT+epi" /opt/mysql/libexec/mysqld +@end example + +You may have to undefine some things in @file{config.h} after running +@code{configure} and before compiling. + +In some Irix implementations, the @code{alloca()} function is broken. If the +@code{mysqld} server dies on some @code{SELECT} statements, remove the lines +from @file{config.h} that define @code{HAVE_ALLOC} and @code{HAVE_ALLOCA_H}. +If @code{mysqladmin create} doesn't work, remove the line from @file{config.h} +that defines @code{HAVE_READDIR_R}. You may have to remove the +@code{HAVE_TERM_H} line as well. + +SGI recommends that you install all of the patches on this page as a set: +http://support.sgi.com/surfzone/patches/patchset/6.2_indigo.rps.html + +At the very minimum, you should install the latest kernel rollup, the +latest @code{rld} rollup, and the latest @code{libc} rollup. + +You definitely need all the POSIX patches on this page, for pthreads support: + +@uref{http://support.sgi.com/surfzone/patches/patchset/6.2_posix.rps.html} + +If you get the something like the following error when compiling +@file{mysql.cc}: + +@example +"/usr/include/curses.h", line 82: error(1084): invalid combination of type +@end example + +Type the following in the top-level directory of your @strong{MySQL} source +tree: + +@example +shell> extra/replace bool curses_bool < /usr/include/curses.h > include/curses.h +shell> make +@end example + +There have also been reports of scheduling problems. If only one thread is +running, things go slow. Avoid this by starting another client. This may +lead to a 2-to-10-fold increase in execution speed thereafter for the other +thread. This is a poorly understood problem with Irix threads; you may have +to improvise to find solutions until this can be fixed. + +If you are compiling with @code{gcc}, you can use the following +@code{configure} command: + +@example +CC=gcc CXX=gcc CXXFLAGS=-O3 \ +./configure --prefix=/usr/local/mysql --with-thread-safe-client --with-named-thread-libs=-lpthread +@end example + +On Irix 6.5.11 with native Irix C and C++ compilers ver. 7.3.1.2, the +following is reported to work + +@example +CC=cc CXX=CC CFLAGS='-O3 -n32 -TARG:platform=IP22 -I/usr/local/include \ +-L/usr/local/lib' CXXFLAGS='-O3 -n32 -TARG:platform=IP22 \ +-I/usr/local/include -L/usr/local/lib' ./configure --prefix=/usr/local/mysql \ +--with-berkeley-db --with-innodb \ +--with-libwrap=/usr/local --with-named-curses-libs=/usr/local/lib/libncurses.a +@end example + + +@node SCO, , SGI-Irix, Other Unix Notes +@subsubsection SCO Notes + +The current port is tested only on a ``sco3.2v5.0.4'' and +``sco3.2v5.0.5'' system. There has also been a lot of progress on a +port to ``sco 3.2v4.2''. + +For the moment the recommended compiler on OpenServer is gcc 2.95.2. With this +you should be able to compile @strong{MySQL} with just: + +@example +CC=gcc CXX=gcc ./configure ... (options) +@end example + +@enumerate +@item +For OpenServer 5.0.X you need to use GDS in Skunkware 95 (95q4c). This +is necessary because GNU @code{gcc} 2.7.2 in Skunkware 97 does not have +GNU @code{as}. You can also use @code{egcs} 1.1.2 or newer +@uref{http://www.egcs.com/}. If you are using @code{egcs} 1.1.2 you have +to execute the following command: + +@example +shell> cp -p /usr/include/pthread/stdtypes.h /usr/local/lib/gcc-lib/i386-pc-sco3.2v5.0.5/egcs-2.91.66/include/pthread/ +@end example + +@item +You need the port of GCC 2.5.x for this product and the Development +system. They are required on this version of SCO Unix. You cannot +just use the GCC Dev system. + +@item +You should get the FSU Pthreads package and install it first. This can be +found at +@uref{http://www.cs.wustl.edu/~schmidt/ACE_wrappers/FSU-threads.tar.gz}. +You can also get a precompiled package from +@uref{http://www.mysql.com/Downloads/SCO/FSU-threads-3.5c.tar.gz}. + +@item +FSU Pthreads can be compiled with SCO Unix 4.2 with tcpip. Or +OpenServer 3.0 or Open Desktop 3.0 (OS 3.0 ODT 3.0), with the SCO +Development System installed using a good port of GCC 2.5.x ODT or OS +3.0 you will need a good port of GCC 2.5.x There are a lot of problems +without a good port. The port for this product requires the SCO Unix +Development system. Without it, you are missing the libraries and the +linker that is needed. + +@item +To build FSU Pthreads on your system, do the following: + +@enumerate a +@item +Run @code{./configure} in the @file{threads/src} directory and select +the SCO OpenServer option. This command copies @file{Makefile.SCO5} to +@file{Makefile}. + +@item +Run @code{make}. + +@item +To install in the default @file{/usr/include} directory, login as root, +then @code{cd} to the @file{thread/src} directory, and run @code{make +install}. +@end enumerate + +@item +Remember to use GNU @code{make} when making @strong{MySQL}. + +@item +If you don't start @code{safe_mysqld} as root, you probably will get only the +default 110 open files per process. @code{mysqld} will write a note about this +in the log file. + +@item +With SCO 3.2V5.0.5, you should use FSU Pthreads version 3.5c or newer. +You should also use gcc 2.95.2 or newer! + +The following @code{configure} command should work: + +@example +shell> ./configure --prefix=/usr/local/mysql --disable-shared +@end example + +@item +With SCO 3.2V4.2, you should use FSU Pthreads version 3.5c or newer. +The following @code{configure} command should work: + +@example +shell> CFLAGS="-D_XOPEN_XPG4" CXX=gcc CXXFLAGS="-D_XOPEN_XPG4" \ + ./configure \ + --prefix=/usr/local/mysql \ + --with-named-thread-libs="-lgthreads -lsocket -lgen -lgthreads" \ + --with-named-curses-libs="-lcurses" +@end example + +You may get some problems with some include files. In this case, you can +find new SCO-specific include files at +@uref{http://www.mysql.com/Downloads/SCO/SCO-3.2v4.2-includes.tar.gz}. +You should unpack this file in the @file{include} directory of your +@strong{MySQL} source tree. +@end enumerate + +SCO development notes: + +@itemize @bullet +@item +@strong{MySQL} should automatically detect FSU Pthreads and link @code{mysqld} +with @code{-lgthreads -lsocket -lgthreads}. + +@item +The SCO development libraries are re-entrant in FSU Pthreads. SCO claims +that its libraries' functions are re-entrant, so they must be reentrant with +FSU Pthreads. FSU Pthreads on OpenServer tries to use the SCO scheme to +make re-entrant libraries. + +@item +FSU Pthreads (at least the version at @uref{http://www.mysql.com/}) comes +linked with GNU @code{malloc}. If you encounter problems with memory usage, +make sure that @file{gmalloc.o} is included in @file{libgthreads.a} and +@file{libgthreads.so}. + +@item +In FSU Pthreads, the following system calls are pthreads-aware: @code{read()}, +@code{write()}, @code{getmsg()}, @code{connect()}, @code{accept()}, +@code{select()}, and @code{wait()}. +@end itemize + +If you want to install DBI on SCO, you have to edit the @file{Makefile} in +DBI-xxx and each subdirectory. + +Note that the following assumes gcc 2.95.2 or newer: + +@example +OLD: NEW: +CC = cc CC = gcc +CCCDLFLAGS = -KPIC -W1,-Bexport CCCDLFLAGS = -fpic +CCDLFLAGS = -wl,-Bexport CCDLFLAGS = + +LD = ld LD = gcc -G -fpic +LDDLFLAGS = -G -L/usr/local/lib LDDLFLAGS = -L/usr/local/lib +LDFLAGS = -belf -L/usr/local/lib LDFLAGS = -L/usr/local/lib + +LD = ld LD = gcc -G -fpic +OPTIMISE = -Od OPTIMISE = -O1 + +OLD: +CCCFLAGS = -belf -dy -w0 -U M_XENIX -DPERL_SCO5 -I/usr/local/include + +NEW: +CCFLAGS = -U M_XENIX -DPERL_SCO5 -I/usr/local/include +@end example + +This is because the Perl dynaloader will not load the @code{DBI} modules +if they were compiled with @code{icc} or @code{cc}. + +Perl works best when compiled with @code{cc}. + + +@node SCO Unixware, BeOS, Other Unix Notes, Operating System Specific Notes +@subsection SCO Unixware Version 7.0 Notes + +You must use a version of @strong{MySQL} at least as recent as Version 3.22.13 +because that version fixes some portability problems under Unixware. + +We have been able to compile @strong{MySQL} with the following @code{configure} +command on Unixware Version 7.0.1: + +@example +CC=cc CXX=CC ./configure --prefix=/usr/local/mysql +@end example + +If you want to use @code{gcc}, you must use @code{gcc} 2.95.2 or newer. + + +@menu +* OS/2:: +@end menu + +@node OS/2, , SCO Unixware, SCO Unixware +@subsubsection OS/2 Notes + +@strong{MySQL} uses quite a few open files. Because of this, you should add +something like the following to your @file{CONFIG.SYS} file: + +@example +SET EMXOPT=-c -n -h1024 +@end example + +If you don't do this, you will probably run into the following error: + +@example +File 'xxxx' not found (Errcode: 24) +@end example + +When using @strong{MySQL} with OS/2 Warp 3, FixPack 29 or above is +required. With OS/2 Warp 4, FixPack 4 or above is required. This is a +requirement of the Pthreads library. @strong{MySQL} must be installed +in a partition that supports long filenames such as HPFS, FAT32, etc. + +The @file{INSTALL.CMD} script must be run from OS/2's own @file{CMD.EXE} +and may not work with replacement shells such as @file{4OS2.EXE}. + +The @file{scripts/mysql-install-db} script has been renamed. It is now called +@file{install.cmd} and is a REXX script, which will set up the default +@strong{MySQL} security settings and create the WorkPlace Shell icons +for @strong{MySQL}. + +Dynamic module support is compiled in but not fully tested. Dynamic +modules should be compiled using the Pthreads run-time library. + +@example +gcc -Zdll -Zmt -Zcrtdll=pthrdrtl -I../include -I../regex -I.. \ + -o example udf_example.cc -L../lib -lmysqlclient udf_example.def +mv example.dll example.udf +@end example + +@strong{Note:} Due to limitations in OS/2, UDF module name stems must not +exceed 8 characters. Modules are stored in the @file{/mysql2/udf} +directory; the @code{safe-mysqld.cmd} script will put this directory in +the @code{BEGINLIBPATH} environment variable. When using UDF modules, +specified extensions are ignored --- it is assumed to be @file{.udf}. +For example, in Unix, the shared module might be named @file{example.so} +and you would load a function from it like this: + +@example +mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "example.so"; +@end example + +Is OS/2, the module would be named @file{example.udf}, but you would not +specify the module extension: + +@example +mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "example"; +@end example + + +@node BeOS, Novell Netware, SCO Unixware, Operating System Specific Notes +@subsection BeOS Notes + +We are really interested in getting @strong{MySQL} to work on BeOS, but +unfortunately we don't have any person who knows BeOS or has time to do +a port. + +We are interested in finding someone to do a port, and we will help them +with any technical questions they may have while doing the port. + +We have previously talked with some BeOS developers that have said that +@strong{MySQL} is 80% ported to BeOS, but we haven't heard from them +in a while. + + +@node Novell Netware, , BeOS, Operating System Specific Notes +@subsection Novell Netware Notes + +We are really interested in getting @strong{MySQL} to work on Netware, but +unfortunately we don't have any person who knows Netware or has time to do +a port. + +We are interested in finding someone to do a port, and we will help them +with any technical questions they may have while doing the port. + + + + @node Privilege system, Reference, Installing, Top @chapter The MySQL Access Privilege System + @cindex system, security @cindex access privileges @cindex privileges, access @@ -50746,7 +50050,7 @@ queries with @code{EXPLAIN}. You should also read the OS-specific section in this manual for problems that may be unique to your environment. -@xref{Source install system issues}. +@xref{Operating System Specific Notes}. @menu * Compiling for debugging:: @@ -52101,7 +51405,7 @@ Public License instead of this License. @page -@node LGPL license, Function Index, GPL license, Top +@node LGPL license, Placeholder, GPL license, Top @appendix GNU LESSER GENERAL PUBLIC LICENSE @cindex LGPL, Lesser General Public License @cindex LGPL, GNU Library General Public License @@ -52667,7 +51971,767 @@ Ty Coon, President of Vice That's all there is to it! -@node Function Index, Concept Index, LGPL license, Top +@node Placeholder, Function Index, LGPL license, Top +@appendix Pieces of the manual in transit + + +@menu +* Installing binary:: +* Building clients:: +* Command-line options:: +* Option files:: +* Installing many servers:: +@end menu + +@node Installing binary, Building clients, Placeholder, Placeholder +@appendixsec Installing a MySQL Binary Distribution + +@cindex installing, binary distribution +@cindex binary distributions, installing + +@menu +* Linux-RPM:: Linux RPM files +* Building clients:: Building client programs +@end menu + +You need the following tools to install a @strong{MySQL} binary distribution: + +@itemize @bullet +@item +GNU @code{gunzip} to uncompress the distribution. + +@item +A reasonable @code{tar} to unpack the distribution. GNU @code{tar} is +known to work. Sun @code{tar} is known to have problems. +@end itemize + +@cindex RPM, defined +@cindex RedHat Package Manager +An alternative installation method under Linux is to use RPM (RedHat Package +Manager) distributions. @xref{Linux-RPM}. + +@c texi2html fails to split chapters if I use strong for all of this. +If you run into problems, @strong{PLEASE ALWAYS USE} @code{mysqlbug} when +posting questions to @email{mysql@@lists.mysql.com}. Even if the problem +isn't a bug, @code{mysqlbug} gathers system information that will help others +solve your problem. By not using @code{mysqlbug}, you lessen the likelihood +of getting a solution to your problem! You will find @code{mysqlbug} in the +@file{bin} directory after you unpack the distribution. @xref{Bug reports}. + +@cindex commands, for binary distribution +The basic commands you must execute to install and use a @strong{MySQL} +binary distribution are: + +@example +shell> groupadd mysql +shell> useradd -g mysql mysql +shell> cd /usr/local +shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf - +shell> ln -s mysql-VERSION-OS mysql +shell> cd mysql +shell> scripts/mysql_install_db +shell> chown -R root /usr/local/mysql +shell> chown -R mysql /usr/local/mysql/data +shell> chgrp -R mysql /usr/local/mysql +shell> chown -R root /usr/local/mysql/bin +shell> bin/safe_mysqld --user=mysql & +@end example + +@cindex adding, new users +@cindex new users, adding +@cindex users, adding + +You can add new users using the @code{bin/mysql_setpermission} script if +you install the @code{DBI} and @code{Msql-Mysql-modules} Perl modules. + +A more detailed description follows. + +To install a binary distribution, follow the steps below, then proceed +to @ref{Post-installation}, for post-installation setup and testing: + +@enumerate +@item +Pick the directory under which you want to unpack the distribution, and move +into it. In the example below, we unpack the distribution under +@file{/usr/local} and create a directory @file{/usr/local/mysql} into which +@strong{MySQL} is installed. (The following instructions therefore assume +you have permission to create files in @file{/usr/local}. If that directory +is protected, you will need to perform the installation as @code{root}.) + +@item +Obtain a distribution file from one of the sites listed in +@ref{Getting MySQL, , Getting @strong{MySQL}}. + +@strong{MySQL} binary distributions are provided as compressed @code{tar} +archives and have names like @file{mysql-VERSION-OS.tar.gz}, where +@code{VERSION} is a number (for example, @code{3.21.15}), and @code{OS} +indicates the type of operating system for which the distribution is intended +(for example, @code{pc-linux-gnu-i586}). + +@item +If you see a binary distribution marked with the @code{-max} prefix, this +means that the binary has support for transaction-safe tables and other +features. @xref{mysqld-max, , @code{mysqld-max}}. Note that all binaries +are built from the same @strong{MySQL} source distribution. + +@item +Add a user and group for @code{mysqld} to run as: + +@example +shell> groupadd mysql +shell> useradd -g mysql mysql +@end example + +These commands add the @code{mysql} group and the @code{mysql} user. The +syntax for @code{useradd} and @code{groupadd} may differ slightly on different +versions of Unix. They may also be called @code{adduser} and @code{addgroup}. +You may wish to call the user and group something else instead of @code{mysql}. + +@item +Change into the intended installation directory: + +@example +shell> cd /usr/local +@end example + +@item +Unpack the distribution and create the installation directory: + +@example +shell> gunzip < /path/to/mysql-VERSION-OS.tar.gz | tar xvf - +shell> ln -s mysql-VERSION-OS mysql +@end example + +The first command creates a directory named @file{mysql-VERSION-OS}. The +second command makes a symbolic link to that directory. This lets you refer +more easily to the installation directory as @file{/usr/local/mysql}. + +@item +Change into the installation directory: + +@example +shell> cd mysql +@end example + +You will find several files and subdirectories in the @code{mysql} directory. +The most important for installation purposes are the @file{bin} and +@file{scripts} subdirectories. + +@table @file +@item bin +@tindex PATH environment variable +@tindex environment variable, PATH +This directory contains client programs and the server +You should add the full pathname of this directory to your +@code{PATH} environment variable so that your shell finds the @strong{MySQL} +programs properly. @xref{Environment variables}. + +@item scripts +This directory contains the @code{mysql_install_db} script used to initialize +the @code{mysql} database containing the grant tables that store the server +access permissions. +@end table + +@item +If you would like to use @code{mysqlaccess} and have the @strong{MySQL} +distribution in some non-standard place, you must change the location where +@code{mysqlaccess} expects to find the @code{mysql} client. Edit the +@file{bin/mysqlaccess} script at approximately line 18. Search for a line +that looks like this: + +@example +$MYSQL = '/usr/local/bin/mysql'; # path to mysql executable +@end example + +Change the path to reflect the location where @code{mysql} actually is +stored on your system. If you do not do this, you will get a @code{Broken +pipe} error when you run @code{mysqlaccess}. + +@item +Create the @strong{MySQL} grant tables (necessary only if you haven't +installed @strong{MySQL} before): +@example +shell> scripts/mysql_install_db +@end example + +Note that @strong{MySQL} versions older than Version 3.22.10 started the +@strong{MySQL} server when you run @code{mysql_install_db}. This is no +longer true! + +@item +Change ownership of binaries to @code{root} and ownership of the data +directory to the user that you will run @code{mysqld} as: + +@example +shell> chown -R root /usr/local/mysql +shell> chown -R mysql /usr/local/mysql/data +shell> chgrp -R mysql /usr/local/mysql +@end example + +The first command changes the @code{owner} attribute of the files to the +@code{root} user, the second one changes the @code{owner} attribute of the +data directory to the @code{mysql} user, and the third one changes the +@code{group} attribute to the @code{mysql} group. + +@item +If you want to install support for the Perl @code{DBI}/@code{DBD} interface, +see @ref{Perl support}. + +@item +If you would like @strong{MySQL} to start automatically when you boot your +machine, you can copy @code{support-files/mysql.server} to the location where +your system has its startup files. More information can be found in the +@code{support-files/mysql.server} script itself and in +@ref{Automatic start}. + +@end enumerate + +After everything has been unpacked and installed, you should initialize +and test your distribution. + +You can start the @strong{MySQL} server with the following command: + +@example +shell> bin/safe_mysqld --user=mysql & +@end example + +@xref{safe_mysqld, , @code{safe_mysqld}}. + +@xref{Post-installation}. + + +@node Building clients, Command-line options, Installing binary, Placeholder +@appendixsec Building Client Programs + +@cindex client programs, building +@cindex linking +@cindex building, client programs +@cindex programs, client + +If you compile @strong{MySQL} clients that you've written yourself or that +you obtain from a third party, they must be linked using the +@code{-lmysqlclient -lz} option on the link command. You may also need to +specify a @code{-L} option to tell the linker where to find the library. For +example, if the library is installed in @file{/usr/local/mysql/lib}, use +@code{-L/usr/local/mysql/lib -lmysqlclient -lz} on the link command. + +For clients that use @strong{MySQL} header files, you may need to specify a +@code{-I} option when you compile them (for example, +@code{-I/usr/local/mysql/include}), so the compiler can find the header +files. + + +@node Command-line options, Option files, Building clients, Placeholder +@appendixsec mysqld Command-line Options + +@findex command-line options +@cindex options, command-line +@cindex mysqld options + +@code{mysqld} accepts the following command-line options: + +@table @code +@item --ansi +Use ANSI SQL syntax instead of MySQL syntax. @xref{ANSI mode}. + +@item -b, --basedir=path +Path to installation directory. All paths are usually resolved relative to +this. + +@item --big-tables +Allow big result sets by saving all temporary sets on file. It solves +most 'table full' errors, but also slows down the queries where +in-memory tables would suffice. Since Version 3.23.2, @strong{MySQL} is +able to solve it automatically by using memory for small temporary +tables and switching to disk tables where necessary. + +@item --bind-address=IP +IP address to bind to. + +@item --character-sets-dir=path +Directory where character sets are. @xref{Character sets}. + +@item --chroot=path +Chroot @code{mysqld} daemon during startup. Recommended security measure. It will +somewhat limit @code{LOAD DATA INFILE} and @code{SELECT ... INTO OUTFILE} +though. + +@item --core-file +Write a core file if @code{mysqld} dies. For some systems you must also +specify @code{--core-file-size} to @code{safe_mysqld}. @xref{safe_mysqld, , +@code{safe_mysqld}}. + +@item -h, --datadir=path +Path to the database root. + +@item --default-character-set=charset +Set the default character set. @xref{Character sets}. + +@item --default-table-type=type +Set the default table type for tables. @xref{Table types}. + +@item --debug[...]= +If @strong{MySQL} is configured with @code{--with-debug}, you can use this +option to get a trace file of what @code{mysqld} is doing. +@xref{Making trace files}. + +@item --delay-key-write-for-all-tables +Don't flush key buffers between writes for any @code{MyISAM} table. +@xref{Server parameters}. + +@item --enable-locking +Enable system locking. Note that if you use this option on a system +which a not fully working lockd() (as on Linux) you will easily get +mysqld to deadlock. + +@item -T, --exit-info +This is a bit mask of different flags one can use for debugging the +mysqld server; One should not use this option if one doesn't know +exactly what it does! + +@item --flush +Flush all changes to disk after each SQL command. Normally @strong{MySQL} +only does a write of all changes to disk after each SQL command and lets +the operating system handle the syncing to disk. +@xref{Crashing}. + +@item -?, --help +Display short help and exit. + +@item --init-file=file +Read SQL commands from this file at startup. + +@item -L, --language=... +Client error messages in given language. May be given as a full path. +@xref{Languages}. + +@item -l, --log[=file] +Log connections and queries to file. @xref{Query log}. + +@item --log-isam[=file] +Log all ISAM/MyISAM changes to file (only used when debugging ISAM/MyISAM). + +@item --log-slow-queries[=file] +Log all queries that have taken more than @code{long_query_time} seconds to +execute to file. @xref{Slow query log}. + +@item --log-update[=file] +Log updates to @code{file.#} where @code{#} is a unique number if not given. +@xref{Update log}. + +@item --log-long-format +Log some extra information to update log. If you are using +@code{--log-slow-queries} then queries that are not using indexes are logged +to the slow query log. + +@item --low-priority-updates +Table-modifying operations (@code{INSERT}/@code{DELETE}/@code{UPDATE}) +will have lower priority than selects. It can also be done via +@code{@{INSERT | REPLACE | UPDATE | DELETE@} LOW_PRIORITY ...} to lower +the priority of only one query, or by +@code{SET OPTION SQL_LOW_PRIORITY_UPDATES=1} to change the priority in one +thread. @xref{Table locking}. + +@item --memlock +Lock the @code{mysqld} process in memory. This works only if your +system supports the @code{mlockall()} system call (like Solaris). This +may help if you have a problem where the operating system is causing +@code{mysqld} to swap on disk. + +@item --myisam-recover [=option[,option...]]] where option is one of DEFAULT, BACKUP, FORCE or QUICK. +If this option is used, @code{mysqld} will on open check if the table is +marked as crashed or if if the table wasn't closed properly. (The last +option only works if you are running with @code{--skip-locking}). If this +is the case @code{mysqld} will run check on the table. If the table was corrupted, +@code{mysqld} will attempt to repair it. + +The following options affects how the repair works. + +@multitable @columnfractions .3 .7 +@item DEFAULT @tab The same as not giving any option to + @code{--myisam-recover}. +@item BACKUP @tab If the data table was changed during recover, save a + backup of the @file{table_name.MYD} data file as + @file{table_name-datetime.BAK}. +@item FORCE @tab Run recover even if we will loose more than one row + from the .MYD file. +@item QUICK @tab Don't check the rows in the table if there isn't any + delete blocks. +@end multitable + +Before a table is automatically repaired, @strong{MySQL} will add a note +about this in the error log. If you want to be able to recover from most +things without user intervention, you should use the options +@code{BACKUP,FORCE}. This will force a repair of a table even if some rows +would be deleted, but it will keep the old data file as a backup so that +you can later examine what happened. + +@item --pid-file=path +Path to pid file used by @code{safe_mysqld}. + +@item -P, --port=... +Port number to listen for TCP/IP connections. + +@item -o, --old-protocol +Use the 3.20 protocol for compatibility with some very old clients. +@xref{Upgrading-from-3.20}. + +@item --one-thread +Only use one thread (for debugging under Linux). @xref{Debugging server}. + +@item -O, --set-variable var=option +Give a variable a value. @code{--help} lists variables. You can find a full +description for all variables in the @code{SHOW VARIABLES} section in this +manual. @xref{SHOW VARIABLES}. The tuning server parameters section includes +information of how to optimize these. @xref{Server parameters}. + +@item --safe-mode +Skip some optimize stages. Implies @code{--skip-delay-key-write}. + +@item --safe-show-database +Don't show databases for which the user doesn't have any privileges. + +@item --secure +IP numbers returned by the @code{gethostbyname()} system call are +checked to make sure they resolve back to the original hostname. This +makes it harder for someone on the outside to get access by pretending +to be another host. This option also adds some sanity checks of +hostnames. The option is turned off by default in @strong{MySQL} Version 3.21 +because sometimes it takes a long time to perform backward resolutions. +@strong{MySQL} Version 3.22 caches hostnames (unless @code{--skip-host-cache} +is used) and has this option enabled by default. + +@item --skip-concurrent-insert +Turn off the ability to select and insert at the same time on @code{MyISAM} +tables. (This is only to be used if you think you have found a bug in this +feature). + +@item --skip-delay-key-write +Ignore the @code{delay_key_write} option for all tables. +@xref{Server parameters}. + +@item --skip-grant-tables +This option causes the server not to use the privilege system at all. This +gives everyone @emph{full access} to all databases! (You can tell a running +server to start using the grant tables again by executing @code{mysqladmin +flush-privileges} or @code{mysqladmin reload}.) + +@item --skip-host-cache +Never use host name cache for faster name-ip resolution, but query DNS server +on every connect instead. @xref{DNS}. + +@item --skip-locking +Don't use system locking. To use @code{isamchk} or @code{myisamchk} you must +shut down the server. @xref{Stability}. Note that in @strong{MySQL} Version +3.23 you can use @code{REPAIR} and @code{CHECK} to repair/check @code{MyISAM} +tables. + +@item --skip-name-resolve +Hostnames are not resolved. All @code{Host} column values in the grant tables +must be IP numbers or @code{localhost}. @xref{DNS}. + +@item --skip-networking +Don't listen for TCP/IP connections at all. All interaction with +@code{mysqld} must be made via Unix sockets. This option is highly +recommended for systems where only local requests are allowed. @xref{DNS}. + +@item --skip-new +Don't use new, possible wrong routines. Implies @code{--skip-delay-key-write}. +This will also set default table type to @code{ISAM}. @xref{ISAM}. + +@item --skip-symlink +Don't delete or rename files that a symlinked file in the data directory +points to. + +@item --skip-safemalloc +If @strong{MySQL} is configured with @code{--with-debug=full}, all programs +will check the memory for overruns for every memory allocation and memory +freeing. As this checking is very slow, you can avoid this, when you don't +need memory checking, by using this option. + +@item --skip-show-database +Don't allow 'SHOW DATABASE' commands, unless the user has @strong{process} +privilege. + +@item --skip-stack-trace +Don't write stack traces. This option is useful when you are running +@code{mysqld} under a debugger. @xref{Debugging server}. + +@item --skip-thread-priority +Disable using thread priorities for faster response time. + +@item --socket=path +Socket file to use for local connections instead of default +@code{/tmp/mysql.sock}. + +@item transaction-isolation= @{ READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE @} +Sets the default transaction isolation level. @xref{SET TRANSACTION}. + +@item -t, --tmpdir=path +Path for temporary files. It may be useful if your default @code{/tmp} +directory resides on a partition too small to hold temporary tables. + +@item -u, --user=user_name +Run @code{mysqld} daemon as user @code{user_name}. This option is +@emph{mandatory} when starting @code{mysqld} as root. + +@item -V, --version +Output version information and exit. + +@item -W, --warnings +Print out warnings like @code{Aborted connection...} to the @code{.err} file. +@xref{Communication errors}. +@end table + +@node Option files, Installing many servers, Command-line options, Placeholder +@appendixsec Option Files + +@cindex default options +@cindex option files +@cindex creating, default startup options +@cindex startup options, default + +@strong{MySQL} can, since Version 3.22, read default startup options for the +server and for clients from option files. + +@strong{MySQL} reads default options from the following files on Unix: + +@tindex .my.cnf file +@multitable @columnfractions .3 .7 +@item @strong{Filename} @tab @strong{Purpose} +@item @code{/etc/my.cnf} @tab Global options +@item @code{DATADIR/my.cnf} @tab Server-specific options +@item @code{defaults-extra-file} @tab The file specified with --defaults-extra-file=# +@item @code{~/.my.cnf} @tab User-specific options +@end multitable + +@code{DATADIR} is the @strong{MySQL} data directory (typically +@file{/usr/local/mysql/data} for a binary installation or +@file{/usr/local/var} for a source installation). Note that this is the +directory that was specified at configuration time, not the one specified +with @code{--datadir} when @code{mysqld} starts up! (@code{--datadir} has no +effect on where the server looks for option files, because it looks for them +before it processes any command-line arguments.) + +@strong{MySQL} reads default options from the following files on Windows: + +@multitable @columnfractions .3 .7 +@item @strong{Filename} @tab @strong{Purpose} +@item @code{windows-system-directory\my.ini} @tab Global options +@item @code{C:\my.cnf} @tab Global options +@item @code{C:\mysql\data\my.cnf} @tab Server-specific options +@end multitable + +Note that on Windows, you should specify all paths with @code{/} instead of +@code{\}. If you use @code{\}, you need to specify this twice, as +@code{\} is the escape character in @strong{MySQL}. + +@cindex Environment variables +@strong{MySQL} tries to read option files in the order listed above. If +multiple option files exist, an option specified in a file read later takes +precedence over the same option specified in a file read earlier. Options +specified on the command line take precedence over options specified in any +option file. Some options can be specified using environment variables. +Options specified on the command line or in option files take precedence over +environment variable values. @xref{Environment variables}. + +The following programs support option files: @code{mysql}, +@code{mysqladmin}, @code{mysqld}, @code{mysqldump}, @code{mysqlimport}, +@code{mysql.server}, @code{myisamchk}, and @code{myisampack}. + +You can use option files to specify any long option that a program supports! +Run the program with @code{--help} to get a list of available options. + +An option file can contain lines of the following forms: + +@table @code +@item #comment +Comment lines start with @samp{#} or @samp{;}. Empty lines are ignored. + +@item [group] +@code{group} is the name of the program or group for which you want to set +options. After a group line, any @code{option} or @code{set-variable} lines +apply to the named group until the end of the option file or another group +line is given. + +@item option +This is equivalent to @code{--option} on the command line. + +@item option=value +This is equivalent to @code{--option=value} on the command line. + +@item set-variable = variable=value +This is equivalent to @code{--set-variable variable=value} on the command line. +This syntax must be used to set a @code{mysqld} variable. +@end table + +The @code{client} group allows you to specify options that apply to all +@strong{MySQL} clients (not @code{mysqld}). This is the perfect group to use +to specify the password you use to connect to the server. (But make +sure the option file is readable and writable only by yourself.) + +Note that for options and values, all leading and trailing blanks are +automatically deleted. You may use the escape sequences @samp{\b}, +@samp{\t}, @samp{\n}, @samp{\r}, @samp{\\}, and @samp{\s} in your value string +(@samp{\s} == blank). + +Here is a typical global option file: + +@example +[client] +port=3306 +socket=/tmp/mysql.sock + +[mysqld] +port=3306 +socket=/tmp/mysql.sock +set-variable = key_buffer_size=16M +set-variable = max_allowed_packet=1M + +[mysqldump] +quick +@end example + +Here is typical user option file: + +@example +[client] +# The following password will be sent to all standard MySQL clients +password=my_password + +[mysql] +no-auto-rehash +set-variable = connect_timeout=2 + +[mysqlhotcopy] +interactive-timeout + +@end example + +@tindex .my.cnf file +If you have a source distribution, you will find sample configuration +files named @file{my-xxxx.cnf} in the @file{support-files} directory. +If you have a binary distribution, look in the @file{DIR/support-files} +directory, where @code{DIR} is the pathname to the @strong{MySQL} +installation directory (typically @file{/usr/local/mysql}). Currently +there are sample configuration files for small, medium, large, and very +large systems. You can copy @file{my-xxxx.cnf} to your home directory +(rename the copy to @file{.my.cnf}) to experiment with this. + +All @strong{MySQL} clients that support option files support the +following options: + +@multitable @columnfractions .40 .60 +@item --no-defaults @tab Don't read any option files. +@item --print-defaults @tab Print the program name and all options that it will get. +@item --defaults-file=full-path-to-default-file @tab Only use the given configuration file. +@item --defaults-extra-file=full-path-to-default-file @tab Read this configuration file after the global configuration file but before the user configuration file. +@end multitable + +Note that the above options must be first on the command line to work! +@code{--print-defaults} may however be used directly after the +@code{--defaults-xxx-file} commands. + +Note for developers: Option file handling is implemented simply by +processing all matching options (that is, options in the appropriate group) +before any command-line arguments. This works nicely for programs that use +the last instance of an option that is specified multiple times. If you have +an old program that handles multiply-specified options this way but doesn't +read option files, you need add only two lines to give it that capability. +Check the source code of any of the standard @strong{MySQL} clients to see +how to do this. + +In shell scripts you can use the @file{my_print_defaults} command to parse the +config files: + +@example + +shell> my_print_defaults client mysql +--port=3306 +--socket=/tmp/mysql.sock +--no-auto-rehash +@end example + +The above output contains all options for the groups 'client' and 'mysql'. + + +@node Installing many servers, , Option files, Placeholder +@appendixsec Installing Many Servers on the Same Machine + +@cindex post-install, many servers +@cindex Installing many servers +@cindex Starting many servers + +In some cases you may want to have many different @code{mysqld} daemons +(servers) running on the same machine. You may for example want to run +a new version of @strong{MySQL} for testing together with an old version +that is in production. Another case is when you want to give different +users access to different @code{mysqld} servers that they manage themselves. + +One way to get a new server running is by starting it with a different +socket and port as follows: + +@tindex MYSQL_UNIX_PORT environment variable +@tindex MYSQL_TCP_PORT environment variable +@tindex Environment variable, MYSQL_UNIX_PORT +@tindex Environment variable, MYSQL_TCP_PORT +@example +shell> MYSQL_UNIX_PORT=/tmp/mysqld-new.sock +shell> MYSQL_TCP_PORT=3307 +shell> export MYSQL_UNIX_PORT MYSQL_TCP_PORT +shell> scripts/mysql_install_db +shell> bin/safe_mysqld & +@end example + +The environment variables appendix includes a list of other environment +variables you can use to affect @code{mysqld}. @xref{Environment variables}. + +The above is the quick and dirty way that one commonly uses for testing. +The nice thing with this is that all connections you do in the above shell +will automatically be directed to the new running server! + +If you need to do this more permanently, you should create an option +file for each server. @xref{Option files}. In your startup script that +is executed at boot time (mysql.server?) you should specify for both +servers: + +@code{safe_mysqld --default-file=path-to-option-file} + +At least the following options should be different per server: + +@table @code +@item port=# +@item socket=path +@item pid-file=path +@end table + +The following options should be different, if they are used: + +@table @code +@item log=path +@item log-bin=path +@item log-update=path +@item log-isam=path +@item bdb-logdir=path +@end table + +If you want more performance, you can also specify the following differently: + +@table @code +@item tmpdir=path +@item bdb-tmpdir=path +@end table + +@xref{Command-line options}. + +If you are installing binary @strong{MySQL} versions (.tar files) and +start them with @code{./bin/safe_mysqld} then in most cases the only +option you need to add/change is the @code{socket} and @code{port} +argument to @code{safe_mysqld}. + + + +@node Function Index, Concept Index, Placeholder, Top @unnumbered SQL command, type and function index @printindex fn From 2f4aad65375c64a8ffaa9dd536e585a7bbc83445 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 31 Jul 2001 09:15:56 -0500 Subject: [PATCH 16/51] Fixes to DocTOC Chapter 2. --- Docs/manual.texi | 639 ++++++++++++++++++++++++----------------------- 1 file changed, 321 insertions(+), 318 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 18a204069ca..e19f7c1e9d9 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -5962,10 +5962,7 @@ Nothing; In the long run we plan to be fully ANSI 92 / ANSI 99 compliant. @menu * Quick Standard Installation:: * General Installation Issues:: -* Many versions:: How and when updates are released -* MySQL binaries:: MySQL binaries * Installing source:: Installing a @strong{MySQL} source distribution -* Perl support:: Perl installation comments * Post-installation:: Post-installation setup and testing * Upgrade:: Upgrading/Downgrading MySQL * Operating System Specific Notes:: @@ -6160,7 +6157,7 @@ NOTE: If you want to use InnoDB tables, there are certain startup options that must be specified in your @file{my.ini} file! @xref{InnoDB start}. -@node General Installation Issues, Many versions, Quick Standard Installation, Installing +@node General Installation Issues, Installing source, Quick Standard Installation, Installing @section General Installation Issues @c @node Methods of Installation, , , @@ -6173,6 +6170,8 @@ options that must be specified in your @file{my.ini} file! @xref{InnoDB start}. * Which OS:: * Which version:: * Installation layouts:: +* Many versions:: +* MySQL binaries:: @end menu @node Getting MySQL, Which OS, General Installation Issues, General Installation Issues @@ -7266,7 +7265,7 @@ Another test is that we use the newest @strong{MySQL} version in our internal production environment, on at least one machine. We have more than 100 gigabytes of data to work with. -@node Installation layouts, , Which version, General Installation Issues +@node Installation layouts, Many versions, Which version, General Installation Issues @subsection Installation Layouts @cindex installation layouts @@ -7331,8 +7330,8 @@ The header file and library directories are @file{include/mysql} and You can create your own binary installation from a compiled source distribution by executing the script @file{scripts/make_binary_distribution}. -@node Many versions, MySQL binaries, General Installation Issues, Installing -@section How and When Updates Are Released +@node Many versions, MySQL binaries, Installation layouts, General Installation Issues +@subsection How and When Updates Are Released @cindex releases, updating @cindex updating, releases of MySQL @@ -7392,8 +7391,8 @@ and things that ``must be done.'' ``Somewhat frozen'' means that we may add small things that ``almost surely will not affect anything that's already working.'' -@node MySQL binaries, Installing source, Many versions, Installing -@section MySQL Binaries Compiled by MySQL AB +@node MySQL binaries, , Many versions, General Installation Issues +@subsection MySQL Binaries Compiled by MySQL AB @cindex binary distributions @@ -7451,7 +7450,7 @@ If you want to compile a debug version of @strong{MySQL}, you should add @code{--with-debug} or @code{--with-debug=full} to the above configure lines and remove any @code{-fomit-frame-pointer} options. -@node Installing source, Perl support, MySQL binaries, Installing +@node Installing source, Post-installation, General Installation Issues, Installing @section Installing a MySQL Source Distribution @cindex installing, source distribution @@ -8380,294 +8379,8 @@ We haven't gotten @code{readline} to work with MIT-pthreads. (This isn't needed, but may be interesting for someone.) @end itemize -@cindex Perl, installing -@cindex installing, Perl -@node Perl support, Post-installation, Installing source, Installing -@section Perl Installation Comments -@menu -* Perl installation:: Installing Perl on Unix -* ActiveState Perl:: Installing ActiveState Perl on Windows -* Windows Perl:: Installing the @strong{MySQL} Perl distribution on Windows -* Perl support problems:: Problems using the Perl @code{DBI}/@code{DBD} interface -@end menu - -@node Perl installation, ActiveState Perl, Perl support, Perl support -@subsection Installing Perl on Unix - -Perl support for @strong{MySQL} is provided by means of the -@code{DBI}/@code{DBD} client interface. @xref{Perl}. The Perl -@code{DBD}/@code{DBI} client code requires Perl Version 5.004 or later. The -interface @strong{will not work} if you have an older version of Perl. - -@strong{MySQL} Perl support also requires that you've installed -@strong{MySQL} client programming support. If you installed @strong{MySQL} -from RPM files, client programs are in the client RPM, but client programming -support is in the developer RPM. Make sure you've installed the latter RPM. - -As of Version 3.22.8, Perl support is distributed separately from the main -@strong{MySQL} distribution. If you want to install Perl support, the files -you will need can be obtained from -@uref{http://www.mysql.com/Downloads/Contrib/}. - -The Perl distributions are provided as compressed @code{tar} archives and -have names like @file{MODULE-VERSION.tar.gz}, where @code{MODULE} is the -module name and @code{VERSION} is the version number. You should get the -@code{Data-Dumper}, @code{DBI}, and @code{Msql-Mysql-modules} distributions -and install them in that order. The installation procedure is shown below. -The example shown is for the @code{Data-Dumper} module, but the procedure is -the same for all three distributions: - -@enumerate -@item -Unpack the distribution into the current directory: -@example -shell> gunzip < Data-Dumper-VERSION.tar.gz | tar xvf - -@end example -This command creates a directory named @file{Data-Dumper-VERSION}. - -@item -Change into the top-level directory of the unpacked distribution: -@example -shell> cd Data-Dumper-VERSION -@end example - -@item -Build the distribution and compile everything: -@example -shell> perl Makefile.PL -shell> make -shell> make test -shell> make install -@end example -@end enumerate - -The @code{make test} command is important because it verifies that the -module is working. Note that when you run that command during the -@code{Msql-Mysql-modules} installation to exercise the interface code, the -@strong{MySQL} server must be running or the test will fail. - -It is a good idea to rebuild and reinstall the @code{Msql-Mysql-modules} -distribution whenever you install a new release of @strong{MySQL}, -particularly if you notice symptoms such as all your @code{DBI} scripts -dumping core after you upgrade @strong{MySQL}. - -If you don't have the right to install Perl modules in the system directory -or if you to install local Perl modules, the following reference may help -you: - -@example -@uref{http://www.iserver.com/support/contrib/perl5/modules.html} -@end example - -Look under the heading -@code{Installing New Modules that Require Locally Installed Modules}. - -@node ActiveState Perl, Windows Perl, Perl installation, Perl support -@subsection Installing ActiveState Perl on Windows -@cindex installing, Perl on Windows -@cindex Perl, installing on Windows -@cindex ActiveState Perl - -To install the @strong{MySQL} @code{DBD} module with ActiveState Perl on -Windows, you should do the following: - -@itemize @bullet -@item -Get ActiveState Perl from -@uref{http://www.activestate.com/Products/ActivePerl/index.html} -and install it. - -@item -Open a DOS shell. - -@item -If required, set the HTTP_proxy variable. For example, you might try: - -@example -set HTTP_proxy=my.proxy.com:3128 -@end example - -@item -Start the PPM program: - -@example -C:\> c:\perl\bin\ppm.pl -@end example - -@item -If you have not already done so, install @code{DBI}: - -@example -ppm> install DBI -@end example - -@item -If this succeeds, run the following command: - -@example -install ftp://ftp.de.uu.net/pub/CPAN/authors/id/JWIED/DBD-mysql-1.2212.x86.ppd -@end example -@end itemize - -The above should work at least with ActiveState Perl Version 5.6. - -If you can't get the above to work, you should instead install the -@strong{MyODBC} driver and connect to @strong{MySQL} server through -ODBC: - -@example -use DBI; -$dbh= DBI->connect("DBI:ODBC:$dsn","$user","$password") || - die "Got error $DBI::errstr when connecting to $dsn\n"; -@end example - -@node Windows Perl, Perl support problems, ActiveState Perl, Perl support -@subsection Installing the MySQL Perl Distribution on Windows - -The @strong{MySQL} Perl distribution contains @code{DBI}, -@code{DBD:MySQL} and @code{DBD:ODBC}. - -@itemize @bullet -@item -Get the Perl distribution for Windows from -@uref{http://www.mysql.com/download.html}. - -@item -Unzip the distribution in @code{C:} so that you get a @file{C:\PERL} directory. - -@item -Add the directory @file{C:\PERL\BIN} to your path. - -@item -Add the directory @file{C:\PERL\BIN\MSWIN32-x86-thread} or -@file{C:\PERL\BIN\MSWIN32-x86} to your path. - -@item -Test that @code{perl} works by executing @code{perl -v} in a DOS shell. -@end itemize - -@cindex problems, installing Perl -@cindex Perl DBI/DBD, installation problems -@node Perl support problems, , Windows Perl, Perl support -@subsection Problems Using the Perl @code{DBI}/@code{DBD} Interface - -If Perl reports that it can't find the @file{../mysql/mysql.so} module, -then the problem is probably that Perl can't locate the shared library -@file{libmysqlclient.so}. - -You can fix this by any of the following methods: - -@itemize @bullet -@item -Compile the @code{Msql-Mysql-modules} distribution with @code{perl -Makefile.PL -static -config} rather than @code{perl Makefile.PL}. - -@item -Copy @code{libmysqlclient.so} to the directory where your other shared -libraries are located (probably @file{/usr/lib} or @file{/lib}). - -@item -On Linux you can add the pathname of the directory where -@file{libmysqlclient.so} is located to the @file{/etc/ld.so.conf} file. - -@tindex LD_RUN_PATH environment variable -@tindex Environment variable, LD_RUN_PATH -@item -Add the pathname of the directory where @file{libmysqlclient.so} is located -to the @code{LD_RUN_PATH} environment variable. -@end itemize - -If you get the following errors from @code{DBD-mysql}, -you are probably using @code{gcc} (or using an old binary compiled with -@code{gcc}): - -@example -/usr/bin/perl: can't resolve symbol '__moddi3' -/usr/bin/perl: can't resolve symbol '__divdi3' -@end example - -Add @code{-L/usr/lib/gcc-lib/... -lgcc} to the link command when the -@file{mysql.so} library gets built (check the output from @code{make} for -@file{mysql.so} when you compile the Perl client). The @code{-L} option -should specify the pathname of the directory where @file{libgcc.a} is located -on your system. - -Another cause of this problem may be that Perl and @strong{MySQL} aren't both -compiled with @code{gcc}. In this case, you can solve the mismatch by -compiling both with @code{gcc}. - -If you get the following error from @code{Msql-Mysql-modules} -when you run the tests: - -@example -t/00base............install_driver(mysql) failed: Can't load '../blib/arch/auto/DBD/mysql/mysql.so' for module DBD::mysql: ../blib/arch/auto/DBD/mysql/mysql.so: undefined symbol: uncompress at /usr/lib/perl5/5.00503/i586-linux/DynaLoader.pm line 169. -@end example - -it means that you need to include the compression library, -lz, to the -link line. This can be doing the following change in the file -@file{lib/DBD/mysql/Install.pm}: - -@example -$sysliblist .= " -lm"; - -to - -$sysliblist .= " -lm -lz"; -@end example - -After this, you MUST run 'make realclean' and then proceed with the -installation from the beginning. - -If you want to use the Perl module on a system that doesn't support dynamic -linking (like SCO) you can generate a static version of Perl that includes -@code{DBI} and @code{DBD-mysql}. The way this works is that you generate a -version of Perl with the @code{DBI} code linked in and install it on top of -your current Perl. Then you use that to build a version of Perl that -additionally has the @code{DBD} code linked in, and install that. - -On SCO, you must have the following environment variables set: - -@example -shell> LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/progressive/lib -or -shell> LD_LIBRARY_PATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:/usr/progressive/lib:/usr/skunk/lib -shell> LIBPATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:/usr/progressive/lib:/usr/skunk/lib -shell> MANPATH=scohelp:/usr/man:/usr/local1/man:/usr/local/man:/usr/skunk/man: -@end example - -First, create a Perl that includes a statically linked @code{DBI} by running -these commands in the directory where your @code{DBI} distribution is -located: - -@example -shell> perl Makefile.PL -static -config -shell> make -shell> make install -shell> make perl -@end example - -Then you must install the new Perl. The output of @code{make perl} will -indicate the exact @code{make} command you will need to execute to perform -the installation. On SCO, this is @code{make -f Makefile.aperl inst_perl -MAP_TARGET=perl}. - -Next, use the just-created Perl to create another Perl that also includes a -statically-linked @code{DBD::mysql} by running these commands in the -directory where your @code{Msql-Mysql-modules} distribution is located: - -@example -shell> perl Makefile.PL -static -config -shell> make -shell> make install -shell> make perl -@end example - -Finally, you should install this new Perl. Again, the output of @code{make -perl} indicates the command to use. - - -@node Post-installation, Upgrade, Perl support, Installing +@node Post-installation, Upgrade, Installing source, Installing @section Post-installation Setup and Testing @cindex post-installation, setup and testing @@ -9659,12 +9372,10 @@ information. * Linux:: * Windows:: * Solaris:: -* Solaris 2.7:: -* Solaris x86:: * BSD Notes:: * Mac OS X:: * Other Unix Notes:: -* SCO Unixware:: +* OS/2:: * BeOS:: * Novell Netware:: @end menu @@ -10014,7 +9725,7 @@ and clients on the same machine. We hope that the @code{Linux 2.4} kernel will fix this problem in the future. @node Linux-x86, Linux-SPARC, Binary notes-Linux, Linux -@subsubsection Linux-x86 Notes +@subsubsection Linux x86 Notes @strong{MySQL} requires @code{libc} Version 5.4.12 or newer. It's known to work with @code{libc} 5.4.46. @code{glibc} Version 2.0.6 and later should @@ -10717,7 +10428,7 @@ Other Windows-specific issues are described in the @file{README} file that comes with the @strong{MySQL}-Windows distribution. -@node Solaris, Solaris 2.7, Windows, Operating System Specific Notes +@node Solaris, BSD Notes, Windows, Operating System Specific Notes @subsection Solaris Notes @cindex Solaris installation problems @@ -10899,8 +10610,13 @@ If you would like @strong{MySQL} to start automatically, you can copy symbolic link to it named @file{/etc/rc3.d/S99mysql.server}. -@node Solaris 2.7, Solaris x86, Solaris, Operating System Specific Notes -@subsection Solaris 2.7/2.8 Notes +@menu +* Solaris 2.7:: +* Solaris x86:: +@end menu + +@node Solaris 2.7, Solaris x86, Solaris, Solaris +@subsubsection Solaris 2.7/2.8 Notes You can normally use a Solaris 2.6 binary on Solaris 2.7 and 2.8. Most of the Solaris 2.6 issues also apply for Solaris 2.7 and 2.8. @@ -10979,8 +10695,8 @@ Configure @strong{MySQL} with the @code{--with-named-z-libs=no} option. @end itemize -@node Solaris x86, BSD Notes, Solaris 2.7, Operating System Specific Notes -@subsection Solaris x86 Notes +@node Solaris x86, , Solaris 2.7, Solaris +@subsubsection Solaris x86 Notes On Solaris 2.8 on x86, @strong{mysqld} will core dump if you run 'strip' in. @@ -11003,7 +10719,7 @@ If this doesn't help, you should compile a debug version and run it with a trace file or under @code{gdb}. @xref{Using gdb on mysqld}. -@node BSD Notes, Mac OS X, Solaris x86, Operating System Specific Notes +@node BSD Notes, Mac OS X, Solaris, Operating System Specific Notes @subsection BSD Notes @menu @@ -11265,7 +10981,7 @@ alias mysqladmin '/usr/local/mysql/bin/mysqladmin' @end example -@node Other Unix Notes, SCO Unixware, Mac OS X, Operating System Specific Notes +@node Other Unix Notes, OS/2, Mac OS X, Operating System Specific Notes @subsection Other Unix Notes @menu @@ -11278,6 +10994,7 @@ alias mysqladmin '/usr/local/mysql/bin/mysqladmin' * Alpha-DEC-OSF1:: * SGI-Irix:: * SCO:: +* SCO Unixware:: @end menu @@ -11877,7 +11594,7 @@ CC=cc CXX=CC CFLAGS='-O3 -n32 -TARG:platform=IP22 -I/usr/local/include \ @end example -@node SCO, , SGI-Irix, Other Unix Notes +@node SCO, SCO Unixware, SGI-Irix, Other Unix Notes @subsubsection SCO Notes The current port is tested only on a ``sco3.2v5.0.4'' and @@ -12035,8 +11752,8 @@ if they were compiled with @code{icc} or @code{cc}. Perl works best when compiled with @code{cc}. -@node SCO Unixware, BeOS, Other Unix Notes, Operating System Specific Notes -@subsection SCO Unixware Version 7.0 Notes +@node SCO Unixware, , SCO, Other Unix Notes +@subsubsection SCO Unixware Version 7.0 Notes You must use a version of @strong{MySQL} at least as recent as Version 3.22.13 because that version fixes some portability problems under Unixware. @@ -12055,8 +11772,8 @@ If you want to use @code{gcc}, you must use @code{gcc} 2.95.2 or newer. * OS/2:: @end menu -@node OS/2, , SCO Unixware, SCO Unixware -@subsubsection OS/2 Notes +@node OS/2, BeOS, Other Unix Notes, Operating System Specific Notes +@subsection OS/2 Notes @strong{MySQL} uses quite a few open files. Because of this, you should add something like the following to your @file{CONFIG.SYS} file: @@ -12113,7 +11830,7 @@ mysql> CREATE FUNCTION metaphon RETURNS STRING SONAME "example"; @end example -@node BeOS, Novell Netware, SCO Unixware, Operating System Specific Notes +@node BeOS, Novell Netware, OS/2, Operating System Specific Notes @subsection BeOS Notes We are really interested in getting @strong{MySQL} to work on BeOS, but @@ -12139,9 +11856,6 @@ We are interested in finding someone to do a port, and we will help them with any technical questions they may have while doing the port. - - - @node Privilege system, Reference, Installing, Top @chapter The MySQL Access Privilege System @@ -51981,6 +51695,7 @@ That's all there is to it! * Command-line options:: * Option files:: * Installing many servers:: +* Perl support:: @end menu @node Installing binary, Building clients, Placeholder, Placeholder @@ -52655,7 +52370,7 @@ shell> my_print_defaults client mysql The above output contains all options for the groups 'client' and 'mysql'. -@node Installing many servers, , Option files, Placeholder +@node Installing many servers, Perl support, Option files, Placeholder @appendixsec Installing Many Servers on the Same Machine @cindex post-install, many servers @@ -52730,6 +52445,294 @@ option you need to add/change is the @code{socket} and @code{port} argument to @code{safe_mysqld}. +@node Perl support, , Installing many servers, Placeholder +@appendixsec Perl Installation Comments + +@cindex Perl, installing +@cindex installing, Perl + +@menu +* Perl installation:: Installing Perl on Unix +* ActiveState Perl:: Installing ActiveState Perl on Windows +* Windows Perl:: Installing the @strong{MySQL} Perl distribution on Windows +* Perl support problems:: Problems using the Perl @code{DBI}/@code{DBD} interface +@end menu + +@node Perl installation, ActiveState Perl, Perl support, Perl support +@appendixsubsec Installing Perl on Unix + +Perl support for @strong{MySQL} is provided by means of the +@code{DBI}/@code{DBD} client interface. @xref{Perl}. The Perl +@code{DBD}/@code{DBI} client code requires Perl Version 5.004 or later. The +interface @strong{will not work} if you have an older version of Perl. + +@strong{MySQL} Perl support also requires that you've installed +@strong{MySQL} client programming support. If you installed @strong{MySQL} +from RPM files, client programs are in the client RPM, but client programming +support is in the developer RPM. Make sure you've installed the latter RPM. + +As of Version 3.22.8, Perl support is distributed separately from the main +@strong{MySQL} distribution. If you want to install Perl support, the files +you will need can be obtained from +@uref{http://www.mysql.com/Downloads/Contrib/}. + +The Perl distributions are provided as compressed @code{tar} archives and +have names like @file{MODULE-VERSION.tar.gz}, where @code{MODULE} is the +module name and @code{VERSION} is the version number. You should get the +@code{Data-Dumper}, @code{DBI}, and @code{Msql-Mysql-modules} distributions +and install them in that order. The installation procedure is shown below. +The example shown is for the @code{Data-Dumper} module, but the procedure is +the same for all three distributions: + +@enumerate +@item +Unpack the distribution into the current directory: +@example +shell> gunzip < Data-Dumper-VERSION.tar.gz | tar xvf - +@end example +This command creates a directory named @file{Data-Dumper-VERSION}. + +@item +Change into the top-level directory of the unpacked distribution: +@example +shell> cd Data-Dumper-VERSION +@end example + +@item +Build the distribution and compile everything: +@example +shell> perl Makefile.PL +shell> make +shell> make test +shell> make install +@end example +@end enumerate + +The @code{make test} command is important because it verifies that the +module is working. Note that when you run that command during the +@code{Msql-Mysql-modules} installation to exercise the interface code, the +@strong{MySQL} server must be running or the test will fail. + +It is a good idea to rebuild and reinstall the @code{Msql-Mysql-modules} +distribution whenever you install a new release of @strong{MySQL}, +particularly if you notice symptoms such as all your @code{DBI} scripts +dumping core after you upgrade @strong{MySQL}. + +If you don't have the right to install Perl modules in the system directory +or if you to install local Perl modules, the following reference may help +you: + +@example +@uref{http://www.iserver.com/support/contrib/perl5/modules.html} +@end example + +Look under the heading +@code{Installing New Modules that Require Locally Installed Modules}. + +@node ActiveState Perl, Windows Perl, Perl installation, Perl support +@appendixsubsec Installing ActiveState Perl on Windows + +@cindex installing, Perl on Windows +@cindex Perl, installing on Windows +@cindex ActiveState Perl + +To install the @strong{MySQL} @code{DBD} module with ActiveState Perl on +Windows, you should do the following: + +@itemize @bullet +@item +Get ActiveState Perl from +@uref{http://www.activestate.com/Products/ActivePerl/index.html} +and install it. + +@item +Open a DOS shell. + +@item +If required, set the HTTP_proxy variable. For example, you might try: + +@example +set HTTP_proxy=my.proxy.com:3128 +@end example + +@item +Start the PPM program: + +@example +C:\> c:\perl\bin\ppm.pl +@end example + +@item +If you have not already done so, install @code{DBI}: + +@example +ppm> install DBI +@end example + +@item +If this succeeds, run the following command: + +@example +install ftp://ftp.de.uu.net/pub/CPAN/authors/id/JWIED/DBD-mysql-1.2212.x86.ppd +@end example +@end itemize + +The above should work at least with ActiveState Perl Version 5.6. + +If you can't get the above to work, you should instead install the +@strong{MyODBC} driver and connect to @strong{MySQL} server through +ODBC: + +@example +use DBI; +$dbh= DBI->connect("DBI:ODBC:$dsn","$user","$password") || + die "Got error $DBI::errstr when connecting to $dsn\n"; +@end example + +@node Windows Perl, Perl support problems, ActiveState Perl, Perl support +@appendixsubsec Installing the MySQL Perl Distribution on Windows + +The @strong{MySQL} Perl distribution contains @code{DBI}, +@code{DBD:MySQL} and @code{DBD:ODBC}. + +@itemize @bullet +@item +Get the Perl distribution for Windows from +@uref{http://www.mysql.com/download.html}. + +@item +Unzip the distribution in @code{C:} so that you get a @file{C:\PERL} directory. + +@item +Add the directory @file{C:\PERL\BIN} to your path. + +@item +Add the directory @file{C:\PERL\BIN\MSWIN32-x86-thread} or +@file{C:\PERL\BIN\MSWIN32-x86} to your path. + +@item +Test that @code{perl} works by executing @code{perl -v} in a DOS shell. +@end itemize + +@cindex problems, installing Perl +@cindex Perl DBI/DBD, installation problems +@node Perl support problems, , Windows Perl, Perl support +@appendixsubsec Problems Using the Perl @code{DBI}/@code{DBD} Interface + +If Perl reports that it can't find the @file{../mysql/mysql.so} module, +then the problem is probably that Perl can't locate the shared library +@file{libmysqlclient.so}. + +You can fix this by any of the following methods: + +@itemize @bullet +@item +Compile the @code{Msql-Mysql-modules} distribution with @code{perl +Makefile.PL -static -config} rather than @code{perl Makefile.PL}. + +@item +Copy @code{libmysqlclient.so} to the directory where your other shared +libraries are located (probably @file{/usr/lib} or @file{/lib}). + +@item +On Linux you can add the pathname of the directory where +@file{libmysqlclient.so} is located to the @file{/etc/ld.so.conf} file. + +@tindex LD_RUN_PATH environment variable +@tindex Environment variable, LD_RUN_PATH +@item +Add the pathname of the directory where @file{libmysqlclient.so} is located +to the @code{LD_RUN_PATH} environment variable. +@end itemize + +If you get the following errors from @code{DBD-mysql}, +you are probably using @code{gcc} (or using an old binary compiled with +@code{gcc}): + +@example +/usr/bin/perl: can't resolve symbol '__moddi3' +/usr/bin/perl: can't resolve symbol '__divdi3' +@end example + +Add @code{-L/usr/lib/gcc-lib/... -lgcc} to the link command when the +@file{mysql.so} library gets built (check the output from @code{make} for +@file{mysql.so} when you compile the Perl client). The @code{-L} option +should specify the pathname of the directory where @file{libgcc.a} is located +on your system. + +Another cause of this problem may be that Perl and @strong{MySQL} aren't both +compiled with @code{gcc}. In this case, you can solve the mismatch by +compiling both with @code{gcc}. + +If you get the following error from @code{Msql-Mysql-modules} +when you run the tests: + +@example +t/00base............install_driver(mysql) failed: Can't load '../blib/arch/auto/DBD/mysql/mysql.so' for module DBD::mysql: ../blib/arch/auto/DBD/mysql/mysql.so: undefined symbol: uncompress at /usr/lib/perl5/5.00503/i586-linux/DynaLoader.pm line 169. +@end example + +it means that you need to include the compression library, -lz, to the +link line. This can be doing the following change in the file +@file{lib/DBD/mysql/Install.pm}: + +@example +$sysliblist .= " -lm"; + +to + +$sysliblist .= " -lm -lz"; +@end example + +After this, you MUST run 'make realclean' and then proceed with the +installation from the beginning. + +If you want to use the Perl module on a system that doesn't support dynamic +linking (like SCO) you can generate a static version of Perl that includes +@code{DBI} and @code{DBD-mysql}. The way this works is that you generate a +version of Perl with the @code{DBI} code linked in and install it on top of +your current Perl. Then you use that to build a version of Perl that +additionally has the @code{DBD} code linked in, and install that. + +On SCO, you must have the following environment variables set: + +@example +shell> LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/progressive/lib +or +shell> LD_LIBRARY_PATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:/usr/progressive/lib:/usr/skunk/lib +shell> LIBPATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:/usr/progressive/lib:/usr/skunk/lib +shell> MANPATH=scohelp:/usr/man:/usr/local1/man:/usr/local/man:/usr/skunk/man: +@end example + +First, create a Perl that includes a statically linked @code{DBI} by running +these commands in the directory where your @code{DBI} distribution is +located: + +@example +shell> perl Makefile.PL -static -config +shell> make +shell> make install +shell> make perl +@end example + +Then you must install the new Perl. The output of @code{make perl} will +indicate the exact @code{make} command you will need to execute to perform +the installation. On SCO, this is @code{make -f Makefile.aperl inst_perl +MAP_TARGET=perl}. + +Next, use the just-created Perl to create another Perl that also includes a +statically-linked @code{DBD::mysql} by running these commands in the +directory where your @code{Msql-Mysql-modules} distribution is located: + +@example +shell> perl Makefile.PL -static -config +shell> make +shell> make install +shell> make perl +@end example + +Finally, you should install this new Perl. Again, the output of @code{make +perl} indicates the command to use. + @node Function Index, Concept Index, Placeholder, Top @unnumbered SQL command, type and function index From 72390f797f870d8b2da70194d6b54a1a7fa2a606 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 31 Jul 2001 09:37:49 -0500 Subject: [PATCH 17/51] DocTOC Chapter 3 Complete! --- Docs/manual.texi | 4847 +++++++++++++++++++++++----------------------- 1 file changed, 2438 insertions(+), 2409 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index e19f7c1e9d9..28b0638936a 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -112,10 +112,10 @@ distribution for that version. @menu * Introduction:: General Information about @strong{MySQL} * Installing:: Installing @strong{MySQL} +* Tutorial:: @strong{MySQL} Tutorial * Privilege system:: The @strong{MySQL} access privilege system * Reference:: @strong{MySQL} language reference * Table types:: @strong{MySQL} table types -* Tutorial:: @strong{MySQL} Tutorial * Server:: @strong{MySQL} Server * Replication:: Replication * Fulltext Search:: Fulltext Search @@ -5954,7 +5954,7 @@ Time is given according to amount of work, not real time. Nothing; In the long run we plan to be fully ANSI 92 / ANSI 99 compliant. @end itemize -@node Installing, Privilege system, Introduction, Top +@node Installing, Tutorial, Introduction, Top @chapter MySQL Installation @cindex installing, overview @@ -11856,7 +11856,2435 @@ We are interested in finding someone to do a port, and we will help them with any technical questions they may have while doing the port. -@node Privilege system, Reference, Installing, Top +@node Tutorial, Privilege system, Installing, Top +@chapter Introduction to MySQL: A MySQL Tutorial + +@cindex tutorial +@cindex terminal monitor, defined +@cindex monitor, terminal +@cindex options, provided by MySQL + +@menu +* Connecting-disconnecting:: Connecting to and disconnecting from the server +* Entering queries:: Entering queries +* Database use:: Creating and using a database +* Getting information:: Getting information about databases and tables +* Examples:: Examples +* Batch mode:: Using @code{mysql} in batch mode +* Twin:: Queries from twin project +* Apache:: +@end menu + +This chapter provides a tutorial introduction to @strong{MySQL} by showing +how to use the @code{mysql} client program to create and use a simple +database. @code{mysql} (sometimes referred to as the ``terminal monitor'' or +just ``monitor'') is an interactive program that allows you to connect to a +@strong{MySQL} server, run queries, and view the results. @code{mysql} may +also be used in batch mode: you place your queries in a file beforehand, then +tell @code{mysql} to execute the contents of the file. Both ways of using +@code{mysql} are covered here. + +To see a list of options provided by @code{mysql}, invoke it with +the @code{--help} option: + +@example +shell> mysql --help +@end example + +This chapter assumes that @code{mysql} is installed on your machine and that +a @strong{MySQL} server is available to which you can connect. If this is +not true, contact your @strong{MySQL} administrator. (If @emph{you} are the +administrator, you will need to consult other sections of this manual.) + +This chapter describes the entire process of setting up and using a +database. If you are interested only in accessing an already-existing +database, you may want to skip over the sections that describe how to +create the database and the tables it contains. + +Because this chapter is tutorial in nature, many details are necessarily left +out. Consult the relevant sections of the manual for more +information on the topics covered here. + +@node Connecting-disconnecting, Entering queries, Tutorial, Tutorial +@section Connecting to and Disconnecting from the Server + +@cindex connecting, to the server +@cindex disconnecting, from the server +@cindex server, connecting +@cindex server, disconnecting + +To connect to the server, you'll usually need to provide a @strong{MySQL} +user name when you invoke @code{mysql} and, most likely, a password. If the +server runs on a machine other than the one where you log in, you'll also +need to specify a hostname. Contact your administrator to find out what +connection parameters you should use to connect (that is, what host, user name, +and password to use). Once you know the proper parameters, you should be +able to connect like this: + +@example +shell> mysql -h host -u user -p +Enter password: ******** +@end example + +The @code{********} represents your password; enter it when @code{mysql} +displays the @code{Enter password:} prompt. + +If that works, you should see some introductory information followed by a +@code{mysql>} prompt: + + +@example +shell> mysql -h host -u user -p +Enter password: ******** +Welcome to the MySQL monitor. Commands end with ; or \g. +Your MySQL connection id is 459 to server version: 3.22.20a-log + +Type 'help' for help. + +mysql> +@end example + +The prompt tells you that @code{mysql} is ready for you to enter commands. + +Some @strong{MySQL} installations allow users to connect as the anonymous +(unnamed) user to the server running on the local host. If this is the case +on your machine, you should be able to connect to that server by invoking +@code{mysql} without any options: + +@example +shell> mysql +@end example + +After you have connected successfully, you can disconnect any time by typing +@code{QUIT} at the @code{mysql>} prompt: + +@example +mysql> QUIT +Bye +@end example + +You can also disconnect by pressing Control-D. + +Most examples in the following sections assume you are connected to the +server. They indicate this by the @code{mysql>} prompt. + +@node Entering queries, Database use, Connecting-disconnecting, Tutorial +@section Entering Queries + +@cindex running, queries +@cindex queries, entering +@cindex entering, queries + +Make sure you are connected to the server, as discussed in the previous +section. Doing so will not in itself select any database to work with, but +that's okay. At this point, it's more important to find out a little about +how to issue queries than to jump right in creating tables, loading data +into them, and retrieving data from them. This section describes the basic +principles of entering commands, using several queries you can try out to +familiarize yourself with how @code{mysql} works. + +Here's a simple command that asks the server to tell you its version number +and the current date. Type it in as shown below following the @code{mysql>} +prompt and hit the RETURN key: + +@example +mysql> SELECT VERSION(), CURRENT_DATE; ++--------------+--------------+ +| version() | CURRENT_DATE | ++--------------+--------------+ +| 3.22.20a-log | 1999-03-19 | ++--------------+--------------+ +1 row in set (0.01 sec) +mysql> +@end example + +This query illustrates several things about @code{mysql}: + +@itemize @bullet +@item +A command normally consists of a SQL statement followed by a semicolon. +(There are some exceptions where a semicolon is not needed. @code{QUIT}, +mentioned earlier, is one of them. We'll get to others later.) + +@item +When you issue a command, @code{mysql} sends it to the server for execution +and displays the results, then prints another @code{mysql>} to indicate +that it is ready for another command. + +@item +@code{mysql} displays query output as a table (rows and columns). The first +row contains labels for the columns. The rows following are the query +results. Normally, column labels are the names of the columns you fetch from +database tables. If you're retrieving the value of an expression rather than +a table column (as in the example just shown), @code{mysql} labels the column +using the expression itself. + +@item +@code{mysql} shows how many rows were returned and how long the query took +to execute, which gives you a rough idea of server performance. These values +are imprecise because they represent wall clock time (not CPU or machine +time), and because they are affected by factors such as server load and +network latency. (For brevity, the ``rows in set'' line is not shown in +the remaining examples in this chapter.) +@end itemize + +Keywords may be entered in any lettercase. The following queries are +equivalent: + +@example +mysql> SELECT VERSION(), CURRENT_DATE; +mysql> select version(), current_date; +mysql> SeLeCt vErSiOn(), current_DATE; +@end example + +Here's another query. It demonstrates that you can use @code{mysql} as a +simple calculator: + +@example +mysql> SELECT SIN(PI()/4), (4+1)*5; ++-------------+---------+ +| SIN(PI()/4) | (4+1)*5 | ++-------------+---------+ +| 0.707107 | 25 | ++-------------+---------+ +@end example + +The commands shown thus far have been relatively short, single-line +statements. You can even enter multiple statements on a single line. +Just end each one with a semicolon: + +@example +mysql> SELECT VERSION(); SELECT NOW(); ++--------------+ +| version() | ++--------------+ +| 3.22.20a-log | ++--------------+ + ++---------------------+ +| NOW() | ++---------------------+ +| 1999-03-19 00:15:33 | ++---------------------+ +@end example + +A command need not be given all on a single line, so lengthy commands that +require several lines are not a problem. @code{mysql} determines where your +statement ends by looking for the terminating semicolon, not by looking for +the end of the input line. (In other words, @code{mysql} +accepts free-format input: it collects input lines but does not execute them +until it sees the semicolon.) + +Here's a simple multiple-line statement: + +@example +mysql> SELECT + -> USER() + -> , + -> CURRENT_DATE; ++--------------------+--------------+ +| USER() | CURRENT_DATE | ++--------------------+--------------+ +| joesmith@@localhost | 1999-03-18 | ++--------------------+--------------+ +@end example + +In this example, notice how the prompt changes from @code{mysql>} to +@code{->} after you enter the first line of a multiple-line query. This is +how @code{mysql} indicates that it hasn't seen a complete statement and is +waiting for the rest. The prompt is your friend, because it provides +valuable feedback. If you use that feedback, you will always be aware of +what @code{mysql} is waiting for. + +If you decide you don't want to execute a command that you are in the +process of entering, cancel it by typing @code{\c}: + +@example +mysql> SELECT + -> USER() + -> \c +mysql> +@end example + +Here, too, notice the prompt. It switches back to @code{mysql>} after you +type @code{\c}, providing feedback to indicate that @code{mysql} is ready +for a new command. + +The following table shows each of the prompts you may see and summarizes what +they mean about the state that @code{mysql} is in: + +@cindex prompts, meanings +@multitable @columnfractions .10 .9 +@item @strong{Prompt} @tab @strong{Meaning} +@item @code{mysql>} @tab Ready for new command. +@item @code{@ @ @ @ ->} @tab Waiting for next line of multiple-line command. +@item @code{@ @ @ @ '>} @tab Waiting for next line, collecting a string that begins +with a single quote (@samp{'}). +@item @code{@ @ @ @ ">} @tab Waiting for next line, collecting a string that begins +with a double quote (@samp{"}). +@end multitable + +Multiple-line statements commonly occur by accident when you intend to +issue a command on a single line, but forget the terminating semicolon. In +this case, @code{mysql} waits for more input: + +@example +mysql> SELECT USER() + -> +@end example + +If this happens to you (you think you've entered a statement but the only +response is a @code{->} prompt), most likely @code{mysql} is waiting for the +semicolon. If you don't notice what the prompt is telling you, you might sit +there for a while before realizing what you need to do. Enter a semicolon to +complete the statement, and @code{mysql} will execute it: + +@example +mysql> SELECT USER() + -> ; ++--------------------+ +| USER() | ++--------------------+ +| joesmith@@localhost | ++--------------------+ +@end example + +The @code{'>} and @code{">} prompts occur during string collection. +In @strong{MySQL}, you can write strings surrounded by either @samp{'} +or @samp{"} characters (for example, @code{'hello'} or @code{"goodbye"}), +and @code{mysql} lets you enter strings that span multiple lines. When you +see a @code{'>} or @code{">} prompt, it means that you've entered a line +containing a string that begins with a @samp{'} or @samp{"} quote character, +but have not yet entered the matching quote that terminates the string. +That's fine if you really are entering a multiple-line string, but how likely +is that? Not very. More often, the @code{'>} and @code{">} prompts indicate +that you've inadvertantly left out a quote character. For example: + +@example +mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30; + "> +@end example + +If you enter this @code{SELECT} statement, then hit RETURN and wait for the +result, nothing will happen. Instead of wondering why this +query takes so long, notice the clue provided by the @code{">} prompt. It +tells you that @code{mysql} expects to see the rest of an unterminated +string. (Do you see the error in the statement? The string @code{"Smith} is +missing the second quote.) + +At this point, what do you do? The simplest thing is to cancel the command. +However, you cannot just type @code{\c} in this case, because @code{mysql} +interprets it as part of the string that it is collecting! Instead, enter +the closing quote character (so @code{mysql} knows you've finished the +string), then type @code{\c}: + +@example +mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30; + "> "\c +mysql> +@end example + +The prompt changes back to @code{mysql>}, indicating that @code{mysql} +is ready for a new command. + +It's important to know what the @code{'>} and @code{">} prompts signify, +because if you mistakenly enter an unterminated string, any further lines you +type will appear to be ignored by @code{mysql} --- including a line +containing @code{QUIT}! This can be quite confusing, especially if you +don't know that you need to supply the terminating quote before you can +cancel the current command. + +@node Database use, Getting information, Entering queries, Tutorial +@section Creating and Using a Database + +@cindex databases, creating +@cindex databases, using +@cindex creating, databases + +@menu +* Creating database:: Creating a database +* Creating tables:: Creating a table +* Loading tables:: Loading data into a table +* Retrieving data:: Retrieving information from a table +@end menu + +Now that you know how to enter commands, it's time to access a database. + +Suppose you have several pets in your home (your menagerie) and you'd +like to keep track of various types of information about them. You can do so +by creating tables to hold your data and loading them with the desired +information. Then you can answer different sorts of questions about your +animals by retrieving data from the tables. This section shows you how to: + +@itemize @bullet +@item +Create a database +@item +Create a table +@item +Load data into the table +@item +Retrieve data from the table in various ways +@item +Use multiple tables +@end itemize + +The menagerie database will be simple (deliberately), but it is not difficult +to think of real-world situations in which a similar type of database might +be used. For example, a database like this could be used by a farmer to keep +track of livestock, or by a veterinarian to keep track of patient records. +A menagerie distribution containing some of the queries and sample data used +in the following sections can be obtained from the @strong{MySQL} Web site. +It's available in either +@uref{http://www.mysql.com/Downloads/Contrib/Examples/menagerie.tar.gz,compressed @code{tar} format} +or +@uref{http://www.mysql.com/Downloads/Contrib/Examples/menagerie.zip,Zip format}. + +Use the @code{SHOW} statement to find out what databases currently exist +on the server: + +@example +mysql> SHOW DATABASES; ++----------+ +| Database | ++----------+ +| mysql | +| test | +| tmp | ++----------+ +@end example + +The list of databases is probably different on your machine, but the +@code{mysql} and @code{test} databases are likely to be among them. The +@code{mysql} database is required because it describes user access +privileges. The @code{test} database is often provided as a workspace for +users to try things out. + +If the @code{test} database exists, try to access it: + +@example +mysql> USE test +Database changed +@end example + +Note that @code{USE}, like @code{QUIT}, does not require a semicolon. (You +can terminate such statements with a semicolon if you like; it does no harm.) +The @code{USE} statement is special in another way, too: it must be given on +a single line. + +You can use the @code{test} database (if you have access to it) for the +examples that follow, but anything you create in that database can be +removed by anyone else with access to it. For this reason, you should +probably ask your @strong{MySQL} administrator for permission to use a +database of your own. Suppose you want to call yours @code{menagerie}. The +administrator needs to execute a command like this: + +@example +mysql> GRANT ALL ON menagerie.* TO your_mysql_name; +@end example + +where @code{your_mysql_name} is the @strong{MySQL} user name assigned to +you. + +@node Creating database, Creating tables, Database use, Database use +@subsection Creating and Selecting a Database + +@cindex selecting, databases +@cindex databases, selecting + +If the administrator creates your database for you when setting up your +permissions, you can begin using it. Otherwise, you need to create it +yourself: + +@example +mysql> CREATE DATABASE menagerie; +@end example + +Under Unix, database names are case sensitive (unlike SQL keywords), so you +must always refer to your database as @code{menagerie}, not as +@code{Menagerie}, @code{MENAGERIE}, or some other variant. This is also true +for table names. (Under Windows, this restriction does not apply, although +you must refer to databases and tables using the same lettercase throughout a +given query.) + +Creating a database does not select it for use; you must do that explicitly. +To make @code{menagerie} the current database, use this command: + +@example +mysql> USE menagerie +Database changed +@end example + +Your database needs to be created only once, but you must select it for use +each time you begin a @code{mysql} session. You can do this by issuing a +@code{USE} statement as shown above. Alternatively, you can select the +database on the command line when you invoke @code{mysql}. Just specify its +name after any connection parameters that you might need to provide. For +example: + +@example +shell> mysql -h host -u user -p menagerie +Enter password: ******** +@end example + +Note that @code{menagerie} is not your password on the command just shown. +If you want to supply your password on the command line after the @code{-p} +option, you must do so with no intervening space (for example, as +@code{-pmypassword}, not as @code{-p mypassword}). However, putting your +password on the command line is not recommended, because doing so exposes it +to snooping by other users logged in on your machine. + +@node Creating tables, Loading tables, Creating database, Database use +@subsection Creating a Table + +@cindex tables, creating +@cindex creating, tables + +Creating the database is the easy part, but at this point it's empty, as +@code{SHOW TABLES} will tell you: + +@example +mysql> SHOW TABLES; +Empty set (0.00 sec) +@end example + +The harder part is deciding what the structure of your database should be: +what tables you will need and what columns will be in each of them. + +You'll want a table that contains a record for each of your pets. This can +be called the @code{pet} table, and it should contain, as a bare minimum, +each animal's name. Because the name by itself is not very interesting, the +table should contain other information. For example, if more than one person +in your family keeps pets, you might want to list each animal's owner. You +might also want to record some basic descriptive information such as species +and sex. + +How about age? That might be of interest, but it's not a good thing to store +in a database. Age changes as time passes, which means you'd have to update +your records often. Instead, it's better to store a fixed value such as +date of birth. Then, whenever you need age, you can calculate it as the +difference between the current date and the birth date. @strong{MySQL} +provides functions for doing date arithmetic, so this is not difficult. +Storing birth date rather than age has other advantages, too: + +@itemize @bullet +@item +You can use the database for tasks such as generating reminders for upcoming +pet birthdays. (If you think this type of query is somewhat silly, note that +it is the same question you might ask in the context of a business database +to identify clients to whom you'll soon need to send out birthday greetings, +for that computer-assisted personal touch.) + +@item +You can calculate age in relation to dates other than the current date. For +example, if you store death date in the database, you can easily calculate +how old a pet was when it died. +@end itemize + +You can probably think of other types of information that would be useful in +the @code{pet} table, but the ones identified so far are sufficient for now: +name, owner, species, sex, birth, and death. + +Use a @code{CREATE TABLE} statement to specify the layout of your table: + +@example +mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), + -> species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); +@end example + +@code{VARCHAR} is a good choice for the @code{name}, @code{owner}, and +@code{species} columns because the column values will vary in length. The +lengths of those columns need not all be the same, and need not be +@code{20}. You can pick any length from @code{1} to @code{255}, whatever +seems most reasonable to you. (If you make a poor choice and it turns +out later that you need a longer field, @strong{MySQL} provides an +@code{ALTER TABLE} statement.) + +Animal sex can be represented in a variety of ways, for example, @code{"m"} +and @code{"f"}, or perhaps @code{"male"} and @code{"female"}. It's simplest +to use the single characters @code{"m"} and @code{"f"}. + +The use of the @code{DATE} data type for the @code{birth} and @code{death} +columns is a fairly obvious choice. + +Now that you have created a table, @code{SHOW TABLES} should produce some +output: + +@example +mysql> SHOW TABLES; ++---------------------+ +| Tables in menagerie | ++---------------------+ +| pet | ++---------------------+ +@end example + +To verify that your table was created the way you expected, use +a @code{DESCRIBE} statement: + +@example +mysql> DESCRIBE pet; ++---------+-------------+------+-----+---------+-------+ +| Field | Type | Null | Key | Default | Extra | ++---------+-------------+------+-----+---------+-------+ +| name | varchar(20) | YES | | NULL | | +| owner | varchar(20) | YES | | NULL | | +| species | varchar(20) | YES | | NULL | | +| sex | char(1) | YES | | NULL | | +| birth | date | YES | | NULL | | +| death | date | YES | | NULL | | ++---------+-------------+------+-----+---------+-------+ +@end example + +You can use @code{DESCRIBE} any time, for example, if you forget the names of +the columns in your table or what types they are. + +@node Loading tables, Retrieving data, Creating tables, Database use +@subsection Loading Data into a Table + +@cindex loading, tables +@cindex tables, loading data +@cindex data, loading into tables + +After creating your table, you need to populate it. The @code{LOAD DATA} and +@code{INSERT} statements are useful for this. + +Suppose your pet records can be described as shown below. +(Observe that @strong{MySQL} expects dates in @code{YYYY-MM-DD} format; +this may be different than what you are used to.) + +@multitable @columnfractions .16 .16 .16 .16 .16 .16 +@item @strong{name} @tab @strong{owner} @tab @strong{species} @tab @strong{sex} @tab @strong{birth} @tab @strong{death} +@item Fluffy @tab Harold @tab cat @tab f @tab 1993-02-04 @tab +@item Claws @tab Gwen @tab cat @tab m @tab 1994-03-17 @tab +@item Buffy @tab Harold @tab dog @tab f @tab 1989-05-13 @tab +@item Fang @tab Benny @tab dog @tab m @tab 1990-08-27 @tab +@item Bowser @tab Diane @tab dog @tab m @tab 1989-08-31 @tab 1995-07-29 +@item Chirpy @tab Gwen @tab bird @tab f @tab 1998-09-11 @tab +@item Whistler @tab Gwen @tab bird @tab @tab 1997-12-09 @tab +@item Slim @tab Benny @tab snake @tab m @tab 1996-04-29 @tab +@end multitable + +Because you are beginning with an empty table, an easy way to populate it is to +create a text file containing a row for each of your animals, then load the +contents of the file into the table with a single statement. + +You could create a text file @file{pet.txt} containing one record per line, +with values separated by tabs, and given in the order in which the columns +were listed in the @code{CREATE TABLE} statement. For missing values (such +as unknown sexes or death dates for animals that are still living), you can +use @code{NULL} values. To represent these in your text file, use +@code{\N}. For example, the record for Whistler the bird would look like +this (where the whitespace between values is a single tab character): + +@multitable @columnfractions .15 .15 .15 .15 .25 .15 +@item @code{Whistler} @tab @code{Gwen} @tab @code{bird} @tab @code{\N} @tab @code{1997-12-09} @tab @code{\N} +@end multitable + +To load the text file @file{pet.txt} into the @code{pet} table, use this +command: + +@example +mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet; +@end example + +You can specify the column value separator and end of line marker explicitly +in the @code{LOAD DATA} statement if you wish, but the defaults are tab and +linefeed. These are sufficient for the statement to read the file +@file{pet.txt} properly. + +When you want to add new records one at a time, the @code{INSERT} statement +is useful. In its simplest form, you supply values for each column, in the +order in which the columns were listed in the @code{CREATE TABLE} statement. +Suppose Diane gets a new hamster named Puffball. You could add a new record +using an @code{INSERT} statement like this: + +@example +mysql> INSERT INTO pet + -> VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL); +@end example + +Note that string and date values are specified as quoted strings here. Also, +with @code{INSERT}, you can insert @code{NULL} directly to represent a +missing value. You do not use @code{\N} like you do with @code{LOAD DATA}. + +From this example, you should be able to see that there would be a lot more +typing involved to load +your records initially using several @code{INSERT} statements rather +than a single @code{LOAD DATA} statement. + +@node Retrieving data, , Loading tables, Database use +@subsection Retrieving Information from a Table + +@cindex data, retrieving +@cindex tables, retrieving data +@cindex retrieving, data from tables +@cindex unloading, tables + +@menu +* Selecting all:: Selecting all data +* Selecting rows:: Selecting particular rows +* Selecting columns:: Selecting particular columns +* Sorting rows:: Sorting rows +* Date calculations:: Date calculations +* Working with NULL:: Working with @code{NULL} values +* Pattern matching:: Pattern matching +* Counting rows:: Counting rows +* Multiple tables:: +@end menu + +The @code{SELECT} statement is used to pull information from a table. +The general form of the statement is: + +@example +SELECT what_to_select +FROM which_table +WHERE conditions_to_satisfy +@end example + +@code{what_to_select} indicates what you want to see. This can be a list of +columns, or @code{*} to indicate ``all columns.'' @code{which_table} +indicates the table from which you want to retrieve data. The @code{WHERE} +clause is optional. If it's present, @code{conditions_to_satisfy} specifies +conditions that rows must satisfy to qualify for retrieval. + +@node Selecting all, Selecting rows, Retrieving data, Retrieving data +@subsubsection Selecting All Data + +The simplest form of @code{SELECT} retrieves everything from a table: + +@example +mysql> SELECT * FROM pet; ++----------+--------+---------+------+------------+------------+ +| name | owner | species | sex | birth | death | ++----------+--------+---------+------+------------+------------+ +| Fluffy | Harold | cat | f | 1993-02-04 | NULL | +| Claws | Gwen | cat | m | 1994-03-17 | NULL | +| Buffy | Harold | dog | f | 1989-05-13 | NULL | +| Fang | Benny | dog | m | 1990-08-27 | NULL | +| Bowser | Diane | dog | m | 1998-08-31 | 1995-07-29 | +| Chirpy | Gwen | bird | f | 1998-09-11 | NULL | +| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | +| Slim | Benny | snake | m | 1996-04-29 | NULL | +| Puffball | Diane | hamster | f | 1999-03-30 | NULL | ++----------+--------+---------+------+------------+------------+ +@end example + +This form of @code{SELECT} is useful if you want to review your entire table, +for instance, after you've just loaded it with your initial dataset. As it +happens, the output just shown reveals an error in your data file: Bowser +appears to have been born after he died! Consulting your original pedigree +papers, you find that the correct birth year is 1989, not 1998. + +There are are least a couple of ways to fix this: + +@itemize @bullet +@item +Edit the file @file{pet.txt} to correct the error, then empty the table +and reload it using @code{DELETE} and @code{LOAD DATA}: + +@example +mysql> SET AUTOCOMMIT=1; # Used for quick re-create of the table +mysql> DELETE FROM pet; +mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet; +@end example + +However, if you do this, you must also re-enter the record for Puffball. + +@item +Fix only the erroneous record with an @code{UPDATE} statement: + +@example +mysql> UPDATE pet SET birth = "1989-08-31" WHERE name = "Bowser"; +@end example +@end itemize + +As shown above, it is easy to retrieve an entire table. But typically you +don't want to do that, particularly when the table becomes large. Instead, +you're usually more interested in answering a particular question, in which +case you specify some constraints on the information you want. Let's look at +some selection queries in terms of questions about your pets that they +answer. + +@node Selecting rows, Selecting columns, Selecting all, Retrieving data +@subsubsection Selecting Particular Rows + +@cindex rows, selecting +@cindex tables, selecting rows + +You can select only particular rows from your table. For example, if you want +to verify the change that you made to Bowser's birth date, select Bowser's +record like this: + +@example +mysql> SELECT * FROM pet WHERE name = "Bowser"; ++--------+-------+---------+------+------------+------------+ +| name | owner | species | sex | birth | death | ++--------+-------+---------+------+------------+------------+ +| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | ++--------+-------+---------+------+------------+------------+ +@end example + +The output confirms that the year is correctly recorded now as 1989, not 1998. + +String comparisons are normally case insensitive, so you can specify the +name as @code{"bowser"}, @code{"BOWSER"}, etc. The query result will be +the same. + +You can specify conditions on any column, not just @code{name}. For example, +if you want to know which animals were born after 1998, test the @code{birth} +column: + +@example +mysql> SELECT * FROM pet WHERE birth >= "1998-1-1"; ++----------+-------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++----------+-------+---------+------+------------+-------+ +| Chirpy | Gwen | bird | f | 1998-09-11 | NULL | +| Puffball | Diane | hamster | f | 1999-03-30 | NULL | ++----------+-------+---------+------+------------+-------+ +@end example + +You can combine conditions, for example, to locate female dogs: + +@example +mysql> SELECT * FROM pet WHERE species = "dog" AND sex = "f"; ++-------+--------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++-------+--------+---------+------+------------+-------+ +| Buffy | Harold | dog | f | 1989-05-13 | NULL | ++-------+--------+---------+------+------------+-------+ +@end example + +The preceding query uses the @code{AND} logical operator. There is also an +@code{OR} operator: + +@example +mysql> SELECT * FROM pet WHERE species = "snake" OR species = "bird"; ++----------+-------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++----------+-------+---------+------+------------+-------+ +| Chirpy | Gwen | bird | f | 1998-09-11 | NULL | +| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | +| Slim | Benny | snake | m | 1996-04-29 | NULL | ++----------+-------+---------+------+------------+-------+ +@end example + +@code{AND} and @code{OR} may be intermixed. If you do that, it's a good idea +to use parentheses to indicate how conditions should be grouped: + +@example +mysql> SELECT * FROM pet WHERE (species = "cat" AND sex = "m") + -> OR (species = "dog" AND sex = "f"); ++-------+--------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++-------+--------+---------+------+------------+-------+ +| Claws | Gwen | cat | m | 1994-03-17 | NULL | +| Buffy | Harold | dog | f | 1989-05-13 | NULL | ++-------+--------+---------+------+------------+-------+ +@end example + +@node Selecting columns, Sorting rows, Selecting rows, Retrieving data +@subsubsection Selecting Particular Columns + +@cindex columns, selecting +@cindex tables, selecting columns + +If you don't want to see entire rows from your table, just name the columns +in which you're interested, separated by commas. For example, if you want to +know when your animals were born, select the @code{name} and @code{birth} +columns: + +@example +mysql> SELECT name, birth FROM pet; ++----------+------------+ +| name | birth | ++----------+------------+ +| Fluffy | 1993-02-04 | +| Claws | 1994-03-17 | +| Buffy | 1989-05-13 | +| Fang | 1990-08-27 | +| Bowser | 1989-08-31 | +| Chirpy | 1998-09-11 | +| Whistler | 1997-12-09 | +| Slim | 1996-04-29 | +| Puffball | 1999-03-30 | ++----------+------------+ +@end example + +To find out who owns pets, use this query: + +@example +mysql> SELECT owner FROM pet; ++--------+ +| owner | ++--------+ +| Harold | +| Gwen | +| Harold | +| Benny | +| Diane | +| Gwen | +| Gwen | +| Benny | +| Diane | ++--------+ +@end example + +@findex DISTINCT +However, notice that the query simply retrieves the @code{owner} field from +each record, and some of them appear more than once. To minimize the output, +retrieve each unique output record just once by adding the keyword +@code{DISTINCT}: + +@example +mysql> SELECT DISTINCT owner FROM pet; ++--------+ +| owner | ++--------+ +| Benny | +| Diane | +| Gwen | +| Harold | ++--------+ +@end example + +You can use a @code{WHERE} clause to combine row selection with column +selection. For example, to get birth dates for dogs and cats only, +use this query: + +@example +mysql> SELECT name, species, birth FROM pet + -> WHERE species = "dog" OR species = "cat"; ++--------+---------+------------+ +| name | species | birth | ++--------+---------+------------+ +| Fluffy | cat | 1993-02-04 | +| Claws | cat | 1994-03-17 | +| Buffy | dog | 1989-05-13 | +| Fang | dog | 1990-08-27 | +| Bowser | dog | 1989-08-31 | ++--------+---------+------------+ +@end example + +@node Sorting rows, Date calculations, Selecting columns, Retrieving data +@subsubsection Sorting Rows + +@cindex rows, sorting +@cindex sorting, table rows +@cindex sorting, data +@cindex tables, sorting rows + +You may have noticed in the preceding examples that the result rows are +displayed in no particular order. However, it's often easier to examine +query output when the rows are sorted in some meaningful way. To sort a +result, use an @code{ORDER BY} clause. + +Here are animal birthdays, sorted by date: + +@example +mysql> SELECT name, birth FROM pet ORDER BY birth; ++----------+------------+ +| name | birth | ++----------+------------+ +| Buffy | 1989-05-13 | +| Bowser | 1989-08-31 | +| Fang | 1990-08-27 | +| Fluffy | 1993-02-04 | +| Claws | 1994-03-17 | +| Slim | 1996-04-29 | +| Whistler | 1997-12-09 | +| Chirpy | 1998-09-11 | +| Puffball | 1999-03-30 | ++----------+------------+ +@end example + +To sort in reverse order, add the @code{DESC} (descending) keyword to the +name of the column you are sorting by: + +@example +mysql> SELECT name, birth FROM pet ORDER BY birth DESC; ++----------+------------+ +| name | birth | ++----------+------------+ +| Puffball | 1999-03-30 | +| Chirpy | 1998-09-11 | +| Whistler | 1997-12-09 | +| Slim | 1996-04-29 | +| Claws | 1994-03-17 | +| Fluffy | 1993-02-04 | +| Fang | 1990-08-27 | +| Bowser | 1989-08-31 | +| Buffy | 1989-05-13 | ++----------+------------+ +@end example + +You can sort on multiple columns. For example, to sort by type of +animal, then by birth date within animal type with youngest animals first, +use the following query: + +@example +mysql> SELECT name, species, birth FROM pet ORDER BY species, birth DESC; ++----------+---------+------------+ +| name | species | birth | ++----------+---------+------------+ +| Chirpy | bird | 1998-09-11 | +| Whistler | bird | 1997-12-09 | +| Claws | cat | 1994-03-17 | +| Fluffy | cat | 1993-02-04 | +| Fang | dog | 1990-08-27 | +| Bowser | dog | 1989-08-31 | +| Buffy | dog | 1989-05-13 | +| Puffball | hamster | 1999-03-30 | +| Slim | snake | 1996-04-29 | ++----------+---------+------------+ +@end example + +Note that the @code{DESC} keyword applies only to the column name immediately +preceding it (@code{birth}); @code{species} values are still sorted in +ascending order. + +@node Date calculations, Working with NULL, Sorting rows, Retrieving data +@subsubsection Date Calculations + +@cindex date calculations +@cindex calculating, dates +@cindex extracting, dates +@cindex age, calculating + +@strong{MySQL} provides several functions that you can use to perform +calculations on dates, for example, to calculate ages or extract +parts of dates. + +To determine how many years old each of your pets is, compute age as the +difference between the birth date and the current date. Do this by +converting the two dates to days, take the difference, and divide by 365 (the +number of days in a year): + +@example +mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 FROM pet; ++----------+-------------------------------------+ +| name | (TO_DAYS(NOW())-TO_DAYS(birth))/365 | ++----------+-------------------------------------+ +| Fluffy | 6.15 | +| Claws | 5.04 | +| Buffy | 9.88 | +| Fang | 8.59 | +| Bowser | 9.58 | +| Chirpy | 0.55 | +| Whistler | 1.30 | +| Slim | 2.92 | +| Puffball | 0.00 | ++----------+-------------------------------------+ +@end example + +Although the query works, there are some things about it that could be +improved. First, the result could be scanned more easily if the rows were +presented in some order. Second, the heading for the age column isn't very +meaningful. + +The first problem can be handled by adding an @code{ORDER BY name} clause to +sort the output by name. To deal with the column heading, provide a name for +the column so that a different label appears in the output (this is called a +column alias): + +@example +mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 AS age + -> FROM pet ORDER BY name; ++----------+------+ +| name | age | ++----------+------+ +| Bowser | 9.58 | +| Buffy | 9.88 | +| Chirpy | 0.55 | +| Claws | 5.04 | +| Fang | 8.59 | +| Fluffy | 6.15 | +| Puffball | 0.00 | +| Slim | 2.92 | +| Whistler | 1.30 | ++----------+------+ +@end example + +To sort the output by @code{age} rather than @code{name}, just use a +different @code{ORDER BY} clause: + +@example +mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 AS age + -> FROM pet ORDER BY age; ++----------+------+ +| name | age | ++----------+------+ +| Puffball | 0.00 | +| Chirpy | 0.55 | +| Whistler | 1.30 | +| Slim | 2.92 | +| Claws | 5.04 | +| Fluffy | 6.15 | +| Fang | 8.59 | +| Bowser | 9.58 | +| Buffy | 9.88 | ++----------+------+ +@end example + +A similar query can be used to determine age at death for animals that have +died. You determine which animals these are by checking whether or not the +@code{death} value is @code{NULL}. Then, for those with non-@code{NULL} +values, compute the difference between the @code{death} and @code{birth} +values: + +@example +mysql> SELECT name, birth, death, (TO_DAYS(death)-TO_DAYS(birth))/365 AS age + -> FROM pet WHERE death IS NOT NULL ORDER BY age; ++--------+------------+------------+------+ +| name | birth | death | age | ++--------+------------+------------+------+ +| Bowser | 1989-08-31 | 1995-07-29 | 5.91 | ++--------+------------+------------+------+ +@end example + +The query uses @code{death IS NOT NULL} rather than @code{death != NULL} +because @code{NULL} is a special value. This is explained later. +@xref{Working with NULL, , Working with @code{NULL}}. + +What if you want to know which animals have birthdays next month? For this +type of calculation, year and day are irrelevant; you simply want to extract +the month part of the @code{birth} column. @strong{MySQL} provides several +date-part extraction functions, such as @code{YEAR()}, @code{MONTH()}, and +@code{DAYOFMONTH()}. @code{MONTH()} is the appropriate function here. To +see how it works, run a simple query that displays the value of both +@code{birth} and @code{MONTH(birth)}: + +@example +mysql> SELECT name, birth, MONTH(birth) FROM pet; ++----------+------------+--------------+ +| name | birth | MONTH(birth) | ++----------+------------+--------------+ +| Fluffy | 1993-02-04 | 2 | +| Claws | 1994-03-17 | 3 | +| Buffy | 1989-05-13 | 5 | +| Fang | 1990-08-27 | 8 | +| Bowser | 1989-08-31 | 8 | +| Chirpy | 1998-09-11 | 9 | +| Whistler | 1997-12-09 | 12 | +| Slim | 1996-04-29 | 4 | +| Puffball | 1999-03-30 | 3 | ++----------+------------+--------------+ +@end example + +Finding animals with birthdays in the upcoming month is easy, too. Suppose +the current month is April. Then the month value is @code{4} and you look +for animals born in May (month 5) like this: + +@example +mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = 5; ++-------+------------+ +| name | birth | ++-------+------------+ +| Buffy | 1989-05-13 | ++-------+------------+ +@end example + +There is a small complication if the current month is December, of course. +You don't just add one to the month number (@code{12}) and look for animals +born in month 13, because there is no such month. Instead, you look for +animals born in January (month 1). + +You can even write the query so that it works no matter what the current +month is. That way you don't have to use a particular month number +in the query. @code{DATE_ADD()} allows you to add a time interval to a +given date. If you add a month to the value of @code{NOW()}, then extract +the month part with @code{MONTH()}, the result produces the month in which to +look for birthdays: + +@example +mysql> SELECT name, birth FROM pet + -> WHERE MONTH(birth) = MONTH(DATE_ADD(NOW(), INTERVAL 1 MONTH)); +@end example + +A different way to accomplish the same task is to add @code{1} to get the +next month after the current one (after using the modulo function (@code{MOD}) +to wrap around the month value to @code{0} if it is currently +@code{12}): + +@example +mysql> SELECT name, birth FROM pet + -> WHERE MONTH(birth) = MOD(MONTH(NOW()), 12) + 1; +@end example + +Note that @code{MONTH} returns a number between 1 and 12. And +@code{MOD(something,12)} returns a number between 0 and 11. So the +addition has to be after the @code{MOD()} otherwise we would go from +November (11) to January (1). + +@node Working with NULL, Pattern matching, Date calculations, Retrieving data +@subsubsection Working with @code{NULL} Values + +@findex NULL +@cindex NULL value + +The @code{NULL} value can be surprising until you get used to it. +Conceptually, @code{NULL} means missing value or unknown value and it +is treated somewhat differently than other values. To test for @code{NULL}, +you cannot use the arithmetic comparison operators such as @code{=}, @code{<}, +or @code{!=}. To demonstrate this for yourself, try the following query: + +@example +mysql> SELECT 1 = NULL, 1 != NULL, 1 < NULL, 1 > NULL; ++----------+-----------+----------+----------+ +| 1 = NULL | 1 != NULL | 1 < NULL | 1 > NULL | ++----------+-----------+----------+----------+ +| NULL | NULL | NULL | NULL | ++----------+-----------+----------+----------+ +@end example + +Clearly you get no meaningful results from these comparisons. Use +the @code{IS NULL} and @code{IS NOT NULL} operators instead: + +@example +mysql> SELECT 1 IS NULL, 1 IS NOT NULL; ++-----------+---------------+ +| 1 IS NULL | 1 IS NOT NULL | ++-----------+---------------+ +| 0 | 1 | ++-----------+---------------+ +@end example + +In @strong{MySQL}, 0 or @code{NULL} means false and anything else means true. +The default truth value from a boolean operation is 1. + +This special treatment of @code{NULL} is why, in the previous section, it +was necessary to determine which animals are no longer alive using +@code{death IS NOT NULL} instead of @code{death != NULL}. + +@node Pattern matching, Counting rows, Working with NULL, Retrieving data +@subsubsection Pattern Matching + +@cindex pattern matching +@cindex matching, patterns +@cindex expressions, extended + +@strong{MySQL} provides standard SQL pattern matching as well as a form of +pattern matching based on extended regular expressions similar to those used +by Unix utilities such as @code{vi}, @code{grep}, and @code{sed}. + +SQL pattern matching allows you to use @samp{_} to match any single +character and @samp{%} to match an arbitrary number of characters (including +zero characters). In @strong{MySQL}, SQL patterns are case insensitive by +default. Some examples are shown below. Note that you do not use @code{=} +or @code{!=} when you use SQL patterns; use the @code{LIKE} or @code{NOT +LIKE} comparison operators instead. + +To find names beginning with @samp{b}: + +@example +mysql> SELECT * FROM pet WHERE name LIKE "b%"; ++--------+--------+---------+------+------------+------------+ +| name | owner | species | sex | birth | death | ++--------+--------+---------+------+------------+------------+ +| Buffy | Harold | dog | f | 1989-05-13 | NULL | +| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | ++--------+--------+---------+------+------------+------------+ +@end example + +To find names ending with @samp{fy}: + +@example +mysql> SELECT * FROM pet WHERE name LIKE "%fy"; ++--------+--------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++--------+--------+---------+------+------------+-------+ +| Fluffy | Harold | cat | f | 1993-02-04 | NULL | +| Buffy | Harold | dog | f | 1989-05-13 | NULL | ++--------+--------+---------+------+------------+-------+ +@end example + +To find names containing a @samp{w}: + +@example +mysql> SELECT * FROM pet WHERE name LIKE "%w%"; ++----------+-------+---------+------+------------+------------+ +| name | owner | species | sex | birth | death | ++----------+-------+---------+------+------------+------------+ +| Claws | Gwen | cat | m | 1994-03-17 | NULL | +| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | +| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | ++----------+-------+---------+------+------------+------------+ +@end example + +To find names containing exactly five characters, use the @samp{_} pattern +character: + +@example +mysql> SELECT * FROM pet WHERE name LIKE "_____"; ++-------+--------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++-------+--------+---------+------+------------+-------+ +| Claws | Gwen | cat | m | 1994-03-17 | NULL | +| Buffy | Harold | dog | f | 1989-05-13 | NULL | ++-------+--------+---------+------+------------+-------+ +@end example + +The other type of pattern matching provided by @strong{MySQL} uses extended +regular expressions. When you test for a match for this type of pattern, use +the @code{REGEXP} and @code{NOT REGEXP} operators (or @code{RLIKE} and +@code{NOT RLIKE}, which are synonyms). + +Some characteristics of extended regular expressions are: + +@itemize @bullet +@item +@samp{.} matches any single character. + +@item +A character class @samp{[...]} matches any character within the brackets. +For example, @samp{[abc]} matches @samp{a}, @samp{b}, or @samp{c}. To name a +range of characters, use a dash. @samp{[a-z]} matches any lowercase letter, +whereas @samp{[0-9]} matches any digit. + +@item +@samp{*} matches zero or more instances of the thing preceding it. For +example, @samp{x*} matches any number of @samp{x} characters, +@samp{[0-9]*} matches any number of digits, and @samp{.*} matches any +number of anything. + +@item +Regular expressions are case sensitive, but you can use a character class to +match both lettercases if you wish. For example, @samp{[aA]} matches +lowercase or uppercase @samp{a} and @samp{[a-zA-Z]} matches any letter in +either case. + +@item +The pattern matches if it occurs anywhere in the value being tested. +(SQL patterns match only if they match the entire value.) + +@item +To anchor a pattern so that it must match the beginning or end of the value +being tested, use @samp{^} at the beginning or @samp{$} at the end of the +pattern. +@end itemize + +To demonstrate how extended regular expressions work, the @code{LIKE} queries +shown above are rewritten below to use @code{REGEXP}. + +To find names beginning with @samp{b}, use @samp{^} to match the beginning of +the name: + +@example +mysql> SELECT * FROM pet WHERE name REGEXP "^b"; ++--------+--------+---------+------+------------+------------+ +| name | owner | species | sex | birth | death | ++--------+--------+---------+------+------------+------------+ +| Buffy | Harold | dog | f | 1989-05-13 | NULL | +| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | ++--------+--------+---------+------+------------+------------+ +@end example + +Prior to @strong{MySQL} Version 3.23.4, @code{REGEXP} is case sensitive, +and the previous query will return no rows. To match either lowercase or +uppercase @samp{b}, use this query instead: + +@example +mysql> SELECT * FROM pet WHERE name REGEXP "^[bB]"; +@end example + +From @strong{MySQL} 3.23.4 on, to force a @code{REGEXP} comparison to +be case sensitive, use the @code{BINARY} keyword to make one of the +strings a binary string. This query will match only lowercase @samp{b} +at the beginning of a name: + +@example +mysql> SELECT * FROM pet WHERE name REGEXP BINARY "^b"; +@end example + +To find names ending with @samp{fy}, use @samp{$} to match the end of the +name: + +@example +mysql> SELECT * FROM pet WHERE name REGEXP "fy$"; ++--------+--------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++--------+--------+---------+------+------------+-------+ +| Fluffy | Harold | cat | f | 1993-02-04 | NULL | +| Buffy | Harold | dog | f | 1989-05-13 | NULL | ++--------+--------+---------+------+------------+-------+ +@end example + +To find names containing a lowercase or uppercase @samp{w}, use this query: + +@example +mysql> SELECT * FROM pet WHERE name REGEXP "w"; ++----------+-------+---------+------+------------+------------+ +| name | owner | species | sex | birth | death | ++----------+-------+---------+------+------------+------------+ +| Claws | Gwen | cat | m | 1994-03-17 | NULL | +| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | +| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | ++----------+-------+---------+------+------------+------------+ +@end example + +Because a regular expression pattern matches if it occurs anywhere in the +value, it is not necessary in the previous query to put a wild card on either +side of the pattern to get it to match the entire value like it would be if +you used a SQL pattern. + +To find names containing exactly five characters, use @samp{^} and @samp{$} +to match the beginning and end of the name, and five instances of @samp{.} +in between: + +@example +mysql> SELECT * FROM pet WHERE name REGEXP "^.....$"; ++-------+--------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++-------+--------+---------+------+------------+-------+ +| Claws | Gwen | cat | m | 1994-03-17 | NULL | +| Buffy | Harold | dog | f | 1989-05-13 | NULL | ++-------+--------+---------+------+------------+-------+ +@end example + +You could also write the previous query using the @samp{@{n@}} +``repeat-@code{n}-times'' operator: + +@example +mysql> SELECT * FROM pet WHERE name REGEXP "^.@{5@}$"; ++-------+--------+---------+------+------------+-------+ +| name | owner | species | sex | birth | death | ++-------+--------+---------+------+------------+-------+ +| Claws | Gwen | cat | m | 1994-03-17 | NULL | +| Buffy | Harold | dog | f | 1989-05-13 | NULL | ++-------+--------+---------+------+------------+-------+ +@end example + +@node Counting rows, Multiple tables, Pattern matching, Retrieving data +@subsubsection Counting Rows + +@cindex rows, counting +@cindex tables, counting rows +@cindex counting, table rows + +Databases are often used to answer the question, ``How often does a certain +type of data occur in a table?'' For example, you might want to know how +many pets you have, or how many pets each owner has, or you might want to +perform various kinds of censuses on your animals. + +Counting the total number of animals you have is the same question as ``How +many rows are in the @code{pet} table?'' because there is one record per pet. +The @code{COUNT()} function counts the number of non-@code{NULL} results, so +the query to count your animals looks like this: + +@example +mysql> SELECT COUNT(*) FROM pet; ++----------+ +| COUNT(*) | ++----------+ +| 9 | ++----------+ +@end example + +Earlier, you retrieved the names of the people who owned pets. You can +use @code{COUNT()} if you want to find out how many pets each owner has: + +@example +mysql> SELECT owner, COUNT(*) FROM pet GROUP BY owner; ++--------+----------+ +| owner | COUNT(*) | ++--------+----------+ +| Benny | 2 | +| Diane | 2 | +| Gwen | 3 | +| Harold | 2 | ++--------+----------+ +@end example + +Note the use of @code{GROUP BY} to group together all records for each +@code{owner}. Without it, all you get is an error message: + +@example +mysql> SELECT owner, COUNT(owner) FROM pet; +ERROR 1140 at line 1: Mixing of GROUP columns (MIN(),MAX(),COUNT()...) +with no GROUP columns is illegal if there is no GROUP BY clause +@end example + +@code{COUNT()} and @code{GROUP BY} are useful for characterizing your +data in various ways. The following examples show different ways to +perform animal census operations. + +Number of animals per species: + +@example +mysql> SELECT species, COUNT(*) FROM pet GROUP BY species; ++---------+----------+ +| species | COUNT(*) | ++---------+----------+ +| bird | 2 | +| cat | 2 | +| dog | 3 | +| hamster | 1 | +| snake | 1 | ++---------+----------+ +@end example + +Number of animals per sex: + +@example +mysql> SELECT sex, COUNT(*) FROM pet GROUP BY sex; ++------+----------+ +| sex | COUNT(*) | ++------+----------+ +| NULL | 1 | +| f | 4 | +| m | 4 | ++------+----------+ +@end example + +(In this output, @code{NULL} indicates sex unknown.) + +Number of animals per combination of species and sex: + +@example +mysql> SELECT species, sex, COUNT(*) FROM pet GROUP BY species, sex; ++---------+------+----------+ +| species | sex | COUNT(*) | ++---------+------+----------+ +| bird | NULL | 1 | +| bird | f | 1 | +| cat | f | 1 | +| cat | m | 1 | +| dog | f | 1 | +| dog | m | 2 | +| hamster | f | 1 | +| snake | m | 1 | ++---------+------+----------+ +@end example + +You need not retrieve an entire table when you use @code{COUNT()}. For +example, the previous query, when performed just on dogs and cats, looks like +this: + +@example +mysql> SELECT species, sex, COUNT(*) FROM pet + -> WHERE species = "dog" OR species = "cat" + -> GROUP BY species, sex; ++---------+------+----------+ +| species | sex | COUNT(*) | ++---------+------+----------+ +| cat | f | 1 | +| cat | m | 1 | +| dog | f | 1 | +| dog | m | 2 | ++---------+------+----------+ +@end example + +Or, if you wanted the number of animals per sex only for known-sex animals: + +@example +mysql> SELECT species, sex, COUNT(*) FROM pet + -> WHERE sex IS NOT NULL + -> GROUP BY species, sex; ++---------+------+----------+ +| species | sex | COUNT(*) | ++---------+------+----------+ +| bird | f | 1 | +| cat | f | 1 | +| cat | m | 1 | +| dog | f | 1 | +| dog | m | 2 | +| hamster | f | 1 | +| snake | m | 1 | ++---------+------+----------+ +@end example + +@node Multiple tables, , Counting rows, Retrieving data +@subsubsection Using More Than one Table + +@cindex tables, multiple + +The @code{pet} table keeps track of which pets you have. If you want to +record other information about them, such as events in their lives like +visits to the vet or when litters are born, you need another table. What +should this table look like? It needs: + +@itemize @bullet +@item +To contain the pet name so you know which animal each event pertains +to. + +@item +A date so you know when the event occurred. + +@item +A field to describe the event. + +@item +An event type field, if you want to be able to categorize events. +@end itemize + +Given these considerations, the @code{CREATE TABLE} statement for the +@code{event} table might look like this: + +@example +mysql> CREATE TABLE event (name VARCHAR(20), date DATE, + -> type VARCHAR(15), remark VARCHAR(255)); +@end example + +As with the @code{pet} table, it's easiest to load the initial records +by creating a tab-delimited text file containing the information: + +@multitable @columnfractions .15 .15 .15 .55 +@item Fluffy @tab 1995-05-15 @tab litter @tab 4 kittens, 3 female, 1 male +@item Buffy @tab 1993-06-23 @tab litter @tab 5 puppies, 2 female, 3 male +@item Buffy @tab 1994-06-19 @tab litter @tab 3 puppies, 3 female +@item Chirpy @tab 1999-03-21 @tab vet @tab needed beak straightened +@item Slim @tab 1997-08-03 @tab vet @tab broken rib +@item Bowser @tab 1991-10-12 @tab kennel +@item Fang @tab 1991-10-12 @tab kennel +@item Fang @tab 1998-08-28 @tab birthday @tab Gave him a new chew toy +@item Claws @tab 1998-03-17 @tab birthday @tab Gave him a new flea collar +@item Whistler @tab 1998-12-09 @tab birthday @tab First birthday +@end multitable + +Load the records like this: + +@example +mysql> LOAD DATA LOCAL INFILE "event.txt" INTO TABLE event; +@end example + +Based on what you've learned from the queries you've run on the @code{pet} +table, you should be able to perform retrievals on the records in the +@code{event} table; the principles are the same. But when is the +@code{event} table by itself insufficient to answer questions you might ask? + +Suppose you want to find out the ages of each pet when they had their +litters. The @code{event} table indicates when this occurred, but to +calculate the age of the mother, you need her birth date. Because that is +stored in the @code{pet} table, you need both tables for the query: + +@example +mysql> SELECT pet.name, (TO_DAYS(date) - TO_DAYS(birth))/365 AS age, remark + -> FROM pet, event + -> WHERE pet.name = event.name AND type = "litter"; ++--------+------+-----------------------------+ +| name | age | remark | ++--------+------+-----------------------------+ +| Fluffy | 2.27 | 4 kittens, 3 female, 1 male | +| Buffy | 4.12 | 5 puppies, 2 female, 3 male | +| Buffy | 5.10 | 3 puppies, 3 female | ++--------+------+-----------------------------+ +@end example + +There are several things to note about this query: + +@itemize @bullet +@item +The @code{FROM} clause lists two tables because the query needs to pull +information from both of them. + +@item +When combining (joining) information from multiple tables, you need to +specify how records in one table can be matched to records in the other. +This is easy because they both have a @code{name} column. The query uses +@code{WHERE} clause to match up records in the two tables based on the +@code{name} values. + +@item +Because the @code{name} column occurs in both tables, you must be specific +about which table you mean when referring to the column. This is done +by prepending the table name to the column name. +@end itemize + +You need not have two different tables to perform a join. Sometimes it is +useful to join a table to itself, if you want to compare records in a table +to other records in that same table. For example, to find breeding pairs +among your pets, you can join the @code{pet} table with itself to pair up +males and females of like species: + +@example +mysql> SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species + -> FROM pet AS p1, pet AS p2 + -> WHERE p1.species = p2.species AND p1.sex = "f" AND p2.sex = "m"; ++--------+------+--------+------+---------+ +| name | sex | name | sex | species | ++--------+------+--------+------+---------+ +| Fluffy | f | Claws | m | cat | +| Buffy | f | Fang | m | dog | +| Buffy | f | Bowser | m | dog | ++--------+------+--------+------+---------+ +@end example + +In this query, we specify aliases for the table name in order +to refer to the columns and keep straight which instance of the table +each column reference is associated with. + +@node Getting information, Examples, Database use, Tutorial +@section Getting Information About Databases and Tables + +@cindex databases, information about +@cindex tables, information about +@findex DESCRIBE + +What if you forget the name of a database or table, or what the structure of +a given table is (for example, what its columns are called)? @strong{MySQL} +addresses this problem through several statements that provide information +about the databases and tables it supports. + +You have already seen @code{SHOW DATABASES}, which lists the databases +managed by the server. To find out which database is currently selected, +use the @code{DATABASE()} function: + +@example +mysql> SELECT DATABASE(); ++------------+ +| DATABASE() | ++------------+ +| menagerie | ++------------+ +@end example + +If you haven't selected any database yet, the result is blank. + +To find out what tables the current database contains (for example, when +you're not sure about the name of a table), use this command: + +@example +mysql> SHOW TABLES; ++---------------------+ +| Tables in menagerie | ++---------------------+ +| event | +| pet | ++---------------------+ +@end example + +If you want to find out about the structure of a table, the @code{DESCRIBE} +command is useful; it displays information about each of a table's columns: + +@example +mysql> DESCRIBE pet; ++---------+-------------+------+-----+---------+-------+ +| Field | Type | Null | Key | Default | Extra | ++---------+-------------+------+-----+---------+-------+ +| name | varchar(20) | YES | | NULL | | +| owner | varchar(20) | YES | | NULL | | +| species | varchar(20) | YES | | NULL | | +| sex | char(1) | YES | | NULL | | +| birth | date | YES | | NULL | | +| death | date | YES | | NULL | | ++---------+-------------+------+-----+---------+-------+ +@end example + +@code{Field} indicates the column name, @code{Type} is the data type for +the column, @code{Null} indicates whether or not the column can contain +@code{NULL} values, @code{Key} indicates whether or not the column is +indexed, and @code{Default} specifies the column's default value. + +If you have indexes on a table, +@code{SHOW INDEX FROM tbl_name} produces information about them. + +@node Examples, Batch mode, Getting information, Tutorial +@section Examples of Common Queries + +@cindex queries, examples +@cindex examples, queries + +Here are examples of how to solve some common problems with +@strong{MySQL}. + +Some of the examples use the table @code{shop} to hold the price of each +article (item number) for certain traders (dealers). Supposing that each +trader has a single fixed price per article, then (@code{item}, +@code{trader}) is a primary key for the records. + +Start the command line tool @code{mysql} and select a database: + +@example +mysql your-database-name +@end example + +(In most @strong{MySQL} installations, you can use the database-name 'test'). + +You can create the example table as: + +@example +CREATE TABLE shop ( + article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL, + dealer CHAR(20) DEFAULT '' NOT NULL, + price DOUBLE(16,2) DEFAULT '0.00' NOT NULL, + PRIMARY KEY(article, dealer)); + +INSERT INTO shop VALUES +(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),(3,'C',1.69), +(3,'D',1.25),(4,'D',19.95); +@end example + +Okay, so the example data is: + +@example +mysql> SELECT * FROM shop; + ++---------+--------+-------+ +| article | dealer | price | ++---------+--------+-------+ +| 0001 | A | 3.45 | +| 0001 | B | 3.99 | +| 0002 | A | 10.99 | +| 0003 | B | 1.45 | +| 0003 | C | 1.69 | +| 0003 | D | 1.25 | +| 0004 | D | 19.95 | ++---------+--------+-------+ +@end example + +@menu +* example-Maximum-column:: The maximum value for a column +* example-Maximum-row:: The row holding the maximum of a certain column +* example-Maximum-column-group:: Maximum of column per group +* example-Maximum-column-group-row:: The rows holding the group-wise maximum of a certain field +* example-user-variables:: Using user variables +* example-Foreign keys:: Using foreign keys +* Searching on two keys:: +* Calculating days:: +@end menu + +@node example-Maximum-column, example-Maximum-row, Examples, Examples +@subsection The Maximum Value for a Column + +``What's the highest item number?'' + +@example +SELECT MAX(article) AS article FROM shop + ++---------+ +| article | ++---------+ +| 4 | ++---------+ +@end example + +@node example-Maximum-row, example-Maximum-column-group, example-Maximum-column, Examples +@subsection The Row Holding the Maximum of a Certain Column + +``Find number, dealer, and price of the most expensive article.'' + +In ANSI SQL this is easily done with a sub-query: + +@example +SELECT article, dealer, price +FROM shop +WHERE price=(SELECT MAX(price) FROM shop) +@end example + +In @strong{MySQL} (which does not yet have sub-selects), just do it in +two steps: + +@enumerate +@item +Get the maximum price value from the table with a @code{SELECT} statement. +@item +Using this value compile the actual query: +@example +SELECT article, dealer, price +FROM shop +WHERE price=19.95 +@end example +@end enumerate + +Another solution is to sort all rows descending by price and only +get the first row using the @strong{MySQL} specific @code{LIMIT} clause: + +@example +SELECT article, dealer, price +FROM shop +ORDER BY price DESC +LIMIT 1 +@end example + +@strong{NOTE}: If there are several most expensive articles (for example, each 19.95) +the @code{LIMIT} solution shows only one of them! + +@node example-Maximum-column-group, example-Maximum-column-group-row, example-Maximum-row, Examples +@subsection Maximum of Column per Group + +``What's the highest price per article?'' + +@example +SELECT article, MAX(price) AS price +FROM shop +GROUP BY article + ++---------+-------+ +| article | price | ++---------+-------+ +| 0001 | 3.99 | +| 0002 | 10.99 | +| 0003 | 1.69 | +| 0004 | 19.95 | ++---------+-------+ +@end example + +@node example-Maximum-column-group-row, example-user-variables, example-Maximum-column-group, Examples +@subsection The Rows Holding the Group-wise Maximum of a Certain Field + +``For each article, find the dealer(s) with the most expensive price.'' + +In ANSI SQL, I'd do it with a sub-query like this: + +@example +SELECT article, dealer, price +FROM shop s1 +WHERE price=(SELECT MAX(s2.price) + FROM shop s2 + WHERE s1.article = s2.article); +@end example + +In @strong{MySQL} it's best do it in several steps: + +@enumerate +@item +Get the list of (article,maxprice). +@item +For each article get the corresponding rows that have the stored maximum +price. +@end enumerate + +This can easily be done with a temporary table: + +@example +CREATE TEMPORARY TABLE tmp ( + article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL, + price DOUBLE(16,2) DEFAULT '0.00' NOT NULL); + +LOCK TABLES shop read; + +INSERT INTO tmp SELECT article, MAX(price) FROM shop GROUP BY article; + +SELECT shop.article, dealer, shop.price FROM shop, tmp +WHERE shop.article=tmp.article AND shop.price=tmp.price; + +UNLOCK TABLES; + +DROP TABLE tmp; +@end example + +If you don't use a @code{TEMPORARY} table, you must also lock the 'tmp' table. + +``Can it be done with a single query?'' + +Yes, but only by using a quite inefficient trick that I call the +``MAX-CONCAT trick'': + +@example +SELECT article, + SUBSTRING( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 7) AS dealer, + 0.00+LEFT( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 6) AS price +FROM shop +GROUP BY article; + ++---------+--------+-------+ +| article | dealer | price | ++---------+--------+-------+ +| 0001 | B | 3.99 | +| 0002 | A | 10.99 | +| 0003 | C | 1.69 | +| 0004 | D | 19.95 | ++---------+--------+-------+ +@end example + +The last example can, of course, be made a bit more efficient by doing the +splitting of the concatenated column in the client. + +@node example-user-variables, example-Foreign keys, example-Maximum-column-group-row, Examples +@subsection Using user variables + +You can use @strong{MySQL} user variables to remember results without +having to store them in a temporary variables in the client. +@xref{Variables}. + +For example, to find the articles with the highest and lowest price you +can do: + +@example +select @@min_price:=min(price),@@max_price:=max(price) from shop; +select * from shop where price=@@min_price or price=@@max_price; + ++---------+--------+-------+ +| article | dealer | price | ++---------+--------+-------+ +| 0003 | D | 1.25 | +| 0004 | D | 19.95 | ++---------+--------+-------+ +@end example + +@node example-Foreign keys, Searching on two keys, example-user-variables, Examples +@subsection Using Foreign Keys + +@cindex foreign keys +@cindex keys, foreign + +You don't need foreign keys to join 2 tables. + +The only thing @strong{MySQL} doesn't do is @code{CHECK} to make sure that +the keys you use really exist in the table(s) you're referencing and it +doesn't automatically delete rows from table with a foreign key +definition. If you use your keys like normal, it'll work just fine: + + +@example +CREATE TABLE persons ( + id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, + name CHAR(60) NOT NULL, + PRIMARY KEY (id) +); + +CREATE TABLE shirts ( + id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, + style ENUM('t-shirt', 'polo', 'dress') NOT NULL, + color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL, + owner SMALLINT UNSIGNED NOT NULL REFERENCES persons, + PRIMARY KEY (id) +); + + +INSERT INTO persons VALUES (NULL, 'Antonio Paz'); + +INSERT INTO shirts VALUES +(NULL, 'polo', 'blue', LAST_INSERT_ID()), +(NULL, 'dress', 'white', LAST_INSERT_ID()), +(NULL, 't-shirt', 'blue', LAST_INSERT_ID()); + + +INSERT INTO persons VALUES (NULL, 'Lilliana Angelovska'); + +INSERT INTO shirts VALUES +(NULL, 'dress', 'orange', LAST_INSERT_ID()), +(NULL, 'polo', 'red', LAST_INSERT_ID()), +(NULL, 'dress', 'blue', LAST_INSERT_ID()), +(NULL, 't-shirt', 'white', LAST_INSERT_ID()); + + +SELECT * FROM persons; ++----+---------------------+ +| id | name | ++----+---------------------+ +| 1 | Antonio Paz | +| 2 | Lilliana Angelovska | ++----+---------------------+ + +SELECT * FROM shirts; ++----+---------+--------+-------+ +| id | style | color | owner | ++----+---------+--------+-------+ +| 1 | polo | blue | 1 | +| 2 | dress | white | 1 | +| 3 | t-shirt | blue | 1 | +| 4 | dress | orange | 2 | +| 5 | polo | red | 2 | +| 6 | dress | blue | 2 | +| 7 | t-shirt | white | 2 | ++----+---------+--------+-------+ + + +SELECT s.* FROM persons p, shirts s + WHERE p.name LIKE 'Lilliana%' + AND s.owner = p.id + AND s.color <> 'white'; + ++----+-------+--------+-------+ +| id | style | color | owner | ++----+-------+--------+-------+ +| 4 | dress | orange | 2 | +| 5 | polo | red | 2 | +| 6 | dress | blue | 2 | ++----+-------+--------+-------+ +@end example + +@node Searching on two keys, Calculating days, example-Foreign keys, Examples +@subsection Searching on Two Keys + +@findex UNION +@cindex searching, two keys +@cindex keys, searching on two + +@strong{MySQL} doesn't yet optimize when you search on two different +keys combined with @code{OR} (Searching on one key with different @code{OR} +parts is optimized quite good): + +@example +SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1' +OR field2_index = '1' +@end example + +The reason is that we haven't yet had time to come up with an efficient +way to handle this in the general case. (The @code{AND} handling is, +in comparison, now completely general and works very well). + +For the moment you can solve this very efficiently by using a +@code{TEMPORARY} table. This type of optimization is also very good if +you are using very complicated queries where the SQL server does the +optimizations in the wrong order. + +@example +CREATE TEMPORARY TABLE tmp +SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1'; +INSERT INTO tmp +SELECT field1_index, field2_index FROM test_table WHERE field2_index = '1'; +SELECT * from tmp; +DROP TABLE tmp; +@end example + +The above way to solve this query is in effect an @code{UNION} of two queries. + +@node Calculating days, , Searching on two keys, Examples +@subsection Calculating visits per day + +@findex BIT_OR +@findex BIT_COUNT +@findex << +@cindex bit_functions, example + +The following shows an idea of how you can use the bit group functions +to calculate the number of days per month a user has visited a web page. + +@example +CREATE TABLE t1 (year YEAR(4), month INT(2) UNSIGNED ZEROFILL, day INT(2) UNSIGNED ZEROFILL); +INSERT INTO t1 VALUES(2000,1,1),(2000,1,20),(2000,1,30),(2000,2,2),(2000,2,23),(2000,2,23); + +SELECT year,month,BIT_COUNT(BIT_OR(1< mysql < batch-file +@end example + +If you need to specify connection parameters on the command line, the +command might look like this: + +@example +shell> mysql -h host -u user -p < batch-file +Enter password: ******** +@end example + +When you use @code{mysql} this way, you are creating a script file, then +executing the script. + +Why use a script? Here are a few reasons: + +@itemize @bullet +@item +If you run a query repeatedly (say, every day or every week), making it a +script allows you to avoid retyping it each time you execute it. + +@item +You can generate new queries from existing ones that are similar by copying +and editing script files. + +@item +Batch mode can also be useful while you're developing a query, particularly +for multiple-line commands or multiple-statement sequences of commands. If +you make a mistake, you don't have to retype everything. Just edit your +script to correct the error, then tell @code{mysql} to execute it again. + +@item +If you have a query that produces a lot of output, you can run the output +through a pager rather than watching it scroll off the top of your screen: + +@example +shell> mysql < batch-file | more +@end example + +@item +You can catch the output in a file for further processing: + +@example +shell> mysql < batch-file > mysql.out +@end example + +@item +You can distribute your script to other people so they can run the commands, +too. + +@item +Some situations do not allow for interactive use, for example, when you run +a query from a @code{cron} job. In this case, you must use batch mode. +@end itemize + +The default output format is different (more concise) when you run +@code{mysql} in batch mode than when you use it interactively. For +example, the output of @code{SELECT DISTINCT species FROM pet} looks like +this when run interactively: + +@example ++---------+ +| species | ++---------+ +| bird | +| cat | +| dog | +| hamster | +| snake | ++---------+ +@end example + +But like this when run in batch mode: + +@example +species +bird +cat +dog +hamster +snake +@end example + +If you want to get the interactive output format in batch mode, use +@code{mysql -t}. To echo to the output the commands that are executed, use +@code{mysql -vvv}. + +@node Twin, Apache, Batch mode, Tutorial +@section Queries from Twin Project + +@cindex Twin Studies, queries +@cindex queries, Twin Studeis project + +At Analytikerna and Lentus, we have been doing the systems and field work +for a big research project. This project is a collaboration between the +Institute of Environmental Medicine at Karolinska Institutet Stockholm +and the Section on Clinical Research in Aging and Psychology at the +University of Southern California. + +The project involves a screening part where all twins in Sweden older +than 65 years are interviewed by telephone. Twins who meet certain +criteria are passed on to the next stage. In this latter stage, twins who +want to participate are visited by a doctor/nurse team. Some of the +examinations include physical and neuropsychological examination, +laboratory testing, neuroimaging, psychological status assessment, and family +history collection. In addition, data are collected on medical and +environmental risk factors. + +More information about Twin studies can be found at: + +@example +@url{http://www.imm.ki.se/TWIN/TWINUKW.HTM} +@end example + +The latter part of the project is administered with a Web interface +written using Perl and @strong{MySQL}. + +Each night all data from the interviews are moved into a @strong{MySQL} +database. + +@menu +* Twin pool:: Find all non-distributed twins +* Twin event:: Show a table on twin pair status +@end menu + +@node Twin pool, Twin event, Twin, Twin +@subsection Find all Non-distributed Twins + +The following query is used to determine who goes into the second part of the +project: + +@example +select + concat(p1.id, p1.tvab) + 0 as tvid, + concat(p1.christian_name, " ", p1.surname) as Name, + p1.postal_code as Code, + p1.city as City, + pg.abrev as Area, + if(td.participation = "Aborted", "A", " ") as A, + p1.dead as dead1, + l.event as event1, + td.suspect as tsuspect1, + id.suspect as isuspect1, + td.severe as tsevere1, + id.severe as isevere1, + p2.dead as dead2, + l2.event as event2, + h2.nurse as nurse2, + h2.doctor as doctor2, + td2.suspect as tsuspect2, + id2.suspect as isuspect2, + td2.severe as tsevere2, + id2.severe as isevere2, + l.finish_date +from + twin_project as tp + /* For Twin 1 */ + left join twin_data as td on tp.id = td.id and tp.tvab = td.tvab + left join informant_data as id on tp.id = id.id and tp.tvab = id.tvab + left join harmony as h on tp.id = h.id and tp.tvab = h.tvab + left join lentus as l on tp.id = l.id and tp.tvab = l.tvab + /* For Twin 2 */ + left join twin_data as td2 on p2.id = td2.id and p2.tvab = td2.tvab + left join informant_data as id2 on p2.id = id2.id and p2.tvab = id2.tvab + left join harmony as h2 on p2.id = h2.id and p2.tvab = h2.tvab + left join lentus as l2 on p2.id = l2.id and p2.tvab = l2.tvab, + person_data as p1, + person_data as p2, + postal_groups as pg +where + /* p1 gets main twin and p2 gets his/her twin. */ + /* ptvab is a field inverted from tvab */ + p1.id = tp.id and p1.tvab = tp.tvab and + p2.id = p1.id and p2.ptvab = p1.tvab and + /* Just the sceening survey */ + tp.survey_no = 5 and + /* Skip if partner died before 65 but allow emigration (dead=9) */ + (p2.dead = 0 or p2.dead = 9 or + (p2.dead = 1 and + (p2.death_date = 0 or + (((to_days(p2.death_date) - to_days(p2.birthday)) / 365) + >= 65)))) + and + ( + /* Twin is suspect */ + (td.future_contact = 'Yes' and td.suspect = 2) or + /* Twin is suspect - Informant is Blessed */ + (td.future_contact = 'Yes' and td.suspect = 1 and id.suspect = 1) or + /* No twin - Informant is Blessed */ + (ISNULL(td.suspect) and id.suspect = 1 and id.future_contact = 'Yes') or + /* Twin broken off - Informant is Blessed */ + (td.participation = 'Aborted' + and id.suspect = 1 and id.future_contact = 'Yes') or + /* Twin broken off - No inform - Have partner */ + (td.participation = 'Aborted' and ISNULL(id.suspect) and p2.dead = 0)) + and + l.event = 'Finished' + /* Get at area code */ + and substring(p1.postal_code, 1, 2) = pg.code + /* Not already distributed */ + and (h.nurse is NULL or h.nurse=00 or h.doctor=00) + /* Has not refused or been aborted */ + and not (h.status = 'Refused' or h.status = 'Aborted' + or h.status = 'Died' or h.status = 'Other') +order by + tvid; +@end example + +Some explanations: +@table @asis +@item @code{concat(p1.id, p1.tvab) + 0 as tvid} +We want to sort on the concatenated @code{id} and @code{tvab} in +numerical order. Adding @code{0} to the result causes @strong{MySQL} to +treat the result as a number. +@item column @code{id} +This identifies a pair of twins. It is a key in all tables. +@item column @code{tvab} +This identifies a twin in a pair. It has a value of @code{1} or @code{2}. +@item column @code{ptvab} +This is an inverse of @code{tvab}. When @code{tvab} is @code{1} this is +@code{2}, and vice versa. It exists to save typing and to make it easier for +@strong{MySQL} to optimize the query. +@end table + +This query demonstrates, among other things, how to do lookups on a +table from the same table with a join (@code{p1} and @code{p2}). In the example, this +is used to check whether a twin's partner died before the age of 65. If so, +the row is not returned. + +All of the above exist in all tables with twin-related information. We +have a key on both @code{id,tvab} (all tables), and @code{id,ptvab} +(@code{person_data}) to make queries faster. + +On our production machine (A 200MHz UltraSPARC), this query returns +about 150-200 rows and takes less than one second. + +The current number of records in the tables used above: +@multitable @columnfractions .3 .5 +@item @strong{Table} @tab @strong{Rows} +@item @code{person_data} @tab 71074 +@item @code{lentus} @tab 5291 +@item @code{twin_project} @tab 5286 +@item @code{twin_data} @tab 2012 +@item @code{informant_data} @tab 663 +@item @code{harmony} @tab 381 +@item @code{postal_groups} @tab 100 +@end multitable + +@node Twin event, , Twin pool, Twin +@subsection Show a Table on Twin Pair Status + +Each interview ends with a status code called @code{event}. The query +shown below is used to display a table over all twin pairs combined by +event. This indicates in how many pairs both twins are finished, in how many +pairs one twin is finished and the other refused, and so on. + +@example +select + t1.event, + t2.event, + count(*) +from + lentus as t1, + lentus as t2, + twin_project as tp +where + /* We are looking at one pair at a time */ + t1.id = tp.id + and t1.tvab=tp.tvab + and t1.id = t2.id + /* Just the sceening survey */ + and tp.survey_no = 5 + /* This makes each pair only appear once */ + and t1.tvab='1' and t2.tvab='2' +group by + t1.event, t2.event; + +@end example + + +@node Apache, , Twin, Tutorial +@section Using MySQL with Apache + +@cindex Apache + +The Contrib section includes programs that let you authenticate your +users from a @strong{MySQL} database and also let you log your log files +into a @strong{MySQL} table. @xref{Contrib}. + +You can change the Apache logging format to be easily readable by +@strong{MySQL} by putting the following into the Apache configuration file: + +@example +LogFormat \ + "\"%h\",%@{%Y%m%d%H%M%S@}t,%>s,\"%b\",\"%@{Content-Type@}o\", \ + \"%U\",\"%@{Referer@}i\",\"%@{User-Agent@}i\"" +@end example + +In @strong{MySQL} you can do something like this: + +@example +LOAD DATA INFILE '/local/access_log' INTO TABLE table_name +FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' +@end example + + +@node Privilege system, Reference, Tutorial, Top @chapter The MySQL Access Privilege System @cindex system, security @@ -23622,7 +26050,7 @@ used them. @cindex MySQL table types @cindex @code{MyISAM} table type @cindex types, of tables -@node Table types, Tutorial, Reference, Top +@node Table types, Server, Reference, Top @chapter MySQL Table Types As of @strong{MySQL} Version 3.23.6, you can choose between three basic @@ -26037,2388 +28465,12 @@ not trivial). @end itemize -@cindex tutorial -@cindex terminal monitor, defined -@cindex monitor, terminal -@cindex options, provided by MySQL -@node Tutorial, Server, Table types, Top -@chapter MySQL Tutorial -@menu -* Connecting-disconnecting:: Connecting to and disconnecting from the server -* Entering queries:: Entering queries -* Database use:: Creating and using a database -* Getting information:: Getting information about databases and tables -* Examples:: Examples -* Batch mode:: Using @code{mysql} in batch mode -* Twin:: Queries from twin project -@end menu - -This chapter provides a tutorial introduction to @strong{MySQL} by showing -how to use the @code{mysql} client program to create and use a simple -database. @code{mysql} (sometimes referred to as the ``terminal monitor'' or -just ``monitor'') is an interactive program that allows you to connect to a -@strong{MySQL} server, run queries, and view the results. @code{mysql} may -also be used in batch mode: you place your queries in a file beforehand, then -tell @code{mysql} to execute the contents of the file. Both ways of using -@code{mysql} are covered here. - -To see a list of options provided by @code{mysql}, invoke it with -the @code{--help} option: - -@example -shell> mysql --help -@end example - -This chapter assumes that @code{mysql} is installed on your machine and that -a @strong{MySQL} server is available to which you can connect. If this is -not true, contact your @strong{MySQL} administrator. (If @emph{you} are the -administrator, you will need to consult other sections of this manual.) - -This chapter describes the entire process of setting up and using a -database. If you are interested only in accessing an already-existing -database, you may want to skip over the sections that describe how to -create the database and the tables it contains. - -Because this chapter is tutorial in nature, many details are necessarily left -out. Consult the relevant sections of the manual for more -information on the topics covered here. - -@cindex connecting, to the server -@cindex disconnecting, from the server -@cindex server, connecting -@cindex server, disconnecting -@node Connecting-disconnecting, Entering queries, Tutorial, Tutorial -@section Connecting to and Disconnecting from the Server - -To connect to the server, you'll usually need to provide a @strong{MySQL} -user name when you invoke @code{mysql} and, most likely, a password. If the -server runs on a machine other than the one where you log in, you'll also -need to specify a hostname. Contact your administrator to find out what -connection parameters you should use to connect (that is, what host, user name, -and password to use). Once you know the proper parameters, you should be -able to connect like this: - -@example -shell> mysql -h host -u user -p -Enter password: ******** -@end example - -The @code{********} represents your password; enter it when @code{mysql} -displays the @code{Enter password:} prompt. - -If that works, you should see some introductory information followed by a -@code{mysql>} prompt: - - -@example -shell> mysql -h host -u user -p -Enter password: ******** -Welcome to the MySQL monitor. Commands end with ; or \g. -Your MySQL connection id is 459 to server version: 3.22.20a-log - -Type 'help' for help. - -mysql> -@end example - -The prompt tells you that @code{mysql} is ready for you to enter commands. - -Some @strong{MySQL} installations allow users to connect as the anonymous -(unnamed) user to the server running on the local host. If this is the case -on your machine, you should be able to connect to that server by invoking -@code{mysql} without any options: - -@example -shell> mysql -@end example - -After you have connected successfully, you can disconnect any time by typing -@code{QUIT} at the @code{mysql>} prompt: - -@example -mysql> QUIT -Bye -@end example - -You can also disconnect by pressing Control-D. - -Most examples in the following sections assume you are connected to the -server. They indicate this by the @code{mysql>} prompt. - -@cindex running, queries -@cindex queries, entering -@cindex entering, queries -@node Entering queries, Database use, Connecting-disconnecting, Tutorial -@section Entering Queries - -Make sure you are connected to the server, as discussed in the previous -section. Doing so will not in itself select any database to work with, but -that's okay. At this point, it's more important to find out a little about -how to issue queries than to jump right in creating tables, loading data -into them, and retrieving data from them. This section describes the basic -principles of entering commands, using several queries you can try out to -familiarize yourself with how @code{mysql} works. - -Here's a simple command that asks the server to tell you its version number -and the current date. Type it in as shown below following the @code{mysql>} -prompt and hit the RETURN key: - -@example -mysql> SELECT VERSION(), CURRENT_DATE; -+--------------+--------------+ -| version() | CURRENT_DATE | -+--------------+--------------+ -| 3.22.20a-log | 1999-03-19 | -+--------------+--------------+ -1 row in set (0.01 sec) -mysql> -@end example - -This query illustrates several things about @code{mysql}: - -@itemize @bullet -@item -A command normally consists of a SQL statement followed by a semicolon. -(There are some exceptions where a semicolon is not needed. @code{QUIT}, -mentioned earlier, is one of them. We'll get to others later.) - -@item -When you issue a command, @code{mysql} sends it to the server for execution -and displays the results, then prints another @code{mysql>} to indicate -that it is ready for another command. - -@item -@code{mysql} displays query output as a table (rows and columns). The first -row contains labels for the columns. The rows following are the query -results. Normally, column labels are the names of the columns you fetch from -database tables. If you're retrieving the value of an expression rather than -a table column (as in the example just shown), @code{mysql} labels the column -using the expression itself. - -@item -@code{mysql} shows how many rows were returned and how long the query took -to execute, which gives you a rough idea of server performance. These values -are imprecise because they represent wall clock time (not CPU or machine -time), and because they are affected by factors such as server load and -network latency. (For brevity, the ``rows in set'' line is not shown in -the remaining examples in this chapter.) -@end itemize - -Keywords may be entered in any lettercase. The following queries are -equivalent: - -@example -mysql> SELECT VERSION(), CURRENT_DATE; -mysql> select version(), current_date; -mysql> SeLeCt vErSiOn(), current_DATE; -@end example - -Here's another query. It demonstrates that you can use @code{mysql} as a -simple calculator: - -@example -mysql> SELECT SIN(PI()/4), (4+1)*5; -+-------------+---------+ -| SIN(PI()/4) | (4+1)*5 | -+-------------+---------+ -| 0.707107 | 25 | -+-------------+---------+ -@end example - -The commands shown thus far have been relatively short, single-line -statements. You can even enter multiple statements on a single line. -Just end each one with a semicolon: - -@example -mysql> SELECT VERSION(); SELECT NOW(); -+--------------+ -| version() | -+--------------+ -| 3.22.20a-log | -+--------------+ - -+---------------------+ -| NOW() | -+---------------------+ -| 1999-03-19 00:15:33 | -+---------------------+ -@end example - -A command need not be given all on a single line, so lengthy commands that -require several lines are not a problem. @code{mysql} determines where your -statement ends by looking for the terminating semicolon, not by looking for -the end of the input line. (In other words, @code{mysql} -accepts free-format input: it collects input lines but does not execute them -until it sees the semicolon.) - -Here's a simple multiple-line statement: - -@example -mysql> SELECT - -> USER() - -> , - -> CURRENT_DATE; -+--------------------+--------------+ -| USER() | CURRENT_DATE | -+--------------------+--------------+ -| joesmith@@localhost | 1999-03-18 | -+--------------------+--------------+ -@end example - -In this example, notice how the prompt changes from @code{mysql>} to -@code{->} after you enter the first line of a multiple-line query. This is -how @code{mysql} indicates that it hasn't seen a complete statement and is -waiting for the rest. The prompt is your friend, because it provides -valuable feedback. If you use that feedback, you will always be aware of -what @code{mysql} is waiting for. - -If you decide you don't want to execute a command that you are in the -process of entering, cancel it by typing @code{\c}: - -@example -mysql> SELECT - -> USER() - -> \c -mysql> -@end example - -Here, too, notice the prompt. It switches back to @code{mysql>} after you -type @code{\c}, providing feedback to indicate that @code{mysql} is ready -for a new command. - -The following table shows each of the prompts you may see and summarizes what -they mean about the state that @code{mysql} is in: - -@cindex prompts, meanings -@multitable @columnfractions .10 .9 -@item @strong{Prompt} @tab @strong{Meaning} -@item @code{mysql>} @tab Ready for new command. -@item @code{@ @ @ @ ->} @tab Waiting for next line of multiple-line command. -@item @code{@ @ @ @ '>} @tab Waiting for next line, collecting a string that begins -with a single quote (@samp{'}). -@item @code{@ @ @ @ ">} @tab Waiting for next line, collecting a string that begins -with a double quote (@samp{"}). -@end multitable - -Multiple-line statements commonly occur by accident when you intend to -issue a command on a single line, but forget the terminating semicolon. In -this case, @code{mysql} waits for more input: - -@example -mysql> SELECT USER() - -> -@end example - -If this happens to you (you think you've entered a statement but the only -response is a @code{->} prompt), most likely @code{mysql} is waiting for the -semicolon. If you don't notice what the prompt is telling you, you might sit -there for a while before realizing what you need to do. Enter a semicolon to -complete the statement, and @code{mysql} will execute it: - -@example -mysql> SELECT USER() - -> ; -+--------------------+ -| USER() | -+--------------------+ -| joesmith@@localhost | -+--------------------+ -@end example - -The @code{'>} and @code{">} prompts occur during string collection. -In @strong{MySQL}, you can write strings surrounded by either @samp{'} -or @samp{"} characters (for example, @code{'hello'} or @code{"goodbye"}), -and @code{mysql} lets you enter strings that span multiple lines. When you -see a @code{'>} or @code{">} prompt, it means that you've entered a line -containing a string that begins with a @samp{'} or @samp{"} quote character, -but have not yet entered the matching quote that terminates the string. -That's fine if you really are entering a multiple-line string, but how likely -is that? Not very. More often, the @code{'>} and @code{">} prompts indicate -that you've inadvertantly left out a quote character. For example: - -@example -mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30; - "> -@end example - -If you enter this @code{SELECT} statement, then hit RETURN and wait for the -result, nothing will happen. Instead of wondering why this -query takes so long, notice the clue provided by the @code{">} prompt. It -tells you that @code{mysql} expects to see the rest of an unterminated -string. (Do you see the error in the statement? The string @code{"Smith} is -missing the second quote.) - -At this point, what do you do? The simplest thing is to cancel the command. -However, you cannot just type @code{\c} in this case, because @code{mysql} -interprets it as part of the string that it is collecting! Instead, enter -the closing quote character (so @code{mysql} knows you've finished the -string), then type @code{\c}: - -@example -mysql> SELECT * FROM my_table WHERE name = "Smith AND age < 30; - "> "\c -mysql> -@end example - -The prompt changes back to @code{mysql>}, indicating that @code{mysql} -is ready for a new command. - -It's important to know what the @code{'>} and @code{">} prompts signify, -because if you mistakenly enter an unterminated string, any further lines you -type will appear to be ignored by @code{mysql} --- including a line -containing @code{QUIT}! This can be quite confusing, especially if you -don't know that you need to supply the terminating quote before you can -cancel the current command. - -@cindex databases, creating -@cindex databases, using -@cindex creating, databases -@node Database use, Getting information, Entering queries, Tutorial -@section Creating and Using a Database - -@menu -* Creating database:: Creating a database -* Creating tables:: Creating a table -* Loading tables:: Loading data into a table -* Retrieving data:: Retrieving information from a table -@end menu - -Now that you know how to enter commands, it's time to access a database. - -Suppose you have several pets in your home (your menagerie) and you'd -like to keep track of various types of information about them. You can do so -by creating tables to hold your data and loading them with the desired -information. Then you can answer different sorts of questions about your -animals by retrieving data from the tables. This section shows you how to: - -@itemize @bullet -@item -Create a database -@item -Create a table -@item -Load data into the table -@item -Retrieve data from the table in various ways -@item -Use multiple tables -@end itemize - -The menagerie database will be simple (deliberately), but it is not difficult -to think of real-world situations in which a similar type of database might -be used. For example, a database like this could be used by a farmer to keep -track of livestock, or by a veterinarian to keep track of patient records. -A menagerie distribution containing some of the queries and sample data used -in the following sections can be obtained from the @strong{MySQL} Web site. -It's available in either -@uref{http://www.mysql.com/Downloads/Contrib/Examples/menagerie.tar.gz,compressed @code{tar} format} -or -@uref{http://www.mysql.com/Downloads/Contrib/Examples/menagerie.zip,Zip format}. - -Use the @code{SHOW} statement to find out what databases currently exist -on the server: - -@example -mysql> SHOW DATABASES; -+----------+ -| Database | -+----------+ -| mysql | -| test | -| tmp | -+----------+ -@end example - -The list of databases is probably different on your machine, but the -@code{mysql} and @code{test} databases are likely to be among them. The -@code{mysql} database is required because it describes user access -privileges. The @code{test} database is often provided as a workspace for -users to try things out. - -If the @code{test} database exists, try to access it: - -@example -mysql> USE test -Database changed -@end example - -Note that @code{USE}, like @code{QUIT}, does not require a semicolon. (You -can terminate such statements with a semicolon if you like; it does no harm.) -The @code{USE} statement is special in another way, too: it must be given on -a single line. - -You can use the @code{test} database (if you have access to it) for the -examples that follow, but anything you create in that database can be -removed by anyone else with access to it. For this reason, you should -probably ask your @strong{MySQL} administrator for permission to use a -database of your own. Suppose you want to call yours @code{menagerie}. The -administrator needs to execute a command like this: - -@example -mysql> GRANT ALL ON menagerie.* TO your_mysql_name; -@end example - -where @code{your_mysql_name} is the @strong{MySQL} user name assigned to -you. - -@cindex selecting, databases -@cindex databases, selecting -@node Creating database, Creating tables, Database use, Database use -@subsection Creating and Selecting a Database - -If the administrator creates your database for you when setting up your -permissions, you can begin using it. Otherwise, you need to create it -yourself: - -@example -mysql> CREATE DATABASE menagerie; -@end example - -Under Unix, database names are case sensitive (unlike SQL keywords), so you -must always refer to your database as @code{menagerie}, not as -@code{Menagerie}, @code{MENAGERIE}, or some other variant. This is also true -for table names. (Under Windows, this restriction does not apply, although -you must refer to databases and tables using the same lettercase throughout a -given query.) - -Creating a database does not select it for use; you must do that explicitly. -To make @code{menagerie} the current database, use this command: - -@example -mysql> USE menagerie -Database changed -@end example - -Your database needs to be created only once, but you must select it for use -each time you begin a @code{mysql} session. You can do this by issuing a -@code{USE} statement as shown above. Alternatively, you can select the -database on the command line when you invoke @code{mysql}. Just specify its -name after any connection parameters that you might need to provide. For -example: - -@example -shell> mysql -h host -u user -p menagerie -Enter password: ******** -@end example - -Note that @code{menagerie} is not your password on the command just shown. -If you want to supply your password on the command line after the @code{-p} -option, you must do so with no intervening space (for example, as -@code{-pmypassword}, not as @code{-p mypassword}). However, putting your -password on the command line is not recommended, because doing so exposes it -to snooping by other users logged in on your machine. - -@cindex tables, creating -@cindex creating, tables -@node Creating tables, Loading tables, Creating database, Database use -@subsection Creating a Table - -Creating the database is the easy part, but at this point it's empty, as -@code{SHOW TABLES} will tell you: - -@example -mysql> SHOW TABLES; -Empty set (0.00 sec) -@end example - -The harder part is deciding what the structure of your database should be: -what tables you will need and what columns will be in each of them. - -You'll want a table that contains a record for each of your pets. This can -be called the @code{pet} table, and it should contain, as a bare minimum, -each animal's name. Because the name by itself is not very interesting, the -table should contain other information. For example, if more than one person -in your family keeps pets, you might want to list each animal's owner. You -might also want to record some basic descriptive information such as species -and sex. - -How about age? That might be of interest, but it's not a good thing to store -in a database. Age changes as time passes, which means you'd have to update -your records often. Instead, it's better to store a fixed value such as -date of birth. Then, whenever you need age, you can calculate it as the -difference between the current date and the birth date. @strong{MySQL} -provides functions for doing date arithmetic, so this is not difficult. -Storing birth date rather than age has other advantages, too: - -@itemize @bullet -@item -You can use the database for tasks such as generating reminders for upcoming -pet birthdays. (If you think this type of query is somewhat silly, note that -it is the same question you might ask in the context of a business database -to identify clients to whom you'll soon need to send out birthday greetings, -for that computer-assisted personal touch.) - -@item -You can calculate age in relation to dates other than the current date. For -example, if you store death date in the database, you can easily calculate -how old a pet was when it died. -@end itemize - -You can probably think of other types of information that would be useful in -the @code{pet} table, but the ones identified so far are sufficient for now: -name, owner, species, sex, birth, and death. - -Use a @code{CREATE TABLE} statement to specify the layout of your table: - -@example -mysql> CREATE TABLE pet (name VARCHAR(20), owner VARCHAR(20), - -> species VARCHAR(20), sex CHAR(1), birth DATE, death DATE); -@end example - -@code{VARCHAR} is a good choice for the @code{name}, @code{owner}, and -@code{species} columns because the column values will vary in length. The -lengths of those columns need not all be the same, and need not be -@code{20}. You can pick any length from @code{1} to @code{255}, whatever -seems most reasonable to you. (If you make a poor choice and it turns -out later that you need a longer field, @strong{MySQL} provides an -@code{ALTER TABLE} statement.) - -Animal sex can be represented in a variety of ways, for example, @code{"m"} -and @code{"f"}, or perhaps @code{"male"} and @code{"female"}. It's simplest -to use the single characters @code{"m"} and @code{"f"}. - -The use of the @code{DATE} data type for the @code{birth} and @code{death} -columns is a fairly obvious choice. - -Now that you have created a table, @code{SHOW TABLES} should produce some -output: - -@example -mysql> SHOW TABLES; -+---------------------+ -| Tables in menagerie | -+---------------------+ -| pet | -+---------------------+ -@end example - -To verify that your table was created the way you expected, use -a @code{DESCRIBE} statement: - -@example -mysql> DESCRIBE pet; -+---------+-------------+------+-----+---------+-------+ -| Field | Type | Null | Key | Default | Extra | -+---------+-------------+------+-----+---------+-------+ -| name | varchar(20) | YES | | NULL | | -| owner | varchar(20) | YES | | NULL | | -| species | varchar(20) | YES | | NULL | | -| sex | char(1) | YES | | NULL | | -| birth | date | YES | | NULL | | -| death | date | YES | | NULL | | -+---------+-------------+------+-----+---------+-------+ -@end example - -You can use @code{DESCRIBE} any time, for example, if you forget the names of -the columns in your table or what types they are. - -@cindex loading, tables -@cindex tables, loading data -@cindex data, loading into tables -@node Loading tables, Retrieving data, Creating tables, Database use -@subsection Loading Data into a Table - -After creating your table, you need to populate it. The @code{LOAD DATA} and -@code{INSERT} statements are useful for this. - -Suppose your pet records can be described as shown below. -(Observe that @strong{MySQL} expects dates in @code{YYYY-MM-DD} format; -this may be different than what you are used to.) - -@multitable @columnfractions .16 .16 .16 .16 .16 .16 -@item @strong{name} @tab @strong{owner} @tab @strong{species} @tab @strong{sex} @tab @strong{birth} @tab @strong{death} -@item Fluffy @tab Harold @tab cat @tab f @tab 1993-02-04 @tab -@item Claws @tab Gwen @tab cat @tab m @tab 1994-03-17 @tab -@item Buffy @tab Harold @tab dog @tab f @tab 1989-05-13 @tab -@item Fang @tab Benny @tab dog @tab m @tab 1990-08-27 @tab -@item Bowser @tab Diane @tab dog @tab m @tab 1989-08-31 @tab 1995-07-29 -@item Chirpy @tab Gwen @tab bird @tab f @tab 1998-09-11 @tab -@item Whistler @tab Gwen @tab bird @tab @tab 1997-12-09 @tab -@item Slim @tab Benny @tab snake @tab m @tab 1996-04-29 @tab -@end multitable - -Because you are beginning with an empty table, an easy way to populate it is to -create a text file containing a row for each of your animals, then load the -contents of the file into the table with a single statement. - -You could create a text file @file{pet.txt} containing one record per line, -with values separated by tabs, and given in the order in which the columns -were listed in the @code{CREATE TABLE} statement. For missing values (such -as unknown sexes or death dates for animals that are still living), you can -use @code{NULL} values. To represent these in your text file, use -@code{\N}. For example, the record for Whistler the bird would look like -this (where the whitespace between values is a single tab character): - -@multitable @columnfractions .15 .15 .15 .15 .25 .15 -@item @code{Whistler} @tab @code{Gwen} @tab @code{bird} @tab @code{\N} @tab @code{1997-12-09} @tab @code{\N} -@end multitable - -To load the text file @file{pet.txt} into the @code{pet} table, use this -command: - -@example -mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet; -@end example - -You can specify the column value separator and end of line marker explicitly -in the @code{LOAD DATA} statement if you wish, but the defaults are tab and -linefeed. These are sufficient for the statement to read the file -@file{pet.txt} properly. - -When you want to add new records one at a time, the @code{INSERT} statement -is useful. In its simplest form, you supply values for each column, in the -order in which the columns were listed in the @code{CREATE TABLE} statement. -Suppose Diane gets a new hamster named Puffball. You could add a new record -using an @code{INSERT} statement like this: - -@example -mysql> INSERT INTO pet - -> VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL); -@end example - -Note that string and date values are specified as quoted strings here. Also, -with @code{INSERT}, you can insert @code{NULL} directly to represent a -missing value. You do not use @code{\N} like you do with @code{LOAD DATA}. - -From this example, you should be able to see that there would be a lot more -typing involved to load -your records initially using several @code{INSERT} statements rather -than a single @code{LOAD DATA} statement. - -@cindex data, retrieving -@cindex tables, retrieving data -@cindex retrieving, data from tables -@cindex unloading, tables -@node Retrieving data, , Loading tables, Database use -@subsection Retrieving Information from a Table - -@menu -* Selecting all:: Selecting all data -* Selecting rows:: Selecting particular rows -* Selecting columns:: Selecting particular columns -* Sorting rows:: Sorting rows -* Date calculations:: Date calculations -* Working with NULL:: Working with @code{NULL} values -* Pattern matching:: Pattern matching -* Counting rows:: Counting rows -* Multiple tables:: -@end menu - -The @code{SELECT} statement is used to pull information from a table. -The general form of the statement is: - -@example -SELECT what_to_select -FROM which_table -WHERE conditions_to_satisfy -@end example - -@code{what_to_select} indicates what you want to see. This can be a list of -columns, or @code{*} to indicate ``all columns.'' @code{which_table} -indicates the table from which you want to retrieve data. The @code{WHERE} -clause is optional. If it's present, @code{conditions_to_satisfy} specifies -conditions that rows must satisfy to qualify for retrieval. - -@node Selecting all, Selecting rows, Retrieving data, Retrieving data -@subsubsection Selecting All Data - -The simplest form of @code{SELECT} retrieves everything from a table: - -@example -mysql> SELECT * FROM pet; -+----------+--------+---------+------+------------+------------+ -| name | owner | species | sex | birth | death | -+----------+--------+---------+------+------------+------------+ -| Fluffy | Harold | cat | f | 1993-02-04 | NULL | -| Claws | Gwen | cat | m | 1994-03-17 | NULL | -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -| Fang | Benny | dog | m | 1990-08-27 | NULL | -| Bowser | Diane | dog | m | 1998-08-31 | 1995-07-29 | -| Chirpy | Gwen | bird | f | 1998-09-11 | NULL | -| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | -| Slim | Benny | snake | m | 1996-04-29 | NULL | -| Puffball | Diane | hamster | f | 1999-03-30 | NULL | -+----------+--------+---------+------+------------+------------+ -@end example - -This form of @code{SELECT} is useful if you want to review your entire table, -for instance, after you've just loaded it with your initial dataset. As it -happens, the output just shown reveals an error in your data file: Bowser -appears to have been born after he died! Consulting your original pedigree -papers, you find that the correct birth year is 1989, not 1998. - -There are are least a couple of ways to fix this: - -@itemize @bullet -@item -Edit the file @file{pet.txt} to correct the error, then empty the table -and reload it using @code{DELETE} and @code{LOAD DATA}: - -@example -mysql> SET AUTOCOMMIT=1; # Used for quick re-create of the table -mysql> DELETE FROM pet; -mysql> LOAD DATA LOCAL INFILE "pet.txt" INTO TABLE pet; -@end example - -However, if you do this, you must also re-enter the record for Puffball. - -@item -Fix only the erroneous record with an @code{UPDATE} statement: - -@example -mysql> UPDATE pet SET birth = "1989-08-31" WHERE name = "Bowser"; -@end example -@end itemize - -As shown above, it is easy to retrieve an entire table. But typically you -don't want to do that, particularly when the table becomes large. Instead, -you're usually more interested in answering a particular question, in which -case you specify some constraints on the information you want. Let's look at -some selection queries in terms of questions about your pets that they -answer. - -@cindex rows, selecting -@cindex tables, selecting rows -@node Selecting rows, Selecting columns, Selecting all, Retrieving data -@subsubsection Selecting Particular Rows - -You can select only particular rows from your table. For example, if you want -to verify the change that you made to Bowser's birth date, select Bowser's -record like this: - -@example -mysql> SELECT * FROM pet WHERE name = "Bowser"; -+--------+-------+---------+------+------------+------------+ -| name | owner | species | sex | birth | death | -+--------+-------+---------+------+------------+------------+ -| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | -+--------+-------+---------+------+------------+------------+ -@end example - -The output confirms that the year is correctly recorded now as 1989, not 1998. - -String comparisons are normally case insensitive, so you can specify the -name as @code{"bowser"}, @code{"BOWSER"}, etc. The query result will be -the same. - -You can specify conditions on any column, not just @code{name}. For example, -if you want to know which animals were born after 1998, test the @code{birth} -column: - -@example -mysql> SELECT * FROM pet WHERE birth >= "1998-1-1"; -+----------+-------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+----------+-------+---------+------+------------+-------+ -| Chirpy | Gwen | bird | f | 1998-09-11 | NULL | -| Puffball | Diane | hamster | f | 1999-03-30 | NULL | -+----------+-------+---------+------+------------+-------+ -@end example - -You can combine conditions, for example, to locate female dogs: - -@example -mysql> SELECT * FROM pet WHERE species = "dog" AND sex = "f"; -+-------+--------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+-------+--------+---------+------+------------+-------+ -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -+-------+--------+---------+------+------------+-------+ -@end example - -The preceding query uses the @code{AND} logical operator. There is also an -@code{OR} operator: - -@example -mysql> SELECT * FROM pet WHERE species = "snake" OR species = "bird"; -+----------+-------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+----------+-------+---------+------+------------+-------+ -| Chirpy | Gwen | bird | f | 1998-09-11 | NULL | -| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | -| Slim | Benny | snake | m | 1996-04-29 | NULL | -+----------+-------+---------+------+------------+-------+ -@end example - -@code{AND} and @code{OR} may be intermixed. If you do that, it's a good idea -to use parentheses to indicate how conditions should be grouped: - -@example -mysql> SELECT * FROM pet WHERE (species = "cat" AND sex = "m") - -> OR (species = "dog" AND sex = "f"); -+-------+--------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+-------+--------+---------+------+------------+-------+ -| Claws | Gwen | cat | m | 1994-03-17 | NULL | -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -+-------+--------+---------+------+------------+-------+ -@end example - -@cindex columns, selecting -@cindex tables, selecting columns -@node Selecting columns, Sorting rows, Selecting rows, Retrieving data -@subsubsection Selecting Particular Columns - - -If you don't want to see entire rows from your table, just name the columns -in which you're interested, separated by commas. For example, if you want to -know when your animals were born, select the @code{name} and @code{birth} -columns: - -@example -mysql> SELECT name, birth FROM pet; -+----------+------------+ -| name | birth | -+----------+------------+ -| Fluffy | 1993-02-04 | -| Claws | 1994-03-17 | -| Buffy | 1989-05-13 | -| Fang | 1990-08-27 | -| Bowser | 1989-08-31 | -| Chirpy | 1998-09-11 | -| Whistler | 1997-12-09 | -| Slim | 1996-04-29 | -| Puffball | 1999-03-30 | -+----------+------------+ -@end example - -To find out who owns pets, use this query: - -@example -mysql> SELECT owner FROM pet; -+--------+ -| owner | -+--------+ -| Harold | -| Gwen | -| Harold | -| Benny | -| Diane | -| Gwen | -| Gwen | -| Benny | -| Diane | -+--------+ -@end example - -@findex DISTINCT -However, notice that the query simply retrieves the @code{owner} field from -each record, and some of them appear more than once. To minimize the output, -retrieve each unique output record just once by adding the keyword -@code{DISTINCT}: - -@example -mysql> SELECT DISTINCT owner FROM pet; -+--------+ -| owner | -+--------+ -| Benny | -| Diane | -| Gwen | -| Harold | -+--------+ -@end example - -You can use a @code{WHERE} clause to combine row selection with column -selection. For example, to get birth dates for dogs and cats only, -use this query: - -@example -mysql> SELECT name, species, birth FROM pet - -> WHERE species = "dog" OR species = "cat"; -+--------+---------+------------+ -| name | species | birth | -+--------+---------+------------+ -| Fluffy | cat | 1993-02-04 | -| Claws | cat | 1994-03-17 | -| Buffy | dog | 1989-05-13 | -| Fang | dog | 1990-08-27 | -| Bowser | dog | 1989-08-31 | -+--------+---------+------------+ -@end example - -@cindex rows, sorting -@cindex sorting, table rows -@cindex sorting, data -@cindex tables, sorting rows -@node Sorting rows, Date calculations, Selecting columns, Retrieving data -@subsubsection Sorting Rows - -You may have noticed in the preceding examples that the result rows are -displayed in no particular order. However, it's often easier to examine -query output when the rows are sorted in some meaningful way. To sort a -result, use an @code{ORDER BY} clause. - -Here are animal birthdays, sorted by date: - -@example -mysql> SELECT name, birth FROM pet ORDER BY birth; -+----------+------------+ -| name | birth | -+----------+------------+ -| Buffy | 1989-05-13 | -| Bowser | 1989-08-31 | -| Fang | 1990-08-27 | -| Fluffy | 1993-02-04 | -| Claws | 1994-03-17 | -| Slim | 1996-04-29 | -| Whistler | 1997-12-09 | -| Chirpy | 1998-09-11 | -| Puffball | 1999-03-30 | -+----------+------------+ -@end example - -To sort in reverse order, add the @code{DESC} (descending) keyword to the -name of the column you are sorting by: - -@example -mysql> SELECT name, birth FROM pet ORDER BY birth DESC; -+----------+------------+ -| name | birth | -+----------+------------+ -| Puffball | 1999-03-30 | -| Chirpy | 1998-09-11 | -| Whistler | 1997-12-09 | -| Slim | 1996-04-29 | -| Claws | 1994-03-17 | -| Fluffy | 1993-02-04 | -| Fang | 1990-08-27 | -| Bowser | 1989-08-31 | -| Buffy | 1989-05-13 | -+----------+------------+ -@end example - -You can sort on multiple columns. For example, to sort by type of -animal, then by birth date within animal type with youngest animals first, -use the following query: - -@example -mysql> SELECT name, species, birth FROM pet ORDER BY species, birth DESC; -+----------+---------+------------+ -| name | species | birth | -+----------+---------+------------+ -| Chirpy | bird | 1998-09-11 | -| Whistler | bird | 1997-12-09 | -| Claws | cat | 1994-03-17 | -| Fluffy | cat | 1993-02-04 | -| Fang | dog | 1990-08-27 | -| Bowser | dog | 1989-08-31 | -| Buffy | dog | 1989-05-13 | -| Puffball | hamster | 1999-03-30 | -| Slim | snake | 1996-04-29 | -+----------+---------+------------+ -@end example - -Note that the @code{DESC} keyword applies only to the column name immediately -preceding it (@code{birth}); @code{species} values are still sorted in -ascending order. - -@cindex date calculations -@cindex calculating, dates -@cindex extracting, dates -@cindex age, calculating -@node Date calculations, Working with NULL, Sorting rows, Retrieving data -@subsubsection Date Calculations - -@strong{MySQL} provides several functions that you can use to perform -calculations on dates, for example, to calculate ages or extract -parts of dates. - -To determine how many years old each of your pets is, compute age as the -difference between the birth date and the current date. Do this by -converting the two dates to days, take the difference, and divide by 365 (the -number of days in a year): - -@example -mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 FROM pet; -+----------+-------------------------------------+ -| name | (TO_DAYS(NOW())-TO_DAYS(birth))/365 | -+----------+-------------------------------------+ -| Fluffy | 6.15 | -| Claws | 5.04 | -| Buffy | 9.88 | -| Fang | 8.59 | -| Bowser | 9.58 | -| Chirpy | 0.55 | -| Whistler | 1.30 | -| Slim | 2.92 | -| Puffball | 0.00 | -+----------+-------------------------------------+ -@end example - -Although the query works, there are some things about it that could be -improved. First, the result could be scanned more easily if the rows were -presented in some order. Second, the heading for the age column isn't very -meaningful. - -The first problem can be handled by adding an @code{ORDER BY name} clause to -sort the output by name. To deal with the column heading, provide a name for -the column so that a different label appears in the output (this is called a -column alias): - -@example -mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 AS age - -> FROM pet ORDER BY name; -+----------+------+ -| name | age | -+----------+------+ -| Bowser | 9.58 | -| Buffy | 9.88 | -| Chirpy | 0.55 | -| Claws | 5.04 | -| Fang | 8.59 | -| Fluffy | 6.15 | -| Puffball | 0.00 | -| Slim | 2.92 | -| Whistler | 1.30 | -+----------+------+ -@end example - -To sort the output by @code{age} rather than @code{name}, just use a -different @code{ORDER BY} clause: - -@example -mysql> SELECT name, (TO_DAYS(NOW())-TO_DAYS(birth))/365 AS age - -> FROM pet ORDER BY age; -+----------+------+ -| name | age | -+----------+------+ -| Puffball | 0.00 | -| Chirpy | 0.55 | -| Whistler | 1.30 | -| Slim | 2.92 | -| Claws | 5.04 | -| Fluffy | 6.15 | -| Fang | 8.59 | -| Bowser | 9.58 | -| Buffy | 9.88 | -+----------+------+ -@end example - -A similar query can be used to determine age at death for animals that have -died. You determine which animals these are by checking whether or not the -@code{death} value is @code{NULL}. Then, for those with non-@code{NULL} -values, compute the difference between the @code{death} and @code{birth} -values: - -@example -mysql> SELECT name, birth, death, (TO_DAYS(death)-TO_DAYS(birth))/365 AS age - -> FROM pet WHERE death IS NOT NULL ORDER BY age; -+--------+------------+------------+------+ -| name | birth | death | age | -+--------+------------+------------+------+ -| Bowser | 1989-08-31 | 1995-07-29 | 5.91 | -+--------+------------+------------+------+ -@end example - -The query uses @code{death IS NOT NULL} rather than @code{death != NULL} -because @code{NULL} is a special value. This is explained later. -@xref{Working with NULL, , Working with @code{NULL}}. - -What if you want to know which animals have birthdays next month? For this -type of calculation, year and day are irrelevant; you simply want to extract -the month part of the @code{birth} column. @strong{MySQL} provides several -date-part extraction functions, such as @code{YEAR()}, @code{MONTH()}, and -@code{DAYOFMONTH()}. @code{MONTH()} is the appropriate function here. To -see how it works, run a simple query that displays the value of both -@code{birth} and @code{MONTH(birth)}: - -@example -mysql> SELECT name, birth, MONTH(birth) FROM pet; -+----------+------------+--------------+ -| name | birth | MONTH(birth) | -+----------+------------+--------------+ -| Fluffy | 1993-02-04 | 2 | -| Claws | 1994-03-17 | 3 | -| Buffy | 1989-05-13 | 5 | -| Fang | 1990-08-27 | 8 | -| Bowser | 1989-08-31 | 8 | -| Chirpy | 1998-09-11 | 9 | -| Whistler | 1997-12-09 | 12 | -| Slim | 1996-04-29 | 4 | -| Puffball | 1999-03-30 | 3 | -+----------+------------+--------------+ -@end example - -Finding animals with birthdays in the upcoming month is easy, too. Suppose -the current month is April. Then the month value is @code{4} and you look -for animals born in May (month 5) like this: - -@example -mysql> SELECT name, birth FROM pet WHERE MONTH(birth) = 5; -+-------+------------+ -| name | birth | -+-------+------------+ -| Buffy | 1989-05-13 | -+-------+------------+ -@end example - -There is a small complication if the current month is December, of course. -You don't just add one to the month number (@code{12}) and look for animals -born in month 13, because there is no such month. Instead, you look for -animals born in January (month 1). - -You can even write the query so that it works no matter what the current -month is. That way you don't have to use a particular month number -in the query. @code{DATE_ADD()} allows you to add a time interval to a -given date. If you add a month to the value of @code{NOW()}, then extract -the month part with @code{MONTH()}, the result produces the month in which to -look for birthdays: - -@example -mysql> SELECT name, birth FROM pet - -> WHERE MONTH(birth) = MONTH(DATE_ADD(NOW(), INTERVAL 1 MONTH)); -@end example - -A different way to accomplish the same task is to add @code{1} to get the -next month after the current one (after using the modulo function (@code{MOD}) -to wrap around the month value to @code{0} if it is currently -@code{12}): - -@example -mysql> SELECT name, birth FROM pet - -> WHERE MONTH(birth) = MOD(MONTH(NOW()), 12) + 1; -@end example - -Note that @code{MONTH} returns a number between 1 and 12. And -@code{MOD(something,12)} returns a number between 0 and 11. So the -addition has to be after the @code{MOD()} otherwise we would go from -November (11) to January (1). - -@findex NULL -@cindex NULL value -@node Working with NULL, Pattern matching, Date calculations, Retrieving data -@subsubsection Working with @code{NULL} Values - -The @code{NULL} value can be surprising until you get used to it. -Conceptually, @code{NULL} means missing value or unknown value and it -is treated somewhat differently than other values. To test for @code{NULL}, -you cannot use the arithmetic comparison operators such as @code{=}, @code{<}, -or @code{!=}. To demonstrate this for yourself, try the following query: - -@example -mysql> SELECT 1 = NULL, 1 != NULL, 1 < NULL, 1 > NULL; -+----------+-----------+----------+----------+ -| 1 = NULL | 1 != NULL | 1 < NULL | 1 > NULL | -+----------+-----------+----------+----------+ -| NULL | NULL | NULL | NULL | -+----------+-----------+----------+----------+ -@end example - -Clearly you get no meaningful results from these comparisons. Use -the @code{IS NULL} and @code{IS NOT NULL} operators instead: - -@example -mysql> SELECT 1 IS NULL, 1 IS NOT NULL; -+-----------+---------------+ -| 1 IS NULL | 1 IS NOT NULL | -+-----------+---------------+ -| 0 | 1 | -+-----------+---------------+ -@end example - -In @strong{MySQL}, 0 or @code{NULL} means false and anything else means true. -The default truth value from a boolean operation is 1. - -This special treatment of @code{NULL} is why, in the previous section, it -was necessary to determine which animals are no longer alive using -@code{death IS NOT NULL} instead of @code{death != NULL}. - -@cindex pattern matching -@cindex matching, patterns -@cindex expressions, extended -@node Pattern matching, Counting rows, Working with NULL, Retrieving data -@subsubsection Pattern Matching - -@strong{MySQL} provides standard SQL pattern matching as well as a form of -pattern matching based on extended regular expressions similar to those used -by Unix utilities such as @code{vi}, @code{grep}, and @code{sed}. - -SQL pattern matching allows you to use @samp{_} to match any single -character and @samp{%} to match an arbitrary number of characters (including -zero characters). In @strong{MySQL}, SQL patterns are case insensitive by -default. Some examples are shown below. Note that you do not use @code{=} -or @code{!=} when you use SQL patterns; use the @code{LIKE} or @code{NOT -LIKE} comparison operators instead. - -To find names beginning with @samp{b}: - -@example -mysql> SELECT * FROM pet WHERE name LIKE "b%"; -+--------+--------+---------+------+------------+------------+ -| name | owner | species | sex | birth | death | -+--------+--------+---------+------+------------+------------+ -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | -+--------+--------+---------+------+------------+------------+ -@end example - -To find names ending with @samp{fy}: - -@example -mysql> SELECT * FROM pet WHERE name LIKE "%fy"; -+--------+--------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+--------+--------+---------+------+------------+-------+ -| Fluffy | Harold | cat | f | 1993-02-04 | NULL | -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -+--------+--------+---------+------+------------+-------+ -@end example - -To find names containing a @samp{w}: - -@example -mysql> SELECT * FROM pet WHERE name LIKE "%w%"; -+----------+-------+---------+------+------------+------------+ -| name | owner | species | sex | birth | death | -+----------+-------+---------+------+------------+------------+ -| Claws | Gwen | cat | m | 1994-03-17 | NULL | -| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | -| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | -+----------+-------+---------+------+------------+------------+ -@end example - -To find names containing exactly five characters, use the @samp{_} pattern -character: - -@example -mysql> SELECT * FROM pet WHERE name LIKE "_____"; -+-------+--------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+-------+--------+---------+------+------------+-------+ -| Claws | Gwen | cat | m | 1994-03-17 | NULL | -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -+-------+--------+---------+------+------------+-------+ -@end example - -The other type of pattern matching provided by @strong{MySQL} uses extended -regular expressions. When you test for a match for this type of pattern, use -the @code{REGEXP} and @code{NOT REGEXP} operators (or @code{RLIKE} and -@code{NOT RLIKE}, which are synonyms). - -Some characteristics of extended regular expressions are: - -@itemize @bullet -@item -@samp{.} matches any single character. - -@item -A character class @samp{[...]} matches any character within the brackets. -For example, @samp{[abc]} matches @samp{a}, @samp{b}, or @samp{c}. To name a -range of characters, use a dash. @samp{[a-z]} matches any lowercase letter, -whereas @samp{[0-9]} matches any digit. - -@item -@samp{*} matches zero or more instances of the thing preceding it. For -example, @samp{x*} matches any number of @samp{x} characters, -@samp{[0-9]*} matches any number of digits, and @samp{.*} matches any -number of anything. - -@item -Regular expressions are case sensitive, but you can use a character class to -match both lettercases if you wish. For example, @samp{[aA]} matches -lowercase or uppercase @samp{a} and @samp{[a-zA-Z]} matches any letter in -either case. - -@item -The pattern matches if it occurs anywhere in the value being tested. -(SQL patterns match only if they match the entire value.) - -@item -To anchor a pattern so that it must match the beginning or end of the value -being tested, use @samp{^} at the beginning or @samp{$} at the end of the -pattern. -@end itemize - -To demonstrate how extended regular expressions work, the @code{LIKE} queries -shown above are rewritten below to use @code{REGEXP}. - -To find names beginning with @samp{b}, use @samp{^} to match the beginning of -the name: - -@example -mysql> SELECT * FROM pet WHERE name REGEXP "^b"; -+--------+--------+---------+------+------------+------------+ -| name | owner | species | sex | birth | death | -+--------+--------+---------+------+------------+------------+ -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | -+--------+--------+---------+------+------------+------------+ -@end example - -Prior to @strong{MySQL} Version 3.23.4, @code{REGEXP} is case sensitive, -and the previous query will return no rows. To match either lowercase or -uppercase @samp{b}, use this query instead: - -@example -mysql> SELECT * FROM pet WHERE name REGEXP "^[bB]"; -@end example - -From @strong{MySQL} 3.23.4 on, to force a @code{REGEXP} comparison to -be case sensitive, use the @code{BINARY} keyword to make one of the -strings a binary string. This query will match only lowercase @samp{b} -at the beginning of a name: - -@example -mysql> SELECT * FROM pet WHERE name REGEXP BINARY "^b"; -@end example - -To find names ending with @samp{fy}, use @samp{$} to match the end of the -name: - -@example -mysql> SELECT * FROM pet WHERE name REGEXP "fy$"; -+--------+--------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+--------+--------+---------+------+------------+-------+ -| Fluffy | Harold | cat | f | 1993-02-04 | NULL | -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -+--------+--------+---------+------+------------+-------+ -@end example - -To find names containing a lowercase or uppercase @samp{w}, use this query: - -@example -mysql> SELECT * FROM pet WHERE name REGEXP "w"; -+----------+-------+---------+------+------------+------------+ -| name | owner | species | sex | birth | death | -+----------+-------+---------+------+------------+------------+ -| Claws | Gwen | cat | m | 1994-03-17 | NULL | -| Bowser | Diane | dog | m | 1989-08-31 | 1995-07-29 | -| Whistler | Gwen | bird | NULL | 1997-12-09 | NULL | -+----------+-------+---------+------+------------+------------+ -@end example - -Because a regular expression pattern matches if it occurs anywhere in the -value, it is not necessary in the previous query to put a wild card on either -side of the pattern to get it to match the entire value like it would be if -you used a SQL pattern. - -To find names containing exactly five characters, use @samp{^} and @samp{$} -to match the beginning and end of the name, and five instances of @samp{.} -in between: - -@example -mysql> SELECT * FROM pet WHERE name REGEXP "^.....$"; -+-------+--------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+-------+--------+---------+------+------------+-------+ -| Claws | Gwen | cat | m | 1994-03-17 | NULL | -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -+-------+--------+---------+------+------------+-------+ -@end example - -You could also write the previous query using the @samp{@{n@}} -``repeat-@code{n}-times'' operator: - -@example -mysql> SELECT * FROM pet WHERE name REGEXP "^.@{5@}$"; -+-------+--------+---------+------+------------+-------+ -| name | owner | species | sex | birth | death | -+-------+--------+---------+------+------------+-------+ -| Claws | Gwen | cat | m | 1994-03-17 | NULL | -| Buffy | Harold | dog | f | 1989-05-13 | NULL | -+-------+--------+---------+------+------------+-------+ -@end example - -@cindex rows, counting -@cindex tables, counting rows -@cindex counting, table rows -@node Counting rows, Multiple tables, Pattern matching, Retrieving data -@subsubsection Counting Rows - -Databases are often used to answer the question, ``How often does a certain -type of data occur in a table?'' For example, you might want to know how -many pets you have, or how many pets each owner has, or you might want to -perform various kinds of censuses on your animals. - -Counting the total number of animals you have is the same question as ``How -many rows are in the @code{pet} table?'' because there is one record per pet. -The @code{COUNT()} function counts the number of non-@code{NULL} results, so -the query to count your animals looks like this: - -@example -mysql> SELECT COUNT(*) FROM pet; -+----------+ -| COUNT(*) | -+----------+ -| 9 | -+----------+ -@end example - -Earlier, you retrieved the names of the people who owned pets. You can -use @code{COUNT()} if you want to find out how many pets each owner has: - -@example -mysql> SELECT owner, COUNT(*) FROM pet GROUP BY owner; -+--------+----------+ -| owner | COUNT(*) | -+--------+----------+ -| Benny | 2 | -| Diane | 2 | -| Gwen | 3 | -| Harold | 2 | -+--------+----------+ -@end example - -Note the use of @code{GROUP BY} to group together all records for each -@code{owner}. Without it, all you get is an error message: - -@example -mysql> SELECT owner, COUNT(owner) FROM pet; -ERROR 1140 at line 1: Mixing of GROUP columns (MIN(),MAX(),COUNT()...) -with no GROUP columns is illegal if there is no GROUP BY clause -@end example - -@code{COUNT()} and @code{GROUP BY} are useful for characterizing your -data in various ways. The following examples show different ways to -perform animal census operations. - -Number of animals per species: - -@example -mysql> SELECT species, COUNT(*) FROM pet GROUP BY species; -+---------+----------+ -| species | COUNT(*) | -+---------+----------+ -| bird | 2 | -| cat | 2 | -| dog | 3 | -| hamster | 1 | -| snake | 1 | -+---------+----------+ -@end example - -Number of animals per sex: - -@example -mysql> SELECT sex, COUNT(*) FROM pet GROUP BY sex; -+------+----------+ -| sex | COUNT(*) | -+------+----------+ -| NULL | 1 | -| f | 4 | -| m | 4 | -+------+----------+ -@end example - -(In this output, @code{NULL} indicates sex unknown.) - -Number of animals per combination of species and sex: - -@example -mysql> SELECT species, sex, COUNT(*) FROM pet GROUP BY species, sex; -+---------+------+----------+ -| species | sex | COUNT(*) | -+---------+------+----------+ -| bird | NULL | 1 | -| bird | f | 1 | -| cat | f | 1 | -| cat | m | 1 | -| dog | f | 1 | -| dog | m | 2 | -| hamster | f | 1 | -| snake | m | 1 | -+---------+------+----------+ -@end example - -You need not retrieve an entire table when you use @code{COUNT()}. For -example, the previous query, when performed just on dogs and cats, looks like -this: - -@example -mysql> SELECT species, sex, COUNT(*) FROM pet - -> WHERE species = "dog" OR species = "cat" - -> GROUP BY species, sex; -+---------+------+----------+ -| species | sex | COUNT(*) | -+---------+------+----------+ -| cat | f | 1 | -| cat | m | 1 | -| dog | f | 1 | -| dog | m | 2 | -+---------+------+----------+ -@end example - -Or, if you wanted the number of animals per sex only for known-sex animals: - -@example -mysql> SELECT species, sex, COUNT(*) FROM pet - -> WHERE sex IS NOT NULL - -> GROUP BY species, sex; -+---------+------+----------+ -| species | sex | COUNT(*) | -+---------+------+----------+ -| bird | f | 1 | -| cat | f | 1 | -| cat | m | 1 | -| dog | f | 1 | -| dog | m | 2 | -| hamster | f | 1 | -| snake | m | 1 | -+---------+------+----------+ -@end example - -@cindex tables, multiple -@node Multiple tables, , Counting rows, Retrieving data -@subsubsection Using More Than one Table - -The @code{pet} table keeps track of which pets you have. If you want to -record other information about them, such as events in their lives like -visits to the vet or when litters are born, you need another table. What -should this table look like? It needs: - -@itemize @bullet -@item -To contain the pet name so you know which animal each event pertains -to. - -@item -A date so you know when the event occurred. - -@item -A field to describe the event. - -@item -An event type field, if you want to be able to categorize events. -@end itemize - -Given these considerations, the @code{CREATE TABLE} statement for the -@code{event} table might look like this: - -@example -mysql> CREATE TABLE event (name VARCHAR(20), date DATE, - -> type VARCHAR(15), remark VARCHAR(255)); -@end example - -As with the @code{pet} table, it's easiest to load the initial records -by creating a tab-delimited text file containing the information: - -@multitable @columnfractions .15 .15 .15 .55 -@item Fluffy @tab 1995-05-15 @tab litter @tab 4 kittens, 3 female, 1 male -@item Buffy @tab 1993-06-23 @tab litter @tab 5 puppies, 2 female, 3 male -@item Buffy @tab 1994-06-19 @tab litter @tab 3 puppies, 3 female -@item Chirpy @tab 1999-03-21 @tab vet @tab needed beak straightened -@item Slim @tab 1997-08-03 @tab vet @tab broken rib -@item Bowser @tab 1991-10-12 @tab kennel -@item Fang @tab 1991-10-12 @tab kennel -@item Fang @tab 1998-08-28 @tab birthday @tab Gave him a new chew toy -@item Claws @tab 1998-03-17 @tab birthday @tab Gave him a new flea collar -@item Whistler @tab 1998-12-09 @tab birthday @tab First birthday -@end multitable - -Load the records like this: - -@example -mysql> LOAD DATA LOCAL INFILE "event.txt" INTO TABLE event; -@end example - -Based on what you've learned from the queries you've run on the @code{pet} -table, you should be able to perform retrievals on the records in the -@code{event} table; the principles are the same. But when is the -@code{event} table by itself insufficient to answer questions you might ask? - -Suppose you want to find out the ages of each pet when they had their -litters. The @code{event} table indicates when this occurred, but to -calculate the age of the mother, you need her birth date. Because that is -stored in the @code{pet} table, you need both tables for the query: - -@example -mysql> SELECT pet.name, (TO_DAYS(date) - TO_DAYS(birth))/365 AS age, remark - -> FROM pet, event - -> WHERE pet.name = event.name AND type = "litter"; -+--------+------+-----------------------------+ -| name | age | remark | -+--------+------+-----------------------------+ -| Fluffy | 2.27 | 4 kittens, 3 female, 1 male | -| Buffy | 4.12 | 5 puppies, 2 female, 3 male | -| Buffy | 5.10 | 3 puppies, 3 female | -+--------+------+-----------------------------+ -@end example - -There are several things to note about this query: - -@itemize @bullet -@item -The @code{FROM} clause lists two tables because the query needs to pull -information from both of them. - -@item -When combining (joining) information from multiple tables, you need to -specify how records in one table can be matched to records in the other. -This is easy because they both have a @code{name} column. The query uses -@code{WHERE} clause to match up records in the two tables based on the -@code{name} values. - -@item -Because the @code{name} column occurs in both tables, you must be specific -about which table you mean when referring to the column. This is done -by prepending the table name to the column name. -@end itemize - -You need not have two different tables to perform a join. Sometimes it is -useful to join a table to itself, if you want to compare records in a table -to other records in that same table. For example, to find breeding pairs -among your pets, you can join the @code{pet} table with itself to pair up -males and females of like species: - -@example -mysql> SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species - -> FROM pet AS p1, pet AS p2 - -> WHERE p1.species = p2.species AND p1.sex = "f" AND p2.sex = "m"; -+--------+------+--------+------+---------+ -| name | sex | name | sex | species | -+--------+------+--------+------+---------+ -| Fluffy | f | Claws | m | cat | -| Buffy | f | Fang | m | dog | -| Buffy | f | Bowser | m | dog | -+--------+------+--------+------+---------+ -@end example - -In this query, we specify aliases for the table name in order -to refer to the columns and keep straight which instance of the table -each column reference is associated with. - -@cindex databases, information about -@cindex tables, information about -@findex DESCRIBE -@node Getting information, Examples, Database use, Tutorial -@section Getting Information About Databases and Tables - -What if you forget the name of a database or table, or what the structure of -a given table is (for example, what its columns are called)? @strong{MySQL} -addresses this problem through several statements that provide information -about the databases and tables it supports. - -You have already seen @code{SHOW DATABASES}, which lists the databases -managed by the server. To find out which database is currently selected, -use the @code{DATABASE()} function: - -@example -mysql> SELECT DATABASE(); -+------------+ -| DATABASE() | -+------------+ -| menagerie | -+------------+ -@end example - -If you haven't selected any database yet, the result is blank. - -To find out what tables the current database contains (for example, when -you're not sure about the name of a table), use this command: - -@example -mysql> SHOW TABLES; -+---------------------+ -| Tables in menagerie | -+---------------------+ -| event | -| pet | -+---------------------+ -@end example - -If you want to find out about the structure of a table, the @code{DESCRIBE} -command is useful; it displays information about each of a table's columns: - -@example -mysql> DESCRIBE pet; -+---------+-------------+------+-----+---------+-------+ -| Field | Type | Null | Key | Default | Extra | -+---------+-------------+------+-----+---------+-------+ -| name | varchar(20) | YES | | NULL | | -| owner | varchar(20) | YES | | NULL | | -| species | varchar(20) | YES | | NULL | | -| sex | char(1) | YES | | NULL | | -| birth | date | YES | | NULL | | -| death | date | YES | | NULL | | -+---------+-------------+------+-----+---------+-------+ -@end example - -@code{Field} indicates the column name, @code{Type} is the data type for -the column, @code{Null} indicates whether or not the column can contain -@code{NULL} values, @code{Key} indicates whether or not the column is -indexed, and @code{Default} specifies the column's default value. - -If you have indexes on a table, -@code{SHOW INDEX FROM tbl_name} produces information about them. - -@cindex queries, examples -@cindex examples, queries -@node Examples, Batch mode, Getting information, Tutorial -@section Examples of Common Queries - -Here are examples of how to solve some common problems with -@strong{MySQL}. - -Some of the examples use the table @code{shop} to hold the price of each -article (item number) for certain traders (dealers). Supposing that each -trader has a single fixed price per article, then (@code{item}, -@code{trader}) is a primary key for the records. - -Start the command line tool @code{mysql} and select a database: - -@example -mysql your-database-name -@end example - -(In most @strong{MySQL} installations, you can use the database-name 'test'). - -You can create the example table as: - -@example -CREATE TABLE shop ( - article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL, - dealer CHAR(20) DEFAULT '' NOT NULL, - price DOUBLE(16,2) DEFAULT '0.00' NOT NULL, - PRIMARY KEY(article, dealer)); - -INSERT INTO shop VALUES -(1,'A',3.45),(1,'B',3.99),(2,'A',10.99),(3,'B',1.45),(3,'C',1.69), -(3,'D',1.25),(4,'D',19.95); -@end example - -Okay, so the example data is: - -@example -mysql> SELECT * FROM shop; - -+---------+--------+-------+ -| article | dealer | price | -+---------+--------+-------+ -| 0001 | A | 3.45 | -| 0001 | B | 3.99 | -| 0002 | A | 10.99 | -| 0003 | B | 1.45 | -| 0003 | C | 1.69 | -| 0003 | D | 1.25 | -| 0004 | D | 19.95 | -+---------+--------+-------+ -@end example - -@menu -* example-Maximum-column:: The maximum value for a column -* example-Maximum-row:: The row holding the maximum of a certain column -* example-Maximum-column-group:: Maximum of column per group -* example-Maximum-column-group-row:: The rows holding the group-wise maximum of a certain field -* example-user-variables:: Using user variables -* example-Foreign keys:: Using foreign keys -* Searching on two keys:: -* Calculating days:: -@end menu - -@node example-Maximum-column, example-Maximum-row, Examples, Examples -@subsection The Maximum Value for a Column - -``What's the highest item number?'' - -@example -SELECT MAX(article) AS article FROM shop - -+---------+ -| article | -+---------+ -| 4 | -+---------+ -@end example - -@node example-Maximum-row, example-Maximum-column-group, example-Maximum-column, Examples -@subsection The Row Holding the Maximum of a Certain Column - -``Find number, dealer, and price of the most expensive article.'' - -In ANSI SQL this is easily done with a sub-query: - -@example -SELECT article, dealer, price -FROM shop -WHERE price=(SELECT MAX(price) FROM shop) -@end example - -In @strong{MySQL} (which does not yet have sub-selects), just do it in -two steps: - -@enumerate -@item -Get the maximum price value from the table with a @code{SELECT} statement. -@item -Using this value compile the actual query: -@example -SELECT article, dealer, price -FROM shop -WHERE price=19.95 -@end example -@end enumerate - -Another solution is to sort all rows descending by price and only -get the first row using the @strong{MySQL} specific @code{LIMIT} clause: - -@example -SELECT article, dealer, price -FROM shop -ORDER BY price DESC -LIMIT 1 -@end example - -@strong{NOTE}: If there are several most expensive articles (for example, each 19.95) -the @code{LIMIT} solution shows only one of them! - -@node example-Maximum-column-group, example-Maximum-column-group-row, example-Maximum-row, Examples -@subsection Maximum of Column per Group - -``What's the highest price per article?'' - -@example -SELECT article, MAX(price) AS price -FROM shop -GROUP BY article - -+---------+-------+ -| article | price | -+---------+-------+ -| 0001 | 3.99 | -| 0002 | 10.99 | -| 0003 | 1.69 | -| 0004 | 19.95 | -+---------+-------+ -@end example - -@node example-Maximum-column-group-row, example-user-variables, example-Maximum-column-group, Examples -@subsection The Rows Holding the Group-wise Maximum of a Certain Field - -``For each article, find the dealer(s) with the most expensive price.'' - -In ANSI SQL, I'd do it with a sub-query like this: - -@example -SELECT article, dealer, price -FROM shop s1 -WHERE price=(SELECT MAX(s2.price) - FROM shop s2 - WHERE s1.article = s2.article); -@end example - -In @strong{MySQL} it's best do it in several steps: - -@enumerate -@item -Get the list of (article,maxprice). -@item -For each article get the corresponding rows that have the stored maximum -price. -@end enumerate - -This can easily be done with a temporary table: - -@example -CREATE TEMPORARY TABLE tmp ( - article INT(4) UNSIGNED ZEROFILL DEFAULT '0000' NOT NULL, - price DOUBLE(16,2) DEFAULT '0.00' NOT NULL); - -LOCK TABLES shop read; - -INSERT INTO tmp SELECT article, MAX(price) FROM shop GROUP BY article; - -SELECT shop.article, dealer, shop.price FROM shop, tmp -WHERE shop.article=tmp.article AND shop.price=tmp.price; - -UNLOCK TABLES; - -DROP TABLE tmp; -@end example - -If you don't use a @code{TEMPORARY} table, you must also lock the 'tmp' table. - -``Can it be done with a single query?'' - -Yes, but only by using a quite inefficient trick that I call the -``MAX-CONCAT trick'': - -@example -SELECT article, - SUBSTRING( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 7) AS dealer, - 0.00+LEFT( MAX( CONCAT(LPAD(price,6,'0'),dealer) ), 6) AS price -FROM shop -GROUP BY article; - -+---------+--------+-------+ -| article | dealer | price | -+---------+--------+-------+ -| 0001 | B | 3.99 | -| 0002 | A | 10.99 | -| 0003 | C | 1.69 | -| 0004 | D | 19.95 | -+---------+--------+-------+ -@end example - -The last example can, of course, be made a bit more efficient by doing the -splitting of the concatenated column in the client. - -@node example-user-variables, example-Foreign keys, example-Maximum-column-group-row, Examples -@subsection Using user variables - -You can use @strong{MySQL} user variables to remember results without -having to store them in a temporary variables in the client. -@xref{Variables}. - -For example, to find the articles with the highest and lowest price you -can do: - -@example -select @@min_price:=min(price),@@max_price:=max(price) from shop; -select * from shop where price=@@min_price or price=@@max_price; - -+---------+--------+-------+ -| article | dealer | price | -+---------+--------+-------+ -| 0003 | D | 1.25 | -| 0004 | D | 19.95 | -+---------+--------+-------+ -@end example - -@cindex foreign keys -@cindex keys, foreign -@node example-Foreign keys, Searching on two keys, example-user-variables, Examples -@subsection Using Foreign Keys - -You don't need foreign keys to join 2 tables. - -The only thing @strong{MySQL} doesn't do is @code{CHECK} to make sure that -the keys you use really exist in the table(s) you're referencing and it -doesn't automatically delete rows from table with a foreign key -definition. If you use your keys like normal, it'll work just fine: - - -@example -CREATE TABLE persons ( - id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, - name CHAR(60) NOT NULL, - PRIMARY KEY (id) -); - -CREATE TABLE shirts ( - id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT, - style ENUM('t-shirt', 'polo', 'dress') NOT NULL, - color ENUM('red', 'blue', 'orange', 'white', 'black') NOT NULL, - owner SMALLINT UNSIGNED NOT NULL REFERENCES persons, - PRIMARY KEY (id) -); - - -INSERT INTO persons VALUES (NULL, 'Antonio Paz'); - -INSERT INTO shirts VALUES -(NULL, 'polo', 'blue', LAST_INSERT_ID()), -(NULL, 'dress', 'white', LAST_INSERT_ID()), -(NULL, 't-shirt', 'blue', LAST_INSERT_ID()); - - -INSERT INTO persons VALUES (NULL, 'Lilliana Angelovska'); - -INSERT INTO shirts VALUES -(NULL, 'dress', 'orange', LAST_INSERT_ID()), -(NULL, 'polo', 'red', LAST_INSERT_ID()), -(NULL, 'dress', 'blue', LAST_INSERT_ID()), -(NULL, 't-shirt', 'white', LAST_INSERT_ID()); - - -SELECT * FROM persons; -+----+---------------------+ -| id | name | -+----+---------------------+ -| 1 | Antonio Paz | -| 2 | Lilliana Angelovska | -+----+---------------------+ - -SELECT * FROM shirts; -+----+---------+--------+-------+ -| id | style | color | owner | -+----+---------+--------+-------+ -| 1 | polo | blue | 1 | -| 2 | dress | white | 1 | -| 3 | t-shirt | blue | 1 | -| 4 | dress | orange | 2 | -| 5 | polo | red | 2 | -| 6 | dress | blue | 2 | -| 7 | t-shirt | white | 2 | -+----+---------+--------+-------+ - - -SELECT s.* FROM persons p, shirts s - WHERE p.name LIKE 'Lilliana%' - AND s.owner = p.id - AND s.color <> 'white'; - -+----+-------+--------+-------+ -| id | style | color | owner | -+----+-------+--------+-------+ -| 4 | dress | orange | 2 | -| 5 | polo | red | 2 | -| 6 | dress | blue | 2 | -+----+-------+--------+-------+ -@end example - -@findex UNION -@cindex searching, two keys -@cindex keys, searching on two -@node Searching on two keys, Calculating days, example-Foreign keys, Examples -@subsection Searching on Two Keys - -@strong{MySQL} doesn't yet optimize when you search on two different -keys combined with @code{OR} (Searching on one key with different @code{OR} -parts is optimized quite good): - -@example -SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1' -OR field2_index = '1' -@end example - -The reason is that we haven't yet had time to come up with an efficient -way to handle this in the general case. (The @code{AND} handling is, -in comparison, now completely general and works very well). - -For the moment you can solve this very efficiently by using a -@code{TEMPORARY} table. This type of optimization is also very good if -you are using very complicated queries where the SQL server does the -optimizations in the wrong order. - -@example -CREATE TEMPORARY TABLE tmp -SELECT field1_index, field2_index FROM test_table WHERE field1_index = '1'; -INSERT INTO tmp -SELECT field1_index, field2_index FROM test_table WHERE field2_index = '1'; -SELECT * from tmp; -DROP TABLE tmp; -@end example - -The above way to solve this query is in effect an @code{UNION} of two queries. - -@cindex bit_functions, example -@findex BIT_OR -@findex BIT_COUNT -@findex << -@node Calculating days, , Searching on two keys, Examples -@subsection Calculating visits per day - -The following shows an idea of how you can use the bit group functions -to calculate the number of days per month a user has visited a web page. - -@example -CREATE TABLE t1 (year YEAR(4), month INT(2) UNSIGNED ZEROFILL, day INT(2) UNSIGNED ZEROFILL); -INSERT INTO t1 VALUES(2000,1,1),(2000,1,20),(2000,1,30),(2000,2,2),(2000,2,23),(2000,2,23); - -SELECT year,month,BIT_COUNT(BIT_OR(1< mysql < batch-file -@end example - -If you need to specify connection parameters on the command line, the -command might look like this: - -@example -shell> mysql -h host -u user -p < batch-file -Enter password: ******** -@end example - -When you use @code{mysql} this way, you are creating a script file, then -executing the script. - -Why use a script? Here are a few reasons: - -@itemize @bullet -@item -If you run a query repeatedly (say, every day or every week), making it a -script allows you to avoid retyping it each time you execute it. - -@item -You can generate new queries from existing ones that are similar by copying -and editing script files. - -@item -Batch mode can also be useful while you're developing a query, particularly -for multiple-line commands or multiple-statement sequences of commands. If -you make a mistake, you don't have to retype everything. Just edit your -script to correct the error, then tell @code{mysql} to execute it again. - -@item -If you have a query that produces a lot of output, you can run the output -through a pager rather than watching it scroll off the top of your screen: - -@example -shell> mysql < batch-file | more -@end example - -@item -You can catch the output in a file for further processing: - -@example -shell> mysql < batch-file > mysql.out -@end example - -@item -You can distribute your script to other people so they can run the commands, -too. - -@item -Some situations do not allow for interactive use, for example, when you run -a query from a @code{cron} job. In this case, you must use batch mode. -@end itemize - -The default output format is different (more concise) when you run -@code{mysql} in batch mode than when you use it interactively. For -example, the output of @code{SELECT DISTINCT species FROM pet} looks like -this when run interactively: - -@example -+---------+ -| species | -+---------+ -| bird | -| cat | -| dog | -| hamster | -| snake | -+---------+ -@end example - -But like this when run in batch mode: - -@example -species -bird -cat -dog -hamster -snake -@end example - -If you want to get the interactive output format in batch mode, use -@code{mysql -t}. To echo to the output the commands that are executed, use -@code{mysql -vvv}. - -@cindex Twin Studies, queries -@cindex queries, Twin Studeis project -@node Twin, , Batch mode, Tutorial -@section Queries from Twin Project - -At Analytikerna and Lentus, we have been doing the systems and field work -for a big research project. This project is a collaboration between the -Institute of Environmental Medicine at Karolinska Institutet Stockholm -and the Section on Clinical Research in Aging and Psychology at the -University of Southern California. - -The project involves a screening part where all twins in Sweden older -than 65 years are interviewed by telephone. Twins who meet certain -criteria are passed on to the next stage. In this latter stage, twins who -want to participate are visited by a doctor/nurse team. Some of the -examinations include physical and neuropsychological examination, -laboratory testing, neuroimaging, psychological status assessment, and family -history collection. In addition, data are collected on medical and -environmental risk factors. - -More information about Twin studies can be found at: - -@example -@url{http://www.imm.ki.se/TWIN/TWINUKW.HTM} -@end example - -The latter part of the project is administered with a Web interface -written using Perl and @strong{MySQL}. - -Each night all data from the interviews are moved into a @strong{MySQL} -database. - -@menu -* Twin pool:: Find all non-distributed twins -* Twin event:: Show a table on twin pair status -@end menu - -@node Twin pool, Twin event, Twin, Twin -@subsection Find all Non-distributed Twins - -The following query is used to determine who goes into the second part of the -project: - -@example -select - concat(p1.id, p1.tvab) + 0 as tvid, - concat(p1.christian_name, " ", p1.surname) as Name, - p1.postal_code as Code, - p1.city as City, - pg.abrev as Area, - if(td.participation = "Aborted", "A", " ") as A, - p1.dead as dead1, - l.event as event1, - td.suspect as tsuspect1, - id.suspect as isuspect1, - td.severe as tsevere1, - id.severe as isevere1, - p2.dead as dead2, - l2.event as event2, - h2.nurse as nurse2, - h2.doctor as doctor2, - td2.suspect as tsuspect2, - id2.suspect as isuspect2, - td2.severe as tsevere2, - id2.severe as isevere2, - l.finish_date -from - twin_project as tp - /* For Twin 1 */ - left join twin_data as td on tp.id = td.id and tp.tvab = td.tvab - left join informant_data as id on tp.id = id.id and tp.tvab = id.tvab - left join harmony as h on tp.id = h.id and tp.tvab = h.tvab - left join lentus as l on tp.id = l.id and tp.tvab = l.tvab - /* For Twin 2 */ - left join twin_data as td2 on p2.id = td2.id and p2.tvab = td2.tvab - left join informant_data as id2 on p2.id = id2.id and p2.tvab = id2.tvab - left join harmony as h2 on p2.id = h2.id and p2.tvab = h2.tvab - left join lentus as l2 on p2.id = l2.id and p2.tvab = l2.tvab, - person_data as p1, - person_data as p2, - postal_groups as pg -where - /* p1 gets main twin and p2 gets his/her twin. */ - /* ptvab is a field inverted from tvab */ - p1.id = tp.id and p1.tvab = tp.tvab and - p2.id = p1.id and p2.ptvab = p1.tvab and - /* Just the sceening survey */ - tp.survey_no = 5 and - /* Skip if partner died before 65 but allow emigration (dead=9) */ - (p2.dead = 0 or p2.dead = 9 or - (p2.dead = 1 and - (p2.death_date = 0 or - (((to_days(p2.death_date) - to_days(p2.birthday)) / 365) - >= 65)))) - and - ( - /* Twin is suspect */ - (td.future_contact = 'Yes' and td.suspect = 2) or - /* Twin is suspect - Informant is Blessed */ - (td.future_contact = 'Yes' and td.suspect = 1 and id.suspect = 1) or - /* No twin - Informant is Blessed */ - (ISNULL(td.suspect) and id.suspect = 1 and id.future_contact = 'Yes') or - /* Twin broken off - Informant is Blessed */ - (td.participation = 'Aborted' - and id.suspect = 1 and id.future_contact = 'Yes') or - /* Twin broken off - No inform - Have partner */ - (td.participation = 'Aborted' and ISNULL(id.suspect) and p2.dead = 0)) - and - l.event = 'Finished' - /* Get at area code */ - and substring(p1.postal_code, 1, 2) = pg.code - /* Not already distributed */ - and (h.nurse is NULL or h.nurse=00 or h.doctor=00) - /* Has not refused or been aborted */ - and not (h.status = 'Refused' or h.status = 'Aborted' - or h.status = 'Died' or h.status = 'Other') -order by - tvid; -@end example - -Some explanations: -@table @asis -@item @code{concat(p1.id, p1.tvab) + 0 as tvid} -We want to sort on the concatenated @code{id} and @code{tvab} in -numerical order. Adding @code{0} to the result causes @strong{MySQL} to -treat the result as a number. -@item column @code{id} -This identifies a pair of twins. It is a key in all tables. -@item column @code{tvab} -This identifies a twin in a pair. It has a value of @code{1} or @code{2}. -@item column @code{ptvab} -This is an inverse of @code{tvab}. When @code{tvab} is @code{1} this is -@code{2}, and vice versa. It exists to save typing and to make it easier for -@strong{MySQL} to optimize the query. -@end table - -This query demonstrates, among other things, how to do lookups on a -table from the same table with a join (@code{p1} and @code{p2}). In the example, this -is used to check whether a twin's partner died before the age of 65. If so, -the row is not returned. - -All of the above exist in all tables with twin-related information. We -have a key on both @code{id,tvab} (all tables), and @code{id,ptvab} -(@code{person_data}) to make queries faster. - -On our production machine (A 200MHz UltraSPARC), this query returns -about 150-200 rows and takes less than one second. - -The current number of records in the tables used above: -@multitable @columnfractions .3 .5 -@item @strong{Table} @tab @strong{Rows} -@item @code{person_data} @tab 71074 -@item @code{lentus} @tab 5291 -@item @code{twin_project} @tab 5286 -@item @code{twin_data} @tab 2012 -@item @code{informant_data} @tab 663 -@item @code{harmony} @tab 381 -@item @code{postal_groups} @tab 100 -@end multitable - -@node Twin event, , Twin pool, Twin -@subsection Show a Table on Twin Pair Status - -Each interview ends with a status code called @code{event}. The query -shown below is used to display a table over all twin pairs combined by -event. This indicates in how many pairs both twins are finished, in how many -pairs one twin is finished and the other refused, and so on. - -@example -select - t1.event, - t2.event, - count(*) -from - lentus as t1, - lentus as t2, - twin_project as tp -where - /* We are looking at one pair at a time */ - t1.id = tp.id - and t1.tvab=tp.tvab - and t1.id = t2.id - /* Just the sceening survey */ - and tp.survey_no = 5 - /* This makes each pair only appear once */ - and t1.tvab='1' and t2.tvab='2' -group by - t1.event, t2.event; - -@end example +@node Server, Replication, Table types, Top +@chapter MySQL Server Functions @cindex functions, server @cindex server functions -@node Server, Replication, Tutorial, Top -@chapter MySQL Server Functions @menu * Languages:: What languages are supported by @strong{MySQL}? @@ -28428,12 +28480,13 @@ This chapter describes the languages @strong{MySQL} supports, how sorting works in @strong{MySQL}, and how to add new character sets to @strong{MySQL}. You will also find information about maximum table sizes in this chapter. +@node Languages, , Server, Server +@section What Languages Are Supported by MySQL? + @cindex error messages, languages @cindex messages, languages @cindex files, error messages @cindex language support -@node Languages, , Server, Server -@section What Languages Are Supported by MySQL? @code{mysqld} can issue error messages in the following languages: Czech, Danish, Dutch, English (the default), Estonian, French, German, Greek, @@ -36579,7 +36632,6 @@ likely it is that we can fix the problem! @chapter Using MySQL with Some Common Programs @menu -* Apache:: Using @strong{MySQL} with Apache * Borland C++:: @end menu @@ -36596,32 +36648,9 @@ Find some tips on how to compile @strong{MySQL} and @strong{MySQL}-based programs using Borland C++. @end itemize -@cindex Apache -@node Apache, Borland C++, Common programs, Common programs -@section Using MySQL with Apache - -The Contrib section includes programs that let you authenticate your -users from a @strong{MySQL} database and also let you log your log files -into a @strong{MySQL} table. @xref{Contrib}. - -You can change the Apache logging format to be easily readable by -@strong{MySQL} by putting the following into the Apache configuration file: - -@example -LogFormat \ - "\"%h\",%@{%Y%m%d%H%M%S@}t,%>s,\"%b\",\"%@{Content-Type@}o\", \ - \"%U\",\"%@{Referer@}i\",\"%@{User-Agent@}i\"" -@end example - -In @strong{MySQL} you can do something like this: - -@example -LOAD DATA INFILE '/local/access_log' INTO TABLE table_name -FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' -@end example @cindex Borland C++ compiler -@node Borland C++, , Apache, Common programs +@node Borland C++, , Common programs, Common programs @section Borland C++ You can compile the @strong{MySQL} Windows source with Borland C++ 5.02. From 9563e658c986be854453215d22c7e090c4132df6 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 31 Jul 2001 09:45:14 -0500 Subject: [PATCH 18/51] small fix per user email --- Docs/manual.texi | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 28b0638936a..230f73e5804 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -28312,7 +28312,7 @@ For disaster recovery, one should use table backups plus @strong{MySQL}'s binary log. @xref{Backup}. @strong{Warning}: If you delete old log files that are in use, BDB will -not be able to do recovery at all and you may loose data if something +not be able to do recovery at all and you may lose data if something goes wrong. @item @strong{MySQL} requires a @code{PRIMARY KEY} in each BDB table to be From ef049e69fa0c082be39fec1c3c79dedc78049a13 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 1 Aug 2001 15:17:39 -0500 Subject: [PATCH 19/51] DocTOC Chapter 4 Complete! --- Docs/manual.texi | 15583 +++++++++++++++++++++++---------------------- 1 file changed, 7964 insertions(+), 7619 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 230f73e5804..aa3e03c3b2d 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -113,15 +113,12 @@ distribution for that version. * Introduction:: General Information about @strong{MySQL} * Installing:: Installing @strong{MySQL} * Tutorial:: @strong{MySQL} Tutorial -* Privilege system:: The @strong{MySQL} access privilege system +* MySQL Database Administration:: * Reference:: @strong{MySQL} language reference * Table types:: @strong{MySQL} table types -* Server:: @strong{MySQL} Server -* Replication:: Replication * Fulltext Search:: Fulltext Search * Performance:: Getting maximum performance from @strong{MySQL} * MySQL Benchmarks:: The @strong{MySQL} benchmark suite -* Tools:: @strong{MySQL} Utilities * Maintenance:: Maintaining a @strong{MySQL} installation * Adding functions:: Adding new functions to @strong{MySQL} * Adding procedures:: Adding new procedures to @strong{MySQL} @@ -129,7 +126,6 @@ distribution for that version. * Common programs:: Using @strong{MySQL} with some common programs * Problems:: Problems * Common problems:: Solving some common problems with @strong{MySQL} -* Log files:: * Clients:: @strong{MySQL} client tools and APIs * MySQL internals:: @strong{MySQL} internals * Environment variables:: @strong{MySQL} environment variables @@ -11856,7 +11852,7 @@ We are interested in finding someone to do a port, and we will help them with any technical questions they may have while doing the port. -@node Tutorial, Privilege system, Installing, Top +@node Tutorial, MySQL Database Administration, Installing, Top @chapter Introduction to MySQL: A MySQL Tutorial @cindex tutorial @@ -14284,8 +14280,682 @@ FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' @end example -@node Privilege system, Reference, Tutorial, Top -@chapter The MySQL Access Privilege System +@node MySQL Database Administration, Reference, Tutorial, Top +@chapter MySQL Database Administration + +@menu +* Configuring MySQL:: +* Installing many servers:: +* Privilege system:: +* User Account Management:: +* Disaster Prevention:: +* Database Administration:: +* KILL:: +* Localization:: +* Server-Side Scripts:: +* Client-Side Scripts:: +* perror:: +* Batch Commands:: +* Log Files:: +* Log file maintenance:: +* Replication:: +* Replication HOWTO:: +@end menu + + +@node Configuring MySQL, Installing many servers, MySQL Database Administration, MySQL Database Administration +@section Configuring MySQL + + +@menu +* Command-line options:: +* Option files:: +@end menu + +@node Command-line options, Option files, Configuring MySQL, Configuring MySQL +@subsection mysqld Command-line Options + +@findex command-line options +@cindex options, command-line +@cindex mysqld options + +@code{mysqld} accepts the following command-line options: + +@table @code +@item --ansi +Use ANSI SQL syntax instead of MySQL syntax. @xref{ANSI mode}. + +@item -b, --basedir=path +Path to installation directory. All paths are usually resolved relative to +this. + +@item --big-tables +Allow big result sets by saving all temporary sets on file. It solves +most 'table full' errors, but also slows down the queries where +in-memory tables would suffice. Since Version 3.23.2, @strong{MySQL} is +able to solve it automatically by using memory for small temporary +tables and switching to disk tables where necessary. + +@item --bind-address=IP +IP address to bind to. + +@item --character-sets-dir=path +Directory where character sets are. @xref{Character sets}. + +@item --chroot=path +Chroot @code{mysqld} daemon during startup. Recommended security measure. It will +somewhat limit @code{LOAD DATA INFILE} and @code{SELECT ... INTO OUTFILE} +though. + +@item --core-file +Write a core file if @code{mysqld} dies. For some systems you must also +specify @code{--core-file-size} to @code{safe_mysqld}. @xref{safe_mysqld, , +@code{safe_mysqld}}. + +@item -h, --datadir=path +Path to the database root. + +@item --default-character-set=charset +Set the default character set. @xref{Character sets}. + +@item --default-table-type=type +Set the default table type for tables. @xref{Table types}. + +@item --debug[...]= +If @strong{MySQL} is configured with @code{--with-debug}, you can use this +option to get a trace file of what @code{mysqld} is doing. +@xref{Making trace files}. + +@item --delay-key-write-for-all-tables +Don't flush key buffers between writes for any @code{MyISAM} table. +@xref{Server parameters}. + +@item --enable-locking +Enable system locking. Note that if you use this option on a system +which a not fully working lockd() (as on Linux) you will easily get +mysqld to deadlock. + +@item -T, --exit-info +This is a bit mask of different flags one can use for debugging the +mysqld server; One should not use this option if one doesn't know +exactly what it does! + +@item --flush +Flush all changes to disk after each SQL command. Normally @strong{MySQL} +only does a write of all changes to disk after each SQL command and lets +the operating system handle the syncing to disk. +@xref{Crashing}. + +@item -?, --help +Display short help and exit. + +@item --init-file=file +Read SQL commands from this file at startup. + +@item -L, --language=... +Client error messages in given language. May be given as a full path. +@xref{Languages}. + +@item -l, --log[=file] +Log connections and queries to file. @xref{Query log}. + +@item --log-isam[=file] +Log all ISAM/MyISAM changes to file (only used when debugging ISAM/MyISAM). + +@item --log-slow-queries[=file] +Log all queries that have taken more than @code{long_query_time} seconds to +execute to file. @xref{Slow query log}. + +@item --log-update[=file] +Log updates to @code{file.#} where @code{#} is a unique number if not given. +@xref{Update log}. + +@item --log-long-format +Log some extra information to update log. If you are using +@code{--log-slow-queries} then queries that are not using indexes are logged +to the slow query log. + +@item --low-priority-updates +Table-modifying operations (@code{INSERT}/@code{DELETE}/@code{UPDATE}) +will have lower priority than selects. It can also be done via +@code{@{INSERT | REPLACE | UPDATE | DELETE@} LOW_PRIORITY ...} to lower +the priority of only one query, or by +@code{SET OPTION SQL_LOW_PRIORITY_UPDATES=1} to change the priority in one +thread. @xref{Table locking}. + +@item --memlock +Lock the @code{mysqld} process in memory. This works only if your +system supports the @code{mlockall()} system call (like Solaris). This +may help if you have a problem where the operating system is causing +@code{mysqld} to swap on disk. + +@item --myisam-recover [=option[,option...]]] where option is one of DEFAULT, BACKUP, FORCE or QUICK. +If this option is used, @code{mysqld} will on open check if the table is +marked as crashed or if if the table wasn't closed properly. (The last +option only works if you are running with @code{--skip-locking}). If this +is the case @code{mysqld} will run check on the table. If the table was corrupted, +@code{mysqld} will attempt to repair it. + +The following options affects how the repair works. + +@multitable @columnfractions .3 .7 +@item DEFAULT @tab The same as not giving any option to + @code{--myisam-recover}. +@item BACKUP @tab If the data table was changed during recover, save a + backup of the @file{table_name.MYD} data file as + @file{table_name-datetime.BAK}. +@item FORCE @tab Run recover even if we will loose more than one row + from the .MYD file. +@item QUICK @tab Don't check the rows in the table if there isn't any + delete blocks. +@end multitable + +Before a table is automatically repaired, @strong{MySQL} will add a note +about this in the error log. If you want to be able to recover from most +things without user intervention, you should use the options +@code{BACKUP,FORCE}. This will force a repair of a table even if some rows +would be deleted, but it will keep the old data file as a backup so that +you can later examine what happened. + +@item --pid-file=path +Path to pid file used by @code{safe_mysqld}. + +@item -P, --port=... +Port number to listen for TCP/IP connections. + +@item -o, --old-protocol +Use the 3.20 protocol for compatibility with some very old clients. +@xref{Upgrading-from-3.20}. + +@item --one-thread +Only use one thread (for debugging under Linux). @xref{Debugging server}. + +@item -O, --set-variable var=option +Give a variable a value. @code{--help} lists variables. You can find a full +description for all variables in the @code{SHOW VARIABLES} section in this +manual. @xref{SHOW VARIABLES}. The tuning server parameters section includes +information of how to optimize these. @xref{Server parameters}. + +@item --safe-mode +Skip some optimize stages. Implies @code{--skip-delay-key-write}. + +@item --safe-show-database +Don't show databases for which the user doesn't have any privileges. + +@item --secure +IP numbers returned by the @code{gethostbyname()} system call are +checked to make sure they resolve back to the original hostname. This +makes it harder for someone on the outside to get access by pretending +to be another host. This option also adds some sanity checks of +hostnames. The option is turned off by default in @strong{MySQL} Version 3.21 +because sometimes it takes a long time to perform backward resolutions. +@strong{MySQL} Version 3.22 caches hostnames (unless @code{--skip-host-cache} +is used) and has this option enabled by default. + +@item --skip-concurrent-insert +Turn off the ability to select and insert at the same time on @code{MyISAM} +tables. (This is only to be used if you think you have found a bug in this +feature). + +@item --skip-delay-key-write +Ignore the @code{delay_key_write} option for all tables. +@xref{Server parameters}. + +@item --skip-grant-tables +This option causes the server not to use the privilege system at all. This +gives everyone @emph{full access} to all databases! (You can tell a running +server to start using the grant tables again by executing @code{mysqladmin +flush-privileges} or @code{mysqladmin reload}.) + +@item --skip-host-cache +Never use host name cache for faster name-ip resolution, but query DNS server +on every connect instead. @xref{DNS}. + +@item --skip-locking +Don't use system locking. To use @code{isamchk} or @code{myisamchk} you must +shut down the server. @xref{Stability}. Note that in @strong{MySQL} Version +3.23 you can use @code{REPAIR} and @code{CHECK} to repair/check @code{MyISAM} +tables. + +@item --skip-name-resolve +Hostnames are not resolved. All @code{Host} column values in the grant tables +must be IP numbers or @code{localhost}. @xref{DNS}. + +@item --skip-networking +Don't listen for TCP/IP connections at all. All interaction with +@code{mysqld} must be made via Unix sockets. This option is highly +recommended for systems where only local requests are allowed. @xref{DNS}. + +@item --skip-new +Don't use new, possible wrong routines. Implies @code{--skip-delay-key-write}. +This will also set default table type to @code{ISAM}. @xref{ISAM}. + +@item --skip-symlink +Don't delete or rename files that a symlinked file in the data directory +points to. + +@item --skip-safemalloc +If @strong{MySQL} is configured with @code{--with-debug=full}, all programs +will check the memory for overruns for every memory allocation and memory +freeing. As this checking is very slow, you can avoid this, when you don't +need memory checking, by using this option. + +@item --skip-show-database +Don't allow 'SHOW DATABASE' commands, unless the user has @strong{process} +privilege. + +@item --skip-stack-trace +Don't write stack traces. This option is useful when you are running +@code{mysqld} under a debugger. @xref{Debugging server}. + +@item --skip-thread-priority +Disable using thread priorities for faster response time. + +@item --socket=path +Socket file to use for local connections instead of default +@code{/tmp/mysql.sock}. + +@item transaction-isolation= @{ READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE @} +Sets the default transaction isolation level. @xref{SET TRANSACTION}. + +@item -t, --tmpdir=path +Path for temporary files. It may be useful if your default @code{/tmp} +directory resides on a partition too small to hold temporary tables. + +@item -u, --user=user_name +Run @code{mysqld} daemon as user @code{user_name}. This option is +@emph{mandatory} when starting @code{mysqld} as root. + +@item -V, --version +Output version information and exit. + +@item -W, --warnings +Print out warnings like @code{Aborted connection...} to the @code{.err} file. +@xref{Communication errors}. +@end table + + +@node Option files, , Command-line options, Configuring MySQL +@subsection my.cnf Option Files + +@cindex default options +@cindex option files +@cindex creating, default startup options +@cindex startup options, default + +@strong{MySQL} can, since Version 3.22, read default startup options for the +server and for clients from option files. + +@strong{MySQL} reads default options from the following files on Unix: + +@tindex .my.cnf file +@multitable @columnfractions .3 .7 +@item @strong{Filename} @tab @strong{Purpose} +@item @code{/etc/my.cnf} @tab Global options +@item @code{DATADIR/my.cnf} @tab Server-specific options +@item @code{defaults-extra-file} @tab The file specified with --defaults-extra-file=# +@item @code{~/.my.cnf} @tab User-specific options +@end multitable + +@code{DATADIR} is the @strong{MySQL} data directory (typically +@file{/usr/local/mysql/data} for a binary installation or +@file{/usr/local/var} for a source installation). Note that this is the +directory that was specified at configuration time, not the one specified +with @code{--datadir} when @code{mysqld} starts up! (@code{--datadir} has no +effect on where the server looks for option files, because it looks for them +before it processes any command-line arguments.) + +@strong{MySQL} reads default options from the following files on Windows: + +@multitable @columnfractions .3 .7 +@item @strong{Filename} @tab @strong{Purpose} +@item @code{windows-system-directory\my.ini} @tab Global options +@item @code{C:\my.cnf} @tab Global options +@item @code{C:\mysql\data\my.cnf} @tab Server-specific options +@end multitable + +Note that on Windows, you should specify all paths with @code{/} instead of +@code{\}. If you use @code{\}, you need to specify this twice, as +@code{\} is the escape character in @strong{MySQL}. + +@cindex Environment variables +@strong{MySQL} tries to read option files in the order listed above. If +multiple option files exist, an option specified in a file read later takes +precedence over the same option specified in a file read earlier. Options +specified on the command line take precedence over options specified in any +option file. Some options can be specified using environment variables. +Options specified on the command line or in option files take precedence over +environment variable values. @xref{Environment variables}. + +The following programs support option files: @code{mysql}, +@code{mysqladmin}, @code{mysqld}, @code{mysqldump}, @code{mysqlimport}, +@code{mysql.server}, @code{myisamchk}, and @code{myisampack}. + +You can use option files to specify any long option that a program supports! +Run the program with @code{--help} to get a list of available options. + +An option file can contain lines of the following forms: + +@table @code +@item #comment +Comment lines start with @samp{#} or @samp{;}. Empty lines are ignored. + +@item [group] +@code{group} is the name of the program or group for which you want to set +options. After a group line, any @code{option} or @code{set-variable} lines +apply to the named group until the end of the option file or another group +line is given. + +@item option +This is equivalent to @code{--option} on the command line. + +@item option=value +This is equivalent to @code{--option=value} on the command line. + +@item set-variable = variable=value +This is equivalent to @code{--set-variable variable=value} on the command line. +This syntax must be used to set a @code{mysqld} variable. +@end table + +The @code{client} group allows you to specify options that apply to all +@strong{MySQL} clients (not @code{mysqld}). This is the perfect group to use +to specify the password you use to connect to the server. (But make +sure the option file is readable and writable only by yourself.) + +Note that for options and values, all leading and trailing blanks are +automatically deleted. You may use the escape sequences @samp{\b}, +@samp{\t}, @samp{\n}, @samp{\r}, @samp{\\}, and @samp{\s} in your value string +(@samp{\s} == blank). + +Here is a typical global option file: + +@example +[client] +port=3306 +socket=/tmp/mysql.sock + +[mysqld] +port=3306 +socket=/tmp/mysql.sock +set-variable = key_buffer_size=16M +set-variable = max_allowed_packet=1M + +[mysqldump] +quick +@end example + +Here is typical user option file: + +@example +[client] +# The following password will be sent to all standard MySQL clients +password=my_password + +[mysql] +no-auto-rehash +set-variable = connect_timeout=2 + +[mysqlhotcopy] +interactive-timeout + +@end example + +@tindex .my.cnf file +If you have a source distribution, you will find sample configuration +files named @file{my-xxxx.cnf} in the @file{support-files} directory. +If you have a binary distribution, look in the @file{DIR/support-files} +directory, where @code{DIR} is the pathname to the @strong{MySQL} +installation directory (typically @file{/usr/local/mysql}). Currently +there are sample configuration files for small, medium, large, and very +large systems. You can copy @file{my-xxxx.cnf} to your home directory +(rename the copy to @file{.my.cnf}) to experiment with this. + +All @strong{MySQL} clients that support option files support the +following options: + +@multitable @columnfractions .40 .60 +@item --no-defaults @tab Don't read any option files. +@item --print-defaults @tab Print the program name and all options that it will get. +@item --defaults-file=full-path-to-default-file @tab Only use the given configuration file. +@item --defaults-extra-file=full-path-to-default-file @tab Read this configuration file after the global configuration file but before the user configuration file. +@end multitable + +Note that the above options must be first on the command line to work! +@code{--print-defaults} may however be used directly after the +@code{--defaults-xxx-file} commands. + +Note for developers: Option file handling is implemented simply by +processing all matching options (that is, options in the appropriate group) +before any command-line arguments. This works nicely for programs that use +the last instance of an option that is specified multiple times. If you have +an old program that handles multiply-specified options this way but doesn't +read option files, you need add only two lines to give it that capability. +Check the source code of any of the standard @strong{MySQL} clients to see +how to do this. + +In shell scripts you can use the @file{my_print_defaults} command to parse the +config files: + +@example + +shell> my_print_defaults client mysql +--port=3306 +--socket=/tmp/mysql.sock +--no-auto-rehash +@end example + +The above output contains all options for the groups 'client' and 'mysql'. + + +@node Installing many servers, Privilege system, Configuring MySQL, MySQL Database Administration +@appendixsec Installing Many Servers on the Same Machine + +@cindex post-install, many servers +@cindex Installing many servers +@cindex Starting many servers + +In some cases you may want to have many different @code{mysqld} daemons +(servers) running on the same machine. You may for example want to run +a new version of @strong{MySQL} for testing together with an old version +that is in production. Another case is when you want to give different +users access to different @code{mysqld} servers that they manage themselves. + +One way to get a new server running is by starting it with a different +socket and port as follows: + +@tindex MYSQL_UNIX_PORT environment variable +@tindex MYSQL_TCP_PORT environment variable +@tindex Environment variable, MYSQL_UNIX_PORT +@tindex Environment variable, MYSQL_TCP_PORT +@example +shell> MYSQL_UNIX_PORT=/tmp/mysqld-new.sock +shell> MYSQL_TCP_PORT=3307 +shell> export MYSQL_UNIX_PORT MYSQL_TCP_PORT +shell> scripts/mysql_install_db +shell> bin/safe_mysqld & +@end example + +The environment variables appendix includes a list of other environment +variables you can use to affect @code{mysqld}. @xref{Environment variables}. + +The above is the quick and dirty way that one commonly uses for testing. +The nice thing with this is that all connections you do in the above shell +will automatically be directed to the new running server! + +If you need to do this more permanently, you should create an option +file for each server. @xref{Option files}. In your startup script that +is executed at boot time (mysql.server?) you should specify for both +servers: + +@code{safe_mysqld --default-file=path-to-option-file} + +At least the following options should be different per server: + +@table @code +@item port=# +@item socket=path +@item pid-file=path +@end table + +The following options should be different, if they are used: + +@table @code +@item log=path +@item log-bin=path +@item log-update=path +@item log-isam=path +@item bdb-logdir=path +@end table + +If you want more performance, you can also specify the following differently: + +@table @code +@item tmpdir=path +@item bdb-tmpdir=path +@end table + +@xref{Command-line options}. + +If you are installing binary @strong{MySQL} versions (.tar files) and +start them with @code{./bin/safe_mysqld} then in most cases the only +option you need to add/change is the @code{socket} and @code{port} +argument to @code{safe_mysqld}. + + +@menu +* Multiple servers:: +@end menu + +@node Multiple servers, , Installing many servers, Installing many servers +@subsection Running Multiple MySQL Servers on the Same Machine + +@cindex multiple servers +@cindex servers, multiple +@cindex running, multiple servers + +There are circumstances when you might want to run multiple servers on the same +machine. For example, you might want to test a new @strong{MySQL} release +while leaving your existing production setup undisturbed. Or you might +be an Internet service provider that wants to provide independent +@strong{MySQL} installations for different customers. + +If you want to run multiple servers, the easiest way is to compile the servers +with different TCP/IP ports and socket files so they are not +both listening to the same TCP/IP port or socket file. @xref{mysqld_multi, , +@code{mysqld_multi}}. + +Assume an existing server is configured for the default port number and +socket file. Then configure the new server with a @code{configure} command +something like this: + +@example +shell> ./configure --with-tcp-port=port_number \ + --with-unix-socket-path=file_name \ + --prefix=/usr/local/mysql-3.22.9 +@end example + +Here @code{port_number} and @code{file_name} should be different than the +default port number and socket file pathname, and the @code{--prefix} value +should specify an installation directory different than the one under which +the existing @strong{MySQL} installation is located. + +You can check the socket used by any currently executing @strong{MySQL} server +with this command: + +@example +shell> mysqladmin -h hostname --port=port_number variables +@end example + +Note that if you specify ``@code{localhost}'' as a hostname, @code{mysqladmin} +will default to using Unix sockets instead of TCP/IP. + +If you have a @strong{MySQL} server running on the port you used, you will +get a list of some of the most important configurable variables in +@strong{MySQL}, including the socket name. + +You don't have to recompile a new @strong{MySQL} server just to start with +a different port and socket. You can change the port and socket to be used +by specifying them at run time as options to @code{safe_mysqld}: + +@example +shell> /path/to/safe_mysqld --socket=file_name --port=port_number +@end example + +@code{mysqld_multi} can also take @code{safe_mysqld} (or @code{mysqld}) +as an argument and pass the options from a configuration file to +@code{safe_mysqld} and further to @code{mysqld}. + +If you run the new server on the same database directory as another +server with logging enabled, you should also specify the name of the log +files to @code{safe_mysqld} with @code{--log}, @code{--log-update}, or +@code{--log-slow-queries}. Otherwise, both servers may be trying to +write to the same log file. + +@strong{WARNING}: Normally you should never have two servers that update +data in the same database! If your OS doesn't support fault-free system +locking, this may lead to unpleasant surprises! + +If you want to use another database directory for the second server, you +can use the @code{--datadir=path} option to @code{safe_mysqld}. + +@strong{NOTE} also that starting several @strong{MySQL} servers +(@code{mysqlds}) in different machines and letting them access one data +directory over @code{NFS} is generally a @strong{BAD IDEA}! The problem +is that the @code{NFS} will become the bottleneck with the speed. It is +not meant for such use. And last but not least, you would still have to +come up with a solution how to make sure that two or more @code{mysqlds} +are not interfering with each other. At the moment there is no platform +that would 100% reliable do the file locking (@code{lockd} daemon +usually) in every situation. Yet there would be one more possible risk +with @code{NFS}; it would make the work even more complicated for +@code{lockd} daemon to handle. So make it easy for your self and forget +about the idea. The working solution is to have one computer with an +operating system that efficiently handles threads and have several CPUs +in it. + +When you want to connect to a @strong{MySQL} server that is running with +a different port than the port that is compiled into your client, you +can use one of the following methods: + +@itemize @bullet +@item +Start the client with @code{--host 'hostname' --port=port_number} to connect +with TCP/IP, or @code{[--host localhost] --socket=file_name} to connect via +a Unix socket. + +@item +In your C or Perl programs, you can give the port or socket arguments +when connecting to the @strong{MySQL} server. + +@item +If your are using the Perl @code{DBD::mysql} module you can read the options +from the @strong{MySQL} option files. @xref{Option files}. + +@example +$dsn = "DBI:mysql:test;mysql_read_default_group=client;mysql_read_default_file=/usr/local/mysql/data/my.cnf" +$dbh = DBI->connect($dsn, $user, $password); +@end example + +@item +@tindex MYSQL_UNIX_PORT environment variable +@tindex MYSQL_TCP_PORT environment variable +@tindex environment variable, MYSQL_UNIX_PORT +@tindex environment variable, MYSQL_TCP_PORT +Set the @code{MYSQL_UNIX_PORT} and @code{MYSQL_TCP_PORT} environment variables +to point to the Unix socket and TCP/IP port before you start your clients. +If you normally use a specific socket or port, you should place commands +to set these environment variables in your @file{.login} file. +@xref{Environment variables}. + +@item +@tindex .my.cnf file +Specify the default socket and TCP/IP port in the @file{.my.cnf} file in your +home directory. @xref{Option files}. +@end itemize + + +@node Privilege system, User Account Management, Installing many servers, MySQL Database Administration +@section General Security Issues and the MySQL Access Privilege System @cindex system, security @cindex access privileges @@ -14293,7 +14963,6 @@ FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' @cindex security system @cindex ACLs - @strong{MySQL} has an advanced but non-standard security/privilege system. This section describes how it works. @@ -14302,22 +14971,17 @@ system. This section describes how it works. * Security:: How to make @strong{MySQL} secure against crackers * Privileges options:: * What Privileges:: What the privilege system does -* User names:: @strong{MySQL} user names and passwords -* Connecting:: Connecting to the @strong{MySQL} server -* Password security:: Keeping your password secure -* Privileges provided:: Privileges provided by @strong{MySQL} * Privileges:: How the privilege system works +* Privileges provided:: Privileges provided by @strong{MySQL} +* Connecting:: Connecting to the @strong{MySQL} server * Connection access:: Access control, stage 1: Connection verification * Request access:: Access control, stage 2: Request verification -* Privilege changes:: When privilege changes take effect -* Default privileges:: Setting up the initial @strong{MySQL} privileges -* Adding users:: Adding new users to @strong{MySQL} -* Passwords:: How to set up passwords * Access denied:: Causes of @code{Access denied} errors @end menu + @node General security, Security, Privilege system, Privilege system -@section General Security +@subsection General Security Guidelines Anyone using @strong{MySQL} on a computer connected to the Internet should read this section to avoid the most common security mistakes. @@ -14501,8 +15165,10 @@ actually mean that it is encrypted. If you need high security, you should consult with a security expert. @end itemize + @node Security, Privileges options, General security, Privilege system -@section How to Make MySQL Secure Against Crackers +@subsection How to Make MySQL Secure Against Crackers + @cindex crackers, security against @cindex security, against crackers @@ -14620,7 +15286,7 @@ can do this by setting the @code{max_user_connections} variable in @end itemize @node Privileges options, What Privileges, Security, Privilege system -@section Startup Options for @code{mysqld} Concerning Security +@subsection Startup Options for @code{mysqld} Concerning Security The following @code{mysqld} options affect networking security: @@ -14662,8 +15328,10 @@ some kind of privilege. @end table -@node What Privileges, User names, Privileges options, Privilege system -@section What the Privilege System Does + +@node What Privileges, Privileges, Privileges options, Privilege system +@subsection What the Privilege System Does + @cindex system, privilege @cindex privilege system @cindex passwords, security @@ -14677,391 +15345,10 @@ Additional functionality includes the ability to have an anonymous user and to grant privileges for @strong{MySQL}-specific functions such as @code{LOAD DATA INFILE} and administrative operations. -@node User names, Connecting, What Privileges, Privilege system -@section MySQL User Names and Passwords -@cindex user names, and passwords -@cindex passwords, for users -There are several distinctions between the way user names and passwords are -used by @strong{MySQL} and the way they are used by Unix or Windows: +@node Privileges, Privileges provided, What Privileges, Privilege system +@subsection How the Privilege System Works -@itemize @bullet -@item -User names, as used by @strong{MySQL} for authentication purposes, have -nothing to do with Unix user names (login names) or Windows user names. Most -@strong{MySQL} clients by default try to log in using the current Unix user -name as the @strong{MySQL} user name, but that is for convenience only. -Client programs allow a different name to be specified with the @code{-u} or -@code{--user} options. This means that you can't make a database secure in -any way unless all @strong{MySQL} user names have passwords. Anyone may -attempt to connect to the server using any name, and they will succeed if -they specify any name that doesn't have a password. - -@item -@strong{MySQL} user names can be up to 16 characters long; Unix user names -typically are limited to 8 characters. - -@item -@strong{MySQL} passwords have nothing to do with Unix passwords. There is no -necessary connection between the password you use to log in to a Unix machine -and the password you use to access a database on that machine. - -@item -@strong{MySQL} encrypts passwords using a different algorithm than the -one used during the Unix login process. See the descriptions of the -@code{PASSWORD()} and @code{ENCRYPT()} functions in @ref{Miscellaneous -functions}. Note that even if the password is stored 'scrambled', and -knowing your 'scrambled' password is enough to be able to connect to -the @strong{MySQL} server! -@end itemize - -@strong{MySQL} users and they privileges are normally created with the -@code{GRANT} command. @xref{GRANT}. - -When you login to a @strong{MySQL} server with a command line client you -should specify the password with @code{--password=your-password}. -@xref{Connecting}. - -@example -mysql --user=monty --password=guess database_name -@end example - -If you want the client to prompt for a password, you should use -@code{--password} without any argument - -@example -mysql --user=monty --password database_name -@end example - -or the short form: - -@example -mysql -u monty -p database_name -@end example - -Note that in the last example the password is @strong{NOT} 'database_name'. - -If you want to use the @code{-p} option to supply a password you should do like this: - -@example -mysql -u monty -pguess database_name -@end example - -On some system the library call that @strong{MySQL} uses to prompt for a -password will automatically cut the password to 8 characters. Internally -@strong{MySQL} doesn't have any limit for the length of the password. - -@node Connecting, Password security, User names, Privilege system -@section Connecting to the MySQL Server -@cindex connecting, to the server -@cindex default hostname -@cindex hostname, default -@cindex server, connecting - -@strong{MySQL} client programs generally require that you specify connection -parameters when you want to access a @strong{MySQL} server: the host you want -to connect to, your user name, and your password. For example, the -@code{mysql} client can be started like this (optional arguments are enclosed -between @samp{[} and @samp{]}): - -@example -shell> mysql [-h host_name] [-u user_name] [-pyour_pass] -@end example - -Alternate forms of the @code{-h}, @code{-u}, and @code{-p} options are -@code{--host=host_name}, @code{--user=user_name}, and -@code{--password=your_pass}. Note that there is @emph{no space} between -@code{-p} or @code{--password=} and the password following it. - -@strong{NOTE:} Specifying a password on the command line is not secure! -Any user on your system may then find out your password by typing a command -like: @code{ps auxww}. @xref{Option files}. - -@code{mysql} uses default values for connection parameters that are missing -from the command line: - -@itemize @bullet -@item -The default hostname is @code{localhost}. - -@item -The default user name is your Unix login name. - -@item -No password is supplied if @code{-p} is missing. -@end itemize - -Thus, for a Unix user @code{joe}, the following commands are equivalent: - -@example -shell> mysql -h localhost -u joe -shell> mysql -h localhost -shell> mysql -u joe -shell> mysql -@end example - -Other @strong{MySQL} clients behave similarly. - -On Unix systems, you can specify different default values to be used when you -make a connection, so that you need not enter them on the command line each -time you invoke a client program. This can be done in a couple of ways: - -@itemize @bullet -@item -@tindex .my.cnf file -You can specify connection parameters in the @code{[client]} section of the -@file{.my.cnf} configuration file in your home directory. The relevant -section of the file might look like this: - -@example -[client] -host=host_name -user=user_name -password=your_pass -@end example - -@xref{Option files}. - -@item -@tindex MYSQL_HOST environment variable -@tindex Environment variable, MYSQL_HOST -@tindex MYSQL_PWD environment variable -@tindex Environment variable, MYSQL_PWD -@tindex USER environment variable -@tindex Environment variable, USER -You can specify connection parameters using environment variables. The -host can be specified for @code{mysql} using @code{MYSQL_HOST}. The -@strong{MySQL} user name can be specified using @code{USER} (this is for -Windows only). The password can be specified using @code{MYSQL_PWD} -(but this is insecure; see the next section). @xref{Environment variables}. -@end itemize - -@node Password security, Privileges provided, Connecting, Privilege system -@section Keeping Your Password Secure - -It is inadvisable to specify your password in a way that exposes it to -discovery by other users. The methods you can use to specify your password -when you run client programs are listed below, along with an assessment of -the risks of each method: - -@itemize @bullet -@item -Never give a normal user access to the @code{mysql.user} table. Knowing -the encrypted password for a user makes it possible to login as this -user. The passwords are only scrambled so that one shouldn't be able to -see the real password you used (if you happen to use a similar password -with your other applications). - -@item -Use a @code{-pyour_pass} or @code{--password=your_pass} option on the command -line. This is convenient but insecure, because your password becomes visible -to system status programs (such as @code{ps}) that may be invoked by other -users to display command lines. (@strong{MySQL} clients typically overwrite -the command-line argument with zeroes during their initialization sequence, -but there is still a brief interval during which the value is visible.) - -@item -Use a @code{-p} or @code{--password} option (with no @code{your_pass} value -specified). In this case, the client program solicits the password from -the terminal: -@findex -p option -@findex -password option - -@example -shell> mysql -u user_name -p -Enter password: ******** -@end example - -The @samp{*} characters represent your password. - -It is more secure to enter your password this way than to specify it on the -command line because it is not visible to other users. However, this method -of entering a password is suitable only for programs that you run -interactively. If you want to invoke a client from a script that runs -non-interactively, there is no opportunity to enter the password from the -terminal. On some systems, you may even find that the first line of your -script is read and interpreted (incorrectly) as your password! - -@item -@tindex .my.cnf file -Store your password in a configuration file. For example, you can list your -password in the @code{[client]} section of the @file{.my.cnf} file in your -home directory: - -@example -[client] -password=your_pass -@end example - -If you store your password in @file{.my.cnf}, the file should not be group or -world readable or writable. Make sure the file's access mode is @code{400} -or @code{600}. - -@xref{Option files}. -@item -You can store your password in the @code{MYSQL_PWD} environment variable, but -this method must be considered extremely insecure and should not be used. -Some versions of @code{ps} include an option to display the environment of -running processes; your password will be in plain sight for all to see if -you set @code{MYSQL_PWD}. Even on systems without such a version of -@code{ps}, it is unwise to assume there is no other method to observe process -environments. @xref{Environment variables}. -@end itemize - -All in all, the safest methods are to have the client program prompt for the -password or to specify the password in a properly protected @file{.my.cnf} -file. - -@node Privileges provided, Privileges, Password security, Privilege system -@section Privileges Provided by MySQL -@cindex privilege information, location - -Information about user privileges is stored in the @code{user}, @code{db}, -@code{host}, @code{tables_priv}, and @code{columns_priv} tables in the -@code{mysql} database (that is, in the database named @code{mysql}). The -@strong{MySQL} server reads the contents of these tables when it starts up -and under the circumstances indicated in @ref{Privilege changes}. - -The names used in this manual to refer to the privileges provided by -@strong{MySQL} are shown below, along with the table column name associated -with each privilege in the grant tables and the context in which the -privilege applies: - -@multitable @columnfractions .15 .25 .6 -@item @strong{Privilege} @tab @strong{Column} @tab @strong{Context} -@item @strong{select} @tab @code{Select_priv} @tab tables -@item @strong{insert} @tab @code{Insert_priv} @tab tables -@item @strong{update} @tab @code{Update_priv} @tab tables -@item @strong{delete} @tab @code{Delete_priv} @tab tables -@item @strong{index} @tab @code{Index_priv} @tab tables -@item @strong{alter} @tab @code{Alter_priv} @tab tables -@item @strong{create} @tab @code{Create_priv} @tab databases, tables, or indexes -@item @strong{drop} @tab @code{Drop_priv} @tab databases or tables -@item @strong{grant} @tab @code{Grant_priv} @tab databases or tables -@item @strong{references} @tab @code{References_priv} @tab databases or tables -@item @strong{reload} @tab @code{Reload_priv} @tab server administration -@item @strong{shutdown} @tab @code{Shutdown_priv} @tab server administration -@item @strong{process} @tab @code{Process_priv} @tab server administration -@item @strong{file} @tab @code{File_priv} @tab file access on server -@end multitable - -The @strong{select}, @strong{insert}, @strong{update}, and @strong{delete} -privileges allow you to perform operations on rows in existing tables in -a database. - -@code{SELECT} statements require the @strong{select} privilege only if they -actually retrieve rows from a table. You can execute certain @code{SELECT} -statements even without permission to access any of the databases on the -server. For example, you could use the @code{mysql} client as a simple -calculator: - -@example -mysql> SELECT 1+1; -mysql> SELECT PI()*2; -@end example - -The @strong{index} privilege allows you to create or drop (remove) indexes. - -The @strong{alter} privilege allows you to use @code{ALTER TABLE}. - -The @strong{create} and @strong{drop} privileges allow you to create new -databases and tables, or to drop (remove) existing databases and tables. - -Note that if you grant the @strong{drop} privilege for the @code{mysql} -database to a user, that user can drop the database in which the -@strong{MySQL} access privileges are stored! - -The @strong{grant} privilege allows you to give to other users those -privileges you yourself possess. - -The @strong{file} privilege gives you permission to read and write files on -the server using the @code{LOAD DATA INFILE} and @code{SELECT ... INTO -OUTFILE} statements. Any user to whom this privilege is granted can read or -write any file that the @strong{MySQL} server can read or write. - -The remaining privileges are used for administrative operations, which are -performed using the @code{mysqladmin} program. The table below shows which -@code{mysqladmin} commands each administrative privilege allows you to -execute: - -@multitable @columnfractions .15 .85 -@item @strong{Privilege} @tab @strong{Commands permitted to privilege holders} -@item @strong{reload} @tab @code{reload}, @code{refresh}, -@code{flush-privileges}, @code{flush-hosts}, @code{flush-logs}, and -@code{flush-tables} -@item @strong{shutdown} @tab @code{shutdown} -@item @strong{process} @tab @code{processlist}, @code{kill} -@end multitable - -The @code{reload} command tells the server to re-read the grant tables. The -@code{refresh} command flushes all tables and opens and closes the log -files. @code{flush-privileges} is a synonym for @code{reload}. The other -@code{flush-*} commands perform functions similar to @code{refresh} but are -more limited in scope, and may be preferable in some instances. For example, -if you want to flush just the log files, @code{flush-logs} is a better choice -than @code{refresh}. - -The @code{shutdown} command shuts down the server. - -The @code{processlist} command displays information about the threads -executing within the server. The @code{kill} command kills server threads. -You can always display or kill your own threads, but you need the -@strong{process} privilege to display or kill threads initiated by other -users. @xref{KILL}. - -It is a good idea in general to grant privileges only to those users who need -them, but you should exercise particular caution in granting certain -privileges: - -@itemize @bullet -@item -The @strong{grant} privilege allows users to give away their privileges to -other users. Two users with different privileges and with the @strong{grant} -privilege are able to combine privileges. - -@item -The @strong{alter} privilege may be used to subvert the privilege system -by renaming tables. - -@item -The @strong{file} privilege can be abused to read any world-readable file on -the server into a database table, the contents of which can then be -accessed using @code{SELECT}. This includes the contents of all databases -hosted by the server! - -@item -The @strong{shutdown} privilege can be abused to deny service to other -users entirely, by terminating the server. - -@item -The @strong{process} privilege can be used to view the plain text of -currently executing queries, including queries that set or change passwords. - -@item -Privileges on the @code{mysql} database can be used to change passwords -and other access privilege information. (Passwords are stored -encrypted, so a malicious user cannot simply read them to know the plain -text password). If they can access the @code{mysql.user} password -column, they can use it to log into the @strong{MySQL} server -for the given user. (With sufficient privileges, the same user can -replace a password with a different one.) -@end itemize - -There are some things that you cannot do with the @strong{MySQL} -privilege system: - -@itemize @bullet -@item -You cannot explicitly specify that a given user should be denied access. -That is, you cannot explicitly match a user and then refuse the connection. - -@item -You cannot specify that a user has privileges to create or drop tables -in a database but not to create or drop the database itself. -@end itemize - -@node Privileges, Connection access, Privileges provided, Privilege system -@section How the Privilege System Works @cindex privilege system, described The @strong{MySQL} privilege system ensures that all users may do exactly the @@ -15262,8 +15549,247 @@ Note that @code{mysqlaccess} checks access using only the @code{user}, @code{db} and @code{host} tables. It does not check table- or column-level privileges. -@node Connection access, Request access, Privileges, Privilege system -@section Access Control, Stage 1: Connection Verification + +@node Privileges provided, Connecting, Privileges, Privilege system +@subsection Privileges Provided by MySQL + +@cindex privilege information, location + +Information about user privileges is stored in the @code{user}, @code{db}, +@code{host}, @code{tables_priv}, and @code{columns_priv} tables in the +@code{mysql} database (that is, in the database named @code{mysql}). The +@strong{MySQL} server reads the contents of these tables when it starts up +and under the circumstances indicated in @ref{Privilege changes}. + +The names used in this manual to refer to the privileges provided by +@strong{MySQL} are shown below, along with the table column name associated +with each privilege in the grant tables and the context in which the +privilege applies: + +@multitable @columnfractions .15 .25 .6 +@item @strong{Privilege} @tab @strong{Column} @tab @strong{Context} +@item @strong{select} @tab @code{Select_priv} @tab tables +@item @strong{insert} @tab @code{Insert_priv} @tab tables +@item @strong{update} @tab @code{Update_priv} @tab tables +@item @strong{delete} @tab @code{Delete_priv} @tab tables +@item @strong{index} @tab @code{Index_priv} @tab tables +@item @strong{alter} @tab @code{Alter_priv} @tab tables +@item @strong{create} @tab @code{Create_priv} @tab databases, tables, or indexes +@item @strong{drop} @tab @code{Drop_priv} @tab databases or tables +@item @strong{grant} @tab @code{Grant_priv} @tab databases or tables +@item @strong{references} @tab @code{References_priv} @tab databases or tables +@item @strong{reload} @tab @code{Reload_priv} @tab server administration +@item @strong{shutdown} @tab @code{Shutdown_priv} @tab server administration +@item @strong{process} @tab @code{Process_priv} @tab server administration +@item @strong{file} @tab @code{File_priv} @tab file access on server +@end multitable + +The @strong{select}, @strong{insert}, @strong{update}, and @strong{delete} +privileges allow you to perform operations on rows in existing tables in +a database. + +@code{SELECT} statements require the @strong{select} privilege only if they +actually retrieve rows from a table. You can execute certain @code{SELECT} +statements even without permission to access any of the databases on the +server. For example, you could use the @code{mysql} client as a simple +calculator: + +@example +mysql> SELECT 1+1; +mysql> SELECT PI()*2; +@end example + +The @strong{index} privilege allows you to create or drop (remove) indexes. + +The @strong{alter} privilege allows you to use @code{ALTER TABLE}. + +The @strong{create} and @strong{drop} privileges allow you to create new +databases and tables, or to drop (remove) existing databases and tables. + +Note that if you grant the @strong{drop} privilege for the @code{mysql} +database to a user, that user can drop the database in which the +@strong{MySQL} access privileges are stored! + +The @strong{grant} privilege allows you to give to other users those +privileges you yourself possess. + +The @strong{file} privilege gives you permission to read and write files on +the server using the @code{LOAD DATA INFILE} and @code{SELECT ... INTO +OUTFILE} statements. Any user to whom this privilege is granted can read or +write any file that the @strong{MySQL} server can read or write. + +The remaining privileges are used for administrative operations, which are +performed using the @code{mysqladmin} program. The table below shows which +@code{mysqladmin} commands each administrative privilege allows you to +execute: + +@multitable @columnfractions .15 .85 +@item @strong{Privilege} @tab @strong{Commands permitted to privilege holders} +@item @strong{reload} @tab @code{reload}, @code{refresh}, +@code{flush-privileges}, @code{flush-hosts}, @code{flush-logs}, and +@code{flush-tables} +@item @strong{shutdown} @tab @code{shutdown} +@item @strong{process} @tab @code{processlist}, @code{kill} +@end multitable + +The @code{reload} command tells the server to re-read the grant tables. The +@code{refresh} command flushes all tables and opens and closes the log +files. @code{flush-privileges} is a synonym for @code{reload}. The other +@code{flush-*} commands perform functions similar to @code{refresh} but are +more limited in scope, and may be preferable in some instances. For example, +if you want to flush just the log files, @code{flush-logs} is a better choice +than @code{refresh}. + +The @code{shutdown} command shuts down the server. + +The @code{processlist} command displays information about the threads +executing within the server. The @code{kill} command kills server threads. +You can always display or kill your own threads, but you need the +@strong{process} privilege to display or kill threads initiated by other +users. @xref{KILL}. + +It is a good idea in general to grant privileges only to those users who need +them, but you should exercise particular caution in granting certain +privileges: + +@itemize @bullet +@item +The @strong{grant} privilege allows users to give away their privileges to +other users. Two users with different privileges and with the @strong{grant} +privilege are able to combine privileges. + +@item +The @strong{alter} privilege may be used to subvert the privilege system +by renaming tables. + +@item +The @strong{file} privilege can be abused to read any world-readable file on +the server into a database table, the contents of which can then be +accessed using @code{SELECT}. This includes the contents of all databases +hosted by the server! + +@item +The @strong{shutdown} privilege can be abused to deny service to other +users entirely, by terminating the server. + +@item +The @strong{process} privilege can be used to view the plain text of +currently executing queries, including queries that set or change passwords. + +@item +Privileges on the @code{mysql} database can be used to change passwords +and other access privilege information. (Passwords are stored +encrypted, so a malicious user cannot simply read them to know the plain +text password). If they can access the @code{mysql.user} password +column, they can use it to log into the @strong{MySQL} server +for the given user. (With sufficient privileges, the same user can +replace a password with a different one.) +@end itemize + +There are some things that you cannot do with the @strong{MySQL} +privilege system: + +@itemize @bullet +@item +You cannot explicitly specify that a given user should be denied access. +That is, you cannot explicitly match a user and then refuse the connection. + +@item +You cannot specify that a user has privileges to create or drop tables +in a database but not to create or drop the database itself. +@end itemize + + +@node Connecting, Connection access, Privileges provided, Privilege system +@subsection Connecting to the MySQL Server + +@cindex connecting, to the server +@cindex default hostname +@cindex hostname, default +@cindex server, connecting + +@strong{MySQL} client programs generally require that you specify connection +parameters when you want to access a @strong{MySQL} server: the host you want +to connect to, your user name, and your password. For example, the +@code{mysql} client can be started like this (optional arguments are enclosed +between @samp{[} and @samp{]}): + +@example +shell> mysql [-h host_name] [-u user_name] [-pyour_pass] +@end example + +Alternate forms of the @code{-h}, @code{-u}, and @code{-p} options are +@code{--host=host_name}, @code{--user=user_name}, and +@code{--password=your_pass}. Note that there is @emph{no space} between +@code{-p} or @code{--password=} and the password following it. + +@strong{NOTE:} Specifying a password on the command line is not secure! +Any user on your system may then find out your password by typing a command +like: @code{ps auxww}. @xref{Option files}. + +@code{mysql} uses default values for connection parameters that are missing +from the command line: + +@itemize @bullet +@item +The default hostname is @code{localhost}. + +@item +The default user name is your Unix login name. + +@item +No password is supplied if @code{-p} is missing. +@end itemize + +Thus, for a Unix user @code{joe}, the following commands are equivalent: + +@example +shell> mysql -h localhost -u joe +shell> mysql -h localhost +shell> mysql -u joe +shell> mysql +@end example + +Other @strong{MySQL} clients behave similarly. + +On Unix systems, you can specify different default values to be used when you +make a connection, so that you need not enter them on the command line each +time you invoke a client program. This can be done in a couple of ways: + +@itemize @bullet +@item +@tindex .my.cnf file +You can specify connection parameters in the @code{[client]} section of the +@file{.my.cnf} configuration file in your home directory. The relevant +section of the file might look like this: + +@example +[client] +host=host_name +user=user_name +password=your_pass +@end example + +@xref{Option files}. + +@item +@tindex MYSQL_HOST environment variable +@tindex Environment variable, MYSQL_HOST +@tindex MYSQL_PWD environment variable +@tindex Environment variable, MYSQL_PWD +@tindex USER environment variable +@tindex Environment variable, USER +You can specify connection parameters using environment variables. The +host can be specified for @code{mysql} using @code{MYSQL_HOST}. The +@strong{MySQL} user name can be specified using @code{USER} (this is for +Windows only). The password can be specified using @code{MYSQL_PWD} +(but this is insecure; see the next section). @xref{Environment variables}. +@end itemize + + +@node Connection access, Request access, Connecting, Privilege system +@subsection Access Control, Stage 1: Connection Verification + @cindex access control @cindex control access @cindex connecting, verification @@ -15468,8 +15994,9 @@ as the @code{User} field value, but by the entry with no user name! If you have problems connecting to the server, print out the @code{user} table and sort it by hand to see where the first match is being made. -@node Request access, Privilege changes, Connection access, Privilege system -@section Access Control, Stage 2: Request Verification + +@node Request access, Access denied, Connection access, Privilege system +@subsection Access Control, Stage 2: Request Verification Once you establish a connection, the server enters Stage 2. For each request that comes in on the connection, the server checks whether you have @@ -15667,8 +16194,657 @@ Naturally, you should always test your entries in the grant tables (for example, using @code{mysqlaccess}) to make sure your access privileges are actually set up the way you think they are. -@node Privilege changes, Default privileges, Request access, Privilege system -@section When Privilege Changes Take Effect + +@node Access denied, , Request access, Privilege system +@subsection Causes of @code{Access denied} Errors + +If you encounter @code{Access denied} errors when you try to connect to the +@strong{MySQL} server, the list below indicates some courses of +action you can take to correct the problem: + +@itemize @bullet +@item +After installing @strong{MySQL}, did you run the @code{mysql_install_db} +script to set up the initial grant table contents? If not, do so. +@xref{Default privileges}. Test the initial privileges by executing +this command: + +@example +shell> mysql -u root test +@end example + +The server should let you connect without error. You should also make sure +you have a file @file{user.MYD} in the @strong{MySQL} database directory. +Ordinarily, this is @file{PATH/var/mysql/user.MYD}, where @code{PATH} is the +pathname to the @strong{MySQL} installation root. + +@item +After a fresh installation, you should connect to the server and set up +your users and their access permissions: + +@example +shell> mysql -u root mysql +@end example + +The server should let you connect because the @strong{MySQL} @code{root} user +has no password initially. That is also a security risk, so setting the +@code{root} password is something you should do while you're setting up +your other @strong{MySQL} users. + +If you try to connect as @code{root} and get this error: + +@example +Access denied for user: '@@unknown' to database mysql +@end example + +this means that you don't have an entry in the @code{user} table with a +@code{User} column value of @code{'root'} and that @code{mysqld} cannot +resolve the hostname for your client. In this case, you must restart the +server with the @code{--skip-grant-tables} option and edit your +@file{/etc/hosts} or @file{\windows\hosts} file to add an entry for your +host. + +@item +If you get an error like the following: + +@example +shell> mysqladmin -u root -pxxxx ver +Access denied for user: 'root@@localhost' (Using password: YES) +@end example + +It means that you are using a wrong password. @xref{Passwords}. + +If you have forgot the root password, you can restart @code{mysqld} with +@code{--skip-grant-tables} to change the password. You can find more +about this option later on in this manual section. + +If you get the above error even if you haven't specified a password, +this means that you a wrong password in some @code{my.ini} +file. @xref{Option files}. You can avoid using option files with the @code{--no-defaults} option, as follows: + +@example +shell> mysqladmin --no-defaults -u root ver +@end example + +@item +@cindex @code{mysql_fix_privilege_tables} +If you updated an existing @strong{MySQL} installation from a version earlier +than Version 3.22.11 to Version 3.22.11 or later, did you run the +@code{mysql_fix_privilege_tables} script? If not, do so. The structure of +the grant tables changed with @strong{MySQL} Version 3.22.11 when the +@code{GRANT} statement became functional. + +@item +If your privileges seem to have changed in the middle of a session, it may be +that a superuser has changed them. Reloading the grant tables affects new +client connections, but it also affects existing connections as indicated in +@ref{Privilege changes}. + +@item +If you can't get your password to work, remember that you must use +the @code{PASSWORD()} function if you set the password with the +@code{INSERT}, @code{UPDATE}, or @code{SET PASSWORD} statements. The +@code{PASSWORD()} function is unnecessary if you specify the password using +the @code{GRANT ... INDENTIFIED BY} statement or the @code{mysqladmin +password} command. +@xref{Passwords}. + +@item +@code{localhost} is a synonym for your local hostname, and is also the +default host to which clients try to connect if you specify no host +explicitly. However, connections to @code{localhost} do not work if you are +running on a system that uses MIT-pthreads (@code{localhost} connections are +made using Unix sockets, which are not supported by MIT-pthreads). To avoid +this problem on such systems, you should use the @code{--host} option to name +the server host explicitly. This will make a TCP/IP connection to the +@code{mysqld} server. In this case, you must have your real hostname in +@code{user} table entries on the server host. (This is true even if you are +running a client program on the same host as the server.) + +@item +If you get an @code{Access denied} error when trying to connect to the +database with @code{mysql -u user_name db_name}, you may have a problem +with the @code{user} table. Check this by executing @code{mysql -u root +mysql} and issuing this SQL statement: + +@example +mysql> SELECT * FROM user; +@end example + +The result should include an entry with the @code{Host} and @code{User} +columns matching your computer's hostname and your @strong{MySQL} user name. + +@item +The @code{Access denied} error message will tell you who you are trying +to log in as, the host from which you are trying to connect, and whether +or not you were using a password. Normally, you should have one entry in +the @code{user} table that exactly matches the hostname and user name +that were given in the error message. For example if you get an error +message that contains @code{Using password: NO}, this means that you +tried to login without an password. + +@item +If you get the following error when you try to connect from a different host +than the one on which the @strong{MySQL} server is running, then there is no +row in the @code{user} table that matches that host: + +@example +Host ... is not allowed to connect to this MySQL server +@end example + +You can fix this by using the command-line tool @code{mysql} (on the +server host!) to add a row to the @code{user}, @code{db}, or @code{host} +table for the user/hostname combination from which you are trying to +connect and then execute @code{mysqladmin flush-privileges}. If you are +not running @strong{MySQL} Version 3.22 and you don't know the IP number or +hostname of the machine from which you are connecting, you should put an +entry with @code{'%'} as the @code{Host} column value in the @code{user} +table and restart @code{mysqld} with the @code{--log} option on the +server machine. After trying to connect from the client machine, the +information in the @strong{MySQL} log will indicate how you really did +connect. (Then replace the @code{'%'} in the @code{user} table entry +with the actual hostname that shows up in the log. Otherwise, you'll +have a system that is insecure.) + +Another reason for this error on Linux is that you are using a binary +@strong{MySQL} version that is compiled with a different glibc version +than the one you are using. In this case you should either upgrade your +OS/glibc or download the source @strong{MySQL} version and compile this +yourself. A source RPM is normally trivial to compile and install, so +this isn't a big problem. + +@item +If you get an error message where the hostname is not shown or where the +hostname is an IP, even if you try to connect with a hostname: + +@example +shell> mysqladmin -u root -pxxxx -h some-hostname ver +Access denied for user: 'root@' (Using password: YES) +@end example + +This means that @strong{MySQL} got some error when trying to resolve the +IP to a hostname. In this case you can execute @code{mysqladmin +flush-hosts} to reset the internal DNS cache. @xref{DNS}. + +Some permanent solutions are: + +@itemize @minus +@item +Try to find out what is wrong with your DNS server and fix this. + +@item +Specify IPs instead of hostnames in the @strong{MySQL} privilege tables. + +@item +Start @code{mysqld} with @code{--skip-name-resolve}. + +@item +Start @code{mysqld} with @code{--skip-host-cache}. + +@item +Connect to @code{localhost} if you are running the server and the client +on the same machine. + +@item +Put the client machine names in @code{/etc/hosts}. +@end itemize + +@item +If @code{mysql -u root test} works but @code{mysql -h your_hostname -u root +test} results in @code{Access denied}, then you may not have the correct name +for your host in the @code{user} table. A common problem here is that the +@code{Host} value in the user table entry specifies an unqualified hostname, +but your system's name resolution routines return a fully qualified domain +name (or vice-versa). For example, if you have an entry with host +@code{'tcx'} in the @code{user} table, but your DNS tells @strong{MySQL} that +your hostname is @code{'tcx.subnet.se'}, the entry will not work. Try adding +an entry to the @code{user} table that contains the IP number of your host as +the @code{Host} column value. (Alternatively, you could add an entry to the +@code{user} table with a @code{Host} value that contains a wild card---for +example, @code{'tcx.%'}. However, use of hostnames ending with @samp{%} is +@emph{insecure} and is @emph{not} recommended!) + +@item +If @code{mysql -u user_name test} works but @code{mysql -u user_name +other_db_name} doesn't work, you don't have an entry for @code{other_db_name} +listed in the @code{db} table. + +@item +If @code{mysql -u user_name db_name} works when executed on the server +machine, but @code{mysql -u host_name -u user_name db_name} doesn't work when +executed on another client machine, you don't have the client machine listed +in the @code{user} table or the @code{db} table. + +@item +If you can't figure out why you get @code{Access denied}, remove from the +@code{user} table all entries that have @code{Host} values containing +wild cards (entries that contain @samp{%} or @samp{_}). A very common error +is to insert a new entry with @code{Host}=@code{'%'} and +@code{User}=@code{'some user'}, thinking that this will allow you to specify +@code{localhost} to connect from the same machine. The reason that this +doesn't work is that the default privileges include an entry with +@code{Host}=@code{'localhost'} and @code{User}=@code{''}. Because that entry +has a @code{Host} value @code{'localhost'} that is more specific than +@code{'%'}, it is used in preference to the new entry when connecting from +@code{localhost}! The correct procedure is to insert a second entry with +@code{Host}=@code{'localhost'} and @code{User}=@code{'some_user'}, or to +remove the entry with @code{Host}=@code{'localhost'} and +@code{User}=@code{''}. + +@item +If you get the following error, you may have a problem with the @code{db} or +@code{host} table: + +@example +Access to database denied +@end example + +If the entry selected from the @code{db} table has an empty value in the +@code{Host} column, make sure there are one or more corresponding entries in +the @code{host} table specifying which hosts the @code{db} table entry +applies to. + +If you get the error when using the SQL commands @code{SELECT ... +INTO OUTFILE} or @code{LOAD DATA INFILE}, your entry in the @code{user} table +probably doesn't have the @strong{file} privilege enabled. + +@item +@cindex configuration files +@cindex environment variables +@tindex .my.cnf file +Remember that client programs will use connection parameters specified +in configuration files or environment variables. @xref{Environment +variables}. If a client seems to be sending the wrong default +connection parameters when you don't specify them on the command line, +check your environment and the @file{.my.cnf} file in your home +directory. You might also check the system-wide @strong{MySQL} +configuration files, though it is far less likely that client connection +parameters will be specified there. @xref{Option files}. If you get +@code{Access denied} when you run a client without any options, make +sure you haven't specified an old password in any of your option files! +@xref{Option files}. + +@item +If you make changes to the grant tables directly (using an @code{INSERT} or +@code{UPDATE} statement) and your changes seem to be ignored, remember +that you must issue a @code{FLUSH PRIVILEGES} statement or execute a +@code{mysqladmin flush-privileges} command to cause the server to re-read +the privilege tables. Otherwise your changes have no effect until the +next time the server is restarted. Remember that after you set the +@code{root} password with an @code{UPDATE} command, you won't need to +specify it until after you flush the privileges, because the server +won't know you've changed the password yet! + +@item +If you have access problems with a Perl, PHP, Python, or ODBC program, try to +connect to the server with @code{mysql -u user_name db_name} or @code{mysql +-u user_name -pyour_pass db_name}. If you are able to connect using the +@code{mysql} client, there is a problem with your program and not with the +access privileges. (Note that there is no space between @code{-p} and the +password; you can also use the @code{--password=your_pass} syntax to specify +the password. If you use the @code{-p} option alone, @strong{MySQL} will +prompt you for the password.) + +@item +For testing, start the @code{mysqld} daemon with the +@code{--skip-grant-tables} option. Then you can change the @strong{MySQL} +grant tables and use the @code{mysqlaccess} script to check whether or not +your modifications have the desired effect. When you are satisfied with your +changes, execute @code{mysqladmin flush-privileges} to tell the @code{mysqld} +server to start using the new grant tables. @strong{Note:} Reloading the +grant tables overrides the @code{--skip-grant-tables} option. This allows +you to tell the server to begin using the grant tables again without bringing +it down and restarting it. + +@item +If everything else fails, start the @code{mysqld} daemon with a debugging +option (for example, @code{--debug=d,general,query}). This will print host and +user information about attempted connections, as well as information about +each command issued. @xref{Making trace files}. + +@item +If you have any other problems with the @strong{MySQL} grant tables and +feel you must post the problem to the mailing list, always provide a +dump of the @strong{MySQL} grant tables. You can dump the tables with +the @code{mysqldump mysql} command. As always, post your problem using +the @code{mysqlbug} script. @xref{Bug reports}. In some cases you may need +to restart @code{mysqld} with @code{--skip-grant-tables} to run +@code{mysqldump}. +@end itemize + + +@node User Account Management, Disaster Prevention, Privilege system, MySQL Database Administration +@section MySQL User Account Management + +@menu +* GRANT:: +* User names:: +* Privilege changes:: +* Default privileges:: +* Adding users:: +* Passwords:: +* Password security:: +@end menu + + +@node GRANT, User names, User Account Management, User Account Management +@subsection @code{GRANT} and @code{REVOKE} Syntax + +@findex GRANT +@findex REVOKE + +@cindex privileges, granting +@cindex privileges, revoking +@cindex global privileges +@cindex revoking, privleges +@cindex granting, privleges + +@example +GRANT priv_type [(column_list)] [, priv_type [(column_list)] ...] + ON @{tbl_name | * | *.* | db_name.*@} + TO user_name [IDENTIFIED BY 'password'] + [, user_name [IDENTIFIED BY 'password'] ...] + [WITH GRANT OPTION] + +REVOKE priv_type [(column_list)] [, priv_type [(column_list)] ...] + ON @{tbl_name | * | *.* | db_name.*@} + FROM user_name [, user_name ...] +@end example + +@code{GRANT} is implemented in @strong{MySQL} Version 3.22.11 or later. For +earlier @strong{MySQL} versions, the @code{GRANT} statement does nothing. + +The @code{GRANT} and @code{REVOKE} commands allow system administrators +to create users and grant and revoke rights to @strong{MySQL} users at +four privilege levels: + +@table @strong +@item Global level +Global privileges apply to all databases on a given server. These privileges +are stored in the @code{mysql.user} table. + +@item Database level +Database privileges apply to all tables in a given database. These privileges +are stored in the @code{mysql.db} and @code{mysql.host} tables. + +@item Table level +Table privileges apply to all columns in a given table. These privileges are +stored in the @code{mysql.tables_priv} table. + +@item Column level +Column privileges apply to single columns in a given table. These privileges are +stored in the @code{mysql.columns_priv} table. +@end table + +If you give a grant for a users that doesn't exists, that user is created. +For examples of how @code{GRANT} works, see @ref{Adding users}. + +For the @code{GRANT} and @code{REVOKE} statements, @code{priv_type} may be +specified as any of the following: + +@example +ALL PRIVILEGES FILE RELOAD +ALTER INDEX SELECT +CREATE INSERT SHUTDOWN +DELETE PROCESS UPDATE +DROP REFERENCES USAGE +@end example + +@code{ALL} is a synonym for @code{ALL PRIVILEGES}. @code{REFERENCES} is not +yet implemented. @code{USAGE} is currently a synonym for ``no privileges.'' +It can be used when you want to create a user that has no privileges. + +To revoke the @strong{grant} privilege from a user, use a @code{priv_type} +value of @code{GRANT OPTION}: + +@example +REVOKE GRANT OPTION ON ... FROM ...; +@end example + +The only @code{priv_type} values you can specify for a table are @code{SELECT}, +@code{INSERT}, @code{UPDATE}, @code{DELETE}, @code{CREATE}, @code{DROP}, +@code{GRANT}, @code{INDEX}, and @code{ALTER}. + +The only @code{priv_type} values you can specify for a column (that is, when +you use a @code{column_list} clause) are @code{SELECT}, @code{INSERT}, and +@code{UPDATE}. + +You can set global privileges by using @code{ON *.*} syntax. You can set +database privileges by using @code{ON db_name.*} syntax. If you specify +@code{ON *} and you have a current database, you will set the privileges for +that database. (@strong{WARNING:} If you specify @code{ON *} and you +@emph{don't} have a current database, you will affect the global privileges!) + +In order to accommodate granting rights to users from arbitrary hosts, +@strong{MySQL} supports specifying the @code{user_name} value in the form +@code{user@@host}. If you want to specify a @code{user} string +containing special characters (such as @samp{-}), or a @code{host} string +containing special characters or wild-card characters (such as @samp{%}), you +can quote the user or host name (for example, @code{'test-user'@@'test-hostname'}). + +You can specify wild cards in the hostname. For example, +@code{user@@"%.loc.gov"} applies to @code{user} for any host in the +@code{loc.gov} domain, and @code{user@@"144.155.166.%"} applies to @code{user} +for any host in the @code{144.155.166} class C subnet. + +The simple form @code{user} is a synonym for @code{user@@"%"}. +@strong{NOTE:} If you allow anonymous users to connect to the @strong{MySQL} +server (which is the default), you should also add all local users as +@code{user@@localhost} because otherwise the anonymous user entry for the +local host in the @code{mysql.user} table will be used when the user tries to +log into the @strong{MySQL} server from the local machine! Anonymous users +are defined by inserting entries with @code{User=''} into the +@code{mysql.user} table. You can verify if this applies to you by executing +this query: + +@example +mysql> SELECT Host,User FROM mysql.user WHERE User=''; +@end example + +For the moment, @code{GRANT} only supports host, table, database, and +column names up to 60 characters long. A user name can be up to 16 +characters. + +The privileges for a table or column are formed from the +logical OR of the privileges at each of the four privilege +levels. For example, if the @code{mysql.user} table specifies that a +user has a global @strong{select} privilege, this can't be denied by an +entry at the database, table, or column level. + +The privileges for a column can be calculated as follows: + +@example +global privileges +OR (database privileges AND host privileges) +OR table privileges +OR column privileges +@end example + +In most cases, you grant rights to a user at only one of the privilege +levels, so life isn't normally as complicated as above. The details of the +privilege-checking procedure are presented in +@ref{Privilege system}. + +If you grant privileges for a user/hostname combination that does not exist +in the @code{mysql.user} table, an entry is added and remains there until +deleted with a @code{DELETE} command. In other words, @code{GRANT} may +create @code{user} table entries, but @code{REVOKE} will not remove them; +you must do that explicitly using @code{DELETE}. + +@cindex passwords, setting +In @strong{MySQL} Version 3.22.12 or later, +if a new user is created or if you have global grant privileges, the user's +password will be set to the password specified by the @code{IDENTIFIED BY} +clause, if one is given. If the user already had a password, it is replaced +by the new one. + +@strong{WARNING:} If you create a new user but do not specify an +@code{IDENTIFIED BY} clause, the user has no password. This is insecure. + +Passwords can also be set with the @code{SET PASSWORD} command. +@xref{SET OPTION, , @code{SET OPTION}}. + +If you grant privileges for a database, an entry in the @code{mysql.db} +table is created if needed. When all privileges for the database have been +removed with @code{REVOKE}, this entry is deleted. + +If a user doesn't have any privileges on a table, the table is not displayed +when the user requests a list of tables (for example, with a @code{SHOW TABLES} +statement). + +The @code{WITH GRANT OPTION} clause gives the user the ability to give +to other users any privileges the user has at the specified privilege level. +You should be careful to whom you give the @strong{grant} privilege, as two +users with different privileges may be able to join privileges! + +You cannot grant another user a privilege you don't have yourself; +the @strong{grant} privilege allows you to give away only those privileges +you possess. + +Be aware that when you grant a user the @strong{grant} privilege at a +particular privilege level, any privileges the user already possesses (or +is given in the future!) at that level are also grantable by that user. +Suppose you grant a user the @strong{insert} privilege on a database. If +you then grant the @strong{select} privilege on the database and specify +@code{WITH GRANT OPTION}, the user can give away not only the @strong{select} +privilege, but also @strong{insert}. If you then grant the @strong{update} +privilege to the user on the database, the user can give away the +@strong{insert}, @strong{select} and @strong{update}. + +You should not grant @strong{alter} privileges to a normal user. If you +do that, the user can try to subvert the privilege system by renaming +tables! + +Note that if you are using table or column privileges for even one user, the +server examines table and column privileges for all users and this will slow +down @strong{MySQL} a bit. + +When @code{mysqld} starts, all privileges are read into memory. +Database, table, and column privileges take effect at once, and +user-level privileges take effect the next time the user connects. +Modifications to the grant tables that you perform using @code{GRANT} or +@code{REVOKE} are noticed by the server immediately. +If you modify the grant tables manually (using @code{INSERT}, @code{UPDATE}, +etc.), you should execute a @code{FLUSH PRIVILEGES} statement or run +@code{mysqladmin flush-privileges} to tell the server to reload the grant +tables. +@xref{Privilege changes}. + +@cindex ANSI SQL, differences from +The biggest differences between the ANSI SQL and @strong{MySQL} versions of +@code{GRANT} are: + +@itemize @bullet +@item +In @strong{MySQL} privileges are given for an username + hostname combination +and not only for an username. + +@item +ANSI SQL doesn't have global or database-level privileges, and ANSI SQL +doesn't support all privilege types that @strong{MySQL} supports. +@strong{MySQL} doesn't support the ANSI SQL @code{TRIGGER}, @code{EXECUTE} or +@code{UNDER} privileges. + +@item +ANSI SQL privileges are structured in a hierarchal manner. If you remove +an user, all privileges the user has granted are revoked. In +@strong{MySQL} the granted privileges are not automatically revoked, but +you have to revoke these yourself if needed. + +@item +If you in @strong{MySQL} have the @code{INSERT} grant on only part of the +columns in a table, you can execute @code{INSERT} statements on the +table; The columns for which you don't have the @code{INSERT} privilege +will set to their default values. ANSI SQL requires you to have the +@code{INSERT} privilege on all columns. + +@item +When you drop a table in ANSI SQL, all privileges for the table are revoked. +If you revoke a privilege in ANSI SQL, all privileges that were granted based +on this privilege are also revoked. In @strong{MySQL}, privileges can be +dropped only with explicit @code{REVOKE} commands or by manipulating the +@strong{MySQL} grant tables. +@end itemize + + +@node User names, Privilege changes, GRANT, User Account Management +@subsection MySQL User Names and Passwords + +@cindex user names, and passwords +@cindex passwords, for users + +There are several distinctions between the way user names and passwords are +used by @strong{MySQL} and the way they are used by Unix or Windows: + +@itemize @bullet +@item +User names, as used by @strong{MySQL} for authentication purposes, have +nothing to do with Unix user names (login names) or Windows user names. Most +@strong{MySQL} clients by default try to log in using the current Unix user +name as the @strong{MySQL} user name, but that is for convenience only. +Client programs allow a different name to be specified with the @code{-u} or +@code{--user} options. This means that you can't make a database secure in +any way unless all @strong{MySQL} user names have passwords. Anyone may +attempt to connect to the server using any name, and they will succeed if +they specify any name that doesn't have a password. + +@item +@strong{MySQL} user names can be up to 16 characters long; Unix user names +typically are limited to 8 characters. + +@item +@strong{MySQL} passwords have nothing to do with Unix passwords. There is no +necessary connection between the password you use to log in to a Unix machine +and the password you use to access a database on that machine. + +@item +@strong{MySQL} encrypts passwords using a different algorithm than the +one used during the Unix login process. See the descriptions of the +@code{PASSWORD()} and @code{ENCRYPT()} functions in @ref{Miscellaneous +functions}. Note that even if the password is stored 'scrambled', and +knowing your 'scrambled' password is enough to be able to connect to +the @strong{MySQL} server! +@end itemize + +@strong{MySQL} users and they privileges are normally created with the +@code{GRANT} command. @xref{GRANT}. + +When you login to a @strong{MySQL} server with a command line client you +should specify the password with @code{--password=your-password}. +@xref{Connecting}. + +@example +mysql --user=monty --password=guess database_name +@end example + +If you want the client to prompt for a password, you should use +@code{--password} without any argument + +@example +mysql --user=monty --password database_name +@end example + +or the short form: + +@example +mysql -u monty -p database_name +@end example + +Note that in the last example the password is @strong{NOT} 'database_name'. + +If you want to use the @code{-p} option to supply a password you should do like this: + +@example +mysql -u monty -pguess database_name +@end example + +On some system the library call that @strong{MySQL} uses to prompt for a +password will automatically cut the password to 8 characters. Internally +@strong{MySQL} doesn't have any limit for the length of the password. + + +@node Privilege changes, Default privileges, User names, User Account Management +@subsection When Privilege Changes Take Effect When @code{mysqld} starts, all grant table contents are read into memory and become effective at that point. @@ -15700,6 +16876,10 @@ command. Global privilege changes and password changes take effect the next time the client connects. + +@node Default privileges, Adding users, Privilege changes, User Account Management +@subsection Setting Up the Initial MySQL Privileges + @cindex privileges, default @cindex default, privileges @cindex root password @@ -15707,8 +16887,6 @@ client connects. @cindex users, root @cindex anonymous user @cindex password, root user -@node Default privileges, Adding users, Privilege changes, Privilege system -@section Setting Up the Initial MySQL Privileges After installing @strong{MySQL}, you set up the initial access privileges by running @code{scripts/mysql_install_db}. @@ -15804,13 +16982,16 @@ you should NOT delete the @file{.frm} files. If you accidentally do this, you should copy them back from your @strong{MySQL} distribution before running @code{mysql_install_db}. + +@node Adding users, Passwords, Default privileges, User Account Management +@subsection Adding New Users to MySQL + +@findex GRANT statement +@findex statements, GRANT + @cindex privileges, adding @cindex adding, new user privileges @cindex user privileges, adding -@findex GRANT statement -@findex statements, GRANT -@node Adding users, Passwords, Default privileges, Privilege system -@section Adding New Users to MySQL You can add users two different ways: by using @code{GRANT} statements or by manipulating the @strong{MySQL} grant tables directly. The @@ -15996,12 +17177,15 @@ You can find these utilities in the @uref{http://www.mysql.com/Downloads/Contrib/,Contrib directory of the @strong{MySQL} Website}. -@cindex passwords, setting + +@node Passwords, Password security, Adding users, User Account Management +@subsection Setting Up Passwords + @findex PASSWORD() @findex SET PASSWORD statement + +@cindex passwords, setting @cindex setting, passwords -@node Passwords, Access denied, Adding users, Privilege system -@section Setting Up Passwords In most cases you should use @code{GRANT} to set up your users/passwords, so the following only applies for advanced users. @xref{GRANT, , @code{GRANT}}. @@ -16071,319 +17255,6373 @@ your Unix password and your @strong{MySQL} password are the same, that @code{PASSWORD()} will result in the same encrypted value as is stored in the Unix password file. @xref{User names}. -@node Access denied, , Passwords, Privilege system -@section Causes of @code{Access denied} Errors -If you encounter @code{Access denied} errors when you try to connect to the -@strong{MySQL} server, the list below indicates some courses of -action you can take to correct the problem: +@node Password security, , Passwords, User Account Management +@subsection Keeping Your Password Secure + +It is inadvisable to specify your password in a way that exposes it to +discovery by other users. The methods you can use to specify your password +when you run client programs are listed below, along with an assessment of +the risks of each method: @itemize @bullet @item -After installing @strong{MySQL}, did you run the @code{mysql_install_db} -script to set up the initial grant table contents? If not, do so. -@xref{Default privileges}. Test the initial privileges by executing -this command: +Never give a normal user access to the @code{mysql.user} table. Knowing +the encrypted password for a user makes it possible to login as this +user. The passwords are only scrambled so that one shouldn't be able to +see the real password you used (if you happen to use a similar password +with your other applications). + +@item +Use a @code{-pyour_pass} or @code{--password=your_pass} option on the command +line. This is convenient but insecure, because your password becomes visible +to system status programs (such as @code{ps}) that may be invoked by other +users to display command lines. (@strong{MySQL} clients typically overwrite +the command-line argument with zeroes during their initialization sequence, +but there is still a brief interval during which the value is visible.) + +@item +Use a @code{-p} or @code{--password} option (with no @code{your_pass} value +specified). In this case, the client program solicits the password from +the terminal: +@findex -p option +@findex -password option @example -shell> mysql -u root test +shell> mysql -u user_name -p +Enter password: ******** @end example -The server should let you connect without error. You should also make sure -you have a file @file{user.MYD} in the @strong{MySQL} database directory. -Ordinarily, this is @file{PATH/var/mysql/user.MYD}, where @code{PATH} is the -pathname to the @strong{MySQL} installation root. +The @samp{*} characters represent your password. + +It is more secure to enter your password this way than to specify it on the +command line because it is not visible to other users. However, this method +of entering a password is suitable only for programs that you run +interactively. If you want to invoke a client from a script that runs +non-interactively, there is no opportunity to enter the password from the +terminal. On some systems, you may even find that the first line of your +script is read and interpreted (incorrectly) as your password! @item -After a fresh installation, you should connect to the server and set up -your users and their access permissions: +@tindex .my.cnf file +Store your password in a configuration file. For example, you can list your +password in the @code{[client]} section of the @file{.my.cnf} file in your +home directory: @example -shell> mysql -u root mysql +[client] +password=your_pass @end example -The server should let you connect because the @strong{MySQL} @code{root} user -has no password initially. That is also a security risk, so setting the -@code{root} password is something you should do while you're setting up -your other @strong{MySQL} users. - -If you try to connect as @code{root} and get this error: - -@example -Access denied for user: '@@unknown' to database mysql -@end example - -this means that you don't have an entry in the @code{user} table with a -@code{User} column value of @code{'root'} and that @code{mysqld} cannot -resolve the hostname for your client. In this case, you must restart the -server with the @code{--skip-grant-tables} option and edit your -@file{/etc/hosts} or @file{\windows\hosts} file to add an entry for your -host. +If you store your password in @file{.my.cnf}, the file should not be group or +world readable or writable. Make sure the file's access mode is @code{400} +or @code{600}. +@xref{Option files}. @item -If you get an error like the following: - -@example -shell> mysqladmin -u root -pxxxx ver -Access denied for user: 'root@@localhost' (Using password: YES) -@end example - -It means that you are using a wrong password. @xref{Passwords}. - -If you have forgot the root password, you can restart @code{mysqld} with -@code{--skip-grant-tables} to change the password. You can find more -about this option later on in this manual section. - -If you get the above error even if you haven't specified a password, -this means that you a wrong password in some @code{my.ini} -file. @xref{Option files}. You can avoid using option files with the @code{--no-defaults} option, as follows: - -@example -shell> mysqladmin --no-defaults -u root ver -@end example - -@item -@cindex @code{mysql_fix_privilege_tables} -If you updated an existing @strong{MySQL} installation from a version earlier -than Version 3.22.11 to Version 3.22.11 or later, did you run the -@code{mysql_fix_privilege_tables} script? If not, do so. The structure of -the grant tables changed with @strong{MySQL} Version 3.22.11 when the -@code{GRANT} statement became functional. - -@item -If your privileges seem to have changed in the middle of a session, it may be -that a superuser has changed them. Reloading the grant tables affects new -client connections, but it also affects existing connections as indicated in -@ref{Privilege changes}. - -@item -If you can't get your password to work, remember that you must use -the @code{PASSWORD()} function if you set the password with the -@code{INSERT}, @code{UPDATE}, or @code{SET PASSWORD} statements. The -@code{PASSWORD()} function is unnecessary if you specify the password using -the @code{GRANT ... INDENTIFIED BY} statement or the @code{mysqladmin -password} command. -@xref{Passwords}. - -@item -@code{localhost} is a synonym for your local hostname, and is also the -default host to which clients try to connect if you specify no host -explicitly. However, connections to @code{localhost} do not work if you are -running on a system that uses MIT-pthreads (@code{localhost} connections are -made using Unix sockets, which are not supported by MIT-pthreads). To avoid -this problem on such systems, you should use the @code{--host} option to name -the server host explicitly. This will make a TCP/IP connection to the -@code{mysqld} server. In this case, you must have your real hostname in -@code{user} table entries on the server host. (This is true even if you are -running a client program on the same host as the server.) - -@item -If you get an @code{Access denied} error when trying to connect to the -database with @code{mysql -u user_name db_name}, you may have a problem -with the @code{user} table. Check this by executing @code{mysql -u root -mysql} and issuing this SQL statement: - -@example -mysql> SELECT * FROM user; -@end example - -The result should include an entry with the @code{Host} and @code{User} -columns matching your computer's hostname and your @strong{MySQL} user name. - -@item -The @code{Access denied} error message will tell you who you are trying -to log in as, the host from which you are trying to connect, and whether -or not you were using a password. Normally, you should have one entry in -the @code{user} table that exactly matches the hostname and user name -that were given in the error message. For example if you get an error -message that contains @code{Using password: NO}, this means that you -tried to login without an password. - -@item -If you get the following error when you try to connect from a different host -than the one on which the @strong{MySQL} server is running, then there is no -row in the @code{user} table that matches that host: - -@example -Host ... is not allowed to connect to this MySQL server -@end example - -You can fix this by using the command-line tool @code{mysql} (on the -server host!) to add a row to the @code{user}, @code{db}, or @code{host} -table for the user/hostname combination from which you are trying to -connect and then execute @code{mysqladmin flush-privileges}. If you are -not running @strong{MySQL} Version 3.22 and you don't know the IP number or -hostname of the machine from which you are connecting, you should put an -entry with @code{'%'} as the @code{Host} column value in the @code{user} -table and restart @code{mysqld} with the @code{--log} option on the -server machine. After trying to connect from the client machine, the -information in the @strong{MySQL} log will indicate how you really did -connect. (Then replace the @code{'%'} in the @code{user} table entry -with the actual hostname that shows up in the log. Otherwise, you'll -have a system that is insecure.) - -Another reason for this error on Linux is that you are using a binary -@strong{MySQL} version that is compiled with a different glibc version -than the one you are using. In this case you should either upgrade your -OS/glibc or download the source @strong{MySQL} version and compile this -yourself. A source RPM is normally trivial to compile and install, so -this isn't a big problem. - -@item -If you get an error message where the hostname is not shown or where the -hostname is an IP, even if you try to connect with a hostname: - -@example -shell> mysqladmin -u root -pxxxx -h some-hostname ver -Access denied for user: 'root@' (Using password: YES) -@end example - -This means that @strong{MySQL} got some error when trying to resolve the -IP to a hostname. In this case you can execute @code{mysqladmin -flush-hosts} to reset the internal DNS cache. @xref{DNS}. - -Some permanent solutions are: - -@itemize @minus -@item -Try to find out what is wrong with your DNS server and fix this. -@item -Specify IPs instead of hostnames in the @strong{MySQL} privilege tables. -@item -Start @code{mysqld} with @code{--skip-name-resolve}. -@item -Start @code{mysqld} with @code{--skip-host-cache}. -@item -Connect to @code{localhost} if you are running the server and the client -on the same machine. -@item -Put the client machine names in @code{/etc/hosts}. +You can store your password in the @code{MYSQL_PWD} environment variable, but +this method must be considered extremely insecure and should not be used. +Some versions of @code{ps} include an option to display the environment of +running processes; your password will be in plain sight for all to see if +you set @code{MYSQL_PWD}. Even on systems without such a version of +@code{ps}, it is unwise to assume there is no other method to observe process +environments. @xref{Environment variables}. @end itemize -@item -If @code{mysql -u root test} works but @code{mysql -h your_hostname -u root -test} results in @code{Access denied}, then you may not have the correct name -for your host in the @code{user} table. A common problem here is that the -@code{Host} value in the user table entry specifies an unqualified hostname, -but your system's name resolution routines return a fully qualified domain -name (or vice-versa). For example, if you have an entry with host -@code{'tcx'} in the @code{user} table, but your DNS tells @strong{MySQL} that -your hostname is @code{'tcx.subnet.se'}, the entry will not work. Try adding -an entry to the @code{user} table that contains the IP number of your host as -the @code{Host} column value. (Alternatively, you could add an entry to the -@code{user} table with a @code{Host} value that contains a wild card---for -example, @code{'tcx.%'}. However, use of hostnames ending with @samp{%} is -@emph{insecure} and is @emph{not} recommended!) +All in all, the safest methods are to have the client program prompt for the +password or to specify the password in a properly protected @file{.my.cnf} +file. -@item -If @code{mysql -u user_name test} works but @code{mysql -u user_name -other_db_name} doesn't work, you don't have an entry for @code{other_db_name} -listed in the @code{db} table. -@item -If @code{mysql -u user_name db_name} works when executed on the server -machine, but @code{mysql -u host_name -u user_name db_name} doesn't work when -executed on another client machine, you don't have the client machine listed -in the @code{user} table or the @code{db} table. +@node Disaster Prevention, Database Administration, User Account Management, MySQL Database Administration +@section Disaster Prevention and Recovery -@item -If you can't figure out why you get @code{Access denied}, remove from the -@code{user} table all entries that have @code{Host} values containing -wild cards (entries that contain @samp{%} or @samp{_}). A very common error -is to insert a new entry with @code{Host}=@code{'%'} and -@code{User}=@code{'some user'}, thinking that this will allow you to specify -@code{localhost} to connect from the same machine. The reason that this -doesn't work is that the default privileges include an entry with -@code{Host}=@code{'localhost'} and @code{User}=@code{''}. Because that entry -has a @code{Host} value @code{'localhost'} that is more specific than -@code{'%'}, it is used in preference to the new entry when connecting from -@code{localhost}! The correct procedure is to insert a second entry with -@code{Host}=@code{'localhost'} and @code{User}=@code{'some_user'}, or to -remove the entry with @code{Host}=@code{'localhost'} and -@code{User}=@code{''}. +@menu +* Backup:: +* BACKUP TABLE:: +* RESTORE TABLE:: +* CHECK TABLE:: +* REPAIR TABLE:: +* Table maintenance:: +* Maintenance regimen:: +* Table-info:: +@end menu + +@node Backup, BACKUP TABLE, Disaster Prevention, Disaster Prevention +@subsection Database Backups + +@cindex databases, backups +@cindex backups + +Because @strong{MySQL} tables are stored as files, it is easy to do a +backup. To get a consistent backup, do a @code{LOCK TABLES} on the +relevant tables followed by @code{FLUSH TABLES} for the tables. +@xref{LOCK TABLES, , @code{LOCK TABLES}}. +@xref{FLUSH, , @code{FLUSH}}. +You only need a read lock; this allows other threads to continue to +query the tables while you are making a copy of the files in the +database directory. The @code{FLUSH TABLE} is needed to ensure that +the all active index pages is written to disk before you start the backup. + +If you want to make a SQL level backup of a table, you can use +@code{SELECT INTO OUTFILE} or @code{BACKUP TABLE}. @xref{SELECT}. +@xref{BACKUP TABLE}. + +Another way to back up a database is to use the @code{mysqldump} program or +the @code{mysqlhotcopy script}. @xref{mysqldump, , @code{mysqldump}}. +@xref{mysqlhotcopy, , @code{mysqlhotcopy}}. + +@enumerate @item -If you get the following error, you may have a problem with the @code{db} or -@code{host} table: +Do a full backup of your databases: @example -Access to database denied +shell> mysqldump --tab=/path/to/some/dir --opt --full + +or + +shell> mysqlhotcopy database /path/to/some/dir @end example -If the entry selected from the @code{db} table has an empty value in the -@code{Host} column, make sure there are one or more corresponding entries in -the @code{host} table specifying which hosts the @code{db} table entry -applies to. - -If you get the error when using the SQL commands @code{SELECT ... -INTO OUTFILE} or @code{LOAD DATA INFILE}, your entry in the @code{user} table -probably doesn't have the @strong{file} privilege enabled. +You can also simply copy all table files (@file{*.frm}, @file{*.MYD}, and +@file{*.MYI} files) as long as the server isn't updating anything. +The script @code{mysqlhotcopy} does use this method. @item -@cindex configuration files +@cindex log files, names +Stop @code{mysqld} if it's running, then start it with the +@code{--log-update[=file_name]} option. @xref{Update log}. The update +log file(s) provide you with the information you need to replicate +changes to the database that are made subsequent to the point at which +you executed @code{mysqldump}. +@end enumerate + +If you have to restore something, try to recover your tables using +@code{REPAIR TABLE} or @code{myisamchk -r} first. That should work in +99.9% of all cases. If @code{myisamchk} fails, try the following +procedure: (This will only work if you have started @strong{MySQL} with +@code{--log-update}. @xref{Update log}.): + +@enumerate +@item +Restore the original @code{mysqldump} backup. +@item +Execute the following command to re-run the updates in the binary log: + +@example +shell> mysqlbinlog hostname-bin.[0-9]* | mysql +@end example + +If you are using the update log you can use: + +@example +shell> ls -1 -t -r hostname.[0-9]* | xargs cat | mysql +@end example +@end enumerate + +@code{ls} is used to get all the update log files in the right order. + +You can also do selective backups with @code{SELECT * INTO OUTFILE 'file_name' +FROM tbl_name} and restore with @code{LOAD DATA INFILE 'file_name' REPLACE +...} To avoid duplicate records, you need a @code{PRIMARY KEY} or a +@code{UNIQUE} key in the table. The @code{REPLACE} keyword causes old records +to be replaced with new ones when a new record duplicates an old record on +a unique key value. + +If you get performance problems in making backups on your system, you can +solve this by setting up replication and do the backups on the slave +instead of on the master. @xref{Replication Intro}. + +If you are using a Veritas file system, you can do: + +@enumerate +@item +Execute in a client (perl ?) @code{FLUSH TABLES WITH READ LOCK} + +@item +Fork a shell or execute in another client @code{mount vxfs snapshot}. + +@item +Execute in the first client @code{UNLOCK TABLES} + +@item +Copy files from snapshot + +@item +Unmount snapshot +@end enumerate + + +@node BACKUP TABLE, RESTORE TABLE, Backup, Disaster Prevention +@subsection @code{BACKUP TABLE} Syntax + +@findex BACKUP TABLE + +@cindex backups, database + +@example +BACKUP TABLE tbl_name[,tbl_name...] TO '/path/to/backup/directory' +@end example + +Make a copy of all the table files to the backup directory that are the +minimum needed to restore it. Currenlty only works for @code{MyISAM} +tables. For @code{MyISAM} table, copies @code{.frm} (definition) and +@code{.MYD} (data) files. The index file can be rebuilt from those two. + +Before using this command, please see @xref{Backup}. + +During the backup, read lock will be held for each table, one at time, +as they are being backed up. If you want to backup several tables as +a snapshot, you must first issue @code{LOCK TABLES} obtaining a read +lock for each table in the group. + +The command returns a table with the following columns: + +@multitable @columnfractions .35 .65 +@item @strong{Column} @tab @strong{Value} +@item Table @tab Table name +@item Op @tab Always ``backup'' +@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. +@item Msg_text @tab The message. +@end multitable + +Note that @code{BACKUP TABLE} is only available in @strong{MySQL} +version 3.23.25 and later. + + +@node RESTORE TABLE, CHECK TABLE, BACKUP TABLE, Disaster Prevention +@subsection @code{RESTORE TABLE} Syntax + +@findex RESTORE TABLE + +@example +RESTORE TABLE tbl_name[,tbl_name...] FROM '/path/to/backup/directory' +@end example + +Restores the table(s) from the backup that was made with +@code{BACKUP TABLE}. Existing tables will not be overwritten - if you +try to restore over an existing table, you will get an error. Restore +will take longer than BACKUP due to the need to rebuilt the index. The +more keys you have, the longer it is going to take. Just as +@code{BACKUP TABLE}, currently only works of @code{MyISAM} tables. + + +The command returns a table with the following columns: + +@multitable @columnfractions .35 .65 +@item @strong{Column} @tab @strong{Value} +@item Table @tab Table name +@item Op @tab Always ``restore'' +@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. +@item Msg_text @tab The message. +@end multitable + + +@node CHECK TABLE, REPAIR TABLE, RESTORE TABLE, Disaster Prevention +@subsection @code{CHECK TABLE} Syntax + +@findex CHECK TABLE + +@example +CHECK TABLE tbl_name[,tbl_name...] [option [option...]] + +option = QUICK | FAST | MEDIUM | EXTEND | CHANGED +@end example + +@code{CHECK TABLE} only works on @code{MyISAM} tables. On +@code{MyISAM} tables it's the same thing as running @code{myisamchk -m +table_name} on the table. + +If you don't specify any option @code{MEDIUM} is used. + +Checks the table(s) for errors. For @code{MyISAM} tables the key statistics +is updated. The command returns a table with the following columns: + +@multitable @columnfractions .35 .65 +@item @strong{Column} @tab @strong{Value} +@item Table @tab Table name. +@item Op @tab Always ``check''. +@item Msg_type @tab One of @code{status}, @code{error}, @code{info}, or @code{warning}. +@item Msg_text @tab The message. +@end multitable + +Note that you can get many rows of information for each checked +table. The last row will be of @code{Msg_type status} and should +normally be @code{OK}. If you don't get @code{OK}, or @code{Not +checked} you should normally run a repair of the table. @xref{Table +maintenance}. @code{Not checked} means that the table the given @code{TYPE} +told @strong{MySQL} that there wasn't any need to check the table. + +The different check types stand for the following: + +@multitable @columnfractions .20 .80 +@item @strong{Type} @tab @strong{Meaning} +@item @code{QUICK} @tab Don't scan the rows to check for wrong links. +@item @code{FAST} @tab Only check tables which haven't been closed properly. +@item @code{CHANGED} @tab Only check tables which have been changed since last check or haven't been closed properly. +@item @code{MEDIUM} @tab Scan rows to verify that deleted links are ok. This also calculates a key checksum for the rows and verifies this with a calcualted checksum for the keys. +@item @code{EXTENDED} @tab Do a full key lookup for all keys for each row. This ensures that the table is 100 % consistent, but will take a long time! +@end multitable + +For dynamic sized @code{MyISAM} tables a started check will always +do a @code{MEDIUM} check. For static size rows we skip the row scan +for @code{QUICK} and @code{FAST} as the rows are very seldom corrupted. + +You can combine check options as in: + +@example +CHECK TABLE test_table FAST QUICK; +@end example + +Which only would do a quick check on the table if it wasn't closed properly. + +@strong{NOTE:} that in some case @code{CHECK TABLE} will change the +table! This happens if the table is marked as 'corrupted' or 'not +closed properly' but @code{CHECK TABLE} didn't find any problems in the +table. In this case @code{CHECK TABLE} will mark the table as ok. + +If a table is corrupted, then it's most likely that the problem is in +the indexes and not in the data part. All of the above check types +checks the indexes throughly and should thus find most errors. + +If you just want to check a table that you assume is ok, you should use +no check options or the @code{QUICK} option. The later should be used +when you are in a hurry and can take the very small risk that +@code{QUICK} didn't find an error in the data file (In most cases +@strong{MySQL} should find, under normal usage, any error in the data +file. If this happens then the table will be marked as 'corrupted', +in which case the table can't be used until it's repaired). + +@code{FAST} and @code{CHANGED} are mostly intended to be used from a +script (for example to be executed from cron) if you want to check your +table from time to time. In most cases you @code{FAST} is to be prefered +over @code{CHANGED}. (The only case when it isn't is when you suspect a +bug you have found a bug in the @code{MyISAM} code.). + +@code{EXTENDED} is only to be used after you have run a normal check but +still get strange errors from a table when @strong{MySQL} tries to +update a row or find a row by key (this is VERY unlikely to happen if a +normal check has succeeded!). + +Some things reported by check table, can't be corrected automatically: + +@itemize @bullet +@item +@code{Found row where the auto_increment column has the value 0}. + +This means that you have in the table a row where the +@code{auto_increment} index column contains the value 0. +(It's possible to create a row where the auto_increment column is 0 by +explicitely setting the column to 0 with an @code{UPDATE} statement) + +This isn't an error in itself, but could cause trouble if you decide to +dump the table and restore it or do an @code{ALTER TABLE} on the +table. In this case the auto_increment column will change value, +according to the rules of auto_increment columns, which could cause +problems like a duplicate key error. + +To get rid of the warning, just execute an @code{UPDATE} statement +to set the column to some other value than 0. +@end itemize + + +@node REPAIR TABLE, Table maintenance, CHECK TABLE, Disaster Prevention +@subsection @code{REPAIR TABLE} Syntax + +@findex REPAIR TABLE + +@example +REPAIR TABLE tbl_name[,tbl_name...] [QUICK] [EXTENDED] +@end example + +@code{REPAIR TABLE} only works on @code{MyISAM} tables and is the same +as running @code{myisamchk -r table_name} on the table. + +Normally you should never have to run this command, but if disaster strikes +you are very likely to get back all your data from a MyISAM table with +@code{REPAIR TABLE}. If your tables get corrupted a lot you should +try to find the reason for this! @xref{Crashing}. @xref{MyISAM table problems}. + +@code{REPAIR TABLE} repairs a possible corrupted table. The command returns a +table with the following columns: + +@multitable @columnfractions .35 .65 +@item @strong{Column} @tab @strong{Value} +@item Table @tab Table name +@item Op @tab Always ``repair'' +@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. +@item Msg_text @tab The message. +@end multitable + +Note that you can get many rows of information for each repaired +table. The last one row will be of @code{Msg_type status} and should +normally be @code{OK}. If you don't get @code{OK}, you should try +repairing the table with @code{myisamchk -o}, as @code{REPAIR TABLE} +does not yet implement all the options of @code{myisamchk}. In the near +future, we will make it more flexible. + +If @code{QUICK} is given then @strong{MySQL} will try to do a +@code{REPAIR} of only the index tree. + +If you use @code{EXTENDED} then @strong{MySQL} will create the index row +by row instead of creating one index at a time with sorting; This may be +better than sorting on fixed-length keys if you have long @code{char()} +keys that compress very good. + + +@node Table maintenance, Maintenance regimen, REPAIR TABLE, Disaster Prevention +@subsection Using @code{myisamchk} for Table Maintenance and Crash Recovery + +Starting with @strong{MySQL} Version 3.23.13, you can check MyISAM +tables with the @code{CHECK TABLE} command. @xref{CHECK TABLE}. You can +repair tables with the @code{REPAIR TABLE} command. @xref{REPAIR TABLE}. + +To check/repair MyISAM tables (@code{.MYI} and @code{.MYD}) you should +use the @code{myisamchk} utility. To check/repair ISAM tables +(@code{.ISM} and @code{.ISD}) you should use the @code{isamchk} +utility. @xref{Table types}. + +In the following text we will talk about @code{myisamchk}, but everything +also applies to the old @code{isamchk}. + +You can use the @code{myisamchk} utility to get information about your +database tables, check and repair them, or optimize them. The following +sections describe how to invoke @code{myisamchk} (including a +description of its options), how to set up a table maintenance schedule, +and how to use @code{myisamchk} to perform its various functions. + +You can, in most cases, also use the command @code{OPTIMIZE TABLES} to +optimize and repair tables, but this is not as fast or reliable (in case +of real fatal errors) as @code{myisamchk}. On the other hand, +@code{OPTIMIZE TABLE} is easier to use and you don't have to worry about +flushing tables. +@xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}. + +Even that the repair in @code{myisamchk} is quite secure, it's always a +good idea to make a backup BEFORE doing a repair (or anything that could +make a lot of changes to a table) + +@menu +* myisamchk syntax:: +* myisamchk general options:: +* myisamchk check options:: +* myisamchk repair options:: +* myisamchk other options:: +* myisamchk memory:: +* Crash recovery:: +* Check:: +* Repair:: +* Optimization:: +@end menu + +@node myisamchk syntax, myisamchk general options, Table maintenance, Table maintenance +@subsubsection @code{myisamchk} Invocation Syntax + +@code{myisamchk} is invoked like this: + +@example +shell> myisamchk [options] tbl_name +@end example + +The @code{options} specify what you want @code{myisamchk} to do. They are +described below. (You can also get a list of options by invoking +@code{myisamchk --help}.) With no options, @code{myisamchk} simply checks your +table. To get more information or to tell @code{myisamchk} to take corrective +action, specify options as described below and in the following sections. + +@code{tbl_name} is the database table you want to check/repair. If you run +@code{myisamchk} somewhere other than in the database directory, you must +specify the path to the file, because @code{myisamchk} has no idea where your +database is located. Actually, @code{myisamchk} doesn't care whether or not +the files you are working on are located in a database directory; you can +copy the files that correspond to a database table into another location and +perform recovery operations on them there. + +You can name several tables on the @code{myisamchk} command line if you +wish. You can also specify a name as an index file +name (with the @file{.MYI} suffix), which allows you to specify all +tables in a directory by using the pattern @file{*.MYI}. +For example, if you are in a database directory, you can check all the +tables in the directory like this: + +@example +shell> myisamchk *.MYI +@end example + +If you are not in the database directory, you can check all the tables there +by specifying the path to the directory: + +@example +shell> myisamchk /path/to/database_dir/*.MYI +@end example + +You can even check all tables in all databases by specifying a wild card +with the path to the @strong{MySQL} data directory: + +@example +shell> myisamchk /path/to/datadir/*/*.MYI +@end example + +The recommended way to quickly check all tables is: + +@example +myisamchk --silent --fast /path/to/datadir/*/*.MYI +isamchk --silent /path/to/datadir/*/*.ISM +@end example + +If you want to check all tables and repair all tables that are corrupted, +you can use the following line: + +@example +myisamchk --silent --force --fast --update-state -O key_buffer=64M -O sort_buffer=64M -O read_buffer=1M -O write_buffer=1M /path/to/datadir/*/*.MYI +isamchk --silent --force -O key_buffer=64M -O sort_buffer=64M -O read_buffer=1M -O write_buffer=1M /path/to/datadir/*/*.ISM +@end example + +The above assumes that you have more than 64 M free. + +Note that if you get an error like: + +@example +myisamchk: warning: 1 clients is using or hasn't closed the table properly +@end example + +This means that you are trying to check a table that has been updated by +the another program (like the @code{mysqld} server) that hasn't yet closed +the file or that has died without closing the file properly. + +If you @code{mysqld} is running, you must force a sync/close of all +tables with @code{FLUSH TABLES} and ensure that no one is using the +tables while you are running @code{myisamchk}. In @strong{MySQL} Version 3.23 +the easiest way to avoid this problem is to use @code{CHECK TABLE} +instead of @code{myisamchk} to check tables. + +@menu +* myisamchk general options:: +* myisamchk check options:: +* myisamchk repair options:: +* myisamchk other options:: +@end menu + + +@node myisamchk general options, myisamchk check options, myisamchk syntax, Table maintenance +@subsubsection General Options for @code{myisamchk} + +@cindex options, @code{myisamchk} +@cindex @code{myisamchk}, options + +@code{myisamchk} supports the following options. + +@table @code +@item -# or --debug=debug_options +Output debug log. The @code{debug_options} string often is +@code{'d:t:o,filename'}. +@item -? or --help +Display a help message and exit. +@item -O var=option, --set-variable var=option +Set the value of a variable. The possible variables and their default values +for myisamchk can be examined with @code{myisamchk --help}: +@multitable @columnfractions .3 .7 +@item key_buffer_size @tab 523264 +@item read_buffer_size @tab 262136 +@item write_buffer_size @tab 262136 +@item sort_buffer_size @tab 2097144 +@item sort_key_blocks @tab 16 +@item decode_bits @tab 9 +@end multitable + +@code{sort_buffer_size} is used when the keys are repaired by sorting +keys, which is the normal case when you use @code{--recover}. + +@code{key_buffer_size} is used when you are checking the table with +@code{--extended-check} or when the keys are repaired by inserting key +row by row in to the table (like when doing normal inserts). Repairing +through the key buffer is used in the following cases: + +@itemize @bullet +@item +If you use @code{--safe-recover}. +@item +If you are using a @code{FULLTEXT} index. +@item +If the temporary files needed to sort the keys would be more than twice +as big as when creating the key file directly. This is often the case +when you have big @code{CHAR}, @code{VARCHAR} or @code{TEXT} keys as the +sort needs to store the whole keys during sorting. If you have lots +of temporary space and you can force @code{myisamchk} to repair by sorting +you can use the @code{--sort-recover} option. +@end itemize + +Reparing through the key buffer takes much less disk space than using +sorting, but is also much slower. + +If you want a faster repair, set the above variables to about 1/4 of your +available memory. You can set both variables to big values, as only one +of the above buffers will be used at a time. + +@item -s or --silent +Silent mode. Write output only when errors occur. You can use @code{-s} +twice (@code{-ss}) to make @code{myisamchk} very silent. +@item -v or --verbose +Verbose mode. Print more information. This can be used with @code{-d} and +@code{-e}. Use @code{-v} multiple times (@code{-vv}, @code{-vvv}) for more +verbosity! +@item -V or --version +Print the @code{myisamchk} version and exit. +@item -w or, --wait +Instead of giving an error if the table is locked, wait until the table +is unlocked before continuing. Note that if you are running @code{mysqld} +on the table with @code{--skip-locking}, the table can only be locked +by another @code{myisamchk} command. +@end table + + +@node myisamchk check options, myisamchk repair options, myisamchk general options, Table maintenance +@subsubsection Check Options for @code{myisamchk} + +@cindex check options, myisamchk +@cindex tables, checking + +@table @code +@item -c or --check +Check table for errors. This is the default operation if you are not +giving @code{myisamchk} any options that override this. + +@item -e or --extend-check +Check the table VERY thoroughly (which is quite slow if you have many +indexes). This option should only be used in extreme cases. Normally, +@code{myisamchk} or @code{myisamchk --medium-check} should, in most +cases, be able to find out if there are any errors in the table. + +If you are using @code{--extended-check} and have much memory, you should +increase the value of @code{key_buffer_size} a lot! + +@item -F or --fast +Check only tables that haven't been closed properly. +@item -C or --check-only-changed +Check only tables that have changed since the last check. +@item -f or --force +Restart @code{myisamchk} with @code{-r} (repair) on the table, if +@code{myisamchk} finds any errors in the table. +@item -i or --information +Print informational statistics about the table that is checked. +@item -m or --medium-check +Faster than extended-check, but only finds 99.99% of all errors. +Should, however, be good enough for most cases. +@item -U or --update-state +Store in the @file{.MYI} file when the table was checked and if the table crashed. This should be used to get full benefit of the +@code{--check-only-changed} option, but you shouldn't use this +option if the @code{mysqld} server is using the table and you are +running @code{mysqld} with @code{--skip-locking}. +@item -T or --read-only +Don't mark table as checked. This is useful if you use @code{myisamchk} +to check a table that is in use by some other application that doesn't +use locking (like @code{mysqld --skip-locking}). +@end table + + +@node myisamchk repair options, myisamchk other options, myisamchk check options, Table maintenance +@subsubsection Repair Options for myisamchk + +@cindex repair options, myisamchk +@cindex files, repairing + +The following options are used if you start @code{myisamchk} with +@code{-r} or @code{-o}: + +@table @code +@item -D # or --data-file-length=# +Max length of data file (when re-creating data file when it's 'full'). +@item -e or --extend-check +Try to recover every possible row from the data file. +Normally this will also find a lot of garbage rows. Don't use this option +if you are not totally desperate. +@item -f or --force +Overwrite old temporary files (@code{table_name.TMD}) instead of aborting. +@item -k # or keys-used=# +If you are using ISAM, tells the ISAM table handler to update only the +first @code{#} indexes. If you are using @code{MyISAM}, tells which keys +to use, where each binary bit stands for one key (first key is bit 0). +This can be used to get faster inserts! Deactivated indexes can be +reactivated by using @code{myisamchk -r}. keys. +@item -l or --no-symlinks +Do not follow symbolic links. Normally @code{myisamchk} repairs the +table a symlink points at. This option doesn't exist in MySQL 4.0, +as MySQL 4.0 will not remove symlinks during repair. +@item -r or --recover +Can fix almost anything except unique keys that aren't unique +(which is an extremely unlikely error with ISAM/MyISAM tables). +If you want to recover a table, this is the option to try first. Only if +myisamchk reports that the table can't be recovered by @code{-r}, you +should then try @code{-o}. (Note that in the unlikely case that @code{-r} +fails, the data file is still intact.) +If you have lots of memory, you should increase the size of +@code{sort_buffer_size}! +@item -o or --safe-recover +Uses an old recovery method (reads through all rows in order and updates +all index trees based on the found rows); this is a magnitude slower +than @code{-r}, but can handle a couple of very unlikely cases that +@code{-r} cannot handle. This recovery method also uses much less disk +space than @code{-r}. Normally one should always first repair with +@code{-r}, and only if this fails use @code{-o}. + +If you have lots of memory, you should increase the size of +@code{key_buffer_size}! +@item -n or --sort-recover +Force @code{myisamchk} to use sorting to resolve the keys even if the +temporary files should be very big. This will not have any effect if you have +fulltext keys in the table. + +@item --character-sets-dir=... +Directory where character sets are stored. +@item --set-character-set=name +Change the character set used by the index +@item .t or --tmpdir=path +Path for storing temporary files. If this is not set, @code{myisamchk} will +use the environment variable @code{TMPDIR} for this. +@item -q or --quick +Faster repair by not modifying the data file. One can give a second +@code{-q} to force @code{myisamchk} to modify the original datafile in case +of duplicate keys +@item -u or --unpack +Unpack file packed with myisampack. +@end table + +@node myisamchk other options, myisamchk memory, myisamchk repair options, Table maintenance +@subsubsection Other Options for @code{myisamchk} + +Other actions that @code{myisamchk} can do, besides repair and check tables: + +@table @code +@item -a or --analyze +Analyze the distribution of keys. This improves join performance by +enabling the join optimizer to better choose in which order it should +join the tables and which keys it should use: +@code{myisamchk --describe --verbose table_name'} or using @code{SHOW KEYS} in +@strong{MySQL}. +@item -d or --description +Prints some information about table. +@item -A or --set-auto-increment[=value] +Force auto_increment to start at this or higher value. If no value is +given, then sets the next auto_increment value to the highest used value +for the auto key + 1. +@item -S or --sort-index +Sort the index tree blocks in high-low order. +This will optimize seeks and will make table scanning by key faster. +@item -R or --sort-records=# +Sorts records according to an index. This makes your data much more localized +and may speed up ranged @code{SELECT} and @code{ORDER BY} operations on +this index. (It may be VERY slow to do a sort the first time!) +To find out a table's index numbers, use @code{SHOW INDEX}, which shows a +table's indexes in the same order that @code{myisamchk} sees them. Indexes are +numbered beginning with 1. +@end table + +@node myisamchk memory, Crash recovery, myisamchk other options, Table maintenance +@subsubsection @code{myisamchk} Memory Usage + +@cindex memory usage, myisamchk + +Memory allocation is important when you run @code{myisamchk}. +@code{myisamchk} uses no more memory than you specify with the @code{-O} +options. If you are going to use @code{myisamchk} on very large files, +you should first decide how much memory you want it to use. The default +is to use only about 3M to fix things. By using larger values, you can +get @code{myisamchk} to operate faster. For example, if you have more +than 32M RAM, you could use options such as these (in addition to any +other options you might specify): + +@example +shell> myisamchk -O sort=16M -O key=16M -O read=1M -O write=1M ... +@end example + +Using @code{-O sort=16M} should probably be enough for most cases. + +Be aware that @code{myisamchk} uses temporary files in @code{TMPDIR}. If +@code{TMPDIR} points to a memory file system, you may easily get out of +memory errors. If this happens, set @code{TMPDIR} to point at some directory +with more space and restart @code{myisamchk}. + +When repairing, @code{myisamchk} will also need a lot of disk space: + +@itemize @bullet +@item +Double the size of the record file (the original one and a copy). This +space is not needed if one does a repair with @code{--quick}, as in this +case only the index file will be re-created. This space is needed on the +same disk as the original record file! +@item +Space for the new index file that replaces the old one. The old +index file is truncated at start, so one usually ignore this space. +This space is needed on the same disk as the original index file! +@item +When using @code{--recover} or @code{--sort-recover} +(but not when using @code{--safe-recover}, you will need space for a +sort buffer for: +@code{(largest_key + row_pointer_length)*number_of_rows * 2}. +You can check the length of the keys and the row_pointer_length with +@code{myisamchk -dv table}. +This space is allocated on the temporary disk (specified by @code{TMPDIR} or +@code{--tmpdir=#}). +@end itemize + +If you have a problem with disk space during repair, you can try to use +@code{--safe-recover} instead of @code{--recover}. + + +@node Crash recovery, Check, myisamchk memory, Table maintenance +@subsubsection Using @code{myisamchk} for Crash Recovery + +@cindex crash, recovery +@cindex recovery, from crash + +If you run @code{mysqld} with @code{--skip-locking} (which is the default on +some systems, like Linux), you can't reliably use @code{myisamchk} to +check a table when @code{mysqld} is using the same table. If you +can be sure that no one is accessing the tables through @code{mysqld} +while you run @code{myisamchk}, you only have to do @code{mysqladmin +flush-tables} before you start checking the tables. If you can't +guarantee the above, then you must take down @code{mysqld} while you +check the tables. If you run @code{myisamchk} while @code{mysqld} is updating +the tables, you may get a warning that a table is corrupt even if it +isn't. + +If you are not using @code{--skip-locking}, you can use @code{myisamchk} +to check tables at any time. While you do this, all clients that try +to update the table will wait until @code{myisamchk} is ready before +continuing. + +If you use @code{myisamchk} to repair or optimize tables, you +@strong{MUST} always ensure that the @code{mysqld} server is not using +the table (this also applies if you are using @code{--skip-locking}). +If you don't take down @code{mysqld} you should at least do a +@code{mysqladmin flush-tables} before you run @code{myisamchk}. + +This chapter describes how to check for and deal with data corruption +in @strong{MySQL} databases. If your tables get corrupted a lot you should +try to find the reason for this! @xref{Crashing}. + +The @code{MyISAM} table section contains reason for why a table could be +corrupted. @xref{MyISAM table problems}. + +When performing crash recovery, it is important to understand that each table +@code{tbl_name} in a database corresponds to three files in the database +directory: + +@multitable @columnfractions .2 .8 +@item @strong{File} @tab @strong{Purpose} +@item @file{tbl_name.frm} @tab Table definition (form) file +@item @file{tbl_name.MYD} @tab Data file +@item @file{tbl_name.MYI} @tab Index file +@end multitable + +Each of these three file types is subject to corruption in various ways, but +problems occur most often in data files and index files. + +@code{myisamchk} works by creating a copy of the @file{.MYD} (data) file +row by row. It ends the repair stage by removing the old @file{.MYD} +file and renaming the new file to the original file name. If you use +@code{--quick}, @code{myisamchk} does not create a temporary @file{.MYD} +file, but instead assumes that the @file{.MYD} file is correct and only +generates a new index file without touching the @file{.MYD} file. This +is safe, because @code{myisamchk} automatically detects if the +@file{.MYD} file is corrupt and aborts the repair in this case. You can +also give two @code{--quick} options to @code{myisamchk}. In this case, +@code{myisamchk} does not abort on some errors (like duplicate key) but +instead tries to resolve them by modifying the @file{.MYD} +file. Normally the use of two @code{--quick} options is useful only if +you have too little free disk space to perform a normal repair. In this +case you should at least make a backup before running @code{myisamchk}. + + +@node Check, Repair, Crash recovery, Table maintenance +@subsubsection How to Check Tables for Errors + +@cindex checking, tables for errors +@cindex tables, error checking +@cindex errors, checking tables for + +To check a MyISAM table, use the following commands: + +@table @code +@item myisamchk tbl_name +This finds 99.99% of all errors. What it can't find is corruption that +involves @strong{ONLY} the data file (which is very unusual). If you want +to check a table, you should normally run @code{myisamchk} without options or +with either the @code{-s} or @code{--silent} option. + +@item myisamchk -m tbl_name +This finds 99.999% of all errors. It checks first all index entries for errors and +then it reads through all rows. It calculates a checksum for all keys in +the rows and verifies that they checksum matches the checksum for the keys +in the index tree. + +@item myisamchk -e tbl_name +This does a complete and thorough check of all data (@code{-e} means +``extended check''). It does a check-read of every key for each row to verify +that they indeed point to the correct row. This may take a LONG time on a +big table with many keys. @code{myisamchk} will normally stop after the first +error it finds. If you want to obtain more information, you can add the +@code{--verbose} (@code{-v}) option. This causes @code{myisamchk} to keep +going, up through a maximum of 20 errors. In normal usage, a simple +@code{myisamchk} (with no arguments other than the table name) is sufficient. + +@item myisamchk -e -i tbl_name +Like the previous command, but the @code{-i} option tells @code{myisamchk} to +print some informational statistics, too. +@end table + + +@node Repair, Optimization, Check, Table maintenance +@subsubsection How to Repair Tables + +@cindex tables, repairing +@cindex repairing, tables + +In the following section we only talk about using @code{myisamchk} on +@code{MyISAM} tables (extensions @code{.MYI} and @code{.MYD}). If you +are using @code{ISAM} tables (extensions @code{.ISM} and @code{.ISD}), +you should use @code{isamchk} instead. + +Starting with @strong{MySQL} Version 3.23.14, you can repair MyISAM +tables with the @code{REPAIR TABLE} command. @xref{REPAIR TABLE}. + +The symptoms of a corrupted table include queries that abort unexpectedly +and observable errors such as these: + +@itemize @bullet +@item +@file{tbl_name.frm} is locked against change +@item +Can't find file @file{tbl_name.MYI} (Errcode: ###) +@item +Unexpected end of file +@item +Record file is crashed +@item +Got error ### from table handler + +To get more information about the error you can run @code{perror ###}. Here +is the most common errors that indicates a problem with the table: + +@example +shell> perror 126 127 132 134 135 136 141 144 145 +126 = Index file is crashed / Wrong file format +127 = Record-file is crashed +132 = Old database file +134 = Record was already deleted (or record file crashed) +135 = No more room in record file +136 = No more room in index file +141 = Duplicate unique key or constraint on write or update +144 = Table is crashed and last repair failed +145 = Table was marked as crashed and should be repaired +@end example + +Note that error 135, no more room in record file, is not an error that +can be fixed by a simple repair. In this case you have to do: + +@example +ALTER TABLE table MAX_ROWS=xxx AVG_ROW_LENGTH=yyy; +@end example + +@end itemize + +In the other cases, you must repair your tables. @code{myisamchk} +can usually detect and fix most things that go wrong. + +The repair process involves up to four stages, described below. Before you +begin, you should @code{cd} to the database directory and check the +permissions of the table files. Make sure they are readable by the Unix user +that @code{mysqld} runs as (and to you, because you need to access the files +you are checking). If it turns out you need to modify files, they must also +be writable by you. + +If you are using @strong{MySQL} Version 3.23.16 and above, you can (and +should) use the @code{CHECK} and @code{REPAIR} commands to check and repair +@code{MyISAM} tables. @xref{CHECK TABLE}. @xref{REPAIR TABLE}. + +The manual section about table maintenance includes the options to +@code{isamchk}/@code{myisamchk}. @xref{Table maintenance}. + +The following section is for the cases where the above command fails or +if you want to use the extended features that @code{isamchk}/@code{myisamchk} provides. + +If you are going to repair a table from the command line, you must first +take down the @code{mysqld} server. Note that when you do +@code{mysqladmin shutdown} on a remote server, the @code{mysqld} server +will still be alive for a while after @code{mysqladmin} returns, until +all queries are stopped and all keys have been flushed to disk. + +@noindent +@strong{Stage 1: Checking your tables} + +Run @code{myisamchk *.MYI} or @code{myisamchk -e *.MYI} if you have +more time. Use the @code{-s} (silent) option to suppress unnecessary +information. + +If the @code{mysqld} server is done you should use the --update option to tell +@code{myisamchk} to mark the table as 'checked'. + +You have to repair only those tables for which @code{myisamchk} announces an +error. For such tables, proceed to Stage 2. + +If you get weird errors when checking (such as @code{out of +memory} errors), or if @code{myisamchk} crashes, go to Stage 3. + +@noindent +@strong{Stage 2: Easy safe repair} + +NOTE: If you want repairing to go much faster, you should add: @code{-O +sort_buffer=# -O key_buffer=#} (where # is about 1/4 of the available +memory) to all @code{isamchk/myisamchk} commands. + +First, try @code{myisamchk -r -q tbl_name} (@code{-r -q} means ``quick +recovery mode''). This will attempt to repair the index file without +touching the data file. If the data file contains everything that it +should and the delete links point at the correct locations within the +data file, this should work, and the table is fixed. Start repairing the +next table. Otherwise, use the following procedure: + +@enumerate +@item +Make a backup of the data file before continuing. + +@item +Use @code{myisamchk -r tbl_name} (@code{-r} means ``recovery mode''). This will +remove incorrect records and deleted records from the data file and +reconstruct the index file. + +@item +If the preceding step fails, use @code{myisamchk --safe-recover tbl_name}. +Safe recovery mode uses an old recovery method that handles a few cases that +regular recovery mode doesn't (but is slower). +@end enumerate + +If you get weird errors when repairing (such as @code{out of +memory} errors), or if @code{myisamchk} crashes, go to Stage 3. + +@noindent +@strong{Stage 3: Difficult repair} + +You should only reach this stage if the first 16K block in the index file is +destroyed or contains incorrect information, or if the index file is +missing. In this case, it's necessary to create a new index file. Do so as +follows: + +@enumerate +@item +Move the data file to some safe place. + +@item +Use the table description file to create new (empty) data and index files: + +@example +shell> mysql db_name +mysql> SET AUTOCOMMIT=1; +mysql> TRUNCATE TABLE table_name; +mysql> quit +@end example + +If your SQL version doesn't have @code{TRUNCATE TABLE}, use @code{DELETE FROM +table_name} instead. + +@item +Copy the old data file back onto the newly created data file. +(Don't just move the old file back onto the new file; you want to retain +a copy in case something goes wrong.) +@end enumerate + +Go back to Stage 2. @code{myisamchk -r -q} should work now. (This shouldn't +be an endless loop.) + +@noindent +@strong{Stage 4: Very difficult repair} + +You should reach this stage only if the description file has also +crashed. That should never happen, because the description file isn't changed +after the table is created: + +@enumerate +@item +Restore the description file from a backup and go back to Stage 3. You can +also restore the index file and go back to Stage 2. In the latter case, you +should start with @code{myisamchk -r}. + +@item +If you don't have a backup but know exactly how the table was created, create +a copy of the table in another database. Remove the new data file, then move +the description and index files from the other database to your crashed +database. This gives you new description and index files, but leaves +the data file alone. Go back to Stage 2 and attempt to reconstruct +the index file. +@end enumerate + + +@node Optimization, , Repair, Table maintenance +@subsubsection Table Optimization + +@cindex tables, optimizing +@cindex optimizing, tables + +To coalesce fragmented records and eliminate wasted space resulting from +deleting or updating records, run @code{myisamchk} in recovery mode: + +@example +shell> myisamchk -r tbl_name +@end example + +You can optimize a table in the same way using the SQL @code{OPTIMIZE TABLE} +statement. @code{OPTIMIZE TABLE} does a repair of the table, a key +analyzes and also sorts the index tree to give faster key lookups. +There is also no possibility of unwanted interaction between a utility +and the server, because the server does all the work when you use +@code{OPTIMIZE TABLE}. @xref{OPTIMIZE TABLE}. + +@code{myisamchk} also has a number of other options you can use to improve +the performance of a table: + +@table @code +@item -S, --sort-index +@item -R index_num, --sort-records=index_num +@item -a, --analyze +@end table + +For a full description of the option. @xref{myisamchk syntax}. + + +@node Maintenance regimen, Table-info, Table maintenance, Disaster Prevention +@subsection Setting Up a Table Maintenance Regimen + +@cindex maintaining, tables +@cindex tables, maintenance regimen + +Starting with @strong{MySQL} Version 3.23.13, you can check MyISAM +tables with the @code{CHECK TABLE} command. @xref{CHECK TABLE}. You can +repair tables with the @code{REPAIR TABLE} command. @xref{REPAIR TABLE}. + +It is a good idea to perform table checks on a regular basis rather than +waiting for problems to occur. For maintenance purposes, you can use +@code{myisamchk -s} to check tables. The @code{-s} option (short for +@code{--silent}) causes @code{myisamchk} to run in silent mode, printing +messages only when errors occur. + +@tindex .pid (process ID) file +It's also a good idea to check tables when the server starts up. +For example, whenever the machine has done a reboot in the middle of an +update, you usually need to check all the tables that could have been +affected. (This is an ``expected crashed table''.) You could add a test to +@code{safe_mysqld} that runs @code{myisamchk} to check all tables that have +been modified during the last 24 hours if there is an old @file{.pid} +(process ID) file left after a reboot. (The @file{.pid} file is created by +@code{mysqld} when it starts up and removed when it terminates normally. The +presence of a @file{.pid} file at system startup time indicates that +@code{mysqld} terminated abnormally.) + +An even better test would be to check any table whose last-modified time +is more recent than that of the @file{.pid} file. + +You should also check your tables regularly during normal system +operation. At @strong{MySQL AB}, we run a @code{cron} job to check all +our important tables once a week, using a line like this in a @file{crontab} +file: + +@example +35 0 * * 0 /path/to/myisamchk --fast --silent /path/to/datadir/*/*.MYI +@end example + +This prints out information about crashed tables so we can examine and repair +them when needed. + +As we haven't had any unexpectedly crashed tables (tables that become +corrupted for reasons other than hardware trouble) +for a couple of years now (this is really true), once a week is +more than enough for us. + +We recommend that to start with, you execute @code{myisamchk -s} each +night on all tables that have been updated during the last 24 hours, +until you come to trust @strong{MySQL} as much as we do. + +@cindex tables, defragment +Normally you don't need to maintain @strong{MySQL} tables that much. If +you are changing tables with dynamic size rows (tables with @code{VARCHAR}, +@code{BLOB} or @code{TEXT} columns) or have tables with many deleted rows +you may want to from time to time (once a month?) defragment/reclaim space +from the tables. + +You can do this by using @code{OPTIMIZE TABLE} on the tables in question or +if you can take the @code{mysqld} server down for a while do: + +@example +isamchk -r --silent --sort-index -O sort_buffer_size=16M */*.ISM +myisamchk -r --silent --sort-index -O sort_buffer_size=16M */*.MYI +@end example + + +@node Table-info, , Maintenance regimen, Disaster Prevention +@subsection Getting Information About a Table + +@cindex tables, information + +To get a description of a table or statistics about it, use the commands shown +below. We explain some of the information in more detail later: + +@table @code +@item myisamchk -d tbl_name +Runs @code{myisamchk} in ``describe mode'' to produce a description of +your table. If you start the @strong{MySQL} server using the +@code{--skip-locking} option, @code{myisamchk} may report an error for a +table that is updated while it runs. However, because @code{myisamchk} +doesn't change the table in describe mode, there isn't any risk of +destroying data. + +@item myisamchk -d -v tbl_name +To produce more information about what @code{myisamchk} is doing, add @code{-v} +to tell it to run in verbose mode. + +@item myisamchk -eis tbl_name +Shows only the most important information from a table. It is slow because it +must read the whole table. + +@item myisamchk -eiv tbl_name +This is like @code{-eis}, but tells you what is being done. +@end table + +@cindex examples, @code{myisamchk} output +@cindex @code{myisamchk}, example output +Example of @code{myisamchk -d} output: +@example +MyISAM file: company.MYI +Record format: Fixed length +Data records: 1403698 Deleted blocks: 0 +Recordlength: 226 + +table description: +Key Start Len Index Type +1 2 8 unique double +2 15 10 multip. text packed stripped +3 219 8 multip. double +4 63 10 multip. text packed stripped +5 167 2 multip. unsigned short +6 177 4 multip. unsigned long +7 155 4 multip. text +8 138 4 multip. unsigned long +9 177 4 multip. unsigned long + 193 1 text +@end example + +Example of @code{myisamchk -d -v} output: +@example +MyISAM file: company +Record format: Fixed length +File-version: 1 +Creation time: 1999-10-30 12:12:51 +Recover time: 1999-10-31 19:13:01 +Status: checked +Data records: 1403698 Deleted blocks: 0 +Datafile parts: 1403698 Deleted data: 0 +Datafilepointer (bytes): 3 Keyfile pointer (bytes): 3 +Max datafile length: 3791650815 Max keyfile length: 4294967294 +Recordlength: 226 + +table description: +Key Start Len Index Type Rec/key Root Blocksize +1 2 8 unique double 1 15845376 1024 +2 15 10 multip. text packed stripped 2 25062400 1024 +3 219 8 multip. double 73 40907776 1024 +4 63 10 multip. text packed stripped 5 48097280 1024 +5 167 2 multip. unsigned short 4840 55200768 1024 +6 177 4 multip. unsigned long 1346 65145856 1024 +7 155 4 multip. text 4995 75090944 1024 +8 138 4 multip. unsigned long 87 85036032 1024 +9 177 4 multip. unsigned long 178 96481280 1024 + 193 1 text +@end example + +Example of @code{myisamchk -eis} output: +@example +Checking MyISAM file: company +Key: 1: Keyblocks used: 97% Packed: 0% Max levels: 4 +Key: 2: Keyblocks used: 98% Packed: 50% Max levels: 4 +Key: 3: Keyblocks used: 97% Packed: 0% Max levels: 4 +Key: 4: Keyblocks used: 99% Packed: 60% Max levels: 3 +Key: 5: Keyblocks used: 99% Packed: 0% Max levels: 3 +Key: 6: Keyblocks used: 99% Packed: 0% Max levels: 3 +Key: 7: Keyblocks used: 99% Packed: 0% Max levels: 3 +Key: 8: Keyblocks used: 99% Packed: 0% Max levels: 3 +Key: 9: Keyblocks used: 98% Packed: 0% Max levels: 4 +Total: Keyblocks used: 98% Packed: 17% + +Records: 1403698 M.recordlength: 226 Packed: 0% +Recordspace used: 100% Empty space: 0% Blocks/Record: 1.00 +Record blocks: 1403698 Delete blocks: 0 +Recorddata: 317235748 Deleted data: 0 +Lost space: 0 Linkdata: 0 + +User time 1626.51, System time 232.36 +Maximum resident set size 0, Integral resident set size 0 +Non physical pagefaults 0, Physical pagefaults 627, Swaps 0 +Blocks in 0 out 0, Messages in 0 out 0, Signals 0 +Voluntary context switches 639, Involuntary context switches 28966 +@end example + +Example of @code{myisamchk -eiv} output: +@example +Checking MyISAM file: company +Data records: 1403698 Deleted blocks: 0 +- check file-size +- check delete-chain +block_size 1024: +index 1: +index 2: +index 3: +index 4: +index 5: +index 6: +index 7: +index 8: +index 9: +No recordlinks +- check index reference +- check data record references index: 1 +Key: 1: Keyblocks used: 97% Packed: 0% Max levels: 4 +- check data record references index: 2 +Key: 2: Keyblocks used: 98% Packed: 50% Max levels: 4 +- check data record references index: 3 +Key: 3: Keyblocks used: 97% Packed: 0% Max levels: 4 +- check data record references index: 4 +Key: 4: Keyblocks used: 99% Packed: 60% Max levels: 3 +- check data record references index: 5 +Key: 5: Keyblocks used: 99% Packed: 0% Max levels: 3 +- check data record references index: 6 +Key: 6: Keyblocks used: 99% Packed: 0% Max levels: 3 +- check data record references index: 7 +Key: 7: Keyblocks used: 99% Packed: 0% Max levels: 3 +- check data record references index: 8 +Key: 8: Keyblocks used: 99% Packed: 0% Max levels: 3 +- check data record references index: 9 +Key: 9: Keyblocks used: 98% Packed: 0% Max levels: 4 +Total: Keyblocks used: 9% Packed: 17% + +- check records and index references +[LOTS OF ROW NUMBERS DELETED] + +Records: 1403698 M.recordlength: 226 Packed: 0% +Recordspace used: 100% Empty space: 0% Blocks/Record: 1.00 +Record blocks: 1403698 Delete blocks: 0 +Recorddata: 317235748 Deleted data: 0 +Lost space: 0 Linkdata: 0 + +User time 1639.63, System time 251.61 +Maximum resident set size 0, Integral resident set size 0 +Non physical pagefaults 0, Physical pagefaults 10580, Swaps 0 +Blocks in 4 out 0, Messages in 0 out 0, Signals 0 +Voluntary context switches 10604, Involuntary context switches 122798 +@end example + +Here are the sizes of the data and index files for the table used in the +preceding examples: + +@example +-rw-rw-r-- 1 monty tcx 317235748 Jan 12 17:30 company.MYD +-rw-rw-r-- 1 davida tcx 96482304 Jan 12 18:35 company.MYM +@end example + +Explanations for the types of information @code{myisamchk} produces are +given below. The ``keyfile'' is the index file. ``Record'' and ``row'' +are synonymous: + +@table @code +@item ISAM file +Name of the ISAM (index) file. + +@item Isam-version +Version of ISAM format. Currently always 2. + +@item Creation time +When the data file was created. + +@item Recover time +When the index/data file was last reconstructed. + +@item Data records +How many records are in the table. + +@item Deleted blocks +How many deleted blocks still have reserved space. +You can optimize your table to minimize this space. +@xref{Optimization}. + +@item Datafile: Parts +For dynamic record format, this indicates how many data blocks there are. For +an optimized table without fragmented records, this is the same as @code{Data +records}. + +@item Deleted data +How many bytes of non-reclaimed deleted data there are. +You can optimize your table to minimize this space. +@xref{Optimization}. + +@item Datafile pointer +The size of the data file pointer, in bytes. It is usually 2, 3, 4, or 5 +bytes. Most tables manage with 2 bytes, but this cannot be controlled +from @strong{MySQL} yet. For fixed tables, this is a record address. For +dynamic tables, this is a byte address. + +@item Keyfile pointer +The size of the index file pointer, in bytes. It is usually 1, 2, or 3 +bytes. Most tables manage with 2 bytes, but this is calculated +automatically by @strong{MySQL}. It is always a block address. + +@item Max datafile length +How long the table's data file (@code{.MYD} file) can become, in bytes. + +@item Max keyfile length +How long the table's key file (@code{.MYI} file) can become, in bytes. + +@item Recordlength +How much space each record takes, in bytes. + +@item Record format +The format used to store table rows. +The examples shown above use @code{Fixed length}. +Other possible values are @code{Compressed} and @code{Packed}. + +@item table description +A list of all keys in the table. For each key, some low-level information +is presented: + +@table @code +@item Key +This key's number. + +@item Start +Where in the record this index part starts. + +@item Len +How long this index part is. For packed numbers, this should always be +the full length of the column. For strings, it may be shorter than the full +length of the indexed column, because you can index a prefix of a string +column. + +@item Index +@code{unique} or @code{multip.} (multiple). Indicates whether or not one value +can exist multiple times in this index. + +@item Type +What data-type this index part has. This is an ISAM data-type +with the options @code{packed}, @code{stripped} or @code{empty}. + +@item Root +Address of the root index block. + +@item Blocksize +The size of each index block. By default this is 1024, but the value may be +changed at compile time. + +@item Rec/key +This is a statistical value used by the optimizer. It tells how many +records there are per value for this key. A unique key always has a +value of 1. This may be updated after a table is loaded (or greatly +changed) with @code{myisamchk -a}. If this is not updated at all, a default +value of 30 is given. +@end table + +@item +In the first example above, the 9th key is a multi-part key with two parts. + +@item Keyblocks used +What percentage of the keyblocks are used. Because the table used in the +examples had just been reorganized with @code{myisamchk}, the values are very +high (very near the theoretical maximum). + +@item Packed +@strong{MySQL} tries to pack keys with a common suffix. This can only be used +for @code{CHAR}/@code{VARCHAR}/@code{DECIMAL} keys. For long strings like +names, this can significantly reduce the space used. In the third example +above, the 4th key is 10 characters long and a 60% reduction in space is +achieved. + +@item Max levels +How deep the B-tree for this key is. Large tables with long keys get high +values. + +@item Records +How many rows are in the table. + +@item M.recordlength +The average record length. For tables with fixed-length records, this is the +exact record length. + +@item Packed +@strong{MySQL} strips spaces from the end of strings. The @code{Packed} +value indicates the percentage of savings achieved by doing this. + +@item Recordspace used +What percentage of the data file is used. + +@item Empty space +What percentage of the data file is unused. + +@item Blocks/Record +Average number of blocks per record (that is, how many links a fragmented +record is composed of). This is always 1 for fixed-format tables. This value +should stay as close to 1.0 as possible. If it gets too big, you can +reorganize the table with @code{myisamchk}. +@xref{Optimization}. + +@item Recordblocks +How many blocks (links) are used. For fixed format, this is the same as the number +of records. + +@item Deleteblocks +How many blocks (links) are deleted. + +@item Recorddata +How many bytes in the data file are used. + +@item Deleted data +How many bytes in the data file are deleted (unused). + +@item Lost space +If a record is updated to a shorter length, some space is lost. This is +the sum of all such losses, in bytes. + +@item Linkdata +When the dynamic table format is used, record fragments are linked with +pointers (4 to 7 bytes each). @code{Linkdata} is the sum of the amount of +storage used by all such pointers. +@end table + +If a table has been compressed with @code{myisampack}, @code{myisamchk +-d} prints additional information about each table column. See +@ref{myisampack, , @code{myisampack}}, for an example of this +information and a description of what it means. + + +@node Database Administration, KILL, Disaster Prevention, MySQL Database Administration +@section Database Administration Language Reference + + +@menu +* OPTIMIZE TABLE:: +* ANALYZE TABLE:: +* FLUSH:: +@end menu + +@node OPTIMIZE TABLE, ANALYZE TABLE, Database Administration, Database Administration +@subsection @code{OPTIMIZE TABLE} Syntax + +@findex OPTIMIZE TABLE + +@cindex tables, defragmenting +@cindex tables, fragmentation + +@example +OPTIMIZE TABLE tbl_name[,tbl_name]... +@end example + +@code{OPTIMIZE TABLE} should be used if you have deleted a large part of a +table or if you have made many changes to a table with variable-length rows +(tables that have @code{VARCHAR}, @code{BLOB}, or @code{TEXT} columns). +Deleted records are maintained in a linked list and subsequent @code{INSERT} +operations reuse old record positions. You can use @code{OPTIMIZE TABLE} to +reclaim the unused space and to defragment the data file. + +For the moment @code{OPTIMIZE TABLE} only works on @strong{MyISAM} and +@code{BDB} tables. For @code{BDB} tables, @code{OPTIMIZE TABLE} is +currently mapped to @code{ANALYZE TABLE}. @xref{ANALYZE TABLE}. + +You can get optimize table to work on other table types by starting +@code{mysqld} with @code{--skip-new} or @code{--safe-mode}, but in this +case @code{OPTIMIZE TABLE} is just mapped to @code{ALTER TABLE}. + +@code{OPTIMIZE TABLE} works the following way: +@itemize @bullet +@item +If the table has deleted or split rows, repair the table. +@item +If the index pages are not sorted, sort them. +@item +If the statistics are not up to date (and the repair couldn't be done +by sorting the index), update them. +@end itemize + +@code{OPTIMIZE TABLE} for @code{MyISAM} tables is equvialent of running +@code{myisamchk --quick --check-changed-tables --sort-index --analyze} +on the table. + +Note that the table is locked during the time @code{OPTIMIZE TABLE} is +running! + + +@node ANALYZE TABLE, FLUSH, OPTIMIZE TABLE, Database Administration +@subsection @code{ANALYZE TABLE} Syntax + +@findex ANALYZE TABLE + +@example +ANALYZE TABLE tbl_name[,tbl_name...] +@end example + +Analyze and store the key distribution for the table. During the +analyze the table is locked with a read lock. This works on +@code{MyISAM} and @code{BDB} tables. + +This is equivalent to running @code{myisamchk -a} on the table. + +@strong{MySQL} uses the stored key distribution to decide in which order +tables should be joined when one does a join on something else than a +constant. + +The command returns a table with the following columns: + +@multitable @columnfractions .35 .65 +@item @strong{Column} @tab @strong{Value} +@item Table @tab Table name +@item Op @tab Always ``analyze'' +@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. +@item Msg_text @tab The message. +@end multitable + +You can check the stored key distribution with the @code{SHOW INDEX} command. +@xref{SHOW DATABASE INFO}. + +If the table hasn't changed since the last @code{ANALYZE TABLE} command, +the table will not be analyzed again. + + +@node FLUSH, , ANALYZE TABLE, Database Administration +@subsection @code{FLUSH} Syntax + +@findex FLUSH + +@cindex @code{mysqladmin} +@cindex clearing, caches +@cindex caches, clearing + +@example +FLUSH flush_option [,flush_option] +@end example + +You should use the @code{FLUSH} command if you want to clear some of the +internal caches @strong{MySQL} uses. To execute @code{FLUSH}, you must have +the @strong{RELOAD} privilege. + +@code{flush_option} can be any of the following: + +@multitable @columnfractions .15 .85 +@item @code{HOSTS} @tab Empties the host cache tables. You should flush the +host tables if some of your hosts change IP number or if you get the +error message @code{Host ... is blocked}. When more than +@code{max_connect_errors} errors occur in a row for a given host while +connection to the @strong{MySQL} server, @strong{MySQL} assumes +something is wrong and blocks the host from further connection requests. +Flushing the host tables allows the host to attempt to connect +again. @xref{Blocked host}.) You can start @code{mysqld} with +@code{-O max_connection_errors=999999999} to avoid this error message. + +@item @code{LOGS} @tab Closes and reopens all log files. +If you have specified the update log file or a binary log file without +an extension, the extension number of the log file will be incremented +by one relative to the previous file. If you have used an extension in +the file name, @strong{MySQL} will close and reopen the update log file. +@xref{Update log}. This is the same thing as sending the @code{SIGHUP} +signal to the @code{mysqld} server. + +@item @code{PRIVILEGES} @tab Reloads the privileges from the grant tables in +the @code{mysql} database. + +@item @code{TABLES} @tab Closes all open tables and force all tables in use to be closed. + +@item @code{[TABLE | TABLES] table_name [,table_name...]} @tab Flushes only the given tables. + +@item @code{TABLES WITH READ LOCK} @tab Closes all open tables and locks all tables for all databases with a read until one executes @code{UNLOCK TABLES}. This is very convenient way to get backups if you have a file system, like Veritas,that can take snapshots in time. + +@item @code{STATUS} @tab Resets most status variables to zero. This is something one should only use when debugging a query. +@end multitable + +You can also access each of the commands shown above with the @code{mysqladmin} +utility, using the @code{flush-hosts}, @code{flush-logs}, @code{reload}, +or @code{flush-tables} commands. + +Take also a look at the @code{RESET} command used with +replication. @xref{Replication SQL}. + + + +@node KILL, Localization, Database Administration, MySQL Database Administration +@section @code{KILL} Syntax + +@findex KILL + +@cindex @code{mysqladmin} + +@example +KILL thread_id +@end example + +Each connection to @code{mysqld} runs in a separate thread. You can see +which threads are running with the @code{SHOW PROCESSLIST} command and kill +a thread with the @code{KILL thread_id} command. + +If you have the @strong{process} privilege, you can see and kill all threads. +Otherwise, you can see and kill only your own threads. + +You can also use the @code{mysqladmin processlist} and @code{mysqladmin kill} +commands to examine and kill threads. + +When you do a @code{KILL}, a thread specific @code{kill flag} is set for +the thread. + +In most cases it may take some time for the thread to die as the kill +flag is only checked at specific intervals. + +@itemize @bullet +@item +In @code{SELECT}, @code{ORDER BY} and @code{GROUP BY} loops, the flag is +checked after reading a block of rows. If the kill flag is set the +statement is aborted +@item +When doing an @code{ALTER TABLE} the kill flag is checked before each block of +rows are read from the original table. If the kill flag was set the command +is aborted and the temporary table is deleted. +@item +When doing an @code{UPDATE TABLE} and @code{DELETE TABLE}, the kill flag +is checked after each block read and after each updated or delete +row. If the kill flag is set the statement is aborted. Note that if you +are not using transactions, the changes will not be rolled back! +@item +@code{GET_LOCK()} will abort with @code{NULL}. +@item +An @code{INSERT DELAYED} thread will quickly flush all rows it has in +memory and die. +@item +If the thread is in the table lock handler (state: @code{Locked}), +the table lock will be quickly aborted. +@item +If the thread is waiting for free disk space in a @code{write} call, the +write is aborted with an disk full error message. +@end itemize + + +@menu +* SHOW:: +@end menu + +@node SHOW, , KILL, KILL +@subsection @code{SHOW} Syntax + +@c FIX more index hits needed + +@findex SHOW DATABASE INFO +@findex SHOW DATABASES +@findex SHOW TABLES +@findex SHOW COLUMNS +@findex SHOW FIELDS +@findex SHOW INDEX +@findex SHOW KEYS +@findex SHOW STATUS +@findex SHOW VARIABLES +@findex SHOW PROCESSLIST +@findex SHOW TABLE STATUS +@findex SHOW GRANTS +@findex SHOW CREATE TABLE +@findex SHOW MASTER STATUS +@findex SHOW MASTER LOGS +@findex SHOW SLAVE STATUS + +@example + SHOW DATABASES [LIKE wild] +or SHOW [OPEN] TABLES [FROM db_name] [LIKE wild] +or SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [LIKE wild] +or SHOW INDEX FROM tbl_name [FROM db_name] +or SHOW TABLE STATUS [FROM db_name] [LIKE wild] +or SHOW STATUS [LIKE wild] +or SHOW VARIABLES [LIKE wild] +or SHOW LOGS +or SHOW [FULL] PROCESSLIST +or SHOW GRANTS FOR user +or SHOW CREATE TABLE table_name +or SHOW MASTER STATUS +or SHOW MASTER LOGS +or SHOW SLAVE STATUS +@end example + +@code{SHOW} provides information about databases, tables, columns, or +status information about the server. If the @code{LIKE wild} part is +used, the @code{wild} string can be a string that uses the SQL @samp{%} +and @samp{_} wild-card characters. + +@menu +* SHOW DATABASE INFO:: +* SHOW TABLE STATUS:: +* SHOW STATUS:: +* SHOW VARIABLES:: +* SHOW LOGS:: +* SHOW PROCESSLIST:: +* SHOW GRANTS:: +* SHOW CREATE TABLE:: +@end menu + + +@node SHOW DATABASE INFO, SHOW TABLE STATUS, SHOW, SHOW +@subsubsection Retrieving information about Database, Tables, Columns, and Indexes + +@cindex displaying, information, @code{SHOW} + +You can use @code{db_name.tbl_name} as an alternative to the @code{tbl_name +FROM db_name} syntax. These two statements are equivalent: + +@example +mysql> SHOW INDEX FROM mytable FROM mydb; +mysql> SHOW INDEX FROM mydb.mytable; +@end example + +@code{SHOW DATABASES} lists the databases on the @strong{MySQL} server +host. You can also get this list using the @code{mysqlshow} command. + +@code{SHOW TABLES} lists the tables in a given database. You can also +get this list using the @code{mysqlshow db_name} command. + +@strong{NOTE:} If a user doesn't have any privileges for a table, the table +will not show up in the output from @code{SHOW TABLES} or @code{mysqlshow +db_name}. + +@code{SHOW OPEN TABLES} lists the tables that are currently open in +the table cache. @xref{Table cache}. The @code{Comment} field tells +how many times the table is @code{cached} and @code{in_use}. + +@code{SHOW COLUMNS} lists the columns in a given table. If you specify +the @code{FULL} option, you will also get the privileges you have for +each column. If the column types are different than you expect them to +be based on a @code{CREATE TABLE} statement, note that @strong{MySQL} +sometimes changes column types. @xref{Silent column changes}. + +The @code{DESCRIBE} statement provides information similar to +@code{SHOW COLUMNS}. +@xref{DESCRIBE, , @code{DESCRIBE}}. + +@code{SHOW FIELDS} is a synonym for @code{SHOW COLUMNS}, and +@code{SHOW KEYS} is a synonym for @code{SHOW INDEX}. You can also +list a table's columns or indexes with @code{mysqlshow db_name tbl_name} +or @code{mysqlshow -k db_name tbl_name}. + +@code{SHOW INDEX} returns the index information in a format that closely +resembles the @code{SQLStatistics} call in ODBC. The following columns +are returned: + +@multitable @columnfractions .35 .65 +@item @strong{Column} @tab @strong{Meaning} +@item @code{Table} @tab Name of the table. +@item @code{Non_unique} @tab 0 if the index can't contain duplicates. +@item @code{Key_name} @tab Name of the index. +@item @code{Seq_in_index} @tab Column sequence number in index, + starting with 1. +@item @code{Column_name} @tab Column name. +@item @code{Collation} @tab How the column is sorted in the index. + In @strong{MySQL}, this can have values + @samp{A} (Ascending) or @code{NULL} (Not + sorted). +@item @code{Cardinality} @tab Number of unique values in the index. + This is updated by running + @code{isamchk -a}. +@item @code{Sub_part} @tab Number of indexed characters if the + column is only partly indexed. + @code{NULL} if the entire key is indexed. +@item @code{Comment} @tab Various remarks. For now, it tells + whether index is FULLTEXT or not. +@end multitable + +Note that as the @code{Cardinality} is counted based on statistics +stored as integers, it's not necessarily accurate for small tables. + + +@node SHOW TABLE STATUS, SHOW STATUS, SHOW DATABASE INFO, SHOW +@subsubsection @code{SHOW TABLE STATUS} + +@cindex displaying, table status +@cindex tables, displaying status +@cindex status, tables + +@example +SHOW TABLE STATUS [FROM db_name] [LIKE wild] +@end example + +@code{SHOW TABLE STATUS} (new in Version 3.23) works likes @code{SHOW +STATUS}, but provides a lot of information about each table. You can +also get this list using the @code{mysqlshow --status db_name} command. +The following columns are returned: + +@multitable @columnfractions .30 .70 +@item @strong{Column} @tab @strong{Meaning} +@item @code{Name} @tab Name of the table. +@item @code{Type} @tab Type of table. @xref{Table types}. +@item @code{Row_format} @tab The row storage format (Fixed, Dynamic, or Compressed). +@item @code{Rows} @tab Number of rows. +@item @code{Avg_row_length} @tab Average row length. +@item @code{Data_length} @tab Length of the data file. +@item @code{Max_data_length} @tab Max length of the data file. +@item @code{Index_length} @tab Length of the index file. +@item @code{Data_free} @tab Number of allocated but not used bytes. +@item @code{Auto_increment} @tab Next autoincrement value. +@item @code{Create_time} @tab When the table was created. +@item @code{Update_time} @tab When the data file was last updated. +@item @code{Check_time} @tab When the table was last checked. +@item @code{Create_options} @tab Extra options used with @code{CREATE TABLE}. +@item @code{Comment} @tab The comment used when creating the table (or some information why @strong{MySQL} couldn't access the table information). +@end multitable + +@code{InnoDB} tables will report the free space in the tablespace +in the table comment. + + +@node SHOW STATUS, SHOW VARIABLES, SHOW TABLE STATUS, SHOW +@subsubsection @code{SHOW STATUS} + +@cindex @code{mysqladmin} +@code{SHOW STATUS} provides server status information +(like @code{mysqladmin extended-status}). The output resembles that shown +below, though the format and numbers probably differ: + +@example ++--------------------------+------------+ +| Variable_name | Value | ++--------------------------+------------+ +| Aborted_clients | 0 | +| Aborted_connects | 0 | +| Bytes_received | 155372598 | +| Bytes_sent | 1176560426 | +| Connections | 30023 | +| Created_tmp_disk_tables | 0 | +| Created_tmp_tables | 8340 | +| Created_tmp_files | 60 | +| Delayed_insert_threads | 0 | +| Delayed_writes | 0 | +| Delayed_errors | 0 | +| Flush_commands | 1 | +| Handler_delete | 462604 | +| Handler_read_first | 105881 | +| Handler_read_key | 27820558 | +| Handler_read_next | 390681754 | +| Handler_read_prev | 6022500 | +| Handler_read_rnd | 30546748 | +| Handler_read_rnd_next | 246216530 | +| Handler_update | 16945404 | +| Handler_write | 60356676 | +| Key_blocks_used | 14955 | +| Key_read_requests | 96854827 | +| Key_reads | 162040 | +| Key_write_requests | 7589728 | +| Key_writes | 3813196 | +| Max_used_connections | 0 | +| Not_flushed_key_blocks | 0 | +| Not_flushed_delayed_rows | 0 | +| Open_tables | 1 | +| Open_files | 2 | +| Open_streams | 0 | +| Opened_tables | 44600 | +| Questions | 2026873 | +| Select_full_join | 0 | +| Select_full_range_join | 0 | +| Select_range | 99646 | +| Select_range_check | 0 | +| Select_scan | 30802 | +| Slave_running | OFF | +| Slave_open_temp_tables | 0 | +| Slow_launch_threads | 0 | +| Slow_queries | 0 | +| Sort_merge_passes | 30 | +| Sort_range | 500 | +| Sort_rows | 30296250 | +| Sort_scan | 4650 | +| Table_locks_immediate | 1920382 | +| Table_locks_waited | 0 | +| Threads_cached | 0 | +| Threads_created | 30022 | +| Threads_connected | 1 | +| Threads_running | 1 | +| Uptime | 80380 | ++--------------------------+------------+ +@end example + +@cindex variables, status +The status variables listed above have the following meaning: + +@multitable @columnfractions .35 .65 +@item @strong{Variable} @tab @strong{Meaning} +@item @code{Aborted_clients} @tab Number of connections aborted because the client died without closing the connection properly. @xref{Communication errors}. +@item @code{Aborted_connects} @tab Number of tries to connect to the @strong{MySQL} server that failed. @xref{Communication errors}. +@item @code{Bytes_received} @tab Number of bytes received from all clients. +@item @code{Bytes_sent} @tab Number of bytes sent to all clients. +@item @code{Connections} @tab Number of connection attempts to the @strong{MySQL} server. +@item @code{Created_tmp_disk_tables} @tab Number of implicit temporary tables on disk created while executing statements. +@item @code{Created_tmp_tables} @tab Number of implicit temporary tables in memory created while executing statements. +@item @code{Created_tmp_files} @tab How many temporary files @code{mysqld} have created. +@item @code{Delayed_insert_threads} @tab Number of delayed insert handler threads in use. +@item @code{Delayed_writes} @tab Number of rows written with @code{INSERT DELAYED}. +@item @code{Delayed_errors} @tab Number of rows written with @code{INSERT DELAYED} for which some error occurred (probably @code{duplicate key}). +@item @code{Flush_commands} @tab Number of executed @code{FLUSH} commands. +@item @code{Handler_delete} @tab Number of times a row was deleted from a table. +@item @code{Handler_read_first} @tab Number of times the first entry was read from an index. +If this is high, it suggests that the server is doing a lot of full index scans, for example, +@code{SELECT col1 FROM foo}, assuming that col1 is indexed. +@item @code{Handler_read_key} @tab Number of requests to read a row based on a key. If this +is high, it is a good indication that your queries and tables are properly indexed. +@item @code{Handler_read_next} @tab Number of requests to read next row in key order. This +will be incremented if you are querying an index column with a range constraint. This also +will be incremented if you are doing an index scan. +@item @code{Handler_read_rnd} @tab Number of requests to read a row based on a fixed position. +This will be high if you are doing a lot of queries that require sorting of the result. +@item @code{Handler_read_rnd_next} @tab Number of requests to read the next row in the datafile. +This will be high if you are doing a lot of table scans. Generally this suggests that your tables +are not properly indexed or that your queries are not written to take advantage of the indexes you +have. +@item @code{Handler_update} @tab Number of requests to update a row in a table. +@item @code{Handler_write} @tab Number of requests to insert a row in a table. +@item @code{Key_blocks_used} @tab The number of used blocks in the key cache. +@item @code{Key_read_requests} @tab The number of requests to read a key block from the cache. +@item @code{Key_reads} @tab The number of physical reads of a key block from disk. +@item @code{Key_write_requests} @tab The number of requests to write a key block to the cache. +@item @code{Key_writes} @tab The number of physical writes of a key block to disk. +@item @code{Max_used_connections} @tab The maximum number of connections in use simultaneously. +@item @code{Not_flushed_key_blocks} @tab Keys blocks in the key cache that has changed but hasn't yet been flushed to disk. +@item @code{Not_flushed_delayed_rows} @tab Number of rows waiting to be written in @code{INSERT DELAY} queues. +@item @code{Open_tables} @tab Number of tables that are open. +@item @code{Open_files} @tab Number of files that are open. +@item @code{Open_streams} @tab Number of streams that are open (used mainly for logging). +@item @code{Opened_tables} @tab Number of tables that have been opened. +@item @code{Select_full_join} @tab Number of joins without keys (Should be 0). +@item @code{Select_full_range_join} @tab Number of joins where we used a range search on reference table. +@item @code{Select_range} @tab Number of joins where we used ranges on the first table. (It's normally not critical even if this is big.) +@item @code{Select_scan} @tab Number of joins where we scanned the first table. +@item @code{Select_range_check} @tab Number of joins without keys where we check for key usage after each row (Should be 0). +@item @code{Questions} @tab Number of queries sent to the server. +@item @code{Slave_open_temp_tables} @tab Number of temporary tables currently +open by the slave thread +@item @code{Slow_launch_threads} @tab Number of threads that have taken more than @code{slow_launch_time} to connect. +@item @code{Slow_queries} @tab Number of queries that have taken more than @code{long_query_time}. @xref{Slow query log}. +@item @code{Sort_merge_passes} @tab Number of merges the sort has to do. If this value is large you should consider increasing @code{sort_buffer}. +@item @code{Sort_range} @tab Number of sorts that where done with ranges. +@item @code{Sort_rows} @tab Number of sorted rows. +@item @code{Sort_scan} @tab Number of sorts that where done by scanning the table. +@item @code{Table_locks_immediate} @tab Number of times a table lock was +acquired immediately. Available after 3.23.33. +@item @code{Table_locks_waited} @tab Number of times a table lock could not +be acquired immediately and a wait was needed. If this is high, and you +have performance problems, you should first optimize your queries, and then +either split your table(s) or use replication. Available after 3.23.33. +@item @code{Threads_cached} @tab Number of threads in the thread cache. +@item @code{Threads_connected} @tab Number of currently open connections. +@item @code{Threads_created} @tab Number of threads created to handle connections. +@item @code{Threads_running} @tab Number of threads that are not sleeping. +@item @code{Uptime} @tab How many seconds the server has been up. +@end multitable + +Some comments about the above: + +@itemize @bullet +@item +If @code{Opened_tables} is big, then your @code{table_cache} +variable is probably too small. +@item +If @code{key_reads} is big, then your @code{key_cache} is probably too +small. The cache hit rate can be calculated with +@code{key_reads}/@code{key_read_requests}. +@item +If @code{Handler_read_rnd} is big, then you probably have a lot of +queries that require @strong{MySQL} to scan whole tables or you have +joins that don't use keys properly. +@item +If @code{Threads_created} is big, you may want to increase the +@code{thread_cache_size} variable. +@end itemize + + +@node SHOW VARIABLES, SHOW LOGS, SHOW STATUS, SHOW +@subsubsection @code{SHOW VARIABLES} + +@example +SHOW VARIABLES [LIKE wild] +@end example + +@code{SHOW VARIABLES} shows the values of some @strong{MySQL} system +variables. You can also get this information using the @code{mysqladmin +variables} command. If the default values are unsuitable, you can set most +of these variables using command-line options when @code{mysqld} starts up. +@xref{Command-line options}. + +The output resembles that shown below, though the format and numbers may +differ somewhat: + +@example ++-------------------------+---------------------------+ +| Variable_name | Value | ++-------------------------+---------------------------+ +| ansi_mode | OFF | +| back_log | 50 | +| basedir | /my/monty/ | +| bdb_cache_size | 16777216 | +| bdb_log_buffer_size | 32768 | +| bdb_home | /my/monty/data/ | +| bdb_max_lock | 10000 | +| bdb_logdir | | +| bdb_shared_data | OFF | +| bdb_tmpdir | /tmp/ | +| binlog_cache_size | 32768 | +| concurrent_insert | ON | +| connect_timeout | 5 | +| datadir | /my/monty/data/ | +| delay_key_write | ON | +| delayed_insert_limit | 100 | +| delayed_insert_timeout | 300 | +| delayed_queue_size | 1000 | +| flush | OFF | +| flush_time | 0 | +| have_bdb | YES | +| have_innodb | YES | +| have_raid | YES | +| have_ssl | NO | +| init_file | | +| interactive_timeout | 28800 | +| join_buffer_size | 131072 | +| key_buffer_size | 16776192 | +| language | /my/monty/share/english/ | +| large_files_support | ON | +| log | OFF | +| log_update | OFF | +| log_bin | OFF | +| log_slave_updates | OFF | +| long_query_time | 10 | +| low_priority_updates | OFF | +| lower_case_table_names | 0 | +| max_allowed_packet | 1048576 | +| max_binlog_cache_size | 4294967295 | +| max_connections | 100 | +| max_connect_errors | 10 | +| max_delayed_threads | 20 | +| max_heap_table_size | 16777216 | +| max_join_size | 4294967295 | +| max_sort_length | 1024 | +| max_tmp_tables | 32 | +| max_write_lock_count | 4294967295 | +| myisam_recover_options | DEFAULT | +| myisam_sort_buffer_size | 8388608 | +| net_buffer_length | 16384 | +| net_read_timeout | 30 | +| net_retry_count | 10 | +| net_write_timeout | 60 | +| open_files_limit | 0 | +| pid_file | /my/monty/data/donna.pid | +| port | 3306 | +| protocol_version | 10 | +| record_buffer | 131072 | +| query_buffer_size | 0 | +| safe_show_database | OFF | +| server_id | 0 | +| skip_locking | ON | +| skip_networking | OFF | +| skip_show_database | OFF | +| slow_launch_time | 2 | +| socket | /tmp/mysql.sock | +| sort_buffer | 2097116 | +| table_cache | 64 | +| table_type | MYISAM | +| thread_cache_size | 4 | +| thread_stack | 65536 | +| tmp_table_size | 1048576 | +| tmpdir | /tmp/ | +| version | 3.23.29a-gamma-debug | +| wait_timeout | 28800 | ++-------------------------+---------------------------+ +@end example + +Each option is described below. Values for buffer sizes, lengths, and stack +sizes are given in bytes. You can specify values with a suffix of @samp{K} +or @samp{M} to indicate kilobytes or megabytes. For example, @code{16M} +indicates 16 megabytes. The case of suffix letters does not matter; +@code{16M} and @code{16m} are equivalent: + +@cindex variables, values +@table @code +@item @code{ansi_mode}. +Is @code{ON} if @code{mysqld} was started with @code{--ansi}. +@xref{ANSI mode}. + +@item @code{back_log} +The number of outstanding connection requests @strong{MySQL} can have. This +comes into play when the main @strong{MySQL} thread gets @strong{VERY} +many connection requests in a very short time. It then takes some time +(although very little) for the main thread to check the connection and start +a new thread. The @code{back_log} value indicates how many requests can be +stacked during this short time before @strong{MySQL} momentarily stops +answering new requests. You need to increase this only if you expect a large +number of connections in a short period of time. + +In other words, this value is the size of the listen queue for incoming +TCP/IP connections. Your operating system has its own limit on the size +of this queue. The manual page for the Unix @code{listen(2)} system +call should have more details. Check your OS documentation for the +maximum value for this variable. Attempting to set @code{back_log} +higher than your operating system limit will be ineffective. + +@item @code{basedir} +The value of the @code{--basedir} option. + +@item @code{bdb_cache_size} +The buffer that is allocated to cache index and rows for @code{BDB} +tables. If you don't use @code{BDB} tables, you should start +@code{mysqld} with @code{--skip-bdb} to not waste memory for this +cache. + +@item @code{bdb_log_buffer_size} +The buffer that is allocated to cache index and rows for @code{BDB} +tables. If you don't use @code{BDB} tables, you should set this to 0 or +start @code{mysqld} with @code{--skip-bdb} to not waste memory for this +cache. + +@item @code{bdb_home} +The value of the @code{--bdb-home} option. + +@item @code{bdb_max_lock} +The maximum number of locks (1000 by default) you can have active on a +BDB table. You should increase this if you get errors of type @code{bdb: +Lock table is out of available locks} or @code{Got error 12 from ...} +when you have do long transactions or when @code{mysqld} has to examine +a lot of rows to calculate the query. + +@item @code{bdb_logdir} +The value of the @code{--bdb-logdir} option. + +@item @code{bdb_shared_data} +Is @code{ON} if you are using @code{--bdb-shared-data}. + +@item @code{bdb_tmpdir} +The value of the @code{--bdb-tmpdir} option. + +@item @code{binlog_cache_size}. The size of the cache to hold the SQL +statements for the binary log during a transaction. If you often use +big, multi-statement transactions you can increase this to get more +performance. @xref{COMMIT}. + +@item @code{character_set} +The default character set. + +@item @code{character_sets} +The supported character sets. + +@item @code{concurrent_inserts} +If @code{ON} (the default), @strong{MySQL} will allow you to use @code{INSERT} +on @code{MyISAM} tables at the same time as you run @code{SELECT} queries +on them. You can turn this option off by starting @code{mysqld} with @code{--safe} +or @code{--skip-new}. + +@cindex timeout +@item @code{connect_timeout} +The number of seconds the @code{mysqld} server is waiting for a connect +packet before responding with @code{Bad handshake}. + +@item @code{datadir} +The value of the @code{--datadir} option. + +@item @code{delay_key_write} +If enabled (is on by default), @strong{MySQL} will honor the +@code{delay_key_write} option @code{CREATE TABLE}. This means that the +key buffer for tables with this option will not get flushed on every +index update, but only when a table is closed. This will speed up +writes on keys a lot, but you should add automatic checking of all tables +with @code{myisamchk --fast --force} if you use this. Note that if you +start @code{mysqld} with the @code{--delay-key-write-for-all-tables} +option this means that all tables will be treated as if they were +created with the @code{delay_key_write} option. You can clear this flag +by starting @code{mysqld} with @code{--skip-new} or @code{--safe-mode}. + +@item @code{delayed_insert_limit} +After inserting @code{delayed_insert_limit} rows, the @code{INSERT +DELAYED} handler will check if there are any @code{SELECT} statements +pending. If so, it allows these to execute before continuing. + +@item @code{delayed_insert_timeout} +How long a @code{INSERT DELAYED} thread should wait for @code{INSERT} +statements before terminating. + +@item @code{delayed_queue_size} +What size queue (in rows) should be allocated for handling @code{INSERT +DELAYED}. If the queue becomes full, any client that does @code{INSERT +DELAYED} will wait until there is room in the queue again. + +@item @code{flush} +This is @code{ON} if you have started @strong{MySQL} with the @code{--flush} +option. + +@item @code{flush_time} +If this is set to a non-zero value, then every @code{flush_time} seconds all +tables will be closed (to free up resources and sync things to disk). We +only recommend this option on Win95, Win98, or on systems where you have +very little resources. + +@item @code{have_bdb} +@code{YES} if @code{mysqld} supports Berkeley DB tables. @code{DISABLED} +if @code{--skip-bdb} is used. +@item @code{have_innodb} +@code{YES} if @code{mysqld} supports InnoDB tables. @code{DISABLED} +if @code{--skip-innodb} is used. +@item @code{have_raid} +@code{YES} if @code{mysqld} supports the @code{RAID} option. +@item @code{have_ssl} +@code{YES} if @code{mysqld} supports SSL (encryption) on the client/server +protocol. + +@item @code{init_file} +The name of the file specified with the @code{--init-file} option when +you start the server. This is a file of SQL statements you want the +server to execute when it starts. + +@item @code{interactive_timeout} +The number of seconds the server waits for activity on an interactive +connection before closing it. An interactive client is defined as a +client that uses the @code{CLIENT_INTERACTIVE} option to +@code{mysql_real_connect()}. See also @code{wait_timeout}. + +@item @code{join_buffer_size} +The size of the buffer that is used for full joins (joins that do not +use indexes). The buffer is allocated one time for each full join +between two tables. Increase this value to get a faster full join when +adding indexes is not possible. (Normally the best way to get fast joins +is to add indexes.) + +@c Make texi2html support index @anchor{Index cache size}. Then change +@c some xrefs to point here +@cindex indexes, block size +@item @code{key_buffer_size} +Index blocks are buffered and are shared by all threads. +@code{key_buffer_size} is the size of the buffer used for index blocks. + +Increase this to get better index handling (for all reads and multiple +writes) to as much as you can afford; 64M on a 256M machine that mainly +runs @strong{MySQL} is quite common. If you, however, make this too big +(more than 50% of your total memory?) your system may start to page and +become REALLY slow. Remember that because @strong{MySQL} does not cache +data read, that you will have to leave some room for the OS filesystem +cache. + +You can check the performance of the key buffer by doing @code{show +status} and examine the variables @code{Key_read_requests}, +@code{Key_reads}, @code{Key_write_requests}, and @code{Key_writes}. The +@code{Key_reads/Key_read_request} ratio should normally be < 0.01. +The @code{Key_write/Key_write_requests} is usually near 1 if you are +using mostly updates/deletes but may be much smaller if you tend to +do updates that affect many at the same time or if you are +using @code{delay_key_write}. @xref{SHOW}. + +To get even more speed when writing many rows at the same time, use +@code{LOCK TABLES}. @xref{LOCK TABLES, , @code{LOCK TABLES}}. + +@item @code{language} +The language used for error messages. + +@item @code{large_file_support} +If @code{mysqld} was compiled with options for big file support. + +@item @code{locked_in_memory} +If @code{mysqld} was locked in memory with @code{--memlock} + +@item @code{log} +If logging of all queries is enabled. + +@item @code{log_update} +If the update log is enabled. + +@item @code{log_bin} +If the binary log is enabled. + +@item @code{log_slave_updates} +If the updates from the slave should be logged. + +@item @code{long_query_time} +If a query takes longer than this (in seconds), the @code{Slow_queries} counter +will be incremented. If you are using @code{--log-slow-queries}, the query +will be logged to the slow query logfile. @xref{Slow query log}. + +@item @code{lower_case_table_names} +If set to 1 table names are stored in lowercase on disk. This will enable +you to access the table names case-insensitive also on Unix. +@xref{Name case sensitivity}. + +@item @code{max_allowed_packet} +The maximum size of one packet. The message buffer is initialized to +@code{net_buffer_length} bytes, but can grow up to @code{max_allowed_packet} +bytes when needed. This value by default is small, to catch big (possibly +wrong) packets. You must increase this value if you are using big +@code{BLOB} columns. It should be as big as the biggest @code{BLOB} you want +to use. The current protocol limits @code{max_allowed_packet} to 16M. + +@item @code{max_binlog_cache_size} +If a multi-statement transaction requires more than this amount of memory, +one will get the error "Multi-statement transaction required more than +'max_binlog_cache_size' bytes of storage". + +@item @code{max_binlog_size} +Available after 3.23.33. If a write to the binary (replication) log exceeds +the given value, rotate the logs. You cannot set it to less than 1024 bytes, +or more than 1 GB. Default is 1 GB. + +@item @code{max_connections} +The number of simultaneous clients allowed. Increasing this value increases +the number of file descriptors that @code{mysqld} requires. See below for +comments on file descriptor limits. @xref{Too many connections}. + +@item @code{max_connect_errors} +If there is more than this number of interrupted connections from a host +this host will be blocked from further connections. You can unblock a host +with the command @code{FLUSH HOSTS}. + +@item @code{max_delayed_threads} +Don't start more than this number of threads to handle @code{INSERT DELAYED} +statements. If you try to insert data into a new table after all @code{INSERT +DELAYED} threads are in use, the row will be inserted as if the +@code{DELAYED} attribute wasn't specified. + +@item @code{max_heap_table_size} +Don't allow creation of heap tables bigger than this. + +@item @code{max_join_size} +Joins that are probably going to read more than @code{max_join_size} +records return an error. Set this value if your users tend to perform joins +that lack a @code{WHERE} clause, that take a long time, and that return +millions of rows. + +@item @code{max_sort_length} +The number of bytes to use when sorting @code{BLOB} or @code{TEXT} +values (only the first @code{max_sort_length} bytes of each value +are used; the rest are ignored). + +@item @code{max_user_connections} +The maximum number of active connections for a single user (0 = no limit). + +@item @code{max_tmp_tables} +(This option doesn't yet do anything.) +Maximum number of temporary tables a client can keep open at the same time. + +@item @code{max_write_lock_count} +After this many write locks, allow some read locks to run in between. + +@item @code{myisam_recover_options} +The value of the @code{--myisam-recover} option. + +@item @code{myisam_sort_buffer_size} +The buffer that is allocated when sorting the index when doing a +@code{REPAIR} or when creating indexes with @code{CREATE INDEX} or +@code{ALTER TABLE}. + +@item @code{myisam_max_extra_sort_file_size}. +If the creating of the temporary file for fast index creation would be +this much bigger than using the key cache, then prefer the key cache +method. This is mainly used to force long character keys in large +tables to use the slower key cache method to create the index. +@strong{NOTE} that this parameter is given in megabytes! + +@item @code{myisam_max_sort_file_size} +The maximum size of the temporary file @strong{MySQL} is allowed to use +while recreating the index (during @code{REPAIR}, @code{ALTER TABLE} +or @code{LOAD DATA INFILE}. If the file size would be bigger than this, +the index will be created through the key cache (which is slower). +@strong{NOTE} that this parameter is given in megabytes! + +@item @code{net_buffer_length} +The communication buffer is reset to this size between queries. This +should not normally be changed, but if you have very little memory, you +can set it to the expected size of a query. (That is, the expected length of +SQL statements sent by clients. If statements exceed this length, the buffer +is automatically enlarged, up to @code{max_allowed_packet} bytes.) + +@item @code{net_read_timeout} +Number of seconds to wait for more data from a connection before aborting +the read. Note that when we don't expect data from a connection, the timeout +is defined by @code{write_timeout}. See also @code{slave_read_timeout}. + +@item @code{net_retry_count} +If a read on a communication port is interrupted, retry this many times +before giving up. This value should be quite high on @code{FreeBSD} as +internal interrupts are sent to all threads. + +@item @code{net_write_timeout} +Number of seconds to wait for a block to be written to a connection before +aborting the write. + +@item @code{open_files_limit} +If this is not 0, then @code{mysqld} will use this value to reserve file +descriptors to use with @code{setrlimit()}. If this value is 0 then +@code{mysqld} will reserve @code{max_connections*5} or +@code{max_connections + table_cache*2} (whichever is larger) number of +files. You should try increasing this if @code{mysqld} gives you the +error 'Too many open files'. + +@item @code{pid_file} +The value of the @code{--pid-file} option. + +@item @code{port} +The value of the @code{--port} option. + +@item @code{protocol_version} +The protocol version used by the @strong{MySQL} server. + +@item @code{record_buffer} +Each thread that does a sequential scan allocates a buffer of this +size for each table it scans. If you do many sequential scans, you may +want to increase this value. + +@item @code{query_buffer_size} +The initial allocation of the query buffer. If most of your queries are +long (like when inserting blobs), you should increase this! + +@item @code{safe_show_databases} +Don't show databases for which the user doesn't have any database or +table privileges. This can improve security if you're concerned about +people being able to see what databases other users have. See also +@code{skip_show_databases}. + +@item @code{server_id} +The value of the @code{--server-id} option. + +@item @code{skip_locking} +Is OFF if @code{mysqld} uses external locking. + +@item @code{skip_networking} +Is ON if we only allow local (socket) connections. + +@item @code{skip_show_databases} +This prevents people from doing @code{SHOW DATABASES} if they don't have +the @code{PROCESS_PRIV} privilege. This can improve security if you're +concerned about people being able to see what databases other users +have. See also @code{safe_show_databases}. + +@item @code{slave_read_timeout} +Number of seconds to wait for more data from a master/slave connection +before aborting the read. + +@item @code{slow_launch_time} +If creating the thread takes longer than this value (in seconds), the +@code{Slow_launch_threads} counter will be incremented. + +@item @code{socket} +The Unix socket used by the server. + +@item @code{sort_buffer} +Each thread that needs to do a sort allocates a buffer of this +size. Increase this value for faster @code{ORDER BY} or @code{GROUP BY} +operations. +@xref{Temporary files}. + +@item @code{table_cache} +The number of open tables for all threads. Increasing this value +increases the number of file descriptors that @code{mysqld} requires. +@strong{MySQL} needs two file descriptors for each unique open table. +See below for comments on file descriptor limits. You can check if you +need to increase the table cache by checking the @code{Opened_tables} +variable. @xref{SHOW}. If this variable is big and you don't do +@code{FLUSH TABLES} a lot (which just forces all tables to be closed and +reopenend), then you should increase the value of this variable. + +Make sure that your operating system can handle the number of open file +descriptors implied by the @code{table_cache} setting. If @code{table_cache} +is set too high, @strong{MySQL} may run out of file descriptors and refuse +connections, fail to perform queries, and be very unreliable. + +For information about how the table cache works, see @ref{Table cache}. + +@item @code{table_type} +The default table type + +@item @code{thread_cache_size} +How many threads we should keep in a cache for reuse. When a +client disconnects, the client's threads are put in the cache if there +aren't more than @code{thread_cache_size} threads from before. All new +threads are first taken from the cache, and only when the cache is empty +is a new thread created. This variable can be increased to improve +performance if you have a lot of new connections. (Normally this doesn't +give a notable performance improvement if you have a good +thread implementation.) By examing the difference between +the @code{Connections} and @code{Threads_created} you can see how efficient +the current thread cache is for you. + +@item @code{thread_concurrency} +On Solaris, @code{mysqld} will call @code{thr_setconcurrency()} with +this value. @code{thr_setconcurrency()} permits the application to give +the threads system a hint for the desired number of threads that should +be run at the same time. + +@item @code{thread_stack} +The stack size for each thread. Many of the limits detected by the +@code{crash-me} test are dependent on this value. The default is +large enough for normal operation. @xref{Benchmarks}. + +@item @code{timezone} +The timezone for the server. + +@item @code{tmp_table_size} +If an in-memory temporary table exceeds this size, @strong{MySQL} +will automatically convert it to an on-disk @code{MyISAM} table. +Increase the value of @code{tmp_table_size} if you do many advanced +@code{GROUP BY} queries and you have lots of memory. + +@item @code{tmpdir} +The directory used for temporary files and temporary tables. + +@item @code{version} +The version number for the server. + +@item @code{wait_timeout} +The number of seconds the server waits for activity on a connection before +closing it. See also @code{interactive_timeout}. +@end table + +The manual section that describes tuning @strong{MySQL} contains some +information of how to tune the above variables. @xref{Server parameters}. + + +@node SHOW LOGS, SHOW PROCESSLIST, SHOW VARIABLES, SHOW +@subsubsection @code{SHOW LOGS} + +@code{SHOW LOGS} shows you status information about existing log +files. It currently only displays information about Berkeley DB log +files. + +@itemize @bullet +@item @code{File} shows the full path to the log file +@item @code{Type} shows the type of the log file (@code{BDB} for Berkeley +DB log files) +@item @code{Status} shows the status of the log file (@code{FREE} if the +file can be removed, or @code{IN USE} if the file is needed by the transaction +subsystem) +@end itemize + + +@node SHOW PROCESSLIST, SHOW GRANTS, SHOW LOGS, SHOW +@subsubsection @code{SHOW PROCESSLIST} + +@findex threads +@findex PROCESSLIST + +@cindex threads, display +@cindex processes, display + +@code{SHOW PROCESSLIST} shows you which threads are running. You can +also get this information using the @code{mysqladmin processlist} +command. If you have the @strong{process} privilege, you can see all +threads. Otherwise, you can see only your own threads. @xref{KILL, , +@code{KILL}}. If you don't use the @code{FULL} option, then only +the first 100 characters of each query will be shown. + +This command is very useful if you get the 'too many connections' error +message and want to find out what's going on. @strong{MySQL} reserves +one extra connection for a client with the @code{Process_priv} privilege +to ensure that you should always be able to login and check the system +(assuming you are not giving this privilege to all your users). + + +@node SHOW GRANTS, SHOW CREATE TABLE, SHOW PROCESSLIST, SHOW +@subsubsection @code{SHOW GRANTS} + +@cindex privileges, display + +@code{SHOW GRANTS FOR user} lists the grant commands that must be issued to +duplicate the grants for a user. + +@example +mysql> SHOW GRANTS FOR root@@localhost; ++---------------------------------------------------------------------+ +| Grants for root@@localhost | ++---------------------------------------------------------------------+ +| GRANT ALL PRIVILEGES ON *.* TO 'root'@@'localhost' WITH GRANT OPTION | ++---------------------------------------------------------------------+ +@end example + + +@node SHOW CREATE TABLE, , SHOW GRANTS, SHOW +@subsubsection @code{SHOW CREATE TABLE} + +Shows a @code{CREATE TABLE} statement that will create the given table: + +@example +mysql> show create table t\G +*************************** 1. row *************************** + Table: t +Create Table: CREATE TABLE t ( + id int(11) default NULL auto_increment, + s char(60) default NULL, + PRIMARY KEY (id) +) TYPE=MyISAM + +@end example + +@code{SHOW CREATE TABLE} will quote table and column names according to +@code{SQL_QUOTE_SHOW_CREATE} option. +@ref{SET OPTION, , @code{SET OPTION SQL_QUOTE_SHOW_CREATE}}. + + +@node Localization, Server-Side Scripts, KILL, MySQL Database Administration +@section MySQL Localization and International Usage + +@menu +* Character sets:: +* Languages:: +* Adding character set:: +* Character arrays:: +* String collating:: +* Multi-byte characters:: +@end menu + + +@node Character sets, Languages, Localization, Localization +@subsection The Character Set Used for Data and Sorting + +@cindex character sets +@cindex data, character sets +@cindex sorting, character sets + +By default, @strong{MySQL} uses the ISO-8859-1 (Latin1) character set +with sorting according to Swedish/Finnish. This is the character set suitable +in the USA and western Europe. + +All standard @strong{MySQL} binaries are compiled with +@code{--with-extra-charsets=complex}. This will add code to all +standard programs to be able to handle @code{latin1} and all multi-byte +character sets within the binary. Other character sets will be +loaded from a character-set definition file when needed. + +The character set determines what characters are allowed in names and how +things are sorted by the @code{ORDER BY} and @code{GROUP BY} clauses of +the @code{SELECT} statement. + +You can change the character set with the @code{--default-character-set} +option when you start the server. The character sets available depend +on the @code{--with-charset=charset} and @code{--with-extra-charset= +list-of-charset | complex | all} options to @code{configure}, and the +character set configuration files listed in +@file{SHAREDIR/charsets/Index}. @xref{configure options}. + +If you change the character set when running @strong{MySQL} (which may +also change the sort order), you must run myisamchk -r -q on all +tables. Otherwise your indexes may not be ordered correctly. + +When a client connects to a @strong{MySQL} server, the server sends the +default character set in use to the client. The client will switch to +use this character set for this connection. + +One should use @code{mysql_real_escape_string()} when escaping strings +for a SQL query. @code{mysql_real_escape_string()} is identical to the +old @code{mysql_escape_string()} function, except that it takes the MYSQL +connection handle as the first parameter. + +If the client is compiled with different paths than where the server is +installed and the user who configured @strong{MySQL} didn't included all +character sets in the @strong{MySQL} binary, one must specify for +the client where it can find the additional character sets it will need +if the server runs with a different character set than the client. + +One can specify this by putting in a @strong{MySQL} option file: + +@example +[client] +character-sets-dir=/usr/local/mysql/share/mysql/charsets +@end example + +where the path points to where the dynamic @strong{MySQL} character sets +are stored. + +One can force the client to use specific character set by specifying: + +@example +[client] +default-character-set=character-set-name +@end example + +but normally this is never needed. + + +@node Languages, Adding character set, Character sets, Localization +@subsection Non-English Error Messages + +@cindex error messages, languages +@cindex messages, languages +@cindex files, error messages +@cindex language support + +@code{mysqld} can issue error messages in the following languages: +Czech, Danish, Dutch, English (the default), Estonian, French, German, Greek, +Hungarian, Italian, Japanese, Korean, Norwegian, Norwegian-ny, Polish, +Portuguese, Romanian, Russian, Slovak, Spanish, and Swedish. + +To start @code{mysqld} with a particular language, use either the +@code{--language=lang} or @code{-L lang} options. For example: + +@example +shell> mysqld --language=swedish +@end example + +or: + +@example +shell> mysqld --language=/usr/local/share/swedish +@end example + +Note that all language names are specified in lowercase. + +The language files are located (by default) in +@file{@var{mysql_base_dir}/share/@var{LANGUAGE}/}. + +To update the error message file, you should edit the @file{errmsg.txt} file +and execute the following command to generate the @file{errmsg.sys} file: + +@example +shell> comp_err errmsg.txt errmsg.sys +@end example + +If you upgrade to a newer version of @strong{MySQL}, remember to repeat +your changes with the new @file{errmsg.txt} file. + + +@node Adding character set, Character arrays, Languages, Localization +@subsection Adding a New Character Set + +@cindex character sets, adding +@cindex adding, character sets + +To add another character set to @strong{MySQL}, use the following procedure. + +Decide if the set is simple or complex. If the character set +does not need to use special string collating routines for +sorting and does not need multi-byte character support, it is +simple. If it needs either of those features, it is complex. + +For example, @code{latin1} and @code{danish} are simple charactersets while +@code{big5} or @code{czech} are complex character sets. + +In the following section, we have assumed that you name your character +set @code{MYSET}. + +For a simple character set do the following: + +@enumerate +@item +Add MYSET to the end of the @file{sql/share/charsets/Index} file +Assign an unique number to it. + +@item +Create the file @file{sql/share/charsets/MYSET.conf}. +(You can use @file{sql/share/charsets/latin1.conf} as a base for this). + +The syntax for the file very simple: + +@itemize @bullet +@item +Comments start with a '#' character and proceed to the end of the line. +@item +Words are separated by arbitrary amounts of whitespace. +@item +When defining the character set, every word must be a number in hexadecimal +format +@item +The @code{ctype} array takes up the first 257 words. The +@code{to_lower}, @code{to_upper} and @code{sort_order} arrays take up +256 words each after that. +@end itemize + +@xref{Character arrays}. + +@item +Add the character set name to the @code{CHARSETS_AVAILABLE} and +@code{COMPILED_CHARSETS} lists in @code{configure.in}. + +@item +Reconfigure, recompile, and test. + +@end enumerate + +For a complex character set do the following: + +@enumerate +@item +Create the file @file{strings/ctype-MYSET.c} in the @strong{MySQL} source +distribution. + +@item +Add MYSET to the end of the @file{sql/share/charsets/Index} file. +Assign an unique number to it. + +@item +Look at one of the existing @file{ctype-*.c} files to see what needs to +be defined, for example @file{strings/ctype-big5.c}. Note that the +arrays in your file must have names like @code{ctype_MYSET}, +@code{to_lower_MYSET}, and so on. This corresponds to the arrays +in the simple character set. @xref{Character arrays}. For a complex +character set + +@item +Near the top of the file, place a special comment like this: + +@example +/* + * This comment is parsed by configure to create ctype.c, + * so don't change it unless you know what you are doing. + * + * .configure. number_MYSET=MYNUMBER + * .configure. strxfrm_multiply_MYSET=N + * .configure. mbmaxlen_MYSET=N + */ +@end example + +The @code{configure} program uses this comment to include +the character set into the @strong{MySQL} library automatically. + +The strxfrm_multiply and mbmaxlen lines will be explained in +the following sections. Only include them if you the string +collating functions or the multi-byte character set functions, +respectively. + +@item +You should then create some of the following functions: + +@itemize @bullet +@item @code{my_strncoll_MYSET()} +@item @code{my_strcoll_MYSET()} +@item @code{my_strxfrm_MYSET()} +@item @code{my_like_range_MYSET()} +@end itemize + +@xref{String collating}. + +@item +Add the character set name to the @code{CHARSETS_AVAILABLE} and +@code{COMPILED_CHARSETS} lists in @code{configure.in}. + +@item +Reconfigure, recompile, and test. +@end enumerate + +The file @file{sql/share/charsets/README} includes some more instructions. + +If you want to have the character set included in the @strong{MySQL} +distribution, mail a patch to @email{internals@@lists.mysql.com}. + + +@node Character arrays, String collating, Adding character set, Localization +@subsection The character definition arrays + +@code{to_lower[]} and @code{to_upper[]} are simple arrays that hold the +lowercase and uppercase characters corresponding to each member of the +character set. For example: + +@example +to_lower['A'] should contain 'a' +to_upper['a'] should contain 'A' +@end example + +@code{sort_order[]} is a map indicating how characters should be ordered for +comparison and sorting purposes. For many character sets, this is the same as +@code{to_upper[]} (which means sorting will be case insensitive). +@strong{MySQL} will sort characters based on the value of +@code{sort_order[character]}. For more complicated sorting rules, see +the discussion of string collating below. @xref{String collating}. + +@code{ctype[]} is an array of bit values, with one element for one character. +(Note that @code{to_lower[]}, @code{to_upper[]}, and @code{sort_order[]} +are indexed by character value, but @code{ctype[]} is indexed by character +value + 1. This is an old legacy to be able to handle EOF.) + +You can find the following bitmask definitions in @file{m_ctype.h}: + +@example +#define _U 01 /* Uppercase */ +#define _L 02 /* Lowercase */ +#define _N 04 /* Numeral (digit) */ +#define _S 010 /* Spacing character */ +#define _P 020 /* Punctuation */ +#define _C 040 /* Control character */ +#define _B 0100 /* Blank */ +#define _X 0200 /* heXadecimal digit */ +@end example + +The @code{ctype[]} entry for each character should be the union of the +applicable bitmask values that describe the character. For example, +@code{'A'} is an uppercase character (@code{_U}) as well as a +hexadecimal digit (@code{_X}), so @code{ctype['A'+1]} should contain the +value: + +@example +_U + _X = 01 + 0200 = 0201 +@end example + + +@node String collating, Multi-byte characters, Character arrays, Localization +@subsection String Collating Support + +@cindex collating, strings +@cindex string collating + +If the sorting rules for your language are too complex to be handled +with the simple @code{sort_order[]} table, you need to use the string +collating functions. + +Right now the best documentation on this is the character sets that are +already implemented. Look at the big5, czech, gbk, sjis, and tis160 +character sets for examples. + +You must specify the @code{strxfrm_multiply_MYSET=N} value in the +special comment at the top of the file. @code{N} should be set to +the maximum ratio the strings may grow during @code{my_strxfrm_MYSET} (it +must be a positive integer). + + +@node Multi-byte characters, , String collating, Localization +@subsection Multi-byte Character Support + +@cindex characters, multi-byte +@cindex multi-byte characters + +If your want to add support for a new character set that includes +multi-byte characters, you need to use the multi-byte character +functions. + +Right now the best documentation on this is the character sets that are +already implemented. Look at the euc_kr, gb2312, gbk, sjis and ujis +character sets for examples. These are implemented in the +@code{ctype-'charset'.c} files in the @file{strings} directory. + +You must specify the @code{mbmaxlen_MYSET=N} value in the special +comment at the top of the source file. @code{N} should be set to the +size in bytes of the largest character in the set. + + +@node Server-Side Scripts, Client-Side Scripts, Localization, MySQL Database Administration +@section MySQL Server-Side Scripts and Utilities + +@menu +* Server-Side Overview:: +* safe_mysqld:: +* mysqld_multi:: +* myisampack:: +* mysqld-max:: +@end menu + + +@node Server-Side Overview, safe_mysqld, Server-Side Scripts, Server-Side Scripts +@subsection Overview of the Server-Side Scripts and Utilities + @cindex environment variables -@tindex .my.cnf file -Remember that client programs will use connection parameters specified -in configuration files or environment variables. @xref{Environment -variables}. If a client seems to be sending the wrong default -connection parameters when you don't specify them on the command line, -check your environment and the @file{.my.cnf} file in your home -directory. You might also check the system-wide @strong{MySQL} -configuration files, though it is far less likely that client connection -parameters will be specified there. @xref{Option files}. If you get -@code{Access denied} when you run a client without any options, make -sure you haven't specified an old password in any of your option files! +@cindex programs, list of + +All @strong{MySQL} clients that communicate with the server using the +@code{mysqlclient} library use the following environment variables: + +@tindex MYSQL_UNIX_PORT environment variable +@tindex Environment variable, MYSQL_UNIX_PORT +@tindex MYSQL_TCP_PORT environment variable +@tindex Environment variable, MYSQL_TCP_PORT +@tindex MYSQL_PWD environment variable +@tindex Environment variable, MYSQL_PWD +@tindex MYSQL_DEBUG environment variable +@tindex Environment variable, MYSQL_DEBUG +@multitable @columnfractions .25 .75 +@item @strong{Name} @tab @strong{Description} +@item @code{MYSQL_UNIX_PORT} @tab The default socket; used for connections to @code{localhost} +@item @code{MYSQL_TCP_PORT} @tab The default TCP/IP port +@item @code{MYSQL_PWD} @tab The default password +@item @code{MYSQL_DEBUG} @tab Debug-trace options when debugging +@item @code{TMPDIR} @tab The directory where temporary tables/files are created +@end multitable + +Use of @code{MYSQL_PWD} is insecure. +@xref{Connecting}. + +@tindex MYSQL_HISTFILE environment variable +@tindex Environment variable, MYSQL_HISTFILE +@tindex HOME environment variable +@tindex Environment variable, HOME +@cindex history file +@cindex command line history +@tindex .mysql_history file +The @file{mysql} client uses the file named in the @code{MYSQL_HISTFILE} +environment variable to save the command-line history. The default value for +the history file is @file{$HOME/.mysql_history}, where @code{$HOME} is the +value of the @code{HOME} environment variable. @xref{Environment variables}. + +All @strong{MySQL} programs take many different options. However, every +@strong{MySQL} program provides a @code{--help} option that you can use +to get a full description of the program's different options. For example, try +@code{mysql --help}. + +You can override default options for all standard client programs with an +option file. @ref{Option files}. + +The list below briefly describes the @strong{MySQL} programs: + +@table @code + +@cindex @code{myisamchk} +@item myisamchk +Utility to describe, check, optimize, and repair @strong{MySQL} tables. +Because @code{myisamchk} has many functions, it is described in its own +chapter. @xref{Maintenance}. + +@cindex @code{make_binary_distribution} +@item make_binary_distribution +Makes a binary release of a compiled @strong{MySQL}. This could be sent +by FTP to @file{/pub/mysql/Incoming} on @code{support.mysql.com} for the +convenience of other @strong{MySQL} users. + +@cindex @code{msql2mysql} +@item msql2mysql +A shell script that converts @code{mSQL} programs to @strong{MySQL}. It doesn't +handle all cases, but it gives a good start when converting. + +@cindex @code{mysqlaccess} +@item mysqlaccess +A script that checks the access privileges for a host, user, and database +combination. + +@cindex @code{mysqladmin} +@item mysqladmin +Utility for performing administrative operations, such as creating or +dropping databases, reloading the grant tables, flushing tables to disk, and +reopening log files. @code{mysqladmin} can also be used to retrieve version, +process, and status information from the server. +@xref{mysqladmin, , @code{mysqladmin}}. + +@cindex @code{mysqlbug} +@item mysqlbug +The @strong{MySQL} bug report script. This script should always be used when +filing a bug report to the @strong{MySQL} list. + +@cindex @code{mysqld} +@item mysqld +The SQL daemon. This should always be running. + +@cindex @code{mysqldump} +@item mysqldump +Dumps a @strong{MySQL} database into a file as SQL statements or +as tab-separated text files. Enhanced freeware originally by Igor Romanenko. +@xref{mysqldump, , @code{mysqldump}}. + +@cindex @code{mysqlimport} +@item mysqlimport +Imports text files into their respective tables using @code{LOAD DATA +INFILE}. @xref{mysqlimport, , @code{mysqlimport}}. + +@cindex @code{mysqlshow} +@item mysqlshow +Displays information about databases, tables, columns, and indexes. + +@cindex @code{mysql_install_db} +@item mysql_install_db +Creates the @strong{MySQL} grant tables with default privileges. This is +usually executed only once, when first installing @strong{MySQL} +on a system. + +@cindex @code{replace} +@item replace +A utility program that is used by @code{msql2mysql}, but that has more +general applicability as well. @code{replace} changes strings in place in +files or on the standard input. Uses a finite state machine to match longer +strings first. Can be used to swap strings. For example, this command +swaps @code{a} and @code{b} in the given files: + +@example +shell> replace a b b a -- file1 file2 ... +@end example +@end table + + +@node safe_mysqld, mysqld_multi, Server-Side Overview, Server-Side Scripts +@subsection safe_mysqld, the wrapper around mysqld + +@cindex tools, safe_mysqld +@cindex scripts +@cindex @code{safe_mysqld} + +@code{safe_mysqld} is the recommended way to start a @code{mysqld} +daemon on Unix. @code{safe_mysqld} adds some safety features such as +restarting the server when an error occurs and logging run-time +information to a log file. + +If you don't use @code{--mysqld=#} or @code{--mysqld-version=#} +@code{safe_mysqld} will use an executable named @code{mysqld-max} if it +exists. If not, @code{safe_mysqld} will start @code{mysqld}. +This makes it very easy to test to use @code{mysqld-max} instead of +@code{mysqld}; Just copy @code{mysqld-max} to where you have +@code{mysqld} and it will be used. + +Normally one should never edit the @code{safe_mysqld} script, but +instead put the options to @code{safe_mysqld} in the +@code{[safe_mysqld]} section in the @code{my.cnf} +file. @code{safe_mysqld} will read all options from the @code{[mysqld]}, +@code{[server]} and @code{[safe_mysqld]} sections from the option files. @xref{Option files}. +Note that all options on the command line to @code{safe_mysqld} are passed +to @code{mysqld}. If you wants to use any options in @code{safe_mysqld} that +@code{mysqld} doesn't support, you must specify these in the option file. + +Most of the options to @code{safe_mysqld} are the same as the options to +@code{mysqld}. @xref{Command-line options}. + +@code{safe_mysqld} supports the following options: + +@table @code +@item --basedir=path +@item --core-file-size=# +Size of the core file @code{mysqld} should be able to create. Passed to @code{ulimit -c}. +@item --datadir=path +@item --defaults-extra-file=path +@item --defaults-file=path +@item --err-log=path +@item --ledir=path +Path to @code{mysqld} +@item --log=path +@item --mysqld=mysqld-version +Name of the @code{mysqld} version in the @code{ledir} directory you want to start. +@item --mysqld-version=version +Similar to @code{--mysqld=} but here you only give the suffix for @code{mysqld}. +For example if you use @code{--mysqld-version=max}, @code{safe_mysqld} will +start the @code{ledir/mysqld-max} version. If the argument to +@code{--mysqld-version} is empty, @code{ledir/mysqld} will be used. +@item --no-defaults +@item --open-files-limit=# +Number of files @code{mysqld} should be able to open. Passed to @code{ulimit -n}. Note that you need to start @code{safe_mysqld} as root for this to work properly! +@item --pid-file=path +@item --port=# +@item --socket=path +@item --timezone=# +Set the timezone (the @code{TZ}) variable to the value of this parameter. +@item --user=# +@end table + +The @code{safe_mysqld} script is written so that it normally is able to start +a server that was installed from either a source or a binary version of +@strong{MySQL}, even if these install the server in slightly different +locations. @code{safe_mysqld} expects one of these conditions to be true: + +@itemize @bullet @item -If you make changes to the grant tables directly (using an @code{INSERT} or -@code{UPDATE} statement) and your changes seem to be ignored, remember -that you must issue a @code{FLUSH PRIVILEGES} statement or execute a -@code{mysqladmin flush-privileges} command to cause the server to re-read -the privilege tables. Otherwise your changes have no effect until the -next time the server is restarted. Remember that after you set the -@code{root} password with an @code{UPDATE} command, you won't need to -specify it until after you flush the privileges, because the server -won't know you've changed the password yet! +The server and databases can be found relative to the directory from which +@code{safe_mysqld} is invoked. @code{safe_mysqld} looks under its working +directory for @file{bin} and @file{data} directories (for binary +distributions) or for @file{libexec} and @file{var} directories (for source +distributions). This condition should be met if you execute +@code{safe_mysqld} from your @strong{MySQL} installation directory (for +example, @file{/usr/local/mysql} for a binary distribution). @item -If you have access problems with a Perl, PHP, Python, or ODBC program, try to -connect to the server with @code{mysql -u user_name db_name} or @code{mysql --u user_name -pyour_pass db_name}. If you are able to connect using the -@code{mysql} client, there is a problem with your program and not with the -access privileges. (Note that there is no space between @code{-p} and the -password; you can also use the @code{--password=your_pass} syntax to specify -the password. If you use the @code{-p} option alone, @strong{MySQL} will -prompt you for the password.) - -@item -For testing, start the @code{mysqld} daemon with the -@code{--skip-grant-tables} option. Then you can change the @strong{MySQL} -grant tables and use the @code{mysqlaccess} script to check whether or not -your modifications have the desired effect. When you are satisfied with your -changes, execute @code{mysqladmin flush-privileges} to tell the @code{mysqld} -server to start using the new grant tables. @strong{Note:} Reloading the -grant tables overrides the @code{--skip-grant-tables} option. This allows -you to tell the server to begin using the grant tables again without bringing -it down and restarting it. - -@item -If everything else fails, start the @code{mysqld} daemon with a debugging -option (for example, @code{--debug=d,general,query}). This will print host and -user information about attempted connections, as well as information about -each command issued. @xref{Making trace files}. - -@item -If you have any other problems with the @strong{MySQL} grant tables and -feel you must post the problem to the mailing list, always provide a -dump of the @strong{MySQL} grant tables. You can dump the tables with -the @code{mysqldump mysql} command. As always, post your problem using -the @code{mysqlbug} script. @xref{Bug reports}. In some cases you may need -to restart @code{mysqld} with @code{--skip-grant-tables} to run -@code{mysqldump}. +If the server and databases cannot be found relative to the working directory, +@code{safe_mysqld} attempts to locate them by absolute pathnames. Typical +locations are @file{/usr/local/libexec} and @file{/usr/local/var}. +The actual locations are determined when the distribution was built from which +@code{safe_mysqld} comes. They should be correct if +@strong{MySQL} was installed in a standard location. @end itemize -@node Reference, Table types, Privilege system, Top +Because @code{safe_mysqld} will try to find the server and databases relative +to its own working directory, you can install a binary distribution of +@strong{MySQL} anywhere, as long as you start @code{safe_mysqld} from the +@strong{MySQL} installation directory: + +@example +shell> cd mysql_installation_directory +shell> bin/safe_mysqld & +@end example + +If @code{safe_mysqld} fails, even when invoked from the @strong{MySQL} +installation directory, you can modify it to use the path to @code{mysqld} +and the pathname options that are correct for your system. Note that if you +upgrade @strong{MySQL} in the future, your modified version of +@code{safe_mysqld} will be overwritten, so you should make a copy of your +edited version that you can reinstall. + + +@node mysqld_multi, myisampack, safe_mysqld, Server-Side Scripts +@subsection mysqld_multi, program for managing multiple @strong{MySQL} servers + +@cindex tools, mysqld_multi +@cindex scripts +@cindex multi mysqld +@cindex @code{mysqld_multi} + +@code{mysqld_multi} is meant for managing several @code{mysqld} +processes running in different UNIX sockets and TCP/IP ports. + +The program will search for group(s) named [mysqld#] from my.cnf (or the +given --config-file=...), where # can be any positive number starting +from 1. These groups should be the same as the usual @code{[mysqld]} +group (e.g. options to mysqld, see @strong{MySQL} manual for detailed +information about this group), but with those port, socket etc. options +that are wanted for each separate @code{mysqld} processes. The number in +the group name has another function; it can be used for starting, +stopping, or reporting some specific @code{mysqld} servers with this +program. See the usage and options below for more information. + +@example +Usage: mysqld_multi [OPTIONS] @{start|stop|report@} [GNR,GNR,GNR...] +or mysqld_multi [OPTIONS] @{start|stop|report@} [GNR-GNR,GNR,GNR-GNR,...] +@end example + +The GNR above 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, of which the latter +means that all the GNRs between GNR1-GNR2 will be affected. Without +GNR argument all the found groups will be either started, stopped, or +reported. Note that you must not have any white spaces in the GNR +list. Anything after a white space is ignored. + +@code{mysqld_multi} supports the following options: + +@table @code +@cindex config-file option +@item --config-file=... +Alternative config file. NOTE: This will not affect this program's own +options (group @code{[mysqld_multi]}), but only groups +[mysqld#]. Without this option everything will be searched from the +ordinary my.cnf file. +@cindex example option +@item --example +Give an example of a config file. +@cindex help option +@item --help +Print this help and exit. +@cindex log option +@item --log=... +Log file. Full path to and the name for the log file. NOTE: If the file +exists, everything will be appended. +@cindex mysqladmin option +@item --mysqladmin=... +@code{mysqladmin} binary to be used for a server shutdown. +@cindex mysqld option +@item --mysqld=... +@code{mysqld} binary to be used. Note that you can give +@code{safe_mysqld} to this option also. The options are passed to +@code{mysqld}. Just make sure you have @code{mysqld} in your environment +variable @code{PATH} or fix @code{safe_mysqld}. +@cindex no-log option +@item --no-log +Print to stdout instead of the log file. By default the log file is +turned on. +@cindex password option +@item --password=... +Password for user for @code{mysqladmin}. +@cindex tcp-ip option +@item --tcp-ip +Connect to the @strong{MySQL} 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. +@cindex user option +@item --user=... +@strong{MySQL} user for @code{mysqladmin}. +@cindex version option +@item --version +Print the version number and exit. +@end table + +Some notes about @code{mysqld_multi}: + +@itemize @bullet +@item +Make sure that the @strong{MySQL} user, who is stopping the +@code{mysqld} services (e.g using the @code{mysqladmin}) have the same +password and username for all the data directories accessed (to the +'mysql' database) And make sure that the user has the 'Shutdown_priv' +privilege! If you have many data- directories and many different 'mysql' +databases with different passwords for the @strong{MySQL} 'root' user, +you may want to create a common 'multi_admin' user for each using the +same password (see below). Example how to do it: +@example +shell> mysql -u root -S /tmp/mysql.sock -proot_password -e +"GRANT SHUTDOWN ON *.* TO multi_admin@@localhost IDENTIFIED BY 'multipass'" +@xref{Privileges}. +@end example +You will have to do the above for each @code{mysqld} running in each +data directory, that you have (just change the socket, -S=...) +@item +@code{pid-file} is very important, if you are using @code{safe_mysqld} +to start @code{mysqld} (e.g. --mysqld=safe_mysqld) Every @code{mysqld} +should have its own @code{pid-file}. The advantage using +@code{safe_mysqld} instead of @code{mysqld} directly here is, that +@code{safe_mysqld} 'guards' every @code{mysqld} process and will restart +it, if a @code{mysqld} process fails due to signal kill -9, or +similar. (Like segmentation fault, which @strong{MySQL} should never do, +of course ;) Please note that @code{safe_mysqld} script may require that +you start it from a certain place. This means that you may have to CD to +a certain directory, before you start the @code{mysqld_multi}. If +you have problems starting, please see the @code{safe_mysqld} +script. Check especially the lines: +@example +-------------------------------------------------------------------------- +MY_PWD=`pwd` Check if we are starting this relative (for the binary +release) if test -d /data/mysql -a -f ./share/mysql/english/errmsg.sys +-a -x ./bin/mysqld +-------------------------------------------------------------------------- +@xref{safe_mysqld, , @code{safe_mysqld}}. +@end example +The above test should be successful, or you may encounter problems. +@item +Beware of the dangers starting multiple @code{mysqlds} in the same data +directory. Use separate data directories, unless you @strong{KNOW} what +you are doing! +@item +The socket file and the TCP/IP port must be different for every @code{mysqld}. +@item +The first and fifth @code{mysqld} group were intentionally left out from +the example. You may have 'gaps' in the config file. This gives you +more flexibility. The order in which the @code{mysqlds} are started or +stopped depends on the order in which they appear in the config file. +@item +When you want to refer to a certain group using GNR with this program, +just use the number in the end of the group name ( [mysqld# <== ). +@item +You may want to use option '--user' for @code{mysqld}, but in order to +do this you need to be root when you start the @code{mysqld_multi} +script. Having the option in the config file doesn't matter; you will +just get a warning, if you are not the superuser and the @code{mysqlds} +are started under @strong{YOUR} UNIX account. @strong{IMPORTANT}: Make +sure that the @code{pid-file} and the data directory are +read+write(+execute for the latter one) accessible for @strong{THAT} +UNIX user, who the specific @code{mysqld} process is started +as. @strong{DON'T} use the UNIX root account for this, unless you +@strong{KNOW} what you are doing! +@item +@strong{MOST IMPORTANT}: Make sure that you understand the meanings of +the options that are passed to the @code{mysqlds} and why @strong{WOULD +YOU WANT} to have separate @code{mysqld} processes. Starting multiple +@code{mysqlds} in one data directory @strong{WILL NOT} give you extra +performance in a threaded system! +@end itemize + +@xref{Multiple servers}. + +This is an example of the config file on behalf of @code{mysqld_multi}. + +@example +# This file should probably be in your home dir (~/.my.cnf) or /etc/my.cnf +# Version 2.1 by Jani Tolonen + +[mysqld_multi] +mysqld = /usr/local/bin/safe_mysqld +mysqladmin = /usr/local/bin/mysqladmin +user = multi_admin +password = multipass + +[mysqld2] +socket = /tmp/mysql.sock2 +port = 3307 +pid-file = /usr/local/mysql/var2/hostname.pid2 +datadir = /usr/local/mysql/var2 +language = /usr/local/share/mysql/english +user = john + +[mysqld3] +socket = /tmp/mysql.sock3 +port = 3308 +pid-file = /usr/local/mysql/var3/hostname.pid3 +datadir = /usr/local/mysql/var3 +language = /usr/local/share/mysql/swedish +user = monty + +[mysqld4] +socket = /tmp/mysql.sock4 +port = 3309 +pid-file = /usr/local/mysql/var4/hostname.pid4 +datadir = /usr/local/mysql/var4 +language = /usr/local/share/mysql/estonia +user = tonu + +[mysqld6] +socket = /tmp/mysql.sock6 +port = 3311 +pid-file = /usr/local/mysql/var6/hostname.pid6 +datadir = /usr/local/mysql/var6 +language = /usr/local/share/mysql/japanese +user = jani +@end example + +@xref{Option files}. + + +@node myisampack, mysqld-max, mysqld_multi, Server-Side Scripts +@subsection myisampack, The MySQL Compressed Read-only Table Generator + +@cindex compressed tables +@cindex tables, compressed +@cindex MyISAM, compressed tables +@cindex @code{myisampack} +@cindex @code{pack_isam} + +@code{myisampack} is used to compress MyISAM tables, and @code{pack_isam} +is used to compress ISAM tables. Because ISAM tables are deprecated, we +will only discuss @code{myisampack} here, but everything said about +@code{myisampack} should also be true for @code{pack_isam}. + +@code{myisampack} works by compressing each column in the table separately. +The information needed to decompress columns is read into memory when the +table is opened. This results in much better performance when accessing +individual records, because you only have to uncompress exactly one record, not +a much larger disk block as when using Stacker on MS-DOS. +Usually, @code{myisampack} packs the data file 40%-70%. + +@strong{MySQL} uses memory mapping (@code{mmap()}) on compressed tables and +falls back to normal read/write file usage if @code{mmap()} doesn't work. + +There are currently two limitations with @code{myisampack}: +@itemize @bullet +@item +After packing, the table is read-only. +@item +@code{myisampack} can also pack @code{BLOB} or @code{TEXT} columns. The +older @code{pack_isam} could not do this. +@end itemize + +Fixing these limitations is on our TODO list but with low priority. + +@code{myisampack} is invoked like this: + +@example +shell> myisampack [options] filename ... +@end example + +Each filename should be the name of an index (@file{.MYI}) file. If you +are not in the database directory, you should specify the pathname to the +file. It is permissible to omit the @file{.MYI} extension. + +@code{myisampack} supports the following options: + +@table @code +@item -b, --backup +Make a backup of the table as @code{tbl_name.OLD}. + +@item -#, --debug=debug_options +Output debug log. The @code{debug_options} string often is +@code{'d:t:o,filename'}. + +@item -f, --force +Force packing of the table even if it becomes bigger or if the temporary file +exists. @code{myisampack} creates a temporary file named @file{tbl_name.TMD} +while it compresses the table. If you kill @code{myisampack}, the @file{.TMD} +file may not be deleted. Normally, @code{myisampack} exits with an error if +it finds that @file{tbl_name.TMD} exists. With @code{--force}, +@code{myisampack} packs the table anyway. + +@item -?, --help +Display a help message and exit. + +@item -j big_tbl_name, --join=big_tbl_name +Join all tables named on the command line into a single table +@code{big_tbl_name}. All tables that are to be combined +MUST be identical (same column names and types, same indexes, etc.). + +@item -p #, --packlength=# +Specify the record length storage size, in bytes. The value should be 1, 2, +or 3. (@code{myisampack} stores all rows with length pointers of 1, 2, or 3 +bytes. In most normal cases, @code{myisampack} can determine the right length +value before it begins packing the file, but it may notice during the packing +process that it could have used a shorter length. In this case, +@code{myisampack} will print a note that the next time you pack the same file, +you could use a shorter record length.) + +@item -s, --silent +Silent mode. Write output only when errors occur. + +@item -t, --test +Don't actually pack table, just test packing it. + +@item -T dir_name, --tmp_dir=dir_name +Use the named directory as the location in which to write the temporary table. + +@item -v, --verbose +Verbose mode. Write information about progress and packing result. + +@item -V, --version +Display version information and exit. + +@item -w, --wait + +Wait and retry if table is in use. If the @code{mysqld} server was +invoked with the @code{--skip-locking} option, it is not a good idea to +invoke @code{myisampack} if the table might be updated during the +packing process. +@end table + +@cindex examples, compressed tables +The sequence of commands shown below illustrates a typical table compression +session: + +@example +shell> ls -l station.* +-rw-rw-r-- 1 monty my 994128 Apr 17 19:00 station.MYD +-rw-rw-r-- 1 monty my 53248 Apr 17 19:00 station.MYI +-rw-rw-r-- 1 monty my 5767 Apr 17 19:00 station.frm + +shell> myisamchk -dvv station + +MyISAM file: station +Isam-version: 2 +Creation time: 1996-03-13 10:08:58 +Recover time: 1997-02-02 3:06:43 +Data records: 1192 Deleted blocks: 0 +Datafile: Parts: 1192 Deleted data: 0 +Datafile pointer (bytes): 2 Keyfile pointer (bytes): 2 +Max datafile length: 54657023 Max keyfile length: 33554431 +Recordlength: 834 +Record format: Fixed length + +table description: +Key Start Len Index Type Root Blocksize Rec/key +1 2 4 unique unsigned long 1024 1024 1 +2 32 30 multip. text 10240 1024 1 + +Field Start Length Type +1 1 1 +2 2 4 +3 6 4 +4 10 1 +5 11 20 +6 31 1 +7 32 30 +8 62 35 +9 97 35 +10 132 35 +11 167 4 +12 171 16 +13 187 35 +14 222 4 +15 226 16 +16 242 20 +17 262 20 +18 282 20 +19 302 30 +20 332 4 +21 336 4 +22 340 1 +23 341 8 +24 349 8 +25 357 8 +26 365 2 +27 367 2 +28 369 4 +29 373 4 +30 377 1 +31 378 2 +32 380 8 +33 388 4 +34 392 4 +35 396 4 +36 400 4 +37 404 1 +38 405 4 +39 409 4 +40 413 4 +41 417 4 +42 421 4 +43 425 4 +44 429 20 +45 449 30 +46 479 1 +47 480 1 +48 481 79 +49 560 79 +50 639 79 +51 718 79 +52 797 8 +53 805 1 +54 806 1 +55 807 20 +56 827 4 +57 831 4 + +shell> myisampack station.MYI +Compressing station.MYI: (1192 records) +- Calculating statistics + +normal: 20 empty-space: 16 empty-zero: 12 empty-fill: 11 +pre-space: 0 end-space: 12 table-lookups: 5 zero: 7 +Original trees: 57 After join: 17 +- Compressing file +87.14% + +shell> ls -l station.* +-rw-rw-r-- 1 monty my 127874 Apr 17 19:00 station.MYD +-rw-rw-r-- 1 monty my 55296 Apr 17 19:04 station.MYI +-rw-rw-r-- 1 monty my 5767 Apr 17 19:00 station.frm + +shell> myisamchk -dvv station + +MyISAM file: station +Isam-version: 2 +Creation time: 1996-03-13 10:08:58 +Recover time: 1997-04-17 19:04:26 +Data records: 1192 Deleted blocks: 0 +Datafile: Parts: 1192 Deleted data: 0 +Datafilepointer (bytes): 3 Keyfile pointer (bytes): 1 +Max datafile length: 16777215 Max keyfile length: 131071 +Recordlength: 834 +Record format: Compressed + +table description: +Key Start Len Index Type Root Blocksize Rec/key +1 2 4 unique unsigned long 10240 1024 1 +2 32 30 multip. text 54272 1024 1 + +Field Start Length Type Huff tree Bits +1 1 1 constant 1 0 +2 2 4 zerofill(1) 2 9 +3 6 4 no zeros, zerofill(1) 2 9 +4 10 1 3 9 +5 11 20 table-lookup 4 0 +6 31 1 3 9 +7 32 30 no endspace, not_always 5 9 +8 62 35 no endspace, not_always, no empty 6 9 +9 97 35 no empty 7 9 +10 132 35 no endspace, not_always, no empty 6 9 +11 167 4 zerofill(1) 2 9 +12 171 16 no endspace, not_always, no empty 5 9 +13 187 35 no endspace, not_always, no empty 6 9 +14 222 4 zerofill(1) 2 9 +15 226 16 no endspace, not_always, no empty 5 9 +16 242 20 no endspace, not_always 8 9 +17 262 20 no endspace, no empty 8 9 +18 282 20 no endspace, no empty 5 9 +19 302 30 no endspace, no empty 6 9 +20 332 4 always zero 2 9 +21 336 4 always zero 2 9 +22 340 1 3 9 +23 341 8 table-lookup 9 0 +24 349 8 table-lookup 10 0 +25 357 8 always zero 2 9 +26 365 2 2 9 +27 367 2 no zeros, zerofill(1) 2 9 +28 369 4 no zeros, zerofill(1) 2 9 +29 373 4 table-lookup 11 0 +30 377 1 3 9 +31 378 2 no zeros, zerofill(1) 2 9 +32 380 8 no zeros 2 9 +33 388 4 always zero 2 9 +34 392 4 table-lookup 12 0 +35 396 4 no zeros, zerofill(1) 13 9 +36 400 4 no zeros, zerofill(1) 2 9 +37 404 1 2 9 +38 405 4 no zeros 2 9 +39 409 4 always zero 2 9 +40 413 4 no zeros 2 9 +41 417 4 always zero 2 9 +42 421 4 no zeros 2 9 +43 425 4 always zero 2 9 +44 429 20 no empty 3 9 +45 449 30 no empty 3 9 +46 479 1 14 4 +47 480 1 14 4 +48 481 79 no endspace, no empty 15 9 +49 560 79 no empty 2 9 +50 639 79 no empty 2 9 +51 718 79 no endspace 16 9 +52 797 8 no empty 2 9 +53 805 1 17 1 +54 806 1 3 9 +55 807 20 no empty 3 9 +56 827 4 no zeros, zerofill(2) 2 9 +57 831 4 no zeros, zerofill(1) 2 9 +@end example + +The information printed by @code{myisampack} is described below: + +@table @code +@item normal +The number of columns for which no extra packing is used. + +@item empty-space +The number of columns containing +values that are only spaces; these will occupy 1 bit. + +@item empty-zero +The number of columns containing +values that are only binary 0's; these will occupy 1 bit. + +@item empty-fill +The number of integer columns that don't occupy the full byte range of their +type; these are changed to a smaller type (for example, an @code{INTEGER} +column may be changed to @code{MEDIUMINT}). + +@item pre-space +The number of decimal columns that are stored with leading spaces. In this +case, each value will contain a count for the number of leading spaces. + +@item end-space +The number of columns that have a lot of trailing spaces. In this case, each +value will contain a count for the number of trailing spaces. + +@item table-lookup +The column had only a small number of different values, which were +converted to an @code{ENUM} before Huffman compression. + +@item zero +The number of columns for which all values are zero. + +@item Original trees +The initial number of Huffman trees. + +@item After join +The number of distinct Huffman trees left after joining +trees to save some header space. +@end table + +After a table has been compressed, @code{myisamchk -dvv} prints additional +information about each field: + +@table @code +@item Type +The field type may contain the following descriptors: + +@table @code +@item constant +All rows have the same value. + +@item no endspace +Don't store endspace. + +@item no endspace, not_always +Don't store endspace and don't do end space compression for all values. + +@item no endspace, no empty +Don't store endspace. Don't store empty values. + +@item table-lookup +The column was converted to an @code{ENUM}. + +@item zerofill(n) +The most significant @code{n} bytes in the value are always 0 and are not +stored. + +@item no zeros +Don't store zeros. + +@item always zero +0 values are stored in 1 bit. +@end table + +@item Huff tree +The Huffman tree associated with the field. + +@item Bits +The number of bits used in the Huffman tree. +@end table + +After you have run @code{pack_isam}/@code{myisampack} you must run +@code{isamchk}/@code{myisamchk} to re-create the index. At this time you +can also sort the index blocks and create statistics needed for +the @strong{MySQL} optimizer to work more efficiently: + +@example +myisamchk -rq --analyze --sort-index table_name.MYI +isamchk -rq --analyze --sort-index table_name.ISM +@end example + +After you have installed the packed table into the @strong{MySQL} database +directory you should do @code{mysqladmin flush-tables} to force @code{mysqld} +to start using the new table. + +If you want to unpack a packed table, you can do this with the +@code{--unpack} option to @code{isamchk} or @code{myisamchk}. + + +@node mysqld-max, , myisampack, Server-Side Scripts +@subsection mysqld-max, An extended mysqld server + +@cindex @code{mysqld-max} + +@code{mysqld-max} is the MySQL server (@code{mysqld}) configured with +the following configure options: + +@multitable @columnfractions .3 .7 +@item @strong{Option} @tab @strong{Comment} +@item --with-server-suffix=-max @tab Add a suffix to the @code{mysqld} version string. +@item --with-bdb @tab Support for Berkeley DB (BDB) tables +@item --with-innodb @tab Support for InnoDB tables. +@item CFLAGS=-DUSE_SYMDIR @tab Symbolic links support for Windows. +@end multitable + +You can find the @strong{MySQL}-max binaries at +@uref{http://www.mysql.com/downloads/mysql-max-3.23.html}. + +The Windows @strong{MySQL} 3.23 binary distribution includes both the +standard @strong{mysqld.exe} binary and the @code{mysqld-max.exe} binary. +@uref{http://www.mysql.com/downloads/mysql-3.23.html}. +@xref{Windows installation}. + +Note that as Berkeley DB and InnoDB are not available for all platforms, +some of the @code{Max} binaries may not have support for both of these. +You can check which table types are supported by doing the following +query: + +@example +mysql> show variables like "have_%"; ++---------------+-------+ +| Variable_name | Value | ++---------------+-------+ +| have_bdb | YES | +| have_innodb | NO | +| have_isam | YES | +| have_raid | YES | +| have_ssl | NO | ++---------------+-------+ +@end example + +The meaning of the values are: + +@multitable @columnfractions .3 .7 +@item @strong{Value} @tab @strong{Meaning}. +@item YES @tab The option is activated and usable. +@item NO @tab @strong{MySQL} is not compiled with support for this option. +@item DISABLED @tab The xxxx option is disabled because one started @code{mysqld} with @code{--skip-xxxx} or because one didn't start @code{mysqld} with all needed options to enable the option. In this case the @code{hostname.err} file should contain a reason for why the option is disabled. +@end multitable + +@strong{NOTE}: To be able to create InnoDB tables you @strong{MUST} edit +your startup options to include at least the @code{innodb_data_file_path} +option. @xref{InnoDB start}. + +To get better performance for BDB tables, you should add some configuration +options for these too. @xref{BDB start}. + +@code{safe_mysqld} will automatically try to start any @code{mysqld} binary +with the @code{-max} prefix. This makes it very easy to test out a +another @code{mysqld} binary in an existing installation. Just +run @code{configure} with the options you want and then install the +new @code{mysqld} binary as @code{mysqld-max} in the same directory +where your old @code{mysqld} binary is. @xref{safe_mysqld, , @code{safe_mysqld}}. + +The @code{mysqld-max} RPM uses the above mentioned @code{safe_mysqld} +feature. It just installs the @code{mysqld-max} executable and +@code{safe_mysqld} will automatically use this executable when +@code{safe_mysqld} is restarted. + +The following table shows which table types our standard @strong{MySQL-Max} +binaries includes: + +@multitable @columnfractions .4 .3 .3 +@item @strong{System} @tab @strong{BDB} @tab @strong{InnoDB} +@item AIX 4.3 @tab N @tab Y +@item HP-UX 11.0 @tab N @tab Y +@item Linux-Alpha @tab N @tab Y +@item Linux-Intel @tab Y @tab Y +@item Linux-Ia64 @tab N @tab Y +@item Solaris-intel @tab N @tab Y +@item Solaris-sparc @tab Y @tab Y +@item SCO OSR5 @tab Y @tab Y +@item UnixWare @tab Y @tab Y +@item Windows/NT @tab Y @tab Y +@end multitable + + +@node Client-Side Scripts, perror, Server-Side Scripts, MySQL Database Administration +@section MySQL Client-Side Scripts and Utilities + +@menu +* Client-Side Overview:: +* mysql:: +* mysqladmin:: +* mysqldump:: +* mysqlhotcopy:: +* mysqlimport:: +* mysqlshow:: +@end menu + + +@node Client-Side Overview, mysql, Client-Side Scripts, Client-Side Scripts +@subsection Overview of the Client-Side Scripts and Utilities + +@cindex environment variables +@cindex programs, list of + +All @strong{MySQL} clients that communicate with the server using the +@code{mysqlclient} library use the following environment variables: + +@tindex MYSQL_UNIX_PORT environment variable +@tindex Environment variable, MYSQL_UNIX_PORT +@tindex MYSQL_TCP_PORT environment variable +@tindex Environment variable, MYSQL_TCP_PORT +@tindex MYSQL_PWD environment variable +@tindex Environment variable, MYSQL_PWD +@tindex MYSQL_DEBUG environment variable +@tindex Environment variable, MYSQL_DEBUG +@multitable @columnfractions .25 .75 +@item @strong{Name} @tab @strong{Description} +@item @code{MYSQL_UNIX_PORT} @tab The default socket; used for connections to @code{localhost} +@item @code{MYSQL_TCP_PORT} @tab The default TCP/IP port +@item @code{MYSQL_PWD} @tab The default password +@item @code{MYSQL_DEBUG} @tab Debug-trace options when debugging +@item @code{TMPDIR} @tab The directory where temporary tables/files are created +@end multitable + +Use of @code{MYSQL_PWD} is insecure. +@xref{Connecting}. + +@tindex MYSQL_HISTFILE environment variable +@tindex Environment variable, MYSQL_HISTFILE +@tindex HOME environment variable +@tindex Environment variable, HOME +@cindex history file +@cindex command line history +@tindex .mysql_history file +The @file{mysql} client uses the file named in the @code{MYSQL_HISTFILE} +environment variable to save the command-line history. The default value for +the history file is @file{$HOME/.mysql_history}, where @code{$HOME} is the +value of the @code{HOME} environment variable. @xref{Environment variables}. + +All @strong{MySQL} programs take many different options. However, every +@strong{MySQL} program provides a @code{--help} option that you can use +to get a full description of the program's different options. For example, try +@code{mysql --help}. + +You can override default options for all standard client programs with an +option file. @ref{Option files}. + +The list below briefly describes the @strong{MySQL} programs: + +@table @code + +@cindex @code{myisamchk} +@item myisamchk +Utility to describe, check, optimize, and repair @strong{MySQL} tables. +Because @code{myisamchk} has many functions, it is described in its own +chapter. @xref{Maintenance}. + +@cindex @code{make_binary_distribution} +@item make_binary_distribution +Makes a binary release of a compiled @strong{MySQL}. This could be sent +by FTP to @file{/pub/mysql/Incoming} on @code{support.mysql.com} for the +convenience of other @strong{MySQL} users. + +@cindex @code{msql2mysql} +@item msql2mysql +A shell script that converts @code{mSQL} programs to @strong{MySQL}. It doesn't +handle all cases, but it gives a good start when converting. + +@cindex @code{mysqlaccess} +@item mysqlaccess +A script that checks the access privileges for a host, user, and database +combination. + +@cindex @code{mysqladmin} +@item mysqladmin +Utility for performing administrative operations, such as creating or +dropping databases, reloading the grant tables, flushing tables to disk, and +reopening log files. @code{mysqladmin} can also be used to retrieve version, +process, and status information from the server. +@xref{mysqladmin, , @code{mysqladmin}}. + +@cindex @code{mysqlbug} +@item mysqlbug +The @strong{MySQL} bug report script. This script should always be used when +filing a bug report to the @strong{MySQL} list. + +@cindex @code{mysqld} +@item mysqld +The SQL daemon. This should always be running. + +@cindex @code{mysqldump} +@item mysqldump +Dumps a @strong{MySQL} database into a file as SQL statements or +as tab-separated text files. Enhanced freeware originally by Igor Romanenko. +@xref{mysqldump, , @code{mysqldump}}. + +@cindex @code{mysqlimport} +@item mysqlimport +Imports text files into their respective tables using @code{LOAD DATA +INFILE}. @xref{mysqlimport, , @code{mysqlimport}}. + +@cindex @code{mysqlshow} +@item mysqlshow +Displays information about databases, tables, columns, and indexes. + +@cindex @code{mysql_install_db} +@item mysql_install_db +Creates the @strong{MySQL} grant tables with default privileges. This is +usually executed only once, when first installing @strong{MySQL} +on a system. + +@cindex @code{replace} +@item replace +A utility program that is used by @code{msql2mysql}, but that has more +general applicability as well. @code{replace} changes strings in place in +files or on the standard input. Uses a finite state machine to match longer +strings first. Can be used to swap strings. For example, this command +swaps @code{a} and @code{b} in the given files: + +@example +shell> replace a b b a -- file1 file2 ... +@end example +@end table + + +@node mysql, mysqladmin, Client-Side Overview, Client-Side Scripts +@subsection The Command-line Tool + +@cindex command line tool +@cindex tools, command line +@cindex scripts +@cindex @code{mysql} + +@code{mysql} is a simple SQL shell (with GNU @code{readline} capabilities). +It supports interactive and non-interactive use. When used interactively, +query results are presented in an ASCII-table format. When used +non-interactively (for example, as a filter), the result is presented in +tab-separated format. (The output format can be changed using command-line +options.) You can run scripts simply like this: + +@example +shell> mysql database < script.sql > output.tab +@end example + +If you have problems due to insufficient memory in the client, use the +@code{--quick} option! This forces @code{mysql} to use +@code{mysql_use_result()} rather than @code{mysql_store_result()} to +retrieve the result set. + +Using @code{mysql} is very easy. Just start it as follows: +@code{mysql database} or @code{mysql --user=user_name --password=your_password database}. Type a SQL statement, end it with @samp{;}, @samp{\g}, or @samp{\G} +and press RETURN/ENTER. + +@cindex command line options +@cindex options, command line +@cindex startup parameters +@code{mysql} supports the following options: + +@table @code +@cindex help option +@item -?, --help +Display this help and exit. +@cindex automatic rehash option +@item -A, --no-auto-rehash +No automatic rehashing. One has to use 'rehash' to get table and field +completion. This gives a quicker start of mysql. +@cindex batch option +@item -B, --batch +Print results with a tab as separator, each row on a new line. Doesn't use +history file. +@cindex character sets option +@item --character-sets-dir=... +Directory where character sets are located. +@cindex compress option. +@item -C, --compress +Use compression in server/client protocol. +@cindex debug option +@item -#, --debug[=...] +Debug log. Default is 'd:t:o,/tmp/mysql.trace'. +@cindex database option +@item -D, --database=... +Database to use. This is mainly useful in the @code{my.cnf} file. +@cindex default character set option +@item --default-character-set=... +Set the default character set. +@cindex execute option +@item -e, --execute=... +Execute command and quit. (Output like with --batch) +@cindex vertical option +@item -E, --vertical +Print the output of a query (rows) vertically. Without this option you +can also force this output by ending your statements with @code{\G}. +@cindex force option +@item -f, --force +Continue even if we get a SQL error. +@cindex no-named-commands option +@item -g, --no-named-commands +Named commands are disabled. Use \* form only, or use named commands +only in the beginning of a line ending with a semicolon (;). Since +Version 10.9, the client now starts with this option ENABLED by default! +With the -g option, long format commands will still work from the first +line, however. +@cindex enable-named-commands option +@item -G, --enable-named-commands +Named commands are @strong{enabled}. Long format commands are allowed as +well as shortened \* commands. +@cindex ignore space option. +@item -i, --ignore-space +Ignore space after function names. +@cindex host option +@item -h, --host=... +Connect to the given host. +@cindex html option +@item -H, --html +Produce HTML output. +@cindex skip line numbers option +@item -L, --skip-line-numbers +Don't write line number for errors. Useful when one wants to compare result +files that includes error messages +@cindex no pager option +@item --no-pager +Disable pager and print to stdout. See interactive help (\h) also. +@cindex no tee option +@item --no-tee +Disable outfile. See interactive help (\h) also. +@cindex unbuffered option. +@item -n, --unbuffered +Flush buffer after each query. +@cindex skip column names option +@item -N, --skip-column-names +Don't write column names in results. +@cindex set variable option +@item -O, --set-variable var=option +Give a variable a value. @code{--help} lists variables. +@cindex one database option +@item -o, --one-database +Only update the default database. This is useful for skipping updates to +other database in the update log. +@cindex pager option +@item @code{--pager[=...]} +Output type. Default is your @code{ENV} variable @code{PAGER}. Valid +pagers are less, more, cat [> filename], etc. See interactive help (\h) +also. This option does not work in batch mode. Pager works only in UNIX. +@cindex password option +@item -p[password], --password[=...] +Password to use when connecting to server. If a password is not given on +the command line, you will be prompted for it. Note that if you use the +short form @code{-p} you can't have a space between the option and the +password. +@item -P --port=... +TCP/IP port number to use for connection. +@cindex quick option +@item -q, --quick +Don't cache result, print it row-by-row. This may slow down the server +if the output is suspended. Doesn't use history file. +@cindex raw option +@item -r, --raw +Write column values without escape conversion. Used with @code{--batch} +@cindex silent option +@item -s, --silent +Be more silent. +@item -S --socket=... +Socket file to use for connection. +@cindex table option +@item -t --table +Output in table format. This is default in non-batch mode. +@item -T, --debug-info +Print some debug information at exit. +@cindex tee option +@item --tee=... +Append everything into outfile. See interactive help (\h) also. Does not +work in batch mode. +@cindex user option +@item -u, --user=# +User for login if not current user. +@cindex safe updates option +@item -U, --safe-updates[=#], --i-am-a-dummy[=#] +Only allow @code{UPDATE} and @code{DELETE} that uses keys. See below for +more information about this option. You can reset this option if you have +it in your @code{my.cnf} file by using @code{--safe-updates=0}. +@cindex verbose option +@item -v, --verbose +More verbose output (-v -v -v gives the table output format). +@cindex version option +@item -V, --version +Output version information and exit. +@cindex wait option +@item -w, --wait +Wait and retry if connection is down instead of aborting. +@end table + +You can also set the following variables with @code{-O} or +@code{--set-variable}: + +@cindex timeout +@multitable @columnfractions .3 .2 .5 +@item Variablename @tab Default @tab Description +@item connect_timeout @tab 0 @tab Number of seconds before timeout connection. +@item max_allowed_packet @tab 16777216 @tab Max packetlength to send/receive from to server +@item net_buffer_length @tab 16384 @tab Buffer for TCP/IP and socket communication +@item select_limit @tab 1000 @tab Automatic limit for SELECT when using --i-am-a-dummy +@item max_join_size @tab 1000000 @tab Automatic limit for rows in a join when using --i-am-a-dummy. +@end multitable + +If you type 'help' on the command line, @code{mysql} will print out the +commands that it supports: + +@cindex commands, list of +@example +mysql> help + +MySQL commands: +help (\h) Display this text. +? (\h) Synonym for `help'. +clear (\c) Clear command. +connect (\r) Reconnect to the server. Optional arguments are db and host. +edit (\e) Edit command with $EDITOR. +ego (\G) Send command to mysql server, display result vertically. +exit (\q) Exit mysql. Same as quit. +go (\g) Send command to mysql server. +nopager (\n) Disable pager, print to stdout. +notee (\t) Don't write into outfile. +pager (\P) Set PAGER [to_pager]. Print the query results via PAGER. +print (\p) Print current command. +quit (\q) Quit mysql. +rehash (\#) Rebuild completion hash. +source (\.) Execute a SQL script file. Takes a file name as an argument. +status (\s) Get status information from the server. +tee (\T) Set outfile [to_outfile]. Append everything into given outfile. +use (\u) Use another database. Takes database name as argument. +@end example + +From the above, pager only works in UNIX. + +@cindex status command +The @code{status} command gives you some information about the +connection and the server you are using. If you are running in the +@code{--safe-updates} mode, @code{status} will also print the values for +the @code{mysql} variables that affect your queries. + +@cindex @code{safe-mode} command +A useful startup option for beginners (introduced in @strong{MySQL} +Version 3.23.11) is @code{--safe-updates} (or @code{--i-am-a-dummy} for +users that has at some time done a @code{DELETE FROM table_name} but +forgot the @code{WHERE} clause). When using this option, @code{mysql} +sends the following command to the @strong{MySQL} server when opening +the connection: + +@example +SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=#select_limit#, + SQL_MAX_JOIN_SIZE=#max_join_size#" +@end example + +where @code{#select_limit#} and @code{#max_join_size#} are variables that +can be set from the @code{mysql} command line. @xref{SET OPTION, @code{SET}}. + +The effect of the above is: + +@itemize @bullet +@item +You are not allowed to do an @code{UPDATE} or @code{DELETE} statement +if you don't have a key constraint in the @code{WHERE} part. One can, +however, force an @code{UPDATE/DELETE} by using @code{LIMIT}: +@example +UPDATE table_name SET not_key_column=# WHERE not_key_column=# LIMIT 1; +@end example +@item +All big results are automatically limited to @code{#select_limit#} rows. +@item +@code{SELECT}'s that will probably need to examine more than +@code{#max_join_size} row combinations will be aborted. +@end itemize + +Some useful hints about the @code{mysql} client: + +Some data is much more readable when displayed vertically, instead of +the usual horizontal box type output. For example longer text, which +includes new lines, is often much easier to be read with vertical +output. + +@example +mysql> select * from mails where length(txt) < 300 limit 300,1\G +*************************** 1. row *************************** + msg_nro: 3068 + date: 2000-03-01 23:29:50 +time_zone: +0200 +mail_from: Monty + reply: monty@@no.spam.com + mail_to: "Thimble Smith" + sbj: UTF-8 + txt: >>>>> "Thimble" == Thimble Smith writes: + +Thimble> Hi. I think this is a good idea. Is anyone familiar with UTF-8 +Thimble> or Unicode? Otherwise I'll put this on my TODO list and see what +Thimble> happens. + +Yes, please do that. + +Regards, +Monty + file: inbox-jani-1 + hash: 190402944 +1 row in set (0.09 sec) +@end example + +@itemize @bullet +@item +For logging, you can use the @code{tee} option. The @code{tee} can be +started with option @code{--tee=...}, or from the command line +interactively with command @code{tee}. All the data displayed on the +screen will also be appended into a given file. This can be very useful +for debugging purposes also. The @code{tee} can be disabled from the +command line with command @code{notee}. Executing @code{tee} again +starts logging again. Without a parameter the previous file will be +used. Note that @code{tee} will flush the results into the file after +each command, just before the command line appears again waiting for the +next command. + +@item +Browsing, or searching the results in the interactive mode in UNIX less, +more, or any other similar program, is now possible with option +@code{--pager[=...]}. Without argument, @code{mysql} client will look +for environment variable PAGER and set @code{pager} to that. +@code{pager} can be started from the interactive command line with +command @code{pager} and disabled with command @code{nopager}. The +command takes an argument optionally and the @code{pager} will be set to +that. Command @code{pager} can be called without an argument, but this +requires that the option @code{--pager} was used, or the @code{pager} +will default to stdout. @code{pager} works only in UNIX, since it uses +the popen() function, which doesn't exist in Windows. In Windows, the +@code{tee} option can be used instead, although it may not be as handy +as @code{pager} can be in some situations. + +@item +A few tips about @code{pager}: You can use it to write to a file: +@example +mysql> pager cat > /tmp/log.txt +@end example +and the results will only go to a file. You can also pass any options +for the programs that you want to use with the @code{pager}: +@example +mysql> pager less -n -i -S +@end example +From the above do note the option '-S'. You may find it very useful when +browsing the results; try the option with horizontal output (end +commands with '\g', or ';') and with vertical output (end commands with +'\G'). Sometimes a very wide result set is hard to be read from the screen, +with option -S to less you can browse the results within the interactive +less from left to right, preventing lines longer than your screen from +being continued to the next line. This can make the result set much more +readable. You can swith the mode between on and off within the interactive +less with '-S'. See the 'h' for more help about less. + +@item +Last (unless you already understood this from the above examples ;) you +can combine very complex ways to handle the results, for example the +following would send the results to two files in two different +directories, on two different hard-disks mounted on /dr1 and /dr2, yet +let the results still be seen on the screen via less: +@example +mysql> pager cat | tee /dr1/tmp/res.txt | tee /dr2/tmp/res2.txt | less -n -i -S +@end example + +@item +You can also combine the two functions above; have the @code{tee} +enabled, @code{pager} set to 'less' and you will be able to browse the +results in unix 'less' and still have everything appended into a file +the same time. The difference between @code{UNIX tee} used with the +@code{pager} and the @code{mysql} client in-built @code{tee}, is that +the in-built @code{tee} works even if you don't have the @code{UNIX tee} +available. The in-built @code{tee} also logs everything that is printed +on the screen, where the @code{UNIX tee} used with @code{pager} doesn't +log quite that much. Last, but not least, the interactive @code{tee} is +more handy to switch on and off, when you want to log something into a +file, but want to be able to turn the feature off sometimes. +@end itemize + + +@node mysqladmin, mysqldump, mysql, Client-Side Scripts +@subsection mysqladmin, Administrating a MySQL Server + +@cindex administration, server +@cindex server administration +@cindex @code{mysladmn} + +A utility for performing administrative operations. The syntax is: + +@example +shell> mysqladmin [OPTIONS] command [command-option] command ... +@end example + +You can get a list of the options your version of @code{mysqladmin} supports +by executing @code{mysqladmin --help}. + +The current @code{mysqladmin} supports the following commands: + +@multitable @columnfractions .3 .7 +@item create databasename @tab Create a new database. +@item drop databasename @tab Delete a database and all its tables. +@item extended-status @tab Gives an extended status message from the server. +@item flush-hosts @tab Flush all cached hosts. +@item flush-logs @tab Flush all logs. +@item flush-tables @tab Flush all tables. +@item flush-privileges @tab Reload grant tables (same as reload). +@item kill id,id,... @tab Kill mysql threads. +@item password @tab New-password. Change old password to new-password. +@item ping @tab Check if @code{mysqld} is alive. +@item processlist @tab Show list of active threads in server. +@item reload @tab Reload grant tables. +@item refresh @tab Flush all tables and close and open logfiles. +@item shutdown @tab Take server down. +@item slave-start @tab Start slave replication thread. +@item slave-stop @tab Stop slave replication thread. +@item status @tab Gives a short status message from the server. +@item variables @tab Prints variables available. +@item version @tab Get version info from server. +@end multitable + +All commands can be shortened to their unique prefix. For example: + +@example +shell> mysqladmin proc stat ++----+-------+-----------+----+-------------+------+-------+------+ +| Id | User | Host | db | Command | Time | State | Info | ++----+-------+-----------+----+-------------+------+-------+------+ +| 6 | monty | localhost | | Processlist | 0 | | | ++----+-------+-----------+----+-------------+------+-------+------+ +Uptime: 10077 Threads: 1 Questions: 9 Slow queries: 0 Opens: 6 Flush tables: 1 Open tables: 2 Memory in use: 1092K Max memory used: 1116K +@end example + +@cindex status command, results +The @code{mysqladmin status} command result has the following columns: + +@cindex uptime +@multitable @columnfractions .3 .7 +@item Uptime @tab Number of seconds the @strong{MySQL} server has been up. +@cindex threads +@item Threads @tab Number of active threads (clients). +@cindex questions +@item Questions @tab Number of questions from clients since @code{mysqld} was started. +@cindex slow queries +@item Slow queries @tab Queries that have taken more than @code{long_query_time} seconds. @xref{Slow query log}. +@cindex opens +@item Opens @tab How many tables @code{mysqld} has opened. +@cindex flush tables +@cindex tables, flush +@item Flush tables @tab Number of @code{flush ...}, @code{refresh}, and @code{reload} commands. +@cindex open tables +@item Open tables @tab Number of tables that are open now. +@cindex memory use +@item Memory in use @tab Memory allocated directly by the @code{mysqld} code (only available when @strong{MySQL} is compiled with --with-debug=full). +@cindex max memory used +@item Max memory used @tab Maximum memory allocated directly by the @code{mysqld} code (only available when @strong{MySQL} is compiled with --with-debug=full). +@end multitable + +If you do @code{myslqadmin shutdown} on a socket (in other words, on a +the computer where @code{mysqld} is running), @code{mysqladmin} will +wait until the @strong{MySQL} @code{pid-file} is removed to ensure that +the @code{mysqld} server has stopped properly. + + +@node mysqldump, mysqlhotcopy, mysqladmin, Client-Side Scripts +@subsection mysqldump, Dumping Table Structure and Data + +@cindex dumping, databases +@cindex databases, dumping +@cindex tables, dumping +@cindex backing up, databases + +@cindex @code{mysqldump} +Utility to dump a database or a collection of database for backup or for +transferring the data to another SQL server (not necessarily a @strong{MySQL} +server). The dump will contain SQL statements to create the table +and/or populate the table. + +If you are doing a backup on the server, you should consider using +the @code{mysqlhotcopy} instead. @xref{mysqlhotcopy, , @code{mysqlhotcopy}}. + +@example +shell> mysqldump [OPTIONS] database [tables] +OR mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...] +OR mysqldump [OPTIONS] --all-databases [OPTIONS] +@end example + +If you don't give any tables or use the @code{--databases} or +@code{--all-databases}, the whole database(s) will be dumped. + +You can get a list of the options your version of @code{mysqldump} supports +by executing @code{mysqldump --help}. + +Note that if you run @code{mysqldump} without @code{--quick} or +@code{--opt}, @code{mysqldump} will load the whole result set into +memory before dumping the result. This will probably be a problem if +you are dumping a big database. + +Note that if you are using a new copy of the @code{mysqldump} program +and you are going to do a dump that will be read into a very old @strong{MySQL} +server, you should not use the @code{--opt} or @code{-e} options. + +@code{mysqldump} supports the following options: + +@table @code +@item --add-locks +Add @code{LOCK TABLES} before and @code{UNLOCK TABLE} after each table dump. +(To get faster inserts into @strong{MySQL}.) +@item --add-drop-table +Add a @code{drop table} before each create statement. +@item -A, --all-databases +Dump all the databases. This will be same as @code{--databases} with all +databases selected. +@item -a, --all +Include all @strong{MySQL}-specific create options. +@item --allow-keywords +Allow creation of column names that are keywords. This works by +prefixing each column name with the table name. +@item -c, --complete-insert +Use complete insert statements (with column names). +@item -C, --compress +Compress all information between the client and the server if both support +compression. +@item -B, --databases +To dump several databases. Note the difference in usage. In this case +no tables are given. All name arguments are regarded as database names. +@code{USE db_name;} will be included in the output before each new database. +@item --delayed +Insert rows with the @code{INSERT DELAYED} command. +@item -e, --extended-insert +Use the new multiline @code{INSERT} syntax. (Gives more compact and +faster inserts statements.) +@item -#, --debug[=option_string] +Trace usage of the program (for debugging). +@item --help +Display a help message and exit. +@item --fields-terminated-by=... +@itemx --fields-enclosed-by=... +@itemx --fields-optionally-enclosed-by=... +@itemx --fields-escaped-by=... +@itemx --lines-terminated-by=... +These options are used with the @code{-T} option and have the same +meaning as the corresponding clauses for @code{LOAD DATA INFILE}. +@xref{LOAD DATA, , @code{LOAD DATA}}. +@item -F, --flush-logs +Flush log file in the @strong{MySQL} server before starting the dump. +@item -f, --force, +Continue even if we get a SQL error during a table dump. +@item -h, --host=.. +Dump data from the @strong{MySQL} server on the named host. The default host +is @code{localhost}. +@item -l, --lock-tables. +Lock all tables before starting the dump. The tables are locked with +@code{READ LOCAL} to allow concurrent inserts in the case of @code{MyISAM} +tables. +@item -n, --no-create-db +'CREATE DATABASE /*!32312 IF NOT EXISTS*/ db_name;' will not be put in the +output. The above line will be added otherwise, if --databases or +--all-databases option was given. +@item -t, --no-create-info +Don't write table creation information (The @code{CREATE TABLE} statement.) +@item -d, --no-data +Don't write any row information for the table. This is very useful if you +just want to get a dump of the structure for a table! +@item --opt +Same as @code{--quick --add-drop-table --add-locks --extended-insert +--lock-tables}. Should give you the fastest possible dump for reading +into a @strong{MySQL} server. +@item -pyour_pass, --password[=your_pass] +The password to use when connecting to the server. If you specify +no @samp{=your_pass} part, +@code{mysqldump} you will be prompted for a password. +@item -P port_num, --port=port_num +The TCP/IP port number to use for connecting to a host. (This is used for +connections to hosts other than @code{localhost}, for which Unix sockets are +used.) +@item -q, --quick +Don't buffer query, dump directly to stdout. Uses @code{mysql_use_result()} +to do this. +@item -r, --result-file=... +Direct output to a given file. This option should be used in MSDOS, +because it prevents new line '\n' from being converted to '\n\r' (new +line + carriage return). +@item -S /path/to/socket, --socket=/path/to/socket +The socket file to use when connecting to @code{localhost} (which is the +default host). +@item --tables +Overrides option --databases (-B). +@item -T, --tab=path-to-some-directory +Creates a @code{table_name.sql} file, that contains the SQL CREATE commands, +and a @code{table_name.txt} file, that contains the data, for each give table. +@strong{NOTE}: This only works if @code{mysqldump} is run on the same +machine as the @code{mysqld} daemon. The format of the @code{.txt} file +is made according to the @code{--fields-xxx} and @code{--lines--xxx} options. +@item -u user_name, --user=user_name +The @strong{MySQL} user name to use when connecting to the server. The +default value is your Unix login name. +@item -O var=option, --set-variable var=option +Set the value of a variable. The possible variables are listed below. +@item -v, --verbose +Verbose mode. Print out more information on what the program does. +@item -V, --version +Print version information and exit. +@item -w, --where='where-condition' +Dump only selected records. Note that QUOTES are mandatory: + +@example +"--where=user='jimf'" "-wuserid>1" "-wuserid<1" +@end example +@item -O net_buffer_length=#, where # < 16M +When creating multi-row-insert statements (as with option +@code{--extended-insert} or @code{--opt}), @code{mysqldump} will create +rows up to @code{net_buffer_length} length. If you increase this +variable, you should also ensure that the @code{max_allowed_packet} +variable in the @strong{MySQL} server is bigger than the +@code{net_buffer_length}. +@end table + +The most normal use of @code{mysqldump} is probably for making a backup of +whole databases. @xref{Backup}. + +@example +mysqldump --opt database > backup-file.sql +@end example + +You can read this back into @strong{MySQL} with: + +@example +mysql database < backup-file.sql +@end example + +or + +@example +mysql -e "source /patch-to-backup/backup-file.sql" database +@end example + +However, it's also very useful to populate another @strong{MySQL} server with +information from a database: + +@example +mysqldump --opt database | mysql ---host=remote-host -C database +@end example + +It is possible to dump several databases with one command: + +@example +mysqldump --databases database1 [database2 database3...] > my_databases.sql +@end example + +If all the databases are wanted, one can use: + +@example +mysqldump --all-databases > all_databases.sql +@end example + + +@node mysqlhotcopy, mysqlimport, mysqldump, Client-Side Scripts +@subsection mysqlhotcopy, Copying MySQL Databases and Tables + +@cindex dumping, databases +@cindex databases, dumping +@cindex tables, dumping +@cindex backing up, databases + +@code{mysqlhotcopy} is a perl script that uses @code{LOCK TABLES}, +@code{FLUSH TABLES} and @code{cp} or @code{scp} to quickly make a backup +of a database. It's the fastest way to make a backup of the database, +of single tables but it can only be run on the same machine where the +database directories are. + +@example +mysqlhotcopy db_name [/path/to/new_directory] + +mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory + +mysqlhotcopy db_name./regex/ +@end example + +@code{mysqlhotcopy} supports the following options: + +@table @code +@item -?, --help +Display a help screen and exit +@item -u, --user=# +User for database login +@item -p, --password=# +Password to use when connecting to server +@item -P, --port=# +Port to use when connecting to local server +@item -S, --socket=# +Socket to use when connecting to local server +@item --allowold +Don't abort if target already exists (rename it _old) +@item --keepold +Don't delete previous (now renamed) target when done +@item --noindices +Don't include full index files in copy to make the backup smaller and faster +The indexes can later be reconstructed with @code{myisamchk -rq.}. +@item --method=# +Method for copy (@code{cp} or @code{scp}). +@item -q, --quiet +Be silent except for errors +@item --debug +Enable debug +@item -n, --dryrun +Report actions without doing them +@item --regexp=# +Copy all databases with names matching regexp +@item --suffix=# +Suffix for names of copied databases +@item --checkpoint=# +Insert checkpoint entry into specified db.table +@item --flushlog +Flush logs once all tables are locked. +@item --tmpdir=# +Temporary directory (instead of /tmp). +@end table + +You can use @code{perldoc mysqlhotcopy} to get a more complete +documentation for @code{mysqlhotcopy}. + +@code{mysqlhotcopy} reads the groups @code{[client]} and @code{[mysqlhotcopy]} +from the option files. + +To be able to execute @code{mysqlhotcopy} you need write access to the +backup directory, @code{SELECT} privilege to the tables you are about to +copy and the @strong{MySQL} @code{Reload} privilege (to be able to +execute @code{FLUSH TABLES}). + + +@node mysqlimport, mysqlshow, mysqlhotcopy, Client-Side Scripts +@subsection mysqlimport, Importing Data from Text Files + +@cindex importing, data +@cindex data, importing +@cindex files, text +@cindex text files, importing +@cindex @code{mysqlimport} + +@code{mysqlimport} provides a command-line interface to the @code{LOAD DATA +INFILE} SQL statement. Most options to @code{mysqlimport} correspond +directly to the same options to @code{LOAD DATA INFILE}. +@xref{LOAD DATA, , @code{LOAD DATA}}. + +@code{mysqlimport} is invoked like this: + +@example +shell> mysqlimport [options] database textfile1 [textfile2....] +@end example + +For each text file named on the command line, +@code{mysqlimport} strips any extension from the filename and uses the result +to determine which table to import the file's contents into. For example, +files named @file{patient.txt}, @file{patient.text}, and @file{patient} would +all be imported into a table named @code{patient}. + +@code{mysqlimport} supports the following options: + +@table @code +@item -c, --columns=... +This option takes a comma-separated list of field names as an argument. +The field list is used to create a proper @code{LOAD DATA INFILE} command, +which is then passed to @strong{MySQL}. @xref{LOAD DATA, , @code{LOAD DATA}}. + +@item -C, --compress +Compress all information between the client and the server if both support +compression. + +@item -#, --debug[=option_string] +Trace usage of the program (for debugging). + +@item -d, --delete +Empty the table before importing the text file. + +@item --fields-terminated-by=... +@itemx --fields-enclosed-by=... +@itemx --fields-optionally-enclosed-by=... +@itemx --fields-escaped-by=... +@itemx --lines-terminated-by=... +These options have the same meaning as the corresponding clauses for +@code{LOAD DATA INFILE}. @xref{LOAD DATA, , @code{LOAD DATA}}. + +@item -f, --force +Ignore errors. For example, if a table for a text file doesn't exist, +continue processing any remaining files. Without @code{--force}, +@code{mysqlimport} exits if a table doesn't exist. + +@item --help +Display a help message and exit. + +@item -h host_name, --host=host_name +Import data to the @strong{MySQL} server on the named host. The default host +is @code{localhost}. + +@item -i, --ignore +See the description for the @code{--replace} option. + +@item -l, --lock-tables +Lock @strong{ALL} tables for writing before processing any text files. This +ensures that all tables are synchronized on the server. + +@item -L, --local +Read input files from the client. By default, text files are assumed to be on +the server if you connect to @code{localhost} (which is the default host). + +@item -pyour_pass, --password[=your_pass] +The password to use when connecting to the server. If you specify +no @samp{=your_pass} part, +@code{mysqlimport} you will be prompted for a password. + +@item -P port_num, --port=port_num +The TCP/IP port number to use for connecting to a host. (This is used for +connections to hosts other than @code{localhost}, for which Unix sockets are +used.) + +@item -r, --replace +The @code{--replace} and @code{--ignore} options control handling of input +records that duplicate existing records on unique key values. If you specify +@code{--replace}, new rows replace existing rows that have the same unique key +value. If you specify @code{--ignore}, input rows that duplicate an existing +row on a unique key value are skipped. If you don't specify either option, an +error occurs when a duplicate key value is found, and the rest of the text +file is ignored. + +@item -s, --silent +Silent mode. Write output only when errors occur. + +@item -S /path/to/socket, --socket=/path/to/socket +The socket file to use when connecting to @code{localhost} (which is the +default host). + +@item -u user_name, --user=user_name +The @strong{MySQL} user name to use when connecting to the server. The +default value is your Unix login name. + +@item -v, --verbose +Verbose mode. Print out more information what the program does. + +@item -V, --version +Print version information and exit. +@end table + +Here is a sample run using @code{mysqlimport}: + +@example +$ mysql --version +mysql Ver 9.33 Distrib 3.22.25, for pc-linux-gnu (i686) +$ uname -a +Linux xxx.com 2.2.5-15 #1 Mon Apr 19 22:21:09 EDT 1999 i586 unknown +$ mysql -e 'CREATE TABLE imptest(id INT, n VARCHAR(30))' test +$ ed +a +100 Max Sydow +101 Count Dracula +. +w imptest.txt +32 +q +$ od -c imptest.txt +0000000 1 0 0 \t M a x S y d o w \n 1 0 +0000020 1 \t C o u n t D r a c u l a \n +0000040 +$ mysqlimport --local test imptest.txt +test.imptest: Records: 2 Deleted: 0 Skipped: 0 Warnings: 0 +$ mysql -e 'SELECT * FROM imptest' test ++------+---------------+ +| id | n | ++------+---------------+ +| 100 | Max Sydow | +| 101 | Count Dracula | ++------+---------------+ +@end example + + +@node mysqlshow, , mysqlimport, Client-Side Scripts +@subsection Showing Databases, Tables, and Columns + +@cindex databases, displaying +@cindex displaying, database information +@cindex tables, displaying +@cindex columns, displaying +@cindex showing, database information + +@code{mysqlshow} can be used to quickly look at which databases exist, +their tables, and the table's columns. + +With the @code{mysql} program you can get the same information with the +@code{SHOW} commands. @xref{SHOW}. + +@code{mysqlshow} is invoked like this: + +@example +shell> mysqlshow [OPTIONS] [database [table [column]]] +@end example + +@itemize @bullet +@item +If no database is given, all matching databases are shown. +@item +If no table is given, all matching tables in the database are shown. +@item +If no column is given, all matching columns and column types in the table +are shown. +@end itemize + +Note that in newer @strong{MySQL} versions, you only see those +database/tables/columns for which you have some privileges. + +If the last argument contains a shell or SQL wild-card (@code{*}, @code{?}, +@code{%} or @code{_}) then only what's matched by the wild card is shown. +This may cause some confusion when you try to display the columns for a +table with a @code{_} as in this case @code{mysqlshow} only shows you +the table names that match the pattern. This is easily fixed by +adding an extra @code{%} last on the command line (as a separate +argument). + + +@node perror, Batch Commands, Client-Side Scripts, MySQL Database Administration +@section perror, Explaining Error Codes + +@cindex error messages, displaying +@cindex perror + +@code{perror} can be used to print error message(s). @code{perror} can +be invoked like this: + +@example +shell> perror [OPTIONS] [ERRORCODE [ERRORCODE...]] + +For example: + +shell> perror 64 79 +Error code 64: Machine is not on the network +Error code 79: Can not access a needed shared library +@end example + +@code{perror} can be used to display a description for a system error +code, or an MyISAM/ISAM table handler error code. The error messages +are mostly system dependent. + + +@node Batch Commands, Log Files, perror, MySQL Database Administration +@section How to Run SQL Commands from a Text File + +@c FIX add the 'source' command + +The @code{mysql} client typically is used interactively, like this: + +@example +shell> mysql database +@end example + +However, it's also possible to put your SQL commands in a file and tell +@code{mysql} to read its input from that file. To do so, create a text +file @file{text_file} that contains the commands you wish to execute. +Then invoke @code{mysql} as shown below: + +@example +shell> mysql database < text_file +@end example + +You can also start your text file with a @code{USE db_name} statement. In +this case, it is unnecessary to specify the database name on the command +line: + +@example +shell> mysql < text_file +@end example + +@xref{Client-Side Scripts}. + + +@node Log Files, Log file maintenance, Batch Commands, MySQL Database Administration +@section The MySQL Log Files + +@cindex Log files + +@strong{MySQL} has several different log files that can help you find +out what's going on inside @code{mysqld}: + +@multitable @columnfractions .3 .7 +@item The error log @tab Problems encountering starting, running or stopping @code{mysqld}. +@item The isam log @tab Logs all changes to the ISAM tables. Used only for debugging the isam code. +@item The query log @tab Established connections and executed queries. +@item The update log @tab Deprecated: Stores all statements that changes data +@item The binary log @tab Stores all statements that changes something. Used also for replication +@item The slow log @tab Stores all queries that took more than @code{long_query_time} to execute or didn't use indexes. +@end multitable + +All logs can be found in the @code{mysqld} data directory. You can +force @code{mysqld} to reopen the log files (or in some cases +switch to a new log) by executing @code{FLUSH LOGS}. @xref{FLUSH}. + +@menu +* Error log:: +* Query log:: +* Update log:: +* Binary log:: +* Slow query log:: +@end menu + + +@node Error log, Query log, Log Files, Log Files +@subsection The Error Log + +@code{mysqld} writes all errors to the stderr, which the +@code{safe_mysqld} script redirects to a file called +@code{'hostname'.err}. (On Windows, @code{mysqld} writes this directly +to @file{\mysql\data\mysql.err}). + +This contains information indicating when @code{mysqld} was started and +stopped and also any critical errors found when running. If @code{mysqld} +dies unexpectedly and @code{safe_mysqld} needs to restart @code{mysqld}, +@code{safe_mysqld} will write a @code{restarted mysqld} row in this +file. This log also holds a warning if @code{mysqld} notices a table +that needs to be automatically checked or repaired. + +On some operating systems, the error log will contain a stack trace +for where @code{mysqld} died. This can be used to find out where +@code{mysqld} died. @xref{Using stack trace}. + + +@node Query log, Update log, Error log, Log Files +@subsection The General Query Log + +@cindex query log +@cindex files, query log + +If you want to know what happens within @code{mysqld}, you should start +it with @code{--log[=file]}. This will log all connections and queries +to the log file (by default named @file{'hostname'.log}). This log can +be very useful when you suspect an error in a client and want to know +exactly what @code{mysqld} thought the client sent to it. + +By default, the @code{mysql.server} script starts the @strong{MySQL} +server with the @code{-l} option. If you need better performance when +you start using @strong{MySQL} in a production environment, you can +remove the @code{-l} option from @code{mysql.server} or change it to +@code{--log-binary}. + +The entries in this log are written as @code{mysqld} receives the questions. +This may be different than the order in which the statements are executed. +This is in contrast to the update log and the binary log which are written +after the query is executed, but before any locks are released. + + +@node Update log, Binary log, Query log, Log Files +@subsection The Update Log + +@cindex update log +@cindex files, update log + +@strong{NOTE}: The update log is replaced by the binary +log. @xref{Binary log}. With this you can do anything that you can do +with the update log. + +When started with the @code{--log-update[=file_name]} option, +@code{mysqld} writes a log file containing all SQL commands that update +data. If no filename is given, it defaults to the name of the host +machine. If a filename is given, but it doesn't contain a path, the file +is written in the data directory. If @file{file_name} doesn't have an +extension, @code{mysqld} will create log file names like so: +@file{file_name.###}, where @code{###} is a number that is incremented each +time you execute @code{mysqladmin refresh}, execute @code{mysqladmin +flush-logs}, execute the @code{FLUSH LOGS} statement, or restart the server. + +@strong{NOTE:} For the above scheme to work, you should NOT create +your own files with the same filename as the update log + some extensions +that may be regarded as a number, in the directory used by the update log! + +If you use the @code{--log} or @code{-l} options, @code{mysqld} writes a +general log with a filename of @file{hostname.log}, and restarts and +refreshes do not cause a new log file to be generated (although it is closed +and reopened). In this case you can copy it (on Unix) by doing: + +@example +mv hostname.log hostname-old.log +mysqladmin flush-logs +cp hostname-old.log to-backup-directory +rm hostname-old.log +@end example + +Update logging is smart because it logs only statements that really update +data. So an @code{UPDATE} or a @code{DELETE} with a @code{WHERE} that finds no +rows is not written to the log. It even skips @code{UPDATE} statements that +set a column to the value it already has. + +The update logging is done immediately after a query completes but before +any locks are released or any commit is done. This ensures that the log +will be logged in the execution order. + +If you want to update a database from update log files, you could do the +following (assuming your update logs have names of the form +@file{file_name.###}): + +@example +shell> ls -1 -t -r file_name.[0-9]* | xargs cat | mysql +@end example + +@code{ls} is used to get all the log files in the right order. + +This can be useful if you have to revert to backup files after a crash +and you want to redo the updates that occurred between the time of the backup +and the crash. + + +@node Binary log, Slow query log, Update log, Log Files +@subsection The Binary Update Log + +@cindex binary log +@cindex files, binary log + +In the future the binary log will replace the update log, so we +recommend you to switch to this log format as soon as possible! + +The binary log contains all information that is available in the update +log in a more efficient format. It also contains information about how long +every query that updated the database took. + +The binary log is also used when you are replicating a slave from a master. +@xref{Replication}. + +When started with the @code{--log-bin[=file_name]} option, @code{mysqld} +writes a log file containing all SQL commands that update data. If no +file name is given, it defaults to the name of the host machine followed +by @code{-bin}. If file name is given, but it doesn't contain a path, the +file is written in the data directory. + +You can use the following options to @code{mysqld} to affect what is logged +to the binary log: + +@multitable @columnfractions .4 .6 +@item @code{binlog-do-db=database_name} @tab +Tells the master it should log updates for the specified database, and +exclude all others not explicitly mentioned. +(Example: @code{binlog-do-db=some_database}) + +@item @code{binlog-ignore-db=database_name} @tab +Tells the master that updates to the given database should not be logged +to the binary log (Example: @code{binlog-ignore-db=some_database}) +@end multitable + +To the binary log filename @code{mysqld} will append an extension that is a +number that is incremented each time you execute @code{mysqladmin +refresh}, execute @code{mysqladmin flush-logs}, execute the @code{FLUSH LOGS} +statement or restart the server. + +To be able to know which different binary log files have been used, +@code{mysqld} will also create a binary log index file that +contains the name of all used binary log files. By default this has the +same name as the binary log file, with the extension @code{'.index'}. +You can change the name of the binary log index file with the +@code{--log-bin-index=[filename]} option. + +If you are using replication, you should not delete old binary log +files until you are sure that no slave will ever need to use them. +One way to do this is to do @code{mysqladmin flush-logs} once a day and then +remove any logs that are more than 3 days old. + +You can examine the binary log file with the @code{mysqlbinlog} command. +For example, you can update a @strong{MySQL} server from the binary log +as follows: + +@example +mysqlbinlog log-file | mysql -h server_name +@end example + +You can also use the @code{mysqlbinlog} program to read the binary log +directly from a remote @strong{MySQL} server! + +@code{mysqlbinlog --help} will give you more information of how to use +this program! + +If you are using @code{BEGIN [WORK]} or @code{SET AUTOCOMMIT=0}, you must +use the @strong{MySQL} binary log for backups instead of the old update log. + +The binary logging is done immediately after a query completes but before +any locks are released or any commit is done. This ensures that the log +will be logged in the execution order. + +All updates (@code{UPDATE}, @code{DELETE} or @code{INSERT}) that change +a transactional table (like BDB tables) are cached until a @code{COMMIT}. +Any updates to a non-transactional table are stored in the binary log at +once. Every thread will, on start, allocate a buffer of +@code{binlog_cache_size} to buffer queries. If a query is bigger than +this, the thread will open a temporary file to handle the bigger cache. +The temporary file will be deleted when the thread ends. + +The @code{max_binlog_cache_size} can be used to restrict the total size used +to cache a multi-transaction query. + +If you are using the update or binary log, concurrent inserts will +not work together with @code{CREATE ... INSERT} and @code{INSERT ... SELECT}. +This is to ensure that you can recreate an exact copy of your tables by +applying the log on a backup. + + +@node Slow query log, , Binary log, Log Files +@subsection The Slow Query Log + +@cindex slow query log +@cindex files, slow query log + +When started with the @code{--log-slow-queries[=file_name]} option, +@code{mysqld} writes a log file containing all SQL commands that took +more than @code{long_query_time} to execute. The time to get the initial +table locks are not counted as execution time. + +The slow query log is logged after the query is executed and after all +locks has been released. This may be different than the order in which +the statements are executed. + +If no file name is given, it defaults to the name of the host machine +suffixed with @code{-slow.log}. If a filename is given, but doesn't +contain a path, the file is written in the data directory. + +The slow query log can be used to find queries that take a long time to +execute and are thus candidates for optimization. With a large log, that +can become a difficult task. You can pipe the slow query log through the +@code{mysqldumpslow} command to get a summary of the queries which +appear in the log. + +You are using @code{--log-long-format} then also queries that are not +using indexes are printed. @xref{Command-line options}. + + +@node Log file maintenance, Replication, Log Files, MySQL Database Administration +@section Log File Maintenance + +@cindex files, log +@cindex maintaining, log files +@cindex log files, maintaining + +@strong{MySQL} has a lot of log files which make it easy to see what is +going. @xref{Log Files}. One must however from time to time clean up +after @code{MysQL} to ensure that the logs don't take up too much disk +space. + +When using @strong{MySQL} with log files, you will, from time to time, +want to remove/backup old log files and tell @strong{MySQL} to start +logging on new files. @xref{Backup}. + +On a Linux (@code{Redhat}) installation, you can use the +@code{mysql-log-rotate} script for this. If you installed @strong{MySQL} +from an RPM distribution, the script should have been installed +automatically. Note that you should be careful with this if you are using +the log for replication! + +On other systems you must install a short script yourself that you +start from @code{cron} to handle log files. + +You can force @strong{MySQL} to start using new log files by using +@code{mysqladmin flush-logs} or by using the SQL command @code{FLUSH LOGS}. +If you are using @strong{MySQL} Version 3.21 you must use @code{mysqladmin refresh}. + +The above command does the following: + +@itemize @bullet +@item +If standard logging (@code{--log}) or slow query logging +(@code{--log-slow-queries}) is used, closes and reopens the log file. +(@file{mysql.log} and @file{`hostname`-slow.log} as default). +@item +If update logging (@code{--log-update}) is used, closes the update log and +opens a new log file with a higher sequence number. +@end itemize + +If you are using only an update log, you only have to flush the logs and then +move away the old update log files to a backup. +If you are using the normal logging, you can do something like: + +@example +shell> cd mysql-data-directory +shell> mv mysql.log mysql.old +shell> mysqladmin flush-logs +@end example + +and then take a backup and remove @file{mysql.old}. + + +@node Replication, Replication HOWTO, Log file maintenance, MySQL Database Administration +@section Replication in MySQL + +@cindex replication +@cindex increasing, speed +@cindex speed, increasing +@cindex databases, replicating + +@menu +* Replication Intro:: +* Replication Implementation:: +@end menu + +This chapter describes the various replication features in @strong{MySQL}. +It serves as a reference to the options available with replication. +You will be introduced to replication and learn how to implement it. +Towards the end, there are some frequently asked questions and descriptions +of problems and how to solve them. + + +@node Replication Intro, Replication Implementation, Replication, Replication +@subsection Introduction + +One way replication can be used is to increase both robustness and +speed. For robustness you can have two systems and can switch to the backup if +you have problems with the master. The extra speed is achieved by +sending a part of the non-updating queries to the replica server. Of +course this only works if non-updating queries dominate, but that is the +normal case. + +Starting in Version 3.23.15, @strong{MySQL} supports one-way replication +internally. One server acts as the master, while the other acts as the +slave. Note that one server could play the roles of master in one pair +and slave in the other. The master server keeps a binary log of updates +(@xref{Binary log}.) and an index file to binary logs to keep track of +log rotation. The slave, upon connecting, informs the master where it +left off since the last successfully propagated update, catches up on +the updates, and then blocks and waits for the master to notify it of +the new updates. + +Note that if you are replicating a database, all updates to this +database should be done through the master! + +On older servers one can use the update log to do simple replication. +@xref{Log Replication}. + +Another benefit of using replication is that one can get live backups of +the system by doing a backup on a slave instead of doing it on the +master. @xref{Backup}. + + +@node Replication Implementation, , Replication Intro, Replication +@subsection Replication Implementation Overview + +@cindex master-slave setup + +@strong{MySQL} replication is based on the server keeping track of all +changes to your database (updates, deletes, etc) in the binary +log. (@xref{Binary log}.) and the slave server(s) reading the saved +queries from the master server's binary log so that the slave can +execute the same queries on its copy of the data. + +It is @strong{very important} to realize that the binary log is simply a +record starting from a fixed point in time (the moment you enable binary +logging). Any slaves which you set up will need copies of all the data +from your master as it existed the moment that you enabled binary +logging on the master. If you start your slaves with data that doesn't +agree with what was on the master @strong{when the binary log was +started}, your slaves may fail. + +A future version (4.0) of @strong{MySQL} will remove the need to keep a +(possibly large) snapshot of data for new slaves that you might wish to +set up through the live backup functionality with no locking required. +However, at this time, it is necessary to block all writes either with a +global read lock or by shutting down the master while taking a snapshot. + +Once a slave is properly configured and running, it will simply connect +to the master and wait for updates to process. If the master goes away +or the slave loses connectivity with your master, it will keep trying to +connect every @code{master-connect-retry} seconds until it is able to +reconnect and resume listening for updates. + +Each slave keeps track of where it left off. The master server has no +knowledge of how many slaves there are or which ones are up-to-date at +any given time. + +The next section explains the master/slave setup process in more detail. + + +@node Replication HOWTO, , Replication, MySQL Database Administration +@section How To Set Up Replication + +Below is a quick description of how to set up complete replication on +your current @strong{MySQL} server. It assumes you want to replicate all +your databases and have not configured replication before. You will need +to shutdown your master server briefly to complete the steps outlined +below. + +@enumerate +@item +Make sure you have a recent version of @strong{MySQL} installed on the master +and slave(s). + +Use Version 3.23.29 or higher. Previous releases used a different binary +log format and had bugs which have been fixed in newer releases. Please, +do not report bugs until you have verified that the problem is present +in the latest release. + +@item +Set up special a replication user on the master with the @code{FILE} +privilege and permission to connect from all the slaves. If the user is +only doing replication (which is recommended), you don't need to grant any +additional privileges. + +For example, to create a user named @code{repl} which can access your +master from any host, you might use this command: + +@example +GRANT FILE ON *.* TO repl@@"%" IDENTIFIED BY ''; +@end example + +@item +Shut down @strong{MySQL} on the master. + +@example +mysqladmin -u root -p shutdown +@end example + +@item +Snapshot all the data on your master server. + +The easiest way to do this (on Unix) is to simply use @strong{tar} to +produce an archive of your entire data directory. The exact data +directory location depends on your installation. + +@example +tar -cvf /tmp/mysql-snapshot.tar /path/to/data-dir +@end example + +Windows users can use WinZip or similar software to create an archive of +the data directory. + +@item +In @code{my.cnf} on the master add @code{log-bin} and +@code{server-id=unique number} to the @code{[mysqld]} section and +restart it. It is very important that the id of the slave is different from +the id of the master. Think of @code{server-id} as something similar +to the IP address - it uniquely identifies the server instance in the +community of replication partners. + +@example +[mysqld] +log-bin +server-id=1 +@end example + +@item +Restart @strong{MySQL} on the master. + +@item +Add the following to @code{my.cnf} on the slave(s): + +@example +master-host= +master-user= +master-password= +master-port= +server-id= +@end example + +replacing the values in <> with what is relevant to your system. + +@code{server-id} must be different for each server participating in +replication. If you don't specify a server-id, it will be set to 1 if +you have not defined @code{master-host}, else it will be set to 2. Note +that in the case of @code{server-id} omission the master will refuse +connections from all slaves, and the slave will refuse to connect to a +master. Thus, omitting @code{server-id} is only good for backup with a +binary log. + + +@item +Copy the snapshot data into your data directory on your slave(s). Make +sure that the privileges on the files and directories are correct. The +user which @strong{MySQL} runs as needs to be able to read and write to +them, just as on the master. + +@item Restart the slave(s). + +@end enumerate + +After you have done the above, the slave(s) should connect to the master +and catch up on any updates which happened since the snapshot was taken. + +If you have forgotten to set @code{server-id} for the slave you will get +the following error in the error log file: + +@example +Warning: one should set server_id to a non-0 value if master_host is set. +The server will not act as a slave. +@end example + +If you have forgot to do this for the master, the slaves will not be +able to connect to the master. + +If a slave is not able to replicate for any reason, you will find error +messages in the error log on the slave. + +Once a slave is replicating, you will find a file called +@code{master.info} in the same directory as your error log. The +@code{master.info} file is used by the slave to keep track of how much +of the master's binary log is has processed. @strong{Do not} remove or +edit the file, unless you really know what you are doing. Even in that case, +it is preferred that you use @code{CHANGE MASTER TO} command. + + +@menu +* Replication Features:: +* Replication Options:: +* Replication SQL:: +* Replication FAQ:: +* Replication Problems:: +@end menu + +@node Replication Features, Replication Options, Replication HOWTO, Replication HOWTO +@subsection Replication Features and Known Problems + +@cindex options, replication +@cindex @code{my.cnf} file +@cindex files,@code{my.cnf} + +Below is an explanation of what is supported and what is not: + +@itemize @bullet +@item +Replication will be done correctly with @code{AUTO_INCREMENT}, +@code{LAST_INSERT_ID}, and @code{TIMESTAMP} values. +@item +@code{RAND()} in updates does not replicate properly. Use +@code{RAND(some_non_rand_expr)} if you are replicating updates with +@code{RAND()}. You can, for example, use @code{UNIX_TIMESTAMP()} for the +argument to @code{RAND()}. +@item +You have to use the same character set (@code{--default-character-set}) +on the master and the slave. If not, you may get duplicate key errors on +the slave, because a key that is regarded as unique on the master may +not be that in the other character set. +@item +@code{LOAD DATA INFILE} will be handled properly as long as the file +still resides on the master server at the time of update +propagation. @code{LOAD LOCAL DATA INFILE} will be skipped. +@item +Update queries that use user variables are not replication-safe (yet). +@item +@code{FLUSH} commands are not stored in the binary log and are because +of this not replicated to the slaves. This is not normally a problem as +@code{FLUSH} doesn't change anything. This does however mean that if you +update the @code{MySQL} privilege tables directly without using +@code{GRANT} statement and you replicate the @code{MySQL} privilege +database, you must do a @code{FLUSH PRIVILEGES} on your slaves to put +the new privileges into effect. +@item +Temporary tables starting in 3.23.29 are replicated properly with the +exception of the case when you shut down slave server ( not just slave thread), +you have some temporary tables open, and the are used in subsequent updates. +To deal with this problem, to shut down the slave, do @code{SLAVE STOP}, then +check @code{Slave_open_temp_tables} variable to see if it is 0, then issue +@code{mysqladmin shutdown}. If the number is not 0, restart the slave thread +with @code{SLAVE START} and see +if you have better luck next time. There will be a cleaner solution, but it +has to wait until version 4.0. +In earlier versions temporary tables are not being replicated properly - we +recommend that you either upgrade, or execute @code{SET SQL_LOG_BIN=0} on +your clients before all queries with temp tables. +@item +@strong{MySQL} only supports one master and many slaves. We will in 4.x +add a voting algorithm to automatically change master if something goes +wrong with the current master. We will also introduce 'agent' processes +to help doing load balancing by sending select queries to different +slaves. +@item +Starting in Version 3.23.26, it is safe to connect servers in a circular +master-slave relationship with @code{log-slave-updates} enabled. +Note, however, that many queries will not work right in this kind of +setup unless your client code is written to take care of the potential +problems that can happen from updates that occur in different sequence +on different servers. + +This means that you can do a setup like the following: + +@example +A -> B -> C -> A +@end example + +This setup will only works if you only do non conflicting updates +between the tables. In other words, if you insert data in A and C, you +should never insert a row in A that may have a conflicting key with a +row insert in C. You should also not update the sam rows on two servers +if the order in which the updates are applied matters. + +Note that the log format has changed in Version 3.23.26 so that +pre-3.23.26 slaves will not be able to read it. +@item +If the query on the slave gets an error, the slave thread will +terminate, and a message will appear in the @code{.err} file. You should +then connect to the slave manually, fix the cause of the error (for +example, non-existent table), and then run @code{SLAVE START} sql +command (available starting in Version 3.23.16). In Version 3.23.15, you +will have to restart the server. +@item +If connection to the master is lost, the slave will retry immediately, +and then in case of failure every @code{master-connect-retry} (default +60) seconds. Because of this, it is safe to shut down the master, and +then restart it after a while. The slave will also be able to deal with +network connectivity outages. +@item +Shutting down the slave (cleanly) is also safe, as it keeps track of +where it left off. Unclean shutdowns might produce problems, especially +if disk cache was not synced before the system died. Your system fault +tolerance will be greatly increased if you have a good UPS. +@item +If the master is listening on a non-standard port, you will also need to +specify this with @code{master-port} parameter in @code{my.cnf} . +@item +In Version 3.23.15, all of the tables and databases will be +replicated. Starting in Version 3.23.16, you can restrict replication to +a set of databases with @code{replicate-do-db} directives in +@code{my.cnf} or just exclude a set of databases with +@code{replicate-ignore-db}. Note that up until Version 3.23.23, there was a bug +that did not properly deal with @code{LOAD DATA INFILE} if you did it in +a database that was excluded from replication. +@item +Starting in Version 3.23.16, @code{SET SQL_LOG_BIN = 0} will turn off +replication (binary) logging on the master, and @code{SET SQL_LOG_BIN = +1} will turn in back on - you must have the process privilege to do +this. +@item +Starting in Version 3.23.19, you can clean up stale replication leftovers when +something goes wrong and you want a clean start with @code{FLUSH MASTER} +and @code{FLUSH SLAVE} commands. In Version 3.23.26 we have renamed them to +@code{RESET MASTER} and @code{RESET SLAVE} respectively to clarify +what they do. The old @code{FLUSH} variants still work, though, for +compatibility. + +@item +Starting in Version 3.23.21, you can use @code{LOAD TABLE FROM MASTER} for +network backup and to set up replication initially. We have recently +received a number of bug reports concerning it that we are investigating, so +we recommend that you use it only in testing until we make it more stable. +@item +Starting in Version 3.23.23, you can change masters and adjust log position +with @code{CHANGE MASTER TO}. +@item +Starting in Version 3.23.23, you tell the master that updates in certain +databases should not be logged to the binary log with @code{binlog-ignore-db}. +@item +Starting in Version 3.23.26, you can use @code{replicate-rewrite-db} to tell +the slave to apply updates from one database on the master to the one +with a different name on the slave. +@item +Starting in Version 3.23.28, you can use @code{PURGE MASTER LOGS TO 'log-name'} +to get rid of old logs while the slave is running. +@end itemize + + +@node Replication Options, Replication SQL, Replication Features, Replication HOWTO +@subsection Replication Options in my.cnf + +If you are using replication, we recommend you to use @strong{MySQL} Version +3.23.30 or later. Older versions work, but they do have some bugs and are +missing some features. + +On both master and slave you need to use the @code{server-id} option. +This sets an unique replication id. You should pick a unique value in the +range between 1 to 2^32-1 for each master and slave. +Example: @code{server-id=3} + +The following table has the options you can use for the @strong{MASTER}: + +@multitable @columnfractions .3 .7 + +@item @strong{Option} @tab @strong{Description} +@item @code{log-bin=filename} @tab +Write to a binary update log to the specified location. Note that if you +give it a parameter with an extension (for example, +@code{log-bin=/mysql/logs/replication.log} ) versions up to 3.23.24 will +not work right during replication if you do @code{FLUSH LOGS} . The +problem is fixed in Version 3.23.25. If you are using this kind of log +name, @code{FLUSH LOGS} will be ignored on binlog. To clear the log, run +@code{FLUSH MASTER}, and do not forget to run @code{FLUSH SLAVE} on all +slaves. In Version 3.23.26 and in later versions you should use +@code{RESET MASTER} and @code{RESET SLAVE} + +@item @code{log-bin-index=filename} @tab +Because the user could issue the @code{FLUSH LOGS} command, we need to +know which log is currently active and which ones have been rotated out +and in what sequence. This information is stored in the binary log index file. +The default is `hostname`.index. You can use this option if you want to +be a rebel. (Example: @code{log-bin-index=db.index}) + +@item @code{sql-bin-update-same} @tab +If set, setting @code{SQL_LOG_BIN} to a value will automatically set +@code{SQL_LOG_UPDATE} to the same value and vice versa. + +@item @code{binlog-do-db=database_name} @tab +Tells the master it should log updates for the specified database, and +exclude all others not explicitly mentioned. +(Example: @code{binlog-do-db=some_database}) + +@item @code{binlog-ignore-db=database_name} @tab +Tells the master that updates to the given database should not be logged +to the binary log (Example: @code{binlog-ignore-db=some_database}) +@end multitable + +The following table has the options you can use for the @strong{SLAVE}: + +@multitable @columnfractions .3 .7 + +@item @strong{Option} @tab @strong{Description} +@item @code{master-host=host} @tab +Master hostname or IP address for replication. If not set, the slave +thread will not be started. +(Example: @code{master-host=db-master.mycompany.com}) + +@item @code{master-user=username} @tab +The user the slave thread will us for authentication when connecting to +the master. The user must have @code{FILE} privilege. If the master user +is not set, user @code{test} is assumed. (Example: +@code{master-user=scott}) + +@item @code{master-password=password} @tab +The password the slave thread will authenticate with when connecting to +the master. If not set, an empty password is assumed. (Example: +@code{master-password=tiger}) + +@item @code{master-port=portnumber} @tab +The port the master is listening on. If not set, the compiled setting of +@code{MYSQL_PORT} is assumed. If you have not tinkered with +@code{configure} options, this should be 3306. (Example: +@code{master-port=3306}) + +@item @code{master-connect-retry=seconds} @tab +The number of seconds the slave thread will sleep before retrying to +connect to the master in case the master goes down or the connection is +lost. Default is 60. (Example: @code{master-connect-retry=60}) + +@item @code{master-info-file=filename} @tab +The location of the file that remembers where we left off on the master +during the replication process. The default is master.info in the data +directory. Sasha: The only reason I see for ever changing the default +is the desire to be rebelious. (Example: +@code{master-info-file=master.info}) + +@item @code{replicate-do-table=db_name.table_name} @tab +Tells the slave thread to restrict replication to the specified database. +To specify more than one table, use the directive multiple times, +once for each table. . +(Example: @code{replicate-do-table=some_db.some_table}) + +@item @code{replicate-ignore-table=db_name.table_name} @tab +Tells the slave thread to not replicate to the specified table. To +specify more than one table to ignore, use the directive multiple +times, once for each table.(Example: +@code{replicate-ignore-table=db_name.some_table}) + +@item @code{replicate-wild-do-table=db_name.table_name} @tab +Tells the slave thread to restrict replication to the tables that match the +specified wildcard pattern. . +To specify more than one table, use the directive multiple times, +once for each table. . +(Example: @code{replicate-do-table=foo%.bar%} will replicate only updates +to tables in all databases that start with foo and whose table names +start with bar) + +@item @code{replicate-wild-ignore-table=db_name.table_name} @tab +Tells the slave thread to not replicate to the tables that match the given +wild card pattern. To +specify more than one table to ignore, use the directive multiple +times, once for each table.(Example: +@code{replicate-ignore-table=foo%.bar%} - will not upates to tables in all databases that start with foo and whose table names +start with bar) + +@item @code{replicate-ignore-db=database_name} @tab +Tells the slave thread to not replicate to the specified database. To +specify more than one database to ignore, use the directive multiple +times, once for each database. This option will not work if you use cross +database updates. If you need cross database updates to work, make sure +you have 3.23.28 or later, and use +@code{replicate-wild-ignore-table=db_name.%}(Example: +@code{replicate-ignore-db=some_db}) + +@item @code{replicate-do-db=database_name} @tab +Tells the slave thread to restrict replication to the specified database. +To specify more than one database, use the directive multiple times, +once for each database. Note that this will only work if you do not use +cross-database queries such as @code{UPDATE some_db.some_table SET +foo='bar'} while having selected a different or no database. If you need +cross database updates to work, make sure +you have 3.23.28 or later, and use +@code{replicate-wild-do-table=db_name.%} +(Example: @code{replicate-do-db=some_db}) + +@item @code{log-slave-updates} @tab +Tells the slave to log the updates from the slave thread to the binary +log. Off by default. You will need to turn it on if you plan to +daisy-chain the slaves. + +@item @code{replicate-rewrite-db=from_name->to_name} @tab +Updates to a database with a different name than the original (Example: +@code{replicate-rewrite-db=master_db_name->slave_db_name} + +@item @code{skip-slave-start} @tab +Tells the slave server not to start the slave on the startup. The user +can start it later with @code{SLAVE START}. + +@item @code{slave_read_timeout=#} +Number of seconds to wait for more data from the master before aborting +the read. +@end multitable + + +@node Replication SQL, Replication FAQ, Replication Options, Replication HOWTO +@subsection SQL Commands Related to Replication + +@cindex SQL commands, replication +@cindex commands, replication +@cindex replication, commands + +Replication can be controlled through the SQL interface. Below is the +summary of commands: + +@multitable @columnfractions .30 .70 +@item @strong{Command} @tab @strong{Description} + +@item @code{SLAVE START} + @tab Starts the slave thread. (Slave) + +@item @code{SLAVE STOP} + @tab Stops the slave thread. (Slave) + +@item @code{SET SQL_LOG_BIN=0} + @tab Disables update logging if the user has process privilege. + Ignored otherwise. (Master) + +@item @code{SET SQL_LOG_BIN=1} + @tab Re-enables update logging if the user has process privilege. + Ignored otherwise. (Master) + +@item @code{SET SQL_SLAVE_SKIP_COUNTER=n} + @tab Skip the next @code{n} events from the master. Only valid when +the slave thread is not running, otherwise, gives an error. Useful for +recovering from replication glitches. + +@item @code{RESET MASTER} + @tab Deletes all binary logs listed in the index file, resetting the binlog +index file to be empty. In pre-3.23.26 versions, @code{FLUSH MASTER} (Master) + +@item @code{RESET SLAVE} + @tab Makes the slave forget its replication position in the master +logs. In pre 3.23.26 versions the command was called +@code{FLUSH SLAVE}(Slave) + +@item @code{LOAD TABLE tblname FROM MASTER} + @tab Downloads a copy of the table from master to the slave. (Slave) + +@item @code{CHANGE MASTER TO master_def_list} + @tab Changes the master parameters to the values specified in +@code{master_def_list} and restarts the slave thread. @code{master_def_list} +is a comma-separated list of @code{master_def} where @code{master_def} is +one of the following: @code{MASTER_HOST}, @code{MASTER_USER}, +@code{MASTER_PASSWORD}, @code{MASTER_PORT}, @code{MASTER_CONNECT_RETRY}, +@code{MASTER_LOG_FILE}, @code{MASTER_LOG_POS}. Example: + +@example + +CHANGE MASTER TO + MASTER_HOST='master2.mycompany.com', + MASTER_USER='replication', + MASTER_PASSWORD='bigs3cret', + MASTER_PORT=3306, + MASTER_LOG_FILE='master2-bin.001', + MASTER_LOG_POS=4; + +@end example + +You only need to specify the values that need to be changed. The values that +you omit will stay the same with the exception of when you change the host or +the port. In that case, the slave will assume that since you are connecting to +a different host or a different port, the master is different. Therefore, the +old values of log and position are not applicable anymore, and will +automatically be reset to an empty string and 0, respectively (the start +values). Note that if you restart the slave, it will remember its last master. +If this is not desirable, you should delete the @file{master.info} file before +restarting, and the slave will read its master from @code{my.cnf} or the +command line. (Slave) + +@item @code{SHOW MASTER STATUS} @tab Provides status information on the binlog of the master. (Master) + +@item @code{SHOW SLAVE STATUS} @tab Provides status information on essential parameters of the slave thread. (Slave) +@item @code{SHOW MASTER LOGS} @tab Only available starting in Version 3.23.28. Lists the binary logs on the master. You should use this command prior to @code{PURGE MASTER LOGS TO} to find out how far you should go. + +@item @code{PURGE MASTER LOGS TO 'logname'} + @tab Available starting in Version 3.23.28. Deletes all the +replication logs that are listed in the log +index as being prior to the specified log, and removed them from the +log index, so that the given log now becomes first. Example: + +@example +PURGE MASTER LOGS TO 'mysql-bin.010' +@end example + +This command will do nothing and fail with an error if you have an +active slave that is currently reading one of the logs you are trying to +delete. However, if you have a dormant slave, and happen to purge one of +the logs it wants to read, the slave will be unable to replicate once it +comes up. The command is safe to run while slaves are replicating - you +do not need to stop them. + +You must first check all the slaves with @code{SHOW SLAVE STATUS} to +see which log they are on, then do a listing of the logs on the +master with @code{SHOW MASTER LOGS}, find the earliest log among all +the slaves (if all the slaves are up to date, this will be the +last log on the list), backup all the logs you are about to delete +(optional) and purge up to the target log. + +@end multitable + + +@node Replication FAQ, Replication Problems, Replication SQL, Replication HOWTO +@subsection Replication FAQ + +@cindex @code{Binlog_Dump} +@strong{Q}: Why do I sometimes see more than one @code{Binlog_Dump} thread on +the master after I have restarted the slave? + +@strong{A}: @code{Binlog_Dump} is a continuous process that is handled by the +server in the following way: + +@itemize @bullet +@item +Catch up on the updates. +@item +Once there are no more updates left, go into @code{pthread_cond_wait()}, +from which we can be awakened either by an update or a kill. +@item +On wake up, check the reason. If we are not supposed to die, continue +the @code{Binlog_dump} loop. +@item +If there is some fatal error, such as detecting a dead client, +terminate the loop. +@end itemize + +So if the slave thread stops on the slave, the corresponding +@code{Binlog_Dump} thread on the master will not notice it until after +at least one update to the master (or a kill), which is needed to wake +it up from @code{pthread_cond_wait()}. In the meantime, the slave +could have opened another connection, which resulted in another +@code{Binlog_Dump} thread. + +The above problem should not be present in Version 3.23.26 and later +versions. In Version 3.23.26 we added @code{server-id} to each +replication server, and now all the old zombie threads are killed on the +master when a new replication thread connects from the same slave + +@strong{Q}: How do I rotate replication logs? + +@strong{A}: In Version 3.23.28 you should use @code{PURGE MASTER LOGS +TO} command after determining which logs can be deleted, and optionally +backing them up first. In earlier versions the process is much more +painful, and cannot be safely done without stopping all the slaves in +the case that you plan to re-use log names. You will need to stop the +slave threads, edit the binary log index file, delete all the old logs, +restart the master, start slave threads, and then remove the old log files. + + +@strong{Q}: How do I upgrade on a hot replication setup? + +@strong{A}: If you are upgrading pre-3.23.26 versions, you should just +lock the master tables, let the slave catch up, then run @code{FLUSH +MASTER} on the master, and @code{FLUSH SLAVE} on the slave to reset the +logs, then restart new versions of the master and the slave. Note that +the slave can stay down for some time - since the master is logging +all the updates, the slave will be able to catch up once it is up and +can connect. + +After 3.23.26, we have locked the replication protocol for modifications, so +you can upgrade masters and slave on the fly to a newer 3.23 version and you +can have different versions of @strong{MySQL} running on the slave and the +master, as long as they are both newer than 3.23.26. + +@cindex replication, two-way +@strong{Q}: What issues should I be aware of when setting up two-way +replication? + +@strong{A}: @strong{MySQL} replication currently does not support any +locking protocol between master and slave to guarantee the atomicity of +a distributed (cross-server) update. In in other words, it is possible +for client A to make an update to co-master 1, and in the meantime, +before it propagates to co-master 2, client B could make an update to +co-master 2 that will make the update of client A work differently than +it did on co-master 1. Thus when the update of client A will make it +to co-master 2, it will produce tables that will be different than +what you have on co-master 1, even after all the updates from co-master +2 have also propagated. So you should not co-chain two servers in a +two-way replication relationship, unless you are sure that you updates +can safely happen in any order, or unless you take care of mis-ordered +updates somehow in the client code. + + +You must also realize that two-way replication actually does not improve +performance very much, if at all, as far as updates are concerned. Both +servers need to do the same amount of updates each, as you would have +one server do. The only difference is that there will be a little less +lock contention, because the updates originating on another server will +be serialized in one slave thread. This benefit, though, might be +offset by network delays. + +@cindex performance, improving +@cindex increasing, performance +@strong{Q}: How can I use replication to improve performance of my system? + +@strong{A}: You should set up one server as the master, and direct all +writes to it, and configure as many slaves as you have the money and +rackspace for, distributing the reads among the master and the slaves. +You can also start the slaves with @code{--skip-bdb}, +@code{--low-priority-updates} and @code{--delay-key-write-for-all-tables} +to get speed improvements for the slave. In this case the slave will +use non-transactional @code{MyISAM} tables instead of @code{BDB} tables +to get more speed. + +@strong{Q}: What should I do to prepare my client code to use +performance-enhancing replication? + +@strong{A}: +If the part of your code that is responsible for database access has +been properly abstracted/modularized, converting it to run with the +replicated setup should be very smooth and easy - just change the +implementation of your database access to read from some slave or the +master, and to always write to the master. If your code does not have +this level of abstraction, +setting up a replicated system will give you an opportunity/motivation +to it clean up. + You should start by creating a wrapper library +/module with the following functions: + +@itemize +@item +@code{safe_writer_connect()} +@item +@code{safe_reader_connect()} +@item +@code{safe_reader_query()} +@item +@code{safe_writer_query()} +@end itemize + +@code{safe_} means that the function will take care of handling all +the error conditions. + +You should then convert your client code to use the wrapper library. +It may be a painful and scary process at first, but it will pay off in +the long run. All applications that follow the above pattern will be +able to take advantage of one-master/many slaves solution. The +code will be a lot easier to maintain, and adding troubleshooting +options will be trivial. You will just need to modify one or two +functions, for example, to log how long each query took, or which +query, among your many thousands, gave you an error. If you have written a lot of code already, +you may want to automate the conversion task by using Monty's +@code{replace} utility, which comes with the standard distribution of +@strong{MySQL}, or just write your own Perl script. Hopefully, your +code follows some recognizable pattern. If not, then you are probably +better off re-writing it anyway, or at least going through and manually +beating it into a pattern. + +Note that, of course, you can use different names for the +functions. What is important is having unified interface for connecting +for reads, connecting for writes, doing a read, and doing a write. + + +@strong{Q}: When and how much can @strong{MySQL} replication improve the performance +of my system? + +@strong{A}: @strong{MySQL} replication is most beneficial for a system +with frequent reads and not so frequent writes. In theory, by using a +one master/many slaves setup you can scale by adding more slaves until +you either run out of network bandwidth, or your update +load grows to the point +that the master cannot handle it. + +In order to determine how many slaves you can get before the added +benefits begin to level out, and how much you can improve performance +of your site, you need to know your query patterns, and empirically + (by benchmarking) determine the relationship between the throughput +on reads (reads per second, or @code{max_reads}) and on writes +@code{max_writes}) on a typical master and a typical slave. The +example below will show you a rather simplified calculation of what you +can get with replication for our imagined system. + +Let's say our system load consists of 10% writes and 90% reads, and we +have determined that @code{max_reads} = 1200 - 2 * @code{max_writes}, +or in other words, our system can do 1200 reads per second with no +writes, our average write is twice as slow as average read, +and the relationship is +linear. Let us suppose that our master and slave are of the same +capacity, and we have N slaves and 1 master. Then we have for each +server (master or slave): + +@code{reads = 1200 - 2 * writes} (from bencmarks) + +@code{reads = 9* writes / (N + 1) } (reads split, but writes go +to all servers) + +@code{9*writes/(N+1) + 2 * writes = 1200} + +@code{writes = 1200/(2 + 9/(N+1)} + +So if N = 0, which means we have no replication, our system can handle +1200/11, about 109 writes per second (which means we will have 9 times +as many reads due to the nature of our application). + +If N = 1, we can get up to 184 writes per second. + +If N = 8, we get up to 400. + +If N = 17, 480 writes. + +Eventually as N approaches infinity (and our budget negative infinity), +we can get very close to 600 writes per second, increasing system +throughput about 5.5 times. However, with only 8 servers, we increased +it almost 4 times already. + +Note that our computations assumed infinite network bandwidth, and +neglected several other factors that could turn out to be significant on +your system. In many cases, you may not be able to make a computation +similar to the one above that will accurately predict what will happen +on your system if you add N replication slaves. However, answering the +following questions should help you decided whether and how much, if at +all, the replication will improve the performance of your system: + +@itemize @bullet +@item +What is the read/write ratio on your system? +@item +How much more write load can one server handle if you reduce the reads? +@item +How many slaves do you have bandwidth for on your network? +@end itemize + +@strong{Q}: How can I use replication to provide redundancy/high +availability? + +@strong{A}: With the currently available features, you would have to +set up a master and a slave (or several slaves), and write a script +that will monitor the +master to see if it is up, and instruct your applications and +the slaves of the master change in case of failure. Some suggestions: + +@itemize @bullet +@item +To tell a slave to change the master use the @code{CHANGE MASTER TO} command. +@item +A good way to keep your applications informed where the master is by +having a dynamic DNS entry for the master. With @strong{bind} you can +use @code{nsupdate} to dynamically update your DNS. +@item +You should run your slaves with the @code{log-bin} option and without +@code{log-slave-updates}. This way the slave will be ready to become a +master as soon as you issue @code{STOP SLAVE}; @code{RESET MASTER}, and +@code{CHANGE MASTER TO} on the other slaves. It will also help you catch +spurious updates that may happen because of misconfiguration of the +slave (ideally, you want to configure access rights so that no client +can update the slave, except for the slave thread) combined with the +bugs in your client programs (they should never update the slave +directly). + +@end itemize + +We are currently working on integrating an automatic master election +system into @strong{MySQL}, but until it is ready, you will have to +create your own monitoring tools. + + +@node Replication Problems, , Replication FAQ, Replication HOWTO +@subsection Troubleshooting Replication + +If you have followed the instructions, and your replication setup is not +working, first eliminate the user error factor by checking the following: + +@itemize @bullet +@item +Is the master logging to the binary log? Check with @code{SHOW MASTER STATUS}. +If it is, @code{Position} will be non-zero. If not, verify that you have +given the master @code{log-bin} option and have set @code{server-id}. +@item +Is the slave running? Check with @code{SHOW SLAVE STATUS}. The answer is found +in @code{Slave_running} column. If not, verify slave options and check the +error log for messages. +@item +If the slave is running, did it establish connection with the master? Do +@code{SHOW PROCESSLIST}, find the thread with @code{system user} value in +@code{User} column and @code{none} in the @code{Host} column, and check the +@code{State} column. If it says @code{connecting to master}, verify the +privileges for the replication user on the master, master host name, your +DNS setup, whether the master is actually running, whether it is reachable +from the slave, and if all that seems ok, read the error logs. +@item +If the slave was running, but then stopped, look at SHOW SLAVE STATUS +output and check the error logs. It usually +happens when some query that succeeded on the master fails on the slave. This +should never happen if you have taken a proper snapshot of the master, and +never modify the data on the slave outside of the slave thread. If it does, +it is a bug, read below on how to report it. +@item +If a query on that succeeded on the master refuses to run on the slave, and +a full database resync ( the proper thing to do ) does not seem feasible, +try the following: +@itemize bullet +@item +First see if there is some stray record in the way. Understand how it got +there, then delete it and run @code{SLAVE START} +@item +If the above does not work or does not apply, try to understand if it would +be safe to make the update manually ( if needed) and then ignore the next +query from the master. +@item +If you have decided you can skip the next query, do +@code{SET SQL_SLAVE_SKIP_COUNTER=1; SLAVE START;} to skip a query that +does not use auto_increment, or last_insert_id or +@code{SET SQL_SLAVE_SKIP_COUNTER=2; SLAVE START;} otherwise. The reason +auto_increment/last_insert_id queries are different is that they take +two events in the binary log of the master. + +@item +If you are sure the slave started out perfectly in sync with the master, +and no one has updated the tables involved outside of slave thread, +report the bug, so +you will not have to do the above tricks again. +@end itemize +@item +Make sure you are not running into an old bug by upgrading to the most recent +version. +@item +If all else fails, read the error logs. If they are big, +@code{grep -i slave /path/to/your-log.err} on the slave. There is no +generic pattern to search for on the master, as the only errors it logs +are general system errors - if it can, it will send the error to the slave +when things go wrong. +@end itemize + +When you have determined that there is no user error involved, and replication +still either does not work at all or is unstable, it is time to start working +on a bug report. We need to get as much info as possible from you to be able +to track down the bug. Please do spend some time and effort preparing a good +bug report. Ideally, we would like to have a test case in the format found in +@code{mysql-test/t/rpl*} directory of the source tree. If you submit a test +case like that, you can expect a patch within a day or two in most cases, +although, of course, you mileage may vary depending on a number of factors. + +Second best option is a just program with easily configurable connection +arguments for the master and the slave that will demonstrate the problem on our +systems. You can write one in Perl or in C, depending on which language you +know better. + +If you have one of the above ways to demonstrate the bug, use +@code{mysqlbug} to prepare a bug report and send it to +@email{bugs@@lists.mysql.com}. If you have a phantom - a problem that +does occur but you cannot duplicate "at will": + +@itemize @bullet +@item +Verify that there is no user error involved. For example, if you update the +slave outside of the slave thread, the data will be out of sync, and you can +have unique key violations on updates, in which case the slave thread will +stop and wait for you to clean up the tables manually to bring them in sync. +@item +Run slave with @code{log-slave-updates} and @code{log-bin} - this will keep +a log of all updates on the slave. +@item +Save all evidence before resetting the replication. If we have no or only +sketchy information, it would take us a while to track down the problem. The +evidence you should collect is: +@itemize @bullet +@item +All binary logs on the master +@item +All binary log on the slave +@item +The output of @code{SHOW MASTER STATUS} on the master at the time +you have discovered the problem +@item +The output of @code{SHOW SLAVE STATUS} on the master at the time +you have discovered the problem +@item +Error logs on the master and on the slave +@end itemize +@item +Use @code{mysqlbinlog} to examine the binary logs. The following should +be helpful +to find the trouble query, for example: +@example +mysqlbinlog -j pos_from_slave_status /path/to/log_from_slave_status | head +@end example +@end itemize + +Once you have collected the evidence on the phantom problem, try hard to +isolate it into a separate test case first. Then report the problem to +@email{bugs@@lists.mysql.com} with as much info as possible. + + + +@node Reference, Table types, MySQL Database Administration, Top @chapter MySQL Language Reference @menu @@ -16397,12 +23635,6 @@ to restart @code{mysqld} with @code{--skip-grant-tables} to run * ALTER TABLE:: @code{ALTER TABLE} syntax * RENAME TABLE:: @code{RENAME TABLE} syntax * DROP TABLE:: @code{DROP TABLE} syntax -* OPTIMIZE TABLE:: @code{OPTIMIZE TABLE} syntax -* CHECK TABLE:: @code{CHECK TABLE} syntax -* BACKUP TABLE:: @code{BACKUP TABLE} syntax -* RESTORE TABLE:: @code{RESTORE TABLE} syntax -* ANALYZE TABLE:: @code{ANALYZE TABLE} syntax -* REPAIR TABLE:: @code{REPAIR TABLE} syntax * DELETE:: @code{DELETE} syntax * TRUNCATE:: @code{TRUNCATE} syntax * SELECT:: @code{SELECT} syntax @@ -16412,16 +23644,12 @@ to restart @code{mysqld} with @code{--skip-grant-tables} to run * LOAD DATA:: @code{LOAD DATA INFILE} syntax * UPDATE:: @code{UPDATE} syntax * USE:: @code{USE} syntax -* FLUSH:: @code{FLUSH} syntax (clearing caches) -* KILL:: @code{KILL} syntax -* SHOW:: @code{SHOW} syntax (Get information about tables, columns, ...) * EXPLAIN:: @code{EXPLAIN} syntax (Get information about a @code{SELECT}) * DESCRIBE:: @code{DESCRIBE} syntax (Get information about names of columns) * COMMIT:: @code{BEGIN/COMMIT/ROLLBACK} syntax * LOCK TABLES:: @code{LOCK TABLES/UNLOCK TABLES} syntax * SET OPTION:: @code{SET OPTION} syntax * SET TRANSACTION:: @code{SET TRANSACTION} syntax -* GRANT:: @code{GRANT} and @code{REVOKE} syntax * CREATE INDEX:: @code{CREATE INDEX} syntax * DROP INDEX:: @code{DROP INDEX} syntax * Comments:: Comment syntax @@ -16436,13 +23664,15 @@ effectively. This chapter also serves as a reference to all functionality included in @strong{MySQL}. In order to use this chapter effectively, you may find it useful to refer to the various indexes. + +@node Literals, Variables, Reference, Reference +@section Literals: How to Write Strings and Numbers + @cindex strings, defined @cindex strings, escaping characters @cindex literals @cindex escape characters @cindex backslash, escape character -@node Literals, Variables, Reference, Reference -@section Literals: How to Write Strings and Numbers @menu * String syntax:: Strings @@ -21167,7 +28397,7 @@ only creates a directory under the @strong{MySQL} data directory. @cindex @code{mysqladmin} You can also create databases with @code{mysqladmin}. -@xref{Programs}. +@xref{Client-Side Scripts}. @findex DROP DATABASE @node DROP DATABASE, CREATE TABLE, CREATE DATABASE, Reference @@ -21204,7 +28434,7 @@ In @strong{MySQL} Version 3.22 or later, you can use the keywords exist. @cindex @code{mysqladmin} -You can also drop databases with @code{mysqladmin}. @xref{Programs}. +You can also drop databases with @code{mysqladmin}. @xref{Client-Side Scripts}. @findex CREATE TABLE @node CREATE TABLE, ALTER TABLE, DROP DATABASE, Reference @@ -22010,7 +29240,7 @@ will do a reverse rename for all renamed tables to get everything back to the original state. @findex DROP TABLE -@node DROP TABLE, OPTIMIZE TABLE, RENAME TABLE, Reference +@node DROP TABLE, DELETE, RENAME TABLE, Reference @section @code{DROP TABLE} Syntax @example @@ -22030,295 +29260,11 @@ For the moment they don't do anything. @strong{NOTE}: @code{DROP TABLE} is not transaction-safe and will automatically commit any active transactions. -@cindex tables, defragment -@cindex tables, fragmentation -@findex OPTIMIZE TABLE -@node OPTIMIZE TABLE, CHECK TABLE, DROP TABLE, Reference -@section @code{OPTIMIZE TABLE} Syntax -@example -OPTIMIZE TABLE tbl_name[,tbl_name]... -@end example - -@code{OPTIMIZE TABLE} should be used if you have deleted a large part of a -table or if you have made many changes to a table with variable-length rows -(tables that have @code{VARCHAR}, @code{BLOB}, or @code{TEXT} columns). -Deleted records are maintained in a linked list and subsequent @code{INSERT} -operations reuse old record positions. You can use @code{OPTIMIZE TABLE} to -reclaim the unused space and to defragment the data file. - -For the moment @code{OPTIMIZE TABLE} only works on @strong{MyISAM} and -@code{BDB} tables. For @code{BDB} tables, @code{OPTIMIZE TABLE} is -currently mapped to @code{ANALYZE TABLE}. @xref{ANALYZE TABLE}. - -You can get optimize table to work on other table types by starting -@code{mysqld} with @code{--skip-new} or @code{--safe-mode}, but in this -case @code{OPTIMIZE TABLE} is just mapped to @code{ALTER TABLE}. - -@code{OPTIMIZE TABLE} works the following way: -@itemize @bullet -@item -If the table has deleted or split rows, repair the table. -@item -If the index pages are not sorted, sort them. -@item -If the statistics are not up to date (and the repair couldn't be done -by sorting the index), update them. -@end itemize - -@code{OPTIMIZE TABLE} for @code{MyISAM} tables is equvialent of running -@code{myisamchk --quick --check-changed-tables --sort-index --analyze} -on the table. - -Note that the table is locked during the time @code{OPTIMIZE TABLE} is -running! - -@findex CHECK TABLE -@node CHECK TABLE, BACKUP TABLE, OPTIMIZE TABLE, Reference -@section @code{CHECK TABLE} Syntax - -@example -CHECK TABLE tbl_name[,tbl_name...] [option [option...]] - -option = QUICK | FAST | MEDIUM | EXTEND | CHANGED -@end example - -@code{CHECK TABLE} only works on @code{MyISAM} tables. On -@code{MyISAM} tables it's the same thing as running @code{myisamchk -m -table_name} on the table. - -If you don't specify any option @code{MEDIUM} is used. - -Checks the table(s) for errors. For @code{MyISAM} tables the key statistics -is updated. The command returns a table with the following columns: - -@multitable @columnfractions .35 .65 -@item @strong{Column} @tab @strong{Value} -@item Table @tab Table name. -@item Op @tab Always ``check''. -@item Msg_type @tab One of @code{status}, @code{error}, @code{info}, or @code{warning}. -@item Msg_text @tab The message. -@end multitable - -Note that you can get many rows of information for each checked -table. The last row will be of @code{Msg_type status} and should -normally be @code{OK}. If you don't get @code{OK}, or @code{Not -checked} you should normally run a repair of the table. @xref{Table -maintenance}. @code{Not checked} means that the table the given @code{TYPE} -told @strong{MySQL} that there wasn't any need to check the table. - -The different check types stand for the following: - -@multitable @columnfractions .20 .80 -@item @strong{Type} @tab @strong{Meaning} -@item @code{QUICK} @tab Don't scan the rows to check for wrong links. -@item @code{FAST} @tab Only check tables which haven't been closed properly. -@item @code{CHANGED} @tab Only check tables which have been changed since last check or haven't been closed properly. -@item @code{MEDIUM} @tab Scan rows to verify that deleted links are ok. This also calculates a key checksum for the rows and verifies this with a calcualted checksum for the keys. -@item @code{EXTENDED} @tab Do a full key lookup for all keys for each row. This ensures that the table is 100 % consistent, but will take a long time! -@end multitable - -For dynamic sized @code{MyISAM} tables a started check will always -do a @code{MEDIUM} check. For static size rows we skip the row scan -for @code{QUICK} and @code{FAST} as the rows are very seldom corrupted. - -You can combine check options as in: - -@example -CHECK TABLE test_table FAST QUICK; -@end example - -Which only would do a quick check on the table if it wasn't closed properly. - -@strong{NOTE:} that in some case @code{CHECK TABLE} will change the -table! This happens if the table is marked as 'corrupted' or 'not -closed properly' but @code{CHECK TABLE} didn't find any problems in the -table. In this case @code{CHECK TABLE} will mark the table as ok. - -If a table is corrupted, then it's most likely that the problem is in -the indexes and not in the data part. All of the above check types -checks the indexes throughly and should thus find most errors. - -If you just want to check a table that you assume is ok, you should use -no check options or the @code{QUICK} option. The later should be used -when you are in a hurry and can take the very small risk that -@code{QUICK} didn't find an error in the data file (In most cases -@strong{MySQL} should find, under normal usage, any error in the data -file. If this happens then the table will be marked as 'corrupted', -in which case the table can't be used until it's repaired). - -@code{FAST} and @code{CHANGED} are mostly intended to be used from a -script (for example to be executed from cron) if you want to check your -table from time to time. In most cases you @code{FAST} is to be prefered -over @code{CHANGED}. (The only case when it isn't is when you suspect a -bug you have found a bug in the @code{MyISAM} code.). - -@code{EXTENDED} is only to be used after you have run a normal check but -still get strange errors from a table when @strong{MySQL} tries to -update a row or find a row by key (this is VERY unlikely to happen if a -normal check has succeeded!). - -Some things reported by check table, can't be corrected automatically: - -@itemize @bullet -@item -@code{Found row where the auto_increment column has the value 0}. - -This means that you have in the table a row where the -@code{auto_increment} index column contains the value 0. -(It's possible to create a row where the auto_increment column is 0 by -explicitely setting the column to 0 with an @code{UPDATE} statement) - -This isn't an error in itself, but could cause trouble if you decide to -dump the table and restore it or do an @code{ALTER TABLE} on the -table. In this case the auto_increment column will change value, -according to the rules of auto_increment columns, which could cause -problems like a duplicate key error. - -To get rid of the warning, just execute an @code{UPDATE} statement -to set the column to some other value than 0. -@end itemize - - -@findex BACKUP TABLE -@node BACKUP TABLE, RESTORE TABLE, CHECK TABLE, Reference -@section @code{BACKUP TABLE} Syntax - -@example -BACKUP TABLE tbl_name[,tbl_name...] TO '/path/to/backup/directory' -@end example - -Make a copy of all the table files to the backup directory that are the -minimum needed to restore it. Currenlty only works for @code{MyISAM} -tables. For @code{MyISAM} table, copies @code{.frm} (definition) and -@code{.MYD} (data) files. The index file can be rebuilt from those two. - -Before using this command, please see @xref{Backup}. - -During the backup, read lock will be held for each table, one at time, -as they are being backed up. If you want to backup several tables as -a snapshot, you must first issue @code{LOCK TABLES} obtaining a read -lock for each table in the group. - -The command returns a table with the following columns: - -@multitable @columnfractions .35 .65 -@item @strong{Column} @tab @strong{Value} -@item Table @tab Table name -@item Op @tab Always ``backup'' -@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. -@item Msg_text @tab The message. -@end multitable - -Note that @code{BACKUP TABLE} is only available in @strong{MySQL} -version 3.23.25 and later. - -@findex RESTORE TABLE -@node RESTORE TABLE, ANALYZE TABLE, BACKUP TABLE, Reference -@section @code{RESTORE TABLE} Syntax - -@example -RESTORE TABLE tbl_name[,tbl_name...] FROM '/path/to/backup/directory' -@end example - -Restores the table(s) from the backup that was made with -@code{BACKUP TABLE}. Existing tables will not be overwritten - if you -try to restore over an existing table, you will get an error. Restore -will take longer than BACKUP due to the need to rebuilt the index. The -more keys you have, the longer it is going to take. Just as -@code{BACKUP TABLE}, currently only works of @code{MyISAM} tables. - - -The command returns a table with the following columns: - -@multitable @columnfractions .35 .65 -@item @strong{Column} @tab @strong{Value} -@item Table @tab Table name -@item Op @tab Always ``restore'' -@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. -@item Msg_text @tab The message. -@end multitable - - -@findex ANALYZE TABLE -@node ANALYZE TABLE, REPAIR TABLE, RESTORE TABLE, Reference -@section @code{ANALYZE TABLE} Syntax - -@example -ANALYZE TABLE tbl_name[,tbl_name...] -@end example - -Analyze and store the key distribution for the table. During the -analyze the table is locked with a read lock. This works on -@code{MyISAM} and @code{BDB} tables. - -This is equivalent to running @code{myisamchk -a} on the table. - -@strong{MySQL} uses the stored key distribution to decide in which order -tables should be joined when one does a join on something else than a -constant. - -The command returns a table with the following columns: - -@multitable @columnfractions .35 .65 -@item @strong{Column} @tab @strong{Value} -@item Table @tab Table name -@item Op @tab Always ``analyze'' -@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. -@item Msg_text @tab The message. -@end multitable - -You can check the stored key distribution with the @code{SHOW INDEX} command. -@xref{SHOW DATABASE INFO}. - -If the table hasn't changed since the last @code{ANALYZE TABLE} command, -the table will not be analyzed again. - -@findex REPAIR TABLE -@node REPAIR TABLE, DELETE, ANALYZE TABLE, Reference -@section @code{REPAIR TABLE} Syntax - -@example -REPAIR TABLE tbl_name[,tbl_name...] [QUICK] [EXTENDED] -@end example - -@code{REPAIR TABLE} only works on @code{MyISAM} tables and is the same -as running @code{myisamchk -r table_name} on the table. - -Normally you should never have to run this command, but if disaster strikes -you are very likely to get back all your data from a MyISAM table with -@code{REPAIR TABLE}. If your tables get corrupted a lot you should -try to find the reason for this! @xref{Crashing}. @xref{MyISAM table problems}. - -@code{REPAIR TABLE} repairs a possible corrupted table. The command returns a -table with the following columns: - -@multitable @columnfractions .35 .65 -@item @strong{Column} @tab @strong{Value} -@item Table @tab Table name -@item Op @tab Always ``repair'' -@item Msg_type @tab One of @code{status}, @code{error}, @code{info} or @code{warning}. -@item Msg_text @tab The message. -@end multitable - -Note that you can get many rows of information for each repaired -table. The last one row will be of @code{Msg_type status} and should -normally be @code{OK}. If you don't get @code{OK}, you should try -repairing the table with @code{myisamchk -o}, as @code{REPAIR TABLE} -does not yet implement all the options of @code{myisamchk}. In the near -future, we will make it more flexible. - -If @code{QUICK} is given then @strong{MySQL} will try to do a -@code{REPAIR} of only the index tree. - -If you use @code{EXTENDED} then @strong{MySQL} will create the index row -by row instead of creating one index at a time with sorting; This may be -better than sorting on fixed-length keys if you have long @code{char()} -keys that compress very good. +@node DELETE, TRUNCATE, DROP TABLE, Reference +@section @code{DELETE} Syntax @findex DELETE -@node DELETE, TRUNCATE, REPAIR TABLE, Reference -@section @code{DELETE} Syntax @example DELETE [LOW_PRIORITY] FROM tbl_name @@ -23712,7 +30658,7 @@ In @strong{MySQL} Version 3.23, you can use @code{LIMIT #} to ensure that only a given number of rows are changed. @findex USE -@node USE, FLUSH, UPDATE, Reference +@node USE, EXPLAIN, UPDATE, Reference @section @code{USE} Syntax @example @@ -23746,1054 +30692,10 @@ mysql> SELECT author_name,editor_name FROM author,db2.editor @cindex compatibility, with Sybase The @code{USE} statement is provided for Sybase compatibility. -@cindex @code{mysqladmin} -@cindex clearing, caches -@cindex caches, clearing -@findex FLUSH -@node FLUSH, KILL, USE, Reference -@section @code{FLUSH} Syntax - -@example -FLUSH flush_option [,flush_option] -@end example - -You should use the @code{FLUSH} command if you want to clear some of the -internal caches @strong{MySQL} uses. To execute @code{FLUSH}, you must have -the @strong{RELOAD} privilege. - -@code{flush_option} can be any of the following: - -@multitable @columnfractions .15 .85 -@item @code{HOSTS} @tab Empties the host cache tables. You should flush the -host tables if some of your hosts change IP number or if you get the -error message @code{Host ... is blocked}. When more than -@code{max_connect_errors} errors occur in a row for a given host while -connection to the @strong{MySQL} server, @strong{MySQL} assumes -something is wrong and blocks the host from further connection requests. -Flushing the host tables allows the host to attempt to connect -again. @xref{Blocked host}.) You can start @code{mysqld} with -@code{-O max_connection_errors=999999999} to avoid this error message. - -@item @code{LOGS} @tab Closes and reopens all log files. -If you have specified the update log file or a binary log file without -an extension, the extension number of the log file will be incremented -by one relative to the previous file. If you have used an extension in -the file name, @strong{MySQL} will close and reopen the update log file. -@xref{Update log}. This is the same thing as sending the @code{SIGHUP} -signal to the @code{mysqld} server. - -@item @code{PRIVILEGES} @tab Reloads the privileges from the grant tables in -the @code{mysql} database. - -@item @code{TABLES} @tab Closes all open tables and force all tables in use to be closed. - -@item @code{[TABLE | TABLES] table_name [,table_name...]} @tab Flushes only the given tables. - -@item @code{TABLES WITH READ LOCK} @tab Closes all open tables and locks all tables for all databases with a read until one executes @code{UNLOCK TABLES}. This is very convenient way to get backups if you have a file system, like Veritas,that can take snapshots in time. - -@item @code{STATUS} @tab Resets most status variables to zero. This is something one should only use when debugging a query. -@end multitable - -You can also access each of the commands shown above with the @code{mysqladmin} -utility, using the @code{flush-hosts}, @code{flush-logs}, @code{reload}, -or @code{flush-tables} commands. - -Take also a look at the @code{RESET} command used with -replication. @xref{Replication SQL}. - -@cindex @code{mysqladmin} -@findex KILL -@node KILL, SHOW, FLUSH, Reference -@section @code{KILL} Syntax - -@example -KILL thread_id -@end example - -Each connection to @code{mysqld} runs in a separate thread. You can see -which threads are running with the @code{SHOW PROCESSLIST} command and kill -a thread with the @code{KILL thread_id} command. - -If you have the @strong{process} privilege, you can see and kill all threads. -Otherwise, you can see and kill only your own threads. - -You can also use the @code{mysqladmin processlist} and @code{mysqladmin kill} -commands to examine and kill threads. - -When you do a @code{KILL}, a thread specific @code{kill flag} is set for -the thread. - -In most cases it may take some time for the thread to die as the kill -flag is only checked at specific intervals. - -@itemize @bullet -@item -In @code{SELECT}, @code{ORDER BY} and @code{GROUP BY} loops, the flag is -checked after reading a block of rows. If the kill flag is set the -statement is aborted -@item -When doing an @code{ALTER TABLE} the kill flag is checked before each block of -rows are read from the original table. If the kill flag was set the command -is aborted and the temporary table is deleted. -@item -When doing an @code{UPDATE TABLE} and @code{DELETE TABLE}, the kill flag -is checked after each block read and after each updated or delete -row. If the kill flag is set the statement is aborted. Note that if you -are not using transactions, the changes will not be rolled back! -@item -@code{GET_LOCK()} will abort with @code{NULL}. -@item -An @code{INSERT DELAYED} thread will quickly flush all rows it has in -memory and die. -@item -If the thread is in the table lock handler (state: @code{Locked}), -the table lock will be quickly aborted. -@item -If the thread is waiting for free disk space in a @code{write} call, the -write is aborted with an disk full error message. -@end itemize - -@findex SHOW DATABASES -@findex SHOW TABLES -@findex SHOW COLUMNS -@findex SHOW FIELDS -@findex SHOW INDEX -@findex SHOW KEYS -@findex SHOW STATUS -@findex SHOW VARIABLES -@findex SHOW PROCESSLIST -@findex SHOW TABLE STATUS -@findex SHOW GRANTS -@findex SHOW CREATE TABLE -@findex SHOW MASTER STATUS -@findex SHOW MASTER LOGS -@findex SHOW SLAVE STATUS -@node SHOW, EXPLAIN, KILL, Reference -@section @code{SHOW} Syntax - -@example - SHOW DATABASES [LIKE wild] -or SHOW [OPEN] TABLES [FROM db_name] [LIKE wild] -or SHOW [FULL] COLUMNS FROM tbl_name [FROM db_name] [LIKE wild] -or SHOW INDEX FROM tbl_name [FROM db_name] -or SHOW TABLE STATUS [FROM db_name] [LIKE wild] -or SHOW STATUS [LIKE wild] -or SHOW VARIABLES [LIKE wild] -or SHOW LOGS -or SHOW [FULL] PROCESSLIST -or SHOW GRANTS FOR user -or SHOW CREATE TABLE table_name -or SHOW MASTER STATUS -or SHOW MASTER LOGS -or SHOW SLAVE STATUS -@end example - -@code{SHOW} provides information about databases, tables, columns, or -status information about the server. If the @code{LIKE wild} part is -used, the @code{wild} string can be a string that uses the SQL @samp{%} -and @samp{_} wild-card characters. - -@findex SHOW DATABASES -@findex SHOW TABLES -@findex SHOW COLUMNS -@findex SHOW FIELDS -@findex SHOW INDEX -@findex SHOW KEYS -@menu -* SHOW DATABASE INFO:: -* SHOW TABLE STATUS:: -* SHOW STATUS:: -* SHOW VARIABLES:: -* SHOW LOGS:: -* SHOW PROCESSLIST:: -* SHOW GRANTS:: -* SHOW CREATE TABLE:: -@end menu - -@cindex displaying, information, @code{SHOW} -@node SHOW DATABASE INFO, SHOW TABLE STATUS, SHOW, SHOW -@subsection @code{SHOW} Information About Databases, Tables, Columns, and Indexes - -You can use @code{db_name.tbl_name} as an alternative to the @code{tbl_name -FROM db_name} syntax. These two statements are equivalent: - -@example -mysql> SHOW INDEX FROM mytable FROM mydb; -mysql> SHOW INDEX FROM mydb.mytable; -@end example - -@code{SHOW DATABASES} lists the databases on the @strong{MySQL} server -host. You can also get this list using the @code{mysqlshow} command. - -@code{SHOW TABLES} lists the tables in a given database. You can also -get this list using the @code{mysqlshow db_name} command. - -@strong{NOTE:} If a user doesn't have any privileges for a table, the table -will not show up in the output from @code{SHOW TABLES} or @code{mysqlshow -db_name}. - -@code{SHOW OPEN TABLES} lists the tables that are currently open in -the table cache. @xref{Table cache}. The @code{Comment} field tells -how many times the table is @code{cached} and @code{in_use}. - -@code{SHOW COLUMNS} lists the columns in a given table. If you specify -the @code{FULL} option, you will also get the privileges you have for -each column. If the column types are different than you expect them to -be based on a @code{CREATE TABLE} statement, note that @strong{MySQL} -sometimes changes column types. @xref{Silent column changes}. - -The @code{DESCRIBE} statement provides information similar to -@code{SHOW COLUMNS}. -@xref{DESCRIBE, , @code{DESCRIBE}}. - -@code{SHOW FIELDS} is a synonym for @code{SHOW COLUMNS}, and -@code{SHOW KEYS} is a synonym for @code{SHOW INDEX}. You can also -list a table's columns or indexes with @code{mysqlshow db_name tbl_name} -or @code{mysqlshow -k db_name tbl_name}. - -@code{SHOW INDEX} returns the index information in a format that closely -resembles the @code{SQLStatistics} call in ODBC. The following columns -are returned: - -@multitable @columnfractions .35 .65 -@item @strong{Column} @tab @strong{Meaning} -@item @code{Table} @tab Name of the table. -@item @code{Non_unique} @tab 0 if the index can't contain duplicates. -@item @code{Key_name} @tab Name of the index. -@item @code{Seq_in_index} @tab Column sequence number in index, - starting with 1. -@item @code{Column_name} @tab Column name. -@item @code{Collation} @tab How the column is sorted in the index. - In @strong{MySQL}, this can have values - @samp{A} (Ascending) or @code{NULL} (Not - sorted). -@item @code{Cardinality} @tab Number of unique values in the index. - This is updated by running - @code{isamchk -a}. -@item @code{Sub_part} @tab Number of indexed characters if the - column is only partly indexed. - @code{NULL} if the entire key is indexed. -@item @code{Comment} @tab Various remarks. For now, it tells - whether index is FULLTEXT or not. -@end multitable - -Note that as the @code{Cardinality} is counted based on statistics -stored as integers, it's not necessarily accurate for small tables. - -@cindex displaying, table status -@cindex tables, displaying status -@cindex status, tables -@node SHOW TABLE STATUS, SHOW STATUS, SHOW DATABASE INFO, SHOW -@subsection @code{SHOW TABLE STATUS} - -@example -SHOW TABLE STATUS [FROM db_name] [LIKE wild] -@end example - -@code{SHOW TABLE STATUS} (new in Version 3.23) works likes @code{SHOW -STATUS}, but provides a lot of information about each table. You can -also get this list using the @code{mysqlshow --status db_name} command. -The following columns are returned: - -@multitable @columnfractions .30 .70 -@item @strong{Column} @tab @strong{Meaning} -@item @code{Name} @tab Name of the table. -@item @code{Type} @tab Type of table. @xref{Table types}. -@item @code{Row_format} @tab The row storage format (Fixed, Dynamic, or Compressed). -@item @code{Rows} @tab Number of rows. -@item @code{Avg_row_length} @tab Average row length. -@item @code{Data_length} @tab Length of the data file. -@item @code{Max_data_length} @tab Max length of the data file. -@item @code{Index_length} @tab Length of the index file. -@item @code{Data_free} @tab Number of allocated but not used bytes. -@item @code{Auto_increment} @tab Next autoincrement value. -@item @code{Create_time} @tab When the table was created. -@item @code{Update_time} @tab When the data file was last updated. -@item @code{Check_time} @tab When the table was last checked. -@item @code{Create_options} @tab Extra options used with @code{CREATE TABLE}. -@item @code{Comment} @tab The comment used when creating the table (or some information why @strong{MySQL} couldn't access the table information). -@end multitable - -@code{InnoDB} tables will report the free space in the tablespace -in the table comment. - -@node SHOW STATUS, SHOW VARIABLES, SHOW TABLE STATUS, SHOW -@subsection @code{SHOW STATUS} - -@cindex @code{mysqladmin} -@code{SHOW STATUS} provides server status information -(like @code{mysqladmin extended-status}). The output resembles that shown -below, though the format and numbers probably differ: - -@example -+--------------------------+------------+ -| Variable_name | Value | -+--------------------------+------------+ -| Aborted_clients | 0 | -| Aborted_connects | 0 | -| Bytes_received | 155372598 | -| Bytes_sent | 1176560426 | -| Connections | 30023 | -| Created_tmp_disk_tables | 0 | -| Created_tmp_tables | 8340 | -| Created_tmp_files | 60 | -| Delayed_insert_threads | 0 | -| Delayed_writes | 0 | -| Delayed_errors | 0 | -| Flush_commands | 1 | -| Handler_delete | 462604 | -| Handler_read_first | 105881 | -| Handler_read_key | 27820558 | -| Handler_read_next | 390681754 | -| Handler_read_prev | 6022500 | -| Handler_read_rnd | 30546748 | -| Handler_read_rnd_next | 246216530 | -| Handler_update | 16945404 | -| Handler_write | 60356676 | -| Key_blocks_used | 14955 | -| Key_read_requests | 96854827 | -| Key_reads | 162040 | -| Key_write_requests | 7589728 | -| Key_writes | 3813196 | -| Max_used_connections | 0 | -| Not_flushed_key_blocks | 0 | -| Not_flushed_delayed_rows | 0 | -| Open_tables | 1 | -| Open_files | 2 | -| Open_streams | 0 | -| Opened_tables | 44600 | -| Questions | 2026873 | -| Select_full_join | 0 | -| Select_full_range_join | 0 | -| Select_range | 99646 | -| Select_range_check | 0 | -| Select_scan | 30802 | -| Slave_running | OFF | -| Slave_open_temp_tables | 0 | -| Slow_launch_threads | 0 | -| Slow_queries | 0 | -| Sort_merge_passes | 30 | -| Sort_range | 500 | -| Sort_rows | 30296250 | -| Sort_scan | 4650 | -| Table_locks_immediate | 1920382 | -| Table_locks_waited | 0 | -| Threads_cached | 0 | -| Threads_created | 30022 | -| Threads_connected | 1 | -| Threads_running | 1 | -| Uptime | 80380 | -+--------------------------+------------+ -@end example - -@cindex variables, status -The status variables listed above have the following meaning: - -@multitable @columnfractions .35 .65 -@item @strong{Variable} @tab @strong{Meaning} -@item @code{Aborted_clients} @tab Number of connections aborted because the client died without closing the connection properly. @xref{Communication errors}. -@item @code{Aborted_connects} @tab Number of tries to connect to the @strong{MySQL} server that failed. @xref{Communication errors}. -@item @code{Bytes_received} @tab Number of bytes received from all clients. -@item @code{Bytes_sent} @tab Number of bytes sent to all clients. -@item @code{Connections} @tab Number of connection attempts to the @strong{MySQL} server. -@item @code{Created_tmp_disk_tables} @tab Number of implicit temporary tables on disk created while executing statements. -@item @code{Created_tmp_tables} @tab Number of implicit temporary tables in memory created while executing statements. -@item @code{Created_tmp_files} @tab How many temporary files @code{mysqld} have created. -@item @code{Delayed_insert_threads} @tab Number of delayed insert handler threads in use. -@item @code{Delayed_writes} @tab Number of rows written with @code{INSERT DELAYED}. -@item @code{Delayed_errors} @tab Number of rows written with @code{INSERT DELAYED} for which some error occurred (probably @code{duplicate key}). -@item @code{Flush_commands} @tab Number of executed @code{FLUSH} commands. -@item @code{Handler_delete} @tab Number of times a row was deleted from a table. -@item @code{Handler_read_first} @tab Number of times the first entry was read from an index. -If this is high, it suggests that the server is doing a lot of full index scans, for example, -@code{SELECT col1 FROM foo}, assuming that col1 is indexed. -@item @code{Handler_read_key} @tab Number of requests to read a row based on a key. If this -is high, it is a good indication that your queries and tables are properly indexed. -@item @code{Handler_read_next} @tab Number of requests to read next row in key order. This -will be incremented if you are querying an index column with a range constraint. This also -will be incremented if you are doing an index scan. -@item @code{Handler_read_rnd} @tab Number of requests to read a row based on a fixed position. -This will be high if you are doing a lot of queries that require sorting of the result. -@item @code{Handler_read_rnd_next} @tab Number of requests to read the next row in the datafile. -This will be high if you are doing a lot of table scans. Generally this suggests that your tables -are not properly indexed or that your queries are not written to take advantage of the indexes you -have. -@item @code{Handler_update} @tab Number of requests to update a row in a table. -@item @code{Handler_write} @tab Number of requests to insert a row in a table. -@item @code{Key_blocks_used} @tab The number of used blocks in the key cache. -@item @code{Key_read_requests} @tab The number of requests to read a key block from the cache. -@item @code{Key_reads} @tab The number of physical reads of a key block from disk. -@item @code{Key_write_requests} @tab The number of requests to write a key block to the cache. -@item @code{Key_writes} @tab The number of physical writes of a key block to disk. -@item @code{Max_used_connections} @tab The maximum number of connections in use simultaneously. -@item @code{Not_flushed_key_blocks} @tab Keys blocks in the key cache that has changed but hasn't yet been flushed to disk. -@item @code{Not_flushed_delayed_rows} @tab Number of rows waiting to be written in @code{INSERT DELAY} queues. -@item @code{Open_tables} @tab Number of tables that are open. -@item @code{Open_files} @tab Number of files that are open. -@item @code{Open_streams} @tab Number of streams that are open (used mainly for logging). -@item @code{Opened_tables} @tab Number of tables that have been opened. -@item @code{Select_full_join} @tab Number of joins without keys (Should be 0). -@item @code{Select_full_range_join} @tab Number of joins where we used a range search on reference table. -@item @code{Select_range} @tab Number of joins where we used ranges on the first table. (It's normally not critical even if this is big.) -@item @code{Select_scan} @tab Number of joins where we scanned the first table. -@item @code{Select_range_check} @tab Number of joins without keys where we check for key usage after each row (Should be 0). -@item @code{Questions} @tab Number of queries sent to the server. -@item @code{Slave_open_temp_tables} @tab Number of temporary tables currently -open by the slave thread -@item @code{Slow_launch_threads} @tab Number of threads that have taken more than @code{slow_launch_time} to connect. -@item @code{Slow_queries} @tab Number of queries that have taken more than @code{long_query_time}. @xref{Slow query log}. -@item @code{Sort_merge_passes} @tab Number of merges the sort has to do. If this value is large you should consider increasing @code{sort_buffer}. -@item @code{Sort_range} @tab Number of sorts that where done with ranges. -@item @code{Sort_rows} @tab Number of sorted rows. -@item @code{Sort_scan} @tab Number of sorts that where done by scanning the table. -@item @code{Table_locks_immediate} @tab Number of times a table lock was -acquired immediately. Available after 3.23.33. -@item @code{Table_locks_waited} @tab Number of times a table lock could not -be acquired immediately and a wait was needed. If this is high, and you -have performance problems, you should first optimize your queries, and then -either split your table(s) or use replication. Available after 3.23.33. -@item @code{Threads_cached} @tab Number of threads in the thread cache. -@item @code{Threads_connected} @tab Number of currently open connections. -@item @code{Threads_created} @tab Number of threads created to handle connections. -@item @code{Threads_running} @tab Number of threads that are not sleeping. -@item @code{Uptime} @tab How many seconds the server has been up. -@end multitable - -Some comments about the above: - -@itemize @bullet -@item -If @code{Opened_tables} is big, then your @code{table_cache} -variable is probably too small. -@item -If @code{key_reads} is big, then your @code{key_cache} is probably too -small. The cache hit rate can be calculated with -@code{key_reads}/@code{key_read_requests}. -@item -If @code{Handler_read_rnd} is big, then you probably have a lot of -queries that require @strong{MySQL} to scan whole tables or you have -joins that don't use keys properly. -@item -If @code{Threads_created} is big, you may want to increase the -@code{thread_cache_size} variable. -@end itemize - -@node SHOW VARIABLES, SHOW LOGS, SHOW STATUS, SHOW -@subsection @code{SHOW VARIABLES} - -@example -SHOW VARIABLES [LIKE wild] -@end example - -@code{SHOW VARIABLES} shows the values of some @strong{MySQL} system -variables. You can also get this information using the @code{mysqladmin -variables} command. If the default values are unsuitable, you can set most -of these variables using command-line options when @code{mysqld} starts up. -@xref{Command-line options}. - -The output resembles that shown below, though the format and numbers may -differ somewhat: - -@example -+-------------------------+---------------------------+ -| Variable_name | Value | -+-------------------------+---------------------------+ -| ansi_mode | OFF | -| back_log | 50 | -| basedir | /my/monty/ | -| bdb_cache_size | 16777216 | -| bdb_log_buffer_size | 32768 | -| bdb_home | /my/monty/data/ | -| bdb_max_lock | 10000 | -| bdb_logdir | | -| bdb_shared_data | OFF | -| bdb_tmpdir | /tmp/ | -| binlog_cache_size | 32768 | -| concurrent_insert | ON | -| connect_timeout | 5 | -| datadir | /my/monty/data/ | -| delay_key_write | ON | -| delayed_insert_limit | 100 | -| delayed_insert_timeout | 300 | -| delayed_queue_size | 1000 | -| flush | OFF | -| flush_time | 0 | -| have_bdb | YES | -| have_innodb | YES | -| have_raid | YES | -| have_ssl | NO | -| init_file | | -| interactive_timeout | 28800 | -| join_buffer_size | 131072 | -| key_buffer_size | 16776192 | -| language | /my/monty/share/english/ | -| large_files_support | ON | -| log | OFF | -| log_update | OFF | -| log_bin | OFF | -| log_slave_updates | OFF | -| long_query_time | 10 | -| low_priority_updates | OFF | -| lower_case_table_names | 0 | -| max_allowed_packet | 1048576 | -| max_binlog_cache_size | 4294967295 | -| max_connections | 100 | -| max_connect_errors | 10 | -| max_delayed_threads | 20 | -| max_heap_table_size | 16777216 | -| max_join_size | 4294967295 | -| max_sort_length | 1024 | -| max_tmp_tables | 32 | -| max_write_lock_count | 4294967295 | -| myisam_recover_options | DEFAULT | -| myisam_sort_buffer_size | 8388608 | -| net_buffer_length | 16384 | -| net_read_timeout | 30 | -| net_retry_count | 10 | -| net_write_timeout | 60 | -| open_files_limit | 0 | -| pid_file | /my/monty/data/donna.pid | -| port | 3306 | -| protocol_version | 10 | -| record_buffer | 131072 | -| query_buffer_size | 0 | -| safe_show_database | OFF | -| server_id | 0 | -| skip_locking | ON | -| skip_networking | OFF | -| skip_show_database | OFF | -| slow_launch_time | 2 | -| socket | /tmp/mysql.sock | -| sort_buffer | 2097116 | -| table_cache | 64 | -| table_type | MYISAM | -| thread_cache_size | 4 | -| thread_stack | 65536 | -| tmp_table_size | 1048576 | -| tmpdir | /tmp/ | -| version | 3.23.29a-gamma-debug | -| wait_timeout | 28800 | -+-------------------------+---------------------------+ -@end example - -Each option is described below. Values for buffer sizes, lengths, and stack -sizes are given in bytes. You can specify values with a suffix of @samp{K} -or @samp{M} to indicate kilobytes or megabytes. For example, @code{16M} -indicates 16 megabytes. The case of suffix letters does not matter; -@code{16M} and @code{16m} are equivalent: - -@cindex variables, values -@table @code -@item @code{ansi_mode}. -Is @code{ON} if @code{mysqld} was started with @code{--ansi}. -@xref{ANSI mode}. - -@item @code{back_log} -The number of outstanding connection requests @strong{MySQL} can have. This -comes into play when the main @strong{MySQL} thread gets @strong{VERY} -many connection requests in a very short time. It then takes some time -(although very little) for the main thread to check the connection and start -a new thread. The @code{back_log} value indicates how many requests can be -stacked during this short time before @strong{MySQL} momentarily stops -answering new requests. You need to increase this only if you expect a large -number of connections in a short period of time. - -In other words, this value is the size of the listen queue for incoming -TCP/IP connections. Your operating system has its own limit on the size -of this queue. The manual page for the Unix @code{listen(2)} system -call should have more details. Check your OS documentation for the -maximum value for this variable. Attempting to set @code{back_log} -higher than your operating system limit will be ineffective. - -@item @code{basedir} -The value of the @code{--basedir} option. - -@item @code{bdb_cache_size} -The buffer that is allocated to cache index and rows for @code{BDB} -tables. If you don't use @code{BDB} tables, you should start -@code{mysqld} with @code{--skip-bdb} to not waste memory for this -cache. - -@item @code{bdb_log_buffer_size} -The buffer that is allocated to cache index and rows for @code{BDB} -tables. If you don't use @code{BDB} tables, you should set this to 0 or -start @code{mysqld} with @code{--skip-bdb} to not waste memory for this -cache. - -@item @code{bdb_home} -The value of the @code{--bdb-home} option. - -@item @code{bdb_max_lock} -The maximum number of locks (1000 by default) you can have active on a -BDB table. You should increase this if you get errors of type @code{bdb: -Lock table is out of available locks} or @code{Got error 12 from ...} -when you have do long transactions or when @code{mysqld} has to examine -a lot of rows to calculate the query. - -@item @code{bdb_logdir} -The value of the @code{--bdb-logdir} option. - -@item @code{bdb_shared_data} -Is @code{ON} if you are using @code{--bdb-shared-data}. - -@item @code{bdb_tmpdir} -The value of the @code{--bdb-tmpdir} option. - -@item @code{binlog_cache_size}. The size of the cache to hold the SQL -statements for the binary log during a transaction. If you often use -big, multi-statement transactions you can increase this to get more -performance. @xref{COMMIT}. - -@item @code{character_set} -The default character set. - -@item @code{character_sets} -The supported character sets. - -@item @code{concurrent_inserts} -If @code{ON} (the default), @strong{MySQL} will allow you to use @code{INSERT} -on @code{MyISAM} tables at the same time as you run @code{SELECT} queries -on them. You can turn this option off by starting @code{mysqld} with @code{--safe} -or @code{--skip-new}. - -@cindex timeout -@item @code{connect_timeout} -The number of seconds the @code{mysqld} server is waiting for a connect -packet before responding with @code{Bad handshake}. - -@item @code{datadir} -The value of the @code{--datadir} option. - -@item @code{delay_key_write} -If enabled (is on by default), @strong{MySQL} will honor the -@code{delay_key_write} option @code{CREATE TABLE}. This means that the -key buffer for tables with this option will not get flushed on every -index update, but only when a table is closed. This will speed up -writes on keys a lot, but you should add automatic checking of all tables -with @code{myisamchk --fast --force} if you use this. Note that if you -start @code{mysqld} with the @code{--delay-key-write-for-all-tables} -option this means that all tables will be treated as if they were -created with the @code{delay_key_write} option. You can clear this flag -by starting @code{mysqld} with @code{--skip-new} or @code{--safe-mode}. - -@item @code{delayed_insert_limit} -After inserting @code{delayed_insert_limit} rows, the @code{INSERT -DELAYED} handler will check if there are any @code{SELECT} statements -pending. If so, it allows these to execute before continuing. - -@item @code{delayed_insert_timeout} -How long a @code{INSERT DELAYED} thread should wait for @code{INSERT} -statements before terminating. - -@item @code{delayed_queue_size} -What size queue (in rows) should be allocated for handling @code{INSERT -DELAYED}. If the queue becomes full, any client that does @code{INSERT -DELAYED} will wait until there is room in the queue again. - -@item @code{flush} -This is @code{ON} if you have started @strong{MySQL} with the @code{--flush} -option. - -@item @code{flush_time} -If this is set to a non-zero value, then every @code{flush_time} seconds all -tables will be closed (to free up resources and sync things to disk). We -only recommend this option on Win95, Win98, or on systems where you have -very little resources. - -@item @code{have_bdb} -@code{YES} if @code{mysqld} supports Berkeley DB tables. @code{DISABLED} -if @code{--skip-bdb} is used. -@item @code{have_innodb} -@code{YES} if @code{mysqld} supports InnoDB tables. @code{DISABLED} -if @code{--skip-innodb} is used. -@item @code{have_raid} -@code{YES} if @code{mysqld} supports the @code{RAID} option. -@item @code{have_ssl} -@code{YES} if @code{mysqld} supports SSL (encryption) on the client/server -protocol. - -@item @code{init_file} -The name of the file specified with the @code{--init-file} option when -you start the server. This is a file of SQL statements you want the -server to execute when it starts. - -@item @code{interactive_timeout} -The number of seconds the server waits for activity on an interactive -connection before closing it. An interactive client is defined as a -client that uses the @code{CLIENT_INTERACTIVE} option to -@code{mysql_real_connect()}. See also @code{wait_timeout}. - -@item @code{join_buffer_size} -The size of the buffer that is used for full joins (joins that do not -use indexes). The buffer is allocated one time for each full join -between two tables. Increase this value to get a faster full join when -adding indexes is not possible. (Normally the best way to get fast joins -is to add indexes.) - -@c Make texi2html support index @anchor{Index cache size}. Then change -@c some xrefs to point here -@cindex indexes, block size -@item @code{key_buffer_size} -Index blocks are buffered and are shared by all threads. -@code{key_buffer_size} is the size of the buffer used for index blocks. - -Increase this to get better index handling (for all reads and multiple -writes) to as much as you can afford; 64M on a 256M machine that mainly -runs @strong{MySQL} is quite common. If you, however, make this too big -(more than 50% of your total memory?) your system may start to page and -become REALLY slow. Remember that because @strong{MySQL} does not cache -data read, that you will have to leave some room for the OS filesystem -cache. - -You can check the performance of the key buffer by doing @code{show -status} and examine the variables @code{Key_read_requests}, -@code{Key_reads}, @code{Key_write_requests}, and @code{Key_writes}. The -@code{Key_reads/Key_read_request} ratio should normally be < 0.01. -The @code{Key_write/Key_write_requests} is usually near 1 if you are -using mostly updates/deletes but may be much smaller if you tend to -do updates that affect many at the same time or if you are -using @code{delay_key_write}. @xref{SHOW}. - -To get even more speed when writing many rows at the same time, use -@code{LOCK TABLES}. @xref{LOCK TABLES, , @code{LOCK TABLES}}. - -@item @code{language} -The language used for error messages. - -@item @code{large_file_support} -If @code{mysqld} was compiled with options for big file support. - -@item @code{locked_in_memory} -If @code{mysqld} was locked in memory with @code{--memlock} - -@item @code{log} -If logging of all queries is enabled. - -@item @code{log_update} -If the update log is enabled. - -@item @code{log_bin} -If the binary log is enabled. - -@item @code{log_slave_updates} -If the updates from the slave should be logged. - -@item @code{long_query_time} -If a query takes longer than this (in seconds), the @code{Slow_queries} counter -will be incremented. If you are using @code{--log-slow-queries}, the query -will be logged to the slow query logfile. @xref{Slow query log}. - -@item @code{lower_case_table_names} -If set to 1 table names are stored in lowercase on disk. This will enable -you to access the table names case-insensitive also on Unix. -@xref{Name case sensitivity}. - -@item @code{max_allowed_packet} -The maximum size of one packet. The message buffer is initialized to -@code{net_buffer_length} bytes, but can grow up to @code{max_allowed_packet} -bytes when needed. This value by default is small, to catch big (possibly -wrong) packets. You must increase this value if you are using big -@code{BLOB} columns. It should be as big as the biggest @code{BLOB} you want -to use. The current protocol limits @code{max_allowed_packet} to 16M. - -@item @code{max_binlog_cache_size} -If a multi-statement transaction requires more than this amount of memory, -one will get the error "Multi-statement transaction required more than -'max_binlog_cache_size' bytes of storage". - -@item @code{max_binlog_size} -Available after 3.23.33. If a write to the binary (replication) log exceeds -the given value, rotate the logs. You cannot set it to less than 1024 bytes, -or more than 1 GB. Default is 1 GB. - -@item @code{max_connections} -The number of simultaneous clients allowed. Increasing this value increases -the number of file descriptors that @code{mysqld} requires. See below for -comments on file descriptor limits. @xref{Too many connections}. - -@item @code{max_connect_errors} -If there is more than this number of interrupted connections from a host -this host will be blocked from further connections. You can unblock a host -with the command @code{FLUSH HOSTS}. - -@item @code{max_delayed_threads} -Don't start more than this number of threads to handle @code{INSERT DELAYED} -statements. If you try to insert data into a new table after all @code{INSERT -DELAYED} threads are in use, the row will be inserted as if the -@code{DELAYED} attribute wasn't specified. - -@item @code{max_heap_table_size} -Don't allow creation of heap tables bigger than this. - -@item @code{max_join_size} -Joins that are probably going to read more than @code{max_join_size} -records return an error. Set this value if your users tend to perform joins -that lack a @code{WHERE} clause, that take a long time, and that return -millions of rows. - -@item @code{max_sort_length} -The number of bytes to use when sorting @code{BLOB} or @code{TEXT} -values (only the first @code{max_sort_length} bytes of each value -are used; the rest are ignored). - -@item @code{max_user_connections} -The maximum number of active connections for a single user (0 = no limit). - -@item @code{max_tmp_tables} -(This option doesn't yet do anything.) -Maximum number of temporary tables a client can keep open at the same time. - -@item @code{max_write_lock_count} -After this many write locks, allow some read locks to run in between. - -@item @code{myisam_recover_options} -The value of the @code{--myisam-recover} option. - -@item @code{myisam_sort_buffer_size} -The buffer that is allocated when sorting the index when doing a -@code{REPAIR} or when creating indexes with @code{CREATE INDEX} or -@code{ALTER TABLE}. - -@item @code{myisam_max_extra_sort_file_size}. -If the creating of the temporary file for fast index creation would be -this much bigger than using the key cache, then prefer the key cache -method. This is mainly used to force long character keys in large -tables to use the slower key cache method to create the index. -@strong{NOTE} that this parameter is given in megabytes! - -@item @code{myisam_max_sort_file_size} -The maximum size of the temporary file @strong{MySQL} is allowed to use -while recreating the index (during @code{REPAIR}, @code{ALTER TABLE} -or @code{LOAD DATA INFILE}. If the file size would be bigger than this, -the index will be created through the key cache (which is slower). -@strong{NOTE} that this parameter is given in megabytes! - -@item @code{net_buffer_length} -The communication buffer is reset to this size between queries. This -should not normally be changed, but if you have very little memory, you -can set it to the expected size of a query. (That is, the expected length of -SQL statements sent by clients. If statements exceed this length, the buffer -is automatically enlarged, up to @code{max_allowed_packet} bytes.) - -@item @code{net_read_timeout} -Number of seconds to wait for more data from a connection before aborting -the read. Note that when we don't expect data from a connection, the timeout -is defined by @code{write_timeout}. See also @code{slave_read_timeout}. - -@item @code{net_retry_count} -If a read on a communication port is interrupted, retry this many times -before giving up. This value should be quite high on @code{FreeBSD} as -internal interrupts are sent to all threads. - -@item @code{net_write_timeout} -Number of seconds to wait for a block to be written to a connection before -aborting the write. - -@item @code{open_files_limit} -If this is not 0, then @code{mysqld} will use this value to reserve file -descriptors to use with @code{setrlimit()}. If this value is 0 then -@code{mysqld} will reserve @code{max_connections*5} or -@code{max_connections + table_cache*2} (whichever is larger) number of -files. You should try increasing this if @code{mysqld} gives you the -error 'Too many open files'. - -@item @code{pid_file} -The value of the @code{--pid-file} option. - -@item @code{port} -The value of the @code{--port} option. - -@item @code{protocol_version} -The protocol version used by the @strong{MySQL} server. - -@item @code{record_buffer} -Each thread that does a sequential scan allocates a buffer of this -size for each table it scans. If you do many sequential scans, you may -want to increase this value. - -@item @code{query_buffer_size} -The initial allocation of the query buffer. If most of your queries are -long (like when inserting blobs), you should increase this! - -@item @code{safe_show_databases} -Don't show databases for which the user doesn't have any database or -table privileges. This can improve security if you're concerned about -people being able to see what databases other users have. See also -@code{skip_show_databases}. - -@item @code{server_id} -The value of the @code{--server-id} option. - -@item @code{skip_locking} -Is OFF if @code{mysqld} uses external locking. - -@item @code{skip_networking} -Is ON if we only allow local (socket) connections. - -@item @code{skip_show_databases} -This prevents people from doing @code{SHOW DATABASES} if they don't have -the @code{PROCESS_PRIV} privilege. This can improve security if you're -concerned about people being able to see what databases other users -have. See also @code{safe_show_databases}. - -@item @code{slave_read_timeout} -Number of seconds to wait for more data from a master/slave connection -before aborting the read. - -@item @code{slow_launch_time} -If creating the thread takes longer than this value (in seconds), the -@code{Slow_launch_threads} counter will be incremented. - -@item @code{socket} -The Unix socket used by the server. - -@item @code{sort_buffer} -Each thread that needs to do a sort allocates a buffer of this -size. Increase this value for faster @code{ORDER BY} or @code{GROUP BY} -operations. -@xref{Temporary files}. - -@item @code{table_cache} -The number of open tables for all threads. Increasing this value -increases the number of file descriptors that @code{mysqld} requires. -@strong{MySQL} needs two file descriptors for each unique open table. -See below for comments on file descriptor limits. You can check if you -need to increase the table cache by checking the @code{Opened_tables} -variable. @xref{SHOW}. If this variable is big and you don't do -@code{FLUSH TABLES} a lot (which just forces all tables to be closed and -reopenend), then you should increase the value of this variable. - -Make sure that your operating system can handle the number of open file -descriptors implied by the @code{table_cache} setting. If @code{table_cache} -is set too high, @strong{MySQL} may run out of file descriptors and refuse -connections, fail to perform queries, and be very unreliable. - -For information about how the table cache works, see @ref{Table cache}. - -@item @code{table_type} -The default table type - -@item @code{thread_cache_size} -How many threads we should keep in a cache for reuse. When a -client disconnects, the client's threads are put in the cache if there -aren't more than @code{thread_cache_size} threads from before. All new -threads are first taken from the cache, and only when the cache is empty -is a new thread created. This variable can be increased to improve -performance if you have a lot of new connections. (Normally this doesn't -give a notable performance improvement if you have a good -thread implementation.) By examing the difference between -the @code{Connections} and @code{Threads_created} you can see how efficient -the current thread cache is for you. - -@item @code{thread_concurrency} -On Solaris, @code{mysqld} will call @code{thr_setconcurrency()} with -this value. @code{thr_setconcurrency()} permits the application to give -the threads system a hint for the desired number of threads that should -be run at the same time. - -@item @code{thread_stack} -The stack size for each thread. Many of the limits detected by the -@code{crash-me} test are dependent on this value. The default is -large enough for normal operation. @xref{Benchmarks}. - -@item @code{timezone} -The timezone for the server. - -@item @code{tmp_table_size} -If an in-memory temporary table exceeds this size, @strong{MySQL} -will automatically convert it to an on-disk @code{MyISAM} table. -Increase the value of @code{tmp_table_size} if you do many advanced -@code{GROUP BY} queries and you have lots of memory. - -@item @code{tmpdir} -The directory used for temporary files and temporary tables. - -@item @code{version} -The version number for the server. - -@item @code{wait_timeout} -The number of seconds the server waits for activity on a connection before -closing it. See also @code{interactive_timeout}. -@end table - -The manual section that describes tuning @strong{MySQL} contains some -information of how to tune the above variables. @xref{Server parameters}. - -@node SHOW LOGS, SHOW PROCESSLIST, SHOW VARIABLES, SHOW -@subsection @code{SHOW LOGS} -@code{SHOW LOGS} shows you status information about existing log -files. It currently only displays information about Berkeley DB log -files. - -@itemize @bullet -@item @code{File} shows the full path to the log file -@item @code{Type} shows the type of the log file (@code{BDB} for Berkeley -DB log files) -@item @code{Status} shows the status of the log file (@code{FREE} if the -file can be removed, or @code{IN USE} if the file is needed by the transaction -subsystem) -@end itemize - -@cindex threads, display -@cindex processes, display -@findex threads -@findex PROCESSLIST -@node SHOW PROCESSLIST, SHOW GRANTS, SHOW LOGS, SHOW -@subsection @code{SHOW PROCESSLIST} - -@code{SHOW PROCESSLIST} shows you which threads are running. You can -also get this information using the @code{mysqladmin processlist} -command. If you have the @strong{process} privilege, you can see all -threads. Otherwise, you can see only your own threads. @xref{KILL, , -@code{KILL}}. If you don't use the @code{FULL} option, then only -the first 100 characters of each query will be shown. - -This command is very useful if you get the 'too many connections' error -message and want to find out what's going on. @strong{MySQL} reserves -one extra connection for a client with the @code{Process_priv} privilege -to ensure that you should always be able to login and check the system -(assuming you are not giving this privilege to all your users). - -@cindex privileges, display -@node SHOW GRANTS, SHOW CREATE TABLE, SHOW PROCESSLIST, SHOW -@subsection @code{SHOW GRANTS} - -@code{SHOW GRANTS FOR user} lists the grant commands that must be issued to -duplicate the grants for a user. - -@example -mysql> SHOW GRANTS FOR root@@localhost; -+---------------------------------------------------------------------+ -| Grants for root@@localhost | -+---------------------------------------------------------------------+ -| GRANT ALL PRIVILEGES ON *.* TO 'root'@@'localhost' WITH GRANT OPTION | -+---------------------------------------------------------------------+ -@end example - -@node SHOW CREATE TABLE, , SHOW GRANTS, SHOW -@subsection @code{SHOW CREATE TABLE} - -Shows a @code{CREATE TABLE} statement that will create the given table: - -@example -mysql> show create table t\G -*************************** 1. row *************************** - Table: t -Create Table: CREATE TABLE t ( - id int(11) default NULL auto_increment, - s char(60) default NULL, - PRIMARY KEY (id) -) TYPE=MyISAM - -@end example - -@code{SHOW CREATE TABLE} will quote table and column names according to -@code{SQL_QUOTE_SHOW_CREATE} option. -@ref{SET OPTION, , @code{SET OPTION SQL_QUOTE_SHOW_CREATE}}. @findex EXPLAIN @findex SELECT, optimizing -@node EXPLAIN, DESCRIBE, SHOW, Reference +@node EXPLAIN, DESCRIBE, USE, Reference @section @code{EXPLAIN} Syntax (Get Information About a @code{SELECT}) @example @@ -25511,7 +31413,7 @@ with the update log. @end table @findex ISOLATION LEVEL -@node SET TRANSACTION, GRANT, SET OPTION, Reference +@node SET TRANSACTION, CREATE INDEX, SET OPTION, Reference @section @code{SET TRANSACTION} Syntax @example @@ -25534,249 +31436,13 @@ future transactions. You can set the default isolation level for @code{mysqld} with @code{--transaction-isolation=...}. @xref{Command-line options}. -@cindex privileges, granting -@cindex privileges, revoking -@cindex global privileges -@cindex revoking, privleges -@cindex granting, privleges -@findex GRANT -@findex REVOKE -@node GRANT, CREATE INDEX, SET TRANSACTION, Reference -@section @code{GRANT} and @code{REVOKE} Syntax - -@example -GRANT priv_type [(column_list)] [, priv_type [(column_list)] ...] - ON @{tbl_name | * | *.* | db_name.*@} - TO user_name [IDENTIFIED BY 'password'] - [, user_name [IDENTIFIED BY 'password'] ...] - [WITH GRANT OPTION] - -REVOKE priv_type [(column_list)] [, priv_type [(column_list)] ...] - ON @{tbl_name | * | *.* | db_name.*@} - FROM user_name [, user_name ...] -@end example - -@code{GRANT} is implemented in @strong{MySQL} Version 3.22.11 or later. For -earlier @strong{MySQL} versions, the @code{GRANT} statement does nothing. - -The @code{GRANT} and @code{REVOKE} commands allow system administrators -to create users and grant and revoke rights to @strong{MySQL} users at -four privilege levels: - -@table @strong -@item Global level -Global privileges apply to all databases on a given server. These privileges -are stored in the @code{mysql.user} table. - -@item Database level -Database privileges apply to all tables in a given database. These privileges -are stored in the @code{mysql.db} and @code{mysql.host} tables. - -@item Table level -Table privileges apply to all columns in a given table. These privileges are -stored in the @code{mysql.tables_priv} table. - -@item Column level -Column privileges apply to single columns in a given table. These privileges are -stored in the @code{mysql.columns_priv} table. -@end table - -If you give a grant for a users that doesn't exists, that user is created. -For examples of how @code{GRANT} works, see @ref{Adding users}. - -For the @code{GRANT} and @code{REVOKE} statements, @code{priv_type} may be -specified as any of the following: - -@example -ALL PRIVILEGES FILE RELOAD -ALTER INDEX SELECT -CREATE INSERT SHUTDOWN -DELETE PROCESS UPDATE -DROP REFERENCES USAGE -@end example - -@code{ALL} is a synonym for @code{ALL PRIVILEGES}. @code{REFERENCES} is not -yet implemented. @code{USAGE} is currently a synonym for ``no privileges.'' -It can be used when you want to create a user that has no privileges. - -To revoke the @strong{grant} privilege from a user, use a @code{priv_type} -value of @code{GRANT OPTION}: - -@example -REVOKE GRANT OPTION ON ... FROM ...; -@end example - -The only @code{priv_type} values you can specify for a table are @code{SELECT}, -@code{INSERT}, @code{UPDATE}, @code{DELETE}, @code{CREATE}, @code{DROP}, -@code{GRANT}, @code{INDEX}, and @code{ALTER}. - -The only @code{priv_type} values you can specify for a column (that is, when -you use a @code{column_list} clause) are @code{SELECT}, @code{INSERT}, and -@code{UPDATE}. - -You can set global privileges by using @code{ON *.*} syntax. You can set -database privileges by using @code{ON db_name.*} syntax. If you specify -@code{ON *} and you have a current database, you will set the privileges for -that database. (@strong{WARNING:} If you specify @code{ON *} and you -@emph{don't} have a current database, you will affect the global privileges!) - -In order to accommodate granting rights to users from arbitrary hosts, -@strong{MySQL} supports specifying the @code{user_name} value in the form -@code{user@@host}. If you want to specify a @code{user} string -containing special characters (such as @samp{-}), or a @code{host} string -containing special characters or wild-card characters (such as @samp{%}), you -can quote the user or host name (for example, @code{'test-user'@@'test-hostname'}). - -You can specify wild cards in the hostname. For example, -@code{user@@"%.loc.gov"} applies to @code{user} for any host in the -@code{loc.gov} domain, and @code{user@@"144.155.166.%"} applies to @code{user} -for any host in the @code{144.155.166} class C subnet. - -The simple form @code{user} is a synonym for @code{user@@"%"}. -@strong{NOTE:} If you allow anonymous users to connect to the @strong{MySQL} -server (which is the default), you should also add all local users as -@code{user@@localhost} because otherwise the anonymous user entry for the -local host in the @code{mysql.user} table will be used when the user tries to -log into the @strong{MySQL} server from the local machine! Anonymous users -are defined by inserting entries with @code{User=''} into the -@code{mysql.user} table. You can verify if this applies to you by executing -this query: - -@example -mysql> SELECT Host,User FROM mysql.user WHERE User=''; -@end example - -For the moment, @code{GRANT} only supports host, table, database, and -column names up to 60 characters long. A user name can be up to 16 -characters. - -The privileges for a table or column are formed from the -logical OR of the privileges at each of the four privilege -levels. For example, if the @code{mysql.user} table specifies that a -user has a global @strong{select} privilege, this can't be denied by an -entry at the database, table, or column level. - -The privileges for a column can be calculated as follows: - -@example -global privileges -OR (database privileges AND host privileges) -OR table privileges -OR column privileges -@end example - -In most cases, you grant rights to a user at only one of the privilege -levels, so life isn't normally as complicated as above. The details of the -privilege-checking procedure are presented in -@ref{Privilege system}. - -If you grant privileges for a user/hostname combination that does not exist -in the @code{mysql.user} table, an entry is added and remains there until -deleted with a @code{DELETE} command. In other words, @code{GRANT} may -create @code{user} table entries, but @code{REVOKE} will not remove them; -you must do that explicitly using @code{DELETE}. - -@cindex passwords, setting -In @strong{MySQL} Version 3.22.12 or later, -if a new user is created or if you have global grant privileges, the user's -password will be set to the password specified by the @code{IDENTIFIED BY} -clause, if one is given. If the user already had a password, it is replaced -by the new one. - -@strong{WARNING:} If you create a new user but do not specify an -@code{IDENTIFIED BY} clause, the user has no password. This is insecure. - -Passwords can also be set with the @code{SET PASSWORD} command. -@xref{SET OPTION, , @code{SET OPTION}}. - -If you grant privileges for a database, an entry in the @code{mysql.db} -table is created if needed. When all privileges for the database have been -removed with @code{REVOKE}, this entry is deleted. - -If a user doesn't have any privileges on a table, the table is not displayed -when the user requests a list of tables (for example, with a @code{SHOW TABLES} -statement). - -The @code{WITH GRANT OPTION} clause gives the user the ability to give -to other users any privileges the user has at the specified privilege level. -You should be careful to whom you give the @strong{grant} privilege, as two -users with different privileges may be able to join privileges! - -You cannot grant another user a privilege you don't have yourself; -the @strong{grant} privilege allows you to give away only those privileges -you possess. - -Be aware that when you grant a user the @strong{grant} privilege at a -particular privilege level, any privileges the user already possesses (or -is given in the future!) at that level are also grantable by that user. -Suppose you grant a user the @strong{insert} privilege on a database. If -you then grant the @strong{select} privilege on the database and specify -@code{WITH GRANT OPTION}, the user can give away not only the @strong{select} -privilege, but also @strong{insert}. If you then grant the @strong{update} -privilege to the user on the database, the user can give away the -@strong{insert}, @strong{select} and @strong{update}. - -You should not grant @strong{alter} privileges to a normal user. If you -do that, the user can try to subvert the privilege system by renaming -tables! - -Note that if you are using table or column privileges for even one user, the -server examines table and column privileges for all users and this will slow -down @strong{MySQL} a bit. - -When @code{mysqld} starts, all privileges are read into memory. -Database, table, and column privileges take effect at once, and -user-level privileges take effect the next time the user connects. -Modifications to the grant tables that you perform using @code{GRANT} or -@code{REVOKE} are noticed by the server immediately. -If you modify the grant tables manually (using @code{INSERT}, @code{UPDATE}, -etc.), you should execute a @code{FLUSH PRIVILEGES} statement or run -@code{mysqladmin flush-privileges} to tell the server to reload the grant -tables. -@xref{Privilege changes}. - -@cindex ANSI SQL, differences from -The biggest differences between the ANSI SQL and @strong{MySQL} versions of -@code{GRANT} are: - -@itemize @bullet -@item -In @strong{MySQL} privileges are given for an username + hostname combination -and not only for an username. - -@item -ANSI SQL doesn't have global or database-level privileges, and ANSI SQL -doesn't support all privilege types that @strong{MySQL} supports. -@strong{MySQL} doesn't support the ANSI SQL @code{TRIGGER}, @code{EXECUTE} or -@code{UNDER} privileges. - -@item -ANSI SQL privileges are structured in a hierarchal manner. If you remove -an user, all privileges the user has granted are revoked. In -@strong{MySQL} the granted privileges are not automatically revoked, but -you have to revoke these yourself if needed. - -@item -If you in @strong{MySQL} have the @code{INSERT} grant on only part of the -columns in a table, you can execute @code{INSERT} statements on the -table; The columns for which you don't have the @code{INSERT} privilege -will set to their default values. ANSI SQL requires you to have the -@code{INSERT} privilege on all columns. - -@item -When you drop a table in ANSI SQL, all privileges for the table are revoked. -If you revoke a privilege in ANSI SQL, all privileges that were granted based -on this privilege are also revoked. In @strong{MySQL}, privileges can be -dropped only with explicit @code{REVOKE} commands or by manipulating the -@strong{MySQL} grant tables. -@end itemize @cindex indexes @cindex indexes, multi-part @cindex multi-part index @findex CREATE INDEX -@node CREATE INDEX, DROP INDEX, GRANT, Reference +@node CREATE INDEX, DROP INDEX, SET TRANSACTION, Reference @section @code{CREATE INDEX} Syntax @example @@ -26050,7 +31716,7 @@ used them. @cindex MySQL table types @cindex @code{MyISAM} table type @cindex types, of tables -@node Table types, Server, Reference, Top +@node Table types, Fulltext Search, Reference, Top @chapter MySQL Table Types As of @strong{MySQL} Version 3.23.6, you can choose between three basic @@ -28465,1339 +34131,12 @@ not trivial). @end itemize - -@node Server, Replication, Table types, Top -@chapter MySQL Server Functions - -@cindex functions, server -@cindex server functions - -@menu -* Languages:: What languages are supported by @strong{MySQL}? -@end menu - -This chapter describes the languages @strong{MySQL} supports, how sorting -works in @strong{MySQL}, and how to add new character sets to @strong{MySQL}. -You will also find information about maximum table sizes in this chapter. - -@node Languages, , Server, Server -@section What Languages Are Supported by MySQL? - -@cindex error messages, languages -@cindex messages, languages -@cindex files, error messages -@cindex language support - -@code{mysqld} can issue error messages in the following languages: -Czech, Danish, Dutch, English (the default), Estonian, French, German, Greek, -Hungarian, Italian, Japanese, Korean, Norwegian, Norwegian-ny, Polish, -Portuguese, Romanian, Russian, Slovak, Spanish, and Swedish. - -To start @code{mysqld} with a particular language, use either the -@code{--language=lang} or @code{-L lang} options. For example: - -@example -shell> mysqld --language=swedish -@end example - -or: - -@example -shell> mysqld --language=/usr/local/share/swedish -@end example - -Note that all language names are specified in lowercase. - -The language files are located (by default) in -@file{@var{mysql_base_dir}/share/@var{LANGUAGE}/}. - -To update the error message file, you should edit the @file{errmsg.txt} file -and execute the following command to generate the @file{errmsg.sys} file: - -@example -shell> comp_err errmsg.txt errmsg.sys -@end example - -If you upgrade to a newer version of @strong{MySQL}, remember to repeat -your changes with the new @file{errmsg.txt} file. - -@menu -* Character sets:: The character set used for data and sorting -* Adding character set:: Adding a new character set -* Character arrays:: The character definition arrays -* String collating:: String collating support -* Multi-byte characters:: Multi-byte character support -@end menu - -@cindex character sets -@cindex data, character sets -@cindex sorting, character sets -@node Character sets, Adding character set, Languages, Languages -@subsection The Character Set Used for Data and Sorting - -By default, @strong{MySQL} uses the ISO-8859-1 (Latin1) character set -with sorting according to Swedish/Finnish. This is the character set suitable -in the USA and western Europe. - -All standard @strong{MySQL} binaries are compiled with -@code{--with-extra-charsets=complex}. This will add code to all -standard programs to be able to handle @code{latin1} and all multi-byte -character sets within the binary. Other character sets will be -loaded from a character-set definition file when needed. - -The character set determines what characters are allowed in names and how -things are sorted by the @code{ORDER BY} and @code{GROUP BY} clauses of -the @code{SELECT} statement. - -You can change the character set with the @code{--default-character-set} -option when you start the server. The character sets available depend -on the @code{--with-charset=charset} and @code{--with-extra-charset= -list-of-charset | complex | all} options to @code{configure}, and the -character set configuration files listed in -@file{SHAREDIR/charsets/Index}. @xref{configure options}. - -If you change the character set when running @strong{MySQL} (which may -also change the sort order), you must run myisamchk -r -q on all -tables. Otherwise your indexes may not be ordered correctly. - -When a client connects to a @strong{MySQL} server, the server sends the -default character set in use to the client. The client will switch to -use this character set for this connection. - -One should use @code{mysql_real_escape_string()} when escaping strings -for a SQL query. @code{mysql_real_escape_string()} is identical to the -old @code{mysql_escape_string()} function, except that it takes the MYSQL -connection handle as the first parameter. - -If the client is compiled with different paths than where the server is -installed and the user who configured @strong{MySQL} didn't included all -character sets in the @strong{MySQL} binary, one must specify for -the client where it can find the additional character sets it will need -if the server runs with a different character set than the client. - -One can specify this by putting in a @strong{MySQL} option file: - -@example -[client] -character-sets-dir=/usr/local/mysql/share/mysql/charsets -@end example - -where the path points to where the dynamic @strong{MySQL} character sets -are stored. - -One can force the client to use specific character set by specifying: - -@example -[client] -default-character-set=character-set-name -@end example - -but normally this is never needed. - -@cindex character sets, adding -@cindex adding, character sets -@node Adding character set, Character arrays, Character sets, Languages -@subsection Adding a New Character Set - -To add another character set to @strong{MySQL}, use the following procedure. - -Decide if the set is simple or complex. If the character set -does not need to use special string collating routines for -sorting and does not need multi-byte character support, it is -simple. If it needs either of those features, it is complex. - -For example, @code{latin1} and @code{danish} are simple charactersets while -@code{big5} or @code{czech} are complex character sets. - -In the following section, we have assumed that you name your character -set @code{MYSET}. - -For a simple character set do the following: - -@enumerate -@item -Add MYSET to the end of the @file{sql/share/charsets/Index} file -Assign an unique number to it. - -@item -Create the file @file{sql/share/charsets/MYSET.conf}. -(You can use @file{sql/share/charsets/latin1.conf} as a base for this). - -The syntax for the file very simple: - -@itemize @bullet -@item -Comments start with a '#' character and proceed to the end of the line. -@item -Words are separated by arbitrary amounts of whitespace. -@item -When defining the character set, every word must be a number in hexadecimal -format -@item -The @code{ctype} array takes up the first 257 words. The -@code{to_lower}, @code{to_upper} and @code{sort_order} arrays take up -256 words each after that. -@end itemize - -@xref{Character arrays}. - -@item -Add the character set name to the @code{CHARSETS_AVAILABLE} and -@code{COMPILED_CHARSETS} lists in @code{configure.in}. - -@item -Reconfigure, recompile, and test. - -@end enumerate - -For a complex character set do the following: - -@enumerate -@item -Create the file @file{strings/ctype-MYSET.c} in the @strong{MySQL} source -distribution. - -@item -Add MYSET to the end of the @file{sql/share/charsets/Index} file. -Assign an unique number to it. - -@item -Look at one of the existing @file{ctype-*.c} files to see what needs to -be defined, for example @file{strings/ctype-big5.c}. Note that the -arrays in your file must have names like @code{ctype_MYSET}, -@code{to_lower_MYSET}, and so on. This corresponds to the arrays -in the simple character set. @xref{Character arrays}. For a complex -character set - -@item -Near the top of the file, place a special comment like this: - -@example -/* - * This comment is parsed by configure to create ctype.c, - * so don't change it unless you know what you are doing. - * - * .configure. number_MYSET=MYNUMBER - * .configure. strxfrm_multiply_MYSET=N - * .configure. mbmaxlen_MYSET=N - */ -@end example - -The @code{configure} program uses this comment to include -the character set into the @strong{MySQL} library automatically. - -The strxfrm_multiply and mbmaxlen lines will be explained in -the following sections. Only include them if you the string -collating functions or the multi-byte character set functions, -respectively. - -@item -You should then create some of the following functions: - -@itemize @bullet -@item @code{my_strncoll_MYSET()} -@item @code{my_strcoll_MYSET()} -@item @code{my_strxfrm_MYSET()} -@item @code{my_like_range_MYSET()} -@end itemize - -@xref{String collating}. - -@item -Add the character set name to the @code{CHARSETS_AVAILABLE} and -@code{COMPILED_CHARSETS} lists in @code{configure.in}. - -@item -Reconfigure, recompile, and test. -@end enumerate - -The file @file{sql/share/charsets/README} includes some more instructions. - -If you want to have the character set included in the @strong{MySQL} -distribution, mail a patch to @email{internals@@lists.mysql.com}. - -@node Character arrays, String collating, Adding character set, Languages -@subsection The character definition arrays - -@code{to_lower[]} and @code{to_upper[]} are simple arrays that hold the -lowercase and uppercase characters corresponding to each member of the -character set. For example: - -@example -to_lower['A'] should contain 'a' -to_upper['a'] should contain 'A' -@end example - -@code{sort_order[]} is a map indicating how characters should be ordered for -comparison and sorting purposes. For many character sets, this is the same as -@code{to_upper[]} (which means sorting will be case insensitive). -@strong{MySQL} will sort characters based on the value of -@code{sort_order[character]}. For more complicated sorting rules, see -the discussion of string collating below. @xref{String collating}. - -@code{ctype[]} is an array of bit values, with one element for one character. -(Note that @code{to_lower[]}, @code{to_upper[]}, and @code{sort_order[]} -are indexed by character value, but @code{ctype[]} is indexed by character -value + 1. This is an old legacy to be able to handle EOF.) - -You can find the following bitmask definitions in @file{m_ctype.h}: - -@example -#define _U 01 /* Uppercase */ -#define _L 02 /* Lowercase */ -#define _N 04 /* Numeral (digit) */ -#define _S 010 /* Spacing character */ -#define _P 020 /* Punctuation */ -#define _C 040 /* Control character */ -#define _B 0100 /* Blank */ -#define _X 0200 /* heXadecimal digit */ -@end example - -The @code{ctype[]} entry for each character should be the union of the -applicable bitmask values that describe the character. For example, -@code{'A'} is an uppercase character (@code{_U}) as well as a -hexadecimal digit (@code{_X}), so @code{ctype['A'+1]} should contain the -value: - -@example -_U + _X = 01 + 0200 = 0201 -@end example - -@cindex collating, strings -@cindex string collating -@node String collating, Multi-byte characters, Character arrays, Languages -@subsection String Collating Support - -If the sorting rules for your language are too complex to be handled -with the simple @code{sort_order[]} table, you need to use the string -collating functions. - -Right now the best documentation on this is the character sets that are -already implemented. Look at the big5, czech, gbk, sjis, and tis160 -character sets for examples. - -You must specify the @code{strxfrm_multiply_MYSET=N} value in the -special comment at the top of the file. @code{N} should be set to -the maximum ratio the strings may grow during @code{my_strxfrm_MYSET} (it -must be a positive integer). - -@cindex characters, multi-byte -@cindex multi-byte characters -@node Multi-byte characters, , String collating, Languages -@subsection Multi-byte Character Support - -If your want to add support for a new character set that includes -multi-byte characters, you need to use the multi-byte character -functions. - -Right now the best documentation on this is the character sets that are -already implemented. Look at the euc_kr, gb2312, gbk, sjis and ujis -character sets for examples. These are implemented in the -@code{ctype-'charset'.c} files in the @file{strings} directory. - -You must specify the @code{mbmaxlen_MYSET=N} value in the special -comment at the top of the source file. @code{N} should be set to the -size in bytes of the largest character in the set. - - -@cindex replication -@cindex increasing, speed -@cindex speed, increasing -@cindex databases, replicating -@node Replication, Fulltext Search, Server, Top -@chapter Replication in MySQL - -@menu -* Replication Intro:: Introduction -* Replication Implementation:: Replication Implementation Overview -* Replication HOWTO:: HOWTO -* Replication Features:: Replication Features -* Replication Options:: Replication Options in my.cnf -* Replication SQL:: SQL Commands related to replication -* Replication FAQ:: Frequently Asked Questions about replication -* Replication Problems:: Troubleshooting Replication. -@end menu - -This chapter describes the various replication features in @strong{MySQL}. -It serves as a reference to the options available with replication. -You will be introduced to replication and learn how to implement it. -Towards the end, there are some frequently asked questions and descriptions -of problems and how to solve them. - -@node Replication Intro, Replication Implementation, Replication, Replication -@section Introduction - -One way replication can be used is to increase both robustness and -speed. For robustness you can have two systems and can switch to the backup if -you have problems with the master. The extra speed is achieved by -sending a part of the non-updating queries to the replica server. Of -course this only works if non-updating queries dominate, but that is the -normal case. - -Starting in Version 3.23.15, @strong{MySQL} supports one-way replication -internally. One server acts as the master, while the other acts as the -slave. Note that one server could play the roles of master in one pair -and slave in the other. The master server keeps a binary log of updates -(@xref{Binary log}.) and an index file to binary logs to keep track of -log rotation. The slave, upon connecting, informs the master where it -left off since the last successfully propagated update, catches up on -the updates, and then blocks and waits for the master to notify it of -the new updates. - -Note that if you are replicating a database, all updates to this -database should be done through the master! - -On older servers one can use the update log to do simple replication. -@xref{Log Replication}. - -Another benefit of using replication is that one can get live backups of -the system by doing a backup on a slave instead of doing it on the -master. @xref{Backup}. - -@cindex master-slave setup -@node Replication Implementation, Replication HOWTO, Replication Intro, Replication -@section Replication Implementation Overview - -@strong{MySQL} replication is based on the server keeping track of all -changes to your database (updates, deletes, etc) in the binary -log. (@xref{Binary log}.) and the slave server(s) reading the saved -queries from the master server's binary log so that the slave can -execute the same queries on its copy of the data. - -It is @strong{very important} to realize that the binary log is simply a -record starting from a fixed point in time (the moment you enable binary -logging). Any slaves which you set up will need copies of all the data -from your master as it existed the moment that you enabled binary -logging on the master. If you start your slaves with data that doesn't -agree with what was on the master @strong{when the binary log was -started}, your slaves may fail. - -A future version (4.0) of @strong{MySQL} will remove the need to keep a -(possibly large) snapshot of data for new slaves that you might wish to -set up through the live backup functionality with no locking required. -However, at this time, it is necessary to block all writes either with a -global read lock or by shutting down the master while taking a snapshot. - -Once a slave is properly configured and running, it will simply connect -to the master and wait for updates to process. If the master goes away -or the slave loses connectivity with your master, it will keep trying to -connect every @code{master-connect-retry} seconds until it is able to -reconnect and resume listening for updates. - -Each slave keeps track of where it left off. The master server has no -knowledge of how many slaves there are or which ones are up-to-date at -any given time. - -The next section explains the master/slave setup process in more detail. - -@node Replication HOWTO, Replication Features, Replication Implementation, Replication -@section HOWTO - -Below is a quick description of how to set up complete replication on -your current @strong{MySQL} server. It assumes you want to replicate all -your databases and have not configured replication before. You will need -to shutdown your master server briefly to complete the steps outlined -below. - -@enumerate -@item -Make sure you have a recent version of @strong{MySQL} installed on the master -and slave(s). - -Use Version 3.23.29 or higher. Previous releases used a different binary -log format and had bugs which have been fixed in newer releases. Please, -do not report bugs until you have verified that the problem is present -in the latest release. -@item -Set up special a replication user on the master with the @code{FILE} -privilege and permission to connect from all the slaves. If the user is -only doing replication (which is recommended), you don't need to grant any -additional privileges. - -For example, to create a user named @code{repl} which can access your -master from any host, you might use this command: - -@example -GRANT FILE ON *.* TO repl@@"%" IDENTIFIED BY ''; -@end example - -@item -Shut down @strong{MySQL} on the master. - -@example -mysqladmin -u root -p shutdown -@end example - -@item -Snapshot all the data on your master server. - -The easiest way to do this (on Unix) is to simply use @strong{tar} to -produce an archive of your entire data directory. The exact data -directory location depends on your installation. - -@example -tar -cvf /tmp/mysql-snapshot.tar /path/to/data-dir -@end example - -Windows users can use WinZip or similar software to create an archive of -the data directory. - -@item -In @code{my.cnf} on the master add @code{log-bin} and -@code{server-id=unique number} to the @code{[mysqld]} section and -restart it. It is very important that the id of the slave is different from -the id of the master. Think of @code{server-id} as something similar -to the IP address - it uniquely identifies the server instance in the -community of replication partners. - -@example -[mysqld] -log-bin -server-id=1 -@end example - -@item -Restart @strong{MySQL} on the master. - -@item -Add the following to @code{my.cnf} on the slave(s): - -@example -master-host= -master-user= -master-password= -master-port= -server-id= -@end example - -replacing the values in <> with what is relevant to your system. - -@code{server-id} must be different for each server participating in -replication. If you don't specify a server-id, it will be set to 1 if -you have not defined @code{master-host}, else it will be set to 2. Note -that in the case of @code{server-id} omission the master will refuse -connections from all slaves, and the slave will refuse to connect to a -master. Thus, omitting @code{server-id} is only good for backup with a -binary log. - - -@item -Copy the snapshot data into your data directory on your slave(s). Make -sure that the privileges on the files and directories are correct. The -user which @strong{MySQL} runs as needs to be able to read and write to -them, just as on the master. - -@item Restart the slave(s). - -@end enumerate - -After you have done the above, the slave(s) should connect to the master -and catch up on any updates which happened since the snapshot was taken. - -If you have forgotten to set @code{server-id} for the slave you will get -the following error in the error log file: - -@example -Warning: one should set server_id to a non-0 value if master_host is set. -The server will not act as a slave. -@end example - -If you have forgot to do this for the master, the slaves will not be -able to connect to the master. - -If a slave is not able to replicate for any reason, you will find error -messages in the error log on the slave. - -Once a slave is replicating, you will find a file called -@code{master.info} in the same directory as your error log. The -@code{master.info} file is used by the slave to keep track of how much -of the master's binary log is has processed. @strong{Do not} remove or -edit the file, unless you really know what you are doing. Even in that case, -it is preferred that you use @code{CHANGE MASTER TO} command. - -@cindex options, replication -@cindex @code{my.cnf} file -@cindex files,@code{my.cnf} -@node Replication Features, Replication Options, Replication HOWTO, Replication -@section Replication Features and known problems - -Below is an explanation of what is supported and what is not: - -@itemize @bullet -@item -Replication will be done correctly with @code{AUTO_INCREMENT}, -@code{LAST_INSERT_ID}, and @code{TIMESTAMP} values. -@item -@code{RAND()} in updates does not replicate properly. Use -@code{RAND(some_non_rand_expr)} if you are replicating updates with -@code{RAND()}. You can, for example, use @code{UNIX_TIMESTAMP()} for the -argument to @code{RAND()}. -@item -You have to use the same character set (@code{--default-character-set}) -on the master and the slave. If not, you may get duplicate key errors on -the slave, because a key that is regarded as unique on the master may -not be that in the other character set. -@item -@code{LOAD DATA INFILE} will be handled properly as long as the file -still resides on the master server at the time of update -propagation. @code{LOAD LOCAL DATA INFILE} will be skipped. -@item -Update queries that use user variables are not replication-safe (yet). -@item -@code{FLUSH} commands are not stored in the binary log and are because -of this not replicated to the slaves. This is not normally a problem as -@code{FLUSH} doesn't change anything. This does however mean that if you -update the @code{MySQL} privilege tables directly without using -@code{GRANT} statement and you replicate the @code{MySQL} privilege -database, you must do a @code{FLUSH PRIVILEGES} on your slaves to put -the new privileges into effect. -@item -Temporary tables starting in 3.23.29 are replicated properly with the -exception of the case when you shut down slave server ( not just slave thread), -you have some temporary tables open, and the are used in subsequent updates. -To deal with this problem, to shut down the slave, do @code{SLAVE STOP}, then -check @code{Slave_open_temp_tables} variable to see if it is 0, then issue -@code{mysqladmin shutdown}. If the number is not 0, restart the slave thread -with @code{SLAVE START} and see -if you have better luck next time. There will be a cleaner solution, but it -has to wait until version 4.0. -In earlier versions temporary tables are not being replicated properly - we -recommend that you either upgrade, or execute @code{SET SQL_LOG_BIN=0} on -your clients before all queries with temp tables. -@item -@strong{MySQL} only supports one master and many slaves. We will in 4.x -add a voting algorithm to automatically change master if something goes -wrong with the current master. We will also introduce 'agent' processes -to help doing load balancing by sending select queries to different -slaves. -@item -Starting in Version 3.23.26, it is safe to connect servers in a circular -master-slave relationship with @code{log-slave-updates} enabled. -Note, however, that many queries will not work right in this kind of -setup unless your client code is written to take care of the potential -problems that can happen from updates that occur in different sequence -on different servers. - -This means that you can do a setup like the following: - -@example -A -> B -> C -> A -@end example - -This setup will only works if you only do non conflicting updates -between the tables. In other words, if you insert data in A and C, you -should never insert a row in A that may have a conflicting key with a -row insert in C. You should also not update the sam rows on two servers -if the order in which the updates are applied matters. - -Note that the log format has changed in Version 3.23.26 so that -pre-3.23.26 slaves will not be able to read it. -@item -If the query on the slave gets an error, the slave thread will -terminate, and a message will appear in the @code{.err} file. You should -then connect to the slave manually, fix the cause of the error (for -example, non-existent table), and then run @code{SLAVE START} sql -command (available starting in Version 3.23.16). In Version 3.23.15, you -will have to restart the server. -@item -If connection to the master is lost, the slave will retry immediately, -and then in case of failure every @code{master-connect-retry} (default -60) seconds. Because of this, it is safe to shut down the master, and -then restart it after a while. The slave will also be able to deal with -network connectivity outages. -@item -Shutting down the slave (cleanly) is also safe, as it keeps track of -where it left off. Unclean shutdowns might produce problems, especially -if disk cache was not synced before the system died. Your system fault -tolerance will be greatly increased if you have a good UPS. -@item -If the master is listening on a non-standard port, you will also need to -specify this with @code{master-port} parameter in @code{my.cnf} . -@item -In Version 3.23.15, all of the tables and databases will be -replicated. Starting in Version 3.23.16, you can restrict replication to -a set of databases with @code{replicate-do-db} directives in -@code{my.cnf} or just exclude a set of databases with -@code{replicate-ignore-db}. Note that up until Version 3.23.23, there was a bug -that did not properly deal with @code{LOAD DATA INFILE} if you did it in -a database that was excluded from replication. -@item -Starting in Version 3.23.16, @code{SET SQL_LOG_BIN = 0} will turn off -replication (binary) logging on the master, and @code{SET SQL_LOG_BIN = -1} will turn in back on - you must have the process privilege to do -this. -@item -Starting in Version 3.23.19, you can clean up stale replication leftovers when -something goes wrong and you want a clean start with @code{FLUSH MASTER} -and @code{FLUSH SLAVE} commands. In Version 3.23.26 we have renamed them to -@code{RESET MASTER} and @code{RESET SLAVE} respectively to clarify -what they do. The old @code{FLUSH} variants still work, though, for -compatibility. - -@item -Starting in Version 3.23.21, you can use @code{LOAD TABLE FROM MASTER} for -network backup and to set up replication initially. We have recently -received a number of bug reports concerning it that we are investigating, so -we recommend that you use it only in testing until we make it more stable. -@item -Starting in Version 3.23.23, you can change masters and adjust log position -with @code{CHANGE MASTER TO}. -@item -Starting in Version 3.23.23, you tell the master that updates in certain -databases should not be logged to the binary log with @code{binlog-ignore-db}. -@item -Starting in Version 3.23.26, you can use @code{replicate-rewrite-db} to tell -the slave to apply updates from one database on the master to the one -with a different name on the slave. -@item -Starting in Version 3.23.28, you can use @code{PURGE MASTER LOGS TO 'log-name'} -to get rid of old logs while the slave is running. -@end itemize - -@node Replication Options, Replication SQL, Replication Features, Replication -@section Replication Options in my.cnf - -If you are using replication, we recommend you to use @strong{MySQL} Version -3.23.30 or later. Older versions work, but they do have some bugs and are -missing some features. - -On both master and slave you need to use the @code{server-id} option. -This sets an unique replication id. You should pick a unique value in the -range between 1 to 2^32-1 for each master and slave. -Example: @code{server-id=3} - -The following table has the options you can use for the @strong{MASTER}: - -@multitable @columnfractions .3 .7 - -@item @strong{Option} @tab @strong{Description} -@item @code{log-bin=filename} @tab -Write to a binary update log to the specified location. Note that if you -give it a parameter with an extension (for example, -@code{log-bin=/mysql/logs/replication.log} ) versions up to 3.23.24 will -not work right during replication if you do @code{FLUSH LOGS} . The -problem is fixed in Version 3.23.25. If you are using this kind of log -name, @code{FLUSH LOGS} will be ignored on binlog. To clear the log, run -@code{FLUSH MASTER}, and do not forget to run @code{FLUSH SLAVE} on all -slaves. In Version 3.23.26 and in later versions you should use -@code{RESET MASTER} and @code{RESET SLAVE} - -@item @code{log-bin-index=filename} @tab -Because the user could issue the @code{FLUSH LOGS} command, we need to -know which log is currently active and which ones have been rotated out -and in what sequence. This information is stored in the binary log index file. -The default is `hostname`.index. You can use this option if you want to -be a rebel. (Example: @code{log-bin-index=db.index}) - -@item @code{sql-bin-update-same} @tab -If set, setting @code{SQL_LOG_BIN} to a value will automatically set -@code{SQL_LOG_UPDATE} to the same value and vice versa. - -@item @code{binlog-do-db=database_name} @tab -Tells the master it should log updates for the specified database, and -exclude all others not explicitly mentioned. -(Example: @code{binlog-do-db=some_database}) - -@item @code{binlog-ignore-db=database_name} @tab -Tells the master that updates to the given database should not be logged -to the binary log (Example: @code{binlog-ignore-db=some_database}) -@end multitable - -The following table has the options you can use for the @strong{SLAVE}: - -@multitable @columnfractions .3 .7 - -@item @strong{Option} @tab @strong{Description} -@item @code{master-host=host} @tab -Master hostname or IP address for replication. If not set, the slave -thread will not be started. -(Example: @code{master-host=db-master.mycompany.com}) - -@item @code{master-user=username} @tab -The user the slave thread will us for authentication when connecting to -the master. The user must have @code{FILE} privilege. If the master user -is not set, user @code{test} is assumed. (Example: -@code{master-user=scott}) - -@item @code{master-password=password} @tab -The password the slave thread will authenticate with when connecting to -the master. If not set, an empty password is assumed. (Example: -@code{master-password=tiger}) - -@item @code{master-port=portnumber} @tab -The port the master is listening on. If not set, the compiled setting of -@code{MYSQL_PORT} is assumed. If you have not tinkered with -@code{configure} options, this should be 3306. (Example: -@code{master-port=3306}) - -@item @code{master-connect-retry=seconds} @tab -The number of seconds the slave thread will sleep before retrying to -connect to the master in case the master goes down or the connection is -lost. Default is 60. (Example: @code{master-connect-retry=60}) - -@item @code{master-info-file=filename} @tab -The location of the file that remembers where we left off on the master -during the replication process. The default is master.info in the data -directory. Sasha: The only reason I see for ever changing the default -is the desire to be rebelious. (Example: -@code{master-info-file=master.info}) - -@item @code{replicate-do-table=db_name.table_name} @tab -Tells the slave thread to restrict replication to the specified database. -To specify more than one table, use the directive multiple times, -once for each table. . -(Example: @code{replicate-do-table=some_db.some_table}) - -@item @code{replicate-ignore-table=db_name.table_name} @tab -Tells the slave thread to not replicate to the specified table. To -specify more than one table to ignore, use the directive multiple -times, once for each table.(Example: -@code{replicate-ignore-table=db_name.some_table}) - -@item @code{replicate-wild-do-table=db_name.table_name} @tab -Tells the slave thread to restrict replication to the tables that match the -specified wildcard pattern. . -To specify more than one table, use the directive multiple times, -once for each table. . -(Example: @code{replicate-do-table=foo%.bar%} will replicate only updates -to tables in all databases that start with foo and whose table names -start with bar) - -@item @code{replicate-wild-ignore-table=db_name.table_name} @tab -Tells the slave thread to not replicate to the tables that match the given -wild card pattern. To -specify more than one table to ignore, use the directive multiple -times, once for each table.(Example: -@code{replicate-ignore-table=foo%.bar%} - will not upates to tables in all databases that start with foo and whose table names -start with bar) - -@item @code{replicate-ignore-db=database_name} @tab -Tells the slave thread to not replicate to the specified database. To -specify more than one database to ignore, use the directive multiple -times, once for each database. This option will not work if you use cross -database updates. If you need cross database updates to work, make sure -you have 3.23.28 or later, and use -@code{replicate-wild-ignore-table=db_name.%}(Example: -@code{replicate-ignore-db=some_db}) - -@item @code{replicate-do-db=database_name} @tab -Tells the slave thread to restrict replication to the specified database. -To specify more than one database, use the directive multiple times, -once for each database. Note that this will only work if you do not use -cross-database queries such as @code{UPDATE some_db.some_table SET -foo='bar'} while having selected a different or no database. If you need -cross database updates to work, make sure -you have 3.23.28 or later, and use -@code{replicate-wild-do-table=db_name.%} -(Example: @code{replicate-do-db=some_db}) - -@item @code{log-slave-updates} @tab -Tells the slave to log the updates from the slave thread to the binary -log. Off by default. You will need to turn it on if you plan to -daisy-chain the slaves. - -@item @code{replicate-rewrite-db=from_name->to_name} @tab -Updates to a database with a different name than the original (Example: -@code{replicate-rewrite-db=master_db_name->slave_db_name} - -@item @code{skip-slave-start} @tab -Tells the slave server not to start the slave on the startup. The user -can start it later with @code{SLAVE START}. - -@item @code{slave_read_timeout=#} -Number of seconds to wait for more data from the master before aborting -the read. -@end multitable - -@cindex SQL commands, replication -@cindex commands, replication -@cindex replication, commands -@node Replication SQL, Replication FAQ, Replication Options, Replication -@section SQL Commands Related to Replication - -Replication can be controlled through the SQL interface. Below is the -summary of commands: - -@multitable @columnfractions .30 .70 -@item @strong{Command} @tab @strong{Description} - -@item @code{SLAVE START} - @tab Starts the slave thread. (Slave) - -@item @code{SLAVE STOP} - @tab Stops the slave thread. (Slave) - -@item @code{SET SQL_LOG_BIN=0} - @tab Disables update logging if the user has process privilege. - Ignored otherwise. (Master) - -@item @code{SET SQL_LOG_BIN=1} - @tab Re-enables update logging if the user has process privilege. - Ignored otherwise. (Master) - -@item @code{SET SQL_SLAVE_SKIP_COUNTER=n} - @tab Skip the next @code{n} events from the master. Only valid when -the slave thread is not running, otherwise, gives an error. Useful for -recovering from replication glitches. - -@item @code{RESET MASTER} - @tab Deletes all binary logs listed in the index file, resetting the binlog -index file to be empty. In pre-3.23.26 versions, @code{FLUSH MASTER} (Master) - -@item @code{RESET SLAVE} - @tab Makes the slave forget its replication position in the master -logs. In pre 3.23.26 versions the command was called -@code{FLUSH SLAVE}(Slave) - -@item @code{LOAD TABLE tblname FROM MASTER} - @tab Downloads a copy of the table from master to the slave. (Slave) - -@item @code{CHANGE MASTER TO master_def_list} - @tab Changes the master parameters to the values specified in -@code{master_def_list} and restarts the slave thread. @code{master_def_list} -is a comma-separated list of @code{master_def} where @code{master_def} is -one of the following: @code{MASTER_HOST}, @code{MASTER_USER}, -@code{MASTER_PASSWORD}, @code{MASTER_PORT}, @code{MASTER_CONNECT_RETRY}, -@code{MASTER_LOG_FILE}, @code{MASTER_LOG_POS}. Example: - -@example - -CHANGE MASTER TO - MASTER_HOST='master2.mycompany.com', - MASTER_USER='replication', - MASTER_PASSWORD='bigs3cret', - MASTER_PORT=3306, - MASTER_LOG_FILE='master2-bin.001', - MASTER_LOG_POS=4; - -@end example - -You only need to specify the values that need to be changed. The values that -you omit will stay the same with the exception of when you change the host or -the port. In that case, the slave will assume that since you are connecting to -a different host or a different port, the master is different. Therefore, the -old values of log and position are not applicable anymore, and will -automatically be reset to an empty string and 0, respectively (the start -values). Note that if you restart the slave, it will remember its last master. -If this is not desirable, you should delete the @file{master.info} file before -restarting, and the slave will read its master from @code{my.cnf} or the -command line. (Slave) - -@item @code{SHOW MASTER STATUS} @tab Provides status information on the binlog of the master. (Master) - -@item @code{SHOW SLAVE STATUS} @tab Provides status information on essential parameters of the slave thread. (Slave) -@item @code{SHOW MASTER LOGS} @tab Only available starting in Version 3.23.28. Lists the binary logs on the master. You should use this command prior to @code{PURGE MASTER LOGS TO} to find out how far you should go. - -@item @code{PURGE MASTER LOGS TO 'logname'} - @tab Available starting in Version 3.23.28. Deletes all the -replication logs that are listed in the log -index as being prior to the specified log, and removed them from the -log index, so that the given log now becomes first. Example: - -@example -PURGE MASTER LOGS TO 'mysql-bin.010' -@end example - -This command will do nothing and fail with an error if you have an -active slave that is currently reading one of the logs you are trying to -delete. However, if you have a dormant slave, and happen to purge one of -the logs it wants to read, the slave will be unable to replicate once it -comes up. The command is safe to run while slaves are replicating - you -do not need to stop them. - -You must first check all the slaves with @code{SHOW SLAVE STATUS} to -see which log they are on, then do a listing of the logs on the -master with @code{SHOW MASTER LOGS}, find the earliest log among all -the slaves (if all the slaves are up to date, this will be the -last log on the list), backup all the logs you are about to delete -(optional) and purge up to the target log. - -@end multitable - -@node Replication FAQ, Replication Problems, Replication SQL, Replication -@section Replication FAQ - -@cindex @code{Binlog_Dump} -@strong{Q}: Why do I sometimes see more than one @code{Binlog_Dump} thread on -the master after I have restarted the slave? - -@strong{A}: @code{Binlog_Dump} is a continuous process that is handled by the -server in the following way: - -@itemize @bullet -@item -Catch up on the updates. -@item -Once there are no more updates left, go into @code{pthread_cond_wait()}, -from which we can be awakened either by an update or a kill. -@item -On wake up, check the reason. If we are not supposed to die, continue -the @code{Binlog_dump} loop. -@item -If there is some fatal error, such as detecting a dead client, -terminate the loop. -@end itemize - -So if the slave thread stops on the slave, the corresponding -@code{Binlog_Dump} thread on the master will not notice it until after -at least one update to the master (or a kill), which is needed to wake -it up from @code{pthread_cond_wait()}. In the meantime, the slave -could have opened another connection, which resulted in another -@code{Binlog_Dump} thread. - -The above problem should not be present in Version 3.23.26 and later -versions. In Version 3.23.26 we added @code{server-id} to each -replication server, and now all the old zombie threads are killed on the -master when a new replication thread connects from the same slave - -@strong{Q}: How do I rotate replication logs? - -@strong{A}: In Version 3.23.28 you should use @code{PURGE MASTER LOGS -TO} command after determining which logs can be deleted, and optionally -backing them up first. In earlier versions the process is much more -painful, and cannot be safely done without stopping all the slaves in -the case that you plan to re-use log names. You will need to stop the -slave threads, edit the binary log index file, delete all the old logs, -restart the master, start slave threads, and then remove the old log files. - - -@strong{Q}: How do I upgrade on a hot replication setup? - -@strong{A}: If you are upgrading pre-3.23.26 versions, you should just -lock the master tables, let the slave catch up, then run @code{FLUSH -MASTER} on the master, and @code{FLUSH SLAVE} on the slave to reset the -logs, then restart new versions of the master and the slave. Note that -the slave can stay down for some time - since the master is logging -all the updates, the slave will be able to catch up once it is up and -can connect. - -After 3.23.26, we have locked the replication protocol for modifications, so -you can upgrade masters and slave on the fly to a newer 3.23 version and you -can have different versions of @strong{MySQL} running on the slave and the -master, as long as they are both newer than 3.23.26. - -@cindex replication, two-way -@strong{Q}: What issues should I be aware of when setting up two-way -replication? - -@strong{A}: @strong{MySQL} replication currently does not support any -locking protocol between master and slave to guarantee the atomicity of -a distributed (cross-server) update. In in other words, it is possible -for client A to make an update to co-master 1, and in the meantime, -before it propagates to co-master 2, client B could make an update to -co-master 2 that will make the update of client A work differently than -it did on co-master 1. Thus when the update of client A will make it -to co-master 2, it will produce tables that will be different than -what you have on co-master 1, even after all the updates from co-master -2 have also propagated. So you should not co-chain two servers in a -two-way replication relationship, unless you are sure that you updates -can safely happen in any order, or unless you take care of mis-ordered -updates somehow in the client code. - - -You must also realize that two-way replication actually does not improve -performance very much, if at all, as far as updates are concerned. Both -servers need to do the same amount of updates each, as you would have -one server do. The only difference is that there will be a little less -lock contention, because the updates originating on another server will -be serialized in one slave thread. This benefit, though, might be -offset by network delays. - -@cindex performance, improving -@cindex increasing, performance -@strong{Q}: How can I use replication to improve performance of my system? - -@strong{A}: You should set up one server as the master, and direct all -writes to it, and configure as many slaves as you have the money and -rackspace for, distributing the reads among the master and the slaves. -You can also start the slaves with @code{--skip-bdb}, -@code{--low-priority-updates} and @code{--delay-key-write-for-all-tables} -to get speed improvements for the slave. In this case the slave will -use non-transactional @code{MyISAM} tables instead of @code{BDB} tables -to get more speed. - -@strong{Q}: What should I do to prepare my client code to use -performance-enhancing replication? - -@strong{A}: -If the part of your code that is responsible for database access has -been properly abstracted/modularized, converting it to run with the -replicated setup should be very smooth and easy - just change the -implementation of your database access to read from some slave or the -master, and to always write to the master. If your code does not have -this level of abstraction, -setting up a replicated system will give you an opportunity/motivation -to it clean up. - You should start by creating a wrapper library -/module with the following functions: - -@itemize -@item -@code{safe_writer_connect()} -@item -@code{safe_reader_connect()} -@item -@code{safe_reader_query()} -@item -@code{safe_writer_query()} -@end itemize - -@code{safe_} means that the function will take care of handling all -the error conditions. - -You should then convert your client code to use the wrapper library. -It may be a painful and scary process at first, but it will pay off in -the long run. All applications that follow the above pattern will be -able to take advantage of one-master/many slaves solution. The -code will be a lot easier to maintain, and adding troubleshooting -options will be trivial. You will just need to modify one or two -functions, for example, to log how long each query took, or which -query, among your many thousands, gave you an error. If you have written a lot of code already, -you may want to automate the conversion task by using Monty's -@code{replace} utility, which comes with the standard distribution of -@strong{MySQL}, or just write your own Perl script. Hopefully, your -code follows some recognizable pattern. If not, then you are probably -better off re-writing it anyway, or at least going through and manually -beating it into a pattern. - -Note that, of course, you can use different names for the -functions. What is important is having unified interface for connecting -for reads, connecting for writes, doing a read, and doing a write. - - -@strong{Q}: When and how much can @strong{MySQL} replication improve the performance -of my system? - -@strong{A}: @strong{MySQL} replication is most beneficial for a system -with frequent reads and not so frequent writes. In theory, by using a -one master/many slaves setup you can scale by adding more slaves until -you either run out of network bandwidth, or your update -load grows to the point -that the master cannot handle it. - -In order to determine how many slaves you can get before the added -benefits begin to level out, and how much you can improve performance -of your site, you need to know your query patterns, and empirically - (by benchmarking) determine the relationship between the throughput -on reads (reads per second, or @code{max_reads}) and on writes -@code{max_writes}) on a typical master and a typical slave. The -example below will show you a rather simplified calculation of what you -can get with replication for our imagined system. - -Let's say our system load consists of 10% writes and 90% reads, and we -have determined that @code{max_reads} = 1200 - 2 * @code{max_writes}, -or in other words, our system can do 1200 reads per second with no -writes, our average write is twice as slow as average read, -and the relationship is -linear. Let us suppose that our master and slave are of the same -capacity, and we have N slaves and 1 master. Then we have for each -server (master or slave): - -@code{reads = 1200 - 2 * writes} (from bencmarks) - -@code{reads = 9* writes / (N + 1) } (reads split, but writes go -to all servers) - -@code{9*writes/(N+1) + 2 * writes = 1200} - -@code{writes = 1200/(2 + 9/(N+1)} - -So if N = 0, which means we have no replication, our system can handle -1200/11, about 109 writes per second (which means we will have 9 times -as many reads due to the nature of our application). - -If N = 1, we can get up to 184 writes per second. - -If N = 8, we get up to 400. - -If N = 17, 480 writes. - -Eventually as N approaches infinity (and our budget negative infinity), -we can get very close to 600 writes per second, increasing system -throughput about 5.5 times. However, with only 8 servers, we increased -it almost 4 times already. - -Note that our computations assumed infinite network bandwidth, and -neglected several other factors that could turn out to be significant on -your system. In many cases, you may not be able to make a computation -similar to the one above that will accurately predict what will happen -on your system if you add N replication slaves. However, answering the -following questions should help you decided whether and how much, if at -all, the replication will improve the performance of your system: - -@itemize @bullet -@item -What is the read/write ratio on your system? -@item -How much more write load can one server handle if you reduce the reads? -@item -How many slaves do you have bandwidth for on your network? -@end itemize - -@strong{Q}: How can I use replication to provide redundancy/high -availability? - -@strong{A}: With the currently available features, you would have to -set up a master and a slave (or several slaves), and write a script -that will monitor the -master to see if it is up, and instruct your applications and -the slaves of the master change in case of failure. Some suggestions: - -@itemize @bullet -@item -To tell a slave to change the master use the @code{CHANGE MASTER TO} command. -@item -A good way to keep your applications informed where the master is by -having a dynamic DNS entry for the master. With @strong{bind} you can -use @code{nsupdate} to dynamically update your DNS. -@item -You should run your slaves with the @code{log-bin} option and without -@code{log-slave-updates}. This way the slave will be ready to become a -master as soon as you issue @code{STOP SLAVE}; @code{RESET MASTER}, and -@code{CHANGE MASTER TO} on the other slaves. It will also help you catch -spurious updates that may happen because of misconfiguration of the -slave (ideally, you want to configure access rights so that no client -can update the slave, except for the slave thread) combined with the -bugs in your client programs (they should never update the slave -directly). - -@end itemize - -We are currently working on integrating an automatic master election -system into @strong{MySQL}, but until it is ready, you will have to -create your own monitoring tools. - -@node Replication Problems, , Replication FAQ, Replication -@section Troubleshooting Replication - -If you have followed the instructions, and your replication setup is not -working, first eliminate the user error factor by checking the following: - -@itemize @bullet -@item -Is the master logging to the binary log? Check with @code{SHOW MASTER STATUS}. -If it is, @code{Position} will be non-zero. If not, verify that you have -given the master @code{log-bin} option and have set @code{server-id}. -@item -Is the slave running? Check with @code{SHOW SLAVE STATUS}. The answer is found -in @code{Slave_running} column. If not, verify slave options and check the -error log for messages. -@item -If the slave is running, did it establish connection with the master? Do -@code{SHOW PROCESSLIST}, find the thread with @code{system user} value in -@code{User} column and @code{none} in the @code{Host} column, and check the -@code{State} column. If it says @code{connecting to master}, verify the -privileges for the replication user on the master, master host name, your -DNS setup, whether the master is actually running, whether it is reachable -from the slave, and if all that seems ok, read the error logs. -@item -If the slave was running, but then stopped, look at SHOW SLAVE STATUS -output and check the error logs. It usually -happens when some query that succeeded on the master fails on the slave. This -should never happen if you have taken a proper snapshot of the master, and -never modify the data on the slave outside of the slave thread. If it does, -it is a bug, read below on how to report it. -@item -If a query on that succeeded on the master refuses to run on the slave, and -a full database resync ( the proper thing to do ) does not seem feasible, -try the following: -@itemize bullet -@item -First see if there is some stray record in the way. Understand how it got -there, then delete it and run @code{SLAVE START} -@item -If the above does not work or does not apply, try to understand if it would -be safe to make the update manually ( if needed) and then ignore the next -query from the master. -@item -If you have decided you can skip the next query, do -@code{SET SQL_SLAVE_SKIP_COUNTER=1; SLAVE START;} to skip a query that -does not use auto_increment, or last_insert_id or -@code{SET SQL_SLAVE_SKIP_COUNTER=2; SLAVE START;} otherwise. The reason -auto_increment/last_insert_id queries are different is that they take -two events in the binary log of the master. - -@item -If you are sure the slave started out perfectly in sync with the master, -and no one has updated the tables involved outside of slave thread, -report the bug, so -you will not have to do the above tricks again. -@end itemize -@item -Make sure you are not running into an old bug by upgrading to the most recent -version. -@item -If all else fails, read the error logs. If they are big, -@code{grep -i slave /path/to/your-log.err} on the slave. There is no -generic pattern to search for on the master, as the only errors it logs -are general system errors - if it can, it will send the error to the slave -when things go wrong. -@end itemize - -When you have determined that there is no user error involved, and replication -still either does not work at all or is unstable, it is time to start working -on a bug report. We need to get as much info as possible from you to be able -to track down the bug. Please do spend some time and effort preparing a good -bug report. Ideally, we would like to have a test case in the format found in -@code{mysql-test/t/rpl*} directory of the source tree. If you submit a test -case like that, you can expect a patch within a day or two in most cases, -although, of course, you mileage may vary depending on a number of factors. - -Second best option is a just program with easily configurable connection -arguments for the master and the slave that will demonstrate the problem on our -systems. You can write one in Perl or in C, depending on which language you -know better. - -If you have one of the above ways to demonstrate the bug, use -@code{mysqlbug} to prepare a bug report and send it to -@email{bugs@@lists.mysql.com}. If you have a phantom - a problem that -does occur but you cannot duplicate "at will": - -@itemize @bullet -@item -Verify that there is no user error involved. For example, if you update the -slave outside of the slave thread, the data will be out of sync, and you can -have unique key violations on updates, in which case the slave thread will -stop and wait for you to clean up the tables manually to bring them in sync. -@item -Run slave with @code{log-slave-updates} and @code{log-bin} - this will keep -a log of all updates on the slave. -@item -Save all evidence before resetting the replication. If we have no or only -sketchy information, it would take us a while to track down the problem. The -evidence you should collect is: -@itemize @bullet -@item -All binary logs on the master -@item -All binary log on the slave -@item -The output of @code{SHOW MASTER STATUS} on the master at the time -you have discovered the problem -@item -The output of @code{SHOW SLAVE STATUS} on the master at the time -you have discovered the problem -@item -Error logs on the master and on the slave -@end itemize -@item -Use @code{mysqlbinlog} to examine the binary logs. The following should -be helpful -to find the trouble query, for example: -@example -mysqlbinlog -j pos_from_slave_status /path/to/log_from_slave_status | head -@end example -@end itemize - -Once you have collected the evidence on the phantom problem, try hard to -isolate it into a separate test case first. Then report the problem to -@email{bugs@@lists.mysql.com} with as much info as possible. +@node Fulltext Search, Performance, Table types, Top +@chapter MySQL Full-text Search @cindex searching, full-text @cindex full-text search @cindex FULLTEXT -@node Fulltext Search, Performance, Replication, Top -@chapter MySQL Full-text Search Since Version 3.23.23, @strong{MySQL} has support for full-text indexing and searching. Full-text indexes in @strong{MySQL} are an index of type @@ -32157,7 +36496,7 @@ going. Hopefully this will be better handled in future Linux Kernels. @cindex benchmark suite @cindex crash-me program -@node MySQL Benchmarks, Tools, Performance, Top +@node MySQL Benchmarks, Maintenance, Performance, Top @chapter The MySQL Benchmark Suite This should contain a technical description of the @strong{MySQL} @@ -32243,1828 +36582,9 @@ How big a @code{VARCHAR} column can be We can find the result from crash-me on a lot of different databases at @uref{http://www.mysql.com/information/crash-me.php}. -@cindex utilities -@node Tools, Maintenance, MySQL Benchmarks, Top -@chapter MySQL Utilites - -@menu -* Programs:: What do the executables do? -* mysqld-max:: mysqld-max, An extended mysqld server -* safe_mysqld:: safe_mysqld, the wrapper around mysqld -* mysqld_multi:: Program for managing multiple @strong{MySQL} servers -* mysql:: The command line tool -* mysqladmin:: Administering a @strong{MySQL} server -* mysqldump:: Dumping the structure and data from @strong{MySQL} databases and tables -* mysqlhotcopy:: Copying @strong{MySQL} Databases and Tables -* mysqlimport:: Importing data from text files -* perror:: Displaying error messages -* mysqlshow:: Showing databases, tables and columns -* myisampack:: The @strong{MySQL} compressed read-only table generator -@end menu - -In this chapter you will learn about the @strong{MySQL} Utilities that -come in a given distribution. You will learn what each of them does, how -to use it, and what you should use it for. - -@cindex environment variables -@cindex programs, list of -@node Programs, mysqld-max, Tools, Tools -@section Overview of the Different MySQL Programs - -All @strong{MySQL} clients that communicate with the server using the -@code{mysqlclient} library use the following environment variables: - -@tindex MYSQL_UNIX_PORT environment variable -@tindex Environment variable, MYSQL_UNIX_PORT -@tindex MYSQL_TCP_PORT environment variable -@tindex Environment variable, MYSQL_TCP_PORT -@tindex MYSQL_PWD environment variable -@tindex Environment variable, MYSQL_PWD -@tindex MYSQL_DEBUG environment variable -@tindex Environment variable, MYSQL_DEBUG -@multitable @columnfractions .25 .75 -@item @strong{Name} @tab @strong{Description} -@item @code{MYSQL_UNIX_PORT} @tab The default socket; used for connections to @code{localhost} -@item @code{MYSQL_TCP_PORT} @tab The default TCP/IP port -@item @code{MYSQL_PWD} @tab The default password -@item @code{MYSQL_DEBUG} @tab Debug-trace options when debugging -@item @code{TMPDIR} @tab The directory where temporary tables/files are created -@end multitable - -Use of @code{MYSQL_PWD} is insecure. -@xref{Connecting}. - -@tindex MYSQL_HISTFILE environment variable -@tindex Environment variable, MYSQL_HISTFILE -@tindex HOME environment variable -@tindex Environment variable, HOME -@cindex history file -@cindex command line history -@tindex .mysql_history file -The @file{mysql} client uses the file named in the @code{MYSQL_HISTFILE} -environment variable to save the command-line history. The default value for -the history file is @file{$HOME/.mysql_history}, where @code{$HOME} is the -value of the @code{HOME} environment variable. @xref{Environment variables}. - -All @strong{MySQL} programs take many different options. However, every -@strong{MySQL} program provides a @code{--help} option that you can use -to get a full description of the program's different options. For example, try -@code{mysql --help}. - -You can override default options for all standard client programs with an -option file. @ref{Option files}. - -The list below briefly describes the @strong{MySQL} programs: - -@table @code - -@cindex @code{myisamchk} -@item myisamchk -Utility to describe, check, optimize, and repair @strong{MySQL} tables. -Because @code{myisamchk} has many functions, it is described in its own -chapter. @xref{Maintenance}. - -@cindex @code{make_binary_distribution} -@item make_binary_distribution -Makes a binary release of a compiled @strong{MySQL}. This could be sent -by FTP to @file{/pub/mysql/Incoming} on @code{support.mysql.com} for the -convenience of other @strong{MySQL} users. - -@cindex @code{msql2mysql} -@item msql2mysql -A shell script that converts @code{mSQL} programs to @strong{MySQL}. It doesn't -handle all cases, but it gives a good start when converting. - -@cindex @code{mysqlaccess} -@item mysqlaccess -A script that checks the access privileges for a host, user, and database -combination. - -@cindex @code{mysqladmin} -@item mysqladmin -Utility for performing administrative operations, such as creating or -dropping databases, reloading the grant tables, flushing tables to disk, and -reopening log files. @code{mysqladmin} can also be used to retrieve version, -process, and status information from the server. -@xref{mysqladmin, , @code{mysqladmin}}. - -@cindex @code{mysqlbug} -@item mysqlbug -The @strong{MySQL} bug report script. This script should always be used when -filing a bug report to the @strong{MySQL} list. - -@cindex @code{mysqld} -@item mysqld -The SQL daemon. This should always be running. - -@cindex @code{mysqldump} -@item mysqldump -Dumps a @strong{MySQL} database into a file as SQL statements or -as tab-separated text files. Enhanced freeware originally by Igor Romanenko. -@xref{mysqldump, , @code{mysqldump}}. - -@cindex @code{mysqlimport} -@item mysqlimport -Imports text files into their respective tables using @code{LOAD DATA -INFILE}. @xref{mysqlimport, , @code{mysqlimport}}. - -@cindex @code{mysqlshow} -@item mysqlshow -Displays information about databases, tables, columns, and indexes. - -@cindex @code{mysql_install_db} -@item mysql_install_db -Creates the @strong{MySQL} grant tables with default privileges. This is -usually executed only once, when first installing @strong{MySQL} -on a system. - -@cindex @code{replace} -@item replace -A utility program that is used by @code{msql2mysql}, but that has more -general applicability as well. @code{replace} changes strings in place in -files or on the standard input. Uses a finite state machine to match longer -strings first. Can be used to swap strings. For example, this command -swaps @code{a} and @code{b} in the given files: - -@example -shell> replace a b b a -- file1 file2 ... -@end example -@end table - -@cindex @code{mysqld-max} -@node mysqld-max, safe_mysqld, Programs, Tools -@section mysqld-max, An extended mysqld server - -@code{mysqld-max} is the MySQL server (@code{mysqld}) configured with -the following configure options: - -@multitable @columnfractions .3 .7 -@item @strong{Option} @tab @strong{Comment} -@item --with-server-suffix=-max @tab Add a suffix to the @code{mysqld} version string. -@item --with-bdb @tab Support for Berkeley DB (BDB) tables -@item --with-innodb @tab Support for InnoDB tables. -@item CFLAGS=-DUSE_SYMDIR @tab Symbolic links support for Windows. -@end multitable - -You can find the @strong{MySQL}-max binaries at -@uref{http://www.mysql.com/downloads/mysql-max-3.23.html}. - -The Windows @strong{MySQL} 3.23 binary distribution includes both the -standard @strong{mysqld.exe} binary and the @code{mysqld-max.exe} binary. -@uref{http://www.mysql.com/downloads/mysql-3.23.html}. -@xref{Windows installation}. - -Note that as Berkeley DB and InnoDB are not available for all platforms, -some of the @code{Max} binaries may not have support for both of these. -You can check which table types are supported by doing the following -query: - -@example -mysql> show variables like "have_%"; -+---------------+-------+ -| Variable_name | Value | -+---------------+-------+ -| have_bdb | YES | -| have_innodb | NO | -| have_isam | YES | -| have_raid | YES | -| have_ssl | NO | -+---------------+-------+ -@end example - -The meaning of the values are: - -@multitable @columnfractions .3 .7 -@item @strong{Value} @tab @strong{Meaning}. -@item YES @tab The option is activated and usable. -@item NO @tab @strong{MySQL} is not compiled with support for this option. -@item DISABLED @tab The xxxx option is disabled because one started @code{mysqld} with @code{--skip-xxxx} or because one didn't start @code{mysqld} with all needed options to enable the option. In this case the @code{hostname.err} file should contain a reason for why the option is disabled. -@end multitable - -@strong{NOTE}: To be able to create InnoDB tables you @strong{MUST} edit -your startup options to include at least the @code{innodb_data_file_path} -option. @xref{InnoDB start}. - -To get better performance for BDB tables, you should add some configuration -options for these too. @xref{BDB start}. - -@code{safe_mysqld} will automatically try to start any @code{mysqld} binary -with the @code{-max} prefix. This makes it very easy to test out a -another @code{mysqld} binary in an existing installation. Just -run @code{configure} with the options you want and then install the -new @code{mysqld} binary as @code{mysqld-max} in the same directory -where your old @code{mysqld} binary is. @xref{safe_mysqld, , @code{safe_mysqld}}. - -The @code{mysqld-max} RPM uses the above mentioned @code{safe_mysqld} -feature. It just installs the @code{mysqld-max} executable and -@code{safe_mysqld} will automatically use this executable when -@code{safe_mysqld} is restarted. - -The following table shows which table types our standard @strong{MySQL-Max} -binaries includes: - -@multitable @columnfractions .4 .3 .3 -@item @strong{System} @tab @strong{BDB} @tab @strong{InnoDB} -@item AIX 4.3 @tab N @tab Y -@item HP-UX 11.0 @tab N @tab Y -@item Linux-Alpha @tab N @tab Y -@item Linux-Intel @tab Y @tab Y -@item Linux-Ia64 @tab N @tab Y -@item Solaris-intel @tab N @tab Y -@item Solaris-sparc @tab Y @tab Y -@item SCO OSR5 @tab Y @tab Y -@item UnixWare @tab Y @tab Y -@item Windows/NT @tab Y @tab Y -@end multitable - -@cindex tools, safe_mysqld -@cindex scripts -@cindex @code{safe_mysqld} -@node safe_mysqld, mysqld_multi, mysqld-max, Tools -@section safe_mysqld, the wrapper around mysqld - -@code{safe_mysqld} is the recommended way to start a @code{mysqld} -daemon on Unix. @code{safe_mysqld} adds some safety features such as -restarting the server when an error occurs and logging run-time -information to a log file. - -If you don't use @code{--mysqld=#} or @code{--mysqld-version=#} -@code{safe_mysqld} will use an executable named @code{mysqld-max} if it -exists. If not, @code{safe_mysqld} will start @code{mysqld}. -This makes it very easy to test to use @code{mysqld-max} instead of -@code{mysqld}; Just copy @code{mysqld-max} to where you have -@code{mysqld} and it will be used. - -Normally one should never edit the @code{safe_mysqld} script, but -instead put the options to @code{safe_mysqld} in the -@code{[safe_mysqld]} section in the @code{my.cnf} -file. @code{safe_mysqld} will read all options from the @code{[mysqld]}, -@code{[server]} and @code{[safe_mysqld]} sections from the option files. -@xref{Option files}. - -Note that all options on the command line to @code{safe_mysqld} are passed -to @code{mysqld}. If you wants to use any options in @code{safe_mysqld} that -@code{mysqld} doesn't support, you must specify these in the option file. - -Most of the options to @code{safe_mysqld} are the same as the options to -@code{mysqld}. @xref{Command-line options}. - -@code{safe_mysqld} supports the following options: - -@table @code -@item --basedir=path -@item --core-file-size=# -Size of the core file @code{mysqld} should be able to create. Passed to @code{ulimit -c}. -@item --datadir=path -@item --defaults-extra-file=path -@item --defaults-file=path -@item --err-log=path -@item --ledir=path -Path to @code{mysqld} -@item --log=path -@item --mysqld=mysqld-version -Name of the @code{mysqld} version in the @code{ledir} directory you want to start. -@item --mysqld-version=version -Similar to @code{--mysqld=} but here you only give the suffix for @code{mysqld}. -For example if you use @code{--mysqld-version=max}, @code{safe_mysqld} will -start the @code{ledir/mysqld-max} version. If the argument to -@code{--mysqld-version} is empty, @code{ledir/mysqld} will be used. -@item --no-defaults -@item --open-files-limit=# -Number of files @code{mysqld} should be able to open. Passed to @code{ulimit -n}. Note that you need to start @code{safe_mysqld} as root for this to work properly! -@item --pid-file=path -@item --port=# -@item --socket=path -@item --timezone=# -Set the timezone (the @code{TZ}) variable to the value of this parameter. -@item --user=# -@end table - -The @code{safe_mysqld} script is written so that it normally is able to start -a server that was installed from either a source or a binary version of -@strong{MySQL}, even if these install the server in slightly different -locations. @code{safe_mysqld} expects one of these conditions to be true: - -@itemize @bullet -@item -The server and databases can be found relative to the directory from which -@code{safe_mysqld} is invoked. @code{safe_mysqld} looks under its working -directory for @file{bin} and @file{data} directories (for binary -distributions) or for @file{libexec} and @file{var} directories (for source -distributions). This condition should be met if you execute -@code{safe_mysqld} from your @strong{MySQL} installation directory (for -example, @file{/usr/local/mysql} for a binary distribution). - -@item -If the server and databases cannot be found relative to the working directory, -@code{safe_mysqld} attempts to locate them by absolute pathnames. Typical -locations are @file{/usr/local/libexec} and @file{/usr/local/var}. -The actual locations are determined when the distribution was built from which -@code{safe_mysqld} comes. They should be correct if -@strong{MySQL} was installed in a standard location. -@end itemize - -Because @code{safe_mysqld} will try to find the server and databases relative -to its own working directory, you can install a binary distribution of -@strong{MySQL} anywhere, as long as you start @code{safe_mysqld} from the -@strong{MySQL} installation directory: - -@example -shell> cd mysql_installation_directory -shell> bin/safe_mysqld & -@end example - -If @code{safe_mysqld} fails, even when invoked from the @strong{MySQL} -installation directory, you can modify it to use the path to @code{mysqld} -and the pathname options that are correct for your system. Note that if you -upgrade @strong{MySQL} in the future, your modified version of -@code{safe_mysqld} will be overwritten, so you should make a copy of your -edited version that you can reinstall. - -@cindex tools, mysqld_multi -@cindex scripts -@cindex multi mysqld -@cindex @code{mysqld_multi} -@node mysqld_multi, mysql, safe_mysqld, Tools -@section mysqld_multi, program for managing multiple @strong{MySQL} servers - -@code{mysqld_multi} is meant for managing several @code{mysqld} -processes running in different UNIX sockets and TCP/IP ports. - -The program will search for group(s) named [mysqld#] from my.cnf (or the -given --config-file=...), where # can be any positive number starting -from 1. These groups should be the same as the usual @code{[mysqld]} -group (e.g. options to mysqld, see @strong{MySQL} manual for detailed -information about this group), but with those port, socket etc. options -that are wanted for each separate @code{mysqld} processes. The number in -the group name has another function; it can be used for starting, -stopping, or reporting some specific @code{mysqld} servers with this -program. See the usage and options below for more information. - -@example -Usage: mysqld_multi [OPTIONS] @{start|stop|report@} [GNR,GNR,GNR...] -or mysqld_multi [OPTIONS] @{start|stop|report@} [GNR-GNR,GNR,GNR-GNR,...] -@end example - -The GNR above 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, of which the latter -means that all the GNRs between GNR1-GNR2 will be affected. Without -GNR argument all the found groups will be either started, stopped, or -reported. Note that you must not have any white spaces in the GNR -list. Anything after a white space is ignored. - -@code{mysqld_multi} supports the following options: - -@table @code -@cindex config-file option -@item --config-file=... -Alternative config file. NOTE: This will not affect this program's own -options (group @code{[mysqld_multi]}), but only groups -[mysqld#]. Without this option everything will be searched from the -ordinary my.cnf file. -@cindex example option -@item --example -Give an example of a config file. -@cindex help option -@item --help -Print this help and exit. -@cindex log option -@item --log=... -Log file. Full path to and the name for the log file. NOTE: If the file -exists, everything will be appended. -@cindex mysqladmin option -@item --mysqladmin=... -@code{mysqladmin} binary to be used for a server shutdown. -@cindex mysqld option -@item --mysqld=... -@code{mysqld} binary to be used. Note that you can give -@code{safe_mysqld} to this option also. The options are passed to -@code{mysqld}. Just make sure you have @code{mysqld} in your environment -variable @code{PATH} or fix @code{safe_mysqld}. -@cindex no-log option -@item --no-log -Print to stdout instead of the log file. By default the log file is -turned on. -@cindex password option -@item --password=... -Password for user for @code{mysqladmin}. -@cindex tcp-ip option -@item --tcp-ip -Connect to the @strong{MySQL} 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. -@cindex user option -@item --user=... -@strong{MySQL} user for @code{mysqladmin}. -@cindex version option -@item --version -Print the version number and exit. -@end table - -Some notes about @code{mysqld_multi}: - -@itemize @bullet -@item -Make sure that the @strong{MySQL} user, who is stopping the -@code{mysqld} services (e.g using the @code{mysqladmin}) have the same -password and username for all the data directories accessed (to the -'mysql' database) And make sure that the user has the 'Shutdown_priv' -privilege! If you have many data- directories and many different 'mysql' -databases with different passwords for the @strong{MySQL} 'root' user, -you may want to create a common 'multi_admin' user for each using the -same password (see below). Example how to do it: -@example -shell> mysql -u root -S /tmp/mysql.sock -proot_password -e -"GRANT SHUTDOWN ON *.* TO multi_admin@@localhost IDENTIFIED BY 'multipass'" -@xref{Privileges}. -@end example -You will have to do the above for each @code{mysqld} running in each -data directory, that you have (just change the socket, -S=...) -@item -@code{pid-file} is very important, if you are using @code{safe_mysqld} -to start @code{mysqld} (e.g. --mysqld=safe_mysqld) Every @code{mysqld} -should have its own @code{pid-file}. The advantage using -@code{safe_mysqld} instead of @code{mysqld} directly here is, that -@code{safe_mysqld} 'guards' every @code{mysqld} process and will restart -it, if a @code{mysqld} process fails due to signal kill -9, or -similar. (Like segmentation fault, which @strong{MySQL} should never do, -of course ;) Please note that @code{safe_mysqld} script may require that -you start it from a certain place. This means that you may have to CD to -a certain directory, before you start the @code{mysqld_multi}. If -you have problems starting, please see the @code{safe_mysqld} -script. Check especially the lines: -@example --------------------------------------------------------------------------- -MY_PWD=`pwd` Check if we are starting this relative (for the binary -release) if test -d /data/mysql -a -f ./share/mysql/english/errmsg.sys --a -x ./bin/mysqld --------------------------------------------------------------------------- -@xref{safe_mysqld, , @code{safe_mysqld}}. -@end example -The above test should be successful, or you may encounter problems. -@item -Beware of the dangers starting multiple @code{mysqlds} in the same data -directory. Use separate data directories, unless you @strong{KNOW} what -you are doing! -@item -The socket file and the TCP/IP port must be different for every @code{mysqld}. -@item -The first and fifth @code{mysqld} group were intentionally left out from -the example. You may have 'gaps' in the config file. This gives you -more flexibility. The order in which the @code{mysqlds} are started or -stopped depends on the order in which they appear in the config file. -@item -When you want to refer to a certain group using GNR with this program, -just use the number in the end of the group name ( [mysqld# <== ). -@item -You may want to use option '--user' for @code{mysqld}, but in order to -do this you need to be root when you start the @code{mysqld_multi} -script. Having the option in the config file doesn't matter; you will -just get a warning, if you are not the superuser and the @code{mysqlds} -are started under @strong{YOUR} UNIX account. @strong{IMPORTANT}: Make -sure that the @code{pid-file} and the data directory are -read+write(+execute for the latter one) accessible for @strong{THAT} -UNIX user, who the specific @code{mysqld} process is started -as. @strong{DON'T} use the UNIX root account for this, unless you -@strong{KNOW} what you are doing! -@item -@strong{MOST IMPORTANT}: Make sure that you understand the meanings of -the options that are passed to the @code{mysqlds} and why @strong{WOULD -YOU WANT} to have separate @code{mysqld} processes. Starting multiple -@code{mysqlds} in one data directory @strong{WILL NOT} give you extra -performance in a threaded system! -@end itemize - -@xref{Multiple servers}. - -This is an example of the config file on behalf of @code{mysqld_multi}. - -@example -# This file should probably be in your home dir (~/.my.cnf) or /etc/my.cnf -# Version 2.1 by Jani Tolonen - -[mysqld_multi] -mysqld = /usr/local/bin/safe_mysqld -mysqladmin = /usr/local/bin/mysqladmin -user = multi_admin -password = multipass - -[mysqld2] -socket = /tmp/mysql.sock2 -port = 3307 -pid-file = /usr/local/mysql/var2/hostname.pid2 -datadir = /usr/local/mysql/var2 -language = /usr/local/share/mysql/english -user = john - -[mysqld3] -socket = /tmp/mysql.sock3 -port = 3308 -pid-file = /usr/local/mysql/var3/hostname.pid3 -datadir = /usr/local/mysql/var3 -language = /usr/local/share/mysql/swedish -user = monty - -[mysqld4] -socket = /tmp/mysql.sock4 -port = 3309 -pid-file = /usr/local/mysql/var4/hostname.pid4 -datadir = /usr/local/mysql/var4 -language = /usr/local/share/mysql/estonia -user = tonu - -[mysqld6] -socket = /tmp/mysql.sock6 -port = 3311 -pid-file = /usr/local/mysql/var6/hostname.pid6 -datadir = /usr/local/mysql/var6 -language = /usr/local/share/mysql/japanese -user = jani -@end example - -@xref{Option files}. - -@cindex command line tool -@cindex tools, command line -@cindex scripts -@cindex @code{mysql} -@node mysql, mysqladmin, mysqld_multi, Tools -@section The Command-line Tool - -@code{mysql} is a simple SQL shell (with GNU @code{readline} capabilities). -It supports interactive and non-interactive use. When used interactively, -query results are presented in an ASCII-table format. When used -non-interactively (for example, as a filter), the result is presented in -tab-separated format. (The output format can be changed using command-line -options.) You can run scripts simply like this: - -@example -shell> mysql database < script.sql > output.tab -@end example - -If you have problems due to insufficient memory in the client, use the -@code{--quick} option! This forces @code{mysql} to use -@code{mysql_use_result()} rather than @code{mysql_store_result()} to -retrieve the result set. - -Using @code{mysql} is very easy. Just start it as follows: -@code{mysql database} or @code{mysql --user=user_name --password=your_password database}. Type a SQL statement, end it with @samp{;}, @samp{\g}, or @samp{\G} -and press RETURN/ENTER. - -@cindex command line options -@cindex options, command line -@cindex startup parameters -@code{mysql} supports the following options: - -@table @code -@cindex help option -@item -?, --help -Display this help and exit. -@cindex automatic rehash option -@item -A, --no-auto-rehash -No automatic rehashing. One has to use 'rehash' to get table and field -completion. This gives a quicker start of mysql. -@cindex batch option -@item -B, --batch -Print results with a tab as separator, each row on a new line. Doesn't use -history file. -@cindex character sets option -@item --character-sets-dir=... -Directory where character sets are located. -@cindex compress option. -@item -C, --compress -Use compression in server/client protocol. -@cindex debug option -@item -#, --debug[=...] -Debug log. Default is 'd:t:o,/tmp/mysql.trace'. -@cindex database option -@item -D, --database=... -Database to use. This is mainly useful in the @code{my.cnf} file. -@cindex default character set option -@item --default-character-set=... -Set the default character set. -@cindex execute option -@item -e, --execute=... -Execute command and quit. (Output like with --batch) -@cindex vertical option -@item -E, --vertical -Print the output of a query (rows) vertically. Without this option you -can also force this output by ending your statements with @code{\G}. -@cindex force option -@item -f, --force -Continue even if we get a SQL error. -@cindex no-named-commands option -@item -g, --no-named-commands -Named commands are disabled. Use \* form only, or use named commands -only in the beginning of a line ending with a semicolon (;). Since -Version 10.9, the client now starts with this option ENABLED by default! -With the -g option, long format commands will still work from the first -line, however. -@cindex enable-named-commands option -@item -G, --enable-named-commands -Named commands are @strong{enabled}. Long format commands are allowed as -well as shortened \* commands. -@cindex ignore space option. -@item -i, --ignore-space -Ignore space after function names. -@cindex host option -@item -h, --host=... -Connect to the given host. -@cindex html option -@item -H, --html -Produce HTML output. -@cindex skip line numbers option -@item -L, --skip-line-numbers -Don't write line number for errors. Useful when one wants to compare result -files that includes error messages -@cindex no pager option -@item --no-pager -Disable pager and print to stdout. See interactive help (\h) also. -@cindex no tee option -@item --no-tee -Disable outfile. See interactive help (\h) also. -@cindex unbuffered option. -@item -n, --unbuffered -Flush buffer after each query. -@cindex skip column names option -@item -N, --skip-column-names -Don't write column names in results. -@cindex set variable option -@item -O, --set-variable var=option -Give a variable a value. @code{--help} lists variables. -@cindex one database option -@item -o, --one-database -Only update the default database. This is useful for skipping updates to -other database in the update log. -@cindex pager option -@item @code{--pager[=...]} -Output type. Default is your @code{ENV} variable @code{PAGER}. Valid -pagers are less, more, cat [> filename], etc. See interactive help (\h) -also. This option does not work in batch mode. Pager works only in UNIX. -@cindex password option -@item -p[password], --password[=...] -Password to use when connecting to server. If a password is not given on -the command line, you will be prompted for it. Note that if you use the -short form @code{-p} you can't have a space between the option and the -password. -@item -P --port=... -TCP/IP port number to use for connection. -@cindex quick option -@item -q, --quick -Don't cache result, print it row-by-row. This may slow down the server -if the output is suspended. Doesn't use history file. -@cindex raw option -@item -r, --raw -Write column values without escape conversion. Used with @code{--batch} -@cindex silent option -@item -s, --silent -Be more silent. -@item -S --socket=... -Socket file to use for connection. -@cindex table option -@item -t --table -Output in table format. This is default in non-batch mode. -@item -T, --debug-info -Print some debug information at exit. -@cindex tee option -@item --tee=... -Append everything into outfile. See interactive help (\h) also. Does not -work in batch mode. -@cindex user option -@item -u, --user=# -User for login if not current user. -@cindex safe updates option -@item -U, --safe-updates[=#], --i-am-a-dummy[=#] -Only allow @code{UPDATE} and @code{DELETE} that uses keys. See below for -more information about this option. You can reset this option if you have -it in your @code{my.cnf} file by using @code{--safe-updates=0}. -@cindex verbose option -@item -v, --verbose -More verbose output (-v -v -v gives the table output format). -@cindex version option -@item -V, --version -Output version information and exit. -@cindex wait option -@item -w, --wait -Wait and retry if connection is down instead of aborting. -@end table - -You can also set the following variables with @code{-O} or -@code{--set-variable}: - -@cindex timeout -@multitable @columnfractions .3 .2 .5 -@item Variablename @tab Default @tab Description -@item connect_timeout @tab 0 @tab Number of seconds before timeout connection. -@item max_allowed_packet @tab 16777216 @tab Max packetlength to send/receive from to server -@item net_buffer_length @tab 16384 @tab Buffer for TCP/IP and socket communication -@item select_limit @tab 1000 @tab Automatic limit for SELECT when using --i-am-a-dummy -@item max_join_size @tab 1000000 @tab Automatic limit for rows in a join when using --i-am-a-dummy. -@end multitable - -If you type 'help' on the command line, @code{mysql} will print out the -commands that it supports: - -@cindex commands, list of -@example -mysql> help - -MySQL commands: -help (\h) Display this text. -? (\h) Synonym for `help'. -clear (\c) Clear command. -connect (\r) Reconnect to the server. Optional arguments are db and host. -edit (\e) Edit command with $EDITOR. -ego (\G) Send command to mysql server, display result vertically. -exit (\q) Exit mysql. Same as quit. -go (\g) Send command to mysql server. -nopager (\n) Disable pager, print to stdout. -notee (\t) Don't write into outfile. -pager (\P) Set PAGER [to_pager]. Print the query results via PAGER. -print (\p) Print current command. -quit (\q) Quit mysql. -rehash (\#) Rebuild completion hash. -source (\.) Execute a SQL script file. Takes a file name as an argument. -status (\s) Get status information from the server. -tee (\T) Set outfile [to_outfile]. Append everything into given outfile. -use (\u) Use another database. Takes database name as argument. -@end example - -From the above, pager only works in UNIX. - -@cindex status command -The @code{status} command gives you some information about the -connection and the server you are using. If you are running in the -@code{--safe-updates} mode, @code{status} will also print the values for -the @code{mysql} variables that affect your queries. - -@cindex @code{safe-mode} command -A useful startup option for beginners (introduced in @strong{MySQL} -Version 3.23.11) is @code{--safe-updates} (or @code{--i-am-a-dummy} for -users that has at some time done a @code{DELETE FROM table_name} but -forgot the @code{WHERE} clause). When using this option, @code{mysql} -sends the following command to the @strong{MySQL} server when opening -the connection: - -@example -SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=#select_limit#, - SQL_MAX_JOIN_SIZE=#max_join_size#" -@end example - -where @code{#select_limit#} and @code{#max_join_size#} are variables that -can be set from the @code{mysql} command line. @xref{SET OPTION, @code{SET}}. - -The effect of the above is: - -@itemize @bullet -@item -You are not allowed to do an @code{UPDATE} or @code{DELETE} statement -if you don't have a key constraint in the @code{WHERE} part. One can, -however, force an @code{UPDATE/DELETE} by using @code{LIMIT}: -@example -UPDATE table_name SET not_key_column=# WHERE not_key_column=# LIMIT 1; -@end example -@item -All big results are automatically limited to @code{#select_limit#} rows. -@item -@code{SELECT}'s that will probably need to examine more than -@code{#max_join_size} row combinations will be aborted. -@end itemize - -Some useful hints about the @code{mysql} client: - -Some data is much more readable when displayed vertically, instead of -the usual horizontal box type output. For example longer text, which -includes new lines, is often much easier to be read with vertical -output. - -@example -mysql> select * from mails where length(txt) < 300 limit 300,1\G -*************************** 1. row *************************** - msg_nro: 3068 - date: 2000-03-01 23:29:50 -time_zone: +0200 -mail_from: Monty - reply: monty@@no.spam.com - mail_to: "Thimble Smith" - sbj: UTF-8 - txt: >>>>> "Thimble" == Thimble Smith writes: - -Thimble> Hi. I think this is a good idea. Is anyone familiar with UTF-8 -Thimble> or Unicode? Otherwise I'll put this on my TODO list and see what -Thimble> happens. - -Yes, please do that. - -Regards, -Monty - file: inbox-jani-1 - hash: 190402944 -1 row in set (0.09 sec) -@end example - -@itemize @bullet -@item -For logging, you can use the @code{tee} option. The @code{tee} can be -started with option @code{--tee=...}, or from the command line -interactively with command @code{tee}. All the data displayed on the -screen will also be appended into a given file. This can be very useful -for debugging purposes also. The @code{tee} can be disabled from the -command line with command @code{notee}. Executing @code{tee} again -starts logging again. Without a parameter the previous file will be -used. Note that @code{tee} will flush the results into the file after -each command, just before the command line appears again waiting for the -next command. -@item -Browsing, or searching the results in the interactive mode in UNIX less, -more, or any other similar program, is now possible with option -@code{--pager[=...]}. Without argument, @code{mysql} client will look -for environment variable PAGER and set @code{pager} to that. -@code{pager} can be started from the interactive command line with -command @code{pager} and disabled with command @code{nopager}. The -command takes an argument optionally and the @code{pager} will be set to -that. Command @code{pager} can be called without an argument, but this -requires that the option @code{--pager} was used, or the @code{pager} -will default to stdout. @code{pager} works only in UNIX, since it uses -the popen() function, which doesn't exist in Windows. In Windows, the -@code{tee} option can be used instead, although it may not be as handy -as @code{pager} can be in some situations. -@item -A few tips about @code{pager}: You can use it to write to a file: -@example -mysql> pager cat > /tmp/log.txt -@end example -and the results will only go to a file. You can also pass any options -for the programs that you want to use with the @code{pager}: -@example -mysql> pager less -n -i -S -@end example -From the above do note the option '-S'. You may find it very useful when -browsing the results; try the option with horizontal output (end -commands with '\g', or ';') and with vertical output (end commands with -'\G'). Sometimes a very wide result set is hard to be read from the screen, -with option -S to less you can browse the results within the interactive -less from left to right, preventing lines longer than your screen from -being continued to the next line. This can make the result set much more -readable. You can swith the mode between on and off within the interactive -less with '-S'. See the 'h' for more help about less. -@item -Last (unless you already understood this from the above examples ;) you -can combine very complex ways to handle the results, for example the -following would send the results to two files in two different -directories, on two different hard-disks mounted on /dr1 and /dr2, yet -let the results still be seen on the screen via less: -@example -mysql> pager cat | tee /dr1/tmp/res.txt | tee /dr2/tmp/res2.txt | less -n -i -S -@end example -@item -You can also combine the two functions above; have the @code{tee} -enabled, @code{pager} set to 'less' and you will be able to browse the -results in unix 'less' and still have everything appended into a file -the same time. The difference between @code{UNIX tee} used with the -@code{pager} and the @code{mysql} client in-built @code{tee}, is that -the in-built @code{tee} works even if you don't have the @code{UNIX tee} -available. The in-built @code{tee} also logs everything that is printed -on the screen, where the @code{UNIX tee} used with @code{pager} doesn't -log quite that much. Last, but not least, the interactive @code{tee} is -more handy to switch on and off, when you want to log something into a -file, but want to be able to turn the feature off sometimes. -@end itemize - - -@cindex administration, server -@cindex server administration -@cindex @code{mysladmn} -@node mysqladmin, mysqldump, mysql, Tools -@section Administering a MySQL Server - -A utility for performing administrative operations. The syntax is: - -@example -shell> mysqladmin [OPTIONS] command [command-option] command ... -@end example - -You can get a list of the options your version of @code{mysqladmin} supports -by executing @code{mysqladmin --help}. - -The current @code{mysqladmin} supports the following commands: - -@multitable @columnfractions .3 .7 -@item create databasename @tab Create a new database. -@item drop databasename @tab Delete a database and all its tables. -@item extended-status @tab Gives an extended status message from the server. -@item flush-hosts @tab Flush all cached hosts. -@item flush-logs @tab Flush all logs. -@item flush-tables @tab Flush all tables. -@item flush-privileges @tab Reload grant tables (same as reload). -@item kill id,id,... @tab Kill mysql threads. -@item password @tab New-password. Change old password to new-password. -@item ping @tab Check if @code{mysqld} is alive. -@item processlist @tab Show list of active threads in server. -@item reload @tab Reload grant tables. -@item refresh @tab Flush all tables and close and open logfiles. -@item shutdown @tab Take server down. -@item slave-start @tab Start slave replication thread. -@item slave-stop @tab Stop slave replication thread. -@item status @tab Gives a short status message from the server. -@item variables @tab Prints variables available. -@item version @tab Get version info from server. -@end multitable - -All commands can be shortened to their unique prefix. For example: - -@example -shell> mysqladmin proc stat -+----+-------+-----------+----+-------------+------+-------+------+ -| Id | User | Host | db | Command | Time | State | Info | -+----+-------+-----------+----+-------------+------+-------+------+ -| 6 | monty | localhost | | Processlist | 0 | | | -+----+-------+-----------+----+-------------+------+-------+------+ -Uptime: 10077 Threads: 1 Questions: 9 Slow queries: 0 Opens: 6 Flush tables: 1 Open tables: 2 Memory in use: 1092K Max memory used: 1116K -@end example - -@cindex status command, results -The @code{mysqladmin status} command result has the following columns: - -@cindex uptime -@multitable @columnfractions .3 .7 -@item Uptime @tab Number of seconds the @strong{MySQL} server has been up. -@cindex threads -@item Threads @tab Number of active threads (clients). -@cindex questions -@item Questions @tab Number of questions from clients since @code{mysqld} was started. -@cindex slow queries -@item Slow queries @tab Queries that have taken more than @code{long_query_time} seconds. @xref{Slow query log}. -@cindex opens -@item Opens @tab How many tables @code{mysqld} has opened. -@cindex flush tables -@cindex tables, flush -@item Flush tables @tab Number of @code{flush ...}, @code{refresh}, and @code{reload} commands. -@cindex open tables -@item Open tables @tab Number of tables that are open now. -@cindex memory use -@item Memory in use @tab Memory allocated directly by the @code{mysqld} code (only available when @strong{MySQL} is compiled with --with-debug=full). -@cindex max memory used -@item Max memory used @tab Maximum memory allocated directly by the @code{mysqld} code (only available when @strong{MySQL} is compiled with --with-debug=full). -@end multitable - -If you do @code{myslqadmin shutdown} on a socket (in other words, on a -the computer where @code{mysqld} is running), @code{mysqladmin} will -wait until the @strong{MySQL} @code{pid-file} is removed to ensure that -the @code{mysqld} server has stopped properly. - -@cindex dumping, databases -@cindex databases, dumping -@cindex tables, dumping -@cindex backing up, databases -@node mysqldump, mysqlhotcopy, mysqladmin, Tools -@section Dumping the Structure and Data from MySQL Databases and Tables - -@cindex @code{mysqldump} -Utility to dump a database or a collection of database for backup or for -transferring the data to another SQL server (not necessarily a @strong{MySQL} -server). The dump will contain SQL statements to create the table -and/or populate the table. - -If you are doing a backup on the server, you should consider using -the @code{mysqlhotcopy} instead. @xref{mysqlhotcopy, , @code{mysqlhotcopy}}. - -@example -shell> mysqldump [OPTIONS] database [tables] -OR mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...] -OR mysqldump [OPTIONS] --all-databases [OPTIONS] -@end example - -If you don't give any tables or use the @code{--databases} or -@code{--all-databases}, the whole database(s) will be dumped. - -You can get a list of the options your version of @code{mysqldump} supports -by executing @code{mysqldump --help}. - -Note that if you run @code{mysqldump} without @code{--quick} or -@code{--opt}, @code{mysqldump} will load the whole result set into -memory before dumping the result. This will probably be a problem if -you are dumping a big database. - -Note that if you are using a new copy of the @code{mysqldump} program -and you are going to do a dump that will be read into a very old @strong{MySQL} -server, you should not use the @code{--opt} or @code{-e} options. - -@code{mysqldump} supports the following options: - -@table @code -@item --add-locks -Add @code{LOCK TABLES} before and @code{UNLOCK TABLE} after each table dump. -(To get faster inserts into @strong{MySQL}.) -@item --add-drop-table -Add a @code{drop table} before each create statement. -@item -A, --all-databases -Dump all the databases. This will be same as @code{--databases} with all -databases selected. -@item -a, --all -Include all @strong{MySQL}-specific create options. -@item --allow-keywords -Allow creation of column names that are keywords. This works by -prefixing each column name with the table name. -@item -c, --complete-insert -Use complete insert statements (with column names). -@item -C, --compress -Compress all information between the client and the server if both support -compression. -@item -B, --databases -To dump several databases. Note the difference in usage. In this case -no tables are given. All name arguments are regarded as database names. -@code{USE db_name;} will be included in the output before each new database. -@item --delayed -Insert rows with the @code{INSERT DELAYED} command. -@item -e, --extended-insert -Use the new multiline @code{INSERT} syntax. (Gives more compact and -faster inserts statements.) -@item -#, --debug[=option_string] -Trace usage of the program (for debugging). -@item --help -Display a help message and exit. -@item --fields-terminated-by=... -@itemx --fields-enclosed-by=... -@itemx --fields-optionally-enclosed-by=... -@itemx --fields-escaped-by=... -@itemx --lines-terminated-by=... -These options are used with the @code{-T} option and have the same -meaning as the corresponding clauses for @code{LOAD DATA INFILE}. -@xref{LOAD DATA, , @code{LOAD DATA}}. -@item -F, --flush-logs -Flush log file in the @strong{MySQL} server before starting the dump. -@item -f, --force, -Continue even if we get a SQL error during a table dump. -@item -h, --host=.. -Dump data from the @strong{MySQL} server on the named host. The default host -is @code{localhost}. -@item -l, --lock-tables. -Lock all tables before starting the dump. The tables are locked with -@code{READ LOCAL} to allow concurrent inserts in the case of @code{MyISAM} -tables. -@item -n, --no-create-db -'CREATE DATABASE /*!32312 IF NOT EXISTS*/ db_name;' will not be put in the -output. The above line will be added otherwise, if --databases or ---all-databases option was given. -@item -t, --no-create-info -Don't write table creation information (The @code{CREATE TABLE} statement.) -@item -d, --no-data -Don't write any row information for the table. This is very useful if you -just want to get a dump of the structure for a table! -@item --opt -Same as @code{--quick --add-drop-table --add-locks --extended-insert ---lock-tables}. Should give you the fastest possible dump for reading -into a @strong{MySQL} server. -@item -pyour_pass, --password[=your_pass] -The password to use when connecting to the server. If you specify -no @samp{=your_pass} part, -@code{mysqldump} you will be prompted for a password. -@item -P port_num, --port=port_num -The TCP/IP port number to use for connecting to a host. (This is used for -connections to hosts other than @code{localhost}, for which Unix sockets are -used.) -@item -q, --quick -Don't buffer query, dump directly to stdout. Uses @code{mysql_use_result()} -to do this. -@item -r, --result-file=... -Direct output to a given file. This option should be used in MSDOS, -because it prevents new line '\n' from being converted to '\n\r' (new -line + carriage return). -@item -S /path/to/socket, --socket=/path/to/socket -The socket file to use when connecting to @code{localhost} (which is the -default host). -@item --tables -Overrides option --databases (-B). -@item -T, --tab=path-to-some-directory -Creates a @code{table_name.sql} file, that contains the SQL CREATE commands, -and a @code{table_name.txt} file, that contains the data, for each give table. -@strong{NOTE}: This only works if @code{mysqldump} is run on the same -machine as the @code{mysqld} daemon. The format of the @code{.txt} file -is made according to the @code{--fields-xxx} and @code{--lines--xxx} options. -@item -u user_name, --user=user_name -The @strong{MySQL} user name to use when connecting to the server. The -default value is your Unix login name. -@item -O var=option, --set-variable var=option -Set the value of a variable. The possible variables are listed below. -@item -v, --verbose -Verbose mode. Print out more information on what the program does. -@item -V, --version -Print version information and exit. -@item -w, --where='where-condition' -Dump only selected records. Note that QUOTES are mandatory: - -@example -"--where=user='jimf'" "-wuserid>1" "-wuserid<1" -@end example -@item -O net_buffer_length=#, where # < 16M -When creating multi-row-insert statements (as with option -@code{--extended-insert} or @code{--opt}), @code{mysqldump} will create -rows up to @code{net_buffer_length} length. If you increase this -variable, you should also ensure that the @code{max_allowed_packet} -variable in the @strong{MySQL} server is bigger than the -@code{net_buffer_length}. -@end table - -The most normal use of @code{mysqldump} is probably for making a backup of -whole databases. @xref{Backup}. - -@example -mysqldump --opt database > backup-file.sql -@end example - -You can read this back into @strong{MySQL} with: - -@example -mysql database < backup-file.sql -@end example - -or - -@example -mysql -e "source /patch-to-backup/backup-file.sql" database -@end example - -However, it's also very useful to populate another @strong{MySQL} server with -information from a database: - -@example -mysqldump --opt database | mysql ---host=remote-host -C database -@end example - -It is possible to dump several databases with one command: - -@example -mysqldump --databases database1 [database2 database3...] > my_databases.sql -@end example - -If all the databases are wanted, one can use: - -@example -mysqldump --all-databases > all_databases.sql -@end example - -@cindex dumping, databases -@cindex databases, dumping -@cindex tables, dumping -@cindex backing up, databases -@node mysqlhotcopy, mysqlimport, mysqldump, Tools -@section Copying MySQL Databases and Tables - -@code{mysqlhotcopy} is a perl script that uses @code{LOCK TABLES}, -@code{FLUSH TABLES} and @code{cp} or @code{scp} to quickly make a backup -of a database. It's the fastest way to make a backup of the database, -of single tables but it can only be run on the same machine where the -database directories are. - -@example -mysqlhotcopy db_name [/path/to/new_directory] - -mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory - -mysqlhotcopy db_name./regex/ -@end example - -@code{mysqlhotcopy} supports the following options: - -@table @code -@item -?, --help -Display a help screen and exit -@item -u, --user=# -User for database login -@item -p, --password=# -Password to use when connecting to server -@item -P, --port=# -Port to use when connecting to local server -@item -S, --socket=# -Socket to use when connecting to local server -@item --allowold -Don't abort if target already exists (rename it _old) -@item --keepold -Don't delete previous (now renamed) target when done -@item --noindices -Don't include full index files in copy to make the backup smaller and faster -The indexes can later be reconstructed with @code{myisamchk -rq.}. -@item --method=# -Method for copy (@code{cp} or @code{scp}). -@item -q, --quiet -Be silent except for errors -@item --debug -Enable debug -@item -n, --dryrun -Report actions without doing them -@item --regexp=# -Copy all databases with names matching regexp -@item --suffix=# -Suffix for names of copied databases -@item --checkpoint=# -Insert checkpoint entry into specified db.table -@item --flushlog -Flush logs once all tables are locked. -@item --tmpdir=# -Temporary directory (instead of /tmp). -@end table - -You can use @code{perldoc mysqlhotcopy} to get a more complete -documentation for @code{mysqlhotcopy}. - -@code{mysqlhotcopy} reads the groups @code{[client]} and @code{[mysqlhotcopy]} -from the option files. - -To be able to execute @code{mysqlhotcopy} you need write access to the -backup directory, @code{SELECT} privilege to the tables you are about to -copy and the @strong{MySQL} @code{Reload} privilege (to be able to -execute @code{FLUSH TABLES}). - -@cindex importing, data -@cindex data, importing -@cindex files, text -@cindex text files, importing -@cindex @code{mysqlimport} -@node mysqlimport, perror, mysqlhotcopy, Tools -@section Importing Data from Text Files - -@code{mysqlimport} provides a command-line interface to the @code{LOAD DATA -INFILE} SQL statement. Most options to @code{mysqlimport} correspond -directly to the same options to @code{LOAD DATA INFILE}. -@xref{LOAD DATA, , @code{LOAD DATA}}. - -@code{mysqlimport} is invoked like this: - -@example -shell> mysqlimport [options] database textfile1 [textfile2....] -@end example - -For each text file named on the command line, -@code{mysqlimport} strips any extension from the filename and uses the result -to determine which table to import the file's contents into. For example, -files named @file{patient.txt}, @file{patient.text}, and @file{patient} would -all be imported into a table named @code{patient}. - -@code{mysqlimport} supports the following options: - -@table @code -@item -c, --columns=... -This option takes a comma-separated list of field names as an argument. -The field list is used to create a proper @code{LOAD DATA INFILE} command, -which is then passed to @strong{MySQL}. @xref{LOAD DATA, , @code{LOAD DATA}}. - -@item -C, --compress -Compress all information between the client and the server if both support -compression. - -@item -#, --debug[=option_string] -Trace usage of the program (for debugging). - -@item -d, --delete -Empty the table before importing the text file. - -@item --fields-terminated-by=... -@itemx --fields-enclosed-by=... -@itemx --fields-optionally-enclosed-by=... -@itemx --fields-escaped-by=... -@itemx --lines-terminated-by=... -These options have the same meaning as the corresponding clauses for -@code{LOAD DATA INFILE}. @xref{LOAD DATA, , @code{LOAD DATA}}. - -@item -f, --force -Ignore errors. For example, if a table for a text file doesn't exist, -continue processing any remaining files. Without @code{--force}, -@code{mysqlimport} exits if a table doesn't exist. - -@item --help -Display a help message and exit. - -@item -h host_name, --host=host_name -Import data to the @strong{MySQL} server on the named host. The default host -is @code{localhost}. - -@item -i, --ignore -See the description for the @code{--replace} option. - -@item -l, --lock-tables -Lock @strong{ALL} tables for writing before processing any text files. This -ensures that all tables are synchronized on the server. - -@item -L, --local -Read input files from the client. By default, text files are assumed to be on -the server if you connect to @code{localhost} (which is the default host). - -@item -pyour_pass, --password[=your_pass] -The password to use when connecting to the server. If you specify -no @samp{=your_pass} part, -@code{mysqlimport} you will be prompted for a password. - -@item -P port_num, --port=port_num -The TCP/IP port number to use for connecting to a host. (This is used for -connections to hosts other than @code{localhost}, for which Unix sockets are -used.) - -@item -r, --replace -The @code{--replace} and @code{--ignore} options control handling of input -records that duplicate existing records on unique key values. If you specify -@code{--replace}, new rows replace existing rows that have the same unique key -value. If you specify @code{--ignore}, input rows that duplicate an existing -row on a unique key value are skipped. If you don't specify either option, an -error occurs when a duplicate key value is found, and the rest of the text -file is ignored. - -@item -s, --silent -Silent mode. Write output only when errors occur. - -@item -S /path/to/socket, --socket=/path/to/socket -The socket file to use when connecting to @code{localhost} (which is the -default host). - -@item -u user_name, --user=user_name -The @strong{MySQL} user name to use when connecting to the server. The -default value is your Unix login name. - -@item -v, --verbose -Verbose mode. Print out more information what the program does. - -@item -V, --version -Print version information and exit. -@end table - -Here is a sample run using @code{mysqlimport}: - -@example -$ mysql --version -mysql Ver 9.33 Distrib 3.22.25, for pc-linux-gnu (i686) -$ uname -a -Linux xxx.com 2.2.5-15 #1 Mon Apr 19 22:21:09 EDT 1999 i586 unknown -$ mysql -e 'CREATE TABLE imptest(id INT, n VARCHAR(30))' test -$ ed -a -100 Max Sydow -101 Count Dracula -. -w imptest.txt -32 -q -$ od -c imptest.txt -0000000 1 0 0 \t M a x S y d o w \n 1 0 -0000020 1 \t C o u n t D r a c u l a \n -0000040 -$ mysqlimport --local test imptest.txt -test.imptest: Records: 2 Deleted: 0 Skipped: 0 Warnings: 0 -$ mysql -e 'SELECT * FROM imptest' test -+------+---------------+ -| id | n | -+------+---------------+ -| 100 | Max Sydow | -| 101 | Count Dracula | -+------+---------------+ -@end example - -@cindex error messages, displaying -@cindex perror -@node perror, mysqlshow, mysqlimport, Tools -@section Converting an error code to the corresponding error message - -@code{perror} can be used to print error message(s). @code{perror} can -be invoked like this: - -@example -shell> perror [OPTIONS] [ERRORCODE [ERRORCODE...]] - -For example: - -shell> perror 64 79 -Error code 64: Machine is not on the network -Error code 79: Can not access a needed shared library -@end example - -@code{perror} can be used to display a description for a system error -code, or an MyISAM/ISAM table handler error code. The error messages -are mostly system dependent. - -@cindex databases, displaying -@cindex displaying, database information -@cindex tables, displaying -@cindex columns, displaying -@cindex showing, database information -@node mysqlshow, myisampack, perror, Tools -@section Showing Databases, Tables, and Columns - -@code{mysqlshow} can be used to quickly look at which databases exist, -their tables, and the table's columns. - -With the @code{mysql} program you can get the same information with the -@code{SHOW} commands. @xref{SHOW}. - -@code{mysqlshow} is invoked like this: - -@example -shell> mysqlshow [OPTIONS] [database [table [column]]] -@end example - -@itemize @bullet -@item -If no database is given, all matching databases are shown. -@item -If no table is given, all matching tables in the database are shown. -@item -If no column is given, all matching columns and column types in the table -are shown. -@end itemize - -Note that in newer @strong{MySQL} versions, you only see those -database/tables/columns for which you have some privileges. - -If the last argument contains a shell or SQL wild-card (@code{*}, @code{?}, -@code{%} or @code{_}) then only what's matched by the wild card is shown. -This may cause some confusion when you try to display the columns for a -table with a @code{_} as in this case @code{mysqlshow} only shows you -the table names that match the pattern. This is easily fixed by -adding an extra @code{%} last on the command line (as a separate -argument). - -@cindex compressed tables -@cindex tables, compressed -@cindex MyISAM, compressed tables -@cindex @code{myisampack} -@cindex @code{pack_isam} -@node myisampack, , mysqlshow, Tools -@section The MySQL Compressed Read-only Table Generator - -@code{myisampack} is used to compress MyISAM tables, and @code{pack_isam} -is used to compress ISAM tables. Because ISAM tables are deprecated, we -will only discuss @code{myisampack} here, but everything said about -@code{myisampack} should also be true for @code{pack_isam}. - -@code{myisampack} works by compressing each column in the table separately. -The information needed to decompress columns is read into memory when the -table is opened. This results in much better performance when accessing -individual records, because you only have to uncompress exactly one record, not -a much larger disk block as when using Stacker on MS-DOS. -Usually, @code{myisampack} packs the data file 40%-70%. - -@strong{MySQL} uses memory mapping (@code{mmap()}) on compressed tables and -falls back to normal read/write file usage if @code{mmap()} doesn't work. - -There are currently two limitations with @code{myisampack}: -@itemize @bullet -@item -After packing, the table is read-only. -@item -@code{myisampack} can also pack @code{BLOB} or @code{TEXT} columns. The -older @code{pack_isam} could not do this. -@end itemize - -Fixing these limitations is on our TODO list but with low priority. - -@code{myisampack} is invoked like this: - -@example -shell> myisampack [options] filename ... -@end example - -Each filename should be the name of an index (@file{.MYI}) file. If you -are not in the database directory, you should specify the pathname to the -file. It is permissible to omit the @file{.MYI} extension. - -@code{myisampack} supports the following options: - -@table @code -@item -b, --backup -Make a backup of the table as @code{tbl_name.OLD}. - -@item -#, --debug=debug_options -Output debug log. The @code{debug_options} string often is -@code{'d:t:o,filename'}. - -@item -f, --force -Force packing of the table even if it becomes bigger or if the temporary file -exists. @code{myisampack} creates a temporary file named @file{tbl_name.TMD} -while it compresses the table. If you kill @code{myisampack}, the @file{.TMD} -file may not be deleted. Normally, @code{myisampack} exits with an error if -it finds that @file{tbl_name.TMD} exists. With @code{--force}, -@code{myisampack} packs the table anyway. - -@item -?, --help -Display a help message and exit. - -@item -j big_tbl_name, --join=big_tbl_name -Join all tables named on the command line into a single table -@code{big_tbl_name}. All tables that are to be combined -MUST be identical (same column names and types, same indexes, etc.). - -@item -p #, --packlength=# -Specify the record length storage size, in bytes. The value should be 1, 2, -or 3. (@code{myisampack} stores all rows with length pointers of 1, 2, or 3 -bytes. In most normal cases, @code{myisampack} can determine the right length -value before it begins packing the file, but it may notice during the packing -process that it could have used a shorter length. In this case, -@code{myisampack} will print a note that the next time you pack the same file, -you could use a shorter record length.) - -@item -s, --silent -Silent mode. Write output only when errors occur. - -@item -t, --test -Don't actually pack table, just test packing it. - -@item -T dir_name, --tmp_dir=dir_name -Use the named directory as the location in which to write the temporary table. - -@item -v, --verbose -Verbose mode. Write information about progress and packing result. - -@item -V, --version -Display version information and exit. - -@item -w, --wait - -Wait and retry if table is in use. If the @code{mysqld} server was -invoked with the @code{--skip-locking} option, it is not a good idea to -invoke @code{myisampack} if the table might be updated during the -packing process. -@end table - -@cindex examples, compressed tables -The sequence of commands shown below illustrates a typical table compression -session: - -@example -shell> ls -l station.* --rw-rw-r-- 1 monty my 994128 Apr 17 19:00 station.MYD --rw-rw-r-- 1 monty my 53248 Apr 17 19:00 station.MYI --rw-rw-r-- 1 monty my 5767 Apr 17 19:00 station.frm - -shell> myisamchk -dvv station - -MyISAM file: station -Isam-version: 2 -Creation time: 1996-03-13 10:08:58 -Recover time: 1997-02-02 3:06:43 -Data records: 1192 Deleted blocks: 0 -Datafile: Parts: 1192 Deleted data: 0 -Datafile pointer (bytes): 2 Keyfile pointer (bytes): 2 -Max datafile length: 54657023 Max keyfile length: 33554431 -Recordlength: 834 -Record format: Fixed length - -table description: -Key Start Len Index Type Root Blocksize Rec/key -1 2 4 unique unsigned long 1024 1024 1 -2 32 30 multip. text 10240 1024 1 - -Field Start Length Type -1 1 1 -2 2 4 -3 6 4 -4 10 1 -5 11 20 -6 31 1 -7 32 30 -8 62 35 -9 97 35 -10 132 35 -11 167 4 -12 171 16 -13 187 35 -14 222 4 -15 226 16 -16 242 20 -17 262 20 -18 282 20 -19 302 30 -20 332 4 -21 336 4 -22 340 1 -23 341 8 -24 349 8 -25 357 8 -26 365 2 -27 367 2 -28 369 4 -29 373 4 -30 377 1 -31 378 2 -32 380 8 -33 388 4 -34 392 4 -35 396 4 -36 400 4 -37 404 1 -38 405 4 -39 409 4 -40 413 4 -41 417 4 -42 421 4 -43 425 4 -44 429 20 -45 449 30 -46 479 1 -47 480 1 -48 481 79 -49 560 79 -50 639 79 -51 718 79 -52 797 8 -53 805 1 -54 806 1 -55 807 20 -56 827 4 -57 831 4 - -shell> myisampack station.MYI -Compressing station.MYI: (1192 records) -- Calculating statistics - -normal: 20 empty-space: 16 empty-zero: 12 empty-fill: 11 -pre-space: 0 end-space: 12 table-lookups: 5 zero: 7 -Original trees: 57 After join: 17 -- Compressing file -87.14% - -shell> ls -l station.* --rw-rw-r-- 1 monty my 127874 Apr 17 19:00 station.MYD --rw-rw-r-- 1 monty my 55296 Apr 17 19:04 station.MYI --rw-rw-r-- 1 monty my 5767 Apr 17 19:00 station.frm - -shell> myisamchk -dvv station - -MyISAM file: station -Isam-version: 2 -Creation time: 1996-03-13 10:08:58 -Recover time: 1997-04-17 19:04:26 -Data records: 1192 Deleted blocks: 0 -Datafile: Parts: 1192 Deleted data: 0 -Datafilepointer (bytes): 3 Keyfile pointer (bytes): 1 -Max datafile length: 16777215 Max keyfile length: 131071 -Recordlength: 834 -Record format: Compressed - -table description: -Key Start Len Index Type Root Blocksize Rec/key -1 2 4 unique unsigned long 10240 1024 1 -2 32 30 multip. text 54272 1024 1 - -Field Start Length Type Huff tree Bits -1 1 1 constant 1 0 -2 2 4 zerofill(1) 2 9 -3 6 4 no zeros, zerofill(1) 2 9 -4 10 1 3 9 -5 11 20 table-lookup 4 0 -6 31 1 3 9 -7 32 30 no endspace, not_always 5 9 -8 62 35 no endspace, not_always, no empty 6 9 -9 97 35 no empty 7 9 -10 132 35 no endspace, not_always, no empty 6 9 -11 167 4 zerofill(1) 2 9 -12 171 16 no endspace, not_always, no empty 5 9 -13 187 35 no endspace, not_always, no empty 6 9 -14 222 4 zerofill(1) 2 9 -15 226 16 no endspace, not_always, no empty 5 9 -16 242 20 no endspace, not_always 8 9 -17 262 20 no endspace, no empty 8 9 -18 282 20 no endspace, no empty 5 9 -19 302 30 no endspace, no empty 6 9 -20 332 4 always zero 2 9 -21 336 4 always zero 2 9 -22 340 1 3 9 -23 341 8 table-lookup 9 0 -24 349 8 table-lookup 10 0 -25 357 8 always zero 2 9 -26 365 2 2 9 -27 367 2 no zeros, zerofill(1) 2 9 -28 369 4 no zeros, zerofill(1) 2 9 -29 373 4 table-lookup 11 0 -30 377 1 3 9 -31 378 2 no zeros, zerofill(1) 2 9 -32 380 8 no zeros 2 9 -33 388 4 always zero 2 9 -34 392 4 table-lookup 12 0 -35 396 4 no zeros, zerofill(1) 13 9 -36 400 4 no zeros, zerofill(1) 2 9 -37 404 1 2 9 -38 405 4 no zeros 2 9 -39 409 4 always zero 2 9 -40 413 4 no zeros 2 9 -41 417 4 always zero 2 9 -42 421 4 no zeros 2 9 -43 425 4 always zero 2 9 -44 429 20 no empty 3 9 -45 449 30 no empty 3 9 -46 479 1 14 4 -47 480 1 14 4 -48 481 79 no endspace, no empty 15 9 -49 560 79 no empty 2 9 -50 639 79 no empty 2 9 -51 718 79 no endspace 16 9 -52 797 8 no empty 2 9 -53 805 1 17 1 -54 806 1 3 9 -55 807 20 no empty 3 9 -56 827 4 no zeros, zerofill(2) 2 9 -57 831 4 no zeros, zerofill(1) 2 9 -@end example - -The information printed by @code{myisampack} is described below: - -@table @code -@item normal -The number of columns for which no extra packing is used. - -@item empty-space -The number of columns containing -values that are only spaces; these will occupy 1 bit. - -@item empty-zero -The number of columns containing -values that are only binary 0's; these will occupy 1 bit. - -@item empty-fill -The number of integer columns that don't occupy the full byte range of their -type; these are changed to a smaller type (for example, an @code{INTEGER} -column may be changed to @code{MEDIUMINT}). - -@item pre-space -The number of decimal columns that are stored with leading spaces. In this -case, each value will contain a count for the number of leading spaces. - -@item end-space -The number of columns that have a lot of trailing spaces. In this case, each -value will contain a count for the number of trailing spaces. - -@item table-lookup -The column had only a small number of different values, which were -converted to an @code{ENUM} before Huffman compression. - -@item zero -The number of columns for which all values are zero. - -@item Original trees -The initial number of Huffman trees. - -@item After join -The number of distinct Huffman trees left after joining -trees to save some header space. -@end table - -After a table has been compressed, @code{myisamchk -dvv} prints additional -information about each field: - -@table @code -@item Type -The field type may contain the following descriptors: - -@table @code -@item constant -All rows have the same value. - -@item no endspace -Don't store endspace. - -@item no endspace, not_always -Don't store endspace and don't do end space compression for all values. - -@item no endspace, no empty -Don't store endspace. Don't store empty values. - -@item table-lookup -The column was converted to an @code{ENUM}. - -@item zerofill(n) -The most significant @code{n} bytes in the value are always 0 and are not -stored. - -@item no zeros -Don't store zeros. - -@item always zero -0 values are stored in 1 bit. -@end table - -@item Huff tree -The Huffman tree associated with the field. - -@item Bits -The number of bits used in the Huffman tree. -@end table - -After you have run @code{pack_isam}/@code{myisampack} you must run -@code{isamchk}/@code{myisamchk} to re-create the index. At this time you -can also sort the index blocks and create statistics needed for -the @strong{MySQL} optimizer to work more efficiently: - -@example -myisamchk -rq --analyze --sort-index table_name.MYI -isamchk -rq --analyze --sort-index table_name.ISM -@end example - -After you have installed the packed table into the @strong{MySQL} database -directory you should do @code{mysqladmin flush-tables} to force @code{mysqld} -to start using the new table. - -If you want to unpack a packed table, you can do this with the -@code{--unpack} option to @code{isamchk} or @code{myisamchk}. +@node Maintenance, Adding functions, MySQL Benchmarks, Top +@chapter Maintaining a MySQL Installation @cindex installation maintenance @cindex maintaining, tables @@ -34074,406 +36594,19 @@ If you want to unpack a packed table, you can do this with the @cindex @code{mysqlcheck} @cindex crash, recovery @cindex recovery, from crash -@node Maintenance, Adding functions, Tools, Top -@chapter Maintaining a MySQL Installation + @menu -* Table maintenance:: Table maintenance and crash recovery * Using mysqlcheck:: Using mysqlcheck for maintenance and recovery -* Maintenance regimen:: Setting up a table maintenance regimen -* Table-info:: Getting information about a table -* Crash recovery:: Using @code{myisamchk} for crash recovery -* Log file maintenance:: Log file maintenance @end menu This chapter covers what you should know about maintaining a @strong{MySQL} distribution. You will learn how to care for your tables on a regular basis, and what to do when disaster strikes. -@node Table maintenance, Using mysqlcheck, Maintenance, Maintenance -@section Using @code{myisamchk} for Table Maintenance and Crash Recovery -Starting with @strong{MySQL} Version 3.23.13, you can check MyISAM -tables with the @code{CHECK TABLE} command. @xref{CHECK TABLE}. You can -repair tables with the @code{REPAIR TABLE} command. @xref{REPAIR TABLE}. -To check/repair MyISAM tables (@code{.MYI} and @code{.MYD}) you should -use the @code{myisamchk} utility. To check/repair ISAM tables -(@code{.ISM} and @code{.ISD}) you should use the @code{isamchk} -utility. @xref{Table types}. - -In the following text we will talk about @code{myisamchk}, but everything -also applies to the old @code{isamchk}. - -You can use the @code{myisamchk} utility to get information about your -database tables, check and repair them, or optimize them. The following -sections describe how to invoke @code{myisamchk} (including a -description of its options), how to set up a table maintenance schedule, -and how to use @code{myisamchk} to perform its various functions. - -You can, in most cases, also use the command @code{OPTIMIZE TABLES} to -optimize and repair tables, but this is not as fast or reliable (in case -of real fatal errors) as @code{myisamchk}. On the other hand, -@code{OPTIMIZE TABLE} is easier to use and you don't have to worry about -flushing tables. -@xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}. - -Even that the repair in @code{myisamchk} is quite secure, it's always a -good idea to make a backup BEFORE doing a repair (or anything that could -make a lot of changes to a table) - -@menu -* myisamchk syntax:: @code{myisamchk} invocation syntax -* myisamchk memory:: @code{myisamchk} memory usage -@end menu - -@node myisamchk syntax, myisamchk memory, Table maintenance, Table maintenance -@subsection @code{myisamchk} Invocation Syntax - -@code{myisamchk} is invoked like this: - -@example -shell> myisamchk [options] tbl_name -@end example - -The @code{options} specify what you want @code{myisamchk} to do. They are -described below. (You can also get a list of options by invoking -@code{myisamchk --help}.) With no options, @code{myisamchk} simply checks your -table. To get more information or to tell @code{myisamchk} to take corrective -action, specify options as described below and in the following sections. - -@code{tbl_name} is the database table you want to check/repair. If you run -@code{myisamchk} somewhere other than in the database directory, you must -specify the path to the file, because @code{myisamchk} has no idea where your -database is located. Actually, @code{myisamchk} doesn't care whether or not -the files you are working on are located in a database directory; you can -copy the files that correspond to a database table into another location and -perform recovery operations on them there. - -You can name several tables on the @code{myisamchk} command line if you -wish. You can also specify a name as an index file -name (with the @file{.MYI} suffix), which allows you to specify all -tables in a directory by using the pattern @file{*.MYI}. -For example, if you are in a database directory, you can check all the -tables in the directory like this: - -@example -shell> myisamchk *.MYI -@end example - -If you are not in the database directory, you can check all the tables there -by specifying the path to the directory: - -@example -shell> myisamchk /path/to/database_dir/*.MYI -@end example - -You can even check all tables in all databases by specifying a wild card -with the path to the @strong{MySQL} data directory: - -@example -shell> myisamchk /path/to/datadir/*/*.MYI -@end example - -The recommended way to quickly check all tables is: - -@example -myisamchk --silent --fast /path/to/datadir/*/*.MYI -isamchk --silent /path/to/datadir/*/*.ISM -@end example - -If you want to check all tables and repair all tables that are corrupted, -you can use the following line: - -@example -myisamchk --silent --force --fast --update-state -O key_buffer=64M -O sort_buffer=64M -O read_buffer=1M -O write_buffer=1M /path/to/datadir/*/*.MYI -isamchk --silent --force -O key_buffer=64M -O sort_buffer=64M -O read_buffer=1M -O write_buffer=1M /path/to/datadir/*/*.ISM -@end example - -The above assumes that you have more than 64 M free. - -Note that if you get an error like: - -@example -myisamchk: warning: 1 clients is using or hasn't closed the table properly -@end example - -This means that you are trying to check a table that has been updated by -the another program (like the @code{mysqld} server) that hasn't yet closed -the file or that has died without closing the file properly. - -If you @code{mysqld} is running, you must force a sync/close of all -tables with @code{FLUSH TABLES} and ensure that no one is using the -tables while you are running @code{myisamchk}. In @strong{MySQL} Version 3.23 -the easiest way to avoid this problem is to use @code{CHECK TABLE} -instead of @code{myisamchk} to check tables. - -@menu -* myisamchk general options:: -* myisamchk check options:: -* myisamchk repair options:: -* myisamchk other options:: -@end menu - -@cindex options, @code{myisamchk} -@cindex @code{myisamchk}, options -@node myisamchk general options, myisamchk check options, myisamchk syntax, myisamchk syntax -@subsubsection General Options for @code{myisamchk} - -@code{myisamchk} supports the following options. - -@table @code -@item -# or --debug=debug_options -Output debug log. The @code{debug_options} string often is -@code{'d:t:o,filename'}. -@item -? or --help -Display a help message and exit. -@item -O var=option, --set-variable var=option -Set the value of a variable. The possible variables and their default values -for myisamchk can be examined with @code{myisamchk --help}: -@multitable @columnfractions .3 .7 -@item key_buffer_size @tab 523264 -@item read_buffer_size @tab 262136 -@item write_buffer_size @tab 262136 -@item sort_buffer_size @tab 2097144 -@item sort_key_blocks @tab 16 -@item decode_bits @tab 9 -@end multitable - -@code{sort_buffer_size} is used when the keys are repaired by sorting -keys, which is the normal case when you use @code{--recover}. - -@code{key_buffer_size} is used when you are checking the table with -@code{--extended-check} or when the keys are repaired by inserting key -row by row in to the table (like when doing normal inserts). Repairing -through the key buffer is used in the following cases: - -@itemize @bullet -@item -If you use @code{--safe-recover}. -@item -If you are using a @code{FULLTEXT} index. -@item -If the temporary files needed to sort the keys would be more than twice -as big as when creating the key file directly. This is often the case -when you have big @code{CHAR}, @code{VARCHAR} or @code{TEXT} keys as the -sort needs to store the whole keys during sorting. If you have lots -of temporary space and you can force @code{myisamchk} to repair by sorting -you can use the @code{--sort-recover} option. -@end itemize - -Reparing through the key buffer takes much less disk space than using -sorting, but is also much slower. - -If you want a faster repair, set the above variables to about 1/4 of your -available memory. You can set both variables to big values, as only one -of the above buffers will be used at a time. - -@item -s or --silent -Silent mode. Write output only when errors occur. You can use @code{-s} -twice (@code{-ss}) to make @code{myisamchk} very silent. -@item -v or --verbose -Verbose mode. Print more information. This can be used with @code{-d} and -@code{-e}. Use @code{-v} multiple times (@code{-vv}, @code{-vvv}) for more -verbosity! -@item -V or --version -Print the @code{myisamchk} version and exit. -@item -w or, --wait -Instead of giving an error if the table is locked, wait until the table -is unlocked before continuing. Note that if you are running @code{mysqld} -on the table with @code{--skip-locking}, the table can only be locked -by another @code{myisamchk} command. -@end table - -@cindex check options, myisamchk -@cindex tables, checking -@node myisamchk check options, myisamchk repair options, myisamchk general options, myisamchk syntax -@subsubsection Check Options for @code{myisamchk} - -@table @code -@item -c or --check -Check table for errors. This is the default operation if you are not -giving @code{myisamchk} any options that override this. - -@item -e or --extend-check -Check the table VERY thoroughly (which is quite slow if you have many -indexes). This option should only be used in extreme cases. Normally, -@code{myisamchk} or @code{myisamchk --medium-check} should, in most -cases, be able to find out if there are any errors in the table. - -If you are using @code{--extended-check} and have much memory, you should -increase the value of @code{key_buffer_size} a lot! - -@item -F or --fast -Check only tables that haven't been closed properly. -@item -C or --check-only-changed -Check only tables that have changed since the last check. -@item -f or --force -Restart @code{myisamchk} with @code{-r} (repair) on the table, if -@code{myisamchk} finds any errors in the table. -@item -i or --information -Print informational statistics about the table that is checked. -@item -m or --medium-check -Faster than extended-check, but only finds 99.99% of all errors. -Should, however, be good enough for most cases. -@item -U or --update-state -Store in the @file{.MYI} file when the table was checked and if the table crashed. This should be used to get full benefit of the -@code{--check-only-changed} option, but you shouldn't use this -option if the @code{mysqld} server is using the table and you are -running @code{mysqld} with @code{--skip-locking}. -@item -T or --read-only -Don't mark table as checked. This is useful if you use @code{myisamchk} -to check a table that is in use by some other application that doesn't -use locking (like @code{mysqld --skip-locking}). -@end table - -@cindex repair options, myisamchk -@cindex files, repairing -@node myisamchk repair options, myisamchk other options, myisamchk check options, myisamchk syntax -@subsubsection Repair Options for myisamchk - -The following options are used if you start @code{myisamchk} with -@code{-r} or @code{-o}: - -@table @code -@item -D # or --data-file-length=# -Max length of data file (when re-creating data file when it's 'full'). -@item -e or --extend-check -Try to recover every possible row from the data file. -Normally this will also find a lot of garbage rows. Don't use this option -if you are not totally desperate. -@item -f or --force -Overwrite old temporary files (@code{table_name.TMD}) instead of aborting. -@item -k # or keys-used=# -If you are using ISAM, tells the ISAM table handler to update only the -first @code{#} indexes. If you are using @code{MyISAM}, tells which keys -to use, where each binary bit stands for one key (first key is bit 0). -This can be used to get faster inserts! Deactivated indexes can be -reactivated by using @code{myisamchk -r}. keys. -@item -l or --no-symlinks -Do not follow symbolic links. Normally @code{myisamchk} repairs the -table a symlink points at. This option doesn't exist in MySQL 4.0, -as MySQL 4.0 will not remove symlinks during repair. -@item -r or --recover -Can fix almost anything except unique keys that aren't unique -(which is an extremely unlikely error with ISAM/MyISAM tables). -If you want to recover a table, this is the option to try first. Only if -myisamchk reports that the table can't be recovered by @code{-r}, you -should then try @code{-o}. (Note that in the unlikely case that @code{-r} -fails, the data file is still intact.) -If you have lots of memory, you should increase the size of -@code{sort_buffer_size}! -@item -o or --safe-recover -Uses an old recovery method (reads through all rows in order and updates -all index trees based on the found rows); this is a magnitude slower -than @code{-r}, but can handle a couple of very unlikely cases that -@code{-r} cannot handle. This recovery method also uses much less disk -space than @code{-r}. Normally one should always first repair with -@code{-r}, and only if this fails use @code{-o}. - -If you have lots of memory, you should increase the size of -@code{key_buffer_size}! -@item -n or --sort-recover -Force @code{myisamchk} to use sorting to resolve the keys even if the -temporary files should be very big. This will not have any effect if you have -fulltext keys in the table. - -@item --character-sets-dir=... -Directory where character sets are stored. -@item --set-character-set=name -Change the character set used by the index -@item .t or --tmpdir=path -Path for storing temporary files. If this is not set, @code{myisamchk} will -use the environment variable @code{TMPDIR} for this. -@item -q or --quick -Faster repair by not modifying the data file. One can give a second -@code{-q} to force @code{myisamchk} to modify the original datafile in case -of duplicate keys -@item -u or --unpack -Unpack file packed with myisampack. -@end table - -@node myisamchk other options, , myisamchk repair options, myisamchk syntax -@subsubsection Other Options for @code{myisamchk} - -Other actions that @code{myisamchk} can do, besides repair and check tables: - -@table @code -@item -a or --analyze -Analyze the distribution of keys. This improves join performance by -enabling the join optimizer to better choose in which order it should -join the tables and which keys it should use: -@code{myisamchk --describe --verbose table_name'} or using @code{SHOW KEYS} in -@strong{MySQL}. -@item -d or --description -Prints some information about table. -@item -A or --set-auto-increment[=value] -Force auto_increment to start at this or higher value. If no value is -given, then sets the next auto_increment value to the highest used value -for the auto key + 1. -@item -S or --sort-index -Sort the index tree blocks in high-low order. -This will optimize seeks and will make table scanning by key faster. -@item -R or --sort-records=# -Sorts records according to an index. This makes your data much more localized -and may speed up ranged @code{SELECT} and @code{ORDER BY} operations on -this index. (It may be VERY slow to do a sort the first time!) -To find out a table's index numbers, use @code{SHOW INDEX}, which shows a -table's indexes in the same order that @code{myisamchk} sees them. Indexes are -numbered beginning with 1. -@end table - -@cindex memory usage, myisamchk -@node myisamchk memory, , myisamchk syntax, Table maintenance -@subsection @code{myisamchk} Memory Usage - -Memory allocation is important when you run @code{myisamchk}. -@code{myisamchk} uses no more memory than you specify with the @code{-O} -options. If you are going to use @code{myisamchk} on very large files, -you should first decide how much memory you want it to use. The default -is to use only about 3M to fix things. By using larger values, you can -get @code{myisamchk} to operate faster. For example, if you have more -than 32M RAM, you could use options such as these (in addition to any -other options you might specify): - -@example -shell> myisamchk -O sort=16M -O key=16M -O read=1M -O write=1M ... -@end example - -Using @code{-O sort=16M} should probably be enough for most cases. - -Be aware that @code{myisamchk} uses temporary files in @code{TMPDIR}. If -@code{TMPDIR} points to a memory file system, you may easily get out of -memory errors. If this happens, set @code{TMPDIR} to point at some directory -with more space and restart @code{myisamchk}. - -When repairing, @code{myisamchk} will also need a lot of disk space: - -@itemize @bullet -@item -Double the size of the record file (the original one and a copy). This -space is not needed if one does a repair with @code{--quick}, as in this -case only the index file will be re-created. This space is needed on the -same disk as the original record file! -@item -Space for the new index file that replaces the old one. The old -index file is truncated at start, so one usually ignore this space. -This space is needed on the same disk as the original index file! -@item -When using @code{--recover} or @code{--sort-recover} -(but not when using @code{--safe-recover}, you will need space for a -sort buffer for: -@code{(largest_key + row_pointer_length)*number_of_rows * 2}. -You can check the length of the keys and the row_pointer_length with -@code{myisamchk -dv table}. -This space is allocated on the temporary disk (specified by @code{TMPDIR} or -@code{--tmpdir=#}). -@end itemize - -If you have a problem with disk space during repair, you can try to use -@code{--safe-recover} instead of @code{--recover}. - -@node Using mysqlcheck, Maintenance regimen, Table maintenance, Maintenance +@node Using mysqlcheck, , Maintenance, Maintenance @section Using @code{mysqlcheck} for Table Maintenance and Crash Recovery Since @strong{MySQL} version 3.23.38 you will be able to use a new @@ -34596,780 +36729,7 @@ Print info about the various stages. Output version information and exit. @end table -@cindex maintaining, tables -@cindex tables, maintenance regimen -@node Maintenance regimen, Table-info, Using mysqlcheck, Maintenance -@section Setting Up a Table Maintenance Regimen -Starting with @strong{MySQL} Version 3.23.13, you can check MyISAM -tables with the @code{CHECK TABLE} command. @xref{CHECK TABLE}. You can -repair tables with the @code{REPAIR TABLE} command. @xref{REPAIR TABLE}. - -It is a good idea to perform table checks on a regular basis rather than -waiting for problems to occur. For maintenance purposes, you can use -@code{myisamchk -s} to check tables. The @code{-s} option (short for -@code{--silent}) causes @code{myisamchk} to run in silent mode, printing -messages only when errors occur. - -@tindex .pid (process ID) file -It's also a good idea to check tables when the server starts up. -For example, whenever the machine has done a reboot in the middle of an -update, you usually need to check all the tables that could have been -affected. (This is an ``expected crashed table''.) You could add a test to -@code{safe_mysqld} that runs @code{myisamchk} to check all tables that have -been modified during the last 24 hours if there is an old @file{.pid} -(process ID) file left after a reboot. (The @file{.pid} file is created by -@code{mysqld} when it starts up and removed when it terminates normally. The -presence of a @file{.pid} file at system startup time indicates that -@code{mysqld} terminated abnormally.) - -An even better test would be to check any table whose last-modified time -is more recent than that of the @file{.pid} file. - -You should also check your tables regularly during normal system -operation. At @strong{MySQL AB}, we run a @code{cron} job to check all -our important tables once a week, using a line like this in a @file{crontab} -file: - -@example -35 0 * * 0 /path/to/myisamchk --fast --silent /path/to/datadir/*/*.MYI -@end example - -This prints out information about crashed tables so we can examine and repair -them when needed. - -As we haven't had any unexpectedly crashed tables (tables that become -corrupted for reasons other than hardware trouble) -for a couple of years now (this is really true), once a week is -more than enough for us. - -We recommend that to start with, you execute @code{myisamchk -s} each -night on all tables that have been updated during the last 24 hours, -until you come to trust @strong{MySQL} as much as we do. - -@cindex tables, defragment -Normally you don't need to maintain @strong{MySQL} tables that much. If -you are changing tables with dynamic size rows (tables with @code{VARCHAR}, -@code{BLOB} or @code{TEXT} columns) or have tables with many deleted rows -you may want to from time to time (once a month?) defragment/reclaim space -from the tables. - -You can do this by using @code{OPTIMIZE TABLE} on the tables in question or -if you can take the @code{mysqld} server down for a while do: - -@example -isamchk -r --silent --sort-index -O sort_buffer_size=16M */*.ISM -myisamchk -r --silent --sort-index -O sort_buffer_size=16M */*.MYI -@end example - -@cindex tables, information -@node Table-info, Crash recovery, Maintenance regimen, Maintenance -@section Getting Information About a Table - -To get a description of a table or statistics about it, use the commands shown -below. We explain some of the information in more detail later: - -@table @code -@item myisamchk -d tbl_name -Runs @code{myisamchk} in ``describe mode'' to produce a description of -your table. If you start the @strong{MySQL} server using the -@code{--skip-locking} option, @code{myisamchk} may report an error for a -table that is updated while it runs. However, because @code{myisamchk} -doesn't change the table in describe mode, there isn't any risk of -destroying data. - -@item myisamchk -d -v tbl_name -To produce more information about what @code{myisamchk} is doing, add @code{-v} -to tell it to run in verbose mode. - -@item myisamchk -eis tbl_name -Shows only the most important information from a table. It is slow because it -must read the whole table. - -@item myisamchk -eiv tbl_name -This is like @code{-eis}, but tells you what is being done. -@end table - -@cindex examples, @code{myisamchk} output -@cindex @code{myisamchk}, example output -Example of @code{myisamchk -d} output: -@example -MyISAM file: company.MYI -Record format: Fixed length -Data records: 1403698 Deleted blocks: 0 -Recordlength: 226 - -table description: -Key Start Len Index Type -1 2 8 unique double -2 15 10 multip. text packed stripped -3 219 8 multip. double -4 63 10 multip. text packed stripped -5 167 2 multip. unsigned short -6 177 4 multip. unsigned long -7 155 4 multip. text -8 138 4 multip. unsigned long -9 177 4 multip. unsigned long - 193 1 text -@end example - -Example of @code{myisamchk -d -v} output: -@example -MyISAM file: company -Record format: Fixed length -File-version: 1 -Creation time: 1999-10-30 12:12:51 -Recover time: 1999-10-31 19:13:01 -Status: checked -Data records: 1403698 Deleted blocks: 0 -Datafile parts: 1403698 Deleted data: 0 -Datafilepointer (bytes): 3 Keyfile pointer (bytes): 3 -Max datafile length: 3791650815 Max keyfile length: 4294967294 -Recordlength: 226 - -table description: -Key Start Len Index Type Rec/key Root Blocksize -1 2 8 unique double 1 15845376 1024 -2 15 10 multip. text packed stripped 2 25062400 1024 -3 219 8 multip. double 73 40907776 1024 -4 63 10 multip. text packed stripped 5 48097280 1024 -5 167 2 multip. unsigned short 4840 55200768 1024 -6 177 4 multip. unsigned long 1346 65145856 1024 -7 155 4 multip. text 4995 75090944 1024 -8 138 4 multip. unsigned long 87 85036032 1024 -9 177 4 multip. unsigned long 178 96481280 1024 - 193 1 text -@end example - -Example of @code{myisamchk -eis} output: -@example -Checking MyISAM file: company -Key: 1: Keyblocks used: 97% Packed: 0% Max levels: 4 -Key: 2: Keyblocks used: 98% Packed: 50% Max levels: 4 -Key: 3: Keyblocks used: 97% Packed: 0% Max levels: 4 -Key: 4: Keyblocks used: 99% Packed: 60% Max levels: 3 -Key: 5: Keyblocks used: 99% Packed: 0% Max levels: 3 -Key: 6: Keyblocks used: 99% Packed: 0% Max levels: 3 -Key: 7: Keyblocks used: 99% Packed: 0% Max levels: 3 -Key: 8: Keyblocks used: 99% Packed: 0% Max levels: 3 -Key: 9: Keyblocks used: 98% Packed: 0% Max levels: 4 -Total: Keyblocks used: 98% Packed: 17% - -Records: 1403698 M.recordlength: 226 Packed: 0% -Recordspace used: 100% Empty space: 0% Blocks/Record: 1.00 -Record blocks: 1403698 Delete blocks: 0 -Recorddata: 317235748 Deleted data: 0 -Lost space: 0 Linkdata: 0 - -User time 1626.51, System time 232.36 -Maximum resident set size 0, Integral resident set size 0 -Non physical pagefaults 0, Physical pagefaults 627, Swaps 0 -Blocks in 0 out 0, Messages in 0 out 0, Signals 0 -Voluntary context switches 639, Involuntary context switches 28966 -@end example - -Example of @code{myisamchk -eiv} output: -@example -Checking MyISAM file: company -Data records: 1403698 Deleted blocks: 0 -- check file-size -- check delete-chain -block_size 1024: -index 1: -index 2: -index 3: -index 4: -index 5: -index 6: -index 7: -index 8: -index 9: -No recordlinks -- check index reference -- check data record references index: 1 -Key: 1: Keyblocks used: 97% Packed: 0% Max levels: 4 -- check data record references index: 2 -Key: 2: Keyblocks used: 98% Packed: 50% Max levels: 4 -- check data record references index: 3 -Key: 3: Keyblocks used: 97% Packed: 0% Max levels: 4 -- check data record references index: 4 -Key: 4: Keyblocks used: 99% Packed: 60% Max levels: 3 -- check data record references index: 5 -Key: 5: Keyblocks used: 99% Packed: 0% Max levels: 3 -- check data record references index: 6 -Key: 6: Keyblocks used: 99% Packed: 0% Max levels: 3 -- check data record references index: 7 -Key: 7: Keyblocks used: 99% Packed: 0% Max levels: 3 -- check data record references index: 8 -Key: 8: Keyblocks used: 99% Packed: 0% Max levels: 3 -- check data record references index: 9 -Key: 9: Keyblocks used: 98% Packed: 0% Max levels: 4 -Total: Keyblocks used: 9% Packed: 17% - -- check records and index references -[LOTS OF ROW NUMBERS DELETED] - -Records: 1403698 M.recordlength: 226 Packed: 0% -Recordspace used: 100% Empty space: 0% Blocks/Record: 1.00 -Record blocks: 1403698 Delete blocks: 0 -Recorddata: 317235748 Deleted data: 0 -Lost space: 0 Linkdata: 0 - -User time 1639.63, System time 251.61 -Maximum resident set size 0, Integral resident set size 0 -Non physical pagefaults 0, Physical pagefaults 10580, Swaps 0 -Blocks in 4 out 0, Messages in 0 out 0, Signals 0 -Voluntary context switches 10604, Involuntary context switches 122798 -@end example - -Here are the sizes of the data and index files for the table used in the -preceding examples: - -@example --rw-rw-r-- 1 monty tcx 317235748 Jan 12 17:30 company.MYD --rw-rw-r-- 1 davida tcx 96482304 Jan 12 18:35 company.MYM -@end example - -Explanations for the types of information @code{myisamchk} produces are -given below. The ``keyfile'' is the index file. ``Record'' and ``row'' -are synonymous: - -@table @code -@item ISAM file -Name of the ISAM (index) file. - -@item Isam-version -Version of ISAM format. Currently always 2. - -@item Creation time -When the data file was created. - -@item Recover time -When the index/data file was last reconstructed. - -@item Data records -How many records are in the table. - -@item Deleted blocks -How many deleted blocks still have reserved space. -You can optimize your table to minimize this space. -@xref{Optimization}. - -@item Datafile: Parts -For dynamic record format, this indicates how many data blocks there are. For -an optimized table without fragmented records, this is the same as @code{Data -records}. - -@item Deleted data -How many bytes of non-reclaimed deleted data there are. -You can optimize your table to minimize this space. -@xref{Optimization}. - -@item Datafile pointer -The size of the data file pointer, in bytes. It is usually 2, 3, 4, or 5 -bytes. Most tables manage with 2 bytes, but this cannot be controlled -from @strong{MySQL} yet. For fixed tables, this is a record address. For -dynamic tables, this is a byte address. - -@item Keyfile pointer -The size of the index file pointer, in bytes. It is usually 1, 2, or 3 -bytes. Most tables manage with 2 bytes, but this is calculated -automatically by @strong{MySQL}. It is always a block address. - -@item Max datafile length -How long the table's data file (@code{.MYD} file) can become, in bytes. - -@item Max keyfile length -How long the table's key file (@code{.MYI} file) can become, in bytes. - -@item Recordlength -How much space each record takes, in bytes. - -@item Record format -The format used to store table rows. -The examples shown above use @code{Fixed length}. -Other possible values are @code{Compressed} and @code{Packed}. - -@item table description -A list of all keys in the table. For each key, some low-level information -is presented: - -@table @code -@item Key -This key's number. - -@item Start -Where in the record this index part starts. - -@item Len -How long this index part is. For packed numbers, this should always be -the full length of the column. For strings, it may be shorter than the full -length of the indexed column, because you can index a prefix of a string -column. - -@item Index -@code{unique} or @code{multip.} (multiple). Indicates whether or not one value -can exist multiple times in this index. - -@item Type -What data-type this index part has. This is an ISAM data-type -with the options @code{packed}, @code{stripped} or @code{empty}. - -@item Root -Address of the root index block. - -@item Blocksize -The size of each index block. By default this is 1024, but the value may be -changed at compile time. - -@item Rec/key -This is a statistical value used by the optimizer. It tells how many -records there are per value for this key. A unique key always has a -value of 1. This may be updated after a table is loaded (or greatly -changed) with @code{myisamchk -a}. If this is not updated at all, a default -value of 30 is given. -@end table - -@item -In the first example above, the 9th key is a multi-part key with two parts. - -@item Keyblocks used -What percentage of the keyblocks are used. Because the table used in the -examples had just been reorganized with @code{myisamchk}, the values are very -high (very near the theoretical maximum). - -@item Packed -@strong{MySQL} tries to pack keys with a common suffix. This can only be used -for @code{CHAR}/@code{VARCHAR}/@code{DECIMAL} keys. For long strings like -names, this can significantly reduce the space used. In the third example -above, the 4th key is 10 characters long and a 60% reduction in space is -achieved. - -@item Max levels -How deep the B-tree for this key is. Large tables with long keys get high -values. - -@item Records -How many rows are in the table. - -@item M.recordlength -The average record length. For tables with fixed-length records, this is the -exact record length. - -@item Packed -@strong{MySQL} strips spaces from the end of strings. The @code{Packed} -value indicates the percentage of savings achieved by doing this. - -@item Recordspace used -What percentage of the data file is used. - -@item Empty space -What percentage of the data file is unused. - -@item Blocks/Record -Average number of blocks per record (that is, how many links a fragmented -record is composed of). This is always 1 for fixed-format tables. This value -should stay as close to 1.0 as possible. If it gets too big, you can -reorganize the table with @code{myisamchk}. -@xref{Optimization}. - -@item Recordblocks -How many blocks (links) are used. For fixed format, this is the same as the number -of records. - -@item Deleteblocks -How many blocks (links) are deleted. - -@item Recorddata -How many bytes in the data file are used. - -@item Deleted data -How many bytes in the data file are deleted (unused). - -@item Lost space -If a record is updated to a shorter length, some space is lost. This is -the sum of all such losses, in bytes. - -@item Linkdata -When the dynamic table format is used, record fragments are linked with -pointers (4 to 7 bytes each). @code{Linkdata} is the sum of the amount of -storage used by all such pointers. -@end table - -If a table has been compressed with @code{myisampack}, @code{myisamchk --d} prints additional information about each table column. See -@ref{myisampack, , @code{myisampack}}, for an example of this -information and a description of what it means. - -@cindex crash, recovery -@cindex recovery, from crash -@node Crash recovery, Log file maintenance, Table-info, Maintenance -@section Using @code{myisamchk} for Crash Recovery - -If you run @code{mysqld} with @code{--skip-locking} (which is the default on -some systems, like Linux), you can't reliably use @code{myisamchk} to -check a table when @code{mysqld} is using the same table. If you -can be sure that no one is accessing the tables through @code{mysqld} -while you run @code{myisamchk}, you only have to do @code{mysqladmin -flush-tables} before you start checking the tables. If you can't -guarantee the above, then you must take down @code{mysqld} while you -check the tables. If you run @code{myisamchk} while @code{mysqld} is updating -the tables, you may get a warning that a table is corrupt even if it -isn't. - -If you are not using @code{--skip-locking}, you can use @code{myisamchk} -to check tables at any time. While you do this, all clients that try -to update the table will wait until @code{myisamchk} is ready before -continuing. - -If you use @code{myisamchk} to repair or optimize tables, you -@strong{MUST} always ensure that the @code{mysqld} server is not using -the table (this also applies if you are using @code{--skip-locking}). -If you don't take down @code{mysqld} you should at least do a -@code{mysqladmin flush-tables} before you run @code{myisamchk}. - -This chapter describes how to check for and deal with data corruption -in @strong{MySQL} databases. If your tables get corrupted a lot you should -try to find the reason for this! @xref{Crashing}. - -The @code{MyISAM} table section contains reason for why a table could be -corrupted. @xref{MyISAM table problems}. - -When performing crash recovery, it is important to understand that each table -@code{tbl_name} in a database corresponds to three files in the database -directory: - -@multitable @columnfractions .2 .8 -@item @strong{File} @tab @strong{Purpose} -@item @file{tbl_name.frm} @tab Table definition (form) file -@item @file{tbl_name.MYD} @tab Data file -@item @file{tbl_name.MYI} @tab Index file -@end multitable - -Each of these three file types is subject to corruption in various ways, but -problems occur most often in data files and index files. - -@code{myisamchk} works by creating a copy of the @file{.MYD} (data) file -row by row. It ends the repair stage by removing the old @file{.MYD} -file and renaming the new file to the original file name. If you use -@code{--quick}, @code{myisamchk} does not create a temporary @file{.MYD} -file, but instead assumes that the @file{.MYD} file is correct and only -generates a new index file without touching the @file{.MYD} file. This -is safe, because @code{myisamchk} automatically detects if the -@file{.MYD} file is corrupt and aborts the repair in this case. You can -also give two @code{--quick} options to @code{myisamchk}. In this case, -@code{myisamchk} does not abort on some errors (like duplicate key) but -instead tries to resolve them by modifying the @file{.MYD} -file. Normally the use of two @code{--quick} options is useful only if -you have too little free disk space to perform a normal repair. In this -case you should at least make a backup before running @code{myisamchk}. - -@menu -* Check:: How to check tables for errors -* Repair:: How to repair tables -* Optimization:: Table optimization -@end menu - -@cindex checking, tables for errors -@cindex tables, error checking -@cindex errors, checking tables for -@node Check, Repair, Crash recovery, Crash recovery -@subsection How to Check Tables for Errors - -To check a MyISAM table, use the following commands: - -@table @code -@item myisamchk tbl_name -This finds 99.99% of all errors. What it can't find is corruption that -involves @strong{ONLY} the data file (which is very unusual). If you want -to check a table, you should normally run @code{myisamchk} without options or -with either the @code{-s} or @code{--silent} option. - -@item myisamchk -m tbl_name -This finds 99.999% of all errors. It checks first all index entries for errors and -then it reads through all rows. It calculates a checksum for all keys in -the rows and verifies that they checksum matches the checksum for the keys -in the index tree. - -@item myisamchk -e tbl_name -This does a complete and thorough check of all data (@code{-e} means -``extended check''). It does a check-read of every key for each row to verify -that they indeed point to the correct row. This may take a LONG time on a -big table with many keys. @code{myisamchk} will normally stop after the first -error it finds. If you want to obtain more information, you can add the -@code{--verbose} (@code{-v}) option. This causes @code{myisamchk} to keep -going, up through a maximum of 20 errors. In normal usage, a simple -@code{myisamchk} (with no arguments other than the table name) is sufficient. - -@item myisamchk -e -i tbl_name -Like the previous command, but the @code{-i} option tells @code{myisamchk} to -print some informational statistics, too. -@end table - -@cindex tables, repairing -@cindex repairing, tables -@node Repair, Optimization, Check, Crash recovery -@subsection How to Repair Tables - -In the following section we only talk about using @code{myisamchk} on -@code{MyISAM} tables (extensions @code{.MYI} and @code{.MYD}). If you -are using @code{ISAM} tables (extensions @code{.ISM} and @code{.ISD}), -you should use @code{isamchk} instead. - -Starting with @strong{MySQL} Version 3.23.14, you can repair MyISAM -tables with the @code{REPAIR TABLE} command. @xref{REPAIR TABLE}. - -The symptoms of a corrupted table include queries that abort unexpectedly -and observable errors such as these: - -@itemize @bullet -@item -@file{tbl_name.frm} is locked against change -@item -Can't find file @file{tbl_name.MYI} (Errcode: ###) -@item -Unexpected end of file -@item -Record file is crashed -@item -Got error ### from table handler - -To get more information about the error you can run @code{perror ###}. Here -is the most common errors that indicates a problem with the table: - -@example -shell> perror 126 127 132 134 135 136 141 144 145 -126 = Index file is crashed / Wrong file format -127 = Record-file is crashed -132 = Old database file -134 = Record was already deleted (or record file crashed) -135 = No more room in record file -136 = No more room in index file -141 = Duplicate unique key or constraint on write or update -144 = Table is crashed and last repair failed -145 = Table was marked as crashed and should be repaired -@end example - -Note that error 135, no more room in record file, is not an error that -can be fixed by a simple repair. In this case you have to do: - -@example -ALTER TABLE table MAX_ROWS=xxx AVG_ROW_LENGTH=yyy; -@end example - -@end itemize - -In the other cases, you must repair your tables. @code{myisamchk} -can usually detect and fix most things that go wrong. - -The repair process involves up to four stages, described below. Before you -begin, you should @code{cd} to the database directory and check the -permissions of the table files. Make sure they are readable by the Unix user -that @code{mysqld} runs as (and to you, because you need to access the files -you are checking). If it turns out you need to modify files, they must also -be writable by you. - -If you are using @strong{MySQL} Version 3.23.16 and above, you can (and -should) use the @code{CHECK} and @code{REPAIR} commands to check and repair -@code{MyISAM} tables. @xref{CHECK TABLE}. @xref{REPAIR TABLE}. - -The manual section about table maintenance includes the options to -@code{isamchk}/@code{myisamchk}. @xref{Table maintenance}. - -The following section is for the cases where the above command fails or -if you want to use the extended features that @code{isamchk}/@code{myisamchk} provides. - -If you are going to repair a table from the command line, you must first -take down the @code{mysqld} server. Note that when you do -@code{mysqladmin shutdown} on a remote server, the @code{mysqld} server -will still be alive for a while after @code{mysqladmin} returns, until -all queries are stopped and all keys have been flushed to disk. - -@noindent -@strong{Stage 1: Checking your tables} - -Run @code{myisamchk *.MYI} or @code{myisamchk -e *.MYI} if you have -more time. Use the @code{-s} (silent) option to suppress unnecessary -information. - -If the @code{mysqld} server is done you should use the --update option to tell -@code{myisamchk} to mark the table as 'checked'. - -You have to repair only those tables for which @code{myisamchk} announces an -error. For such tables, proceed to Stage 2. - -If you get weird errors when checking (such as @code{out of -memory} errors), or if @code{myisamchk} crashes, go to Stage 3. - -@noindent -@strong{Stage 2: Easy safe repair} - -NOTE: If you want repairing to go much faster, you should add: @code{-O -sort_buffer=# -O key_buffer=#} (where # is about 1/4 of the available -memory) to all @code{isamchk/myisamchk} commands. - -First, try @code{myisamchk -r -q tbl_name} (@code{-r -q} means ``quick -recovery mode''). This will attempt to repair the index file without -touching the data file. If the data file contains everything that it -should and the delete links point at the correct locations within the -data file, this should work, and the table is fixed. Start repairing the -next table. Otherwise, use the following procedure: - -@enumerate -@item -Make a backup of the data file before continuing. - -@item -Use @code{myisamchk -r tbl_name} (@code{-r} means ``recovery mode''). This will -remove incorrect records and deleted records from the data file and -reconstruct the index file. - -@item -If the preceding step fails, use @code{myisamchk --safe-recover tbl_name}. -Safe recovery mode uses an old recovery method that handles a few cases that -regular recovery mode doesn't (but is slower). -@end enumerate - -If you get weird errors when repairing (such as @code{out of -memory} errors), or if @code{myisamchk} crashes, go to Stage 3. - -@noindent -@strong{Stage 3: Difficult repair} - -You should only reach this stage if the first 16K block in the index file is -destroyed or contains incorrect information, or if the index file is -missing. In this case, it's necessary to create a new index file. Do so as -follows: - -@enumerate -@item -Move the data file to some safe place. - -@item -Use the table description file to create new (empty) data and index files: - -@example -shell> mysql db_name -mysql> SET AUTOCOMMIT=1; -mysql> TRUNCATE TABLE table_name; -mysql> quit -@end example - -If your SQL version doesn't have @code{TRUNCATE TABLE}, use @code{DELETE FROM -table_name} instead. - -@item -Copy the old data file back onto the newly created data file. -(Don't just move the old file back onto the new file; you want to retain -a copy in case something goes wrong.) -@end enumerate - -Go back to Stage 2. @code{myisamchk -r -q} should work now. (This shouldn't -be an endless loop.) - -@noindent -@strong{Stage 4: Very difficult repair} - -You should reach this stage only if the description file has also -crashed. That should never happen, because the description file isn't changed -after the table is created: - -@enumerate -@item -Restore the description file from a backup and go back to Stage 3. You can -also restore the index file and go back to Stage 2. In the latter case, you -should start with @code{myisamchk -r}. - -@item -If you don't have a backup but know exactly how the table was created, create -a copy of the table in another database. Remove the new data file, then move -the description and index files from the other database to your crashed -database. This gives you new description and index files, but leaves -the data file alone. Go back to Stage 2 and attempt to reconstruct -the index file. -@end enumerate - -@cindex tables, optimizing -@cindex optimizing, tables -@node Optimization, , Repair, Crash recovery -@subsection Table Optimization - -To coalesce fragmented records and eliminate wasted space resulting from -deleting or updating records, run @code{myisamchk} in recovery mode: - -@example -shell> myisamchk -r tbl_name -@end example - -You can optimize a table in the same way using the SQL @code{OPTIMIZE TABLE} -statement. @code{OPTIMIZE TABLE} does a repair of the table, a key -analyzes and also sorts the index tree to give faster key lookups. -There is also no possibility of unwanted interaction between a utility -and the server, because the server does all the work when you use -@code{OPTIMIZE TABLE}. @xref{OPTIMIZE TABLE}. - -@code{myisamchk} also has a number of other options you can use to improve -the performance of a table: - -@table @code -@item -S, --sort-index -@item -R index_num, --sort-records=index_num -@item -a, --analyze -@end table - -For a full description of the option. @xref{myisamchk syntax}. - -@cindex files, log -@cindex maintaining, log files -@cindex log files, maintaining -@node Log file maintenance, , Crash recovery, Maintenance -@section Log file Maintenance - -@strong{MySQL} has a lot of log files which make it easy to see what is -going. @xref{Log files}. One must however from time to time clean up -after @code{MysQL} to ensure that the logs don't take up too much disk -space. - -When using @strong{MySQL} with log files, you will, from time to time, -want to remove/backup old log files and tell @strong{MySQL} to start -logging on new files. @xref{Backup}. - -On a Linux (@code{Redhat}) installation, you can use the -@code{mysql-log-rotate} script for this. If you installed @strong{MySQL} -from an RPM distribution, the script should have been installed -automatically. Note that you should be careful with this if you are using -the log for replication! - -On other systems you must install a short script yourself that you -start from @code{cron} to handle log files. - -You can force @strong{MySQL} to start using new log files by using -@code{mysqladmin flush-logs} or by using the SQL command @code{FLUSH LOGS}. -If you are using @strong{MySQL} Version 3.21 you must use @code{mysqladmin refresh}. - -The above command does the following: - -@itemize @bullet -@item -If standard logging (@code{--log}) or slow query logging -(@code{--log-slow-queries}) is used, closes and reopens the log file. -(@file{mysql.log} and @file{`hostname`-slow.log} as default). -@item -If update logging (@code{--log-update}) is used, closes the update log and -opens a new log file with a higher sequence number. -@end itemize - -If you are using only an update log, you only have to flush the logs and then -move away the old update log files to a backup. -If you are using the normal logging, you can do something like: - -@example -shell> cd mysql-data-directory -shell> mv mysql.log mysql.old -shell> mysqladmin flush-logs -@end example - -and then take a backup and remove @file{mysql.old}. @cindex functions, new @cindex adding, new functions @@ -36683,7 +38043,6 @@ pre-allocated MYSQL struct. * Link errors:: Problems when linking with the @strong{MySQL} client library * Common errors:: Some common errors when using @strong{MySQL} * Full disk:: How @strong{MySQL} handles a full disk -* Multiple sql commands:: How to run SQL commands from a text file * Temporary files:: Where @strong{MySQL} stores temporary files * Problems with mysql.sock:: How to protect @file{/tmp/mysql.sock} * Changing MySQL user:: How to run @strong{MySQL} as a normal user @@ -37605,7 +38964,7 @@ to be. @cindex full disk @cindex disk full -@node Full disk, Multiple sql commands, Common errors, Problems +@node Full disk, Temporary files, Common errors, Problems @section How MySQL Handles a Full Disk @noindent @@ -37648,35 +39007,8 @@ it will remove the big temporary files and mark the table as crashed (except for @code{ALTER TABLE}, in which the old table will be left unchanged). -@node Multiple sql commands, Temporary files, Full disk, Problems -@section How to Run SQL Commands from a Text File -The @code{mysql} client typically is used interactively, like this: - -@example -shell> mysql database -@end example - -However, it's also possible to put your SQL commands in a file and tell -@code{mysql} to read its input from that file. To do so, create a text -file @file{text_file} that contains the commands you wish to execute. -Then invoke @code{mysql} as shown below: - -@example -shell> mysql database < text_file -@end example - -You can also start your text file with a @code{USE db_name} statement. In -this case, it is unnecessary to specify the database name on the command -line: - -@example -shell> mysql < text_file -@end example - -@xref{Programs}. - -@node Temporary files, Problems with mysql.sock, Multiple sql commands, Problems +@node Temporary files, Problems with mysql.sock, Full disk, Problems @section Where MySQL Stores Temporary Files @strong{MySQL} uses the value of the @code{TMPDIR} environment variable as @@ -38345,14 +39677,12 @@ We plan to fix the above in 4.0. @cindex problems, solving @cindex solving, problems @cindex databases, replicating -@node Common problems, Log files, Problems, Top +@node Common problems, Clients, Problems, Top @chapter Solving Some Common Problems with MySQL @cindex replication @menu * Log Replication:: Database replication with update log -* Backup:: Database backups -* Multiple servers:: Running multiple @strong{MySQL} servers on the same machine @end menu In this chapter, you will find information to solve some of the more common @@ -38362,7 +39692,7 @@ database using the update or binary logs. @cindex database replication @cindex replication, database -@node Log Replication, Backup, Common problems, Common problems +@node Log Replication, , Common problems, Common problems @section Database Replication with Update Log Now that master-slave internal replication is available starting in @@ -38404,491 +39734,15 @@ not return the same value as in the original database: All time functions are safe to use, as the timestamp is sent to the mirror if needed. @code{LAST_INSERT_ID()} is also safe to use. -@cindex databases, backups -@cindex backups -@node Backup, Multiple servers, Log Replication, Common problems -@section Database Backups -Because @strong{MySQL} tables are stored as files, it is easy to do a -backup. To get a consistent backup, do a @code{LOCK TABLES} on the -relevant tables followed by @code{FLUSH TABLES} for the tables. -@xref{LOCK TABLES, , @code{LOCK TABLES}}. -@xref{FLUSH, , @code{FLUSH}}. -You only need a read lock; this allows other threads to continue to -query the tables while you are making a copy of the files in the -database directory. The @code{FLUSH TABLE} is needed to ensure that -the all active index pages is written to disk before you start the backup. - -If you want to make a SQL level backup of a table, you can use -@code{SELECT INTO OUTFILE} or @code{BACKUP TABLE}. @xref{SELECT}. -@xref{BACKUP TABLE}. - -Another way to back up a database is to use the @code{mysqldump} program or -the @code{mysqlhotcopy script}. @xref{mysqldump, , @code{mysqldump}}. -@xref{mysqlhotcopy, , @code{mysqlhotcopy}}. - -@enumerate -@item -Do a full backup of your databases: - -@example -shell> mysqldump --tab=/path/to/some/dir --opt --full - -or - -shell> mysqlhotcopy database /path/to/some/dir -@end example - -You can also simply copy all table files (@file{*.frm}, @file{*.MYD}, and -@file{*.MYI} files) as long as the server isn't updating anything. -The script @code{mysqlhotcopy} does use this method. - -@item -@cindex log files, names -Stop @code{mysqld} if it's running, then start it with the -@code{--log-update[=file_name]} option. @xref{Update log}. The update -log file(s) provide you with the information you need to replicate -changes to the database that are made subsequent to the point at which -you executed @code{mysqldump}. -@end enumerate - -If you have to restore something, try to recover your tables using -@code{REPAIR TABLE} or @code{myisamchk -r} first. That should work in -99.9% of all cases. If @code{myisamchk} fails, try the following -procedure: (This will only work if you have started @strong{MySQL} with -@code{--log-update}. @xref{Update log}.): - -@enumerate -@item -Restore the original @code{mysqldump} backup. -@item -Execute the following command to re-run the updates in the binary log: - -@example -shell> mysqlbinlog hostname-bin.[0-9]* | mysql -@end example - -If you are using the update log you can use: - -@example -shell> ls -1 -t -r hostname.[0-9]* | xargs cat | mysql -@end example -@end enumerate - -@code{ls} is used to get all the update log files in the right order. - -You can also do selective backups with @code{SELECT * INTO OUTFILE 'file_name' -FROM tbl_name} and restore with @code{LOAD DATA INFILE 'file_name' REPLACE -...} To avoid duplicate records, you need a @code{PRIMARY KEY} or a -@code{UNIQUE} key in the table. The @code{REPLACE} keyword causes old records -to be replaced with new ones when a new record duplicates an old record on -a unique key value. - -If you get performance problems in making backups on your system, you can -solve this by setting up replication and do the backups on the slave -instead of on the master. @xref{Replication Intro}. - -If you are using a Veritas file system, you can do: - -@enumerate -@item -Execute in a client (perl ?) @code{FLUSH TABLES WITH READ LOCK} -@item -Fork a shell or execute in another client @code{mount vxfs snapshot}. -@item -Execute in the first client @code{UNLOCK TABLES} -@item -Copy files from snapshot -@item -Unmount snapshot -@end enumerate - -@cindex multiple servers -@cindex servers, multiple -@cindex running, multiple servers -@node Multiple servers, , Backup, Common problems -@section Running Multiple MySQL Servers on the Same Machine - -There are circumstances when you might want to run multiple servers on the same -machine. For example, you might want to test a new @strong{MySQL} release -while leaving your existing production setup undisturbed. Or you might -be an Internet service provider that wants to provide independent -@strong{MySQL} installations for different customers. - -If you want to run multiple servers, the easiest way is to compile the servers -with different TCP/IP ports and socket files so they are not -both listening to the same TCP/IP port or socket file. @xref{mysqld_multi, , -@code{mysqld_multi}}. - -Assume an existing server is configured for the default port number and -socket file. Then configure the new server with a @code{configure} command -something like this: - -@example -shell> ./configure --with-tcp-port=port_number \ - --with-unix-socket-path=file_name \ - --prefix=/usr/local/mysql-3.22.9 -@end example - -Here @code{port_number} and @code{file_name} should be different than the -default port number and socket file pathname, and the @code{--prefix} value -should specify an installation directory different than the one under which -the existing @strong{MySQL} installation is located. - -You can check the socket used by any currently executing @strong{MySQL} server -with this command: - -@example -shell> mysqladmin -h hostname --port=port_number variables -@end example - -Note that if you specify ``@code{localhost}'' as a hostname, @code{mysqladmin} -will default to using Unix sockets instead of TCP/IP. - -If you have a @strong{MySQL} server running on the port you used, you will -get a list of some of the most important configurable variables in -@strong{MySQL}, including the socket name. - -You don't have to recompile a new @strong{MySQL} server just to start with -a different port and socket. You can change the port and socket to be used -by specifying them at run time as options to @code{safe_mysqld}: - -@example -shell> /path/to/safe_mysqld --socket=file_name --port=port_number -@end example - -@code{mysqld_multi} can also take @code{safe_mysqld} (or @code{mysqld}) -as an argument and pass the options from a configuration file to -@code{safe_mysqld} and further to @code{mysqld}. - -If you run the new server on the same database directory as another -server with logging enabled, you should also specify the name of the log -files to @code{safe_mysqld} with @code{--log}, @code{--log-update}, or -@code{--log-slow-queries}. Otherwise, both servers may be trying to -write to the same log file. - -@strong{WARNING}: Normally you should never have two servers that update -data in the same database! If your OS doesn't support fault-free system -locking, this may lead to unpleasant surprises! - -If you want to use another database directory for the second server, you -can use the @code{--datadir=path} option to @code{safe_mysqld}. - -@strong{NOTE} also that starting several @strong{MySQL} servers -(@code{mysqlds}) in different machines and letting them access one data -directory over @code{NFS} is generally a @strong{BAD IDEA}! The problem -is that the @code{NFS} will become the bottleneck with the speed. It is -not meant for such use. And last but not least, you would still have to -come up with a solution how to make sure that two or more @code{mysqlds} -are not interfering with each other. At the moment there is no platform -that would 100% reliable do the file locking (@code{lockd} daemon -usually) in every situation. Yet there would be one more possible risk -with @code{NFS}; it would make the work even more complicated for -@code{lockd} daemon to handle. So make it easy for your self and forget -about the idea. The working solution is to have one computer with an -operating system that efficiently handles threads and have several CPUs -in it. - -When you want to connect to a @strong{MySQL} server that is running with -a different port than the port that is compiled into your client, you -can use one of the following methods: - -@itemize @bullet -@item -Start the client with @code{--host 'hostname' --port=port_number} to connect -with TCP/IP, or @code{[--host localhost] --socket=file_name} to connect via -a Unix socket. - -@item -In your C or Perl programs, you can give the port or socket arguments -when connecting to the @strong{MySQL} server. - -@item -If your are using the Perl @code{DBD::mysql} module you can read the options -from the @strong{MySQL} option files. @xref{Option files}. - -@example -$dsn = "DBI:mysql:test;mysql_read_default_group=client;mysql_read_default_file=/usr/local/mysql/data/my.cnf" -$dbh = DBI->connect($dsn, $user, $password); -@end example - -@item -@tindex MYSQL_UNIX_PORT environment variable -@tindex MYSQL_TCP_PORT environment variable -@tindex environment variable, MYSQL_UNIX_PORT -@tindex environment variable, MYSQL_TCP_PORT -Set the @code{MYSQL_UNIX_PORT} and @code{MYSQL_TCP_PORT} environment variables -to point to the Unix socket and TCP/IP port before you start your clients. -If you normally use a specific socket or port, you should place commands -to set these environment variables in your @file{.login} file. -@xref{Environment variables}. @xref{Programs}. - -@item -@tindex .my.cnf file -Specify the default socket and TCP/IP port in the @file{.my.cnf} file in your -home directory. @xref{Option files}. -@end itemize - -@cindex Log files -@node Log files, Clients, Common problems, Top -@chapter The MySQL log files - -@strong{MySQL} has several different log files that can help you find -out what's going on inside @code{mysqld}: - -@multitable @columnfractions .3 .7 -@item The error log @tab Problems encountering starting, running or stopping @code{mysqld}. -@item The isam log @tab Logs all changes to the ISAM tables. Used only for debugging the isam code. -@item The query log @tab Established connections and executed queries. -@item The update log @tab Deprecated: Stores all statements that changes data -@item The binary log @tab Stores all statements that changes something. Used also for replication -@item The slow log @tab Stores all queries that took more than @code{long_query_time} to execute or didn't use indexes. -@end multitable - -All logs can be found in the @code{mysqld} data directory. You can -force @code{mysqld} to reopen the log files (or in some cases -switch to a new log) by executing @code{FLUSH LOGS}. @xref{FLUSH}. - -@cindex error log -@cindex files, error log -@menu -* Error log:: -* Query log:: -* Update log:: -* Binary log:: -* Slow query log:: -@end menu - -@node Error log, Query log, Log files, Log files -@section The Error Log - -@code{mysqld} writes all errors to the stderr, which the -@code{safe_mysqld} script redirects to a file called -@code{'hostname'.err}. (On Windows, @code{mysqld} writes this directly -to @file{\mysql\data\mysql.err}). - -This contains information indicating when @code{mysqld} was started and -stopped and also any critical errors found when running. If @code{mysqld} -dies unexpectedly and @code{safe_mysqld} needs to restart @code{mysqld}, -@code{safe_mysqld} will write a @code{restarted mysqld} row in this -file. This log also holds a warning if @code{mysqld} notices a table -that needs to be automatically checked or repaired. - -On some operating systems, the error log will contain a stack trace -for where @code{mysqld} died. This can be used to find out where -@code{mysqld} died. @xref{Using stack trace}. - -@cindex query log -@cindex files, query log -@node Query log, Update log, Error log, Log files -@section The Query Log - -If you want to know what happens within @code{mysqld}, you should start -it with @code{--log[=file]}. This will log all connections and queries -to the log file (by default named @file{'hostname'.log}). This log can -be very useful when you suspect an error in a client and want to know -exactly what @code{mysqld} thought the client sent to it. - -By default, the @code{mysql.server} script starts the @strong{MySQL} -server with the @code{-l} option. If you need better performance when -you start using @strong{MySQL} in a production environment, you can -remove the @code{-l} option from @code{mysql.server} or change it to -@code{--log-binary}. - -The entries in this log are written as @code{mysqld} receives the questions. -This may be different than the order in which the statements are executed. -This is in contrast to the update log and the binary log which are written -after the query is executed, but before any locks are released. - -@cindex update log -@cindex files, update log -@node Update log, Binary log, Query log, Log files -@section The Update Log - -@strong{NOTE}: The update log is replaced by the binary -log. @xref{Binary log}. With this you can do anything that you can do -with the update log. - -When started with the @code{--log-update[=file_name]} option, -@code{mysqld} writes a log file containing all SQL commands that update -data. If no filename is given, it defaults to the name of the host -machine. If a filename is given, but it doesn't contain a path, the file -is written in the data directory. If @file{file_name} doesn't have an -extension, @code{mysqld} will create log file names like so: -@file{file_name.###}, where @code{###} is a number that is incremented each -time you execute @code{mysqladmin refresh}, execute @code{mysqladmin -flush-logs}, execute the @code{FLUSH LOGS} statement, or restart the server. - -@strong{NOTE:} For the above scheme to work, you should NOT create -your own files with the same filename as the update log + some extensions -that may be regarded as a number, in the directory used by the update log! - -If you use the @code{--log} or @code{-l} options, @code{mysqld} writes a -general log with a filename of @file{hostname.log}, and restarts and -refreshes do not cause a new log file to be generated (although it is closed -and reopened). In this case you can copy it (on Unix) by doing: - -@example -mv hostname.log hostname-old.log -mysqladmin flush-logs -cp hostname-old.log to-backup-directory -rm hostname-old.log -@end example - -Update logging is smart because it logs only statements that really update -data. So an @code{UPDATE} or a @code{DELETE} with a @code{WHERE} that finds no -rows is not written to the log. It even skips @code{UPDATE} statements that -set a column to the value it already has. - -The update logging is done immediately after a query completes but before -any locks are released or any commit is done. This ensures that the log -will be logged in the execution order. - -If you want to update a database from update log files, you could do the -following (assuming your update logs have names of the form -@file{file_name.###}): - -@example -shell> ls -1 -t -r file_name.[0-9]* | xargs cat | mysql -@end example - -@code{ls} is used to get all the log files in the right order. - -This can be useful if you have to revert to backup files after a crash -and you want to redo the updates that occurred between the time of the backup -and the crash. - -@cindex binary log -@cindex files, binary log -@node Binary log, Slow query log, Update log, Log files -@section The Binary Log - -In the future the binary log will replace the update log, so we -recommend you to switch to this log format as soon as possible! - -The binary log contains all information that is available in the update -log in a more efficient format. It also contains information about how long -every query that updated the database took. - -The binary log is also used when you are replicating a slave from a master. -@xref{Replication}. - -When started with the @code{--log-bin[=file_name]} option, @code{mysqld} -writes a log file containing all SQL commands that update data. If no -file name is given, it defaults to the name of the host machine followed -by @code{-bin}. If file name is given, but it doesn't contain a path, the -file is written in the data directory. - -You can use the following options to @code{mysqld} to affect what is logged -to the binary log: - -@multitable @columnfractions .4 .6 -@item @code{binlog-do-db=database_name} @tab -Tells the master it should log updates for the specified database, and -exclude all others not explicitly mentioned. -(Example: @code{binlog-do-db=some_database}) - -@item @code{binlog-ignore-db=database_name} @tab -Tells the master that updates to the given database should not be logged -to the binary log (Example: @code{binlog-ignore-db=some_database}) -@end multitable - -To the binary log filename @code{mysqld} will append an extension that is a -number that is incremented each time you execute @code{mysqladmin -refresh}, execute @code{mysqladmin flush-logs}, execute the @code{FLUSH LOGS} -statement or restart the server. - -To be able to know which different binary log files have been used, -@code{mysqld} will also create a binary log index file that -contains the name of all used binary log files. By default this has the -same name as the binary log file, with the extension @code{'.index'}. -You can change the name of the binary log index file with the -@code{--log-bin-index=[filename]} option. - -If you are using replication, you should not delete old binary log -files until you are sure that no slave will ever need to use them. -One way to do this is to do @code{mysqladmin flush-logs} once a day and then -remove any logs that are more than 3 days old. - -You can examine the binary log file with the @code{mysqlbinlog} command. -For example, you can update a @strong{MySQL} server from the binary log -as follows: - -@example -mysqlbinlog log-file | mysql -h server_name -@end example - -You can also use the @code{mysqlbinlog} program to read the binary log -directly from a remote @strong{MySQL} server! - -@code{mysqlbinlog --help} will give you more information of how to use -this program! - -If you are using @code{BEGIN [WORK]} or @code{SET AUTOCOMMIT=0}, you must -use the @strong{MySQL} binary log for backups instead of the old update log. - -The binary logging is done immediately after a query completes but before -any locks are released or any commit is done. This ensures that the log -will be logged in the execution order. - -All updates (@code{UPDATE}, @code{DELETE} or @code{INSERT}) that change -a transactional table (like BDB tables) are cached until a @code{COMMIT}. -Any updates to a non-transactional table are stored in the binary log at -once. Every thread will, on start, allocate a buffer of -@code{binlog_cache_size} to buffer queries. If a query is bigger than -this, the thread will open a temporary file to handle the bigger cache. -The temporary file will be deleted when the thread ends. - -The @code{max_binlog_cache_size} can be used to restrict the total size used -to cache a multi-transaction query. - -If you are using the update or binary log, concurrent inserts will -not work together with @code{CREATE ... INSERT} and @code{INSERT ... SELECT}. -This is to ensure that you can recreate an exact copy of your tables by -applying the log on a backup. - -@cindex slow query log -@cindex files, slow query log -@node Slow query log, , Binary log, Log files -@section The Slow Query Log - -When started with the @code{--log-slow-queries[=file_name]} option, -@code{mysqld} writes a log file containing all SQL commands that took -more than @code{long_query_time} to execute. The time to get the initial -table locks are not counted as execution time. - -The slow query log is logged after the query is executed and after all -locks has been released. This may be different than the order in which -the statements are executed. - -If no file name is given, it defaults to the name of the host machine -suffixed with @code{-slow.log}. If a filename is given, but doesn't -contain a path, the file is written in the data directory. - -The slow query log can be used to find queries that take a long time to -execute and are thus candidates for optimization. With a large log, that -can become a difficult task. You can pipe the slow query log through the -@code{mysqldumpslow} command to get a summary of the queries which -appear in the log. - -You are using @code{--log-long-format} then also queries that are not -using indexes are printed. @xref{Command-line options}. - -@cindex database replication -@cindex replication, database -@cindex database mirroring -@cindex mirroring, database -You can also use the update logs when you have a mirrored database on -another host and you want to replicate the changes that have been made -to the master database. @xref{Log Replication}. +@node Clients, MySQL internals, Common problems, Top +@chapter MySQL APIs @cindex client tools @cindex APIs @cindex @code{mysqlclient} library @cindex buffer sizes, client @cindex library, @code{mysqlclient} -@node Clients, MySQL internals, Log files, Top -@chapter MySQL APIs @menu * C:: @strong{MySQL} C API @@ -38931,7 +39785,7 @@ Most of the other client APIs (all except Java) use the @code{mysqlclient} library to communicate with the @strong{MySQL} server. This means that, for example, you can take advantage of many of the same environment variables that are used by other client programs, because they are referenced from the -library. See @ref{Programs}, for a list of these variables. +library. See @ref{Client-Side Scripts}, for a list of these variables. The client has a maximum communication buffer size. The size of the buffer that is allocated initially (16K bytes) is automatically increased up to the @@ -51721,9 +52575,6 @@ That's all there is to it! @menu * Installing binary:: * Building clients:: -* Command-line options:: -* Option files:: -* Installing many servers:: * Perl support:: @end menu @@ -51944,7 +52795,7 @@ shell> bin/safe_mysqld --user=mysql & @xref{Post-installation}. -@node Building clients, Command-line options, Installing binary, Placeholder +@node Building clients, Perl support, Installing binary, Placeholder @appendixsec Building Client Programs @cindex client programs, building @@ -51965,516 +52816,10 @@ For clients that use @strong{MySQL} header files, you may need to specify a files. -@node Command-line options, Option files, Building clients, Placeholder -@appendixsec mysqld Command-line Options -@findex command-line options -@cindex options, command-line -@cindex mysqld options -@code{mysqld} accepts the following command-line options: -@table @code -@item --ansi -Use ANSI SQL syntax instead of MySQL syntax. @xref{ANSI mode}. - -@item -b, --basedir=path -Path to installation directory. All paths are usually resolved relative to -this. - -@item --big-tables -Allow big result sets by saving all temporary sets on file. It solves -most 'table full' errors, but also slows down the queries where -in-memory tables would suffice. Since Version 3.23.2, @strong{MySQL} is -able to solve it automatically by using memory for small temporary -tables and switching to disk tables where necessary. - -@item --bind-address=IP -IP address to bind to. - -@item --character-sets-dir=path -Directory where character sets are. @xref{Character sets}. - -@item --chroot=path -Chroot @code{mysqld} daemon during startup. Recommended security measure. It will -somewhat limit @code{LOAD DATA INFILE} and @code{SELECT ... INTO OUTFILE} -though. - -@item --core-file -Write a core file if @code{mysqld} dies. For some systems you must also -specify @code{--core-file-size} to @code{safe_mysqld}. @xref{safe_mysqld, , -@code{safe_mysqld}}. - -@item -h, --datadir=path -Path to the database root. - -@item --default-character-set=charset -Set the default character set. @xref{Character sets}. - -@item --default-table-type=type -Set the default table type for tables. @xref{Table types}. - -@item --debug[...]= -If @strong{MySQL} is configured with @code{--with-debug}, you can use this -option to get a trace file of what @code{mysqld} is doing. -@xref{Making trace files}. - -@item --delay-key-write-for-all-tables -Don't flush key buffers between writes for any @code{MyISAM} table. -@xref{Server parameters}. - -@item --enable-locking -Enable system locking. Note that if you use this option on a system -which a not fully working lockd() (as on Linux) you will easily get -mysqld to deadlock. - -@item -T, --exit-info -This is a bit mask of different flags one can use for debugging the -mysqld server; One should not use this option if one doesn't know -exactly what it does! - -@item --flush -Flush all changes to disk after each SQL command. Normally @strong{MySQL} -only does a write of all changes to disk after each SQL command and lets -the operating system handle the syncing to disk. -@xref{Crashing}. - -@item -?, --help -Display short help and exit. - -@item --init-file=file -Read SQL commands from this file at startup. - -@item -L, --language=... -Client error messages in given language. May be given as a full path. -@xref{Languages}. - -@item -l, --log[=file] -Log connections and queries to file. @xref{Query log}. - -@item --log-isam[=file] -Log all ISAM/MyISAM changes to file (only used when debugging ISAM/MyISAM). - -@item --log-slow-queries[=file] -Log all queries that have taken more than @code{long_query_time} seconds to -execute to file. @xref{Slow query log}. - -@item --log-update[=file] -Log updates to @code{file.#} where @code{#} is a unique number if not given. -@xref{Update log}. - -@item --log-long-format -Log some extra information to update log. If you are using -@code{--log-slow-queries} then queries that are not using indexes are logged -to the slow query log. - -@item --low-priority-updates -Table-modifying operations (@code{INSERT}/@code{DELETE}/@code{UPDATE}) -will have lower priority than selects. It can also be done via -@code{@{INSERT | REPLACE | UPDATE | DELETE@} LOW_PRIORITY ...} to lower -the priority of only one query, or by -@code{SET OPTION SQL_LOW_PRIORITY_UPDATES=1} to change the priority in one -thread. @xref{Table locking}. - -@item --memlock -Lock the @code{mysqld} process in memory. This works only if your -system supports the @code{mlockall()} system call (like Solaris). This -may help if you have a problem where the operating system is causing -@code{mysqld} to swap on disk. - -@item --myisam-recover [=option[,option...]]] where option is one of DEFAULT, BACKUP, FORCE or QUICK. -If this option is used, @code{mysqld} will on open check if the table is -marked as crashed or if if the table wasn't closed properly. (The last -option only works if you are running with @code{--skip-locking}). If this -is the case @code{mysqld} will run check on the table. If the table was corrupted, -@code{mysqld} will attempt to repair it. - -The following options affects how the repair works. - -@multitable @columnfractions .3 .7 -@item DEFAULT @tab The same as not giving any option to - @code{--myisam-recover}. -@item BACKUP @tab If the data table was changed during recover, save a - backup of the @file{table_name.MYD} data file as - @file{table_name-datetime.BAK}. -@item FORCE @tab Run recover even if we will loose more than one row - from the .MYD file. -@item QUICK @tab Don't check the rows in the table if there isn't any - delete blocks. -@end multitable - -Before a table is automatically repaired, @strong{MySQL} will add a note -about this in the error log. If you want to be able to recover from most -things without user intervention, you should use the options -@code{BACKUP,FORCE}. This will force a repair of a table even if some rows -would be deleted, but it will keep the old data file as a backup so that -you can later examine what happened. - -@item --pid-file=path -Path to pid file used by @code{safe_mysqld}. - -@item -P, --port=... -Port number to listen for TCP/IP connections. - -@item -o, --old-protocol -Use the 3.20 protocol for compatibility with some very old clients. -@xref{Upgrading-from-3.20}. - -@item --one-thread -Only use one thread (for debugging under Linux). @xref{Debugging server}. - -@item -O, --set-variable var=option -Give a variable a value. @code{--help} lists variables. You can find a full -description for all variables in the @code{SHOW VARIABLES} section in this -manual. @xref{SHOW VARIABLES}. The tuning server parameters section includes -information of how to optimize these. @xref{Server parameters}. - -@item --safe-mode -Skip some optimize stages. Implies @code{--skip-delay-key-write}. - -@item --safe-show-database -Don't show databases for which the user doesn't have any privileges. - -@item --secure -IP numbers returned by the @code{gethostbyname()} system call are -checked to make sure they resolve back to the original hostname. This -makes it harder for someone on the outside to get access by pretending -to be another host. This option also adds some sanity checks of -hostnames. The option is turned off by default in @strong{MySQL} Version 3.21 -because sometimes it takes a long time to perform backward resolutions. -@strong{MySQL} Version 3.22 caches hostnames (unless @code{--skip-host-cache} -is used) and has this option enabled by default. - -@item --skip-concurrent-insert -Turn off the ability to select and insert at the same time on @code{MyISAM} -tables. (This is only to be used if you think you have found a bug in this -feature). - -@item --skip-delay-key-write -Ignore the @code{delay_key_write} option for all tables. -@xref{Server parameters}. - -@item --skip-grant-tables -This option causes the server not to use the privilege system at all. This -gives everyone @emph{full access} to all databases! (You can tell a running -server to start using the grant tables again by executing @code{mysqladmin -flush-privileges} or @code{mysqladmin reload}.) - -@item --skip-host-cache -Never use host name cache for faster name-ip resolution, but query DNS server -on every connect instead. @xref{DNS}. - -@item --skip-locking -Don't use system locking. To use @code{isamchk} or @code{myisamchk} you must -shut down the server. @xref{Stability}. Note that in @strong{MySQL} Version -3.23 you can use @code{REPAIR} and @code{CHECK} to repair/check @code{MyISAM} -tables. - -@item --skip-name-resolve -Hostnames are not resolved. All @code{Host} column values in the grant tables -must be IP numbers or @code{localhost}. @xref{DNS}. - -@item --skip-networking -Don't listen for TCP/IP connections at all. All interaction with -@code{mysqld} must be made via Unix sockets. This option is highly -recommended for systems where only local requests are allowed. @xref{DNS}. - -@item --skip-new -Don't use new, possible wrong routines. Implies @code{--skip-delay-key-write}. -This will also set default table type to @code{ISAM}. @xref{ISAM}. - -@item --skip-symlink -Don't delete or rename files that a symlinked file in the data directory -points to. - -@item --skip-safemalloc -If @strong{MySQL} is configured with @code{--with-debug=full}, all programs -will check the memory for overruns for every memory allocation and memory -freeing. As this checking is very slow, you can avoid this, when you don't -need memory checking, by using this option. - -@item --skip-show-database -Don't allow 'SHOW DATABASE' commands, unless the user has @strong{process} -privilege. - -@item --skip-stack-trace -Don't write stack traces. This option is useful when you are running -@code{mysqld} under a debugger. @xref{Debugging server}. - -@item --skip-thread-priority -Disable using thread priorities for faster response time. - -@item --socket=path -Socket file to use for local connections instead of default -@code{/tmp/mysql.sock}. - -@item transaction-isolation= @{ READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE @} -Sets the default transaction isolation level. @xref{SET TRANSACTION}. - -@item -t, --tmpdir=path -Path for temporary files. It may be useful if your default @code{/tmp} -directory resides on a partition too small to hold temporary tables. - -@item -u, --user=user_name -Run @code{mysqld} daemon as user @code{user_name}. This option is -@emph{mandatory} when starting @code{mysqld} as root. - -@item -V, --version -Output version information and exit. - -@item -W, --warnings -Print out warnings like @code{Aborted connection...} to the @code{.err} file. -@xref{Communication errors}. -@end table - -@node Option files, Installing many servers, Command-line options, Placeholder -@appendixsec Option Files - -@cindex default options -@cindex option files -@cindex creating, default startup options -@cindex startup options, default - -@strong{MySQL} can, since Version 3.22, read default startup options for the -server and for clients from option files. - -@strong{MySQL} reads default options from the following files on Unix: - -@tindex .my.cnf file -@multitable @columnfractions .3 .7 -@item @strong{Filename} @tab @strong{Purpose} -@item @code{/etc/my.cnf} @tab Global options -@item @code{DATADIR/my.cnf} @tab Server-specific options -@item @code{defaults-extra-file} @tab The file specified with --defaults-extra-file=# -@item @code{~/.my.cnf} @tab User-specific options -@end multitable - -@code{DATADIR} is the @strong{MySQL} data directory (typically -@file{/usr/local/mysql/data} for a binary installation or -@file{/usr/local/var} for a source installation). Note that this is the -directory that was specified at configuration time, not the one specified -with @code{--datadir} when @code{mysqld} starts up! (@code{--datadir} has no -effect on where the server looks for option files, because it looks for them -before it processes any command-line arguments.) - -@strong{MySQL} reads default options from the following files on Windows: - -@multitable @columnfractions .3 .7 -@item @strong{Filename} @tab @strong{Purpose} -@item @code{windows-system-directory\my.ini} @tab Global options -@item @code{C:\my.cnf} @tab Global options -@item @code{C:\mysql\data\my.cnf} @tab Server-specific options -@end multitable - -Note that on Windows, you should specify all paths with @code{/} instead of -@code{\}. If you use @code{\}, you need to specify this twice, as -@code{\} is the escape character in @strong{MySQL}. - -@cindex Environment variables -@strong{MySQL} tries to read option files in the order listed above. If -multiple option files exist, an option specified in a file read later takes -precedence over the same option specified in a file read earlier. Options -specified on the command line take precedence over options specified in any -option file. Some options can be specified using environment variables. -Options specified on the command line or in option files take precedence over -environment variable values. @xref{Environment variables}. - -The following programs support option files: @code{mysql}, -@code{mysqladmin}, @code{mysqld}, @code{mysqldump}, @code{mysqlimport}, -@code{mysql.server}, @code{myisamchk}, and @code{myisampack}. - -You can use option files to specify any long option that a program supports! -Run the program with @code{--help} to get a list of available options. - -An option file can contain lines of the following forms: - -@table @code -@item #comment -Comment lines start with @samp{#} or @samp{;}. Empty lines are ignored. - -@item [group] -@code{group} is the name of the program or group for which you want to set -options. After a group line, any @code{option} or @code{set-variable} lines -apply to the named group until the end of the option file or another group -line is given. - -@item option -This is equivalent to @code{--option} on the command line. - -@item option=value -This is equivalent to @code{--option=value} on the command line. - -@item set-variable = variable=value -This is equivalent to @code{--set-variable variable=value} on the command line. -This syntax must be used to set a @code{mysqld} variable. -@end table - -The @code{client} group allows you to specify options that apply to all -@strong{MySQL} clients (not @code{mysqld}). This is the perfect group to use -to specify the password you use to connect to the server. (But make -sure the option file is readable and writable only by yourself.) - -Note that for options and values, all leading and trailing blanks are -automatically deleted. You may use the escape sequences @samp{\b}, -@samp{\t}, @samp{\n}, @samp{\r}, @samp{\\}, and @samp{\s} in your value string -(@samp{\s} == blank). - -Here is a typical global option file: - -@example -[client] -port=3306 -socket=/tmp/mysql.sock - -[mysqld] -port=3306 -socket=/tmp/mysql.sock -set-variable = key_buffer_size=16M -set-variable = max_allowed_packet=1M - -[mysqldump] -quick -@end example - -Here is typical user option file: - -@example -[client] -# The following password will be sent to all standard MySQL clients -password=my_password - -[mysql] -no-auto-rehash -set-variable = connect_timeout=2 - -[mysqlhotcopy] -interactive-timeout - -@end example - -@tindex .my.cnf file -If you have a source distribution, you will find sample configuration -files named @file{my-xxxx.cnf} in the @file{support-files} directory. -If you have a binary distribution, look in the @file{DIR/support-files} -directory, where @code{DIR} is the pathname to the @strong{MySQL} -installation directory (typically @file{/usr/local/mysql}). Currently -there are sample configuration files for small, medium, large, and very -large systems. You can copy @file{my-xxxx.cnf} to your home directory -(rename the copy to @file{.my.cnf}) to experiment with this. - -All @strong{MySQL} clients that support option files support the -following options: - -@multitable @columnfractions .40 .60 -@item --no-defaults @tab Don't read any option files. -@item --print-defaults @tab Print the program name and all options that it will get. -@item --defaults-file=full-path-to-default-file @tab Only use the given configuration file. -@item --defaults-extra-file=full-path-to-default-file @tab Read this configuration file after the global configuration file but before the user configuration file. -@end multitable - -Note that the above options must be first on the command line to work! -@code{--print-defaults} may however be used directly after the -@code{--defaults-xxx-file} commands. - -Note for developers: Option file handling is implemented simply by -processing all matching options (that is, options in the appropriate group) -before any command-line arguments. This works nicely for programs that use -the last instance of an option that is specified multiple times. If you have -an old program that handles multiply-specified options this way but doesn't -read option files, you need add only two lines to give it that capability. -Check the source code of any of the standard @strong{MySQL} clients to see -how to do this. - -In shell scripts you can use the @file{my_print_defaults} command to parse the -config files: - -@example - -shell> my_print_defaults client mysql ---port=3306 ---socket=/tmp/mysql.sock ---no-auto-rehash -@end example - -The above output contains all options for the groups 'client' and 'mysql'. - - -@node Installing many servers, Perl support, Option files, Placeholder -@appendixsec Installing Many Servers on the Same Machine - -@cindex post-install, many servers -@cindex Installing many servers -@cindex Starting many servers - -In some cases you may want to have many different @code{mysqld} daemons -(servers) running on the same machine. You may for example want to run -a new version of @strong{MySQL} for testing together with an old version -that is in production. Another case is when you want to give different -users access to different @code{mysqld} servers that they manage themselves. - -One way to get a new server running is by starting it with a different -socket and port as follows: - -@tindex MYSQL_UNIX_PORT environment variable -@tindex MYSQL_TCP_PORT environment variable -@tindex Environment variable, MYSQL_UNIX_PORT -@tindex Environment variable, MYSQL_TCP_PORT -@example -shell> MYSQL_UNIX_PORT=/tmp/mysqld-new.sock -shell> MYSQL_TCP_PORT=3307 -shell> export MYSQL_UNIX_PORT MYSQL_TCP_PORT -shell> scripts/mysql_install_db -shell> bin/safe_mysqld & -@end example - -The environment variables appendix includes a list of other environment -variables you can use to affect @code{mysqld}. @xref{Environment variables}. - -The above is the quick and dirty way that one commonly uses for testing. -The nice thing with this is that all connections you do in the above shell -will automatically be directed to the new running server! - -If you need to do this more permanently, you should create an option -file for each server. @xref{Option files}. In your startup script that -is executed at boot time (mysql.server?) you should specify for both -servers: - -@code{safe_mysqld --default-file=path-to-option-file} - -At least the following options should be different per server: - -@table @code -@item port=# -@item socket=path -@item pid-file=path -@end table - -The following options should be different, if they are used: - -@table @code -@item log=path -@item log-bin=path -@item log-update=path -@item log-isam=path -@item bdb-logdir=path -@end table - -If you want more performance, you can also specify the following differently: - -@table @code -@item tmpdir=path -@item bdb-tmpdir=path -@end table - -@xref{Command-line options}. - -If you are installing binary @strong{MySQL} versions (.tar files) and -start them with @code{./bin/safe_mysqld} then in most cases the only -option you need to add/change is the @code{socket} and @code{port} -argument to @code{safe_mysqld}. - - -@node Perl support, , Installing many servers, Placeholder +@node Perl support, , Building clients, Placeholder @appendixsec Perl Installation Comments @cindex Perl, installing From f72d64809983b8ac2ed81cff9e420e4cb932b0b4 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 1 Aug 2001 15:27:22 -0500 Subject: [PATCH 20/51] Fixes to Chapter 4 of DocTOC. --- Docs/manual.texi | 81 ++++++++++++++++++++++++++---------------------- 1 file changed, 44 insertions(+), 37 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index aa3e03c3b2d..e9a48ada515 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -14285,31 +14285,27 @@ FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' @menu * Configuring MySQL:: -* Installing many servers:: * Privilege system:: * User Account Management:: * Disaster Prevention:: * Database Administration:: -* KILL:: * Localization:: * Server-Side Scripts:: * Client-Side Scripts:: -* perror:: -* Batch Commands:: * Log Files:: -* Log file maintenance:: * Replication:: -* Replication HOWTO:: @end menu -@node Configuring MySQL, Installing many servers, MySQL Database Administration, MySQL Database Administration +@node Configuring MySQL, Privilege system, MySQL Database Administration, MySQL Database Administration @section Configuring MySQL @menu * Command-line options:: * Option files:: +* Installing many servers:: +* Multiple servers:: @end menu @node Command-line options, Option files, Configuring MySQL, Configuring MySQL @@ -14575,7 +14571,7 @@ Print out warnings like @code{Aborted connection...} to the @code{.err} file. @end table -@node Option files, , Command-line options, Configuring MySQL +@node Option files, Installing many servers, Command-line options, Configuring MySQL @subsection my.cnf Option Files @cindex default options @@ -14747,8 +14743,8 @@ shell> my_print_defaults client mysql The above output contains all options for the groups 'client' and 'mysql'. -@node Installing many servers, Privilege system, Configuring MySQL, MySQL Database Administration -@appendixsec Installing Many Servers on the Same Machine +@node Installing many servers, Multiple servers, Option files, Configuring MySQL +@subsection Installing Many Servers on the Same Machine @cindex post-install, many servers @cindex Installing many servers @@ -14826,7 +14822,7 @@ argument to @code{safe_mysqld}. * Multiple servers:: @end menu -@node Multiple servers, , Installing many servers, Installing many servers +@node Multiple servers, , Installing many servers, Configuring MySQL @subsection Running Multiple MySQL Servers on the Same Machine @cindex multiple servers @@ -14954,7 +14950,7 @@ home directory. @xref{Option files}. @end itemize -@node Privilege system, User Account Management, Installing many servers, MySQL Database Administration +@node Privilege system, User Account Management, Configuring MySQL, MySQL Database Administration @section General Security Issues and the MySQL Access Privilege System @cindex system, security @@ -18798,7 +18794,7 @@ If a table has been compressed with @code{myisampack}, @code{myisamchk information and a description of what it means. -@node Database Administration, KILL, Disaster Prevention, MySQL Database Administration +@node Database Administration, Localization, Disaster Prevention, MySQL Database Administration @section Database Administration Language Reference @@ -18806,6 +18802,8 @@ information and a description of what it means. * OPTIMIZE TABLE:: * ANALYZE TABLE:: * FLUSH:: +* KILL:: +* SHOW:: @end menu @node OPTIMIZE TABLE, ANALYZE TABLE, Database Administration, Database Administration @@ -18890,7 +18888,7 @@ If the table hasn't changed since the last @code{ANALYZE TABLE} command, the table will not be analyzed again. -@node FLUSH, , ANALYZE TABLE, Database Administration +@node FLUSH, KILL, ANALYZE TABLE, Database Administration @subsection @code{FLUSH} Syntax @findex FLUSH @@ -18949,8 +18947,8 @@ replication. @xref{Replication SQL}. -@node KILL, Localization, Database Administration, MySQL Database Administration -@section @code{KILL} Syntax +@node KILL, SHOW, FLUSH, Database Administration +@subsection @code{KILL} Syntax @findex KILL @@ -19008,7 +19006,7 @@ write is aborted with an disk full error message. * SHOW:: @end menu -@node SHOW, , KILL, KILL +@node SHOW, , KILL, Database Administration @subsection @code{SHOW} Syntax @c FIX more index hits needed @@ -19959,7 +19957,7 @@ Create Table: CREATE TABLE t ( @ref{SET OPTION, , @code{SET OPTION SQL_QUOTE_SHOW_CREATE}}. -@node Localization, Server-Side Scripts, KILL, MySQL Database Administration +@node Localization, Server-Side Scripts, Database Administration, MySQL Database Administration @section MySQL Localization and International Usage @menu @@ -21217,7 +21215,7 @@ binaries includes: @end multitable -@node Client-Side Scripts, perror, Server-Side Scripts, MySQL Database Administration +@node Client-Side Scripts, Log Files, Server-Side Scripts, MySQL Database Administration @section MySQL Client-Side Scripts and Utilities @menu @@ -21228,6 +21226,8 @@ binaries includes: * mysqlhotcopy:: * mysqlimport:: * mysqlshow:: +* perror:: +* Batch Commands:: @end menu @@ -22205,7 +22205,7 @@ $ mysql -e 'SELECT * FROM imptest' test @end example -@node mysqlshow, , mysqlimport, Client-Side Scripts +@node mysqlshow, perror, mysqlimport, Client-Side Scripts @subsection Showing Databases, Tables, and Columns @cindex databases, displaying @@ -22248,8 +22248,8 @@ adding an extra @code{%} last on the command line (as a separate argument). -@node perror, Batch Commands, Client-Side Scripts, MySQL Database Administration -@section perror, Explaining Error Codes +@node perror, Batch Commands, mysqlshow, Client-Side Scripts +@subsection perror, Explaining Error Codes @cindex error messages, displaying @cindex perror @@ -22272,8 +22272,8 @@ code, or an MyISAM/ISAM table handler error code. The error messages are mostly system dependent. -@node Batch Commands, Log Files, perror, MySQL Database Administration -@section How to Run SQL Commands from a Text File +@node Batch Commands, , perror, Client-Side Scripts +@subsection How to Run SQL Commands from a Text File @c FIX add the 'source' command @@ -22303,7 +22303,7 @@ shell> mysql < text_file @xref{Client-Side Scripts}. -@node Log Files, Log file maintenance, Batch Commands, MySQL Database Administration +@node Log Files, Replication, Client-Side Scripts, MySQL Database Administration @section The MySQL Log Files @cindex Log files @@ -22330,6 +22330,7 @@ switch to a new log) by executing @code{FLUSH LOGS}. @xref{FLUSH}. * Update log:: * Binary log:: * Slow query log:: +* Log file maintenance:: @end menu @@ -22528,7 +22529,7 @@ This is to ensure that you can recreate an exact copy of your tables by applying the log on a backup. -@node Slow query log, , Binary log, Log Files +@node Slow query log, Log file maintenance, Binary log, Log Files @subsection The Slow Query Log @cindex slow query log @@ -22557,8 +22558,8 @@ You are using @code{--log-long-format} then also queries that are not using indexes are printed. @xref{Command-line options}. -@node Log file maintenance, Replication, Log Files, MySQL Database Administration -@section Log File Maintenance +@node Log file maintenance, , Slow query log, Log Files +@subsection Log File Maintenance @cindex files, log @cindex maintaining, log files @@ -22611,7 +22612,7 @@ shell> mysqladmin flush-logs and then take a backup and remove @file{mysql.old}. -@node Replication, Replication HOWTO, Log file maintenance, MySQL Database Administration +@node Replication, , Log Files, MySQL Database Administration @section Replication in MySQL @cindex replication @@ -22622,6 +22623,12 @@ and then take a backup and remove @file{mysql.old}. @menu * Replication Intro:: * Replication Implementation:: +* Replication HOWTO:: +* Replication Features:: +* Replication Options:: +* Replication SQL:: +* Replication FAQ:: +* Replication Problems:: @end menu This chapter describes the various replication features in @strong{MySQL}. @@ -22662,7 +22669,7 @@ the system by doing a backup on a slave instead of doing it on the master. @xref{Backup}. -@node Replication Implementation, , Replication Intro, Replication +@node Replication Implementation, Replication HOWTO, Replication Intro, Replication @subsection Replication Implementation Overview @cindex master-slave setup @@ -22700,8 +22707,8 @@ any given time. The next section explains the master/slave setup process in more detail. -@node Replication HOWTO, , Replication, MySQL Database Administration -@section How To Set Up Replication +@node Replication HOWTO, Replication Features, Replication Implementation, Replication +@subsection How To Set Up Replication Below is a quick description of how to set up complete replication on your current @strong{MySQL} server. It assumes you want to replicate all @@ -22835,7 +22842,7 @@ it is preferred that you use @code{CHANGE MASTER TO} command. * Replication Problems:: @end menu -@node Replication Features, Replication Options, Replication HOWTO, Replication HOWTO +@node Replication Features, Replication Options, Replication HOWTO, Replication @subsection Replication Features and Known Problems @cindex options, replication @@ -22976,7 +22983,7 @@ to get rid of old logs while the slave is running. @end itemize -@node Replication Options, Replication SQL, Replication Features, Replication HOWTO +@node Replication Options, Replication SQL, Replication Features, Replication @subsection Replication Options in my.cnf If you are using replication, we recommend you to use @strong{MySQL} Version @@ -23132,7 +23139,7 @@ the read. @end multitable -@node Replication SQL, Replication FAQ, Replication Options, Replication HOWTO +@node Replication SQL, Replication FAQ, Replication Options, Replication @subsection SQL Commands Related to Replication @cindex SQL commands, replication @@ -23239,7 +23246,7 @@ last log on the list), backup all the logs you are about to delete @end multitable -@node Replication FAQ, Replication Problems, Replication SQL, Replication HOWTO +@node Replication FAQ, Replication Problems, Replication SQL, Replication @subsection Replication FAQ @cindex @code{Binlog_Dump} @@ -23493,7 +23500,7 @@ system into @strong{MySQL}, but until it is ready, you will have to create your own monitoring tools. -@node Replication Problems, , Replication FAQ, Replication HOWTO +@node Replication Problems, , Replication FAQ, Replication @subsection Troubleshooting Replication If you have followed the instructions, and your replication setup is not From ce7470ad349a56350542d5031fddecacb83582ec Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 1 Aug 2001 15:36:47 -0500 Subject: [PATCH 21/51] A few random fixes to manual.texi. Docs/manual.texi: A few random fixes. --- Docs/manual.texi | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index e9a48ada515..bbf0f075612 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -52027,7 +52027,7 @@ as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] @end display -@appendixsubsec Preamble +@appendixsec Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public @@ -52130,7 +52130,7 @@ former contains code derived from the library, whereas the latter must be combined with the library in order to run. @iftex -@appendixsubsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +@appendixsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @end iftex @ifinfo @center GNU LESSER GENERAL PUBLIC LICENSE @@ -52526,7 +52526,7 @@ DAMAGES. @end ifinfo @page -@appendixsubsec How to Apply These Terms to Your New Libraries +@appendixsec How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that @@ -52575,10 +52575,10 @@ Ty Coon, President of Vice That's all there is to it! + @node Placeholder, Function Index, LGPL license, Top @appendix Pieces of the manual in transit - @menu * Installing binary:: * Building clients:: From 48027bd02c3738c14aab0e967695407c24f475ba Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 1 Aug 2001 22:15:15 -0500 Subject: [PATCH 22/51] Aesthetic changes to manual.texi. Docs/manual.texi: Aesthetic changes. --- Docs/manual.texi | 30 ++++++++++++++---------------- 1 file changed, 14 insertions(+), 16 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index bbf0f075612..4972405b68a 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -53,7 +53,7 @@ @end ifset @c We want the contents at the beginning, where it's supposed to be. -@setcontentsaftertitlepage +@setshortcontentsaftertitlepage @c %**end of header @@ -83,15 +83,8 @@ END-INFO-DIR-ENTRY @c printing @headings single -@ifclear nusphere -@everyheading @thispage @| @| @thischapter -@everyfooting @| @| Version: @value{mysql_version} Printed: @today{} -@end ifclear - -@ifset nusphere @oddheading @thischapter @| @| @thispage @evenheading @thispage @| @| MySQL Technical Reference for Version @value{mysql_version} -@end ifset @end iftex @@ -44849,7 +44842,7 @@ helped to make @strong{MySQL} what it is today. @end menu @node Developers, Contributors, Credits, Credits -@appendixsubsec Developers at MySQL AB +@appendixsec Developers at MySQL AB These are the developers that are or have been employed by @strong{MySQL AB} to work on @strong{MySQL}, roughly in the order they started to work with us. @@ -45039,7 +45032,7 @@ Allan Larsson (The BOSS for TCX DataKonsult AB). @cindex contributors, list of @node Contributors, Supporters, Developers, Credits -@appendixsubsec Contributors to MySQL +@appendixsec Contributors to MySQL Contributors to the @strong{MySQL} distribution are listed here, in somewhat random order: @@ -45271,7 +45264,7 @@ ODBC and VisualC++ interface questions. @cindex contributing companies, list of @node Supporters, , Contributors, Credits -@appendixsubsec Supporters to MySQL +@appendixsec Supporters to MySQL The following companies has helped us finance development of @strong{MySQL} by either paying us for developing a new feature, @@ -51616,9 +51609,11 @@ All new development is concentrated to @strong{MySQL}. @node GPL license, LGPL license, Unireg, Top @appendix GNU GENERAL PUBLIC LICENSE -@center Version 2, June 1991 -@c This file is intended to be included in another file. +@cindex GPL, General Public License +@cindex GPL, GNU General Public License + +@center Version 2, June 1991 @display Copyright @copyright{} 1989, 1991 Free Software Foundation, Inc. @@ -51628,7 +51623,7 @@ Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. @end display -@unnumberedsec Preamble +@appendixsec Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public @@ -51679,9 +51674,10 @@ patent must be licensed for everyone's free use or not licensed at all. modification follow. @iftex -@unnumberedsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION +@appendixsec TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @end iftex @ifinfo +@center GNU GENERAL PUBLIC LICENSE @center TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION @end ifinfo @@ -51941,7 +51937,7 @@ POSSIBILITY OF SUCH DAMAGES. @end ifinfo @page -@unnumberedsec Appendix: How to Apply These Terms to Your New Programs +@appendixsec How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it @@ -52011,8 +52007,10 @@ Public License instead of this License. @node LGPL license, Placeholder, GPL license, Top @appendix GNU LESSER GENERAL PUBLIC LICENSE + @cindex LGPL, Lesser General Public License @cindex LGPL, GNU Library General Public License + @center Version 2.1, February 1999 @display From 7589011c8f5793719a852771bda45ed83120926a Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 2 Aug 2001 00:21:19 -0500 Subject: [PATCH 23/51] Fixed some ugly things in manual.texi. Docs/manual.texi: Fixed some ugly things. --- Docs/manual.texi | 105 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 71 insertions(+), 34 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 4972405b68a..824aff08f7e 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -7132,17 +7132,17 @@ If you want to use the @code{MySQL-Max} RPM, you must first install the standard @code{MySQL} RPM. @item -If you want to configure @code{mysqld} with some extra feature that are NOT in -the standard binary distributions. Here is a list of the most common -extra options that you may want to use: +If you want to configure @code{mysqld} with some extra features that are +NOT in the standard binary distributions. Here is a list of the most +common extra options that you may want to use: -@itemize @bullet -@item --with-berkeley-db -@item --with-innodb -@item --with-raid -@item --with-libwrap -@item --with-named-z-lib (This is done for some of the binaries) -@item --with-debug[=full] +@itemize +@item @code{--with-berkeley-db} +@item @code{--with-innodb} +@item @code{--with-raid} +@item @code{--with-libwrap} +@item @code{--with-named-z-lib (This is done for some of the binaries)} +@item @code{--with-debug[=full]} @end itemize @item @@ -21722,27 +21722,64 @@ by executing @code{mysqladmin --help}. The current @code{mysqladmin} supports the following commands: -@multitable @columnfractions .3 .7 -@item create databasename @tab Create a new database. -@item drop databasename @tab Delete a database and all its tables. -@item extended-status @tab Gives an extended status message from the server. -@item flush-hosts @tab Flush all cached hosts. -@item flush-logs @tab Flush all logs. -@item flush-tables @tab Flush all tables. -@item flush-privileges @tab Reload grant tables (same as reload). -@item kill id,id,... @tab Kill mysql threads. -@item password @tab New-password. Change old password to new-password. -@item ping @tab Check if @code{mysqld} is alive. -@item processlist @tab Show list of active threads in server. -@item reload @tab Reload grant tables. -@item refresh @tab Flush all tables and close and open logfiles. -@item shutdown @tab Take server down. -@item slave-start @tab Start slave replication thread. -@item slave-stop @tab Stop slave replication thread. -@item status @tab Gives a short status message from the server. -@item variables @tab Prints variables available. -@item version @tab Get version info from server. -@end multitable +@table @code +@item create databasename +Create a new database. + +@item drop databasename +Delete a database and all its tables. + +@item extended-status +Gives an extended status message from the server. + +@item flush-hosts +Flush all cached hosts. + +@item flush-logs +Flush all logs. + +@item flush-tables +Flush all tables. + +@item flush-privileges +Reload grant tables (same as reload). + +@item kill id,id,... +Kill mysql threads. + +@item password +Set a new password. Change old password to new-password. + +@item ping +Check if mysqld is alive. + +@item processlist +Show list of active threads in server. + +@item reload +Reload grant tables. + +@item refresh +Flush all tables and close and open logfiles. + +@item shutdown +Take server down. + +@item slave-start +Start slave replication thread. + +@item slave-stop +Stop slave replication thread. + +@item status +Gives a short status message from the server. + +@item variables +Prints variables available. + +@item version +Get version info from server. +@end table All commands can be shortened to their unique prefix. For example: @@ -23126,7 +23163,7 @@ Updates to a database with a different name than the original (Example: Tells the slave server not to start the slave on the startup. The user can start it later with @code{SLAVE START}. -@item @code{slave_read_timeout=#} +@item @code{slave_read_timeout=#} @tab Number of seconds to wait for more data from the master before aborting the read. @end multitable @@ -23527,7 +23564,7 @@ it is a bug, read below on how to report it. If a query on that succeeded on the master refuses to run on the slave, and a full database resync ( the proper thing to do ) does not seem feasible, try the following: -@itemize bullet +@itemize @minus @item First see if there is some stray record in the way. Understand how it got there, then delete it and run @code{SLAVE START} @@ -23592,7 +23629,7 @@ a log of all updates on the slave. Save all evidence before resetting the replication. If we have no or only sketchy information, it would take us a while to track down the problem. The evidence you should collect is: -@itemize @bullet +@itemize @minus @item All binary logs on the master @item From a636f4cb8afc37dde23d76f0ff4dcbb532f0735b Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 2 Aug 2001 02:56:09 -0500 Subject: [PATCH 24/51] the back side of the short contents page should be blank... --- Docs/manual.texi | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 824aff08f7e..b27f353df2b 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -53,7 +53,7 @@ @end ifset @c We want the contents at the beginning, where it's supposed to be. -@setshortcontentsaftertitlepage +@c @setshortcontentsaftertitlepage @c %**end of header @@ -75,6 +75,11 @@ END-INFO-DIR-ENTRY @page @end titlepage +@c Short contents, blank page, long contents. +@shortcontents +@page +@contents + @c This should be added. The HTML conversion also needs a MySQL version @c number somewhere. From 03c23b5126f75986d1d5cc7aa16857d84a579919 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 2 Aug 2001 03:29:27 -0500 Subject: [PATCH 25/51] try this again.. --- Docs/manual.texi | 1 + 1 file changed, 1 insertion(+) diff --git a/Docs/manual.texi b/Docs/manual.texi index b27f353df2b..941b5a22f70 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -78,6 +78,7 @@ END-INFO-DIR-ENTRY @c Short contents, blank page, long contents. @shortcontents @page +@page @contents @c This should be added. The HTML conversion also needs a MySQL version From aee57a52b8af28b45ce0962cf4976187d950795c Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 3 Aug 2001 02:10:36 +0800 Subject: [PATCH 26/51] Hong Kong mirrors information updated BitKeeper/etc/logging_ok: Logging to logging@openlogging.org accepted --- BitKeeper/etc/logging_ok | 1 + Docs/manual.texi | 13 +++++++------ 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/BitKeeper/etc/logging_ok b/BitKeeper/etc/logging_ok index 70b86544398..fbf9c3702a3 100644 --- a/BitKeeper/etc/logging_ok +++ b/BitKeeper/etc/logging_ok @@ -13,3 +13,4 @@ tim@threads.polyesthetic.msg tim@white.box jcole@tetra.spaceapes.com davida@isil.mysql.com +tonu@x153.internalnet diff --git a/Docs/manual.texi b/Docs/manual.texi index 941b5a22f70..769b898f8e0 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -6757,14 +6757,15 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @uref{http://www2.linuxforum.net/mirror/mysql/, WWW} @item -@c EMAIL: Vincent_Fong@innovator.com.hk (Vincent Fong) -@image{Flags/china} China [ISL/Hong Kong] @ -@uref{http://mysql.islnet.net, WWW} +@c EMAIL: vfong@hklpg.org (Vincent Fong) +@image{Flags/china} China [HKLPG/Hong Kong] @ +@uref{http://mysql.hklpg.org, WWW} -@item +@c @item +@c Not ok 20010308; Other content! (Tonu) @c EMAIL: xcyber@yahoo.com (xcyber) -@image{Flags/china} China [xcyber.org/Hong Kong] @ -@uref{http://mysql.xcyber.org/, WWW} +@c @image{Flags/china} China [xcyber.org/Hong Kong] @ +@c @uref{http://mysql.xcyber.org/, WWW} @c @item @c Not ok 20010330; Non-existent! (Matt) From 89e1029b2711753ee54aa6893b867e46380bd231 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 2 Aug 2001 14:28:39 -0500 Subject: [PATCH 27/51] DocTOC Chapter 5 Complete! --- Docs/manual.texi | 5857 ++++++++++++++++++++++++---------------------- 1 file changed, 3001 insertions(+), 2856 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 941b5a22f70..f82d8d6baf6 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -113,11 +113,10 @@ distribution for that version. * Installing:: Installing @strong{MySQL} * Tutorial:: @strong{MySQL} Tutorial * MySQL Database Administration:: +* MySQL Optimization:: * Reference:: @strong{MySQL} language reference * Table types:: @strong{MySQL} table types * Fulltext Search:: Fulltext Search -* Performance:: Getting maximum performance from @strong{MySQL} -* MySQL Benchmarks:: The @strong{MySQL} benchmark suite * Maintenance:: Maintaining a @strong{MySQL} installation * Adding functions:: Adding new functions to @strong{MySQL} * Adding procedures:: Adding new procedures to @strong{MySQL} @@ -320,7 +319,8 @@ us. you are looking for, you should give it a try. @strong{MySQL} also has a very practical set of features developed in very close cooperation with our users. You can find a performance comparison of @strong{MySQL} -to some other database managers on our benchmark page. @xref{Benchmarks}. +to some other database managers on our benchmark page. +@xref{MySQL Benchmarks}. @strong{MySQL} was originally developed to handle very large databases much faster than existing solutions and has been successfully used in @@ -4488,7 +4488,7 @@ For a list of all supported limits, functions, and types, see the @item Performance For a true comparison of speed, consult the growing @strong{MySQL} benchmark -suite. @xref{Benchmarks}. +suite. @xref{MySQL Benchmarks}. Because there is no thread creation overhead, a small parser, few features, and simple security, @code{mSQL} should be quicker at: @@ -4547,7 +4547,7 @@ slower than @strong{MySQL} was seen. This is due to @code{mSQL}'s lack of a join optimizer to order tables in the optimal order. However, if you put the tables in exactly the right order in @code{mSQL}2 and the @code{WHERE} is simple and uses index columns, the join will be relatively fast! -@xref{Benchmarks}. +@xref{MySQL Benchmarks}. @item @code{ORDER BY} and @code{GROUP BY}. @item @@ -7249,11 +7249,11 @@ hundreds of megabytes of data. @item The @strong{MySQL} benchmark suite This runs a range of common queries. It is also a test to see whether the latest batch of optimizations actually made the code faster. -@xref{Benchmarks}. +@xref{MySQL Benchmarks}. @item The @code{crash-me} test This tries to determine what features the database supports and what its -capabilities and limitations are. @xref{Benchmarks}. +capabilities and limitations are. @xref{MySQL Benchmarks}. @end table Another test is that we use the newest @strong{MySQL} version in our internal @@ -14279,7 +14279,7 @@ FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' @end example -@node MySQL Database Administration, Reference, Tutorial, Top +@node MySQL Database Administration, MySQL Optimization, Tutorial, Top @chapter MySQL Database Administration @menu @@ -19850,7 +19850,7 @@ be run at the same time. @item @code{thread_stack} The stack size for each thread. Many of the limits detected by the @code{crash-me} test are dependent on this value. The default is -large enough for normal operation. @xref{Benchmarks}. +large enough for normal operation. @xref{MySQL Benchmarks}. @item @code{timezone} The timezone for the server. @@ -23663,8 +23663,2988 @@ isolate it into a separate test case first. Then report the problem to @email{bugs@@lists.mysql.com} with as much info as possible. +@node MySQL Optimization, Reference, MySQL Database Administration, Top +@chapter MySQL Optimization -@node Reference, Table types, MySQL Database Administration, Top +@menu +* Optimize Overview:: +* Query Speed:: +* Locking Issues:: +* Optimizing Database Structure:: +* Optimizing the Server:: +* Disk issues:: +@end menu + + +Optimization is a complicated task because it ultimately requires +understanding of the whole system. While it may be possible to do some +local optimizations with small knowledge of your system or application, +the more optimal you want your system to become the more you will have +to know about it. + +This chapter will try to explain and give some examples of different +ways to optimize @strong{MySQL}. Remember, however, that there are +always some (increasingly harder) additional ways to make the system +even faster. + + +@node Optimize Overview, Query Speed, MySQL Optimization, MySQL Optimization +@section Optimization Overview + +The most important part for getting a system fast is of course the basic +design. You also need to know what kinds of things your system will be +doing, and what your bottlenecks are. + +The most common bottlenecks are: +@itemize @bullet +@item Disk seeks. +It takes time for the disk to find a piece of data. With modern disks in +1999, the mean time for this is usually lower than 10ms, so we can in +theory do about 1000 seeks a second. This time improves slowly with new +disks and is very hard to optimize for a single table. The way to +optimize this is to spread the data on more than one disk. + +@item Disk reading/writing. +When the disk is at the correct position we need to read the data. With +modern disks in 1999, one disk delivers something like 10-20Mb/s. This +is easier to optimize than seeks because you can read in parallel from +multiple disks. + +@item CPU cycles. +When we have the data in main memory (or if it already were +there) we need to process it to get to our result. Having small +tables compared to the memory is the most common limiting +factor. But then, with small tables speed is usually not the problem. + +@item Memory bandwidth. +When the CPU needs more data than can fit in the CPU cache the main +memory bandwidth becomes a bottleneck. This is an uncommon bottleneck +for most systems, but one should be aware of it. +@end itemize + + +@menu +* Design Limitations:: +* Portability:: +* Internal use:: +* MySQL Benchmarks:: +* Custom Benchmarks:: +@end menu + +@node Design Limitations, Portability, Optimize Overview, Optimize Overview +@subsection MySQL Design Limitations/Tradeoffs + +@cindex design, limitations +@cindex limitations, design + +Because @strong{MySQL} uses extremely fast table locking (multiple readers / +single writers) the biggest remaining problem is a mix of a steady stream of +inserts and slow selects on the same table. + +We believe that for a huge number of systems the extremely fast +performance in other cases make this choice a win. This case is usually +also possible to solve by having multiple copies of the table, but it +takes more effort and hardware. + +We are also working on some extensions to solve this problem for some +common application niches. + + +@node Portability, Internal use, Design Limitations, Optimize Overview +@subsection Portability + +@cindex portability +@cindex crash-me program +@cindex programs, crash-me + +Because all SQL servers implement different parts of SQL, it takes work to +write portable SQL applications. For very simple selects/inserts it is +very easy, but the more you need the harder it gets. If you want an +application that is fast with many databases it becomes even harder! + +To make a complex application portable you need to choose a number of +SQL servers that it should work with. + +You can use the @strong{MySQL} crash-me program/web-page +@uref{http://www.mysql.com/information/crash-me.php} to find functions, +types, and limits you can use with a selection of database +servers. Crash-me now tests far from everything possible, but it +is still comprehensive with about 450 things tested. + +For example, you shouldn't have column names longer than 18 characters +if you want to be able to use Informix or DB2. + +Both the @strong{MySQL} benchmarks and crash-me programs are very +database-independent. By taking a look at how we have handled this, you +can get a feeling for what you have to do to write your application +database-independent. The benchmarks themselves can be found in the +@file{sql-bench} directory in the @strong{MySQL} source +distribution. They are written in Perl with DBI database interface +(which solves the access part of the problem). + +See @uref{http://www.mysql.com/information/benchmarks.html} for the results +from this benchmark. + +As you can see in these results, all databases have some weak points. That +is, they have different design compromises that lead to different +behavior. + +If you strive for database independence, you need to get a good feeling +for each SQL server's bottlenecks. @strong{MySQL} is VERY fast in +retrieving and updating things, but will have a problem in mixing slow +readers/writers on the same table. Oracle, on the other hand, has a big +problem when you try to access rows that you have recently updated +(until they are flushed to disk). Transaction databases in general are +not very good at generating summary tables from log tables, as in this +case row locking is almost useless. + +To get your application @emph{really} database-independent, you need to define +an easy extendable interface through which you manipulate your data. As +C++ is available on most systems, it makes sense to use a C++ classes +interface to the databases. + +If you use some specific feature for some database (like the +@code{REPLACE} command in @strong{MySQL}), you should code a method for +the other SQL servers to implement the same feature (but slower). With +@strong{MySQL} you can use the @code{/*! */} syntax to add +@strong{MySQL}-specific keywords to a query. The code inside +@code{/**/} will be treated as a comment (ignored) by most other SQL +servers. + +If REAL high performance is more important than exactness, as in some +Web applications, a possibility is to create an application layer that +caches all results to give you even higher performance. By letting +old results 'expire' after a while, you can keep the cache reasonably +fresh. This is quite nice in case of extremely high load, in which case +you can dynamically increase the cache and set the expire timeout higher +until things get back to normal. + +In this case the table creation information should contain information +of the initial size of the cache and how often the table should normally +be refreshed. + +@node Internal use, MySQL Benchmarks, Portability, Optimize Overview +@subsection What Have We Used MySQL For? + +@cindex uses, of MySQL +@cindex customers, of MySQL + +During @strong{MySQL} initial development, the features of @strong{MySQL} +were made to fit our largest customer. They handle data warehousing for a +couple of the biggest retailers in Sweden. + +From all stores, we get weekly summaries of all bonus card transactions, +and we are expected to provide useful information for the store owners +to help them find how their advertisement campaigns are affecting their +customers. + +The data is quite huge (about 7 million summary transactions per month), +and we have data for 4-10 years that we need to present to the users. +We got weekly requests from the customers that they want to get +'instant' access to new reports from this data. + +We solved this by storing all information per month in compressed +'transaction' tables. We have a set of simple macros (script) that +generates summary tables grouped by different criteria (product group, +customer id, store ...) from the transaction tables. The reports are +Web pages that are dynamically generated by a small Perl script that +parses a Web page, executes the SQL statements in it, and inserts the +results. We would have used PHP or mod_perl instead but they were +not available at that time. + +For graphical data we wrote a simple tool in @code{C} that can produce +GIFs based on the result of a SQL query (with some processing of the +result). This is also dynamically executed from the Perl script that +parses the @code{HTML} files. + +In most cases a new report can simply be done by copying an existing +script and modifying the SQL query in it. In some cases, we will need to +add more fields to an existing summary table or generate a new one, but +this is also quite simple, as we keep all transactions tables on disk. +(Currently we have at least 50G of transactions tables and 200G of other +customer data.) + +We also let our customers access the summary tables directly with ODBC +so that the advanced users can themselves experiment with the data. + +We haven't had any problems handling this with quite modest Sun Ultra +SPARCstation (2x200 Mhz). We recently upgraded one of our servers to a 2 +CPU 400 Mhz UltraSPARC, and we are now planning to start handling +transactions on the product level, which would mean a ten-fold increase +of data. We think we can keep up with this by just adding more disk to +our systems. + +We are also experimenting with Intel-Linux to be able to get more CPU +power cheaper. Now that we have the binary portable database format (new +in Version 3.23), we will start to use this for some parts of the application. + +Our initial feelings are that Linux will perform much better on +low-to-medium load and Solaris will perform better when you start to get a +high load because of extreme disk IO, but we don't yet have anything +conclusive about this. After some discussion with a Linux Kernel +developer, this might be a side effect of Linux giving so much resources +to the batch job that the interactive performance gets very low. This +makes the machine feel very slow and unresponsive while big batches are +going. Hopefully this will be better handled in future Linux Kernels. + + +@node MySQL Benchmarks, Custom Benchmarks, Internal use, Optimize Overview +@subsection The MySQL Benchmark Suite + +@cindex benchmark suite +@cindex crash-me program + +This should contain a technical description of the @strong{MySQL} +benchmark suite (and @code{crash-me}), but that description is not +written yet. Currently, you can get a good idea of the benchmark by +looking at the code and results in the @file{sql-bench} directory in any +@strong{MySQL} source distributions. + +This benchmark suite is meant to be a benchmark that will tell any user +what things a given SQL implementation performs well or poorly at. + +Note that this benchmark is single threaded, so it measures the minimum +time for the operations. We plan to in the future add a lot of +multi-threaded tests to the benchmark suite. + +For example, (run on the same NT 4.0 machine): + +@multitable @columnfractions .6 .2 .2 +@strong{Reading 2000000 rows by index} @tab @strong{Seconds} @tab @strong{Seconds} +@item mysql @tab 367 @tab 249 +@item mysql_odbc @tab 464 +@item db2_odbc @tab 1206 +@item informix_odbc @tab 121126 +@item ms-sql_odbc @tab 1634 +@item oracle_odbc @tab 20800 +@item solid_odbc @tab 877 +@item sybase_odbc @tab 17614 +@end multitable + +@multitable @columnfractions .6 .2 .2 +@strong{Inserting (350768) rows} @tab @strong{Seconds} @tab @strong{Seconds} +@item mysql @tab 381 @tab 206 +@item mysql_odbc @tab 619 +@item db2_odbc @tab 3460 +@item informix_odbc @tab 2692 +@item ms-sql_odbc @tab 4012 +@item oracle_odbc @tab 11291 +@item solid_odbc @tab 1801 +@item sybase_odbc @tab 4802 +@end multitable + +In the above test @strong{MySQL} was run with a 8M index cache. + +We have gather some more benchmark results at +@uref{http://www.mysql.com/information/benchmarks.html}. + +Note that Oracle is not included because they asked to be removed. All +Oracle benchmarks have to be passed by Oracle! We believe that makes +Oracle benchmarks @strong{VERY} biased because the above benchmarks are +supposed to show what a standard installation can do for a single +client. + +To run the benchmark suite, you have to download a @strong{MySQL} source +distribution, install the perl DBI driver, the perl DBD driver for the +database you want to test and then do: + +@example +cd sql-bench +perl run-all-tests --server=# +@end example + +where # is one of supported servers. You can get a list of all options +and supported servers by doing @code{run-all-tests --help}. + +@cindex crash-me +@code{crash-me} tries to determine what features a database supports and +what its capabilities and limitations are by actually running +queries. For example, it determines: + +@itemize @bullet +@item +What column types are supported +@item +How many indexes are supported +@item +What functions are supported +@item +How big a query can be +@item +How big a @code{VARCHAR} column can be +@end itemize + +We can find the result from crash-me on a lot of different databases at +@uref{http://www.mysql.com/information/crash-me.php}. + + +@node Custom Benchmarks, , MySQL Benchmarks, Optimize Overview +@subsection Using Your Own Benchmarks + +@cindex benchmarks +@cindex performance, benchmarks + +You should definitely benchmark your application and database to find +out where the bottlenecks are. By fixing it (or by replacing the +bottleneck with a 'dummy module') you can then easily identify the next +bottleneck (and so on). Even if the overall performance for your +application is sufficient, you should at least make a plan for each +bottleneck, and decide how to solve it if someday you really need the +extra performance. + +For an example of portable benchmark programs, look at the @strong{MySQL} +benchmark suite. @xref{MySQL Benchmarks, , @strong{MySQL} Benchmarks}. You +can take any program from this suite and modify it for your needs. By doing +this, you can try different solutions to your problem and test which is really +the fastest solution for you. + +It is very common that some problems only occur when the system is very +heavily loaded. We have had many customers who contact us when they +have a (tested) system in production and have encountered load problems. In +every one of these cases so far, it has been problems with basic design +(table scans are NOT good at high load) or OS/Library issues. Most of +this would be a @strong{LOT} easier to fix if the systems were not +already in production. + +To avoid problems like this, you should put some effort into benchmarking +your whole application under the worst possible load! You can use +Super Smack for this, and it is available at: +@uref{http://www.mysql.com/Downloads/super-smack/super-smack-1.0.tar.gz}. +As the name suggests, it can bring your system down to its knees if you ask it, +so make sure to use it only on your development systems. + + +@node Query Speed, Locking Issues, Optimize Overview, MySQL Optimization +@section Optimizing @code{SELECT}s and Other Queries + +@cindex queries, speed of +@cindex permission checks, effect on speed +@cindex speed, of queries + +First, one thing that affects all queries: The more complex permission +system setup you have, the more overhead you get. + +If you do not have any @code{GRANT} statements done, @strong{MySQL} will +optimize the permission checking somewhat. So if you have a very high +volume it may be worth the time to avoid grants. Otherwise more +permission check results in a larger overhead. + +If your problem is with some explicit @strong{MySQL} function, you can +always time this in the @strong{MySQL} client: + +@example +mysql> select benchmark(1000000,1+1); ++------------------------+ +| benchmark(1000000,1+1) | ++------------------------+ +| 0 | ++------------------------+ +1 row in set (0.32 sec) +@end example + +The above shows that @strong{MySQL} can execute 1,000,000 @code{+} +expressions in 0.32 seconds on a @code{PentiumII 400MHz}. + +All @strong{MySQL} functions should be very optimized, but there may be +some exceptions, and the @code{benchmark(loop_count,expression)} is a +great tool to find out if this is a problem with your query. + +@menu +* EXPLAIN:: +* Estimating performance:: Estimating query performance +* SELECT speed:: Speed of @code{SELECT} queries +* Where optimizations:: How MySQL optimizes @code{WHERE} clauses +* DISTINCT optimization:: How MySQL Optimizes @code{DISTINCT} +* LEFT JOIN optimization:: How MySQL optimizes @code{LEFT JOIN} +* LIMIT optimization:: How MySQL optimizes @code{LIMIT} +* Insert speed:: Speed of @code{INSERT} queries +* Update speed:: Speed of @code{UPDATE} queries +* Delete speed:: Speed of @code{DELETE} queries +* Tips:: +@end menu + + +@node EXPLAIN, Estimating performance, Query Speed, Query Speed +@subsection @code{EXPLAIN} Syntax (Get Information About a @code{SELECT}) + +@findex EXPLAIN +@findex SELECT, optimizing + +@example + EXPLAIN tbl_name +or EXPLAIN SELECT select_options +@end example + +@code{EXPLAIN tbl_name} is a synonym for @code{DESCRIBE tbl_name} or +@code{SHOW COLUMNS FROM tbl_name}. + +When you precede a @code{SELECT} statement with the keyword @code{EXPLAIN}, +@strong{MySQL} explains how it would process the @code{SELECT}, providing +information about how tables are joined and in which order. + +With the help of @code{EXPLAIN}, you can see when you must add indexes +to tables to get a faster @code{SELECT} that uses indexes to find the +records. You can also see if the optimizer joins the tables in an optimal +order. To force the optimizer to use a specific join order for a +@code{SELECT} statement, add a @code{STRAIGHT_JOIN} clause. + +For non-simple joins, @code{EXPLAIN} returns a row of information for each +table used in the @code{SELECT} statement. The tables are listed in the order +they would be read. @strong{MySQL} resolves all joins using a single-sweep +multi-join method. This means that @strong{MySQL} reads a row from the first +table, then finds a matching row in the second table, then in the third table +and so on. When all tables are processed, it outputs the selected columns and +backtracks through the table list until a table is found for which there are +more matching rows. The next row is read from this table and the process +continues with the next table. + +Output from @code{EXPLAIN} includes the following columns: + +@table @code +@item table +The table to which the row of output refers. + +@item type +The join type. Information about the various types is given below. + +@item possible_keys +The @code{possible_keys} column indicates which indexes @strong{MySQL} +could use to find the rows in this table. Note that this column is +totally independent of the order of the tables. That means that some of +the keys in possible_keys may not be usable in practice with the +generated table order. + +If this column is empty, there are no relevant indexes. In this case, +you may be able to improve the performance of your query by examining +the @code{WHERE} clause to see if it refers to some column or columns +that would be suitable for indexing. If so, create an appropriate index +and check the query with @code{EXPLAIN} again. @xref{ALTER TABLE}. + +To see what indexes a table has, use @code{SHOW INDEX FROM tbl_name}. + +@item key +The @code{key} column indicates the key that @strong{MySQL} actually +decided to use. The key is @code{NULL} if no index was chosen. If +@strong{MySQL} chooses the wrong index, you can probably force +@strong{MySQL} to use another index by using @code{myisamchk --analyze}, +@xref{myisamchk syntax}, or by using @code{USE INDEX/IGNORE INDEX}. +@xref{JOIN}. + +@item key_len +The @code{key_len} column indicates the length of the key that +@strong{MySQL} decided to use. The length is @code{NULL} if the +@code{key} is @code{NULL}. Note that this tells us how many parts of a +multi-part key @strong{MySQL} will actually use. + +@item ref +The @code{ref} column shows which columns or constants are used with the +@code{key} to select rows from the table. + +@item rows +The @code{rows} column indicates the number of rows @strong{MySQL} +believes it must examine to execute the query. + +@item Extra +This column contains additional information of how @strong{MySQL} will +resolve the query. Here is an explanation of the different text +strings that can be found in this column: + +@table @code +@item Distinct +@strong{MySQL} will not continue searching for more rows for the current row +combination after it has found the first matching row. + +@item Not exists +@strong{MySQL} was able to do a @code{LEFT JOIN} optimization on the +query and will not examine more rows in this table for the previous row +combination after it finds one row that matches the @code{LEFT JOIN} criteria. + +Here is an example for this: + +@example +SELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL; +@end example + +Assume that @code{t2.id} is defined with @code{NOT NULL}. In this case +@strong{MySQL} will scan @code{t1} and look up the rows in @code{t2} +through @code{t1.id}. If @strong{MySQL} finds a matching row in +@code{t2}, it knows that @code{t2.id} can never be @code{NULL}, and will +not scan through the rest of the rows in @code{t2} that has the same +@code{id}. In other words, for each row in @code{t1}, @strong{MySQL} +only needs to do a single lookup in @code{t2}, independent of how many +matching rows there are in @code{t2}. + +@item @code{range checked for each record (index map: #)} +@strong{MySQL} didn't find a real good index to use. It will, instead, for +each row combination in the preceding tables, do a check on which index to +use (if any), and use this index to retrieve the rows from the table. This +isn't very fast but is faster than having to do a join without +an index. + +@item Using filesort +@strong{MySQL} will need to do an extra pass to find out how to retrieve +the rows in sorted order. The sort is done by going through all rows +according to the @code{join type} and storing the sort key + pointer to +the row for all rows that match the @code{WHERE}. Then the keys are +sorted. Finally the rows are retrieved in sorted order. + +@item Using index +The column information is retrieved from the table using only +information in the index tree without having to do an additional seek to +read the actual row. This can be done when all the used columns for +the table are part of the same index. + +@item Using temporary +To resolve the query @strong{MySQL} will need to create a +temporary table to hold the result. This typically happens if you do an +@code{ORDER BY} on a different column set than you did a @code{GROUP +BY} on. + +@item Where used +A @code{WHERE} clause will be used to restrict which rows will be +matched against the next table or sent to the client. If you don't have +this information and the table is of type @code{ALL} or @code{index}, +you may have something wrong in your query (if you don't intend to +fetch/examine all rows from the table). +@end table + +If you want to get your queries as fast as possible, you should look out for +@code{Using filesort} and @code{Using temporary}. +@end table + +The different join types are listed below, ordered from best to worst type: + +@cindex system table +@cindex tables, system +@table @code +@item system +The table has only one row (= system table). This is a special case of +the @code{const} join type. + +@cindex constant table +@cindex tables, constant +@item const +The table has at most one matching row, which will be read at the start +of the query. Because there is only one row, values from the column in +this row can be regarded as constants by the rest of the +optimizer. @code{const} tables are very fast as they are read only once! + +@item eq_ref +One row will be read from this table for each combination of rows from +the previous tables. This is the best possible join type, other than the +@code{const} types. It is used when all parts of an index are used by +the join and the index is @code{UNIQUE} or a @code{PRIMARY KEY}. + +@item ref +All rows with matching index values will be read from this table for each +combination of rows from the previous tables. @code{ref} is used if the join +uses only a leftmost prefix of the key, or if the key is not @code{UNIQUE} +or a @code{PRIMARY KEY} (in other words, if the join cannot select a single +row based on the key value). If the key that is used matches only a few rows, +this join type is good. + +@item range +Only rows that are in a given range will be retrieved, using an index to +select the rows. The @code{key} column indicates which index is used. +The @code{key_len} contains the longest key part that was used. +The @code{ref} column will be NULL for this type. + +@item index +This is the same as @code{ALL}, except that only the index tree is +scanned. This is usually faster than @code{ALL}, as the index file is usually +smaller than the data file. + +@item ALL +A full table scan will be done for each combination of rows from the +previous tables. This is normally not good if the table is the first +table not marked @code{const}, and usually @strong{very} bad in all other +cases. You normally can avoid @code{ALL} by adding more indexes, so that +the row can be retrieved based on constant values or column values from +earlier tables. +@end table + +You can get a good indication of how good a join is by multiplying all values +in the @code{rows} column of the @code{EXPLAIN} output. This should tell you +roughly how many rows @strong{MySQL} must examine to execute the query. This +number is also used when you restrict queries with the @code{max_join_size} +variable. +@xref{Server parameters}. + +The following example shows how a @code{JOIN} can be optimized progressively +using the information provided by @code{EXPLAIN}. + +Suppose you have the @code{SELECT} statement shown below, that you examine +using @code{EXPLAIN}: + +@example +EXPLAIN SELECT tt.TicketNumber, tt.TimeIn, + tt.ProjectReference, tt.EstimatedShipDate, + tt.ActualShipDate, tt.ClientID, + tt.ServiceCodes, tt.RepetitiveID, + tt.CurrentProcess, tt.CurrentDPPerson, + tt.RecordVolume, tt.DPPrinted, et.COUNTRY, + et_1.COUNTRY, do.CUSTNAME + FROM tt, et, et AS et_1, do + WHERE tt.SubmitTime IS NULL + AND tt.ActualPC = et.EMPLOYID + AND tt.AssignedPC = et_1.EMPLOYID + AND tt.ClientID = do.CUSTNMBR; +@end example + +For this example, assume that: + +@itemize @bullet +@item +The columns being compared have been declared as follows: + +@multitable @columnfractions .1 .2 .7 +@item @strong{Table} @tab @strong{Column} @tab @strong{Column type} +@item @code{tt} @tab @code{ActualPC} @tab @code{CHAR(10)} +@item @code{tt} @tab @code{AssignedPC} @tab @code{CHAR(10)} +@item @code{tt} @tab @code{ClientID} @tab @code{CHAR(10)} +@item @code{et} @tab @code{EMPLOYID} @tab @code{CHAR(15)} +@item @code{do} @tab @code{CUSTNMBR} @tab @code{CHAR(15)} +@end multitable + +@item +The tables have the indexes shown below: + +@multitable @columnfractions .1 .9 +@item @strong{Table} @tab @strong{Index} +@item @code{tt} @tab @code{ActualPC} +@item @code{tt} @tab @code{AssignedPC} +@item @code{tt} @tab @code{ClientID} +@item @code{et} @tab @code{EMPLOYID} (primary key) +@item @code{do} @tab @code{CUSTNMBR} (primary key) +@end multitable + +@item +The @code{tt.ActualPC} values aren't evenly distributed. +@end itemize + +Initially, before any optimizations have been performed, the @code{EXPLAIN} +statement produces the following information: + +@example +table type possible_keys key key_len ref rows Extra +et ALL PRIMARY NULL NULL NULL 74 +do ALL PRIMARY NULL NULL NULL 2135 +et_1 ALL PRIMARY NULL NULL NULL 74 +tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 + range checked for each record (key map: 35) +@end example + +Because @code{type} is @code{ALL} for each table, this output indicates that +@strong{MySQL} is doing a full join for all tables! This will take quite a +long time, as the product of the number of rows in each table must be +examined! For the case at hand, this is @code{74 * 2135 * 74 * 3872 = +45,268,558,720} rows. If the tables were bigger, you can only imagine how +long it would take. + +One problem here is that @strong{MySQL} can't (yet) use indexes on columns +efficiently if they are declared differently. In this context, +@code{VARCHAR} and @code{CHAR} are the same unless they are declared as +different lengths. Because @code{tt.ActualPC} is declared as @code{CHAR(10)} +and @code{et.EMPLOYID} is declared as @code{CHAR(15)}, there is a length +mismatch. + +To fix this disparity between column lengths, use @code{ALTER TABLE} to +lengthen @code{ActualPC} from 10 characters to 15 characters: + +@example +mysql> ALTER TABLE tt MODIFY ActualPC VARCHAR(15); +@end example + +Now @code{tt.ActualPC} and @code{et.EMPLOYID} are both @code{VARCHAR(15)}. +Executing the @code{EXPLAIN} statement again produces this result: + +@example +table type possible_keys key key_len ref rows Extra +tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 where used +do ALL PRIMARY NULL NULL NULL 2135 + range checked for each record (key map: 1) +et_1 ALL PRIMARY NULL NULL NULL 74 + range checked for each record (key map: 1) +et eq_ref PRIMARY PRIMARY 15 tt.ActualPC 1 +@end example + +This is not perfect, but is much better (the product of the @code{rows} +values is now less by a factor of 74). This version is executed in a couple +of seconds. + +A second alteration can be made to eliminate the column length mismatches +for the @code{tt.AssignedPC = et_1.EMPLOYID} and @code{tt.ClientID = +do.CUSTNMBR} comparisons: + +@example +mysql> ALTER TABLE tt MODIFY AssignedPC VARCHAR(15), + MODIFY ClientID VARCHAR(15); +@end example + +Now @code{EXPLAIN} produces the output shown below: + +@example +table type possible_keys key key_len ref rows Extra +et ALL PRIMARY NULL NULL NULL 74 +tt ref AssignedPC,ClientID,ActualPC ActualPC 15 et.EMPLOYID 52 where used +et_1 eq_ref PRIMARY PRIMARY 15 tt.AssignedPC 1 +do eq_ref PRIMARY PRIMARY 15 tt.ClientID 1 +@end example + +This is almost as good as it can get. + +The remaining problem is that, by default, @strong{MySQL} assumes that values +in the @code{tt.ActualPC} column are evenly distributed, and that isn't the +case for the @code{tt} table. Fortunately, it is easy to tell @strong{MySQL} +about this: + +@example +shell> myisamchk --analyze PATH_TO_MYSQL_DATABASE/tt +shell> mysqladmin refresh +@end example + +Now the join is perfect, and @code{EXPLAIN} produces this result: + +@example +table type possible_keys key key_len ref rows Extra +tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 where used +et eq_ref PRIMARY PRIMARY 15 tt.ActualPC 1 +et_1 eq_ref PRIMARY PRIMARY 15 tt.AssignedPC 1 +do eq_ref PRIMARY PRIMARY 15 tt.ClientID 1 +@end example + +Note that the @code{rows} column in the output from @code{EXPLAIN} is an +educated guess from the @strong{MySQL} join optimizer. To optimize a +query, you should check if the numbers are even close to the truth. If not, +you may get better performance by using @code{STRAIGHT_JOIN} in your +@code{SELECT} statement and trying to list the tables in a different order in +the @code{FROM} clause. + + +@node Estimating performance, SELECT speed, EXPLAIN, Query Speed +@subsection Estimating Query Performance + +@cindex estimating, query performance +@cindex queries, estimating performance +@cindex performance, estimating + +In most cases you can estimate the performance by counting disk seeks. +For small tables, you can usually find the row in 1 disk seek (as the +index is probably cached). For bigger tables, you can estimate that +(using B++ tree indexes) you will need: @code{log(row_count) / +log(index_block_length / 3 * 2 / (index_length + data_pointer_length)) + +1} seeks to find a row. + +In @strong{MySQL} an index block is usually 1024 bytes and the data +pointer is usually 4 bytes. A 500,000 row table with an +index length of 3 (medium integer) gives you: +@code{log(500,000)/log(1024/3*2/(3+4)) + 1} = 4 seeks. + +As the above index would require about 500,000 * 7 * 3/2 = 5.2M, +(assuming that the index buffers are filled to 2/3, which is typical) +you will probably have much of the index in memory and you will probably +only need 1-2 calls to read data from the OS to find the row. + +For writes, however, you will need 4 seek requests (as above) to find +where to place the new index and normally 2 seeks to update the index +and write the row. + +Note that the above doesn't mean that your application will slowly +degenerate by N log N! As long as everything is cached by the OS or SQL +server things will only go marginally slower while the table gets +bigger. After the data gets too big to be cached, things will start to +go much slower until your applications is only bound by disk-seeks +(which increase by N log N). To avoid this, increase the index cache as +the data grows. @xref{Server parameters}. + + +@node SELECT speed, Where optimizations, Estimating performance, Query Speed +@subsection Speed of @code{SELECT} Queries + +@findex SELECT speed + +@cindex speed, of queries + +In general, when you want to make a slow @code{SELECT ... WHERE} faster, the +first thing to check is whether or not you can add an index. @xref{MySQL +indexes, , @strong{MySQL} indexes}. All references between different tables +should usually be done with indexes. You can use the @code{EXPLAIN} command +to determine which indexes are used for a @code{SELECT}. +@xref{EXPLAIN, , @code{EXPLAIN}}. + +Some general tips: + +@itemize @bullet +@item +To help @strong{MySQL} optimize queries better, run @code{myisamchk +--analyze} on a table after it has been loaded with relevant data. This +updates a value for each index part that indicates the average number of +rows that have the same value. (For unique indexes, this is always 1, +of course.). @strong{MySQL} will use this to decide which index to +choose when you connect two tables with 'a non-constant expression'. +You can check the result from the @code{analyze} run by doing @code{SHOW +INDEX FROM table_name} and examining the @code{Cardinality} column. + +@item +To sort an index and data according to an index, use @code{myisamchk +--sort-index --sort-records=1} (if you want to sort on index 1). If you +have a unique index from which you want to read all records in order +according to that index, this is a good way to make that faster. Note, +however, that this sorting isn't written optimally and will take a long +time for a large table! +@end itemize + + +@node Where optimizations, DISTINCT optimization, SELECT speed, Query Speed +@subsection How MySQL Optimizes @code{WHERE} Clauses + +@findex WHERE + +@cindex optimizations + +The @code{WHERE} optimizations are put in the @code{SELECT} part here because +they are mostly used with @code{SELECT}, but the same optimizations apply for +@code{WHERE} in @code{DELETE} and @code{UPDATE} statements. + +Also note that this section is incomplete. @strong{MySQL} does many +optimizations, and we have not had time to document them all. + +Some of the optimizations performed by @strong{MySQL} are listed below: + +@itemize @bullet +@item +Removal of unnecessary parentheses: +@example + ((a AND b) AND c OR (((a AND b) AND (c AND d)))) +-> (a AND b AND c) OR (a AND b AND c AND d) +@end example +@item +Constant folding: +@example + (a b>5 AND b=c AND a=5 +@end example +@item +Constant condition removal (needed because of constant folding): +@example + (B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6) +-> B=5 OR B=6 +@end example +@item +Constant expressions used by indexes are evaluated only once. +@item +@code{COUNT(*)} on a single table without a @code{WHERE} is retrieved +directly from the table information. This is also done for any @code{NOT NULL} +expression when used with only one table. +@item +Early detection of invalid constant expressions. @strong{MySQL} quickly +detects that some @code{SELECT} statements are impossible and returns no rows. +@item +@code{HAVING} is merged with @code{WHERE} if you don't use @code{GROUP BY} +or group functions (@code{COUNT()}, @code{MIN()}...). +@item +For each sub-join, a simpler @code{WHERE} is constructed to get a fast +@code{WHERE} evaluation for each sub-join and also to skip records as +soon as possible. +@cindex constant table +@cindex tables, constant +@item +All constant tables are read first, before any other tables in the query. +A constant table is: +@itemize @minus +@item +An empty table or a table with 1 row. +@item +A table that is used with a @code{WHERE} clause on a @code{UNIQUE} +index, or a @code{PRIMARY KEY}, where all index parts are used with constant +expressions and the index parts are defined as @code{NOT NULL}. +@end itemize +All the following tables are used as constant tables: +@example +mysql> SELECT * FROM t WHERE primary_key=1; +mysql> SELECT * FROM t1,t2 + WHERE t1.primary_key=1 AND t2.primary_key=t1.id; +@end example + +@item +The best join combination to join the tables is found by trying all +possibilities. If all columns in @code{ORDER BY} and in @code{GROUP +BY} come from the same table, then this table is preferred first when +joining. +@item +If there is an @code{ORDER BY} clause and a different @code{GROUP BY} +clause, or if the @code{ORDER BY} or @code{GROUP BY} contains columns +from tables other than the first table in the join queue, a temporary +table is created. +@item +If you use @code{SQL_SMALL_RESULT}, @strong{MySQL} will use an in-memory +temporary table. +@item +Each table index is queried, and the best index that spans fewer than 30% of +the rows is used. If no such index can be found, a quick table scan is used. +@item +In some cases, @strong{MySQL} can read rows from the index without even +consulting the data file. If all columns used from the index are numeric, +then only the index tree is used to resolve the query. +@item +Before each record is output, those that do not match the @code{HAVING} clause +are skipped. +@end itemize + +Some examples of queries that are very fast: + +@example +mysql> SELECT COUNT(*) FROM tbl_name; +mysql> SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name; +mysql> SELECT MAX(key_part2) FROM tbl_name + WHERE key_part_1=constant; +mysql> SELECT ... FROM tbl_name + ORDER BY key_part1,key_part2,... LIMIT 10; +mysql> SELECT ... FROM tbl_name + ORDER BY key_part1 DESC,key_part2 DESC,... LIMIT 10; +@end example + +The following queries are resolved using only the index tree (assuming +the indexed columns are numeric): + +@example +mysql> SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val; +mysql> SELECT COUNT(*) FROM tbl_name + WHERE key_part1=val1 AND key_part2=val2; +mysql> SELECT key_part2 FROM tbl_name GROUP BY key_part1; +@end example + +The following queries use indexing to retrieve the rows in sorted +order without a separate sorting pass: + +@example +mysql> SELECT ... FROM tbl_name ORDER BY key_part1,key_part2,... ; +mysql> SELECT ... FROM tbl_name ORDER BY key_part1 DESC,key_part2 DESC,... ; +@end example + +@node DISTINCT optimization, LEFT JOIN optimization, Where optimizations, Query Speed +@subsection How MySQL Optimizes @code{DISTINCT} + +@findex DISTINCT + +@cindex optimizing, DISTINCT + +@code{DISTINCT} is converted to a @code{GROUP BY} on all columns, +@code{DISTINCT} combined with @code{ORDER BY} will in many cases also +need a temporary table. + +When combining @code{LIMIT #} with @code{DISTINCT}, @strong{MySQL} will stop +as soon as it finds @code{#} unique rows. + +If you don't use columns from all used tables, @strong{MySQL} will stop +the scanning of the not used tables as soon as it has found the first match. + +@example +SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a; +@end example + +In the case, assuming t1 is used before t2 (check with @code{EXPLAIN}), then +@strong{MySQL} will stop reading from t2 (for that particular row in t1) +when the first row in t2 is found. + + +@node LEFT JOIN optimization, LIMIT optimization, DISTINCT optimization, Query Speed +@subsection How MySQL Optimizes @code{LEFT JOIN} and @code{RIGHT JOIN} + +@findex LEFT JOIN + +@cindex optimizing, LEFT JOIN + +@code{A LEFT JOIN B} in @strong{MySQL} is implemented as follows: + +@itemize @bullet +@item +The table @code{B} is set to be dependent on table @code{A} and all tables +that @code{A} is dependent on. +@item +The table @code{A} is set to be dependent on all tables (except @code{B}) +that are used in the @code{LEFT JOIN} condition. +@item +All @code{LEFT JOIN} conditions are moved to the @code{WHERE} clause. +@item +All standard join optimizations are done, with the exception that a table is +always read after all tables it is dependent on. If there is a circular +dependence then @strong{MySQL} will issue an error. +@item +All standard @code{WHERE} optimizations are done. +@item +If there is a row in @code{A} that matches the @code{WHERE} clause, but there +wasn't any row in @code{B} that matched the @code{LEFT JOIN} condition, +then an extra @code{B} row is generated with all columns set to @code{NULL}. +@item +If you use @code{LEFT JOIN} to find rows that don't exist in some +table and you have the following test: @code{column_name IS NULL} in the +@code{WHERE} part, where column_name is a column that is declared as +@code{NOT NULL}, then @strong{MySQL} will stop searching after more rows +(for a particular key combination) after it has found one row that +matches the @code{LEFT JOIN} condition. +@end itemize + +@code{RIGHT JOIN} is implemented analogously as @code{LEFT JOIN}. + +The table read order forced by @code{LEFT JOIN} and @code{STRAIGHT JOIN} +will help the join optimizer (which calculates in which order tables +should be joined) to do its work much more quickly, as there are fewer +table permutations to check. + +Note that the above means that if you do a query of type: + +@example +SELECT * FROM a,b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key +@end example + +@strong{MySQL} will do a full scan on @code{b} as the @code{LEFT +JOIN} will force it to be read before @code{d}. + +The fix in this case is to change the query to: + +@example +SELECT * FROM b,a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key +@end example + + +@node LIMIT optimization, Insert speed, LEFT JOIN optimization, Query Speed +@subsection How MySQL Optimizes @code{LIMIT} + +@findex LIMIT + +@cindex optimizing, LIMIT + +In some cases @strong{MySQL} will handle the query differently when you are +using @code{LIMIT #} and not using @code{HAVING}: + +@itemize @bullet +@item +If you are selecting only a few rows with @code{LIMIT}, @strong{MySQL} +will use indexes in some cases when it normally would prefer to do a +full table scan. +@item +If you use @code{LIMIT #} with @code{ORDER BY}, @strong{MySQL} will end the +sorting as soon as it has found the first @code{#} lines instead of sorting +the whole table. +@item +When combining @code{LIMIT #} with @code{DISTINCT}, @strong{MySQL} will stop +as soon as it finds @code{#} unique rows. +@item +In some cases a @code{GROUP BY} can be resolved by reading the key in order +(or do a sort on the key) and then calculate summaries until the +key value changes. In this case @code{LIMIT #} will not calculate any +unnecessary @code{GROUP BY}'s. +@item +As soon as @strong{MySQL} has sent the first @code{#} rows to the client, it +will abort the query. +@item +@code{LIMIT 0} will always quickly return an empty set. This is useful +to check the query and to get the column types of the result columns. +@item +The size of temporary tables uses the @code{LIMIT #} to calculate how much +space is needed to resolve the query. +@end itemize + +@node Insert speed, Update speed, LIMIT optimization, Query Speed +@subsection Speed of @code{INSERT} Queries + +@findex INSERT + +@cindex speed, inserting +@cindex inserting, speed of + +The time to insert a record consists approximately of: + +@itemize @bullet +@item +Connect: (3) +@item +Sending query to server: (2) +@item +Parsing query: (2) +@item +Inserting record: (1 x size of record) +@item +Inserting indexes: (1 x number of indexes) +@item +Close: (1) +@end itemize + +where the numbers are somewhat proportional to the overall time. This +does not take into consideration the initial overhead to open tables +(which is done once for each concurrently running query). + +The size of the table slows down the insertion of indexes by N log N +(B-trees). + +Some ways to speed up inserts: + +@itemize @bullet +@item +If you are inserting many rows from the same client at the same time, use +multiple value lists @code{INSERT} statements. This is much faster (many +times in some cases) than using separate @code{INSERT} statements. +@item +If you are inserting a lot of rows from different clients, you can get +higher speed by using the @code{INSERT DELAYED} statement. @xref{INSERT, +, @code{INSERT}}. +@item +Note that with @code{MyISAM} you can insert rows at the same time +@code{SELECT}s are running if there are no deleted rows in the tables. +@item +When loading a table from a text file, use @code{LOAD DATA INFILE}. This +is usually 20 times faster than using a lot of @code{INSERT} statements. +@xref{LOAD DATA, , @code{LOAD DATA}}. +@item +It is possible with some extra work to make @code{LOAD DATA INFILE} run even +faster when the table has many indexes. Use the following procedure: + +@enumerate +@item +Optionally create the table with @code{CREATE TABLE}. For example, using +@code{mysql} or Perl-DBI. + +@item +Execute a @code{FLUSH TABLES} statement or the shell command @code{mysqladmin +flush-tables}. + +@item +Use @code{myisamchk --keys-used=0 -rq /path/to/db/tbl_name}. This will +remove all usage of all indexes from the table. + +@item +Insert data into the table with @code{LOAD DATA INFILE}. This will not +update any indexes and will therefore be very fast. + +@item +If you are going to only read the table in the future, run @code{myisampack} +on it to make it smaller. @xref{Compressed format}. + +@item +Re-create the indexes with @code{myisamchk -r -q +/path/to/db/tbl_name}. This will create the index tree in memory before +writing it to disk, which is much faster because it avoids lots of disk +seeks. The resulting index tree is also perfectly balanced. + +@item +Execute a @code{FLUSH TABLES} statement or the shell command @code{mysqladmin +flush-tables}. +@end enumerate + +This procedure will be built into @code{LOAD DATA INFILE} in some future +version of @strong{MySQL}. +@item +You can speed up insertions by locking your tables: + +@example +mysql> LOCK TABLES a WRITE; +mysql> INSERT INTO a VALUES (1,23),(2,34),(4,33); +mysql> INSERT INTO a VALUES (8,26),(6,29); +mysql> UNLOCK TABLES; +@end example + +The main speed difference is that the index buffer is flushed to disk only +once, after all @code{INSERT} statements have completed. Normally there would +be as many index buffer flushes as there are different @code{INSERT} +statements. Locking is not needed if you can insert all rows with a single +statement. + +Locking will also lower the total time of multi-connection tests, but the +maximum wait time for some threads will go up (because they wait for +locks). For example: + +@example +thread 1 does 1000 inserts +thread 2, 3, and 4 does 1 insert +thread 5 does 1000 inserts +@end example + +If you don't use locking, 2, 3, and 4 will finish before 1 and 5. If you +use locking, 2, 3, and 4 probably will not finish before 1 or 5, but the +total time should be about 40% faster. + +As @code{INSERT}, @code{UPDATE}, and @code{DELETE} operations are very +fast in @strong{MySQL}, you will obtain better overall performance by +adding locks around everything that does more than about 5 inserts or +updates in a row. If you do very many inserts in a row, you could do a +@code{LOCK TABLES} followed by an @code{UNLOCK TABLES} once in a while +(about each 1000 rows) to allow other threads access to the table. This +would still result in a nice performance gain. + +Of course, @code{LOAD DATA INFILE} is much faster for loading data. +@end itemize + +To get some more speed for both @code{LOAD DATA INFILE} and +@code{INSERT}, enlarge the key buffer. @xref{Server parameters}. + + +@node Update speed, Delete speed, Insert speed, Query Speed +@subsection Speed of @code{UPDATE} Queries + +Update queries are optimized as a @code{SELECT} query with the additional +overhead of a write. The speed of the write is dependent on the size of +the data that is being updated and the number of indexes that are +updated. Indexes that are not changed will not be updated. + +Also, another way to get fast updates is to delay updates and then do +many updates in a row later. Doing many updates in a row is much quicker +than doing one at a time if you lock the table. + +Note that, with dynamic record format, updating a record to +a longer total length may split the record. So if you do this often, +it is very important to @code{OPTIMIZE TABLE} sometimes. +@xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}. + + +@node Delete speed, Tips, Update speed, Query Speed +@subsection Speed of @code{DELETE} Queries + +If you want to delete all rows in the table, you should use +@code{TRUNCATE TABLE table_name}. @xref{TRUNCATE}. + +The time to delete a record is exactly proportional to the number of +indexes. To delete records more quickly, you can increase the size of +the index cache. @xref{Server parameters}. + + +@node Tips, , Delete speed, Query Speed +@subsection Other Optimization Tips + +@cindex optimization, tips +@cindex tips, optimization + +Unsorted tips for faster systems: + +@itemize @bullet +@item +Use persistent connections to the database to avoid the connection +overhead. If you can't use persistent connections and you are doing a +lot of new connections to the database, you may want to change the value +of the @code{thread_cache_size} variable. @xref{Server parameters}. +@item +Always check that all your queries really use the indexes you have created +in the tables. In @strong{MySQL} you can do this with the @code{EXPLAIN} +command. @xref{EXPLAIN, Explain, Explain, manual}. +@item +Try to avoid complex @code{SELECT} queries on tables that are updated a +lot. This is to avoid problems with table locking. +@item +The new @code{MyISAM} tables can insert rows in a table without deleted +rows at the same time another table is reading from it. If this is important +for you, you should consider methods where you don't have to delete rows +or run @code{OPTIMIZE TABLE} after you have deleted a lot of rows. +@item +Use @code{ALTER TABLE ... ORDER BY expr1,expr2...} if you mostly +retrieve rows in expr1,expr2.. order. By using this option after big +changes to the table, you may be able to get higher performance. +@item +In some cases it may make sense to introduce a column that is 'hashed' +based on information from other columns. If this column is short and +reasonably unique it may be much faster than a big index on many +columns. In @strong{MySQL} it's very easy to use this extra column: +@code{SELECT * FROM table_name WHERE hash=MD5(concat(col1,col2)) +AND col_1='constant' AND col_2='constant'} +@item +For tables that change a lot you should try to avoid all @code{VARCHAR} +or @code{BLOB} columns. You will get dynamic row length as soon as you +are using a single @code{VARCHAR} or @code{BLOB} column. @xref{Table +types}. +@item +It's not normally useful to split a table into different tables just +because the rows gets 'big'. To access a row, the biggest performance +hit is the disk seek to find the first byte of the row. After finding +the data most new disks can read the whole row fast enough for most +applications. The only cases where it really matters to split up a table is if +it's a dynamic row size table (see above) that you can change to a fixed +row size, or if you very often need to scan the table and don't need +most of the columns. @xref{Table types}. +@item +If you very often need to calculate things based on information from a +lot of rows (like counts of things), it's probably much better to +introduce a new table and update the counter in real time. An update of +type @code{UPDATE table set count=count+1 where index_column=constant} +is very fast! + +This is really important when you use databases like @strong{MySQL} that +only have table locking (multiple readers / single writers). This will +also give better performance with most databases, as the row locking +manager in this case will have less to do. +@item +If you need to collect statistics from big log tables, use summary tables +instead of scanning the whole table. Maintaining the summaries should be +much faster than trying to do statistics 'live'. It's much faster to +regenerate new summary tables from the logs when things change +(depending on business decisions) than to have to change the running +application! +@item +If possible, one should classify reports as 'live' or 'statistical', +where data needed for statistical reports are only generated based on +summary tables that are generated from the actual data. +@item +Take advantage of the fact that columns have default values. Insert +values explicitly only when the value to be inserted differs from the +default. This reduces the parsing that @strong{MySQL} need to do and +improves the insert speed. +@item +In some cases it's convenient to pack and store data into a blob. In this +case you have to add some extra code in your application to pack/unpack +things in the blob, but this may save a lot of accesses at some stage. +This is practical when you have data that doesn't conform to a static +table structure. +@item +Normally you should try to keep all data non-redundant (what +is called 3rd normal form in database theory), but you should not be +afraid of duplicating things or creating summary tables if you need these +to gain more speed. +@item +Stored procedures or UDF (user-defined functions) may be a good way to +get more performance. In this case you should, however, always have a way +to do this some other (slower) way if you use some database that doesn't +support this. +@item +You can always gain something by caching queries/answers in your +application and trying to do many inserts/updates at the same time. If +your database supports lock tables (like @strong{MySQL} and Oracle), +this should help to ensure that the index cache is only flushed once +after all updates. +@item +Use @code{INSERT /*! DELAYED */} when you do not need to know when your +data is written. This speeds things up because many records can be written +with a single disk write. +@item +Use @code{INSERT /*! LOW_PRIORITY */} when you want your selects to be +more important. +@item +Use @code{SELECT /*! HIGH_PRIORITY */} to get selects that jump the +queue. That is, the select is done even if there is somebody waiting to +do a write. +@item +Use the multi-line @code{INSERT} statement to store many rows with one +SQL command (many SQL servers supports this). +@item +Use @code{LOAD DATA INFILE} to load bigger amounts of data. This is +faster than normal inserts and will be even faster when @code{myisamchk} +is integrated in @code{mysqld}. +@item +Use @code{AUTO_INCREMENT} columns to make unique values. +@item +Use @code{OPTIMIZE TABLE} once in a while to avoid fragmentation when +using dynamic table format. @xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}. + +@item +Use @code{HEAP} tables to get more speed when possible. @xref{Table +types}. +@item +When using a normal Web server setup, images should be stored as +files. That is, store only a file reference in the database. The main +reason for this is that a normal Web server is much better at caching +files than database contents. So it it's much easier to get a fast +system if you are using files. +@item +Use in memory tables for non-critical data that are accessed often (like +information about the last shown banner for users that don't have +cookies). +@item +Columns with identical information in different tables should be +declared identical and have identical names. Before Version 3.23 you +got slow joins otherwise. + +Try to keep the names simple (use @code{name} instead of +@code{customer_name} in the customer table). To make your names portable +to other SQL servers you should keep them shorter than 18 characters. +@item +If you need REALLY high speed, you should take a look at the low-level +interfaces for data storage that the different SQL servers support! For +example, by accessing the @strong{MySQL} @code{MyISAM} directly, you could +get a speed increase of 2-5 times compared to using the SQL interface. +To be able to do this the data must be on the same server as +the application, and usually it should only be accessed by one process +(because external file locking is really slow). One could eliminate the +above problems by introducing low-level @code{MyISAM} commands in the +@strong{MySQL} server (this could be one easy way to get more +performance if needed). By carefully designing the database interface, +it should be quite easy to support this types of optimization. +@item +In many cases it's faster to access data from a database (using a live +connection) than accessing a text file, just because the database is +likely to be more compact than the text file (if you are using numerical +data), and this will involve fewer disk accesses. You will also save +code because you don't have to parse your text files to find line and +column boundaries. +@item +You can also use replication to speed things up. @xref{Replication}. +@item +Declaring a table with @code{DELAY_KEY_WRITE=1} will make the updating of +indexes faster, as these are not logged to disk until the file is closed. +The downside is that you should run @code{myisamchk} on these tables before +you start @code{mysqld} to ensure that they are okay if something killed +@code{mysqld} in the middle. As the key information can always be generated +from the data, you should not lose anything by using @code{DELAY_KEY_WRITE}. +@end itemize + + +@node Locking Issues, Optimizing Database Structure, Query Speed, MySQL Optimization +@section Locking Issues + + +@menu +* Internal locking:: +* Table locking:: +@end menu + +@node Internal locking, Table locking, Locking Issues, Locking Issues +@subsection How MySQL Locks Tables + +@cindex internal locking +@cindex locking, tables +@cindex tables, locking + +You can find a discussion about different locking methods in the appendix. +@xref{Locking methods}. + +All locking in @strong{MySQL} is deadlock-free. This is managed by always +requesting all needed locks at once at the beginning of a query and always +locking the tables in the same order. + +The locking method @strong{MySQL} uses for @code{WRITE} locks works as follows: + +@itemize @bullet +@item +If there are no locks on the table, put a write lock on it. +@item +Otherwise, put the lock request in the write lock queue. +@end itemize + +The locking method @strong{MySQL} uses for @code{READ} locks works as follows: + +@itemize @bullet +@item +If there are no write locks on the table, put a read lock on it. +@item +Otherwise, put the lock request in the read lock queue. +@end itemize + +When a lock is released, the lock is made available to the threads +in the write lock queue, then to the threads in the read lock queue. + +This means that if you have many updates on a table, @code{SELECT} +statements will wait until there are no more updates. + +To work around this for the case where you want to do many @code{INSERT} and +@code{SELECT} operations on a table, you can insert rows in a temporary +table and update the real table with the records from the temporary table +once in a while. + +This can be done with the following code: +@example +mysql> LOCK TABLES real_table WRITE, insert_table WRITE; +mysql> insert into real_table select * from insert_table; +mysql> TRUNCATE TABLE insert_table; +mysql> UNLOCK TABLES; +@end example + +You can use the @code{LOW_PRIORITY} options with @code{INSERT}, +@code{UPDATE} or @code{DELETE} or @code{HIGH_PRIORITY} with +@code{SELECT} if you want to prioritize retrieval in some specific +cases. You can also start @code{mysqld} with @code{--low-priority-updates} +to get the same behaveour. + +Using @code{SQL_BUFFER_RESULT} can also help making table locks shorter. +@xref{SELECT}. + +You could also change the locking code in @file{mysys/thr_lock.c} to use a +single queue. In this case, write locks and read locks would have the same +priority, which might help some applications. + + +@node Table locking, , Internal locking, Locking Issues +@subsection Table Locking Issues + +@cindex problems, table locking + +The table locking code in @strong{MySQL} is deadlock free. + +@strong{MySQL} uses table locking (instead of row locking or column +locking) on all table types, except @code{BDB} tables, to achieve a very +high lock speed. For large tables, table locking is MUCH better than +row locking for most applications, but there are, of course, some +pitfalls. + +For @code{BDB} and @code{InnoDB} tables, @strong{MySQL} only uses table +locking if you explicitely lock the table with @code{LOCK TABLES} or +execute a command that will modify every row in the table, like +@code{ALTER TABLE}. For these table types we recommend you to not use +@code{LOCK TABLES} at all. + +In @strong{MySQL} Version 3.23.7 and above, you can insert rows into +@code{MyISAM} tables at the same time other threads are reading from the +table. Note that currently this only works if there are no holes after +deleted rows in the table at the time the insert is made. When all holes +has been filled with new data, concurrent inserts will automatically be +enabled again. + +Table locking enables many threads to read from a table at the same +time, but if a thread wants to write to a table, it must first get +exclusive access. During the update, all other threads that want to +access this particular table will wait until the update is ready. + +As updates on tables normally are considered to be more important than +@code{SELECT}, all statements that update a table have higher priority +than statements that retrieve information from a table. This should +ensure that updates are not 'starved' because one issues a lot of heavy +queries against a specific table. (You can change this by using +LOW_PRIORITY with the statement that does the update or +@code{HIGH_PRIORITY} with the @code{SELECT} statement.) + +Starting from @strong{MySQL} Version 3.23.7 one can use the +@code{max_write_lock_count} variable to force @strong{MySQL} to +temporary give all @code{SELECT} statements, that wait for a table, a +higher priority after a specific number of inserts on a table. + +Table locking is, however, not very good under the following senario: + +@itemize @bullet +@item +A client issues a @code{SELECT} that takes a long time to run. +@item +Another client then issues an @code{UPDATE} on a used table. This client +will wait until the @code{SELECT} is finished. +@item +Another client issues another @code{SELECT} statement on the same table. As +@code{UPDATE} has higher priority than @code{SELECT}, this @code{SELECT} +will wait for the @code{UPDATE} to finish. It will also wait for the first +@code{SELECT} to finish! +@item +A thread is waiting for something like @code{full disk}, in which case all +threads that wants to access the problem table will also be put in a waiting +state until more disk space is made available. +@end itemize + +Some possible solutions to this problem are: + +@itemize @bullet +@item +Try to get the @code{SELECT} statements to run faster. You may have to create +some summary tables to do this. + +@item +Start @code{mysqld} with @code{--low-priority-updates}. This will give +all statements that update (modify) a table lower priority than a @code{SELECT} +statement. In this case the last @code{SELECT} statement in the previous +scenario would execute before the @code{INSERT} statement. + +@item +You can give a specific @code{INSERT}, @code{UPDATE}, or @code{DELETE} +statement lower priority with the @code{LOW_PRIORITY} attribute. + +@item +Start @code{mysqld} with a low value for @strong{max_write_lock_count} to give +@code{READ} locks after a certain number of @code{WRITE} locks. + +@item +You can specify that all updates from a specific thread should be done with +low priority by using the SQL command: @code{SET SQL_LOW_PRIORITY_UPDATES=1}. +@xref{SET OPTION, , @code{SET OPTION}}. + +@item +You can specify that a specific @code{SELECT} is very important with the +@code{HIGH_PRIORITY} attribute. @xref{SELECT, , @code{SELECT}}. + +@item +If you have problems with @code{INSERT} combined with @code{SELECT}, +switch to use the new @code{MyISAM} tables as these support concurrent +@code{SELECT}s and @code{INSERT}s. + +@item +If you mainly mix @code{INSERT} and @code{SELECT} statements, the +@code{DELAYED} attribute to @code{INSERT} will probably solve your problems. +@xref{INSERT, , @code{INSERT}}. + +@item +If you have problems with @code{SELECT} and @code{DELETE}, the @code{LIMIT} +option to @code{DELETE} may help. @xref{DELETE, , @code{DELETE}}. +@end itemize + + +@node Optimizing Database Structure, Optimizing the Server, Locking Issues, MySQL Optimization +@section Optimizing Database Structure + + +@menu +* Design:: +* Data size:: +* MySQL indexes:: +* Indexes:: +* Multiple-column indexes:: +* Table cache:: +* Creating many tables:: +* Open tables:: +@end menu + +@node Design, Data size, Optimizing Database Structure, Optimizing Database Structure +@subsection Design Choices + +@cindex design, choices +@cindex database design +@cindex storage of data + +@strong{MySQL} keeps row data and index data in separate files. Many (almost +all) other databases mix row and index data in the same file. We believe that +the @strong{MySQL} choice is better for a very wide range of modern systems. + +Another way to store the row data is to keep the information for each +column in a separate area (examples are SDBM and Focus). This will cause a +performance hit for every query that accesses more than one column. Because +this degenerates so quickly when more than one column is accessed, +we believe that this model is not good for general purpose databases. + +The more common case is that the index and data are stored together +(like in Oracle/Sybase et al). In this case you will find the row +information at the leaf page of the index. The good thing with this +layout is that it, in many cases, depending on how well the index is +cached, saves a disk read. The bad things with this layout are: + +@itemize @bullet +@item +Table scanning is much slower because you have to read through the indexes +to get at the data. +@item +You can't use only the index table to retrieve data for a query. +@item +You lose a lot of space, as you must duplicate indexes from the nodes +(as you can't store the row in the nodes). +@item +Deletes will degenerate the table over time (as indexes in nodes are +usually not updated on delete). +@item +It's harder to cache ONLY the index data. +@end itemize + + +@node Data size, MySQL indexes, Design, Optimizing Database Structure +@subsection Get Your Data as Small as Possible + +@cindex data, size +@cindex reducing, data size +@cindex storage space, minimizing +@cindex tables, improving performance +@cindex performance, improving + +One of the most basic optimization is to get your data (and indexes) to +take as little space on the disk (and in memory) as possible. This can +give huge improvements because disk reads are faster and normally less +main memory will be used. Indexing also takes less resources if +done on smaller columns. + +@strong{MySQL} supports a lot of different table types and row formats. +Choosing the right table format may give you a big performance gain. +@xref{Table types}. + +You can get better performance on a table and minimize storage space +using the techniques listed below: + +@itemize @bullet +@item +Use the most efficient (smallest) types possible. @strong{MySQL} has +many specialized types that save disk space and memory. + +@item +Use the smaller integer types if possible to get smaller tables. For +example, @code{MEDIUMINT} is often better than @code{INT}. + +@item +Declare columns to be @code{NOT NULL} if possible. It makes everything +faster and you save one bit per column. Note that if you really need +@code{NULL} in your application you should definitely use it. Just avoid +having it on all columns by default. + +@item +If you don't have any variable-length columns (@code{VARCHAR}, +@code{TEXT}, or @code{BLOB} columns), a fixed-size record format is +used. This is faster but unfortunately may waste some space. +@xref{MyISAM table formats}. + +@item +The primary index of a table should be as short as possible. This makes +identification of one row easy and efficient. + +@item +For each table, you have to decide which storage/index method to +use. @xref{Table types}. + +@item +Only create the indexes that you really need. Indexes are good for +retrieval but bad when you need to store things fast. If you mostly +access a table by searching on a combination of columns, make an index +on them. The first index part should be the most used column. If you are +ALWAYS using many columns, you should use the column with more duplicates +first to get better compression of the index. + +@item +If it's very likely that a column has a unique prefix on the first number +of characters, it's better to only index this prefix. @strong{MySQL} +supports an index on a part of a character column. Shorter indexes are +faster not only because they take less disk space but also because they +will give you more hits in the index cache and thus fewer disk +seeks. @xref{Server parameters}. + +@item +In some circumstances it can be beneficial to split into two a table that is +scanned very often. This is especially true if it is a dynamic +format table and it is possible to use a smaller static format table that +can be used to find the relevant rows when scanning the table. +@end itemize + + +@node MySQL indexes, Indexes, Data size, Optimizing Database Structure +@subsection How MySQL Uses Indexes + +@cindex indexes, use of + +Indexes are used to find rows with a specific value of one column +fast. Without an index @strong{MySQL} has to start with the first record +and then read through the whole table until it finds the relevant +rows. The bigger the table, the more this costs. If the table has an index +for the columns in question, @strong{MySQL} can quickly get a position to +seek to in the middle of the data file without having to look at all the +data. If a table has 1000 rows, this is at least 100 times faster than +reading sequentially. Note that if you need to access almost all 1000 +rows it is faster to read sequentially because we then avoid disk seeks. + +All @strong{MySQL} indexes (@code{PRIMARY}, @code{UNIQUE}, and +@code{INDEX}) are stored in B-trees. Strings are automatically prefix- +and end-space compressed. @xref{CREATE INDEX, , @code{CREATE INDEX}}. + +Indexes are used to: +@itemize @bullet +@item +Quickly find the rows that match a @code{WHERE} clause. + +@item +Retrieve rows from other tables when performing joins. + +@item +Find the @code{MAX()} or @code{MIN()} value for a specific indexed +column. This is optimized by a preprocessor that checks if you are +using @code{WHERE} key_part_# = constant on all key parts < N. In this case +@strong{MySQL} will do a single key lookup and replace the @code{MIN()} +expression with a constant. If all expressions are replaced with +constants, the query will return at once: + +@example +SELECT MIN(key_part2),MAX(key_part2) FROM table_name where key_part1=10 +@end example + +@item +Sort or group a table if the sorting or grouping is done on a leftmost +prefix of a usable key (for example, @code{ORDER BY key_part_1,key_part_2 }). The +key is read in reverse order if all key parts are followed by @code{DESC}. + +The index can also be used even if the @code{ORDER BY} doesn't match the index +exactly, as long as all the unused index parts and all the extra +are @code{ORDER BY} columns are constants in the @code{WHERE} clause. The +following queries will use the index to resolve the @code{ORDER BY} part: + +@example +SELECT * FROM foo ORDER BY key_part1,key_part2,key_part3; +SELECT * FROM foo WHERE column=constant ORDER BY column, key_part1; +SELECT * FROM foo WHERE key_part1=const GROUP BY key_part2; +@end example + +@item +In some cases a query can be optimized to retrieve values without +consulting the data file. If all used columns for some table are numeric +and form a leftmost prefix for some key, the values may be retrieved +from the index tree for greater speed: + +@example +SELECT key_part3 FROM table_name WHERE key_part1=1 +@end example + +@end itemize + +Suppose you issue the following @code{SELECT} statement: + +@example +mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2; +@end example + +If a multiple-column index exists on @code{col1} and @code{col2}, the +appropriate rows can be fetched directly. If separate single-column +indexes exist on @code{col1} and @code{col2}, the optimizer tries to +find the most restrictive index by deciding which index will find fewer +rows and using that index to fetch the rows. + +@cindex indexes, leftmost prefix of +@cindex leftmost prefix of indexes +If the table has a multiple-column index, any leftmost prefix of the +index can be used by the optimizer to find rows. For example, if you +have a three-column index on @code{(col1,col2,col3)}, you have indexed +search capabilities on @code{(col1)}, @code{(col1,col2)}, and +@code{(col1,col2,col3)}. + +@strong{MySQL} can't use a partial index if the columns don't form a +leftmost prefix of the index. Suppose you have the @code{SELECT} +statements shown below: + +@example +mysql> SELECT * FROM tbl_name WHERE col1=val1; +mysql> SELECT * FROM tbl_name WHERE col2=val2; +mysql> SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3; +@end example + +If an index exists on @code{(col1,col2,col3)}, only the first query +shown above uses the index. The second and third queries do involve +indexed columns, but @code{(col2)} and @code{(col2,col3)} are not +leftmost prefixes of @code{(col1,col2,col3)}. + +@findex LIKE, and indexes +@findex LIKE, and wildcards +@cindex indexes, and @code{LIKE} +@cindex wildcards, and @code{LIKE} +@strong{MySQL} also uses indexes for @code{LIKE} comparisons if the argument +to @code{LIKE} is a constant string that doesn't start with a wild-card +character. For example, the following @code{SELECT} statements use indexes: + +@example +mysql> select * from tbl_name where key_col LIKE "Patrick%"; +mysql> select * from tbl_name where key_col LIKE "Pat%_ck%"; +@end example + +In the first statement, only rows with @code{"Patrick" <= key_col < +"Patricl"} are considered. In the second statement, only rows with +@code{"Pat" <= key_col < "Pau"} are considered. + +The following @code{SELECT} statements will not use indexes: +@example +mysql> select * from tbl_name where key_col LIKE "%Patrick%"; +mysql> select * from tbl_name where key_col LIKE other_col; +@end example + +In the first statement, the @code{LIKE} value begins with a wild-card +character. In the second statement, the @code{LIKE} value is not a +constant. + +@findex IS NULL, and indexes +@cindex indexes, and @code{IS NULL} +Searching using @code{column_name IS NULL} will use indexes if column_name +is an index. + +@strong{MySQL} normally uses the index that finds the least number of rows. An +index is used for columns that you compare with the following operators: +@code{=}, @code{>}, @code{>=}, @code{<}, @code{<=}, @code{BETWEEN}, and a +@code{LIKE} with a non-wild-card prefix like @code{'something%'}. + +Any index that doesn't span all @code{AND} levels in the @code{WHERE} clause +is not used to optimize the query. In other words: To be able to use an +index, a prefix of the index must be used in every @code{AND} group. + +The following @code{WHERE} clauses use indexes: +@example +... WHERE index_part1=1 AND index_part2=2 AND other_column=3 +... WHERE index=1 OR A=10 AND index=2 /* index = 1 OR index = 2 */ +... WHERE index_part1='hello' AND index_part_3=5 + /* optimized like "index_part1='hello'" */ +... WHERE index1=1 and index2=2 or index1=3 and index3=3; + /* Can use index on index1 but not on index2 or index 3 */ +@end example + +These @code{WHERE} clauses do @strong{NOT} use indexes: +@example +... WHERE index_part2=1 AND index_part3=2 /* index_part_1 is not used */ +... WHERE index=1 OR A=10 /* Index is not used in both AND parts */ +... WHERE index_part1=1 OR index_part2=10 /* No index spans all rows */ +@end example + +Note that in some cases @strong{MySQL} will not use an index, even if one +would be available. Some of the cases where this happens are: + +@itemize @bullet +@item +If the use of the index would require @strong{MySQL} to access more +than 30 % of the rows in the table. (In this case a table scan is +probably much faster, as this will require us to do much fewer seeks). +Note that if such a query uses @code{LIMIT} to only retrieve +part of the rows, @strong{MySQL} will use an index anyway, as it can +much more quickly find the few rows to return in the result. +@end itemize + + +@menu +* Indexes:: +* Multiple-column indexes:: +* Table cache:: +* Creating many tables:: +* Open tables:: +@end menu + +@node Indexes, Multiple-column indexes, MySQL indexes, Optimizing Database Structure +@subsection Column Indexes + +@cindex indexes, columns +@cindex columns, indexes +@cindex keys + +All @strong{MySQL} column types can be indexed. Use of indexes on the +relevant columns is the best way to improve the performance of @code{SELECT} +operations. + +The maximum number of keys and the maximum index length is defined per +table handler. @xref{Table types}. You can with all table handlers have +at least 16 keys and a total index length of at least 256 bytes. + +For @code{CHAR} and @code{VARCHAR} columns, you can index a prefix of a +column. This is much faster and requires less disk space than indexing the +whole column. The syntax to use in the @code{CREATE TABLE} statement to +index a column prefix looks like this: + +@example +KEY index_name (col_name(length)) +@end example + +The example below creates an index for the first 10 characters of the +@code{name} column: + +@example +mysql> CREATE TABLE test ( + name CHAR(200) NOT NULL, + KEY index_name (name(10))); +@end example + +For @code{BLOB} and @code{TEXT} columns, you must index a prefix of the +column. You cannot index the entire column. + +In @strong{MySQL} Version 3.23.23 or later, you can also create special +@strong{FULLTEXT} indexes. They are used for full-text search. Only the +@code{MyISAM} table type supports @code{FULLTEXT} indexes. They can be +created only from @code{VARCHAR} and @code{TEXT} columns. +Indexing always happens over the entire column and partial indexing is not +supported. See @ref{Fulltext Search} for details. + +@node Multiple-column indexes, Table cache, Indexes, Optimizing Database Structure +@subsection Multiple-Column Indexes + +@cindex multi-column indexes +@cindex indexes, multi-column +@cindex keys, multi-column + +@strong{MySQL} can create indexes on multiple columns. An index may +consist of up to 15 columns. (On @code{CHAR} and @code{VARCHAR} columns you +can also use a prefix of the column as a part of an index). + +A multiple-column index can be considered a sorted array containing values +that are created by concatenating the values of the indexed columns. + +@strong{MySQL} uses multiple-column indexes in such a way that queries are +fast when you specify a known quantity for the first column of the index in a +@code{WHERE} clause, even if you don't specify values for the other columns. + +Suppose a table is created using the following specification: + +@example +mysql> CREATE TABLE test ( + id INT NOT NULL, + last_name CHAR(30) NOT NULL, + first_name CHAR(30) NOT NULL, + PRIMARY KEY (id), + INDEX name (last_name,first_name)); +@end example + +Then the index @code{name} is an index over @code{last_name} and +@code{first_name}. The index will be used for queries that specify +values in a known range for @code{last_name}, or for both @code{last_name} +and @code{first_name}. +Therefore, the @code{name} index will be used in the following queries: + +@example +mysql> SELECT * FROM test WHERE last_name="Widenius"; + +mysql> SELECT * FROM test WHERE last_name="Widenius" + AND first_name="Michael"; + +mysql> SELECT * FROM test WHERE last_name="Widenius" + AND (first_name="Michael" OR first_name="Monty"); + +mysql> SELECT * FROM test WHERE last_name="Widenius" + AND first_name >="M" AND first_name < "N"; +@end example + +However, the @code{name} index will NOT be used in the following queries: + +@example +mysql> SELECT * FROM test WHERE first_name="Michael"; + +mysql> SELECT * FROM test WHERE last_name="Widenius" + OR first_name="Michael"; +@end example + +For more information on the manner in which @strong{MySQL} uses indexes to +improve query performance, see @ref{MySQL indexes, , @strong{MySQL} +indexes}. + + +@node Table cache, Creating many tables, Multiple-column indexes, Optimizing Database Structure +@subsection How MySQL Opens and Closes Tables + +@findex table_cache + +@cindex tables, opening +@cindex tables, closing +@cindex opening, tables +@cindex closing, tables +@cindex table cache + +@code{table_cache}, @code{max_connections}, and @code{max_tmp_tables} +affect the maximum number of files the server keeps open. If you +increase one or both of these values, you may run up against a limit +imposed by your operating system on the per-process number of open file +descriptors. However, you can increase the limit on many systems. +Consult your OS documentation to find out how to do this, because the +method for changing the limit varies widely from system to system. + +@code{table_cache} is related to @code{max_connections}. For example, +for 200 concurrent running connections, you should have a table cache of +at least @code{200 * n}, where @code{n} is the maximum number of tables +in a join. You also need to reserve some extra file descriptors for +temporary tables and files. + +The cache of open tables can grow to a maximum of @code{table_cache} +(default 64; this can be changed with the @code{-O table_cache=#} +option to @code{mysqld}). A table is never closed, except when the +cache is full and another thread tries to open a table or if you use +@code{mysqladmin refresh} or @code{mysqladmin flush-tables}. + +When the table cache fills up, the server uses the following procedure +to locate a cache entry to use: + +@itemize @bullet +@item +Tables that are not currently in use are released, in least-recently-used +order. + +@item +If the cache is full and no tables can be released, but a new table needs to +be opened, the cache is temporarily extended as necessary. + +@item +If the cache is in a temporarily-extended state and a table goes from in-use +to not-in-use state, the table is closed and released from the cache. +@end itemize + +A table is opened for each concurrent access. This means that +if you have two threads accessing the same table or access the table +twice in the same query (with @code{AS}) the table needs to be opened twice. +The first open of any table takes two file descriptors; each additional +use of the table takes only one file descriptor. The extra descriptor +for the first open is used for the index file; this descriptor is shared +among all threads. + +You can check if your table cache is too small by checking the mysqld +variable @code{opened_tables}. If this is quite big, even if you +haven't done a lot of @code{FLUSH TABLES}, you should increase your table +cache. @xref{SHOW STATUS}. + + +@node Creating many tables, Open tables, Table cache, Optimizing Database Structure +@subsection Drawbacks to Creating Large Numbers of Tables in the Same Database + +@cindex tables, too many + +If you have many files in a directory, open, close, and create operations will +be slow. If you execute @code{SELECT} statements on many different tables, +there will be a little overhead when the table cache is full, because for +every table that has to be opened, another must be closed. You can reduce +this overhead by making the table cache larger. + + +@node Open tables, , Creating many tables, Optimizing Database Structure +@subsection Why So Many Open tables? + +@cindex tables, open +@cindex open tables + +When you run @code{mysqladmin status}, you'll see something like this: + +@example +Uptime: 426 Running threads: 1 Questions: 11082 Reloads: 1 Open tables: 12 +@end example + +This can be somewhat perplexing if you only have 6 tables. + +@strong{MySQL} is multithreaded, so it may have many queries on the same +table simultaneously. To minimize the problem with two threads having +different states on the same file, the table is opened independently by +each concurrent thread. This takes some memory and one extra file +descriptor for the data file. The index file descriptor is shared +between all threads. + + +@node Optimizing the Server, Disk issues, Optimizing Database Structure, MySQL Optimization +@section Optimizing the MySQL Server + + +@menu +* System:: +* Server parameters:: +* Compile and link options:: +* Memory use:: +* DNS:: +* SET OPTION:: +@end menu + +@node System, Server parameters, Optimizing the Server, Optimizing the Server +@subsection System/Compile Time and Startup Parameter Tuning + +@cindex compiling, optimizing +@cindex system optimization +@cindex startup parameters, tuning + +We start with the system level things since some of these decisions have +to be made very early. In other cases a fast look at this part may +suffice because it not that important for the big gains. However, it is always +nice to have a feeling about how much one could gain by changing things +at this level. + +The default OS to use is really important! To get the most use of +multiple CPU machines one should use Solaris (because the threads works +really nice) or Linux (because the 2.2 kernel has really good SMP +support). Also on 32-bit machines Linux has a 2G file size limit by +default. Hopefully this will be fixed soon when new filesystems are +released (XFS/Reiserfs). If you have a desperate need for files bigger +than 2G on Linux-intel 32 bit, you should get the LFS patch for the ext2 +file system. + +Because we have not run @strong{MySQL} in production on that many platforms, we +advice you to test your intended platform before choosing it, if possible. + +@cindex locking +Other tips: +@itemize @bullet +@item +If you have enough RAM, you could remove all swap devices. Some +operating systems will use a swap device in some contexts even if you +have free memory. +@item +Use the @code{--skip-locking} @strong{MySQL} option to avoid external +locking. Note that this will not impact @strong{MySQL}'s functionality as +long as you only run one server. Just remember to take down the server (or +lock relevant parts) before you run @code{myisamchk}. On some system +this switch is mandatory because the external locking does not work in any +case. + +The @code{--skip-locking} option is on by default when compiling with +MIT-pthreads, because @code{flock()} isn't fully supported by +MIT-pthreads on all platforms. It's also on default for Linux +as Linux file locking are not yet safe. + +The only case when you can't use @code{--skip-locking} is if you run +multiple @strong{MySQL} @emph{servers} (not clients) on the same data, +or run @code{myisamchk} on the table without first flushing and locking +the @code{mysqld} server tables first. + +You can still use @code{LOCK TABLES}/@code{UNLOCK TABLES} even if you +are using @code{--skip-locking} +@end itemize + + +@node Server parameters, Compile and link options, System, Optimizing the Server +@subsection Tuning Server Parameters + +@cindex parameters, server +@cindex @code{mysqld} server, buffer sizes +@cindex buffer sizes, @code{mysqld} server +@cindex startup parameters + +You can get the default buffer sizes used by the @code{mysqld} server +with this command: + +@example +shell> mysqld --help +@end example + +@cindex @code{mysqld} options +@cindex variables, @code{mysqld} +This command produces a list of all @code{mysqld} options and configurable +variables. The output includes the default values and looks something +like this: + +@example +Possible variables for option --set-variable (-O) are: +back_log current value: 5 +bdb_cache_size current value: 1048540 +binlog_cache_size current_value: 32768 +connect_timeout current value: 5 +delayed_insert_timeout current value: 300 +delayed_insert_limit current value: 100 +delayed_queue_size current value: 1000 +flush_time current value: 0 +interactive_timeout current value: 28800 +join_buffer_size current value: 131072 +key_buffer_size current value: 1048540 +lower_case_table_names current value: 0 +long_query_time current value: 10 +max_allowed_packet current value: 1048576 +max_binlog_cache_size current_value: 4294967295 +max_connections current value: 100 +max_connect_errors current value: 10 +max_delayed_threads current value: 20 +max_heap_table_size current value: 16777216 +max_join_size current value: 4294967295 +max_sort_length current value: 1024 +max_tmp_tables current value: 32 +max_write_lock_count current value: 4294967295 +myisam_sort_buffer_size current value: 8388608 +net_buffer_length current value: 16384 +net_retry_count current value: 10 +net_read_timeout current value: 30 +net_write_timeout current value: 60 +query_buffer_size current value: 0 +record_buffer current value: 131072 +slow_launch_time current value: 2 +sort_buffer current value: 2097116 +table_cache current value: 64 +thread_concurrency current value: 10 +tmp_table_size current value: 1048576 +thread_stack current value: 131072 +wait_timeout current value: 28800 +@end example + +If there is a @code{mysqld} server currently running, you can see what +values it actually is using for the variables by executing this command: + +@example +shell> mysqladmin variables +@end example + +You can find a full description for all variables in the @code{SHOW VARIABLES} +section in this manual. @xref{SHOW VARIABLES}. + +You can also see some statistics from a running server by issuing the command +@code{SHOW STATUS}. @xref{SHOW STATUS}. + +@strong{MySQL} uses algorithms that are very scalable, so you can usually +run with very little memory. If you, however, give @strong{MySQL} more +memory, you will normally also get better performance. + +When tuning a @strong{MySQL} server, the two most important variables to use +are @code{key_buffer_size} and @code{table_cache}. You should first feel +confident that you have these right before trying to change any of the +other variables. + +If you have much memory (>=256M) and many tables and want maximum performance +with a moderate number of clients, you should use something like this: + +@example +shell> safe_mysqld -O key_buffer=64M -O table_cache=256 \ + -O sort_buffer=4M -O record_buffer=1M & +@end example + +If you have only 128M and only a few tables, but you still do a lot of +sorting, you can use something like: + +@example +shell> safe_mysqld -O key_buffer=16M -O sort_buffer=1M +@end example + +If you have little memory and lots of connections, use something like this: + +@example +shell> safe_mysqld -O key_buffer=512k -O sort_buffer=100k \ + -O record_buffer=100k & +@end example + +or even: + +@example +shell> safe_mysqld -O key_buffer=512k -O sort_buffer=16k \ + -O table_cache=32 -O record_buffer=8k -O net_buffer=1K & +@end example + +When you have installed @strong{MySQL}, the @file{support-files} directory will +contain some different @code{my.cnf} example files, @file{my-huge.cnf}, +@file{my-large.cnf}, @file{my-medium.cnf}, and @file{my-small.cnf}, you can +use as a base to optimize your system. + +If there are very many connections, ``swapping problems'' may occur unless +@code{mysqld} has been configured to use very little memory for each +connection. @code{mysqld} performs better if you have enough memory for all +connections, of course. + +Note that if you change an option to @code{mysqld}, it remains in effect only +for that instance of the server. + +To see the effects of a parameter change, do something like this: + +@example +shell> mysqld -O key_buffer=32m --help +@end example + +Make sure that the @code{--help} option is last; otherwise, the effect of any +options listed after it on the command line will not be reflected in the +output. + + +@node Compile and link options, Memory use, Server parameters, Optimizing the Server +@subsection How Compiling and Linking Affects the Speed of MySQL + +@cindex linking, speed +@cindex compiling, speed +@cindex speed, compiling +@cindex speed, linking + +Most of the following tests are done on Linux with the +@strong{MySQL} benchmarks, but they should give some indication for +other operating systems and workloads. + +You get the fastest executable when you link with @code{-static}. + +On Linux, you will get the fastest code when compiling with @code{pgcc} +and @code{-O3}. To compile @file{sql_yacc.cc} with these options, you +need about 200M memory because @code{gcc/pgcc} needs a lot of memory to +make all functions inline. You should also set @code{CXX=gcc} when +configuring @strong{MySQL} to avoid inclusion of the @code{libstdc++} +library (it is not needed). Note that with some versions of @code{pgcc}, +the resulting code will only run on true Pentium processors, even if you +use the compiler option that you want the resulting code to be working on +all x586 type processors (like AMD). + +By just using a better compiler and/or better compiler options you can +get a 10-30 % speed increase in your application. This is particularly +important if you compile the SQL server yourself! + +We have tested both the Cygnus CodeFusion and Fujitsu compilers, but +when we tested them, neither was sufficiently bug free to allow +@strong{MySQL} to be compiled with optimizations on. + +When you compile @strong{MySQL} you should only include support for the +character sets that you are going to use. (Option @code{--with-charset=xxx}). +The standard @strong{MySQL} binary distributions are compiled with support +for all character sets. + +Here is a list of some measurements that we have done: +@itemize @bullet +@item +If you use @code{pgcc} and compile everything with @code{-O6}, the +@code{mysqld} server is 1% faster than with @code{gcc} 2.95.2. + +@item +If you link dynamically (without @code{-static}), the result is 13% +slower on Linux. Note that you still can use a dynamic linked +@strong{MySQL} library. It is only the server that is critical for +performance. + +@item +If you strip your @code{mysqld} binary with @code{strip libexec/mysqld}, +the resulting binary can be up to 4 % faster. + +@item +If you connect using TCP/IP rather than Unix sockets, the result is 7.5% +slower on the same computer. (If you are connection to @code{localhost}, +@strong{MySQL} will, by default, use sockets). + +@item +If you connect using TCP/IP from another computer over a 100M Ethernet, +things will be 8-11 % slower. + +@item +If you compile with @code{--with-debug=full}, then you will loose 20 % +for most queries, but some queries may take substantially longer (The +@strong{MySQL} benchmarks ran 35 % slower) +If you use @code{--with-debug}, then you will only loose 15 %. +By starting a @code{mysqld} version compiled with @code{--with-debug=full} +with @code{--skip-safemalloc} the end result should be close to when +configuring with @code{--with-debug}. + +@item +On a Sun SPARCstation 20, SunPro C++ 4.2 is 5 % faster than @code{gcc} 2.95.2. + +@item +Compiling with @code{gcc} 2.95.2 for ultrasparc with the option +@code{-mcpu=v8 -Wa,-xarch=v8plusa} gives 4 % more performance. + +@item +On Solaris 2.5.1, MIT-pthreads is 8-12% slower than Solaris native +threads on a single processor. With more load/CPUs the difference should +get bigger. + +@item +Running with @code{--log-bin} makes @strong{[MySQL} 1 % slower. + +@item +Compiling on Linux-x86 using gcc without frame pointers +@code{-fomit-frame-pointer} or @code{-fomit-frame-pointer -ffixed-ebp} +@code{mysqld} 1-4% faster. +@end itemize + +The @strong{MySQL}-Linux distribution provided by @strong{MySQL AB} used +to be compiled with @code{pgcc}, but we had to go back to regular gcc +because of a bug in @code{pgcc} that would generate the code that does +not run on AMD. We will continue using gcc until that bug is resolved. +In the meantime, if you have a non-AMD machine, you can get a faster +binary by compiling with @code{pgcc}. The standard @strong{MySQL} +Linux binary is linked statically to get it faster and more portable. + + +@node Memory use, DNS, Compile and link options, Optimizing the Server +@subsection How MySQL Uses Memory + +@cindex memory use + +The list below indicates some of the ways that the @code{mysqld} server +uses memory. Where applicable, the name of the server variable relevant +to the memory use is given: + +@itemize @bullet +@item +The key buffer (variable @code{key_buffer_size}) is shared by all +threads; Other buffers used by the server are allocated as +needed. @xref{Server parameters}. + +@item +Each connection uses some thread-specific space: A stack (default 64K, +variable @code{thread_stack}), a connection buffer (variable +@code{net_buffer_length}), and a result buffer (variable +@code{net_buffer_length}). The connection buffer and result buffer are +dynamically enlarged up to @code{max_allowed_packet} when needed. When +a query is running, a copy of the current query string is also allocated. + +@item +All threads share the same base memory. + +@item +Only the compressed ISAM / MyISAM tables are memory mapped. This is +because the 32-bit memory space of 4GB is not large enough for most +big tables. When systems with a 64-bit address space become more +common we may add general support for memory mapping. + +@item +Each request doing a sequential scan over a table allocates a read buffer +(variable @code{record_buffer}). + +@item +All joins are done in one pass, and most joins can be done without even +using a temporary table. Most temporary tables are memory-based (HEAP) +tables. Temporary tables with a big record length (calculated as the +sum of all column lengths) or that contain @code{BLOB} columns are +stored on disk. + +One problem in @strong{MySQL} versions before Version 3.23.2 is that if a HEAP table +exceeds the size of @code{tmp_table_size}, you get the error @code{The +table tbl_name is full}. In newer versions this is handled by +automatically changing the in-memory (HEAP) table to a disk-based +(MyISAM) table as necessary. To work around this problem, you can +increase the temporary table size by setting the @code{tmp_table_size} +option to @code{mysqld}, or by setting the SQL option +@code{SQL_BIG_TABLES} in the client program. @xref{SET OPTION, , +@code{SET OPTION}}. In @strong{MySQL} Version 3.20, the maximum size of the +temporary table was @code{record_buffer*16}, so if you are using this +version, you have to increase the value of @code{record_buffer}. You can +also start @code{mysqld} with the @code{--big-tables} option to always +store temporary tables on disk. However, this will affect the speed of +many complicated queries. + +@item +Most requests doing a sort allocates a sort buffer and 0-2 temporary +files depending on the result set size. @xref{Temporary files}. + +@item +Almost all parsing and calculating is done in a local memory store. No +memory overhead is needed for small items and the normal slow memory +allocation and freeing is avoided. Memory is allocated only for +unexpectedly large strings (this is done with @code{malloc()} and +@code{free()}). + +@item +Each index file is opened once and the data file is opened once for each +concurrently running thread. For each concurrent thread, a table structure, +column structures for each column, and a buffer of size @code{3 * n} is +allocated (where @code{n} is the maximum row length, not counting @code{BLOB} +columns). A @code{BLOB} uses 5 to 8 bytes plus the length of the @code{BLOB} +data. The @code{ISAM}/@code{MyISAM} table handlers will use one extra row +buffer for internal usage. + +@item +For each table having @code{BLOB} columns, a buffer is enlarged dynamically +to read in larger @code{BLOB} values. If you scan a table, a buffer as large +as the largest @code{BLOB} value is allocated. + +@item +Table handlers for all in-use tables are saved in a cache and managed as a +FIFO. Normally the cache has 64 entries. If a table has been used by two +running threads at the same time, the cache contains two entries for the +table. @xref{Table cache}. + +@item +A @code{mysqladmin flush-tables} command closes all tables that are not in +use and marks all in-use tables to be closed when the currently executing +thread finishes. This will effectively free most in-use memory. +@end itemize + +@code{ps} and other system status programs may report that @code{mysqld} +uses a lot of memory. This may be caused by thread-stacks on different +memory addresses. For example, the Solaris version of @code{ps} counts +the unused memory between stacks as used memory. You can verify this by +checking available swap with @code{swap -s}. We have tested +@code{mysqld} with commercial memory-leakage detectors, so there should +be no memory leaks. + + +@node DNS, SET OPTION, Memory use, Optimizing the Server +@subsection How MySQL uses DNS + +@cindex DNS +@cindex hostname caching + +When a new thread connects to @code{mysqld}, @code{mysqld} will span a +new thread to handle the request. This thread will first check if the +hostname is in the hostname cache. If not the thread will call +@code{gethostbyaddr_r()} and @code{gethostbyname_r()} to resolve the +hostname. + +If the operating system doesn't support the above thread-safe calls, the +thread will lock a mutex and call @code{gethostbyaddr()} and +@code{gethostbyname()} instead. Note that in this case no other thread +can resolve other hostnames that is not in the hostname cache until the +first thread is ready. + +You can disable DNS host lookup by starting @code{mysqld} with +@code{--skip-name-resolve}. In this case you can however only use IP +names in the @strong{MySQL} privilege tables. + +If you have a very slow DNS and many hosts, you can get more performance by +either disabling DNS lookop with @code{--skip-name-resolve} or by +increasing the @code{HOST_CACHE_SIZE} define (default: 128) and recompile +@code{mysqld}. + +You can disable the hostname cache with @code{--skip-host-cache}. You +can clear the hostname cache with @code{FLUSH HOSTS} or @code{mysqladmin +flush-hosts}. + +If you don't want to allow connections over @code{TCP/IP}, you can do this +by starting @code{mysqld} with @code{--skip-networking}. + + +@node SET OPTION, , DNS, Optimizing the Server +@subsection @code{SET} Syntax + +@findex SET OPTION + +@example +SET [OPTION] SQL_VALUE_OPTION= value, ... +@end example + +@code{SET OPTION} sets various options that affect the operation of the +server or your client. Any option you set remains in effect until the +current session ends, or until you set the option to a different value. + +@table @code +@item CHARACTER SET character_set_name | DEFAULT +This maps all strings from and to the client with the given mapping. +Currently the only option for @code{character_set_name} is +@code{cp1251_koi8}, but you can easily add new mappings by editing the +@file{sql/convert.cc} file in the @strong{MySQL} source distribution. The +default mapping can be restored by using a @code{character_set_name} value of +@code{DEFAULT}. + +Note that the syntax for setting the @code{CHARACTER SET} option differs +from the syntax for setting the other options. + +@item PASSWORD = PASSWORD('some password') +@cindex passwords, setting +Set the password for the current user. Any non-anonymous user can change his +own password! + +@item PASSWORD FOR user = PASSWORD('some password') +Set the password for a specific user on the current server host. Only a user +with access to the @code{mysql} database can do this. The user should be +given in @code{user@@hostname} format, where @code{user} and @code{hostname} +are exactly as they are listed in the @code{User} and @code{Host} columns of +the @code{mysql.user} table entry. For example, if you had an entry with +@code{User} and @code{Host} fields of @code{'bob'} and @code{'%.loc.gov'}, +you would write: + +@example +mysql> SET PASSWORD FOR bob@@"%.loc.gov" = PASSWORD("newpass"); + +or + +mysql> UPDATE mysql.user SET password=PASSWORD("newpass") where user="bob' and host="%.loc.gov"; +@end example + +@item SQL_AUTO_IS_NULL = 0 | 1 +If set to @code{1} (default) then one can find the last inserted row +for a table with an auto_increment row with the following construct: +@code{WHERE auto_increment_column IS NULL}. This is used by some +ODBC programs like Access. + +@item AUTOCOMMIT= 0 | 1 +If set to @code{1} all changes to a table will be done at once. To start +a multi-command transaction, you have to use the @code{BEGIN} +statement. @xref{COMMIT}. If set to @code{0} you have to use @code{COMMIT} / +@code{ROLLBACK} to accept/revoke that transaction. @xref{COMMIT}. Note +that when you change from not @code{AUTOCOMMIT} mode to +@code{AUTOCOMMIT} mode, @strong{MySQL} will do an automatic +@code{COMMIT} on any open transactions. + +@item SQL_BIG_TABLES = 0 | 1 +@cindex table is full +If set to @code{1}, all temporary tables are stored on disk rather than in +memory. This will be a little slower, but you will not get the error +@code{The table tbl_name is full} for big @code{SELECT} operations that +require a large temporary table. The default value for a new connection is +@code{0} (that is, use in-memory temporary tables). + +@item SQL_BIG_SELECTS = 0 | 1 +If set to @code{0}, @strong{MySQL} will abort if a @code{SELECT} is attempted +that probably will take a very long time. This is useful when an inadvisable +@code{WHERE} statement has been issued. A big query is defined as a +@code{SELECT} that probably will have to examine more than +@code{max_join_size} rows. The default value for a new connection is +@code{1} (which will allow all @code{SELECT} statements). + +@item SQL_BUFFER_RESULT = 0 | 1 +@code{SQL_BUFFER_RESULT} will force the result from @code{SELECT}'s +to be put into a temporary table. This will help @strong{MySQL} free the +table locks early and will help in cases where it takes a long time to +send the result set to the client. + +@item SQL_LOW_PRIORITY_UPDATES = 0 | 1 +If set to @code{1}, all @code{INSERT}, @code{UPDATE}, @code{DELETE}, and +and @code{LOCK TABLE WRITE} statements wait until there is no pending +@code{SELECT} or @code{LOCK TABLE READ} on the affected table. + +@item SQL_MAX_JOIN_SIZE = value | DEFAULT +Don't allow @code{SELECT}s that will probably need to examine more than +@code{value} row combinations. By setting this value, you can catch +@code{SELECT}s where keys are not used properly and that would probably +take a long time. Setting this to a value other than @code{DEFAULT} will reset +the @code{SQL_BIG_SELECTS} flag. If you set the @code{SQL_BIG_SELECTS} +flag again, the @code{SQL_MAX_JOIN_SIZE} variable will be ignored. +You can set a default value for this variable by starting @code{mysqld} with +@code{-O max_join_size=#}. + +@item SQL_SAFE_MODE = 0 | 1 +If set to @code{1}, @strong{MySQL} will abort if an @code{UPDATE} or +@code{DELETE} is attempted that doesn't use a key or @code{LIMIT} in the +@code{WHERE} clause. This makes it possible to catch wrong updates +when creating SQL commands by hand. + +@item SQL_SELECT_LIMIT = value | DEFAULT +The maximum number of records to return from @code{SELECT} statements. If +a @code{SELECT} has a @code{LIMIT} clause, the @code{LIMIT} takes precedence +over the value of @code{SQL_SELECT_LIMIT}. The default value for a new +connection is ``unlimited.'' If you have changed the limit, the default value +can be restored by using a @code{SQL_SELECT_LIMIT} value of @code{DEFAULT}. + +@item SQL_LOG_OFF = 0 | 1 +If set to @code{1}, no logging will be done to the standard log for this +client, if the client has the @strong{process} privilege. This does not +affect the update log! + +@item SQL_LOG_UPDATE = 0 | 1 +If set to @code{0}, no logging will be done to the update log for the client, +if the client has the @strong{process} privilege. This does not affect the +standard log! + +@item SQL_QUOTE_SHOW_CREATE = 0 | 1 +If set to @code{1}, @code{SHOW CREATE TABLE} will quote +table and column names. This is @strong{on} by default, +for replication of tables with fancy column names to work. +@ref{SHOW CREATE TABLE, , @code{SHOW CREATE TABLE}}. + +@item TIMESTAMP = timestamp_value | DEFAULT +Set the time for this client. This is used to get the original timestamp if +you use the update log to restore rows. @code{timestamp_value} should be a +UNIX Epoch timestamp, not a @strong{MySQL} timestamp. + +@item LAST_INSERT_ID = # +Set the value to be returned from @code{LAST_INSERT_ID()}. This is stored in +the update log when you use @code{LAST_INSERT_ID()} in a command that updates +a table. + +@item INSERT_ID = # +Set the value to be used by the following @code{INSERT} or @code{ALTER TABLE} +command when inserting an @code{AUTO_INCREMENT} value. This is mainly used +with the update log. +@end table + + +@menu +* SET TRANSACTION:: +@end menu + +@node SET TRANSACTION, , SET OPTION, SET OPTION +@subsubsection @code{SET TRANSACTION} Syntax + +@findex ISOLATION LEVEL + +@example +SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL +[READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE] +@end example + +Sets the transaction isolation level for the global, whole session or +the next transaction. + +The default behavior is to set the isolation level for the next (not started) +transaction. + +If you set the @code{GLOBAL} privilege it will affect all new created threads. +You will need the @code{PROCESS} privilege to do do this. + +Setting the @code{SESSION} privilege will affect the following and all +future transactions. + +You can set the default isolation level for @code{mysqld} with +@code{--transaction-isolation=...}. @xref{Command-line options}. + + +@node Disk issues, , Optimizing the Server, MySQL Optimization +@section Disk Issues + +@cindex disk issues +@cindex performance, disk issues + +@itemize @bullet +@item +As mentioned before, disks seeks are a big performance bottleneck. This +problems gets more and more apparent when the data starts to grow so +large that effective caching becomes impossible. For large databases, +where you access data more or less randomly, you can be sure that you +will need at least one disk seek to read and a couple of disk seeks to +write things. To minimize this problem, use disks with low seek times. + +@item +Increase the number of available disk spindles (and thereby reduce +the seek overhead) by either symlink files to different disks or striping +the disks. + +@table @strong +@item Using symbolic links +This means that you symlink the index and/or data file(s) from the +normal data directory to another disk (that may also be striped). This +makes both the seek and read times better (if the disks are not used for +other things). @xref{Symbolic links}. + +@cindex striping, defined +@item Striping +Striping means that you have many disks and put the first block on the +first disk, the second block on the second disk, and the Nth on the +(N mod number_of_disks) disk, and so on. This means if your normal data +size is less than the stripe size (or perfectly aligned) you will get +much better performance. Note that striping is very dependent on the OS +and stripe-size. So benchmark your application with different +stripe-sizes. @xref{Custom Benchmarks}. + +Note that the speed difference for striping is @strong{very} dependent +on the parameters. Depending on how you set the striping parameters and +number of disks you may get a difference in orders of magnitude. Note that +you have to choose to optimize for random or sequential access. +@end table + +@item +For reliability you may want to use RAID 0+1 (striping + mirroring), but +in this case you will need 2*N drives to hold N drives of data. This is +probably the best option if you have the money for it! You may, however, +also have to invest in some volume-management software to handle it +efficiently. + +@item +A good option is to have semi-important data (that can be regenerated) +on RAID 0 disk while storing really important data (like host information +and logs) on a RAID 0+1 or RAID N disk. RAID N can be a problem if you +have many writes because of the time to update the parity bits. + +@item +You may also set the parameters for the file system that the database +uses. One easy change is to mount the file system with the noatime +option. That makes it skip the updating of the last access time in the +inode and by this will avoid some disk seeks. + +@item +On Linux, you can get much more performance (up to 100 % under load is +not uncommon) by using hdpram to configure your disk's interface! The +following should be quite good hdparm options for @strong{MySQL} (and +probably many other applications): + +@example +hdparm -m 16 -d 1 +@end example + +Note that the performance/reliability when using the above depends on +your hardware, so we strongly suggest that you test your system +thoroughly after using @code{hdparm}! Please consult the @code{hdparm} +man page for more information! If @code{hdparm} is not used wisely, +filesystem corruption may result. Backup everything before experimenting! + +@item +On many operating systems you can mount the disks with the 'async' flag to +set the file system to be updated asynchronously. If your computer is +reasonable stable, this should give you more performance without sacrificing +too much reliability. (This flag is on by default on Linux.) + +@item +If you don't need to know when a file was last accessed (which is not +really useful on a database server), you can mount your file systems +with the noatime flag. +@end itemize + +@menu +* Symbolic links:: +@end menu + +@node Symbolic links, , Disk issues, Disk issues +@subsection Using Symbolic Links + +@cindex symbolic links +@cindex links, symbolic + +You can move tables and databases from the database directory to other +locations and replace them with symbolic links to the new locations. +You might want to do this, for example, to move a database to a file +system with more free space or increase the speed of your system by +spreading your tables to different disk. + +The recommended may to do this, is to just symlink databases to different +disk and only symlink tables as a last resort. + +@cindex databases, symbolic links +@menu +* Symbolic links to databases:: +* Symbolic links to tables:: +@end menu + + +@node Symbolic links to databases, Symbolic links to tables, Symbolic links, Symbolic links +@subsubsection Using Symbolic Links for Databases + +The way to symlink a database is to first create a directory on some +disk where you have free space and then create a symlink to it from +the @strong{MySQL} database directory. + +@example +shell> mkdir /dr1/databases/test +shell> ln -s /dr1/databases/test mysqld-datadir +@end example + +@strong{MySQL} doesn't support that you link one directory to multiple +databases. Replacing a database directory with a symbolic link will +work fine as long as you don't make a symbolic link between databases. +Suppose you have a database @code{db1} under the @strong{MySQL} data +directory, and then make a symlink @code{db2} that points to @code{db1}: + +@example +shell> cd /path/to/datadir +shell> ln -s db1 db2 +@end example + +Now, for any table @code{tbl_a} in @code{db1}, there also appears to be +a table @code{tbl_a} in @code{db2}. If one thread updates @code{db1.tbl_a} +and another thread updates @code{db2.tbl_a}, there will be problems. + +If you really need this, you must change the following code in +@file{mysys/mf_format.c}: + +@example +if (flag & 32 || (!lstat(to,&stat_buff) && S_ISLNK(stat_buff.st_mode))) +@end example + +to + +@example +if (1) +@end example + +On Windows you can use internal symbolic links to directories by compiling +@strong{MySQL} with @code{-DUSE_SYMDIR}. This allows you to put different +databases on different disks. @xref{Windows symbolic links}. + + +@node Symbolic links to tables, , Symbolic links to databases, Symbolic links +@subsubsection Using Symbolic Links for Tables + +@cindex databases, symbolic links + +Before @strong{MySQL} 4.0 you should not symlink tables, if you are not +very carefully with them. The problem is that if you run @code{ALTER +TABLE}, @code{REPAIR TABLE} or @code{OPTIMIZE TABLE} on a symlinked +table, the symlinks will be removed and replaced by the original +files. This happens because the above command works by creating a +temporary file in the database directory and when the command is +complete, replace the original file with the temporary file. + +You should not symlink tables on system that doesn't have a fully +working @code{realpath()} call. (At least Linux and Solaris support +@code{realpath()}) + +In @strong{MySQL} 4.0 symlinks is only fully supported for @code{MyISAM} +tables. For other table types you will probably get strange problems +when doing any of the above mentioned commands. + +The handling of symbolic links in @strong{MySQL} 4.0 works the following +way (this is mostly relevant only for @code{MyISAM} tables). + +@itemize @bullet +@item +In the data directory you will always have the table definition file +and the data/index files. + +@item +You can symlink the index file and the data file to different directories +independent of the other. + +@item +The symlinking can be done from the operating system (if @code{mysqld} is +not running) or with the @code{INDEX/DATA DIRECTORY="path-to-dir"} command +in @code{CREATE TABLE}. @xref{CREATE TABLE}. + +@item +@code{myisamchk} will not replace a symlink with the index/file but +work directly on the files the symlinks points to. Any temporary files +will be created in the same directory where the data/index file is. + +@item +When you drop a table that is using symlinks, both the symlink and the +file the symlink points to is dropped. This is a good reason to why you +should NOT run @code{mysqld} as root and not allow persons to have write +access to the @strong{MySQL} database directories. + +@item +If you rename a table with @code{ALTER TABLE RENAME} and you don't change +database, the symlink in the database directory will be renamed to the new +name and the data/index file will be renamed accordingly. + +@item +If you use @code{ALTER TABLE RENAME} to move a table to another database, +then the table will be moved to the other database directory and the old +symlinks and the files they pointed to will be deleted. + +@item +If you are not using symlinks you should use the @code{--skip-symlink} +option to @code{mysqld} to ensure that no one can drop or rename a file +outside of the @code{mysqld} data directory. +@end itemize + +Things that are not yet supported: + +@cindex TODO, symlinks +@itemize @bullet +@item +@code{ALTER TABLE} ignores all @code{INDEX/DATA DIRECTORY="path"} options. +@item +@code{CREATE TABLE} doesn't report if the table has symbolic links. +@item +@code{mysqldump} doesn't include the symbolic links information in the output. +@item +@code{BACKUP TABLE} and @code{RESTORE TABLE} doesn't use symbolic links. +@end itemize + + + + + +@node Reference, Table types, MySQL Optimization, Top @chapter MySQL Language Reference @menu @@ -23687,12 +26667,9 @@ isolate it into a separate test case first. Then report the problem to * LOAD DATA:: @code{LOAD DATA INFILE} syntax * UPDATE:: @code{UPDATE} syntax * USE:: @code{USE} syntax -* EXPLAIN:: @code{EXPLAIN} syntax (Get information about a @code{SELECT}) * DESCRIBE:: @code{DESCRIBE} syntax (Get information about names of columns) * COMMIT:: @code{BEGIN/COMMIT/ROLLBACK} syntax * LOCK TABLES:: @code{LOCK TABLES/UNLOCK TABLES} syntax -* SET OPTION:: @code{SET OPTION} syntax -* SET TRANSACTION:: @code{SET TRANSACTION} syntax * CREATE INDEX:: @code{CREATE INDEX} syntax * DROP INDEX:: @code{DROP INDEX} syntax * Comments:: Comment syntax @@ -24489,8 +27466,6 @@ be chosen from the list of values @code{'value1'}, @code{'value2'}, * Date and time types:: Date and time types * String types:: String types * Choosing types:: Choosing the right type for a column -* Indexes:: Column indexes -* Multiple-column indexes:: Multiple-column indexes * Other-vendor column types:: Using column types from other database engines @end menu @@ -25547,7 +28522,7 @@ the @code{SET} definition in the second column. @cindex types, columns @cindex choosing types -@node Choosing types, Indexes, String types, Column types +@node Choosing types, Other-vendor column types, String types, Column types @subsection Choosing the Right Type for a Column For the most efficient use of storage, try to use the most precise type in @@ -25564,113 +28539,13 @@ For high precision, you can always convert to a fixed-point type stored in a @code{BIGINT}. This allows you to do all calculations with integers and convert results back to floating-point values only when necessary. -@cindex indexes, columns -@cindex columns, indexes -@cindex keys -@node Indexes, Multiple-column indexes, Choosing types, Column types -@subsection Column Indexes -All @strong{MySQL} column types can be indexed. Use of indexes on the -relevant columns is the best way to improve the performance of @code{SELECT} -operations. - -The maximum number of keys and the maximum index length is defined per -table handler. @xref{Table types}. You can with all table handlers have -at least 16 keys and a total index length of at least 256 bytes. - -For @code{CHAR} and @code{VARCHAR} columns, you can index a prefix of a -column. This is much faster and requires less disk space than indexing the -whole column. The syntax to use in the @code{CREATE TABLE} statement to -index a column prefix looks like this: - -@example -KEY index_name (col_name(length)) -@end example - -The example below creates an index for the first 10 characters of the -@code{name} column: - -@example -mysql> CREATE TABLE test ( - name CHAR(200) NOT NULL, - KEY index_name (name(10))); -@end example - -For @code{BLOB} and @code{TEXT} columns, you must index a prefix of the -column. You cannot index the entire column. - -In @strong{MySQL} Version 3.23.23 or later, you can also create special -@strong{FULLTEXT} indexes. They are used for full-text search. Only the -@code{MyISAM} table type supports @code{FULLTEXT} indexes. They can be -created only from @code{VARCHAR} and @code{TEXT} columns. -Indexing always happens over the entire column and partial indexing is not -supported. See @ref{Fulltext Search} for details. - -@cindex multi-column indexes -@cindex indexes, multi-column -@cindex keys, multi-column -@node Multiple-column indexes, Other-vendor column types, Indexes, Column types -@subsection Multiple-column Indexes - -@strong{MySQL} can create indexes on multiple columns. An index may -consist of up to 15 columns. (On @code{CHAR} and @code{VARCHAR} columns you -can also use a prefix of the column as a part of an index). - -A multiple-column index can be considered a sorted array containing values -that are created by concatenating the values of the indexed columns. - -@strong{MySQL} uses multiple-column indexes in such a way that queries are -fast when you specify a known quantity for the first column of the index in a -@code{WHERE} clause, even if you don't specify values for the other columns. - -Suppose a table is created using the following specification: - -@example -mysql> CREATE TABLE test ( - id INT NOT NULL, - last_name CHAR(30) NOT NULL, - first_name CHAR(30) NOT NULL, - PRIMARY KEY (id), - INDEX name (last_name,first_name)); -@end example - -Then the index @code{name} is an index over @code{last_name} and -@code{first_name}. The index will be used for queries that specify -values in a known range for @code{last_name}, or for both @code{last_name} -and @code{first_name}. -Therefore, the @code{name} index will be used in the following queries: - -@example -mysql> SELECT * FROM test WHERE last_name="Widenius"; - -mysql> SELECT * FROM test WHERE last_name="Widenius" - AND first_name="Michael"; - -mysql> SELECT * FROM test WHERE last_name="Widenius" - AND (first_name="Michael" OR first_name="Monty"); - -mysql> SELECT * FROM test WHERE last_name="Widenius" - AND first_name >="M" AND first_name < "N"; -@end example - -However, the @code{name} index will NOT be used in the following queries: - -@example -mysql> SELECT * FROM test WHERE first_name="Michael"; - -mysql> SELECT * FROM test WHERE last_name="Widenius" - OR first_name="Michael"; -@end example - -For more information on the manner in which @strong{MySQL} uses indexes to -improve query performance, see @ref{MySQL indexes, , @strong{MySQL} -indexes}. +@node Other-vendor column types, , Choosing types, Column types +@subsection Using Column Types from Other Database Engines @cindex types, portability @cindex portability, types @cindex columns, other types -@node Other-vendor column types, , Multiple-column indexes, Column types -@subsection Using Column Types from Other Database Engines To make it easier to use code written for SQL implementations from other vendors, @strong{MySQL} maps column types as shown in the table below. These @@ -30701,7 +33576,7 @@ In @strong{MySQL} Version 3.23, you can use @code{LIMIT #} to ensure that only a given number of rows are changed. @findex USE -@node USE, EXPLAIN, UPDATE, Reference +@node USE, DESCRIBE, UPDATE, Reference @section @code{USE} Syntax @example @@ -30736,364 +33611,10 @@ mysql> SELECT author_name,editor_name FROM author,db2.editor The @code{USE} statement is provided for Sybase compatibility. -@findex EXPLAIN -@findex SELECT, optimizing -@node EXPLAIN, DESCRIBE, USE, Reference -@section @code{EXPLAIN} Syntax (Get Information About a @code{SELECT}) - -@example - EXPLAIN tbl_name -or EXPLAIN SELECT select_options -@end example - -@code{EXPLAIN tbl_name} is a synonym for @code{DESCRIBE tbl_name} or -@code{SHOW COLUMNS FROM tbl_name}. - -When you precede a @code{SELECT} statement with the keyword @code{EXPLAIN}, -@strong{MySQL} explains how it would process the @code{SELECT}, providing -information about how tables are joined and in which order. - -With the help of @code{EXPLAIN}, you can see when you must add indexes -to tables to get a faster @code{SELECT} that uses indexes to find the -records. You can also see if the optimizer joins the tables in an optimal -order. To force the optimizer to use a specific join order for a -@code{SELECT} statement, add a @code{STRAIGHT_JOIN} clause. - -For non-simple joins, @code{EXPLAIN} returns a row of information for each -table used in the @code{SELECT} statement. The tables are listed in the order -they would be read. @strong{MySQL} resolves all joins using a single-sweep -multi-join method. This means that @strong{MySQL} reads a row from the first -table, then finds a matching row in the second table, then in the third table -and so on. When all tables are processed, it outputs the selected columns and -backtracks through the table list until a table is found for which there are -more matching rows. The next row is read from this table and the process -continues with the next table. - -Output from @code{EXPLAIN} includes the following columns: - -@table @code -@item table -The table to which the row of output refers. - -@item type -The join type. Information about the various types is given below. - -@item possible_keys -The @code{possible_keys} column indicates which indexes @strong{MySQL} -could use to find the rows in this table. Note that this column is -totally independent of the order of the tables. That means that some of -the keys in possible_keys may not be usable in practice with the -generated table order. - -If this column is empty, there are no relevant indexes. In this case, -you may be able to improve the performance of your query by examining -the @code{WHERE} clause to see if it refers to some column or columns -that would be suitable for indexing. If so, create an appropriate index -and check the query with @code{EXPLAIN} again. @xref{ALTER TABLE}. - -To see what indexes a table has, use @code{SHOW INDEX FROM tbl_name}. - -@item key -The @code{key} column indicates the key that @strong{MySQL} actually -decided to use. The key is @code{NULL} if no index was chosen. If -@strong{MySQL} chooses the wrong index, you can probably force -@strong{MySQL} to use another index by using @code{myisamchk --analyze}, -@xref{myisamchk syntax}, or by using @code{USE INDEX/IGNORE INDEX}. -@xref{JOIN}. - -@item key_len -The @code{key_len} column indicates the length of the key that -@strong{MySQL} decided to use. The length is @code{NULL} if the -@code{key} is @code{NULL}. Note that this tells us how many parts of a -multi-part key @strong{MySQL} will actually use. - -@item ref -The @code{ref} column shows which columns or constants are used with the -@code{key} to select rows from the table. - -@item rows -The @code{rows} column indicates the number of rows @strong{MySQL} -believes it must examine to execute the query. - -@item Extra -This column contains additional information of how @strong{MySQL} will -resolve the query. Here is an explanation of the different text -strings that can be found in this column: - -@table @code -@item Distinct -@strong{MySQL} will not continue searching for more rows for the current row -combination after it has found the first matching row. - -@item Not exists -@strong{MySQL} was able to do a @code{LEFT JOIN} optimization on the -query and will not examine more rows in this table for the previous row -combination after it finds one row that matches the @code{LEFT JOIN} criteria. - -Here is an example for this: - -@example -SELECT * FROM t1 LEFT JOIN t2 ON t1.id=t2.id WHERE t2.id IS NULL; -@end example - -Assume that @code{t2.id} is defined with @code{NOT NULL}. In this case -@strong{MySQL} will scan @code{t1} and look up the rows in @code{t2} -through @code{t1.id}. If @strong{MySQL} finds a matching row in -@code{t2}, it knows that @code{t2.id} can never be @code{NULL}, and will -not scan through the rest of the rows in @code{t2} that has the same -@code{id}. In other words, for each row in @code{t1}, @strong{MySQL} -only needs to do a single lookup in @code{t2}, independent of how many -matching rows there are in @code{t2}. - -@item @code{range checked for each record (index map: #)} -@strong{MySQL} didn't find a real good index to use. It will, instead, for -each row combination in the preceding tables, do a check on which index to -use (if any), and use this index to retrieve the rows from the table. This -isn't very fast but is faster than having to do a join without -an index. - -@item Using filesort -@strong{MySQL} will need to do an extra pass to find out how to retrieve -the rows in sorted order. The sort is done by going through all rows -according to the @code{join type} and storing the sort key + pointer to -the row for all rows that match the @code{WHERE}. Then the keys are -sorted. Finally the rows are retrieved in sorted order. - -@item Using index -The column information is retrieved from the table using only -information in the index tree without having to do an additional seek to -read the actual row. This can be done when all the used columns for -the table are part of the same index. - -@item Using temporary -To resolve the query @strong{MySQL} will need to create a -temporary table to hold the result. This typically happens if you do an -@code{ORDER BY} on a different column set than you did a @code{GROUP -BY} on. - -@item Where used -A @code{WHERE} clause will be used to restrict which rows will be -matched against the next table or sent to the client. If you don't have -this information and the table is of type @code{ALL} or @code{index}, -you may have something wrong in your query (if you don't intend to -fetch/examine all rows from the table). -@end table - -If you want to get your queries as fast as possible, you should look out for -@code{Using filesort} and @code{Using temporary}. -@end table - -The different join types are listed below, ordered from best to worst type: - -@cindex system table -@cindex tables, system -@table @code -@item system -The table has only one row (= system table). This is a special case of -the @code{const} join type. - -@cindex constant table -@cindex tables, constant -@item const -The table has at most one matching row, which will be read at the start -of the query. Because there is only one row, values from the column in -this row can be regarded as constants by the rest of the -optimizer. @code{const} tables are very fast as they are read only once! - -@item eq_ref -One row will be read from this table for each combination of rows from -the previous tables. This is the best possible join type, other than the -@code{const} types. It is used when all parts of an index are used by -the join and the index is @code{UNIQUE} or a @code{PRIMARY KEY}. - -@item ref -All rows with matching index values will be read from this table for each -combination of rows from the previous tables. @code{ref} is used if the join -uses only a leftmost prefix of the key, or if the key is not @code{UNIQUE} -or a @code{PRIMARY KEY} (in other words, if the join cannot select a single -row based on the key value). If the key that is used matches only a few rows, -this join type is good. - -@item range -Only rows that are in a given range will be retrieved, using an index to -select the rows. The @code{key} column indicates which index is used. -The @code{key_len} contains the longest key part that was used. -The @code{ref} column will be NULL for this type. - -@item index -This is the same as @code{ALL}, except that only the index tree is -scanned. This is usually faster than @code{ALL}, as the index file is usually -smaller than the data file. - -@item ALL -A full table scan will be done for each combination of rows from the -previous tables. This is normally not good if the table is the first -table not marked @code{const}, and usually @strong{very} bad in all other -cases. You normally can avoid @code{ALL} by adding more indexes, so that -the row can be retrieved based on constant values or column values from -earlier tables. -@end table - -You can get a good indication of how good a join is by multiplying all values -in the @code{rows} column of the @code{EXPLAIN} output. This should tell you -roughly how many rows @strong{MySQL} must examine to execute the query. This -number is also used when you restrict queries with the @code{max_join_size} -variable. -@xref{Server parameters}. - -The following example shows how a @code{JOIN} can be optimized progressively -using the information provided by @code{EXPLAIN}. - -Suppose you have the @code{SELECT} statement shown below, that you examine -using @code{EXPLAIN}: - -@example -EXPLAIN SELECT tt.TicketNumber, tt.TimeIn, - tt.ProjectReference, tt.EstimatedShipDate, - tt.ActualShipDate, tt.ClientID, - tt.ServiceCodes, tt.RepetitiveID, - tt.CurrentProcess, tt.CurrentDPPerson, - tt.RecordVolume, tt.DPPrinted, et.COUNTRY, - et_1.COUNTRY, do.CUSTNAME - FROM tt, et, et AS et_1, do - WHERE tt.SubmitTime IS NULL - AND tt.ActualPC = et.EMPLOYID - AND tt.AssignedPC = et_1.EMPLOYID - AND tt.ClientID = do.CUSTNMBR; -@end example - -For this example, assume that: - -@itemize @bullet -@item -The columns being compared have been declared as follows: - -@multitable @columnfractions .1 .2 .7 -@item @strong{Table} @tab @strong{Column} @tab @strong{Column type} -@item @code{tt} @tab @code{ActualPC} @tab @code{CHAR(10)} -@item @code{tt} @tab @code{AssignedPC} @tab @code{CHAR(10)} -@item @code{tt} @tab @code{ClientID} @tab @code{CHAR(10)} -@item @code{et} @tab @code{EMPLOYID} @tab @code{CHAR(15)} -@item @code{do} @tab @code{CUSTNMBR} @tab @code{CHAR(15)} -@end multitable - -@item -The tables have the indexes shown below: - -@multitable @columnfractions .1 .9 -@item @strong{Table} @tab @strong{Index} -@item @code{tt} @tab @code{ActualPC} -@item @code{tt} @tab @code{AssignedPC} -@item @code{tt} @tab @code{ClientID} -@item @code{et} @tab @code{EMPLOYID} (primary key) -@item @code{do} @tab @code{CUSTNMBR} (primary key) -@end multitable - -@item -The @code{tt.ActualPC} values aren't evenly distributed. -@end itemize - -Initially, before any optimizations have been performed, the @code{EXPLAIN} -statement produces the following information: - -@example -table type possible_keys key key_len ref rows Extra -et ALL PRIMARY NULL NULL NULL 74 -do ALL PRIMARY NULL NULL NULL 2135 -et_1 ALL PRIMARY NULL NULL NULL 74 -tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 - range checked for each record (key map: 35) -@end example - -Because @code{type} is @code{ALL} for each table, this output indicates that -@strong{MySQL} is doing a full join for all tables! This will take quite a -long time, as the product of the number of rows in each table must be -examined! For the case at hand, this is @code{74 * 2135 * 74 * 3872 = -45,268,558,720} rows. If the tables were bigger, you can only imagine how -long it would take. - -One problem here is that @strong{MySQL} can't (yet) use indexes on columns -efficiently if they are declared differently. In this context, -@code{VARCHAR} and @code{CHAR} are the same unless they are declared as -different lengths. Because @code{tt.ActualPC} is declared as @code{CHAR(10)} -and @code{et.EMPLOYID} is declared as @code{CHAR(15)}, there is a length -mismatch. - -To fix this disparity between column lengths, use @code{ALTER TABLE} to -lengthen @code{ActualPC} from 10 characters to 15 characters: - -@example -mysql> ALTER TABLE tt MODIFY ActualPC VARCHAR(15); -@end example - -Now @code{tt.ActualPC} and @code{et.EMPLOYID} are both @code{VARCHAR(15)}. -Executing the @code{EXPLAIN} statement again produces this result: - -@example -table type possible_keys key key_len ref rows Extra -tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 where used -do ALL PRIMARY NULL NULL NULL 2135 - range checked for each record (key map: 1) -et_1 ALL PRIMARY NULL NULL NULL 74 - range checked for each record (key map: 1) -et eq_ref PRIMARY PRIMARY 15 tt.ActualPC 1 -@end example - -This is not perfect, but is much better (the product of the @code{rows} -values is now less by a factor of 74). This version is executed in a couple -of seconds. - -A second alteration can be made to eliminate the column length mismatches -for the @code{tt.AssignedPC = et_1.EMPLOYID} and @code{tt.ClientID = -do.CUSTNMBR} comparisons: - -@example -mysql> ALTER TABLE tt MODIFY AssignedPC VARCHAR(15), - MODIFY ClientID VARCHAR(15); -@end example - -Now @code{EXPLAIN} produces the output shown below: - -@example -table type possible_keys key key_len ref rows Extra -et ALL PRIMARY NULL NULL NULL 74 -tt ref AssignedPC,ClientID,ActualPC ActualPC 15 et.EMPLOYID 52 where used -et_1 eq_ref PRIMARY PRIMARY 15 tt.AssignedPC 1 -do eq_ref PRIMARY PRIMARY 15 tt.ClientID 1 -@end example - -This is almost as good as it can get. - -The remaining problem is that, by default, @strong{MySQL} assumes that values -in the @code{tt.ActualPC} column are evenly distributed, and that isn't the -case for the @code{tt} table. Fortunately, it is easy to tell @strong{MySQL} -about this: - -@example -shell> myisamchk --analyze PATH_TO_MYSQL_DATABASE/tt -shell> mysqladmin refresh -@end example - -Now the join is perfect, and @code{EXPLAIN} produces this result: - -@example -table type possible_keys key key_len ref rows Extra -tt ALL AssignedPC,ClientID,ActualPC NULL NULL NULL 3872 where used -et eq_ref PRIMARY PRIMARY 15 tt.ActualPC 1 -et_1 eq_ref PRIMARY PRIMARY 15 tt.AssignedPC 1 -do eq_ref PRIMARY PRIMARY 15 tt.ClientID 1 -@end example - -Note that the @code{rows} column in the output from @code{EXPLAIN} is an -educated guess from the @strong{MySQL} join optimizer. To optimize a -query, you should check if the numbers are even close to the truth. If not, -you may get better performance by using @code{STRAIGHT_JOIN} in your -@code{SELECT} statement and trying to list the tables in a different order in -the @code{FROM} clause. @findex DESC @findex DESCRIBE -@node DESCRIBE, COMMIT, EXPLAIN, Reference +@node DESCRIBE, COMMIT, USE, Reference @section @code{DESCRIBE} Syntax (Get Information About Columns) @example @@ -31178,7 +33699,7 @@ You can change the isolation level for transactions with @findex LOCK TABLES @findex UNLOCK TABLES -@node LOCK TABLES, SET OPTION, COMMIT, Reference +@node LOCK TABLES, CREATE INDEX, COMMIT, Reference @section @code{LOCK TABLES/UNLOCK TABLES} Syntax @example @@ -31312,181 +33833,15 @@ that can take snapshots in time. automatically commit any active transactions before attempting to lock the tables. -@findex SET OPTION -@node SET OPTION, SET TRANSACTION, LOCK TABLES, Reference -@section @code{SET} Syntax - -@example -SET [OPTION] SQL_VALUE_OPTION= value, ... -@end example - -@code{SET OPTION} sets various options that affect the operation of the -server or your client. Any option you set remains in effect until the -current session ends, or until you set the option to a different value. - -@table @code -@item CHARACTER SET character_set_name | DEFAULT -This maps all strings from and to the client with the given mapping. -Currently the only option for @code{character_set_name} is -@code{cp1251_koi8}, but you can easily add new mappings by editing the -@file{sql/convert.cc} file in the @strong{MySQL} source distribution. The -default mapping can be restored by using a @code{character_set_name} value of -@code{DEFAULT}. - -Note that the syntax for setting the @code{CHARACTER SET} option differs -from the syntax for setting the other options. - -@item PASSWORD = PASSWORD('some password') -@cindex passwords, setting -Set the password for the current user. Any non-anonymous user can change his -own password! - -@item PASSWORD FOR user = PASSWORD('some password') -Set the password for a specific user on the current server host. Only a user -with access to the @code{mysql} database can do this. The user should be -given in @code{user@@hostname} format, where @code{user} and @code{hostname} -are exactly as they are listed in the @code{User} and @code{Host} columns of -the @code{mysql.user} table entry. For example, if you had an entry with -@code{User} and @code{Host} fields of @code{'bob'} and @code{'%.loc.gov'}, -you would write: - -@example -mysql> SET PASSWORD FOR bob@@"%.loc.gov" = PASSWORD("newpass"); - -or - -mysql> UPDATE mysql.user SET password=PASSWORD("newpass") where user="bob' and host="%.loc.gov"; -@end example - -@item SQL_AUTO_IS_NULL = 0 | 1 -If set to @code{1} (default) then one can find the last inserted row -for a table with an auto_increment row with the following construct: -@code{WHERE auto_increment_column IS NULL}. This is used by some -ODBC programs like Access. - -@item AUTOCOMMIT= 0 | 1 -If set to @code{1} all changes to a table will be done at once. To start -a multi-command transaction, you have to use the @code{BEGIN} -statement. @xref{COMMIT}. If set to @code{0} you have to use @code{COMMIT} / -@code{ROLLBACK} to accept/revoke that transaction. @xref{COMMIT}. Note -that when you change from not @code{AUTOCOMMIT} mode to -@code{AUTOCOMMIT} mode, @strong{MySQL} will do an automatic -@code{COMMIT} on any open transactions. - -@item SQL_BIG_TABLES = 0 | 1 -@cindex table is full -If set to @code{1}, all temporary tables are stored on disk rather than in -memory. This will be a little slower, but you will not get the error -@code{The table tbl_name is full} for big @code{SELECT} operations that -require a large temporary table. The default value for a new connection is -@code{0} (that is, use in-memory temporary tables). - -@item SQL_BIG_SELECTS = 0 | 1 -If set to @code{0}, @strong{MySQL} will abort if a @code{SELECT} is attempted -that probably will take a very long time. This is useful when an inadvisable -@code{WHERE} statement has been issued. A big query is defined as a -@code{SELECT} that probably will have to examine more than -@code{max_join_size} rows. The default value for a new connection is -@code{1} (which will allow all @code{SELECT} statements). - -@item SQL_BUFFER_RESULT = 0 | 1 -@code{SQL_BUFFER_RESULT} will force the result from @code{SELECT}'s -to be put into a temporary table. This will help @strong{MySQL} free the -table locks early and will help in cases where it takes a long time to -send the result set to the client. - -@item SQL_LOW_PRIORITY_UPDATES = 0 | 1 -If set to @code{1}, all @code{INSERT}, @code{UPDATE}, @code{DELETE}, and -and @code{LOCK TABLE WRITE} statements wait until there is no pending -@code{SELECT} or @code{LOCK TABLE READ} on the affected table. - -@item SQL_MAX_JOIN_SIZE = value | DEFAULT -Don't allow @code{SELECT}s that will probably need to examine more than -@code{value} row combinations. By setting this value, you can catch -@code{SELECT}s where keys are not used properly and that would probably -take a long time. Setting this to a value other than @code{DEFAULT} will reset -the @code{SQL_BIG_SELECTS} flag. If you set the @code{SQL_BIG_SELECTS} -flag again, the @code{SQL_MAX_JOIN_SIZE} variable will be ignored. -You can set a default value for this variable by starting @code{mysqld} with -@code{-O max_join_size=#}. - -@item SQL_SAFE_MODE = 0 | 1 -If set to @code{1}, @strong{MySQL} will abort if an @code{UPDATE} or -@code{DELETE} is attempted that doesn't use a key or @code{LIMIT} in the -@code{WHERE} clause. This makes it possible to catch wrong updates -when creating SQL commands by hand. - -@item SQL_SELECT_LIMIT = value | DEFAULT -The maximum number of records to return from @code{SELECT} statements. If -a @code{SELECT} has a @code{LIMIT} clause, the @code{LIMIT} takes precedence -over the value of @code{SQL_SELECT_LIMIT}. The default value for a new -connection is ``unlimited.'' If you have changed the limit, the default value -can be restored by using a @code{SQL_SELECT_LIMIT} value of @code{DEFAULT}. - -@item SQL_LOG_OFF = 0 | 1 -If set to @code{1}, no logging will be done to the standard log for this -client, if the client has the @strong{process} privilege. This does not -affect the update log! - -@item SQL_LOG_UPDATE = 0 | 1 -If set to @code{0}, no logging will be done to the update log for the client, -if the client has the @strong{process} privilege. This does not affect the -standard log! - -@item SQL_QUOTE_SHOW_CREATE = 0 | 1 -If set to @code{1}, @code{SHOW CREATE TABLE} will quote -table and column names. This is @strong{on} by default, -for replication of tables with fancy column names to work. -@ref{SHOW CREATE TABLE, , @code{SHOW CREATE TABLE}}. - -@item TIMESTAMP = timestamp_value | DEFAULT -Set the time for this client. This is used to get the original timestamp if -you use the update log to restore rows. @code{timestamp_value} should be a -UNIX Epoch timestamp, not a @strong{MySQL} timestamp. - -@item LAST_INSERT_ID = # -Set the value to be returned from @code{LAST_INSERT_ID()}. This is stored in -the update log when you use @code{LAST_INSERT_ID()} in a command that updates -a table. - -@item INSERT_ID = # -Set the value to be used by the following @code{INSERT} or @code{ALTER TABLE} -command when inserting an @code{AUTO_INCREMENT} value. This is mainly used -with the update log. -@end table - -@findex ISOLATION LEVEL -@node SET TRANSACTION, CREATE INDEX, SET OPTION, Reference -@section @code{SET TRANSACTION} Syntax - -@example -SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL -[READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE] -@end example - -Sets the transaction isolation level for the global, whole session or -the next transaction. - -The default behavior is to set the isolation level for the next (not started) -transaction. - -If you set the @code{GLOBAL} privilege it will affect all new created threads. -You will need the @code{PROCESS} privilege to do do this. - -Setting the @code{SESSION} privilege will affect the following and all -future transactions. - -You can set the default isolation level for @code{mysqld} with -@code{--transaction-isolation=...}. @xref{Command-line options}. +@node CREATE INDEX, DROP INDEX, LOCK TABLES, Reference +@section @code{CREATE INDEX} Syntax +@findex CREATE INDEX @cindex indexes @cindex indexes, multi-part @cindex multi-part index -@findex CREATE INDEX -@node CREATE INDEX, DROP INDEX, SET TRANSACTION, Reference -@section @code{CREATE INDEX} Syntax @example CREATE [UNIQUE|FULLTEXT] INDEX index_name ON tbl_name (col_name[(length)],... ) @@ -34174,7 +36529,7 @@ not trivial). @end itemize -@node Fulltext Search, Performance, Table types, Top +@node Fulltext Search, Maintenance, Table types, Top @chapter MySQL Full-text Search @cindex searching, full-text @@ -34417,2216 +36772,8 @@ the user wants to treat as words, examples are "C++", "AS/400", "TCP/IP", etc. parameters to @code{FULLTEXT} in @code{CREATE/ALTER TABLE}). @end itemize -@cindex performance, maximizing -@cindex optimization -@node Performance, MySQL Benchmarks, Fulltext Search, Top -@chapter Getting Maximum Performance from MySQL -Optimization is a complicated task because it ultimately requires -understanding of the whole system. While it may be possible to do some -local optimizations with small knowledge of your system/application, the -more optimal you want your system to become the more you will have to -know about it. - -So this chapter will try to explain and give some examples of different -ways to optimize @strong{MySQL}. But remember that there are always some -(increasingly harder) additional ways to make the system even faster. - -@menu -* Optimize Basics:: Optimization overview -* System:: System/Compile time and startup parameter tuning -* Data size:: Get your data as small as possible -* MySQL indexes:: How @strong{MySQL} uses indexes -* Query Speed:: Speed of queries that access or update data -* Tips:: Other optimization tips -* Benchmarks:: Using your own benchmarks -* Design:: Design choices -* Design Limitations:: MySQL design limitations/tradeoffs -* Portability:: Portability -* Internal use:: What have we used MySQL for? -@end menu - -@node Optimize Basics, System, Performance, Performance -@section Optimization Overview - -The most important part for getting a system fast is of course the basic -design. You also need to know what kinds of things your system will be -doing, and what your bottlenecks are. - -The most common bottlenecks are: -@itemize @bullet -@item Disk seeks. -It takes time for the disk to find a piece of data. With modern disks in -1999, the mean time for this is usually lower than 10ms, so we can in -theory do about 1000 seeks a second. This time improves slowly with new -disks and is very hard to optimize for a single table. The way to -optimize this is to spread the data on more than one disk. -@item Disk reading/writing. -When the disk is at the correct position we need to read the data. With -modern disks in 1999, one disk delivers something like 10-20Mb/s. This -is easier to optimize than seeks because you can read in parallel from -multiple disks. -@item CPU cycles. -When we have the data in main memory (or if it already were -there) we need to process it to get to our result. Having small -tables compared to the memory is the most common limiting -factor. But then, with small tables speed is usually not the problem. -@item Memory bandwidth. -When the CPU needs more data than can fit in the CPU cache the main -memory bandwidth becomes a bottleneck. This is an uncommon bottleneck -for most systems, but one should be aware of it. -@end itemize - -@cindex compiling, optimizing -@cindex system optimization -@cindex startup parameters, tuning -@node System, Data size, Optimize Basics, Performance -@section System/Compile Time and Startup Parameter Tuning - -We start with the system level things since some of these decisions have -to be made very early. In other cases a fast look at this part may -suffice because it not that important for the big gains. However, it is always -nice to have a feeling about how much one could gain by changing things -at this level. - -The default OS to use is really important! To get the most use of -multiple CPU machines one should use Solaris (because the threads works -really nice) or Linux (because the 2.2 kernel has really good SMP -support). Also on 32-bit machines Linux has a 2G file size limit by -default. Hopefully this will be fixed soon when new filesystems are -released (XFS/Reiserfs). If you have a desperate need for files bigger -than 2G on Linux-intel 32 bit, you should get the LFS patch for the ext2 -file system. - -Because we have not run @strong{MySQL} in production on that many platforms, we -advice you to test your intended platform before choosing it, if possible. - -@cindex locking -Other tips: -@itemize @bullet -@item -If you have enough RAM, you could remove all swap devices. Some -operating systems will use a swap device in some contexts even if you -have free memory. -@item -Use the @code{--skip-locking} @strong{MySQL} option to avoid external -locking. Note that this will not impact @strong{MySQL}'s functionality as -long as you only run one server. Just remember to take down the server (or -lock relevant parts) before you run @code{myisamchk}. On some system -this switch is mandatory because the external locking does not work in any -case. - -The @code{--skip-locking} option is on by default when compiling with -MIT-pthreads, because @code{flock()} isn't fully supported by -MIT-pthreads on all platforms. It's also on default for Linux -as Linux file locking are not yet safe. - -The only case when you can't use @code{--skip-locking} is if you run -multiple @strong{MySQL} @emph{servers} (not clients) on the same data, -or run @code{myisamchk} on the table without first flushing and locking -the @code{mysqld} server tables first. - -You can still use @code{LOCK TABLES}/@code{UNLOCK TABLES} even if you -are using @code{--skip-locking} -@end itemize - -@menu -* Compile and link options:: How compiling and linking affects the speed of MySQL -* Disk issues:: Disk issues -* Symbolic links:: Using Symbolic Links -* Server parameters:: Tuning server parameters -* Table cache:: How MySQL opens and closes tables -* Creating many tables:: Drawbacks of creating large numbers of tables in the same database -* Open tables:: Why so many open tables? -* Memory use:: How MySQL uses memory -* Internal locking:: How MySQL locks tables -* Table locking:: Table locking issues -* DNS:: -@end menu - -@node Compile and link options, Disk issues, System, System -@subsection How Compiling and Linking Affects the Speed of MySQL - -Most of the following tests are done on Linux with the -@strong{MySQL} benchmarks, but they should give some indication for -other operating systems and workloads. - -@cindex linking, speed -@cindex compiling, speed -@cindex speed, compiling -@cindex speed, linking - -You get the fastest executable when you link with @code{-static}. - -On Linux, you will get the fastest code when compiling with @code{pgcc} -and @code{-O3}. To compile @file{sql_yacc.cc} with these options, you -need about 200M memory because @code{gcc/pgcc} needs a lot of memory to -make all functions inline. You should also set @code{CXX=gcc} when -configuring @strong{MySQL} to avoid inclusion of the @code{libstdc++} -library (it is not needed). Note that with some versions of @code{pgcc}, -the resulting code will only run on true Pentium processors, even if you -use the compiler option that you want the resulting code to be working on -all x586 type processors (like AMD). - -By just using a better compiler and/or better compiler options you can -get a 10-30 % speed increase in your application. This is particularly -important if you compile the SQL server yourself! - -We have tested both the Cygnus CodeFusion and Fujitsu compilers, but -when we tested them, neither was sufficiently bug free to allow -@strong{MySQL} to be compiled with optimizations on. - -When you compile @strong{MySQL} you should only include support for the -character sets that you are going to use. (Option @code{--with-charset=xxx}). -The standard @strong{MySQL} binary distributions are compiled with support -for all character sets. - -Here is a list of some measurements that we have done: -@itemize @bullet -@item -If you use @code{pgcc} and compile everything with @code{-O6}, the -@code{mysqld} server is 1% faster than with @code{gcc} 2.95.2. - -@item -If you link dynamically (without @code{-static}), the result is 13% -slower on Linux. Note that you still can use a dynamic linked -@strong{MySQL} library. It is only the server that is critical for -performance. - -@item -If you strip your @code{mysqld} binary with @code{strip libexec/mysqld}, -the resulting binary can be up to 4 % faster. - -@item -If you connect using TCP/IP rather than Unix sockets, the result is 7.5% -slower on the same computer. (If you are connection to @code{localhost}, -@strong{MySQL} will, by default, use sockets). - -@item -If you connect using TCP/IP from another computer over a 100M Ethernet, -things will be 8-11 % slower. - -@item -If you compile with @code{--with-debug=full}, then you will loose 20 % -for most queries, but some queries may take substantially longer (The -@strong{MySQL} benchmarks ran 35 % slower) -If you use @code{--with-debug}, then you will only loose 15 %. -By starting a @code{mysqld} version compiled with @code{--with-debug=full} -with @code{--skip-safemalloc} the end result should be close to when -configuring with @code{--with-debug}. - -@item -On a Sun SPARCstation 20, SunPro C++ 4.2 is 5 % faster than @code{gcc} 2.95.2. - -@item -Compiling with @code{gcc} 2.95.2 for ultrasparc with the option -@code{-mcpu=v8 -Wa,-xarch=v8plusa} gives 4 % more performance. - -@item -On Solaris 2.5.1, MIT-pthreads is 8-12% slower than Solaris native -threads on a single processor. With more load/CPUs the difference should -get bigger. - -@item -Running with @code{--log-bin} makes @strong{[MySQL} 1 % slower. - -@item -Compiling on Linux-x86 using gcc without frame pointers -@code{-fomit-frame-pointer} or @code{-fomit-frame-pointer -ffixed-ebp} -@code{mysqld} 1-4% faster. -@end itemize - -The @strong{MySQL}-Linux distribution provided by @strong{MySQL AB} used -to be compiled with @code{pgcc}, but we had to go back to regular gcc -because of a bug in @code{pgcc} that would generate the code that does -not run on AMD. We will continue using gcc until that bug is resolved. -In the meantime, if you have a non-AMD machine, you can get a faster -binary by compiling with @code{pgcc}. The standard @strong{MySQL} -Linux binary is linked statically to get it faster and more portable. - -@cindex disk issues -@cindex performance, disk issues -@node Disk issues, Symbolic links, Compile and link options, System -@subsection Disk Issues - -@itemize @bullet -@item -As mentioned before, disks seeks are a big performance bottleneck. This -problems gets more and more apparent when the data starts to grow so -large that effective caching becomes impossible. For large databases, -where you access data more or less randomly, you can be sure that you -will need at least one disk seek to read and a couple of disk seeks to -write things. To minimize this problem, use disks with low seek times. -@item -Increase the number of available disk spindles (and thereby reduce -the seek overhead) by either symlink files to different disks or striping -the disks. -@table @strong -@item Using symbolic links -This means that you symlink the index and/or data file(s) from the -normal data directory to another disk (that may also be striped). This -makes both the seek and read times better (if the disks are not used for -other things). @xref{Symbolic links}. -@cindex striping, defined -@item Striping -Striping means that you have many disks and put the first block on the -first disk, the second block on the second disk, and the Nth on the -(N mod number_of_disks) disk, and so on. This means if your normal data -size is less than the stripe size (or perfectly aligned) you will get -much better performance. Note that striping is very dependent on the OS -and stripe-size. So benchmark your application with different -stripe-sizes. @xref{Benchmarks}. - -Note that the speed difference for striping is @strong{very} dependent -on the parameters. Depending on how you set the striping parameters and -number of disks you may get a difference in orders of magnitude. Note that -you have to choose to optimize for random or sequential access. -@end table -@item -For reliability you may want to use RAID 0+1 (striping + mirroring), but -in this case you will need 2*N drives to hold N drives of data. This is -probably the best option if you have the money for it! You may, however, -also have to invest in some volume-management software to handle it -efficiently. -@item -A good option is to have semi-important data (that can be regenerated) -on RAID 0 disk while storing really important data (like host information -and logs) on a RAID 0+1 or RAID N disk. RAID N can be a problem if you -have many writes because of the time to update the parity bits. -@item -You may also set the parameters for the file system that the database -uses. One easy change is to mount the file system with the noatime -option. That makes it skip the updating of the last access time in the -inode and by this will avoid some disk seeks. -@item -On Linux, you can get much more performance (up to 100 % under load is -not uncommon) by using hdpram to configure your disk's interface! The -following should be quite good hdparm options for @strong{MySQL} (and -probably many other applications): -@example -hdparm -m 16 -d 1 - -@end example - -Note that the performance/reliability when using the above depends on -your hardware, so we strongly suggest that you test your system -thoroughly after using @code{hdparm}! Please consult the @code{hdparm} -man page for more information! If @code{hdparm} is not used wisely, -filesystem corruption may result. Backup everything before experimenting! -@item -On many operating systems you can mount the disks with the 'async' flag to set the file -system to be updated asynchronously. If your computer is reasonable stable, -this should give you more performance without sacrificing too much reliability. -(This flag is on by default on Linux.) -@item -If you don't need to know when a file was last accessed (which is not -really useful on a database server), you can mount your file systems -with the noatime flag. -@end itemize - -@cindex symbolic links -@cindex links, symbolic -@node Symbolic links, Server parameters, Disk issues, System -@subsection Using Symbolic Links - -You can move tables and databases from the database directory to other -locations and replace them with symbolic links to the new locations. -You might want to do this, for example, to move a database to a file -system with more free space or increase the speed of your system by -spreading your tables to different disk. - -The recommended may to do this, is to just symlink databases to different -disk and only symlink tables as a last resort. -. - -@cindex databases, symbolic links -@menu -* Symbolic links to database:: -* Symbolic links to tables:: -@end menu - -@node Symbolic links to database, Symbolic links to tables, Symbolic links, Symbolic links -@subsubsection Using Symbolic Links for Databases - -The way to symlink a database is to first create a directory on some -disk where you have free space and then create a symlink to it from -the @strong{MySQL} database directory. - -@example -shell> mkdir /dr1/databases/test -shell> ln -s /dr1/databases/test mysqld-datadir -@end example - -@strong{MySQL} doesn't support that you link one directory to multiple -databases. Replacing a database directory with a symbolic link will -work fine as long as you don't make a symbolic link between databases. -Suppose you have a database @code{db1} under the @strong{MySQL} data -directory, and then make a symlink @code{db2} that points to @code{db1}: - -@example -shell> cd /path/to/datadir -shell> ln -s db1 db2 -@end example - -Now, for any table @code{tbl_a} in @code{db1}, there also appears to be -a table @code{tbl_a} in @code{db2}. If one thread updates @code{db1.tbl_a} -and another thread updates @code{db2.tbl_a}, there will be problems. - -If you really need this, you must change the following code in -@file{mysys/mf_format.c}: - -@example -if (flag & 32 || (!lstat(to,&stat_buff) && S_ISLNK(stat_buff.st_mode))) -@end example - -to - -@example -if (1) -@end example - -On Windows you can use internal symbolic links to directories by compiling -@strong{MySQL} with @code{-DUSE_SYMDIR}. This allows you to put different -databases on different disks. @xref{Windows symbolic links}. - -@cindex databases, symbolic links -@node Symbolic links to tables, , Symbolic links to database, Symbolic links -@subsubsection Using Symbolic Links for Tables - -Before @strong{MySQL} 4.0 you should not symlink tables, if you are not -very carefully with them. The problem is that if you run @code{ALTER -TABLE}, @code{REPAIR TABLE} or @code{OPTIMIZE TABLE} on a symlinked -table, the symlinks will be removed and replaced by the original -files. This happens because the above command works by creating a -temporary file in the database directory and when the command is -complete, replace the original file with the temporary file. - -You should not symlink tables on system that doesn't have a fully -working @code{realpath()} call. (At least Linux and Solaris support -@code{realpath()}) - -In @strong{MySQL} 4.0 symlinks is only fully supported for @code{MyISAM} -tables. For other table types you will probably get strange problems -when doing any of the above mentioned commands. - -The handling of symbolic links in @strong{MySQL} 4.0 works the following -way (this is mostly relevant only for @code{MyISAM} tables). - -@itemize @bullet -@item -In the data directory you will always have the table definition file -and the data/index files. -@item -You can symlink the index file and the data file to different directories -independent of the other. -@item -The symlinking can be done from the operating system (if @code{mysqld} is -not running) or with the @code{INDEX/DATA DIRECTORY="path-to-dir"} command -in @code{CREATE TABLE}. @xref{CREATE TABLE}. -@item -@code{myisamchk} will not replace a symlink with the index/file but -work directly on the files the symlinks points to. Any temporary files -will be created in the same directory where the data/index file is. -@item -When you drop a table that is using symlinks, both the symlink and the -file the symlink points to is dropped. This is a good reason to why you -should NOT run @code{mysqld} as root and not allow persons to have write -access to the @strong{MySQL} database directories. -@item -If you rename a table with @code{ALTER TABLE RENAME} and you don't change -database, the symlink in the database directory will be renamed to the new -name and the data/index file will be renamed accordingly. -@item -If you use @code{ALTER TABLE RENAME} to move a table to another database, -then the table will be moved to the other database directory and the old -symlinks and the files they pointed to will be deleted. -@item -If you are not using symlinks you should use the @code{--skip-symlink} -option to @code{mysqld} to ensure that no one can drop or rename a file -outside of the @code{mysqld} data directory. -@end itemize - -Things that are not yet supported: - -@cindex TODO, symlinks -@itemize @bullet -@item -@code{ALTER TABLE} ignores all @code{INDEX/DATA DIRECTORY="path"} options. -@item -@code{CREATE TABLE} doesn't report if the table has symbolic links. -@item -@code{mysqldump} doesn't include the symbolic links information in the output. -@item -@code{BACKUP TABLE} and @code{RESTORE TABLE} doesn't use symbolic links. -@end itemize - -@cindex parameters, server -@cindex @code{mysqld} server, buffer sizes -@cindex buffer sizes, @code{mysqld} server -@cindex startup parameters -@node Server parameters, Table cache, Symbolic links, System -@subsection Tuning Server Parameters - -You can get the default buffer sizes used by the @code{mysqld} server -with this command: - -@example -shell> mysqld --help -@end example - -@cindex @code{mysqld} options -@cindex variables, @code{mysqld} -This command produces a list of all @code{mysqld} options and configurable -variables. The output includes the default values and looks something -like this: - -@example -Possible variables for option --set-variable (-O) are: -back_log current value: 5 -bdb_cache_size current value: 1048540 -binlog_cache_size current_value: 32768 -connect_timeout current value: 5 -delayed_insert_timeout current value: 300 -delayed_insert_limit current value: 100 -delayed_queue_size current value: 1000 -flush_time current value: 0 -interactive_timeout current value: 28800 -join_buffer_size current value: 131072 -key_buffer_size current value: 1048540 -lower_case_table_names current value: 0 -long_query_time current value: 10 -max_allowed_packet current value: 1048576 -max_binlog_cache_size current_value: 4294967295 -max_connections current value: 100 -max_connect_errors current value: 10 -max_delayed_threads current value: 20 -max_heap_table_size current value: 16777216 -max_join_size current value: 4294967295 -max_sort_length current value: 1024 -max_tmp_tables current value: 32 -max_write_lock_count current value: 4294967295 -myisam_sort_buffer_size current value: 8388608 -net_buffer_length current value: 16384 -net_retry_count current value: 10 -net_read_timeout current value: 30 -net_write_timeout current value: 60 -query_buffer_size current value: 0 -record_buffer current value: 131072 -slow_launch_time current value: 2 -sort_buffer current value: 2097116 -table_cache current value: 64 -thread_concurrency current value: 10 -tmp_table_size current value: 1048576 -thread_stack current value: 131072 -wait_timeout current value: 28800 -@end example - -If there is a @code{mysqld} server currently running, you can see what -values it actually is using for the variables by executing this command: - -@example -shell> mysqladmin variables -@end example - -You can find a full description for all variables in the @code{SHOW VARIABLES} -section in this manual. @xref{SHOW VARIABLES}. - -You can also see some statistics from a running server by issuing the command -@code{SHOW STATUS}. @xref{SHOW STATUS}. - -@strong{MySQL} uses algorithms that are very scalable, so you can usually -run with very little memory. If you, however, give @strong{MySQL} more -memory, you will normally also get better performance. - -When tuning a @strong{MySQL} server, the two most important variables to use -are @code{key_buffer_size} and @code{table_cache}. You should first feel -confident that you have these right before trying to change any of the -other variables. - -If you have much memory (>=256M) and many tables and want maximum performance -with a moderate number of clients, you should use something like this: - -@example -shell> safe_mysqld -O key_buffer=64M -O table_cache=256 \ - -O sort_buffer=4M -O record_buffer=1M & -@end example - -If you have only 128M and only a few tables, but you still do a lot of -sorting, you can use something like: - -@example -shell> safe_mysqld -O key_buffer=16M -O sort_buffer=1M -@end example - -If you have little memory and lots of connections, use something like this: - -@example -shell> safe_mysqld -O key_buffer=512k -O sort_buffer=100k \ - -O record_buffer=100k & -@end example - -or even: - -@example -shell> safe_mysqld -O key_buffer=512k -O sort_buffer=16k \ - -O table_cache=32 -O record_buffer=8k -O net_buffer=1K & -@end example - -When you have installed @strong{MySQL}, the @file{support-files} directory will -contain some different @code{my.cnf} example files, @file{my-huge.cnf}, -@file{my-large.cnf}, @file{my-medium.cnf}, and @file{my-small.cnf}, you can -use as a base to optimize your system. - -If there are very many connections, ``swapping problems'' may occur unless -@code{mysqld} has been configured to use very little memory for each -connection. @code{mysqld} performs better if you have enough memory for all -connections, of course. - -Note that if you change an option to @code{mysqld}, it remains in effect only -for that instance of the server. - -To see the effects of a parameter change, do something like this: - -@example -shell> mysqld -O key_buffer=32m --help -@end example - -Make sure that the @code{--help} option is last; otherwise, the effect of any -options listed after it on the command line will not be reflected in the -output. - -@cindex tables, opening -@cindex tables, closing -@cindex opening, tables -@cindex closing, tables -@cindex table cache -@findex table_cache -@node Table cache, Creating many tables, Server parameters, System -@subsection How MySQL Opens and Closes Tables - -@code{table_cache}, @code{max_connections}, and @code{max_tmp_tables} -affect the maximum number of files the server keeps open. If you -increase one or both of these values, you may run up against a limit -imposed by your operating system on the per-process number of open file -descriptors. However, you can increase the limit on many systems. -Consult your OS documentation to find out how to do this, because the -method for changing the limit varies widely from system to system. - -@code{table_cache} is related to @code{max_connections}. For example, -for 200 concurrent running connections, you should have a table cache of -at least @code{200 * n}, where @code{n} is the maximum number of tables -in a join. You also need to reserve some extra file descriptors for -temporary tables and files. - -The cache of open tables can grow to a maximum of @code{table_cache} -(default 64; this can be changed with the @code{-O table_cache=#} -option to @code{mysqld}). A table is never closed, except when the -cache is full and another thread tries to open a table or if you use -@code{mysqladmin refresh} or @code{mysqladmin flush-tables}. - -When the table cache fills up, the server uses the following procedure -to locate a cache entry to use: - -@itemize @bullet -@item -Tables that are not currently in use are released, in least-recently-used -order. - -@item -If the cache is full and no tables can be released, but a new table needs to -be opened, the cache is temporarily extended as necessary. - -@item -If the cache is in a temporarily-extended state and a table goes from in-use -to not-in-use state, the table is closed and released from the cache. -@end itemize - -A table is opened for each concurrent access. This means that -if you have two threads accessing the same table or access the table -twice in the same query (with @code{AS}) the table needs to be opened twice. -The first open of any table takes two file descriptors; each additional -use of the table takes only one file descriptor. The extra descriptor -for the first open is used for the index file; this descriptor is shared -among all threads. - -You can check if your table cache is too small by checking the mysqld -variable @code{opened_tables}. If this is quite big, even if you -haven't done a lot of @code{FLUSH TABLES}, you should increase your table -cache. @xref{SHOW STATUS}. - -@cindex tables, too many -@node Creating many tables, Open tables, Table cache, System -@subsection Drawbacks to Creating Large Numbers of Tables in the Same Database - -If you have many files in a directory, open, close, and create operations will -be slow. If you execute @code{SELECT} statements on many different tables, -there will be a little overhead when the table cache is full, because for -every table that has to be opened, another must be closed. You can reduce -this overhead by making the table cache larger. - -@cindex tables, open -@cindex open tables -@node Open tables, Memory use, Creating many tables, System -@subsection Why So Many Open tables? - -When you run @code{mysqladmin status}, you'll see something like this: - -@example -Uptime: 426 Running threads: 1 Questions: 11082 Reloads: 1 Open tables: 12 -@end example - -This can be somewhat perplexing if you only have 6 tables. - -@strong{MySQL} is multithreaded, so it may have many queries on the same -table simultaneously. To minimize the problem with two threads having -different states on the same file, the table is opened independently by -each concurrent thread. This takes some memory and one extra file -descriptor for the data file. The index file descriptor is shared -between all threads. - -@cindex memory use -@node Memory use, Internal locking, Open tables, System -@subsection How MySQL Uses Memory - -The list below indicates some of the ways that the @code{mysqld} server -uses memory. Where applicable, the name of the server variable relevant -to the memory use is given: - -@itemize @bullet -@item -The key buffer (variable @code{key_buffer_size}) is shared by all -threads; Other buffers used by the server are allocated as -needed. @xref{Server parameters}. - -@item -Each connection uses some thread-specific space: A stack (default 64K, -variable @code{thread_stack}), a connection buffer (variable -@code{net_buffer_length}), and a result buffer (variable -@code{net_buffer_length}). The connection buffer and result buffer are -dynamically enlarged up to @code{max_allowed_packet} when needed. When -a query is running, a copy of the current query string is also allocated. - -@item -All threads share the same base memory. - -@item -Only the compressed ISAM / MyISAM tables are memory mapped. This is -because the 32-bit memory space of 4GB is not large enough for most -big tables. When systems with a 64-bit address space become more -common we may add general support for memory mapping. - -@item -Each request doing a sequential scan over a table allocates a read buffer -(variable @code{record_buffer}). - -@item -All joins are done in one pass, and most joins can be done without even -using a temporary table. Most temporary tables are memory-based (HEAP) -tables. Temporary tables with a big record length (calculated as the -sum of all column lengths) or that contain @code{BLOB} columns are -stored on disk. - -One problem in @strong{MySQL} versions before Version 3.23.2 is that if a HEAP table -exceeds the size of @code{tmp_table_size}, you get the error @code{The -table tbl_name is full}. In newer versions this is handled by -automatically changing the in-memory (HEAP) table to a disk-based -(MyISAM) table as necessary. To work around this problem, you can -increase the temporary table size by setting the @code{tmp_table_size} -option to @code{mysqld}, or by setting the SQL option -@code{SQL_BIG_TABLES} in the client program. @xref{SET OPTION, , -@code{SET OPTION}}. In @strong{MySQL} Version 3.20, the maximum size of the -temporary table was @code{record_buffer*16}, so if you are using this -version, you have to increase the value of @code{record_buffer}. You can -also start @code{mysqld} with the @code{--big-tables} option to always -store temporary tables on disk. However, this will affect the speed of -many complicated queries. - -@item -Most requests doing a sort allocates a sort buffer and 0-2 temporary -files depending on the result set size. @xref{Temporary files}. - -@item -Almost all parsing and calculating is done in a local memory store. No -memory overhead is needed for small items and the normal slow memory -allocation and freeing is avoided. Memory is allocated only for -unexpectedly large strings (this is done with @code{malloc()} and -@code{free()}). - -@item -Each index file is opened once and the data file is opened once for each -concurrently running thread. For each concurrent thread, a table structure, -column structures for each column, and a buffer of size @code{3 * n} is -allocated (where @code{n} is the maximum row length, not counting @code{BLOB} -columns). A @code{BLOB} uses 5 to 8 bytes plus the length of the @code{BLOB} -data. The @code{ISAM}/@code{MyISAM} table handlers will use one extra row -buffer for internal usage. - -@item -For each table having @code{BLOB} columns, a buffer is enlarged dynamically -to read in larger @code{BLOB} values. If you scan a table, a buffer as large -as the largest @code{BLOB} value is allocated. - -@item -Table handlers for all in-use tables are saved in a cache and managed as a -FIFO. Normally the cache has 64 entries. If a table has been used by two -running threads at the same time, the cache contains two entries for the -table. @xref{Table cache}. - -@item -A @code{mysqladmin flush-tables} command closes all tables that are not in -use and marks all in-use tables to be closed when the currently executing -thread finishes. This will effectively free most in-use memory. -@end itemize - -@code{ps} and other system status programs may report that @code{mysqld} -uses a lot of memory. This may be caused by thread-stacks on different -memory addresses. For example, the Solaris version of @code{ps} counts -the unused memory between stacks as used memory. You can verify this by -checking available swap with @code{swap -s}. We have tested -@code{mysqld} with commercial memory-leakage detectors, so there should -be no memory leaks. - -@cindex internal locking -@cindex locking, tables -@cindex tables, locking -@node Internal locking, Table locking, Memory use, System -@subsection How MySQL Locks Tables - -You can find a discussion about different locking methods in the appendix. -@xref{Locking methods}. - -All locking in @strong{MySQL} is deadlock-free. This is managed by always -requesting all needed locks at once at the beginning of a query and always -locking the tables in the same order. - -The locking method @strong{MySQL} uses for @code{WRITE} locks works as follows: - -@itemize @bullet -@item -If there are no locks on the table, put a write lock on it. -@item -Otherwise, put the lock request in the write lock queue. -@end itemize - -The locking method @strong{MySQL} uses for @code{READ} locks works as follows: - -@itemize @bullet -@item -If there are no write locks on the table, put a read lock on it. -@item -Otherwise, put the lock request in the read lock queue. -@end itemize - -When a lock is released, the lock is made available to the threads -in the write lock queue, then to the threads in the read lock queue. - -This means that if you have many updates on a table, @code{SELECT} -statements will wait until there are no more updates. - -To work around this for the case where you want to do many @code{INSERT} and -@code{SELECT} operations on a table, you can insert rows in a temporary -table and update the real table with the records from the temporary table -once in a while. - -This can be done with the following code: -@example -mysql> LOCK TABLES real_table WRITE, insert_table WRITE; -mysql> insert into real_table select * from insert_table; -mysql> TRUNCATE TABLE insert_table; -mysql> UNLOCK TABLES; -@end example - -You can use the @code{LOW_PRIORITY} options with @code{INSERT}, -@code{UPDATE} or @code{DELETE} or @code{HIGH_PRIORITY} with -@code{SELECT} if you want to prioritize retrieval in some specific -cases. You can also start @code{mysqld} with @code{--low-priority-updates} -to get the same behaveour. - -Using @code{SQL_BUFFER_RESULT} can also help making table locks shorter. -@xref{SELECT}. - -You could also change the locking code in @file{mysys/thr_lock.c} to use a -single queue. In this case, write locks and read locks would have the same -priority, which might help some applications. - -@cindex problems, table locking -@node Table locking, DNS, Internal locking, System -@subsection Table Locking Issues - -The table locking code in @strong{MySQL} is deadlock free. - -@strong{MySQL} uses table locking (instead of row locking or column -locking) on all table types, except @code{BDB} tables, to achieve a very -high lock speed. For large tables, table locking is MUCH better than -row locking for most applications, but there are, of course, some -pitfalls. - -For @code{BDB} and @code{InnoDB} tables, @strong{MySQL} only uses table -locking if you explicitely lock the table with @code{LOCK TABLES} or -execute a command that will modify every row in the table, like -@code{ALTER TABLE}. For these table types we recommend you to not use -@code{LOCK TABLES} at all. - -In @strong{MySQL} Version 3.23.7 and above, you can insert rows into -@code{MyISAM} tables at the same time other threads are reading from the -table. Note that currently this only works if there are no holes after -deleted rows in the table at the time the insert is made. When all holes -has been filled with new data, concurrent inserts will automatically be -enabled again. - -Table locking enables many threads to read from a table at the same -time, but if a thread wants to write to a table, it must first get -exclusive access. During the update, all other threads that want to -access this particular table will wait until the update is ready. - -As updates on tables normally are considered to be more important than -@code{SELECT}, all statements that update a table have higher priority -than statements that retrieve information from a table. This should -ensure that updates are not 'starved' because one issues a lot of heavy -queries against a specific table. (You can change this by using -LOW_PRIORITY with the statement that does the update or -@code{HIGH_PRIORITY} with the @code{SELECT} statement.) - -Starting from @strong{MySQL} Version 3.23.7 one can use the -@code{max_write_lock_count} variable to force @strong{MySQL} to -temporary give all @code{SELECT} statements, that wait for a table, a -higher priority after a specific number of inserts on a table. - -Table locking is, however, not very good under the following senario: - -@itemize @bullet -@item -A client issues a @code{SELECT} that takes a long time to run. -@item -Another client then issues an @code{UPDATE} on a used table. This client -will wait until the @code{SELECT} is finished. -@item -Another client issues another @code{SELECT} statement on the same table. As -@code{UPDATE} has higher priority than @code{SELECT}, this @code{SELECT} -will wait for the @code{UPDATE} to finish. It will also wait for the first -@code{SELECT} to finish! -@item -A thread is waiting for something like @code{full disk}, in which case all -threads that wants to access the problem table will also be put in a waiting -state until more disk space is made available. -@end itemize - -Some possible solutions to this problem are: - -@itemize @bullet -@item -Try to get the @code{SELECT} statements to run faster. You may have to create -some summary tables to do this. - -@item -Start @code{mysqld} with @code{--low-priority-updates}. This will give -all statements that update (modify) a table lower priority than a @code{SELECT} -statement. In this case the last @code{SELECT} statement in the previous -scenario would execute before the @code{INSERT} statement. - -@item -You can give a specific @code{INSERT}, @code{UPDATE}, or @code{DELETE} -statement lower priority with the @code{LOW_PRIORITY} attribute. - -@item -Start @code{mysqld} with a low value for @strong{max_write_lock_count} to give -@code{READ} locks after a certain number of @code{WRITE} locks. - -@item -You can specify that all updates from a specific thread should be done with -low priority by using the SQL command: @code{SET SQL_LOW_PRIORITY_UPDATES=1}. -@xref{SET OPTION, , @code{SET OPTION}}. - -@item -You can specify that a specific @code{SELECT} is very important with the -@code{HIGH_PRIORITY} attribute. @xref{SELECT, , @code{SELECT}}. - -@item -If you have problems with @code{INSERT} combined with @code{SELECT}, -switch to use the new @code{MyISAM} tables as these support concurrent -@code{SELECT}s and @code{INSERT}s. - -@item -If you mainly mix @code{INSERT} and @code{SELECT} statements, the -@code{DELAYED} attribute to @code{INSERT} will probably solve your problems. -@xref{INSERT, , @code{INSERT}}. - -@item -If you have problems with @code{SELECT} and @code{DELETE}, the @code{LIMIT} -option to @code{DELETE} may help. @xref{DELETE, , @code{DELETE}}. -@end itemize - -@cindex DNS -@cindex hostname caching -@node DNS, , Table locking, System -@subsection How MySQL uses DNS - -When a new thread connects to @code{mysqld}, @code{mysqld} will span a -new thread to handle the request. This thread will first check if the -hostname is in the hostname cache. If not the thread will call -@code{gethostbyaddr_r()} and @code{gethostbyname_r()} to resolve the -hostname. - -If the operating system doesn't support the above thread-safe calls, the -thread will lock a mutex and call @code{gethostbyaddr()} and -@code{gethostbyname()} instead. Note that in this case no other thread -can resolve other hostnames that is not in the hostname cache until the -first thread is ready. - -You can disable DNS host lookup by starting @code{mysqld} with -@code{--skip-name-resolve}. In this case you can however only use IP -names in the @strong{MySQL} privilege tables. - -If you have a very slow DNS and many hosts, you can get more performance by -either disabling DNS lookop with @code{--skip-name-resolve} or by -increasing the @code{HOST_CACHE_SIZE} define (default: 128) and recompile -@code{mysqld}. - -You can disable the hostname cache with @code{--skip-host-cache}. You -can clear the hostname cache with @code{FLUSH HOSTS} or @code{mysqladmin -flush-hosts}. - -If you don't want to allow connections over @code{TCP/IP}, you can do this -by starting @code{mysqld} with @code{--skip-networking}. - -@cindex data, size -@cindex reducing, data size -@cindex storage space, minimizing -@cindex tables, improving performance -@cindex performance, improving -@node Data size, MySQL indexes, System, Performance -@section Get Your Data as Small as Possible - -One of the most basic optimization is to get your data (and indexes) to -take as little space on the disk (and in memory) as possible. This can -give huge improvements because disk reads are faster and normally less -main memory will be used. Indexing also takes less resources if -done on smaller columns. - -@strong{MySQL} supports a lot of different table types and row formats. -Choosing the right table format may give you a big performance gain. -@xref{Table types}. - -You can get better performance on a table and minimize storage space -using the techniques listed below: - -@itemize @bullet -@item -Use the most efficient (smallest) types possible. @strong{MySQL} has -many specialized types that save disk space and memory. -@item -Use the smaller integer types if possible to get smaller tables. For -example, @code{MEDIUMINT} is often better than @code{INT}. -@item -Declare columns to be @code{NOT NULL} if possible. It makes everything -faster and you save one bit per column. Note that if you really need -@code{NULL} in your application you should definitely use it. Just avoid -having it on all columns by default. -@item -If you don't have any variable-length columns (@code{VARCHAR}, -@code{TEXT}, or @code{BLOB} columns), a fixed-size record format is -used. This is faster but unfortunately may waste some space. -@xref{MyISAM table formats}. -@item -The primary index of a table should be as short as possible. This makes -identification of one row easy and efficient. -@item -For each table, you have to decide which storage/index method to -use. @xref{Table types}. -@item -Only create the indexes that you really need. Indexes are good for -retrieval but bad when you need to store things fast. If you mostly -access a table by searching on a combination of columns, make an index -on them. The first index part should be the most used column. If you are -ALWAYS using many columns, you should use the column with more duplicates -first to get better compression of the index. -@item -If it's very likely that a column has a unique prefix on the first number -of characters, it's better to only index this prefix. @strong{MySQL} -supports an index on a part of a character column. Shorter indexes are -faster not only because they take less disk space but also because they -will give you more hits in the index cache and thus fewer disk -seeks. @xref{Server parameters}. -@item -In some circumstances it can be beneficial to split into two a table that is -scanned very often. This is especially true if it is a dynamic -format table and it is possible to use a smaller static format table that -can be used to find the relevant rows when scanning the table. -@end itemize - -@cindex indexes, uses for -@node MySQL indexes, Query Speed, Data size, Performance -@section How MySQL Uses Indexes - -Indexes are used to find rows with a specific value of one column -fast. Without an index @strong{MySQL} has to start with the first record -and then read through the whole table until it finds the relevant -rows. The bigger the table, the more this costs. If the table has an index -for the columns in question, @strong{MySQL} can quickly get a position to -seek to in the middle of the data file without having to look at all the -data. If a table has 1000 rows, this is at least 100 times faster than -reading sequentially. Note that if you need to access almost all 1000 -rows it is faster to read sequentially because we then avoid disk seeks. - -All @strong{MySQL} indexes (@code{PRIMARY}, @code{UNIQUE}, and -@code{INDEX}) are stored in B-trees. Strings are automatically prefix- -and end-space compressed. @xref{CREATE INDEX, , @code{CREATE INDEX}}. - -Indexes are used to: -@itemize @bullet -@item -Quickly find the rows that match a @code{WHERE} clause. - -@item -Retrieve rows from other tables when performing joins. - -@item -Find the @code{MAX()} or @code{MIN()} value for a specific indexed -column. This is optimized by a preprocessor that checks if you are -using @code{WHERE} key_part_# = constant on all key parts < N. In this case -@strong{MySQL} will do a single key lookup and replace the @code{MIN()} -expression with a constant. If all expressions are replaced with -constants, the query will return at once: - -@example -SELECT MIN(key_part2),MAX(key_part2) FROM table_name where key_part1=10 -@end example - -@item -Sort or group a table if the sorting or grouping is done on a leftmost -prefix of a usable key (for example, @code{ORDER BY key_part_1,key_part_2 }). The -key is read in reverse order if all key parts are followed by @code{DESC}. - -The index can also be used even if the @code{ORDER BY} doesn't match the index -exactly, as long as all the unused index parts and all the extra -are @code{ORDER BY} columns are constants in the @code{WHERE} clause. The -following queries will use the index to resolve the @code{ORDER BY} part: - -@example -SELECT * FROM foo ORDER BY key_part1,key_part2,key_part3; -SELECT * FROM foo WHERE column=constant ORDER BY column, key_part1; -SELECT * FROM foo WHERE key_part1=const GROUP BY key_part2; -@end example - -@item -In some cases a query can be optimized to retrieve values without -consulting the data file. If all used columns for some table are numeric -and form a leftmost prefix for some key, the values may be retrieved -from the index tree for greater speed: - -@example -SELECT key_part3 FROM table_name WHERE key_part1=1 -@end example - -@end itemize - -Suppose you issue the following @code{SELECT} statement: - -@example -mysql> SELECT * FROM tbl_name WHERE col1=val1 AND col2=val2; -@end example - -If a multiple-column index exists on @code{col1} and @code{col2}, the -appropriate rows can be fetched directly. If separate single-column -indexes exist on @code{col1} and @code{col2}, the optimizer tries to -find the most restrictive index by deciding which index will find fewer -rows and using that index to fetch the rows. - -@cindex indexes, leftmost prefix of -@cindex leftmost prefix of indexes -If the table has a multiple-column index, any leftmost prefix of the -index can be used by the optimizer to find rows. For example, if you -have a three-column index on @code{(col1,col2,col3)}, you have indexed -search capabilities on @code{(col1)}, @code{(col1,col2)}, and -@code{(col1,col2,col3)}. - -@strong{MySQL} can't use a partial index if the columns don't form a -leftmost prefix of the index. Suppose you have the @code{SELECT} -statements shown below: - -@example -mysql> SELECT * FROM tbl_name WHERE col1=val1; -mysql> SELECT * FROM tbl_name WHERE col2=val2; -mysql> SELECT * FROM tbl_name WHERE col2=val2 AND col3=val3; -@end example - -If an index exists on @code{(col1,col2,col3)}, only the first query -shown above uses the index. The second and third queries do involve -indexed columns, but @code{(col2)} and @code{(col2,col3)} are not -leftmost prefixes of @code{(col1,col2,col3)}. - -@findex LIKE, and indexes -@findex LIKE, and wildcards -@cindex indexes, and @code{LIKE} -@cindex wildcards, and @code{LIKE} -@strong{MySQL} also uses indexes for @code{LIKE} comparisons if the argument -to @code{LIKE} is a constant string that doesn't start with a wild-card -character. For example, the following @code{SELECT} statements use indexes: - -@example -mysql> select * from tbl_name where key_col LIKE "Patrick%"; -mysql> select * from tbl_name where key_col LIKE "Pat%_ck%"; -@end example - -In the first statement, only rows with @code{"Patrick" <= key_col < -"Patricl"} are considered. In the second statement, only rows with -@code{"Pat" <= key_col < "Pau"} are considered. - -The following @code{SELECT} statements will not use indexes: -@example -mysql> select * from tbl_name where key_col LIKE "%Patrick%"; -mysql> select * from tbl_name where key_col LIKE other_col; -@end example - -In the first statement, the @code{LIKE} value begins with a wild-card -character. In the second statement, the @code{LIKE} value is not a -constant. - -@findex IS NULL, and indexes -@cindex indexes, and @code{IS NULL} -Searching using @code{column_name IS NULL} will use indexes if column_name -is an index. - -@strong{MySQL} normally uses the index that finds the least number of rows. An -index is used for columns that you compare with the following operators: -@code{=}, @code{>}, @code{>=}, @code{<}, @code{<=}, @code{BETWEEN}, and a -@code{LIKE} with a non-wild-card prefix like @code{'something%'}. - -Any index that doesn't span all @code{AND} levels in the @code{WHERE} clause -is not used to optimize the query. In other words: To be able to use an -index, a prefix of the index must be used in every @code{AND} group. - -The following @code{WHERE} clauses use indexes: -@example -... WHERE index_part1=1 AND index_part2=2 AND other_column=3 -... WHERE index=1 OR A=10 AND index=2 /* index = 1 OR index = 2 */ -... WHERE index_part1='hello' AND index_part_3=5 - /* optimized like "index_part1='hello'" */ -... WHERE index1=1 and index2=2 or index1=3 and index3=3; - /* Can use index on index1 but not on index2 or index 3 */ -@end example - -These @code{WHERE} clauses do @strong{NOT} use indexes: -@example -... WHERE index_part2=1 AND index_part3=2 /* index_part_1 is not used */ -... WHERE index=1 OR A=10 /* Index is not used in both AND parts */ -... WHERE index_part1=1 OR index_part2=10 /* No index spans all rows */ -@end example - -Note that in some cases @strong{MySQL} will not use an index, even if one -would be available. Some of the cases where this happens are: - -@itemize @bullet -@item -If the use of the index would require @strong{MySQL} to access more -than 30 % of the rows in the table. (In this case a table scan is -probably much faster, as this will require us to do much fewer seeks). -Note that if such a query uses @code{LIMIT} to only retrieve -part of the rows, @strong{MySQL} will use an index anyway, as it can -much more quickly find the few rows to return in the result. -@end itemize - -@cindex queries, speed of -@cindex permission checks, effect on speed -@cindex speed, of queries -@node Query Speed, Tips, MySQL indexes, Performance -@section Speed of Queries that Access or Update Data - -First, one thing that affects all queries: The more complex permission -system setup you have, the more overhead you get. - -If you do not have any @code{GRANT} statements done, @strong{MySQL} will -optimize the permission checking somewhat. So if you have a very high -volume it may be worth the time to avoid grants. Otherwise more -permission check results in a larger overhead. - -If your problem is with some explicit @strong{MySQL} function, you can -always time this in the @strong{MySQL} client: - -@example -mysql> select benchmark(1000000,1+1); -+------------------------+ -| benchmark(1000000,1+1) | -+------------------------+ -| 0 | -+------------------------+ -1 row in set (0.32 sec) -@end example - -The above shows that @strong{MySQL} can execute 1,000,000 @code{+} -expressions in 0.32 seconds on a @code{PentiumII 400MHz}. - -All @strong{MySQL} functions should be very optimized, but there may be -some exceptions, and the @code{benchmark(loop_count,expression)} is a -great tool to find out if this is a problem with your query. - -@menu -* Estimating performance:: Estimating query performance -* SELECT speed:: Speed of @code{SELECT} queries -* Where optimizations:: How MySQL optimizes @code{WHERE} clauses -* DISTINCT optimization:: How MySQL Optimizes @code{DISTINCT} -* LEFT JOIN optimization:: How MySQL optimizes @code{LEFT JOIN} -* LIMIT optimization:: How MySQL optimizes @code{LIMIT} -* Insert speed:: Speed of @code{INSERT} queries -* Update speed:: Speed of @code{UPDATE} queries -* Delete speed:: Speed of @code{DELETE} queries -@end menu - -@cindex estimating, query performance -@cindex queries, estimating performance -@cindex performance, estimating -@node Estimating performance, SELECT speed, Query Speed, Query Speed -@subsection Estimating Query Performance - -In most cases you can estimate the performance by counting disk seeks. -For small tables, you can usually find the row in 1 disk seek (as the -index is probably cached). For bigger tables, you can estimate that -(using B++ tree indexes) you will need: @code{log(row_count) / -log(index_block_length / 3 * 2 / (index_length + data_pointer_length)) + -1} seeks to find a row. - -In @strong{MySQL} an index block is usually 1024 bytes and the data -pointer is usually 4 bytes. A 500,000 row table with an -index length of 3 (medium integer) gives you: -@code{log(500,000)/log(1024/3*2/(3+4)) + 1} = 4 seeks. - -As the above index would require about 500,000 * 7 * 3/2 = 5.2M, -(assuming that the index buffers are filled to 2/3, which is typical) -you will probably have much of the index in memory and you will probably -only need 1-2 calls to read data from the OS to find the row. - -For writes, however, you will need 4 seek requests (as above) to find -where to place the new index and normally 2 seeks to update the index -and write the row. - -Note that the above doesn't mean that your application will slowly -degenerate by N log N! As long as everything is cached by the OS or SQL -server things will only go marginally slower while the table gets -bigger. After the data gets too big to be cached, things will start to -go much slower until your applications is only bound by disk-seeks -(which increase by N log N). To avoid this, increase the index cache as -the data grows. @xref{Server parameters}. - -@cindex speed, of queries -@findex SELECT speed - -@node SELECT speed, Where optimizations, Estimating performance, Query Speed -@subsection Speed of @code{SELECT} Queries - -In general, when you want to make a slow @code{SELECT ... WHERE} faster, the -first thing to check is whether or not you can add an index. @xref{MySQL -indexes, , @strong{MySQL} indexes}. All references between different tables -should usually be done with indexes. You can use the @code{EXPLAIN} command -to determine which indexes are used for a @code{SELECT}. -@xref{EXPLAIN, , @code{EXPLAIN}}. - -Some general tips: - -@itemize @bullet -@item -To help @strong{MySQL} optimize queries better, run @code{myisamchk ---analyze} on a table after it has been loaded with relevant data. This -updates a value for each index part that indicates the average number of -rows that have the same value. (For unique indexes, this is always 1, -of course.). @strong{MySQL} will use this to decide which index to -choose when you connect two tables with 'a non-constant expression'. -You can check the result from the @code{analyze} run by doing @code{SHOW -INDEX FROM table_name} and examining the @code{Cardinality} column. - -@item -To sort an index and data according to an index, use @code{myisamchk ---sort-index --sort-records=1} (if you want to sort on index 1). If you -have a unique index from which you want to read all records in order -according to that index, this is a good way to make that faster. Note, -however, that this sorting isn't written optimally and will take a long -time for a large table! -@end itemize - -@cindex optimizations -@findex WHERE -@node Where optimizations, DISTINCT optimization, SELECT speed, Query Speed -@subsection How MySQL Optimizes @code{WHERE} Clauses - -The @code{WHERE} optimizations are put in the @code{SELECT} part here because -they are mostly used with @code{SELECT}, but the same optimizations apply for -@code{WHERE} in @code{DELETE} and @code{UPDATE} statements. - -Also note that this section is incomplete. @strong{MySQL} does many -optimizations, and we have not had time to document them all. - -Some of the optimizations performed by @strong{MySQL} are listed below: - -@itemize @bullet -@item -Removal of unnecessary parentheses: -@example - ((a AND b) AND c OR (((a AND b) AND (c AND d)))) --> (a AND b AND c) OR (a AND b AND c AND d) -@end example -@item -Constant folding: -@example - (a b>5 AND b=c AND a=5 -@end example -@item -Constant condition removal (needed because of constant folding): -@example - (B>=5 AND B=5) OR (B=6 AND 5=5) OR (B=7 AND 5=6) --> B=5 OR B=6 -@end example -@item -Constant expressions used by indexes are evaluated only once. -@item -@code{COUNT(*)} on a single table without a @code{WHERE} is retrieved -directly from the table information. This is also done for any @code{NOT NULL} -expression when used with only one table. -@item -Early detection of invalid constant expressions. @strong{MySQL} quickly -detects that some @code{SELECT} statements are impossible and returns no rows. -@item -@code{HAVING} is merged with @code{WHERE} if you don't use @code{GROUP BY} -or group functions (@code{COUNT()}, @code{MIN()}...). -@item -For each sub-join, a simpler @code{WHERE} is constructed to get a fast -@code{WHERE} evaluation for each sub-join and also to skip records as -soon as possible. -@cindex constant table -@cindex tables, constant -@item -All constant tables are read first, before any other tables in the query. -A constant table is: -@itemize @minus -@item -An empty table or a table with 1 row. -@item -A table that is used with a @code{WHERE} clause on a @code{UNIQUE} -index, or a @code{PRIMARY KEY}, where all index parts are used with constant -expressions and the index parts are defined as @code{NOT NULL}. -@end itemize -All the following tables are used as constant tables: -@example -mysql> SELECT * FROM t WHERE primary_key=1; -mysql> SELECT * FROM t1,t2 - WHERE t1.primary_key=1 AND t2.primary_key=t1.id; -@end example - -@item -The best join combination to join the tables is found by trying all -possibilities. If all columns in @code{ORDER BY} and in @code{GROUP -BY} come from the same table, then this table is preferred first when -joining. -@item -If there is an @code{ORDER BY} clause and a different @code{GROUP BY} -clause, or if the @code{ORDER BY} or @code{GROUP BY} contains columns -from tables other than the first table in the join queue, a temporary -table is created. -@item -If you use @code{SQL_SMALL_RESULT}, @strong{MySQL} will use an in-memory -temporary table. -@item -Each table index is queried, and the best index that spans fewer than 30% of -the rows is used. If no such index can be found, a quick table scan is used. -@item -In some cases, @strong{MySQL} can read rows from the index without even -consulting the data file. If all columns used from the index are numeric, -then only the index tree is used to resolve the query. -@item -Before each record is output, those that do not match the @code{HAVING} clause -are skipped. -@end itemize - -Some examples of queries that are very fast: - -@example -mysql> SELECT COUNT(*) FROM tbl_name; -mysql> SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name; -mysql> SELECT MAX(key_part2) FROM tbl_name - WHERE key_part_1=constant; -mysql> SELECT ... FROM tbl_name - ORDER BY key_part1,key_part2,... LIMIT 10; -mysql> SELECT ... FROM tbl_name - ORDER BY key_part1 DESC,key_part2 DESC,... LIMIT 10; -@end example - -The following queries are resolved using only the index tree (assuming -the indexed columns are numeric): - -@example -mysql> SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val; -mysql> SELECT COUNT(*) FROM tbl_name - WHERE key_part1=val1 AND key_part2=val2; -mysql> SELECT key_part2 FROM tbl_name GROUP BY key_part1; -@end example - -The following queries use indexing to retrieve the rows in sorted -order without a separate sorting pass: - -@example -mysql> SELECT ... FROM tbl_name ORDER BY key_part1,key_part2,... ; -mysql> SELECT ... FROM tbl_name ORDER BY key_part1 DESC,key_part2 DESC,... ; -@end example - -@findex DISTINCT -@cindex optimizing, DISTINCT -@node DISTINCT optimization, LEFT JOIN optimization, Where optimizations, Query Speed -@subsection How MySQL Optimizes @code{DISTINCT} - -@code{DISTINCT} is converted to a @code{GROUP BY} on all columns, -@code{DISTINCT} combined with @code{ORDER BY} will in many cases also -need a temporary table. - -When combining @code{LIMIT #} with @code{DISTINCT}, @strong{MySQL} will stop -as soon as it finds @code{#} unique rows. - -If you don't use columns from all used tables, @strong{MySQL} will stop -the scanning of the not used tables as soon as it has found the first match. - -@example -SELECT DISTINCT t1.a FROM t1,t2 where t1.a=t2.a; -@end example - -In the case, assuming t1 is used before t2 (check with @code{EXPLAIN}), then -@strong{MySQL} will stop reading from t2 (for that particular row in t1) -when the first row in t2 is found. - -@findex LEFT JOIN -@cindex optimizing, LEFT JOIN -@node LEFT JOIN optimization, LIMIT optimization, DISTINCT optimization, Query Speed -@subsection How MySQL Optimizes @code{LEFT JOIN} and @code{RIGHT JOIN} - -@code{A LEFT JOIN B} in @strong{MySQL} is implemented as follows: - -@itemize @bullet -@item -The table @code{B} is set to be dependent on table @code{A} and all tables -that @code{A} is dependent on. -@item -The table @code{A} is set to be dependent on all tables (except @code{B}) -that are used in the @code{LEFT JOIN} condition. -@item -All @code{LEFT JOIN} conditions are moved to the @code{WHERE} clause. -@item -All standard join optimizations are done, with the exception that a table is -always read after all tables it is dependent on. If there is a circular -dependence then @strong{MySQL} will issue an error. -@item -All standard @code{WHERE} optimizations are done. -@item -If there is a row in @code{A} that matches the @code{WHERE} clause, but there -wasn't any row in @code{B} that matched the @code{LEFT JOIN} condition, -then an extra @code{B} row is generated with all columns set to @code{NULL}. -@item -If you use @code{LEFT JOIN} to find rows that don't exist in some -table and you have the following test: @code{column_name IS NULL} in the -@code{WHERE} part, where column_name is a column that is declared as -@code{NOT NULL}, then @strong{MySQL} will stop searching after more rows -(for a particular key combination) after it has found one row that -matches the @code{LEFT JOIN} condition. -@end itemize - -@code{RIGHT JOIN} is implemented analogously as @code{LEFT JOIN}. - -The table read order forced by @code{LEFT JOIN} and @code{STRAIGHT JOIN} -will help the join optimizer (which calculates in which order tables -should be joined) to do its work much more quickly, as there are fewer -table permutations to check. - -Note that the above means that if you do a query of type: - -@example -SELECT * FROM a,b LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key -@end example - -@strong{MySQL} will do a full scan on @code{b} as the @code{LEFT -JOIN} will force it to be read before @code{d}. - -The fix in this case is to change the query to: - -@example -SELECT * FROM b,a LEFT JOIN c ON (c.key=a.key) LEFT JOIN d (d.key=a.key) WHERE b.key=d.key -@end example - -@cindex optimizing, LIMIT -@findex LIMIT -@node LIMIT optimization, Insert speed, LEFT JOIN optimization, Query Speed -@subsection How MySQL Optimizes @code{LIMIT} - -In some cases @strong{MySQL} will handle the query differently when you are -using @code{LIMIT #} and not using @code{HAVING}: - -@itemize @bullet -@item -If you are selecting only a few rows with @code{LIMIT}, @strong{MySQL} -will use indexes in some cases when it normally would prefer to do a -full table scan. -@item -If you use @code{LIMIT #} with @code{ORDER BY}, @strong{MySQL} will end the -sorting as soon as it has found the first @code{#} lines instead of sorting -the whole table. -@item -When combining @code{LIMIT #} with @code{DISTINCT}, @strong{MySQL} will stop -as soon as it finds @code{#} unique rows. -@item -In some cases a @code{GROUP BY} can be resolved by reading the key in order -(or do a sort on the key) and then calculate summaries until the -key value changes. In this case @code{LIMIT #} will not calculate any -unnecessary @code{GROUP BY}'s. -@item -As soon as @strong{MySQL} has sent the first @code{#} rows to the client, it -will abort the query. -@item -@code{LIMIT 0} will always quickly return an empty set. This is useful -to check the query and to get the column types of the result columns. -@item -The size of temporary tables uses the @code{LIMIT #} to calculate how much -space is needed to resolve the query. -@end itemize - -@cindex speed, inserting -@cindex inserting, speed of -@node Insert speed, Update speed, LIMIT optimization, Query Speed -@subsection Speed of @code{INSERT} Queries - -The time to insert a record consists approximately of: - -@itemize @bullet -@item -Connect: (3) -@item -Sending query to server: (2) -@item -Parsing query: (2) -@item -Inserting record: (1 x size of record) -@item -Inserting indexes: (1 x number of indexes) -@item -Close: (1) -@end itemize - -where the numbers are somewhat proportional to the overall time. This -does not take into consideration the initial overhead to open tables -(which is done once for each concurrently running query). - -The size of the table slows down the insertion of indexes by N log N -(B-trees). - -Some ways to speed up inserts: - -@itemize @bullet -@item -If you are inserting many rows from the same client at the same time, use -multiple value lists @code{INSERT} statements. This is much faster (many -times in some cases) than using separate @code{INSERT} statements. -@item -If you are inserting a lot of rows from different clients, you can get -higher speed by using the @code{INSERT DELAYED} statement. @xref{INSERT, -, @code{INSERT}}. -@item -Note that with @code{MyISAM} you can insert rows at the same time -@code{SELECT}s are running if there are no deleted rows in the tables. -@item -When loading a table from a text file, use @code{LOAD DATA INFILE}. This -is usually 20 times faster than using a lot of @code{INSERT} statements. -@xref{LOAD DATA, , @code{LOAD DATA}}. -@item -It is possible with some extra work to make @code{LOAD DATA INFILE} run even -faster when the table has many indexes. Use the following procedure: - -@enumerate -@item -Optionally create the table with @code{CREATE TABLE}. For example, using -@code{mysql} or Perl-DBI. - -@item -Execute a @code{FLUSH TABLES} statement or the shell command @code{mysqladmin -flush-tables}. - -@item -Use @code{myisamchk --keys-used=0 -rq /path/to/db/tbl_name}. This will -remove all usage of all indexes from the table. - -@item -Insert data into the table with @code{LOAD DATA INFILE}. This will not -update any indexes and will therefore be very fast. - -@item -If you are going to only read the table in the future, run @code{myisampack} -on it to make it smaller. @xref{Compressed format}. - -@item -Re-create the indexes with @code{myisamchk -r -q -/path/to/db/tbl_name}. This will create the index tree in memory before -writing it to disk, which is much faster because it avoids lots of disk -seeks. The resulting index tree is also perfectly balanced. - -@item -Execute a @code{FLUSH TABLES} statement or the shell command @code{mysqladmin -flush-tables}. -@end enumerate - -This procedure will be built into @code{LOAD DATA INFILE} in some future -version of @strong{MySQL}. -@item -You can speed up insertions by locking your tables: - -@example -mysql> LOCK TABLES a WRITE; -mysql> INSERT INTO a VALUES (1,23),(2,34),(4,33); -mysql> INSERT INTO a VALUES (8,26),(6,29); -mysql> UNLOCK TABLES; -@end example - -The main speed difference is that the index buffer is flushed to disk only -once, after all @code{INSERT} statements have completed. Normally there would -be as many index buffer flushes as there are different @code{INSERT} -statements. Locking is not needed if you can insert all rows with a single -statement. - -Locking will also lower the total time of multi-connection tests, but the -maximum wait time for some threads will go up (because they wait for -locks). For example: - -@example -thread 1 does 1000 inserts -thread 2, 3, and 4 does 1 insert -thread 5 does 1000 inserts -@end example - -If you don't use locking, 2, 3, and 4 will finish before 1 and 5. If you -use locking, 2, 3, and 4 probably will not finish before 1 or 5, but the -total time should be about 40% faster. - -As @code{INSERT}, @code{UPDATE}, and @code{DELETE} operations are very -fast in @strong{MySQL}, you will obtain better overall performance by -adding locks around everything that does more than about 5 inserts or -updates in a row. If you do very many inserts in a row, you could do a -@code{LOCK TABLES} followed by an @code{UNLOCK TABLES} once in a while -(about each 1000 rows) to allow other threads access to the table. This -would still result in a nice performance gain. - -Of course, @code{LOAD DATA INFILE} is much faster for loading data. -@end itemize - -To get some more speed for both @code{LOAD DATA INFILE} and -@code{INSERT}, enlarge the key buffer. @xref{Server parameters}. - -@node Update speed, Delete speed, Insert speed, Query Speed -@subsection Speed of @code{UPDATE} Queries - -Update queries are optimized as a @code{SELECT} query with the additional -overhead of a write. The speed of the write is dependent on the size of -the data that is being updated and the number of indexes that are -updated. Indexes that are not changed will not be updated. - -Also, another way to get fast updates is to delay updates and then do -many updates in a row later. Doing many updates in a row is much quicker -than doing one at a time if you lock the table. - -Note that, with dynamic record format, updating a record to -a longer total length may split the record. So if you do this often, -it is very important to @code{OPTIMIZE TABLE} sometimes. -@xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}. - -@node Delete speed, , Update speed, Query Speed -@subsection Speed of @code{DELETE} Queries - -If you want to delete all rows in the table, you should use -@code{TRUNCATE TABLE table_name}. @xref{TRUNCATE}. - -The time to delete a record is exactly proportional to the number of -indexes. To delete records more quickly, you can increase the size of -the index cache. @xref{Server parameters}. - -@cindex optimization, tips -@cindex tips, optimization -@node Tips, Benchmarks, Query Speed, Performance -@section Other Optimization Tips - -Unsorted tips for faster systems: - -@itemize @bullet -@item -Use persistent connections to the database to avoid the connection -overhead. If you can't use persistent connections and you are doing a -lot of new connections to the database, you may want to change the value -of the @code{thread_cache_size} variable. @xref{Server parameters}. -@item -Always check that all your queries really use the indexes you have created -in the tables. In @strong{MySQL} you can do this with the @code{EXPLAIN} -command. @xref{EXPLAIN, Explain, Explain, manual}. -@item -Try to avoid complex @code{SELECT} queries on tables that are updated a -lot. This is to avoid problems with table locking. -@item -The new @code{MyISAM} tables can insert rows in a table without deleted -rows at the same time another table is reading from it. If this is important -for you, you should consider methods where you don't have to delete rows -or run @code{OPTIMIZE TABLE} after you have deleted a lot of rows. -@item -Use @code{ALTER TABLE ... ORDER BY expr1,expr2...} if you mostly -retrieve rows in expr1,expr2.. order. By using this option after big -changes to the table, you may be able to get higher performance. -@item -In some cases it may make sense to introduce a column that is 'hashed' -based on information from other columns. If this column is short and -reasonably unique it may be much faster than a big index on many -columns. In @strong{MySQL} it's very easy to use this extra column: -@code{SELECT * FROM table_name WHERE hash=MD5(concat(col1,col2)) -AND col_1='constant' AND col_2='constant'} -@item -For tables that change a lot you should try to avoid all @code{VARCHAR} -or @code{BLOB} columns. You will get dynamic row length as soon as you -are using a single @code{VARCHAR} or @code{BLOB} column. @xref{Table -types}. -@item -It's not normally useful to split a table into different tables just -because the rows gets 'big'. To access a row, the biggest performance -hit is the disk seek to find the first byte of the row. After finding -the data most new disks can read the whole row fast enough for most -applications. The only cases where it really matters to split up a table is if -it's a dynamic row size table (see above) that you can change to a fixed -row size, or if you very often need to scan the table and don't need -most of the columns. @xref{Table types}. -@item -If you very often need to calculate things based on information from a -lot of rows (like counts of things), it's probably much better to -introduce a new table and update the counter in real time. An update of -type @code{UPDATE table set count=count+1 where index_column=constant} -is very fast! - -This is really important when you use databases like @strong{MySQL} that -only have table locking (multiple readers / single writers). This will -also give better performance with most databases, as the row locking -manager in this case will have less to do. -@item -If you need to collect statistics from big log tables, use summary tables -instead of scanning the whole table. Maintaining the summaries should be -much faster than trying to do statistics 'live'. It's much faster to -regenerate new summary tables from the logs when things change -(depending on business decisions) than to have to change the running -application! -@item -If possible, one should classify reports as 'live' or 'statistical', -where data needed for statistical reports are only generated based on -summary tables that are generated from the actual data. -@item -Take advantage of the fact that columns have default values. Insert -values explicitly only when the value to be inserted differs from the -default. This reduces the parsing that @strong{MySQL} need to do and -improves the insert speed. -@item -In some cases it's convenient to pack and store data into a blob. In this -case you have to add some extra code in your application to pack/unpack -things in the blob, but this may save a lot of accesses at some stage. -This is practical when you have data that doesn't conform to a static -table structure. -@item -Normally you should try to keep all data non-redundant (what -is called 3rd normal form in database theory), but you should not be -afraid of duplicating things or creating summary tables if you need these -to gain more speed. -@item -Stored procedures or UDF (user-defined functions) may be a good way to -get more performance. In this case you should, however, always have a way -to do this some other (slower) way if you use some database that doesn't -support this. -@item -You can always gain something by caching queries/answers in your -application and trying to do many inserts/updates at the same time. If -your database supports lock tables (like @strong{MySQL} and Oracle), -this should help to ensure that the index cache is only flushed once -after all updates. -@item -Use @code{INSERT /*! DELAYED */} when you do not need to know when your -data is written. This speeds things up because many records can be written -with a single disk write. -@item -Use @code{INSERT /*! LOW_PRIORITY */} when you want your selects to be -more important. -@item -Use @code{SELECT /*! HIGH_PRIORITY */} to get selects that jump the -queue. That is, the select is done even if there is somebody waiting to -do a write. -@item -Use the multi-line @code{INSERT} statement to store many rows with one -SQL command (many SQL servers supports this). -@item -Use @code{LOAD DATA INFILE} to load bigger amounts of data. This is -faster than normal inserts and will be even faster when @code{myisamchk} -is integrated in @code{mysqld}. -@item -Use @code{AUTO_INCREMENT} columns to make unique values. -@item -Use @code{OPTIMIZE TABLE} once in a while to avoid fragmentation when -using dynamic table format. @xref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}}. - -@item -Use @code{HEAP} tables to get more speed when possible. @xref{Table -types}. -@item -When using a normal Web server setup, images should be stored as -files. That is, store only a file reference in the database. The main -reason for this is that a normal Web server is much better at caching -files than database contents. So it it's much easier to get a fast -system if you are using files. -@item -Use in memory tables for non-critical data that are accessed often (like -information about the last shown banner for users that don't have -cookies). -@item -Columns with identical information in different tables should be -declared identical and have identical names. Before Version 3.23 you -got slow joins otherwise. - -Try to keep the names simple (use @code{name} instead of -@code{customer_name} in the customer table). To make your names portable -to other SQL servers you should keep them shorter than 18 characters. -@item -If you need REALLY high speed, you should take a look at the low-level -interfaces for data storage that the different SQL servers support! For -example, by accessing the @strong{MySQL} @code{MyISAM} directly, you could -get a speed increase of 2-5 times compared to using the SQL interface. -To be able to do this the data must be on the same server as -the application, and usually it should only be accessed by one process -(because external file locking is really slow). One could eliminate the -above problems by introducing low-level @code{MyISAM} commands in the -@strong{MySQL} server (this could be one easy way to get more -performance if needed). By carefully designing the database interface, -it should be quite easy to support this types of optimization. -@item -In many cases it's faster to access data from a database (using a live -connection) than accessing a text file, just because the database is -likely to be more compact than the text file (if you are using numerical -data), and this will involve fewer disk accesses. You will also save -code because you don't have to parse your text files to find line and -column boundaries. -@item -You can also use replication to speed things up. @xref{Replication}. -@item -Declaring a table with @code{DELAY_KEY_WRITE=1} will make the updating of -indexes faster, as these are not logged to disk until the file is closed. -The downside is that you should run @code{myisamchk} on these tables before -you start @code{mysqld} to ensure that they are okay if something killed -@code{mysqld} in the middle. As the key information can always be generated -from the data, you should not lose anything by using @code{DELAY_KEY_WRITE}. -@end itemize - -@cindex benchmarks -@cindex performance, benchmarks -@node Benchmarks, Design, Tips, Performance -@section Using Your Own Benchmarks - -You should definitely benchmark your application and database to find -out where the bottlenecks are. By fixing it (or by replacing the -bottleneck with a 'dummy module') you can then easily identify the next -bottleneck (and so on). Even if the overall performance for your -application is sufficient, you should at least make a plan for each -bottleneck, and decide how to solve it if someday you really need the -extra performance. - -For an example of portable benchmark programs, look at the @strong{MySQL} -benchmark suite. @xref{MySQL Benchmarks, , @strong{MySQL} Benchmarks}. You -can take any program from this suite and modify it for your needs. By doing this, -you can try different solutions to your problem and test which is really the -fastest solution for you. - -It is very common that some problems only occur when the system is very -heavily loaded. We have had many customers who contact us when they -have a (tested) system in production and have encountered load problems. In -every one of these cases so far, it has been problems with basic design -(table scans are NOT good at high load) or OS/Library issues. Most of -this would be a @strong{LOT} easier to fix if the systems were not -already in production. - -To avoid problems like this, you should put some effort into benchmarking -your whole application under the worst possible load! You can use Sasha's -recent hack for this - -@uref{http://www.mysql.com/Downloads/super-smack/super-smack-1.0.tar.gz, -super-smack}. -As the name suggests, it can bring your system down to its knees if you ask it, -so make sure to use it only on your development systems. - -@cindex design, choices -@cindex database design -@cindex storage of data -@node Design, Design Limitations, Benchmarks, Performance -@section Design Choices - -@strong{MySQL} keeps row data and index data in separate files. Many (almost -all) other databases mix row and index data in the same file. We believe that -the @strong{MySQL} choice is better for a very wide range of modern systems. - -Another way to store the row data is to keep the information for each -column in a separate area (examples are SDBM and Focus). This will cause a -performance hit for every query that accesses more than one column. Because -this degenerates so quickly when more than one column is accessed, -we believe that this model is not good for general purpose databases. - -The more common case is that the index and data are stored together -(like in Oracle/Sybase et al). In this case you will find the row -information at the leaf page of the index. The good thing with this -layout is that it, in many cases, depending on how well the index is -cached, saves a disk read. The bad things with this layout are: - -@itemize @bullet -@item -Table scanning is much slower because you have to read through the indexes -to get at the data. -@item -You can't use only the index table to retrieve data for a query. -@item -You lose a lot of space, as you must duplicate indexes from the nodes -(as you can't store the row in the nodes). -@item -Deletes will degenerate the table over time (as indexes in nodes are -usually not updated on delete). -@item -It's harder to cache ONLY the index data. -@end itemize - -@cindex design, limitations -@node Design Limitations, Portability, Design, Performance -@section MySQL Design Limitations/Tradeoffs - -Because @strong{MySQL} uses extremely fast table locking (multiple readers / -single writers) the biggest remaining problem is a mix of a steady stream of -inserts and slow selects on the same table. - -We believe that for a huge number of systems the extremely fast -performance in other cases make this choice a win. This case is usually -also possible to solve by having multiple copies of the table, but it -takes more effort and hardware. - -We are also working on some extensions to solve this problem for some -common application niches. - -@cindex portability -@cindex crash-me program -@cindex programs, crash-me -@node Portability, Internal use, Design Limitations, Performance -@section Portability - -Because all SQL servers implement different parts of SQL, it takes work to -write portable SQL applications. For very simple selects/inserts it is -very easy, but the more you need the harder it gets. If you want an -application that is fast with many databases it becomes even harder! - -To make a complex application portable you need to choose a number of -SQL servers that it should work with. - -You can use the @strong{MySQL} crash-me program/web-page -@uref{http://www.mysql.com/information/crash-me.php} to find functions, -types, and limits you can use with a selection of database -servers. Crash-me now tests far from everything possible, but it -is still comprehensive with about 450 things tested. - -For example, you shouldn't have column names longer than 18 characters -if you want to be able to use Informix or DB2. - -Both the @strong{MySQL} benchmarks and crash-me programs are very -database-independent. By taking a look at how we have handled this, you -can get a feeling for what you have to do to write your application -database-independent. The benchmarks themselves can be found in the -@file{sql-bench} directory in the @strong{MySQL} source -distribution. They are written in Perl with DBI database interface -(which solves the access part of the problem). - -See @uref{http://www.mysql.com/information/benchmarks.html} for the results -from this benchmark. - -As you can see in these results, all databases have some weak points. That -is, they have different design compromises that lead to different -behavior. - -If you strive for database independence, you need to get a good feeling -for each SQL server's bottlenecks. @strong{MySQL} is VERY fast in -retrieving and updating things, but will have a problem in mixing slow -readers/writers on the same table. Oracle, on the other hand, has a big -problem when you try to access rows that you have recently updated -(until they are flushed to disk). Transaction databases in general are -not very good at generating summary tables from log tables, as in this -case row locking is almost useless. - -To get your application @emph{really} database-independent, you need to define -an easy extendable interface through which you manipulate your data. As -C++ is available on most systems, it makes sense to use a C++ classes -interface to the databases. - -If you use some specific feature for some database (like the -@code{REPLACE} command in @strong{MySQL}), you should code a method for -the other SQL servers to implement the same feature (but slower). With -@strong{MySQL} you can use the @code{/*! */} syntax to add -@strong{MySQL}-specific keywords to a query. The code inside -@code{/**/} will be treated as a comment (ignored) by most other SQL -servers. - -If REAL high performance is more important than exactness, as in some -Web applications, a possibility is to create an application layer that -caches all results to give you even higher performance. By letting -old results 'expire' after a while, you can keep the cache reasonably -fresh. This is quite nice in case of extremely high load, in which case -you can dynamically increase the cache and set the expire timeout higher -until things get back to normal. - -In this case the table creation information should contain information -of the initial size of the cache and how often the table should normally -be refreshed. - -@cindex uses, of MySQL -@cindex customers, of MySQL -@node Internal use, , Portability, Performance -@section What Have We Used MySQL For? - -During @strong{MySQL} initial development, the features of @strong{MySQL} were made to fit -our largest customer. They handle data warehousing for a couple of the -biggest retailers in Sweden. - -From all stores, we get weekly summaries of all bonus card transactions, -and we are expected to provide useful information for the store owners -to help them find how their advertisement campaigns are affecting their -customers. - -The data is quite huge (about 7 million summary transactions per month), -and we have data for 4-10 years that we need to present to the users. -We got weekly requests from the customers that they want to get -'instant' access to new reports from this data. - -We solved this by storing all information per month in compressed -'transaction' tables. We have a set of simple macros (script) that -generates summary tables grouped by different criteria (product group, -customer id, store ...) from the transaction tables. The reports are -Web pages that are dynamically generated by a small Perl script that -parses a Web page, executes the SQL statements in it, and inserts the -results. We would have used PHP or mod_perl instead but they were -not available at that time. - -For graphical data we wrote a simple tool in @code{C} that can produce -GIFs based on the result of a SQL query (with some processing of the -result). This is also dynamically executed from the Perl script that -parses the @code{HTML} files. - -In most cases a new report can simply be done by copying an existing -script and modifying the SQL query in it. In some cases, we will need to -add more fields to an existing summary table or generate a new one, but -this is also quite simple, as we keep all transactions tables on disk. -(Currently we have at least 50G of transactions tables and 200G of other -customer data.) - -We also let our customers access the summary tables directly with ODBC -so that the advanced users can themselves experiment with the data. - -We haven't had any problems handling this with quite modest Sun Ultra -SPARCstation (2x200 Mhz). We recently upgraded one of our servers to a 2 -CPU 400 Mhz UltraSPARC, and we are now planning to start handling -transactions on the product level, which would mean a ten-fold increase -of data. We think we can keep up with this by just adding more disk to -our systems. - -We are also experimenting with Intel-Linux to be able to get more CPU -power cheaper. Now that we have the binary portable database format (new -in Version 3.23), we will start to use this for some parts of the application. - -Our initial feelings are that Linux will perform much better on -low-to-medium load and Solaris will perform better when you start to get a -high load because of extreme disk IO, but we don't yet have anything -conclusive about this. After some discussion with a Linux Kernel -developer, this might be a side effect of Linux giving so much resources -to the batch job that the interactive performance gets very low. This -makes the machine feel very slow and unresponsive while big batches are -going. Hopefully this will be better handled in future Linux Kernels. - -@cindex benchmark suite -@cindex crash-me program -@node MySQL Benchmarks, Maintenance, Performance, Top -@chapter The MySQL Benchmark Suite - -This should contain a technical description of the @strong{MySQL} -benchmark suite (and @code{crash-me}), but that description is not -written yet. Currently, you can get a good idea of the benchmark by -looking at the code and results in the @file{sql-bench} directory in any -@strong{MySQL} source distributions. - -This benchmark suite is meant to be a benchmark that will tell any user -what things a given SQL implementation performs well or poorly at. - -Note that this benchmark is single threaded, so it measures the minimum -time for the operations. We plan to in the future add a lot of -multi-threaded tests to the benchmark suite. - -For example, (run on the same NT 4.0 machine): - -@multitable @columnfractions .6 .2 .2 -@strong{Reading 2000000 rows by index} @tab @strong{Seconds} @tab @strong{Seconds} -@item mysql @tab 367 @tab 249 -@item mysql_odbc @tab 464 -@item db2_odbc @tab 1206 -@item informix_odbc @tab 121126 -@item ms-sql_odbc @tab 1634 -@item oracle_odbc @tab 20800 -@item solid_odbc @tab 877 -@item sybase_odbc @tab 17614 -@end multitable - -@multitable @columnfractions .6 .2 .2 -@strong{Inserting (350768) rows} @tab @strong{Seconds} @tab @strong{Seconds} -@item mysql @tab 381 @tab 206 -@item mysql_odbc @tab 619 -@item db2_odbc @tab 3460 -@item informix_odbc @tab 2692 -@item ms-sql_odbc @tab 4012 -@item oracle_odbc @tab 11291 -@item solid_odbc @tab 1801 -@item sybase_odbc @tab 4802 -@end multitable - -In the above test @strong{MySQL} was run with a 8M index cache. - -We have gather some more benchmark results at -@uref{http://www.mysql.com/information/benchmarks.html}. - -Note that Oracle is not included because they asked to be removed. All -Oracle benchmarks have to be passed by Oracle! We believe that makes -Oracle benchmarks @strong{VERY} biased because the above benchmarks are -supposed to show what a standard installation can do for a single -client. - -To run the benchmark suite, you have to download a @strong{MySQL} source -distribution, install the perl DBI driver, the perl DBD driver for the -database you want to test and then do: - -@example -cd sql-bench -perl run-all-tests --server=# -@end example - -where # is one of supported servers. You can get a list of all options -and supported servers by doing @code{run-all-tests --help}. - -@cindex crash-me -@code{crash-me} tries to determine what features a database supports and -what its capabilities and limitations are by actually running -queries. For example, it determines: - -@itemize @bullet -@item -What column types are supported -@item -How many indexes are supported -@item -What functions are supported -@item -How big a query can be -@item -How big a @code{VARCHAR} column can be -@end itemize - -We can find the result from crash-me on a lot of different databases at -@uref{http://www.mysql.com/information/crash-me.php}. - - -@node Maintenance, Adding functions, MySQL Benchmarks, Top +@node Maintenance, Adding functions, Fulltext Search, Top @chapter Maintaining a MySQL Installation @cindex installation maintenance @@ -36647,8 +36794,6 @@ This chapter covers what you should know about maintaining a @strong{MySQL} distribution. You will learn how to care for your tables on a regular basis, and what to do when disaster strikes. - - @node Using mysqlcheck, , Maintenance, Maintenance @section Using @code{mysqlcheck} for Table Maintenance and Crash Recovery From 386ded555ed75c97d4086e2d8b04b3d67466fe44 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 2 Aug 2001 15:29:08 -0500 Subject: [PATCH 28/51] Fixes to manual --- Docs/manual.texi | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index ab8e1815c5e..998b4145cbf 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -52,9 +52,6 @@ @smallbook @end ifset -@c We want the contents at the beginning, where it's supposed to be. -@c @setshortcontentsaftertitlepage - @c %**end of header @ifinfo @@ -76,9 +73,10 @@ END-INFO-DIR-ENTRY @end titlepage @c Short contents, blank page, long contents. -@shortcontents -@page -@page +@c until i can figure out the blank page, no short contents. +@c @shortcontents +@c @page +@c @page @contents @c This should be added. The HTML conversion also needs a MySQL version @@ -4716,10 +4714,11 @@ Some incompatibilities exist as a result of @strong{MySQL} supporting multiple connections to the server from the same process. @end itemize +@node Protocol differences, Compare PostgreSQL, Compare mSQL, Comparisons +@subsubsection How @code{mSQL} and MySQL Client/Server Communications Protocols Differ + @cindex communications protocols @cindex mSQL vs. MySQL -@node Protocol differences, Compare PostgreSQL, Compare mSQL, Comparisons -@subsection How @code{mSQL} and MySQL Client/Server Communications Protocols Differ There are enough differences that it is impossible (or at least not easy) to support both. @@ -4941,6 +4940,7 @@ users. @item @end table + @node Compare PostgreSQL, MySQL-PostgreSQL features, Protocol differences, Comparisons @subsection How MySQL Compares to PostgreSQL @@ -5013,9 +5013,11 @@ reusable code and, in our opinion, fewer bugs. Because we are the authors of the @strong{MySQL} server code we are better able to coordinate new features and releases. -@cindex PostgreSQL/MySQL, features + @node MySQL-PostgreSQL features, , Compare PostgreSQL, Comparisons -@subsection Featurevise Comparison of MySQL and PostgreSQL +@subsubsection Featurewise Comparison of MySQL and PostgreSQL + +@cindex PostgreSQL/MySQL, features On the @uref{http://www.mysql.com/information/crash-me.php, crash-me} page you can find a list of those database constructs and limits that From 36bfb9e167011b059711471b5af842d2cb0083ee Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 2 Aug 2001 18:53:54 -0500 Subject: [PATCH 29/51] fixed menus/nodes --- Docs/manual.texi | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 998b4145cbf..ee7c21f28ba 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -4463,9 +4463,7 @@ For platform-specific bugs, see the sections about compiling and porting. @menu * Compare mSQL:: How @strong{MySQL} compares to @code{mSQL} -* Protocol differences:: * Compare PostgreSQL:: How @strong{MySQL} compares with PostgreSQL -* MySQL-PostgreSQL features:: @end menu This section compares @strong{MySQL} to other popular databases. @@ -4479,7 +4477,7 @@ For a list of all supported limits, functions, and types, see the @code{crash-me} Web page at @uref{http://www.mysql.com/information/crash-me.php}. -@node Compare mSQL, Protocol differences, Comparisons, Comparisons +@node Compare mSQL, Compare PostgreSQL, Comparisons, Comparisons @subsection How MySQL Compares to @code{mSQL} @table @strong @@ -4667,9 +4665,11 @@ For example, it changes instances of @code{msqlConnect()} to @menu * Using mSQL tools:: How to convert @code{mSQL} tools for @strong{MySQL} +* Protocol differences:: +* Syntax differences:: @end menu -@node Using mSQL tools, , Compare mSQL, Compare mSQL +@node Using mSQL tools, Protocol differences, Compare mSQL, Compare mSQL @subsubsection How to Convert @code{mSQL} Tools for MySQL @cindex MySQL tools, conversion @@ -4714,7 +4714,7 @@ Some incompatibilities exist as a result of @strong{MySQL} supporting multiple connections to the server from the same process. @end itemize -@node Protocol differences, Compare PostgreSQL, Compare mSQL, Comparisons +@node Protocol differences, Syntax differences, Using mSQL tools, Compare mSQL @subsubsection How @code{mSQL} and MySQL Client/Server Communications Protocols Differ @cindex communications protocols @@ -4752,7 +4752,7 @@ If a connection is idle for 8 hours, the server closes the connection. * Syntax differences:: @end menu -@node Syntax differences, , Protocol differences, Protocol differences +@node Syntax differences, , Protocol differences, Compare mSQL @subsubsection How @code{mSQL} 2.0 SQL Syntax Differs from MySQL @noindent @@ -4941,7 +4941,7 @@ users. @end table -@node Compare PostgreSQL, MySQL-PostgreSQL features, Protocol differences, Comparisons +@node Compare PostgreSQL, , Compare mSQL, Comparisons @subsection How MySQL Compares to PostgreSQL @cindex PostgreSQL vs. MySQL, overview @@ -4970,9 +4970,11 @@ can offer, you should use @code{PostgreSQL}. @cindex PostgreSQL/MySQL, strategies @menu * MySQL-PostgreSQL goals:: MySQL and PostgreSQL development strategies +* MySQL-PostgreSQL features:: +* MySQL-PostgreSQL benchmarks:: @end menu -@node MySQL-PostgreSQL goals, , Compare PostgreSQL, Compare PostgreSQL +@node MySQL-PostgreSQL goals, MySQL-PostgreSQL features, Compare PostgreSQL, Compare PostgreSQL @subsubsection MySQL and PostgreSQL development strategies When adding things to MySQL we take pride to do an optimal, definite @@ -5014,7 +5016,7 @@ authors of the @strong{MySQL} server code we are better able to coordinate new features and releases. -@node MySQL-PostgreSQL features, , Compare PostgreSQL, Comparisons +@node MySQL-PostgreSQL features, MySQL-PostgreSQL benchmarks, MySQL-PostgreSQL goals, Compare PostgreSQL @subsubsection Featurewise Comparison of MySQL and PostgreSQL @cindex PostgreSQL/MySQL, features @@ -5239,7 +5241,7 @@ in this section. * MySQL-PostgreSQL benchmarks:: @end menu -@node MySQL-PostgreSQL benchmarks, , MySQL-PostgreSQL features, MySQL-PostgreSQL features +@node MySQL-PostgreSQL benchmarks, , MySQL-PostgreSQL features, Compare PostgreSQL @subsubsection Benchmarking MySQL and PostgreSQL @cindex PostgreSQL vs. MySQL, benchmarks From 9d7a659b21d5afe1073adaa5a9320022683a23cc Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 4 Aug 2001 00:10:00 +0300 Subject: [PATCH 30/51] Fix when using --without-server --with-thread-safe-client Added prototype for my_thread_end New error message for MATCH Give error when using myisamchk --force --readonly BitKeeper/deleted/.del-fulltext_join.test~e347c8f04405c916: Delete: mysql-test/t/fulltext_join.test Docs/manual.texi: Added node to fulltext configure.in: Fix when using --without-server --with-thread-safe-client include/mysql_com.h: Added prototype for my_thread_end include/mysqld_error.h: New error message for MATCH myisam/myisamchk.c: Give error when using --force --readonly mysql-test/t/fulltext.test: Added test for error conditons with fulltext sql/item_func.cc: Fixed error messages when using MATCH ... AGAINST sql/mysqld.cc: Portability fix sql/share/czech/errmsg.txt: New error message when using MATCH sql/share/danish/errmsg.txt: New error message when using MATCH sql/share/dutch/errmsg.txt: New error message when using MATCH sql/share/english/errmsg.txt: New error message when using MATCH sql/share/estonian/errmsg.txt: New error message when using MATCH sql/share/french/errmsg.txt: New error message when using MATCH sql/share/german/errmsg.txt: New error message when using MATCH sql/share/greek/errmsg.txt: New error message when using MATCH sql/share/hungarian/errmsg.txt: New error message when using MATCH sql/share/italian/errmsg.txt: New error message when using MATCH sql/share/japanese/errmsg.txt: New error message when using MATCH sql/share/korean/errmsg.txt: New error message when using MATCH sql/share/norwegian-ny/errmsg.txt: New error message when using MATCH sql/share/norwegian/errmsg.txt: New error message when using MATCH sql/share/polish/errmsg.txt: New error message when using MATCH sql/share/portuguese/errmsg.txt: New error message when using MATCH sql/share/romanian/errmsg.txt: New error message when using MATCH sql/share/russian/errmsg.txt: New error message when using MATCH sql/share/slovak/errmsg.txt: New error message when using MATCH sql/share/spanish/errmsg.txt: New error message when using MATCH sql/share/swedish/errmsg.OLD: New error message when using MATCH sql/share/swedish/errmsg.txt: New error message when using MATCH --- Docs/manual.texi | 24 +++++++++++++++++-- configure.in | 11 +++++++-- include/mysql_com.h | 1 + include/mysqld_error.h | 3 ++- myisam/myisamchk.c | 4 ++-- mysql-test/t/fulltext.test | 23 +++++++++++++++++-- mysql-test/t/fulltext_join.test | 38 ------------------------------- sql/item_func.cc | 20 ++++++++++++---- sql/mysqld.cc | 2 +- sql/share/czech/errmsg.txt | 1 + sql/share/danish/errmsg.txt | 1 + sql/share/dutch/errmsg.txt | 1 + sql/share/english/errmsg.txt | 1 + sql/share/estonian/errmsg.txt | 1 + sql/share/french/errmsg.txt | 1 + sql/share/german/errmsg.txt | 1 + sql/share/greek/errmsg.txt | 1 + sql/share/hungarian/errmsg.txt | 1 + sql/share/italian/errmsg.txt | 1 + sql/share/japanese/errmsg.txt | 1 + sql/share/korean/errmsg.txt | 1 + sql/share/norwegian-ny/errmsg.txt | 1 + sql/share/norwegian/errmsg.txt | 1 + sql/share/polish/errmsg.txt | 1 + sql/share/portuguese/errmsg.txt | 1 + sql/share/romanian/errmsg.txt | 1 + sql/share/russian/errmsg.txt | 1 + sql/share/slovak/errmsg.txt | 1 + sql/share/spanish/errmsg.txt | 1 + sql/share/swedish/errmsg.OLD | 4 ++++ sql/share/swedish/errmsg.txt | 1 + 31 files changed, 98 insertions(+), 53 deletions(-) delete mode 100644 mysql-test/t/fulltext_join.test diff --git a/Docs/manual.texi b/Docs/manual.texi index 230f73e5804..ff0473fbf5a 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -21610,6 +21610,15 @@ mysql> select * from bar; For each row in table @code{foo}, a row is inserted in @code{bar} with the values from @code{foo} and default values for the new columns. +@code{CREATE TABLE ... SELECT} will not automaticly create any indexes +for you. This is done intentionally to make the command as flexible as +possible. If you want to have indexes in the created table, you should +specify these before the @code{SELECT} statement: + +@example +mysql> create table bar (unique (n)) select n from foo; +@end example + If any errors occur while copying the data to the table, it will automatically be deleted. @@ -29928,12 +29937,23 @@ the Internet with a search engine. It is with this reasoning that such rows have been assigned a low semantical value in @strong{this particular dataset}. @menu +* Fulltext restrictions:: * Fulltext Fine-tuning:: * Fulltext Features to Appear in MySQL 4.0:: * Fulltext TODO:: @end menu -@node Fulltext Fine-tuning, Fulltext Features to Appear in MySQL 4.0, Fulltext Search, Fulltext Search +@node Fulltext restrictions, Fulltext Fine-tuning, Fulltext Search, Fulltext Search +@section Fulltext restrictions +@itemize @bullet +@item +All parameters to the @code{MATCH} function must be columns from the +same table that is part of the same fulltext index. +@item +The argument to @code{AGAINST} must be a constant string. +@end itemize + +@node Fulltext Fine-tuning, Fulltext Features to Appear in MySQL 4.0, Fulltext restrictions, Fulltext Search @section Fine-tuning MySQL Full-text Search Unfortunately, full-text search has no user-tunable parameters yet, @@ -29990,7 +30010,7 @@ implemented in the 4.0 tree. It explains @code{OPTIMIZE TABLE} with @code{FULLTEXT} indexes are now up to 100 times faster. -@item @code{MATCH ... AGAINST} now supports the following +@item @code{MATCH ... AGAINST} is going to support the following @strong{boolean operators}: @itemize @bullet diff --git a/configure.in b/configure.in index cfe6d323021..87a144b4b57 100644 --- a/configure.in +++ b/configure.in @@ -4,7 +4,7 @@ dnl Process this file with autoconf to produce a configure script. AC_INIT(sql/mysqld.cc) AC_CANONICAL_SYSTEM # The Docs Makefile.am parses this line! -AM_INIT_AUTOMAKE(mysql, 3.23.40) +AM_INIT_AUTOMAKE(mysql, 3.23.41) AM_CONFIG_HEADER(config.h) PROTOCOL_VERSION=10 @@ -1946,9 +1946,13 @@ AC_SUBST(CLIENT_LIBS) AC_SUBST(sql_client_dirs) AC_SUBST(linked_client_targets) -if test "$with_server" = "yes" +if test "$with_server" = "yes" -o "$THREAD_SAFE_CLIENT" != "no" then AC_DEFINE(THREAD) +fi + +if test "$with_server" = "yes" +then # Avoid _PROGRAMS names THREAD_LPROGRAMS="test_thr_alarm test_thr_lock" AC_SUBST(THREAD_LPROGRAMS) @@ -2044,7 +2048,10 @@ EOF AC_DEFINE(HAVE_GEMINI_DB) fi +fi +if test "$with_server" = "yes" -o "$THREAD_SAFE_CLIENT" != "no" +then if test "$with_posix_threads" = "no" -o "$with_mit_threads" = "yes" then # MIT user level threads diff --git a/include/mysql_com.h b/include/mysql_com.h index 8a5eea1024c..5b22d58150d 100644 --- a/include/mysql_com.h +++ b/include/mysql_com.h @@ -227,6 +227,7 @@ void hash_password(unsigned long *result, const char *password); void my_init(void); void load_defaults(const char *conf_file, const char **groups, int *argc, char ***argv); +void my_thread_end(void); #define NULL_LENGTH ((unsigned long) ~0) /* For net_store_length */ diff --git a/include/mysqld_error.h b/include/mysqld_error.h index cfcf7672013..32967931eac 100644 --- a/include/mysqld_error.h +++ b/include/mysqld_error.h @@ -210,4 +210,5 @@ #define ER_READ_ONLY_TRANSACTION 1207 #define ER_DROP_DB_WITH_READ_LOCK 1208 #define ER_CREATE_DB_WITH_READ_LOCK 1209 -#define ER_ERROR_MESSAGES 210 +#define ER_WRONG_ARGUMENTS 1210 +#define ER_ERROR_MESSAGES 211 diff --git a/myisam/myisamchk.c b/myisam/myisamchk.c index 61ad939d6ed..ec3f0c8dca4 100644 --- a/myisam/myisamchk.c +++ b/myisam/myisamchk.c @@ -201,7 +201,7 @@ static struct option long_options[] = static void print_version(void) { - printf("%s Ver 1.48 for %s at %s\n",my_progname,SYSTEM_TYPE, + printf("%s Ver 1.49 for %s at %s\n",my_progname,SYSTEM_TYPE, MACHINE_TYPE); } @@ -468,7 +468,7 @@ static void get_options(register int *argc,register char ***argv) if ((check_param.testflag & T_READONLY) && (check_param.testflag & (T_REP_BY_SORT | T_REP | T_STATISTICS | T_AUTO_INC | - T_SORT_RECORDS | T_SORT_INDEX))) + T_SORT_RECORDS | T_SORT_INDEX | T_FORCE_CREATE))) { VOID(fprintf(stderr, "%s: Can't use --readonly when repairing or sorting\n", diff --git a/mysql-test/t/fulltext.test b/mysql-test/t/fulltext.test index 064219c6ad3..153fdefd960 100644 --- a/mysql-test/t/fulltext.test +++ b/mysql-test/t/fulltext.test @@ -2,7 +2,7 @@ # Test of fulltext index # -drop table if exists t1,t2; +drop table if exists t1,t2,t3; CREATE TABLE t1 (a VARCHAR(200), b TEXT, FULLTEXT (a,b)); INSERT INTO t1 VALUES('MySQL has now support', 'for full-text search'),('Full-text indexes', 'are called collections'),('Only MyISAM tables','support collections'),('Function MATCH ... AGAINST()','is used to do a search'),('Full-text search in MySQL', 'implements vector space model'); @@ -61,4 +61,23 @@ select * from t2 where MATCH inhalt AGAINST (NULL); select * from t2 where MATCH inhalt AGAINST ('foobar'); select * from t2 having MATCH inhalt AGAINST ('foobar'); -drop table t1,t2; +# +# check of fulltext errors +# + +CREATE TABLE t3 ( + ticket int(11), + inhalt text, + KEY tig (ticket), + fulltext index tix (inhalt) +); + +--error 1210 +select * from t2 having MATCH inhalt AGAINST (t1.id); +--error 1210 +select * from t2 having MATCH ticket AGAINST ('foobar'); +--error 1210 +select * from t2,t3 having MATCH (t2.inhalt,t3.inhalt) AGAINST ('foobar'); + +drop table t1,t2,t3; + diff --git a/mysql-test/t/fulltext_join.test b/mysql-test/t/fulltext_join.test deleted file mode 100644 index c5e6037180a..00000000000 --- a/mysql-test/t/fulltext_join.test +++ /dev/null @@ -1,38 +0,0 @@ -DROP TABLE IF EXISTS stories; -CREATE TABLE stories ( - sid char(16) NOT NULL, - tid smallint UNSIGNED NOT NULL, - uid mediumint UNSIGNED NOT NULL, - title varchar(100) DEFAULT '' NOT NULL, - dept varchar(100), - time datetime DEFAULT '0000-00-00 00:00:00' NOT NULL, - hits mediumint UNSIGNED DEFAULT '0' NOT NULL, - section varchar(30) DEFAULT '' NOT NULL, - displaystatus tinyint DEFAULT '0' NOT NULL, - commentstatus tinyint, - discussion mediumint UNSIGNED, - submitter mediumint UNSIGNED NOT NULL, - flags set("delete_me","data_dirty") DEFAULT '' NOT NULL, - PRIMARY KEY (sid), - FOREIGN KEY (uid) REFERENCES users(uid), - FOREIGN KEY (tid) REFERENCES tid(topic), - FOREIGN KEY (section) REFERENCES sections(section), - KEY time (time), - KEY searchform (displaystatus,time) -) TYPE = myisam; -DROP TABLE IF EXISTS story_text; -CREATE TABLE story_text ( - sid char(16) NOT NULL, - introtext text, - bodytext text, - relatedtext text, - FOREIGN KEY (sid) REFERENCES stories(sid), - PRIMARY KEY (sid) -) TYPE = myisam; -ALTER TABLE stories add fulltext (title); -ALTER TABLE story_text add fulltext (introtext,bodytext); - -SELECT stories.sid,title, TRUNCATE((MATCH (title,introtext,bodytext) -AGAINST('install')), 1) as score FROM stories,story_text WHERE -stories.sid = story_text.sid AND MATCH (title,introtext,bodytext) -AGAINST ('install'); diff --git a/sql/item_func.cc b/sql/item_func.cc index e540f850063..10298ce67f2 100644 --- a/sql/item_func.cc +++ b/sql/item_func.cc @@ -1954,13 +1954,17 @@ bool Item_func_match::fix_fields(THD *thd,struct st_table_list *tlist) maybe_null=1; join_key=0; - /* Why testing for const_item ? Monty */ - /* I'll remove it later, but this should include modifications to - find_best and auto_close as complement to auto_init code above. SerG */ - /* I'd rather say now that const_item is assumed in quite a bit of - places, so it would be difficult to remove. SerG */ + /* Serg: + I'd rather say now that const_item is assumed in quite a bit of + places, so it would be difficult to remove; If it would ever to be + removed, this should include modifications to find_best and auto_close + as complement to auto_init code above. + */ if (Item_func::fix_fields(thd,tlist) || !const_item()) + { + my_error(ER_WRONG_ARGUMENTS,MYF(0),"AGAINST"); return 1; + } while ((item=li++)) { @@ -1969,12 +1973,18 @@ bool Item_func_match::fix_fields(THD *thd,struct st_table_list *tlist) if (item->type() == Item::REF_ITEM) li.replace(item= *((Item_ref *)item)->ref); if (item->type() != Item::FIELD_ITEM || !item->used_tables()) + { + my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH"); return 1; + } used_tables_cache|=item->used_tables(); } /* check that all columns come from the same table */ if (count_bits(used_tables_cache) != 1) + { + my_error(ER_WRONG_ARGUMENTS,MYF(0),"MATCH"); return 1; + } const_item_cache=0; table=((Item_field *)fields.head())->field->table; return 0; diff --git a/sql/mysqld.cc b/sql/mysqld.cc index 5d4339d3ca6..a9771184b4b 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -1481,7 +1481,7 @@ static void open_log(MYSQL_LOG *log, const char *hostname, // get rid of extention if the log is binary to avoid problems if (type == LOG_BIN) { - char* p = strrchr(opt_name, FN_EXTCHAR); + char* p = strrchr((char*) opt_name, FN_EXTCHAR); if (p) *p = 0; } diff --git a/sql/share/czech/errmsg.txt b/sql/share/czech/errmsg.txt index 6d35e913ffd..a0540bfe270 100644 --- a/sql/share/czech/errmsg.txt +++ b/sql/share/czech/errmsg.txt @@ -220,3 +220,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/danish/errmsg.txt b/sql/share/danish/errmsg.txt index d1e0ea71175..73fa8b79f0f 100644 --- a/sql/share/danish/errmsg.txt +++ b/sql/share/danish/errmsg.txt @@ -214,3 +214,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/dutch/errmsg.txt b/sql/share/dutch/errmsg.txt index 7ae6c564283..df3d35600ba 100644 --- a/sql/share/dutch/errmsg.txt +++ b/sql/share/dutch/errmsg.txt @@ -211,3 +211,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/english/errmsg.txt b/sql/share/english/errmsg.txt index 2a6e23b6281..f6ab398e92f 100644 --- a/sql/share/english/errmsg.txt +++ b/sql/share/english/errmsg.txt @@ -211,3 +211,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/estonian/errmsg.txt b/sql/share/estonian/errmsg.txt index 264badebe38..8686b7e17a4 100644 --- a/sql/share/estonian/errmsg.txt +++ b/sql/share/estonian/errmsg.txt @@ -215,3 +215,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/french/errmsg.txt b/sql/share/french/errmsg.txt index 0da5cf94ed8..fb181535764 100644 --- a/sql/share/french/errmsg.txt +++ b/sql/share/french/errmsg.txt @@ -211,3 +211,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/german/errmsg.txt b/sql/share/german/errmsg.txt index 9abbb3a8a2f..eabbff043f3 100644 --- a/sql/share/german/errmsg.txt +++ b/sql/share/german/errmsg.txt @@ -214,3 +214,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/greek/errmsg.txt b/sql/share/greek/errmsg.txt index 8f81fcfda31..2dcbad5ffba 100644 --- a/sql/share/greek/errmsg.txt +++ b/sql/share/greek/errmsg.txt @@ -211,3 +211,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/hungarian/errmsg.txt b/sql/share/hungarian/errmsg.txt index 84d8c56cd04..edeaec62590 100644 --- a/sql/share/hungarian/errmsg.txt +++ b/sql/share/hungarian/errmsg.txt @@ -213,3 +213,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/italian/errmsg.txt b/sql/share/italian/errmsg.txt index b85dc03286a..434fb2fc7a0 100644 --- a/sql/share/italian/errmsg.txt +++ b/sql/share/italian/errmsg.txt @@ -211,3 +211,4 @@ "I lock di aggiornamento non possono essere acquisiti durante una transazione 'READ UNCOMMITTED'", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/japanese/errmsg.txt b/sql/share/japanese/errmsg.txt index 49e58079588..306fe22ab1d 100644 --- a/sql/share/japanese/errmsg.txt +++ b/sql/share/japanese/errmsg.txt @@ -213,3 +213,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/korean/errmsg.txt b/sql/share/korean/errmsg.txt index 2e278dbd129..89e3abd9680 100644 --- a/sql/share/korean/errmsg.txt +++ b/sql/share/korean/errmsg.txt @@ -211,3 +211,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/norwegian-ny/errmsg.txt b/sql/share/norwegian-ny/errmsg.txt index df9efbd28a4..dd9b153acff 100644 --- a/sql/share/norwegian-ny/errmsg.txt +++ b/sql/share/norwegian-ny/errmsg.txt @@ -213,3 +213,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/norwegian/errmsg.txt b/sql/share/norwegian/errmsg.txt index c95669aa016..87c25bd933f 100644 --- a/sql/share/norwegian/errmsg.txt +++ b/sql/share/norwegian/errmsg.txt @@ -213,3 +213,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/polish/errmsg.txt b/sql/share/polish/errmsg.txt index d708bc6fffb..2bb0dbb9802 100644 --- a/sql/share/polish/errmsg.txt +++ b/sql/share/polish/errmsg.txt @@ -215,3 +215,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/portuguese/errmsg.txt b/sql/share/portuguese/errmsg.txt index 8acb2365996..a8a7b0a565f 100644 --- a/sql/share/portuguese/errmsg.txt +++ b/sql/share/portuguese/errmsg.txt @@ -211,3 +211,4 @@ "Travamentos de atualização não podem ser obtidos durante um READ UNCOMMITTED na transação", "DROP DATABASE não permitido enquanto uma 'thread' está assegurando um travamento global de leitura", "CREATE DATABASE não permitido enquanto uma 'thread' está assegurando um travamento global de leitura", +"Wrong arguments to %s", diff --git a/sql/share/romanian/errmsg.txt b/sql/share/romanian/errmsg.txt index 8069f9907bb..9a964780398 100644 --- a/sql/share/romanian/errmsg.txt +++ b/sql/share/romanian/errmsg.txt @@ -215,3 +215,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/russian/errmsg.txt b/sql/share/russian/errmsg.txt index 6bc845d5599..6d4fd4bcea6 100644 --- a/sql/share/russian/errmsg.txt +++ b/sql/share/russian/errmsg.txt @@ -214,3 +214,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/slovak/errmsg.txt b/sql/share/slovak/errmsg.txt index 8631ee6bdeb..de12b57638f 100644 --- a/sql/share/slovak/errmsg.txt +++ b/sql/share/slovak/errmsg.txt @@ -219,3 +219,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Wrong arguments to %s", diff --git a/sql/share/spanish/errmsg.txt b/sql/share/spanish/errmsg.txt index a56bebbcf47..3bb80df41a9 100644 --- a/sql/share/spanish/errmsg.txt +++ b/sql/share/spanish/errmsg.txt @@ -212,3 +212,4 @@ "Bloqueos de actualización no pueden ser adqueridos durante una transición READ UNCOMMITTED", "DROP DATABASE no permitido mientras un thread está ejerciendo un bloqueo de lectura global", "CREATE DATABASE no permitido mientras un thread está ejerciendo un bloqueo de lectura global", +"Wrong arguments to %s", diff --git a/sql/share/swedish/errmsg.OLD b/sql/share/swedish/errmsg.OLD index fc26a08e9ee..cc54e051e63 100644 --- a/sql/share/swedish/errmsg.OLD +++ b/sql/share/swedish/errmsg.OLD @@ -209,3 +209,7 @@ "Lock wait timeout exceeded", "The total number of locks exceeds the lock table size", "Update locks cannot be acquired during a READ UNCOMMITTED transaction", +"DROP DATABASE not allowed while thread is holding global read lock", +"CREATE DATABASE not allowed while thread is holding global read lock", +#ER_WRONG_ARGUMENTS +"Felaktiga argument till %s", diff --git a/sql/share/swedish/errmsg.txt b/sql/share/swedish/errmsg.txt index 7f43afd04b6..0451e4fe6eb 100644 --- a/sql/share/swedish/errmsg.txt +++ b/sql/share/swedish/errmsg.txt @@ -211,3 +211,4 @@ "Update locks cannot be acquired during a READ UNCOMMITTED transaction", "DROP DATABASE not allowed while thread is holding global read lock", "CREATE DATABASE not allowed while thread is holding global read lock", +"Felaktiga argument till %s", From ee82985a98c2c302e54a81ef586ffc8a867a550c Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 4 Aug 2001 01:13:44 +0300 Subject: [PATCH 31/51] Fixed bad manual merge Docs/manual.texi: Fixed bad merge --- Docs/manual.texi | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index ee7c21f28ba..256362850f0 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -31763,6 +31763,15 @@ mysql> select * from bar; For each row in table @code{foo}, a row is inserted in @code{bar} with the values from @code{foo} and default values for the new columns. +@code{CREATE TABLE ... SELECT} will not automaticly create any indexes +for you. This is done intentionally to make the command as flexible as +possible. If you want to have indexes in the created table, you should +specify these before the @code{SELECT} statement: + +@example +mysql> create table bar (unique (n)) select n from foo; +@end example + If any errors occur while copying the data to the table, it will automatically be deleted. @@ -36670,12 +36679,23 @@ the Internet with a search engine. It is with this reasoning that such rows have been assigned a low semantical value in @strong{this particular dataset}. @menu +* Fulltext restrictions:: * Fulltext Fine-tuning:: * Fulltext Features to Appear in MySQL 4.0:: * Fulltext TODO:: @end menu -@node Fulltext Fine-tuning, Fulltext Features to Appear in MySQL 4.0, Fulltext Search, Fulltext Search +@node Fulltext restrictions, Fulltext Fine-tuning, Fulltext Search, Fulltext Search +@section Fulltext restrictions +@itemize @bullet +@item +All parameters to the @code{MATCH} function must be columns from the +same table that is part of the same fulltext index. +@item +The argument to @code{AGAINST} must be a constant string. +@end itemize + +@node Fulltext Fine-tuning, Fulltext Features to Appear in MySQL 4.0, Fulltext restrictions, Fulltext Search @section Fine-tuning MySQL Full-text Search Unfortunately, full-text search has no user-tunable parameters yet, @@ -36732,7 +36752,7 @@ implemented in the 4.0 tree. It explains @code{OPTIMIZE TABLE} with @code{FULLTEXT} indexes are now up to 100 times faster. -@item @code{MATCH ... AGAINST} now supports the following +@item @code{MATCH ... AGAINST} is going to supports the following @strong{boolean operators}: @itemize @bullet From c67510f0939fbcad4f2f0efcc79272322d5ffa57 Mon Sep 17 00:00:00 2001 From: unknown Date: Sat, 4 Aug 2001 19:36:14 +0300 Subject: [PATCH 32/51] srv0srv.h Support raw disk partitions as data files srv0start.c Support raw disk partitions as data files srv0srv.c Support raw disk partitions as data files row0purge.c < 4 GB rows, doublewrite, hang fixes row0row.c < 4 GB rows, doublewrite, hang fixes row0sel.c < 4 GB rows, doublewrite, hang fixes row0uins.c < 4 GB rows, doublewrite, hang fixes row0umod.c < 4 GB rows, doublewrite, hang fixes row0undo.c < 4 GB rows, doublewrite, hang fixes row0upd.c < 4 GB rows, doublewrite, hang fixes srv0srv.c < 4 GB rows, doublewrite, hang fixes srv0start.c < 4 GB rows, doublewrite, hang fixes sync0rw.c < 4 GB rows, doublewrite, hang fixes sync0sync.c < 4 GB rows, doublewrite, hang fixes trx0purge.c < 4 GB rows, doublewrite, hang fixes trx0rec.c < 4 GB rows, doublewrite, hang fixes trx0sys.c < 4 GB rows, doublewrite, hang fixes btr0btr.c < 4 GB rows, doublewrite, hang fixes btr0cur.c < 4 GB rows, doublewrite, hang fixes buf0buf.c < 4 GB rows, doublewrite, hang fixes buf0flu.c < 4 GB rows, doublewrite, hang fixes buf0rea.c < 4 GB rows, doublewrite, hang fixes data0data.c < 4 GB rows, doublewrite, hang fixes fil0fil.c < 4 GB rows, doublewrite, hang fixes fsp0fsp.c < 4 GB rows, doublewrite, hang fixes ibuf0ibuf.c < 4 GB rows, doublewrite, hang fixes lock0lock.c < 4 GB rows, doublewrite, hang fixes log0log.c < 4 GB rows, doublewrite, hang fixes log0recv.c < 4 GB rows, doublewrite, hang fixes os0file.c < 4 GB rows, doublewrite, hang fixes page0cur.c < 4 GB rows, doublewrite, hang fixes pars0pars.c < 4 GB rows, doublewrite, hang fixes rem0cmp.c < 4 GB rows, doublewrite, hang fixes rem0rec.c < 4 GB rows, doublewrite, hang fixes row0ins.c < 4 GB rows, doublewrite, hang fixes row0mysql.c < 4 GB rows, doublewrite, hang fixes univ.i < 4 GB rows, doublewrite, hang fixes data0data.ic < 4 GB rows, doublewrite, hang fixes mach0data.ic < 4 GB rows, doublewrite, hang fixes rem0rec.ic < 4 GB rows, doublewrite, hang fixes row0upd.ic < 4 GB rows, doublewrite, hang fixes trx0rec.ic < 4 GB rows, doublewrite, hang fixes rem0cmp.h < 4 GB rows, doublewrite, hang fixes rem0rec.h < 4 GB rows, doublewrite, hang fixes row0ins.h < 4 GB rows, doublewrite, hang fixes row0mysql.h < 4 GB rows, doublewrite, hang fixes row0row.h < 4 GB rows, doublewrite, hang fixes row0upd.h < 4 GB rows, doublewrite, hang fixes srv0srv.h < 4 GB rows, doublewrite, hang fixes sync0sync.h < 4 GB rows, doublewrite, hang fixes trx0rec.h < 4 GB rows, doublewrite, hang fixes trx0sys.h < 4 GB rows, doublewrite, hang fixes trx0types.h < 4 GB rows, doublewrite, hang fixes trx0undo.h < 4 GB rows, doublewrite, hang fixes ut0dbg.h < 4 GB rows, doublewrite, hang fixes ut0ut.h < 4 GB rows, doublewrite, hang fixes btr0btr.h < 4 GB rows, doublewrite, hang fixes btr0cur.h < 4 GB rows, doublewrite, hang fixes buf0buf.h < 4 GB rows, doublewrite, hang fixes buf0flu.h < 4 GB rows, doublewrite, hang fixes data0data.h < 4 GB rows, doublewrite, hang fixes dict0mem.h < 4 GB rows, doublewrite, hang fixes fil0fil.h < 4 GB rows, doublewrite, hang fixes fsp0fsp.h < 4 GB rows, doublewrite, hang fixes os0file.h < 4 GB rows, doublewrite, hang fixes innobase/include/btr0btr.h: < 4 GB rows, doublewrite, hang fixes innobase/include/btr0cur.h: < 4 GB rows, doublewrite, hang fixes innobase/include/buf0buf.h: < 4 GB rows, doublewrite, hang fixes innobase/include/buf0flu.h: < 4 GB rows, doublewrite, hang fixes innobase/include/data0data.h: < 4 GB rows, doublewrite, hang fixes innobase/include/dict0mem.h: < 4 GB rows, doublewrite, hang fixes innobase/include/fil0fil.h: < 4 GB rows, doublewrite, hang fixes innobase/include/fsp0fsp.h: < 4 GB rows, doublewrite, hang fixes innobase/include/os0file.h: < 4 GB rows, doublewrite, hang fixes innobase/include/rem0cmp.h: < 4 GB rows, doublewrite, hang fixes innobase/include/rem0rec.h: < 4 GB rows, doublewrite, hang fixes innobase/include/row0ins.h: < 4 GB rows, doublewrite, hang fixes innobase/include/row0mysql.h: < 4 GB rows, doublewrite, hang fixes innobase/include/row0row.h: < 4 GB rows, doublewrite, hang fixes innobase/include/row0upd.h: < 4 GB rows, doublewrite, hang fixes innobase/include/sync0sync.h: < 4 GB rows, doublewrite, hang fixes innobase/include/trx0rec.h: < 4 GB rows, doublewrite, hang fixes innobase/include/trx0sys.h: < 4 GB rows, doublewrite, hang fixes innobase/include/trx0types.h: < 4 GB rows, doublewrite, hang fixes innobase/include/trx0undo.h: < 4 GB rows, doublewrite, hang fixes innobase/include/ut0dbg.h: < 4 GB rows, doublewrite, hang fixes innobase/include/ut0ut.h: < 4 GB rows, doublewrite, hang fixes innobase/include/data0data.ic: < 4 GB rows, doublewrite, hang fixes innobase/include/mach0data.ic: < 4 GB rows, doublewrite, hang fixes innobase/include/rem0rec.ic: < 4 GB rows, doublewrite, hang fixes innobase/include/row0upd.ic: < 4 GB rows, doublewrite, hang fixes innobase/include/trx0rec.ic: < 4 GB rows, doublewrite, hang fixes innobase/include/univ.i: < 4 GB rows, doublewrite, hang fixes innobase/btr/btr0btr.c: < 4 GB rows, doublewrite, hang fixes innobase/btr/btr0cur.c: < 4 GB rows, doublewrite, hang fixes innobase/buf/buf0buf.c: < 4 GB rows, doublewrite, hang fixes innobase/buf/buf0flu.c: < 4 GB rows, doublewrite, hang fixes innobase/buf/buf0rea.c: < 4 GB rows, doublewrite, hang fixes innobase/data/data0data.c: < 4 GB rows, doublewrite, hang fixes innobase/fil/fil0fil.c: < 4 GB rows, doublewrite, hang fixes innobase/fsp/fsp0fsp.c: < 4 GB rows, doublewrite, hang fixes innobase/ibuf/ibuf0ibuf.c: < 4 GB rows, doublewrite, hang fixes innobase/lock/lock0lock.c: < 4 GB rows, doublewrite, hang fixes innobase/log/log0log.c: < 4 GB rows, doublewrite, hang fixes innobase/log/log0recv.c: < 4 GB rows, doublewrite, hang fixes innobase/os/os0file.c: < 4 GB rows, doublewrite, hang fixes innobase/page/page0cur.c: < 4 GB rows, doublewrite, hang fixes innobase/pars/pars0pars.c: < 4 GB rows, doublewrite, hang fixes innobase/rem/rem0cmp.c: < 4 GB rows, doublewrite, hang fixes innobase/rem/rem0rec.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0ins.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0mysql.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0purge.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0row.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0sel.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0uins.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0umod.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0undo.c: < 4 GB rows, doublewrite, hang fixes innobase/row/row0upd.c: < 4 GB rows, doublewrite, hang fixes innobase/sync/sync0rw.c: < 4 GB rows, doublewrite, hang fixes innobase/sync/sync0sync.c: < 4 GB rows, doublewrite, hang fixes innobase/trx/trx0purge.c: < 4 GB rows, doublewrite, hang fixes innobase/trx/trx0rec.c: < 4 GB rows, doublewrite, hang fixes innobase/trx/trx0sys.c: < 4 GB rows, doublewrite, hang fixes innobase/srv/srv0srv.c: Support raw disk partitions as data files innobase/srv/srv0start.c: Support raw disk partitions as data files innobase/include/srv0srv.h: Support raw disk partitions as data files --- innobase/btr/btr0btr.c | 71 +-- innobase/btr/btr0cur.c | 820 ++++++++++++++++++++++++++++++++-- innobase/buf/buf0buf.c | 83 +++- innobase/buf/buf0flu.c | 195 +++++++- innobase/buf/buf0rea.c | 14 +- innobase/data/data0data.c | 171 ++++++- innobase/fil/fil0fil.c | 81 +++- innobase/fsp/fsp0fsp.c | 4 +- innobase/ibuf/ibuf0ibuf.c | 7 +- innobase/include/btr0btr.h | 38 ++ innobase/include/btr0cur.h | 123 ++++- innobase/include/buf0buf.h | 8 + innobase/include/buf0flu.h | 2 +- innobase/include/data0data.h | 58 ++- innobase/include/data0data.ic | 7 +- innobase/include/dict0mem.h | 2 +- innobase/include/fil0fil.h | 10 + innobase/include/fsp0fsp.h | 2 +- innobase/include/mach0data.ic | 4 +- innobase/include/os0file.h | 18 +- innobase/include/rem0cmp.h | 13 +- innobase/include/rem0rec.h | 53 +++ innobase/include/rem0rec.ic | 72 ++- innobase/include/row0ins.h | 6 + innobase/include/row0mysql.h | 8 +- innobase/include/row0row.h | 1 + innobase/include/row0upd.h | 12 +- innobase/include/row0upd.ic | 5 + innobase/include/srv0srv.h | 22 +- innobase/include/sync0sync.h | 2 + innobase/include/trx0rec.h | 16 +- innobase/include/trx0rec.ic | 17 + innobase/include/trx0sys.h | 70 +++ innobase/include/trx0types.h | 1 + innobase/include/trx0undo.h | 4 +- innobase/include/univ.i | 24 +- innobase/include/ut0dbg.h | 10 +- innobase/include/ut0ut.h | 3 +- innobase/lock/lock0lock.c | 40 +- innobase/log/log0log.c | 15 +- innobase/log/log0recv.c | 3 +- innobase/os/os0file.c | 84 +++- innobase/page/page0cur.c | 8 +- innobase/pars/pars0pars.c | 4 - innobase/rem/rem0cmp.c | 49 +- innobase/rem/rem0rec.c | 67 ++- innobase/row/row0ins.c | 91 +++- innobase/row/row0mysql.c | 42 +- innobase/row/row0purge.c | 99 +++- innobase/row/row0row.c | 34 +- innobase/row/row0sel.c | 63 ++- innobase/row/row0uins.c | 9 +- innobase/row/row0umod.c | 121 +++-- innobase/row/row0undo.c | 12 + innobase/row/row0upd.c | 145 ++++-- innobase/srv/srv0srv.c | 160 +++---- innobase/srv/srv0start.c | 135 +++--- innobase/sync/sync0rw.c | 5 +- innobase/sync/sync0sync.c | 36 +- innobase/trx/trx0purge.c | 7 + innobase/trx/trx0rec.c | 62 ++- innobase/trx/trx0sys.c | 319 ++++++++++++- 62 files changed, 3148 insertions(+), 519 deletions(-) diff --git a/innobase/btr/btr0btr.c b/innobase/btr/btr0btr.c index 2507f805cd6..af2029bf1e8 100644 --- a/innobase/btr/btr0btr.c +++ b/innobase/btr/btr0btr.c @@ -71,30 +71,6 @@ btr_page_create( dict_tree_t* tree, /* in: index tree */ mtr_t* mtr); /* in: mtr */ /****************************************************************** -Allocates a new file page to be used in an index tree. */ -static -page_t* -btr_page_alloc( -/*===========*/ - /* out: new allocated page, - x-latched */ - dict_tree_t* tree, /* in: index tree */ - ulint hint_page_no, /* in: hint of a good page */ - byte file_direction, /* in: direction where a possible - page split is made */ - ulint level, /* in: level where the page is placed - in the tree */ - mtr_t* mtr); /* in: mtr */ -/****************************************************************** -Frees a file page used in an index tree. */ -static -void -btr_page_free( -/*==========*/ - dict_tree_t* tree, /* in: index tree */ - page_t* page, /* in, own: page to be freed */ - mtr_t* mtr); /* in: mtr */ -/****************************************************************** Sets the child node file address in a node pointer. */ UNIV_INLINE void @@ -319,11 +295,12 @@ btr_page_alloc_for_ibuf( /****************************************************************** Allocates a new file page to be used in an index tree. NOTE: we assume that the caller has made the reservation for free extents! */ -static + page_t* btr_page_alloc( /*===========*/ - /* out: new allocated page, x-latched */ + /* out: new allocated page, x-latched; + NULL if out of space */ dict_tree_t* tree, /* in: index tree */ ulint hint_page_no, /* in: hint of a good page */ byte file_direction, /* in: direction where a possible @@ -358,7 +335,10 @@ btr_page_alloc( new_page_no = fseg_alloc_free_page_general(seg_header, hint_page_no, file_direction, TRUE, mtr); - ut_a(new_page_no != FIL_NULL); + if (new_page_no == FIL_NULL) { + + return(NULL); + } new_page = buf_page_get(dict_tree_get_space(tree), new_page_no, RW_X_LATCH, mtr); @@ -435,20 +415,22 @@ btr_page_free_for_ibuf( } /****************************************************************** -Frees a file page used in an index tree. */ -static +Frees a file page used in an index tree. Can be used also to (BLOB) +external storage pages, because the page level 0 can be given as an +argument. */ + void -btr_page_free( -/*==========*/ +btr_page_free_low( +/*==============*/ dict_tree_t* tree, /* in: index tree */ page_t* page, /* in: page to be freed, x-latched */ + ulint level, /* in: page level */ mtr_t* mtr) /* in: mtr */ { fseg_header_t* seg_header; page_t* root; ulint space; ulint page_no; - ulint level; ut_ad(mtr_memo_contains(mtr, buf_block_align(page), MTR_MEMO_PAGE_X_FIX)); @@ -465,8 +447,6 @@ btr_page_free( } root = btr_root_get(tree, mtr); - - level = btr_page_get_level(page, mtr); if (level == 0) { seg_header = root + PAGE_HEADER + PAGE_BTR_SEG_LEAF; @@ -480,6 +460,26 @@ btr_page_free( fseg_free_page(seg_header, space, page_no, mtr); } +/****************************************************************** +Frees a file page used in an index tree. NOTE: cannot free field external +storage pages because the page must contain info on its level. */ + +void +btr_page_free( +/*==========*/ + dict_tree_t* tree, /* in: index tree */ + page_t* page, /* in: page to be freed, x-latched */ + mtr_t* mtr) /* in: mtr */ +{ + ulint level; + + ut_ad(mtr_memo_contains(mtr, buf_block_align(page), + MTR_MEMO_PAGE_X_FIX)); + level = btr_page_get_level(page, mtr); + + btr_page_free_low(tree, page, level, mtr); +} + /****************************************************************** Sets the child node file address in a node pointer. */ UNIV_INLINE @@ -1276,6 +1276,7 @@ btr_insert_on_non_leaf_level( dtuple_t* tuple, /* in: the record to be inserted */ mtr_t* mtr) /* in: mtr */ { + big_rec_t* dummy_big_rec; btr_cur_t cursor; ulint err; rec_t* rec; @@ -1294,7 +1295,7 @@ btr_insert_on_non_leaf_level( | BTR_KEEP_SYS_FLAG | BTR_NO_UNDO_LOG_FLAG, &cursor, tuple, - &rec, NULL, mtr); + &rec, &dummy_big_rec, NULL, mtr); ut_a(err == DB_SUCCESS); } diff --git a/innobase/btr/btr0cur.c b/innobase/btr/btr0cur.c index a8680c6b380..e8ff88c6f4f 100644 --- a/innobase/btr/btr0cur.c +++ b/innobase/btr/btr0cur.c @@ -12,7 +12,7 @@ many pages in the tablespace before we start the operation, because if leaf splitting has been started, it is difficult to undo, except by crashing the database and doing a roll-forward. -(c) 1994-1996 Innobase Oy +(c) 1994-2001 Innobase Oy Created 10/16/1994 Heikki Tuuri *******************************************************/ @@ -49,6 +49,15 @@ can be released by page reorganize, then it is reorganized */ this many index pages */ #define BTR_KEY_VAL_ESTIMATE_N_PAGES 8 +/* The structure of a BLOB part header */ +/*--------------------------------------*/ +#define BTR_BLOB_HDR_PART_LEN 0 /* BLOB part len on this + page */ +#define BTR_BLOB_HDR_NEXT_PAGE_NO 4 /* next BLOB part page no, + FIL_NULL if none */ +/*--------------------------------------*/ +#define BTR_BLOB_HDR_SIZE 8 + /*********************************************************************** Adds path information to the cursor for the current page, for which the binary search has been performed. */ @@ -60,6 +69,19 @@ btr_cur_add_path_info( ulint height, /* in: height of the page in tree; 0 means leaf node */ ulint root_height); /* in: root node height in tree */ +/*************************************************************** +Frees the externally stored fields for a record, if the field is mentioned +in the update vector. */ +static +void +btr_rec_free_updated_extern_fields( +/*===============================*/ + dict_index_t* index, /* in: index of rec; the index tree MUST be + X-latched */ + rec_t* rec, /* in: record */ + upd_t* update, /* in: update vector */ + mtr_t* mtr); /* in: mini-transaction handle which contains + an X-latch to record page and to the tree */ /*==================== B-TREE SEARCH =========================*/ @@ -745,9 +767,13 @@ btr_cur_optimistic_insert( dtuple_t* entry, /* in: entry to insert */ rec_t** rec, /* out: pointer to inserted record if succeed */ + big_rec_t** big_rec,/* out: big rec vector whose fields have to + be stored externally by the caller, or + NULL */ que_thr_t* thr, /* in: query thread or NULL */ mtr_t* mtr) /* in: mtr */ { + big_rec_t* big_rec_vec = NULL; dict_index_t* index; page_cur_t* page_cursor; page_t* page; @@ -764,6 +790,8 @@ btr_cur_optimistic_insert( ut_ad(dtuple_check_typed(entry)); + *big_rec = NULL; + page = btr_cur_get_page(cursor); index = cursor->index; @@ -772,15 +800,27 @@ btr_cur_optimistic_insert( max_size = page_get_max_insert_size_after_reorganize(page, 1); level = btr_page_get_level(page, mtr); +calculate_sizes_again: /* Calculate the record size when entry is converted to a record */ data_size = dtuple_get_data_size(entry); extra_size = rec_get_converted_extra_size(data_size, dtuple_get_n_fields(entry)); rec_size = data_size + extra_size; - if (rec_size >= page_get_free_space_of_empty() / 2) { + if ((rec_size >= page_get_free_space_of_empty() / 2) + || (rec_size >= REC_MAX_DATA_SIZE)) { - return(DB_TOO_BIG_RECORD); + /* The record is so big that we have to store some fields + externally on separate database pages */ + + big_rec_vec = dtuple_convert_big_rec(index, entry); + + if (big_rec_vec == NULL) { + + return(DB_TOO_BIG_RECORD); + } + + goto calculate_sizes_again; } /* If there have been many consecutive inserts, and we are on the leaf @@ -795,7 +835,11 @@ btr_cur_optimistic_insert( && (0 == level) && (btr_page_get_split_rec_to_right(cursor, &dummy_rec) || btr_page_get_split_rec_to_left(cursor, &dummy_rec))) { - + + if (big_rec_vec) { + dtuple_convert_back_big_rec(index, entry, big_rec_vec); + } + return(DB_FAIL); } @@ -804,6 +848,9 @@ btr_cur_optimistic_insert( || (page_get_max_insert_size(page, 1) >= rec_size) || (page_get_n_recs(page) <= 1))) { + if (big_rec_vec) { + dtuple_convert_back_big_rec(index, entry, big_rec_vec); + } return(DB_FAIL); } @@ -812,6 +859,9 @@ btr_cur_optimistic_insert( if (err != DB_SUCCESS) { + if (big_rec_vec) { + dtuple_convert_back_big_rec(index, entry, big_rec_vec); + } return(err); } @@ -835,6 +885,19 @@ btr_cur_optimistic_insert( *rec = page_cur_tuple_insert(page_cursor, entry, mtr); + if (!(*rec)) { + char* err_buf = mem_alloc(1000); + + dtuple_sprintf(err_buf, 900, entry); + + fprintf(stderr, + "InnoDB: Error: cannot insert tuple %s to index %s of table %s\n" + "InnoDB: max insert size %lu\n", + err_buf, index->name, index->table->name, max_size); + + mem_free(err_buf); + } + ut_a(*rec); /* <- We calculated above the record would fit */ } @@ -845,6 +908,7 @@ btr_cur_optimistic_insert( btr_search_update_hash_on_insert(cursor); } #endif + if (!(flags & BTR_NO_LOCKING_FLAG) && inherit) { lock_update_insert(*rec); @@ -860,6 +924,8 @@ btr_cur_optimistic_insert( rec_size + PAGE_DIR_SLOT_SIZE); } + *big_rec = big_rec_vec; + return(DB_SUCCESS); } @@ -884,17 +950,24 @@ btr_cur_pessimistic_insert( dtuple_t* entry, /* in: entry to insert */ rec_t** rec, /* out: pointer to inserted record if succeed */ + big_rec_t** big_rec,/* out: big rec vector whose fields have to + be stored externally by the caller, or + NULL */ que_thr_t* thr, /* in: query thread or NULL */ mtr_t* mtr) /* in: mtr */ { - page_t* page; - ulint err; - ibool dummy_inh; - ibool success; - ulint n_extents = 0; + dict_index_t* index = cursor->index; + big_rec_t* big_rec_vec = NULL; + page_t* page; + ulint err; + ibool dummy_inh; + ibool success; + ulint n_extents = 0; ut_ad(dtuple_check_typed(entry)); + *big_rec = NULL; + page = btr_cur_get_page(cursor); ut_ad(mtr_memo_contains(mtr, @@ -908,8 +981,8 @@ btr_cur_pessimistic_insert( cursor->flag = BTR_CUR_BINARY; - err = btr_cur_optimistic_insert(flags, cursor, entry, rec, thr, mtr); - + err = btr_cur_optimistic_insert(flags, cursor, entry, rec, big_rec, + thr, mtr); if (err != DB_FAIL) { return(err); @@ -932,7 +1005,7 @@ btr_cur_pessimistic_insert( n_extents = cursor->tree_height / 16 + 3; - success = fsp_reserve_free_extents(cursor->index->space, + success = fsp_reserve_free_extents(index->space, n_extents, FSP_NORMAL, mtr); if (!success) { err = DB_OUT_OF_FILE_SPACE; @@ -941,7 +1014,22 @@ btr_cur_pessimistic_insert( } } - if (dict_tree_get_page(cursor->index->tree) + if ((rec_get_converted_size(entry) + >= page_get_free_space_of_empty() / 2) + || (rec_get_converted_size(entry) >= REC_MAX_DATA_SIZE)) { + + /* The record is so big that we have to store some fields + externally on separate database pages */ + + big_rec_vec = dtuple_convert_big_rec(index, entry); + + if (big_rec_vec == NULL) { + + return(DB_TOO_BIG_RECORD); + } + } + + if (dict_tree_get_page(index->tree) == buf_frame_get_page_no(page)) { /* The page is the root page */ @@ -950,7 +1038,7 @@ btr_cur_pessimistic_insert( *rec = btr_page_split_and_insert(cursor, entry, mtr); } - btr_cur_position(cursor->index, page_rec_get_prev(*rec), cursor); + btr_cur_position(index, page_rec_get_prev(*rec), cursor); #ifdef BTR_CUR_ADAPT btr_search_update_hash_on_insert(cursor); @@ -963,9 +1051,11 @@ btr_cur_pessimistic_insert( err = DB_SUCCESS; if (n_extents > 0) { - fil_space_release_free_extents(cursor->index->space, n_extents); + fil_space_release_free_extents(index->space, n_extents); } - + + *big_rec = big_rec_vec; + return(err); } @@ -1227,7 +1317,8 @@ btr_cur_optimistic_update( dulint roll_ptr; trx_t* trx; mem_heap_t* heap; - ibool reorganized = FALSE; + ibool reorganized = FALSE; + ulint i; /* Only clustered index records are updated using this function */ ut_ad((cursor->index)->type & DICT_CLUSTERED); @@ -1247,6 +1338,23 @@ btr_cur_optimistic_update( cmpl_info, thr, mtr)); } + for (i = 0; i < upd_get_n_fields(update); i++) { + if (upd_get_nth_field(update, i)->extern_storage) { + + /* Externally stored fields are treated in pessimistic + update */ + + return(DB_OVERFLOW); + } + } + + if (rec_contains_externally_stored_field(btr_cur_get_rec(cursor))) { + /* Externally stored fields are treated in pessimistic + update */ + + return(DB_OVERFLOW); + } + page_cursor = btr_cur_get_page_cur(cursor); heap = mem_heap_create(1024); @@ -1260,9 +1368,9 @@ btr_cur_optimistic_update( if (new_rec_size >= page_get_free_space_of_empty() / 2) { - mem_heap_free(heap); + mem_heap_free(heap); - return(DB_TOO_BIG_RECORD); + return(DB_OVERFLOW); } max_size = old_rec_size @@ -1377,6 +1485,48 @@ btr_cur_pess_upd_restore_supremum( rec); } +/*************************************************************** +Replaces and copies the data in the new column values stored in the +update vector to the clustered index entry given. */ +static +void +btr_cur_copy_new_col_vals( +/*======================*/ + dtuple_t* entry, /* in/out: index entry where replaced */ + upd_t* update, /* in: update vector */ + mem_heap_t* heap) /* in: heap where data is copied */ +{ + upd_field_t* upd_field; + dfield_t* dfield; + dfield_t* new_val; + ulint field_no; + byte* data; + ulint i; + + dtuple_set_info_bits(entry, update->info_bits); + + for (i = 0; i < upd_get_n_fields(update); i++) { + + upd_field = upd_get_nth_field(update, i); + + field_no = upd_field->field_no; + + dfield = dtuple_get_nth_field(entry, field_no); + + new_val = &(upd_field->new_val); + + if (new_val->len == UNIV_SQL_NULL) { + data = NULL; + } else { + data = mem_heap_alloc(heap, new_val->len); + + ut_memcpy(data, new_val->data, new_val->len); + } + + dfield_set_data(dfield, data, new_val->len); + } +} + /***************************************************************** Performs an update of a record on a page of a tree. It is assumed that mtr holds an x-latch on the tree and on the cursor page. If the @@ -1389,8 +1539,9 @@ btr_cur_pessimistic_update( /* out: DB_SUCCESS or error code */ ulint flags, /* in: undo logging, locking, and rollback flags */ - btr_cur_t* cursor, /* in: cursor on the record to update; - cursor does not stay valid */ + btr_cur_t* cursor, /* in: cursor on the record to update */ + big_rec_t** big_rec,/* out: big rec vector whose fields have to + be stored externally by the caller, or NULL */ upd_t* update, /* in: update vector; this is allowed also contain trx id and roll ptr fields, but the values in update vector have no effect */ @@ -1399,6 +1550,8 @@ btr_cur_pessimistic_update( que_thr_t* thr, /* in: query thread */ mtr_t* mtr) /* in: mtr */ { + big_rec_t* big_rec_vec = NULL; + big_rec_t* dummy_big_rec; dict_index_t* index; page_t* page; dict_tree_t* tree; @@ -1414,6 +1567,11 @@ btr_cur_pessimistic_update( ibool was_first; ibool success; ulint n_extents = 0; + ulint* ext_vect; + ulint n_ext_vect; + ulint reserve_flag; + + *big_rec = NULL; page = btr_cur_get_page(cursor); rec = btr_cur_get_rec(cursor); @@ -1449,8 +1607,14 @@ btr_cur_pessimistic_update( n_extents = cursor->tree_height / 16 + 3; + if (flags & BTR_NO_UNDO_LOG_FLAG) { + reserve_flag = FSP_CLEANING; + } else { + reserve_flag = FSP_NORMAL; + } + success = fsp_reserve_free_extents(cursor->index->space, - n_extents, FSP_NORMAL, mtr); + n_extents, reserve_flag, mtr); if (!success) { err = DB_OUT_OF_FILE_SPACE; @@ -1464,7 +1628,7 @@ btr_cur_pessimistic_update( new_entry = row_rec_to_index_entry(ROW_COPY_DATA, index, rec, heap); - row_upd_clust_index_replace_new_col_vals(new_entry, update); + btr_cur_copy_new_col_vals(new_entry, update, heap); if (!(flags & BTR_KEEP_SYS_FLAG)) { row_upd_index_entry_sys_field(new_entry, index, DATA_ROLL_PTR, @@ -1487,17 +1651,49 @@ btr_cur_pessimistic_update( lock_rec_store_on_page_infimum(rec); btr_search_update_hash_on_delete(cursor); + + if (flags & BTR_NO_UNDO_LOG_FLAG) { + /* We are in a transaction rollback undoing a row + update: we must free possible externally stored fields + which got new values in the update */ + + ut_a(big_rec_vec == NULL); + + btr_rec_free_updated_extern_fields(index, rec, update, mtr); + } + + /* We have to set appropriate extern storage bits in the new + record to be inserted: we have to remember which fields were such */ + + ext_vect = mem_heap_alloc(heap, sizeof(ulint) * rec_get_n_fields(rec)); + n_ext_vect = btr_push_update_extern_fields(ext_vect, rec, update); + page_cur_delete_rec(page_cursor, mtr); page_cur_move_to_prev(page_cursor); - if (optim_err == DB_UNDERFLOW) { - rec = btr_cur_insert_if_possible(cursor, new_entry, + if ((rec_get_converted_size(new_entry) >= + page_get_free_space_of_empty() / 2) + || (rec_get_converted_size(new_entry) >= REC_MAX_DATA_SIZE)) { + + big_rec_vec = dtuple_convert_big_rec(index, new_entry); + + if (big_rec_vec == NULL) { + + mem_heap_free(heap); + + goto return_after_reservations; + } + } + + rec = btr_cur_insert_if_possible(cursor, new_entry, &dummy_reorganized, mtr); - ut_a(rec); /* <- We knew the insert would fit */ + ut_a(rec || optim_err != DB_UNDERFLOW); + if (rec) { lock_rec_restore_from_page_infimum(rec, page); - + rec_set_field_extern_bits(rec, ext_vect, n_ext_vect, mtr); + btr_cur_compress_if_useful(cursor, mtr); err = DB_SUCCESS; @@ -1521,9 +1717,13 @@ btr_cur_pessimistic_update( err = btr_cur_pessimistic_insert(BTR_NO_UNDO_LOG_FLAG | BTR_NO_LOCKING_FLAG | BTR_KEEP_SYS_FLAG, - cursor, new_entry, &rec, NULL, mtr); + cursor, new_entry, &rec, + &dummy_big_rec, NULL, mtr); ut_a(rec); ut_a(err == DB_SUCCESS); + ut_a(dummy_big_rec == NULL); + + rec_set_field_extern_bits(rec, ext_vect, n_ext_vect, mtr); lock_rec_restore_from_page_infimum(rec, page); @@ -1541,9 +1741,12 @@ btr_cur_pessimistic_update( return_after_reservations: if (n_extents > 0) { - fil_space_release_free_extents(cursor->index->space, n_extents); + fil_space_release_free_extents(cursor->index->space, + n_extents); } + *big_rec = big_rec_vec; + return(err); } @@ -1932,6 +2135,11 @@ btr_cur_optimistic_delete( ut_ad(btr_page_get_level(page, mtr) == 0); + if (rec_contains_externally_stored_field(btr_cur_get_rec(cursor))) { + + return(FALSE); + } + if (btr_cur_can_delete_without_compress(cursor, mtr)) { lock_update_delete(btr_cur_get_rec(cursor)); @@ -2009,6 +2217,8 @@ btr_cur_pessimistic_delete( } } + btr_rec_free_externally_stored_fields(cursor->index, + btr_cur_get_rec(cursor), mtr); if ((page_get_n_recs(page) < 2) && (dict_tree_get_page(btr_cur_get_tree(cursor)) != buf_frame_get_page_no(page))) { @@ -2079,7 +2289,7 @@ return_after_reservations: fil_space_release_free_extents(cursor->index->space, n_extents); } - return(ret); + return(ret); } /*********************************************************************** @@ -2292,3 +2502,553 @@ btr_estimate_number_of_different_key_vals( return(index->table->stat_n_rows / (total_n_recs / n_diff)); } + +/*================== EXTERNAL STORAGE OF BIG FIELDS ===================*/ + +/*********************************************************************** +Stores the positions of the fields marked as extern storage in the update +vector, and also those fields who are marked as extern storage in rec +and not mentioned in updated fields. We use this function to remember +which fields we must mark as extern storage in a record inserted for an +update. */ + +ulint +btr_push_update_extern_fields( +/*==========================*/ + /* out: number of values stored in ext_vect */ + ulint* ext_vect, /* in: array of ulints, must be preallocated + to have space for all fields in rec */ + rec_t* rec, /* in: record */ + upd_t* update) /* in: update vector or NULL */ +{ + ulint n_pushed = 0; + ibool is_updated; + ulint n; + ulint j; + ulint i; + + if (update) { + n = upd_get_n_fields(update); + + for (i = 0; i < n; i++) { + + if (upd_get_nth_field(update, i)->extern_storage) { + + ext_vect[n_pushed] = + upd_get_nth_field(update, i)->field_no; + + n_pushed++; + } + } + } + + n = rec_get_n_fields(rec); + + for (i = 0; i < n; i++) { + if (rec_get_nth_field_extern_bit(rec, i)) { + + /* Check it is not in updated fields */ + is_updated = FALSE; + + if (update) { + for (j = 0; j < upd_get_n_fields(update); + j++) { + if (upd_get_nth_field(update, j) + ->field_no == i) { + is_updated = TRUE; + } + } + } + + if (!is_updated) { + ext_vect[n_pushed] = i; + n_pushed++; + } + } + } + + return(n_pushed); +} + +/*********************************************************************** +Returns the length of a BLOB part stored on the header page. */ +static +ulint +btr_blob_get_part_len( +/*==================*/ + /* out: part length */ + byte* blob_header) /* in: blob header */ +{ + return(mach_read_from_4(blob_header + BTR_BLOB_HDR_PART_LEN)); +} + +/*********************************************************************** +Returns the page number where the next BLOB part is stored. */ +static +ulint +btr_blob_get_next_page_no( +/*======================*/ + /* out: page number or FIL_NULL if + no more pages */ + byte* blob_header) /* in: blob header */ +{ + return(mach_read_from_4(blob_header + BTR_BLOB_HDR_NEXT_PAGE_NO)); +} + +/*********************************************************************** +Stores the fields in big_rec_vec to the tablespace and puts pointers to +them in rec. The fields are stored on pages allocated from leaf node +file segment of the index tree. */ + +ulint +btr_store_big_rec_extern_fields( +/*============================*/ + /* out: DB_SUCCESS or error */ + dict_index_t* index, /* in: index of rec; the index tree + MUST be X-latched */ + rec_t* rec, /* in: record */ + big_rec_t* big_rec_vec, /* in: vector containing fields + to be stored externally */ + mtr_t* local_mtr) /* in: mtr containing the latch to + rec and to the tree */ +{ + byte* data; + ulint local_len; + ulint extern_len; + ulint store_len; + ulint page_no; + page_t* page; + ulint space_id; + page_t* prev_page; + page_t* rec_page; + ulint prev_page_no; + ulint hint_page_no; + ulint i; + mtr_t mtr; + + ut_ad(mtr_memo_contains(local_mtr, dict_tree_get_lock(index->tree), + MTR_MEMO_X_LOCK)); + ut_ad(mtr_memo_contains(local_mtr, buf_block_align(data), + MTR_MEMO_PAGE_X_FIX)); + ut_a(index->type & DICT_CLUSTERED); + + space_id = buf_frame_get_space_id(rec); + + /* We have to create a file segment to the tablespace + for each field and put the pointer to the field in rec */ + + for (i = 0; i < big_rec_vec->n_fields; i++) { + + data = rec_get_nth_field(rec, big_rec_vec->fields[i].field_no, + &local_len); + ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE); + local_len -= BTR_EXTERN_FIELD_REF_SIZE; + extern_len = big_rec_vec->fields[i].len; + + ut_a(extern_len > 0); + + prev_page_no = FIL_NULL; + + while (extern_len > 0) { + mtr_start(&mtr); + + if (prev_page_no == FIL_NULL) { + hint_page_no = buf_frame_get_page_no(rec) + 1; + } else { + hint_page_no = prev_page_no + 1; + } + + page = btr_page_alloc(index->tree, hint_page_no, + FSP_NO_DIR, 0, &mtr); + if (page == NULL) { + + mtr_commit(&mtr); + + return(DB_OUT_OF_FILE_SPACE); + } + + page_no = buf_frame_get_page_no(page); + + if (prev_page_no != FIL_NULL) { + prev_page = buf_page_get(space_id, + prev_page_no, + RW_X_LATCH, &mtr); + + buf_page_dbg_add_level(prev_page, + SYNC_EXTERN_STORAGE); + + mlog_write_ulint(prev_page + FIL_PAGE_DATA + + BTR_BLOB_HDR_NEXT_PAGE_NO, + page_no, MLOG_4BYTES, &mtr); + } + + if (extern_len > (UNIV_PAGE_SIZE - FIL_PAGE_DATA + - BTR_BLOB_HDR_SIZE + - FIL_PAGE_DATA_END)) { + store_len = UNIV_PAGE_SIZE - FIL_PAGE_DATA + - BTR_BLOB_HDR_SIZE + - FIL_PAGE_DATA_END; + } else { + store_len = extern_len; + } + + mlog_write_string(page + FIL_PAGE_DATA + + BTR_BLOB_HDR_SIZE, + big_rec_vec->fields[i].data + + big_rec_vec->fields[i].len + - extern_len, + store_len, &mtr); + mlog_write_ulint(page + FIL_PAGE_DATA + + BTR_BLOB_HDR_PART_LEN, + store_len, MLOG_4BYTES, &mtr); + mlog_write_ulint(page + FIL_PAGE_DATA + + BTR_BLOB_HDR_NEXT_PAGE_NO, + FIL_NULL, MLOG_4BYTES, &mtr); + + extern_len -= store_len; + + rec_page = buf_page_get(space_id, + buf_frame_get_page_no(data), + RW_X_LATCH, &mtr); + + buf_page_dbg_add_level(rec_page, SYNC_NO_ORDER_CHECK); + + mlog_write_ulint(data + local_len + BTR_EXTERN_LEN, 0, + MLOG_4BYTES, &mtr); + mlog_write_ulint(data + local_len + BTR_EXTERN_LEN + 4, + big_rec_vec->fields[i].len + - extern_len, + MLOG_4BYTES, &mtr); + + if (prev_page_no == FIL_NULL) { + mlog_write_ulint(data + local_len + + BTR_EXTERN_SPACE_ID, + space_id, + MLOG_4BYTES, &mtr); + + mlog_write_ulint(data + local_len + + BTR_EXTERN_PAGE_NO, + page_no, + MLOG_4BYTES, &mtr); + + mlog_write_ulint(data + local_len + + BTR_EXTERN_OFFSET, + FIL_PAGE_DATA, + MLOG_4BYTES, &mtr); + + /* Set the bit denoting that this field + in rec is stored externally */ + + rec_set_nth_field_extern_bit(rec, + big_rec_vec->fields[i].field_no, + TRUE, &mtr); + } + + prev_page_no = page_no; + + mtr_commit(&mtr); + } + } + + return(DB_SUCCESS); +} + +/*********************************************************************** +Frees the space in an externally stored field to the file space +management. */ + +void +btr_free_externally_stored_field( +/*=============================*/ + dict_index_t* index, /* in: index of the data, the index + tree MUST be X-latched */ + byte* data, /* in: internally stored data + + reference to the externally + stored part */ + ulint local_len, /* in: length of data */ + mtr_t* local_mtr) /* in: mtr containing the latch to + data an an X-latch to the index + tree */ +{ + page_t* page; + page_t* rec_page; + ulint space_id; + ulint page_no; + ulint offset; + ulint extern_len; + ulint next_page_no; + ulint part_len; + mtr_t mtr; + + ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE); + ut_ad(mtr_memo_contains(local_mtr, dict_tree_get_lock(index->tree), + MTR_MEMO_X_LOCK)); + ut_ad(mtr_memo_contains(local_mtr, buf_block_align(data), + MTR_MEMO_PAGE_X_FIX)); + ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE); + local_len -= BTR_EXTERN_FIELD_REF_SIZE; + + for (;;) { + mtr_start(&mtr); + + rec_page = buf_page_get(buf_frame_get_space_id(data), + buf_frame_get_page_no(data), RW_X_LATCH, &mtr); + + buf_page_dbg_add_level(rec_page, SYNC_NO_ORDER_CHECK); + + space_id = mach_read_from_4(data + local_len + + BTR_EXTERN_SPACE_ID); + + page_no = mach_read_from_4(data + local_len + + BTR_EXTERN_PAGE_NO); + + offset = mach_read_from_4(data + local_len + BTR_EXTERN_OFFSET); + + extern_len = mach_read_from_4(data + local_len + + BTR_EXTERN_LEN + 4); + + /* If extern len is 0, then there is no external storage data + at all */ + + if (extern_len == 0) { + + mtr_commit(&mtr); + + return; + } + + page = buf_page_get(space_id, page_no, RW_X_LATCH, &mtr); + + buf_page_dbg_add_level(page, SYNC_EXTERN_STORAGE); + + next_page_no = mach_read_from_4(page + FIL_PAGE_DATA + + BTR_BLOB_HDR_NEXT_PAGE_NO); + + part_len = btr_blob_get_part_len(page + FIL_PAGE_DATA); + + ut_a(extern_len >= part_len); + + /* We must supply the page level (= 0) as an argument + because we did not store it on the page (we save the space + overhead from an index page header. */ + + btr_page_free_low(index->tree, page, 0, &mtr); + + mlog_write_ulint(data + local_len + BTR_EXTERN_PAGE_NO, + next_page_no, + MLOG_4BYTES, &mtr); + mlog_write_ulint(data + local_len + BTR_EXTERN_LEN + 4, + extern_len - part_len, + MLOG_4BYTES, &mtr); + if (next_page_no == FIL_NULL) { + ut_a(extern_len - part_len == 0); + } + + if (extern_len - part_len == 0) { + ut_a(next_page_no == FIL_NULL); + } + + mtr_commit(&mtr); + } +} + +/*************************************************************** +Frees the externally stored fields for a record. */ + +void +btr_rec_free_externally_stored_fields( +/*==================================*/ + dict_index_t* index, /* in: index of the data, the index + tree MUST be X-latched */ + rec_t* rec, /* in: record */ + mtr_t* mtr) /* in: mini-transaction handle which contains + an X-latch to record page and to the index + tree */ +{ + ulint n_fields; + byte* data; + ulint len; + ulint i; + + ut_ad(mtr_memo_contains(mtr, buf_block_align(rec), + MTR_MEMO_PAGE_X_FIX)); + if (rec_get_data_size(rec) <= REC_1BYTE_OFFS_LIMIT) { + + return; + } + + /* Free possible externally stored fields in the record */ + + n_fields = rec_get_n_fields(rec); + + for (i = 0; i < n_fields; i++) { + if (rec_get_nth_field_extern_bit(rec, i)) { + + data = rec_get_nth_field(rec, i, &len); + btr_free_externally_stored_field(index, data, len, mtr); + } + } +} + +/*************************************************************** +Frees the externally stored fields for a record, if the field is mentioned +in the update vector. */ +static +void +btr_rec_free_updated_extern_fields( +/*===============================*/ + dict_index_t* index, /* in: index of rec; the index tree MUST be + X-latched */ + rec_t* rec, /* in: record */ + upd_t* update, /* in: update vector */ + mtr_t* mtr) /* in: mini-transaction handle which contains + an X-latch to record page and to the tree */ +{ + upd_field_t* ufield; + ulint n_fields; + byte* data; + ulint len; + ulint i; + + ut_ad(mtr_memo_contains(mtr, buf_block_align(rec), + MTR_MEMO_PAGE_X_FIX)); + if (rec_get_data_size(rec) <= REC_1BYTE_OFFS_LIMIT) { + + return; + } + + /* Free possible externally stored fields in the record */ + + n_fields = upd_get_n_fields(update); + + for (i = 0; i < n_fields; i++) { + ufield = upd_get_nth_field(update, i); + + if (rec_get_nth_field_extern_bit(rec, ufield->field_no)) { + + data = rec_get_nth_field(rec, ufield->field_no, &len); + btr_free_externally_stored_field(index, data, len, mtr); + } + } +} + +/*********************************************************************** +Copies an externally stored field of a record to mem heap. Parameter +data contains a pointer to 'internally' stored part of the field: +possibly some data, and the reference to the externally stored part in +the last 20 bytes of data. */ + +byte* +btr_copy_externally_stored_field( +/*=============================*/ + /* out: the whole field copied to heap */ + ulint* len, /* out: length of the whole field */ + byte* data, /* in: 'internally' stored part of the + field containing also the reference to + the external part */ + ulint local_len,/* in: length of data */ + mem_heap_t* heap) /* in: mem heap */ +{ + page_t* page; + ulint space_id; + ulint page_no; + ulint offset; + ulint extern_len; + byte* blob_header; + ulint part_len; + byte* buf; + ulint copied_len; + mtr_t mtr; + + ut_a(local_len >= BTR_EXTERN_FIELD_REF_SIZE); + + local_len -= BTR_EXTERN_FIELD_REF_SIZE; + + space_id = mach_read_from_4(data + local_len + BTR_EXTERN_SPACE_ID); + + page_no = mach_read_from_4(data + local_len + BTR_EXTERN_PAGE_NO); + + offset = mach_read_from_4(data + local_len + BTR_EXTERN_OFFSET); + + /* Currently a BLOB cannot be bigger that 4 GB; we + leave the 4 upper bytes in the length field unused */ + + extern_len = mach_read_from_4(data + local_len + BTR_EXTERN_LEN + 4); + + buf = mem_heap_alloc(heap, local_len + extern_len); + + ut_memcpy(buf, data, local_len); + copied_len = local_len; + + if (extern_len == 0) { + *len = copied_len; + + return(buf); + } + + for (;;) { + mtr_start(&mtr); + + page = buf_page_get(space_id, page_no, RW_S_LATCH, &mtr); + + buf_page_dbg_add_level(page, SYNC_EXTERN_STORAGE); + + blob_header = page + offset; + + part_len = btr_blob_get_part_len(blob_header); + + ut_memcpy(buf + copied_len, blob_header + BTR_BLOB_HDR_SIZE, + part_len); + copied_len += part_len; + + page_no = btr_blob_get_next_page_no(blob_header); + + /* On other BLOB pages except the first the BLOB header + always is at the page data start: */ + + offset = FIL_PAGE_DATA; + + mtr_commit(&mtr); + + if (page_no == FIL_NULL) { + ut_a(copied_len == local_len + extern_len); + + *len = copied_len; + + return(buf); + } + + ut_a(copied_len < local_len + extern_len); + } +} + +/*********************************************************************** +Copies an externally stored field of a record to mem heap. */ + +byte* +btr_rec_copy_externally_stored_field( +/*=================================*/ + /* out: the field copied to heap */ + rec_t* rec, /* in: record */ + ulint no, /* in: field number */ + ulint* len, /* out: length of the field */ + mem_heap_t* heap) /* in: mem heap */ +{ + ulint local_len; + byte* data; + + ut_a(rec_get_nth_field_extern_bit(rec, no)); + + /* An externally stored field can contain some initial + data from the field, and in the last 20 bytes it has the + space id, page number, and offset where the rest of the + field data is stored, and the data length in addition to + the data stored locally. We may need to store some data + locally to get the local record length above the 128 byte + limit so that field offsets are stored in two bytes, and + the extern bit is available in those two bytes. */ + + data = rec_get_nth_field(rec, no, &local_len); + + return(btr_copy_externally_stored_field(len, data, local_len, heap)); +} diff --git a/innobase/buf/buf0buf.c b/innobase/buf/buf0buf.c index ede9e621462..3fabe6c6d0e 100644 --- a/innobase/buf/buf0buf.c +++ b/innobase/buf/buf0buf.c @@ -216,14 +216,44 @@ buf_calc_page_checksum( /* out: checksum */ byte* page) /* in: buffer page */ { - ulint checksum; + ulint checksum; - checksum = ut_fold_binary(page, FIL_PAGE_FILE_FLUSH_LSN); - + ut_fold_binary(page + FIL_PAGE_DATA, UNIV_PAGE_SIZE - FIL_PAGE_DATA - - FIL_PAGE_END_LSN); - checksum = checksum & 0xFFFFFFFF; + checksum = ut_fold_binary(page, FIL_PAGE_FILE_FLUSH_LSN); + + ut_fold_binary(page + FIL_PAGE_DATA, + UNIV_PAGE_SIZE - FIL_PAGE_DATA + - FIL_PAGE_END_LSN); + checksum = checksum & 0xFFFFFFFF; - return(checksum); + return(checksum); +} + +/************************************************************************ +Checks if a page is corrupt. */ + +ibool +buf_page_is_corrupted( +/*==================*/ + /* out: TRUE if corrupted */ + byte* read_buf) /* in: a database page */ +{ + ulint checksum; + + checksum = buf_calc_page_checksum(read_buf); + + if ((mach_read_from_4(read_buf + FIL_PAGE_LSN + 4) + != mach_read_from_4(read_buf + UNIV_PAGE_SIZE + - FIL_PAGE_END_LSN + 4)) + || (checksum != mach_read_from_4(read_buf + + UNIV_PAGE_SIZE + - FIL_PAGE_END_LSN) + && mach_read_from_4(read_buf + FIL_PAGE_LSN) + != mach_read_from_4(read_buf + + UNIV_PAGE_SIZE + - FIL_PAGE_END_LSN))) { + return(TRUE); + } + + return(FALSE); } /************************************************************************ @@ -1265,34 +1295,22 @@ buf_page_io_complete( dulint id; dict_index_t* index; ulint io_type; - ulint checksum; ut_ad(block); io_type = block->io_fix; if (io_type == BUF_IO_READ) { - checksum = buf_calc_page_checksum(block->frame); - /* From version 3.23.38 up we store the page checksum to the 4 upper bytes of the page end lsn field */ - if ((mach_read_from_4(block->frame + FIL_PAGE_LSN + 4) - != mach_read_from_4(block->frame + UNIV_PAGE_SIZE - - FIL_PAGE_END_LSN + 4)) - || (checksum != mach_read_from_4(block->frame - + UNIV_PAGE_SIZE - - FIL_PAGE_END_LSN) - && mach_read_from_4(block->frame + FIL_PAGE_LSN) - != mach_read_from_4(block->frame - + UNIV_PAGE_SIZE - - FIL_PAGE_END_LSN))) { - fprintf(stderr, + if (buf_page_is_corrupted(block->frame)) { + fprintf(stderr, "InnoDB: Database page corruption or a failed\n" "InnoDB: file read of page %lu.\n", block->offset); - fprintf(stderr, + fprintf(stderr, "InnoDB: You may have to recover from a backup.\n"); - exit(1); + exit(1); } if (recv_recovery_is_on()) { @@ -1601,11 +1619,28 @@ void buf_print_io(void) /*==============*/ { + ulint size; + ut_ad(buf_pool); - mutex_enter(&(buf_pool->mutex)); + size = buf_pool_get_curr_size() / UNIV_PAGE_SIZE; - printf("pages read %lu, created %lu, written %lu\n", + mutex_enter(&(buf_pool->mutex)); + + printf("LRU list length %lu \n", UT_LIST_GET_LEN(buf_pool->LRU)); + printf("Free list length %lu \n", UT_LIST_GET_LEN(buf_pool->free)); + printf("Flush list length %lu \n", + UT_LIST_GET_LEN(buf_pool->flush_list)); + printf("Buffer pool size in pages %lu\n", size); + + printf("Pending reads %lu \n", buf_pool->n_pend_reads); + + printf("Pending writes: LRU %lu, flush list %lu, single page %lu\n", + buf_pool->n_flush[BUF_FLUSH_LRU], + buf_pool->n_flush[BUF_FLUSH_LIST], + buf_pool->n_flush[BUF_FLUSH_SINGLE_PAGE]); + + printf("Pages read %lu, created %lu, written %lu\n", buf_pool->n_pages_read, buf_pool->n_pages_created, buf_pool->n_pages_written); mutex_exit(&(buf_pool->mutex)); diff --git a/innobase/buf/buf0flu.c b/innobase/buf/buf0flu.c index 7129b8d20a9..0f27cee45a5 100644 --- a/innobase/buf/buf0flu.c +++ b/innobase/buf/buf0flu.c @@ -1,7 +1,7 @@ /****************************************************** The database buffer buf_pool flush algorithm -(c) 1995 Innobase Oy +(c) 1995-2001 Innobase Oy Created 11/11/1995 Heikki Tuuri *******************************************************/ @@ -15,7 +15,6 @@ Created 11/11/1995 Heikki Tuuri #include "ut0byte.h" #include "ut0lst.h" #include "fil0fil.h" - #include "buf0buf.h" #include "buf0lru.h" #include "buf0rea.h" @@ -195,9 +194,145 @@ buf_flush_write_complete( } /************************************************************************ -Does an asynchronous write of a buffer page. NOTE: in simulated aio we must -call os_aio_simulated_wake_handler_threads after we have posted a batch -of writes! */ +Flushes possible buffered writes from the doublewrite memory buffer to disk, +and also wakes up the aio thread if simulated aio is used. It is very +important to call this function after a batch of writes has been posted, +and also when we may have to wait for a page latch! Otherwise a deadlock +of threads can occur. */ +static +void +buf_flush_buffered_writes(void) +/*===========================*/ +{ + buf_block_t* block; + ulint len; + ulint i; + + if (trx_doublewrite == NULL) { + os_aio_simulated_wake_handler_threads(); + + return; + } + + mutex_enter(&(trx_doublewrite->mutex)); + + /* Write first to doublewrite buffer blocks. We use synchronous + aio and thus know that file write has been completed when the + control returns. */ + + if (trx_doublewrite->first_free == 0) { + + mutex_exit(&(trx_doublewrite->mutex)); + + return; + } + + if (trx_doublewrite->first_free > TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) { + len = TRX_SYS_DOUBLEWRITE_BLOCK_SIZE * UNIV_PAGE_SIZE; + } else { + len = trx_doublewrite->first_free * UNIV_PAGE_SIZE; + } + + fil_io(OS_FILE_WRITE, + TRUE, TRX_SYS_SPACE, + trx_doublewrite->block1, 0, len, + (void*)trx_doublewrite->write_buf, NULL); + + if (trx_doublewrite->first_free > TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) { + len = (trx_doublewrite->first_free + - TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) * UNIV_PAGE_SIZE; + + fil_io(OS_FILE_WRITE, + TRUE, TRX_SYS_SPACE, + trx_doublewrite->block2, 0, len, + (void*)(trx_doublewrite->write_buf + + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE * UNIV_PAGE_SIZE), + NULL); + } + + /* Now flush the doublewrite buffer data to disk */ + + fil_flush(TRX_SYS_SPACE); + + /* We know that the writes have been flushed to disk now + and in recovery we will find them in the doublewrite buffer + blocks. Next do the writes to the intended positions. */ + + for (i = 0; i < trx_doublewrite->first_free; i++) { + block = trx_doublewrite->buf_block_arr[i]; + + fil_io(OS_FILE_WRITE | OS_AIO_SIMULATED_WAKE_LATER, + FALSE, block->space, block->offset, 0, UNIV_PAGE_SIZE, + (void*)block->frame, (void*)block); + } + + /* Wake possible simulated aio thread to actually post the + writes to the operating system */ + + os_aio_simulated_wake_handler_threads(); + + /* Wait that all async writes to tablespaces have been posted to + the OS */ + + os_aio_wait_until_no_pending_writes(); + + /* Now we flush the data to disk (for example, with fsync) */ + + fil_flush_file_spaces(FIL_TABLESPACE); + + /* We can now reuse the doublewrite memory buffer: */ + + trx_doublewrite->first_free = 0; + + mutex_exit(&(trx_doublewrite->mutex)); +} + +/************************************************************************ +Posts a buffer page for writing. If the doublewrite memory buffer is +full, calls buf_flush_buffered_writes and waits for for free space to +appear. */ +static +void +buf_flush_post_to_doublewrite_buf( +/*==============================*/ + buf_block_t* block) /* in: buffer block to write */ +{ +try_again: + mutex_enter(&(trx_doublewrite->mutex)); + + if (trx_doublewrite->first_free + >= 2 * TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) { + mutex_exit(&(trx_doublewrite->mutex)); + + buf_flush_buffered_writes(); + + goto try_again; + } + + ut_memcpy(trx_doublewrite->write_buf + + UNIV_PAGE_SIZE * trx_doublewrite->first_free, + block->frame, UNIV_PAGE_SIZE); + + trx_doublewrite->buf_block_arr[trx_doublewrite->first_free] = block; + + trx_doublewrite->first_free++; + + if (trx_doublewrite->first_free + >= 2 * TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) { + mutex_exit(&(trx_doublewrite->mutex)); + + buf_flush_buffered_writes(); + + return; + } + + mutex_exit(&(trx_doublewrite->mutex)); +} + +/************************************************************************ +Does an asynchronous write of a buffer page. NOTE: in simulated aio and +also when the doublewrite buffer is used, we must call +buf_flush_buffered_writes after we have posted a batch of writes! */ static void buf_flush_write_block_low( @@ -222,15 +357,24 @@ buf_flush_write_block_low( mach_write_to_8(block->frame + UNIV_PAGE_SIZE - FIL_PAGE_END_LSN, block->newest_modification); + /* Write to the page the space id and page number */ + + mach_write_to_4(block->frame + FIL_PAGE_SPACE, block->space); + mach_write_to_4(block->frame + FIL_PAGE_OFFSET, block->offset); + /* We overwrite the first 4 bytes of the end lsn field to store a page checksum */ mach_write_to_4(block->frame + UNIV_PAGE_SIZE - FIL_PAGE_END_LSN, buf_calc_page_checksum(block->frame)); - fil_io(OS_FILE_WRITE | OS_AIO_SIMULATED_WAKE_LATER, - FALSE, block->space, block->offset, 0, UNIV_PAGE_SIZE, + if (!trx_doublewrite) { + fil_io(OS_FILE_WRITE | OS_AIO_SIMULATED_WAKE_LATER, + FALSE, block->space, block->offset, 0, UNIV_PAGE_SIZE, (void*)block->frame, (void*)block); + } else { + buf_flush_post_to_doublewrite_buf(block); + } } /************************************************************************ @@ -251,14 +395,14 @@ buf_flush_try_page( buf_block_t* block; ibool locked; - ut_ad((flush_type == BUF_FLUSH_LRU) || (flush_type == BUF_FLUSH_LIST) - || (flush_type == BUF_FLUSH_SINGLE_PAGE)); + ut_ad(flush_type == BUF_FLUSH_LRU || flush_type == BUF_FLUSH_LIST + || flush_type == BUF_FLUSH_SINGLE_PAGE); mutex_enter(&(buf_pool->mutex)); block = buf_page_hash_get(space, offset); - if ((flush_type == BUF_FLUSH_LIST) + if (flush_type == BUF_FLUSH_LIST && block && buf_flush_ready_for_flush(block, flush_type)) { block->io_fix = BUF_IO_WRITE; @@ -286,7 +430,7 @@ buf_flush_try_page( mutex_exit(&(buf_pool->mutex)); if (!locked) { - os_aio_simulated_wake_handler_threads(); + buf_flush_buffered_writes(); rw_lock_s_lock_gen(&(block->lock), BUF_IO_WRITE); } @@ -300,7 +444,7 @@ buf_flush_try_page( return(1); - } else if ((flush_type == BUF_FLUSH_LRU) && block + } else if (flush_type == BUF_FLUSH_LRU && block && buf_flush_ready_for_flush(block, flush_type)) { /* VERY IMPORTANT: @@ -328,7 +472,7 @@ buf_flush_try_page( return(1); - } else if ((flush_type == BUF_FLUSH_SINGLE_PAGE) && block + } else if (flush_type == BUF_FLUSH_SINGLE_PAGE && block && buf_flush_ready_for_flush(block, flush_type)) { block->io_fix = BUF_IO_WRITE; @@ -385,6 +529,14 @@ buf_flush_try_neighbors( /* If there is little space, it is better not to flush any block except from the end of the LRU list */ + low = offset; + high = offset + 1; + } else if (flush_type == BUF_FLUSH_LIST) { + /* Since semaphore waits require us to flush the + doublewrite buffer to disk, it is best that the + search area is just the page itself, to minimize + chances for semaphore waits */ + low = offset; high = offset + 1; } @@ -418,13 +570,6 @@ buf_flush_try_neighbors( mutex_exit(&(buf_pool->mutex)); - /* In simulated aio we wake up the i/o-handler threads now that - we have posted a batch of writes: */ - - /* printf("Flush count %lu ; Waking i/o handlers\n", count); */ - - os_aio_simulated_wake_handler_threads(); - return(count); } @@ -565,13 +710,15 @@ buf_flush_batch( mutex_exit(&(buf_pool->mutex)); - if (buf_debug_prints && (page_count > 0)) { + buf_flush_buffered_writes(); + + if (buf_debug_prints && page_count > 0) { if (flush_type == BUF_FLUSH_LRU) { - printf("To flush %lu pages in LRU flush\n", + printf("Flushed %lu pages in LRU flush\n", page_count); } else if (flush_type == BUF_FLUSH_LIST) { - printf("To flush %lu pages in flush list flush\n", - page_count, flush_type); + printf("Flushed %lu pages in flush list flush\n", + page_count); } else { ut_error; } diff --git a/innobase/buf/buf0rea.c b/innobase/buf/buf0rea.c index 728bf4404b8..db187cdd896 100644 --- a/innobase/buf/buf0rea.c +++ b/innobase/buf/buf0rea.c @@ -49,7 +49,9 @@ ulint buf_read_page_low( /*==============*/ /* out: 1 if a read request was queued, 0 if the page - already resided in buf_pool */ + already resided in buf_pool or if the page is in + the doublewrite buffer blocks in which case it is never + read into the pool */ ibool sync, /* in: TRUE if synchronous aio is desired */ ulint mode, /* in: BUF_READ_IBUF_PAGES_ONLY, ..., ORed to OS_AIO_SIMULATED_WAKE_LATER (see below @@ -63,6 +65,16 @@ buf_read_page_low( wake_later = mode & OS_AIO_SIMULATED_WAKE_LATER; mode = mode & ~OS_AIO_SIMULATED_WAKE_LATER; + if (trx_doublewrite && space == TRX_SYS_SPACE + && ( (offset >= trx_doublewrite->block1 + && offset < trx_doublewrite->block1 + + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) + || (offset >= trx_doublewrite->block2 + && offset < trx_doublewrite->block2 + + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE))) { + return(0); + } + #ifdef UNIV_LOG_DEBUG if (space % 2 == 1) { /* We are updating a replicate space while holding the diff --git a/innobase/data/data0data.c b/innobase/data/data0data.c index fe5611bc312..4172fb9c8ce 100644 --- a/innobase/data/data0data.c +++ b/innobase/data/data0data.c @@ -13,7 +13,10 @@ Created 5/30/1994 Heikki Tuuri #endif #include "ut0rnd.h" - +#include "rem0rec.h" +#include "page0page.h" +#include "dict0dict.h" +#include "btr0cur.h" byte data_error; /* data pointers of tuple fields are initialized to point here for error checking */ @@ -378,6 +381,172 @@ dtuple_sprintf( return(len); } +/****************************************************************** +Moves parts of long fields in entry to the big record vector so that +the size of tuple drops below the maximum record size allowed in the +database. Moves data only from those fields which are not necessary +to determine uniquely the insertion place of the tuple in the index. */ + +big_rec_t* +dtuple_convert_big_rec( +/*===================*/ + /* out, own: created big record vector, + NULL if we are not able to shorten + the entry enough, i.e., if there are + too many short fields in entry */ + dict_index_t* index, /* in: index */ + dtuple_t* entry) /* in: index entry */ +{ + mem_heap_t* heap; + big_rec_t* vector; + dfield_t* dfield; + ulint size; + ulint n_fields; + ulint longest; + ulint longest_i; + ulint i; + + size = rec_get_converted_size(entry); + + heap = mem_heap_create(size + dtuple_get_n_fields(entry) + * sizeof(big_rec_field_t) + 1000); + + vector = mem_heap_alloc(heap, sizeof(big_rec_t)); + + vector->heap = heap; + vector->fields = mem_heap_alloc(heap, dtuple_get_n_fields(entry) + * sizeof(big_rec_field_t)); + + /* Decide which fields to shorten: the algorithm is to look for + the longest field which does not occur in the ordering part + of any index on the table */ + + n_fields = 0; + + while ((rec_get_converted_size(entry) + >= page_get_free_space_of_empty() / 2) + || rec_get_converted_size(entry) >= REC_MAX_DATA_SIZE) { + + longest = 0; + for (i = dict_index_get_n_unique_in_tree(index); + i < dtuple_get_n_fields(entry); i++) { + + /* Skip over fields which are ordering in some index */ + + if (dict_field_get_col( + dict_index_get_nth_field(index, i)) + ->ord_part == 0) { + + dfield = dtuple_get_nth_field(entry, i); + + if (dfield->len != UNIV_SQL_NULL && + dfield->len > longest) { + + longest = dfield->len; + + longest_i = i; + } + } + } + + if (longest < BTR_EXTERN_FIELD_REF_SIZE + 10) { + + /* Cannot shorten more */ + + mem_heap_free(heap); + + return(NULL); + } + + /* Move data from field longest_i to big rec vector, + but do not let data size of the remaining entry + drop below 128 which is the limit for the 2-byte + offset storage format in a physical record */ + + dfield = dtuple_get_nth_field(entry, longest_i); + vector->fields[n_fields].field_no = longest_i; + + if (dtuple_get_data_size(entry) - dfield->len + <= REC_1BYTE_OFFS_LIMIT) { + vector->fields[n_fields].len = + dtuple_get_data_size(entry) + - REC_1BYTE_OFFS_LIMIT; + /* Since dfield will contain at least + a 20-byte reference to the extern storage, + we know that the data size of entry will be + > REC_1BYTE_OFFS_LIMIT */ + } else { + vector->fields[n_fields].len = dfield->len; + } + + vector->fields[n_fields].data = mem_heap_alloc(heap, + vector->fields[n_fields].len); + + /* Copy data (from the end of field) to big rec vector */ + + ut_memcpy(vector->fields[n_fields].data, + ((byte*)dfield->data) + dfield->len + - vector->fields[n_fields].len, + vector->fields[n_fields].len); + dfield->len = dfield->len - vector->fields[n_fields].len + + BTR_EXTERN_FIELD_REF_SIZE; + + /* Set the extern field reference in dfield to zero */ + memset(((byte*)dfield->data) + + dfield->len - BTR_EXTERN_FIELD_REF_SIZE, + 0, BTR_EXTERN_FIELD_REF_SIZE); + n_fields++; + } + + vector->n_fields = n_fields; + return(vector); +} + +/****************************************************************** +Puts back to entry the data stored in vector. Note that to ensure the +fields in entry can accommodate the data, vector must have been created +from entry with dtuple_convert_big_rec. */ + +void +dtuple_convert_back_big_rec( +/*========================*/ + dict_index_t* index, /* in: index */ + dtuple_t* entry, /* in: entry whose data was put to vector */ + big_rec_t* vector) /* in, own: big rec vector; it is + freed in this function */ +{ + dfield_t* dfield; + ulint i; + + for (i = 0; i < vector->n_fields; i++) { + + dfield = dtuple_get_nth_field(entry, + vector->fields[i].field_no); + /* Copy data from big rec vector */ + + ut_memcpy(((byte*)dfield->data) + + dfield->len - BTR_EXTERN_FIELD_REF_SIZE, + vector->fields[i].data, + vector->fields[i].len); + dfield->len = dfield->len + vector->fields[i].len + - BTR_EXTERN_FIELD_REF_SIZE; + } + + mem_heap_free(vector->heap); +} + +/****************************************************************** +Frees the memory in a big rec vector. */ + +void +dtuple_big_rec_free( +/*================*/ + big_rec_t* vector) /* in, own: big rec vector; it is + freed in this function */ +{ + mem_heap_free(vector->heap); +} + #ifdef notdefined /****************************************************************** diff --git a/innobase/fil/fil0fil.c b/innobase/fil/fil0fil.c index 6f201c7bce4..5c783627721 100644 --- a/innobase/fil/fil0fil.c +++ b/innobase/fil/fil0fil.c @@ -90,6 +90,9 @@ struct fil_node_struct { is ignored) */ ulint n_pending; /* count of pending i/o-ops on this file */ + ibool is_modified; /* this is set to TRUE when we write + to the file and FALSE when we call fil_flush + for this file space */ UT_LIST_NODE_T(fil_node_t) chain; /* link field for the file chain */ UT_LIST_NODE_T(fil_node_t) LRU; @@ -301,6 +304,8 @@ fil_node_create( node->size = size; node->magic_n = FIL_NODE_MAGIC_N; node->n_pending = 0; + + node->is_modified = FALSE; HASH_SEARCH(hash, system->spaces, id, space, space->id == id); @@ -720,6 +725,47 @@ fil_space_get_size( return(size); } +/*********************************************************************** +Checks if the pair space, page_no refers to an existing page in a +tablespace file space. */ + +ibool +fil_check_adress_in_tablespace( +/*===========================*/ + /* out: TRUE if the address is meaningful */ + ulint id, /* in: space id */ + ulint page_no)/* in: page number */ +{ + fil_space_t* space; + fil_system_t* system = fil_system; + ulint size; + ibool ret; + + ut_ad(system); + + mutex_enter(&(system->mutex)); + + HASH_SEARCH(hash, system->spaces, id, space, space->id == id); + + if (space == NULL) { + ret = FALSE; + } else { + size = space->size; + + if (page_no > size) { + ret = FALSE; + } else if (space->purpose != FIL_TABLESPACE) { + ret = FALSE; + } else { + ret = TRUE; + } + } + + mutex_exit(&(system->mutex)); + + return(ret); +} + /*********************************************************************** Tries to reserve free extents in a file space. */ @@ -812,8 +858,14 @@ fil_node_prepare_for_io( fil_node_close(last_node, system); } - node->handle = os_file_create(node->name, OS_FILE_OPEN, - OS_FILE_AIO, &ret); + if (space->purpose == FIL_LOG) { + node->handle = os_file_create(node->name, OS_FILE_OPEN, + OS_FILE_AIO, OS_LOG_FILE, &ret); + } else { + node->handle = os_file_create(node->name, OS_FILE_OPEN, + OS_FILE_AIO, OS_DATA_FILE, &ret); + } + ut_a(ret); node->open = TRUE; @@ -851,7 +903,8 @@ void fil_node_complete_io( /*=================*/ fil_node_t* node, /* in: file node */ - fil_system_t* system) /* in: file system */ + fil_system_t* system, /* in: file system */ + ulint type) /* in: OS_FILE_WRITE or ..._READ */ { ut_ad(node); ut_ad(system); @@ -860,6 +913,10 @@ fil_node_complete_io( node->n_pending--; + if (type != OS_FILE_READ) { + node->is_modified = TRUE; + } + if (node->n_pending == 0) { /* The node must be put back to the LRU list */ UT_LIST_ADD_FIRST(LRU, system->LRU, node); @@ -1016,7 +1073,7 @@ loop: mutex_enter(&(system->mutex)); - fil_node_complete_io(node, system); + fil_node_complete_io(node, system, type); mutex_exit(&(system->mutex)); @@ -1090,12 +1147,14 @@ fil_aio_wait( fil_node_t* fil_node; fil_system_t* system = fil_system; void* message; + ulint type; ut_ad(fil_validate()); if (os_aio_use_native_aio) { #ifdef WIN_ASYNC_IO - ret = os_aio_windows_handle(segment, 0, &fil_node, &message); + ret = os_aio_windows_handle(segment, 0, &fil_node, &message, + &type); #elif defined(POSIX_ASYNC_IO) ret = os_aio_posix_handle(segment, &fil_node, &message); #else @@ -1103,14 +1162,14 @@ fil_aio_wait( #endif } else { ret = os_aio_simulated_handle(segment, (void**) &fil_node, - &message); + &message, &type); } ut_a(ret); mutex_enter(&(system->mutex)); - fil_node_complete_io(fil_node, fil_system); + fil_node_complete_io(fil_node, fil_system, type); mutex_exit(&(system->mutex)); @@ -1149,8 +1208,10 @@ fil_flush( node = UT_LIST_GET_FIRST(space->chain); while (node) { - if (node->open) { + if (node->open && node->is_modified) { file = node->handle; + + node->is_modified = FALSE; mutex_exit(&(system->mutex)); @@ -1159,9 +1220,11 @@ fil_flush( handle is still open: we assume that the OS will not crash or trap even if we pass a handle to a closed file below in os_file_flush! */ + + /* printf("Flushing to file %s\n", node->name); */ os_file_flush(file); - + mutex_enter(&(system->mutex)); } diff --git a/innobase/fsp/fsp0fsp.c b/innobase/fsp/fsp0fsp.c index 101fb5f3ba0..ccc13f15fde 100644 --- a/innobase/fsp/fsp0fsp.c +++ b/innobase/fsp/fsp0fsp.c @@ -3239,8 +3239,8 @@ fsp_validate( ut_a(descr_count * FSP_EXTENT_SIZE == free_limit); ut_a(n_used + n_full_frag_pages - == n_used2 + (free_limit + XDES_DESCRIBED_PER_PAGE - 1) - / XDES_DESCRIBED_PER_PAGE + == n_used2 + 2* ((free_limit + XDES_DESCRIBED_PER_PAGE - 1) + / XDES_DESCRIBED_PER_PAGE) + seg_inode_len_full + seg_inode_len_free); ut_a(frag_n_used == n_used); diff --git a/innobase/ibuf/ibuf0ibuf.c b/innobase/ibuf/ibuf0ibuf.c index 171c6169927..3db20fb13ee 100644 --- a/innobase/ibuf/ibuf0ibuf.c +++ b/innobase/ibuf/ibuf0ibuf.c @@ -1946,6 +1946,7 @@ ibuf_insert_low( ulint page_no,/* in: page number where to insert */ que_thr_t* thr) /* in: query thread */ { + big_rec_t* dummy_big_rec; ulint entry_size; btr_pcur_t pcur; btr_cur_t* cursor; @@ -2101,7 +2102,8 @@ ibuf_insert_low( if (mode == BTR_MODIFY_PREV) { err = btr_cur_optimistic_insert(BTR_NO_LOCKING_FLAG, cursor, - ibuf_entry, &ins_rec, thr, + ibuf_entry, &ins_rec, + &dummy_big_rec, thr, &mtr); if (err == DB_SUCCESS) { /* Update the page max trx id field */ @@ -2121,7 +2123,8 @@ ibuf_insert_low( err = btr_cur_pessimistic_insert(BTR_NO_LOCKING_FLAG | BTR_NO_UNDO_LOG_FLAG, cursor, - ibuf_entry, &ins_rec, thr, + ibuf_entry, &ins_rec, + &dummy_big_rec, thr, &mtr); if (err == DB_SUCCESS) { /* Update the page max trx id field */ diff --git a/innobase/include/btr0btr.h b/innobase/include/btr0btr.h index f8a3000ca8a..bea85565125 100644 --- a/innobase/include/btr0btr.h +++ b/innobase/include/btr0btr.h @@ -357,6 +357,44 @@ btr_get_size( /* out: number of pages */ dict_index_t* index, /* in: index */ ulint flag); /* in: BTR_N_LEAF_PAGES or BTR_TOTAL_SIZE */ +/****************************************************************** +Allocates a new file page to be used in an index tree. NOTE: we assume +that the caller has made the reservation for free extents! */ + +page_t* +btr_page_alloc( +/*===========*/ + /* out: new allocated page, x-latched; + NULL if out of space */ + dict_tree_t* tree, /* in: index tree */ + ulint hint_page_no, /* in: hint of a good page */ + byte file_direction, /* in: direction where a possible + page split is made */ + ulint level, /* in: level where the page is placed + in the tree */ + mtr_t* mtr); /* in: mtr */ +/****************************************************************** +Frees a file page used in an index tree. NOTE: cannot free field external +storage pages because the page must contain info on its level. */ + +void +btr_page_free( +/*==========*/ + dict_tree_t* tree, /* in: index tree */ + page_t* page, /* in: page to be freed, x-latched */ + mtr_t* mtr); /* in: mtr */ +/****************************************************************** +Frees a file page used in an index tree. Can be used also to BLOB +external storage pages, because the page level 0 can be given as an +argument. */ + +void +btr_page_free_low( +/*==============*/ + dict_tree_t* tree, /* in: index tree */ + page_t* page, /* in: page to be freed, x-latched */ + ulint level, /* in: page level */ + mtr_t* mtr); /* in: mtr */ /***************************************************************** Prints size info of a B-tree. */ diff --git a/innobase/include/btr0cur.h b/innobase/include/btr0cur.h index 4ce2177bfe8..ffae434a5d9 100644 --- a/innobase/include/btr0cur.h +++ b/innobase/include/btr0cur.h @@ -151,11 +151,14 @@ btr_cur_optimistic_insert( ulint flags, /* in: undo logging and locking flags: if not zero, the parameters index and thr should be specified */ - btr_cur_t* cursor, /* in: cursor on page after which - to insert; cursor stays valid */ + btr_cur_t* cursor, /* in: cursor on page after which to insert; + cursor stays valid */ dtuple_t* entry, /* in: entry to insert */ rec_t** rec, /* out: pointer to inserted record if succeed */ + big_rec_t** big_rec,/* out: big rec vector whose fields have to + be stored externally by the caller, or + NULL */ que_thr_t* thr, /* in: query thread or NULL */ mtr_t* mtr); /* in: mtr */ /***************************************************************** @@ -169,13 +172,19 @@ btr_cur_pessimistic_insert( /*=======================*/ /* out: DB_SUCCESS or error number */ ulint flags, /* in: undo logging and locking flags: if not - zero, the parameters index and thr should be - specified */ + zero, the parameter thr should be + specified; if no undo logging is specified, + then the caller must have reserved enough + free extents in the file space so that the + insertion will certainly succeed */ btr_cur_t* cursor, /* in: cursor after which to insert; - cursor does not stay valid */ + cursor stays valid */ dtuple_t* entry, /* in: entry to insert */ rec_t** rec, /* out: pointer to inserted record if succeed */ + big_rec_t** big_rec,/* out: big rec vector whose fields have to + be stored externally by the caller, or + NULL */ que_thr_t* thr, /* in: query thread or NULL */ mtr_t* mtr); /* in: mtr */ /***************************************************************** @@ -228,8 +237,9 @@ btr_cur_pessimistic_update( /* out: DB_SUCCESS or error code */ ulint flags, /* in: undo logging, locking, and rollback flags */ - btr_cur_t* cursor, /* in: cursor on the record to update; - cursor does not stay valid */ + btr_cur_t* cursor, /* in: cursor on the record to update */ + big_rec_t** big_rec,/* out: big rec vector whose fields have to + be stored externally by the caller, or NULL */ upd_t* update, /* in: update vector; this is allowed also contain trx id and roll ptr fields, but the values in update vector have no effect */ @@ -407,6 +417,92 @@ btr_estimate_number_of_different_key_vals( /*======================================*/ /* out: estimated number of key values */ dict_index_t* index); /* in: index */ +/*********************************************************************** +Stores the fields in big_rec_vec to the tablespace and puts pointers to +them in rec. The fields are stored on pages allocated from leaf node +file segment of the index tree. */ + +ulint +btr_store_big_rec_extern_fields( +/*============================*/ + /* out: DB_SUCCESS or error */ + dict_index_t* index, /* in: index of rec; the index tree + MUST be X-latched */ + rec_t* rec, /* in: record */ + big_rec_t* big_rec_vec, /* in: vector containing fields + to be stored externally */ + mtr_t* local_mtr); /* in: mtr containing the latch to + rec and to the tree */ +/*********************************************************************** +Frees the space in an externally stored field to the file space +management. */ + +void +btr_free_externally_stored_field( +/*=============================*/ + dict_index_t* index, /* in: index of the data, the index + tree MUST be X-latched */ + byte* data, /* in: internally stored data + + reference to the externally + stored part */ + ulint local_len, /* in: length of data */ + mtr_t* local_mtr); /* in: mtr containing the latch to + data an an X-latch to the index + tree */ +/*************************************************************** +Frees the externally stored fields for a record. */ + +void +btr_rec_free_externally_stored_fields( +/*==================================*/ + dict_index_t* index, /* in: index of the data, the index + tree MUST be X-latched */ + rec_t* rec, /* in: record */ + mtr_t* mtr); /* in: mini-transaction handle which contains + an X-latch to record page and to the index + tree */ +/*********************************************************************** +Copies an externally stored field of a record to mem heap. */ + +byte* +btr_rec_copy_externally_stored_field( +/*=================================*/ + /* out: the field copied to heap */ + rec_t* rec, /* in: record */ + ulint no, /* in: field number */ + ulint* len, /* out: length of the field */ + mem_heap_t* heap); /* in: mem heap */ +/*********************************************************************** +Copies an externally stored field of a record to mem heap. Parameter +data contains a pointer to 'internally' stored part of the field: +possibly some data, and the reference to the externally stored part in +the last 20 bytes of data. */ + +byte* +btr_copy_externally_stored_field( +/*=============================*/ + /* out: the whole field copied to heap */ + ulint* len, /* out: length of the whole field */ + byte* data, /* in: 'internally' stored part of the + field containing also the reference to + the external part */ + ulint local_len,/* in: length of data */ + mem_heap_t* heap); /* in: mem heap */ +/*********************************************************************** +Stores the positions of the fields marked as extern storage in the update +vector, and also those fields who are marked as extern storage in rec +and not mentioned in updated fields. We use this function to remember +which fields we must mark as extern storage in a record inserted for an +update. */ + +ulint +btr_push_update_extern_fields( +/*==========================*/ + /* out: number of values stored in ext_vect */ + ulint* ext_vect, /* in: array of ulints, must be preallocated + to have place for all fields in rec */ + rec_t* rec, /* in: record */ + upd_t* update); /* in: update vector */ /*######################################################################*/ @@ -516,6 +612,19 @@ and sleep this many microseconds in between */ #define BTR_CUR_RETRY_DELETE_N_TIMES 100 #define BTR_CUR_RETRY_SLEEP_TIME 50000 +/* The reference in a field of which data is stored on a different page */ +/*--------------------------------------*/ +#define BTR_EXTERN_SPACE_ID 0 /* space id where stored */ +#define BTR_EXTERN_PAGE_NO 4 /* page no where stored */ +#define BTR_EXTERN_OFFSET 8 /* offset of BLOB header + on that page */ +#define BTR_EXTERN_LEN 12 /* 8 bytes containing the + length of the externally + stored part of the BLOB */ +/*--------------------------------------*/ +#define BTR_EXTERN_FIELD_REF_SIZE 20 + + extern ulint btr_cur_n_non_sea; #ifndef UNIV_NONINL diff --git a/innobase/include/buf0buf.h b/innobase/include/buf0buf.h index 7f3e20a4505..8b22561adf8 100644 --- a/innobase/include/buf0buf.h +++ b/innobase/include/buf0buf.h @@ -378,6 +378,14 @@ buf_calc_page_checksum( /*===================*/ /* out: checksum */ byte* page); /* in: buffer page */ +/************************************************************************ +Checks if a page is corrupt. */ + +ibool +buf_page_is_corrupted( +/*==================*/ + /* out: TRUE if corrupted */ + byte* read_buf); /* in: a database page */ /************************************************************************** Gets the page number of a pointer pointing within a buffer frame containing a file page. */ diff --git a/innobase/include/buf0flu.h b/innobase/include/buf0flu.h index 9317950904f..cb1c0965a65 100644 --- a/innobase/include/buf0flu.h +++ b/innobase/include/buf0flu.h @@ -101,7 +101,7 @@ make sure that a read-ahead batch can be read efficiently in a single sweep). */ #define BUF_FLUSH_FREE_BLOCK_MARGIN (5 + BUF_READ_AHEAD_AREA) -#define BUF_FLUSH_EXTRA_MARGIN (BUF_FLUSH_FREE_BLOCK_MARGIN / 4) +#define BUF_FLUSH_EXTRA_MARGIN (BUF_FLUSH_FREE_BLOCK_MARGIN / 4 + 100) #ifndef UNIV_NONINL #include "buf0flu.ic" diff --git a/innobase/include/data0data.h b/innobase/include/data0data.h index d7f0986b0b6..f695e0989a5 100644 --- a/innobase/include/data0data.h +++ b/innobase/include/data0data.h @@ -14,6 +14,9 @@ Created 5/30/1994 Heikki Tuuri #include "data0types.h" #include "data0type.h" #include "mem0mem.h" +#include "dict0types.h" + +typedef struct big_rec_struct big_rec_t; /* Some non-inlined functions used in the MySQL interface: */ void @@ -312,6 +315,41 @@ dtuple_sprintf( char* buf, /* in: print buffer */ ulint buf_len,/* in: buf length in bytes */ dtuple_t* tuple); /* in: tuple */ +/****************************************************************** +Moves parts of long fields in entry to the big record vector so that +the size of tuple drops below the maximum record size allowed in the +database. Moves data only from those fields which are not necessary +to determine uniquely the insertion place of the tuple in the index. */ + +big_rec_t* +dtuple_convert_big_rec( +/*===================*/ + /* out, own: created big record vector, + NULL if we are not able to shorten + the entry enough, i.e., if there are + too many short fields in entry */ + dict_index_t* index, /* in: index */ + dtuple_t* entry); /* in: index entry */ +/****************************************************************** +Puts back to entry the data stored in vector. Note that to ensure the +fields in entry can accommodate the data, vector must have been created +from entry with dtuple_convert_big_rec. */ + +void +dtuple_convert_back_big_rec( +/*========================*/ + dict_index_t* index, /* in: index */ + dtuple_t* entry, /* in: entry whose data was put to vector */ + big_rec_t* vector);/* in, own: big rec vector; it is + freed in this function */ +/****************************************************************** +Frees the memory in a big rec vector. */ + +void +dtuple_big_rec_free( +/*================*/ + big_rec_t* vector); /* in, own: big rec vector; it is + freed in this function */ /*************************************************************** Generates a random tuple. */ @@ -396,7 +434,7 @@ dtuple_gen_search_tuple_TPC_C( /* Structure for an SQL data field */ struct dfield_struct{ void* data; /* pointer to data */ - ulint len; /* data length; UNIV_SQL_NULL if SQL null */ + ulint len; /* data length; UNIV_SQL_NULL if SQL null; */ dtype_t type; /* type of data */ ulint col_no; /* when building index entries, the column number can be stored here */ @@ -423,6 +461,24 @@ struct dtuple_struct { }; #define DATA_TUPLE_MAGIC_N 65478679 +/* A slot for a field in a big rec vector */ + +typedef struct big_rec_field_struct big_rec_field_t; +struct big_rec_field_struct { + ulint field_no; /* field number in record */ + ulint len; /* stored data len */ + byte* data; /* stored data */ +}; + +/* Storage format for overflow data in a big record, that is, a record +which needs external storage of data fields */ + +struct big_rec_struct { + mem_heap_t* heap; /* memory heap from which allocated */ + ulint n_fields; /* number of stored fields */ + big_rec_field_t* fields; /* stored fields */ +}; + #ifndef UNIV_NONINL #include "data0data.ic" #endif diff --git a/innobase/include/data0data.ic b/innobase/include/data0data.ic index 27b5552d338..b886ad6c69c 100644 --- a/innobase/include/data0data.ic +++ b/innobase/include/data0data.ic @@ -307,12 +307,13 @@ dtuple_create( /************************************************************** The following function returns the sum of data lengths of a tuple. The space -occupied by the field structs or the tuple struct is not counted. */ +occupied by the field structs or the tuple struct is not counted. Neither +is possible space in externally stored parts of the field. */ UNIV_INLINE ulint dtuple_get_data_size( /*=================*/ - /* out: sum of data lens */ + /* out: sum of data lengths */ dtuple_t* tuple) /* in: typed data tuple */ { dfield_t* field; @@ -382,7 +383,7 @@ dtuple_datas_are_equal( field2 = dtuple_get_nth_field(tuple2, i); data2 = (byte*) dfield_get_data(field2); - len2 = dfield_get_len(field2); + len2 = dfield_get_len(field2); if (len1 != len2) { diff --git a/innobase/include/dict0mem.h b/innobase/include/dict0mem.h index be9cd42b7be..74ecbc8bba2 100644 --- a/innobase/include/dict0mem.h +++ b/innobase/include/dict0mem.h @@ -143,7 +143,7 @@ struct dict_col_struct{ ulint clust_pos;/* position of the column in the clustered index */ ulint ord_part;/* count of how many times this column - appears in an ordering fields of an index */ + appears in ordering fields of an index */ char* name; /* name */ dtype_t type; /* data type */ dict_table_t* table; /* back pointer to table of this column */ diff --git a/innobase/include/fil0fil.h b/innobase/include/fil0fil.h index 9905b5a2c3c..bfc322270fc 100644 --- a/innobase/include/fil0fil.h +++ b/innobase/include/fil0fil.h @@ -196,6 +196,16 @@ fil_space_get_size( /* out: space size */ ulint id); /* in: space id */ /*********************************************************************** +Checks if the pair space, page_no refers to an existing page in a +tablespace file space. */ + +ibool +fil_check_adress_in_tablespace( +/*===========================*/ + /* out: TRUE if the address is meaningful */ + ulint id, /* in: space id */ + ulint page_no);/* in: page number */ +/*********************************************************************** Appends a new file to the chain of files of a space. File must be closed. */ diff --git a/innobase/include/fsp0fsp.h b/innobase/include/fsp0fsp.h index f1be4de4d40..e7f9eab330b 100644 --- a/innobase/include/fsp0fsp.h +++ b/innobase/include/fsp0fsp.h @@ -70,7 +70,7 @@ page_t* fseg_create( /*========*/ /* out: the page where the segment header is placed, - x-latched, FIL_NULL if could not create segment + x-latched, NULL if could not create segment because of lack of space */ ulint space, /* in: space id */ ulint page, /* in: page where the segment header is placed: if diff --git a/innobase/include/mach0data.ic b/innobase/include/mach0data.ic index 176f3415281..1d6badd035b 100644 --- a/innobase/include/mach0data.ic +++ b/innobase/include/mach0data.ic @@ -115,7 +115,7 @@ mach_write_to_4( { ut_ad(b); -#if notdefined && !defined(__STDC__) && defined(UNIV_INTEL) && (UNIV_WORD_SIZE == 4) && defined(UNIV_VISUALC) +#if (0 == 1) && !defined(__STDC__) && defined(UNIV_INTEL) && (UNIV_WORD_SIZE == 4) && defined(UNIV_VISUALC) /* We do not use this even on Intel, because unaligned accesses may be slow */ @@ -143,7 +143,7 @@ mach_read_from_4( /* out: ulint integer */ byte* b) /* in: pointer to four bytes */ { -#if notdefined && !defined(__STDC__) && defined(UNIV_INTEL) && (UNIV_WORD_SIZE == 4) && defined(UNIV_VISUALC) +#if (0 == 1) && !defined(__STDC__) && defined(UNIV_INTEL) && (UNIV_WORD_SIZE == 4) && defined(UNIV_VISUALC) /* We do not use this even on Intel, because unaligned accesses may be slow */ diff --git a/innobase/include/os0file.h b/innobase/include/os0file.h index c093cb92ca9..75bbbba549f 100644 --- a/innobase/include/os0file.h +++ b/innobase/include/os0file.h @@ -59,6 +59,10 @@ log. */ #define OS_FILE_AIO 61 #define OS_FILE_NORMAL 62 +/* Types for file create */ +#define OS_DATA_FILE 100 +#define OS_LOG_FILE 101 + /* Error codes from os_file_get_last_error */ #define OS_FILE_NOT_FOUND 71 #define OS_FILE_DISK_FULL 72 @@ -125,6 +129,7 @@ os_file_create( if a new file is created or an old overwritten */ ulint purpose,/* in: OS_FILE_AIO, if asynchronous, non-buffered i/o is desired, OS_FILE_NORMAL, if any normal file */ + ulint type, /* in: OS_DATA_FILE or OS_LOG_FILE */ ibool* success);/* out: TRUE if succeed, FALSE if error */ /*************************************************************************** Closes a file handle. In case of error, error number can be retrieved with @@ -263,6 +268,13 @@ os_aio( operation); if mode is OS_AIO_SYNC, these are ignored */ void* message2); +/**************************************************************************** +Waits until there are no pending writes in os_aio_write_array. There can +be other, synchronous, pending writes. */ + +void +os_aio_wait_until_no_pending_writes(void); +/*=====================================*/ /************************************************************************** Wakes up simulated aio i/o-handler threads if they have something to do. */ @@ -298,7 +310,8 @@ os_aio_windows_handle( the aio operation failed, these output parameters are valid and can be used to restart the operation, for example */ - void** message2); + void** message2, + ulint* type); /* out: OS_FILE_WRITE or ..._READ */ #endif #ifdef POSIX_ASYNC_IO /************************************************************************** @@ -335,7 +348,8 @@ os_aio_simulated_handle( the aio operation failed, these output parameters are valid and can be used to restart the operation, for example */ - void** message2); + void** message2, + ulint* type); /* out: OS_FILE_WRITE or ..._READ */ /************************************************************************** Validates the consistency of the aio system. */ diff --git a/innobase/include/rem0cmp.h b/innobase/include/rem0cmp.h index 77b9ef9edc8..10c428cb9ca 100644 --- a/innobase/include/rem0cmp.h +++ b/innobase/include/rem0cmp.h @@ -1,7 +1,7 @@ /*********************************************************************** Comparison services for records -(c) 1994-1996 Innobase Oy +(c) 1994-2001 Innobase Oy Created 7/1/1994 Heikki Tuuri ************************************************************************/ @@ -31,14 +31,18 @@ This function is used to compare a data tuple to a physical record. Only dtuple->n_fields_cmp first fields are taken into account for the the data tuple! If we denote by n = n_fields_cmp, then rec must have either m >= n fields, or it must differ from dtuple in some of -the m fields rec has. */ +the m fields rec has. If rec has an externally stored field we do not +compare it but return with value 0 if such a comparison should be +made. */ int cmp_dtuple_rec_with_match( /*======================*/ /* out: 1, 0, -1, if dtuple is greater, equal, less than rec, respectively, when only the - common first fields are compared */ + common first fields are compared, or + until the first externally stored field in + rec */ dtuple_t* dtuple, /* in: data tuple */ rec_t* rec, /* in: physical record which differs from dtuple in some of the common fields, or which @@ -89,7 +93,8 @@ cmp_dtuple_rec_prefix_equal( fields in dtuple */ /***************************************************************** This function is used to compare two physical records. Only the common -first fields are compared. */ +first fields are compared, and if an externally stored field is +encountered, then 0 is returned. */ int cmp_rec_rec_with_match( diff --git a/innobase/include/rem0rec.h b/innobase/include/rem0rec.h index 62c0aa14519..12e3a8b39d6 100644 --- a/innobase/include/rem0rec.h +++ b/innobase/include/rem0rec.h @@ -12,6 +12,7 @@ Created 5/30/1994 Heikki Tuuri #include "univ.i" #include "data0data.h" #include "rem0types.h" +#include "mtr0types.h" /* Maximum values for various fields (for non-blob tuples) */ #define REC_MAX_N_FIELDS (1024 - 1) @@ -162,6 +163,49 @@ rec_get_nth_field_size( /* out: field size in bytes */ rec_t* rec, /* in: record */ ulint n); /* in: index of the field */ +/*************************************************************** +Gets the value of the ith field extern storage bit. If it is TRUE +it means that the field is stored on another page. */ +UNIV_INLINE +ibool +rec_get_nth_field_extern_bit( +/*=========================*/ + /* in: TRUE or FALSE */ + rec_t* rec, /* in: record */ + ulint i); /* in: ith field */ +/********************************************************** +Returns TRUE if the extern bit is set in any of the fields +of rec. */ +UNIV_INLINE +ibool +rec_contains_externally_stored_field( +/*=================================*/ + /* out: TRUE if a field is stored externally */ + rec_t* rec); /* in: record */ +/*************************************************************** +Sets the value of the ith field extern storage bit. */ + +void +rec_set_nth_field_extern_bit( +/*=========================*/ + rec_t* rec, /* in: record */ + ulint i, /* in: ith field */ + ibool val, /* in: value to set */ + mtr_t* mtr); /* in: mtr holding an X-latch to the page where + rec is, or NULL; in the NULL case we do not + write to log about the change */ +/*************************************************************** +Sets TRUE the extern storage bits of fields mentioned in an array. */ + +void +rec_set_field_extern_bits( +/*======================*/ + rec_t* rec, /* in: record */ + ulint* vec, /* in: array of field numbers */ + ulint n_fields, /* in: number of fields numbers */ + mtr_t* mtr); /* in: mtr holding an X-latch to the page + where rec is, or NULL; in the NULL case we + do not write to log about the change */ /**************************************************************** The following function is used to get a copy of the nth data field in the record to a buffer. */ @@ -350,6 +394,15 @@ rec_sprintf( #define REC_INFO_BITS 6 /* This is single byte bit-field */ +/* Maximum lengths for the data in a physical record if the offsets +are given in one byte (resp. two byte) format. */ +#define REC_1BYTE_OFFS_LIMIT 0x7F +#define REC_2BYTE_OFFS_LIMIT 0x7FFF + +/* The data size of record must be smaller than this because we reserve +two upmost bits in a two byte offset for special purposes */ +#define REC_MAX_DATA_SIZE (16 * 1024) + #ifndef UNIV_NONINL #include "rem0rec.ic" #endif diff --git a/innobase/include/rem0rec.ic b/innobase/include/rem0rec.ic index c63b25374dd..1e9ecb47e2e 100644 --- a/innobase/include/rem0rec.ic +++ b/innobase/include/rem0rec.ic @@ -25,12 +25,6 @@ significant bytes and bits are written below less significant. 4 bits info bits */ - -/* Maximum lengths for the data in a physical record if the offsets -are given as one byte (resp. two byte) format. */ -#define REC_1BYTE_OFFS_LIMIT 0x7F -#define REC_2BYTE_OFFS_LIMIT 0x7FFF - /* We list the byte offsets from the origin of the record, the mask, and the shift needed to obtain each bit-field of the record. */ @@ -66,6 +60,11 @@ one-byte and two-byte offsets */ #define REC_1BYTE_SQL_NULL_MASK 0x80 #define REC_2BYTE_SQL_NULL_MASK 0x8000 +/* In a 2-byte offset the second most significant bit denotes +a field stored to another page: */ + +#define REC_2BYTE_EXTERN_MASK 0x4000 + /*************************************************************** Sets the value of the ith field SQL null bit. */ @@ -489,7 +488,7 @@ ulint rec_2_get_field_end_info( /*=====================*/ /* out: offset of the start of the field, SQL null - flag ORed */ + flag and extern storage flag ORed */ rec_t* rec, /* in: record */ ulint n) /* in: field index */ { @@ -499,6 +498,63 @@ rec_2_get_field_end_info( return(mach_read_from_2(rec - (REC_N_EXTRA_BYTES + 2 * n + 2))); } +/*************************************************************** +Gets the value of the ith field extern storage bit. If it is TRUE +it means that the field is stored on another page. */ +UNIV_INLINE +ibool +rec_get_nth_field_extern_bit( +/*=========================*/ + /* in: TRUE or FALSE */ + rec_t* rec, /* in: record */ + ulint i) /* in: ith field */ +{ + ulint info; + + if (rec_get_1byte_offs_flag(rec)) { + + return(FALSE); + } + + info = rec_2_get_field_end_info(rec, i); + + if (info & REC_2BYTE_EXTERN_MASK) { + return(TRUE); + } + + return(FALSE); +} + +/********************************************************** +Returns TRUE if the extern bit is set in any of the fields +of rec. */ +UNIV_INLINE +ibool +rec_contains_externally_stored_field( +/*=================================*/ + /* out: TRUE if a field is stored externally */ + rec_t* rec) /* in: record */ +{ + ulint n; + ulint i; + + if (rec_get_1byte_offs_flag(rec)) { + + return(FALSE); + } + + n = rec_get_n_fields(rec); + + for (i = 0; i < n; i++) { + if (rec_get_nth_field_extern_bit(rec, i)) { + + return(TRUE); + } + } + + return(FALSE); +} + /********************************************************** Returns the offset of n - 1th field end if the record is stored in the 1-byte offsets form. If the field is SQL null, the flag is ORed in the returned @@ -616,7 +672,7 @@ rec_2_get_field_start_offs( } return(rec_2_get_prev_field_end_info(rec, n) - & ~REC_2BYTE_SQL_NULL_MASK); + & ~(REC_2BYTE_SQL_NULL_MASK | REC_2BYTE_EXTERN_MASK)); } /********************************************************** diff --git a/innobase/include/row0ins.h b/innobase/include/row0ins.h index 94b0e8dec37..612b9e8d73a 100644 --- a/innobase/include/row0ins.h +++ b/innobase/include/row0ins.h @@ -56,6 +56,9 @@ row_ins_index_entry_low( pessimistic descent down the index tree */ dict_index_t* index, /* in: index */ dtuple_t* entry, /* in: index entry to insert */ + ulint* ext_vec,/* in: array containing field numbers of + externally stored fields in entry, or NULL */ + ulint n_ext_vec,/* in: number of fields in ext_vec */ que_thr_t* thr); /* in: query thread */ /******************************************************************* Inserts an index entry to index. Tries first optimistic, then pessimistic @@ -70,6 +73,9 @@ row_ins_index_entry( DB_DUPLICATE_KEY, or some other error code */ dict_index_t* index, /* in: index */ dtuple_t* entry, /* in: index entry to insert */ + ulint* ext_vec,/* in: array containing field numbers of + externally stored fields in entry, or NULL */ + ulint n_ext_vec,/* in: number of fields in ext_vec */ que_thr_t* thr); /* in: query thread */ /*************************************************************** Inserts a row to a table. */ diff --git a/innobase/include/row0mysql.h b/innobase/include/row0mysql.h index 554da2c035c..31f9e15cddc 100644 --- a/innobase/include/row0mysql.h +++ b/innobase/include/row0mysql.h @@ -189,7 +189,9 @@ row_update_for_mysql( row_prebuilt_t* prebuilt); /* in: prebuilt struct in MySQL handle */ /************************************************************************* -Does a table creation operation for MySQL. */ +Does a table creation operation for MySQL. If the name of the created +table ends to characters INNODB_MONITOR, then this also starts +printing of monitor output by the master thread. */ int row_create_table_for_mysql( @@ -209,7 +211,9 @@ row_create_index_for_mysql( dict_index_t* index, /* in: index defintion */ trx_t* trx); /* in: transaction handle */ /************************************************************************* -Drops a table for MySQL. */ +Drops a table for MySQL. If the name of the dropped table ends to +characters INNODB_MONITOR, then this also stops printing of monitor +output by the master thread. */ int row_drop_table_for_mysql( diff --git a/innobase/include/row0row.h b/innobase/include/row0row.h index fb1e1b01ee3..09a79e19fd7 100644 --- a/innobase/include/row0row.h +++ b/innobase/include/row0row.h @@ -250,6 +250,7 @@ row_search_index_entry( #define ROW_COPY_DATA 1 #define ROW_COPY_POINTERS 2 +#define ROW_COPY_ALSO_EXTERNALS 3 /* The allowed latching order of index records is the following: (1) a secondary index record -> diff --git a/innobase/include/row0upd.h b/innobase/include/row0upd.h index 3046345f446..9bb73726b29 100644 --- a/innobase/include/row0upd.h +++ b/innobase/include/row0upd.h @@ -147,6 +147,9 @@ row_upd_build_difference( fields, excluding roll ptr and trx id */ dict_index_t* index, /* in: clustered index */ dtuple_t* entry, /* in: entry to insert */ + ulint* ext_vec,/* in: array containing field numbers of + externally stored fields in entry, or NULL */ + ulint n_ext_vec,/* in: number of fields in ext_vec */ rec_t* rec, /* in: clustered index record */ mem_heap_t* heap); /* in: memory heap from which allocated */ /*************************************************************** @@ -262,6 +265,9 @@ struct upd_field_struct{ constants in the symbol table of the query graph */ dfield_t new_val; /* new value for the column */ + ibool extern_storage; /* this is set to TRUE if dfield + actually contains a reference to + an externally stored field */ }; /* Update vector structure */ @@ -318,6 +324,10 @@ struct upd_node_struct{ dtuple_t* row; /* NULL, or a copy (also fields copied to heap) of the row to update; this must be reset to NULL after a successful update */ + ulint* ext_vec;/* array describing which fields are stored + externally in the clustered index record of + row */ + ulint n_ext_vec;/* number of fields in ext_vec */ mem_heap_t* heap; /* memory heap used as auxiliary storage for row; this must be emptied after a successful update if node->row != NULL */ @@ -349,7 +359,7 @@ struct upd_node_struct{ looked at and updated if an ordering field changed */ -/* Compilation info flags: these must fit within one byte */ +/* Compilation info flags: these must fit within 3 bits; see trx0rec.h */ #define UPD_NODE_NO_ORD_CHANGE 1 /* no secondary index record will be changed in the update and no ordering field of the clustered index */ diff --git a/innobase/include/row0upd.ic b/innobase/include/row0upd.ic index b1b10bef0e8..b785e52caa0 100644 --- a/innobase/include/row0upd.ic +++ b/innobase/include/row0upd.ic @@ -23,6 +23,7 @@ upd_create( mem_heap_t* heap) /* in: heap from which memory allocated */ { upd_t* update; + ulint i; update = mem_heap_alloc(heap, sizeof(upd_t)); @@ -30,6 +31,10 @@ upd_create( update->n_fields = n; update->fields = mem_heap_alloc(heap, sizeof(upd_field_t) * n); + for (i = 0; i < n; i++) { + update->fields[i].extern_storage = 0; + } + return(update); } diff --git a/innobase/include/srv0srv.h b/innobase/include/srv0srv.h index f80abda19c6..e635964e5ec 100644 --- a/innobase/include/srv0srv.h +++ b/innobase/include/srv0srv.h @@ -27,6 +27,9 @@ extern char** srv_data_file_names; extern ulint* srv_data_file_sizes; extern ulint* srv_data_file_is_raw_partition; +#define SRV_NEW_RAW 1 +#define SRV_OLD_RAW 2 + extern char** srv_log_group_home_dirs; extern ulint srv_n_log_groups; @@ -52,10 +55,14 @@ extern ulint srv_lock_wait_timeout; extern char* srv_unix_file_flush_method_str; extern ulint srv_unix_file_flush_method; +extern ibool srv_use_doublewrite_buf; + extern ibool srv_set_thread_priorities; extern int srv_query_thread_priority; /*-------------------------------------------*/ + +extern ibool srv_print_innodb_monitor; extern ulint srv_n_spin_wait_rounds; extern ulint srv_spin_wait_delay; extern ibool srv_priority_boost; @@ -104,26 +111,13 @@ typedef struct srv_sys_struct srv_sys_t; /* The server system */ extern srv_sys_t* srv_sys; -/* Alternatives for file flush option in Unix; see the InnoDB manual about +/* Alternatives for fiel flush option in Unix; see the InnoDB manual about what these mean */ #define SRV_UNIX_FDATASYNC 1 #define SRV_UNIX_O_DSYNC 2 #define SRV_UNIX_LITTLESYNC 3 #define SRV_UNIX_NOSYNC 4 -/* Raw partition flags */ -#define SRV_OLD_RAW 1 -#define SRV_NEW_RAW 2 - -void -srv_mysql_thread_release(void); -/*==========================*/ -os_event_t -srv_mysql_thread_event_get(void); -void -srv_mysql_thread_slot_free( -/*==========================*/ - os_event_t event); /************************************************************************* Boots Innobase server. */ diff --git a/innobase/include/sync0sync.h b/innobase/include/sync0sync.h index 4b12dd3c86d..cb86b2b815c 100644 --- a/innobase/include/sync0sync.h +++ b/innobase/include/sync0sync.h @@ -393,6 +393,7 @@ Memory pool mutex */ #define SYNC_RSEG_HEADER_NEW 591 #define SYNC_RSEG_HEADER 590 #define SYNC_TRX_UNDO_PAGE 570 +#define SYNC_EXTERN_STORAGE 500 #define SYNC_FSP 400 #define SYNC_FSP_PAGE 395 /*------------------------------------- Insert buffer headers */ @@ -415,6 +416,7 @@ Memory pool mutex */ the level is SYNC_MEM_HASH. */ #define SYNC_BUF_POOL 150 #define SYNC_BUF_BLOCK 149 +#define SYNC_DOUBLEWRITE 140 #define SYNC_ANY_LATCH 135 #define SYNC_MEM_HASH 131 #define SYNC_MEM_POOL 130 diff --git a/innobase/include/trx0rec.h b/innobase/include/trx0rec.h index ea9e9f3fce5..edfc283d1b2 100644 --- a/innobase/include/trx0rec.h +++ b/innobase/include/trx0rec.h @@ -45,6 +45,14 @@ trx_undo_rec_get_cmpl_info( /* out: compiler info */ trx_undo_rec_t* undo_rec); /* in: undo log record */ /************************************************************************** +Returns TRUE if an undo log record contains an extern storage field. */ +UNIV_INLINE +ibool +trx_undo_rec_get_extern_storage( +/*============================*/ + /* out: TRUE if extern */ + trx_undo_rec_t* undo_rec); /* in: undo log record */ +/************************************************************************** Reads the undo log record number. */ UNIV_INLINE dulint @@ -65,6 +73,8 @@ trx_undo_rec_get_pars( TRX_UNDO_INSERT_REC, ... */ ulint* cmpl_info, /* out: compiler info, relevant only for update type records */ + ibool* updated_extern, /* out: TRUE if we updated an + externally stored fild */ dulint* undo_no, /* out: undo log record number */ dulint* table_id); /* out: table id */ /*********************************************************************** @@ -272,7 +282,11 @@ record */ do not change */ #define TRX_UNDO_CMPL_INFO_MULT 16 /* compilation info is multiplied by this and ORed to the type above */ - +#define TRX_UNDO_UPD_EXTERN 128 /* This bit can be ORed to type_cmpl + to denote that we updated external + storage fields: used by purge to + free the external storage */ + /* Operation type flags used in trx_undo_report_row_operation */ #define TRX_UNDO_INSERT_OP 1 #define TRX_UNDO_MODIFY_OP 2 diff --git a/innobase/include/trx0rec.ic b/innobase/include/trx0rec.ic index f813a52ff9c..cd02ed9e04c 100644 --- a/innobase/include/trx0rec.ic +++ b/innobase/include/trx0rec.ic @@ -30,6 +30,23 @@ trx_undo_rec_get_cmpl_info( return(mach_read_from_1(undo_rec + 2) / TRX_UNDO_CMPL_INFO_MULT); } +/************************************************************************** +Returns TRUE if an undo log record contains an extern storage field. */ +UNIV_INLINE +ibool +trx_undo_rec_get_extern_storage( +/*============================*/ + /* out: TRUE if extern */ + trx_undo_rec_t* undo_rec) /* in: undo log record */ +{ + if (mach_read_from_1(undo_rec + 2) & TRX_UNDO_UPD_EXTERN) { + + return(TRUE); + } + + return(FALSE); +} + /************************************************************************** Reads the undo log record number. */ UNIV_INLINE diff --git a/innobase/include/trx0sys.h b/innobase/include/trx0sys.h index d0506dd65b7..e26f7e19850 100644 --- a/innobase/include/trx0sys.h +++ b/innobase/include/trx0sys.h @@ -27,6 +27,23 @@ Created 3/26/1996 Heikki Tuuri /* The transaction system */ extern trx_sys_t* trx_sys; +/* Doublewrite system */ +extern trx_doublewrite_t* trx_doublewrite; + +/******************************************************************** +Creates the doublewrite buffer at a database start. The header of the +doublewrite buffer is placed on the trx system header page. */ + +void +trx_sys_create_doublewrite_buf(void); +/*================================*/ +/******************************************************************** +At a database startup uses a possible doublewrite buffer to restore +half-written pages in the data files. */ + +void +trx_sys_doublewrite_restore_corrupt_pages(void); +/*===========================================*/ /******************************************************************* Checks if a page address is the trx sys header page. */ UNIV_INLINE @@ -235,6 +252,59 @@ therefore 256 */ segment specification slots */ /*-------------------------------------------------------------*/ +/* The offset of the doublewrite buffer header on the trx system header page */ +#define TRX_SYS_DOUBLEWRITE (UNIV_PAGE_SIZE - 200) +/*-------------------------------------------------------------*/ +#define TRX_SYS_DOUBLEWRITE_FSEG 0 /* fseg header of the fseg + containing the doublewrite + buffer */ +#define TRX_SYS_DOUBLEWRITE_MAGIC FSEG_HEADER_SIZE + /* 4-byte magic number which + shows if we already have + created the doublewrite + buffer */ +#define TRX_SYS_DOUBLEWRITE_BLOCK1 (4 + FSEG_HEADER_SIZE) + /* page number of the + first page in the first + sequence of 64 + (= FSP_EXTENT_SIZE) consecutive + pages in the doublewrite + buffer */ +#define TRX_SYS_DOUBLEWRITE_BLOCK2 (8 + FSEG_HEADER_SIZE) + /* page number of the + first page in the second + sequence of 64 consecutive + pages in the doublewrite + buffer */ +#define TRX_SYS_DOUBLEWRITE_REPEAT 12 /* we repeat the above 3 + numbers so that if the trx + sys header is half-written + to disk, we still may be able + to recover the information */ +/*-------------------------------------------------------------*/ +#define TRX_SYS_DOUBLEWRITE_MAGIC_N 536853855 + +#define TRX_SYS_DOUBLEWRITE_BLOCK_SIZE FSP_EXTENT_SIZE + +/* Doublewrite control struct */ +struct trx_doublewrite_struct{ + mutex_t mutex; /* mutex protecting the first_free field and + write_buf */ + ulint block1; /* the page number of the first + doublewrite block (64 pages) */ + ulint block2; /* page number of the second block */ + ulint first_free; /* first free position in write_buf measured + in units of UNIV_PAGE_SIZE */ + byte* write_buf; /* write buffer used in writing to the + doublewrite buffer, aligned to an + address divisible by UNIV_PAGE_SIZE + (which is required by Windows aio) */ + byte* write_buf_unaligned; /* pointer to write_buf, but unaligned */ + buf_block_t** + buf_block_arr; /* array to store pointers to the buffer + blocks which have been cached to write_buf */ +}; + /* The transaction system central memory data structure; protected by the kernel mutex */ struct trx_sys_struct{ diff --git a/innobase/include/trx0types.h b/innobase/include/trx0types.h index 02da1605077..b8befe7172f 100644 --- a/innobase/include/trx0types.h +++ b/innobase/include/trx0types.h @@ -15,6 +15,7 @@ Created 3/26/1996 Heikki Tuuri /* Memory objects */ typedef struct trx_struct trx_t; typedef struct trx_sys_struct trx_sys_t; +typedef struct trx_doublewrite_struct trx_doublewrite_t; typedef struct trx_sig_struct trx_sig_t; typedef struct trx_rseg_struct trx_rseg_t; typedef struct trx_undo_struct trx_undo_t; diff --git a/innobase/include/trx0undo.h b/innobase/include/trx0undo.h index 82c21f756e6..7f0378c68d3 100644 --- a/innobase/include/trx0undo.h +++ b/innobase/include/trx0undo.h @@ -341,7 +341,9 @@ struct trx_undo_struct{ have delete marked records, because of a delete of a row or an update of an indexed field; purge is then - necessary. */ + necessary; also TRUE if the transaction + has updated an externally stored + field */ dulint trx_id; /* id of the trx assigned to the undo log */ ibool dict_operation; /* TRUE if a dict operation trx */ diff --git a/innobase/include/univ.i b/innobase/include/univ.i index 73bf48b1bc0..6ffbb1b8fef 100644 --- a/innobase/include/univ.i +++ b/innobase/include/univ.i @@ -9,11 +9,12 @@ Created 1/20/1994 Heikki Tuuri #ifndef univ_i #define univ_i -#undef UNIV_INTEL_X86 - -#if (defined(_WIN32) || defined(_WIN64)) && !defined(MYSQL_SERVER) +#if (defined(_WIN32) || defined(_WIN64)) #define __WIN__ + +#ifndef MYSQL_SERVER #include +#endif /* If you want to check for errors with compiler level -W4, comment out the above include of windows.h and let the following defines @@ -40,10 +41,8 @@ subdirectory of 'mysql'. */ #include #include -#ifndef __WIN__ /* Include to get S_I... macros defined for os0file.c */ #include -#endif #undef PACKAGE #undef VERSION @@ -63,19 +62,21 @@ subdirectory of 'mysql'. */ /* DEBUG VERSION CONTROL ===================== */ + +/* +#define UNIV_SYNC_DEBUG +*/ + /* Make a non-inline debug version */ /* #define UNIV_DEBUG #define UNIV_MEM_DEBUG -#define UNIV_SYNC_DEBUG #define UNIV_SEARCH_DEBUG #define UNIV_IBUF_DEBUG #define UNIV_SYNC_PERF_STAT #define UNIV_SEARCH_PERF_STAT - -#define UNIV_DEBUG_FILE_ACCESSES */ #define UNIV_LIGHT_MEM_DEBUG @@ -192,6 +193,13 @@ headers may define 'bool' differently. Do not assume that 'bool' is a ulint! */ has the SQL NULL as its value. */ #define UNIV_SQL_NULL ULINT_UNDEFINED +/* Lengths which are not UNIV_SQL_NULL, but bigger than the following +number indicate that a field contains a reference to an externally +stored part of the field in the tablespace. The length field then +contains the sum of the following flag and the locally stored len. */ + +#define UNIV_EXTERN_STORAGE_FIELD (UNIV_SQL_NULL - UNIV_PAGE_SIZE) + /* The following definition of __FILE__ removes compiler warnings associated with const char* / char* mismatches with __FILE__ */ diff --git a/innobase/include/ut0dbg.h b/innobase/include/ut0dbg.h index 657d1bf95b2..fc5d493ca5e 100644 --- a/innobase/include/ut0dbg.h +++ b/innobase/include/ut0dbg.h @@ -41,7 +41,7 @@ extern ulint* ut_dbg_null_ptr; }\ if (ut_dbg_stop_threads) {\ fprintf(stderr,\ - "Innobase: Thread %lu stopped in file %s line %lu\n",\ + "InnoDB: Thread %lu stopped in file %s line %lu\n",\ os_thread_get_curr_id(), IB__FILE__, (ulint)__LINE__);\ os_thread_sleep(1000000000);\ }\ @@ -50,19 +50,17 @@ extern ulint* ut_dbg_null_ptr; #define ut_error {\ ulint dbg_i;\ fprintf(stderr,\ - "Innobase: Assertion failure in thread %lu in file %s line %lu\n",\ + "InnoDB: Assertion failure in thread %lu in file %s line %lu\n",\ os_thread_get_curr_id(), IB__FILE__, (ulint)__LINE__);\ fprintf(stderr,\ - "Innobase: we intentionally generate a memory trap.\n");\ + "InnoDB: We intentionally generate a memory trap.\n");\ fprintf(stderr,\ - "Innobase: Send a bug report to mysql@lists.mysql.com\n");\ + "InnoDB: Send a detailed bug report to mysql@lists.mysql.com\n");\ ut_dbg_stop_threads = TRUE;\ dbg_i = *(ut_dbg_null_ptr);\ printf("%lu", dbg_i);\ } - - #ifdef UNIV_DEBUG #define ut_ad(EXPR) ut_a(EXPR) #define ut_d(EXPR) {EXPR;} diff --git a/innobase/include/ut0ut.h b/innobase/include/ut0ut.h index 1e93a2b8a36..e1813e763bd 100644 --- a/innobase/include/ut0ut.h +++ b/innobase/include/ut0ut.h @@ -11,8 +11,7 @@ Created 1/20/1994 Heikki Tuuri #include "univ.i" #include -#include - +#include typedef time_t ib_time_t; diff --git a/innobase/lock/lock0lock.c b/innobase/lock/lock0lock.c index 79fb66459b2..5f8f538f392 100644 --- a/innobase/lock/lock0lock.c +++ b/innobase/lock/lock0lock.c @@ -3219,6 +3219,7 @@ lock_rec_print( ulint space; ulint page_no; ulint i; + ulint count = 0; mtr_t mtr; ut_ad(mutex_own(&kernel_mutex)); @@ -3230,7 +3231,8 @@ lock_rec_print( printf("\nRECORD LOCKS space id %lu page no %lu n bits %lu", space, page_no, lock_rec_get_n_bits(lock)); - printf(" index %s trx id %lu %lu", (lock->index)->name, + printf(" table %s index %s trx id %lu %lu", + lock->index->table->name, lock->index->name, (lock->trx)->id.high, (lock->trx)->id.low); if (lock_get_mode(lock) == LOCK_S) { @@ -3281,10 +3283,18 @@ lock_rec_print( rec_print(page_find_rec_with_heap_no(page, i)); } + count++; + printf("\n"); } - } + if (count >= 3) { + printf( + "3 LOCKS PRINTED FOR THIS TRX AND PAGE: SUPPRESSING FURTHER PRINTS\n"); + goto end_prints; + } + } +end_prints: mtr_commit(&mtr); } @@ -3335,7 +3345,6 @@ lock_print_info(void) lock_mutex_enter_kernel(); - printf("------------------------------------\n"); printf("LOCK INFO:\n"); printf("Number of locks in the record hash table %lu\n", lock_get_n_rec_locks()); @@ -3352,7 +3361,7 @@ loop: if (trx == NULL) { lock_mutex_exit_kernel(); - lock_validate(); + /* lock_validate(); */ return; } @@ -3360,6 +3369,19 @@ loop: if (nth_lock == 0) { printf("\nLOCKS FOR TRANSACTION ID %lu %lu\n", trx->id.high, trx->id.low); + if (trx->que_state == TRX_QUE_LOCK_WAIT) { + printf( + "################# TRX IS WAITING FOR THE LOCK: ###\n"); + + if (lock_get_type(trx->wait_lock) == LOCK_REC) { + lock_rec_print(trx->wait_lock); + } else { + lock_table_print(trx->wait_lock); + } + + printf( + "##################################################\n"); + } } i = 0; @@ -3409,6 +3431,16 @@ loop: nth_lock++; + if (nth_lock >= 25) { + printf( + "25 LOCKS PRINTED FOR THIS TRX: SUPPRESSING FURTHER PRINTS\n"); + + nth_trx++; + nth_lock = 0; + + goto loop; + } + goto loop; } diff --git a/innobase/log/log0log.c b/innobase/log/log0log.c index 31cf595e59e..351ea7f2fd5 100644 --- a/innobase/log/log0log.c +++ b/innobase/log/log0log.c @@ -838,7 +838,9 @@ log_io_complete( /* It was a checkpoint write */ group = (log_group_t*)((ulint)group - 1); - if (srv_unix_file_flush_method == SRV_UNIX_LITTLESYNC) { + if (srv_unix_file_flush_method != SRV_UNIX_O_DSYNC + && srv_unix_file_flush_method != SRV_UNIX_NOSYNC) { + fil_flush(group->space_id); } @@ -847,7 +849,9 @@ log_io_complete( return; } - if (srv_unix_file_flush_method == SRV_UNIX_LITTLESYNC) { + if (srv_unix_file_flush_method != SRV_UNIX_O_DSYNC + && srv_unix_file_flush_method != SRV_UNIX_NOSYNC) { + fil_flush(group->space_id); } @@ -1478,7 +1482,7 @@ log_checkpoint( recv_apply_hashed_log_recs(TRUE); } - if (srv_unix_file_flush_method == SRV_UNIX_LITTLESYNC) { + if (srv_unix_file_flush_method != SRV_UNIX_NOSYNC) { fil_flush_file_spaces(FIL_TABLESPACE); } @@ -1885,10 +1889,11 @@ loop: fil_reserve_right_to_open(); file_handle = os_file_create(name, open_mode, OS_FILE_AIO, - &ret); + OS_DATA_FILE, &ret); + if (!ret && (open_mode == OS_FILE_CREATE)) { file_handle = os_file_create(name, OS_FILE_OPEN, - OS_FILE_AIO, &ret); + OS_FILE_AIO, OS_DATA_FILE, &ret); } if (!ret) { diff --git a/innobase/log/log0recv.c b/innobase/log/log0recv.c index d16085a2d6f..edab98fa39c 100644 --- a/innobase/log/log0recv.c +++ b/innobase/log/log0recv.c @@ -2234,7 +2234,8 @@ try_open_again: fil_reserve_right_to_open(); - file_handle = os_file_create(name, OS_FILE_OPEN, OS_FILE_AIO, &ret); + file_handle = os_file_create(name, OS_FILE_OPEN, + OS_FILE_LOG, OS_FILE_AIO, &ret); if (ret == FALSE) { fil_release_right_to_open(); diff --git a/innobase/os/os0file.c b/innobase/os/os0file.c index d3c6232031a..0525fd7b59a 100644 --- a/innobase/os/os0file.c +++ b/innobase/os/os0file.c @@ -10,6 +10,7 @@ Created 10/21/1995 Heikki Tuuri #include "os0sync.h" #include "ut0mem.h" #include "srv0srv.h" +#include "trx0sys.h" #undef HAVE_FDATASYNC @@ -74,9 +75,12 @@ typedef struct os_aio_array_struct os_aio_array_t; struct os_aio_array_struct{ os_mutex_t mutex; /* the mutex protecting the aio array */ - os_event_t not_full; /* The event which is set to signaled + os_event_t not_full; /* The event which is set to the signaled state when there is space in the aio outside the ibuf segment */ + os_event_t is_empty; /* The event which is set to the signaled + state when there are no pending i/os + in this array */ ulint n_slots; /* Total number of slots in the aio array. This must be divisible by n_threads. */ ulint n_segments;/* Number of segments in the aio array of @@ -254,6 +258,7 @@ os_file_create( if a new is created or an old overwritten */ ulint purpose,/* in: OS_FILE_AIO, if asynchronous, non-buffered i/o is desired, OS_FILE_NORMAL, if any normal file */ + ulint type, /* in: OS_DATA_FILE or OS_LOG_FILE */ ibool* success)/* out: TRUE if succeed, FALSE if error */ { #ifdef __WIN__ @@ -347,11 +352,10 @@ try_again: UT_NOT_USED(purpose); - /* Currently use only O_SYNC because there may be a bug in - Linux O_DSYNC! */ - #ifdef O_SYNC - if (srv_unix_file_flush_method == SRV_UNIX_O_DSYNC) { + if ((!srv_use_doublewrite_buf || type != OS_DATA_FILE) + && srv_unix_file_flush_method == SRV_UNIX_O_DSYNC) { + create_flag = create_flag | O_SYNC; } #endif @@ -551,12 +555,6 @@ os_file_flush( #else int ret; -#ifdef O_DSYNC - if (srv_unix_file_flush_method == SRV_UNIX_O_DSYNC) { - return(TRUE); - } -#endif - #ifdef HAVE_FDATASYNC ret = fdatasync(file); #else @@ -637,7 +635,8 @@ os_file_pwrite( ret = pwrite(file, buf, n, offs); if (srv_unix_file_flush_method != SRV_UNIX_LITTLESYNC - && srv_unix_file_flush_method != SRV_UNIX_NOSYNC) { + && srv_unix_file_flush_method != SRV_UNIX_NOSYNC + && !trx_doublewrite) { /* Always do fsync to reduce the probability that when the OS crashes, a database page is only partially @@ -666,7 +665,8 @@ os_file_pwrite( ret = write(file, buf, n); if (srv_unix_file_flush_method != SRV_UNIX_LITTLESYNC - && srv_unix_file_flush_method != SRV_UNIX_NOSYNC) { + && srv_unix_file_flush_method != SRV_UNIX_NOSYNC + && !trx_doublewrite) { /* Always do fsync to reduce the probability that when the OS crashes, a database page is only partially @@ -825,7 +825,9 @@ try_again: /* Always do fsync to reduce the probability that when the OS crashes, a database page is only partially physically written to disk. */ - ut_a(TRUE == os_file_flush(file)); + if (!trx_doublewrite) { + ut_a(TRUE == os_file_flush(file)); + } os_mutex_exit(os_file_seek_mutexes[i]); @@ -900,6 +902,10 @@ os_aio_array_create( array->mutex = os_mutex_create(NULL); array->not_full = os_event_create(NULL); + array->is_empty = os_event_create(NULL); + + os_event_set(array->is_empty); + array->n_slots = n; array->n_segments = n_segments; array->n_reserved = 0; @@ -999,6 +1005,17 @@ os_aio_init( #endif } +/**************************************************************************** +Waits until there are no pending writes in os_aio_write_array. There can +be other, synchronous, pending writes. */ + +void +os_aio_wait_until_no_pending_writes(void) +/*=====================================*/ +{ + os_event_wait(os_aio_write_array->is_empty); +} + /************************************************************************** Calculates segment number for a slot. */ static @@ -1191,6 +1208,10 @@ loop: array->n_reserved++; + if (array->n_reserved == 1) { + os_event_reset(array->is_empty); + } + if (array->n_reserved == array->n_slots) { os_event_reset(array->not_full); } @@ -1264,6 +1285,10 @@ os_aio_array_free_slot( os_event_set(array->not_full); } + if (array->n_reserved == 0) { + os_event_set(array->is_empty); + } + #ifdef WIN_ASYNC_IO os_event_reset(slot->control.hEvent); #endif @@ -1377,6 +1402,7 @@ os_aio( DWORD len = n; void* dummy_mess1; void* dummy_mess2; + ulint dummy_type; #endif ulint err = 0; ibool retry; @@ -1489,8 +1515,9 @@ try_again: use the same wait mechanism as for async i/o */ return(os_aio_windows_handle(ULINT_UNDEFINED, - slot->pos, - &dummy_mess1, &dummy_mess2)); + slot->pos, + &dummy_mess1, &dummy_mess2, + &dummy_type)); } return(TRUE); @@ -1547,7 +1574,8 @@ os_aio_windows_handle( the aio operation failed, these output parameters are valid and can be used to restart the operation, for example */ - void** message2) + void** message2, + ulint* type) /* out: OS_FILE_WRITE or ..._READ */ { os_aio_array_t* array; os_aio_slot_t* slot; @@ -1592,10 +1620,12 @@ os_aio_windows_handle( *message1 = slot->message1; *message2 = slot->message2; + *type = slot->type; + if (ret && len == slot->len) { ret_val = TRUE; - if (slot->type == OS_FILE_WRITE) { + if (slot->type == OS_FILE_WRITE && !trx_doublewrite) { ut_a(TRUE == os_file_flush(slot->file)); } } else { @@ -1679,7 +1709,7 @@ os_aio_posix_handle( *message1 = slot->message1; *message2 = slot->message2; - if (slot->type == OS_FILE_WRITE) { + if (slot->type == OS_FILE_WRITE && !trx_doublewrite) { ut_a(TRUE == os_file_flush(slot->file)); } @@ -1709,7 +1739,8 @@ os_aio_simulated_handle( the aio operation failed, these output parameters are valid and can be used to restart the operation, for example */ - void** message2) + void** message2, + ulint* type) /* out: OS_FILE_WRITE or ..._READ */ { os_aio_array_t* array; ulint segment; @@ -1906,6 +1937,8 @@ slot_io_done: *message1 = slot->message1; *message2 = slot->message2; + *type = slot->type; + os_mutex_exit(array->mutex); os_aio_array_free_slot(array, slot); @@ -1989,13 +2022,13 @@ os_aio_print(void) os_aio_slot_t* slot; ulint n_reserved; ulint i; - + + printf("Pending normal aio reads:\n"); + array = os_aio_read_array; loop: ut_a(array); - printf("INFO OF AN AIO ARRAY\n"); - os_mutex_enter(array->mutex); ut_a(array->n_slots > 0); @@ -2022,24 +2055,29 @@ loop: os_mutex_exit(array->mutex); if (array == os_aio_read_array) { + printf("Pending aio writes:\n"); + array = os_aio_write_array; goto loop; } if (array == os_aio_write_array) { + printf("Pending insert buffer aio reads:\n"); array = os_aio_ibuf_array; goto loop; } if (array == os_aio_ibuf_array) { + printf("Pending log writes or reads:\n"); array = os_aio_log_array; goto loop; } if (array == os_aio_log_array) { + printf("Pending synchronous reads or writes:\n"); array = os_aio_sync_array; goto loop; diff --git a/innobase/page/page0cur.c b/innobase/page/page0cur.c index e329b916b1b..0b233b4dd72 100644 --- a/innobase/page/page0cur.c +++ b/innobase/page/page0cur.c @@ -1019,16 +1019,16 @@ page_cur_delete_rec( page_cur_t* cursor, /* in: a page cursor */ mtr_t* mtr) /* in: mini-transaction handle */ { + page_dir_slot_t* cur_dir_slot; + page_dir_slot_t* prev_slot; page_t* page; rec_t* current_rec; rec_t* prev_rec = NULL; rec_t* next_rec; ulint cur_slot_no; - page_dir_slot_t* cur_dir_slot; - page_dir_slot_t* prev_slot; ulint cur_n_owned; rec_t* rec; - + ut_ad(cursor && mtr); page = page_cur_get_page(cursor); @@ -1037,7 +1037,7 @@ page_cur_delete_rec( /* The record must not be the supremum or infimum record. */ ut_ad(current_rec != page_get_supremum_rec(page)); ut_ad(current_rec != page_get_infimum_rec(page)); - + /* Save to local variables some data associated with current_rec */ cur_slot_no = page_dir_find_owner_slot(current_rec); cur_dir_slot = page_dir_get_nth_slot(page, cur_slot_no); diff --git a/innobase/pars/pars0pars.c b/innobase/pars/pars0pars.c index f6c51f3905a..4a298426476 100644 --- a/innobase/pars/pars0pars.c +++ b/innobase/pars/pars0pars.c @@ -2028,11 +2028,7 @@ pars_complete_graph_for_exec( que_node_set_parent(node, thr); - mutex_enter(&kernel_mutex); - trx->graph = NULL; - mutex_exit(&kernel_mutex); - return(thr); } diff --git a/innobase/rem/rem0cmp.c b/innobase/rem/rem0cmp.c index 78f4e450269..cdf1f363946 100644 --- a/innobase/rem/rem0cmp.c +++ b/innobase/rem/rem0cmp.c @@ -295,14 +295,18 @@ This function is used to compare a data tuple to a physical record. Only dtuple->n_fields_cmp first fields are taken into account for the the data tuple! If we denote by n = n_fields_cmp, then rec must have either m >= n fields, or it must differ from dtuple in some of -the m fields rec has. */ +the m fields rec has. If rec has an externally stored field we do not +compare it but return with value 0 if such a comparison should be +made. */ int cmp_dtuple_rec_with_match( /*======================*/ /* out: 1, 0, -1, if dtuple is greater, equal, less than rec, respectively, when only the - common first fields are compared */ + common first fields are compared, or + until the first externally stored field in + rec */ dtuple_t* dtuple, /* in: data tuple */ rec_t* rec, /* in: physical record which differs from dtuple in some of the common fields, or which @@ -344,7 +348,8 @@ cmp_dtuple_rec_with_match( ut_ad(cur_field <= dtuple_get_n_fields_cmp(dtuple)); ut_ad(cur_field <= rec_get_n_fields(rec)); - /* Match fields in a loop; stop if we run out of fields in dtuple */ + /* Match fields in a loop; stop if we run out of fields in dtuple + or find an externally stored field */ while (cur_field < dtuple_get_n_fields_cmp(dtuple)) { @@ -357,7 +362,8 @@ cmp_dtuple_rec_with_match( /* If we have matched yet 0 bytes, it may be that one or both the fields are SQL null, or the record or dtuple may be - the predefined minimum record */ + the predefined minimum record, or the field is externally + stored */ if (cur_bytes == 0) { if (cur_field == 0) { @@ -384,6 +390,15 @@ cmp_dtuple_rec_with_match( } } + if (rec_get_nth_field_extern_bit(rec, cur_field)) { + /* We do not compare to an externally + stored field */ + + ret = 0; + + goto order_resolved; + } + if (dtuple_f_len == UNIV_SQL_NULL || rec_f_len == UNIV_SQL_NULL) { @@ -604,7 +619,8 @@ cmp_dtuple_rec_prefix_equal( /***************************************************************** This function is used to compare two physical records. Only the common -first fields are compared. */ +first fields are compared, and if an externally stored field is +encountered, then 0 is returned. */ int cmp_rec_rec_with_match( @@ -688,8 +704,18 @@ cmp_rec_rec_with_match( goto order_resolved; } - } + } + if (rec_get_nth_field_extern_bit(rec1, cur_field) + || rec_get_nth_field_extern_bit(rec2, cur_field)) { + /* We do not compare to an externally + stored field */ + + ret = 0; + + goto order_resolved; + } + if (rec1_f_len == UNIV_SQL_NULL || rec2_f_len == UNIV_SQL_NULL) { @@ -812,7 +838,8 @@ order_resolved: Used in debug checking of cmp_dtuple_... . This function is used to compare a data tuple to a physical record. If dtuple has n fields then rec must have either m >= n fields, or it must -differ from dtuple in some of the m fields rec has. */ +differ from dtuple in some of the m fields rec has. If encounters an +externally stored field, returns 0. */ static int cmp_debug_dtuple_rec_with_match( @@ -882,6 +909,14 @@ cmp_debug_dtuple_rec_with_match( rec_f_data = rec_get_nth_field(rec, cur_field, &rec_f_len); + if (rec_get_nth_field_extern_bit(rec, cur_field)) { + /* We do not compare to an externally stored field */ + + ret = 0; + + goto order_resolved; + } + ret = cmp_data_data(cur_type, dtuple_f_data, dtuple_f_len, rec_f_data, rec_f_len); if (ret != 0) { diff --git a/innobase/rem/rem0rec.c b/innobase/rem/rem0rec.c index 9ddfe7a4b9a..88009f2f5c9 100644 --- a/innobase/rem/rem0rec.c +++ b/innobase/rem/rem0rec.c @@ -1,7 +1,7 @@ /************************************************************************ Record manager -(c) 1994-1996 Innobase Oy +(c) 1994-2001 Innobase Oy Created 5/30/1994 Heikki Tuuri *************************************************************************/ @@ -12,6 +12,9 @@ Created 5/30/1994 Heikki Tuuri #include "rem0rec.ic" #endif +#include "mtr0mtr.h" +#include "mtr0log.h" + /* PHYSICAL RECORD =============== @@ -21,7 +24,10 @@ found in index pages of the database, has the following format represented on a higher text line): | offset of the end of the last field of data, the most significant - bit is set to 1 if and only if the field is SQL-null | + bit is set to 1 if and only if the field is SQL-null, + if the offset is 2-byte, then the second most significant + bit is set to 1 if the field is stored on another page: + mostly this will occur in the case of big BLOB fields | ... | offset of the end of the first field of data + the SQL-null bit | | 4 bits used to delete mark a record, and mark a predefined @@ -122,7 +128,8 @@ rec_get_nth_field( return(rec + os); } - next_os = next_os & ~REC_2BYTE_SQL_NULL_MASK; + next_os = next_os & ~(REC_2BYTE_SQL_NULL_MASK + | REC_2BYTE_EXTERN_MASK); } *len = next_os - os; @@ -170,6 +177,60 @@ rec_set_nth_field_null_bit( rec_2_set_field_end_info(rec, i, info); } +/*************************************************************** +Sets the value of the ith field extern storage bit. */ + +void +rec_set_nth_field_extern_bit( +/*=========================*/ + rec_t* rec, /* in: record */ + ulint i, /* in: ith field */ + ibool val, /* in: value to set */ + mtr_t* mtr) /* in: mtr holding an X-latch to the page where + rec is, or NULL; in the NULL case we do not + write to log about the change */ +{ + ulint info; + + ut_a(!rec_get_1byte_offs_flag(rec)); + ut_a(i < rec_get_n_fields(rec)); + + info = rec_2_get_field_end_info(rec, i); + + if (val) { + info = info | REC_2BYTE_EXTERN_MASK; + } else { + info = info & ~REC_2BYTE_EXTERN_MASK; + } + + if (mtr) { + mlog_write_ulint(rec - REC_N_EXTRA_BYTES - 2 * (i + 1), info, + MLOG_2BYTES, mtr); + } else { + rec_2_set_field_end_info(rec, i, info); + } +} + +/*************************************************************** +Sets TRUE the extern storage bits of fields mentioned in an array. */ + +void +rec_set_field_extern_bits( +/*======================*/ + rec_t* rec, /* in: record */ + ulint* vec, /* in: array of field numbers */ + ulint n_fields, /* in: number of fields numbers */ + mtr_t* mtr) /* in: mtr holding an X-latch to the page + where rec is, or NULL; in the NULL case we + do not write to log about the change */ +{ + ulint i; + + for (i = 0; i < n_fields; i++) { + rec_set_nth_field_extern_bit(rec, vec[i], TRUE, mtr); + } +} + /*************************************************************** Sets a record field to SQL null. The physical size of the field is not changed. */ diff --git a/innobase/row/row0ins.c b/innobase/row/row0ins.c index e57622fd1c5..8542dcae326 100644 --- a/innobase/row/row0ins.c +++ b/innobase/row/row0ins.c @@ -234,7 +234,13 @@ row_ins_clust_index_entry_by_modify( depending on whether mtr holds just a leaf latch or also a tree latch */ btr_cur_t* cursor, /* in: B-tree cursor */ + big_rec_t** big_rec,/* out: possible big rec vector of fields + which have to be stored externally by the + caller */ dtuple_t* entry, /* in: index entry to insert */ + ulint* ext_vec,/* in: array containing field numbers of + externally stored fields in entry, or NULL */ + ulint n_ext_vec,/* in: number of fields in ext_vec */ que_thr_t* thr, /* in: query thread */ mtr_t* mtr) /* in: mtr */ { @@ -243,8 +249,10 @@ row_ins_clust_index_entry_by_modify( upd_t* update; ulint err; - ut_ad((cursor->index)->type & DICT_CLUSTERED); + ut_ad(cursor->index->type & DICT_CLUSTERED); + *big_rec = NULL; + rec = btr_cur_get_rec(cursor); ut_ad(rec_get_deleted_flag(rec)); @@ -254,21 +262,21 @@ row_ins_clust_index_entry_by_modify( /* Build an update vector containing all the fields to be modified; NOTE that this vector may contain also system columns! */ - update = row_upd_build_difference(cursor->index, entry, rec, heap); - + update = row_upd_build_difference(cursor->index, entry, ext_vec, + n_ext_vec, rec, heap); if (mode == BTR_MODIFY_LEAF) { /* Try optimistic updating of the record, keeping changes within the page */ - err = btr_cur_optimistic_update(0, cursor, update, 0, thr, - mtr); - if ((err == DB_OVERFLOW) || (err == DB_UNDERFLOW)) { + err = btr_cur_optimistic_update(0, cursor, update, 0, thr, mtr); + + if (err == DB_OVERFLOW || err == DB_UNDERFLOW) { err = DB_FAIL; } } else { - ut_ad(mode == BTR_MODIFY_TREE); - err = btr_cur_pessimistic_update(0, cursor, update, 0, thr, - mtr); + ut_a(mode == BTR_MODIFY_TREE); + err = btr_cur_pessimistic_update(0, cursor, big_rec, update, + 0, thr, mtr); } mem_heap_free(heap); @@ -597,14 +605,18 @@ row_ins_index_entry_low( pessimistic descent down the index tree */ dict_index_t* index, /* in: index */ dtuple_t* entry, /* in: index entry to insert */ + ulint* ext_vec,/* in: array containing field numbers of + externally stored fields in entry, or NULL */ + ulint n_ext_vec,/* in: number of fields in ext_vec */ que_thr_t* thr) /* in: query thread */ { btr_cur_t cursor; ulint modify; - rec_t* dummy_rec; + rec_t* insert_rec; rec_t* rec; ulint err; ulint n_unique; + big_rec_t* big_rec = NULL; mtr_t mtr; log_free_check(); @@ -682,24 +694,54 @@ row_ins_index_entry_low( if (index->type & DICT_CLUSTERED) { err = row_ins_clust_index_entry_by_modify(mode, - &cursor, entry, - thr, &mtr); + &cursor, &big_rec, + entry, + ext_vec, n_ext_vec, + thr, &mtr); } else { err = row_ins_sec_index_entry_by_modify(&cursor, thr, &mtr); } - } else if (mode == BTR_MODIFY_LEAF) { - err = btr_cur_optimistic_insert(0, &cursor, entry, - &dummy_rec, thr, &mtr); } else { - ut_ad(mode == BTR_MODIFY_TREE); - err = btr_cur_pessimistic_insert(0, &cursor, entry, - &dummy_rec, thr, &mtr); + if (mode == BTR_MODIFY_LEAF) { + err = btr_cur_optimistic_insert(0, &cursor, entry, + &insert_rec, &big_rec, thr, &mtr); + } else { + ut_a(mode == BTR_MODIFY_TREE); + err = btr_cur_pessimistic_insert(0, &cursor, entry, + &insert_rec, &big_rec, thr, &mtr); + } + + if (err == DB_SUCCESS) { + if (ext_vec) { + rec_set_field_extern_bits(insert_rec, + ext_vec, n_ext_vec, &mtr); + } + } } + function_exit: mtr_commit(&mtr); + if (big_rec) { + mtr_start(&mtr); + + btr_cur_search_to_nth_level(index, 0, entry, PAGE_CUR_LE, + BTR_MODIFY_TREE, &cursor, 0, &mtr); + + err = btr_store_big_rec_extern_fields(index, + btr_cur_get_rec(&cursor), + big_rec, &mtr); + if (modify) { + dtuple_big_rec_free(big_rec); + } else { + dtuple_convert_back_big_rec(index, entry, big_rec); + } + + mtr_commit(&mtr); + } + return(err); } @@ -716,14 +758,17 @@ row_ins_index_entry( DB_DUPLICATE_KEY, or some other error code */ dict_index_t* index, /* in: index */ dtuple_t* entry, /* in: index entry to insert */ + ulint* ext_vec,/* in: array containing field numbers of + externally stored fields in entry, or NULL */ + ulint n_ext_vec,/* in: number of fields in ext_vec */ que_thr_t* thr) /* in: query thread */ { ulint err; /* Try first optimistic descent to the B-tree */ - err = row_ins_index_entry_low(BTR_MODIFY_LEAF, index, entry, thr); - + err = row_ins_index_entry_low(BTR_MODIFY_LEAF, index, entry, + ext_vec, n_ext_vec, thr); if (err != DB_FAIL) { return(err); @@ -731,8 +776,8 @@ row_ins_index_entry( /* Try then pessimistic descent to the B-tree */ - err = row_ins_index_entry_low(BTR_MODIFY_TREE, index, entry, thr); - + err = row_ins_index_entry_low(BTR_MODIFY_TREE, index, entry, + ext_vec, n_ext_vec, thr); return(err); } @@ -784,7 +829,7 @@ row_ins_index_entry_step( ut_ad(dtuple_check_typed(node->entry)); - err = row_ins_index_entry(node->index, node->entry, thr); + err = row_ins_index_entry(node->index, node->entry, NULL, 0, thr); return(err); } diff --git a/innobase/row/row0mysql.c b/innobase/row/row0mysql.c index 8e1a584f667..9bbc45a5c9a 100644 --- a/innobase/row/row0mysql.c +++ b/innobase/row/row0mysql.c @@ -625,7 +625,8 @@ row_update_for_mysql( ut_ad(prebuilt && trx); ut_ad(trx->mysql_thread_id == os_thread_get_curr_id()); - + UT_NOT_USED(mysql_rec); + node = prebuilt->upd_node; clust_index = dict_table_get_first_index(table); @@ -777,7 +778,9 @@ row_get_mysql_key_number_for_index( } /************************************************************************* -Does a table creation operation for MySQL. */ +Does a table creation operation for MySQL. If the name of the created +table ends to characters INNODB_MONITOR, then this also starts +printing of monitor output by the master thread. */ int row_create_table_for_mysql( @@ -789,6 +792,8 @@ row_create_table_for_mysql( tab_node_t* node; mem_heap_t* heap; que_thr_t* thr; + ulint namelen; + ulint keywordlen; ulint err; ut_ad(trx->mysql_thread_id == os_thread_get_curr_id()); @@ -833,6 +838,20 @@ row_create_table_for_mysql( } trx->error_state = DB_SUCCESS; + } else { + namelen = ut_strlen(table->name); + + keywordlen = ut_strlen("innodb_monitor"); + + if (namelen >= keywordlen + && 0 == ut_memcmp(table->name + namelen - keywordlen, + "innodb_monitor", keywordlen)) { + + /* Table name ends to characters innodb_monitor: + start monitor prints */ + + srv_print_innodb_monitor = TRUE; + } } mutex_exit(&(dict_sys->mutex)); @@ -900,7 +919,9 @@ row_create_index_for_mysql( } /************************************************************************* -Drops a table for MySQL. */ +Drops a table for MySQL. If the name of the dropped table ends to +characters INNODB_MONITOR, then this also stops printing of monitor +output by the master thread. */ int row_drop_table_for_mysql( @@ -918,11 +939,26 @@ row_drop_table_for_mysql( char* str1; char* str2; ulint len; + ulint namelen; + ulint keywordlen; char buf[10000]; ut_ad(trx->mysql_thread_id == os_thread_get_curr_id()); ut_a(name != NULL); + namelen = ut_strlen(name); + keywordlen = ut_strlen("innodb_monitor"); + + if (namelen >= keywordlen + && 0 == ut_memcmp(name + namelen - keywordlen, + "innodb_monitor", keywordlen)) { + + /* Table name ends to characters innodb_monitor: + stop monitor prints */ + + srv_print_innodb_monitor = FALSE; + } + /* We use the private SQL parser of Innobase to generate the query graphs needed in deleting the dictionary data from system tables in Innobase. Deleting a row from SYS_INDEXES table also diff --git a/innobase/row/row0purge.c b/innobase/row/row0purge.c index 0a6fabe584c..ec880d3fe04 100644 --- a/innobase/row/row0purge.c +++ b/innobase/row/row0purge.c @@ -347,20 +347,36 @@ row_purge_del_mark( } /*************************************************************** -Purges an update of an existing record. */ +Purges an update of an existing record. Also purges an update of a delete +marked record if that record contained an externally stored field. */ static void -row_purge_upd_exist( -/*================*/ +row_purge_upd_exist_or_extern( +/*==========================*/ purge_node_t* node, /* in: row purge node */ que_thr_t* thr) /* in: query thread */ { mem_heap_t* heap; dtuple_t* entry; dict_index_t* index; + upd_field_t* ufield; + ibool is_insert; + ulint rseg_id; + ulint page_no; + ulint offset; + ulint internal_offset; + byte* data_field; + ulint data_field_len; + ulint i; + mtr_t mtr; ut_ad(node && thr); + if (node->rec_type == TRX_UNDO_UPD_DEL_REC) { + + goto skip_secondaries; + } + heap = mem_heap_create(1024); while (node->index != NULL) { @@ -378,6 +394,53 @@ row_purge_upd_exist( } mem_heap_free(heap); + +skip_secondaries: + /* Free possible externally stored fields */ + for (i = 0; i < upd_get_n_fields(node->update); i++) { + + ufield = upd_get_nth_field(node->update, i); + + if (ufield->extern_storage) { + /* We use the fact that new_val points to + node->undo_rec and get thus the offset of + dfield data inside the unod record. Then we + can calculate from node->roll_ptr the file + address of the new_val data */ + + internal_offset = ((byte*)ufield->new_val.data) + - node->undo_rec; + + ut_a(internal_offset < UNIV_PAGE_SIZE); + + trx_undo_decode_roll_ptr(node->roll_ptr, + &is_insert, &rseg_id, + &page_no, &offset); + mtr_start(&mtr); + + /* We have to acquire an X-latch to the clustered + index tree */ + + index = dict_table_get_first_index(node->table); + + mtr_x_lock(dict_tree_get_lock(index->tree), &mtr); + + /* We assume in purge of externally stored fields + that the space id of the undo log record is 0! */ + + data_field = buf_page_get(0, page_no, RW_X_LATCH, &mtr) + + offset + internal_offset; + + buf_page_dbg_add_level(buf_frame_align(data_field), + SYNC_TRX_UNDO_PAGE); + + data_field_len = ufield->new_val.len; + + btr_free_externally_stored_field(index, data_field, + data_field_len, &mtr); + mtr_commit(&mtr); + } + } } /*************************************************************** @@ -388,6 +451,9 @@ row_purge_parse_undo_rec( /*=====================*/ /* out: TRUE if purge operation required */ purge_node_t* node, /* in: row undo node */ + ibool* updated_extern, + /* out: TRUE if an externally stored field + was updated */ que_thr_t* thr) /* in: query thread */ { dict_index_t* clust_index; @@ -403,10 +469,10 @@ row_purge_parse_undo_rec( ut_ad(node && thr); ptr = trx_undo_rec_get_pars(node->undo_rec, &type, &cmpl_info, - &undo_no, &table_id); + updated_extern, &undo_no, &table_id); node->rec_type = type; - if (type == TRX_UNDO_UPD_DEL_REC) { + if (type == TRX_UNDO_UPD_DEL_REC && !(*updated_extern)) { return(FALSE); } @@ -416,7 +482,7 @@ row_purge_parse_undo_rec( node->table = NULL; if (type == TRX_UNDO_UPD_EXIST_REC - && cmpl_info & UPD_NODE_NO_ORD_CHANGE) { + && cmpl_info & UPD_NODE_NO_ORD_CHANGE && !(*updated_extern)) { /* Purge requires no changes to indexes: we may return */ @@ -455,8 +521,11 @@ row_purge_parse_undo_rec( /* Read to the partial row the fields that occur in indexes */ - ptr = trx_undo_rec_get_partial_row(ptr, clust_index, &(node->row), - node->heap); + if (!cmpl_info & UPD_NODE_NO_ORD_CHANGE) { + ptr = trx_undo_rec_get_partial_row(ptr, clust_index, + &(node->row), node->heap); + } + return(TRUE); } @@ -475,6 +544,7 @@ row_purge( { dulint roll_ptr; ibool purge_needed; + ibool updated_extern; ut_ad(node && thr); @@ -494,7 +564,8 @@ row_purge( if (node->undo_rec == &trx_purge_dummy_rec) { purge_needed = FALSE; } else { - purge_needed = row_purge_parse_undo_rec(node, thr); + purge_needed = row_purge_parse_undo_rec(node, &updated_extern, + thr); } if (purge_needed) { @@ -503,11 +574,13 @@ row_purge( node->index = dict_table_get_next_index( dict_table_get_first_index(node->table)); - if (node->rec_type == TRX_UNDO_UPD_EXIST_REC) { - row_purge_upd_exist(node, thr); - } else { - ut_ad(node->rec_type == TRX_UNDO_DEL_MARK_REC); + if (node->rec_type == TRX_UNDO_DEL_MARK_REC) { row_purge_del_mark(node, thr); + + } else if (updated_extern + || node->rec_type == TRX_UNDO_UPD_EXIST_REC) { + + row_purge_upd_exist_or_extern(node, thr); } if (node->found_clust) { diff --git a/innobase/row/row0row.c b/innobase/row/row0row.c index f85789fa0d6..59169ef2a98 100644 --- a/innobase/row/row0row.c +++ b/innobase/row/row0row.c @@ -146,15 +146,17 @@ row_build_index_entry( /*********************************************************************** An inverse function to dict_row_build_index_entry. Builds a row from a -record in a clustered index. */ +record in a clustered index. NOTE that externally stored (often big) +fields are always copied to heap. */ dtuple_t* row_build( /*======*/ /* out, own: row built; see the NOTE below! */ - ulint type, /* in: ROW_COPY_DATA, or ROW_COPY_POINTERS: - the former copies also the data fields to - heap as the latter only places pointers to + ulint type, /* in: ROW_COPY_POINTERS, ROW_COPY_DATA, or + ROW_COPY_ALSO_EXTERNALS, + the two last copy also the data fields to + heap as the first only places pointers to data fields on the index page, and thus is more efficient */ dict_index_t* index, /* in: clustered index */ @@ -170,19 +172,19 @@ row_build( { dtuple_t* row; dict_table_t* table; - ulint n_fields; - ulint i; + dict_col_t* col; dfield_t* dfield; + ulint n_fields; byte* field; ulint len; ulint row_len; - dict_col_t* col; byte* buf; + ulint i; ut_ad(index && rec && heap); ut_ad(index->type & DICT_CLUSTERED); - if (type == ROW_COPY_DATA) { + if (type != ROW_COPY_POINTERS) { /* Take a copy of rec to heap */ buf = mem_heap_alloc(heap, rec_get_size(rec)); rec = rec_copy(buf, rec); @@ -207,6 +209,13 @@ row_build( dfield = dtuple_get_nth_field(row, dict_col_get_no(col)); field = rec_get_nth_field(rec, i, &len); + if (type == ROW_COPY_ALSO_EXTERNALS + && rec_get_nth_field_extern_bit(rec, i)) { + + field = btr_rec_copy_externally_stored_field(rec, + i, &len, heap); + } + dfield_set_data(dfield, field, len); } @@ -215,6 +224,7 @@ row_build( return(row); } +#ifdef notdefined /*********************************************************************** An inverse function to dict_row_build_index_entry. Builds a row from a record in a clustered index. */ @@ -229,7 +239,9 @@ row_build_to_tuple( directly into this record, therefore, the buffer page of this record must be at least s-latched and the latch held - as long as the row dtuple is used! */ + as long as the row dtuple is used! + NOTE 2: does not work with externally + stored fields! */ { dict_table_t* table; ulint n_fields; @@ -265,9 +277,11 @@ row_build_to_tuple( ut_ad(dtuple_check_typed(row)); } +#endif /*********************************************************************** -Converts an index record to a typed data tuple. */ +Converts an index record to a typed data tuple. NOTE that externally +stored (often big) fields are NOT copied to heap. */ dtuple_t* row_rec_to_index_entry( diff --git a/innobase/row/row0sel.c b/innobase/row/row0sel.c index 5a77fc5daaa..b74bd29a89e 100644 --- a/innobase/row/row0sel.c +++ b/innobase/row/row0sel.c @@ -2036,7 +2036,8 @@ row_sel_store_mysql_rec( which was described in prebuilt's template */ { - mysql_row_templ_t* templ; + mysql_row_templ_t* templ; + mem_heap_t* extern_field_heap = NULL; byte* data; ulint len; byte* blob_buf; @@ -2059,6 +2060,24 @@ row_sel_store_mysql_rec( data = rec_get_nth_field(rec, templ->rec_field_no, &len); + if (rec_get_nth_field_extern_bit(rec, templ->rec_field_no)) { + /* Copy an externally stored field to the temporary + heap */ + + if (prebuilt->trx->has_search_latch) { + rw_lock_s_unlock(&btr_search_latch); + prebuilt->trx->has_search_latch = FALSE; + } + + extern_field_heap = mem_heap_create(UNIV_PAGE_SIZE); + + data = btr_rec_copy_externally_stored_field(rec, + templ->rec_field_no, &len, + extern_field_heap); + + ut_a(len != UNIV_SQL_NULL); + } + if (len != UNIV_SQL_NULL) { if (templ->type == DATA_BLOB) { @@ -2081,6 +2100,10 @@ row_sel_store_mysql_rec( mysql_rec + templ->mysql_col_offset, templ->mysql_col_len, data, len, templ->type, templ->is_unsigned); + + if (extern_field_heap) { + mem_heap_free(extern_field_heap); + } } else { mysql_rec[templ->mysql_null_byte_offset] |= (byte) (templ->mysql_null_bit_mask); @@ -2450,6 +2473,7 @@ row_search_for_mysql( ibool unique_search_from_clust_index = FALSE; ibool mtr_has_extra_clust_latch = FALSE; ibool moves_up = FALSE; + ulint cnt = 0; mtr_t mtr; ut_ad(index && pcur && search_tuple); @@ -2457,6 +2481,11 @@ row_search_for_mysql( ut_ad(sync_thread_levels_empty_gen(FALSE)); +/* printf("Match mode %lu\n search tuple ", match_mode); + dtuple_print(search_tuple); + + printf("N tables locked %lu\n", trx->mysql_n_tables_locked); +*/ if (direction == 0) { prebuilt->n_rows_fetched = 0; prebuilt->n_fetch_cached = 0; @@ -2528,6 +2557,8 @@ row_search_for_mysql( mtr_commit(&mtr); + /* printf("%s record not found 1\n", index->name); */ + return(DB_RECORD_NOT_FOUND); } @@ -2565,17 +2596,18 @@ row_search_for_mysql( mtr_commit(&mtr); + /* printf("%s shortcut\n", index->name); */ + return(DB_SUCCESS); } else if (shortcut == SEL_EXHAUSTED) { mtr_commit(&mtr); + /* printf("%s record not found 2\n", + index->name); */ return(DB_RECORD_NOT_FOUND); } - - /* Commit the mini-transaction since it can - hold latches */ mtr_commit(&mtr); mtr_start(&mtr); @@ -2659,7 +2691,12 @@ rec_loop: cons_read_requires_clust_rec = FALSE; rec = btr_pcur_get_rec(pcur); - +/* + printf("Using index %s cnt %lu ", index->name, cnt); + printf("; Page no %lu\n", + buf_frame_get_page_no(buf_frame_align(rec))); + rec_print(rec); +*/ if (rec == page_get_infimum_rec(buf_frame_align(rec))) { /* The infimum record on a page cannot be in the result set, @@ -2700,12 +2737,15 @@ rec_loop: /* Test if the index record matches completely to search_tuple in prebuilt: if not, then we return with DB_RECORD_NOT_FOUND */ + /* printf("Comparing rec and search tuple\n"); */ + if (0 != cmp_dtuple_rec(search_tuple, rec)) { btr_pcur_store_position(pcur, &mtr); ret = DB_RECORD_NOT_FOUND; - + /* printf("%s record not found 3\n", index->name); */ + goto normal_return; } @@ -2716,6 +2756,7 @@ rec_loop: btr_pcur_store_position(pcur, &mtr); ret = DB_RECORD_NOT_FOUND; + /* printf("%s record not found 4\n", index->name); */ goto normal_return; } @@ -2884,6 +2925,8 @@ next_rec: moved = sel_restore_position_for_mysql(BTR_SEARCH_LEAF, pcur, moves_up, &mtr); if (moved) { + cnt++; + goto rec_loop; } } @@ -2906,6 +2949,8 @@ next_rec: goto normal_return; } + cnt++; + goto rec_loop; /*-------------------------------------------------------------*/ lock_wait_or_error: @@ -2931,7 +2976,9 @@ lock_wait_or_error: goto rec_loop; } - + + /* printf("Using index %s cnt %lu ret value %lu err\n", index->name, + cnt, err); */ return(err); normal_return: @@ -2945,5 +2992,7 @@ normal_return: ret = DB_SUCCESS; } + /* printf("Using index %s cnt %lu ret value %lu\n", index->name, + cnt, err); */ return(ret); } diff --git a/innobase/row/row0uins.c b/innobase/row/row0uins.c index c9330318ac0..47807877779 100644 --- a/innobase/row/row0uins.c +++ b/innobase/row/row0uins.c @@ -242,11 +242,12 @@ row_undo_ins_parse_undo_rec( dulint table_id; ulint type; ulint dummy; + ibool dummy_extern; ut_ad(node && thr); - ptr = trx_undo_rec_get_pars(node->undo_rec, &type, &dummy, &undo_no, - &table_id); + ptr = trx_undo_rec_get_pars(node->undo_rec, &type, &dummy, + &dummy_extern, &undo_no, &table_id); ut_ad(type == TRX_UNDO_INSERT_REC); node->rec_type = type; @@ -284,9 +285,9 @@ row_undo_ins( row_undo_ins_parse_undo_rec(node, thr); if (node->table == NULL) { - found = FALSE; + found = FALSE; } else { - found = row_undo_search_clust_to_pcur(node, thr); + found = row_undo_search_clust_to_pcur(node, thr); } if (!found) { diff --git a/innobase/row/row0umod.c b/innobase/row/row0umod.c index c8db428bade..0221c51b985 100644 --- a/innobase/row/row0umod.c +++ b/innobase/row/row0umod.c @@ -94,12 +94,12 @@ row_undo_mod_clust_low( mtr_t* mtr, /* in: mtr */ ulint mode) /* in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE */ { + big_rec_t* dummy_big_rec; dict_index_t* index; btr_pcur_t* pcur; btr_cur_t* btr_cur; ulint err; ibool success; - ibool do_remove; index = dict_table_get_first_index(node->table); @@ -110,49 +110,80 @@ row_undo_mod_clust_low( ut_ad(success); + if (mode == BTR_MODIFY_LEAF) { + + err = btr_cur_optimistic_update(BTR_NO_LOCKING_FLAG + | BTR_NO_UNDO_LOG_FLAG + | BTR_KEEP_SYS_FLAG, + btr_cur, node->update, + node->cmpl_info, thr, mtr); + } else { + ut_ad(mode == BTR_MODIFY_TREE); + + err = btr_cur_pessimistic_update(BTR_NO_LOCKING_FLAG + | BTR_NO_UNDO_LOG_FLAG + | BTR_KEEP_SYS_FLAG, + btr_cur, &dummy_big_rec, node->update, + node->cmpl_info, thr, mtr); + } + + return(err); +} + +/*************************************************************** +Removes a clustered index record after undo if possible. */ +static +ulint +row_undo_mod_remove_clust_low( +/*==========================*/ + /* out: DB_SUCCESS, DB_FAIL, or error code: + we may run out of file space */ + undo_node_t* node, /* in: row undo node */ + que_thr_t* thr, /* in: query thread */ + mtr_t* mtr, /* in: mtr */ + ulint mode) /* in: BTR_MODIFY_LEAF or BTR_MODIFY_TREE */ +{ + btr_pcur_t* pcur; + btr_cur_t* btr_cur; + ulint err; + ibool success; + + pcur = &(node->pcur); + btr_cur = btr_pcur_get_btr_cur(pcur); + + success = btr_pcur_restore_position(mode, pcur, mtr); + + if (!success) { + + return(DB_SUCCESS); + } + /* Find out if we can remove the whole clustered index record */ if (node->rec_type == TRX_UNDO_UPD_DEL_REC && !row_vers_must_preserve_del_marked(node->new_trx_id, mtr)) { - do_remove = TRUE; + /* Ok, we can remove */ } else { - do_remove = FALSE; + return(DB_SUCCESS); } if (mode == BTR_MODIFY_LEAF) { + success = btr_cur_optimistic_delete(btr_cur, mtr); - if (do_remove) { - success = btr_cur_optimistic_delete(btr_cur, mtr); - - if (success) { - err = DB_SUCCESS; - } else { - err = DB_FAIL; - } + if (success) { + err = DB_SUCCESS; } else { - err = btr_cur_optimistic_update(BTR_NO_LOCKING_FLAG - | BTR_NO_UNDO_LOG_FLAG - | BTR_KEEP_SYS_FLAG, - btr_cur, node->update, - node->cmpl_info, thr, mtr); + err = DB_FAIL; } } else { ut_ad(mode == BTR_MODIFY_TREE); - if (do_remove) { - btr_cur_pessimistic_delete(&err, FALSE, btr_cur, mtr); + btr_cur_pessimistic_delete(&err, FALSE, btr_cur, mtr); - /* The delete operation may fail if we have little - file space left: TODO: easiest to crash the database - and restart with more file space */ - } else { - err = btr_cur_pessimistic_update(BTR_NO_LOCKING_FLAG - | BTR_NO_UNDO_LOG_FLAG - | BTR_KEEP_SYS_FLAG, - btr_cur, node->update, - node->cmpl_info, thr, mtr); - } + /* The delete operation may fail if we have little + file space left: TODO: easiest to crash the database + and restart with more file space */ } return(err); @@ -204,10 +235,31 @@ row_undo_mod_clust( err = row_undo_mod_clust_low(node, thr, &mtr, BTR_MODIFY_TREE); } - node->state = UNDO_NODE_FETCH_NEXT; - btr_pcur_commit_specify_mtr(pcur, &mtr); + if (err == DB_SUCCESS && node->rec_type == TRX_UNDO_UPD_DEL_REC) { + + mtr_start(&mtr); + + err = row_undo_mod_remove_clust_low(node, thr, &mtr, + BTR_MODIFY_LEAF); + if (err != DB_SUCCESS) { + btr_pcur_commit_specify_mtr(pcur, &mtr); + + /* We may have to modify tree structure: do a + pessimistic descent down the index tree */ + + mtr_start(&mtr); + + err = row_undo_mod_remove_clust_low(node, thr, &mtr, + BTR_MODIFY_TREE); + } + + btr_pcur_commit_specify_mtr(pcur, &mtr); + } + + node->state = UNDO_NODE_FETCH_NEXT; + trx_undo_rec_release(node->trx, node->undo_no); if (more_vers && err == DB_SUCCESS) { @@ -388,7 +440,6 @@ row_undo_mod_del_unmark_sec( mem_free(err_buf); } else { - btr_cur = btr_pcur_get_btr_cur(&pcur); err = btr_cur_del_mark_set_sec_rec(BTR_NO_LOCKING_FLAG, @@ -546,11 +597,12 @@ row_undo_mod_parse_undo_rec( ulint info_bits; ulint type; ulint cmpl_info; + ibool dummy_extern; ut_ad(node && thr); ptr = trx_undo_rec_get_pars(node->undo_rec, &type, &cmpl_info, - &undo_no, &table_id); + &dummy_extern, &undo_no, &table_id); node->rec_type = type; node->table = dict_table_get_on_id(table_id, thr_get_trx(thr)); @@ -598,10 +650,9 @@ row_undo_mod( row_undo_mod_parse_undo_rec(node, thr); if (node->table == NULL) { - found = FALSE; + found = FALSE; } else { - - found = row_undo_search_clust_to_pcur(node, thr); + found = row_undo_search_clust_to_pcur(node, thr); } if (!found) { diff --git a/innobase/row/row0undo.c b/innobase/row/row0undo.c index 10ac3af6de9..5119254f405 100644 --- a/innobase/row/row0undo.c +++ b/innobase/row/row0undo.c @@ -124,6 +124,8 @@ row_undo_node_create( undo->state = UNDO_NODE_FETCH_NEXT; undo->trx = trx; + btr_pcur_init(&(undo->pcur)); + undo->heap = mem_heap_create(256); return(undo); @@ -303,6 +305,16 @@ row_undo_step( if (err != DB_SUCCESS) { /* SQL error detected */ + fprintf(stderr, "InnoDB: Fatal error %lu in rollback.\n", err); + + if (err == DB_OUT_OF_FILE_SPACE) { + fprintf(stderr, + "InnoDB: Error 13 means out of tablespace.\n" + "InnoDB: Consider increasing your tablespace.\n"); + + exit(1); + } + ut_a(0); return(NULL); diff --git a/innobase/row/row0upd.c b/innobase/row/row0upd.c index 5bca2a24c01..d339474df61 100644 --- a/innobase/row/row0upd.c +++ b/innobase/row/row0upd.c @@ -90,8 +90,10 @@ upd_node_create( node->in_mysql_interface = FALSE; node->row = NULL; + node->ext_vec = NULL; node->index = NULL; - + node->update = NULL; + node->select = NULL; node->heap = mem_heap_create(128); @@ -160,7 +162,8 @@ row_upd_index_entry_sys_field( } /*************************************************************** -Returns TRUE if row update changes size of some field in index. */ +Returns TRUE if row update changes size of some field in index +or if some field to be updated is stored externally in rec or update. */ ibool row_upd_changes_field_size( @@ -199,6 +202,16 @@ row_upd_changes_field_size( return(TRUE); } + + if (rec_get_nth_field_extern_bit(rec, upd_field->field_no)) { + + return(TRUE); + } + + if (upd_field->extern_storage) { + + return(TRUE); + } } return(FALSE); @@ -441,6 +454,34 @@ row_upd_index_parse( return(ptr); } + +/******************************************************************* +Returns TRUE if ext_vec contains i. */ +UNIV_INLINE +ibool +upd_ext_vec_contains( +/*=================*/ + /* out: TRUE if i is in ext_vec */ + ulint* ext_vec, /* in: array of indexes or NULL */ + ulint n_ext_vec, /* in: number of numbers in ext_vec */ + ulint i) /* in: a number */ +{ + ulint j; + + if (ext_vec == NULL) { + + return(FALSE); + } + + for (j = 0; j < n_ext_vec; j++) { + if (ext_vec[j] == i) { + + return(TRUE); + } + } + + return(FALSE); +} /******************************************************************* Builds an update vector from those fields, excluding the roll ptr and @@ -454,6 +495,9 @@ row_upd_build_difference( fields, excluding roll ptr and trx id */ dict_index_t* index, /* in: clustered index */ dtuple_t* entry, /* in: entry to insert */ + ulint* ext_vec,/* in: array containing field numbers of + externally stored fields in entry, or NULL */ + ulint n_ext_vec,/* in: number of fields in ext_vec */ rec_t* rec, /* in: clustered index record */ mem_heap_t* heap) /* in: memory heap from which allocated */ { @@ -480,16 +524,25 @@ row_upd_build_difference( for (i = 0; i < dtuple_get_n_fields(entry); i++) { data = rec_get_nth_field(rec, i, &len); + dfield = dtuple_get_nth_field(entry, i); - if ((i != trx_id_pos) && (i != roll_ptr_pos) - && !dfield_data_is_equal(dfield, len, data)) { + if ((rec_get_nth_field_extern_bit(rec, i) + != upd_ext_vec_contains(ext_vec, n_ext_vec, i)) + || ((i != trx_id_pos) && (i != roll_ptr_pos) + && !dfield_data_is_equal(dfield, len, data))) { upd_field = upd_get_nth_field(update, n_diff); dfield_copy(&(upd_field->new_val), dfield); upd_field_set_field_no(upd_field, i, index); + + if (upd_ext_vec_contains(ext_vec, n_ext_vec, i)) { + upd_field->extern_storage = TRUE; + } else { + upd_field->extern_storage = FALSE; + } n_diff++; } @@ -630,9 +683,7 @@ row_upd_changes_ord_field( } /*************************************************************** -Checks if an update vector changes an ordering field of an index record. -This function is fast if the update vector is short or the number of ordering -fields in the index is small. Otherwise, this can be quadratic. */ +Checks if an update vector changes an ordering field of an index record. */ ibool row_upd_changes_some_index_ord_field( @@ -642,19 +693,24 @@ row_upd_changes_some_index_ord_field( dict_table_t* table, /* in: table */ upd_t* update) /* in: update vector for the row */ { + upd_field_t* upd_field; dict_index_t* index; - + ulint i; + index = dict_table_get_first_index(table); - while (index) { - if (row_upd_changes_ord_field(NULL, index, update)) { + for (i = 0; i < upd_get_n_fields(update); i++) { - return(TRUE); + upd_field = upd_get_nth_field(update, i); + + if (dict_field_get_col(dict_index_get_nth_field(index, + upd_field->field_no)) + ->ord_part) { + + return(TRUE); } - - index = dict_table_get_next_index(index); - } - + } + return(FALSE); } @@ -710,15 +766,17 @@ row_upd_eval_new_vals( /*************************************************************** Stores to the heap the row on which the node->pcur is positioned. */ -UNIV_INLINE +static void row_upd_store_row( /*==============*/ upd_node_t* node) /* in: row update node */ { dict_index_t* clust_index; + upd_t* update; + rec_t* rec; - ut_ad((node->pcur)->latch_mode != BTR_NO_LATCHES); + ut_ad(node->pcur->latch_mode != BTR_NO_LATCHES); if (node->row != NULL) { mem_heap_empty(node->heap); @@ -727,8 +785,20 @@ row_upd_store_row( clust_index = dict_table_get_first_index(node->table); - node->row = row_build(ROW_COPY_DATA, clust_index, - btr_pcur_get_rec(node->pcur), node->heap); + rec = btr_pcur_get_rec(node->pcur); + + node->row = row_build(ROW_COPY_DATA, clust_index, rec, node->heap); + + node->ext_vec = mem_heap_alloc(node->heap, rec_get_n_fields(rec)); + + if (node->is_delete) { + update = NULL; + } else { + update = node->update; + } + + node->n_ext_vec = btr_push_update_extern_fields(node->ext_vec, + rec, update); } /*************************************************************** @@ -812,7 +882,7 @@ row_upd_sec_index_entry( row_upd_index_replace_new_col_vals(entry, index, node->update); /* Insert new index entry */ - err = row_ins_index_entry(index, entry, thr); + err = row_ins_index_entry(index, entry, NULL, 0, thr); mem_heap_free(heap); @@ -870,6 +940,8 @@ row_upd_clust_rec_by_insert( dict_table_t* table; mem_heap_t* heap; dtuple_t* entry; + ulint* ext_vec; + ulint n_ext_vec; ulint err; ut_ad(node); @@ -897,14 +969,18 @@ row_upd_clust_rec_by_insert( heap = mem_heap_create(1024); + ext_vec = mem_heap_alloc(heap, + sizeof(ulint) * dtuple_get_n_fields(node->row)); + n_ext_vec = 0; + entry = row_build_index_entry(node->row, index, heap); row_upd_clust_index_replace_new_col_vals(entry, node->update); - + row_upd_index_entry_sys_field(entry, index, DATA_TRX_ID, trx->id); - err = row_ins_index_entry(index, entry, thr); - + err = row_ins_index_entry(index, entry, node->ext_vec, + node->n_ext_vec, thr); mem_heap_free(heap); return(err); @@ -924,6 +1000,7 @@ row_upd_clust_rec( que_thr_t* thr, /* in: query thread */ mtr_t* mtr) /* in: mtr; gets committed here */ { + big_rec_t* big_rec = NULL; btr_pcur_t* pcur; btr_cur_t* btr_cur; ulint err; @@ -973,9 +1050,24 @@ row_upd_clust_rec( ut_ad(FALSE == rec_get_deleted_flag(btr_pcur_get_rec(pcur))); err = btr_cur_pessimistic_update(BTR_NO_LOCKING_FLAG, btr_cur, - node->update, node->cmpl_info, thr, mtr); + &big_rec, node->update, + node->cmpl_info, thr, mtr); mtr_commit(mtr); + if (err == DB_SUCCESS && big_rec) { + mtr_start(mtr); + ut_a(btr_pcur_restore_position(BTR_MODIFY_TREE, pcur, mtr)); + + err = btr_store_big_rec_extern_fields(index, + btr_cur_get_rec(btr_cur), + big_rec, mtr); + mtr_commit(mtr); + } + + if (big_rec) { + dtuple_big_rec_free(big_rec); + } + return(err); } @@ -1194,10 +1286,12 @@ row_upd( ut_ad(node && thr); if (node->in_mysql_interface) { + /* We do not get the cmpl_info value from the MySQL interpreter: we must calculate it on the fly: */ - if (row_upd_changes_some_index_ord_field(node->table, + if (node->is_delete || + row_upd_changes_some_index_ord_field(node->table, node->update)) { node->cmpl_info = 0; } else { @@ -1239,6 +1333,7 @@ function_exit: if (node->row != NULL) { mem_heap_empty(node->heap); node->row = NULL; + node->n_ext_vec = 0; } node->state = UPD_NODE_UPDATE_CLUSTERED; diff --git a/innobase/srv/srv0srv.c b/innobase/srv/srv0srv.c index 028fae010d5..8dd9c9f3feb 100644 --- a/innobase/srv/srv0srv.c +++ b/innobase/srv/srv0srv.c @@ -93,6 +93,8 @@ ulint srv_lock_wait_timeout = 1024 * 1024 * 1024; char* srv_unix_file_flush_method_str = NULL; ulint srv_unix_file_flush_method = 0; +ibool srv_use_doublewrite_buf = TRUE; + ibool srv_set_thread_priorities = TRUE; int srv_query_thread_priority = 0; /*-------------------------------------------*/ @@ -109,6 +111,8 @@ ibool srv_print_buf_io = FALSE; ibool srv_print_log_io = FALSE; ibool srv_print_latch_waits = FALSE; +ibool srv_print_innodb_monitor = FALSE; + /* The parameters below are obsolete: */ ibool srv_print_parsed_sql = FALSE; @@ -1492,7 +1496,6 @@ srv_init(void) slot = srv_mysql_table + i; slot->in_use = FALSE; slot->event = os_event_create(NULL); - slot->suspended = FALSE; ut_a(slot->event); } @@ -1661,7 +1664,6 @@ srv_suspend_mysql_thread( slot->thr = thr; os_event_reset(event); - slot->suspended = TRUE; slot->suspend_time = ut_time(); @@ -1693,27 +1695,6 @@ srv_suspend_mysql_thread( return(FALSE); } -os_event_t -srv_mysql_thread_event_get(void) -{ - srv_slot_t* slot; - os_event_t event; - - mutex_enter(&kernel_mutex); - - slot = srv_table_reserve_slot_for_mysql(); - - event = slot->event; - - os_event_reset(event); - - slot->suspended = TRUE; - - mutex_exit(&kernel_mutex); - - return(event); -} - /************************************************************************ Releases a MySQL OS thread waiting for a lock to be released, if the thread is already suspended. */ @@ -1737,7 +1718,6 @@ srv_release_mysql_thread_if_suspended( /* Found */ os_event_set(slot->event); - slot->suspended = FALSE; return; } @@ -1746,59 +1726,6 @@ srv_release_mysql_thread_if_suspended( /* not found */ } -void -srv_mysql_thread_release(void) -/*==========================*/ -{ - srv_slot_t* slot; - ulint i; - - mutex_enter(&kernel_mutex); - - for (i = 0; i < OS_THREAD_MAX_N; i++) { - - slot = srv_mysql_table + i; - - if (slot->in_use && slot->suspended) { - /* Found */ - slot->suspended = FALSE; - mutex_exit(&kernel_mutex); - - os_event_set(slot->event); - - return; - } - } - - ut_a(0); -} - -void -srv_mysql_thread_slot_free( -/*==========================*/ - os_event_t event) -{ - srv_slot_t* slot; - ulint i; - - mutex_enter(&kernel_mutex); - - for (i = 0; i < OS_THREAD_MAX_N; i++) { - - slot = srv_mysql_table + i; - - if (slot->in_use && slot->event == event) { - /* Found */ - slot->in_use = FALSE; - mutex_exit(&kernel_mutex); - - return; - } - } - - ut_a(0); -} - /************************************************************************* A thread which wakes up threads whose lock wait may have lasted too long. */ @@ -1924,6 +1851,7 @@ srv_master_thread( ulint i; time_t last_flush_time; time_t current_time; + time_t last_monitor_time; UT_NOT_USED(arg); @@ -1936,6 +1864,8 @@ srv_master_thread( mutex_exit(&kernel_mutex); os_event_set(srv_sys->operational); + + last_monitor_time = time(NULL); loop: mutex_enter(&kernel_mutex); @@ -1975,8 +1905,18 @@ loop: while (n_pages_purged) { /* TODO: replace this by a check if we are running out of file space! */ + if (srv_print_innodb_monitor) { + ut_print_timestamp(stdout); + printf(" InnoDB starts purge\n"); + } + n_pages_purged = trx_purge(); + if (srv_print_innodb_monitor) { + ut_print_timestamp(stdout); + printf(" InnoDB purged %lu pages\n", n_pages_purged); + } + current_time = time(NULL); if (difftime(current_time, last_flush_time) > 1) { @@ -1986,14 +1926,40 @@ loop: } background_loop: - /* - sync_array_print_info(sync_primary_wait_array); - os_aio_print(); - buf_print_io(); - */ /* In this loop we run background operations while the server is quiet */ + current_time = time(NULL); + + if (srv_print_innodb_monitor + && difftime(current_time, last_monitor_time) > 8) { + + printf("================================\n"); + last_monitor_time = time(NULL); + ut_print_timestamp(stdout); + + printf(" INNODB MONITOR OUTPUT\n" + "================================\n"); + printf("--------------------------\n" + "LOCKS HELD BY TRANSACTIONS\n" + "--------------------------\n"); + lock_print_info(); + printf("-----------------------------------------------\n" + "CURRENT SEMAPHORES RESERVED AND SEMAPHORE WAITS\n" + "-----------------------------------------------\n"); + sync_print(); + printf("CURRENT PENDING FILE I/O'S\n" + "--------------------------\n"); + os_aio_print(); + printf("-----------\n" + "BUFFER POOL\n" + "-----------\n"); + buf_print_io(); + printf("----------------------------\n" + "END OF INNODB MONITOR OUTPUT\n" + "============================\n"); + } + mutex_enter(&kernel_mutex); if (srv_activity_count != old_activity_count) { mutex_exit(&kernel_mutex); @@ -2005,8 +1971,18 @@ background_loop: /* The server has been quiet for a while: start running background operations */ + if (srv_print_innodb_monitor) { + ut_print_timestamp(stdout); + printf(" InnoDB starts purge\n"); + } + n_pages_purged = trx_purge(); + if (srv_print_innodb_monitor) { + ut_print_timestamp(stdout); + printf(" InnoDB purged %lu pages\n", n_pages_purged); + } + mutex_enter(&kernel_mutex); if (srv_activity_count != old_activity_count) { mutex_exit(&kernel_mutex); @@ -2014,8 +1990,18 @@ background_loop: } mutex_exit(&kernel_mutex); + if (srv_print_innodb_monitor) { + ut_print_timestamp(stdout); + printf(" InnoDB starts insert buffer merge\n"); + } + n_bytes_merged = ibuf_contract(TRUE); + if (srv_print_innodb_monitor) { + ut_print_timestamp(stdout); + printf(" InnoDB merged %lu bytes\n", n_bytes_merged); + } + mutex_enter(&kernel_mutex); if (srv_activity_count != old_activity_count) { mutex_exit(&kernel_mutex); @@ -2023,7 +2009,7 @@ background_loop: } mutex_exit(&kernel_mutex); - n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 20, ut_dulint_max); + n_pages_flushed = buf_flush_batch(BUF_FLUSH_LIST, 100, ut_dulint_max); mutex_enter(&kernel_mutex); if (srv_activity_count != old_activity_count) { @@ -2052,14 +2038,12 @@ background_loop: /* mem_print_new_info(); */ - -/* fsp_print(0); */ - -/* fprintf(stderr, "Validating tablespace\n"); +/* + fsp_print(0); + fprintf(stderr, "Validating tablespace\n"); fsp_validate(0); fprintf(stderr, "Validation ok\n"); */ - #ifdef UNIV_SEARCH_PERF_STAT /* btr_search_print_info(); */ #endif diff --git a/innobase/srv/srv0start.c b/innobase/srv/srv0start.c index a343f2115e7..a79a808ba2e 100644 --- a/innobase/srv/srv0start.c +++ b/innobase/srv/srv0start.c @@ -1,7 +1,7 @@ /************************************************************************ Starts the InnoDB database server -(c) 1996-2000 InnoDB Oy +(c) 1996-2000 Innobase Oy Created 2/16/1996 Heikki Tuuri *************************************************************************/ @@ -203,8 +203,8 @@ open_or_create_log_file( sprintf(name, "%s%s%lu", srv_log_group_home_dirs[k], "ib_logfile", i); - files[i] = os_file_create(name, OS_FILE_CREATE, OS_FILE_NORMAL, &ret); - + files[i] = os_file_create(name, OS_FILE_CREATE, OS_FILE_NORMAL, + OS_LOG_FILE, &ret); if (ret == FALSE) { if (os_file_get_last_error() != OS_FILE_ALREADY_EXISTS) { fprintf(stderr, @@ -214,7 +214,8 @@ open_or_create_log_file( } files[i] = os_file_create( - name, OS_FILE_OPEN, OS_FILE_AIO, &ret); + name, OS_FILE_OPEN, OS_FILE_AIO, + OS_LOG_FILE, &ret); if (!ret) { fprintf(stderr, "InnoDB: Error in opening %s\n", name); @@ -239,7 +240,7 @@ open_or_create_log_file( fprintf(stderr, "InnoDB: Log file %s did not exist: new to be created\n", name); - printf("InnoDB: Setting log file %s size to %lu\n", + fprintf(stderr, "InnoDB: Setting log file %s size to %lu\n", name, UNIV_PAGE_SIZE * srv_log_file_size); ret = os_file_set_size(name, files[i], @@ -330,27 +331,28 @@ open_or_create_data_files( sprintf(name, "%s%s", srv_data_home, srv_data_file_names[i]); - if (srv_data_file_is_raw_partition[i] == 0) { + files[i] = os_file_create(name, OS_FILE_CREATE, + OS_FILE_NORMAL, OS_DATA_FILE, &ret); - files[i] = os_file_create(name, OS_FILE_CREATE, - OS_FILE_NORMAL, &ret); - } else if (srv_data_file_is_raw_partition[i] == SRV_OLD_RAW) { - ret = FALSE; - } else if (srv_data_file_is_raw_partition[i] == SRV_NEW_RAW) { + if (srv_data_file_is_raw_partition[i] == SRV_NEW_RAW) { + /* The partition is opened, not created; then it is + written over */ - files[i] = os_file_create( - name, OS_FILE_OPEN, OS_FILE_NORMAL, &ret); - - if (!ret) { + files[i] = os_file_create( + name, OS_FILE_OPEN, OS_FILE_NORMAL, + OS_DATA_FILE, &ret); + if (!ret) { fprintf(stderr, "InnoDB: Error in opening %s\n", name); return(DB_ERROR); - } + } + } else if (srv_data_file_is_raw_partition[i] == SRV_OLD_RAW) { + ret = FALSE; } if (ret == FALSE) { - if (srv_data_file_is_raw_partition[i] == 0 + if (srv_data_file_is_raw_partition[i] != SRV_OLD_RAW && os_file_get_last_error() != OS_FILE_ALREADY_EXISTS) { fprintf(stderr, @@ -370,8 +372,8 @@ open_or_create_data_files( } files[i] = os_file_create( - name, OS_FILE_OPEN, OS_FILE_NORMAL, &ret); - + name, OS_FILE_OPEN, OS_FILE_NORMAL, + OS_DATA_FILE, &ret); if (!ret) { fprintf(stderr, "InnoDB: Error in opening %s\n", name); @@ -379,18 +381,21 @@ open_or_create_data_files( return(DB_ERROR); } - ret = os_file_get_size(files[i], &size, &size_high); - ut_a(ret); + if (srv_data_file_is_raw_partition[i] != SRV_OLD_RAW) { + + ret = os_file_get_size(files[i], &size, + &size_high); + ut_a(ret); - if (srv_data_file_is_raw_partition[i] == 0 - && (size != UNIV_PAGE_SIZE * srv_data_file_sizes[i] - || size_high != 0)) { - - fprintf(stderr, + if (size != + UNIV_PAGE_SIZE * srv_data_file_sizes[i] + || size_high != 0) { + fprintf(stderr, "InnoDB: Error: data file %s is of different size\n" "InnoDB: than specified in the .cnf file!\n", name); - return(DB_ERROR); + return(DB_ERROR); + } } fil_read_flushed_lsn_and_arch_log_no(files[i], @@ -403,7 +408,8 @@ open_or_create_data_files( if (i > 0) { fprintf(stderr, - "InnoDB: Data file %s did not exist: new to be created\n", name); + "InnoDB: Data file %s did not exist: new to be created\n", + name); } else { fprintf(stderr, "InnoDB: The first specified data file %s did not exist:\n" @@ -411,10 +417,10 @@ open_or_create_data_files( *create_new_db = TRUE; } - printf("InnoDB: Setting file %s size to %lu\n", + fprintf(stderr, "InnoDB: Setting file %s size to %lu\n", name, UNIV_PAGE_SIZE * srv_data_file_sizes[i]); - printf( + fprintf(stderr, "InnoDB: Database physically writes the file full: wait...\n"); ret = os_file_set_size(name, files[i], @@ -555,19 +561,22 @@ innobase_start_or_create_for_mysql(void) srv_startup_is_before_trx_rollback_phase = TRUE; if (0 == ut_strcmp(srv_unix_file_flush_method_str, "fdatasync")) { - srv_unix_file_flush_method = SRV_UNIX_FDATASYNC; + srv_unix_file_flush_method = SRV_UNIX_FDATASYNC; + } else if (0 == ut_strcmp(srv_unix_file_flush_method_str, "O_DSYNC")) { - srv_unix_file_flush_method = SRV_UNIX_O_DSYNC; + srv_unix_file_flush_method = SRV_UNIX_O_DSYNC; + } else if (0 == ut_strcmp(srv_unix_file_flush_method_str, "littlesync")) { - srv_unix_file_flush_method = SRV_UNIX_LITTLESYNC; - } else if (0 == ut_strcmp(srv_unix_file_flush_method_str, "nosync")) { - srv_unix_file_flush_method = SRV_UNIX_NOSYNC; - } else { - fprintf(stderr, - "InnoDB: Unrecognized value for innodb_unix_file_flush_method\n"); + srv_unix_file_flush_method = SRV_UNIX_LITTLESYNC; - return(DB_ERROR); + } else if (0 == ut_strcmp(srv_unix_file_flush_method_str, "nosync")) { + srv_unix_file_flush_method = SRV_UNIX_NOSYNC; + } else { + fprintf(stderr, + "InnoDB: Unrecognized value %s for innodb_flush_method\n", + srv_unix_file_flush_method_str); + return(DB_ERROR); } /* @@ -593,14 +602,15 @@ innobase_start_or_create_for_mysql(void) #ifdef __WIN__ if (os_get_os_version() == OS_WIN95 || os_get_os_version() == OS_WIN31) { - /* On Win 95, 98, ME, and Win32 subsystem for Windows 3.1 use - simulated aio */ - os_aio_use_native_aio = FALSE; - srv_n_file_io_threads = 4; + /* On Win 95, 98, ME, and Win32 subsystem for Windows 3.1 use + simulated aio */ + + os_aio_use_native_aio = FALSE; + srv_n_file_io_threads = 4; } else { - /* On NT and Win 2000 always use aio */ - os_aio_use_native_aio = TRUE; + /* On NT and Win 2000 always use aio */ + os_aio_use_native_aio = TRUE; } #endif if (!os_aio_use_native_aio) { @@ -652,14 +662,21 @@ innobase_start_or_create_for_mysql(void) sum_of_new_sizes = 0; for (i = 0; i < srv_n_data_files; i++) { - sum_of_new_sizes += srv_data_file_sizes[i]; + if (srv_data_file_sizes[i] >= 262144) { + fprintf(stderr, + "InnoDB: Error: file size must be < 4 GB, or on some OS's < 2 GB\n"); + + return(DB_ERROR); + } + + sum_of_new_sizes += srv_data_file_sizes[i]; } if (sum_of_new_sizes < 640) { - fprintf(stderr, + fprintf(stderr, "InnoDB: Error: tablespace size must be at least 10 MB\n"); - return(DB_ERROR); + return(DB_ERROR); } err = open_or_create_data_files(&create_new_db, @@ -673,6 +690,15 @@ innobase_start_or_create_for_mysql(void) return((int) err); } + if (!create_new_db) { + /* If we are using the doublewrite method, we will + check if there are half-written pages in data files, + and restore them from the doublewrite buffer if + possible */ + + trx_sys_doublewrite_restore_corrupt_pages(); + } + srv_normalize_path_for_win(srv_arch_dir); srv_arch_dir = srv_add_path_separator_if_needed(srv_arch_dir); @@ -742,7 +768,6 @@ innobase_start_or_create_for_mysql(void) mutex_exit(&(log_sys->mutex)); } - /* mutex_create(&row_mysql_thread_mutex); */ sess_sys_init_at_db_start(); if (create_new_db) { @@ -834,7 +859,7 @@ innobase_start_or_create_for_mysql(void) } if (srv_measure_contention) { - /* os_thread_create(&test_measure_cont, NULL, thread_ids + + /* os_thread_create(&test_measure_cont, NULL, thread_ids + SRV_MAX_N_IO_THREADS); */ } @@ -849,16 +874,20 @@ innobase_start_or_create_for_mysql(void) /* Create the thread which watches the timeouts for lock waits */ os_thread_create(&srv_lock_timeout_monitor_thread, NULL, thread_ids + 2 + SRV_MAX_N_IO_THREADS); - ut_print_timestamp(stderr); - fprintf(stderr, " InnoDB: Started\n"); - srv_was_started = TRUE; srv_is_being_started = FALSE; sync_order_checks_on = TRUE; + if (srv_use_doublewrite_buf && trx_doublewrite == NULL) { + trx_sys_create_doublewrite_buf(); + } + /* buf_debug_prints = TRUE; */ + ut_print_timestamp(stderr); + fprintf(stderr, " InnoDB: Started\n"); + return((int) DB_SUCCESS); } diff --git a/innobase/sync/sync0rw.c b/innobase/sync/sync0rw.c index a77cc76ed37..dc49ce2197e 100644 --- a/innobase/sync/sync0rw.c +++ b/innobase/sync/sync0rw.c @@ -810,11 +810,10 @@ rw_lock_print( ulint count = 0; rw_lock_debug_t* info; - printf("----------------------------------------------\n"); + printf("-------------------------------------------------\n"); printf("RW-LOCK INFO\n"); printf("RW-LOCK: %lx ", (ulint)lock); - mutex_enter(&(lock->mutex)); if ((rw_lock_get_writer(lock) != RW_LOCK_NOT_LOCKED) || (rw_lock_get_reader_count(lock) != 0) || (rw_lock_get_waiters(lock) != 0)) { @@ -831,8 +830,6 @@ rw_lock_print( info = UT_LIST_GET_NEXT(list, info); } } - - mutex_exit(&(lock->mutex)); #endif } diff --git a/innobase/sync/sync0sync.c b/innobase/sync/sync0sync.c index c3a1ac3b47f..a125f65be41 100644 --- a/innobase/sync/sync0sync.c +++ b/innobase/sync/sync0sync.c @@ -158,7 +158,7 @@ struct sync_thread_struct{ }; /* Number of slots reserved for each OS thread in the sync level array */ -#define SYNC_THREAD_N_LEVELS 256 +#define SYNC_THREAD_N_LEVELS 10000 struct sync_level_struct{ void* latch; /* pointer to a mutex or an rw-lock; NULL means that @@ -768,6 +768,9 @@ sync_thread_levels_g( thread */ ulint limit) /* in: level limit */ { + char* file_name; + ulint line; + ulint thread_id; sync_level_t* slot; rw_lock_t* lock; mutex_t* mutex; @@ -783,8 +786,29 @@ sync_thread_levels_g( lock = slot->latch; mutex = slot->latch; - ut_error; + printf( + "InnoDB error: sync levels should be > %lu but a level is %lu\n", + limit, slot->level); + if (mutex->magic_n == MUTEX_MAGIC_N) { + printf("Mutex created at %s %lu\n", &(mutex->cfile_name), + mutex->cline); + + if (mutex_get_lock_word(mutex) != 0) { + + mutex_get_debug_info(mutex, + &file_name, &line, &thread_id); + + printf("InnoDB: Locked mutex: addr %lx thread %ld file %s line %ld\n", + (ulint)mutex, thread_id, + file_name, line); + } else { + printf("Not locked\n"); + } + } else { + rw_lock_print(lock); + } + return(FALSE); } } @@ -973,6 +997,8 @@ sync_thread_add_level( ut_a(sync_thread_levels_g(array, SYNC_ANY_LATCH)); } else if (level == SYNC_TRX_SYS_HEADER) { ut_a(sync_thread_levels_contain(array, SYNC_KERNEL)); + } else if (level == SYNC_DOUBLEWRITE) { + ut_a(sync_thread_levels_g(array, SYNC_DOUBLEWRITE)); } else if (level == SYNC_BUF_BLOCK) { ut_a((sync_thread_levels_contain(array, SYNC_BUF_POOL) && sync_thread_levels_g(array, SYNC_BUF_BLOCK - 1)) @@ -1000,6 +1026,8 @@ sync_thread_add_level( } else if (level == SYNC_FSP) { ut_a(sync_thread_levels_contain(array, SYNC_FSP) || sync_thread_levels_g(array, SYNC_FSP)); + } else if (level == SYNC_EXTERN_STORAGE) { + ut_a(TRUE); } else if (level == SYNC_TRX_UNDO_PAGE) { ut_a(sync_thread_levels_contain(array, SYNC_TRX_UNDO) || sync_thread_levels_contain(array, SYNC_RSEG) @@ -1221,10 +1249,10 @@ void sync_print(void) /*============*/ { - printf("SYNC INFO:------------------------------------------\n"); + printf("SYNC INFO:\n"); mutex_list_print_info(); rw_lock_list_print_info(); sync_array_print_info(sync_primary_wait_array); sync_print_wait_info(); - printf("----------------------------------------------------\n"); + printf("-----------------------------------------------------\n"); } diff --git a/innobase/trx/trx0purge.c b/innobase/trx/trx0purge.c index f65943f27e3..032b3ffcf3b 100644 --- a/innobase/trx/trx0purge.c +++ b/innobase/trx/trx0purge.c @@ -692,6 +692,9 @@ trx_purge_choose_next_log(void) min_rseg = rseg; min_trx_no = rseg->last_trx_no; space = rseg->space; + ut_a(space == 0); /* We assume in purge of + externally stored fields + that space id == 0 */ page_no = rseg->last_page_no; offset = rseg->last_offset; } @@ -820,6 +823,10 @@ trx_purge_get_next_rec( } cmpl_info = trx_undo_rec_get_cmpl_info(rec2); + + if (trx_undo_rec_get_extern_storage(rec2)) { + break; + } if ((type == TRX_UNDO_UPD_EXIST_REC) && !(cmpl_info & UPD_NODE_NO_ORD_CHANGE)) { diff --git a/innobase/trx/trx0rec.c b/innobase/trx/trx0rec.c index c31d786011d..64febb8f523 100644 --- a/innobase/trx/trx0rec.c +++ b/innobase/trx/trx0rec.c @@ -292,6 +292,8 @@ trx_undo_rec_get_pars( TRX_UNDO_INSERT_REC, ... */ ulint* cmpl_info, /* out: compiler info, relevant only for update type records */ + ibool* updated_extern, /* out: TRUE if we updated an + externally stored fild */ dulint* undo_no, /* out: undo log record number */ dulint* table_id) /* out: table id */ { @@ -303,7 +305,14 @@ trx_undo_rec_get_pars( type_cmpl = mach_read_from_1(ptr); ptr++; - + + if (type_cmpl & TRX_UNDO_UPD_EXTERN) { + *updated_extern = TRUE; + type_cmpl -= TRX_UNDO_UPD_EXTERN; + } else { + *updated_extern = FALSE; + } + *type = type_cmpl & (TRX_UNDO_CMPL_INFO_MULT - 1); *cmpl_info = type_cmpl / TRX_UNDO_CMPL_INFO_MULT; @@ -336,7 +345,11 @@ trx_undo_rec_get_col_val( *field = ptr; if (*len != UNIV_SQL_NULL) { - ptr += *len; + if (*len >= UNIV_EXTERN_STORAGE_FIELD) { + ptr += (*len - UNIV_EXTERN_STORAGE_FIELD); + } else { + ptr += *len; + } } return(ptr); @@ -452,6 +465,7 @@ trx_undo_page_report_modify( ulint col_no; byte* old_ptr; ulint type_cmpl; + byte* type_cmpl_ptr; ulint i; ut_ad(index->type & DICT_CLUSTERED); @@ -491,6 +505,8 @@ trx_undo_page_report_modify( mach_write_to_1(ptr, type_cmpl); + type_cmpl_ptr = ptr; + ptr++; len = mach_dulint_write_much_compressed(ptr, trx->undo_no); ptr += len; @@ -577,7 +593,23 @@ trx_undo_page_report_modify( return(0); } - len = mach_write_compressed(ptr, flen); + if (rec_get_nth_field_extern_bit(rec, pos)) { + /* If a field has external storage, we add to + flen the flag */ + + len = mach_write_compressed(ptr, + UNIV_EXTERN_STORAGE_FIELD + flen); + + /* Notify purge that it eventually has to free the old + externally stored field */ + + (trx->update_undo)->del_marks = TRUE; + + *type_cmpl_ptr = *type_cmpl_ptr | TRX_UNDO_UPD_EXTERN; + } else { + len = mach_write_compressed(ptr, flen); + } + ptr += len; if (flen != UNIV_SQL_NULL) { @@ -825,6 +857,13 @@ trx_undo_update_rec_get_update( upd_field_set_field_no(upd_field, field_no, index); + if (len != UNIV_SQL_NULL && len >= UNIV_EXTERN_STORAGE_FIELD) { + + upd_field->extern_storage = TRUE; + + len -= UNIV_EXTERN_STORAGE_FIELD; + } + dfield_set_data(&(upd_field->new_val), field, len); } @@ -1222,8 +1261,10 @@ trx_undo_prev_version_build( byte* ptr; ulint info_bits; ulint cmpl_info; + ibool dummy_extern; byte* buf; ulint err; + ulint i; ut_ad(rw_lock_own(&(purge_sys->latch), RW_LOCK_SHARED)); ut_ad(mtr_memo_contains(index_mtr, buf_block_align(index_rec), @@ -1252,8 +1293,9 @@ trx_undo_prev_version_build( return(err); } - ptr = trx_undo_rec_get_pars(undo_rec, &type, &cmpl_info, &undo_no, - &table_id); + ptr = trx_undo_rec_get_pars(undo_rec, &type, &cmpl_info, + &dummy_extern, &undo_no, &table_id); + ptr = trx_undo_update_rec_get_sys_cols(ptr, &trx_id, &roll_ptr, &info_bits); ptr = trx_undo_rec_skip_row_ref(ptr, index); @@ -1278,5 +1320,15 @@ trx_undo_prev_version_build( row_upd_rec_in_place(*old_vers, update); } + for (i = 0; i < upd_get_n_fields(update); i++) { + + if (upd_get_nth_field(update, i)->extern_storage) { + + rec_set_nth_field_extern_bit(*old_vers, + upd_get_nth_field(update, i)->field_no, + TRUE, NULL); + } + } + return(DB_SUCCESS); } diff --git a/innobase/trx/trx0sys.c b/innobase/trx/trx0sys.c index 99ec5b50237..b056975d28a 100644 --- a/innobase/trx/trx0sys.c +++ b/innobase/trx/trx0sys.c @@ -19,9 +19,326 @@ Created 3/26/1996 Heikki Tuuri #include "trx0undo.h" #include "srv0srv.h" #include "trx0purge.h" +#include "log0log.h" /* The transaction system */ -trx_sys_t* trx_sys = NULL; +trx_sys_t* trx_sys = NULL; +trx_doublewrite_t* trx_doublewrite = NULL; + +/******************************************************************** +Creates or initialializes the doublewrite buffer at a database start. */ +static +void +trx_doublewrite_init( +/*=================*/ + byte* doublewrite) /* in: pointer to the doublewrite buf + header on trx sys page */ +{ + trx_doublewrite = mem_alloc(sizeof(trx_doublewrite_t)); + + mutex_create(&(trx_doublewrite->mutex)); + mutex_set_level(&(trx_doublewrite->mutex), SYNC_DOUBLEWRITE); + + trx_doublewrite->first_free = 0; + + trx_doublewrite->block1 = mach_read_from_4( + doublewrite + + TRX_SYS_DOUBLEWRITE_BLOCK1); + trx_doublewrite->block2 = mach_read_from_4( + doublewrite + + TRX_SYS_DOUBLEWRITE_BLOCK2); + trx_doublewrite->write_buf_unaligned = + ut_malloc( + (1 + 2 * TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) + * UNIV_PAGE_SIZE); + + trx_doublewrite->write_buf = ut_align( + trx_doublewrite->write_buf_unaligned, + UNIV_PAGE_SIZE); + trx_doublewrite->buf_block_arr = mem_alloc( + 2 * TRX_SYS_DOUBLEWRITE_BLOCK_SIZE + * sizeof(void*)); +} + +/******************************************************************** +Creates the doublewrite buffer at a database start. The header of the +doublewrite buffer is placed on the trx system header page. */ + +void +trx_sys_create_doublewrite_buf(void) +/*================================*/ +{ + page_t* page; + page_t* page2; + page_t* new_page; + byte* doublewrite; + byte* fseg_header; + ulint page_no; + ulint prev_page_no; + ulint i; + mtr_t mtr; + + if (trx_doublewrite) { + /* Already inited */ + + return; + } + +start_again: + mtr_start(&mtr); + + page = buf_page_get(TRX_SYS_SPACE, TRX_SYS_PAGE_NO, RW_X_LATCH, &mtr); + buf_page_dbg_add_level(page, SYNC_NO_ORDER_CHECK); + + doublewrite = page + TRX_SYS_DOUBLEWRITE; + + if (mach_read_from_4(doublewrite + TRX_SYS_DOUBLEWRITE_MAGIC) + == TRX_SYS_DOUBLEWRITE_MAGIC_N) { + + /* The doublewrite buffer has already been created: + just read in some numbers */ + + trx_doublewrite_init(doublewrite); + + mtr_commit(&mtr); + } else { + fprintf(stderr, + "InnoDB: Doublewrite buffer not found: creating new\n"); + + if (buf_pool_get_curr_size() < + (2 * TRX_SYS_DOUBLEWRITE_BLOCK_SIZE + + FSP_EXTENT_SIZE / 2 + 100) + * UNIV_PAGE_SIZE) { + fprintf(stderr, + "InnoDB: Cannot create doublewrite buffer: you must\n" + "InnoDB: increase your buffer pool size.\n" + "InnoDB: Cannot continue operation.\n"); + + exit(1); + } + + page2 = fseg_create(TRX_SYS_SPACE, TRX_SYS_PAGE_NO, + TRX_SYS_DOUBLEWRITE + TRX_SYS_DOUBLEWRITE_FSEG, &mtr); + + /* fseg_create acquires a second latch on the page, + therefore we must declare it: */ + + buf_page_dbg_add_level(page2, SYNC_NO_ORDER_CHECK); + + if (page2 == NULL) { + fprintf(stderr, + "InnoDB: Cannot create doublewrite buffer: you must\n" + "InnoDB: increase your tablespace size.\n" + "InnoDB: Cannot continue operation.\n"); + + /* We exit without committing the mtr to prevent + its modifications to the database getting to disk */ + + exit(1); + } + + fseg_header = page + TRX_SYS_DOUBLEWRITE + + TRX_SYS_DOUBLEWRITE_FSEG; + prev_page_no = 0; + + for (i = 0; i < 2 * TRX_SYS_DOUBLEWRITE_BLOCK_SIZE + + FSP_EXTENT_SIZE / 2; i++) { + page_no = fseg_alloc_free_page(fseg_header, + prev_page_no + 1, + FSP_UP, &mtr); + if (page_no == FIL_NULL) { + fprintf(stderr, + "InnoDB: Cannot create doublewrite buffer: you must\n" + "InnoDB: increase your tablespace size.\n" + "InnoDB: Cannot continue operation.\n"); + + exit(1); + } + + /* We read the allocated pages to the buffer pool; + when they are written to disk in a flush, the space + id and page number fields are also written to the + pages. When we at database startup read pages + from the doublewrite buffer, we know that if the + space id and page number in them are the same as + the page position in the tablespace, then the page + has not been written to in doublewrite. */ + + new_page = buf_page_get(TRX_SYS_SPACE, page_no, + RW_X_LATCH, &mtr); + buf_page_dbg_add_level(new_page, SYNC_NO_ORDER_CHECK); + + /* Make a dummy change to the page to ensure it will + be written to disk in a flush */ + + mlog_write_ulint(new_page + FIL_PAGE_DATA, + TRX_SYS_DOUBLEWRITE_MAGIC_N, + MLOG_4BYTES, &mtr); + + if (i == FSP_EXTENT_SIZE / 2) { + mlog_write_ulint(doublewrite + + TRX_SYS_DOUBLEWRITE_BLOCK1, + page_no, MLOG_4BYTES, &mtr); + mlog_write_ulint(doublewrite + + TRX_SYS_DOUBLEWRITE_REPEAT + + TRX_SYS_DOUBLEWRITE_BLOCK1, + page_no, MLOG_4BYTES, &mtr); + } else if (i == FSP_EXTENT_SIZE / 2 + + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) { + mlog_write_ulint(doublewrite + + TRX_SYS_DOUBLEWRITE_BLOCK2, + page_no, MLOG_4BYTES, &mtr); + mlog_write_ulint(doublewrite + + TRX_SYS_DOUBLEWRITE_REPEAT + + TRX_SYS_DOUBLEWRITE_BLOCK2, + page_no, MLOG_4BYTES, &mtr); + } else if (i > FSP_EXTENT_SIZE / 2) { + ut_a(page_no == prev_page_no + 1); + } + + prev_page_no = page_no; + } + + mlog_write_ulint(doublewrite + TRX_SYS_DOUBLEWRITE_MAGIC, + TRX_SYS_DOUBLEWRITE_MAGIC_N, MLOG_4BYTES, &mtr); + mlog_write_ulint(doublewrite + TRX_SYS_DOUBLEWRITE_MAGIC + + TRX_SYS_DOUBLEWRITE_REPEAT, + TRX_SYS_DOUBLEWRITE_MAGIC_N, MLOG_4BYTES, &mtr); + mtr_commit(&mtr); + + /* Flush the modified pages to disk and make a checkpoint */ + log_make_checkpoint_at(ut_dulint_max, TRUE); + + fprintf(stderr, "InnoDB: Doublewrite buffer created\n"); + + goto start_again; + } +} + +/******************************************************************** +At a database startup uses a possible doublewrite buffer to restore +half-written pages in the data files. */ + +void +trx_sys_doublewrite_restore_corrupt_pages(void) +/*===========================================*/ +{ + byte* buf; + byte* read_buf; + byte* unaligned_read_buf; + ulint block1; + ulint block2; + byte* page; + byte* doublewrite; + ulint space_id; + ulint page_no; + ulint i; + + /* We do the file i/o past the buffer pool */ + + unaligned_read_buf = ut_malloc(2 * UNIV_PAGE_SIZE); + read_buf = ut_align(unaligned_read_buf, UNIV_PAGE_SIZE); + + /* Read the trx sys header to check if we are using the + doublewrite buffer */ + + fil_io(OS_FILE_READ, TRUE, TRX_SYS_SPACE, TRX_SYS_PAGE_NO, 0, + UNIV_PAGE_SIZE, read_buf, NULL); + + doublewrite = read_buf + TRX_SYS_DOUBLEWRITE; + + if (mach_read_from_4(doublewrite + TRX_SYS_DOUBLEWRITE_MAGIC) + == TRX_SYS_DOUBLEWRITE_MAGIC_N) { + /* The doublewrite buffer has been created */ + + trx_doublewrite_init(doublewrite); + + block1 = trx_doublewrite->block1; + block2 = trx_doublewrite->block2; + + buf = trx_doublewrite->write_buf; + } else { + goto leave_func; + } + + /* Read the pages from the doublewrite buffer to memory */ + + fil_io(OS_FILE_READ, TRUE, TRX_SYS_SPACE, block1, 0, + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE * UNIV_PAGE_SIZE, + buf, NULL); + fil_io(OS_FILE_READ, TRUE, TRX_SYS_SPACE, block2, 0, + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE * UNIV_PAGE_SIZE, + buf + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE * UNIV_PAGE_SIZE, + NULL); + /* Check if any of these pages is half-written in data files, in the + intended position */ + + page = buf; + + for (i = 0; i < TRX_SYS_DOUBLEWRITE_BLOCK_SIZE * 2; i++) { + + space_id = mach_read_from_4(page + FIL_PAGE_SPACE); + page_no = mach_read_from_4(page + FIL_PAGE_OFFSET); + + if (!fil_check_adress_in_tablespace(space_id, page_no)) { + fprintf(stderr, + "InnoDB: Warning: an inconsistent page in the doublewrite buffer\n" + "InnoDB: space id %lu page number %lu, %lu'th page in dblwr buf.\n", + space_id, page_no, i); + + } else if (space_id == TRX_SYS_SPACE + && ( (page_no >= block1 + && page_no + < block1 + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE) + || (page_no >= block2 + && page_no + < block2 + TRX_SYS_DOUBLEWRITE_BLOCK_SIZE))) { + + /* It is an unwritten doublewrite buffer page: + do nothing */ + + } else { + /* Read in the actual page from the data files */ + + fil_io(OS_FILE_READ, TRUE, space_id, page_no, 0, + UNIV_PAGE_SIZE, read_buf, NULL); + /* Check if the page is corrupt */ + + if (buf_page_is_corrupted(read_buf)) { + + fprintf(stderr, + "InnoDB: Warning: database page corruption or a failed\n" + "InnoDB: file read of page %lu.\n", page_no); + fprintf(stderr, + "InnoDB: Trying to recover it from the doublewrite buffer.\n"); + + if (buf_page_is_corrupted(page)) { + fprintf(stderr, + "InnoDB: Also the page in the doublewrite buffer is corrupt.\n" + "InnoDB: Cannot continue operation.\n"); + exit(1); + } + + /* Write the good page from the + doublewrite buffer to the intended + position */ + + fil_io(OS_FILE_WRITE, TRUE, space_id, + page_no, 0, + UNIV_PAGE_SIZE, page, NULL); + fprintf(stderr, + "InnoDB: Recovered the page from the doublewrite buffer.\n"); + } + } + + page += UNIV_PAGE_SIZE; + } + + fil_flush_file_spaces(FIL_TABLESPACE); + +leave_func: + ut_free(unaligned_read_buf); +} /******************************************************************** Checks that trx is in the trx list. */ From a8c230adebf205ca849829c840baf47a7ace4aa4 Mon Sep 17 00:00:00 2001 From: unknown Date: Mon, 6 Aug 2001 11:55:44 -0500 Subject: [PATCH 33/51] manual.texi added explicit entry for EXTRACT() function Docs/manual.texi: added explicit entry for EXTRACT() function --- Docs/manual.texi | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 256362850f0..015e23ec009 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -30531,7 +30531,7 @@ mysql> select PERIOD_DIFF(9802,199703); @findex DATE_SUB() @findex ADDDATE() @findex SUBDATE() -@findex EXTRACT(type FROM date) +@findex EXTRACT() @item DATE_ADD(date,INTERVAL expr type) @itemx DATE_SUB(date,INTERVAL expr type) @itemx ADDDATE(date,INTERVAL expr type) @@ -30551,7 +30551,7 @@ or subtracted from the starting date. @code{expr} is a string; it may start with a @samp{-} for negative intervals. @code{type} is a keyword indicating how the expression should be interpreted. -The @code{EXTRACT(type FROM date)} function returns the 'type' +The related function @code{EXTRACT(type FROM date)} returns the 'type' interval from the date. The following table shows how the @code{type} and @code{expr} arguments @@ -30605,12 +30605,6 @@ mysql> SELECT DATE_ADD("1998-01-01 00:00:00", -> 1997-12-30 14:00:00 mysql> SELECT DATE_SUB("1998-01-02", INTERVAL 31 DAY); -> 1997-12-02 -mysql> SELECT EXTRACT(YEAR FROM "1999-07-02"); - -> 1999 -mysql> SELECT EXTRACT(YEAR_MONTH FROM "1999-07-02 01:02:03"); - -> 199907 -mysql> SELECT EXTRACT(DAY_MINUTE FROM "1999-07-02 01:02:03"); - -> 20102 @end example If you specify an interval value that is too short (does not include all the @@ -30649,6 +30643,22 @@ mysql> select DATE_ADD('1998-01-30', Interval 1 month); Note from the preceding example that the word @code{INTERVAL} and the @code{type} keyword are not case sensitive. +@findex EXTRACT() +@item EXTRACT(type FROM date) + +The @code{EXTRACT()} function uses the same kinds of interval type +specifiers as @code{DATE_ADD()} or @code{DATE_SUB()}, but extracts parts +from the date rather than performing date arithmetic. + +@example +mysql> SELECT EXTRACT(YEAR FROM "1999-07-02"); + -> 1999 +mysql> SELECT EXTRACT(YEAR_MONTH FROM "1999-07-02 01:02:03"); + -> 199907 +mysql> SELECT EXTRACT(DAY_MINUTE FROM "1999-07-02 01:02:03"); + -> 20102 +@end example + @findex TO_DAYS() @item TO_DAYS(date) Given a date @code{date}, returns a daynumber (the number of days since year From c810b4a444edbe36c938a2cfbc1228e92603c974 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 7 Aug 2001 09:17:24 -0500 Subject: [PATCH 34/51] manual.texi Mirror updates Docs/manual.texi: Mirror updates --- Docs/manual.texi | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 015e23ec009..2991a3095b2 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -6704,6 +6704,11 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @image{Flags/usa} USA [adgrafix.com/Boston, MA] @ @uref{http://mysql.adgrafix.com/, WWW} +@item +@c EMAIL: Pjacob@netnumina.com (Philip Jacob) +@image{Flags/usa} USA [netNumina/Cambridge, MA] @ +@uref{http://mysql.mirrors.netnumina.com/, WWW} + @end itemize @strong{South America:} @@ -6765,6 +6770,12 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @image{Flags/china} China [HKLPG/Hong Kong] @ @uref{http://mysql.hklpg.org, WWW} +@item +@c EMAIL: jason-wong@gremlins.com.hk (Gremlins Jason Wong) +@image{Flags/china} China [Gremlins/Hong Kong] @ +@uref{http://mysql.gremlins.com.hk/, WWW} +@uref{ftp://ftp.mirrors.gremlins.com.hk/mysql/, FTP} + @c @item @c Not ok 20010308; Other content! (Tonu) @c EMAIL: xcyber@yahoo.com (xcyber) @@ -6897,9 +6908,9 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @item @c Added 980610 @c EMAIL: jason@dstc.edu.au (Jason Andrade) -@image{Flags/australia} Australia [AARNet/Queensland] @ -@uref{http://mysql.mirror.aarnet.edu.au/, WWW} -@uref{ftp://mysql.mirror.aarnet.edu.au/, FTP} +@c @image{Flags/australia} Australia [AARNet/Queensland] @ +@c @uref{http://mysql.mirror.aarnet.edu.au/, WWW} +@c @uref{ftp://mysql.mirror.aarnet.edu.au/, FTP} @c @item @c Added 980805. Removed 000102 'no such directory' From 78a2de43adf1c4c123d7375d0c091b44d08b0528 Mon Sep 17 00:00:00 2001 From: unknown Date: Tue, 7 Aug 2001 16:46:58 -0400 Subject: [PATCH 35/51] Add --default-character-set option to mysqlimport. Thanks to takeshi@softagent.co.jp for the patch. client/mysqlimport.c: add --default-character-set option --- client/mysqlimport.c | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/client/mysqlimport.c b/client/mysqlimport.c index 3672edd62e5..79f0a8d584e 100644 --- a/client/mysqlimport.c +++ b/client/mysqlimport.c @@ -48,17 +48,19 @@ static MYSQL mysql_connection; static char *opt_password=0, *current_user=0, *current_host=0, *current_db=0, *fields_terminated=0, *lines_terminated=0, *enclosed=0, *opt_enclosed=0, - *escaped=0, opt_low_priority=0, *opt_columns=0; + *escaped=0, opt_low_priority=0, *opt_columns=0, + *default_charset; static uint opt_mysql_port=0; static my_string opt_mysql_unix_port=0; #include "sslopt-vars.h" enum options {OPT_FTB=256, OPT_LTB, OPT_ENC, OPT_O_ENC, OPT_ESC, - OPT_LOW_PRIORITY, OPT_CHARSETS_DIR}; + OPT_LOW_PRIORITY, OPT_CHARSETS_DIR, OPT_DEFAULT_CHARSET}; static struct option long_options[] = { {"character-sets-dir", required_argument, 0, OPT_CHARSETS_DIR}, + {"default-character-set", required_argument, 0, OPT_DEFAULT_CHARSET}, {"columns", required_argument, 0, 'c'}, {"compress", no_argument, 0, 'C'}, {"debug", optional_argument, 0, '#'}, @@ -119,6 +121,8 @@ file. The SQL command 'LOAD DATA INFILE' is used to import the rows.\n"); printf("\n\ -#, --debug[=...] Output debug log. Often this is 'd:t:o,filename`\n\ -?, --help Displays this help and exits.\n\ + --default-character-set=...\n\ + Set the default character set.\n\ --character-sets-dir=...\n\ Directory where character sets are\n\ -c, --columns=... Use only these columns to import the data to.\n\ @@ -179,6 +183,9 @@ static int get_options(int *argc, char ***argv) case 'C': opt_compress=1; break; + case OPT_DEFAULT_CHARSET: + default_charset= optarg; + break; case OPT_CHARSETS_DIR: charsets_dir= optarg; break; @@ -269,6 +276,11 @@ static int get_options(int *argc, char ***argv) fprintf(stderr, "You can't use --ignore (-i) and --replace (-r) at the same time.\n"); return(1); } + if (default_charset) + { + if (set_default_charset_by_name(default_charset, MYF(MY_WME))) + exit(1); + } (*argc)-=optind; (*argv)+=optind; if (*argc < 2) From 9d8135199d789cba71aff434744c22d56b068e32 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 8 Aug 2001 03:50:25 +0300 Subject: [PATCH 36/51] Fix of big in SELECT DISTINCT ... HAVING Docs/manual.texi: Update of changelog --- Docs/manual.texi | 5 ++++- sql/sql_select.cc | 1 + 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 015e23ec009..ece321592ca 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -45632,7 +45632,7 @@ users use this code as the rest of the code and because of this we are not yet 100% confident in this code. @menu -* News-3.23.41:: +* News-3.23.41:: Changes in release 3.23.41 * News-3.23.40:: Changes in release 3.23.40 * News-3.23.39:: Changes in release 3.23.39 * News-3.23.38:: Changes in release 3.23.38 @@ -45683,6 +45683,9 @@ not yet 100% confident in this code. @item Fixed optimizing bug in @code{ORDER BY} where some @code{ORDER BY} parts where wrongly removed. +@item +Fixed bug in @code{SELECT DISTINCT ... HAVING} that casued error message +@code{Can't find record in '#...} @end itemize @node News-3.23.40, News-3.23.39, News-3.23.41, News-3.23.x diff --git a/sql/sql_select.cc b/sql/sql_select.cc index d23a7edd37e..00f92e56b71 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -5425,6 +5425,7 @@ static int remove_dup_with_compare(THD *thd, TABLE *table, Field **first_field, { if ((error=file->delete_row(record))) goto err; + error=file->rnd_next(record); continue; } if (copy_blobs(first_field)) From 671c6c9333d7995a6badd48f971fadfac0abfd6b Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 8 Aug 2001 03:33:00 -0500 Subject: [PATCH 37/51] manual.texi More mirror list maintenance indonesia.eps BitKeeper file /home/mwagner/work/bk/mysql/Docs/Flags/indonesia.eps yugoslavia.eps BitKeeper file /home/mwagner/work/bk/mysql/Docs/Flags/yugoslavia.eps yugoslavia.gif BitKeeper file /home/mwagner/work/bk/mysql/Docs/Flags/yugoslavia.gif yugoslavia.txt BitKeeper file /home/mwagner/work/bk/mysql/Docs/Flags/yugoslavia.txt indonesia.gif BitKeeper file /home/mwagner/work/bk/mysql/Docs/Flags/indonesia.gif indonesia.txt BitKeeper file /home/mwagner/work/bk/mysql/Docs/Flags/indonesia.txt Docs/manual.texi: More mirror list maintenance --- Docs/Flags/indonesia.eps | 0 Docs/Flags/indonesia.gif | Bin 0 -> 133 bytes Docs/Flags/indonesia.txt | 0 Docs/Flags/yugoslavia.eps | 0 Docs/Flags/yugoslavia.gif | Bin 0 -> 250 bytes Docs/Flags/yugoslavia.txt | 0 Docs/manual.texi | 81 ++++++++++++++++++++++++-------------- 7 files changed, 52 insertions(+), 29 deletions(-) create mode 100644 Docs/Flags/indonesia.eps create mode 100644 Docs/Flags/indonesia.gif create mode 100644 Docs/Flags/indonesia.txt create mode 100644 Docs/Flags/yugoslavia.eps create mode 100644 Docs/Flags/yugoslavia.gif create mode 100644 Docs/Flags/yugoslavia.txt diff --git a/Docs/Flags/indonesia.eps b/Docs/Flags/indonesia.eps new file mode 100644 index 00000000000..e69de29bb2d diff --git a/Docs/Flags/indonesia.gif b/Docs/Flags/indonesia.gif new file mode 100644 index 0000000000000000000000000000000000000000..1c421df50ba6bf6e7213143075d6194150022fb3 GIT binary patch literal 133 zcmZ?wbhEHbRA3NeSjYeZXBZg%|NjqUDE-p9>~C84FH;UGR*)0 literal 0 HcmV?d00001 diff --git a/Docs/Flags/indonesia.txt b/Docs/Flags/indonesia.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/Docs/Flags/yugoslavia.eps b/Docs/Flags/yugoslavia.eps new file mode 100644 index 00000000000..e69de29bb2d diff --git a/Docs/Flags/yugoslavia.gif b/Docs/Flags/yugoslavia.gif new file mode 100644 index 0000000000000000000000000000000000000000..650eac242d68b7e6e75f2752d316395c2dd8f246 GIT binary patch literal 250 zcmVcPlQN$Az;xOkTSM?YBBEH$(1tM*;vl&*-#z&2GEj z@VIs;jK6uCK7Mva__cwzs&sy1Tr+zQ4f1!o$SH#>dFX%FE2n&d<=%(zp=-J7b@N AK>z>% literal 0 HcmV?d00001 diff --git a/Docs/Flags/yugoslavia.txt b/Docs/Flags/yugoslavia.txt new file mode 100644 index 00000000000..e69de29bb2d diff --git a/Docs/manual.texi b/Docs/manual.texi index 2991a3095b2..abae3e70e02 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -6360,6 +6360,11 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @uref{http://mysql.tiszanet.hu/, WWW} @uref{ftp://mysql.tiszanet.hu/pub/mirrors/mysql/, FTP} +@item +@c EMAIL: i.habencius@telnet.hu (Habencius Istvan) +@image{Flags/hungary} Hungary [stop.hu] @ +@uref{http://mysql.mirror.stop.hu/, WWW} + @item @c EMAIL: mirrors@gm.is (Tomas Edwardsson) @image{Flags/iceland} Iceland [GM] @ @@ -6547,10 +6552,11 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @uref{http://ftp.plig.org/pub/mysql/, WWW} @uref{ftp://ftp.plig.org/pub/mysql/, FTP} -@item +@c @item +@c Not ok 20010808; Non-existent (Matt) @c EMAIL: sean@telekon.co.uk (Sean Gibson) -@image{Flags/great-britain} UK [Telekon Internet/UK] @ -@uref{ftp://ftp.telekon.co.uk/pub/mysql/, FTP} +@c @image{Flags/great-britain} UK [Telekon Internet/UK] @ +@c @uref{ftp://ftp.telekon.co.uk/pub/mysql/, FTP} @c @item @c lance@uklinux.net (Lance) @@ -6571,16 +6577,22 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @c @uref{ftp://sunsite.org.uk/packages/mysql/, FTP} @item -@c sander@paco.net (Alexander Ivanov) +@c EMAIL: sander@paco.net (Alexander Ivanov) @image{Flags/ukraine} Ukraine [PACO] @ @uref{http://mysql.paco.net.ua, WWW} @uref{ftp://mysql.paco.net.ua/, FTP} @item -@c mizi@alkar.net (Alexander Ryumshin) +@c EMAIL: mizi@alkar.net (Alexander Ryumshin) @image{Flags/ukraine} Ukraine [ISP Alkar Teleport/Dnepropetrovsk] @ @uref{http://mysql.dp.ua/, WWW} +@item +@c EMAIL: bole@bolex.bolex.co.yu (Bosko Radivojevic) +@image{Flags/yugoslavia} Yugoslavia [bolex.co.yu] @ +@uref{http://mysql.boa.org.yu/, WWW} +@uref{ftp://ftp.linux.org.yu/pub/MySQL/, FTP} + @end itemize @strong{North America:} @@ -6709,6 +6721,12 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @image{Flags/usa} USA [netNumina/Cambridge, MA] @ @uref{http://mysql.mirrors.netnumina.com/, WWW} +@item +@c EMAIL: hagler@ahaza.com (Mark Hagler) +@image{Flags/usa} USA [Ahaza Systems/Seattle, WA] @ +@uref{http://mysql.mirrortree.com/, WWW} +@uref{ftp://mysql.mirrortree.com/pub/mysql/, FTP} + @end itemize @strong{South America:} @@ -6794,27 +6812,10 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @c @image{Flags/china} China [Netfirm] @ @c @uref{http://mysql.netfirm.net, WWW} -@c @item -@c Not ok 20000919; Old site (Matt) -@c EMAIL: ahmlhs@nmsvr.chosun.com (Ho-sun Lee) -@c @image{Flags/south-korea} South Korea [KREONet] @ -@c @uref{http://linux.kreonet.re.kr/mysql/, WWW} - @item -@c EMAIL: jasper@webiiz.com (Kang, Tae-jin) -@image{Flags/south-korea} South Korea [Webiiz] @ -@uref{http://mysql.webiiz.com/, WWW} - -@item -@c EMAIL: hollywar@holywar.net (Oh Junseon) -@image{Flags/south-korea} South Korea [PanworldNet] @ -@uref{http://mysql.holywar.net/, WWW} - -@c @item -@c ftp -> remove old files -@c EX: ahmlhs@nmsvr.chosun.com (Ho-sun Lee) -@c @image{Flags/south-korea} South Korea [KREONet] @ -@c @uref{ftp://linux.kreonet.re.kr/pub/tools/db/mysql/, FTP} +@c EMAIL: dnata@incaf.net "Denie Nataprawira" +@image{Flags/indonesia} Indonesia [incaf.net] +@uref{http://mysql.incaf.net/, WWW} @item @c Ok 980805 @@ -6842,6 +6843,28 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @c @uref{http://mirror.nucba.ac.jp/mirror/mysql, WWW} @c @uref{ftp://mirror.nucba.ac.jp/mirror/mysql, FTP} +@c @item +@c Not ok 20000919; Old site (Matt) +@c EMAIL: ahmlhs@nmsvr.chosun.com (Ho-sun Lee) +@c @image{Flags/south-korea} South Korea [KREONet] @ +@c @uref{http://linux.kreonet.re.kr/mysql/, WWW} + +@item +@c EMAIL: jasper@webiiz.com (Kang, Tae-jin) +@image{Flags/south-korea} South Korea [Webiiz] @ +@uref{http://mysql.webiiz.com/, WWW} + +@item +@c EMAIL: hollywar@holywar.net (Oh Junseon) +@image{Flags/south-korea} South Korea [PanworldNet] @ +@uref{http://mysql.holywar.net/, WWW} + +@c @item +@c ftp -> remove old files +@c EX: ahmlhs@nmsvr.chosun.com (Ho-sun Lee) +@c @image{Flags/south-korea} South Korea [KREONet] @ +@c @uref{ftp://linux.kreonet.re.kr/pub/tools/db/mysql/, FTP} + @c @item @c Removed 990308 @c EMAIL: terence@com5.net (Terence Chan) @@ -6902,10 +6925,10 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @end itemize -@strong{Australia:} +@c @strong{Australia:} -@itemize @bullet -@item +@c @itemize @bullet +@c @item @c Added 980610 @c EMAIL: jason@dstc.edu.au (Jason Andrade) @c @image{Flags/australia} Australia [AARNet/Queensland] @ @@ -6939,7 +6962,7 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @c EMAIL: lucifer@maths.uq.edu.au (David Conran) @c @image{Flags/australia} Australia FTP @ @c @uref{ftp://ftp.sage-au.org.au/pub/database/mysql, [Sage]} -@end itemize +@c @end itemize @strong{Africa:} From 5d7647dcb3891815069e7bb06eb0abe889bdcf6d Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 8 Aug 2001 07:12:45 -0500 Subject: [PATCH 38/51] manual.texi Another Indonesian mirror Docs/manual.texi: Another Indonesian mirror --- Docs/manual.texi | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index abae3e70e02..86a4b92f304 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -6813,10 +6813,16 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @c @uref{http://mysql.netfirm.net, WWW} @item -@c EMAIL: dnata@incaf.net "Denie Nataprawira" -@image{Flags/indonesia} Indonesia [incaf.net] +@c EMAIL: dnata@incaf.net (Denie Nataprawira) +@image{Flags/indonesia} Indonesia [incaf.net] @ @uref{http://mysql.incaf.net/, WWW} +@item +@c EMAIL: andika@piksi.itb.ac.id (Andika Triwidada) +@image{Flags/indonesia} Indonesia [web.id] @ +@uref{http://mysql.itb.web.id/, WWW} +@uref{ftp://mysql.itb.web.id/pub/MySQL/, FTP} + @item @c Ok 980805 @c EMAIL: takeshi@SoftAgency.co.jp From a102f17d1a08abc3e1779a4ac51b07e036313c65 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 01:42:39 +0800 Subject: [PATCH 39/51] manual.texi Removed broken mirror Docs/manual.texi: Removed broken mirror --- Docs/manual.texi | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 2991a3095b2..c90db7f238b 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -6755,10 +6755,11 @@ Please report bad or out-of-date mirrors to @email{webmaster@@mysql.com}. @strong{Asia:} @itemize @bullet -@item +@c @item +@c Host cannot be resolved for last week at least 20010809 Tonu @c EMAIL: mirnshi@263.net (Meng Lingbo) -@image{Flags/china} China [Freecode] @ -@uref{http://www.freecode.net.cn/mirror/mysql/, WWW} +@c @image{Flags/china} China [Freecode] @ +@c @uref{http://www.freecode.net.cn/mirror/mysql/, WWW} @item @c EMAIL: yusun@atwell.co.jp (yu sun) From ac60b56ffb2e17e669addc189c203267d33b1f72 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 8 Aug 2001 13:04:51 -0500 Subject: [PATCH 40/51] small fixes from users --- Docs/manual.texi | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 015e23ec009..421a1d13909 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -28950,8 +28950,8 @@ mysql> select 0.1 <= 2; @item < Less than: @example -mysql> select 2 <= 2; - -> 1 +mysql> select 2 < 2; + -> 0 @end example @findex >= (greater than or equal) @@ -38589,7 +38589,7 @@ you should be able to solve this by adding @code{-Lpath-to-the-mysql-library -lmysqlclient} @strong{LAST} on your link line. If you get @code{undefined reference} errors for the @code{uncompress} -or @code{compress} function, add @code{-lgz} @strong{LAST} on your link +or @code{compress} function, add @code{-lz} @strong{LAST} on your link line and try again! If you get @code{undefined reference} errors for functions that should From a9a445437a702270a090b74d713e9524a98304b1 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 8 Aug 2001 21:35:43 +0300 Subject: [PATCH 41/51] trx0purge.c Fix a bug which might stop purge from running buf0flu.c Add an include to fix compile problem in non-inlined version innobase/buf/buf0flu.c: Add an include to fix compile problem in non-inlined version innobase/trx/trx0purge.c: Fix a bug which might stop purge from running --- innobase/buf/buf0flu.c | 1 + innobase/trx/trx0purge.c | 2 ++ 2 files changed, 3 insertions(+) diff --git a/innobase/buf/buf0flu.c b/innobase/buf/buf0flu.c index 0f27cee45a5..82b12103c4c 100644 --- a/innobase/buf/buf0flu.c +++ b/innobase/buf/buf0flu.c @@ -21,6 +21,7 @@ Created 11/11/1995 Heikki Tuuri #include "ibuf0ibuf.h" #include "log0log.h" #include "os0file.h" +#include "trx0sys.h" /* When flushed, dirty blocks are searched in neigborhoods of this size, and flushed along with the original page. */ diff --git a/innobase/trx/trx0purge.c b/innobase/trx/trx0purge.c index 032b3ffcf3b..afb83926fa3 100644 --- a/innobase/trx/trx0purge.c +++ b/innobase/trx/trx0purge.c @@ -678,6 +678,8 @@ trx_purge_choose_next_log(void) rseg = UT_LIST_GET_FIRST(trx_sys->rseg_list); + min_trx_no = ut_dulint_max; + min_rseg = NULL; while (rseg) { From 40f6a1d693220a0119618390a78cf0b47401bd52 Mon Sep 17 00:00:00 2001 From: unknown Date: Wed, 8 Aug 2001 22:31:44 +0300 Subject: [PATCH 42/51] row0upd.c Fix a memory overwrite which can happen if we update or delete a > 8000-byte row innobase/row/row0upd.c: Fix a memory overwrite which can happen if we update or delete a > 8000-byte row --- innobase/row/row0upd.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/innobase/row/row0upd.c b/innobase/row/row0upd.c index d339474df61..67a5925a3f5 100644 --- a/innobase/row/row0upd.c +++ b/innobase/row/row0upd.c @@ -789,8 +789,8 @@ row_upd_store_row( node->row = row_build(ROW_COPY_DATA, clust_index, rec, node->heap); - node->ext_vec = mem_heap_alloc(node->heap, rec_get_n_fields(rec)); - + node->ext_vec = mem_heap_alloc(node->heap, sizeof(ulint) + * rec_get_n_fields(rec)); if (node->is_delete) { update = NULL; } else { From f8f08143c360b4227a1a51d5f0a99d141ce8a0c7 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 01:34:11 -0500 Subject: [PATCH 43/51] fixed some spacing and tag nesting problems in manual.texi Docs/manual.texi: fixed some spacing and tag nesting problems --- Docs/manual.texi | 187 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 181 insertions(+), 6 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index c90d00e19ba..f3ab70cf180 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -92,6 +92,7 @@ END-INFO-DIR-ENTRY @end iftex + @node Top, Introduction, (dir), (dir) @c @ifhtml @@ -141,14 +142,17 @@ distribution for that version. @end menu + + + +@node Introduction, Installing, Top, Top +@chapter General Information About MySQL + @cindex overview @cindex general information @cindex online location of manual @cindex manual, online location -@node Introduction, Installing, Top, Top -@chapter General Information About MySQL - This is the @strong{MySQL} reference manual; it documents @strong{MySQL} Version @value{mysql_version}. As @strong{MySQL} is work in progress, the manual gets updated frequently. There is a very good chance that @@ -245,6 +249,7 @@ see @ref{General-SQL}. For books that focus more specifically on * TODO:: @end menu + @node MySQL and MySQL AB, MySQL Information Sources, Introduction, Introduction @section MySQL, MySQL AB, and Open Source @@ -260,6 +265,7 @@ see @ref{General-SQL}. For books that focus more specifically on * Year 2000 compliance:: Year 2000 compliance @end menu + @node What-is, What is MySQL AB, MySQL and MySQL AB, MySQL and MySQL AB @subsection What Is MySQL @@ -351,6 +357,7 @@ language already supports @strong{MySQL}. The official way to pronounce @strong{MySQL} is ``My Ess Que Ell'' (not MY-SEQUEL). But we try to avoid correcting people who say MY-SEQUEL. + @node What is MySQL AB, Manual-info, What-is, MySQL and MySQL AB @subsection What Is MySQL AB @@ -463,6 +470,7 @@ Are a virtual company, networking with others. Work against software patents. @end itemize + @node Manual-info, Manual conventions, What is MySQL AB, MySQL and MySQL AB @subsection About This Manual @@ -480,6 +488,7 @@ This manual is written and maintained by David Axmark, Michael (Monty) Widenius, Jeremy Cole, and Paul DuBois. For other contributors, see @ref{Credits}. + @node Manual conventions, History, Manual-info, MySQL and MySQL AB @subsection Conventions Used in This Manual @@ -604,6 +613,7 @@ alternatives are listed within braces (@samp{@{} and @samp{@}}): @{DESCRIBE | DESC@} tbl_name @{col_name | wild@} @end example + @node History, Features, Manual conventions, MySQL and MySQL AB @subsection History of MySQL @@ -789,10 +799,12 @@ information about databases, tables, and indexes. The @code{EXPLAIN} command can be used to determine how the optimizer resolves a query. @end itemize -@cindex stability + @node Stability, Table size, Features, MySQL and MySQL AB @subsection How Stable Is MySQL? +@cindex stability + This section addresses the questions ``How stable is @strong{MySQL}?'' and ``Can I depend on @strong{MySQL} in this project?'' We will try to clarify some issues and to answer some of the more important questions that seem to @@ -948,6 +960,7 @@ Text search seems to work, but is still not widely used. Bugs are usually fixed right away with a patch; for serious bugs, there is almost always a new release. + @node Table size, Year 2000 compliance, Stability, MySQL and MySQL AB @subsection How Big Can MySQL Tables Be? @@ -1004,6 +1017,7 @@ Another solution can be the included MERGE library, which allows you to handle a collection of identical tables as one. @xref{MERGE, MERGE tables}. + @node Year 2000 compliance, , Table size, MySQL and MySQL AB @subsection Year 2000 Compliance @@ -1103,6 +1117,7 @@ provide unambiguous input. See @ref{Y2K issues} for @strong{MySQL}'s rules for dealing with ambiguous date input data (data containing 2-digit year values). + @node MySQL Information Sources, Licensing and Support, MySQL and MySQL AB, Introduction @section MySQL Information Sources @@ -1116,6 +1131,7 @@ values). * Questions:: @end menu + @node MySQL-Books, General-SQL, MySQL Information Sources, MySQL Information Sources @subsection Books About MySQL @@ -1468,6 +1484,7 @@ A complete reference to DBI. @end itemize @* + @node General-SQL, Useful Links, MySQL-Books, MySQL Information Sources @subsection General SQL Information and Tutorials @@ -1497,6 +1514,7 @@ Alameda, CA USA A SQL tutorial is available on the net at http://w3.one.net/~jhoffman/sqltut.htm + @node Useful Links, Questions, General-SQL, MySQL Information Sources @subsection Useful MySQL-related Links @@ -2085,6 +2103,7 @@ require that you show a @strong{MySQL} logo somewhere if you wish your site to be added. It is okay to have it on a ``used tools'' page or something similar. + @node Questions, , Useful Links, MySQL Information Sources @subsection MySQL Mailing Lists @@ -2101,6 +2120,7 @@ something similar. This section introduces you to the @strong{MySQL} mailing lists, and gives some guidelines as to how to use them. + @node Mailing-list, Asking questions, Questions, Questions @subsubsection The MySQL Mailing Lists @@ -2246,6 +2266,7 @@ Email @code{subscribe mysql-br your@@email.address} to this list. Email @code{subscribe mysql your@@email.address} to this list. @end table + @node Asking questions, Bug reports, Mailing-list, Questions @subsubsection Asking Questions or Reporting Bugs @@ -2280,6 +2301,7 @@ local @strong{MySQL} expert. If you still can't find an answer to your question, go ahead and read the next section about how to send mail to @email{mysql@@lists.mysql.com}. + @node Bug reports, Answering questions, Asking questions, Questions @subsubsection How to Report Bugs or Problems @@ -2587,6 +2609,7 @@ it is considered good etiquette to summarize the answers and send the summary to the mailing list so that others may have the benefit of responses you received that helped you solve your problem! + @node Answering questions, , Bug reports, Questions @subsubsection Guidelines for Answering Question on the Mailing List @@ -2607,6 +2630,7 @@ obliged to quote the entire original message. Please don't post mail messages from your browser with HTML mode turned on! Many users don't read mail with a browser! + @node Licensing and Support, Compatibility, MySQL Information Sources, Introduction @section MySQL Licensing and Support @@ -2638,6 +2662,7 @@ arrangements: @item Commercial licensing costs @end itemize + @node Licensing policy, Copyright, Licensing and Support, Licensing and Support @subsection MySQL Licensing Policy @@ -2724,6 +2749,7 @@ is to use the license form on @strong{MySQL}'s secure server at @uref{https://order.mysql.com/}. Other forms of payment are discussed in @ref{Payment information}. + @node Copyright, Licensing examples, Licensing policy, Licensing and Support @subsection Copyrights Used by MySQL @@ -2770,12 +2796,14 @@ However, if you use @strong{MySQL} for something important to you, you may want to help secure its development by purchasing licenses or a support contract. @xref{Support}. + @node Copyright changes, , Copyright, Copyright @subsubsection Copyright Changes Version 3.22 of @strong{MySQL} is still using a more strict license. See the documentation for that version for more information. + @node Licensing examples, Cost, Copyright, Licensing and Support @subsection Example Licensing Situations @@ -2797,6 +2825,7 @@ Note that a single @strong{MySQL} license covers any number of CPUs and @code{mysqld} servers on a machine! There is no artificial limit on the number of clients that connect to the server in any way. + @node Products that use MySQL, ISP, Licensing examples, Licensing examples @subsubsection Selling Products that use MySQL @@ -2841,6 +2870,7 @@ don't need a license. @end itemize + @node ISP, Web server, Products that use MySQL, Licensing examples @subsubsection ISP MySQL Services @@ -2867,6 +2897,7 @@ it should give its customers at least read access to the source of the @strong{MySQL} installation so that its customer can verify that it is patched correctly. + @node Web server, , ISP, Licensing examples @subsubsection Running a Web Server Using MySQL @@ -2881,6 +2912,7 @@ This is true even if you run a commercial Web server that uses version yourself. However, in this case we would like you to purchase @strong{MySQL} support, because @strong{MySQL} is helping your enterprise. + @node Cost, Support, Licensing examples, Licensing and Support @subsection MySQL Licensing and Support Costs @@ -2963,6 +2995,7 @@ Note that as our sales staff is very busy, it may take some time until your request is handled. Our support staff does however always answer promptly to support questions! + @node Payment information, Contact information, Cost, Cost @subsubsection Payment information @@ -3011,6 +3044,7 @@ us'' in the comment field. You can also mail a message to @email{sales@@mysql.com} (@strong{not} @code{mysql@@lists.mysql.com}!) with your company information and ask us to bill you. + @node Contact information, , Payment information, Cost @subsubsection Contact Information @@ -3053,6 +3087,7 @@ For general information inquires, please send e-mail to For questions or comments about the workings or content of the Web site, please send e-mail to @email{webmaster@@mysql.com}. + @node Support, , Cost, Licensing and Support @subsection Types of Commercial Support @@ -3091,6 +3126,7 @@ if you have login support (2000 EURO), you can expect us to work up to 10 hours to help you with things like this. @end itemize + @node Basic email support, Extended email support, Support, Support @subsubsection Basic E-mail Support @@ -3164,6 +3200,7 @@ If you want us to help optimize your system, you must upgrade to a higher level of support. @end itemize + @node Extended email support, Login support, Basic email support, Support @subsubsection Extended E-mail Support @@ -3211,6 +3248,7 @@ TODO List. @xref{TODO}. This will ensure that the features you really need will be implemented sooner than they might be otherwise. @end itemize + @node Login support, Extended login support, Extended email support, Support @subsubsection Login Support @@ -3254,6 +3292,7 @@ before talking on phone, to be able to work as efficiently as possible on solving the problem. @end itemize + @node Extended login support, Telephone support, Login support, Support @subsubsection Extended Login Support @@ -3291,6 +3330,7 @@ without charge. For the hours above 8 hours, you will be charged with a rate that is at least 20 % less than our standard rates. @end itemize + @node Telephone support, Table handler support, Extended login support, Support @subsubsection Telephone Support @@ -3307,6 +3347,7 @@ For non critical problem, you can request a @strong{MySQL} developer to phone back within 48 hours to discuss @code{MySQL} related issues. @end itemize + @node Table handler support, , Telephone support, Support @subsubsection Support for other table handlers @@ -3327,6 +3368,7 @@ timely manner, we can't guarantee a quick solution for any problems you can get with the different table handlers. We will however do our best to help you get the problem solved. + @node Compatibility, Comparisons, Licensing and Support, Introduction @section How Standards-compatible Is MySQL? @@ -3351,6 +3393,7 @@ will find out what they are, and how to use them. You will also find information about functionality missing from @strong{MySQL}, and how to work around some differences. + @node Extensions to ANSI, Differences from ANSI, Compatibility, Compatibility @subsection MySQL Extensions to ANSI SQL92 @@ -3596,6 +3639,7 @@ SELECT @@t1:=(@@t2:=1)+@@t3:=4,@@t1,@@t2,@@t3; @end itemize + @node Differences from ANSI, ANSI mode, Extensions to ANSI, Compatibility @subsection MySQL Differences Compared to ANSI SQL92 @@ -3623,6 +3667,7 @@ This is because we don't think it's good to have to evaluate a lot of extra conditions in this case. @end itemize + @node ANSI mode, Missing functions, Differences from ANSI, Compatibility @subsection Running MySQL in ANSI Mode @@ -3649,6 +3694,7 @@ The default transaction isolation level is @code{SERIALIZABLE}. @xref{SET TRANSACTION}. @end itemize + @node Missing functions, Standards, ANSI mode, Compatibility @subsection Functionality Missing from MySQL @@ -3673,6 +3719,7 @@ list in this manual. @xref{TODO}. * Missing comments:: @samp{--} as the start of a comment @end menu + @node Missing Sub-selects, Missing SELECT INTO TABLE, Missing functions, Missing functions @subsubsection Sub-selects @@ -3730,6 +3777,7 @@ prompt> mysql --skip-column-names mydb < myscript.sql | mysql mydb be available in Version 4.0. You can now use the function @code{IN()} in other contexts, however. + @node Missing SELECT INTO TABLE, Missing Transactions, Missing Sub-selects, Missing functions @subsubsection @code{SELECT INTO TABLE} @@ -3748,6 +3796,7 @@ tblTemp1.fldOrder_ID > 100; Alternatively, you can use @code{SELECT INTO OUTFILE...} or @code{CREATE TABLE ... SELECT} to solve your problem. + @node Missing Transactions, Missing Triggers, Missing SELECT INTO TABLE, Missing functions @subsubsection Transactions @@ -3863,6 +3912,7 @@ that we believe to be better than any commercial replication system we know of. This system will work most reliably under the atomic operations, non-transactional, paradigm. Stay tuned. + @node Missing Triggers, Missing Foreign Keys, Missing Transactions, Missing functions @subsubsection Stored Procedures and Triggers @@ -3870,7 +3920,6 @@ operations, non-transactional, paradigm. Stay tuned. @cindex procedures, stored @cindex triggers, stored - A stored procedure is a set of SQL commands that can be compiled and stored in the server. Once this has been done, clients don't need to keep reissuing the entire query but can refer to the stored procedure. This provides better @@ -3890,6 +3939,7 @@ down everything, even queries for which they are not needed. To see when @strong{MySQL} might get stored procedures, see @ref{TODO}. + @node Missing Foreign Keys, Broken Foreign KEY, Missing Triggers, Missing functions @subsubsection Foreign Keys @@ -3934,6 +3984,7 @@ coded to avoid them. * Broken Foreign KEY:: Reasons NOT to use foreign keys constraints @end menu + @node Broken Foreign KEY, Missing Views, Missing Foreign Keys, Missing functions @subsubsection Reasons NOT to Use Foreign Keys constraints @@ -3990,6 +4041,7 @@ connection was made. The current @file{.frm} file format does not have any place for it. At a later stage we will implement the foreign key constraints for application that can't easily be coded to avoid them. + @node Missing Views, Missing comments, Broken Foreign KEY, Missing functions @subsubsection Views @@ -4012,6 +4064,7 @@ One doesn't need views in @strong{MySQL} to restrict access to columns as @strong{MySQL} has a very sophisticated privilege system. @xref{Privilege system}. + @node Missing comments, , Missing Views, Missing functions @subsubsection @samp{--} as the Start of a Comment @@ -4074,11 +4127,13 @@ Change them back with this command: shell> replace " #" " --" -- text-file-with-funny-comments.sql @end example + @node Standards, Commit-rollback, Missing functions, Compatibility @subsection What Standards Does MySQL Follow? Entry level SQL92. ODBC levels 0-2. + @node Commit-rollback, Bugs, Standards, Compatibility @subsection How to Cope Without @code{COMMIT}/@code{ROLLBACK} @@ -4213,6 +4268,7 @@ You can think of it as @strong{MySQL} changed the above query to: UPDATE tbl_name SET row_flag=1 WHERE id=ID and row_flag <> 1; @end example + @node Bugs, , Commit-rollback, Compatibility @subsection Known errors and design deficiencies in MySQL @@ -4455,6 +4511,7 @@ decimals. For platform-specific bugs, see the sections about compiling and porting. + @node Comparisons, TODO, Compatibility, Introduction @section How MySQL Compares to Other Databases @@ -4477,6 +4534,7 @@ For a list of all supported limits, functions, and types, see the @code{crash-me} Web page at @uref{http://www.mysql.com/information/crash-me.php}. + @node Compare mSQL, Compare PostgreSQL, Comparisons, Comparisons @subsection How MySQL Compares to @code{mSQL} @@ -4669,6 +4727,7 @@ For example, it changes instances of @code{msqlConnect()} to * Syntax differences:: @end menu + @node Using mSQL tools, Protocol differences, Compare mSQL, Compare mSQL @subsubsection How to Convert @code{mSQL} Tools for MySQL @@ -4714,6 +4773,7 @@ Some incompatibilities exist as a result of @strong{MySQL} supporting multiple connections to the server from the same process. @end itemize + @node Protocol differences, Syntax differences, Using mSQL tools, Compare mSQL @subsubsection How @code{mSQL} and MySQL Client/Server Communications Protocols Differ @@ -4752,6 +4812,7 @@ If a connection is idle for 8 hours, the server closes the connection. * Syntax differences:: @end menu + @node Syntax differences, , Protocol differences, Compare mSQL @subsubsection How @code{mSQL} 2.0 SQL Syntax Differs from MySQL @@ -4974,6 +5035,7 @@ can offer, you should use @code{PostgreSQL}. * MySQL-PostgreSQL benchmarks:: @end menu + @node MySQL-PostgreSQL goals, MySQL-PostgreSQL features, Compare PostgreSQL, Compare PostgreSQL @subsubsection MySQL and PostgreSQL development strategies @@ -5241,6 +5303,7 @@ in this section. * MySQL-PostgreSQL benchmarks:: @end menu + @node MySQL-PostgreSQL benchmarks, , MySQL-PostgreSQL features, Compare PostgreSQL @subsubsection Benchmarking MySQL and PostgreSQL @@ -5462,6 +5525,7 @@ We are working on an even better benchmark suite, including much better documentation of what the individual tests really do and how to add more tests to the suite. + @node TODO, , Comparisons, Introduction @section MySQL and the future (The TODO) @@ -5484,6 +5548,7 @@ The plan is that we in the future will support the full ANSI SQL99 standard, but with a lot of useful extensions. The challenge is to do this without sacrifying the speed or compromise the code. + @node TODO MySQL 4.0, TODO future, TODO, TODO @subsection Things that should be in 4.0 @@ -5569,6 +5634,7 @@ of @code{analyze} is run on all sub tables. @code{SET SQL_DEFAULT_TABLE_TYPE=[MyISAM | INNODB | BDB | HEAP]}. @end itemize + @node TODO future, TODO sometime, TODO MySQL 4.0, TODO @subsection Things that must be done in the real near future @@ -5850,6 +5916,7 @@ if it exists and @code{INSERT} a new row if the row didn't exist. (Like @code{REPLACE} works with @code{INSERT} / @code{DELETE}) @end itemize + @node TODO sometime, TODO unplanned, TODO future, TODO @subsection Things that have to be done sometime @@ -5945,6 +6012,7 @@ one must also handle the possible deadlocks this change will introduce. Time is given according to amount of work, not real time. + @node TODO unplanned, , TODO sometime, TODO @subsection Some things we don't have any plans to do @@ -5953,6 +6021,9 @@ Time is given according to amount of work, not real time. Nothing; In the long run we plan to be fully ANSI 92 / ANSI 99 compliant. @end itemize + + + @node Installing, Tutorial, Introduction, Top @chapter MySQL Installation @@ -6000,6 +6071,7 @@ procedures apply whether you install @strong{MySQL} using a binary or source distribution. @end itemize + @node Quick Standard Installation, General Installation Issues, Installing, Installing @section Quick Standard Installation of MySQL @@ -6009,6 +6081,7 @@ source distribution. * Windows installation:: @end menu + @node Linux-RPM, Windows installation, Quick Standard Installation, Quick Standard Installation @subsection Installing MySQL on Linux @@ -6084,6 +6157,7 @@ and you should now be able to start using @strong{MySQL}. If something goes wrong, you can find more information in the binary installation chapter. @xref{Installing binary}. + @node Windows installation, , Linux-RPM, Quick Standard Installation @subsection Installing MySQL on Windows @@ -6173,6 +6247,7 @@ options that must be specified in your @file{my.ini} file! @xref{InnoDB start}. * MySQL binaries:: @end menu + @node Getting MySQL, Which OS, General Installation Issues, General Installation Issues @subsection How to Get MySQL @@ -7125,6 +7200,7 @@ forth more effort into testing on and optimizing for that particular platform. We are just stating our observations to help you make a decision on which platform to use @strong{MySQL} on in your setup. + @node Which version, Installation layouts, Which OS, General Installation Issues @subsection Which MySQL Version to Use @@ -7306,6 +7382,7 @@ Another test is that we use the newest @strong{MySQL} version in our internal production environment, on at least one machine. We have more than 100 gigabytes of data to work with. + @node Installation layouts, Many versions, Which version, General Installation Issues @subsection Installation Layouts @@ -7371,6 +7448,7 @@ The header file and library directories are @file{include/mysql} and You can create your own binary installation from a compiled source distribution by executing the script @file{scripts/make_binary_distribution}. + @node Many versions, MySQL binaries, Installation layouts, General Installation Issues @subsection How and When Updates Are Released @@ -7432,6 +7510,7 @@ and things that ``must be done.'' ``Somewhat frozen'' means that we may add small things that ``almost surely will not affect anything that's already working.'' + @node MySQL binaries, , Many versions, General Installation Issues @subsection MySQL Binaries Compiled by MySQL AB @@ -7491,6 +7570,7 @@ If you want to compile a debug version of @strong{MySQL}, you should add @code{--with-debug} or @code{--with-debug=full} to the above configure lines and remove any @code{-fomit-frame-pointer} options. + @node Installing source, Post-installation, General Installation Issues, Installing @section Installing a MySQL Source Distribution @@ -7565,6 +7645,7 @@ of getting a solution to your problem! You will find @code{mysqlbug} in the * MIT-pthreads:: @end menu + @node Quick install, Applying patches, Installing source, Installing source @subsection Quick Installation Overview @@ -7744,6 +7825,7 @@ running. @xref{Multiple servers}. @xref{Post-installation}. + @node Applying patches, configure options, Quick install, Installing source @subsection Applying Patches @@ -7785,6 +7867,7 @@ You may need to bring down any currently running server before you run systems do not allow you to install a new version of a program if it replaces the version that is currently executing. + @node configure options, Installing source tree, Applying patches, Installing source @subsection Typical @code{configure} Options @@ -8007,6 +8090,7 @@ system-specific section of this manual. @xref{Operating System Specific Notes}. @end itemize + @node Installing source tree, Compilation problems, configure options, Installing source @subsection Installing from the Development Source Tree @@ -8108,6 +8192,7 @@ a description. @end enumerate + @node Compilation problems, MIT-pthreads, Installing source tree, Installing source @subsection Problems Compiling? @@ -8329,6 +8414,7 @@ If you need to debug @code{mysqld} or a @strong{MySQL} client, run link your clients with the new client library. @xref{Debugging client}. @end itemize + @node MIT-pthreads, , Compilation problems, Installing source @subsection MIT-pthreads Notes @@ -8695,6 +8781,7 @@ shell> BINDIR/mysql -vvf test < ./tests/auto_increment.tst The expected results are shown in the @file{./tests/auto_increment.res} file. @end enumerate + @node mysql_install_db, Starting server, Post-installation, Post-installation @subsection Problems Running @code{mysql_install_db} @cindex @code{mysql_install_db} script @@ -8807,6 +8894,7 @@ flush-privileges} or @code{mysqladmin reload} afterward to tell the server to reload the grant tables. @end table + @node Starting server, Automatic start, mysql_install_db, Post-installation @subsection Problems Starting the MySQL Server @cindex server, starting problems @@ -8965,8 +9053,10 @@ options. @xref{InnoDB start}. If you are using BDB (Berkeley DB) tables, you should familiarize yourself with the different BDB specific startup options. @xref{BDB start}. + @node Automatic start, , Starting server, Post-installation @subsection Starting and Stopping MySQL Automatically + @cindex starting, the server automatically @cindex stopping, the server @cindex server, starting and stopping @@ -9040,6 +9130,7 @@ read from option files: @xref{Option files}. + @node Upgrade, Operating System Specific Notes, Post-installation, Installing @section Upgrading/Downgrading MySQL @@ -9086,6 +9177,7 @@ dumping core after you upgrade @strong{MySQL}. * Upgrading-to-arch:: Upgrading to another architecture @end menu + @node Upgrading-from-3.22, Upgrading-from-3.21, Upgrade, Upgrade @subsection Upgrading From Version 3.22 to Version 3.23 @@ -9211,6 +9303,7 @@ on an @code{AND/OR} expression as @code{NOT NULL} = @code{NULL}. than the length argument. @end itemize + @node Upgrading-from-3.21, Upgrading-from-3.20, Upgrading-from-3.22, Upgrade @subsection Upgrading from Version 3.21 to Version 3.22 @@ -9242,8 +9335,10 @@ The @code{mysqld} variable @code{key_buffer} has changed names to @code{key_buffer_size}, but you can still use the old name in your startup files. + @node Upgrading-from-3.20, Upgrading-to-arch, Upgrading-from-3.21, Upgrade @subsection Upgrading from Version 3.20 to Version 3.21 + @cindex upgrading, 3.20 to 3.21 If you are running a version older than Version 3.20.28 and want to @@ -9311,6 +9406,7 @@ There are some new reserved words. The most notable are @code{DATE}, @code{TIME}, and @code{TIMESTAMP}. @end itemize + @node Upgrading-to-arch, , Upgrading-from-3.20, Upgrade @subsection Upgrading to Another Architecture @@ -9406,6 +9502,7 @@ After you import the @code{mysql} database on the new machine, execute @code{mysqladmin flush-privileges} so that the server reloads the grant table information. + @node Operating System Specific Notes, , Upgrade, Installing @section Operating System Specific Notes @@ -9421,6 +9518,7 @@ information. * Novell Netware:: @end menu + @node Linux, Windows, Operating System Specific Notes, Operating System Specific Notes @subsection Linux Notes (All Linux Versions) @@ -9686,6 +9784,7 @@ The following @code{configure} line should work with @code{fcc/FCC}: CC=fcc CFLAGS="-O -K fast -K lib -K omitfp -Kpreex -D_GNU_SOURCE -DCONST=const -DNO_STRTOLL_PROTO" CXX=FCC CXXFLAGS="-O -K fast -K lib -K omitfp -K preex --no_exceptions --no_rtti -D_GNU_SOURCE -DCONST=const -Dalloca=__builtin_alloca -DNO_STRTOLL_PROTO '-D_EXTERN_INLINE=static __inline'" ./configure --prefix=/usr/local/mysql --enable-assembler --with-mysqld-ldflags=-all-static --disable-shared --with-low-memory @end example + @node Binary notes-Linux, Linux-x86, Linux, Linux @subsubsection Linux Notes for Binary Distributions @@ -9765,6 +9864,7 @@ your clients or use sockets, if you are running the database server and clients on the same machine. We hope that the @code{Linux 2.4} kernel will fix this problem in the future. + @node Linux-x86, Linux-SPARC, Binary notes-Linux, Linux @subsubsection Linux x86 Notes @@ -9826,6 +9926,7 @@ You can avoid using @file{libg++.a} by running @code{configure} like this: shell> CXX=gcc ./configure @end example + @node Linux-SPARC, Linux-Alpha, Linux-x86, Linux @subsubsection Linux SPARC Notes @@ -9842,6 +9943,7 @@ that is available at @code{vger.rutgers.edu} (a version of Linux that was never merged with the official 2.0.30). You must also install LinuxThreads Version 0.6 or newer. + @node Linux-Alpha, Linux-PowerPC, Linux-SPARC, Linux @subsubsection Linux Alpha Notes @@ -9888,12 +9990,14 @@ resulting image will core dump at start. In other words, @strong{DON'T} use @code{--with-mysqld-ldflags=-all-static} with @code{gcc}. @end itemize + @node Linux-PowerPC, Linux-MIPS, Linux-Alpha, Linux @subsubsection Linux PowerPC Notes @strong{MySQL} should work on MkLinux with the newest @code{glibc} package (tested with @code{glibc} 2.0.7). + @node Linux-MIPS, Linux-IA64, Linux-PowerPC, Linux @subsubsection Linux MIPS Notes @@ -9902,6 +10006,7 @@ newest @code{glibc} libraries (@code{glibc-2.0.7-29C2} is known to work). You must also use the @code{egcs} C++ compiler (@code{egcs-1.0.2-9}, @code{gcc 2.95.2} or newer). + @node Linux-IA64, , Linux-MIPS, Linux @subsubsection Linux IA64 Notes @@ -9948,6 +10053,7 @@ with the @strong{MySQL} Windows distribution. * Windows vs Unix:: @strong{MySQL}-Windows compared to Unix @strong{MySQL} @end menu + @node Win95 start, NT start, Windows, Windows @subsubsection Starting MySQL on Windows 95 or Windows 98 @@ -9995,6 +10101,7 @@ The last option is to start @code{mysqld} with @code{--standalone @file{C:\mysqld.trace} that should contain the reason why @code{mysqld} doesn't start. @xref{Making trace files}. + @node NT start, Windows running, Win95 start, Windows @subsubsection Starting MySQL on Windows NT or Windows 2000 @@ -10084,6 +10191,7 @@ C:\> C:\mysql\bin\mysqld --standalone --debug The last version gives you a debug trace in @file{C:\mysqld.trace}. @xref{Making trace files}. + @node Windows running, Windows and SSH, NT start, Windows @subsubsection Running MySQL on Windows @@ -10169,10 +10277,12 @@ With the current @strong{MySQL} versions you can easily add new users and change privileges with @code{GRANT} and @code{REVOKE} commands. @xref{GRANT}. -@c FIX this is ugly, real ugly. + @node Windows and SSH, Windows symbolic links, Windows running, Windows @subsubsection Connecting to a Remote MySQL from Windows with SSH +@c FIX this is ugly, real ugly. + @cindex SSH @cindex connecting, remotely with SSH @@ -10214,6 +10324,7 @@ for the @strong{MySQL} host server --- not @code{yourmysqlservername}. You should now have an ODBC connection to @strong{MySQL}, encrypted using SSH. + @node Windows symbolic links, Windows compiling, Windows and SSH, Windows @subsubsection Splitting Data Across Different Disks on Windows @@ -10253,6 +10364,7 @@ In @strong{MySQL} 4.0 we will enable symlinks by default. Then you should instead use the @code{skip-symlink} option if you want to disable this. + @node Windows compiling, Windows vs Unix, Windows symbolic links, Windows @subsubsection Compiling MySQL Clients on Windows @@ -10276,6 +10388,7 @@ with the static @file{mysqlclient.lib} library. Note that as the mysqlclient libraries are compiled as threaded libraries, you should also compile your code to be multi-threaded! + @node Windows vs Unix, , Windows compiling, Windows @subsubsection MySQL-Windows Compared to Unix MySQL @@ -10656,6 +10769,7 @@ symbolic link to it named @file{/etc/rc3.d/S99mysql.server}. * Solaris x86:: @end menu + @node Solaris 2.7, Solaris x86, Solaris, Solaris @subsubsection Solaris 2.7/2.8 Notes @@ -10864,6 +10978,7 @@ crash when @code{make} tries to run @code{lint} on C++ files. * OpenBSD 2.8:: OpenBSD 2.8 Notes @end menu + @node OpenBSD 2.5, OpenBSD 2.8, OpenBSD, BSD Notes @subsubsection OpenBSD 2.5 Notes @@ -10874,6 +10989,7 @@ with the following options: CFLAGS=-pthread CXXFLAGS=-pthread ./configure --with-mit-threads=no @end example + @node OpenBSD 2.8, BSDI, OpenBSD 2.5, BSD Notes @subsubsection OpenBSD 2.8 Notes @@ -10893,6 +11009,7 @@ usage, and crashes. * BSDI4:: BSD/OS 4.x notes @end menu + @node BSDI2, BSDI3, BSDI, BSD Notes @subsubsection BSD/OS Version 2.x Notes @@ -10917,6 +11034,7 @@ If you are using @code{gcc}, you may also use have to use the If you get problems with the current date in @strong{MySQL}, setting the @code{TZ} variable will probably help. @xref{Environment variables}. + @node BSDI3, BSDI4, BSDI2, BSD Notes @subsubsection BSD/OS Version 3.x Notes @@ -10957,6 +11075,7 @@ If this doesn't work and you are using @code{bash}, try switching to @code{csh} or @code{sh}; some BSDI users have reported problems with @code{bash} and @code{ulimit}. + @node BSDI4, , BSDI3, BSD Notes @subsubsection BSD/OS Version 4.x Notes @@ -11813,6 +11932,7 @@ If you want to use @code{gcc}, you must use @code{gcc} 2.95.2 or newer. * OS/2:: @end menu + @node OS/2, BeOS, Other Unix Notes, Operating System Specific Notes @subsection OS/2 Notes @@ -11897,6 +12017,8 @@ We are interested in finding someone to do a port, and we will help them with any technical questions they may have while doing the port. + + @node Tutorial, MySQL Database Administration, Installing, Top @chapter Introduction to MySQL: A MySQL Tutorial @@ -11946,6 +12068,7 @@ Because this chapter is tutorial in nature, many details are necessarily left out. Consult the relevant sections of the manual for more information on the topics covered here. + @node Connecting-disconnecting, Entering queries, Tutorial, Tutorial @section Connecting to and Disconnecting from the Server @@ -12009,6 +12132,7 @@ You can also disconnect by pressing Control-D. Most examples in the following sections assume you are connected to the server. They indicate this by the @code{mysql>} prompt. + @node Entering queries, Database use, Connecting-disconnecting, Tutorial @section Entering Queries @@ -12235,6 +12359,7 @@ containing @code{QUIT}! This can be quite confusing, especially if you don't know that you need to supply the terminating quote before you can cancel the current command. + @node Database use, Getting information, Entering queries, Tutorial @section Creating and Using a Database @@ -12327,6 +12452,7 @@ mysql> GRANT ALL ON menagerie.* TO your_mysql_name; where @code{your_mysql_name} is the @strong{MySQL} user name assigned to you. + @node Creating database, Creating tables, Database use, Database use @subsection Creating and Selecting a Database @@ -12375,6 +12501,7 @@ option, you must do so with no intervening space (for example, as password on the command line is not recommended, because doing so exposes it to snooping by other users logged in on your machine. + @node Creating tables, Loading tables, Creating database, Database use @subsection Creating a Table @@ -12480,6 +12607,7 @@ mysql> DESCRIBE pet; You can use @code{DESCRIBE} any time, for example, if you forget the names of the columns in your table or what types they are. + @node Loading tables, Retrieving data, Creating tables, Database use @subsection Loading Data into a Table @@ -12554,6 +12682,7 @@ typing involved to load your records initially using several @code{INSERT} statements rather than a single @code{LOAD DATA} statement. + @node Retrieving data, , Loading tables, Database use @subsection Retrieving Information from a Table @@ -12589,6 +12718,7 @@ indicates the table from which you want to retrieve data. The @code{WHERE} clause is optional. If it's present, @code{conditions_to_satisfy} specifies conditions that rows must satisfy to qualify for retrieval. + @node Selecting all, Selecting rows, Retrieving data, Retrieving data @subsubsection Selecting All Data @@ -12647,6 +12777,7 @@ case you specify some constraints on the information you want. Let's look at some selection queries in terms of questions about your pets that they answer. + @node Selecting rows, Selecting columns, Selecting all, Retrieving data @subsubsection Selecting Particular Rows @@ -12725,6 +12856,7 @@ mysql> SELECT * FROM pet WHERE (species = "cat" AND sex = "m") +-------+--------+---------+------+------------+-------+ @end example + @node Selecting columns, Sorting rows, Selecting rows, Retrieving data @subsubsection Selecting Particular Columns @@ -12808,6 +12940,7 @@ mysql> SELECT name, species, birth FROM pet +--------+---------+------------+ @end example + @node Sorting rows, Date calculations, Selecting columns, Retrieving data @subsubsection Sorting Rows @@ -12885,6 +13018,7 @@ Note that the @code{DESC} keyword applies only to the column name immediately preceding it (@code{birth}); @code{species} values are still sorted in ascending order. + @node Date calculations, Working with NULL, Sorting rows, Retrieving data @subsubsection Date Calculations @@ -13058,6 +13192,7 @@ Note that @code{MONTH} returns a number between 1 and 12. And addition has to be after the @code{MOD()} otherwise we would go from November (11) to January (1). + @node Working with NULL, Pattern matching, Date calculations, Retrieving data @subsubsection Working with @code{NULL} Values @@ -13098,6 +13233,7 @@ This special treatment of @code{NULL} is why, in the previous section, it was necessary to determine which animals are no longer alive using @code{death IS NOT NULL} instead of @code{death != NULL}. + @node Pattern matching, Counting rows, Working with NULL, Retrieving data @subsubsection Pattern Matching @@ -13296,6 +13432,7 @@ mysql> SELECT * FROM pet WHERE name REGEXP "^.@{5@}$"; +-------+--------+---------+------+------------+-------+ @end example + @node Counting rows, Multiple tables, Pattern matching, Retrieving data @subsubsection Counting Rows @@ -13435,6 +13572,7 @@ mysql> SELECT species, sex, COUNT(*) FROM pet +---------+------+----------+ @end example + @node Multiple tables, , Counting rows, Retrieving data @subsubsection Using More Than one Table @@ -13556,6 +13694,7 @@ In this query, we specify aliases for the table name in order to refer to the columns and keep straight which instance of the table each column reference is associated with. + @node Getting information, Examples, Database use, Tutorial @section Getting Information About Databases and Tables @@ -13621,6 +13760,7 @@ indexed, and @code{Default} specifies the column's default value. If you have indexes on a table, @code{SHOW INDEX FROM tbl_name} produces information about them. + @node Examples, Batch mode, Getting information, Tutorial @section Examples of Common Queries @@ -13686,6 +13826,7 @@ mysql> SELECT * FROM shop; * Calculating days:: @end menu + @node example-Maximum-column, example-Maximum-row, Examples, Examples @subsection The Maximum Value for a Column @@ -13701,6 +13842,7 @@ SELECT MAX(article) AS article FROM shop +---------+ @end example + @node example-Maximum-row, example-Maximum-column-group, example-Maximum-column, Examples @subsection The Row Holding the Maximum of a Certain Column @@ -13742,6 +13884,7 @@ LIMIT 1 @strong{NOTE}: If there are several most expensive articles (for example, each 19.95) the @code{LIMIT} solution shows only one of them! + @node example-Maximum-column-group, example-Maximum-column-group-row, example-Maximum-row, Examples @subsection Maximum of Column per Group @@ -13762,6 +13905,7 @@ GROUP BY article +---------+-------+ @end example + @node example-Maximum-column-group-row, example-user-variables, example-Maximum-column-group, Examples @subsection The Rows Holding the Group-wise Maximum of a Certain Field @@ -13833,6 +13977,7 @@ GROUP BY article; The last example can, of course, be made a bit more efficient by doing the splitting of the concatenated column in the client. + @node example-user-variables, example-Foreign keys, example-Maximum-column-group-row, Examples @subsection Using user variables @@ -13855,6 +14000,7 @@ select * from shop where price=@@min_price or price=@@max_price; +---------+--------+-------+ @end example + @node example-Foreign keys, Searching on two keys, example-user-variables, Examples @subsection Using Foreign Keys @@ -13938,6 +14084,7 @@ SELECT s.* FROM persons p, shirts s +----+-------+--------+-------+ @end example + @node Searching on two keys, Calculating days, example-Foreign keys, Examples @subsection Searching on Two Keys @@ -13974,6 +14121,7 @@ DROP TABLE tmp; The above way to solve this query is in effect an @code{UNION} of two queries. + @node Calculating days, , Searching on two keys, Examples @subsection Calculating visits per day @@ -14004,6 +14152,7 @@ Which returns: The above calculates how many different days was used for a given year/month combination, with automatic removal of duplicate entries. + @node Batch mode, Twin, Examples, Tutorial @section Using @code{mysql} in Batch Mode @@ -14106,6 +14255,7 @@ If you want to get the interactive output format in batch mode, use @code{mysql -t}. To echo to the output the commands that are executed, use @code{mysql -vvv}. + @node Twin, Apache, Batch mode, Tutorial @section Queries from Twin Project @@ -14144,6 +14294,7 @@ database. * Twin event:: Show a table on twin pair status @end menu + @node Twin pool, Twin event, Twin, Twin @subsection Find all Non-distributed Twins @@ -14267,6 +14418,7 @@ The current number of records in the tables used above: @item @code{postal_groups} @tab 100 @end multitable + @node Twin event, , Twin pool, Twin @subsection Show a Table on Twin Pair Status @@ -14325,6 +14477,8 @@ FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' @end example + + @node MySQL Database Administration, MySQL Optimization, Tutorial, Top @chapter MySQL Database Administration @@ -14353,6 +14507,7 @@ FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' * Multiple servers:: @end menu + @node Command-line options, Option files, Configuring MySQL, Configuring MySQL @subsection mysqld Command-line Options @@ -14867,6 +15022,7 @@ argument to @code{safe_mysqld}. * Multiple servers:: @end menu + @node Multiple servers, , Installing many servers, Configuring MySQL @subsection Running Multiple MySQL Servers on the Same Machine @@ -15326,6 +15482,7 @@ can do this by setting the @code{max_user_connections} variable in @code{mysqld}. @end itemize + @node Privileges options, What Privileges, Security, Privilege system @subsection Startup Options for @code{mysqld} Concerning Security @@ -17756,6 +17913,7 @@ make a lot of changes to a table) * Optimization:: @end menu + @node myisamchk syntax, myisamchk general options, Table maintenance, Table maintenance @subsubsection @code{myisamchk} Invocation Syntax @@ -18028,6 +18186,7 @@ of duplicate keys Unpack file packed with myisampack. @end table + @node myisamchk other options, myisamchk memory, myisamchk repair options, Table maintenance @subsubsection Other Options for @code{myisamchk} @@ -18058,6 +18217,7 @@ table's indexes in the same order that @code{myisamchk} sees them. Indexes are numbered beginning with 1. @end table + @node myisamchk memory, Crash recovery, myisamchk other options, Table maintenance @subsubsection @code{myisamchk} Memory Usage @@ -18851,6 +19011,7 @@ information and a description of what it means. * SHOW:: @end menu + @node OPTIMIZE TABLE, ANALYZE TABLE, Database Administration, Database Administration @subsection @code{OPTIMIZE TABLE} Syntax @@ -19051,6 +19212,7 @@ write is aborted with an disk full error message. * SHOW:: @end menu + @node SHOW, , KILL, Database Administration @subsection @code{SHOW} Syntax @@ -22924,6 +23086,7 @@ it is preferred that you use @code{CHANGE MASTER TO} command. * Replication Problems:: @end menu + @node Replication Features, Replication Options, Replication HOWTO, Replication @subsection Replication Features and Known Problems @@ -23709,6 +23872,8 @@ isolate it into a separate test case first. Then report the problem to @email{bugs@@lists.mysql.com} with as much info as possible. + + @node MySQL Optimization, Reference, MySQL Database Administration, Top @chapter MySQL Optimization @@ -23777,6 +23942,7 @@ for most systems, but one should be aware of it. * Custom Benchmarks:: @end menu + @node Design Limitations, Portability, Optimize Overview, Optimize Overview @subsection MySQL Design Limitations/Tradeoffs @@ -23869,6 +24035,7 @@ In this case the table creation information should contain information of the initial size of the cache and how often the table should normally be refreshed. + @node Internal use, MySQL Benchmarks, Portability, Optimize Overview @subsection What Have We Used MySQL For? @@ -24668,6 +24835,7 @@ mysql> SELECT ... FROM tbl_name ORDER BY key_part1,key_part2,... ; mysql> SELECT ... FROM tbl_name ORDER BY key_part1 DESC,key_part2 DESC,... ; @end example + @node DISTINCT optimization, LEFT JOIN optimization, Where optimizations, Query Speed @subsection How MySQL Optimizes @code{DISTINCT} @@ -24792,6 +24960,7 @@ The size of temporary tables uses the @code{LIMIT #} to calculate how much space is needed to resolve the query. @end itemize + @node Insert speed, Update speed, LIMIT optimization, Query Speed @subsection Speed of @code{INSERT} Queries @@ -25139,6 +25308,7 @@ from the data, you should not lose anything by using @code{DELAY_KEY_WRITE}. * Table locking:: @end menu + @node Internal locking, Table locking, Locking Issues, Locking Issues @subsection How MySQL Locks Tables @@ -25328,6 +25498,7 @@ option to @code{DELETE} may help. @xref{DELETE, , @code{DELETE}}. * Open tables:: @end menu + @node Design, Data size, Optimizing Database Structure, Optimizing Database Structure @subsection Design Choices @@ -25625,6 +25796,7 @@ much more quickly find the few rows to return in the result. * Open tables:: @end menu + @node Indexes, Multiple-column indexes, MySQL indexes, Optimizing Database Structure @subsection Column Indexes @@ -25839,6 +26011,7 @@ between all threads. * SET OPTION:: @end menu + @node System, Server parameters, Optimizing the Server, Optimizing the Server @subsection System/Compile Time and Startup Parameter Tuning @@ -26420,6 +26593,7 @@ with the update log. * SET TRANSACTION:: @end menu + @node SET TRANSACTION, , SET OPTION, SET OPTION @subsubsection @code{SET TRANSACTION} Syntax @@ -26540,6 +26714,7 @@ with the noatime flag. * Symbolic links:: @end menu + @node Symbolic links, , Disk issues, Disk issues @subsection Using Symbolic Links From b95d4398ff9c02f338f6b023481b0d8448070997 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 18:51:38 +0300 Subject: [PATCH 44/51] Added new optino --sql-mode to mysqld. Docs/manual.texi: New option, --sql-mode=option[,option[,option]] sql/ha_myisam.cc: Fixed a segmentation fault -bug with myisam-recover which occurred if option specified was not a legal one. sql/mysql_priv.h: New option --sql-mode sql/mysqld.cc: New option --sql-mode sql/sql_class.cc: New option --sql-mode sql/sql_class.h: New option --sql-mode sql/sql_lex.cc: option --sql-mode, ansi_quotes and ignore_space sql/sql_parse.cc: option --sql-mode, ignore_space sql/sql_select.cc: option --sql-mode, mode only_full_group_by sql/sql_yacc.yy: option --sql-mode, modes pipes_as_concat and real_as_float BitKeeper/etc/logging_ok: Logging to logging@openlogging.org accepted --- BitKeeper/etc/logging_ok | 17 +---------------- Docs/manual.texi | 9 +++++++++ sql/ha_myisam.cc | 2 +- sql/mysql_priv.h | 13 ++++++++++--- sql/mysqld.cc | 36 +++++++++++++++++++++++++++++++----- sql/sql_class.cc | 1 + sql/sql_class.h | 2 +- sql/sql_lex.cc | 4 ++-- sql/sql_parse.cc | 4 ++-- sql/sql_select.cc | 4 ++-- sql/sql_yacc.yy | 4 ++-- 11 files changed, 62 insertions(+), 34 deletions(-) diff --git a/BitKeeper/etc/logging_ok b/BitKeeper/etc/logging_ok index fbf9c3702a3..966f7a398de 100644 --- a/BitKeeper/etc/logging_ok +++ b/BitKeeper/etc/logging_ok @@ -1,16 +1 @@ -heikki@donna.mysql.fi -jani@janikt.pp.saunalahti.fi -miguel@light.local -monty@hundin.mysql.fi -monty@tik.mysql.fi -monty@work.mysql.com -mwagner@evoq.mwagner.org -paul@central.snake.net -paul@teton.kitebird.com -sasha@mysql.sashanet.com -serg@serg.mysql.com -tim@threads.polyesthetic.msg -tim@white.box -jcole@tetra.spaceapes.com -davida@isil.mysql.com -tonu@x153.internalnet +jani@hynda.mysql.fi diff --git a/Docs/manual.texi b/Docs/manual.texi index e7cce565698..ab268ded406 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -14595,6 +14595,13 @@ Disable using thread priorities for faster response time. Socket file to use for local connections instead of default @code{/tmp/mysql.sock}. +@item --sql-mode=option[,option[,option...]] +Option can be one of: REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, +IGNORE_SPACE, SERIALIZE, ONLY_FULL_GROUP_BY. + +By specifying all of the above options is same as using --ansi. +With this option one can turn on only needed SQL modes. @xref{ANSI mode}. + @item transaction-isolation= @{ READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE @} Sets the default transaction isolation level. @xref{SET TRANSACTION}. @@ -45720,6 +45727,8 @@ not yet 100% confident in this code. @node News-3.23.41, News-3.23.40, News-3.23.x, News-3.23.x @appendixsubsec Changes in release 3.23.41 @itemize @bullet +@item Added option @code{--sql-mode=option[,option[,option]]}. Please see +@code{mysqld --help} for legal modes. @item Fixed optimizing bug in @code{ORDER BY} where some @code{ORDER BY} parts where wrongly removed. diff --git a/sql/ha_myisam.cc b/sql/ha_myisam.cc index 6409ec5d019..8be62920308 100644 --- a/sql/ha_myisam.cc +++ b/sql/ha_myisam.cc @@ -35,7 +35,7 @@ ulong myisam_recover_options= HA_RECOVER_NONE; /* bits in myisam_recover_options */ const char *myisam_recover_names[] = -{ "DEFAULT", "BACKUP", "FORCE", "QUICK"}; +{ "DEFAULT", "BACKUP", "FORCE", "QUICK", NullS}; TYPELIB myisam_recover_typelib= {array_elements(myisam_recover_names),"", myisam_recover_names}; diff --git a/sql/mysql_priv.h b/sql/mysql_priv.h index f21c635dbdf..f8c0efd6eb2 100644 --- a/sql/mysql_priv.h +++ b/sql/mysql_priv.h @@ -156,8 +156,7 @@ void kill_one_thread(THD *thd, ulong id); #define OPTION_LOW_PRIORITY_UPDATES 8192 #define OPTION_WARNINGS 16384 #define OPTION_AUTO_IS_NULL 32768 -#define OPTION_ANSI_MODE 65536L -#define OPTION_SAFE_UPDATES OPTION_ANSI_MODE*2 +#define OPTION_SAFE_UPDATES 65536L*2 #define OPTION_BUFFER_RESULT OPTION_SAFE_UPDATES*2 #define OPTION_BIN_LOG OPTION_BUFFER_RESULT*2 #define OPTION_NOT_AUTO_COMMIT OPTION_BIN_LOG*2 @@ -173,6 +172,14 @@ void kill_one_thread(THD *thd, ulong id); #define QUERY_NO_INDEX_USED OPTION_STATUS_NO_TRANS_UPDATE*2 #define QUERY_NO_GOOD_INDEX_USED QUERY_NO_INDEX_USED*2 +/* Bits for different SQL modes modes (including ANSI mode) */ +#define MODE_REAL_AS_FLOAT 1 +#define MODE_PIPES_AS_CONCAT 2 +#define MODE_ANSI_QUOTES 4 +#define MODE_IGNORE_SPACE 8 +#define MODE_SERIALIZABLE 16 +#define MODE_ONLY_FULL_GROUP_BY 32 + #define RAID_BLOCK_SIZE 1024 /* BINLOG_DUMP options */ @@ -530,7 +537,7 @@ extern ulong keybuff_size,sortbuff_size,max_item_sort_length,table_cache_size, what_to_log,flush_time, max_tmp_tables,max_heap_table_size,query_buff_size, lower_case_table_names,thread_stack,thread_stack_min, - binlog_cache_size, max_binlog_cache_size; + binlog_cache_size, max_binlog_cache_size, opt_sql_mode; extern ulong specialflag, current_pid; extern bool low_priority_updates, using_update_log; extern bool opt_sql_bin_update, opt_safe_show_db, opt_warnings; diff --git a/sql/mysqld.cc b/sql/mysqld.cc index a9771184b4b..36ee127580c 100644 --- a/sql/mysqld.cc +++ b/sql/mysqld.cc @@ -211,7 +211,7 @@ static char mysql_home[FN_REFLEN],pidfile_name[FN_REFLEN]; static pthread_t select_thread; static bool opt_log,opt_update_log,opt_bin_log,opt_slow_log,opt_noacl, opt_disable_networking=0, opt_bootstrap=0,opt_skip_show_db=0, - opt_ansi_mode=0,opt_myisam_log=0, + opt_myisam_log=0, opt_large_files=sizeof(my_off_t) > 4; bool opt_sql_bin_update = 0, opt_log_slave_updates = 0, opt_safe_show_db=0; FILE *bootstrap_file=0; @@ -307,6 +307,7 @@ char server_version[SERVER_VERSION_LENGTH]=MYSQL_SERVER_VERSION; const char *first_keyword="first"; const char **errmesg; /* Error messages */ const char *myisam_recover_options_str="OFF"; +const char *sql_mode_str="OFF"; const char *default_tx_isolation_name; enum_tx_isolation default_tx_isolation=ISO_READ_COMMITTED; @@ -320,6 +321,12 @@ double log_10[32]; /* 10 potences */ I_List threads,thread_cache; time_t start_time; +ulong opt_sql_mode = 0L; +const char *sql_mode_names[] = +{ "REAL_AS_FLOAT", "PIPES_AS_CONCAT", "ANSI_QUOTES", "IGNORE_SPACE", + "SERIALIZE","ONLY_FULL_GROUP_BY", NullS }; +TYPELIB sql_mode_typelib= {array_elements(sql_mode_names),"", + sql_mode_names}; MY_BITMAP temp_pool; bool use_temp_pool=0; @@ -2471,7 +2478,8 @@ enum options { OPT_GEMINI_FLUSH_LOG, OPT_GEMINI_RECOVER, OPT_GEMINI_UNBUFFERED_IO, OPT_SKIP_SAFEMALLOC, OPT_SKIP_STACK_TRACE, OPT_SKIP_SYMLINKS, - OPT_MAX_BINLOG_DUMP_EVENTS, OPT_SPORADIC_BINLOG_DUMP_FAIL + OPT_MAX_BINLOG_DUMP_EVENTS, OPT_SPORADIC_BINLOG_DUMP_FAIL, + OPT_SQL_MODE }; static struct option long_options[] = { @@ -2604,6 +2612,7 @@ static struct option long_options[] = { {"skip-symlink", no_argument, 0, (int) OPT_SKIP_SYMLINKS}, {"skip-thread-priority", no_argument, 0, (int) OPT_SKIP_PRIOR}, {"sql-bin-update-same", no_argument, 0, (int) OPT_SQL_BIN_UPDATE_SAME}, + {"sql-mode", required_argument, 0, (int) OPT_SQL_MODE}, #include "sslopt-longopts.h" #ifdef __WIN__ {"standalone", no_argument, 0, (int) OPT_STANDALONE}, @@ -2764,7 +2773,6 @@ CHANGEABLE_VAR changeable_vars[] = { struct show_var_st init_vars[]= { - {"ansi_mode", (char*) &opt_ansi_mode, SHOW_BOOL}, {"back_log", (char*) &back_log, SHOW_LONG}, {"basedir", mysql_home, SHOW_CHAR}, #ifdef HAVE_BERKELEY_DB @@ -2866,6 +2874,7 @@ struct show_var_st init_vars[]= { {"slow_launch_time", (char*) &slow_launch_time, SHOW_LONG}, {"socket", (char*) &mysql_unix_port, SHOW_CHAR_PTR}, {"sort_buffer", (char*) &sortbuff_size, SHOW_LONG}, + {"sql_mode", (char*) &sql_mode_str, SHOW_CHAR_PTR}, {"table_cache", (char*) &table_cache_size, SHOW_LONG}, {"table_type", (char*) &default_table_type_name, SHOW_CHAR_PTR}, {"thread_cache_size", (char*) &thread_cache_size, SHOW_LONG}, @@ -3049,6 +3058,9 @@ static void usage(void) Don't give threads different priorities.\n\ --socket=... Socket file to use for connection\n\ -t, --tmpdir=path Path for temporary files\n\ + --sql-mode=option[,option[,option...]] where option can be one of:\n\ + REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES,\n\ + IGNORE_SPACE, SERIALIZE, ONLY_FULL_GROUP_BY.\n\ --transaction-isolation\n\ Default transaction isolation level\n\ --temp-pool Use a pool of temporary files\n\ @@ -3202,8 +3214,9 @@ static void get_options(int argc,char **argv) opt_warnings=1; break; case 'a': - opt_ansi_mode=1; - thd_startup_options|=OPTION_ANSI_MODE; + opt_sql_mode = (MODE_REAL_AS_FLOAT | MODE_PIPES_AS_CONCAT | + MODE_ANSI_QUOTES | MODE_IGNORE_SPACE | MODE_SERIALIZABLE + | MODE_ONLY_FULL_GROUP_BY); default_tx_isolation= ISO_SERIALIZABLE; break; case 'b': @@ -3726,6 +3739,19 @@ static void get_options(int argc,char **argv) ha_open_options|=HA_OPEN_ABORT_IF_CRASHED; break; } + case OPT_SQL_MODE: + { + sql_mode_str = optarg; + if ((opt_sql_mode = + find_bit_type(optarg, &sql_mode_typelib)) == ~(ulong) 0) + { + fprintf(stderr, "Unknown option to sql-mode: %s\n", optarg); + exit(1); + } + if (opt_sql_mode & MODE_SERIALIZABLE) + default_tx_isolation= ISO_SERIALIZABLE; + break; + } case OPT_MASTER_HOST: master_host=optarg; break; diff --git a/sql/sql_class.cc b/sql/sql_class.cc index 9ea3896fd78..efe0d7864b9 100644 --- a/sql/sql_class.cc +++ b/sql/sql_class.cc @@ -120,6 +120,7 @@ THD::THD():user_time(0),fatal_error(0),last_insert_id_used(0), server_status=SERVER_STATUS_AUTOCOMMIT; update_lock_default= low_priority_updates ? TL_WRITE_LOW_PRIORITY : TL_WRITE; options=thd_startup_options; + sql_mode=(uint) opt_sql_mode; inactive_timeout=net_wait_timeout; open_options=ha_open_options; tx_isolation=session_tx_isolation=default_tx_isolation; diff --git a/sql/sql_class.h b/sql/sql_class.h index a092de2602d..4ccbeb6f01f 100644 --- a/sql/sql_class.h +++ b/sql/sql_class.h @@ -232,7 +232,7 @@ public: char *query,*thread_stack; char *host,*user,*priv_user,*db,*ip; const char *proc_info; - uint client_capabilities,max_packet_length; + uint client_capabilities,sql_mode,max_packet_length; uint master_access,db_access; TABLE *open_tables,*temporary_tables; MYSQL_LOCK *lock,*locked_tables; diff --git a/sql/sql_lex.cc b/sql/sql_lex.cc index a78fef62657..20bda932f2f 100644 --- a/sql/sql_lex.cc +++ b/sql/sql_lex.cc @@ -121,7 +121,7 @@ void lex_init(void) state_map[(uchar)'*']= (uchar) STATE_END_LONG_COMMENT; state_map[(uchar)'@']= (uchar) STATE_USER_END; state_map[(uchar) '`']= (uchar) STATE_USER_VARIABLE_DELIMITER; - if (thd_startup_options & OPTION_ANSI_MODE) + if (opt_sql_mode & MODE_ANSI_QUOTES) { state_map[(uchar) '"'] = STATE_USER_VARIABLE_DELIMITER; } @@ -149,7 +149,7 @@ LEX *lex_start(THD *thd, uchar *buf,uint length) lex->ftfunc_list.empty(); lex->convert_set=(lex->thd=thd)->convert_set; lex->yacc_yyss=lex->yacc_yyvs=0; - lex->ignore_space=test(thd->client_capabilities & CLIENT_IGNORE_SPACE); + lex->ignore_space=test(thd->sql_mode & MODE_IGNORE_SPACE); return lex; } diff --git a/sql/sql_parse.cc b/sql/sql_parse.cc index 87fbed47ef1..1c8c917babe 100644 --- a/sql/sql_parse.cc +++ b/sql/sql_parse.cc @@ -412,6 +412,8 @@ check_connections(THD *thd) return(ER_OUT_OF_RESOURCES); thd->client_capabilities=uint2korr(net->read_pos); + if (thd->client_capabilities & CLIENT_IGNORE_SPACE) + thd->sql_mode|= MODE_IGNORE_SPACE; #ifdef HAVE_OPENSSL DBUG_PRINT("info", ("pkt_len:%d, client capabilities: %d", @@ -538,8 +540,6 @@ pthread_handler_decl(handle_one_connection,arg) thd->options |= OPTION_BIG_SELECTS; if (thd->client_capabilities & CLIENT_COMPRESS) net->compress=1; // Use compression - if (thd->options & OPTION_ANSI_MODE) - thd->client_capabilities|=CLIENT_IGNORE_SPACE; thd->proc_info=0; // Remove 'login' thd->command=COM_SLEEP; diff --git a/sql/sql_select.cc b/sql/sql_select.cc index 00f92e56b71..5c3e7516eaf 100644 --- a/sql/sql_select.cc +++ b/sql/sql_select.cc @@ -5937,7 +5937,7 @@ setup_group(THD *thd,TABLE_LIST *tables,List &fields, if (!order) return 0; /* Everything is ok */ - if (thd->options & OPTION_ANSI_MODE) + if (thd->sql_mode & MODE_ONLY_FULL_GROUP_BY) { Item *item; List_iterator li(fields); @@ -5959,7 +5959,7 @@ setup_group(THD *thd,TABLE_LIST *tables,List &fields, return 1; } } - if (thd->options & OPTION_ANSI_MODE) + if (thd->sql_mode & MODE_ONLY_FULL_GROUP_BY) { /* Don't allow one to use fields that is not used in GROUP BY */ Item *item; diff --git a/sql/sql_yacc.yy b/sql/sql_yacc.yy index c1069d91746..9ab97d52650 100644 --- a/sql/sql_yacc.yy +++ b/sql/sql_yacc.yy @@ -34,7 +34,7 @@ int yylex(void *yylval); inline Item *or_or_concat(Item* A, Item* B) { - return (current_thd->options & OPTION_ANSI_MODE ? + return (current_thd->sql_mode & MODE_PIPES_AS_CONCAT ? (Item*) new Item_func_concat(A,B) : (Item*) new Item_cond_or(A,B)); } @@ -915,7 +915,7 @@ int_type: | BIGINT { $$=FIELD_TYPE_LONGLONG; } real_type: - REAL { $$= current_thd->options & OPTION_ANSI_MODE ? + REAL { $$= current_thd->sql_mode & MODE_REAL_AS_FLOAT ? FIELD_TYPE_FLOAT : FIELD_TYPE_DOUBLE; } | DOUBLE_SYM { $$=FIELD_TYPE_DOUBLE; } | DOUBLE_SYM PRECISION { $$=FIELD_TYPE_DOUBLE; } From 799bf1cdb61e64c5e551ce6a7791df275a1f9071 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 19:10:24 +0200 Subject: [PATCH 45/51] logging_ok Logging to logging@openlogging.org accepted ltmain.sh Don't add -lc to deplibs on FreeBSD. ltmain.sh: Don't add -lc to deplibs on FreeBSD. BitKeeper/etc/logging_ok: Logging to logging@openlogging.org accepted --- BitKeeper/etc/logging_ok | 1 + ltmain.sh | 3 +++ 2 files changed, 4 insertions(+) diff --git a/BitKeeper/etc/logging_ok b/BitKeeper/etc/logging_ok index 966f7a398de..0bc2e507968 100644 --- a/BitKeeper/etc/logging_ok +++ b/BitKeeper/etc/logging_ok @@ -1 +1,2 @@ jani@hynda.mysql.fi +tim@work.mysql.com diff --git a/ltmain.sh b/ltmain.sh index eba25223e45..cebed74c167 100644 --- a/ltmain.sh +++ b/ltmain.sh @@ -1798,6 +1798,9 @@ compiler." *-*-cygwin* | *-*-mingw* | *-*-os2* | *-*-beos*) # these systems don't actually have a c library (as such)! ;; + *-*-freebsd*) + #FreeBSD needs to handle -lc and -lc_r itself + ;; *-*-rhapsody*) # rhapsody is a little odd... deplibs="$deplibs -framework System" From 5ea83eed346740875aa8d9544c111c4c3abb0136 Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 20:41:20 +0300 Subject: [PATCH 46/51] btr0cur.c Improve range size estimate for big ranges ha_innobase.cc Fix Sort aborted bug sql/ha_innobase.cc: Fix Sort aborted bug innobase/btr/btr0cur.c: Improve range size estimate for big ranges BitKeeper/etc/logging_ok: Logging to logging@openlogging.org accepted --- BitKeeper/etc/logging_ok | 1 + innobase/btr/btr0cur.c | 11 +++++++++++ sql/ha_innobase.cc | 41 +++++++++++++++++++++++++++++++++++----- 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/BitKeeper/etc/logging_ok b/BitKeeper/etc/logging_ok index 966f7a398de..10d6827b09d 100644 --- a/BitKeeper/etc/logging_ok +++ b/BitKeeper/etc/logging_ok @@ -1 +1,2 @@ jani@hynda.mysql.fi +heikki@donna.mysql.fi diff --git a/innobase/btr/btr0cur.c b/innobase/btr/btr0cur.c index e8ff88c6f4f..47a67d425cd 100644 --- a/innobase/btr/btr0cur.c +++ b/innobase/btr/btr0cur.c @@ -2351,6 +2351,7 @@ btr_estimate_n_rows_in_range( btr_path_t* slot1; btr_path_t* slot2; ibool diverged; + ulint divergence_level; ulint n_rows; ulint i; mtr_t mtr; @@ -2393,6 +2394,7 @@ btr_estimate_n_rows_in_range( n_rows = 1; diverged = FALSE; + divergence_level = 1000000; for (i = 0; ; i++) { ut_ad(i < BTR_PATH_ARRAY_N_SLOTS); @@ -2403,6 +2405,13 @@ btr_estimate_n_rows_in_range( if (slot1->nth_rec == ULINT_UNDEFINED || slot2->nth_rec == ULINT_UNDEFINED) { + if (i > divergence_level + 1) { + /* In trees whose height is > 1 our algorithm + tends to underestimate: multiply the estimate + by 2: */ + + n_rows = n_rows * 2; + } return(n_rows); } @@ -2417,6 +2426,8 @@ btr_estimate_n_rows_in_range( return(10); } + divergence_level = i; + diverged = TRUE; } else if (diverged) { n_rows = (n_rows * (slot1->n_recs + slot2->n_recs)) diff --git a/sql/ha_innobase.cc b/sql/ha_innobase.cc index 8ea700de789..7bd71363915 100644 --- a/sql/ha_innobase.cc +++ b/sql/ha_innobase.cc @@ -822,11 +822,11 @@ ha_innobase::open( if (NULL == (ib_table = dict_table_get(norm_name, NULL))) { - fprintf(stderr, "\ -Cannot find table %s from the internal data dictionary\n\ -of InnoDB though the .frm file for the table exists. Maybe you have deleted\n\ -and created again an InnoDB database but forgotten to delete the\n\ -corresponding .frm files of old InnoDB tables?\n", + fprintf(stderr, +"Cannot find table %s from the internal data dictionary\n" +"of InnoDB though the .frm file for the table exists. Maybe you have deleted\n" +"and created again an InnoDB database but forgotten to delete the\n" +"corresponding .frm files of old InnoDB tables?\n", norm_name); free_share(share); @@ -2659,6 +2659,37 @@ ha_innobase::records_in_range( DBUG_RETURN((ha_rows) n_rows); } +/************************************************************************* +Gives an UPPER BOUND to the number of rows in a table. This is used in +filesort.cc and the upper bound must hold. TODO: Since the number of +rows in a table may change after this function is called, we still may +get a 'Sort aborted' error in filesort.cc of MySQL. The ultimate fix is to +improve the algorithm of filesort.cc. */ + +ha_rows +ha_innobase::estimate_number_of_rows(void) +/*======================================*/ + /* out: upper bound of rows, currently 32-bit int + or uint */ +{ + row_prebuilt_t* prebuilt = (row_prebuilt_t*) innobase_prebuilt; + dict_table_t* ib_table; + + DBUG_ENTER("info"); + + ib_table = prebuilt->table; + + dict_update_statistics(ib_table); + + data_file_length = ((ulonglong) + ib_table->stat_clustered_index_size) + * UNIV_PAGE_SIZE; + + /* The minimum clustered index record size is 20 bytes */ + + return((ha_rows) (1000 + data_file_length / 20)); +} + /************************************************************************* How many seeks it will take to read through the table. This is to be comparable to the number returned by records_in_range so that we can From 5c3764b5abdb24400e6f5850d26bbd583a5fce3e Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 20:42:32 +0300 Subject: [PATCH 47/51] ha_innobase.h Fix Sort aborted bug sql/ha_innobase.h: Fix Sort aborted bug --- sql/ha_innobase.h | 1 + 1 file changed, 1 insertion(+) diff --git a/sql/ha_innobase.h b/sql/ha_innobase.h index 4dbff654337..d129e00ba6e 100644 --- a/sql/ha_innobase.h +++ b/sql/ha_innobase.h @@ -137,6 +137,7 @@ class ha_innobase: public handler enum ha_rkey_function start_search_flag, const byte *end_key,uint end_key_len, enum ha_rkey_function end_search_flag); + ha_rows estimate_number_of_rows(); int create(const char *name, register TABLE *form, HA_CREATE_INFO *create_info); From 75ca573a52a1c4cf3912c8d76d2b37f3cb7797ef Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 13:08:06 -0500 Subject: [PATCH 48/51] DocTOC Chapter 6 Complete! --- Docs/manual.texi | 5466 ++++++++++++++++++++++++---------------------- 1 file changed, 2835 insertions(+), 2631 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index f3ab70cf180..5f6025a757d 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -115,7 +115,6 @@ distribution for that version. * MySQL Optimization:: * Reference:: @strong{MySQL} language reference * Table types:: @strong{MySQL} table types -* Fulltext Search:: Fulltext Search * Maintenance:: Maintaining a @strong{MySQL} installation * Adding functions:: Adding new functions to @strong{MySQL} * Adding procedures:: Adding new procedures to @strong{MySQL} @@ -26594,30 +26593,6 @@ with the update log. @end menu -@node SET TRANSACTION, , SET OPTION, SET OPTION -@subsubsection @code{SET TRANSACTION} Syntax - -@findex ISOLATION LEVEL - -@example -SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL -[READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE] -@end example - -Sets the transaction isolation level for the global, whole session or -the next transaction. - -The default behavior is to set the isolation level for the next (not started) -transaction. - -If you set the @code{GLOBAL} privilege it will affect all new created threads. -You will need the @code{PROCESS} privilege to do do this. - -Setting the @code{SESSION} privilege will affect the following and all -future transactions. - -You can set the default isolation level for @code{mysqld} with -@code{--transaction-isolation=...}. @xref{Command-line options}. @node Disk issues, , Optimizing the Server, MySQL Optimization @@ -26858,7 +26833,7 @@ Things that are not yet supported: @item @code{mysqldump} doesn't include the symbolic links information in the output. @item -@code{BACKUP TABLE} and @code{RESTORE TABLE} doesn't use symbolic links. +@code{BACKUP TABLE} and @code{RESTORE TABLE} don't respect symbolic links. @end itemize @@ -26869,33 +26844,16 @@ Things that are not yet supported: @chapter MySQL Language Reference @menu -* Literals:: Literals: How to write strings and numbers +* Language Structure:: * Variables:: User variables * Column types:: Column types * Functions:: Functions -* CREATE DATABASE:: @code{CREATE DATABASE} syntax +* Data Manipulation:: +* Data Definition:: * DROP DATABASE:: @code{DROP DATABASE} syntax -* CREATE TABLE:: @code{CREATE TABLE} syntax -* ALTER TABLE:: @code{ALTER TABLE} syntax -* RENAME TABLE:: @code{RENAME TABLE} syntax -* DROP TABLE:: @code{DROP TABLE} syntax -* DELETE:: @code{DELETE} syntax -* TRUNCATE:: @code{TRUNCATE} syntax -* SELECT:: @code{SELECT} syntax -* JOIN:: @code{JOIN} syntax -* INSERT:: @code{INSERT} syntax -* REPLACE:: @code{REPLACE} syntax -* LOAD DATA:: @code{LOAD DATA INFILE} syntax -* UPDATE:: @code{UPDATE} syntax -* USE:: @code{USE} syntax -* DESCRIBE:: @code{DESCRIBE} syntax (Get information about names of columns) -* COMMIT:: @code{BEGIN/COMMIT/ROLLBACK} syntax -* LOCK TABLES:: @code{LOCK TABLES/UNLOCK TABLES} syntax -* CREATE INDEX:: @code{CREATE INDEX} syntax -* DROP INDEX:: @code{DROP INDEX} syntax -* Comments:: Comment syntax -* CREATE FUNCTION:: @code{CREATE FUNCTION} syntax -* Reserved words:: Is @strong{MySQL} picky about reserved words? +* Basic User Commands:: +* Transactional Commands:: +* Fulltext Search:: @end menu @strong{MySQL} has a very complex, but intuitive and easy to learn SQL @@ -26906,8 +26864,18 @@ included in @strong{MySQL}. In order to use this chapter effectively, you may find it useful to refer to the various indexes. -@node Literals, Variables, Reference, Reference -@section Literals: How to Write Strings and Numbers +@node Language Structure, Variables, Reference, Reference +@section Language Structure + +@menu +* Literals:: +* Legal names:: +* Name case sensitivity:: +@end menu + + +@node Literals, Legal names, Language Structure, Language Structure +@subsection Literals: How to Write Strings and Numbers @cindex strings, defined @cindex strings, escaping characters @@ -26920,15 +26888,16 @@ may find it useful to refer to the various indexes. * Number syntax:: Numbers * Hexadecimal values:: Hexadecimal values * NULL values:: @code{NULL} values -* Legal names:: Database, Table, Index, Column, and Alias Names @end menu + This section describes the various ways to write strings and numbers in @strong{MySQL}. It also covers the various nuances and ``gotchas'' that you may run into when dealing with these basic types in @strong{MySQL}. + @node String syntax, Number syntax, Literals, Literals -@subsection Strings +@subsubsection Strings A string is a sequence of characters, surrounded by either single quote (@samp{'}) or double quote (@samp{"}) characters (only the single quote @@ -27085,13 +27054,15 @@ characters to the proper escape sequences. @xref{Perl DBI Class, , Perl You should use an escape function on any string that might contain any of the special characters listed above! + +@node Number syntax, Hexadecimal values, String syntax, Literals +@subsubsection Numbers + @cindex numbers @cindex valid numbers, examples @cindex integers @cindex floats @cindex negative values -@node Number syntax, Hexadecimal values, String syntax, Literals -@subsection Numbers Integers are represented as a sequence of digits. Floats use @samp{.} as a decimal separator. Either type of number may be preceded by @samp{-} to @@ -27116,9 +27087,11 @@ Examples of valid floating-point numbers: An integer may be used in a floating-point context; it is interpreted as the equivalent floating-point number. -@tindex hexadecimal values + @node Hexadecimal values, NULL values, Number syntax, Literals -@subsection Hexadecimal Values +@subsubsection Hexadecimal Values + +@tindex hexadecimal values @strong{MySQL} supports hexadecimal values. In number context these act like an integer (64-bit precision). In string context these act like a binary @@ -27133,9 +27106,11 @@ mysql> select 0x5061756c; Hexadecimal strings are often used by ODBC to give values for BLOB columns. + +@node NULL values, , Hexadecimal values, Literals +@subsubsection @code{NULL} Values + @tindex NULL value -@node NULL values, Legal names, Hexadecimal values, Literals -@subsection @code{NULL} Values The @code{NULL} value means ``no data'' and is different from values such as @code{0} for numeric types or the empty string for string types. @@ -27145,6 +27120,10 @@ as @code{0} for numeric types or the empty string for string types. or export formats (@code{LOAD DATA INFILE}, @code{SELECT ... INTO OUTFILE}). @xref{LOAD DATA, , @code{LOAD DATA}}. + +@node Legal names, Name case sensitivity, Literals, Language Structure +@subsection Database, Table, Index, Column, and Alias Names + @cindex names @cindex legal names @cindex databases, names @@ -27152,13 +27131,12 @@ or export formats (@code{LOAD DATA INFILE}, @code{SELECT ... INTO OUTFILE}). @cindex indexes, names @cindex columns, names @cindex aliases, names -@node Legal names, , NULL values, Literals -@subsection Database, Table, Index, Column, and Alias Names @menu * Name case sensitivity:: Case sensitivity in names @end menu + Database, table, index, column, and alias names all follow the same rules in @strong{MySQL}. @@ -27245,10 +27223,12 @@ The syntax @code{.tbl_name} means the table @code{tbl_name} in the current database. This syntax is accepted for ODBC compatibility, because some ODBC programs prefix table names with a @samp{.} character. + +@node Name case sensitivity, , Legal names, Language Structure +@subsection Case Sensitivity in Names + @cindex names, case-sensitivity @cindex case-sensitivity, in names -@node Name case sensitivity, , Legal names, Legal names -@subsubsection Case Sensitivity in Names @cindex database names, case sensitivity @cindex table names, case sensitivity @cindex column names, case sensitivity @@ -27294,11 +27274,13 @@ table names to lower case on storage and lookup. Note that if you change this option, you need to first convert your old table names to lower case before starting @code{mysqld}. + +@node Variables, Column types, Language Structure, Reference +@section User Variables + @cindex variables, user @cindex user variables @cindex names, variables -@node Variables, Column types, Literals, Reference -@section User Variables @strong{MySQL} supports thread-specific variables with the @code{@@variablename} syntax. A variable name may consist of @@ -27352,11 +27334,184 @@ SELECT (@@aa:=id) AS a, (@@aa+3) AS b FROM table_name HAVING b=5; The reason is that @code{@@aa} will not contain the value of the current row, but the value of @code{id} for the previous accepted row. -@cindex columns, types -@cindex types, columns + +@menu +* Comments:: +* Reserved words:: +@end menu + +@node Comments, Reserved words, Variables, Variables +@subsection Comment Syntax + +@findex Comment syntax + +@cindex comments, adding + +The @strong{MySQL} server supports the @code{# to end of line}, @code{-- +to end of line} and @code{/* in-line or multiple-line */} comment +styles: + +@example +mysql> select 1+1; # This comment continues to the end of line +mysql> select 1+1; -- This comment continues to the end of line +mysql> select 1 /* this is an in-line comment */ + 1; +mysql> select 1+ +/* +this is a +multiple-line comment +*/ +1; +@end example + +Note that the @code{--} comment style requires you to have at least one space +after the @code{--}! + +Although the server understands the comment syntax just described, +there are some limitations on the way that the @code{mysql} client +parses @code{/* ... */} comments: + +@itemize @bullet +@item +Single-quote and double-quote characters are taken to indicate the beginning +of a quoted string, even within a comment. If the quote is not matched by a +second quote within the comment, the parser doesn't realize the comment has +ended. If you are running @code{mysql} interactively, you can tell that it +has gotten confused like this because the prompt changes from @code{mysql>} +to @code{'>} or @code{">}. + +@item +A semicolon is taken to indicate the end of the current SQL statement +and anything following it to indicate the beginning of the next statement. +@end itemize + +These limitations apply both when you run @code{mysql} interactively +and when you put commands in a file and tell @code{mysql} to read its +input from that file with @code{mysql < some-file}. + +@strong{MySQL} doesn't support the @samp{--} ANSI SQL comment style. +@xref{Missing comments}. + + +@node Reserved words, , Comments, Variables +@subsection Is MySQL Picky About Reserved Words? + +@cindex keywords +@cindex reserved words, exceptions + +A common problem stems from trying to create a table with column names that +use the names of datatypes or functions built into @strong{MySQL}, such as +@code{TIMESTAMP} or @code{GROUP}. You're allowed to do it (for example, +@code{ABS} is an allowed column name), but whitespace is not allowed between +a function name and the @samp{(} when using functions whose names are also +column names. + +The following words are explicitly reserved in @strong{MySQL}. Most of +them are forbidden by ANSI SQL92 as column and/or table names +(for example, @code{group}). +A few are reserved because @strong{MySQL} needs them and is +(currently) using a @code{yacc} parser: + +@c This is fixed by including the symbols table from lex.h here and then running +@c fix-mysql-reserved-words in emacs (or let David do it): +@c (defun fix-mysql-reserved-words () +@c (interactive) +@c (let ((cnt 0)) +@c (insert "\n@item ") +@c (while (looking-at "[ \t]*{ +\"\\([^\"]+\\)\"[ \t]*,.*\n") +@c (replace-match "@code{\\1}") +@c (incf cnt) +@c (if (> cnt 3) +@c (progn +@c (setf cnt 0) +@c (insert "\n@item ")) +@c (insert " @tab "))))) +@c But remove the non alphanumeric entries by hand first. +@c Updated after 3.23.4 990928 by David + +@multitable @columnfractions .25 .25 .25 .25 +@item @code{action} @tab @code{add} @tab @code{aggregate} @tab @code{all} +@item @code{alter} @tab @code{after} @tab @code{and} @tab @code{as} +@item @code{asc} @tab @code{avg} @tab @code{avg_row_length} @tab @code{auto_increment} +@item @code{between} @tab @code{bigint} @tab @code{bit} @tab @code{binary} +@item @code{blob} @tab @code{bool} @tab @code{both} @tab @code{by} +@item @code{cascade} @tab @code{case} @tab @code{char} @tab @code{character} +@item @code{change} @tab @code{check} @tab @code{checksum} @tab @code{column} +@item @code{columns} @tab @code{comment} @tab @code{constraint} @tab @code{create} +@item @code{cross} @tab @code{current_date} @tab @code{current_time} @tab @code{current_timestamp} +@item @code{data} @tab @code{database} @tab @code{databases} @tab @code{date} +@item @code{datetime} @tab @code{day} @tab @code{day_hour} @tab @code{day_minute} +@item @code{day_second} @tab @code{dayofmonth} @tab @code{dayofweek} @tab @code{dayofyear} +@item @code{dec} @tab @code{decimal} @tab @code{default} @tab @code{delayed} +@item @code{delay_key_write} @tab @code{delete} @tab @code{desc} @tab @code{describe} +@item @code{distinct} @tab @code{distinctrow} @tab @code{double} @tab @code{drop} +@item @code{end} @tab @code{else} @tab @code{escape} @tab @code{escaped} +@item @code{enclosed} @tab @code{enum} @tab @code{explain} @tab @code{exists} +@item @code{fields} @tab @code{file} @tab @code{first} @tab @code{float} +@item @code{float4} @tab @code{float8} @tab @code{flush} @tab @code{foreign} +@item @code{from} @tab @code{for} @tab @code{full} @tab @code{function} +@item @code{global} @tab @code{grant} @tab @code{grants} @tab @code{group} +@item @code{having} @tab @code{heap} @tab @code{high_priority} @tab @code{hour} +@item @code{hour_minute} @tab @code{hour_second} @tab @code{hosts} @tab @code{identified} +@item @code{ignore} @tab @code{in} @tab @code{index} @tab @code{infile} +@item @code{inner} @tab @code{insert} @tab @code{insert_id} @tab @code{int} +@item @code{integer} @tab @code{interval} @tab @code{int1} @tab @code{int2} +@item @code{int3} @tab @code{int4} @tab @code{int8} @tab @code{into} +@item @code{if} @tab @code{is} @tab @code{isam} @tab @code{join} +@item @code{key} @tab @code{keys} @tab @code{kill} @tab @code{last_insert_id} +@item @code{leading} @tab @code{left} @tab @code{length} @tab @code{like} +@item @code{lines} @tab @code{limit} @tab @code{load} @tab @code{local} +@item @code{lock} @tab @code{logs} @tab @code{long} @tab @code{longblob} +@item @code{longtext} @tab @code{low_priority} @tab @code{max} @tab @code{max_rows} +@item @code{match} @tab @code{mediumblob} @tab @code{mediumtext} @tab @code{mediumint} +@item @code{middleint} @tab @code{min_rows} @tab @code{minute} @tab @code{minute_second} +@item @code{modify} @tab @code{month} @tab @code{monthname} @tab @code{myisam} +@item @code{natural} @tab @code{numeric} @tab @code{no} @tab @code{not} +@item @code{null} @tab @code{on} @tab @code{optimize} @tab @code{option} +@item @code{optionally} @tab @code{or} @tab @code{order} @tab @code{outer} +@item @code{outfile} @tab @code{pack_keys} @tab @code{partial} @tab @code{password} +@item @code{precision} @tab @code{primary} @tab @code{procedure} @tab @code{process} +@item @code{processlist} @tab @code{privileges} @tab @code{read} @tab @code{real} +@item @code{references} @tab @code{reload} @tab @code{regexp} @tab @code{rename} +@item @code{replace} @tab @code{restrict} @tab @code{returns} @tab @code{revoke} +@item @code{rlike} @tab @code{row} @tab @code{rows} @tab @code{second} +@item @code{select} @tab @code{set} @tab @code{show} @tab @code{shutdown} +@item @code{smallint} @tab @code{soname} @tab @code{sql_big_tables} @tab @code{sql_big_selects} +@item @code{sql_low_priority_updates} @tab @code{sql_log_off} @tab @code{sql_log_update} @tab @code{sql_select_limit} +@item @code{sql_small_result} @tab @code{sql_big_result} @tab @code{sql_warnings} @tab @code{straight_join} +@item @code{starting} @tab @code{status} @tab @code{string} @tab @code{table} +@item @code{tables} @tab @code{temporary} @tab @code{terminated} @tab @code{text} +@item @code{then} @tab @code{time} @tab @code{timestamp} @tab @code{tinyblob} +@item @code{tinytext} @tab @code{tinyint} @tab @code{trailing} @tab @code{to} +@item @code{type} @tab @code{use} @tab @code{using} @tab @code{unique} +@item @code{unlock} @tab @code{unsigned} @tab @code{update} @tab @code{usage} +@item @code{values} @tab @code{varchar} @tab @code{variables} @tab @code{varying} +@item @code{varbinary} @tab @code{with} @tab @code{write} @tab @code{when} +@item @code{where} @tab @code{year} @tab @code{year_month} @tab @code{zerofill} +@end multitable + +The following symbols (from the table above) are disallowed by ANSI SQL +but allowed by @strong{MySQL} as column/table names. This is because some +of these names are very natural names and a lot of people have already +used them. + +@itemize @bullet +@item @code{ACTION} +@item @code{BIT} +@item @code{DATE} +@item @code{ENUM} +@item @code{NO} +@item @code{TEXT} +@item @code{TIME} +@item @code{TIMESTAMP} +@end itemize + + @node Column types, Functions, Variables, Reference @section Column Types +@cindex columns, types +@cindex types, columns + @strong{MySQL} supports a number of column types, which may be grouped into three categories: numeric types, date and time types, and string (character) types. This section first gives an overview of the types available and @@ -27682,116 +27837,16 @@ be chosen from the list of values @code{'value1'}, @code{'value2'}, @end table @menu -* Storage requirements:: Column type storage requirements * Numeric types:: Numeric types * Date and time types:: Date and time types * String types:: String types * Choosing types:: Choosing the right type for a column * Other-vendor column types:: Using column types from other database engines +* Storage requirements:: Column type storage requirements @end menu -@cindex storage requirements, column type -@cindex columns, storage requirements -@node Storage requirements, Numeric types, Column types, Column types -@subsection Column Type Storage Requirements - -The storage requirements for each of the column types supported by -@strong{MySQL} are listed below by category. - -@cindex numeric types -@cindex types, numeric - -@subsubheading Storage requirements for numeric types - -@multitable @columnfractions .5 .5 -@item @strong{Column type} @tab @strong{Storage required} -@item @code{TINYINT} @tab 1 byte -@item @code{SMALLINT} @tab 2 bytes -@item @code{MEDIUMINT} @tab 3 bytes -@item @code{INT} @tab 4 bytes -@item @code{INTEGER} @tab 4 bytes -@item @code{BIGINT} @tab 8 bytes -@item @code{FLOAT(X)} @tab 4 if X <= 24 or 8 if 25 <= X <= 53 -@item @code{FLOAT} @tab 4 bytes -@item @code{DOUBLE} @tab 8 bytes -@item @code{DOUBLE PRECISION} @tab 8 bytes -@item @code{REAL} @tab 8 bytes -@item @code{DECIMAL(M,D)} @tab @code{M+2} bytes if D > 0, @code{M+1} bytes if D = 0 (@code{D}+2, if @code{M < D}) -@item @code{NUMERIC(M,D)} @tab @code{M+2} bytes if D > 0, @code{M+1} bytes if D = 0 (@code{D}+2, if @code{M < D}) -@end multitable - -@cindex date types -@cindex time types -@cindex types, date -@cindex types, time - -@subsubheading Storage requirements for date and time types - -@multitable @columnfractions .5 .5 -@item @strong{Column type} @tab @strong{Storage required} -@item @code{DATE} @tab 3 bytes -@item @code{DATETIME} @tab 8 bytes -@item @code{TIMESTAMP} @tab 4 bytes -@item @code{TIME} @tab 3 bytes -@item @code{YEAR} @tab 1 byte -@end multitable - -@subsubheading Storage requirements for string types - -@multitable @columnfractions .5 .5 -@item @strong{Column type} @tab @strong{Storage required} -@item @code{CHAR(M)} @tab @code{M} bytes, @code{1 <= M <= 255} -@item @code{VARCHAR(M)} @tab @code{L}+1 bytes, where @code{L <= M} and -@code{1 <= M <= 255} -@item @code{TINYBLOB}, @code{TINYTEXT} @tab @code{L}+1 bytes, -where @code{L} < 2^8 -@item @code{BLOB}, @code{TEXT} @tab @code{L}+2 bytes, -where @code{L} < 2^16 -@item @code{MEDIUMBLOB}, @code{MEDIUMTEXT} @tab @code{L}+3 bytes, -where @code{L} < 2^24 -@item @code{LONGBLOB}, @code{LONGTEXT} @tab @code{L}+4 bytes, -where @code{L} < 2^32 -@item @code{ENUM('value1','value2',...)} @tab 1 or 2 bytes, depending on -the number of enumeration values (65535 values maximum) -@item @code{SET('value1','value2',...)} @tab 1, 2, 3, 4 or 8 bytes, depending -on the number of set members (64 members maximum) -@end multitable - -@cindex BLOB, size -@cindex TEXT, size -@cindex VARCHAR, size -@code{VARCHAR} and the @code{BLOB} and @code{TEXT} types are variable-length -types, for which the storage requirements depend on the actual length of -column values (represented by @code{L} in the preceding table), rather than -on the type's maximum possible size. For example, a @code{VARCHAR(10)} -column can hold a string with a maximum length of 10 characters. The actual -storage required is the length of the string (@code{L}), plus 1 byte to -record the length of the string. For the string @code{'abcd'}, @code{L} is 4 -and the storage requirement is 5 bytes. - -The @code{BLOB} and @code{TEXT} types require 1, 2, 3, or 4 bytes to record -the length of the column value, depending on the maximum possible length of -the type. @xref{BLOB}. - -If a table includes any variable-length column types, the record format will -also be variable-length. Note that when a table is created, @strong{MySQL} -may, under certain conditions, change a column from a variable-length type to a -fixed-length type, or vice-versa. @xref{Silent column changes}. - -@cindex ENUM, size -The size of an @code{ENUM} object is determined by the number of -different enumeration values. One byte is used for enumerations with up -to 255 possible values. Two bytes are used for enumerations with up to -65535 values. @xref{ENUM}. - -@cindex SET, size -The size of a @code{SET} object is determined by the number of different -set members. If the set size is @code{N}, the object occupies @code{(N+7)/8} -bytes, rounded up to 1, 2, 3, 4, or 8 bytes. A @code{SET} can have a maximum -of 64 members. @xref{SET}. - -@node Numeric types, Date and time types, Storage requirements, Column types +@node Numeric types, Date and time types, Column types, Column types @subsection Numeric Types @strong{MySQL} supports all of the ANSI/ISO SQL92 numeric types. These @@ -27917,11 +27972,13 @@ Conversions that occur due to clipping are reported as ``warnings'' for @code{ALTER TABLE}, @code{LOAD DATA INFILE}, @code{UPDATE}, and multi-row @code{INSERT} statements. -@cindex types, Date and Time -@cindex Date and Time types + @node Date and time types, String types, Numeric types, Column types @subsection Date and Time Types +@cindex types, Date and Time +@cindex Date and Time types + @menu * Y2K issues:: Y2K issues and date types * DATETIME:: The @code{DATETIME}, @code{DATE} and @code{TIMESTAMP} types @@ -27929,6 +27986,7 @@ multi-row @code{INSERT} statements. * YEAR:: The @code{YEAR} type @end menu + The date and time types are @code{DATETIME}, @code{DATE}, @code{TIMESTAMP}, @code{TIME}, and @code{YEAR}. Each of these has a range of legal values, as well as a ``zero'' value that is used when you @@ -27998,11 +28056,13 @@ automatically to @code{NULL} in @strong{MyODBC} Version 2.50.12 and above, because ODBC can't handle such values. @end itemize -@cindex Year 2000 issues -@cindex date types, Y2K issues + @node Y2K issues, DATETIME, Date and time types, Date and time types @subsubsection Y2K Issues and Date Types +@cindex Year 2000 issues +@cindex date types, Y2K issues + @strong{MySQL} itself is Y2K-safe (@pxref{Year 2000 compliance}), but input values presented to @strong{MySQL} may not be. Any input containing 2-digit year values is ambiguous, because the century is unknown. @@ -28034,11 +28094,13 @@ Note also that some functions like @code{MIN()} and @code{MAX()} will convert a case is to convert the @code{TIMESTAMP/DATE} to 4-digit year format or use something like @code{MIN(DATE_ADD(timestamp,INTERVAL 0 DAYS))}. + +@node DATETIME, TIME, Y2K issues, Date and time types +@subsubsection The @code{DATETIME}, @code{DATE}, and @code{TIMESTAMP} Types + @tindex DATETIME @tindex DATE @tindex TIMESTAMP -@node DATETIME, TIME, Y2K issues, Date and time types -@subsubsection The @code{DATETIME}, @code{DATE}, and @code{TIMESTAMP} Types The @code{DATETIME}, @code{DATE}, and @code{TIMESTAMP} types are related. This section describes their characteristics, how they are similar, and how @@ -28295,10 +28357,12 @@ Year values in the range @code{70-99} are converted to @code{1970-1999}. @end itemize @end itemize -@tindex TIME + @node TIME, YEAR, DATETIME, Date and time types @subsubsection The @code{TIME} Type +@tindex TIME + @strong{MySQL} retrieves and displays @code{TIME} values in @code{'HH:MM:SS'} format (or @code{'HHH:MM:SS'} format for large hours values). @code{TIME} values may range from @code{'-838:59:59'} to @code{'838:59:59'}. The reason @@ -28364,10 +28428,12 @@ because @code{'00:00:00'} is itself a legal @code{TIME} value, there is no way to tell, from a value of @code{'00:00:00'} stored in a table, whether the original value was specified as @code{'00:00:00'} or whether it was illegal. -@tindex YEAR + @node YEAR, , TIME, Date and time types @subsubsection The @code{YEAR} Type +@tindex YEAR + The @code{YEAR} type is a 1-byte type used for representing years. @strong{MySQL} retrieves and displays @code{YEAR} values in @code{YYYY} @@ -28405,13 +28471,16 @@ in a @code{YEAR} context, such as @code{NOW()}. Illegal @code{YEAR} values are converted to @code{0000}. -@cindex types, strings -@cindex string types + @node String types, Choosing types, Date and time types, Column types @subsection String Types +@cindex types, strings +@cindex string types + @tindex CHAR @tindex VARCHAR + @menu * CHAR:: The @code{CHAR} and @code{VARCHAR} types * BLOB:: The @code{BLOB} and @code{TEXT} types @@ -28419,10 +28488,12 @@ Illegal @code{YEAR} values are converted to @code{0000}. * SET:: The @code{SET} type @end menu + The string types are @code{CHAR}, @code{VARCHAR}, @code{BLOB}, @code{TEXT}, @code{ENUM}, and @code{SET}. This section describes how these types work, their storage requirements, and how to use them in your queries. + @node CHAR, BLOB, String types, String types @subsubsection The @code{CHAR} and @code{VARCHAR} Types @@ -28482,11 +28553,13 @@ The @code{BINARY} attribute is sticky. This means that if a column marked column at table creation time. @xref{Silent column changes}. -@tindex BLOB -@tindex TEXT + @node BLOB, ENUM, CHAR, String types @subsubsection The @code{BLOB} and @code{TEXT} Types +@tindex BLOB +@tindex TEXT + A @code{BLOB} is a binary large object that can hold a variable amount of data. The four @code{BLOB} types @code{TINYBLOB}, @code{BLOB}, @code{MEDIUMBLOB}, and @code{LONGBLOB} differ only in the maximum length of @@ -28569,10 +28642,12 @@ internally by a separately allocated object. This is in contrast to all other column types, for which storage is allocated once per column when the table is opened. -@tindex ENUM + @node ENUM, SET, BLOB, String types @subsubsection The @code{ENUM} Type +@tindex ENUM + An @code{ENUM} is a string object whose value normally is chosen from a list of allowed values that are enumerated explicitly in the column specification at table creation time. @@ -28656,10 +28731,12 @@ If you want to get all possible values for an @code{ENUM} column, you should use: @code{SHOW COLUMNS FROM table_name LIKE enum_column_name} and parse the @code{ENUM} definition in the second column. -@tindex SET + @node SET, , ENUM, String types @subsubsection The @code{SET} Type +@tindex SET + A @code{SET} is a string object that can have zero or more values, each of which must be chosen from a list of allowed values specified when the table is created. @code{SET} column values that consist of multiple set members @@ -28741,11 +28818,13 @@ If you want to get all possible values for a @code{SET} column, you should use: @code{SHOW COLUMNS FROM table_name LIKE set_column_name} and parse the @code{SET} definition in the second column. -@cindex types, columns -@cindex choosing types + @node Choosing types, Other-vendor column types, String types, Column types @subsection Choosing the Right Type for a Column +@cindex types, columns +@cindex choosing types + For the most efficient use of storage, try to use the most precise type in all cases. For example, if an integer column will be used for values in the range between @code{1} and @code{99999}, @code{MEDIUMINT UNSIGNED} is the @@ -28761,7 +28840,7 @@ in a @code{BIGINT}. This allows you to do all calculations with integers and convert results back to floating-point values only when necessary. -@node Other-vendor column types, , Choosing types, Column types +@node Other-vendor column types, Storage requirements, Choosing types, Column types @subsection Using Column Types from Other Database Engines @cindex types, portability @@ -28795,10 +28874,114 @@ with types used by other vendors and then issue a @code{DESCRIBE tbl_name} statement, @strong{MySQL} reports the table structure using the equivalent @strong{MySQL} types. -@cindex functions for @code{SELECT} and @code{WHERE} clauses -@node Functions, CREATE DATABASE, Column types, Reference + +@node Storage requirements, , Other-vendor column types, Column types +@subsection Column Type Storage Requirements + +@cindex storage requirements, column type +@cindex columns, storage requirements + +The storage requirements for each of the column types supported by +@strong{MySQL} are listed below by category. + +@cindex numeric types +@cindex types, numeric + +@subsubheading Storage requirements for numeric types + +@multitable @columnfractions .5 .5 +@item @strong{Column type} @tab @strong{Storage required} +@item @code{TINYINT} @tab 1 byte +@item @code{SMALLINT} @tab 2 bytes +@item @code{MEDIUMINT} @tab 3 bytes +@item @code{INT} @tab 4 bytes +@item @code{INTEGER} @tab 4 bytes +@item @code{BIGINT} @tab 8 bytes +@item @code{FLOAT(X)} @tab 4 if X <= 24 or 8 if 25 <= X <= 53 +@item @code{FLOAT} @tab 4 bytes +@item @code{DOUBLE} @tab 8 bytes +@item @code{DOUBLE PRECISION} @tab 8 bytes +@item @code{REAL} @tab 8 bytes +@item @code{DECIMAL(M,D)} @tab @code{M+2} bytes if D > 0, @code{M+1} bytes if D = 0 (@code{D}+2, if @code{M < D}) +@item @code{NUMERIC(M,D)} @tab @code{M+2} bytes if D > 0, @code{M+1} bytes if D = 0 (@code{D}+2, if @code{M < D}) +@end multitable + +@cindex date types +@cindex time types +@cindex types, date +@cindex types, time + +@subsubheading Storage requirements for date and time types + +@multitable @columnfractions .5 .5 +@item @strong{Column type} @tab @strong{Storage required} +@item @code{DATE} @tab 3 bytes +@item @code{DATETIME} @tab 8 bytes +@item @code{TIMESTAMP} @tab 4 bytes +@item @code{TIME} @tab 3 bytes +@item @code{YEAR} @tab 1 byte +@end multitable + +@subsubheading Storage requirements for string types + +@multitable @columnfractions .5 .5 +@item @strong{Column type} @tab @strong{Storage required} +@item @code{CHAR(M)} @tab @code{M} bytes, @code{1 <= M <= 255} +@item @code{VARCHAR(M)} @tab @code{L}+1 bytes, where @code{L <= M} and +@code{1 <= M <= 255} +@item @code{TINYBLOB}, @code{TINYTEXT} @tab @code{L}+1 bytes, +where @code{L} < 2^8 +@item @code{BLOB}, @code{TEXT} @tab @code{L}+2 bytes, +where @code{L} < 2^16 +@item @code{MEDIUMBLOB}, @code{MEDIUMTEXT} @tab @code{L}+3 bytes, +where @code{L} < 2^24 +@item @code{LONGBLOB}, @code{LONGTEXT} @tab @code{L}+4 bytes, +where @code{L} < 2^32 +@item @code{ENUM('value1','value2',...)} @tab 1 or 2 bytes, depending on +the number of enumeration values (65535 values maximum) +@item @code{SET('value1','value2',...)} @tab 1, 2, 3, 4 or 8 bytes, depending +on the number of set members (64 members maximum) +@end multitable + +@cindex BLOB, size +@cindex TEXT, size +@cindex VARCHAR, size +@code{VARCHAR} and the @code{BLOB} and @code{TEXT} types are variable-length +types, for which the storage requirements depend on the actual length of +column values (represented by @code{L} in the preceding table), rather than +on the type's maximum possible size. For example, a @code{VARCHAR(10)} +column can hold a string with a maximum length of 10 characters. The actual +storage required is the length of the string (@code{L}), plus 1 byte to +record the length of the string. For the string @code{'abcd'}, @code{L} is 4 +and the storage requirement is 5 bytes. + +The @code{BLOB} and @code{TEXT} types require 1, 2, 3, or 4 bytes to record +the length of the column value, depending on the maximum possible length of +the type. @xref{BLOB}. + +If a table includes any variable-length column types, the record format will +also be variable-length. Note that when a table is created, @strong{MySQL} +may, under certain conditions, change a column from a variable-length type to a +fixed-length type, or vice-versa. @xref{Silent column changes}. + +@cindex ENUM, size +The size of an @code{ENUM} object is determined by the number of +different enumeration values. One byte is used for enumerations with up +to 255 possible values. Two bytes are used for enumerations with up to +65535 values. @xref{ENUM}. + +@cindex SET, size +The size of a @code{SET} object is determined by the number of different +set members. If the set size is @code{N}, the object occupies @code{(N+7)/8} +bytes, rounded up to 1, 2, 3, 4, or 8 bytes. A @code{SET} can have a maximum +of 64 members. @xref{SET}. + + +@node Functions, Data Manipulation, Column types, Reference @section Functions for Use in @code{SELECT} and @code{WHERE} Clauses +@cindex functions for @code{SELECT} and @code{WHERE} clauses + A @code{select_expression} or @code{where_definition} in a SQL statement can consist of any expression using the functions described below. @@ -28840,229 +29023,57 @@ mysql> select MOD(29,9); @end example @menu -* Grouping functions:: Grouping functions -* Arithmetic functions:: Normal arithmetic operations -* Bit functions:: Bit functions -* Logical functions:: Logical operations -* Comparison functions:: Comparison operators -* String comparison functions:: String comparison functions -* Casts:: Cast operators -* Control flow functions:: Control flow functions -* Mathematical functions:: Mathematical functions +* Non-typed Operators:: * String functions:: String functions +* Numeric Functions:: * Date and time functions:: Date and time functions -* Miscellaneous functions:: Miscellaneous functions -* Group by functions:: Functions for @code{GROUP BY} clause +* Other Functions:: @end menu -@cindex functions, grouping -@cindex grouping, expressions -@node Grouping functions, Arithmetic functions, Functions, Functions -@subsection Grouping Functions -@table @code + +@node Non-typed Operators, String functions, Functions, Functions +@subsection Non-Type-Specific Operators and Functions + +@menu +* Parenthesis:: +* Comparison Operators:: +* Logical Operators:: +* Control flow functions:: +@end menu + + +@node Parenthesis, Comparison Operators, Non-typed Operators, Non-typed Operators +@subsubsection Parenthesis @findex () (parentheses) @findex parentheses ( and ) -@item ( ... ) -Parentheses. Use these to force the order of evaluation in an expression: + +@cindex functions, grouping +@cindex grouping, expressions + +@example +( ... ) +@end example + +Use parenthesis to force the order of evaluation in an expression. For +example: + @example mysql> select 1+2*3; -> 7 mysql> select (1+2)*3; -> 9 @end example -@end table -@node Arithmetic functions, Bit functions, Grouping functions, Functions -@subsection Normal Arithmetic Operations -The usual arithmetic operators are available. Note that in the case of -@samp{-}, @samp{+}, and @samp{*}, the result is calculated with -@code{BIGINT} (64-bit) precision if both arguments are integers! -@cindex operations, arithmetic -@cindex arithmetic expressions -@table @code -@findex + (addition) -@findex addition (+) -@item + -Addition: -@example -mysql> select 3+5; - -> 8 -@end example +@node Comparison Operators, Logical Operators, Parenthesis, Non-typed Operators +@subsubsection Comparison Operators -@findex - (subtraction) -@findex subtraction (-) -@item - -Subtraction: -@example -mysql> select 3-5; - -> -2 -@end example - -@findex * (multiplication) -@findex multiplication (*) -@item * -Multiplication: -@example -mysql> select 3*5; - -> 15 -mysql> select 18014398509481984*18014398509481984.0; - -> 324518553658426726783156020576256.0 -mysql> select 18014398509481984*18014398509481984; - -> 0 -@end example - -The result of the last expression is incorrect because the result of the integer -multiplication exceeds the 64-bit range of @code{BIGINT} calculations. - -@findex / (division) -@findex division (/) -@item / -Division: -@example -mysql> select 3/5; - -> 0.60 -@end example - -Division by zero produces a @code{NULL} result: - -@example -mysql> select 102/(1-1); - -> NULL -@end example - -A division will be calculated with @code{BIGINT} arithmetic only if performed -in a context where its result is converted to an integer! -@end table - -@findex arithmetic functions -@findex bit functions -@findex functions, arithmetic -@findex functions, bit -@node Bit functions, Logical functions, Arithmetic functions, Functions -@subsection Bit Functions - -@strong{MySQL} uses @code{BIGINT} (64-bit) arithmetic for bit operations, so -these operators have a maximum range of 64 bits. - -@table @code -@findex | (bitwise OR) -@findex OR, bitwise -@item | -Bitwise OR: -@example -mysql> select 29 | 15; - -> 31 -@end example - -@findex & (bitwise AND) -@findex AND, bitwise -@item & -Bitwise AND: -@example -mysql> select 29 & 15; - -> 13 -@end example - -@findex << (left shift) -@item << -Shifts a longlong (@code{BIGINT}) number to the left: -@example -mysql> select 1 << 2; - -> 4 -@end example - -@findex >> (right shift) -@item >> -Shifts a longlong (@code{BIGINT}) number to the right: -@example -mysql> select 4 >> 2; - -> 1 -@end example - -@findex ~ -@item ~ -Invert all bits: -@example -mysql> select 5 & ~1; - -> 4 -@end example - -@findex BIT_COUNT() -@item BIT_COUNT(N) -Returns the number of bits that are set in the argument @code{N}: -@example -mysql> select BIT_COUNT(29); - -> 4 -@end example -@end table - -@findex Logical functions -@findex Functions, logical -@node Logical functions, Comparison functions, Bit functions, Functions -@subsection Logical Operations - -All logical functions return @code{1} (TRUE), @code{0} (FALSE) or -@code{NULL} (unknown, which is in most cases the same as FALSE): - -@table @code -@findex NOT, logical -@findex ! (logical NOT) -@item NOT -@itemx ! -Logical NOT. Returns @code{1} if the argument is @code{0}, otherwise returns -@code{0}. -Exception: @code{NOT NULL} returns @code{NULL}: -@example -mysql> select NOT 1; - -> 0 -mysql> select NOT NULL; - -> NULL -mysql> select ! (1+1); - -> 0 -mysql> select ! 1+1; - -> 1 -@end example -The last example returns @code{1} because the expression evaluates -the same way as @code{(!1)+1}. - -@findex OR, logical -@findex || (logical OR) -@item OR -@itemx || -Logical OR. Returns @code{1} if either argument is not @code{0} and not -@code{NULL}: -@example -mysql> select 1 || 0; - -> 1 -mysql> select 0 || 0; - -> 0 -mysql> select 1 || NULL; - -> 1 - -@end example - -@findex AND, logical -@findex && (logical AND) -@item AND -@itemx && -Logical AND. Returns @code{0} if either argument is @code{0} or @code{NULL}, -otherwise returns @code{1}: -@example -mysql> select 1 && NULL; - -> 0 -mysql> select 1 && 0; - -> 0 -@end example -@end table +@findex comparison operators @cindex casts @cindex type conversions -@findex comparison operators -@node Comparison functions, String comparison functions, Logical functions, Functions -@subsection Comparison Operators Comparison operations result in a value of @code{1} (TRUE), @code{0} (FALSE), or @code{NULL}. These functions work for both numbers and strings. Strings @@ -29311,193 +29322,73 @@ mysql> select INTERVAL(22, 23, 30, 44, 200); @end example @end table -@findex string comparison functions -@findex functions, string comparison -@node String comparison functions, Casts, Comparison functions, Functions -@subsection String Comparison Functions -@cindex case sensitivity, in string comparisons -@cindex string comparisons, case sensitivity -Normally, if any expression in a string comparison is case sensitive, the -comparison is performed in case-sensitive fashion. +@node Logical Operators, Control flow functions, Comparison Operators, Non-typed Operators +@subsubsection Logical Operators + +@findex Logical functions +@findex Functions, logical + +All logical functions return @code{1} (TRUE), @code{0} (FALSE) or +@code{NULL} (unknown, which is in most cases the same as FALSE): @table @code -@findex LIKE -@item expr LIKE pat [ESCAPE 'escape-char'] -Pattern matching using -SQL simple regular expression comparison. Returns @code{1} (TRUE) or @code{0} -(FALSE). With @code{LIKE} you can use the following two wild-card characters -in the pattern: - -@multitable @columnfractions .1 .9 -@item @code{%} @tab Matches any number of characters, even zero characters -@item @code{_} @tab Matches exactly one character -@end multitable - +@findex NOT, logical +@findex ! (logical NOT) +@item NOT +@itemx ! +Logical NOT. Returns @code{1} if the argument is @code{0}, otherwise returns +@code{0}. +Exception: @code{NOT NULL} returns @code{NULL}: @example -mysql> select 'David!' LIKE 'David_'; - -> 1 -mysql> select 'David!' LIKE '%D%v%'; - -> 1 -@end example - -To test for literal instances of a wild-card character, precede the character -with the escape character. If you don't specify the @code{ESCAPE} character, -@samp{\} is assumed: - -@multitable @columnfractions .1 .9 -@item @code{\%} @tab Matches one @code{%} character -@item @code{\_} @tab Matches one @code{_} character -@end multitable - -@example -mysql> select 'David!' LIKE 'David\_'; +mysql> select NOT 1; -> 0 -mysql> select 'David_' LIKE 'David\_'; +mysql> select NOT NULL; + -> NULL +mysql> select ! (1+1); + -> 0 +mysql> select ! 1+1; -> 1 @end example +The last example returns @code{1} because the expression evaluates +the same way as @code{(!1)+1}. -To specify a different escape character, use the @code{ESCAPE} clause: - +@findex OR, logical +@findex || (logical OR) +@item OR +@itemx || +Logical OR. Returns @code{1} if either argument is not @code{0} and not +@code{NULL}: @example -mysql> select 'David_' LIKE 'David|_' ESCAPE '|'; +mysql> select 1 || 0; -> 1 +mysql> select 0 || 0; + -> 0 +mysql> select 1 || NULL; + -> 1 + @end example -The following two statements illustrate that string comparisons are -case insensitive unless one of the operands is a binary string: - +@findex AND, logical +@findex && (logical AND) +@item AND +@itemx && +Logical AND. Returns @code{0} if either argument is @code{0} or @code{NULL}, +otherwise returns @code{1}: @example -mysql> select 'abc' LIKE 'ABC'; - -> 1 -mysql> SELECT 'abc' LIKE BINARY 'ABC'; +mysql> select 1 && NULL; + -> 0 +mysql> select 1 && 0; -> 0 @end example - -@code{LIKE} is allowed on numeric expressions! (This is a @strong{MySQL} -extension to the ANSI SQL @code{LIKE}.) - -@example -mysql> select 10 LIKE '1%'; - -> 1 -@end example - -Note: Because @strong{MySQL} uses the C escape syntax in strings (for example, -@samp{\n}), you must double any @samp{\} that you use in your @code{LIKE} -strings. For example, to search for @samp{\n}, specify it as @samp{\\n}. To -search for @samp{\}, specify it as @samp{\\\\} (the backslashes are stripped -once by the parser and another time when the pattern match is done, leaving -a single backslash to be matched). - -@findex NOT LIKE -@item expr NOT LIKE pat [ESCAPE 'escape-char'] -Same as @code{NOT (expr LIKE pat [ESCAPE 'escape-char'])}. - -@cindex mSQL compatibility -@cindex compatibility, with mSQL -@findex REGEXP -@findex RLIKE -@item expr REGEXP pat -@itemx expr RLIKE pat -Performs a pattern match of a string expression @code{expr} against a pattern -@code{pat}. The pattern can be an extended regular expression. -@xref{Regexp}. Returns @code{1} if @code{expr} matches @code{pat}, otherwise -returns @code{0}. @code{RLIKE} is a synonym for @code{REGEXP}, provided for -@code{mSQL} compatibility. Note: Because @strong{MySQL} uses the C escape -syntax in strings (for example, @samp{\n}), you must double any @samp{\} that -you use in your @code{REGEXP} strings. As of @strong{MySQL} Version 3.23.4, -@code{REGEXP} is case insensitive for normal (not binary) strings: - -@example -mysql> select 'Monty!' REGEXP 'm%y%%'; - -> 0 -mysql> select 'Monty!' REGEXP '.*'; - -> 1 -mysql> select 'new*\n*line' REGEXP 'new\\*.\\*line'; - -> 1 -mysql> select "a" REGEXP "A", "a" REGEXP BINARY "A"; - -> 1 0 -mysql> select "a" REGEXP "^[a-d]"; - -> 1 -@end example - -@item -@code{REGEXP} and @code{RLIKE} use the current character set (ISO-8859-1 -Latin1 by default) when deciding the type of a character. - -@findex NOT REGEXP -@item expr NOT REGEXP pat -@itemx expr NOT RLIKE pat -Same as @code{NOT (expr REGEXP pat)}. - -@findex STRCMP() -@item STRCMP(expr1,expr2) -@code{STRCMP()} -returns @code{0} if the strings are the same, @code{-1} if the first -argument is smaller than the second according to the current sort order, -and @code{1} otherwise: - -@example -mysql> select STRCMP('text', 'text2'); - -> -1 -mysql> select STRCMP('text2', 'text'); - -> 1 -mysql> select STRCMP('text', 'text'); - -> 0 -@end example - -@findex MATCH ... AGAINST() -@item MATCH (col1,col2,...) AGAINST (expr) -@code{MATCH ... AGAINST()} is used for full-text search and returns -relevance - similarity measure between the text in columns -@code{(col1,col2,...)} and the query @code{expr}. Relevance is a -positive floating-point number. Zero relevance means no similarity. -For @code{MATCH ... AGAINST()} to work, a @strong{FULLTEXT} index -must be created first. @xref{CREATE TABLE, , @code{CREATE TABLE}}. -@code{MATCH ... AGAINST()} is available in @strong{MySQL} Version -3.23.23 or later. For details and usage examples -@pxref{Fulltext Search}. @end table -@findex casts -@cindex cast operators -@cindex operators, cast -@node Casts, Control flow functions, String comparison functions, Functions -@subsection Cast Operators -@table @code -@findex BINARY -@item @code{BINARY} -The @code{BINARY} operator casts the string following it to a binary string. -This is an easy way to force a column comparison to be case sensitive even -if the column isn't defined as @code{BINARY} or @code{BLOB}: -@example -mysql> select "a" = "A"; - -> 1 -mysql> select BINARY "a" = "A"; - -> 0 -@end example - -@code{BINARY} was introduced in @strong{MySQL} Version 3.23.0. - -Note that in some context @strong{MySQL} will not be able to use the -index efficiently when you cast an indexed column to @code{BINARY}. -@end table - -If you want to compare a blob case-insensitively you can always convert -the blob to upper case before doing the comparison: - -@example -SELECT 'A' LIKE UPPER(blob_col) FROM table_name; -@end example - -We plan to soon introduce casting between different character sets to -make string comparison even more flexible. +@node Control flow functions, , Logical Operators, Non-typed Operators +@subsubsection Control Flow Functions @findex control flow functions @findex functions, control flow -@node Control flow functions, Mathematical functions, Casts, Functions -@subsection Control Flow Functions @table @code @cindex @code{NULL}, testing for null @@ -29599,400 +29490,12 @@ The type of the return value (@code{INTEGER}, @code{DOUBLE} or @code{STRING}) is the same as the type of the first returned value (the expression after the first @code{THEN}). -@findex mathematical functions -@findex functions, mathematical -@node Mathematical functions, String functions, Control flow functions, Functions -@subsection Mathematical Functions -All mathematical functions return @code{NULL} in case of an error. -@table @code -@findex - (unary minus) -@findex minus, unary (-) -@findex unary minus (-) -@item - -Unary minus. Changes the sign of the argument: -@example -mysql> select - 2; - -> -2 -@end example - -Note that if this operator is used with a @code{BIGINT}, the return value is a -@code{BIGINT}! This means that you should avoid using @code{-} on integers that -may have the value of @code{-2^63}! - -@findex ABS() -@item ABS(X) -Returns the absolute value of @code{X}: -@example -mysql> select ABS(2); - -> 2 -mysql> select ABS(-32); - -> 32 -@end example - -This function is safe to use with @code{BIGINT} values. - -@findex SIGN() -@item SIGN(X) -Returns the sign of the argument as @code{-1}, @code{0}, or @code{1}, depending -on whether @code{X} is negative, zero, or positive: -@example -mysql> select SIGN(-32); - -> -1 -mysql> select SIGN(0); - -> 0 -mysql> select SIGN(234); - -> 1 -@end example - -@findex MOD() -@findex % (modulo) -@findex modulo (%) -@item MOD(N,M) -@itemx % -Modulo (like the @code{%} operator in C). -Returns the remainder of @code{N} divided by @code{M}: -@example -mysql> select MOD(234, 10); - -> 4 -mysql> select 253 % 7; - -> 1 -mysql> select MOD(29,9); - -> 2 -@end example - -This function is safe to use with @code{BIGINT} values. - -@findex FLOOR() -@item FLOOR(X) -Returns the largest integer value not greater than @code{X}: -@example -mysql> select FLOOR(1.23); - -> 1 -mysql> select FLOOR(-1.23); - -> -2 -@end example - -Note that the return value is converted to a @code{BIGINT}! - -@findex CEILING() -@item CEILING(X) -Returns the smallest integer value not less than @code{X}: -@example -mysql> select CEILING(1.23); - -> 2 -mysql> select CEILING(-1.23); - -> -1 -@end example - -Note that the return value is converted to a @code{BIGINT}! - -@findex ROUND() -@item ROUND(X) -Returns the argument @code{X}, rounded to the nearest integer: -@example -mysql> select ROUND(-1.23); - -> -1 -mysql> select ROUND(-1.58); - -> -2 -mysql> select ROUND(1.58); - -> 2 -@end example - -Note that the behavior of @code{ROUND()} when the argument -is half way between two integers depends on the C library -implementation. Some round to the nearest even number, -always up, always down, or always towards zero. If you need -one kind of rounding, you should use a well-defined function -like @code{TRUNCATE()} or @code{FLOOR()} instead. - -@findex ROUND() -@item ROUND(X,D) -Returns the argument @code{X}, rounded to a number with @code{D} decimals. -If @code{D} is @code{0}, the result will have no decimal point or fractional -part: - -@example -mysql> select ROUND(1.298, 1); - -> 1.3 -mysql> select ROUND(1.298, 0); - -> 1 -@end example - -@findex EXP() -@item EXP(X) -Returns the value of @code{e} (the base of natural logarithms) raised to -the power of @code{X}: -@example -mysql> select EXP(2); - -> 7.389056 -mysql> select EXP(-2); - -> 0.135335 -@end example -@findex LOG() -@item LOG(X) -Returns the natural logarithm of @code{X}: -@example -mysql> select LOG(2); - -> 0.693147 -mysql> select LOG(-2); - -> NULL -@end example -If you want the log of a number @code{X} to some arbitary base @code{B}, use -the formula @code{LOG(X)/LOG(B)}. - -@findex LOG10() -@item LOG10(X) -Returns the base-10 logarithm of @code{X}: -@example -mysql> select LOG10(2); - -> 0.301030 -mysql> select LOG10(100); - -> 2.000000 -mysql> select LOG10(-100); - -> NULL -@end example - -@findex POW() -@findex POWER() -@item POW(X,Y) -@itemx POWER(X,Y) -Returns the value of @code{X} raised to the power of @code{Y}: -@example -mysql> select POW(2,2); - -> 4.000000 -mysql> select POW(2,-2); - -> 0.250000 -@end example - -@findex SQRT() -@item SQRT(X) -Returns the non-negative square root of @code{X}: -@example -mysql> select SQRT(4); - -> 2.000000 -mysql> select SQRT(20); - -> 4.472136 -@end example - -@findex PI() -@item PI() -Returns the value of PI. The default shown number of decimals is 5, but -@strong{MySQL} internally uses the full double precession for PI. -@example -mysql> select PI(); - -> 3.141593 -mysql> SELECT PI()+0.000000000000000000; - -> 3.141592653589793116 -@end example - -@findex COS() -@item COS(X) -Returns the cosine of @code{X}, where @code{X} is given in radians: -@example -mysql> select COS(PI()); - -> -1.000000 -@end example - -@findex SIN() -@item SIN(X) -Returns the sine of @code{X}, where @code{X} is given in radians: -@example -mysql> select SIN(PI()); - -> 0.000000 -@end example - -@findex TAN() -@item TAN(X) -Returns the tangent of @code{X}, where @code{X} is given in radians: -@example -mysql> select TAN(PI()+1); - -> 1.557408 -@end example - -@findex ACOS() -@item ACOS(X) -Returns the arc cosine of @code{X}, that is, the value whose cosine is -@code{X}. Returns @code{NULL} if @code{X} is not in the range @code{-1} to -@code{1}: -@example -mysql> select ACOS(1); - -> 0.000000 -mysql> select ACOS(1.0001); - -> NULL -mysql> select ACOS(0); - -> 1.570796 -@end example - -@findex ASIN() -@item ASIN(X) -Returns the arc sine of @code{X}, that is, the value whose sine is -@code{X}. Returns @code{NULL} if @code{X} is not in the range @code{-1} to -@code{1}: -@example -mysql> select ASIN(0.2); - -> 0.201358 -mysql> select ASIN('foo'); - -> 0.000000 -@end example - -@findex ATAN() -@item ATAN(X) -Returns the arc tangent of @code{X}, that is, the value whose tangent is -@code{X}: -@example -mysql> select ATAN(2); - -> 1.107149 -mysql> select ATAN(-2); - -> -1.107149 -@end example - -@findex ATAN2() -@item ATAN2(Y,X) -Returns the arc tangent of the two variables @code{X} and @code{Y}. It is -similar to calculating the arc tangent of @code{Y / X}, except that the -signs of both arguments are used to determine the quadrant of the -result: -@example -mysql> select ATAN(-2,2); - -> -0.785398 -mysql> select ATAN(PI(),0); - -> 1.570796 -@end example - -@findex COT() -@item COT(X) -Returns the cotangent of @code{X}: -@example -mysql> select COT(12); - -> -1.57267341 -mysql> select COT(0); - -> NULL -@end example - -@findex RAND() -@item RAND() -@itemx RAND(N) -Returns a random floating-point value in the range @code{0} to @code{1.0}. -If an integer argument @code{N} is specified, it is used as the seed value: -@example -mysql> select RAND(); - -> 0.5925 -mysql> select RAND(20); - -> 0.1811 -mysql> select RAND(20); - -> 0.1811 -mysql> select RAND(); - -> 0.2079 -mysql> select RAND(); - -> 0.7888 -@end example -You can't use a column with @code{RAND()} values in an @code{ORDER BY} -clause, because @code{ORDER BY} would evaluate the column multiple times. -In @strong{MySQL} Version 3.23, you can, however, do: -@code{SELECT * FROM table_name ORDER BY RAND()} - -This is useful to get a random sample of a set @code{SELECT * FROM -table1,table2 WHERE a=b AND c select LEAST(2,0); - -> 0 -mysql> select LEAST(34.0,3.0,5.0,767.0); - -> 3.0 -mysql> select LEAST("B","A","C"); - -> "A" -@end example -In @strong{MySQL} versions prior to Version 3.22.5, you can use @code{MIN()} -instead of @code{LEAST}. - -@findex GREATEST() -@item GREATEST(X,Y,...) -Returns the largest (maximum-valued) argument. -The arguments are compared using the same rules as for @code{LEAST}: -@example -mysql> select GREATEST(2,0); - -> 2 -mysql> select GREATEST(34.0,3.0,5.0,767.0); - -> 767.0 -mysql> select GREATEST("B","A","C"); - -> "C" -@end example -In @strong{MySQL} versions prior to Version 3.22.5, you can use @code{MAX()} -instead of @code{GREATEST}. - -@findex DEGREES() -@item DEGREES(X) -Returns the argument @code{X}, converted from radians to degrees: -@example -mysql> select DEGREES(PI()); - -> 180.000000 -@end example - -@findex RADIANS() -@item RADIANS(X) -Returns the argument @code{X}, converted from degrees to radians: -@example -mysql> select RADIANS(90); - -> 1.570796 -@end example - -@findex TRUNCATE() -@item TRUNCATE(X,D) -Returns the number @code{X}, truncated to @code{D} decimals. If @code{D} -is @code{0}, the result will have no decimal point or fractional part: -@example -mysql> select TRUNCATE(1.223,1); - -> 1.2 -mysql> select TRUNCATE(1.999,1); - -> 1.9 -mysql> select TRUNCATE(1.999,0); - -> 1 -@end example - -Note that as decimal numbers are normally not stored as exact numbers in -computers, but as double values, you may be fooled by the following -result: - -@cindex rounding errors -@example -mysql> select TRUNCATE(10.28*100,0); - -> 1027 -@end example - -The above happens because 10.28 is actually stored as something like -10.2799999999999999. -@end table +@node String functions, Numeric Functions, Non-typed Operators, Functions +@subsection String Functions @findex string functions @findex functions, string -@node String functions, Date and time functions, Mathematical functions, Functions -@subsection String Functions String-valued functions return @code{NULL} if the length of the result would be greater than the @code{max_allowed_packet} server parameter. @xref{Server @@ -30549,10 +30052,672 @@ If a string function is given a binary string as an argument, the resulting string is also a binary string. A number converted to a string is treated as a binary string. This only affects comparisons. + +@menu +* String comparison functions:: +* Case Sensitivity:: +@end menu + +@node String comparison functions, Case Sensitivity, String functions, String functions +@subsubsection String Comparison Functions + +@findex string comparison functions +@findex functions, string comparison + +@cindex case sensitivity, in string comparisons +@cindex string comparisons, case sensitivity + +Normally, if any expression in a string comparison is case sensitive, the +comparison is performed in case-sensitive fashion. + +@table @code +@findex LIKE +@item expr LIKE pat [ESCAPE 'escape-char'] +Pattern matching using +SQL simple regular expression comparison. Returns @code{1} (TRUE) or @code{0} +(FALSE). With @code{LIKE} you can use the following two wild-card characters +in the pattern: + +@multitable @columnfractions .1 .9 +@item @code{%} @tab Matches any number of characters, even zero characters +@item @code{_} @tab Matches exactly one character +@end multitable + +@example +mysql> select 'David!' LIKE 'David_'; + -> 1 +mysql> select 'David!' LIKE '%D%v%'; + -> 1 +@end example + +To test for literal instances of a wild-card character, precede the character +with the escape character. If you don't specify the @code{ESCAPE} character, +@samp{\} is assumed: + +@multitable @columnfractions .1 .9 +@item @code{\%} @tab Matches one @code{%} character +@item @code{\_} @tab Matches one @code{_} character +@end multitable + +@example +mysql> select 'David!' LIKE 'David\_'; + -> 0 +mysql> select 'David_' LIKE 'David\_'; + -> 1 +@end example + +To specify a different escape character, use the @code{ESCAPE} clause: + +@example +mysql> select 'David_' LIKE 'David|_' ESCAPE '|'; + -> 1 +@end example + +The following two statements illustrate that string comparisons are +case insensitive unless one of the operands is a binary string: + +@example +mysql> select 'abc' LIKE 'ABC'; + -> 1 +mysql> SELECT 'abc' LIKE BINARY 'ABC'; + -> 0 +@end example + +@code{LIKE} is allowed on numeric expressions! (This is a @strong{MySQL} +extension to the ANSI SQL @code{LIKE}.) + +@example +mysql> select 10 LIKE '1%'; + -> 1 +@end example + +Note: Because @strong{MySQL} uses the C escape syntax in strings (for example, +@samp{\n}), you must double any @samp{\} that you use in your @code{LIKE} +strings. For example, to search for @samp{\n}, specify it as @samp{\\n}. To +search for @samp{\}, specify it as @samp{\\\\} (the backslashes are stripped +once by the parser and another time when the pattern match is done, leaving +a single backslash to be matched). + +@findex NOT LIKE +@item expr NOT LIKE pat [ESCAPE 'escape-char'] +Same as @code{NOT (expr LIKE pat [ESCAPE 'escape-char'])}. + +@cindex mSQL compatibility +@cindex compatibility, with mSQL +@findex REGEXP +@findex RLIKE +@item expr REGEXP pat +@itemx expr RLIKE pat +Performs a pattern match of a string expression @code{expr} against a pattern +@code{pat}. The pattern can be an extended regular expression. +@xref{Regexp}. Returns @code{1} if @code{expr} matches @code{pat}, otherwise +returns @code{0}. @code{RLIKE} is a synonym for @code{REGEXP}, provided for +@code{mSQL} compatibility. Note: Because @strong{MySQL} uses the C escape +syntax in strings (for example, @samp{\n}), you must double any @samp{\} that +you use in your @code{REGEXP} strings. As of @strong{MySQL} Version 3.23.4, +@code{REGEXP} is case insensitive for normal (not binary) strings: + +@example +mysql> select 'Monty!' REGEXP 'm%y%%'; + -> 0 +mysql> select 'Monty!' REGEXP '.*'; + -> 1 +mysql> select 'new*\n*line' REGEXP 'new\\*.\\*line'; + -> 1 +mysql> select "a" REGEXP "A", "a" REGEXP BINARY "A"; + -> 1 0 +mysql> select "a" REGEXP "^[a-d]"; + -> 1 +@end example + +@item +@code{REGEXP} and @code{RLIKE} use the current character set (ISO-8859-1 +Latin1 by default) when deciding the type of a character. + +@findex NOT REGEXP +@item expr NOT REGEXP pat +@itemx expr NOT RLIKE pat +Same as @code{NOT (expr REGEXP pat)}. + +@findex STRCMP() +@item STRCMP(expr1,expr2) +@code{STRCMP()} +returns @code{0} if the strings are the same, @code{-1} if the first +argument is smaller than the second according to the current sort order, +and @code{1} otherwise: + +@example +mysql> select STRCMP('text', 'text2'); + -> -1 +mysql> select STRCMP('text2', 'text'); + -> 1 +mysql> select STRCMP('text', 'text'); + -> 0 +@end example + +@findex MATCH ... AGAINST() +@item MATCH (col1,col2,...) AGAINST (expr) +@code{MATCH ... AGAINST()} is used for full-text search and returns +relevance - similarity measure between the text in columns +@code{(col1,col2,...)} and the query @code{expr}. Relevance is a +positive floating-point number. Zero relevance means no similarity. +For @code{MATCH ... AGAINST()} to work, a @strong{FULLTEXT} index +must be created first. @xref{CREATE TABLE, , @code{CREATE TABLE}}. +@code{MATCH ... AGAINST()} is available in @strong{MySQL} Version +3.23.23 or later. For details and usage examples +@pxref{Fulltext Search}. +@end table + + +@node Case Sensitivity, , String comparison functions, String functions +@subsubsection Case Sensitivity + +@findex casts + +@cindex cast operators +@cindex operators, cast + +@table @code +@findex BINARY +@item @code{BINARY} +The @code{BINARY} operator casts the string following it to a binary string. +This is an easy way to force a column comparison to be case sensitive even +if the column isn't defined as @code{BINARY} or @code{BLOB}: +@example +mysql> select "a" = "A"; + -> 1 +mysql> select BINARY "a" = "A"; + -> 0 +@end example + +@code{BINARY} was introduced in @strong{MySQL} Version 3.23.0. + +Note that in some context @strong{MySQL} will not be able to use the +index efficiently when you cast an indexed column to @code{BINARY}. +@end table + +If you want to compare a blob case-insensitively you can always convert +the blob to upper case before doing the comparison: + +@example +SELECT 'A' LIKE UPPER(blob_col) FROM table_name; +@end example + +We plan to soon introduce casting between different character sets to +make string comparison even more flexible. + + +@node Numeric Functions, Date and time functions, String functions, Functions +@subsection Numeric Functions + +@menu +* Arithmetic functions:: +* Mathematical functions:: +@end menu + + +@node Arithmetic functions, Mathematical functions, Numeric Functions, Numeric Functions +@subsubsection Arithmetic Operations + +The usual arithmetic operators are available. Note that in the case of +@samp{-}, @samp{+}, and @samp{*}, the result is calculated with +@code{BIGINT} (64-bit) precision if both arguments are integers! + +@cindex operations, arithmetic +@cindex arithmetic expressions +@table @code +@findex + (addition) +@findex addition (+) +@item + +Addition: +@example +mysql> select 3+5; + -> 8 +@end example + +@findex - (subtraction) +@findex subtraction (-) +@item - +Subtraction: +@example +mysql> select 3-5; + -> -2 +@end example + +@findex * (multiplication) +@findex multiplication (*) +@item * +Multiplication: +@example +mysql> select 3*5; + -> 15 +mysql> select 18014398509481984*18014398509481984.0; + -> 324518553658426726783156020576256.0 +mysql> select 18014398509481984*18014398509481984; + -> 0 +@end example + +The result of the last expression is incorrect because the result of the integer +multiplication exceeds the 64-bit range of @code{BIGINT} calculations. + +@findex / (division) +@findex division (/) +@item / +Division: +@example +mysql> select 3/5; + -> 0.60 +@end example + +Division by zero produces a @code{NULL} result: + +@example +mysql> select 102/(1-1); + -> NULL +@end example + +A division will be calculated with @code{BIGINT} arithmetic only if performed +in a context where its result is converted to an integer! +@end table + + +@node Mathematical functions, , Arithmetic functions, Numeric Functions +@subsubsection Mathematical Functions +All mathematical functions return @code{NULL} in case of an error. + +@findex mathematical functions +@findex functions, mathematical + +@table @code +@findex - (unary minus) +@findex minus, unary (-) +@findex unary minus (-) +@item - +Unary minus. Changes the sign of the argument: +@example +mysql> select - 2; + -> -2 +@end example + +Note that if this operator is used with a @code{BIGINT}, the return value is a +@code{BIGINT}! This means that you should avoid using @code{-} on integers that +may have the value of @code{-2^63}! + +@findex ABS() +@item ABS(X) +Returns the absolute value of @code{X}: +@example +mysql> select ABS(2); + -> 2 +mysql> select ABS(-32); + -> 32 +@end example + +This function is safe to use with @code{BIGINT} values. + +@findex SIGN() +@item SIGN(X) +Returns the sign of the argument as @code{-1}, @code{0}, or @code{1}, depending +on whether @code{X} is negative, zero, or positive: +@example +mysql> select SIGN(-32); + -> -1 +mysql> select SIGN(0); + -> 0 +mysql> select SIGN(234); + -> 1 +@end example + +@findex MOD() +@findex % (modulo) +@findex modulo (%) +@item MOD(N,M) +@itemx % +Modulo (like the @code{%} operator in C). +Returns the remainder of @code{N} divided by @code{M}: +@example +mysql> select MOD(234, 10); + -> 4 +mysql> select 253 % 7; + -> 1 +mysql> select MOD(29,9); + -> 2 +@end example + +This function is safe to use with @code{BIGINT} values. + +@findex FLOOR() +@item FLOOR(X) +Returns the largest integer value not greater than @code{X}: +@example +mysql> select FLOOR(1.23); + -> 1 +mysql> select FLOOR(-1.23); + -> -2 +@end example + +Note that the return value is converted to a @code{BIGINT}! + +@findex CEILING() +@item CEILING(X) +Returns the smallest integer value not less than @code{X}: +@example +mysql> select CEILING(1.23); + -> 2 +mysql> select CEILING(-1.23); + -> -1 +@end example + +Note that the return value is converted to a @code{BIGINT}! + +@findex ROUND() +@item ROUND(X) +Returns the argument @code{X}, rounded to the nearest integer: +@example +mysql> select ROUND(-1.23); + -> -1 +mysql> select ROUND(-1.58); + -> -2 +mysql> select ROUND(1.58); + -> 2 +@end example + +Note that the behavior of @code{ROUND()} when the argument +is half way between two integers depends on the C library +implementation. Some round to the nearest even number, +always up, always down, or always towards zero. If you need +one kind of rounding, you should use a well-defined function +like @code{TRUNCATE()} or @code{FLOOR()} instead. + +@findex ROUND() +@item ROUND(X,D) +Returns the argument @code{X}, rounded to a number with @code{D} decimals. +If @code{D} is @code{0}, the result will have no decimal point or fractional +part: + +@example +mysql> select ROUND(1.298, 1); + -> 1.3 +mysql> select ROUND(1.298, 0); + -> 1 +@end example + +@findex EXP() +@item EXP(X) +Returns the value of @code{e} (the base of natural logarithms) raised to +the power of @code{X}: +@example +mysql> select EXP(2); + -> 7.389056 +mysql> select EXP(-2); + -> 0.135335 +@end example +@findex LOG() +@item LOG(X) +Returns the natural logarithm of @code{X}: +@example +mysql> select LOG(2); + -> 0.693147 +mysql> select LOG(-2); + -> NULL +@end example +If you want the log of a number @code{X} to some arbitary base @code{B}, use +the formula @code{LOG(X)/LOG(B)}. + +@findex LOG10() +@item LOG10(X) +Returns the base-10 logarithm of @code{X}: +@example +mysql> select LOG10(2); + -> 0.301030 +mysql> select LOG10(100); + -> 2.000000 +mysql> select LOG10(-100); + -> NULL +@end example + +@findex POW() +@findex POWER() +@item POW(X,Y) +@itemx POWER(X,Y) +Returns the value of @code{X} raised to the power of @code{Y}: +@example +mysql> select POW(2,2); + -> 4.000000 +mysql> select POW(2,-2); + -> 0.250000 +@end example + +@findex SQRT() +@item SQRT(X) +Returns the non-negative square root of @code{X}: +@example +mysql> select SQRT(4); + -> 2.000000 +mysql> select SQRT(20); + -> 4.472136 +@end example + +@findex PI() +@item PI() +Returns the value of PI. The default shown number of decimals is 5, but +@strong{MySQL} internally uses the full double precession for PI. +@example +mysql> select PI(); + -> 3.141593 +mysql> SELECT PI()+0.000000000000000000; + -> 3.141592653589793116 +@end example + +@findex COS() +@item COS(X) +Returns the cosine of @code{X}, where @code{X} is given in radians: +@example +mysql> select COS(PI()); + -> -1.000000 +@end example + +@findex SIN() +@item SIN(X) +Returns the sine of @code{X}, where @code{X} is given in radians: +@example +mysql> select SIN(PI()); + -> 0.000000 +@end example + +@findex TAN() +@item TAN(X) +Returns the tangent of @code{X}, where @code{X} is given in radians: +@example +mysql> select TAN(PI()+1); + -> 1.557408 +@end example + +@findex ACOS() +@item ACOS(X) +Returns the arc cosine of @code{X}, that is, the value whose cosine is +@code{X}. Returns @code{NULL} if @code{X} is not in the range @code{-1} to +@code{1}: +@example +mysql> select ACOS(1); + -> 0.000000 +mysql> select ACOS(1.0001); + -> NULL +mysql> select ACOS(0); + -> 1.570796 +@end example + +@findex ASIN() +@item ASIN(X) +Returns the arc sine of @code{X}, that is, the value whose sine is +@code{X}. Returns @code{NULL} if @code{X} is not in the range @code{-1} to +@code{1}: +@example +mysql> select ASIN(0.2); + -> 0.201358 +mysql> select ASIN('foo'); + -> 0.000000 +@end example + +@findex ATAN() +@item ATAN(X) +Returns the arc tangent of @code{X}, that is, the value whose tangent is +@code{X}: +@example +mysql> select ATAN(2); + -> 1.107149 +mysql> select ATAN(-2); + -> -1.107149 +@end example + +@findex ATAN2() +@item ATAN2(Y,X) +Returns the arc tangent of the two variables @code{X} and @code{Y}. It is +similar to calculating the arc tangent of @code{Y / X}, except that the +signs of both arguments are used to determine the quadrant of the +result: +@example +mysql> select ATAN(-2,2); + -> -0.785398 +mysql> select ATAN(PI(),0); + -> 1.570796 +@end example + +@findex COT() +@item COT(X) +Returns the cotangent of @code{X}: +@example +mysql> select COT(12); + -> -1.57267341 +mysql> select COT(0); + -> NULL +@end example + +@findex RAND() +@item RAND() +@itemx RAND(N) +Returns a random floating-point value in the range @code{0} to @code{1.0}. +If an integer argument @code{N} is specified, it is used as the seed value: +@example +mysql> select RAND(); + -> 0.5925 +mysql> select RAND(20); + -> 0.1811 +mysql> select RAND(20); + -> 0.1811 +mysql> select RAND(); + -> 0.2079 +mysql> select RAND(); + -> 0.7888 +@end example +You can't use a column with @code{RAND()} values in an @code{ORDER BY} +clause, because @code{ORDER BY} would evaluate the column multiple times. +In @strong{MySQL} Version 3.23, you can, however, do: +@code{SELECT * FROM table_name ORDER BY RAND()} + +This is useful to get a random sample of a set @code{SELECT * FROM +table1,table2 WHERE a=b AND c select LEAST(2,0); + -> 0 +mysql> select LEAST(34.0,3.0,5.0,767.0); + -> 3.0 +mysql> select LEAST("B","A","C"); + -> "A" +@end example +In @strong{MySQL} versions prior to Version 3.22.5, you can use @code{MIN()} +instead of @code{LEAST}. + +@findex GREATEST() +@item GREATEST(X,Y,...) +Returns the largest (maximum-valued) argument. +The arguments are compared using the same rules as for @code{LEAST}: +@example +mysql> select GREATEST(2,0); + -> 2 +mysql> select GREATEST(34.0,3.0,5.0,767.0); + -> 767.0 +mysql> select GREATEST("B","A","C"); + -> "C" +@end example +In @strong{MySQL} versions prior to Version 3.22.5, you can use @code{MAX()} +instead of @code{GREATEST}. + +@findex DEGREES() +@item DEGREES(X) +Returns the argument @code{X}, converted from radians to degrees: +@example +mysql> select DEGREES(PI()); + -> 180.000000 +@end example + +@findex RADIANS() +@item RADIANS(X) +Returns the argument @code{X}, converted from degrees to radians: +@example +mysql> select RADIANS(90); + -> 1.570796 +@end example + +@findex TRUNCATE() +@item TRUNCATE(X,D) +Returns the number @code{X}, truncated to @code{D} decimals. If @code{D} +is @code{0}, the result will have no decimal point or fractional part: +@example +mysql> select TRUNCATE(1.223,1); + -> 1.2 +mysql> select TRUNCATE(1.999,1); + -> 1.9 +mysql> select TRUNCATE(1.999,0); + -> 1 +@end example + +Note that as decimal numbers are normally not stored as exact numbers in +computers, but as double values, you may be fooled by the following +result: + +@cindex rounding errors +@example +mysql> select TRUNCATE(10.28*100,0); + -> 1027 +@end example + +The above happens because 10.28 is actually stored as something like +10.2799999999999999. +@end table + + +@node Date and time functions, Other Functions, Numeric Functions, Functions +@subsection Date and Time Functions + @findex date and time functions @findex functions, date and time -@node Date and time functions, Miscellaneous functions, String functions, Functions -@subsection Date and Time Functions See @ref{Date and time types} for a description of the range of values each type has and the valid formats in which date and time values may be @@ -31090,10 +31255,85 @@ mysql> select TIME_TO_SEC('00:39:38'); @end example @end table + +@node Other Functions, , Date and time functions, Functions +@subsection Other Functions + +@menu +* Bit functions:: +* Miscellaneous functions:: +@end menu + + +@node Bit functions, Miscellaneous functions, Other Functions, Other Functions +@subsubsection Bit Functions + +@findex arithmetic functions +@findex bit functions +@findex functions, arithmetic +@findex functions, bit + +@strong{MySQL} uses @code{BIGINT} (64-bit) arithmetic for bit operations, so +these operators have a maximum range of 64 bits. + +@table @code +@findex | (bitwise OR) +@findex OR, bitwise +@item | +Bitwise OR: +@example +mysql> select 29 | 15; + -> 31 +@end example + +@findex & (bitwise AND) +@findex AND, bitwise +@item & +Bitwise AND: +@example +mysql> select 29 & 15; + -> 13 +@end example + +@findex << (left shift) +@item << +Shifts a longlong (@code{BIGINT}) number to the left: +@example +mysql> select 1 << 2; + -> 4 +@end example + +@findex >> (right shift) +@item >> +Shifts a longlong (@code{BIGINT}) number to the right: +@example +mysql> select 4 >> 2; + -> 1 +@end example + +@findex ~ +@item ~ +Invert all bits: +@example +mysql> select 5 & ~1; + -> 4 +@end example + +@findex BIT_COUNT() +@item BIT_COUNT(N) +Returns the number of bits that are set in the argument @code{N}: +@example +mysql> select BIT_COUNT(29); + -> 4 +@end example +@end table + + +@node Miscellaneous functions, , Bit functions, Other Functions +@subsubsection Miscellaneous Functions + @findex miscellaneous functions @findex functions, miscellaneous -@node Miscellaneous functions, Group by functions, Date and time functions, Functions -@subsection Miscellaneous Functions @table @code @findex DATABASE() @@ -31372,1145 +31612,26 @@ control of master-slave synchronization, but was originally written to facilitate replication testing. @end table -@findex GROUP BY functions -@findex functions, GROUP BY -@node Group by functions, , Miscellaneous functions, Functions -@subsection Functions for Use with @code{GROUP BY} Clauses -If you use a group function in a statement containing no @code{GROUP BY} -clause, it is equivalent to grouping on all rows. +@node Data Manipulation, Data Definition, Functions, Reference +@section Data Manipulation: @code{SELECT}, @code{INSERT}, @code{UPDATE}, @code{DELETE} -@table @code -@findex COUNT() -@item COUNT(expr) -Returns a count of the number of non-@code{NULL} values in the rows -retrieved by a @code{SELECT} statement: - -@example -mysql> select student.student_name,COUNT(*) - from student,course - where student.student_id=course.student_id - GROUP BY student_name; - -@end example - -@code{COUNT(*)} is somewhat different in that it returns a count of -the number of rows retrieved, whether or not they contain @code{NULL} -values. - -@code{COUNT(*)} is optimized to -return very quickly if the @code{SELECT} retrieves from one table, no -other columns are retrieved, and there is no @code{WHERE} clause. -For example: - -@example -mysql> select COUNT(*) from student; -@end example - -@findex COUNT(DISTINCT) -@findex DISTINCT -@item COUNT(DISTINCT expr,[expr...]) -Returns a count of the number of different non-@code{NULL} values: - -@example -mysql> select COUNT(DISTINCT results) from student; -@end example - -In @strong{MySQL} you can get the number of distinct expression -combinations that don't contain NULL by giving a list of expressions. -In ANSI SQL you would have to do a concatenation of all expressions -inside @code{CODE(DISTINCT ..)}. - -@findex AVG() -@item AVG(expr) -Returns the average value of @code{expr}: - -@example -mysql> select student_name, AVG(test_score) - from student - GROUP BY student_name; -@end example - -@findex MIN() -@findex MAX() -@item MIN(expr) -@itemx MAX(expr) -Returns the minimum or maximum value of @code{expr}. @code{MIN()} and -@code{MAX()} may take a string argument; in such cases they return the -minimum or maximum string value. @xref{MySQL indexes}. - -@example -mysql> select student_name, MIN(test_score), MAX(test_score) - from student - GROUP BY student_name; -@end example - -@findex SUM() -@item SUM(expr) -Returns the sum of @code{expr}. Note that if the return set has no rows, -it returns NULL! - -@findex STD() -@findex STDDEV() -@cindex Oracle compatibility -@cindex compatibility, with Oracle -@item STD(expr) -@itemx STDDEV(expr) -Returns the standard deviation of @code{expr}. This is an extension to -ANSI SQL. The @code{STDDEV()} form of this function is provided for Oracle -compatibility. - -@findex BIT_OR() -@item BIT_OR(expr) -Returns the bitwise @code{OR} of all bits in @code{expr}. The calculation is -performed with 64-bit (@code{BIGINT}) precision. - -@findex BIT_AND() -@item BIT_AND(expr) -Returns the bitwise @code{AND} of all bits in @code{expr}. The calculation is -performed with 64-bit (@code{BIGINT}) precision. -@end table - -@cindex @code{GROUP BY}, extensions to ANSI SQL -@strong{MySQL} has extended the use of @code{GROUP BY}. You can use columns or -calculations in the @code{SELECT} expressions that don't appear in -the @code{GROUP BY} part. This stands for @emph{any possible value for this -group}. You can use this to get better performance by avoiding sorting and -grouping on unnecessary items. For example, you don't need to group on -@code{customer.name} in the following query: - -@example -mysql> select order.custid,customer.name,max(payments) - from order,customer - where order.custid = customer.custid - GROUP BY order.custid; -@end example - -In ANSI SQL, you would have to add @code{customer.name} to the @code{GROUP -BY} clause. In @strong{MySQL}, the name is redundant if you don't run in -ANSI mode. - -@strong{Don't use this feature} if the columns you omit from the -@code{GROUP BY} part aren't unique in the group! You will get -unpredictable results. - -In some cases, you can use @code{MIN()} and @code{MAX()} to obtain a specific -column value even if it isn't unique. The following gives the value of -@code{column} from the row containing the smallest value in the @code{sort} -column: - -@example -substr(MIN(concat(rpad(sort,6,' '),column)),7) -@end example - -@xref{example-Maximum-column-group-row}. - -@cindex @code{ORDER BY}, aliases in -@cindex aliases, in @code{ORDER BY} clauses -@cindex @code{GROUP BY}, aliases in -@cindex aliases, in @code{GROUP BY} clauses -@cindex expression aliases -@cindex aliases, for expressions -Note that if you are using @strong{MySQL} Version 3.22 (or earlier) or if -you are trying to follow ANSI SQL, you can't use expressions in @code{GROUP -BY} or @code{ORDER BY} clauses. You can work around this limitation by -using an alias for the expression: - -@example -mysql> SELECT id,FLOOR(value/100) AS val FROM tbl_name - GROUP BY id,val ORDER BY val; -@end example - -In @strong{MySQL} Version 3.23 you can do: - -@example -mysql> SELECT id,FLOOR(value/100) FROM tbl_name ORDER BY RAND(); -@end example - -@findex CREATE DATABASE -@node CREATE DATABASE, DROP DATABASE, Functions, Reference -@section @code{CREATE DATABASE} Syntax - -@example -CREATE DATABASE [IF NOT EXISTS] db_name -@end example - -@code{CREATE DATABASE} creates a database with the given name. Rules for -allowable database names are given in @ref{Legal names}. An error occurs if -the database already exists and you didn't specify @code{IF NOT EXISTS}. - -Databases in @strong{MySQL} are implemented as directories containing files -that correspond to tables in the database. Because there are no tables in a -database when it is initially created, the @code{CREATE DATABASE} statement -only creates a directory under the @strong{MySQL} data directory. - -@cindex @code{mysqladmin} -You can also create databases with @code{mysqladmin}. -@xref{Client-Side Scripts}. - -@findex DROP DATABASE -@node DROP DATABASE, CREATE TABLE, CREATE DATABASE, Reference -@section @code{DROP DATABASE} Syntax - -@example -DROP DATABASE [IF EXISTS] db_name -@end example - -@code{DROP DATABASE} drops all tables in the database and deletes the -database. If you do a @code{DROP DATABASE} on a symbolic linked -database, both the link and the original database is deleted. @strong{Be -VERY careful with this command!} - -@code{DROP DATABASE} returns the number of files that were removed from -the database directory. Normally, this is three times the number of -tables, because normally each table corresponds to a @file{.MYD} file, a -@file{.MYI} file, and a @file{.frm} file. - -The @code{DROP DATABASE} command removes from the given database -directory all files with the following extensions: - -@multitable @columnfractions .25 .25 .25 .25 -@item .BAK @tab .DAT @tab .HSH @tab .ISD -@item .ISM @tab .ISM @tab .MRG @tab .MYD -@item .MYI @tab .db @tab .frm -@end multitable - -All subdirectories that consists of 2 digits (@code{RAID} directories) -are also removed. - -In @strong{MySQL} Version 3.22 or later, you can use the keywords -@code{IF EXISTS} to prevent an error from occurring if the database doesn't -exist. - -@cindex @code{mysqladmin} -You can also drop databases with @code{mysqladmin}. @xref{Client-Side Scripts}. - -@findex CREATE TABLE -@node CREATE TABLE, ALTER TABLE, DROP DATABASE, Reference -@section @code{CREATE TABLE} Syntax @menu -* Silent column changes:: Silent column changes +* SELECT:: +* INSERT:: +* INSERT DELAYED:: +* UPDATE:: +* DELETE:: +* TRUNCATE:: +* REPLACE:: +* LOAD DATA:: @end menu -@example -CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)] -[table_options] [select_statement] - -create_definition: - col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] - [PRIMARY KEY] [reference_definition] - or PRIMARY KEY (index_col_name,...) - or KEY [index_name] (index_col_name,...) - or INDEX [index_name] (index_col_name,...) - or UNIQUE [INDEX] [index_name] (index_col_name,...) - or FULLTEXT [INDEX] [index_name] (index_col_name,...) - or [CONSTRAINT symbol] FOREIGN KEY index_name (index_col_name,...) - [reference_definition] - or CHECK (expr) - -type: - TINYINT[(length)] [UNSIGNED] [ZEROFILL] - or SMALLINT[(length)] [UNSIGNED] [ZEROFILL] - or MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] - or INT[(length)] [UNSIGNED] [ZEROFILL] - or INTEGER[(length)] [UNSIGNED] [ZEROFILL] - or BIGINT[(length)] [UNSIGNED] [ZEROFILL] - or REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] - or DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] - or FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] - or DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL] - or NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL] - or CHAR(length) [BINARY] - or VARCHAR(length) [BINARY] - or DATE - or TIME - or TIMESTAMP - or DATETIME - or TINYBLOB - or BLOB - or MEDIUMBLOB - or LONGBLOB - or TINYTEXT - or TEXT - or MEDIUMTEXT - or LONGTEXT - or ENUM(value1,value2,value3,...) - or SET(value1,value2,value3,...) - -index_col_name: - col_name [(length)] - -reference_definition: - REFERENCES tbl_name [(index_col_name,...)] - [MATCH FULL | MATCH PARTIAL] - [ON DELETE reference_option] - [ON UPDATE reference_option] - -reference_option: - RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT - -table_options: - TYPE = @{BDB | HEAP | ISAM | InnoDB | MERGE | MYISAM @} -or AUTO_INCREMENT = # -or AVG_ROW_LENGTH = # -or CHECKSUM = @{0 | 1@} -or COMMENT = "string" -or MAX_ROWS = # -or MIN_ROWS = # -or PACK_KEYS = @{0 | 1@} -or PASSWORD = "string" -or DELAY_KEY_WRITE = @{0 | 1@} -or ROW_FORMAT= @{ default | dynamic | fixed | compressed @} -or RAID_TYPE= @{1 | STRIPED | RAID0 @} RAID_CHUNKS=# RAID_CHUNKSIZE=# -or UNION = (table_name,[table_name...]) -or DATA DIRECTORY="directory" -or INDEX DIRECTORY="directory" - -select_statement: - [IGNORE | REPLACE] SELECT ... (Some legal select statement) -@end example - -@code{CREATE TABLE} -creates a table with the given name in the current database. Rules for -allowable table names are given in @ref{Legal names}. An error occurs if -there is no current database or if the table already exists. - -In @strong{MySQL} Version 3.22 or later, the table name can be specified as -@code{db_name.tbl_name}. This works whether or not there is a current -database. - -In @strong{MySQL} Version 3.23, you can use the @code{TEMPORARY} keyword when -you create a table. A temporary table will automatically be deleted if a -connection dies and the name is per connection. This means that two different -connections can both use the same temporary table name without conflicting -with each other or with an existing table of the same name. (The existing table -is hidden until the temporary table is deleted). - -In @strong{MySQL} Version 3.23 or later, you can use the keywords -@code{IF NOT EXISTS} so that an error does not occur if the table already -exists. Note that there is no verification that the table structures are -identical. - -Each table @code{tbl_name} is represented by some files in the database -directory. In the case of MyISAM-type tables you will get: - -@multitable @columnfractions .2 .8 -@item @strong{File} @tab @strong{Purpose} -@item @code{tbl_name.frm} @tab Table definition (form) file -@item @code{tbl_name.MYD} @tab Data file -@item @code{tbl_name.MYI} @tab Index file -@end multitable - -For more information on the properties of the various column types, see -@ref{Column types}: - -@itemize @bullet -@item -If neither @code{NULL} nor @code{NOT NULL} is specified, the column -is treated as though @code{NULL} had been specified. - -@item -An integer column may have the additional attribute @code{AUTO_INCREMENT}. -When you insert a value of @code{NULL} (recommended) or @code{0} into an -@code{AUTO_INCREMENT} column, the column is set to @code{value+1}, where -@code{value} is the largest value for the column currently in the table. -@code{AUTO_INCREMENT} sequences begin with @code{1}. -@xref{mysql_insert_id, , @code{mysql_insert_id()}}. - -If you delete the row containing the maximum value for an -@code{AUTO_INCREMENT} column, the value will be reused with an -@code{ISAM}, or @code{BDB} table but not with a -@code{MyISAM} or @code{InnoDB} table. If you delete all rows in the table -with @code{DELETE FROM table_name} (without a @code{WHERE}) in -@code{AUTOCOMMIT} mode, the sequence starts over for all table types. - -@strong{NOTE:} There can be only one @code{AUTO_INCREMENT} column per -table, and it must be indexed. @strong{MySQL} Version 3.23 will also only -work properly if the auto_increment column only has positive -values. Inserting a negative number is regarded as inserting a very large -positive number. This is done to avoid precision problems when -numbers 'wrap' over from positive to negative and also to ensure that one -doesn't accidentally get an auto_increment column that contains 0. - -@cindex ODBC compatibility -@cindex compatibility, with ODBC -To make @strong{MySQL} compatible with some ODBC applications, you can find -the last inserted row with the following query: - -@example -SELECT * FROM tbl_name WHERE auto_col IS NULL -@end example - -@item -@code{NULL} values are handled differently for @code{TIMESTAMP} columns than -for other column types. You cannot store a literal @code{NULL} in a -@code{TIMESTAMP} column; setting the column to @code{NULL} sets it to the -current date and time. Because @code{TIMESTAMP} columns behave this way, the -@code{NULL} and @code{NOT NULL} attributes do not apply in the normal way and -are ignored if you specify them. - -On the other hand, to make it easier for @strong{MySQL} clients to use -@code{TIMESTAMP} columns, the server reports that such columns may be -assigned @code{NULL} values (which is true), even though @code{TIMESTAMP} -never actually will contain a @code{NULL} value. You can see this when you -use @code{DESCRIBE tbl_name} to get a description of your table. - -Note that setting a @code{TIMESTAMP} column to @code{0} is not the same -as setting it to @code{NULL}, because @code{0} is a valid @code{TIMESTAMP} -value. - -@item -If no @code{DEFAULT} value is specified for a column, @strong{MySQL} -automatically assigns one. - -If the column may take @code{NULL} as a value, the default value is -@code{NULL}. - -If the column is declared as @code{NOT NULL}, the default value depends on -the column type: - -@itemize @minus -@item -For numeric types other than those declared with the @code{AUTO_INCREMENT} -attribute, the default is @code{0}. For an @code{AUTO_INCREMENT} column, the -default value is the next value in the sequence. - -@item -For date and time types other than @code{TIMESTAMP}, the default is the -appropriate zero value for the type. For the first @code{TIMESTAMP} -column in a table, the default value is the current date and time. -@xref{Date and time types}. - -@item -For string types other than @code{ENUM}, the default value is the empty string. -For @code{ENUM}, the default is the first enumeration value. -@end itemize - -Default values must be constants. This means, for example, that you cannot -set the default for a date column to be the value of a function such as -@code{NOW()} or @code{CURRENT_DATE}. - -@item -@code{KEY} is a synonym for @code{INDEX}. - -@item -In @strong{MySQL}, a @code{UNIQUE} key can have only distinct values. An -error occurs if you try to add a new row with a key that matches an existing -row. - -@item -@tindex PRIMARY KEY -A @code{PRIMARY KEY} is a unique @code{KEY} with the extra constraint -that all key columns must be defined as @code{NOT NULL}. In @strong{MySQL} -the key is named @code{PRIMARY}. A table can have only one @code{PRIMARY KEY}. -If you don't have a @code{PRIMARY KEY} and some applications ask for the -@code{PRIMARY KEY} in your tables, @strong{MySQL} will return the first -@code{UNIQUE} key, which doesn't have any @code{NULL} columns, as the -@code{PRIMARY KEY}. - -@item -A @code{PRIMARY KEY} can be a multiple-column index. However, you cannot -create a multiple-column index using the @code{PRIMARY KEY} key attibute in a -column specification. Doing so will mark only that single column as primary. -You must use the @code{PRIMARY KEY(index_col_name, ...)} syntax. - -@item -If the @code{PRIMARY} or @code{UNIQUE} key consists of only one column and this -is of type integer, you can also refer to it as @code{_rowid} -(new in Version 3.23.11). - -@item -If you don't assign a name to an index, the index will be assigned the same -name as the first @code{index_col_name}, with an optional suffix (@code{_2}, -@code{_3}, @code{...}) to make it unique. You can see index names for a -table using @code{SHOW INDEX FROM tbl_name}. -@xref{SHOW, , @code{SHOW}}. - -@item -@cindex @code{NULL} values, and indexes -@cindex indexes, and @code{NULL} values -Only the @code{MyISAM} table type supports indexes on columns that can have -@code{NULL} values. In other cases you must declare such columns -@code{NOT NULL} or an error results. - -@item -With @code{col_name(length)} syntax, you can specify an index that -uses only a part of a @code{CHAR} or @code{VARCHAR} column. This can -make the index file much smaller. -@xref{Indexes}. - -@item -@cindex @code{BLOB} columns, indexing -@cindex indexes, and @code{BLOB} columns -@cindex @code{TEXT} columns, indexing -@cindex indexes, and @code{TEXT} columns -Only the @code{MyISAM} table type supports indexing on @code{BLOB} and -@code{TEXT} columns. When putting an index on a @code{BLOB} or @code{TEXT} -column you MUST always specify the length of the index: -@example -CREATE TABLE test (blob_col BLOB, index(blob_col(10))); -@end example - -@item -When you use @code{ORDER BY} or @code{GROUP BY} with a @code{TEXT} or -@code{BLOB} column, only the first @code{max_sort_length} bytes are used. -@xref{BLOB, , @code{BLOB}}. - -@item -In @strong{MySQL} Version 3.23.23 or later, you can also create special -@strong{FULLTEXT} indexes. They are used for full-text search. Only the -@code{MyISAM} table type supports @code{FULLTEXT} indexes. They can be created -only from @code{VARCHAR} and @code{TEXT} columns. -Indexing always happens over the entire column, partial indexing is not -supported. See @ref{Fulltext Search} for details of operation. - -@item -The @code{FOREIGN KEY}, @code{CHECK}, and @code{REFERENCES} clauses don't -actually do anything. The syntax for them is provided only for compatibility, -to make it easier to port code from other SQL servers and to run applications -that create tables with references. -@xref{Missing functions}. - -@item -Each @code{NULL} column takes one bit extra, rounded up to the nearest byte. - -@item -The maximum record length in bytes can be calculated as follows: - -@example -row length = 1 - + (sum of column lengths) - + (number of NULL columns + 7)/8 - + (number of variable-length columns) -@end example - -@item -The @code{table_options} and @code{SELECT} options are only -implemented in @strong{MySQL} Version 3.23 and above. - -The different table types are: - -@multitable @columnfractions .20 .80 -@item BDB or Berkeley_db @tab Transaction-safe tables with page locking. @xref{BDB}. -@item HEAP @tab The data for this table is only stored in memory. @xref{HEAP}. -@item ISAM @tab The original table handler. @xref{ISAM}. -@item InnoDB @tab Transaction-safe tables with row locking. @xref{InnoDB}. -@item MERGE @tab A collection of MyISAM tables used as one table. @xref{MERGE}. -@item MyISAM @tab The new binary portable table handler that is replacing ISAM. @xref{MyISAM}. -@end multitable -@xref{Table types}. - -If a table type is specified, and that particular type is not available, -@strong{MySQL} will choose the closest table type to the one that you have -specified. For example, if @code{TYPE=BDB} is specified, and that distribution -of @strong{MySQL} does not support @code{BDB} tables, the table will be created -as @code{MyISAM} instead. - -The other table options are used to optimize the behavior of the -table. In most cases, you don't have to specify any of them. -The options work for all table types, if not otherwise indicated: - -@multitable @columnfractions .20 .80 -@item @code{AUTO_INCREMENT} @tab The next auto_increment value you want to set for your table (MyISAM). -@item @code{AVG_ROW_LENGTH} @tab An approximation of the average row length for your table. You only need to set this for large tables with variable size records. -@item @code{CHECKSUM} @tab Set this to 1 if you want @strong{MySQL} to maintain a checksum for all rows (makes the table a little slower to update but makes it easier to find corrupted tables) (MyISAM). -@item @code{COMMENT} @tab A 60-character comment for your table. -@item @code{MAX_ROWS} @tab Max number of rows you plan to store in the table. -@item @code{MIN_ROWS} @tab Minimum number of rows you plan to store in the table. -@item @code{PACK_KEYS} @tab Set this to 1 if you want to have a smaller index. This usually makes updates slower and reads faster (MyISAM, ISAM). -@item @code{PASSWORD} @tab Encrypt the @code{.frm} file with a password. This option doesn't do anything in the standard @strong{MySQL} version. -@item @code{DELAY_KEY_WRITE} @tab Set this to 1 if want to delay key table updates until the table is closed (MyISAM). -@item @code{ROW_FORMAT} @tab Defines how the rows should be stored. Currently you can only use the DYNAMIC and STATIC options for MyISAM tables. -@end multitable - -When you use a @code{MyISAM} table, @strong{MySQL} uses the product of -@code{max_rows * avg_row_length} to decide how big the resulting table -will be. If you don't specify any of the above options, the maximum size -for a table will be 4G (or 2G if your operating systems only supports 2G -tables). The reason for this is just to keep down the pointer sizes -to make the index smaller and faster if you don't really need big files. - -If you don't use @code{PACK_KEYS}, the default is to only pack strings, -not numbers. If you use @code{PACK_KEYS=1}, numbers will be packed as well. - -When packing binary number keys, @strong{MySQL} will use prefix compression. -This means that you will only get a big benefit of this if you have -many numbers that are the same. Prefix compression means that every -key needs one extra byte to indicate how many bytes of the previous key are -the same for the next key (note that the pointer to the row is stored -in high-byte-first-order directly after the key, to improve -compression.) This means that if you have many equal keys on two rows -in a row, all following 'same' keys will usually only take 2 bytes -(including the pointer to the row). Compare this to the ordinary case -where the following keys will take storage_size_for_key + -pointer_size (usually 4). On the other hand, if all keys are -totally different, you will lose 1 byte per key, if the key isn't a -key that can have @code{NULL} values (In this case the packed key length will -be stored in the same byte that is used to mark if a key is @code{NULL}.) - -@item -If you specify a @code{SELECT} after the @code{CREATE} statement, -@strong{MySQL} will create new fields for all elements in the -@code{SELECT}. For example: - -@example -mysql> CREATE TABLE test (a int not null auto_increment, - primary key (a), key(b)) - TYPE=MyISAM SELECT b,c from test2; -@end example - -This will create a @code{MyISAM} table with three columns, a, b, and c. -Notice that the columns from the @code{SELECT} statement are appended to -the right side of the table, not overlapped onto it. Take the following -example: - -@example -mysql> select * from foo; -+---+ -| n | -+---+ -| 1 | -+---+ - -mysql> create table bar (m int) select n from foo; -Query OK, 1 row affected (0.02 sec) -Records: 1 Duplicates: 0 Warnings: 0 - -mysql> select * from bar; -+------+---+ -| m | n | -+------+---+ -| NULL | 1 | -+------+---+ -1 row in set (0.00 sec) -@end example - -For each row in table @code{foo}, a row is inserted in @code{bar} with -the values from @code{foo} and default values for the new columns. - -@code{CREATE TABLE ... SELECT} will not automaticly create any indexes -for you. This is done intentionally to make the command as flexible as -possible. If you want to have indexes in the created table, you should -specify these before the @code{SELECT} statement: - -@example -mysql> create table bar (unique (n)) select n from foo; -@end example - -If any errors occur while copying the data to the table, it will -automatically be deleted. - -To ensure that the update log/binary log can be used to re-create the -original tables, @strong{MySQL} will not allow concurrent inserts during -@code{CREATE TABLE .... SELECT}. -@item -The @code{RAID_TYPE} option will help you to break the 2G/4G limit for -the MyISAM data file (not the index file) on -operating systems that don't support big files. You can get also more speed -from the I/O bottleneck by putting @code{RAID} directories on different -physical disks. @code{RAID_TYPE} will work on any OS, as long as you have -configured @strong{MySQL} with @code{--with-raid}. For now the only allowed -@code{RAID_TYPE} is @code{STRIPED} (@code{1} and @code{RAID0} are aliases -for this). - -If you specify @code{RAID_TYPE=STRIPED} for a @code{MyISAM} table, -@code{MyISAM} will create @code{RAID_CHUNKS} subdirectories named 00, -01, 02 in the database directory. In each of these directories -@code{MyISAM} will create a @code{table_name.MYD}. When writing data -to the data file, the @code{RAID} handler will map the first -@code{RAID_CHUNKSIZE} *1024 bytes to the first file, the next -@code{RAID_CHUNKSIZE} *1024 bytes to the next file and so on. -@item -@code{UNION} is used when you want to use a collection of identical -tables as one. This only works with MERGE tables. @xref{MERGE}. - -For the moment you need to have @code{SELECT}, @code{UPDATE}, and -@code{DELETE} privileges on the tables you map to a @code{MERGE} table. -All mapped tables must be in the same database as the @code{MERGE} table. -@item -In the created table the @code{PRIMARY} key will be placed first, followed -by all @code{UNIQUE} keys and then the normal keys. This helps the -@strong{MySQL} optimizer to prioritize which key to use and also more quickly -detect duplicated @code{UNIQUE} keys. - -@item -By using @code{DATA DIRECTORY="directory"} or @code{INDEX -DIRECTORY="directory"} you can specify where the table handler should -put it's table and index files. This only works for @code{MyISAM} tables -in @code{MySQL} 4.0, when you are not using the @code{--skip-symlink} -option. @xref{Symbolic links to tables}. - -@end itemize - -@cindex silent column changes -@node Silent column changes, , CREATE TABLE, CREATE TABLE -@subsection Silent Column Specification Changes - -In some cases, @strong{MySQL} silently changes a column specification from -that given in a @code{CREATE TABLE} statement. (This may also occur with -@code{ALTER TABLE}.): - -@itemize @bullet -@item -@code{VARCHAR} columns with a length less than four are changed to -@code{CHAR}. - -@item -If any column in a table has a variable length, the entire row is -variable-length as a result. Therefore, if a table contains any -variable-length columns (@code{VARCHAR}, @code{TEXT}, or @code{BLOB}), -all @code{CHAR} columns longer than three characters are changed to -@code{VARCHAR} columns. This doesn't affect how you use the columns in -any way; in @strong{MySQL}, @code{VARCHAR} is just a different way to -store characters. @strong{MySQL} performs this conversion because it -saves space and makes table operations faster. @xref{Table types}. - -@item -@code{TIMESTAMP} display sizes must be even and in the range from 2 to 14. -If you specify a display size of 0 or greater than 14, the size is coerced -to 14. Odd-valued sizes in the range from 1 to 13 are coerced -to the next higher even number. - -@item -You cannot store a literal @code{NULL} in a @code{TIMESTAMP} column; setting -it to @code{NULL} sets it to the current date and time. Because -@code{TIMESTAMP} columns behave this way, the @code{NULL} and @code{NOT NULL} -attributes do not apply in the normal way and are ignored if you specify -them. @code{DESCRIBE tbl_name} always reports that a @code{TIMESTAMP} -column may be assigned @code{NULL} values. - -@item -@strong{MySQL} maps certain column types used by other SQL database vendors -to @strong{MySQL} types. @xref{Other-vendor column types}. -@end itemize - -If you want to see whether or not @strong{MySQL} used a column type other -than the one you specified, issue a @code{DESCRIBE tbl_name} statement after -creating or altering your table. - -@cindex @code{myisampack} -Certain other column type changes may occur if you compress a table -using @code{myisampack}. @xref{Compressed format}. - -@findex ALTER TABLE -@node ALTER TABLE, RENAME TABLE, CREATE TABLE, Reference -@section @code{ALTER TABLE} Syntax - -@example -ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...] - -alter_specification: - ADD [COLUMN] create_definition [FIRST | AFTER column_name ] - or ADD [COLUMN] (create_definition, create_definition,...) - or ADD INDEX [index_name] (index_col_name,...) - or ADD PRIMARY KEY (index_col_name,...) - or ADD UNIQUE [index_name] (index_col_name,...) - or ADD FULLTEXT [index_name] (index_col_name,...) - or ADD [CONSTRAINT symbol] FOREIGN KEY index_name (index_col_name,...) - [reference_definition] - or ALTER [COLUMN] col_name @{SET DEFAULT literal | DROP DEFAULT@} - or CHANGE [COLUMN] old_col_name create_definition - or MODIFY [COLUMN] create_definition - or DROP [COLUMN] col_name - or DROP PRIMARY KEY - or DROP INDEX index_name - or RENAME [TO] new_tbl_name - or ORDER BY col - or table_options -@end example - -@code{ALTER TABLE} allows you to change the structure of an existing table. -For example, you can add or delete columns, create or destroy indexes, change -the type of existing columns, or rename columns or the table itself. You can -also change the comment for the table and type of the table. -@xref{CREATE TABLE, , @code{CREATE TABLE}}. - -If you use @code{ALTER TABLE} to change a column specification but -@code{DESCRIBE tbl_name} indicates that your column was not changed, it is -possible that @strong{MySQL} ignored your modification for one of the reasons -described in @ref{Silent column changes}. For example, if you try to change -a @code{VARCHAR} column to @code{CHAR}, @strong{MySQL} will still use -@code{VARCHAR} if the table contains other variable-length columns. - -@code{ALTER TABLE} works by making a temporary copy of the original table. -The alteration is performed on the copy, then the original table is -deleted and the new one is renamed. This is done in such a way that -all updates are automatically redirected to the new table without -any failed updates. While @code{ALTER TABLE} is executing, the original -table is readable by other clients. Updates and writes to the table -are stalled until the new table is ready. - -Note that if you use any other option to @code{ALTER TABLE} than -@code{RENAME}, @strong{MySQL} will always create a temporary table, even -if the data wouldn't strictly need to be copied (like when you change the -name of a column). We plan to fix this in the future, but as one doesn't -normally do @code{ALTER TABLE} that often this isn't that high on our TODO. - -@itemize @bullet -@item -To use @code{ALTER TABLE}, you need @strong{ALTER}, @strong{INSERT}, -and @strong{CREATE} privileges on the table. - -@item -@code{IGNORE} is a @strong{MySQL} extension to ANSI SQL92. -It controls how @code{ALTER TABLE} works if there are duplicates on -unique keys in the new table. -If @code{IGNORE} isn't specified, the copy is aborted and rolled back. -If @code{IGNORE} is specified, then for rows with duplicates on a unique -key, only the first row is used; the others are deleted. - -@item -You can issue multiple @code{ADD}, @code{ALTER}, @code{DROP}, and -@code{CHANGE} clauses in a single @code{ALTER TABLE} statement. This is a -@strong{MySQL} extension to ANSI SQL92, which allows only one of each clause -per @code{ALTER TABLE} statement. - -@item -@code{CHANGE col_name}, @code{DROP col_name}, and @code{DROP -INDEX} are @strong{MySQL} extensions to ANSI SQL92. - -@item -@code{MODIFY} is an Oracle extension to @code{ALTER TABLE}. - -@item -The optional word @code{COLUMN} is a pure noise word and can be omitted. - -@item -If you use @code{ALTER TABLE tbl_name RENAME TO new_name} without any other -options, @strong{MySQL} simply renames the files that correspond to the table -@code{tbl_name}. There is no need to create the temporary table. -@xref{RENAME TABLE,, @code{RENAME TABLE}}. - -@item -@code{create_definition} clauses use the same syntax for @code{ADD} and -@code{CHANGE} as for @code{CREATE TABLE}. Note that this syntax includes -the column name, not just the column type. -@xref{CREATE TABLE, , @code{CREATE TABLE}}. - -@item -You can rename a column using a @code{CHANGE old_col_name create_definition} -clause. To do so, specify the old and new column names and the type that -the column currently has. For example, to rename an @code{INTEGER} column -from @code{a} to @code{b}, you can do this: - -@example -mysql> ALTER TABLE t1 CHANGE a b INTEGER; -@end example - -If you want to change a column's type but not the name, @code{CHANGE} -syntax still requires two column names even if they are the same. For -example: - -@example -mysql> ALTER TABLE t1 CHANGE b b BIGINT NOT NULL; -@end example - -However, as of @strong{MySQL} Version 3.22.16a, you can also use @code{MODIFY} -to change a column's type without renaming it: - -@example -mysql> ALTER TABLE t1 MODIFY b BIGINT NOT NULL; -@end example - -@item -If you use @code{CHANGE} or @code{MODIFY} to shorten a column for which -an index exists on part of the column (for instance, if you have an index -on the first 10 characters of a @code{VARCHAR} column), you cannot make -the column shorter than the number of characters that are indexed. - -@item -When you change a column type using @code{CHANGE} or @code{MODIFY}, -@strong{MySQL} tries to convert data to the new type as well as possible. - -@item -In @strong{MySQL} Version 3.22 or later, you can use @code{FIRST} or -@code{ADD ... AFTER col_name} to add a column at a specific position within -a table row. The default is to add the column last. - -@findex ALTER COLUMN -@item -@code{ALTER COLUMN} specifies a new default value for a column -or removes the old default value. -If the old default is removed and the column can be @code{NULL}, the new -default is @code{NULL}. If the column cannot be @code{NULL}, @strong{MySQL} -assigns a default value, as described in -@ref{CREATE TABLE, , @code{CREATE TABLE}}. - -@findex DROP INDEX -@item -@code{DROP INDEX} removes an index. This is a @strong{MySQL} extension to -ANSI SQL92. @xref{DROP INDEX}. - -@item -If columns are dropped from a table, the columns are also removed from any -index of which they are a part. If all columns that make up an index are -dropped, the index is dropped as well. - -@item -If a table contains only one column, the column cannot be dropped. -If what you intend is to remove the table, use @code{DROP TABLE} instead. - -@findex DROP PRIMARY KEY -@item -@code{DROP PRIMARY KEY} drops the primary index. If no such -index exists, it drops the first @code{UNIQUE} index in the table. -(@strong{MySQL} marks the first @code{UNIQUE} key as the @code{PRIMARY KEY} -if no @code{PRIMARY KEY} was specified explicitly.) - -@findex ORDER BY -@item -@code{ORDER BY} allows you to create the new table with the rows in a -specific order. Note that the table will not remain in this order after -inserts and deletes. In some cases, it may make sorting easier for -@strong{MySQL} if the table is in order by the column that you wish to -order it by later. This option is mainly useful when you know that you -are mostly going to query the rows in a certain order; By using this -option after big changes to the table, you may be able to get higher -performance. - -@findex ALTER TABLE -@item -If you use @code{ALTER TABLE} on a @code{MyISAM} table, all non-unique -indexes are created in a separate batch (like in @code{REPAIR}). -This should make @code{ALTER TABLE} much faster when you have many indexes. - -@item -@findex mysql_info() -With the C API function @code{mysql_info()}, you can find out how many -records were copied, and (when @code{IGNORE} is used) how many records were -deleted due to duplication of unique key values. - -@item -@cindex foreign keys -@cindex references -The @code{FOREIGN KEY}, @code{CHECK}, and @code{REFERENCES} clauses don't -actually do anything. The syntax for them is provided only for compatibility, -to make it easier to port code from other SQL servers and to run applications -that create tables with references. -@xref{Missing functions}. -@end itemize - -Here is an example that shows some of the uses of @code{ALTER TABLE}. We -begin with a table @code{t1} that is created as shown below: - -@example -mysql> CREATE TABLE t1 (a INTEGER,b CHAR(10)); -@end example - -To rename the table from @code{t1} to @code{t2}: - -@example -mysql> ALTER TABLE t1 RENAME t2; -@end example - -To change column @code{a} from @code{INTEGER} to @code{TINYINT NOT NULL} -(leaving the name the same), and to change column @code{b} from -@code{CHAR(10)} to @code{CHAR(20)} as well as renaming it from @code{b} to -@code{c}: - -@example -mysql> ALTER TABLE t2 MODIFY a TINYINT NOT NULL, CHANGE b c CHAR(20); -@end example - -To add a new @code{TIMESTAMP} column named @code{d}: - -@example -mysql> ALTER TABLE t2 ADD d TIMESTAMP; -@end example - -To add an index on column @code{d}, and make column @code{a} the primary key: - -@example -mysql> ALTER TABLE t2 ADD INDEX (d), ADD PRIMARY KEY (a); -@end example - -To remove column @code{c}: - -@example -mysql> ALTER TABLE t2 DROP COLUMN c; -@end example - -To add a new @code{AUTO_INCREMENT} integer column named @code{c}: - -@example -mysql> ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, - ADD INDEX (c); -@end example - -Note that we indexed @code{c}, because @code{AUTO_INCREMENT} columns must be -indexed, and also that we declare @code{c} as @code{NOT NULL}, because -indexed columns cannot be @code{NULL}. - -When you add an @code{AUTO_INCREMENT} column, column values are filled in -with sequence numbers for you automatically. You can set the first -sequence number by executing @code{SET INSERT_ID=#} before -@code{ALTER TABLE} or using the @code{AUTO_INCREMENT = #} table option. -@xref{SET OPTION}. - -With MyISAM tables, if you don't change the @code{AUTO_INCREMENT} -column, the sequence number will not be affected. If you drop an -@code{AUTO_INCREMENT} column and then add another @code{AUTO_INCREMENT} -column, the numbers will start from 1 again. - -@xref{ALTER TABLE problems}. - -@findex RENAME TABLE -@node RENAME TABLE, DROP TABLE, ALTER TABLE, Reference -@section @code{RENAME TABLE} Syntax - -@example -RENAME TABLE tbl_name TO new_table_name[, tbl_name2 TO new_table_name2,...] -@end example - -The rename is done atomically, which means that no other thread can -access any of the tables while the rename is running. This makes it -possible to replace a table with an empty one: - -@example -CREATE TABLE new_table (...); -RENAME TABLE old_table TO backup_table, new_table TO old_table; -@end example - -The rename is done from left to right, which means that if you want to -swap two tables names, you have to: - -@example -RENAME TABLE old_table TO backup_table, - new_table TO old_table, - backup_table TO new_table; -@end example - -As long as two databases are on the same disk you can also rename -from one database to another: - -@example -RENAME TABLE current_database.table_name TO other_database.table_name; -@end example - -When you execute @code{RENAME}, you can't have any locked tables or -active transactions. You must also have the @code{ALTER} and @code{DROP} -privilege on the original table and @code{CREATE} and @code{INSERT} -privilege on the new table. - -If @strong{MySQL} encounters any errors in a multiple table rename, it -will do a reverse rename for all renamed tables to get everything back -to the original state. - -@findex DROP TABLE -@node DROP TABLE, DELETE, RENAME TABLE, Reference -@section @code{DROP TABLE} Syntax - -@example -DROP TABLE [IF EXISTS] tbl_name [, tbl_name,...] [RESTRICT | CASCADE] -@end example - -@code{DROP TABLE} removes one or more tables. All table data and the table -definition are @emph{removed}, so @strong{be careful} with this command! - -In @strong{MySQL} Version 3.22 or later, you can use the keywords -@code{IF EXISTS} to prevent an error from occurring for tables that don't -exist. - -@code{RESTRICT} and @code{CASCADE} are allowed to make porting easier. -For the moment they don't do anything. - -@strong{NOTE}: @code{DROP TABLE} is not transaction-safe and will -automatically commit any active transactions. - - -@node DELETE, TRUNCATE, DROP TABLE, Reference -@section @code{DELETE} Syntax - -@findex DELETE - -@example -DELETE [LOW_PRIORITY] FROM tbl_name - [WHERE where_definition] - [LIMIT rows] -@end example - -@code{DELETE} deletes rows from @code{tbl_name} that satisfy the condition -given by @code{where_definition}, and returns the number of records deleted. - -@c If an @code{ORDER BY} clause is used, the rows will be deleted in that order. -@c This is really only useful in conjunction with @code{LIMIT}. For example: - -@c @example -@c DELETE FROM somelog -@c WHERE user = 'jcole' -@c ORDER BY timestamp -@c LIMIT 1 -@c @end example - -@c This will delete the oldest entry (by @code{timestamp}) where the row matches -@c the @code{WHERE} clause. - -If you issue a @code{DELETE} with no @code{WHERE} clause, all rows are -deleted. If you do this in @code{AUTOCOMMIT} mode, this works as -@code{TRUNCATE}. @xref{TRUNCATE}. One problem with this is that -@code{DELETE} will return zero as the number of affected records, but -this will be fixed in 4.0. - -If you really want to know how many records are deleted when you are deleting -all rows, and are willing to suffer a speed penalty, you can use a -@code{DELETE} statement of this form: - -@example -mysql> DELETE FROM tbl_name WHERE 1>0; -@end example - -Note that this is MUCH slower than @code{DELETE FROM tbl_name} with no -@code{WHERE} clause, because it deletes rows one at a time. - -If you specify the keyword @code{LOW_PRIORITY}, execution of the -@code{DELETE} is delayed until no other clients are reading from the table. - -Deleted records are maintained in a linked list and subsequent @code{INSERT} -operations reuse old record positions. To reclaim unused space and reduce -file sizes, use the @code{OPTIMIZE TABLE} statement or the @code{myisamchk} -utility to reorganize tables. @code{OPTIMIZE TABLE} is easier, but -@code{myisamchk} is faster. -See @ref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}} and @ref{Optimization}. - -The @strong{MySQL}-specific @code{LIMIT rows} option to @code{DELETE} tells -the server the maximum number of rows to be deleted before control is -returned to the client. This can be used to ensure that a specific -@code{DELETE} command doesn't take too much time. You can simply repeat -the @code{DELETE} command until the number of affected rows is less than -the @code{LIMIT} value. - -@findex TRUNCATE -@node TRUNCATE, SELECT, DELETE, Reference -@section @code{TRUNCATE} Syntax - -@example -TRUNCATE TABLE table_name -@end example - -Is in 3.23 and the same thing as @code{DELETE FROM table_name}. @xref{DELETE}. -The differences are: - -@itemize @bullet -@item -Implemented as a drop and re-create of the table, which makes this -much faster when deleting many rows. -@item -Not transaction-safe; @code{TRUNCATE TABLE} will automatically end the current -transaction as if @code{COMMIT} would have been called. -@item -Doesn't return the number of deleted rows. -@item -As long as the table definition file @file{table_name.frm} is -valid, the table can be re-created this way, even if the data or index -files have become corrupted. -@end itemize - -@code{TRUNCATE} is an Oracle SQL extension. +@node SELECT, INSERT, Data Manipulation, Data Manipulation +@subsection @code{SELECT} Syntax @findex SELECT -@node SELECT, JOIN, TRUNCATE, Reference -@section @code{SELECT} Syntax @c help SELECT @example @@ -32782,6 +31903,14 @@ If you are using @code{FOR UPDATE} on a table handler with page/row locks, the examined rows will be write locked. @end itemize + +@menu +* JOIN:: +@end menu + +@node JOIN, , SELECT, SELECT +@subsubsection @code{JOIN} Syntax + @findex JOIN @findex INNER JOIN @findex CROSS JOIN @@ -32794,8 +31923,6 @@ the examined rows will be write locked. @findex NATURAL RIGHT JOIN @findex NATURAL RIGHT OUTER JOIN @findex STRAIGHT_JOIN -@node JOIN, INSERT, SELECT, Reference -@section @code{JOIN} Syntax @strong{MySQL} supports the following @code{JOIN} syntaxes for use in @code{SELECT} statements: @@ -32928,9 +32055,11 @@ mysql> select * from table1 IGNORE INDEX (key3) WHERE key1=1 and key2=2 AND @xref{LEFT JOIN optimization, , @code{LEFT JOIN} optimization}. + +@node INSERT, INSERT DELAYED, SELECT, Data Manipulation +@subsection @code{INSERT} Syntax + @findex INSERT -@node INSERT, REPLACE, JOIN, Reference -@section @code{INSERT} Syntax @example INSERT [LOW_PRIORITY | DELAYED] [IGNORE] @@ -33056,13 +32185,14 @@ type. The column is set to the appropriate zero value for the type. @findex REPLACE ... SELECT @findex INSERT ... SELECT + @menu * INSERT SELECT:: -* INSERT DELAYED:: @end menu -@node INSERT SELECT, INSERT DELAYED, INSERT, INSERT -@subsection @code{INSERT ... SELECT} Syntax + +@node INSERT SELECT, , INSERT, INSERT +@subsubsection @code{INSERT ... SELECT} Syntax @example INSERT [LOW_PRIORITY] [IGNORE] [INTO] tbl_name [(column list)] SELECT ... @@ -33106,11 +32236,14 @@ original tables, @strong{MySQL} will not allow concurrent inserts during You can of course also use @code{REPLACE} instead of @code{INSERT} to overwrite old rows. + +@node INSERT DELAYED, UPDATE, INSERT, Data Manipulation +@subsection @code{INSERT DELAYED} syntax + @findex INSERT DELAYED @findex DELAYED + @cindex INSERT DELAYED -@node INSERT DELAYED, , INSERT SELECT, INSERT -@subsection @code{INSERT DELAYED} syntax @example INSERT DELAYED ... @@ -33236,9 +32369,145 @@ server to handle a separate thread for each table on which you use @code{INSERT DELAYED}. This means that you should only use @code{INSERT DELAYED} when you are really sure you need it! + +@node UPDATE, DELETE, INSERT DELAYED, Data Manipulation +@subsection @code{UPDATE} Syntax + +@findex UPDATE + +@example +UPDATE [LOW_PRIORITY] [IGNORE] tbl_name + SET col_name1=expr1, [col_name2=expr2, ...] + [WHERE where_definition] + [LIMIT #] +@end example + +@code{UPDATE} updates columns in existing table rows with new values. +The @code{SET} clause indicates which columns to modify and the values +they should be given. The @code{WHERE} clause, if given, specifies +which rows should be updated. Otherwise all rows are updated. If the +@code{ORDER BY} clause is specified, the rows will be updated in the +order that is specified. + +If you specify the keyword @code{LOW_PRIORITY}, execution of the +@code{UPDATE} is delayed until no other clients are reading from the table. + +If you specify the keyword @code{IGNORE}, the update statement will not +abort even if we get duplicate key errors during the update. Rows that +would cause conflicts will not be updated. + +If you access a column from @code{tbl_name} in an expression, +@code{UPDATE} uses the current value of the column. For example, the +following statement sets the @code{age} column to one more than its +current value: + +@example +mysql> UPDATE persondata SET age=age+1; +@end example + +@code{UPDATE} assignments are evaluated from left to right. For example, the +following statement doubles the @code{age} column, then increments it: + +@example +mysql> UPDATE persondata SET age=age*2, age=age+1; +@end example + +If you set a column to the value it currently has, @strong{MySQL} notices +this and doesn't update it. + +@findex mysql_info() +@code{UPDATE} returns the number of rows that were actually changed. +In @strong{MySQL} Version 3.22 or later, the C API function @code{mysql_info()} +returns the number of rows that were matched and updated and the number of +warnings that occurred during the @code{UPDATE}. + +In @strong{MySQL} Version 3.23, you can use @code{LIMIT #} to ensure that +only a given number of rows are changed. + + +@node DELETE, TRUNCATE, UPDATE, Data Manipulation +@subsection @code{DELETE} Syntax + +@findex DELETE + +@example +DELETE [LOW_PRIORITY] FROM tbl_name + [WHERE where_definition] + [LIMIT rows] +@end example + +@code{DELETE} deletes rows from @code{tbl_name} that satisfy the condition +given by @code{where_definition}, and returns the number of records deleted. + +If you issue a @code{DELETE} with no @code{WHERE} clause, all rows are +deleted. If you do this in @code{AUTOCOMMIT} mode, this works as +@code{TRUNCATE}. @xref{TRUNCATE}. One problem with this is that +@code{DELETE} will return zero as the number of affected records, but +this will be fixed in 4.0. + +If you really want to know how many records are deleted when you are deleting +all rows, and are willing to suffer a speed penalty, you can use a +@code{DELETE} statement of this form: + +@example +mysql> DELETE FROM tbl_name WHERE 1>0; +@end example + +Note that this is MUCH slower than @code{DELETE FROM tbl_name} with no +@code{WHERE} clause, because it deletes rows one at a time. + +If you specify the keyword @code{LOW_PRIORITY}, execution of the +@code{DELETE} is delayed until no other clients are reading from the table. + +Deleted records are maintained in a linked list and subsequent @code{INSERT} +operations reuse old record positions. To reclaim unused space and reduce +file sizes, use the @code{OPTIMIZE TABLE} statement or the @code{myisamchk} +utility to reorganize tables. @code{OPTIMIZE TABLE} is easier, but +@code{myisamchk} is faster. +See @ref{OPTIMIZE TABLE, , @code{OPTIMIZE TABLE}} and @ref{Optimization}. + +The @strong{MySQL}-specific @code{LIMIT rows} option to @code{DELETE} tells +the server the maximum number of rows to be deleted before control is +returned to the client. This can be used to ensure that a specific +@code{DELETE} command doesn't take too much time. You can simply repeat +the @code{DELETE} command until the number of affected rows is less than +the @code{LIMIT} value. + + +@node TRUNCATE, REPLACE, DELETE, Data Manipulation +@subsection @code{TRUNCATE} Syntax + +@findex TRUNCATE + +@example +TRUNCATE TABLE table_name +@end example + +Is in 3.23 and the same thing as @code{DELETE FROM table_name}. @xref{DELETE}. +The differences are: + +@itemize @bullet +@item +Implemented as a drop and re-create of the table, which makes this +much faster when deleting many rows. +@item +Not transaction-safe; @code{TRUNCATE TABLE} will automatically end the current +transaction as if @code{COMMIT} would have been called. +@item +Doesn't return the number of deleted rows. +@item +As long as the table definition file @file{table_name.frm} is +valid, the table can be re-created this way, even if the data or index +files have become corrupted. +@end itemize + +@code{TRUNCATE} is an Oracle SQL extension. + + +@node REPLACE, LOAD DATA, TRUNCATE, Data Manipulation +@subsection @code{REPLACE} Syntax + @findex REPLACE -@node REPLACE, LOAD DATA, INSERT, Reference -@section @code{REPLACE} Syntax @example REPLACE [LOW_PRIORITY | DELAYED] @@ -33268,9 +32537,11 @@ this case one row was inserted and then the duplicate was deleted. The above makes it easy to check if @code{REPLACE} added or replaced a row. + +@node LOAD DATA, , REPLACE, Data Manipulation +@subsection @code{LOAD DATA INFILE} Syntax + @findex LOAD DATA INFILE -@node LOAD DATA, UPDATE, REPLACE, Reference -@section @code{LOAD DATA INFILE} Syntax @example LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL] INFILE 'file_name.txt' @@ -33762,62 +33033,1015 @@ For more information about the efficiency of @code{INSERT} versus @code{LOAD DATA INFILE} and speeding up @code{LOAD DATA INFILE}, @xref{Insert speed}. -@findex UPDATE -@node UPDATE, USE, LOAD DATA, Reference -@section @code{UPDATE} Syntax + +@node Data Definition, DROP DATABASE, Data Manipulation, Reference +@section Data Definition: @code{CREATE}, @code{DROP}, @code{ALTER} + +@menu +* CREATE DATABASE:: +@end menu + + +@node CREATE DATABASE, , Data Definition, Data Definition +@subsection @code{CREATE DATABASE} Syntax + +@findex CREATE DATABASE @example -UPDATE [LOW_PRIORITY] [IGNORE] tbl_name - SET col_name1=expr1, [col_name2=expr2, ...] - [WHERE where_definition] - [LIMIT #] +CREATE DATABASE [IF NOT EXISTS] db_name @end example -@code{UPDATE} updates columns in existing table rows with new values. -The @code{SET} clause indicates which columns to modify and the values -they should be given. The @code{WHERE} clause, if given, specifies -which rows should be updated. Otherwise all rows are updated. If the -@code{ORDER BY} clause is specified, the rows will be updated in the -order that is specified. +@code{CREATE DATABASE} creates a database with the given name. Rules for +allowable database names are given in @ref{Legal names}. An error occurs if +the database already exists and you didn't specify @code{IF NOT EXISTS}. -If you specify the keyword @code{LOW_PRIORITY}, execution of the -@code{UPDATE} is delayed until no other clients are reading from the table. +Databases in @strong{MySQL} are implemented as directories containing files +that correspond to tables in the database. Because there are no tables in a +database when it is initially created, the @code{CREATE DATABASE} statement +only creates a directory under the @strong{MySQL} data directory. -If you specify the keyword @code{IGNORE}, the update statement will not -abort even if we get duplicate key errors during the update. Rows that -would cause conflicts will not be updated. +@cindex @code{mysqladmin} +You can also create databases with @code{mysqladmin}. +@xref{Client-Side Scripts}. -If you access a column from @code{tbl_name} in an expression, -@code{UPDATE} uses the current value of the column. For example, the -following statement sets the @code{age} column to one more than its -current value: + +@node DROP DATABASE, Basic User Commands, Data Definition, Reference +@section @code{DROP DATABASE} Syntax + +@findex DROP DATABASE @example -mysql> UPDATE persondata SET age=age+1; +DROP DATABASE [IF EXISTS] db_name @end example -@code{UPDATE} assignments are evaluated from left to right. For example, the -following statement doubles the @code{age} column, then increments it: +@code{DROP DATABASE} drops all tables in the database and deletes the +database. If you do a @code{DROP DATABASE} on a symbolic linked +database, both the link and the original database is deleted. @strong{Be +VERY careful with this command!} + +@code{DROP DATABASE} returns the number of files that were removed from +the database directory. Normally, this is three times the number of +tables, because normally each table corresponds to a @file{.MYD} file, a +@file{.MYI} file, and a @file{.frm} file. + +The @code{DROP DATABASE} command removes from the given database +directory all files with the following extensions: + +@multitable @columnfractions .25 .25 .25 .25 +@item .BAK @tab .DAT @tab .HSH @tab .ISD +@item .ISM @tab .ISM @tab .MRG @tab .MYD +@item .MYI @tab .db @tab .frm +@end multitable + +All subdirectories that consists of 2 digits (@code{RAID} directories) +are also removed. + +In @strong{MySQL} Version 3.22 or later, you can use the keywords +@code{IF EXISTS} to prevent an error from occurring if the database doesn't +exist. + +@cindex @code{mysqladmin} +You can also drop databases with @code{mysqladmin}. @xref{Client-Side Scripts}. + + +@menu +* CREATE TABLE:: +* ALTER TABLE:: +* RENAME TABLE:: +* DROP TABLE:: +* CREATE INDEX:: +* DROP INDEX:: +@end menu + +@node CREATE TABLE, ALTER TABLE, DROP DATABASE, DROP DATABASE +@subsection @code{CREATE TABLE} Syntax + +@findex CREATE TABLE + +@menu +* Silent column changes:: Silent column changes +@end menu @example -mysql> UPDATE persondata SET age=age*2, age=age+1; +CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)] +[table_options] [select_statement] + +create_definition: + col_name type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] + [PRIMARY KEY] [reference_definition] + or PRIMARY KEY (index_col_name,...) + or KEY [index_name] (index_col_name,...) + or INDEX [index_name] (index_col_name,...) + or UNIQUE [INDEX] [index_name] (index_col_name,...) + or FULLTEXT [INDEX] [index_name] (index_col_name,...) + or [CONSTRAINT symbol] FOREIGN KEY index_name (index_col_name,...) + [reference_definition] + or CHECK (expr) + +type: + TINYINT[(length)] [UNSIGNED] [ZEROFILL] + or SMALLINT[(length)] [UNSIGNED] [ZEROFILL] + or MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL] + or INT[(length)] [UNSIGNED] [ZEROFILL] + or INTEGER[(length)] [UNSIGNED] [ZEROFILL] + or BIGINT[(length)] [UNSIGNED] [ZEROFILL] + or REAL[(length,decimals)] [UNSIGNED] [ZEROFILL] + or DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL] + or FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL] + or DECIMAL(length,decimals) [UNSIGNED] [ZEROFILL] + or NUMERIC(length,decimals) [UNSIGNED] [ZEROFILL] + or CHAR(length) [BINARY] + or VARCHAR(length) [BINARY] + or DATE + or TIME + or TIMESTAMP + or DATETIME + or TINYBLOB + or BLOB + or MEDIUMBLOB + or LONGBLOB + or TINYTEXT + or TEXT + or MEDIUMTEXT + or LONGTEXT + or ENUM(value1,value2,value3,...) + or SET(value1,value2,value3,...) + +index_col_name: + col_name [(length)] + +reference_definition: + REFERENCES tbl_name [(index_col_name,...)] + [MATCH FULL | MATCH PARTIAL] + [ON DELETE reference_option] + [ON UPDATE reference_option] + +reference_option: + RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT + +table_options: + TYPE = @{BDB | HEAP | ISAM | InnoDB | MERGE | MYISAM @} +or AUTO_INCREMENT = # +or AVG_ROW_LENGTH = # +or CHECKSUM = @{0 | 1@} +or COMMENT = "string" +or MAX_ROWS = # +or MIN_ROWS = # +or PACK_KEYS = @{0 | 1@} +or PASSWORD = "string" +or DELAY_KEY_WRITE = @{0 | 1@} +or ROW_FORMAT= @{ default | dynamic | fixed | compressed @} +or RAID_TYPE= @{1 | STRIPED | RAID0 @} RAID_CHUNKS=# RAID_CHUNKSIZE=# +or UNION = (table_name,[table_name...]) +or DATA DIRECTORY="directory" +or INDEX DIRECTORY="directory" + +select_statement: + [IGNORE | REPLACE] SELECT ... (Some legal select statement) @end example -If you set a column to the value it currently has, @strong{MySQL} notices -this and doesn't update it. +@code{CREATE TABLE} +creates a table with the given name in the current database. Rules for +allowable table names are given in @ref{Legal names}. An error occurs if +there is no current database or if the table already exists. +In @strong{MySQL} Version 3.22 or later, the table name can be specified as +@code{db_name.tbl_name}. This works whether or not there is a current +database. + +In @strong{MySQL} Version 3.23, you can use the @code{TEMPORARY} keyword when +you create a table. A temporary table will automatically be deleted if a +connection dies and the name is per connection. This means that two different +connections can both use the same temporary table name without conflicting +with each other or with an existing table of the same name. (The existing table +is hidden until the temporary table is deleted). + +In @strong{MySQL} Version 3.23 or later, you can use the keywords +@code{IF NOT EXISTS} so that an error does not occur if the table already +exists. Note that there is no verification that the table structures are +identical. + +Each table @code{tbl_name} is represented by some files in the database +directory. In the case of MyISAM-type tables you will get: + +@multitable @columnfractions .2 .8 +@item @strong{File} @tab @strong{Purpose} +@item @code{tbl_name.frm} @tab Table definition (form) file +@item @code{tbl_name.MYD} @tab Data file +@item @code{tbl_name.MYI} @tab Index file +@end multitable + +For more information on the properties of the various column types, see +@ref{Column types}: + +@itemize @bullet +@item +If neither @code{NULL} nor @code{NOT NULL} is specified, the column +is treated as though @code{NULL} had been specified. + +@item +An integer column may have the additional attribute @code{AUTO_INCREMENT}. +When you insert a value of @code{NULL} (recommended) or @code{0} into an +@code{AUTO_INCREMENT} column, the column is set to @code{value+1}, where +@code{value} is the largest value for the column currently in the table. +@code{AUTO_INCREMENT} sequences begin with @code{1}. +@xref{mysql_insert_id, , @code{mysql_insert_id()}}. + +If you delete the row containing the maximum value for an +@code{AUTO_INCREMENT} column, the value will be reused with an +@code{ISAM}, or @code{BDB} table but not with a +@code{MyISAM} or @code{InnoDB} table. If you delete all rows in the table +with @code{DELETE FROM table_name} (without a @code{WHERE}) in +@code{AUTOCOMMIT} mode, the sequence starts over for all table types. + +@strong{NOTE:} There can be only one @code{AUTO_INCREMENT} column per +table, and it must be indexed. @strong{MySQL} Version 3.23 will also only +work properly if the auto_increment column only has positive +values. Inserting a negative number is regarded as inserting a very large +positive number. This is done to avoid precision problems when +numbers 'wrap' over from positive to negative and also to ensure that one +doesn't accidentally get an auto_increment column that contains 0. + +@cindex ODBC compatibility +@cindex compatibility, with ODBC +To make @strong{MySQL} compatible with some ODBC applications, you can find +the last inserted row with the following query: + +@example +SELECT * FROM tbl_name WHERE auto_col IS NULL +@end example + +@item +@code{NULL} values are handled differently for @code{TIMESTAMP} columns than +for other column types. You cannot store a literal @code{NULL} in a +@code{TIMESTAMP} column; setting the column to @code{NULL} sets it to the +current date and time. Because @code{TIMESTAMP} columns behave this way, the +@code{NULL} and @code{NOT NULL} attributes do not apply in the normal way and +are ignored if you specify them. + +On the other hand, to make it easier for @strong{MySQL} clients to use +@code{TIMESTAMP} columns, the server reports that such columns may be +assigned @code{NULL} values (which is true), even though @code{TIMESTAMP} +never actually will contain a @code{NULL} value. You can see this when you +use @code{DESCRIBE tbl_name} to get a description of your table. + +Note that setting a @code{TIMESTAMP} column to @code{0} is not the same +as setting it to @code{NULL}, because @code{0} is a valid @code{TIMESTAMP} +value. + +@item +If no @code{DEFAULT} value is specified for a column, @strong{MySQL} +automatically assigns one. + +If the column may take @code{NULL} as a value, the default value is +@code{NULL}. + +If the column is declared as @code{NOT NULL}, the default value depends on +the column type: + +@itemize @minus +@item +For numeric types other than those declared with the @code{AUTO_INCREMENT} +attribute, the default is @code{0}. For an @code{AUTO_INCREMENT} column, the +default value is the next value in the sequence. + +@item +For date and time types other than @code{TIMESTAMP}, the default is the +appropriate zero value for the type. For the first @code{TIMESTAMP} +column in a table, the default value is the current date and time. +@xref{Date and time types}. + +@item +For string types other than @code{ENUM}, the default value is the empty string. +For @code{ENUM}, the default is the first enumeration value. +@end itemize + +Default values must be constants. This means, for example, that you cannot +set the default for a date column to be the value of a function such as +@code{NOW()} or @code{CURRENT_DATE}. + +@item +@code{KEY} is a synonym for @code{INDEX}. + +@item +In @strong{MySQL}, a @code{UNIQUE} key can have only distinct values. An +error occurs if you try to add a new row with a key that matches an existing +row. + +@item +@tindex PRIMARY KEY +A @code{PRIMARY KEY} is a unique @code{KEY} with the extra constraint +that all key columns must be defined as @code{NOT NULL}. In @strong{MySQL} +the key is named @code{PRIMARY}. A table can have only one @code{PRIMARY KEY}. +If you don't have a @code{PRIMARY KEY} and some applications ask for the +@code{PRIMARY KEY} in your tables, @strong{MySQL} will return the first +@code{UNIQUE} key, which doesn't have any @code{NULL} columns, as the +@code{PRIMARY KEY}. + +@item +A @code{PRIMARY KEY} can be a multiple-column index. However, you cannot +create a multiple-column index using the @code{PRIMARY KEY} key attibute in a +column specification. Doing so will mark only that single column as primary. +You must use the @code{PRIMARY KEY(index_col_name, ...)} syntax. + +@item +If the @code{PRIMARY} or @code{UNIQUE} key consists of only one column and this +is of type integer, you can also refer to it as @code{_rowid} +(new in Version 3.23.11). + +@item +If you don't assign a name to an index, the index will be assigned the same +name as the first @code{index_col_name}, with an optional suffix (@code{_2}, +@code{_3}, @code{...}) to make it unique. You can see index names for a +table using @code{SHOW INDEX FROM tbl_name}. +@xref{SHOW, , @code{SHOW}}. + +@item +@cindex @code{NULL} values, and indexes +@cindex indexes, and @code{NULL} values +Only the @code{MyISAM} table type supports indexes on columns that can have +@code{NULL} values. In other cases you must declare such columns +@code{NOT NULL} or an error results. + +@item +With @code{col_name(length)} syntax, you can specify an index that +uses only a part of a @code{CHAR} or @code{VARCHAR} column. This can +make the index file much smaller. +@xref{Indexes}. + +@item +@cindex @code{BLOB} columns, indexing +@cindex indexes, and @code{BLOB} columns +@cindex @code{TEXT} columns, indexing +@cindex indexes, and @code{TEXT} columns +Only the @code{MyISAM} table type supports indexing on @code{BLOB} and +@code{TEXT} columns. When putting an index on a @code{BLOB} or @code{TEXT} +column you MUST always specify the length of the index: +@example +CREATE TABLE test (blob_col BLOB, index(blob_col(10))); +@end example + +@item +When you use @code{ORDER BY} or @code{GROUP BY} with a @code{TEXT} or +@code{BLOB} column, only the first @code{max_sort_length} bytes are used. +@xref{BLOB, , @code{BLOB}}. + +@item +In @strong{MySQL} Version 3.23.23 or later, you can also create special +@strong{FULLTEXT} indexes. They are used for full-text search. Only the +@code{MyISAM} table type supports @code{FULLTEXT} indexes. They can be created +only from @code{VARCHAR} and @code{TEXT} columns. +Indexing always happens over the entire column, partial indexing is not +supported. See @ref{Fulltext Search} for details of operation. + +@item +The @code{FOREIGN KEY}, @code{CHECK}, and @code{REFERENCES} clauses don't +actually do anything. The syntax for them is provided only for compatibility, +to make it easier to port code from other SQL servers and to run applications +that create tables with references. +@xref{Missing functions}. + +@item +Each @code{NULL} column takes one bit extra, rounded up to the nearest byte. + +@item +The maximum record length in bytes can be calculated as follows: + +@example +row length = 1 + + (sum of column lengths) + + (number of NULL columns + 7)/8 + + (number of variable-length columns) +@end example + +@item +The @code{table_options} and @code{SELECT} options are only +implemented in @strong{MySQL} Version 3.23 and above. + +The different table types are: + +@multitable @columnfractions .20 .80 +@item BDB or Berkeley_db @tab Transaction-safe tables with page locking. @xref{BDB}. +@item HEAP @tab The data for this table is only stored in memory. @xref{HEAP}. +@item ISAM @tab The original table handler. @xref{ISAM}. +@item InnoDB @tab Transaction-safe tables with row locking. @xref{InnoDB}. +@item MERGE @tab A collection of MyISAM tables used as one table. @xref{MERGE}. +@item MyISAM @tab The new binary portable table handler that is replacing ISAM. @xref{MyISAM}. +@end multitable +@xref{Table types}. + +If a table type is specified, and that particular type is not available, +@strong{MySQL} will choose the closest table type to the one that you have +specified. For example, if @code{TYPE=BDB} is specified, and that distribution +of @strong{MySQL} does not support @code{BDB} tables, the table will be created +as @code{MyISAM} instead. + +The other table options are used to optimize the behavior of the +table. In most cases, you don't have to specify any of them. +The options work for all table types, if not otherwise indicated: + +@multitable @columnfractions .20 .80 +@item @code{AUTO_INCREMENT} @tab The next auto_increment value you want to set for your table (MyISAM). +@item @code{AVG_ROW_LENGTH} @tab An approximation of the average row length for your table. You only need to set this for large tables with variable size records. +@item @code{CHECKSUM} @tab Set this to 1 if you want @strong{MySQL} to maintain a checksum for all rows (makes the table a little slower to update but makes it easier to find corrupted tables) (MyISAM). +@item @code{COMMENT} @tab A 60-character comment for your table. +@item @code{MAX_ROWS} @tab Max number of rows you plan to store in the table. +@item @code{MIN_ROWS} @tab Minimum number of rows you plan to store in the table. +@item @code{PACK_KEYS} @tab Set this to 1 if you want to have a smaller index. This usually makes updates slower and reads faster (MyISAM, ISAM). +@item @code{PASSWORD} @tab Encrypt the @code{.frm} file with a password. This option doesn't do anything in the standard @strong{MySQL} version. +@item @code{DELAY_KEY_WRITE} @tab Set this to 1 if want to delay key table updates until the table is closed (MyISAM). +@item @code{ROW_FORMAT} @tab Defines how the rows should be stored. Currently you can only use the DYNAMIC and STATIC options for MyISAM tables. +@end multitable + +When you use a @code{MyISAM} table, @strong{MySQL} uses the product of +@code{max_rows * avg_row_length} to decide how big the resulting table +will be. If you don't specify any of the above options, the maximum size +for a table will be 4G (or 2G if your operating systems only supports 2G +tables). The reason for this is just to keep down the pointer sizes +to make the index smaller and faster if you don't really need big files. + +If you don't use @code{PACK_KEYS}, the default is to only pack strings, +not numbers. If you use @code{PACK_KEYS=1}, numbers will be packed as well. + +When packing binary number keys, @strong{MySQL} will use prefix compression. +This means that you will only get a big benefit of this if you have +many numbers that are the same. Prefix compression means that every +key needs one extra byte to indicate how many bytes of the previous key are +the same for the next key (note that the pointer to the row is stored +in high-byte-first-order directly after the key, to improve +compression.) This means that if you have many equal keys on two rows +in a row, all following 'same' keys will usually only take 2 bytes +(including the pointer to the row). Compare this to the ordinary case +where the following keys will take storage_size_for_key + +pointer_size (usually 4). On the other hand, if all keys are +totally different, you will lose 1 byte per key, if the key isn't a +key that can have @code{NULL} values (In this case the packed key length will +be stored in the same byte that is used to mark if a key is @code{NULL}.) + +@item +If you specify a @code{SELECT} after the @code{CREATE} statement, +@strong{MySQL} will create new fields for all elements in the +@code{SELECT}. For example: + +@example +mysql> CREATE TABLE test (a int not null auto_increment, + primary key (a), key(b)) + TYPE=MyISAM SELECT b,c from test2; +@end example + +This will create a @code{MyISAM} table with three columns, a, b, and c. +Notice that the columns from the @code{SELECT} statement are appended to +the right side of the table, not overlapped onto it. Take the following +example: + +@example +mysql> select * from foo; ++---+ +| n | ++---+ +| 1 | ++---+ + +mysql> create table bar (m int) select n from foo; +Query OK, 1 row affected (0.02 sec) +Records: 1 Duplicates: 0 Warnings: 0 + +mysql> select * from bar; ++------+---+ +| m | n | ++------+---+ +| NULL | 1 | ++------+---+ +1 row in set (0.00 sec) +@end example + +For each row in table @code{foo}, a row is inserted in @code{bar} with +the values from @code{foo} and default values for the new columns. + +@code{CREATE TABLE ... SELECT} will not automaticly create any indexes +for you. This is done intentionally to make the command as flexible as +possible. If you want to have indexes in the created table, you should +specify these before the @code{SELECT} statement: + +@example +mysql> create table bar (unique (n)) select n from foo; +@end example + +If any errors occur while copying the data to the table, it will +automatically be deleted. + +To ensure that the update log/binary log can be used to re-create the +original tables, @strong{MySQL} will not allow concurrent inserts during +@code{CREATE TABLE .... SELECT}. +@item +The @code{RAID_TYPE} option will help you to break the 2G/4G limit for +the MyISAM data file (not the index file) on +operating systems that don't support big files. You can get also more speed +from the I/O bottleneck by putting @code{RAID} directories on different +physical disks. @code{RAID_TYPE} will work on any OS, as long as you have +configured @strong{MySQL} with @code{--with-raid}. For now the only allowed +@code{RAID_TYPE} is @code{STRIPED} (@code{1} and @code{RAID0} are aliases +for this). + +If you specify @code{RAID_TYPE=STRIPED} for a @code{MyISAM} table, +@code{MyISAM} will create @code{RAID_CHUNKS} subdirectories named 00, +01, 02 in the database directory. In each of these directories +@code{MyISAM} will create a @code{table_name.MYD}. When writing data +to the data file, the @code{RAID} handler will map the first +@code{RAID_CHUNKSIZE} *1024 bytes to the first file, the next +@code{RAID_CHUNKSIZE} *1024 bytes to the next file and so on. +@item +@code{UNION} is used when you want to use a collection of identical +tables as one. This only works with MERGE tables. @xref{MERGE}. + +For the moment you need to have @code{SELECT}, @code{UPDATE}, and +@code{DELETE} privileges on the tables you map to a @code{MERGE} table. +All mapped tables must be in the same database as the @code{MERGE} table. +@item +In the created table the @code{PRIMARY} key will be placed first, followed +by all @code{UNIQUE} keys and then the normal keys. This helps the +@strong{MySQL} optimizer to prioritize which key to use and also more quickly +detect duplicated @code{UNIQUE} keys. + +@item +By using @code{DATA DIRECTORY="directory"} or @code{INDEX +DIRECTORY="directory"} you can specify where the table handler should +put it's table and index files. This only works for @code{MyISAM} tables +in @code{MySQL} 4.0, when you are not using the @code{--skip-symlink} +option. @xref{Symbolic links to tables}. + +@end itemize + + +@node Silent column changes, , CREATE TABLE, CREATE TABLE +@subsubsection Silent Column Specification Changes + +@cindex silent column changes + +In some cases, @strong{MySQL} silently changes a column specification from +that given in a @code{CREATE TABLE} statement. (This may also occur with +@code{ALTER TABLE}.): + +@itemize @bullet +@item +@code{VARCHAR} columns with a length less than four are changed to +@code{CHAR}. + +@item +If any column in a table has a variable length, the entire row is +variable-length as a result. Therefore, if a table contains any +variable-length columns (@code{VARCHAR}, @code{TEXT}, or @code{BLOB}), +all @code{CHAR} columns longer than three characters are changed to +@code{VARCHAR} columns. This doesn't affect how you use the columns in +any way; in @strong{MySQL}, @code{VARCHAR} is just a different way to +store characters. @strong{MySQL} performs this conversion because it +saves space and makes table operations faster. @xref{Table types}. + +@item +@code{TIMESTAMP} display sizes must be even and in the range from 2 to 14. +If you specify a display size of 0 or greater than 14, the size is coerced +to 14. Odd-valued sizes in the range from 1 to 13 are coerced +to the next higher even number. + +@item +You cannot store a literal @code{NULL} in a @code{TIMESTAMP} column; setting +it to @code{NULL} sets it to the current date and time. Because +@code{TIMESTAMP} columns behave this way, the @code{NULL} and @code{NOT NULL} +attributes do not apply in the normal way and are ignored if you specify +them. @code{DESCRIBE tbl_name} always reports that a @code{TIMESTAMP} +column may be assigned @code{NULL} values. + +@item +@strong{MySQL} maps certain column types used by other SQL database vendors +to @strong{MySQL} types. @xref{Other-vendor column types}. +@end itemize + +If you want to see whether or not @strong{MySQL} used a column type other +than the one you specified, issue a @code{DESCRIBE tbl_name} statement after +creating or altering your table. + +@cindex @code{myisampack} +Certain other column type changes may occur if you compress a table +using @code{myisampack}. @xref{Compressed format}. + + +@node ALTER TABLE, RENAME TABLE, CREATE TABLE, DROP DATABASE +@subsection @code{ALTER TABLE} Syntax + +@findex ALTER TABLE + +@example +ALTER [IGNORE] TABLE tbl_name alter_spec [, alter_spec ...] + +alter_specification: + ADD [COLUMN] create_definition [FIRST | AFTER column_name ] + or ADD [COLUMN] (create_definition, create_definition,...) + or ADD INDEX [index_name] (index_col_name,...) + or ADD PRIMARY KEY (index_col_name,...) + or ADD UNIQUE [index_name] (index_col_name,...) + or ADD FULLTEXT [index_name] (index_col_name,...) + or ADD [CONSTRAINT symbol] FOREIGN KEY index_name (index_col_name,...) + [reference_definition] + or ALTER [COLUMN] col_name @{SET DEFAULT literal | DROP DEFAULT@} + or CHANGE [COLUMN] old_col_name create_definition + or MODIFY [COLUMN] create_definition + or DROP [COLUMN] col_name + or DROP PRIMARY KEY + or DROP INDEX index_name + or RENAME [TO] new_tbl_name + or ORDER BY col + or table_options +@end example + +@code{ALTER TABLE} allows you to change the structure of an existing table. +For example, you can add or delete columns, create or destroy indexes, change +the type of existing columns, or rename columns or the table itself. You can +also change the comment for the table and type of the table. +@xref{CREATE TABLE, , @code{CREATE TABLE}}. + +If you use @code{ALTER TABLE} to change a column specification but +@code{DESCRIBE tbl_name} indicates that your column was not changed, it is +possible that @strong{MySQL} ignored your modification for one of the reasons +described in @ref{Silent column changes}. For example, if you try to change +a @code{VARCHAR} column to @code{CHAR}, @strong{MySQL} will still use +@code{VARCHAR} if the table contains other variable-length columns. + +@code{ALTER TABLE} works by making a temporary copy of the original table. +The alteration is performed on the copy, then the original table is +deleted and the new one is renamed. This is done in such a way that +all updates are automatically redirected to the new table without +any failed updates. While @code{ALTER TABLE} is executing, the original +table is readable by other clients. Updates and writes to the table +are stalled until the new table is ready. + +Note that if you use any other option to @code{ALTER TABLE} than +@code{RENAME}, @strong{MySQL} will always create a temporary table, even +if the data wouldn't strictly need to be copied (like when you change the +name of a column). We plan to fix this in the future, but as one doesn't +normally do @code{ALTER TABLE} that often this isn't that high on our TODO. + +@itemize @bullet +@item +To use @code{ALTER TABLE}, you need @strong{ALTER}, @strong{INSERT}, +and @strong{CREATE} privileges on the table. + +@item +@code{IGNORE} is a @strong{MySQL} extension to ANSI SQL92. +It controls how @code{ALTER TABLE} works if there are duplicates on +unique keys in the new table. +If @code{IGNORE} isn't specified, the copy is aborted and rolled back. +If @code{IGNORE} is specified, then for rows with duplicates on a unique +key, only the first row is used; the others are deleted. + +@item +You can issue multiple @code{ADD}, @code{ALTER}, @code{DROP}, and +@code{CHANGE} clauses in a single @code{ALTER TABLE} statement. This is a +@strong{MySQL} extension to ANSI SQL92, which allows only one of each clause +per @code{ALTER TABLE} statement. + +@item +@code{CHANGE col_name}, @code{DROP col_name}, and @code{DROP +INDEX} are @strong{MySQL} extensions to ANSI SQL92. + +@item +@code{MODIFY} is an Oracle extension to @code{ALTER TABLE}. + +@item +The optional word @code{COLUMN} is a pure noise word and can be omitted. + +@item +If you use @code{ALTER TABLE tbl_name RENAME TO new_name} without any other +options, @strong{MySQL} simply renames the files that correspond to the table +@code{tbl_name}. There is no need to create the temporary table. +@xref{RENAME TABLE,, @code{RENAME TABLE}}. + +@item +@code{create_definition} clauses use the same syntax for @code{ADD} and +@code{CHANGE} as for @code{CREATE TABLE}. Note that this syntax includes +the column name, not just the column type. +@xref{CREATE TABLE, , @code{CREATE TABLE}}. + +@item +You can rename a column using a @code{CHANGE old_col_name create_definition} +clause. To do so, specify the old and new column names and the type that +the column currently has. For example, to rename an @code{INTEGER} column +from @code{a} to @code{b}, you can do this: + +@example +mysql> ALTER TABLE t1 CHANGE a b INTEGER; +@end example + +If you want to change a column's type but not the name, @code{CHANGE} +syntax still requires two column names even if they are the same. For +example: + +@example +mysql> ALTER TABLE t1 CHANGE b b BIGINT NOT NULL; +@end example + +However, as of @strong{MySQL} Version 3.22.16a, you can also use @code{MODIFY} +to change a column's type without renaming it: + +@example +mysql> ALTER TABLE t1 MODIFY b BIGINT NOT NULL; +@end example + +@item +If you use @code{CHANGE} or @code{MODIFY} to shorten a column for which +an index exists on part of the column (for instance, if you have an index +on the first 10 characters of a @code{VARCHAR} column), you cannot make +the column shorter than the number of characters that are indexed. + +@item +When you change a column type using @code{CHANGE} or @code{MODIFY}, +@strong{MySQL} tries to convert data to the new type as well as possible. + +@item +In @strong{MySQL} Version 3.22 or later, you can use @code{FIRST} or +@code{ADD ... AFTER col_name} to add a column at a specific position within +a table row. The default is to add the column last. + +@findex ALTER COLUMN +@item +@code{ALTER COLUMN} specifies a new default value for a column +or removes the old default value. +If the old default is removed and the column can be @code{NULL}, the new +default is @code{NULL}. If the column cannot be @code{NULL}, @strong{MySQL} +assigns a default value, as described in +@ref{CREATE TABLE, , @code{CREATE TABLE}}. + +@findex DROP INDEX +@item +@code{DROP INDEX} removes an index. This is a @strong{MySQL} extension to +ANSI SQL92. @xref{DROP INDEX}. + +@item +If columns are dropped from a table, the columns are also removed from any +index of which they are a part. If all columns that make up an index are +dropped, the index is dropped as well. + +@item +If a table contains only one column, the column cannot be dropped. +If what you intend is to remove the table, use @code{DROP TABLE} instead. + +@findex DROP PRIMARY KEY +@item +@code{DROP PRIMARY KEY} drops the primary index. If no such +index exists, it drops the first @code{UNIQUE} index in the table. +(@strong{MySQL} marks the first @code{UNIQUE} key as the @code{PRIMARY KEY} +if no @code{PRIMARY KEY} was specified explicitly.) + +@findex ORDER BY +@item +@code{ORDER BY} allows you to create the new table with the rows in a +specific order. Note that the table will not remain in this order after +inserts and deletes. In some cases, it may make sorting easier for +@strong{MySQL} if the table is in order by the column that you wish to +order it by later. This option is mainly useful when you know that you +are mostly going to query the rows in a certain order; By using this +option after big changes to the table, you may be able to get higher +performance. + +@findex ALTER TABLE +@item +If you use @code{ALTER TABLE} on a @code{MyISAM} table, all non-unique +indexes are created in a separate batch (like in @code{REPAIR}). +This should make @code{ALTER TABLE} much faster when you have many indexes. + +@item @findex mysql_info() -@code{UPDATE} returns the number of rows that were actually changed. -In @strong{MySQL} Version 3.22 or later, the C API function @code{mysql_info()} -returns the number of rows that were matched and updated and the number of -warnings that occurred during the @code{UPDATE}. +With the C API function @code{mysql_info()}, you can find out how many +records were copied, and (when @code{IGNORE} is used) how many records were +deleted due to duplication of unique key values. -In @strong{MySQL} Version 3.23, you can use @code{LIMIT #} to ensure that -only a given number of rows are changed. +@item +@cindex foreign keys +@cindex references +The @code{FOREIGN KEY}, @code{CHECK}, and @code{REFERENCES} clauses don't +actually do anything. The syntax for them is provided only for compatibility, +to make it easier to port code from other SQL servers and to run applications +that create tables with references. +@xref{Missing functions}. +@end itemize + +Here is an example that shows some of the uses of @code{ALTER TABLE}. We +begin with a table @code{t1} that is created as shown below: + +@example +mysql> CREATE TABLE t1 (a INTEGER,b CHAR(10)); +@end example + +To rename the table from @code{t1} to @code{t2}: + +@example +mysql> ALTER TABLE t1 RENAME t2; +@end example + +To change column @code{a} from @code{INTEGER} to @code{TINYINT NOT NULL} +(leaving the name the same), and to change column @code{b} from +@code{CHAR(10)} to @code{CHAR(20)} as well as renaming it from @code{b} to +@code{c}: + +@example +mysql> ALTER TABLE t2 MODIFY a TINYINT NOT NULL, CHANGE b c CHAR(20); +@end example + +To add a new @code{TIMESTAMP} column named @code{d}: + +@example +mysql> ALTER TABLE t2 ADD d TIMESTAMP; +@end example + +To add an index on column @code{d}, and make column @code{a} the primary key: + +@example +mysql> ALTER TABLE t2 ADD INDEX (d), ADD PRIMARY KEY (a); +@end example + +To remove column @code{c}: + +@example +mysql> ALTER TABLE t2 DROP COLUMN c; +@end example + +To add a new @code{AUTO_INCREMENT} integer column named @code{c}: + +@example +mysql> ALTER TABLE t2 ADD c INT UNSIGNED NOT NULL AUTO_INCREMENT, + ADD INDEX (c); +@end example + +Note that we indexed @code{c}, because @code{AUTO_INCREMENT} columns must be +indexed, and also that we declare @code{c} as @code{NOT NULL}, because +indexed columns cannot be @code{NULL}. + +When you add an @code{AUTO_INCREMENT} column, column values are filled in +with sequence numbers for you automatically. You can set the first +sequence number by executing @code{SET INSERT_ID=#} before +@code{ALTER TABLE} or using the @code{AUTO_INCREMENT = #} table option. +@xref{SET OPTION}. + +With MyISAM tables, if you don't change the @code{AUTO_INCREMENT} +column, the sequence number will not be affected. If you drop an +@code{AUTO_INCREMENT} column and then add another @code{AUTO_INCREMENT} +column, the numbers will start from 1 again. + +@xref{ALTER TABLE problems}. + + +@node RENAME TABLE, DROP TABLE, ALTER TABLE, DROP DATABASE +@subsection @code{RENAME TABLE} Syntax + +@findex RENAME TABLE + +@example +RENAME TABLE tbl_name TO new_table_name[, tbl_name2 TO new_table_name2,...] +@end example + +The rename is done atomically, which means that no other thread can +access any of the tables while the rename is running. This makes it +possible to replace a table with an empty one: + +@example +CREATE TABLE new_table (...); +RENAME TABLE old_table TO backup_table, new_table TO old_table; +@end example + +The rename is done from left to right, which means that if you want to +swap two tables names, you have to: + +@example +RENAME TABLE old_table TO backup_table, + new_table TO old_table, + backup_table TO new_table; +@end example + +As long as two databases are on the same disk you can also rename +from one database to another: + +@example +RENAME TABLE current_database.table_name TO other_database.table_name; +@end example + +When you execute @code{RENAME}, you can't have any locked tables or +active transactions. You must also have the @code{ALTER} and @code{DROP} +privilege on the original table and @code{CREATE} and @code{INSERT} +privilege on the new table. + +If @strong{MySQL} encounters any errors in a multiple table rename, it +will do a reverse rename for all renamed tables to get everything back +to the original state. + + +@node DROP TABLE, CREATE INDEX, RENAME TABLE, DROP DATABASE +@subsection @code{DROP TABLE} Syntax + +@findex DROP TABLE + +@example +DROP TABLE [IF EXISTS] tbl_name [, tbl_name,...] [RESTRICT | CASCADE] +@end example + +@code{DROP TABLE} removes one or more tables. All table data and the table +definition are @emph{removed}, so @strong{be careful} with this command! + +In @strong{MySQL} Version 3.22 or later, you can use the keywords +@code{IF EXISTS} to prevent an error from occurring for tables that don't +exist. + +@code{RESTRICT} and @code{CASCADE} are allowed to make porting easier. +For the moment they don't do anything. + +@strong{NOTE}: @code{DROP TABLE} is not transaction-safe and will +automatically commit any active transactions. + + +@node CREATE INDEX, DROP INDEX, DROP TABLE, DROP DATABASE +@subsection @code{CREATE INDEX} Syntax + +@findex CREATE INDEX + +@cindex indexes +@cindex indexes, multi-part +@cindex multi-part index + +@example +CREATE [UNIQUE|FULLTEXT] INDEX index_name ON tbl_name (col_name[(length)],... ) +@end example + +The @code{CREATE INDEX} statement doesn't do anything in @strong{MySQL} prior +to Version 3.22. In Version 3.22 or later, @code{CREATE INDEX} is mapped to an +@code{ALTER TABLE} statement to create indexes. +@xref{ALTER TABLE, , @code{ALTER TABLE}}. + +Normally, you create all indexes on a table at the time the table itself +is created with @code{CREATE TABLE}. +@xref{CREATE TABLE, , @code{CREATE TABLE}}. +@code{CREATE INDEX} allows you to add indexes to existing tables. + +A column list of the form @code{(col1,col2,...)} creates a multiple-column +index. Index values are formed by concatenating the values of the given +columns. + +For @code{CHAR} and @code{VARCHAR} columns, indexes can be created that +use only part of a column, using @code{col_name(length)} syntax. (On +@code{BLOB} and @code{TEXT} columns the length is required). The +statement shown below creates an index using the first 10 characters of +the @code{name} column: + +@example +mysql> CREATE INDEX part_of_name ON customer (name(10)); +@end example + +Because most names usually differ in the first 10 characters, this index should +not be much slower than an index created from the entire @code{name} column. +Also, using partial columns for indexes can make the index file much smaller, +which could save a lot of disk space and might also speed up @code{INSERT} +operations! + +Note that you can only add an index on a column that can have @code{NULL} +values or on a @code{BLOB}/@code{TEXT} column if you are using +@strong{MySQL} Version 3.23.2 or newer and are using the @code{MyISAM} +table type. + +For more information about how @strong{MySQL} uses indexes, see +@ref{MySQL indexes, , @strong{MySQL} indexes}. + +@code{FULLTEXT} indexes can index only @code{VARCHAR} and +@code{TEXT} columns, and only in @code{MyISAM} tables. @code{FULLTEXT} indexes +are available in @strong{MySQL} Version 3.23.23 and later. +@ref{Fulltext Search}. + + +@node DROP INDEX, , CREATE INDEX, DROP DATABASE +@subsection @code{DROP INDEX} Syntax + +@findex DROP INDEX + +@example +DROP INDEX index_name ON tbl_name +@end example + +@code{DROP INDEX} drops the index named @code{index_name} from the table +@code{tbl_name}. @code{DROP INDEX} doesn't do anything in @strong{MySQL} +prior to Version 3.22. In Version 3.22 or later, @code{DROP INDEX} is mapped to an +@code{ALTER TABLE} statement to drop the index. +@xref{ALTER TABLE, , @code{ALTER TABLE}}. + + +@node Basic User Commands, Transactional Commands, DROP DATABASE, Reference +@section Basic MySQL User Utility Commands + +@menu +* USE:: +* DESCRIBE:: +@end menu + + +@node USE, DESCRIBE, Basic User Commands, Basic User Commands +@subsection @code{USE} Syntax @findex USE -@node USE, DESCRIBE, UPDATE, Reference -@section @code{USE} Syntax @example USE db_name @@ -33851,11 +34075,11 @@ mysql> SELECT author_name,editor_name FROM author,db2.editor The @code{USE} statement is provided for Sybase compatibility. +@node DESCRIBE, , USE, Basic User Commands +@subsection @code{DESCRIBE} Syntax (Get Information About Columns) @findex DESC @findex DESCRIBE -@node DESCRIBE, COMMIT, USE, Reference -@section @code{DESCRIBE} Syntax (Get Information About Columns) @example @{DESCRIBE | DESC@} tbl_name @{col_name | wild@} @@ -33879,11 +34103,23 @@ This statement is provided for Oracle compatibility. The @code{SHOW} statement provides similar information. @xref{SHOW, , @code{SHOW}}. + +@node Transactional Commands, Fulltext Search, Basic User Commands, Reference +@section MYSQL Transactional and Locking Commands + +@menu +* COMMIT:: +* LOCK TABLES:: +* SET TRANSACTION:: +@end menu + + +@node COMMIT, LOCK TABLES, Transactional Commands, Transactional Commands +@subsection @code{BEGIN/COMMIT/ROLLBACK} Syntax + @findex BEGIN @findex COMMIT @findex ROLLBACK -@node COMMIT, LOCK TABLES, DESCRIBE, Reference -@section @code{BEGIN/COMMIT/ROLLBACK} Syntax By default, @strong{MySQL} runs in @code{autocommit} mode. This means that as soon as you execute an update, @strong{MySQL} will store the update on @@ -33937,10 +34173,12 @@ a @code{COMMIT} before executing the command): You can change the isolation level for transactions with @code{SET TRANSACTION ISOLATION LEVEL ...}. @xref{SET TRANSACTION}. + +@node LOCK TABLES, SET TRANSACTION, COMMIT, Transactional Commands +@subsection @code{LOCK TABLES/UNLOCK TABLES} Syntax + @findex LOCK TABLES @findex UNLOCK TABLES -@node LOCK TABLES, CREATE INDEX, COMMIT, Reference -@section @code{LOCK TABLES/UNLOCK TABLES} Syntax @example LOCK TABLES tbl_name [AS alias] @{READ | [READ LOCAL] | [LOW_PRIORITY] WRITE@} @@ -34074,276 +34312,295 @@ automatically commit any active transactions before attempting to lock the tables. -@node CREATE INDEX, DROP INDEX, LOCK TABLES, Reference -@section @code{CREATE INDEX} Syntax +@node SET TRANSACTION, , LOCK TABLES, Transactional Commands +@subsection @code{SET TRANSACTION} Syntax -@findex CREATE INDEX - -@cindex indexes -@cindex indexes, multi-part -@cindex multi-part index +@findex ISOLATION LEVEL @example -CREATE [UNIQUE|FULLTEXT] INDEX index_name ON tbl_name (col_name[(length)],... ) +SET [GLOBAL | SESSION] TRANSACTION ISOLATION LEVEL +[READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE] @end example -The @code{CREATE INDEX} statement doesn't do anything in @strong{MySQL} prior -to Version 3.22. In Version 3.22 or later, @code{CREATE INDEX} is mapped to an -@code{ALTER TABLE} statement to create indexes. -@xref{ALTER TABLE, , @code{ALTER TABLE}}. +Sets the transaction isolation level for the global, whole session or +the next transaction. -Normally, you create all indexes on a table at the time the table itself -is created with @code{CREATE TABLE}. -@xref{CREATE TABLE, , @code{CREATE TABLE}}. -@code{CREATE INDEX} allows you to add indexes to existing tables. +The default behavior is to set the isolation level for the next (not started) +transaction. -A column list of the form @code{(col1,col2,...)} creates a multiple-column -index. Index values are formed by concatenating the values of the given -columns. +If you set the @code{GLOBAL} privilege it will affect all new created threads. +You will need the @code{PROCESS} privilege to do do this. -For @code{CHAR} and @code{VARCHAR} columns, indexes can be created that -use only part of a column, using @code{col_name(length)} syntax. (On -@code{BLOB} and @code{TEXT} columns the length is required). The -statement shown below creates an index using the first 10 characters of -the @code{name} column: +Setting the @code{SESSION} privilege will affect the following and all +future transactions. + +You can set the default isolation level for @code{mysqld} with +@code{--transaction-isolation=...}. @xref{Command-line options}. + + +@node Fulltext Search, , Transactional Commands, Reference +@section MySQL Full-text Search + +@cindex searching, full-text +@cindex full-text search +@cindex FULLTEXT + +Since Version 3.23.23, @strong{MySQL} has support for full-text indexing +and searching. Full-text indexes in @strong{MySQL} are an index of type +@code{FULLTEXT}. @code{FULLTEXT} indexes can be created from @code{VARCHAR} +and @code{TEXT} columns at @code{CREATE TABLE} time or added later with +@code{ALTER TABLE} or @code{CREATE INDEX}. For large datasets, adding +@code{FULLTEXT} index with @code{ALTER TABLE} (or @code{CREATE INDEX}) would +be much faster than inserting rows into the empty table with a @code{FULLTEXT} +index. + +Full-text search is performed with the @code{MATCH} function. @example -mysql> CREATE INDEX part_of_name ON customer (name(10)); +mysql> CREATE TABLE articles ( + -> id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, + -> title VARCHAR(200), + -> body TEXT, + -> FULLTEXT (title,body) + -> ); +Query OK, 0 rows affected (0.00 sec) + +mysql> INSERT INTO articles VALUES + -> (0,'MySQL Tutorial', 'DBMS stands for DataBase Management ...'), + -> (0,'How To Use MySQL Efficiently', 'After you went through a ...'), + -> (0,'Optimizing MySQL','In this tutorial we will show how to ...'), + -> (0,'1001 MySQL Trick','1. Never run mysqld as root. 2. Normalize ...'), + -> (0,'MySQL vs. YourSQL', 'In the following database comparison we ...'), + -> (0,'MySQL Security', 'When configured properly, MySQL could be ...'); +Query OK, 5 rows affected (0.00 sec) +Records: 5 Duplicates: 0 Warnings: 0 + +mysql> SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('database'); ++----+-------------------+---------------------------------------------+ +| id | title | body | ++----+-------------------+---------------------------------------------+ +| 5 | MySQL vs. YourSQL | In the following database comparison we ... | +| 1 | MySQL Tutorial | DBMS stands for DataBase Management ... | ++----+-------------------+---------------------------------------------+ +2 rows in set (0.00 sec) @end example -Because most names usually differ in the first 10 characters, this index should -not be much slower than an index created from the entire @code{name} column. -Also, using partial columns for indexes can make the index file much smaller, -which could save a lot of disk space and might also speed up @code{INSERT} -operations! +The function @code{MATCH} matches a natural language query @code{AGAINST} +a text collection (which is simply the set of columns covered by a +@code{FULLTEXT} index). For every row in a table it returns relevance - +a similarity measure between the text in that row (in the columns that are +part of the collection) and the query. When it is used in a @code{WHERE} +clause (see example above) the rows returned are automatically sorted with +relevance decreasing. Relevance is a non-negative floating-point number. +Zero relevance means no similarity. Relevance is computed based on the +number of words in the row, the number of unique words in that row, the +total number of words in the collection, and the number of documents (rows) +that contain a particular word. -Note that you can only add an index on a column that can have @code{NULL} -values or on a @code{BLOB}/@code{TEXT} column if you are using -@strong{MySQL} Version 3.23.2 or newer and are using the @code{MyISAM} -table type. - -For more information about how @strong{MySQL} uses indexes, see -@ref{MySQL indexes, , @strong{MySQL} indexes}. - -@code{FULLTEXT} indexes can index only @code{VARCHAR} and -@code{TEXT} columns, and only in @code{MyISAM} tables. @code{FULLTEXT} indexes -are available in @strong{MySQL} Version 3.23.23 and later. -@ref{Fulltext Search}. - -@findex DROP INDEX -@node DROP INDEX, Comments, CREATE INDEX, Reference -@section @code{DROP INDEX} Syntax +The above is a basic example of using @code{MATCH} function. Rows are +returned with relevance decreasing. @example -DROP INDEX index_name ON tbl_name +mysql> SELECT id,MATCH (title,body) AGAINST ('Tutorial') FROM articles; ++----+-----------------------------------------+ +| id | MATCH (title,body) AGAINST ('Tutorial') | ++----+-----------------------------------------+ +| 1 | 0.64840710366884 | +| 2 | 0 | +| 3 | 0.66266459031789 | +| 4 | 0 | +| 5 | 0 | +| 6 | 0 | ++----+-----------------------------------------+ +5 rows in set (0.00 sec) @end example -@code{DROP INDEX} drops the index named @code{index_name} from the table -@code{tbl_name}. @code{DROP INDEX} doesn't do anything in @strong{MySQL} -prior to Version 3.22. In Version 3.22 or later, @code{DROP INDEX} is mapped to an -@code{ALTER TABLE} statement to drop the index. -@xref{ALTER TABLE, , @code{ALTER TABLE}}. - -@findex Comment syntax -@cindex comments, adding -@node Comments, CREATE FUNCTION, DROP INDEX, Reference -@section Comment Syntax - -The @strong{MySQL} server supports the @code{# to end of line}, @code{-- -to end of line} and @code{/* in-line or multiple-line */} comment -styles: +This example shows how to retrieve the relevances. As neither @code{WHERE} +nor @code{ORDER BY} clauses are present, returned rows are not ordered. @example -mysql> select 1+1; # This comment continues to the end of line -mysql> select 1+1; -- This comment continues to the end of line -mysql> select 1 /* this is an in-line comment */ + 1; -mysql> select 1+ -/* -this is a -multiple-line comment -*/ -1; +mysql> SELECT id, body, MATCH (title,body) AGAINST ( + -> 'Security implications of running MySQL as root') AS score + -> FROM articles WHERE MATCH (title,body) AGAINST + -> ('Security implications of running MySQL as root'); ++----+-----------------------------------------------+-----------------+ +| id | body | score | ++----+-----------------------------------------------+-----------------+ +| 4 | 1. Never run mysqld as root. 2. Normalize ... | 1.5055546709332 | +| 6 | When configured properly, MySQL could be ... | 1.31140957288 | ++----+-----------------------------------------------+-----------------+ +2 rows in set (0.00 sec) @end example -Note that the @code{--} comment style requires you to have at least one space -after the @code{--}! +This is more complex example - the query returns the relevance and still +sorts the rows with relevance decreasing. To achieve it one should specify +@code{MATCH} twice. Note, that this will cause no additional overhead, as +@strong{MySQL} optimizer will notice that these two @code{MATCH} calls are +identical and will call full-text search code only once. -Although the server understands the comment syntax just described, -there are some limitations on the way that the @code{mysql} client -parses @code{/* ... */} comments: +@strong{MySQL} uses a very simple parser to split text into words. A +``word'' is any sequence of letters, numbers, @samp{'}, and @samp{_}. Any +``word'' that is present in the stopword list or just too short (3 +characters or less) is ignored. + +Every correct word in the collection and in the query is weighted, +according to its significance in the query or collection. This way, a +word that is present in many documents will have lower weight (and may +even have a zero weight), because it has lower semantic value in this +particular collection. Otherwise, if the word is rare, it will receive a +higher weight. The weights of the words are then combined to compute the +relevance of the row. + +Such a technique works best with large collections (in fact, it was +carefully tuned this way). For very small tables, word distribution +does not reflect adequately their semantical value, and this model +may sometimes produce bizarre results. + +@example +mysql> SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('MySQL'); +Empty set (0.00 sec) +@end example + +Search for the word @code{MySQL} produces no results in the above example. +Word @code{MySQL} is present in more than half of rows, and as such, is +effectively treated as a stopword (that is, with semantical value zero). +It is, really, the desired behavior - a natural language query should not +return every second row in 1GB table. + +A word that matches half of rows in a table is less likely to locate relevant +documents. In fact, it will most likely find plenty of irrelevant documents. +We all know this happens far too often when we are trying to find something on +the Internet with a search engine. It is with this reasoning that such rows +have been assigned a low semantical value in @strong{this particular dataset}. + +@menu +* Fulltext restrictions:: +* Fulltext Fine-tuning:: +* Fulltext Features to Appear in MySQL 4.0:: +* Fulltext TODO:: +@end menu + + +@node Fulltext restrictions, Fulltext Fine-tuning, Fulltext Search, Fulltext Search +@subsection Fulltext restrictions @itemize @bullet @item -Single-quote and double-quote characters are taken to indicate the beginning -of a quoted string, even within a comment. If the quote is not matched by a -second quote within the comment, the parser doesn't realize the comment has -ended. If you are running @code{mysql} interactively, you can tell that it -has gotten confused like this because the prompt changes from @code{mysql>} -to @code{'>} or @code{">}. +All parameters to the @code{MATCH} function must be columns from the +same table that is part of the same fulltext index. +@item +The argument to @code{AGAINST} must be a constant string. +@end itemize + + +@node Fulltext Fine-tuning, Fulltext Features to Appear in MySQL 4.0, Fulltext restrictions, Fulltext Search +@subsection Fine-tuning MySQL Full-text Search + +Unfortunately, full-text search has no user-tunable parameters yet, +although adding some is very high on the TODO. However, if you have a +@strong{MySQL} source distribution (@xref{Installing source}.), you can +somewhat alter the full-text search behavior. + +Note that full-text search was carefully tuned for the best searching +effectiveness. Modifying the default behavior will, in most cases, +only make the search results worse. Do not alter the @strong{MySQL} sources +unless you know what you are doing! + +@itemize @item -A semicolon is taken to indicate the end of the current SQL statement -and anything following it to indicate the beginning of the next statement. +Minimal length of word to be indexed is defined in +@code{myisam/ftdefs.h} file by the line +@example +#define MIN_WORD_LEN 4 +@end example +Change it to the value you prefer, recompile @strong{MySQL}, and rebuild +your @code{FULLTEXT} indexes. + +@item +The stopword list is defined in @code{myisam/ft_static.c} +Modify it to your taste, recompile @strong{MySQL} and rebuild +your @code{FULLTEXT} indexes. + +@item +The 50% threshold is caused by the particular weighting scheme chosen. To +disable it, change the following line in @code{myisam/ftdefs.h}: +@example +#define GWS_IN_USE GWS_PROB +@end example +to +@example +#define GWS_IN_USE GWS_FREQ +@end example +and recompile @strong{MySQL}. +There is no need to rebuild the indexes in this case. + @end itemize -These limitations apply both when you run @code{mysql} interactively -and when you put commands in a file and tell @code{mysql} to read its -input from that file with @code{mysql < some-file}. -@strong{MySQL} doesn't support the @samp{--} ANSI SQL comment style. -@xref{Missing comments}. +@node Fulltext Features to Appear in MySQL 4.0, Fulltext TODO, Fulltext Fine-tuning, Fulltext Search +@subsection New Features of Full-text Search to Appear in MySQL 4.0 -@findex CREATE FUNCTION -@findex DROP FUNCTION -@findex UDF functions -@findex User-defined functions -@findex Functions, user-defined -@node CREATE FUNCTION, Reserved words, Comments, Reference -@section @code{CREATE FUNCTION/DROP FUNCTION} Syntax - -@example -CREATE [AGGREGATE] FUNCTION function_name RETURNS @{STRING|REAL|INTEGER@} - SONAME shared_library_name - -DROP FUNCTION function_name -@end example - -A user-definable function (UDF) is a way to extend @strong{MySQL} with a new -function that works like native (built in) @strong{MySQL} functions such as -@code{ABS()} and @code{CONCAT()}. - -@code{AGGREGATE} is a new option for @strong{MySQL} Version 3.23. An -@code{AGGREGATE} function works exactly like a native @strong{MySQL} -@code{GROUP} function like @code{SUM} or @code{COUNT()}. - -@code{CREATE FUNCTION} saves the function's name, type, and shared library -name in the @code{mysql.func} system table. You must have the -@strong{insert} and @strong{delete} privileges for the @code{mysql} database -to create and drop functions. - -All active functions are reloaded each time the server starts, unless -you start @code{mysqld} with the @code{--skip-grant-tables} option. In -this case, UDF initialization is skipped and UDFs are unavailable. -(An active function is one that has been loaded with @code{CREATE FUNCTION} -and not removed with @code{DROP FUNCTION}.) - -For instructions on writing user-definable functions, see @ref{Adding -functions}. For the UDF mechanism to work, functions must be written in C or -C++, your operating system must support dynamic loading and you must have -compiled @code{mysqld} dynamically (not statically). - -@cindex keywords -@cindex reserved words, exceptions -@node Reserved words, , CREATE FUNCTION, Reference -@section Is MySQL Picky About Reserved Words? - -A common problem stems from trying to create a table with column names that -use the names of datatypes or functions built into @strong{MySQL}, such as -@code{TIMESTAMP} or @code{GROUP}. You're allowed to do it (for example, -@code{ABS} is an allowed column name), but whitespace is not allowed between -a function name and the @samp{(} when using functions whose names are also -column names. - -The following words are explicitly reserved in @strong{MySQL}. Most of -them are forbidden by ANSI SQL92 as column and/or table names -(for example, @code{group}). -A few are reserved because @strong{MySQL} needs them and is -(currently) using a @code{yacc} parser: - -@c This is fixed by including the symbols table from lex.h here and then running -@c fix-mysql-reserved-words in emacs (or let David do it): -@c (defun fix-mysql-reserved-words () -@c (interactive) -@c (let ((cnt 0)) -@c (insert "\n@item ") -@c (while (looking-at "[ \t]*{ +\"\\([^\"]+\\)\"[ \t]*,.*\n") -@c (replace-match "@code{\\1}") -@c (incf cnt) -@c (if (> cnt 3) -@c (progn -@c (setf cnt 0) -@c (insert "\n@item ")) -@c (insert " @tab "))))) -@c But remove the non alphanumeric entries by hand first. -@c Updated after 3.23.4 990928 by David - -@multitable @columnfractions .25 .25 .25 .25 -@item @code{action} @tab @code{add} @tab @code{aggregate} @tab @code{all} -@item @code{alter} @tab @code{after} @tab @code{and} @tab @code{as} -@item @code{asc} @tab @code{avg} @tab @code{avg_row_length} @tab @code{auto_increment} -@item @code{between} @tab @code{bigint} @tab @code{bit} @tab @code{binary} -@item @code{blob} @tab @code{bool} @tab @code{both} @tab @code{by} -@item @code{cascade} @tab @code{case} @tab @code{char} @tab @code{character} -@item @code{change} @tab @code{check} @tab @code{checksum} @tab @code{column} -@item @code{columns} @tab @code{comment} @tab @code{constraint} @tab @code{create} -@item @code{cross} @tab @code{current_date} @tab @code{current_time} @tab @code{current_timestamp} -@item @code{data} @tab @code{database} @tab @code{databases} @tab @code{date} -@item @code{datetime} @tab @code{day} @tab @code{day_hour} @tab @code{day_minute} -@item @code{day_second} @tab @code{dayofmonth} @tab @code{dayofweek} @tab @code{dayofyear} -@item @code{dec} @tab @code{decimal} @tab @code{default} @tab @code{delayed} -@item @code{delay_key_write} @tab @code{delete} @tab @code{desc} @tab @code{describe} -@item @code{distinct} @tab @code{distinctrow} @tab @code{double} @tab @code{drop} -@item @code{end} @tab @code{else} @tab @code{escape} @tab @code{escaped} -@item @code{enclosed} @tab @code{enum} @tab @code{explain} @tab @code{exists} -@item @code{fields} @tab @code{file} @tab @code{first} @tab @code{float} -@item @code{float4} @tab @code{float8} @tab @code{flush} @tab @code{foreign} -@item @code{from} @tab @code{for} @tab @code{full} @tab @code{function} -@item @code{global} @tab @code{grant} @tab @code{grants} @tab @code{group} -@item @code{having} @tab @code{heap} @tab @code{high_priority} @tab @code{hour} -@item @code{hour_minute} @tab @code{hour_second} @tab @code{hosts} @tab @code{identified} -@item @code{ignore} @tab @code{in} @tab @code{index} @tab @code{infile} -@item @code{inner} @tab @code{insert} @tab @code{insert_id} @tab @code{int} -@item @code{integer} @tab @code{interval} @tab @code{int1} @tab @code{int2} -@item @code{int3} @tab @code{int4} @tab @code{int8} @tab @code{into} -@item @code{if} @tab @code{is} @tab @code{isam} @tab @code{join} -@item @code{key} @tab @code{keys} @tab @code{kill} @tab @code{last_insert_id} -@item @code{leading} @tab @code{left} @tab @code{length} @tab @code{like} -@item @code{lines} @tab @code{limit} @tab @code{load} @tab @code{local} -@item @code{lock} @tab @code{logs} @tab @code{long} @tab @code{longblob} -@item @code{longtext} @tab @code{low_priority} @tab @code{max} @tab @code{max_rows} -@item @code{match} @tab @code{mediumblob} @tab @code{mediumtext} @tab @code{mediumint} -@item @code{middleint} @tab @code{min_rows} @tab @code{minute} @tab @code{minute_second} -@item @code{modify} @tab @code{month} @tab @code{monthname} @tab @code{myisam} -@item @code{natural} @tab @code{numeric} @tab @code{no} @tab @code{not} -@item @code{null} @tab @code{on} @tab @code{optimize} @tab @code{option} -@item @code{optionally} @tab @code{or} @tab @code{order} @tab @code{outer} -@item @code{outfile} @tab @code{pack_keys} @tab @code{partial} @tab @code{password} -@item @code{precision} @tab @code{primary} @tab @code{procedure} @tab @code{process} -@item @code{processlist} @tab @code{privileges} @tab @code{read} @tab @code{real} -@item @code{references} @tab @code{reload} @tab @code{regexp} @tab @code{rename} -@item @code{replace} @tab @code{restrict} @tab @code{returns} @tab @code{revoke} -@item @code{rlike} @tab @code{row} @tab @code{rows} @tab @code{second} -@item @code{select} @tab @code{set} @tab @code{show} @tab @code{shutdown} -@item @code{smallint} @tab @code{soname} @tab @code{sql_big_tables} @tab @code{sql_big_selects} -@item @code{sql_low_priority_updates} @tab @code{sql_log_off} @tab @code{sql_log_update} @tab @code{sql_select_limit} -@item @code{sql_small_result} @tab @code{sql_big_result} @tab @code{sql_warnings} @tab @code{straight_join} -@item @code{starting} @tab @code{status} @tab @code{string} @tab @code{table} -@item @code{tables} @tab @code{temporary} @tab @code{terminated} @tab @code{text} -@item @code{then} @tab @code{time} @tab @code{timestamp} @tab @code{tinyblob} -@item @code{tinytext} @tab @code{tinyint} @tab @code{trailing} @tab @code{to} -@item @code{type} @tab @code{use} @tab @code{using} @tab @code{unique} -@item @code{unlock} @tab @code{unsigned} @tab @code{update} @tab @code{usage} -@item @code{values} @tab @code{varchar} @tab @code{variables} @tab @code{varying} -@item @code{varbinary} @tab @code{with} @tab @code{write} @tab @code{when} -@item @code{where} @tab @code{year} @tab @code{year_month} @tab @code{zerofill} -@end multitable - -The following symbols (from the table above) are disallowed by ANSI SQL -but allowed by @strong{MySQL} as column/table names. This is because some -of these names are very natural names and a lot of people have already -used them. +This section includes a list of the fulltext features that are already +implemented in the 4.0 tree. It explains +@strong{More functions for full-text search} entry of @ref{TODO MySQL 4.0}. @itemize @bullet -@item @code{ACTION} -@item @code{BIT} -@item @code{DATE} -@item @code{ENUM} -@item @code{NO} -@item @code{TEXT} -@item @code{TIME} -@item @code{TIMESTAMP} +@item @code{REPAIR TABLE} with @code{FULLTEXT} indexes, +@code{ALTER TABLE} with @code{FULLTEXT} indexes, and +@code{OPTIMIZE TABLE} with @code{FULLTEXT} indexes are now +up to 100 times faster. + +@item @code{MATCH ... AGAINST} is going to supports the following +@strong{boolean operators}: + +@itemize @bullet +@item @code{+}word means the that word @strong{must} be present in every +row returned. +@item @code{-}word means the that word @strong{must not} be present in every +row returned. +@item @code{<} and @code{>} can be used to decrease and increase word +weight in the query. +@item @code{~} can be used to assign a @strong{negative} weight to a noise +word. +@item @code{*} is a truncation operator. @end itemize +Boolean search utilizes a more simplistic way of calculating the relevance, +that does not have a 50% threshold. + +@item Searches are now up to 2 times faster due to optimized search algorithm. + +@item Utility program @code{ft_dump} added for low-level @code{FULLTEXT} +index operations (querying/dumping/statistics). + +@end itemize + + +@node Fulltext TODO, , Fulltext Features to Appear in MySQL 4.0, Fulltext Search +@subsection Full-text Search TODO + +@itemize @bullet +@item Make all operations with @code{FULLTEXT} index @strong{faster}. +@item Support for braces @code{()} in boolean full-text search. +@item Phrase search, proximity operators +@item Boolean search can work without @code{FULLTEXT} index +(yes, @strong{very} slow). +@item Support for "always-index words". They could be any strings +the user wants to treat as words, examples are "C++", "AS/400", "TCP/IP", etc. +@item Support for full-text search in @code{MERGE} tables. +@item Support for multi-byte charsets. +@item Make stopword list to depend of the language of the data. +@item Stemming (dependent of the language of the data, of course). +@item Generic user-supplyable UDF (?) preparser. +@item Make the model more flexible (by adding some adjustable +parameters to @code{FULLTEXT} in @code{CREATE/ALTER TABLE}). +@end itemize + + +@node Table types, Maintenance, Reference, Top +@chapter MySQL Table Types + @cindex table types, choosing @cindex @code{BDB} table type @cindex @code{Berkeley_db} table type @@ -34354,8 +34611,6 @@ used them. @cindex MySQL table types @cindex @code{MyISAM} table type @cindex types, of tables -@node Table types, Fulltext Search, Reference, Top -@chapter MySQL Table Types As of @strong{MySQL} Version 3.23.6, you can choose between three basic table formats (@code{ISAM}, @code{HEAP} and @code{MyISAM}. Newer @@ -36769,262 +37024,9 @@ not trivial). @end itemize -@node Fulltext Search, Maintenance, Table types, Top -@chapter MySQL Full-text Search - -@cindex searching, full-text -@cindex full-text search -@cindex FULLTEXT - -Since Version 3.23.23, @strong{MySQL} has support for full-text indexing -and searching. Full-text indexes in @strong{MySQL} are an index of type -@code{FULLTEXT}. @code{FULLTEXT} indexes can be created from @code{VARCHAR} -and @code{TEXT} columns at @code{CREATE TABLE} time or added later with -@code{ALTER TABLE} or @code{CREATE INDEX}. For large datasets, adding -@code{FULLTEXT} index with @code{ALTER TABLE} (or @code{CREATE INDEX}) would -be much faster than inserting rows into the empty table with a @code{FULLTEXT} -index. - -Full-text search is performed with the @code{MATCH} function. - -@example -mysql> CREATE TABLE articles ( - -> id INT UNSIGNED AUTO_INCREMENT NOT NULL PRIMARY KEY, - -> title VARCHAR(200), - -> body TEXT, - -> FULLTEXT (title,body) - -> ); -Query OK, 0 rows affected (0.00 sec) - -mysql> INSERT INTO articles VALUES - -> (0,'MySQL Tutorial', 'DBMS stands for DataBase Management ...'), - -> (0,'How To Use MySQL Efficiently', 'After you went through a ...'), - -> (0,'Optimizing MySQL','In this tutorial we will show how to ...'), - -> (0,'1001 MySQL Trick','1. Never run mysqld as root. 2. Normalize ...'), - -> (0,'MySQL vs. YourSQL', 'In the following database comparison we ...'), - -> (0,'MySQL Security', 'When configured properly, MySQL could be ...'); -Query OK, 5 rows affected (0.00 sec) -Records: 5 Duplicates: 0 Warnings: 0 - -mysql> SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('database'); -+----+-------------------+---------------------------------------------+ -| id | title | body | -+----+-------------------+---------------------------------------------+ -| 5 | MySQL vs. YourSQL | In the following database comparison we ... | -| 1 | MySQL Tutorial | DBMS stands for DataBase Management ... | -+----+-------------------+---------------------------------------------+ -2 rows in set (0.00 sec) -@end example - -The function @code{MATCH} matches a natural language query @code{AGAINST} -a text collection (which is simply the set of columns covered by a -@code{FULLTEXT} index). For every row in a table it returns relevance - -a similarity measure between the text in that row (in the columns that are -part of the collection) and the query. When it is used in a @code{WHERE} -clause (see example above) the rows returned are automatically sorted with -relevance decreasing. Relevance is a non-negative floating-point number. -Zero relevance means no similarity. Relevance is computed based on the -number of words in the row, the number of unique words in that row, the -total number of words in the collection, and the number of documents (rows) -that contain a particular word. - -The above is a basic example of using @code{MATCH} function. Rows are -returned with relevance decreasing. - -@example -mysql> SELECT id,MATCH (title,body) AGAINST ('Tutorial') FROM articles; -+----+-----------------------------------------+ -| id | MATCH (title,body) AGAINST ('Tutorial') | -+----+-----------------------------------------+ -| 1 | 0.64840710366884 | -| 2 | 0 | -| 3 | 0.66266459031789 | -| 4 | 0 | -| 5 | 0 | -| 6 | 0 | -+----+-----------------------------------------+ -5 rows in set (0.00 sec) -@end example - -This example shows how to retrieve the relevances. As neither @code{WHERE} -nor @code{ORDER BY} clauses are present, returned rows are not ordered. - -@example -mysql> SELECT id, body, MATCH (title,body) AGAINST ( - -> 'Security implications of running MySQL as root') AS score - -> FROM articles WHERE MATCH (title,body) AGAINST - -> ('Security implications of running MySQL as root'); -+----+-----------------------------------------------+-----------------+ -| id | body | score | -+----+-----------------------------------------------+-----------------+ -| 4 | 1. Never run mysqld as root. 2. Normalize ... | 1.5055546709332 | -| 6 | When configured properly, MySQL could be ... | 1.31140957288 | -+----+-----------------------------------------------+-----------------+ -2 rows in set (0.00 sec) -@end example - -This is more complex example - the query returns the relevance and still -sorts the rows with relevance decreasing. To achieve it one should specify -@code{MATCH} twice. Note, that this will cause no additional overhead, as -@strong{MySQL} optimizer will notice that these two @code{MATCH} calls are -identical and will call full-text search code only once. - -@strong{MySQL} uses a very simple parser to split text into words. A -``word'' is any sequence of letters, numbers, @samp{'}, and @samp{_}. Any -``word'' that is present in the stopword list or just too short (3 -characters or less) is ignored. - -Every correct word in the collection and in the query is weighted, -according to its significance in the query or collection. This way, a -word that is present in many documents will have lower weight (and may -even have a zero weight), because it has lower semantic value in this -particular collection. Otherwise, if the word is rare, it will receive a -higher weight. The weights of the words are then combined to compute the -relevance of the row. - -Such a technique works best with large collections (in fact, it was -carefully tuned this way). For very small tables, word distribution -does not reflect adequately their semantical value, and this model -may sometimes produce bizarre results. - -@example -mysql> SELECT * FROM articles WHERE MATCH (title,body) AGAINST ('MySQL'); -Empty set (0.00 sec) -@end example - -Search for the word @code{MySQL} produces no results in the above example. -Word @code{MySQL} is present in more than half of rows, and as such, is -effectively treated as a stopword (that is, with semantical value zero). -It is, really, the desired behavior - a natural language query should not -return every second row in 1GB table. - -A word that matches half of rows in a table is less likely to locate relevant -documents. In fact, it will most likely find plenty of irrelevant documents. -We all know this happens far too often when we are trying to find something on -the Internet with a search engine. It is with this reasoning that such rows -have been assigned a low semantical value in @strong{this particular dataset}. - -@menu -* Fulltext restrictions:: -* Fulltext Fine-tuning:: -* Fulltext Features to Appear in MySQL 4.0:: -* Fulltext TODO:: -@end menu - -@node Fulltext restrictions, Fulltext Fine-tuning, Fulltext Search, Fulltext Search -@section Fulltext restrictions -@itemize @bullet -@item -All parameters to the @code{MATCH} function must be columns from the -same table that is part of the same fulltext index. -@item -The argument to @code{AGAINST} must be a constant string. -@end itemize - -@node Fulltext Fine-tuning, Fulltext Features to Appear in MySQL 4.0, Fulltext restrictions, Fulltext Search -@section Fine-tuning MySQL Full-text Search - -Unfortunately, full-text search has no user-tunable parameters yet, -although adding some is very high on the TODO. However, if you have a -@strong{MySQL} source distribution (@xref{Installing source}.), you can -somewhat alter the full-text search behavior. - -Note that full-text search was carefully tuned for the best searching -effectiveness. Modifying the default behavior will, in most cases, -only make the search results worse. Do not alter the @strong{MySQL} sources -unless you know what you are doing! - -@itemize - -@item -Minimal length of word to be indexed is defined in -@code{myisam/ftdefs.h} file by the line -@example -#define MIN_WORD_LEN 4 -@end example -Change it to the value you prefer, recompile @strong{MySQL}, and rebuild -your @code{FULLTEXT} indexes. - -@item -The stopword list is defined in @code{myisam/ft_static.c} -Modify it to your taste, recompile @strong{MySQL} and rebuild -your @code{FULLTEXT} indexes. - -@item -The 50% threshold is caused by the particular weighting scheme chosen. To -disable it, change the following line in @code{myisam/ftdefs.h}: -@example -#define GWS_IN_USE GWS_PROB -@end example -to -@example -#define GWS_IN_USE GWS_FREQ -@end example -and recompile @strong{MySQL}. -There is no need to rebuild the indexes in this case. - -@end itemize - -@node Fulltext Features to Appear in MySQL 4.0, Fulltext TODO, Fulltext Fine-tuning, Fulltext Search -@section New Features of Full-text Search to Appear in MySQL 4.0 - -This section includes a list of the fulltext features that are already -implemented in the 4.0 tree. It explains -@strong{More functions for full-text search} entry of @ref{TODO MySQL 4.0}. - -@itemize @bullet -@item @code{REPAIR TABLE} with @code{FULLTEXT} indexes, -@code{ALTER TABLE} with @code{FULLTEXT} indexes, and -@code{OPTIMIZE TABLE} with @code{FULLTEXT} indexes are now -up to 100 times faster. - -@item @code{MATCH ... AGAINST} is going to supports the following -@strong{boolean operators}: - -@itemize @bullet -@item @code{+}word means the that word @strong{must} be present in every -row returned. -@item @code{-}word means the that word @strong{must not} be present in every -row returned. -@item @code{<} and @code{>} can be used to decrease and increase word -weight in the query. -@item @code{~} can be used to assign a @strong{negative} weight to a noise -word. -@item @code{*} is a truncation operator. -@end itemize - -Boolean search utilizes a more simplistic way of calculating the relevance, -that does not have a 50% threshold. - -@item Searches are now up to 2 times faster due to optimized search algorithm. - -@item Utility program @code{ft_dump} added for low-level @code{FULLTEXT} -index operations (querying/dumping/statistics). - -@end itemize - -@node Fulltext TODO, , Fulltext Features to Appear in MySQL 4.0, Fulltext Search -@section Full-text Search TODO - -@itemize @bullet -@item Make all operations with @code{FULLTEXT} index @strong{faster}. -@item Support for braces @code{()} in boolean full-text search. -@item Phrase search, proximity operators -@item Boolean search can work without @code{FULLTEXT} index -(yes, @strong{very} slow). -@item Support for "always-index words". They could be any strings -the user wants to treat as words, examples are "C++", "AS/400", "TCP/IP", etc. -@item Support for full-text search in @code{MERGE} tables. -@item Support for multi-byte charsets. -@item Make stopword list to depend of the language of the data. -@item Stemming (dependent of the language of the data, of course). -@item Generic user-supplyable UDF (?) preparser. -@item Make the model more flexible (by adding some adjustable -parameters to @code{FULLTEXT} in @code{CREATE/ALTER TABLE}). -@end itemize -@node Maintenance, Adding functions, Fulltext Search, Top +@node Maintenance, Adding functions, Table types, Top @chapter Maintaining a MySQL Installation @cindex installation maintenance @@ -39791,12 +39793,13 @@ your current time zone. This should be done for the environment in which the server runs, for example, in @code{safe_mysqld} or @code{mysql.server}. @xref{Environment variables}. +@node Case sensitivity, Problems with NULL, Timezone problems, Problems +@section Case Sensitivity in Searches + @cindex case sensitivity, in searches @cindex searching, and case-sensitivity @cindex Chinese @cindex Big5 Chinese character encoding -@node Case sensitivity, Problems with NULL, Timezone problems, Problems -@section Case Sensitivity in Searches By default, @strong{MySQL} searches are case-insensitive (although there are some character sets that are never case insensitive, such as @code{czech}). @@ -53023,6 +53026,8 @@ That's all there is to it! * Installing binary:: * Building clients:: * Perl support:: +* Group by functions:: +* CREATE FUNCTION:: @end menu @node Installing binary, Building clients, Placeholder, Placeholder @@ -53266,7 +53271,7 @@ files. -@node Perl support, , Building clients, Placeholder +@node Perl support, Group by functions, Building clients, Placeholder @appendixsec Perl Installation Comments @cindex Perl, installing @@ -53555,6 +53560,205 @@ Finally, you should install this new Perl. Again, the output of @code{make perl} indicates the command to use. +@node Group by functions, CREATE FUNCTION, Perl support, Placeholder +@appendixsec Functions for Use with @code{GROUP BY} Clauses + +@findex GROUP BY functions +@findex functions, GROUP BY + +If you use a group function in a statement containing no @code{GROUP BY} +clause, it is equivalent to grouping on all rows. + +@table @code +@findex COUNT() +@item COUNT(expr) +Returns a count of the number of non-@code{NULL} values in the rows +retrieved by a @code{SELECT} statement: + +@example +mysql> select student.student_name,COUNT(*) + from student,course + where student.student_id=course.student_id + GROUP BY student_name; + +@end example + +@code{COUNT(*)} is somewhat different in that it returns a count of +the number of rows retrieved, whether or not they contain @code{NULL} +values. + +@code{COUNT(*)} is optimized to +return very quickly if the @code{SELECT} retrieves from one table, no +other columns are retrieved, and there is no @code{WHERE} clause. +For example: + +@example +mysql> select COUNT(*) from student; +@end example + +@findex COUNT(DISTINCT) +@findex DISTINCT +@item COUNT(DISTINCT expr,[expr...]) +Returns a count of the number of different non-@code{NULL} values: + +@example +mysql> select COUNT(DISTINCT results) from student; +@end example + +In @strong{MySQL} you can get the number of distinct expression +combinations that don't contain NULL by giving a list of expressions. +In ANSI SQL you would have to do a concatenation of all expressions +inside @code{CODE(DISTINCT ..)}. + +@findex AVG() +@item AVG(expr) +Returns the average value of @code{expr}: + +@example +mysql> select student_name, AVG(test_score) + from student + GROUP BY student_name; +@end example + +@findex MIN() +@findex MAX() +@item MIN(expr) +@itemx MAX(expr) +Returns the minimum or maximum value of @code{expr}. @code{MIN()} and +@code{MAX()} may take a string argument; in such cases they return the +minimum or maximum string value. @xref{MySQL indexes}. + +@example +mysql> select student_name, MIN(test_score), MAX(test_score) + from student + GROUP BY student_name; +@end example + +@findex SUM() +@item SUM(expr) +Returns the sum of @code{expr}. Note that if the return set has no rows, +it returns NULL! + +@findex STD() +@findex STDDEV() +@cindex Oracle compatibility +@cindex compatibility, with Oracle +@item STD(expr) +@itemx STDDEV(expr) +Returns the standard deviation of @code{expr}. This is an extension to +ANSI SQL. The @code{STDDEV()} form of this function is provided for Oracle +compatibility. + +@findex BIT_OR() +@item BIT_OR(expr) +Returns the bitwise @code{OR} of all bits in @code{expr}. The calculation is +performed with 64-bit (@code{BIGINT}) precision. + +@findex BIT_AND() +@item BIT_AND(expr) +Returns the bitwise @code{AND} of all bits in @code{expr}. The calculation is +performed with 64-bit (@code{BIGINT}) precision. +@end table + +@cindex @code{GROUP BY}, extensions to ANSI SQL +@strong{MySQL} has extended the use of @code{GROUP BY}. You can use columns or +calculations in the @code{SELECT} expressions that don't appear in +the @code{GROUP BY} part. This stands for @emph{any possible value for this +group}. You can use this to get better performance by avoiding sorting and +grouping on unnecessary items. For example, you don't need to group on +@code{customer.name} in the following query: + +@example +mysql> select order.custid,customer.name,max(payments) + from order,customer + where order.custid = customer.custid + GROUP BY order.custid; +@end example + +In ANSI SQL, you would have to add @code{customer.name} to the @code{GROUP +BY} clause. In @strong{MySQL}, the name is redundant if you don't run in +ANSI mode. + +@strong{Don't use this feature} if the columns you omit from the +@code{GROUP BY} part aren't unique in the group! You will get +unpredictable results. + +In some cases, you can use @code{MIN()} and @code{MAX()} to obtain a specific +column value even if it isn't unique. The following gives the value of +@code{column} from the row containing the smallest value in the @code{sort} +column: + +@example +substr(MIN(concat(rpad(sort,6,' '),column)),7) +@end example + +@xref{example-Maximum-column-group-row}. + +@cindex @code{ORDER BY}, aliases in +@cindex aliases, in @code{ORDER BY} clauses +@cindex @code{GROUP BY}, aliases in +@cindex aliases, in @code{GROUP BY} clauses +@cindex expression aliases +@cindex aliases, for expressions +Note that if you are using @strong{MySQL} Version 3.22 (or earlier) or if +you are trying to follow ANSI SQL, you can't use expressions in @code{GROUP +BY} or @code{ORDER BY} clauses. You can work around this limitation by +using an alias for the expression: + +@example +mysql> SELECT id,FLOOR(value/100) AS val FROM tbl_name + GROUP BY id,val ORDER BY val; +@end example + +In @strong{MySQL} Version 3.23 you can do: + +@example +mysql> SELECT id,FLOOR(value/100) FROM tbl_name ORDER BY RAND(); +@end example + + +@node CREATE FUNCTION, , Group by functions, Placeholder +@appendixsec @code{CREATE FUNCTION/DROP FUNCTION} Syntax + +@findex CREATE FUNCTION +@findex DROP FUNCTION +@findex UDF functions +@findex User-defined functions +@findex Functions, user-defined + +@example +CREATE [AGGREGATE] FUNCTION function_name RETURNS @{STRING|REAL|INTEGER@} + SONAME shared_library_name + +DROP FUNCTION function_name +@end example + +A user-definable function (UDF) is a way to extend @strong{MySQL} with a new +function that works like native (built in) @strong{MySQL} functions such as +@code{ABS()} and @code{CONCAT()}. + +@code{AGGREGATE} is a new option for @strong{MySQL} Version 3.23. An +@code{AGGREGATE} function works exactly like a native @strong{MySQL} +@code{GROUP} function like @code{SUM} or @code{COUNT()}. + +@code{CREATE FUNCTION} saves the function's name, type, and shared library +name in the @code{mysql.func} system table. You must have the +@strong{insert} and @strong{delete} privileges for the @code{mysql} database +to create and drop functions. + +All active functions are reloaded each time the server starts, unless +you start @code{mysqld} with the @code{--skip-grant-tables} option. In +this case, UDF initialization is skipped and UDFs are unavailable. +(An active function is one that has been loaded with @code{CREATE FUNCTION} +and not removed with @code{DROP FUNCTION}.) + +For instructions on writing user-definable functions, see @ref{Adding +functions}. For the UDF mechanism to work, functions must be written in C or +C++, your operating system must support dynamic loading and you must have +compiled @code{mysqld} dynamically (not statically). + + + @node Function Index, Concept Index, Placeholder, Top @unnumbered SQL command, type and function index From a04a6034e33bb586a2bcf67b6ffa8653bedda71c Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 13:14:05 -0500 Subject: [PATCH 49/51] Fixes to DocTOC Chapter 6. --- Docs/manual.texi | 50 ++++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/Docs/manual.texi b/Docs/manual.texi index 5f6025a757d..95830d1ca0a 100644 --- a/Docs/manual.texi +++ b/Docs/manual.texi @@ -26845,12 +26845,10 @@ Things that are not yet supported: @menu * Language Structure:: -* Variables:: User variables * Column types:: Column types * Functions:: Functions * Data Manipulation:: * Data Definition:: -* DROP DATABASE:: @code{DROP DATABASE} syntax * Basic User Commands:: * Transactional Commands:: * Fulltext Search:: @@ -26864,13 +26862,16 @@ included in @strong{MySQL}. In order to use this chapter effectively, you may find it useful to refer to the various indexes. -@node Language Structure, Variables, Reference, Reference +@node Language Structure, Column types, Reference, Reference @section Language Structure @menu * Literals:: * Legal names:: * Name case sensitivity:: +* Variables:: +* Comments:: +* Reserved words:: @end menu @@ -27224,7 +27225,7 @@ database. This syntax is accepted for ODBC compatibility, because some ODBC programs prefix table names with a @samp{.} character. -@node Name case sensitivity, , Legal names, Language Structure +@node Name case sensitivity, Variables, Legal names, Language Structure @subsection Case Sensitivity in Names @cindex names, case-sensitivity @@ -27275,8 +27276,8 @@ change this option, you need to first convert your old table names to lower case before starting @code{mysqld}. -@node Variables, Column types, Language Structure, Reference -@section User Variables +@node Variables, Comments, Name case sensitivity, Language Structure +@subsection User Variables @cindex variables, user @cindex user variables @@ -27340,7 +27341,7 @@ row, but the value of @code{id} for the previous accepted row. * Reserved words:: @end menu -@node Comments, Reserved words, Variables, Variables +@node Comments, Reserved words, Variables, Language Structure @subsection Comment Syntax @findex Comment syntax @@ -27392,7 +27393,7 @@ input from that file with @code{mysql < some-file}. @xref{Missing comments}. -@node Reserved words, , Comments, Variables +@node Reserved words, , Comments, Language Structure @subsection Is MySQL Picky About Reserved Words? @cindex keywords @@ -27506,7 +27507,7 @@ used them. @end itemize -@node Column types, Functions, Variables, Reference +@node Column types, Functions, Language Structure, Reference @section Column Types @cindex columns, types @@ -33034,15 +33035,22 @@ For more information about the efficiency of @code{INSERT} versus @xref{Insert speed}. -@node Data Definition, DROP DATABASE, Data Manipulation, Reference +@node Data Definition, Basic User Commands, Data Manipulation, Reference @section Data Definition: @code{CREATE}, @code{DROP}, @code{ALTER} @menu * CREATE DATABASE:: +* DROP DATABASE:: +* CREATE TABLE:: +* ALTER TABLE:: +* RENAME TABLE:: +* DROP TABLE:: +* CREATE INDEX:: +* DROP INDEX:: @end menu -@node CREATE DATABASE, , Data Definition, Data Definition +@node CREATE DATABASE, DROP DATABASE, Data Definition, Data Definition @subsection @code{CREATE DATABASE} Syntax @findex CREATE DATABASE @@ -33065,8 +33073,8 @@ You can also create databases with @code{mysqladmin}. @xref{Client-Side Scripts}. -@node DROP DATABASE, Basic User Commands, Data Definition, Reference -@section @code{DROP DATABASE} Syntax +@node DROP DATABASE, CREATE TABLE, CREATE DATABASE, Data Definition +@subsection @code{DROP DATABASE} Syntax @findex DROP DATABASE @@ -33113,7 +33121,7 @@ You can also drop databases with @code{mysqladmin}. @xref{Client-Side Scripts}. * DROP INDEX:: @end menu -@node CREATE TABLE, ALTER TABLE, DROP DATABASE, DROP DATABASE +@node CREATE TABLE, ALTER TABLE, DROP DATABASE, Data Definition @subsection @code{CREATE TABLE} Syntax @findex CREATE TABLE @@ -33625,7 +33633,7 @@ Certain other column type changes may occur if you compress a table using @code{myisampack}. @xref{Compressed format}. -@node ALTER TABLE, RENAME TABLE, CREATE TABLE, DROP DATABASE +@node ALTER TABLE, RENAME TABLE, CREATE TABLE, Data Definition @subsection @code{ALTER TABLE} Syntax @findex ALTER TABLE @@ -33889,7 +33897,7 @@ column, the numbers will start from 1 again. @xref{ALTER TABLE problems}. -@node RENAME TABLE, DROP TABLE, ALTER TABLE, DROP DATABASE +@node RENAME TABLE, DROP TABLE, ALTER TABLE, Data Definition @subsection @code{RENAME TABLE} Syntax @findex RENAME TABLE @@ -33933,7 +33941,7 @@ will do a reverse rename for all renamed tables to get everything back to the original state. -@node DROP TABLE, CREATE INDEX, RENAME TABLE, DROP DATABASE +@node DROP TABLE, CREATE INDEX, RENAME TABLE, Data Definition @subsection @code{DROP TABLE} Syntax @findex DROP TABLE @@ -33956,7 +33964,7 @@ For the moment they don't do anything. automatically commit any active transactions. -@node CREATE INDEX, DROP INDEX, DROP TABLE, DROP DATABASE +@node CREATE INDEX, DROP INDEX, DROP TABLE, Data Definition @subsection @code{CREATE INDEX} Syntax @findex CREATE INDEX @@ -34013,7 +34021,7 @@ are available in @strong{MySQL} Version 3.23.23 and later. @ref{Fulltext Search}. -@node DROP INDEX, , CREATE INDEX, DROP DATABASE +@node DROP INDEX, , CREATE INDEX, Data Definition @subsection @code{DROP INDEX} Syntax @findex DROP INDEX @@ -34029,7 +34037,7 @@ prior to Version 3.22. In Version 3.22 or later, @code{DROP INDEX} is mapped to @xref{ALTER TABLE, , @code{ALTER TABLE}}. -@node Basic User Commands, Transactional Commands, DROP DATABASE, Reference +@node Basic User Commands, Transactional Commands, Data Definition, Reference @section Basic MySQL User Utility Commands @menu @@ -34105,7 +34113,7 @@ The @code{SHOW} statement provides similar information. @node Transactional Commands, Fulltext Search, Basic User Commands, Reference -@section MYSQL Transactional and Locking Commands +@section MySQL Transactional and Locking Commands @menu * COMMIT:: From 95b28dbbb3c7d972d6e35e16dec161ac743566f7 Mon Sep 17 00:00:00 2001 From: unknown Date: Fri, 10 Aug 2001 01:12:42 +0300 Subject: [PATCH 50/51] ibuf0ibuf.c Fix a potential hang in database shutdown (not known if there is such, but let us play safe) innobase/ibuf/ibuf0ibuf.c: Fix a potential hang in database shutdown (not known if there is such, but let us play safe) --- innobase/ibuf/ibuf0ibuf.c | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/innobase/ibuf/ibuf0ibuf.c b/innobase/ibuf/ibuf0ibuf.c index 3db20fb13ee..fd7b415551f 100644 --- a/innobase/ibuf/ibuf0ibuf.c +++ b/innobase/ibuf/ibuf0ibuf.c @@ -1698,8 +1698,7 @@ loop: btr_pcur_open_at_rnd_pos(data->index, BTR_SEARCH_LEAF, &pcur, &mtr); - if (data->size == 1 - && 0 == page_get_n_recs(btr_pcur_get_page(&pcur))) { + if (0 == page_get_n_recs(btr_pcur_get_page(&pcur))) { /* This tree is empty */ From 8ddf0c441464bcb19595ff7735d3f0de8a54318f Mon Sep 17 00:00:00 2001 From: unknown Date: Thu, 9 Aug 2001 18:16:43 -0600 Subject: [PATCH 51/51] mysqlbinlog->client BitKeeper/etc/ignore: Added client/log_event.cc client/log_event.h client/mf_iocache.c client/mf_iocache.cc client/mysqlbinlog client/mysys_priv.h mysql.kdevprj to the ignore list Makefile.am: do symlink hack in the client directory ( originally needed to get log_event.cc for mysqlbinlog) client/mysqlbinlog.cc: fixes to make it compile in the client directory libmysql/Makefile.shared: link mysqlbinlog dependencies into libmysqlclient libmysql/libmysql.c: make simple_command and net_safe_read extern ( for mysqlbinlog) sql/log_event.cc: removed pthread dependency in mysqlbinlog sql/log_event.h: removed pthread dependency in mysqlbinlog --- .bzrignore | 7 +++++++ Makefile.am | 1 + client/Makefile.am | 17 ++++++++++++++++- {sql => client}/mysqlbinlog.cc | 35 ++++++++++++++++++---------------- libmysql/Makefile.shared | 3 ++- libmysql/libmysql.c | 4 ++-- sql/Makefile.am | 4 ---- sql/log_event.cc | 31 +++++++++++++++++++----------- sql/log_event.h | 4 ++++ 9 files changed, 71 insertions(+), 35 deletions(-) rename {sql => client}/mysqlbinlog.cc (93%) diff --git a/.bzrignore b/.bzrignore index e18c49af87c..c6cfce671f6 100644 --- a/.bzrignore +++ b/.bzrignore @@ -291,3 +291,10 @@ myisam/test1.MYD myisam/test1.MYI .gdbinit .vimrc +client/log_event.cc +client/log_event.h +client/mf_iocache.c +client/mf_iocache.cc +client/mysqlbinlog +client/mysys_priv.h +mysql.kdevprj diff --git a/Makefile.am b/Makefile.am index bfe6a8a2e43..22e066ac9d4 100644 --- a/Makefile.am +++ b/Makefile.am @@ -37,6 +37,7 @@ linked_include_sources: echo timestamp > linked_include_sources linked_client_sources: @linked_client_targets@ + cd client; $(MAKE) link_sources echo timestamp > linked_client_sources linked_libmysql_sources: diff --git a/client/Makefile.am b/client/Makefile.am index 24221dcab74..c05f6a396dc 100644 --- a/client/Makefile.am +++ b/client/Makefile.am @@ -21,7 +21,8 @@ INCLUDES = -I$(srcdir)/../include \ -I.. LIBS = @CLIENT_LIBS@ LDADD = @CLIENT_EXTRA_LDFLAGS@ ../libmysql/libmysqlclient.la -bin_PROGRAMS = mysql mysqladmin mysqlcheck mysqlshow mysqldump mysqlimport mysqltest +bin_PROGRAMS = mysql mysqladmin mysqlcheck mysqlshow \ + mysqldump mysqlimport mysqltest mysqlbinlog noinst_PROGRAMS = insert_test select_test thread_test noinst_HEADERS = sql_string.h completion_hash.h my_readline.h mysql_SOURCES = mysql.cc readline.cc sql_string.cc completion_hash.cc @@ -36,10 +37,24 @@ insert_test_DEPENDENCIES= $(LIBRARIES) $(pkglib_LTLIBRARIES) select_test_DEPENDENCIES= $(LIBRARIES) $(pkglib_LTLIBRARIES) mysqltest_SOURCES= mysqltest.c mysqltest_DEPENDENCIES= $(LIBRARIES) $(pkglib_LTLIBRARIES) +mysqlbinlog_SOURCES = mysqlbinlog.cc +mysqlbinlog_DEPENDENCIES= $(LIBRARIES) $(pkglib_LTLIBRARIES) +sql_src=log_event.h log_event.cc +mysys_src=mysys_priv.h # Fix for mit-threads DEFS = -DUNDEF_THREADS_HACK +link_sources: + for f in $(sql_src) ; do \ + rm -f $$f; \ + @LN_CP_F@ ../sql/$$f $$f; \ + done; \ + for f in $(mysys_src); do \ + rm -f $$f; \ + @LN_CP_F@ ../mysys/$$f $$f; \ + done; + thread_test.o: thread_test.c $(COMPILE) -c @MT_INCLUDES@ $(INCLUDES) $< diff --git a/sql/mysqlbinlog.cc b/client/mysqlbinlog.cc similarity index 93% rename from sql/mysqlbinlog.cc rename to client/mysqlbinlog.cc index 5edfe6e0591..a89b41fdfd3 100644 --- a/sql/mysqlbinlog.cc +++ b/client/mysqlbinlog.cc @@ -22,13 +22,19 @@ #include #include #include -#define MYSQL_SERVER // We want the C++ version of net #include #include "log_event.h" -#include "mini_client.h" #define CLIENT_CAPABILITIES (CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | CLIENT_LOCAL_FILES) +extern "C" +{ + int simple_command(MYSQL *mysql,enum enum_server_command command, + const char *arg, + uint length, my_bool skipp_check); + int net_safe_read(MYSQL* mysql); +} + char server_version[SERVER_VERSION_LENGTH]; uint32 server_id = 0; @@ -108,7 +114,7 @@ static void die(const char* fmt, ...) static void print_version() { - printf("%s Ver 1.4 for %s at %s\n",my_progname,SYSTEM_TYPE, MACHINE_TYPE); + printf("%s Ver 1.5 for %s at %s\n",my_progname,SYSTEM_TYPE, MACHINE_TYPE); } @@ -248,12 +254,12 @@ static int parse_args(int *argc, char*** argv) static MYSQL* safe_connect() { - MYSQL *local_mysql = mc_mysql_init(NULL); + MYSQL *local_mysql = mysql_init(NULL); if(!local_mysql) - die("Failed on mc_mysql_init"); + die("Failed on mysql_init"); - if(!mc_mysql_connect(local_mysql, host, user, pass, 0, port, 0, 0)) - die("failed on connect: %s", mc_mysql_error(local_mysql)); + if(!mysql_real_connect(local_mysql, host, user, pass, 0, port, 0, 0)) + die("failed on connect: %s", mysql_error(local_mysql)); return local_mysql; } @@ -281,7 +287,7 @@ static void dump_remote_table(NET* net, const char* db, const char* table) *p++ = table_len; memcpy(p, table, table_len); - if(mc_simple_command(mysql, COM_TABLE_DUMP, buf, p - buf + table_len, 1)) + if(simple_command(mysql, COM_TABLE_DUMP, buf, p - buf + table_len, 1)) die("Error sending the table dump command"); for(;;) @@ -314,14 +320,14 @@ static void dump_remote_log_entries(const char* logname) len = (uint) strlen(logname); int4store(buf + 6, 0); memcpy(buf + 10, logname,len); - if(mc_simple_command(mysql, COM_BINLOG_DUMP, buf, len + 10, 1)) + if(simple_command(mysql, COM_BINLOG_DUMP, buf, len + 10, 1)) die("Error sending the log dump command"); for(;;) { - len = mc_net_safe_read(mysql); + len = net_safe_read(mysql); if (len == packet_error) - die("Error reading packet from server: %s", mc_mysql_error(mysql)); + die("Error reading packet from server: %s", mysql_error(mysql)); if(len == 1 && net->read_pos[0] == 254) break; // end of data DBUG_PRINT("info",( "len= %u, net->read_pos[5] = %d\n", @@ -391,7 +397,7 @@ static void dump_local_log_entries(const char* logname) char llbuff[21]; my_off_t old_off = my_b_tell(file); - Log_event* ev = Log_event::read_log_event(file, 0); + Log_event* ev = Log_event::read_log_event(file); if (!ev) { if (file->error) @@ -430,9 +436,6 @@ int main(int argc, char** argv) if(use_remote) { -#ifndef __WIN__ - init_thr_alarm(10); // need to do this manually -#endif mysql = safe_connect(); } @@ -457,7 +460,7 @@ int main(int argc, char** argv) if (result_file != stdout) my_fclose(result_file, MYF(0)); if (use_remote) - mc_mysql_close(mysql); + mysql_close(mysql); return 0; } diff --git a/libmysql/Makefile.shared b/libmysql/Makefile.shared index b6ea5832e04..e9e100e38b1 100644 --- a/libmysql/Makefile.shared +++ b/libmysql/Makefile.shared @@ -55,7 +55,8 @@ mysysobjects1 = my_init.lo my_static.lo my_malloc.lo my_realloc.lo \ mf_loadpath.lo my_pthread.lo my_thr_init.lo \ thr_mutex.lo mulalloc.lo string.lo default.lo \ my_compress.lo array.lo my_once.lo list.lo my_net.lo \ - charset.lo hash.lo + charset.lo hash.lo mf_iocache.lo my_seek.lo \ + my_pread.lo mf_cache.lo # Not needed in the minimum library mysysobjects2 = getopt.lo getopt1.lo getvar.lo my_lib.lo mysysobjects = $(mysysobjects1) $(mysysobjects2) diff --git a/libmysql/libmysql.c b/libmysql/libmysql.c index 9221812ea65..4101fe18ea1 100644 --- a/libmysql/libmysql.c +++ b/libmysql/libmysql.c @@ -287,7 +287,7 @@ HANDLE create_named_pipe(NET *net, uint connect_timeout, char **arg_host, ** or packet is an error message *****************************************************************************/ -static uint +uint net_safe_read(MYSQL *mysql) { NET *net= &mysql->net; @@ -417,7 +417,7 @@ static void free_rows(MYSQL_DATA *cur) } -static int +int simple_command(MYSQL *mysql,enum enum_server_command command, const char *arg, uint length, my_bool skipp_check) { diff --git a/sql/Makefile.am b/sql/Makefile.am index 28484f09b3d..f1941e1e25c 100644 --- a/sql/Makefile.am +++ b/sql/Makefile.am @@ -27,7 +27,6 @@ INCLUDES = @MT_INCLUDES@ \ -I$(srcdir) -I../include -I.. -I. WRAPLIBS= @WRAPLIBS@ SUBDIRS = share -bin_PROGRAMS = mysqlbinlog libexec_PROGRAMS = mysqld noinst_PROGRAMS = gen_lex_hash gen_lex_hash_LDFLAGS = @NOINST_LDFLAGS@ @@ -83,9 +82,6 @@ mysqld_SOURCES = sql_lex.cc \ md5.c stacktrace.c gen_lex_hash_SOURCES = gen_lex_hash.cc gen_lex_hash_LDADD = $(LDADD) $(CXXLDFLAGS) -mysqlbinlog_SOURCES = mysqlbinlog.cc mini_client.cc net_serv.cc \ - mini_client_errors.c violite.c password.c -mysqlbinlog_LDADD = $(LDADD) $(CXXLDFLAGS) # $(mysqld_LDADD) DEFS = -DMYSQL_SERVER \ -DDEFAULT_MYSQL_HOME="\"$(MYSQLBASEdir)\"" \ diff --git a/sql/log_event.cc b/sql/log_event.cc index ac985c266c8..1263d361b7f 100644 --- a/sql/log_event.cc +++ b/sql/log_event.cc @@ -111,18 +111,29 @@ int Log_event::read_log_event(IO_CACHE* file, String* packet, #endif // MYSQL_CLIENT -// allocates memory - the caller is responsible for clean-up +#ifndef MYSQL_CLIENT +#define UNLOCK_MUTEX if(log_lock) pthread_mutex_unlock(log_lock); +#else +#define UNLOCK_MUTEX +#endif +// allocates memory - the caller is responsible for clean-up +#ifndef MYSQL_CLIENT Log_event* Log_event::read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock) +#else +Log_event* Log_event::read_log_event(IO_CACHE* file) +#endif { time_t timestamp; uint32 server_id; char buf[LOG_EVENT_HEADER_LEN-4]; +#ifndef MYSQL_CLIENT if(log_lock) pthread_mutex_lock(log_lock); +#endif if (my_b_read(file, (byte *) buf, sizeof(buf))) { - if (log_lock) pthread_mutex_unlock(log_lock); + UNLOCK_MUTEX return NULL; } timestamp = uint4korr(buf); @@ -133,7 +144,7 @@ Log_event* Log_event::read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock) case QUERY_EVENT: { Query_log_event* q = new Query_log_event(file, timestamp, server_id); - if(log_lock) pthread_mutex_unlock(log_lock); + UNLOCK_MUTEX if (!q->query) { delete q; @@ -145,7 +156,7 @@ Log_event* Log_event::read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock) case LOAD_EVENT: { Load_log_event* l = new Load_log_event(file, timestamp, server_id); - if(log_lock) pthread_mutex_unlock(log_lock); + UNLOCK_MUTEX if (!l->table_name) { delete l; @@ -158,8 +169,7 @@ Log_event* Log_event::read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock) case ROTATE_EVENT: { Rotate_log_event* r = new Rotate_log_event(file, timestamp, server_id); - if(log_lock) pthread_mutex_unlock(log_lock); - + UNLOCK_MUTEX if (!r->new_log_ident) { delete r; @@ -171,8 +181,7 @@ Log_event* Log_event::read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock) case INTVAR_EVENT: { Intvar_log_event* e = new Intvar_log_event(file, timestamp, server_id); - if(log_lock) pthread_mutex_unlock(log_lock); - + UNLOCK_MUTEX if (e->type == INVALID_INT_EVENT) { delete e; @@ -184,13 +193,13 @@ Log_event* Log_event::read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock) case START_EVENT: { Start_log_event* e = new Start_log_event(file, timestamp, server_id); - if(log_lock) pthread_mutex_unlock(log_lock); + UNLOCK_MUTEX return e; } case STOP_EVENT: { Stop_log_event* e = new Stop_log_event(file, timestamp, server_id); - if(log_lock) pthread_mutex_unlock(log_lock); + UNLOCK_MUTEX return e; } default: @@ -198,7 +207,7 @@ Log_event* Log_event::read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock) } // default - if (log_lock) pthread_mutex_unlock(log_lock); + UNLOCK_MUTEX return NULL; } diff --git a/sql/log_event.h b/sql/log_event.h index 8d8ac183f61..94f7cce0e35 100644 --- a/sql/log_event.h +++ b/sql/log_event.h @@ -105,8 +105,12 @@ public: void print_timestamp(FILE* file, time_t *ts = 0); void print_header(FILE* file); +#ifndef MYSQL_CLIENT // if mutex is 0, the read will proceed without mutex static Log_event* read_log_event(IO_CACHE* file, pthread_mutex_t* log_lock); +#else // avoid having to link mysqlbinlog against libpthread + static Log_event* read_log_event(IO_CACHE* file); +#endif static Log_event* read_log_event(const char* buf, int event_len); #ifndef MYSQL_CLIENT