Go to the first, previous, next, last section, table of contents.


4 データベース管理

4.1 Configuring MySQL

4.1.1 mysqld コマンド行オプション

多くの場合、オプションファイルを通じて mysqld オプションを管理すべきです。 「4.1.2 `my.cnf' オプションファイル」節参照.

mysqldmysqld.servermysqldserver グループからオプションを読み込みます。mysqld_safemysqld, server, mysqld_safe, safe_mysqld グ ループからオプションを読み込みます。組み込み MySQL サーバは通常 server, embedded, xxxxx_SERVER からオプションを読み 込みます。xxxxx はアプリケーション名です。

mysqld は次のコマンド行オプションを受け付けます。 完全なリストについては mysqld --help を実行してください。

--ansi
MySQL 構文の代わりに ANSI SQL 構文を使用します。 「1.7.2 MySQLをANSIモードで実行する」節参照.
-b, --basedir=path
インストール先ディレクトリのパス。すべてのパスは通常ここからの相対パスで決 定されます。
--big-tables
ファイルにすべての一時セットを保存することにより、大きな結果セットを許しま す。これは、多くの 'table full' エラーを解決します。しかし、メモリ内テーブ ルでも十分なクエリは遅くなります。バージョン 3.23.2 からは、 MySQL は自動的にメモリを使用し、必要なときにディスクテーブルにス イッチすることによって、これを解決します。
--bind-address=IP
bind する IP アドレス。
--console
--log-error が指定されていても、エラーログメッセージを stderr/stdout に書き出します。Windows mysqld はこのオプションが使用され た場合はコンソールスクリーンをクローズしません。
--character-sets-dir=path
キャラクタ・セット ディレクトリ。 「4.6.1 データとソートに使用されるキャラクター・セット」節参照.
--chroot=path
起動時に mysqld デーモンを chroot 下に置きます。 MySQL 4.0 からの推奨されるセキュリティ手法です。 (MySQL 3.23 は 100% クローズな chroot jail を提供できません)。 これは LOAD DATA INFILESELECT ... INTO OUTFILE を制限します。
--core-file
mysqld が死んだ場合 core ファイルを書き出します。いくつかのシステム では、--core-file-sizesafe_mysqld に記述する必要がありま す。 「4.7.2 safe_mysqld, The Wrapper Around mysqld」節参照. 注意: Solaris のようないくつかのシステムでは、--user オプションも 使用すると core ファイルを得られません。
-h, --datadir=path
データベースルートのパス。
--debug[...]=
MySQL が --with-debug つきで configure された場合、このオ プション使用して、mysqld が何を行なっているかのトレースファイルを得 ることができます 「E.1.2 Creating Trace Files」節参照.
--default-character-set=charset
デフォルト のキャラクタ・セットの設定。 「4.6.1 データとソートに使用されるキャラクター・セット」節参照.
--default-table-type=type
テーブルのデフォルトテーブル型を設定する。 「7 MySQL テーブル型」節参照.
--delay-key-write[= OFF | ON | ALL]
MyISAM DELAYED KEYS が使用される方法。 「5.5.2 サーバーパラメーターのチューニング」節参照。
--delay-key-write-for-all-tables; MySQL 4.0.3 では代わりに --delay-key-write=ALL を使用。
任意の MyISAM テーブルについて書き込み間でキーバッファをフラッシュ しません。 「5.5.2 サーバーパラメーターのチューニング」節参照.
--des-key-file=filename
このファイルから DES_ENCRYPT()DES_DECRYPT() で使用され るデフォルトキーを読み込みます。
--enable-external-locking (4.0.3 から. それ以前のバージョンでは --enable-locking)
システムロックを有効にします。注意: lockd() が完全に働かない(Linux のよう な)システムでこのオプションを使用した場合、mysqld が簡単にデッドロックしま す。
--enable-named-pipe
名前付きパイプのサポートを有効にします (NT/Win2000/XP のみ)。
-T, --exit-info
mysqld サーバをデバッグするために使用できる、様々なフラグのビットマスクで す; 何が行なわれるのか正確に知らない場合は、このオプションを使用すべきでは ありません!
--flush
各 SQL コマンド後にすべての変更をディスクにフラッシュします。通常 MySQL は各 SQL コマンドにすべての変更をディスクに書き出すだけで、 OS がディスクへの sync を処理します。 「A.4.1 What To Do If MySQL Keeps Crashing」節参照.
-?, --help
短いへルプを表示して終了します。
--init-file=file
起動時にファイルから SQL コマンドを読み込みます。
-L, --language=...
与えられた言語のクライアントエラーメッセージ。フルパスで与えることもできます。 「4.6.2 Non-English Error Messages」節参照.
-l, --log[=file]
接続とクエリをファイルに記録します。 「4.9.2 The General Query Log」節参照.
--log-bin=[file]
データを変更するすべてのクエリをファイルに記録します。バックアップとレプ リケーションのために使用されます。 「4.9.4 The Binary Update Log バイナリ更新ログ (3.23.15以上)」節参照。
--log-bin-index[=file]
バイナリログファイル名のためのインデックスファイル。 「4.9.4 The Binary Update Log バイナリ更新ログ (3.23.15以上)」節参照。
--log-error[=file]
エラーと起動メッセージをこのファイルに記録します。 「4.9.1 The Error Log」節参照。
--log-isam[=file]
すべての ISAM/MyISAM 変更をファイルに記録します(ISAM/MyISAM のデバッグ時に のみ使用できます)。
--log-slow-queries[=file]
実行に long_query_time 秒以上掛かるすべてのクエリをファイルに記録し ます。 「4.9.5 The Slow Query Log (3.23.28以上)」節参照.
--log-update[=file]
更新を file.# に記録します。# は与えられなければ一意な番号で す。 「4.9.3 更新ログ」節参照.
--log-long-format
更新ログに拡張情報を記録します。--log-slow-queries を使用すると、イ ンデックスを使用しないクエリが slow query ログに記録されます。
--low-priority-updates
テーブル変更操作 (INSERT/DELETE/UPDATE) は SELECT よ りも低い優先度になります。あるクエリだけ優先度を低くするには、 {INSERT | REPLACE | UPDATE | DELETE} LOW_PRIORITY ... によって行 なわれます。また、ひとつのスレッドの優先度を変更するには、 SET LOW_PRIORITY_UPDATES=1 で行なわれます。 「5.3.2 テーブル・ロッキングの問題」節参照.
--memlock
メモリに mysqld プロセスをロックします。これはシステムが mlockall() システムコールをサポートしている時(Solaris のように)にだけ動作します。 これは、OS が mysqld をディスク上にスワップさせる問題がある場合の助けに なります。
--myisam-recover [=option[,option...]]]
ここで option は DEFAULTBACKUPFORCEQUICK の組み合わせ. 3.23.26以上で有効. このオプションを使用すると、mysqld はオープン時にテーブルがクラッシュ したとマークされているかどうか、テーブルが適切にクローズされていないかどう かチェックします。(最後のオプションは --skip-external-locking (4.0.3より前のバージョンでは --skip-locking) で起動している 場合にだけ働きます)。この場合、mysqld はテーブル上でチェックを実 行します。テーブルが壊れている場合、mysqld はその修復を試みます。 次のオプションは修復の動作に影響します:
Option Description
DEFAULT --myisam-recover にオプションを与えないのと同じです。
BACKUP データテーブルが修復中に変更された場合、 `table_name.MYD' データファイルのバックアップを `table_name-datetime.BAK' に保存します。
FORCE .MYD ファイルからひとつより多くのレコードが失われている 場合でも修復を実行します。
QUICK 削除ブロックがない場合にテーブル内のレコードをチェック しません。
テーブルが自動的に修復される前に、MySQL はエラーログにこれについ てのメモを追加します。ユーザの介入なしで多くのことを修復したい場合は、オプ ション BACKUP,FORCE を使用すべきです。いくつかのレコードが削除され る場合でも、テーブルを強制的に修復しますが、古いデータファイルをバックアッ プとして保存するため、あとで何が起こったか検証できます。
--pid-file=path
safe_mysqld によって使用される pid ファイルのパス。
-P, --port=...
TCP/IP 接続で listen するポート番号。
-o, --old-protocol
とても古いクライアントとの互換のために、3.20 プロトコルを使用します。 「2.5.5 バージョン 3.20 から バージョン 3.21 へのアップグレード」節参照.
--one-thread
一つのスレッドだけを使用します(Linux 下でデバックするため)。 「E.1 MySQL server のデバッグ」節参照.
-O, --set-variable var=option
変数に値を与えます。--help は変数をリストします。すべての変数の完全 な詳細はこのマニュアルの SHOW VARIABLES 節で見られます。 「4.5.6.4 SHOW VARIABLES」節参照。サーバパラメータの調整についての節はこれらの最適化 方法の情報を含んでいます。 MySQL 4.0 からは --set-variable は推奨されないことに注意してください。 --var=option を使用してください。 「5.5.2 サーバーパラメーターのチューニング」節参照。 MySQL 4.0.2 では、--variable-name=option で直接変数を設定できます。 set-variable はオプションファイル中ではもはや必要ありません。 SET で設定できる起動オプションの最大値を制限したい場合は、 --maximum-variable-name コマンドラインオプションを使用することで 定義できます。 「5.5.6 SET 構文」節参照。 注意: 変数に値を設定する時、MySQL は自動的に与えられた範囲に収まるように 補正し、使用されるアルゴリズム用に合うように値を少し調整します。
--safe-mode
いくつかの最適化ステージをスキップします。
--safe-show-database
このオプションをつけると、SHOW DATABASES コマンドは、ユーザが何か の権限を持つデータベースだけを返します。 バージョン 4.0.2 からはこのオプションは推奨されず何もしません(デフォルト でこのオプションは有効です)。現在は SHOW DATABASES 権限を持つため です。 「4.3.1 GRANTREVOKE 構文」節参照。
--safe-user-create
これが有効な場合、ユーザが mysql.user テーブルやこのテーブル内の 任意のフィールドについて INSERT 権限を持っていない場合、そのユー ザは GRANT コマンドで新しいユーザを作成できません。
--skip-bdb
BDB テーブルの使用を無効にします。これはメモリを節約し、いくつかのことを 高速化します。
--skip-concurrent-insert
同時に MyISAM テーブルに select と insert を行なう機能をオフにしま す。(この機能にバグを見つけたと考える場合にだけ使用します)。
--skip-delay-key-write; MySQL 4.0.3 では代わりに --delay-key-write=OFF を使用
すべてのテーブルに対し DELAY_KEY_WRITE オプションを無視します。 「5.5.2 サーバーパラメーターのチューニング」節参照.
--skip-grant-tables
このオプションは、サーバをすべての権限システムを使用しないようにします。これ は全員にすべてのデータベースへの完全アクセスを与えます! (mysqladmin flush-privilegesmysqladmin reload を実行する ことで、権限テーブルを使用して起動するように実行中のサーバに伝えることがで きます。)
--skip-host-cache
より速いホスト名-IP解決のためのホスト名キャッシュを使用しません。代わりに すべての接続で DNS サーバへクエリします。 「5.5.5 How MySQL uses DNS」節参照.
--skip-innodb
Innodb テーブルの使用を無効にします。これはメモリとディスク領域の節約と いくつかのことを高速化します。
--skip-external-locking (4.0.3から. 4.0.3より前では --skip-locking)
システムロックを使用しません。isamchk または myisamchk を使 用するためには、サーバをシャットダウンする必要があります。 「1.2.3 MySQL はどれくらい安定か?」節参照。注意: MySQL バージョン 3.23 では、 REPAIRCHECKMyISAM テーブルの修復/チェックに 使用できます。
--skip-name-resolve
ホスト名を解決しません。権限テーブルのすべての Host フィールド値は IP 番号か localhost でなければなりません。 「5.5.5 How MySQL uses DNS」節参照.
--skip-networking
TCP/IP 接続の listen をまったく行ないません。mysqld との接続には Unix ソケット経由で行なう必要があります。このオプションはローカル要求だけ を許可するシステムでは、高く推奨されます。 「5.5.5 How MySQL uses DNS」節参照.
--skip-new
Don't use new, possible wrong routines.
--skip-symlink
データディレクトリ中のシンボリックリンクファイルが指すファイルを削除、リ ネームしません。
--skip-safemalloc
MySQL が --with-debug=full で configure されている場合、す べてのプログラムがすべてのメモリ割り当てとメモリ解放をオーバーラン用にチェッ クします。このチェックはとても遅いので、メモリチェックが不要な場合、このオ プションを使用することでこれを無効にできます。
--skip-show-database
SHOW DATABASES 権限を持っていないユーザに SHOW DATABASES コマンドを 許しません。 バージョン 4.0.2 からは、このオプションは必要ありません。現在、アクセス は SHOW DATABASES 権限で特別に与えられるためです。
--skip-stack-trace
スタックトレースを書き出しません。このオプションは、mysqld をデバッ ガ下で実行している時に有用です。 いくつかのシステムでは、core ファイルを得るためにこのオプションも使用す る必要があります。 「E.1 MySQL server のデバッグ」節参照。
--skip-thread-priority
より速いレスポンスタイム用のスレッド優先度の使用を無効にします。
--socket=path
デフォルト /tmp/mysql.sock の代わりに、ローカル接続用に使用されるソ ケットファイル。
--sql-mode=option[,option[,option...]]
オプションは次の任意の組合わせです: REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, SERIALIZE, ONLY_FULL_GROUP_BY。リセットしたい場合は、空 ("") も指定できます。 上記オプションの全てを指定することで、--ansi の使用と同じになります。 このオプションで、必要とされる SQL モードだけを有効にできます。 「1.7.2 MySQLをANSIモードで実行する」節参照。
--temp-pool
Using this option will cause most temporary files created to use a small set of names, rather than a unique name for each new file. This is to work around a problem in the Linux kernel dealing with creating a bunch of new files with different names. With the old behaviour, Linux seems to 'leak' memory, as it's being allocated to the directory entry cache instead of the disk cache.
--transaction-isolation= { READ-UNCOMMITTED | READ-COMMITTED | REPEATABLE-READ | SERIALIZABLE }
トランザクション分離レベルのデフォルトを設定します。 「6.7.3 SET TRANSACTION 構文」節参照。
-t, --tmpdir=path
一時ファイル用のパス。デフォルトの /tmp ディレクトリが一時テーブル を保持するのに小さすぎるパーティション上にある場合に有用です。 MySQL 4.1 からは、このオプションはコロン :(Windows ではセミコロン ;)で区切られたいくつかのパスを受け付けます。これらはラウンドロビ ン方法で使用されます。
-u, --user= [user_name | userid]
ユーザ user_nameuserid (数値) で mysqld デーモンを実行します。 このオプションは、mysqld を root で起動した時に 強制されます。 Starting from MySQL 3.23.56 and 4.0.12: To avoid a possible security hole where a user adds an --user=root option to some `my.cnf' file, mysqld will only use the first --user option specified and give a warning if there are multiple options. Note that `/etc/my.cnf' and `datadir/my.cnf' may override a command line option - therefore it is recommended to put this option in `/etc/my.cnf'.
-V, --version
バージョン情報を出力して終了します
-W, --log-warnings (4.0.3 より前では --warnings)
Aborted connection... のような警告を .err ファイルに出力します。 「A.2.9 Communication Errors / Aborted Connection」節参照.

SET コマンドで実行中のサーバの多くの値を変更できます。 「5.5.6 SET 構文」節参照。

4.1.2 `my.cnf' オプションファイル

MySQL バージョン 3.22 のサーバー、クライアントともに、 オプションファイルからデフォルトの起動オプションを読み込むことができます。

Unix では MySQL は以下のファイルからデフォルトオプションを読みます:

ファイル名 意味
/etc/my.cnf グローバルなオプション
DATADIR/my.cnf サーバ固有オプション
defaults-extra-file --defaults-extra-file=# で指定されたファイル
~/.my.cnf ユーザ固有オプション

DATADIR は MySQL データディレクトリです (普通 バイナリディストリビューションでは `/usr/local/mysql/data' 、ソースディストリビューションでは `/usr/local/var'). このディレクトリはconfigure時に決定されており、 --datadirmysqld 起動時に指定しても変更されません。 (サーバーはコマンドラインの引数を処理する前にオプションファイルを探します。 よって、--datadir 引数を指定してもオプションファイルを探す場所を指定することにはなりません。)

Windows では MySQL は以下のファイルからデフォルトオプションを読みます:

ファイル名 意味
windows-system-directory\my.ini グローバルオプション
C:\my.cnf グローバルオプション

注意: Windows では \ の代わりに / で全てのパスを記述すべきで す。\ を使用する場合、\ は MySQL のエスケープ文字 なので、これを二重に記述する必要があります。

MySQL は上記の表にかかれている順にオプションファイルを読みます。 もし複数オプションファイルがあった場合、後から読まれた設定が有効になります。 全てのオプションはコマンドラインの引数に上書きされます。 いくつかのオプションは環境変数に定義できます。 オプションファイルとコマンドラインの引数は環境変数を上書きします。 「F Environment Variables」節参照.

次のプログラムはオプションファイルをサポートします: mysql, mysqladmin, mysqld, mysqld_safe, mysql.server, mysqldump, mysqlimport, mysqlshow, mysqlcheck, myisamchk, myisampack.

オプションファイルには、プログラムがサポートしているコマンドラインの long オプション(例えば、-u ではなくて --user の方)を書くことができます。 プログラムを --help で起動すれば、設定可能な変数名が得られます。

オプションファイルの書式は以下です:

#comment
コメントは `#'`;' 文字で始めます。空の行は無視します。
[group]
グループ宣言。 group はオプションを定義するプログラムかグループの名前です。 この宣言の後、オプションset-variable 行で、このグループにオプションを与えます。 このセクションの範囲は、他のグループ宣言の行が来るか、ファイルの最後に来るまでです。
option
これはコマンドラインの --option と等価です。
option=value
これはコマンドラインの --option=value と等価です。
set-variable = variable=value
これはコマンドラインの --set-variable variable=value と等価です。 これは mysqld 変数で使用される形式です。 MySQL 4.0 からは --set-variable は推奨されないことに注意してくだ さい。--variable=value を使用してください。

client グループは、全ての MySQL クライアント(mysqldは除)に対してオプションを定義します。 これはサーバーに接続する際に使用するパスワードを指定できるグループです。 (この場合、オプションファイルは自分だけが読み書きできるようにしてください)

オプションや値の善後にある全てのブランク文字は自動で取り除かれます。 値として、`\b',`\t', `\n', `\r', `\\', `\s' のエスケープシーケンスが使用できます。 (`\s' == blank).

オプションファイル例:

[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

ユーザーオプションファイル例:

[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

もしソース配布を持っているなら、 `my-xxxx.cnf' という名前のサンプルファイルを `support-files' ディレクトリに見ることができます。 もしバイナリ配布を使用しているなら、 `DIR/support-files' ディレクトリを探してください (ここで DIR は MySQL がインストールされたディレクトリのパス名で、 普通は `/usr/local/mysql')。 この `my-xxxx.cnf' ファイルを自分のディレクトリに `.my.cnf' という名前でコピーして使用できます。

オプションファイルをサポートするすべての MySQL クライアントは次 のオプションをサポートします:

Option Description
--no-defaults オプションファイルを読み込まない。
--print-defaults プログラム名と得られる全てのオプションを出力する。
--defaults-file=full-path-to-default-file 与えられたコンフィグレーションファイルだけを使用する。
--defaults-extra-file=full-path-to-default-file グローバルコンフィグレーションファイルの後、ユーザコンフィグレーションファイルの前にこのコンフィグレーションファイルを読み込む。

注意: 上記のオプションはコマンドラインの先頭になければ働きません! ただ し、--print-defualts--defaults-xxx-file コマンドの直後 にも置けます。

開発者向け情報: オプションファイルの操作は全てのオプションをコマンドラインの 引数より先に処理するように簡単に埋め込まれています。 これはオプションを最後に処理するプログラムを複数立ちあげる場合に都合よく動きます。 もしオプションファイルを読み込む機能のない古いプログラムを使用しているなら、 たった二行だけ注意して書けばいいだけです。 この動作については MySQL クライアントプログラムのコードを参考にしてください。

シェルスクリプト内では、`my_print_defaults' コマンドを使用して、コ ンフィグファイルを解析することができます:


shell> my_print_defaults client mysql
--port=3306
--socket=/tmp/mysql.sock
--no-auto-rehash

上記は、'client' と 'mysql' グループ用の全オプションを出力します。

4.1.3 同じマシンに多くのサーバをインストールする

同じマシン上で多くの異なる mysqld デーモン(サーバ)を動作させたい場 合があります。例えば、テスト用に MySQL の新しいバージョンを使用中の 古いバージョンと共に実行したい場合や、異なる mysqld サーバにそれを管理する 異なるユーザアクセスを与えたい場合などです。

一つの方法は、新しいサーバを次のように異なるソケットとポートで起動すること です:

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 &

The environment variables appendix は mysqld に影響する他の環境変数の 一覧を含んでいます。 「F 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. 「4.1.2 `my.cnf' オプションファイル」節参照. In your startup script that is executed at boot time you should specify for both servers:

safe_mysqld --defaults-file=path-to-option-file

少なくとも、次のオプションはサーバごとに異なるようにすべきです:

次のオプションが使用される場合、異なるようにすべきです:

さらに性能を求める場合、次も異なるように記述できます:

4.1.1 mysqld コマンド行オプション」節参照. Starting from MySQL 4.1, tmpdir can be set to a list of paths separated by colon : (semicolon ; on Windows). They will be used in round-robin fashion. This feature can be used to spread load between several physical disks.

バイナリの MySQL バージョン (.tar ファイル) をインストールして、 ./bin/safe_mysqld で起動する場合、多くの場合では、追加/変更する必要 のあるオプションは safe_mysqld への socketport 引 数だけです。

4.1.4 同一マシン上に複数の MySQL サーバーを走らせる」節参照.

4.1.4 同一マシン上に複数の MySQL サーバーを走らせる

同じマシン上で複数のサーバーを走らせたい場合があります。 例えば、すでに存在しているサーバーはそのままにしておいて、新しい MySQL をテストしたい場合や、 あるいは、インターネットプロバイダーを営んでいて、MySQL をそれぞれの顧客用に提供したい場合など。

複数のサーバーをたちあげる場合、簡単な方法として、 TCP/IP ポート、ソケットファイルを変えて、サーバーをコンパイルする方法があります。 「4.7.3 mysqld_multi, 複数の MySQL サーバーを管理するプログラム」節参照.

そでに走っているサーバーがデフォルトのポート番号とソケットファイルで動作しているとします。 新しくサーバーを作るには、以下のように configure します:

shell> ./configure  --with-tcp-port=port_number \
             --with-unix-socket-path=file_name \
             --prefix=/usr/local/mysql-3.22.9

port_numberfile_name には、デフォルトのポート番号、 ソケットファイルとは違うものを指定します。 そして --prefix を、すでに走っている MySQL の インストール先とは違うディレクトリーに指定します。

現在走っている MySQL サーバーが使用している ソケットとポートをチェックするには、以下のようにします:

shell> mysqladmin -h hostname --port=port_number variables

Note that if you specify ``localhost'' as a hostname, mysqladmin will default to using Unix sockets instead of TCP/IP.

In MySQL 4.1 you can also specify the protocol to use by using the --protocol=(TCP | SOCKET | PIPE | MEMORY) option.

あなたが使用しているポートに MySQL サーバーが走っていれば、 これは変更可能な MySQL 変数を(ソケットファイルの名前も含んで)出力します。

この場合、MySQL サーバーを再コンパイルする必要はありません。 safe_mysqld のオプションを指定してサーバーを起動すれば、 ポートとソケットを変更できます:

shell> /path/to/safe_mysqld --socket=file_name --port=port_number

mysqld_multi can also take safe_mysqld (or mysqld) as an argument and pass the options from a configuration file to safe_mysqld and further to mysqld.

もし、他のサーバーがロギングを行っているディレクトリと同じデータベースディレクトリを、 新しいサーバーで使用するのであれば、ログファイルの名前を指定すべきです。 ( safe_mysqld--log , --log-update , --log-slow-queries を指定する) そうしないと、両方のサーバーが同じログファイルに書き込もうとするからです。

Warning: 通常、二つサーバーに同じデータベースを操作させてはいけません! もし使用している OS が fault-free system locking をサポートしていないと、 これは悲惨なことになるでしょう!

もし二つ目のサーバーに違うデータベースディレクトリを使用させたい場合、 safe_mysqld--datadir=path オプションを指定します。

Note also that starting several MySQL servers (mysqlds) in different machines and letting them access one data directory over NFS is generally a bad idea! The problem is that the 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 mysqlds are not interfering with each other. At the moment there is no platform that would 100% reliable do the file locking (lockd daemon usually) in every situation. Yet there would be one more possible risk with NFS; it would make the work even more complicated for 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.

もし違うポートで走っている MySQL サーバーに、 これまた違うポートを使用するように作られたクライアントから接続したい場合、 以下のようにします:

4.2 General Security Issues and the MySQL Access Privilege System

MySQL has an advanced but non-standard security/privilege system. This section describes how it works.

4.2.1 General Security Guidelines

よくあるセキュリティの間違いを避けるために、インターネットに接続されたコン ピュータ上で MySQL を使用する誰もが、このセクションを読むべきです。

``セキュリティ'' の議論において、我々は、すべての該当するアタックタイプ (eavesdropping, altering, playback, Denial of Service) に対して、すべてのサー バホスト(MySQL サーバだけではなく)の完全な保護の必要性を強調しま す。We do not cover all aspects of availability and fault tolerance here.

MySQL は、ユーザが実行しようとするすべての接続、クエリ、その他の オペレーションに対して、アクセス制御リスト(ACLs: Access Control Lists)セキュ リティを使用します。MySQL クライアントとサーバの間で SSL 暗号化接 続のサポートもいくつかあります。ここで議論されるコンセプトの多くは、 MySQL に特有のものではありません; 同じ一般的なアイデアはほとんど すべてのアプリケーションに適用します。

MySQL 実行時、可能な限りいつでもこれらのガイドラインに従ってくだ さい:

4.2.2 MySQL をクラッカーに対して安全にする方法

MySQL サーバーに接続するときは、パスワードを使用すべきです。 パスワードはコネクション間で、べたテキストでは流れません。 しかし、暗号化アルゴリズムはそんなに強力なわけではありません。クライアント とサーバ間のトラフィックを sniff できれば、いくつかの試みで、賢いアタッカー はパスワードをクラックできます。クライアントとサーバ間の接続が信頼できない ネットワークを通るなら、通信を暗号化するために SSH トンネルを使用 すべきです。

その他の全ての情報はテキストで転送され、 これは接続を覗くことが出来る人に読まれます。 もしこれを心配するなら、圧縮プロトコル(MySQL バージョン 3.22 以上)を 使用することが出来ます。より安全にしたい場合、 ssh をインストールすべきです。 オープンソースの ssh クライアントは http://www.openssh.org/ に、 商用の ssh クライアントは http://www.ssh.com/ に見ることができます。 これを使用すれば、MySQL サーバーと MySQL クライアント 間の TCP/IP コネクションは全て暗号化されます。

If you are using MySQL 4.0, you can also use internal OpenSSL support. 「4.3.9 Using Secure Connections」節参照.

MySQL システムを安全にするためには、次のことを考えるべきです:

4.2.3 セキュリティに関する mysqld の起動オプション

mysqld の次のオプションはセキュリティに影響します:

--local-infile[=(0|1)]
If one uses --local-infile=0 then one can't use LOAD DATA LOCAL INFILE.
--safe-show-database
With this option, the SHOW DATABASES command returns only those databases for which the user has some kind of privilege. From version 4.0.2 this option is deprecated and doesn't do anything (the option is enabled by default) as we now have the SHOW DATABASES privilege. 「4.3.1 GRANTREVOKE 構文」節参照.
--safe-user-create
If this is enabled, an user can't create new users with the GRANT command, if the user doesn't have the INSERT privilege for the mysql.user table. If you want to give a user access to just create new users with those privileges that the user has right to grant, you should give the user the following privilege:
mysql> GRANT INSERT(user) ON mysql.user TO 'user'@'hostname';
This will ensure that the user can't change any privilege columns directly, but has to use the GRANT command to give privileges to other users.
--skip-grant-tables
特権システムを全く使用しません。これは全員に全てのデータベースへの 完全なアクセス を与えます! (mysqladmin flush-privilegesmysqladmin reload を実行することで、 起動しているサーバーは特権システムを使用するようになります。)
--skip-name-resolve
ホスト名を解析しません。権限テーブル中の全ての Hostフィールドは IP アドレスか localhost でなければなりません。
--skip-networking
ネットワーク (TCP/IP) 経由の接続を許可しません。mysqld への全ての接続は、 Unix ソケットで行われます。MIT-pthreads は Unix ソケットをサポートしない ため、このオプションは MIT-pthreads を使用するシステム上で MySQL 3.23.27 以前のバージョンを使用する場合は、うまく動きません。
--skip-show-database
Don't allow SHOW DATABASES command, unless the user has the SHOW DATABASES privilege. From version 4.0.2 you should no longer need this option, since access can now be granted specifically with the SHOW DATABASES privilege.

4.2.4 Security issues with LOAD DATA LOCAL

In MySQL 3.23.49 and MySQL 4.0.2, we added some new options to deal with possible security issues when it comes to LOAD DATA LOCAL.

There are two possible problems with supporting this command:

As the reading of the file is initiated from the server, one could theoretically create a patched MySQL server that could read any file on the client machine that the current user has read access to, when the client issues a query against the table.

In a web environment where the clients are connecting from a web server, a user could use LOAD DATA LOCAL to read any files that the web server process has read access to (assuming a user could run any command against the SQL server).

There are two separate fixes for this:

If you don't configure MySQL with --enable-local-infile, then LOAD DATA LOCAL will be disabled by all clients, unless one calls mysql_options(... MYSQL_OPT_LOCAL_INFILE, 0) in the client. 「8.4.3.163 mysql_options()」節参照.

For the mysql command-line client, LOAD DATA LOCAL can be enabled by specifying the option --local-infile[=1], or disabled with --local-infile=0.

By default, all MySQL clients and libraries are compiled with --enable-local-infile, to be compatible with MySQL 3.23.48 and before.

One can disable all LOAD DATA LOCAL commands in the MySQL server by starting mysqld with --local-infile=0.

In the case that LOAD DATA LOCAL INFILE is disabled in the server or the client, you will get the error message (1148):

The used command is not allowed with this MySQL version

4.2.5 特権システムの行うこと

MySQL 特権システムの基本機能は、与えられたホストから接続する ユーザを認証すること、そしてデータベースに対する SELECT, INSERT, UPDATE, DELETE 等の権限を与えることです。

拡張機能は匿名ユーザをもつ能力を含み、LOAD DATA INFILE のような MySQL 固有の機能を使用する許可を与えます。

4.2.6 特権システムはどのように動くか?

MySQL の特権システムは、全てのユーザーが与えられた許可の範囲内で動く事を保証します。 MySQL サーバーに接続するとき、本人の身元は、接続元のホスト接続に使用するユーザー名 によって確認されます。 このシステムは、あなたの身元とあなたが要求することが何か によって、権限を与えます。

MySQL はあなたのホスト名とユーザー名の両方をあわせてチェックします。 これはインターネット上に同じ名前のユーザーがどこかにいるかもしれないということからそうしています。 例えば、office.com から接続してきた joe と、 elsewhere.com から接続してきた joe は同一人物である必要はありません。 MySQL はこの違うホストから接続してきた同名のユーザーを以下のようにして扱います: office.com から接続した joe にある許可をあたえ、 それとは違う許可を elsewhere.com から接続してきた joe に与えます。

MySQL のアクセスコントロールは以下の二つからなります:

サーバーは mysql データベースの user, db, host 3つのテーブルから、 この2つのアクセス制限を決定します。 このテーブルのフィールドは以下のようになっています:

Table name user db host
Scope fields Host Host Host
User Db Db
Password User
Privilege fields Select_priv Select_priv Select_priv
Insert_priv Insert_priv Insert_priv
Update_priv Update_priv Update_priv
Delete_priv Delete_priv Delete_priv
Index_priv Index_priv Index_priv
Alter_priv Alter_priv Alter_priv
Create_priv Create_priv Create_priv
Drop_priv Drop_priv Drop_priv
Grant_priv Grant_priv Grant_priv
References_priv
Reload_priv
Shutdown_priv
Process_priv
File_priv

 アクセスコントロールの第2段階(要求承認)のために、サーバーはこれら 3 つの テーブルによって決められた許可を基本としますが、もしテーブルに対する要求で あるならば、tables_privcolumns_priv テーブルを さらに調べます。これらのテーブルのフィールドは以下のようになっています:

Table name tables_priv columns_priv
Scope fields Host Host
Db Db
User User
Table_name Table_name
Column_name
Privilege fields Table_priv Column_priv
Column_priv
Other fields Timestamp Timestamp
Grantor

 テーブルの各フィールドを分類すると、2種類にわかれます: 適用範囲を指定するフィールド(以下 スコープフィールド)と許可を定義するフィールド(以下 権限フィールド)です。

 スコープフィールドは、権限テーブルの登録ごとに、その適用範囲を決めます。 例えば、 user テーブルの HostUser'thomas.loc.gov''bob' が登録されている場合、 サーバーへの接続は ホスト thomas.loc.gov から来た 'bob' に許可されます。 同様に、db テーブルの Host, User, Db'thomas.loc.gov', 'bob', 'reports' が登録されていると、 ホスト thomas.loc.gov から来た bob に対し reports データベースへの接続が許されます。 tables_privcolumns_priv テーブルは、 テーブルか、テーブルとフィールドを対にしたスコープフィールドを含みます。

 アクセスのチェックは、Host の値はケース非依存で比較されます。 User, Password, Db, Table_name の値はケース依存で比較されます。 Column_name の値は MySQL バージョン 3.22.12 以上ではケース非依存で比較されます。 (バージョン 3.22.11 までは ケース依存です)

権限フィールドは、どのような操作が実行できるか、許可されているかを示します。 サーバーは権限テーブルの情報を、ユーザーの権限を得るために使用します。 このユーザーの権限を割り出す方法は 「4.2.10 Access Control, Stage 2: Request Verification」節 に述べておきます。

スコープフィールドは文字で定義され、デフォルト値は空文字になっています:

Field name Type Notes
Host CHAR(60)
User CHAR(16)
Password CHAR(16)
Db CHAR(64) (CHAR(60) for the tables_priv and columns_priv tables)
Table_name CHAR(60)
Column_name CHAR(60)

user, db, host テーブルでは、 全ての権限フィールドは ENUM('N','Y') で定義されます。 この値は 'N''Y' のどちらかで、デフォルト値は 'N' です。

tables_privcolumns_priv テーブルでは、 権限フィールドは SET フィールドとして定義されます:

Table name Field name Possible set elements
tables_priv Table_priv 'Select', 'Insert', 'Update', 'Delete', 'Create', 'Drop', 'Grant', 'References', 'Index', 'Alter'
tables_priv Column_priv 'Select', 'Insert', 'Update', 'References'
columns_priv Column_priv 'Select', 'Insert', 'Update', 'References'

サーバーは以下のように権限テーブルを使用します:

管理者権限 (RELOAD, SHUTDOWN,など) は user テーブルにだけ定義するように。 これは、管理者操作はデータベースではなくサーバーへの操作であり、 他の許可テーブルにある必要がないからです。 またこうしておくと、管理者操作の許可は、user テーブルの定義だけを 見ればわかるようになります。

FILE 操作の権限は user テーブルにだけ定義するように。 これは管理者操作ではありませんが、アクセスしているデータベースにかかわらず、 サーバー内のファイルを読み書きできるのです。

mysqld サーバーは起動時にこれらのテーブルを読み込みます。 許可テーブルの変更を反映させる方法はこちらを参照のこと → 「4.3.3 いつ権限の変更が反映されるか」節

これらのテーブルの登録を変更した場合、思ったとおりの権限状態になっている事を確認することはいいことです。 問題の解決には, 「4.2.11 何故 Access denied エラーになるのか」節. セキュリティに関するアドバイスは 「4.2.2 MySQL をクラッカーに対して安全にする方法」節.

便利なツールとして mysqlaccess スクリプト( Yves Carlier 作)が MySQL の配布に含まれています。 mysqlaccess--help オプションで起動するとヘルプが表示されます。 mysqlaccessuser,db and host テーブルだけしか 検査しません。テーブルレベルの権限、フィールドレベルの権限は調べません。

4.2.7 MySQL が提供する権限

権限の設定は mysql データベースの user, db, host, tables_priv, columns_priv で行います。 (mysql はデータベースの名前です) MySQL サーバーは、サーバーの起動時か 「4.3.3 いつ権限の変更が反映されるか」節 で説明されている方法により、 これらのテーブルから権限の設定を読み込みます。

MySQL 4.0.2 が提供する権限の名称は, 本マニュアルでは以下の表の名称を用います。 この表の項目名がそれぞれの許可される権限とその説明に対応しています:

Privilege Column Context
ALTER Alter_priv tables
DELETE Delete_priv tables
INDEX Index_priv tables
INSERT Insert_priv tables
SELECT Select_priv tables
UPDATE Update_priv tables
CREATE Create_priv databases, tables, or indexes
DROP Drop_priv databases or tables
GRANT Grant_priv databases or tables
REFERENCES References_priv databases or tables
CREATE TEMPORARY TABLES Create_tmp_table_priv server administration
EXECUTE Execute_priv server administration
FILE File_priv file access on server
LOCK TABLES Lock_tables_priv server administration
PROCESS Process_priv server administration
RELOAD Reload_priv server administration
REPLICATION CLIENT Repl_client_priv server administration
REPLICATION SLAVE Repl_slave_priv server administration
SHOW DATABASES Show_db_priv server administration
SHUTDOWN Shutdown_priv server administration
SUPER Super_priv server administration

SELECT, INSERT, UPDATE, DELETE の権限は、 存在しているデータベースのテーブルに対して許可されます。

もしテーブルから行を取り出すだけなら、SELECT 構文を実行するためには SELECT 権限だけあればかまいません。 ただし、サーバーのどのデータベースにアクセスを許可されていない場合でも、 ある種の SELECT は実行することができます。 例えば、簡単な計算を mysql クライアントで行う場合です:

mysql> SELECT 1+1;
mysql> SELECT PI()*2;

INDEX 権限はインデックスの作成と破棄(削除)を許可します。

ALTER 権限は ALTER TABLE の実行を許可します。

CREATEDROP 権限は、新しいデータベースやテーブルの作成、 あるいは既に存在するデータベース、テーブルの破棄(削除)を許可します。

注意: mysql データベースに登録されているユーザーに DROP 権限を与えると、 そのユーザーは MySQL のアクセス権限が格納されているデータベースを破棄できます!

GRANT 権限は、あなたが他のユーザーに対して自分の権限を持たせる事を許可します。

FILE 権限を与えると、LOAD DATA INFILESELECT ... INTO OUTFILE 構文を 使用して、サーバーのファイルを読み書きする事ができます。 この権限が与えられたユーザーは、MySQL サーバーを使用していかなるファイルも 読むことが出来ますし、MySQL サーバーが書き込めるディレクトリに誰もが読める 新しいファイルを作成することも出来ます。 そのユーザーはカレントのデータベースのディレクトリにあるいかなるファイルも 読むことができます。 しかし、既に存在しているファイルを変更することはできません。

残りの権限はアドミン操作に関する許可で、mysqladmin コマンドを使用して実行します。 次の表に mysqladmin コマンドのどれが、どの権限に対応しているかを示します:

Privilege Commands permitted to privilege holders
RELOAD reload, refresh, flush-privileges, flush-hosts, flush-logs, and flush-tables
SHUTDOWN shutdown
PROCESS processlist
SUPER kill

reload コマンドはサーバーに権限の設定を再読込させるように伝えます。 refresh コマンドは全てのテーブルをフラッシュし、ログファイルを開き直します。 flush-privilegesreload と同義です。 その他の flush-* コマンドは refresh の動作とよく似ていますが、 適用範囲を絞っており、ちょっとした場合に有効です。 例えば、ログファイルだけをフラッシュしたい場合、 refresh を行うよりも flush-logs がいいです。

shutdown コマンドは、サーバーをシャットダウンします。

processlist コマンドはサーバーが実行しているスレッドの情報を表示します。 kill コマンドはサーバーのスレッドをkillします。 自分のスレッドは常に表示、killできますが、他人のスレッドを見るには PROCESS 権限が必要で、他人のスレッドをkillするには SUPER 権限が必要です。 「4.5.5 KILL 構文」節参照. (SUPER 権限は 4.0.2で追加されました)

ある権限を欲しがるユーザーだけにその権限を許可するのはよい考えですが、 権限を与えるときには、特定の事項を熟知していなければなりません:

以下は MySQL の特権システムで行うものではありません:

4.2.8 MySQL サーバーに接続

MySQL クライアントプログラムは、共通の決まった引数を持ちます: 接続したいホスト名、接続ユーザー名、そしてパスワードです。 例えば、mysql コマンドは以下のような引数を持ちます (オプションの引数は `['`]' で囲まれている部分です)

shell> mysql [-h host_name] [-u user_name] [-pyour_pass]

-h, -u, -p オプションは以下と等価です。 --host=host_name, --user=user_name, --password=your_pass -p とパスワードの間にはスペースがないことに注意

注意: コマンドラインにパスワードを与えるのは安全ではありません! システムに入っている如何なるユーザーも ps auxww のようなコマンドを 使用する事でパスワードを見付ける事ができます. 「4.1.2 `my.cnf' オプションファイル」節参照.

mysql コマンドはコマンドラインに引数がなければ接続にデフォルト値を用います。

Unix のログインユーザーが joe の場合、以下のコマンドは等価です:

shell> mysql -h localhost -u joe
shell> mysql -h localhost
shell> mysql -u joe
shell> mysql

他の MySQL クライアントも同じように動作します。

Unix システムでは、ある値をデフォルト値にして接続に使用することができます。 そうすることにより、毎回毎回コマンドラインに引数を与えなくてすむようになります:

4.2.9 Access Control, Stage 1: 接続の承認

MySQL サーバーに接続すると、あなたがパスワード認証して接続していようがいまいが、 サーバーはあなたの身元により接続の許可拒否を行います。 もし身元が一致しない場合接続を拒否し、接続許可した場合、 サーバーは Stage 2 へと進み、要求を待ちます。

身元は二つのものに基づいて確認されます:

身元の確認は user テーブルのスコープフィールド (Host, User, Password) を使用して行います。 サーバーは user テーブルの登録に一致しているホスト名と ユーザー名に限り接続を許可し、その後、パスワードを要求します。

user テーブルのスコープフィールドの登録は以下のようになります:

非ブランクの Password 値はパスワードを暗号化したものです。 MySQL はだれもが見れるようにパスワードを平文では保存しません。 接続を試みようとしているユーザーのパスワードも、(PASSWORD() 関数で) 暗号化されます。 それから、暗号化パスワードは、クライアント/サーバがパスワードが正しいかチェッ クする時に使用されます(This is done without the encrypted password ever traveling over the connection)。注意: MySQL では、暗号化パスワー ドが本当のパスワードです。そのため、それへのアクセスを誰にも与えるべきでは ありません! 特に、一般ユーザにはmysql データベース内のテーブルの読 み取り権を与えないでください! From version 4.1, MySQL employs a different password and login mechanism that is secure even if TCP/IP packets are sniffed and/or the mysql database is captured.

以下の表は、接続要求に対して与える、 user テーブルの HostUser の設定例です:

Host value User value Connections matched by entry
'thomas.loc.gov' 'fred' fred, thomas.loc.gov から接続
'thomas.loc.gov' '' thomas.loc.gov から接続してくる全てのユーザー
'%' 'fred' fred, 全てのホストから接続
'%' '' 全てのホストから接続してくる全ユーザー
'%.loc.gov' 'fred' fred, loc.gov ドメイン内の全てのホストからの接続
'x.y.%' 'fred' fred, x.y.net, x.y.com,x.y.edu, などからの接続. (あまり有効な使い方ではないです)
'144.155.166.177' 'fred' fred, IP address が 144.155.166.177 のホストからの接続
'144.155.166.%' 'fred' fred, 144.155.166 class C subnet 内の全てのホストからの接続
'144.155.166.0/255.255.255.0' 'fred' 上の例と同じ

Host に IP のワイルドカード(例えば '144.155.166.%' は サブネットの全てのホストにマッチ) を使用することができます。 が、この場合、 144.155.166.somewhere.com というホスト名で だれかが接続しようとしてくるかもしれません。 このような攻撃に対し、MySQL は数字やドットで始まるホスト名を拒否しています。 もし 1.2.foo.com のような名前のホストを持っている場合、 許可テーブルの Host には絶対にマッチしません。 IPアドレスのみ、IP のワイルドカードにマッチする事になります。

サーバーに来る接続は、user テーブル内の登録に1つ以上 マッチするかもしれません。 例えば, thomas.loc.govfred からの接続は、上に示された 登録のうちのいくつかにマッチするでしょう。 サーバーは、複数の登録にマッチした場合、どのようにしてその中から 使用する登録を選ぶのでしょう? サーバーは起動後に user テーブルをソートし、並び換えられた順に 登録を検索することにより、この問題を解決します。 最初にマッチした登録が使用されます。

user テーブルが以下のようにソートされていた場合:

+-----------+----------+-
| Host      | User     | ...
+-----------+----------+-
| %         | root     | ...
| %         | jeffrey  | ...
| localhost | root     | ...
| localhost |          | ...
+-----------+----------+-

サーバーがこのテーブルを読むと、Host に値が最も確実に特定できる ホストを指定しているエントリを、最初に参照します。 (Host 項の '%' は ``すべてのホスト'' を意味し、 ホスト名をはっきりと特定しているものではありません) Host の値が同じエントリがあった場合、もっとも明確に User の値が ユーザーを指定しているエントリを最初に参照します。 (User の値が空の場合、``だれでも'' を意味します) この結果、user テーブルは以下のようにソートされます:

+-----------+----------+-
| Host      | User     | ...
+-----------+----------+-
| localhost | root     | ...
| localhost |          | ...
| %         | jeffrey  | ...
| %         | root     | ...
+-----------+----------+-

接続が試みられた場合、サーバーは並び換えられた登録を探し、最初に見つけたものを 使用します。 'localhost'jeffrey からの接続は、まず最初に Hostlocalhost を設定しているエントリにマッチします。 ユーザー名が空のエントリは、ホスト名とユーザー名の両方を指定した接続にもマッチします。 ( '%'/'jeffrey' エントリもマッチします。が、これは最初にはマッチしません。)

もう一例。user が以下の設定と仮定します:

+----------------+----------+-
| Host           | User     | ...
+----------------+----------+-
| %              | jeffrey  | ...
| thomas.loc.gov |          | ...
+----------------+----------+-

これは次のようにソートされます:

+----------------+----------+-
| Host           | User     | ...
+----------------+----------+-
| thomas.loc.gov |          | ...
| %              | jeffrey  | ...
+----------------+----------+-

thomas.loc.govjeffrey からの接続は、最初のエントリにマッチし、 whitehouse.govjeffrey からの接続は、二つ目のエントリにマッチします。

よくある考え違いは、ユーザー名を与えて接続した場合、 サーバーが接続にマッチするものを探す際に、 そのユーザー名が指定されているルールが 最初に使用されるだろうと考えることです。これは正しくありません。 前の例でこれを示しましたが、thomas.loc.govjeffrey からの接続が 最初にマッチするのは、 User フィールドの値が 'jeffrey' に なっているエントリではなく、ユーザー名なし(=だれでも) のエントリの方が 先にマッチします!

もしサーバーへの接続がうまく行かない場合、 user テーブルを表示し、 マニュアルでソートしてみて、どのエントリに最初にマッチするか探してください。

If connection was successful, but your privileges are not what you expected you may use CURRENT_USER() function (new in version 4.0.6) to see what user/host combination your connection actually matched. 「6.3.6.2 その他の関数」節参照.

4.2.10 Access Control, Stage 2: Request Verification

一度接続か確立されると、サーバーはステージ2に移ります。 このステージでは、サーバーはこの接続から来るそれぞれの要求が許可されて いるかどうかをチェックします。 チェックは実行しようとしている操作のタイプにより行います。 その操作が許可テーブルのどの権限フィールドに当てはまるかを見ます。 これら権限は user, db,host, tables_privcolumns_priv テーブルより導出されます。 権限テーブルは GRANT, REVOKE コマンドで操作します。 「4.3.1 GRANTREVOKE 構文」節参照. (You may find it helpful to refer to 「4.2.6 特権システムはどのように動くか?」節, which lists the fields present in each of the grant tables.)

user テーブルは全てに対して基本となる権限をユーザーに割り当てます。 たとえカレントのデータベースに許可を与えていなくても、user テーブルの設定方が有効になります。 例えば、user テーブルで DELETE を許可した場合、 サーバーにあるどんなデータベースの行も削除できるのです! いうならば、user テーブルの権限はスーパーユーザーの権限と言ってもいいでしょう。 この権限はスーパーユーザー(サーバーやデーターベース管理者)のみに与えておく事が賢明です。 他のユーザーは、user テーブルの権限の設定を 'N' のままにしておくべきですし、 また、db テーブルと host テーブルを利用して、 データベースを指定した上でユーザーに権限を許可すべきです。

db テーブルと host テーブルは特定のデータベースに対する権限許可を行います。 スコープフィールドの値は次のように記述されます:

サーバー起動時に、db テーブルと host テーブルはサーバーに読み込まれます。 (user テーブルもこの時に同時に読まれます) db テーブルは Host, Db, User のフィールドでソートされ、 host テーブルは Host, Db フィールドでソートされます。 user テーブルは、一番特定できるエントリを最初に、一番特定できないものを最後にソートします。 サーバーはソートされたものの中から、最初にマッチしたものを使用します。

tables_privcolumns_priv テーブルは、 特定のテーブルとフィールドに対する権限を許可します。 スコープフィールドの値は、いかにそって記述されます:

tables_privcolumns_priv テーブルは Host, Db, User フィールドで並び換えられます。 これは db テーブルのソートに似ていますが、 Host フィールドだけが ワイルドカードを含むので、ソートはより単純なものになります。

この要求の承認は次のようにして行います。 もしアクセス承認を決定する部分のソースコードを理解できるなら、 ちょっと変わったアルゴリズムで承認の決定を行っている事に気づくでしょう。

管理者の要求(SHUTDOWN, RELOAD, etc.)については、サーバーは user テーブルだけを参照します。(user テーブルだけが管理者権限のフィールドを持つ)。 エントリに許可登録されている操作は受け入れられ、それ以外は拒否されます。 例えば、mysqladmin shutdown を実行しようとしても、 user テーブルの SHUTDOWN 権限が許されていなければ実行できません。 この時、dbhost テーブルはチェックされません。 (これらのテーブルには Shutdown_priv フィールドが無いからです)

データベースへの要求 (INSERT, UPDATE, etc.) において、 サーバーはまず最初に、ユーザーのグローバルな権限(スーパーユーザー)を user の中から探しだします。 もし許可が与えられていれば、アクセスは成功します。

user テーブルのグローバルな権限の設定が不十分であるなら、 サーバーはユーザーのデータベースに対する権限を db テーブルと host テーブルから決定します:

  1. サーバーは db テーブルの Host,Db,Userフィールドを参照します。 HostUser フィールドはユーザーの接続時のホスト名と MySQL ユーザー名にマッチします。 Db フィールドはユーザーがアクセスしたいデータベース名にマッチします。 HostUser にマッチするものが無かった場合、アクセスは拒否されます。
  2. db テーブル内の Host フィールドが空でないエントリにマッチした場合、 ユーザーの指定されているデータベースに対する権限が定義されます。
  3. Host フィールドが空値の db テーブルのエントリにマッチした場合、 どのホストがそのデータベースへアクセスできるかを host テーブルから探し出します。 この場合、host テーブル の Host, Db フィールドとマッチするものを探し出します。 host テーブルにエントリがなかった場合、アクセスは拒否されます。 もしマッチすると、ユーザーの特定データベースに対する権限は、 host テーブルと db テーブル両方にまたがった権限から割り出されます。 いうならば両方とも 'Y' である権限。 (この方法を使用すると、まず db テーブルのエントリに大まかな権限を設定しておき、 それから host テーブルのエントリを使用して、ホスト情報もとに権限を限定していくという事ができます)

特定データベースに対する権限が db テーブルと host テーブルのエントリから決定された後、 サーバーはその割り出された権限に対し、user テーブルて設定されている権限を加えます。 この結果から得られた権限にマッチした要求は受け入れられます。 そうでなければ、サーバーはユーザーのテーブル、フィールドに対する許可を、 tables_privcolumns_priv 内に探します。 アクセスはこの結果により、許可、拒否されます。

先のユーザーの権限が計算される方法の記述は、boolean 表記で示すならば、 以下のようになるでしょう:

global privileges
OR (database privileges AND host privileges)
OR table privileges
OR column privileges

これは少し分かりにくいかもしれません。もしグローバルの user エントリ 権限許可が、リクエストされたオペレーションには不十分だと最初に分かった際、 サーバーがこれらの権限を database-, table-, column-固有の権限の 後に、なぜ、追加してしまうのか。 その理由は、リクエストが1個以上の権限を要求するだろうということです。 例えば、もしあなたが INSERT ... SELECT 構文を実行するなら、 あなたには INSERTSELECT 権限が必要です。 あなたの権限が、 user テーブルエントリで一つの権限が許可され、 db テーブルで、そのほかの権限が許可されていたとします。 この場合、あなたは、そのリクエストを実行するために、必要な権限を持っています。 しかし、サーバーはどちらのテーブル、それ単体からでは、権限を得ることが出来ません。 権限は、両方のエントリーを合わせなくてはならないのです。

host テーブルは ``安全な'' ホストのリストを維持するために使用できます。

TcX では、host テーブルにはローカルネット上の全てのホストが登録されています。 これらのホストは全ての権限が許可されています。

逆に host table で安全ではないホストを指定することもできます。 public.your.domain というマシンが安全ではない、公開されている場所にあるとします。 その場合以下のようにして、その公開マシン以外のネットワーク上のホストに対して、 アクセスを許可することができます:

+--------------------+----+-
| Host               | Db | ...
+--------------------+----+-
| public.your.domain | %  | ... (all privileges set to 'N')
| %.your.domain      | %  | ... (all privileges set to 'Y')
+--------------------+----+-

権限のテーブル設定は、あなたの思い通りに許可が得られるのか、 常に(mysqlaccess等を使用して)チェックすべきです。

4.2.11 何故 Access denied エラーになるのか

もし、MySQL サーバーに接続しようとして Access denied エラーに 遭遇してしまったら、以下に記すことが問題の解決のための指標となるでしょう:

4.3 MySQL User Account Management

4.3.1 GRANTREVOKE 構文

GRANT priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON {tbl_name | * | *.* | db_name.*}
    TO user_name [IDENTIFIED BY [PASSWORD] 'password']
        [, user_name [IDENTIFIED BY 'password'] ...]
    [REQUIRE
        NONE |
    	[{SSL| X509}]
	[CIPHER cipher [AND]]
	[ISSUER issuer [AND]]
	[SUBJECT subject]]
    [WITH [GRANT OPTION | MAX_QUERIES_PER_HOUR # |
                          MAX_UPDATES_PER_HOUR # |
                          MAX_CONNECTIONS_PER_HOUR #]]

REVOKE priv_type [(column_list)] [, priv_type [(column_list)] ...]
    ON {tbl_name | * | *.* | db_name.*}
    FROM user_name [, user_name ...]

バージョン 4.0 以上:
    REQUIRE
    	[{SSL| X509}]
	[CIPHER cipher [AND]]
	[ISSUER issuer [AND]]
	[SUBJECT subject]

バージョン 4.0.2以上:
    MAX_QUERIES_PER_HOUR=# | MAX_UPDATES_PER_HOUR=# | MAX_CONNECTIONS_PER_HOUR=#

GRANT は MySQL 3.22.11 以上で実装されています; 前の MySQL バージョンでは、GRANT ステートメントは何も行ないません。

GRANTREVOKE コマンドセットの主な目的は、システム管理者 がユーザを生成すること、MySQL ユーザに次の4つの権限レベルの権 利を与えたり取り消すことをできるようにすることです:

Global レベル
Global 権限は与えられたサーバ上の全てのデータベースに適用します。これらの権限は mysql.user テーブル内に格納されます。
Database レベル
Database 権限は与えられたデータベース内の全てのテーブルに適用します。こ れらの権限は mysql.db テーブルと mysql.host テーブル内に格納されます。
Table レベル
Table 権限は与えられたテーブル内の全てのフィールドに適用します。これらの権限は mysql.tables_priv テーブル内に格納されます。
Column レベル
Column 権限は与えられたテーブル内の一つのフィールドに適用します。これらの権限は mysql.columns_priv テーブル内に格納されます。

If you give a grant for a users that doesn't exists, that user is created. For examples of how GRANT works, see 「4.3.5 新しいユーザを MySQL へ追加」節.

GRANTREVOKE ステートメントにおいて priv_type には 以下が指定できます:

ALL [PRIVILEGES] Sets all simple privileges except WITH GRANT OPTION
ALTER Allows usage of ALTER TABLE
CREATE Allows usage of CREATE TABLE
CREATE TEMPORARY TABLES Allows usage of CREATE TEMPORARY TABLE
DELETE Allows usage of DELETE
DROP Allows usage of DROP TABLE.
EXECUTE Allows the user to run stored procedures (for MySQL 5.0)
FILE Allows usage of SELECT ... INTO OUTFILE and LOAD DATA INFILE.
INDEX Allows usage of CREATE INDEX and DROP INDEX
INSERT Allows usage of INSERT
LOCK TABLES Allows usage of LOCK TABLES on tables for which one has the SELECT privilege.
PROCESS Allows usage of SHOW FULL PROCESSLIST
REFERENCES For the future
RELOAD Allows usage of FLUSH
REPLICATION CLIENT Gives the right to the user to ask where the slaves/masters are.
REPLICATION SLAVE Needed for the replication slaves (to read binlogs from master).
SELECT Allows usage of SELECT
SHOW DATABASES SHOW DATABASES shows all databases.
SHUTDOWN Allows usage of mysqladmin shutdown
SUPER Allows one connect (once) even if max_connections is reached and execute commands CHANGE MASTER, KILL thread, mysqladmin debug, PURGE MASTER LOGS and SET GLOBAL
UPDATE Allows usage of UPDATE
USAGE Synonym for ``no privileges.''
GRANT OPTION Synonym for WITH GRANT OPTION

USAGE は ``no privileges'' と同義です. これはなんの権限も持たないユーザーを作る場合に使用します.

The privileges CREATE TEMPORARY TABLES, EXECUTE, LOCK TABLES, REPLICATION ..., SHOW DATABASES and SUPER are new for in version 4.0.2. To use these new privileges after upgrading to 4.0.2, you have to run the mysql_fix_privilege_tables script.

In older MySQL versions(4.0.2未満), the PROCESS privilege gives the same rights as the new SUPER privilege.

ユーザーから GRANT 権限を取り除くには、GRANT OPTION オプションの値に priv_type を指定します:

mysql> REVOKE GRANT OPTION ON ... FROM ...;

テーブルに対する許可のために指定できる priv_type は次のフィールドだけです: SELECT,INSERT, UPDATE, DELETE, CREATE, DROP, GRANT OPTION, INDEX, ALTER.

フィールドに対する許可のために指定できる priv_type は次のフィールドだけです (これは column_list 節を使用する場合に適用されます): SELECT, INSERT, UPDATE.

ON *.* を使用してグローバル権限を設定できます。 ON db_name.* を使用してデータベース権限を設定できます。ON * を 指定すると、現在のデータベースの権限を設定できます。 (警告: 現在のデータベースを持たない状態で ON * を指定した場合、 global 権限に影響します!)

Please note: the `_' and `%' wildcards are allowed when specifying database names in GRANT commands. This means that if you wish to use for instance a `_' character as part of a database name, you should specify it as `\_' in the GRANT command, to prevent the user from being able to access additional databases matching the wildcard pattern, e.g., GRANT ... ON `foo\_bar`.* TO ....

ユーザへの権利の供与を他のホストから適応するために、MySQL は user_name の値を user@host の形で書けるようにしています。 特殊文字(`%' のような)で user_name の値を指定したい場合、 ユーザやホスト名をクォートできます; (例えば 'test-user'@'test-hostname')。

ホスト名にワイルドカードを使用できます。例えば、user@'%.loc.gov'loc.gov ドメインの全てのホストの user を与え、 user@'144.155.166.%'144.155.166 クラスCサブネットの あらゆるホストの user となります。

単に user と書くと user@"%" と同じです.

MySQL doesn't support wildcards in user names. Anonymous users are defined by inserting entries with User='' into the mysql.user table or creating an user with an empty name with the GRANT command.

注意: もし匿名ユーザーからの MySQL サーバーへの接続を 許す場合(デフォルトです)、全てのローカルユーザー username@localhost を加えるべきです。 なぜなら、匿名ユーザーは同じマシンから MySQL サーバーに入ろうとした場合に 使用されるからです! (匿名ユーザーは mysql.user ユーザーテーブルに、 User='' として登録されています。)

これを確認するには、以下のようにします:

mysql> SELECT Host,User FROM mysql.user WHERE User='';

さしあたり, GRANT はホスト名、テーブル名、データベース名、フィールド名に 最大60文字まで使用できます。ユーザー名は最大16文字までです。

テーブル/フィールドの権限は global(ユーザとデータベース)権限と GRANT 権限と OR されます。例えば、ユーザが mysql.user テーブル内の global SELECT 権限を持っている場合、 これはデータベースやテーブル/フィールドレベル内のエントリでは拒否できません。

フィールドに対する権限は次のように計算できます:

global privileges
OR (database privileges AND host privileges)
OR table privileges
OR column privileges

多くの場合、異なる権限レベルの一つでユーザに権利を与えるので、人生は通常 上述のようには複雑ではありません。 アクセス権限のチェックの詳細は→ 「4.2 General Security Issues and the MySQL Access Privilege System」節.

ユーザとホスト名の組が存在しない場合、エントリは mysql.user テー ブルに追加され、DELETE コマンドで削除されるまでそこに残ります。 いうならば GRANTuser テーブルの登録を作りますが、 REVOKE はそれらを削除できません; そうするには DELETE を使用しなくてはなりません。

MySQL バージョン 3.22.12 以上では、 新しいユーザーが作成された場合、あるいは、あなたがグローバルな権限を許可されている場合、 ユーザーのパスワードは IDENTIFIED BY 節を使用して設定できます。 すでにユーザーにパスワードがある場合、新しく設定されたパスワードに置き換えられます。

If you don't want to send the password in clear text you can use the PASSWORD option followed by a scrambled password from SQL function PASSWORD() or the C API function make_scrambled_password(char *to, const char *password).

警告: もし新しいユーザーを作っても IDENTIFIED BY 節を指定しなければ、 そのユーザーはノーパスワードです。 これは危険です。

パスワードは SET PASSWORD コマンドでも設定できます。 「5.5.6 SET 構文」節参照.

データベースに権限を付与 する場合、mysql.db テーブル内の エントリは必要な場合に生成されます。全てのデータベース権限が REVOKE で削除された時、このエントリは削除されます。

ユーザがテーブルに何も権限を持っていない場合、テーブルの一覧要求時(例え ば、SHOW TABLES ステートメントで)には、テーブルは現れません。

WITH GRANT OPTION 節は、他のユーザーに、自分が持っている権限を与えることができます。 GRANT 権限を他に与える場合は注意してください。 あなたと許可を与えるユーザーが違う権限を持っている場合、 与えられる権限の許可は、二つを合わせた物になります!

MAX_QUERIES_PER_HOUR #, MAX_UPDATES_PER_HOUR # and MAX_CONNECTIONS_PER_HOUR # are new in MySQL version 4.0.2. These options limit the number of queries/updates and logins the user can do during one hour. If # is 0 (default), then this means that there are no limitations for that user. 「4.3.6 Limiting user resources」節参照. Note: to specify any of these options for an existing user without adding other additional privileges, use GRANT USAGE ... WITH MAX_....

自分自身が持っていない権限を他のユーザーに与えることはできません; GRANT 権限はあなたが所有する権限の許可だけを与えることができます。

Be aware that when you grant a user the 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. あなたがデータベースに対する INSERT 許可をあるユーザーに与えたと仮定します。 もし、データベースに対する SELECT 権限を与えたり、 WITH GRANT OPTION を行うと、ユーザーは SELECT 権限だけでなく INSERT も得ることになります。 もし UPDATE 権限をユーザーに与えると、そのユーザーは INSERT, SELECT, UPDATE が可能です。

ALTER 権限を一般ユーザに与えるべきではありません。この場合 ユーザはテーブルをリネームでき、この方法で権限を回ることを試みることがで きます!

注意:もし table/column 権限を一人のユーザーにだけ与えた場合、 MySQL は全てのユーザーに対してテーブルとフィールドの承認権限を検討します。 これは MySQL を少し遅くします。

mysqld 開始時、全ての権限はメモリに読み込まれます。データベース、 テーブル、フィールド権限は一度効果を得ます。ユーザレベル権限はユーザ再接続時に 効果を得ます。 これらの許可テーブルを GRANTREVOKE を使って変更しても サーバーにはすぐに反映されません。 もしこれらの許可テーブルを手動で変更した場合(INSERT, UPDATE, 等で変更した場合)、 FLUSH PRIVILEGES 構文を実行するか、mysqladmin flush-privileges を実行して サーバーに許可テーブルの再読み込みを行わせなくてはなりません。 「4.3.3 いつ権限の変更が反映されるか」節参照.

The biggest differences between the ANSI SQL and MySQL versions of GRANT are:

For a description of using REQUIRE, see 「4.3.9 Using Secure Connections」節.

4.3.2 MySQL ユーザ名とパスワード

MySQL によって使用されるユーザー名とパスワードの使用のされ方と、 Unix, Windows で使用される方法とは、いくつか異なる点があります。

MySQL ユーザーと彼らの権限は通常 GRANT コマンドで作成されます。 「4.3.1 GRANTREVOKE 構文」節参照.

MySQL サーバにコマンドラインクライアントでログインする時、 --password=your-password でパスワードを指定すべきです。 「4.2.8 MySQL サーバーに接続」節参照.

mysql --user=monty --password=guess database_name

クライアントにパスワードをプロンプトして欲しければ、引数なしで --password を使用すべきです。

mysql --user=monty --password database_name

または次の短い形式:

mysql -u monty -p database_name

注意: 最後の例でのパスワードは 'database_name' では ありません

パスワードを供給するために -p オプションを使用したい場合、次のようなことを 行なうべきです:

mysql -u monty -pguess database_name

いくつかのシステムでは、MySQL がパスワードをプロンプトするために 使用するライブラリ呼び出しは、自動的にパスワードを 8文字にカットします。内 部的に MySQL はパスワード長に何の制限もありません。

4.3.3 いつ権限の変更が反映されるか

mysqld の起動時、全ての許可テーブルはメモリーに読み込まれ、 この時点で有効になります。

GRANT, REVOKE, SET PASSWORD を使用して許可テーブルを 変更した場合、直にサーバに通知されます。

もし手動で許可テーブルを変更した場合(INSERT, UPDATE などで)、 FLUSH PRIVILEGES 構文か mysqladmin flush-privileges コマンド か mysqladmin reload コマンドを実行して、 サーバーに許可テーブルの読み込みを指示しなければなりません。 そうしなければ、サーバーを再起動させるまで、変更は反映されません。 権限テーブルを手で変更して、権限のリロードを忘れた場合、変更が何も行なわれ ないように見えるのがなぜかと不思議に思うでしょう!

サーバーが許可テーブルの変更を通知した場合、既に接続している クライアントは、以下のような影響を受けます:

4.3.4 MySQL 権限許可の初期設定

MySQL インストール後、scripts/mysql_install_db を 実行して権限のアクセス許可を初期化します。 「2.3.1 素早いインストールの概要」節参照. mysql_install_db スクリプトは mysqld サーバーを起動し、 以下のように権限を初期化してテーブルに登録します:

注意: デフォルトの権限は Windows では違います。 「2.6.2.3 Windows 上で MySQL を実行」節参照.

初期インストールの状態ではかなりアクセスが解放されているので、 インストール後最初にすることは、MySQL root ユーザーにパスワードを設定することです。 以下のようにします(パスワードは PASSWORD() 関数を使用することをお忘れなく):

shell> mysql -u root mysql
mysql> SET PASSWORD FOR root@localhost=PASSWORD('new_password');

If you know what you are doing, you can also directly manipulate the privilege tables:

shell> mysql -u root mysql
mysql> UPDATE user SET Password=PASSWORD('new_password')
    ->     WHERE user='root';
mysql> FLUSH PRIVILEGES;

password をセットする他の方法として、mysqladmin コマンドも使用できます:

shell> mysqladmin -u root password new_password

mysql データベースに書き込み/更新アクセスのあるユーザだけが他のユーザのパ スワードを変更できます。すべての通常のユーザ(匿名ユーザ以外)は、上記のコマ ンドか、または SET PASSWORD=PASSWORD('new password') で、自分のパス ワードだけを変更できます。

もし最初の方法で user テーブルのパスワードを直接更新したなら、 サーバーに許可テーブルの再読み込みを行わせなければなりません(FLUSH PRIVILEGES を使用して)。

一度 root のパスワードを設定したなら、root でサーバーに接続する場合は 常にパスワードを与えなければなりません。

追加設定やテストをしているためパスワードを入れたくない場合、 root パスワードをブランクのままにしておこうと考えるかも知れませんが、 実稼働させる前には必ず設定してください。

どのようにデフォルトの権限を設定しているか、scripts/mysql_install_db 見てみてください。 これは他のユーザーを設定するときに使えるでしょう。

もし権限の初期状態を違うものにして初期化したいなら、 mysql_install_db を実行する前に編集してもよいでしょう。

もしテーブルを完全に作り直したいなら、mysql データベースのディレクトリに存在する 全ての `*.frm', `*.MYI', `*.MYD' ファイルを削除します。 (このディレクトリーはデータベースディレクトリーの下に mysql という名前で存在します。 mysqld --help とすればデータベースのディレクトリーが表示されます。) そして好みの許可状態に mysql_install_db を編集してから実行します。

注意: MySQL 3.22.10 以前のバージョンでは, `*.frm' ファイルを消してはいけません. もしうっかり消してしまった場合、 mysql_install_db を実行する前に、 MySQL 配布からコピーしなおさ なくてはなりません。

4.3.5 新しいユーザを MySQL へ追加

ユーザーは2つの違った方法で追加できます: GRANT 構文を使用して行う方法と、 MySQL の許可テーブルを直接操作する方法とです。 The preferred method is to use GRANT statements, because they are more concise and less error-prone. 「4.3.1 GRANTREVOKE 構文」節参照.

phpmyadmin のような、ユーザの作成と管理に使用できる contribute され たプログラムも多くあります。

以下の例では、いかにして mysql クライアントを使用して新規にユーザーを登録するかを示します。 以下の例では、権限は前節で述べたデフォルト値になっているとします。 よって変更を行うためには、あなたは mysqld が走っているマシン上にログインしていなくてはなりませんし、 かつ、MySQL root ユーザーで接続していなければなりません。 さらに MySQL root ユーザーには mysql データベースに対して INSERT 権限を持ち、 RELOAD, PROCESS のアドミニストレーター権限を持っていなければなりません。 もし root ユーザーのパスワードを変えていたならば、 mysql コマンドにパスワード指定を与えなくてはなりません。

You can add new users by issuing GRANT statements:

shell> mysql --user=root mysql
mysql> GRANT ALL PRIVILEGES ON *.* TO monty@localhost
    ->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
mysql> GRANT ALL PRIVILEGES ON *.* TO monty@"%"
    ->     IDENTIFIED BY 'some_pass' WITH GRANT OPTION;
mysql> GRANT RELOAD,PROCESS ON *.* TO admin@localhost;
mysql> GRANT USAGE ON *.* TO dummy@localhost;

これら GRANT 構文では3つの新しいユーザを作ります:

monty
どこからでもサーバーに接続できる完全なスーパーユーザ。 しかし、MySQL を使用する時にはパスワード 'some_pass' を 使用する必要があります。 monty@localhostmonty@"%" の両方に GRANT 構文を 発行しなくてはならない事に注意してください。 もし localhost からの許可をした登録がないと、localhost から接続した時、 mysql_install_db が自動で作成した localhost への匿名ユーザーが優先されます。 なぜなら、 Host フィールドの値が(ブランクやワールドカード以外に)明記されており、 許可登録が MySQL 内部でソートされる時に順番が上にソートされるからです。
admin
localhost からパスワードなしで接続できますが、reload, process の使用だけが許されます。 これは、mysqladmin reload, mysqladmin refresh, mysqladmin flush-* そして mysqladmin processlist コマンドの実行がこのユーザーに許可されます。 データベースへのアクセスは許可されていません。 しかしこれは後でテーブル GRANT 構文を発行すれば、 個々のデータベースへのアクセス権限が設定できます。
dummy
パスワードなしで localhost からのみ、接続できるユーザー。 グローバルな権限は全て 'N' に設定されます。 USAGE 権限は権限無しユーザーの設定を許可する事になります。 これは、特定データーベースに対しての許可を後から与える事を想定しています。

同じアクセス許可を INSERT 構文を使用して直接設定できます。 サーバーに許可テーブルの再読み込みを指示します:

shell> mysql --user=root mysql
mysql> INSERT INTO user VALUES('localhost','monty',PASSWORD('some_pass'),
    ->          'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO user VALUES('%','monty',PASSWORD('some_pass'),
    ->          'Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO user SET Host='localhost',User='admin',
    ->           Reload_priv='Y', Process_priv='Y';
mysql> INSERT INTO user (Host,User,Password)
    ->                  VALUES('localhost','dummy','');
mysql> FLUSH PRIVILEGES;

MySQL のバージョンにより、上の 'Y' の数が違う事に注意してください。 (3.22.11 以前のバージョンでは項目数が少なくなります). admin ユーザーの登録で使用している INSERT の拡張は バージョン 3.22.11 以上で可能です。 (訳注: version 4.0 以上で openssl を使用する場合、この数が変わります)

スーパーユーザーを定義するためには、user テーブルの許可フィールドを 'Y' にするだけでかまいません。 dbhost テーブルに登録は必要無いのです。

user テーブルの許可フィールドは最後の INSERT 文で(dummy ユーザーのために) は設定されていません。これらのフィールドはデフォルト値の 'N' になります。 これは GRANT USAGE が行うのと同じものです。

以下は、localhost, server.domain, whitehouse.gov から接続が可能な custom ユーザーの追加例です。 custom ユーザーは bankaccount データーベースには localhost からの接続のみを許可され、 expenses データベースには whitehouse.gov からのみ接続が許可され、 customer データベースには全てのホストから接続できます。 custom ユーザーは、 stupid というパスワードを全てのホストで使用したいとします。

このユーザーの許可を GRANT 構文で定義するには、以下のようにします:

shell> mysql --user=root mysql
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON bankaccount.*
    ->     TO custom@localhost
    ->     IDENTIFIED BY 'stupid';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON expenses.*
    ->     TO custom@whitehouse.gov
    ->     IDENTIFIED BY 'stupid';
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
    ->     ON customer.*
    ->     TO custom@'%'
    ->     IDENTIFIED BY 'stupid';

The reason that we do to grant statements for the user 'custom' is that we want the give the user access to MySQL both from the local machine with Unix sockets and from the remote machine 'whitehouse.gov' over TCP/IP.

許可テーブルを直接変更してこのユーザーの権限を設定するにはいかのようにします (FLUSH PRIVILEGES を最後に実行している事に注意):

shell> mysql --user=root mysql
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('localhost','custom',PASSWORD('stupid'));
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('server.domain','custom',PASSWORD('stupid'));
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('whitehouse.gov','custom',PASSWORD('stupid'));
mysql> INSERT INTO db
    -> (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
    ->  Create_priv,Drop_priv)
    -> VALUES
    -> ('localhost','bankaccount','custom','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
    -> (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
    ->  Create_priv,Drop_priv)
    -> VALUES
    -> ('whitehouse.gov','expenses','custom','Y','Y','Y','Y','Y','Y');
mysql> INSERT INTO db
    -> (Host,Db,User,Select_priv,Insert_priv,Update_priv,Delete_priv,
    ->  Create_priv,Drop_priv)
    -> VALUES('%','customer','custom','Y','Y','Y','Y','Y','Y');
mysql> FLUSH PRIVILEGES;

最初の3つの INSERT 文は、 custom ユーザーがそれぞれのホストから パスワードつきで接続できるように user テーブルに追加しています。 しかしここでは権限は1つも与えられていません(権限のデフォルト値は 'N' です)。 次の三つの INSERT 文は、bankaccount, expenses, customer データベースに対する該当ホストからのアクセス許可を custom ユーザーに与えるように、 db テーブルに追加しています。 許可テーブルが直接変更された場合、これらをサーバーに反映させるために、許可テーブルの 再読み込みを(FLUSH PRIVILEGESで) サーバーにつげなければなりません。

もし、あるドメインの全てのマシンに接続を許可したい場合、 以下のように GRANT 構文を発行します:

mysql> GRANT ...
    ->     ON *.*
    ->     TO myusername@"%.mydomainname.com"
    ->     IDENTIFIED BY 'mypassword';

許可テーブルを直接変更するには以下のようにします:

mysql> INSERT INTO user VALUES ('%.mydomainname.com', 'myusername',
    ->             PASSWORD('mypassword'),...);
mysql> FLUSH PRIVILEGES;

4.3.6 Limiting user resources

Starting from MySQL 4.0.2 one can limit certain resources per user.

So far, the only available method of limiting usage of MySQL server resources has been setting the max_user_connections startup variable to a non-zero value. But this method is strictly global and does not allow for management of individual users, which could be of particular interest to Internet Service Providers.

Therefore, management of three resources is introduced on the individual user level:

A user in the aforementioned context is a single entry in the user table, which is uniquely identified by its user and host columns.

All users are by default not limited in using the above resources, unless the limits are granted to them. These limits can be granted only via global GRANT (*.*), using this syntax:

GRANT ... WITH MAX_QUERIES_PER_HOUR N1
               MAX_UPDATES_PER_HOUR N2
               MAX_CONNECTIONS_PER_HOUR N3;

One can specify any combination of the above resources. N1, N2 and N3 are integers and stands for count / hour.

If user reaches any of the above limits withing one hour, his connection will be terminated or refused and the appropriate error message shall be issued.

Current usage values for a particular user can be flushed (set to zero) by issuing a GRANT statement with any of the above clauses, including a GRANT statement with the current values.

Also, current values for all users will be flushed if privileges are reloaded (in the server or using mysqladmin reload) or if the FLUSH USER_RESOURCES command is issued.

The feature is enabled as soon as a single user is granted with any of the limiting GRANT clauses.

As a prerequisite for enabling this feature, the user table in the mysql database must contain the additional columns, as defined in the table creation scripts mysql_install_db and mysql_install_db.sh in `scripts' subdirectory.

4.3.7 パスワードの設定法

多くの場合、ユーザ/パスワードを設定するために、GRANT を使用すべき です。以下は上級ユーザのためにだけあてはまります。 「4.3.1 GRANTREVOKE 構文」節参照.

前節の例で述べた、とても重要な基本原則: INSERTUPDATE で空ではないパスワードを設定する場合、 暗号化するために PASSWORD() 関数を使用しなくてはなりません。 これは user テーブルはプレーンテキストでなく、暗号化されたパスワードであることを要求しているからです。 この原則を忘れてしまった場合、以下のようにしてパスワードをセットしてしまうかもしれません:

shell> mysql -u root mysql
mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('%','jeffrey','biscuit');
mysql> FLUSH PRIVILEGES;

これは user テーブルにプレーンテキストの 'biscuit' をパスワードとして登録してしまいます。 jeffrey ユーザーでこのパスワードを使用してサーバーに接続しようとすると、 mysql クライアントは暗号化したパスワードをサーバーに送ります。 サーバーは暗号化されたパスワード('biscuit' ではありません) と user テーブルに登録された値('biscuit') を比較します。 その結果、比較は失敗し、サーバーは接続を拒否します:

shell> mysql -u jeffrey -pbiscuit test
Access denied

user テーブルに登録されるパスワードは暗号化されたものでなくてはなりません。 INSERT 構文は以下のようにして使用しなくてはなりません:

mysql> INSERT INTO user (Host,User,Password)
    -> VALUES('%','jeffrey',PASSWORD('biscuit'));

SET PASSWORD 構文を使用する場合は、以下のように PASSWORD() 関数を使用しなくてはなりません:

mysql> SET PASSWORD FOR jeffrey@"%" = PASSWORD('biscuit');

もし GRANT ... IDENTIFIED BY 構文や mysqladmin password コマンド でパスワードを設定した場合、PASSWORD() 関数は必要ありません。 両方とも、パスワードを暗号化してくれますので、 以下のように'biscuit'と与えます:

mysql> GRANT USAGE ON *.* TO jeffrey@"%" IDENTIFIED BY 'biscuit';

or

shell> mysqladmin -u jeffrey password biscuit

注意PASSWORD() は UNIX のパスワードで使用されている暗号化と 違うことにも留意してください。 「4.3.2 MySQL ユーザ名とパスワード」節参照.

4.3.8 パスワードを安全にする

自分のパスワードを他人にさらけ出すのは勧められることではありません。 それぞれの方法に於ける危険度に応じ、以下に示す方法でクライアントプログラムに あなたのパスワードをあたえて走らせることができます:

まとめると、より安全な方法は、 パスワードプロンプトを返すクライアントプログラムを実行するか、 適切なパーミッションをかけた `.my.cnf' ファイルにパスワードを書くか です。

4.3.9 Using Secure Connections

4.3.9.1 Basics

Beginning with version 4.0.0, MySQL has support for SSL encrypted connections. To understand how MySQL uses SSL, it's necessary to explain some basic SSL and X509 concepts. People who are already familiar with them can skip this part.

By default, MySQL uses unencrypted connections between the client and the server. This means that someone could watch all your traffic and look at the data being sent or received. They could even change the data while it is in transit between client and server. Sometimes you need to move information over public networks in a secure fashion; in such cases, using an unencrypted connection is unacceptable.

SSL is a protocol that uses different encryption algorithms to ensure that data received over a public network can be trusted. It has mechanisms to detect any change, loss or replay of data. SSL also incorporates algorithms to recognise and provide identity verification using the X509 standard.

Encryption is the way to make any kind of data unreadable. In fact, today's practice requires many additional security elements from encryption algorithms. They should resist many kind of known attacks like just messing with the order of encrypted messages or replaying data twice.

X509 is a standard that makes it possible to identify someone on the Internet. It is most commonly used in e-commerce applications. In basic terms, there should be some company (called a ``Certificate Authority'') that assigns electronic certificates to anyone who needs them. Certificates rely on asymmetric encryption algorithms that have two encryption keys (a public key and a secret key). A certificate owner can prove his identity by showing his certificate to other party. A certificate consists of its owner's public key. Any data encrypted with this public key can be decrypted only using the corresponding secret key, which is held by the owner of the certificate.

MySQL doesn't use encrypted connections by default, because doing so would make the client/server protocol much slower. Any kind of additional functionality requires the computer to do additional work and encrypting data is a CPU-intensive operation that requires time and can delay MySQL main tasks. By default MySQL is tuned to be fast as possible.

If you need more information about SSL, X509, or encryption, you should use your favourite Internet search engine and search for keywords in which you are interested.

4.3.9.2 Requirements

To get secure connections to work with MySQL you must do the following:

  1. OpenSSL ライブラリをインストール。 我々は openssl 0.9.6 でテストしました。 http://www.openssl.org/.
  2. --with-vio --with-openssl で MySQL をコンフィギャ.
  3. もしあなたが古い MySQL (4.0未満)をインストールしているなら、 mysql.user テーブルを update するべきです。 これは mysql_fix_privilege_tables スクリプトで可能です。 MySQL 4.0.0 以上ではこの作業が必要です。 ( 訳注: このスクリプトは、前のバージョンが 3.23 の場合、 mysql.user テーブル に ssl_type, ssl_cipher, x509_issuer, x509_subject フィールドを追加し、 mysql.* の全てのテーブルを ALTER TABLE .. TYPE=MyISAM で作成し直します。 実行前には、念のため、mysql データベースを mysqldump か 他の方法でバックアップしておきましょう。 )
  4. 実行中の mysqld が OpenSSL をサポートしている場合は、 SHOW VARIABLES LIKE 'have_openssl'YES を返します。

4.3.9.3 Setting Up SSL Certificates for MySQL

Here is an example for setting up SSL certificates for MySQL:

DIR=`pwd`/openssl
PRIV=$DIR/private

mkdir $DIR $PRIV $DIR/newcerts
cp /usr/share/ssl/openssl.cnf $DIR
replace ./demoCA $DIR -- $DIR/openssl.cnf

# Create necessary files: $database, $serial and $new_certs_dir 
# directory (optional)

touch $DIR/index.txt
echo "01" > $DIR/serial

#
# Generation of Certificate Authority(CA)
#

openssl req -new -x509 -keyout $PRIV/cakey.pem -out $DIR/cacert.pem \
    -config $DIR/openssl.cnf

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Generating a 1024 bit RSA private key
# ................++++++
# .........++++++
# writing new private key to '/home/monty/openssl/private/cakey.pem'
# Enter PEM pass phrase:
# Verifying password - Enter PEM pass phrase:
# -----
# You are about to be asked to enter information that will be incorporated
# into your certificate request.
# What you are about to enter is what is called a Distinguished Name or a DN.
# There are quite a few fields but you can leave some blank
# For some fields there will be a default value,
# If you enter '.', the field will be left blank.
# -----
# Country Name (2 letter code) [AU]:FI
# State or Province Name (full name) [Some-State]:.
# Locality Name (eg, city) []:
# Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB
# Organizational Unit Name (eg, section) []:
# Common Name (eg, YOUR name) []:MySQL admin
# Email Address []:

#
# Create server request and key
#
openssl req -new -keyout $DIR/server-key.pem -out \
    $DIR/server-req.pem -days 3600 -config $DIR/openssl.cnf

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Generating a 1024 bit RSA private key
# ..++++++
# ..........++++++
# writing new private key to '/home/monty/openssl/server-key.pem'
# Enter PEM pass phrase:
# Verifying password - Enter PEM pass phrase:
# -----
# You are about to be asked to enter information that will be incorporated
# into your certificate request.
# What you are about to enter is what is called a Distinguished Name or a DN.
# There are quite a few fields but you can leave some blank
# For some fields there will be a default value,
# If you enter '.', the field will be left blank.
# -----
# Country Name (2 letter code) [AU]:FI
# State or Province Name (full name) [Some-State]:.
# Locality Name (eg, city) []:
# Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB
# Organizational Unit Name (eg, section) []:
# Common Name (eg, YOUR name) []:MySQL server
# Email Address []:
# 
# Please enter the following 'extra' attributes
# to be sent with your certificate request
# A challenge password []:
# An optional company name []:

#
# Remove the passphrase from the key (optional)
#

openssl rsa -in $DIR/server-key.pem -out $DIR/server-key.pem

#
# Sign server cert
#
openssl ca  -policy policy_anything -out $DIR/server-cert.pem \
    -config $DIR/openssl.cnf -infiles $DIR/server-req.pem

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Enter PEM pass phrase:
# Check that the request matches the signature
# Signature ok
# The Subjects Distinguished Name is as follows
# countryName           :PRINTABLE:'FI'
# organizationName      :PRINTABLE:'MySQL AB'
# commonName            :PRINTABLE:'MySQL admin'
# Certificate is to be certified until Sep 13 14:22:46 2003 GMT (365 days)
# Sign the certificate? [y/n]:y
# 
# 
# 1 out of 1 certificate requests certified, commit? [y/n]y
# Write out database with 1 new entries
# Data Base Updated

#
# Create client request and key
#
openssl req -new -keyout $DIR/client-key.pem -out \
    $DIR/client-req.pem -days 3600 -config $DIR/openssl.cnf

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Generating a 1024 bit RSA private key
# .....................................++++++
# .............................................++++++
# writing new private key to '/home/monty/openssl/client-key.pem'
# Enter PEM pass phrase:
# Verifying password - Enter PEM pass phrase:
# -----
# You are about to be asked to enter information that will be incorporated
# into your certificate request.
# What you are about to enter is what is called a Distinguished Name or a DN.
# There are quite a few fields but you can leave some blank
# For some fields there will be a default value,
# If you enter '.', the field will be left blank.
# -----
# Country Name (2 letter code) [AU]:FI
# State or Province Name (full name) [Some-State]:.
# Locality Name (eg, city) []:
# Organization Name (eg, company) [Internet Widgits Pty Ltd]:MySQL AB
# Organizational Unit Name (eg, section) []:
# Common Name (eg, YOUR name) []:MySQL user
# Email Address []:
# 
# Please enter the following 'extra' attributes
# to be sent with your certificate request
# A challenge password []:
# An optional company name []:

#
# Remove a passphrase from the key (optional)
#
openssl rsa -in $DIR/client-key.pem -out $DIR/client-key.pem

#
# Sign client cert
#

openssl ca  -policy policy_anything -out $DIR/client-cert.pem \
    -config $DIR/openssl.cnf -infiles $DIR/client-req.pem

# Sample output:
# Using configuration from /home/monty/openssl/openssl.cnf
# Enter PEM pass phrase:
# Check that the request matches the signature
# Signature ok
# The Subjects Distinguished Name is as follows
# countryName           :PRINTABLE:'FI'
# organizationName      :PRINTABLE:'MySQL AB'
# commonName            :PRINTABLE:'MySQL user'
# Certificate is to be certified until Sep 13 16:45:17 2003 GMT (365 days)
# Sign the certificate? [y/n]:y
# 
# 
# 1 out of 1 certificate requests certified, commit? [y/n]y
# Write out database with 1 new entries
# Data Base Updated

#
# Create a my.cnf file that you can use to test the certificates
#

cnf=""
cnf="$cnf [client]"
cnf="$cnf ssl-ca=$DIR/cacert.pem"
cnf="$cnf ssl-cert=$DIR/client-cert.pem"
cnf="$cnf ssl-key=$DIR/client-key.pem"
cnf="$cnf [mysqld]"
cnf="$cnf ssl-ca=$DIR/cacert.pem"
cnf="$cnf ssl-cert=$DIR/server-cert.pem"
cnf="$cnf ssl-key=$DIR/server-key.pem"
echo $cnf | replace " " '
' > $DIR/my.cnf

#
# To test MySQL

mysqld --defaults-file=$DIR/my.cnf &

mysql --defaults-file=$DIR/my.cnf

You can also test your setup by modifying the above `my.cnf' file to refer to the demo certificates in the mysql-source-dist/SSL direcory.

4.3.9.4 GRANT オプション

MySQL can check X509 certificate attributes in addition to the normal username/password scheme. All the usual options are still required (username, password, IP address mask, database/table name).

There are different possibilities to limit connections:

4.4 Disaster Prevention and Recovery

4.4.1 データベースのバックアップ

MySQL テーブルはファイルとして格納されるため、バックアップを行 うのは簡単です。矛盾のないバックアップを得るためには、 FLUSH TABLES をおこなって、LOCK TABLES を関連するテーブルで行ってください。 「6.7.2 LOCK TABLES/UNLOCK TABLES 構文」節参照. 「4.5.3 FLUSH 構文」節参照. 読み込みロックだ けが必要なので、そのテーブルでデータベースディレクトリのファイルのコピー が行われている間も、他のスレッドはクエリを継続できます。 The FLUSH TABLE is needed to ensure that the all active index pages is written to disk before you start the backup.

Starting from 3.23.56 and 4.0.12 BACKUP TABLE will not allow you to overwrite existing files as this would be a security risk.

もし、テーブルを SQL レベルでバックアップしたいのであれば、SELECT INTO OUTFILEBACKUP TABLE を使用できます。 「4.4.2 BACKUP TABLE 構文 (3.23.25以上)」節参照.

他の方法は mysqldump プログラムか mysqlhotcopy スクリプト を使用することです。 「4.8.5 mysqldump, データベースとテーブルから、構造とデータをダンプ」節参照. 「4.8.6 mysqlhotcopy, Copying MySQL Databases and Tables」節参照.

  1. フルバックアップをとるには:
    shell> mysqldump --tab=/path/to/some/dir --opt --all
    
    or
    
    shell> mysqlhotcopy database /path/to/some/dir
    
    You can also simply copy all table files (`*.frm', `*.MYD', and `*.MYI' files) as long as the server isn't updating anything. The script mysqlhotcopy does use this method.
  2. mysqld を止め、そして --log-update[=file_name] オプションをつけて起動します。 「4.9.3 更新ログ」節参照. ログファイルは、 mysqldump 実行後に行われたデータベースの変更を 複製するための情報を与えてくれます。

もしリストアをしなければならない場合、まず最初に REPAIR TABLEmyisamchk -r を実行してテーブルの修復を試みてください。 ほとんどの場合、99.9% 修復はできるはずです。 もし myisamchk が失敗した場合、以下のようにします: (this will only work if you have started MySQL with --log-update, 「4.9.3 更新ログ」節参照):

  1. オリジナルの mysqldump バックアップデータをリストアします。
  2. 次のコマンドを実行して、バイナリログ内の更新を再実行します。
    shell> mysqlbinlog hostname-bin.[0-9]* | mysql
    
    更新ログを使用する場合は、次のようにできます:
    shell> ls -1 -t -r hostname.[0-9]* | xargs cat | mysql
    

ls は、全ての更新ログファイルを正しい順で得るために行われます。

SELECT * INTO OUTFILE 'file_name' FROM tbl_name での選択的バックアップと LOAD DATA FROM INFILE 'file_name' REPLACE ... でのリストアを行う こともできます。重複レコードを避けるためには、テーブル内に PRIMARY KEYUNIQUE が必要です。REPLACE は、'重複インデックス' 衝突があった場合、 新しいレコードを挿入する時に古いレコードが新しいものに置き換えられることを意味します。

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. 「4.10.1 Introduction」節参照.

If you are using a Veritas filesystem, you can do:

  1. From a client (or Perl), execute: FLUSH TABLES WITH READ LOCK.
  2. From another shell, execute: mount vxfs snapshot.
  3. From the first client, execute: UNLOCK TABLES.
  4. Copy files from snapshot.
  5. Unmount snapshot.

4.4.2 BACKUP TABLE 構文 (3.23.25以上)

BACKUP TABLE tbl_name[,tbl_name...] TO '/path/to/backup/directory'

Copies to the backup directory the minimum number of table files needed to restore the table, after flushing any buffered changes to disk. Currently works only for MyISAM tables. For MyISAM tables, copies `.frm' (definition) and `.MYD' (data) files. The index file can be rebuilt from those two.

Before using this command, please see 「4.4.1 データベースのバックアップ」節.

During the backup, a read lock will be held for each table, one at time, as they are being backed up. If you want to back up several tables as a snapshot, you must first issue LOCK TABLES obtaining a read lock for each table in the group.

The command returns a table with the following columns:

Column Value
Table Table name
Op Always ``backup''
Msg_type One of status, error, info or warning.
Msg_text The message.

Note that BACKUP TABLE is only available in MySQL version 3.23.25 and later.

4.4.3 RESTORE TABLE 構文 (3.23.25以上)

RESTORE TABLE tbl_name[,tbl_name...] FROM '/path/to/backup/directory'

Restores the table(s) from the backup that was made with BACKUP TABLE. Existing tables will not be overwritten; if you try to restore over an existing table, you will get an error. Restoring will take longer than backing up due to the need to rebuild the index. The more keys you have, the longer it will take. Just as BACKUP TABLE, RESTORE TABLE currently works only for MyISAM tables.

The command returns a table with the following columns:

Column Value
Table Table name
Op Always ``restore''
Msg_type One of status, error, info or warning.
Msg_text The message.

4.4.4 CHECK TABLE 構文 (3.23.13以上)

CHECK TABLE tbl_name[,tbl_name...] [option [option...]]

option = QUICK | FAST | MEDIUM | EXTENDED | CHANGED

CHECK TABLEMyISAM テーブル と InnoDB テーブルだけで動作します。 MyISAM テーブルでは、テーブル上で myisamchk -m table_name を 実行するのと同じことです。

オプションを何も指定しない場合は MEDIUM が使用されます。

テーブルのエラーチェックを行ないます。MyISAM テーブルではキー統計が 更新されます。 このコマンドは次のフィールドを持つテーブルを返します:

Column Value
Table テーブル名
Op 常に ``check''
Msg_type status, error, info, warning のうちの一つ。
Msg_text メッセージ。

注意: チェックされた各テーブルに対する情報の多くのレコードが得られます。 最後の1レコードは Msg_type status になり、通常は OK で あるべきです。OKTable is already up to date が得られない場合は、 テーブルの修復を通常通り実行すべきです。 「4.4.6 テーブルのメンテナンス、クラッシュからの修復のための myisamchk 使用」節参照. Table is already up to date means that the table the given TYPE told MySQL that there wasn't any need to check the table.

様々なチェックタイプは次の意味です:

Type Meaning
QUICK 間違ったリンクをチェックするレコードを走査しません。
FAST 正しくクローズされなかったテーブルだけをチェックします。
CHANGED 最後にチェックしてから変更されたテーブルと、正しくクローズされなかったテーブルだけをチェックします。
MEDIUM 削除されたリンクが OK であることを確かめるためにレコードを走査します。これはレコードのキーチェックサムも計算し、キーの計算されたチェックサムをで、これを確かめます。
EXTENDED 各レコードのすべてのキーを完全キー検索を行ないます。テーブルが 100% 正当なことを確実にしますが、長い時間が掛かります!

動的なサイズの MyISAM テーブルについて、開始されたチェックは常に MEDIUM チェックを行ないます。清適サイズレコードでは、レコードはめっ たに壊れないので、QUICKFAST ではレコードスキャンをスキッ プします。

チェックオプションは次のように組み合わせられます:

CHECK TABLE test_table FAST QUICK;

これは、テーブルが正しくクローズされなかったかどうかだけを素早くチェックし ます。

Note: いくつかのケースでは CHECK TABLE はテーブルを変更し ます! これはテーブルが '汚れている' か '正しくクローズされなかった' とマー クされているのに、CHECK TABLE がテーブル内に何も問題を発見しなかっ た場合に発生します。この場合、CHECK TABLE はテーブルを 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 thoroughly and should thus find most errors.

If you just want to check a table that you assume is okay, you should use no check options or the QUICK option. The latter should be used when you are in a hurry and can take the very small risk that QUICK didn't find an error in the datafile. (In most cases 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.)

FAST and 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 FAST is to be prefered over CHANGED. (The only case when it isn't is when you suspect a bug you have found a bug in the MyISAM code.)

EXTENDED is only to be used after you have run a normal check but still get strange errors from a table when MySQL tries to update a row or find a row by key (this is very unlikely if a normal check has succeeded!).

Some things reported by check table, can't be corrected automatically:

4.4.5 REPAIR TABLE 構文 (3.23.14以上)

REPAIR TABLE tbl_name[,tbl_name...] [QUICK] [EXTENDED] [USE_FRM]

REPAIR TABLEMyISAM テーブルだけで動作します。テーブルに myisamchk -r table_name を実行することと同じです。

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 REPAIR TABLE. If your tables get corrupted a lot you should try to find the reason for this! 「A.4.1 What To Do If MySQL Keeps Crashing」節参照. 「7.1.3 MyISAM table problems.」節参照.

REPAIR TABLE はなんとかなる壊れたテーブルを修復します。コマンドは次 のフィールドを含む表を返します:

Column Value
Table テーブル名
Op Always ``repair''
Msg_type status, error, info, warning のどれか.
Msg_text メッセージ

注意: 修復された各テーブルの情報の多くのレコードを得ることがあります。最後 の1レコードは Msg_type status になり、通常は OK であるべき です。OK が得られなければ、myisamchk -o でテーブルの修復を試 みるべきです。REPAIR TABLE はまだ、myisamchk のオプションの 全てを持っていないからです。 In the near future, we will make it more flexible.

QUICK が与えられた場合は、MySQL はインデックスツリー の REPAIR だけを試みます。

If you use EXTENDED then 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 CHAR keys that compress very well. This type of repair is like that done by myisamchk --safe-recover.

As of MySQL 4.0.2, there is a USE_FRM mode for REPAIR. Use it if the `.MYI' file is missing or if its header is corrupted. In this mode MySQL will recreate the table, using information from the `.frm' file. This kind of repair cannot be done with myisamchk.

4.4.6 テーブルのメンテナンス、クラッシュからの修復のための myisamchk 使用

Starting with MySQL Version 3.23.13, you can check MyISAM tables with the CHECK TABLE command. 「4.4.4 CHECK TABLE 構文 (3.23.13以上)」節参照. You can repair tables with the REPAIR TABLE command. 「4.4.5 REPAIR TABLE 構文 (3.23.14以上)」節参照.

MyISAM テーブル (.MYI and .MYD) の検査・修復には myisamchk を 使用します。 ISAM テーブル (.ISM and .ISD) の検査・修復には isamchk を 使用します。 「7 MySQL テーブル型」節参照.

以下の文は myisamchk について述べていますが、isamchk にもすべて 当てはまります。

myisamchk ユーティリティは、データベースのテーブルの情報を得たり、 チェックしたり、テーブルの修復や最適化に使用します。 以下のセクションでは、 myisamchk の起動方法(オプションの説明も含む)、 テーブルの保守スケジュールのたて方、 myisamchk の色々な機能の使い方を述べます。

テーブルの修復と最適化のために、ほとんどの場合、 OPTIMIZE TABLES コマンドが使用できます。しかしこれは myisamchk に比べて、 遅くて確実でもありません。(fatal error発生時の場合)。これは その反面、使用方法が簡単でテーブルのフラッシュを気にかける必要がありません。 「4.5.1 OPTIMIZE TABLE 構文」節参照.

Even that the repair in 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)

4.4.6.1 myisamchk 起動構文

myisamchk は以下のようにして起動します:

shell> myisamchk [options] tbl_name

options に、あなたが myisamchk にさせたいことを指定します。 その説明は後述します。(myisamchk --help と実行すれば、オプションの一覧が取れます)。 オプションがなければ、 myisamchk は単にテーブルを検査するだけです。 より多くの情報を得たい、あるいは、 myisamchk に誤り訂正の行動を 取らせる事については、後述します。

tbl_name は検査/修復したいテーブル名です。 もしどこか違うディレクトリにあるデータベースに対して myisamchk を走らせたいなら、 myisamchk にはファイルがどこにあるかわからないので、 ファイルのパスを指定しなければなりません。 実際、 myisamchk はあなたが使用しているファイルがデータベースのディレクトリにある かどうかは考慮しません; ほかの場所にデータベーステーブルのファイルをコピーし、そのコピーしたファイルに対して 回復操作を実行することができます。

myisamchk コマンドラインには、複数のテーブル名が指定できます。 また、インデックスファイル名(`.MYI' 接尾語のついたファイル)も指定でき、 さらに `*.MYI' とすれば、ディレクトリ内の全てのテーブルが指定できます。 例えば、現在のカレントディレクトリがデーターベースディレクトリならば、 そのディレクトリ内の全てのテーブルは、以下のようにして検査できます:

shell> myisamchk *.MYI

データベースディレクトリに入っていない場合、 パスを指定することにより全てのテーブルが検査できます:

shell> myisamchk /path/to/database_dir/*.MYI

MySQL データディレクトリのパスにワイルドカードを使用することにより、 データベースの全てのテーブルも検査できます:

shell> myisamchk /path/to/datadir/*/*.MYI

The recommended way to quickly check all tables is:

myisamchk --silent --fast /path/to/datadir/*/*.MYI
isamchk --silent /path/to/datadir/*/*.ISM

If you want to check all tables and repair all tables that are corrupted, you can use the following line:

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

The above assumes that you have more than 64 M free.

Note that if you get an error like:

myisamchk: warning: 1 clients is using or hasn't closed the table properly

This means that you are trying to check a table that has been updated by the another program (like the mysqld server) that hasn't yet closed the file or that has died without closing the file properly.

If you mysqld is running, you must force a sync/close of all tables with FLUSH TABLES and ensure that no one is using the tables while you are running myisamchk. In MySQL Version 3.23 the easiest way to avoid this problem is to use CHECK TABLE instead of myisamchk to check tables.

4.4.6.2 myisamchk の一般オプション

myisamchk supports the following options.

-# or --debug=debug_options
デバッグログの出力。 debug_options はよく 'd:t:o,filename' とされます。
-? or --help
ヘルプを表示して終了。
-O var=option, --set-variable var=option
変数に値を入れます。 Please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own. 可能な変数とデフォルトの値は myisamchk --help で確認できます:
Variable Value
key_buffer_size 523264
read_buffer_size 262136
write_buffer_size 262136
sort_buffer_size 2097144
sort_key_blocks 16
decode_bits 9
sort_buffer_size is used when the keys are repaired by sorting keys, which is the normal case when you use --recover. key_buffer_size is used when you are checking the table with --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: Reparing through the key buffer takes much less disk space than using sorting, but is also much slower. もし速い修復を望むなら、メモリの 1/4 を上記の変数にセットします。 You can set both variables to big values, as only one of the above buffers will be used at a time.
-s or --silent
静粛モード。 エラーのみを出力します。 二度 -s を指定すると(-ss)、myisamchk は ほとんど出力をしなくなります。
-v or --verbose
冗長モード。より多く情報を出力します。 -d-e オプションと共に使用できます。 -v を複数指定すると(-vv, -vvv)、もっと出力が多くなります!
-V or --version
myisamchk バージョンを表示して終了。
-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 mysqld on the table with --skip-external-locking, the table can only be locked by another myisamchk command.

4.4.6.3 myisamchk の検査オプション

-c or --check
テーブルのエラーをチェック。 これは myisamchk にオプションを 与えていない時のデフォルトです。
-e or --extend-check
テーブルを非常に徹底的に検査します。 (ただし多くのインデックスがある場合、 とても遅くなります。). 極端な場合にだけで必要とされます。 通常 myisamchkmyisamchk --medium-check は、 このオプションなしで全てのエラーを見つけるはずです。 多くのメモリがマシンにあるなら、--extended-check を使用する際には key_buffer_size の値を多く増やします。
-F or --fast
Check only tables that haven't been closed properly.
-C or --check-only-changed
Check only tables that have changed since the last check.
-f or --force
Restart myisamchk with -r (repair) on the table, if myisamchk finds any errors in the table.
-i or --information
検査されたテーブルの統計情報を表示。
-m or --medium-check
Faster than extended-check, but only finds 99.99% of all errors. Should, however, be good enough for most cases.
-U or --update-state
Store in the `.MYI' file when the table was checked and if the table crashed. This should be used to get full benefit of the --check-only-changed option, but you shouldn't use this option if the mysqld server is using the table and you are running mysqld with --skip-external-locking.
-T or --read-only
Don't mark table as checked. This is useful if you use myisamchk to check a table that is in use by some other application that doesn't use locking (like mysqld --skip-external-locking).

4.4.6.4 myisamchk の修復オプション

以下のオプションは myisamchk-r-o オプションで 実行した場合に使用できます:

-D # or --data-file-length=#
Max length of datafile (when re-creating datafile when it's 'full').
-e or --extend-check
Try to recover every possible row from the datafile. Normally this will also find a lot of garbage rows. Don't use this option if you are not totally desperate.
-f or --force
Overwrite old temporary files (table_name.TMD) instead of aborting.
-k # or keys-used=#
If you are using ISAM, tells the ISAM storage engine to update only the first # indexes. If you are using MyISAM, tells which keys to use, where each binary bit stands for one key (first key is bit 0). これはインサートを速くします! 非アクティブになったインデックスは、myisamchk -r を使用すれば再びアクティ ブになります。
-l or --no-symlinks
修復時にシンボリックリンクを追いません。 通常、myisamchk はシンボリックリンクが指し示すテーブルも修復します。 This option doesn't exist in MySQL 4.0, as MySQL 4.0 will not remove symlinks during repair.
-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 -r, you should then try -o. (Note that in the unlikely case that -r fails, the datafile is still intact.) If you have lots of memory, you should increase the size of sort_buffer_size!
-o or --safe-recover
古い修復方法を使用します (reads through all rows in order and updates all index trees based on the found rows); これは -r よりも遅いですが、 -r が扱えないものも扱えます。 This recovery method also uses much less disk space than -r. Normally one should always first repair with -r, and only if this fails use -o. If you have lots of memory, you should increase the size of key_buffer_size!
-n or --sort-recover
Force myisamchk to use sorting to resolve the keys even if the temporary files should be very big.
--character-sets-dir=...
Directory where character sets are stored.
--set-character-set=name
Change the character set used by the index
-t or --tmpdir=path
一時ファイルを保存する先のパス。 もしセットされなければ、 myisamchkTMPDIR 環境変数の値をこのパスとします。 Starting from MySQL 4.1, tmpdir can be set to a list of paths separated by colon : (semicolon ; on Windows). They will be used in round-robin fashion.
-q or --quick
Faster repair by not modifying the datafile. One can give a second -q to force myisamchk to modify the original datafile in case of duplicate keys
-u or --unpack
myisampack でパックされたテーブルファイルをアンパックします。

4.4.6.5 myisamchk の他のオプション

Other actions that myisamchk can do, besides repair and check tables:

-a or --analyze
キーの分布(配置)を分析します。 This improves join performance by enabling the join optimiser to better choose in which order it should join the tables and which keys it should use: myisamchk --describe --verbose table_name' or using SHOW KEYS in MySQL.
-d or --description
テーブルに関するいくらかの情報を表示します
-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.
-S or --sort-index
インデックスブロックのソート。 これは、アプリケーションでの ``read-next'' を速くします。
-R or --sort-records=#
インデックスに従ってソート。 これはあなたのデータをよりよく配置し、このインデックスへの SELECT, ORDER BY オペレーションを速くします。 (この操作の最初のソートは非常に遅くなるかもしれません!) テーブルのインデックスの番号をみつけるには SHOW INDEX を使用しますが、 これは myisamchk がテーブルのインデックスを見つけるのと同じ順序で行います。 インデックス番号は 1 から始まります。

4.4.6.6 myisamchk メモリ使用

myisamchk を走らす上でメモリーの配分は重要です。 myisamchk-O オプションで定義した以上のメモリは使用しません。 とても大きなファイルのたいして myisamchk をかけたいなら、 メモリーをどれくらい使用するかを最初に決めなくてはなりません。 デフォルトは固定で約 3M だけを使用します。大きな値を使用することで、 myisamchk をより速く動作できます。 例えば、32MBytesのRAMがあるなら、以下のように指定できます (他のオプションも指定して):

shell> myisamchk -O sort=16M -O key=16M -O read=1M -O write=1M ...

-O sort=16M の使用は多くの場合おそらく十分でしょう。

しかし、myisamchkTMPDIR 内に一時ファイルを使用します。 TMPDIR がメモリファイルシステムを指している場合は、簡単に out of memory エラーを得るでしょう。 If this happens, set TMPDIR to point at some directory with more space and restart myisamchk.

When repairing, myisamchk will also need a lot of disk space:

If you have a problem with disk space during repair, you can try to use --safe-recover instead of --recover.

4.4.6.7 Using myisamchk for Crash Recovery

If you run mysqld with --skip-external-locking (which is the default on some systems, like Linux), you can't reliably use myisamchk to check a table when mysqld is using the same table. If you can be sure that no one is accessing the tables through mysqld while you run myisamchk, you only have to do mysqladmin flush-tables before you start checking the tables. If you can't guarantee the above, then you must take down mysqld while you check the tables. If you run myisamchk while 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 --skip-external-locking, you can use myisamchk to check tables at any time. While you do this, all clients that try to update the table will wait until myisamchk is ready before continuing.

If you use myisamchk to repair or optimise tables, you must always ensure that the mysqld server is not using the table (this also applies if you are using --skip-external-locking). If you don't take down mysqld you should at least do a mysqladmin flush-tables before you run myisamchk. Your tables may be corrupted if the server and myisamchk access the tables simultaneously.

This chapter describes how to check for and deal with data corruption in MySQL databases. If your tables get corrupted frequently you should try to find the reason for this! 「A.4.1 What To Do If MySQL Keeps Crashing」節参照.

The MyISAM table section contains reason for why a table could be corrupted. 「7.1.3 MyISAM table problems.」節参照.

When performing crash recovery, it is important to understand that each table tbl_name in a database corresponds to three files in the database directory:

File Purpose
`tbl_name.frm' Table definition (form) file
`tbl_name.MYD' Datafile
`tbl_name.MYI' Index file

Each of these three file types is subject to corruption in various ways, but problems occur most often in datafiles and index files.

myisamchk works by creating a copy of the `.MYD' (data) file row by row. It ends the repair stage by removing the old `.MYD' file and renaming the new file to the original file name. If you use --quick, myisamchk does not create a temporary `.MYD' file, but instead assumes that the `.MYD' file is correct and only generates a new index file without touching the `.MYD' file. This is safe, because myisamchk automatically detects if the `.MYD' file is corrupt and aborts the repair in this case. You can also give two --quick options to myisamchk. In this case, myisamchk does not abort on some errors (like duplicate key) but instead tries to resolve them by modifying the `.MYD' file. Normally the use of two --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 myisamchk.

4.4.6.8 How to Check Tables for Errors

To check a MyISAM table, use the following commands:

myisamchk tbl_name
This finds 99.99% of all errors. What it can't find is corruption that involves only the datafile (which is very unusual). If you want to check a table, you should normally run myisamchk without options or with either the -s or --silent option.
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.
myisamchk -e tbl_name
This does a complete and thorough check of all data (-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. myisamchk will normally stop after the first error it finds. If you want to obtain more information, you can add the --verbose (-v) option. This causes myisamchk to keep going, up through a maximum of 20 errors. In normal usage, a simple myisamchk (with no arguments other than the table name) is sufficient.
myisamchk -e -i tbl_name
Like the previous command, but the -i option tells myisamchk to print some informational statistics, too.

4.4.6.9 テーブルの修復方法

In the following section we only talk about using myisamchk on MyISAM tables (extensions `.MYI' and `.MYD'). If you are using ISAM tables (extensions `.ISM' and `.ISD'), you should use isamchk instead.

Starting with MySQL Version 3.23.14, you can repair MyISAM tables with the REPAIR TABLE command. 「4.4.5 REPAIR TABLE 構文 (3.23.14以上)」節参照.

テーブル破壊の兆しとして、クエリが予期せず中断したり、以下のようなエラーが出たり します:

この他の場合、あなたは自分のテーブルを修理しなければなりません。 myisamchk はほとんどの問題を見つけ出し修正します。

修復過程は以下で記述する最大4つの段階を踏みます。 これを始める前に、あなたはデータベースディレクトリに cd して テーブルファイルのパーミッションを確認すべきです。 これらファイルは mysqld を実行している UNIX ユーザーが読み込み可能 であるようにしてください(検査のするのにあなたにファイルのアクセス権も必要)。 もしファイルの変更をする必要があるならば、ファイルへの書き込み許可も必要です。

If you are using MySQL Version 3.23.16 and above, you can (and should) use the CHECK and REPAIR commands to check and repair MyISAM tables. 「4.4.4 CHECK TABLE 構文 (3.23.13以上)」節参照. 「4.4.5 REPAIR TABLE 構文 (3.23.14以上)」節参照.

The manual section about table maintenance includes the options to isamchk/myisamchk. 「4.4.6 テーブルのメンテナンス、クラッシュからの修復のための myisamchk 使用」節参照.

The following section is for the cases where the above command fails or if you want to use the extended features that isamchk/myisamchk provides.

If you are going to repair a table from the command-line, you must first take down the mysqld server. Note that when you do mysqladmin shutdown on a remote server, the mysqld server will still be alive for a while after mysqladmin returns, until all queries are stopped and all keys have been flushed to disk.

Stage 1: テーブルをチェックする

myisamchk *.MYI (時間がかかってもよいなら myisamchk -e *.MYI) を実行します。 -s (silent) オプションは不要な情報の出力をおさえます。

If the mysqld server is done you should use the --update option to tell myisamchk to mark the table as 'checked'.

myisamchk がエラーを返した場合にだけ、テーブルを修復する必要があります。 この場合、Stage 2 へ進みます。

チェック時に奇妙なエラー(out of memory エラーのような) が起きた場合、 あるいは myisamchk が落ちた場合、Stage 3 に進んでください。

Stage 2: 簡単で安全な修復

Note: If you want repairing to go much faster, you should add: -O sort_buffer=# -O key_buffer=# (where # is about 1/4 of the available memory) to all isamchk/myisamchk commands.

まず最初に myisamchk -r -q tbl_name を試みてください (-r -q は ``quick recovery mode''の意)。 これはデータファイルに触れないでインデックスファイルの修理を試みます。 もしデータファイルが全てとデータファイル中の正しい場所での削除リンクポイントを 含んでいるなら、これは動作してテーブルを修復します。 成功後、次のテーブルの修復に進んでください。 失敗した場合は、以下の手順で試みてください:

  1. 続ける前にデータファイルをバックアップしてください。
  2. myisamchk -r tbl_name を使用します(-r は ``recovery mode''の意)。 これは不正なレコードと削除されたレコードをデータファイルから消去し、 インデックスファイル(.MYI)を再構築します。
  3. 上記が失敗した場合、myisamchk --safe-recover tbl_name を使用して下さい。 Safe recovery モードは古い方法を使用して修復します。 これは普通の修復モードでは行わない操作をいくつかもっています。(遅いですが)

If you get weird errors when repairing (such as out of memory errors), or if myisamchk crashes, go to Stage 3.

Stage 3: 難しい修復

インデックスファイル(.MYI)の最初の 16K ブロックが破壊された場合、 または不正な情報を含む場合、またはインデックスファイルがない場合にだけ、 本修復段階を経ます。 この場合、新しいインデックスファイルファイルを作成する必要があります。 次のようにしてください:

  1. データファイルをどこか安全場所に移動します。
  2. 新しい(空の)データとインデックスファイルを作るために、 テーブルディスクリプタファイルを使用します:
    shell> mysql db_name
    mysql> SET AUTOCOMMIT=1;
    mysql> TRUNCATE TABLE table_name;
    mysql> quit
    
    If your SQL version doesn't have TRUNCATE TABLE, use DELETE FROM table_name instead.
  3. 古いデータファイルを新しく作ったデータファイルにコピーします。 (Don't just move the old file back onto the new file; you want to retain a copy in case something goes wrong.)

Go back to Stage 2. myisamchk -r -q should work now. (This shouldn't be an endless loop.)

As of MySQL 4.0.2 you can also use REPAIR ... USE_FRM which performs the whole procedure automatically.

Stage 4: とても難しい修復

これは、ディスクリプタファイル(.frm)もクラッシュした場合にだけ発生します。 これは発生することはありません。なぜならディスクリプタファイルは テーブルが生成された後に書かれることはないからです。

  1. ディスクリプタファイルをバックアップからリストアして、Stage 3 に戻ってください。 インデックスファイルのリストアもできます。そして Stage 2 に戻ってください。 後者の場合、myisamchk -r で開始すべきです。
  2. バックアップを持っていなくても、テーブルがどのように作成されたかを正確に知って いれば、他のデータベース内にテーブルのコピーを生成します。 新しいデータファイルを削除し、先ほど作ったデータベースの中の ディスクリプタファイルとインデックスファイルを、壊れたデータベース内に 移動します。これは新しいディスクリプタファイルとインデックスファイルを 与えることになりますが、データファイルはそのまま残っています。 Stage 2 に進み、インデックスファイルの修復を行ってください。

4.4.6.10 テーブルの最適化

断片化されたレコードの結合と、 レコードの削除と更新から生じる無駄なスペースの排除、 これら行うには、修復モード(recovery mode)で myisamchk を実行します:

shell> myisamchk -r tbl_name

You can optimise a table in the same way using the SQL OPTIMIZE TABLE statement. OPTIMIZE TABLE does a repair of the table and a key analysis, 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 OPTIMIZE TABLE. 「4.5.1 OPTIMIZE TABLE 構文」節参照.

myisamchk には、あなたがテーブルの性能を向上させるのに使用することができる 他の多くのオプションがあります:

For a full description of the option. 「4.4.6.1 myisamchk 起動構文」節参照.

4.4.7 テーブルの保守体制の設定

Starting with MySQL Version 3.23.13, you can check MyISAM tables with the CHECK TABLE command. 「4.4.4 CHECK TABLE 構文 (3.23.13以上)」節参照. You can repair tables with the REPAIR TABLE command. 「4.4.5 REPAIR TABLE 構文 (3.23.14以上)」節参照.

問題が発生するまで待つより、定期的にテーブルを検査する方がよりよい考えです。 保守目的には、myisamchk -s でテーブルを検査するのがよいでしょう。 -s オプション(short for --silent) はサイレントモードなので、 エラーが起きた場合にだけメッセージを出力します。

サーバーを開始するときにテーブルを検査するのもよい考えです。 例えば、更新最中にマシンがリブートされたなら、全てのテーブルに関して その影響がないか検査する必要があります。(これは``expected crashed table''です) リブート後にもし古い `.pid' ファイル(プロセスID) があるならば、 24時間以内に変更されたテーブルに対して myisamchk を走らせて検査させるよう に、 safe_mysqld にテストを追加しても構いません。 (`.pid' ファイルは mysqld 起動時に作られ、通常修了時に消されます。 スタート時に `.pid' ファイルが存在するなら mysqld が異常終了したこと を示します。)

良いテストは、`.pid' ファイルの作成時間以降に変更された 全てのテーブルを検査するテストです。

通常のシステム運用中にもテーブルを検査すべきです。 MySQL AB では、週に一度、 cron を使用して重要なテーブルを検査し ています。 `crontab' ファイルには以下のように記述します:

35 0 * * 0 /path/to/myisamchk --fast --silent /path/to/datadir/*/*.MYI

これは壊れたテーブルの情報を出力しますので、必要とあらば検査、修復が行えるわけで す。

予想外の事故で壊れたテーブル(ハードウェアのトラブルが原因で崩壊)を除き、 2,3年間、テーブルは壊れたことはありません(これは本当に本当です)。 ので、一週間に一度のチェックでも十分です。

24時間以内に変更された全てのテーブルに対して、 myisamchk -s を毎晩実行する事を勧めます。 そうすれば、あなたは我々と同じぐらいに MySQL を 信頼することになります。

Normally you don't need to maintain MySQL tables that much. If you are changing tables with dynamic size rows (tables with VARCHAR, BLOB or 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 OPTIMIZE TABLE on the tables in question or if you can take the mysqld server down for a while do:

isamchk -r --silent --sort-index -O sort_buffer_size=16M */*.ISM
myisamchk -r --silent --sort-index  -O sort_buffer_size=16M */*.MYI

4.4.8 テーブル情報取得

テーブルから詳細/統計を得るためには、次の方法を使用します。後でさらに詳細な情 報をいくつか説明します。

myisamchk -d 出力の例:

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

myisamchk -d -v 出力の例:

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

myisamchk -eis 出力の例:

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

myisamchk -eiv 出力の例:

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

上で使用されたテーブルのデータファイルサイズをここに示します:

-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

myisamchk が生成する情報の説明を以下に示します。 ``keyfile'' はインデックスファイルです。 ``Record'' と ``row'' は同義です。

テーブルが pack_isam で圧縮されているなら、myisamchk -d は それぞれのテーブルコラムに関する追加情報を出力します。 「4.7.4 myisampack, MySQL の圧縮された読み込み専用テーブルジェネレータ」節. を参照してください。 この情報例と説明記述の意味があります。

4.5 Database Administration Language Reference

4.5.1 OPTIMIZE TABLE 構文

OPTIMIZE TABLE tbl_name[,tbl_name]...

OPTIMIZE TABLEは、テーブルの大部分を削除したり、可変長となっているテーブ ル(VARCHARBLOBもしくはTEXTフィールドを持つテーブル)に多く の変更を加えた場合に使用すべきです。 削除されたレコードはリンクリストで維持され、次のINSERT操作は、古いレコー ド位置を再利用します。 未使用領域を再生するためにOPTIMIZE TABLEを使用することができます。

今のところ、OPTIMIZE TABLEMyISAMBDB テーブ ル上でだけ動作します。BDB テーブルでは、OPTIMIZE TABLE が現 在 ANALYZE TABLE にマップされます。 「4.5.2 ANALYZE TABLE Syntax」節参照.

--skip-new または --safe-modemysqld を起動するこ とで、他のテーブル型で OPTIMIZE TABLE を動作するようにできます。しかし、こ の場合 OPTIMIZE TABLEALTER TABLE にマップされるだけです。

OPTIMIZE TABLE は次の方法で動作します:

MyISAM テーブルの OPTIMIZE TABLE はテーブル上で myisamchk --quick --check-changed-tables --sort-index --analyze を 実行することと同等です。

注意: テーブルは OPTIMIZE TABLE 実行中はロックされます!

4.5.2 ANALYZE TABLE Syntax

ANALYZE TABLE tbl_name[,tbl_name...]

Analyse and store the key distribution for the table. During the analysis, the table is locked with a read lock. This works on MyISAM and BDB tables.

This is equivalent to running myisamchk -a on the table.

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:

Column Value
Table Table name
Op Always ``analyze''
Msg_type One of status, error, info or warning.
Msg_text The message.

You can check the stored key distribution with the SHOW INDEX command. 「4.5.6.1 Retrieving information about Database, Tables, Columns, and Indexes」節参照.

If the table hasn't changed since the last ANALYZE TABLE command, the table will not be analysed again.

4.5.3 FLUSH 構文

FLUSH flush_option [,flush_option] ...

FLUSH コマンドで MySQL が使用している内部キャッシュの いくつかをきれいに消すことができます。 FLUSH を実行するには、 RELOAD 権限がなければなりません。

flush_option には以下の内一つが指定できます:

Option Description
HOSTS ホストキャッシュテーブルを空にします。あなたのホストの IP アドレスを変えたり、Host ... is blocked というエラーメッセージが 出る場合はホストテーブルキャッシュを一度空にしなくてはなりません。 指定したホストに対して max_connect_errors 以上の接続エラーが出る場合、 MySQL は何か起きたと推定し、そのホストからのいかなる接続要求も 拒否します。ホストテーブルキャッシュの消去は、再び接続を許すようにします。 「A.2.4 Host '...' is blocked エラー」節参照. mysqld-O max_connect_errors=999999999 開始し、 このエラーメッセージを回避できます
DES_KEY_FILE Reloads the DES keys from the file that was specified with the --des-key-file option at server startup time.
LOGS 標準のログファイルと更新ログファイルを 一度閉じて再び開きます。 もし更新ログファイルを拡張子無しで指定している場合、新しい更新ログファイルの 拡張子の番号は、一つ前のファイルより 1 増やした数になります。 ファイル名に拡張を使用した場合、MySQL は更新ログファイルを閉じて開きます。 「4.9.3 更新ログ」節参照. This is the same thing as sending the SIGHUP signal to the mysqld server.
PRIVILEGES mysql データベースの許可テーブルから、権限情報を再読込します。
QUERY CACHE Defragment the query cache to better utilise its memory. This command will not remove any queries from the cache, unlike RESET QUERY CACHE.
TABLES 全ての開いているテーブルを閉じます。使用中のテーブルに も close を強制します。 This also flushes the query cache.
[TABLE | TABLES] tbl_name [,tbl_name...] Flushes only the given tables.
TABLES WITH READ LOCK 全ての開いているテーブルを閉じ、 UNLOCK TABLES を実行するまで全てのテーブルを read lock でロックします。 This is very convenient way to get backups if you have a filesystem, like Veritas,that can take snapshots in time.
STATUS ほとんどのステータス変数を 0 にします。 This is something one should only use when debugging a query.
USER_RESOURCES Resets all user resources to zero. This will enable blocked users to login again. 「4.3.6 Limiting user resources」節参照.

上に示したコマンドは、mysqladmin を使用しても実行できます。 mysqladmin の引数はそれぞれ、flush-hosts, flush-logs, reload, flush-tables となります。

Take also a look at the RESET command used with replication. 「4.5.4 RESET 構文」節参照.

4.5.4 RESET 構文

RESET reset_option [,reset_option] ...

The RESET command is used to clear things. It also acts as an stronger version of the FLUSH command. 「4.5.3 FLUSH 構文」節参照.

To execute RESET, you must have the RELOAD privilege.

Option Description
MASTER Deletes all binary logs listed in the index file, resetting the binlog index file to be empty. In pre-3.23.26 versions, FLUSH MASTER (Master)
SLAVE Makes the slave forget its replication position in the master logs. In pre 3.23.26 versions the command was called FLUSH SLAVE(Slave)
QUERY CACHE Removes all query results from the query cache.

4.5.5 KILL 構文

KILL thread_id

thread_id には、mysqld に接続して走っているスレッドの ID を 空白で区切って指定します。 SHOW PROCESSLIST コマンドで走っているスレッドを知ることができ、 KILL thread_id コマンドでスレッドを KILL できます。

If you have the PROCESS privilege, you can see all threads. If you have the SUPER privilege, you can kill all threads. Otherwise, you can only see and kill your own threads. (version 4.0.2未満では: もし PROCESS 権限があるなら、全てのスレッドを確認し、KILL 出来ます。 そうでなければ、自分のスレッドだけを確認し、KILL する事ができます。)

mysqladmin processlistmysqladmin kill をスレッドの 検査と KILL に使用できます。

When you do a KILL, a thread-specific 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.

4.5.6 SHOW 構文

   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
or SHOW WARNINGS [LIMIT #]
or SHOW ERRORS [LIMIT #]
or SHOW TABLE TYPES

SHOW はデータベース、テーブル、フィールド、サーバーについての情報を与えます。 LIKE wild が使用された場合、wild 文字列は通常の SQL ワイルドカード (`%'`_') です。

4.5.6.1 Retrieving information about Database, Tables, Columns, and Indexes

tbl_name FROM db_name の代わりに、db_name.tbl_name が使用できます。 これら二つは同じです:

mysql> SHOW INDEX FROM mytable FROM mydb;
mysql> SHOW INDEX FROM mydb.mytable;

SHOW DATABASES は MySQL サーバー上のデータベースを示します。 mysqlshow コマンドでも同じ情報が得られます。

SHOW TABLES は指定されたデータベースのテーブルを一覧表示します。 mysqlshow db_name コマンドでも同じ情報が得られます。 In version 4.0.2 you will only see those databases for which you have some kind of privilege, if you don't have the global SHOW DATABASES privilege.

Note: もしユーザーにテーブルに対する権限が無い場合、 テーブルは SHOW TABLESmysqlshow db_name の要求で 表示されません。

SHOW OPEN TABLES はテーブルキャッシュに現在オープン去れているテーブ ルを一覧表示します。 「5.4.7 MySQL はどのようにテーブルのオープン & クローズを行なうか?」節参照. Comment フィールドはテーブ ルが何回 cachedin_use になったかを知らせます。

SHOW COLUMNS は与えられたテーブルのフィールドを表示します。 FULL オプションを指定した場合、各フィールドに持つ権限も得られます。 もしそのフィールドの型が、あなたが CREATE TABLE 構文実行時に与えたものと 違う場合は、 MySQL は、フィールドの型をときおり変更することが あることに注意してください。 「6.5.3.1 暗黙のフィールド定義変更」節参照.

DESCRIBE 文は SHOW COLUMNS と似たような情報を提供します。 「6.6.2 DESCRIBE 構文 (フィールドについての情報を得る)」節参照.

SHOW FIELDSSHOW COLUMNS の別名として使用され、 SHOW KEYSSHOW INDEX の別名として使用されます。 テーブルのフィールドやインデックスは mysqlshow db_name tbl_namemysqlshow -k db_name tbl_name でも見れます。

SHOW INDEX は ODBC でいう SQLStatistics に近い形式で、インデックスの情報を表示します。 以下の項目が返ります:

Column 意味
Table テーブル名
Non_unique インデックスが重複を含まないなら 0
Key_name インデックス名
Seq_in_index インデックスの項目番号。1 から始まります。
Column_name フィールド名。
Collation どのようにこのフィールドがインデックス中で ソートされるか. MySQL ではこれは A (Ascending) か NULL (Not sorted) に なります。
Cardinality インデックス中のユニークな値の数。 これは isamchk -a の実行で更新されます。
Sub_part もしこのフィールドがインデックスに一部分だけ使用 している場合、そのインデックスに使用しているキャラクター数をしめす。 もしキー全 体がインデックスされているなら NULL
Null Contains 'YES' if the column may contain NULL.
Index_type Index method used.
Comment Various remarks. For now, it tells in MySQL < 4.0.2 whether index is FULLTEXT or not.

Note that as the Cardinality is counted based on statistics stored as integers, it's not necessarily accurate for small tables.

The Null and Index_type columns were added in MySQL 4.0.2.

4.5.6.2 SHOW TABLE STATUS

SHOW TABLE STATUS [FROM db_name] [LIKE wild]

SHOW TABLE STATUS (バージョン 3.23 の新機能) は SHOW STATUS のようですが、それぞれのテーブルについてより多くの情報を提供します。 mysqlshow --status db_name コマンドを実行しても同じものが得られます。 以下の項目が返ってきます:

項目 意味
Name テーブル名
Type テーブルの種類. 「7 MySQL テーブル型」節参照.
Row_format レコードの保存形式 (Fixed, Dynamic, or Compressed).
Rows レコード数.
Avg_row_length レコードの平均長.
Data_length データファイルの大きさ.
Max_data_length データファイルの最大長.
Index_length インデックスファイルの大きさ.
Data_free 割り当てられたが使用されていないバイト数.
Auto_increment 次の autoincrement 値.
Create_time テーブル作成時刻.
Update_time 一番最後にデータファイルが更新された時刻.
Check_time 一番最後にテーブルがチェックされた時刻.
Create_options CREATE TABLE で使用された拡張オプション
Comment テーブル作成時につけられたコメント (あるいは、なぜこの テーブルに MySQL がアクセスできないかのいくつかの情報).

InnoDB tables will report the free space in the tablespace in the table comment.

4.5.6.3 SHOW STATUS

SHOW STATUSmysqladmin extended-status と同様に、 サーバからのステータス情報を与えます。出力は次とは異なるかもしれません:

+--------------------------+------------+
| 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      |
+--------------------------+------------+

上に示したステータス変数は以下に示すの意味を持ちます:

Variable Meaning
Aborted_clients クライアントが接続を閉じる前に死んでしまったために中断されたコネクション数。 「A.2.9 Communication Errors / Aborted Connection」節参照.
Aborted_connects MySQL サーバーに接続を試みて失敗した数。 「A.2.9 Communication Errors / Aborted Connection」節参照.
Bytes_received クライアントから受信したバイト数
Bytes_sent クライアントに送信したバイト数
Com_xxx Number of times each xxx command has been executed.
Connections サーバーに接続を試みた数
Created_tmp_disk_tables ステートメント実行中に暗黙のうちに作成されたメモり内にある一時テーブルの数
Created_tmp_tables Number of implicit temporary tables in memory created while executing statements.
Created_tmp_files How many temporary files mysqld has created.
Delayed_insert_threads Number of delayed insert handler threads in use.
Delayed_writes Number of rows written with INSERT DELAYED.
Delayed_errors Number of rows written with INSERT DELAYED for which some error occurred (probably duplicate key).
Flush_commands FLUSH コマンドの実行回数
Handler_commit Number of internal COMMIT commands.
Handler_delete Number of times a row was deleted from a table.
Handler_read_first 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, SELECT col1 FROM foo, assuming that col1 is indexed.
Handler_read_key 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.
Handler_read_next 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.
Handler_read_prev Number of requests to read previous row in key order. This is mainly used to optimise ORDER BY ... DESC.
Handler_read_rnd 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.
Handler_read_rnd_next 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.
Handler_rollback Number of internal ROLLBACK commands.
Handler_update Number of requests to update a row in a table.
Handler_write Number of requests to insert a row in a table.
Key_blocks_used The number of used blocks in the key cache.
Key_read_requests The number of requests to read a key block from the cache.
Key_reads The number of physical reads of a key block from disk.
Key_write_requests The number of requests to write a key block to the cache.
Key_writes The number of physical writes of a key block to disk.
Max_used_connections The maximum number of connections in use simultaneously.
Not_flushed_key_blocks Keys blocks in the key cache that has changed but hasn't yet been flushed to disk.
Not_flushed_delayed_rows Number of rows waiting to be written in INSERT DELAY queues.
Open_tables オープンされているテーブル数
Open_files Number of files that are open.
Open_streams Number of streams that are open (used mainly for logging).
Opened_tables Number of tables that have been opened.
Rpl_status Status of failsafe replication. (Not yet in use).
Select_full_join Number of joins without keys (If this is 0, you should carefully check the index of your tables).
Select_full_range_join Number of joins where we used a range search on reference table.
Select_range Number of joins where we used ranges on the first table. (It's normally not critical even if this is big.)
Select_scan Number of joins where we did a full scan of the first table.
Select_range_check Number of joins without keys where we check for key usage after each row (If this is 0, you should carefully check the index of your tables).
Questions サーバーに送られたクエリの数
Slave_open_temp_tables Number of temporary tables currently open by the slave thread
Slave_running Is ON if this is a slave that is connected to a master.
Slow_launch_threads Number of threads that have taken more than slow_launch_time to create.
Slow_queries long_query_time 以上に時間のかかったクエリの数. 「4.9.5 The Slow Query Log (3.23.28以上)」節参照.
Sort_merge_passes Number of merges passes the sort algoritm have had to do. If this value is large you should consider increasing sort_buffer.
Sort_range Number of sorts that where done with ranges.
Sort_rows Number of sorted rows.
Sort_scan Number of sorts that where done by scanning the table.
ssl_xxx Variables used by SSL; Not yet implemented.
Table_locks_immediate Number of times a table lock was acquired immediately. Available after 3.23.33.
Table_locks_waited 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 optimise your queries, and then either split your table(s) or use replication. Available after 3.23.33.
Threads_cached Number of threads in the thread cache.
Threads_connected 現在開いている接続数
Threads_created Number of threads created to handle connections.
Threads_running スリープ状態になっていないスレッドの数
Uptime サーバーが走っている秒数

上についてのいくつかコメント:

4.5.6.4 SHOW VARIABLES

SHOW [GLOBAL | SESSION] VARIABLES [LIKE wild]

SHOW VARIABLES は MySQL システム変数のいくつかの値を示します。 mysqlshow variables コマンドでも同じ情報が得られます。 もし標準値が適さないなら、ほとんどの変数を mysqld 起動時に コマンドラインのオプションとして与えることにより、変更できます。 「4.1.1 mysqld コマンド行オプション」節参照.

The options GLOBAL and SESSION are new in MySQL 4.0.3. With GLOBAL you will get the variables that will be used for new connections to MySQL. With SESSION you will get the values that are in effect for the current connection. If you are not using either option, SESSION is used.

You can change most options with the SET command. 「5.5.6 SET 構文」節参照.

出力は以下のようになりますが、フォーマットや数はいくぶん違うでしょう:

+---------------------------------+------------------------------+
| Variable_name                   | Value                        |
+---------------------------------+------------------------------|
| back_log                        | 50                           |
| basedir                         | /usr/local/mysql             |
| bdb_cache_size                  | 8388572                      |
| bdb_log_buffer_size             | 32768                        |
| bdb_home                        | /usr/local/mysql             |
| bdb_max_lock                    | 10000                        |
| bdb_logdir                      |                              |
| bdb_shared_data                 | OFF                          |
| bdb_tmpdir                      | /tmp/                        |
| bdb_version                     | Sleepycat Software: ...	 |
| binlog_cache_size               | 32768                        |
| bulk_insert_buffer_size         | 8388608                      |
| character_set                   | latin1                       |
| character_sets                  | latin1 big5 czech euc_kr	 |
| concurrent_insert               | ON                           |
| connect_timeout                 | 5                            |
| convert_character_set           |                              |
| datadir                         | /usr/local/mysql/data/       |
| delay_key_write                 | ON                           |
| delayed_insert_limit            | 100                          |
| delayed_insert_timeout          | 300                          |
| delayed_queue_size              | 1000                         |
| flush                           | OFF                          |
| flush_time                      | 0                            |
| ft_boolean_syntax               | + -><()~*:""&|               |
| ft_min_word_len                 | 4                            |
| ft_max_word_len                 | 254                          |
| ft_max_word_len_for_sort        | 20                           |
| ft_stopword_file                | (built-in)                   |
| have_bdb                        | YES                          |
| have_innodb                     | YES                          |
| have_isam                       | YES                          |
| have_raid                       | NO                           |
| have_symlink                    | DISABLED                     |
| have_openssl                    | YES                          |
| have_query_cache                | YES                          |
| init_file                       |                              |
| innodb_additional_mem_pool_size | 1048576                      |
| innodb_buffer_pool_size         | 8388608                      |
| innodb_data_file_path           | ibdata1:10M:autoextend       |
| innodb_data_home_dir            |                              |
| innodb_file_io_threads          | 4                            |
| innodb_force_recovery           | 0                            |
| innodb_thread_concurrency       | 8                            |
| innodb_flush_log_at_trx_commit  | 0                            |
| innodb_fast_shutdown            | ON                           |
| innodb_flush_method             |                              |
| innodb_lock_wait_timeout        | 50                           |
| innodb_log_arch_dir             |                              |
| innodb_log_archive              | OFF                          |
| innodb_log_buffer_size          | 1048576                      |
| innodb_log_file_size            | 5242880                      |
| innodb_log_files_in_group       | 2                            |
| innodb_log_group_home_dir       | ./                           |
| innodb_mirrored_log_groups      | 1                            |
| interactive_timeout             | 28800                        |
| join_buffer_size                | 131072                       |
| key_buffer_size                 | 16773120                     |
| language                        | /usr/local/mysql/share/...   |
| large_files_support             | ON                           |
| local_infile                    | ON                           |
| locked_in_memory                | OFF                          |
| log                             | OFF                          |
| log_update                      | OFF                          |
| log_bin                         | OFF                          |
| log_slave_updates               | OFF                          |
| log_slow_queries                | OFF                          |
| log_warnings                    | OFF                          |
| long_query_time                 | 10                           |
| low_priority_updates            | OFF                          |
| lower_case_table_names          | OFF                          |
| max_allowed_packet              | 1047552                      |
| max_binlog_cache_size           | 4294967295                   |
| max_binlog_size                 | 1073741824                   |
| 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_user_connections            | 0                            |
| max_tmp_tables                  | 32                           |
| max_write_lock_count            | 4294967295                   |
| myisam_max_extra_sort_file_size | 268435456                    |
| myisam_max_sort_file_size       | 2147483647                   |
| myisam_recover_options          | force                        |
| 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                        | /usr/local/mysql/name.pid    |
| port                            | 3306                         |
| protocol_version                | 10                           |
| read_buffer_size                | 131072                       |
| read_rnd_buffer_size            | 262144                       |
| rpl_recovery_rank               | 0                            |
| query_cache_limit               | 1048576                      |
| query_cache_size                | 0                            |
| query_cache_type                | ON                           |
| safe_show_database              | OFF                          |
| server_id                       | 0                            |
| slave_net_timeout               | 3600                         |
| skip_external_locking           | ON                           |
| skip_networking                 | OFF                          |
| skip_show_database              | OFF                          |
| slow_launch_time                | 2                            |
| socket                          | /tmp/mysql.sock              |
| sort_buffer_size                | 2097116                      |
| sql_mode                        | 0                            |
| table_cache                     | 64                           |
| table_type                      | MYISAM                       |
| thread_cache_size               | 3                            |
| thread_stack                    | 131072                       |
| tx_isolation                    | READ-COMMITTED               |
| timezone                        | EEST                         |
| tmp_table_size                  | 33554432                     |
| tmpdir                          | /tmp/:/mnt/hd2/tmp/          |
| version                         | 4.0.4-beta                   |
| wait_timeout                    | 28800                        |
+---------------------------------+------------------------------+

Each option is described here. Values for buffer sizes, lengths, and stack sizes are given in bytes. これらの値の後ろに `K'`M' を追加すると、キロバイト、 メガバイトになります。 例えば、16M は16メガバイトを示します。大文字小文字の区別はなく、 16M16m は同じ意味になります。

The manual section that describes tuning MySQL contains some information of how to tune the above variables. 「5.5.2 サーバーパラメーターのチューニング」節参照.

4.5.6.5 SHOW LOGS

SHOW LOGS shows you status information about existing log files. It currently only displays information about Berkeley DB log files.

4.5.6.6 SHOW PROCESSLIST

SHOW [FULL] PROCESSLIST はどのスレッドが走っているかを表示します。 mysqlshow processlist コマンドでも同じ情報が得られます。 もし SUPER 権限があるなら、全てのスレッドがみれます。 しかし権限がないなら、自分のスレッドしか見れません。 「4.5.5 KILL 構文」節参照. (SUPERは4.0.2以上。4.0.2未満では PROCESS権限があるだけで全てのスレッドが見れた) FULL オプションを使用しない場合、各クエリの最初の100文字だけが表示 されます。

Starting from 4.0.12, MySQL reports the hostname for TCP/IP connections as hostname:client_port to make it easier to find out which client is doing what.

This command is very useful if you get the 'too many connections' error message and want to find out what's going on. MySQL reserves one extra connection for a client with the SUPER 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).

Some states commonly seen in mysqladmin processlist

Most states are very quick operations. If threads last in any of these states for many seconds, there may be a problem around that needs to be investigated.

There are some other states that are not mentioned previously, but most of these are only useful to find bugs in mysqld.

4.5.6.7 SHOW GRANTS

SHOW GRANTS FOR user はユーザの許可を複製するために発行する必要があ る grant コマンドをリストします。

mysql> SHOW GRANTS FOR root@localhost;
+---------------------------------------------------------------------+
| Grants for root@localhost                                           |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION |
+---------------------------------------------------------------------+

To list grants for the current session one may use CURRENT_USER() function (new in version 4.0.6) to find out what user the session was authentificated as. 「6.3.6.2 その他の関数」節参照.

4.5.6.8 SHOW CREATE TABLE

Shows a CREATE TABLE statement that will create the given table:

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

SHOW CREATE TABLE will quote table and column names according to SQL_QUOTE_SHOW_CREATE option. 「5.5.6 SET 構文」節.

4.5.6.9 SHOW WARNINGS | ERRORS

SHOW WARNINGS [LIMIT #]
SHOW ERRORS [LIMIT #]

This command is implemented in MySQL 4.1.0.

It shows the errors, warnings and notes that one got for the last command. The errors/warnings are reset for each new command that uses a table.

The MySQL server sends back the total number of warnings and errors you got for the last commend; This can be retrieved by calling mysql_warning_count().

Up to max_error_count messages are stored (Global and thread specific variable).

You can retrieve the number of errors from @error_count and warnings from @warning_count.

SHOW WARNINGS shows all errors, warnings and notes you got for the last command while SHOW ERRORS only shows you the errors.

mysql> DROP TABLE IF EXISTS no_such_table;
mysql> SHOW WARNINGS;

+-------+------+-------------------------------+
| Level | Code | Message                       |
+-------+------+-------------------------------+
| Note  | 1051 | Unknown table 'no_such_table' |
+-------+------+-------------------------------+

4.5.6.10 SHOW TABLE TYPES

SHOW TABLE TYPES

This command is implemented in MySQL 4.1.0.

SHOW TABLE TYPES shows you status information about the table types. This is particulary useful for checking if a table type is supported; or to see what is the default table type is.

mysql> SHOW TABLE TYPES;

+--------+---------+-----------------------------------------------------------+
| Type   | Support | Comment                                                   |
+--------+---------+-----------------------------------------------------------+
| MyISAM | DEFAULT | Default type from 3.23 with great performance             |
| HEAP   | YES     | Hash based, stored in memory, useful for temporary tables |
| MERGE  | YES     | Collection of identical MyISAM tables                     |
| ISAM   | YES     | Obsolete table type; Is replaced by MyISAM                |
| InnoDB | YES     | Supports transactions, row-level locking and foreign keys |
| BDB    | NO      | Supports transactions and page-level locking              |
+--------+---------+-----------------------------------------------------------+
6 rows in set (0.00 sec)

The 'Support' option DEFAULT indicates whether the perticular table type is supported, and which is the default type. If the server is started with --default-table-type=InnoDB, then the InnoDB 'Support' field will have the value DEFAULT.

4.5.6.11 SHOW PRIVILEGES

SHOW PRIVILEGES

This command is implemented in MySQL 4.1.0.

SHOW PRIVILEGES shows the list of system privileges that the underlying MySQL server supports.

mysql> show privileges;
+------------+--------------------------+-------------------------------------------------------+
| Privilege  | Context                  | Comment                                               |
+------------+--------------------------+-------------------------------------------------------+
| Select     | Tables                   | To retrieve rows from table                           |
| Insert     | Tables                   | To insert data into tables                            |
| Update     | Tables                   | To update existing rows                               |
| Delete     | Tables                   | To delete existing rows                               |
| Index      | Tables                   | To create or drop indexes                             |
| Alter      | Tables                   | To alter the table                                    |
| Create     | Databases,Tables,Indexes | To create new databases and tables                    |
| Drop       | Databases,Tables         | To drop databases and tables                          |
| Grant      | Databases,Tables         | To give to other users those privileges you possess   |
| References | Databases,Tables         | To have references on tables                          |
| Reload     | Server Admin             | To reload or refresh tables, logs and privileges      |
| Shutdown   | Server Admin             | To shutdown the server                                |
| Process    | Server Admin             | To view the plain text of currently executing queries |
| File       | File access on server    | To read and write files on the server                 |
+------------+--------------------------+-------------------------------------------------------+
14 rows in set (0.00 sec)

4.6 MySQL Localisation and International Usage

4.6.1 データとソートに使用されるキャラクター・セット

デフォルトでは、MySQL は スウェーデン語/フィンランド語に一致する ISO8859-1 (Latin1) キャラクター・セットをソートに使用します。これは USA と西 ヨーロッパに適したキャラクター・セットです。

All standard MySQL binaries are compiled with --with-extra-charsets=complex. This will add code to all standard programs to be able to handle latin1 and all multi-byte character sets within the binary. Other character sets will be loaded from a character-set definition file when needed.

キャラクター・セットは名前として許される文字と、ORDER BYGROUP BY コマンドによってソートされる方法を決定します。 キャラクターセットは、名前として使用してもよい文字と SELECT 構文中の ORDER BYGROUP BY コマンドを用いたソート方法を決定します。

You can change the character set with the --default-character-set option when you start the server. The character sets available depend on the --with-charset=charset and --with-extra-charsets= list-of-charset | complex | all options to configure, and the character set configuration files listed in `SHAREDIR/charsets/Index'. 「2.3.3 典型的な configure オプション」節参照.

もし MySQL が実行中にキャラクター・セットを変更するならば、 (これはソートの順番も変わります)、全てのテーブルに対して myisamchk -r -q --set-character-set=charset を実行しなくてはなりません。 インデックスがただしい順番で並んでいないかもしれないからです。

クライアントが MySQL サーバに接続したとき、サーバは使用している デフォルトのキャラクター・セットをクライアントに送ります。 これを受け取ったクライアントは、キャラクター・セットを切り替えます。

SQL クエリの文字列をエスケープする場合には、 mysql_real_escape_string() を 使用するべきです。 mysql_real_escape_string() は、最初のパラメタとして MySQL へのコネクション・ハンドルを与える以外は、 古い mysql_escape_string() 関数と同じです。

もしクライアントがサーバがインストールされているところ(パス)とは違う パスでコンパイルされていて、 MySQL をコンフィギャしたユーザーが すべてのキャラクター・セットを MySQL バイナリに含めていない場合には、 どこに必要とされるキャラクター・セットの追加情報があるかを、クライアントに 教えなくてはなりません。もしサーバとクライアントが違うキャラクター・セットで動作し ているならば。

これは MySQL オプションファイルに次のように記述することで可能です:

[client]
character-sets-dir=/usr/local/mysql/share/mysql/charsets

ここで、パスはダイナミック MySQL キャラクター・セットが保存されている場所 です。

クライアントに、キャラクター・セットを強制することも可能です:

[client]
default-character-set=character-set-name

しかし通常はこれは不要です。

4.6.1.1 German character set

To get German sorting order, you should start mysqld with --default-character-set=latin1_de. This will give you the following characteristics.

When sorting and comparing string's the following mapping is done on the strings before doing the comparison:

a  ->  ae
o  ->  oe
u  ->  ue
s  ->  ss

All accented characters, are converted to their un-accented uppercase counterpart. All letters are converted to uppercase.

When comparing strings with LIKE the one -> two character mapping is not done. All letters are converted to uppercase. Accent are removed from all letters except: , , , , and .

4.6.2 Non-English Error Messages

mysqld は次の言語でエラーメッセージを提供できます: チェコ語, デンマーク語, オランダ語, 英語(デフォルト), Estonia, フランス語, ドイツ語, ギリシャ語, ハンガリー語, イタリア語, 日本語, 韓国語, ノルウェー語, 新ノルウェー語,ポーランド語, ポルトガル語, スペイン語そしてスウェーデン語。

ある言語で mysqld を開始するためには --language=lang また は -L lang スイッチの一つを使います:

shell> mysqld --language=swedish

or:

shell> mysqld --language=/usr/local/share/swedish

言語名は全て小文字であることに注意してください。

言語ファイルは(デフォルトでは)次の場所にあります。 `mysql_base_dir/share/LANGUAGE/'.

エラーメッセージファイルを更新したい場合は、 `errmsg.txt' ファイルを編集し、 `errmsg.sys' ファイルを作成するために以下のように実行します:

shell> comp_err errmsg.txt errmsg.sys

もし MySQL を新しいものにアップグレードしたなら、以前修正した部分と同じ ところに、 新しい `errmsg.txt' ファイルに修正をほどこしてください。

4.6.3 新しいキャラクター・セットの追加

他のキャラクタ・セットを MySQL に追加するには、 以下の手順で行ないます。

そのキャラクター・セットが、simple か complex かを決めます。 もしそのキャラクター・セットがソートを行なうために特別な文字参照の ルーチンを必要としなくて、マルチバイト文字のサポートも必要としないのであれば、 そのキャラクター・セットは simple です。 もしどちらかの特徴を必要とするのであれば、それは complex です。

例えば、latin1danish は simple キャラクター・セットで、 big5czech は complex キャラクター・セットです。

以下のセクションでは、あなたがキャラクター・セットに MYSET という名前を つけていると仮定します。

For a simple character set do the following:

  1. MYSET を `sql/share/charsets/Index' ファイルの最後に追加。 一意な番号を与えます。
  2. `sql/share/charsets/MYSET.conf' ファイルを作成. (`sql/share/charsets/latin1.conf' をベースにしてよいでしょう). The syntax for the file very simple: 4.6.4 The Character Definition Arrays」節参照.
  3. Add the character set name to the CHARSETS_AVAILABLE and COMPILED_CHARSETS lists in configure.in.
  4. Reconfigure, recompile, and test.

For a complex character set do the following:

  1. `strings/ctype-MYSET.c' ファイルを MySQL のソースディレクトリ以下 に作成します。
  2. MYSET を `sql/share/charsets/Index' ファイルの最後に追加。 一意な番号を与えます。
  3. 必要な定義されるものを調べるために、既存の `ctype-*.c' ファイルの一つを見てく ださい。このファイル中で使用する配列の名前は、 ctype_MYSET, to_lower_MYSET のようにしなければいけないことに注意し てください。 This corresponds to the arrays in the simple character set. 「4.6.4 The Character Definition Arrays」節参照. For a complex character set
  4. `ctype-*.c' ファイルの先頭付近に、以下のようなコメントを書きます:
    /*
     * 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
     */
    
    configure プログラムは、MySQL ライブラリに自動的に キャラクター・セットを含めるために、このコメントを使用します。 The strxfrm_multiply and mbmaxlen lines will be explained in the following sections. Only include these if you need the string collating functions or the multi-byte character set functions, respectively.
  5. 以下の関数を作成しなくてはなりません: 4.6.5 String Collating Support」節参照.
  6. キャラクター・セット名を、configure.in 中の CHARSETS_AVAILABLECOMPILED_CHARSETS に追加します。
  7. Reconfigure, recompile, and test.

The file `sql/share/charsets/README' includes some more instructions.

If you want to have the character set included in the MySQL distribution, mail a patch to internals@lists.mysql.com.

4.6.4 The Character Definition Arrays

to_lower[]to_upper[] は、それぞれのキャラクターセットに於ける 大文字、小文字の対応を定義した、単純な配列です。 例えば:

to_lower['A'] should contain 'a'
to_upper['a'] should contain 'A'

sort_order[] は文字がどのように比較され、ソートされるべきかのマップです。 本当に多くの(しかし全てのキャラクタセットではありません)セットでは、 これは to_upper[] と同じです (ケース非依存ソート)。 MySQL は sort_order[character] の値を元に文字をソートします。 MySQL will sort characters based on the value of sort_order[character]. For more complicated sorting rules, see the discussion of string collating below. 「4.6.5 String Collating Support」節参照.

ctype[] は各文字を説明するビットの配列で、1かたまりのビット列が1文字を定 義します。 ( to_lower[], to_upper[],sort_order[]は、文字の値でインデッ クスされますが、 ctype[]は文字の値+1 でインデックスされます。

これは EOF を操作するためにずいぶん前から使われているので、この方法を使用してい ます。) `m_ctype.h' に次のビットマスクの定義を見ることができます:

#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 */

それぞれの文字に対する ctype[] は、文字を確定するために ビット列と組になっていなければなりません。 たとえば、'A' は大文字定義 (_U) と 16進定義 (_X) 両方ともに 属するので、ctype['A'+1] は以下の値を含まなくてはなりません:

_U + _X = 01 + 0200 = 0201

4.6.5 String Collating Support

If the sorting rules for your language are too complex to be handled with the simple 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 strxfrm_multiply_MYSET=N value in the special comment at the top of the file. N should be set to the maximum ratio the strings may grow during my_strxfrm_MYSET (it must be a positive integer).

4.6.6 マルチバイト文字のサポート

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 `ctype-'charset'.c' files in the `strings' directory.

You must specify the mbmaxlen_MYSET=N value in the special comment at the top of the source file. N should be set to the size in bytes of the largest character in the set.

4.6.7 Problems With Character Sets

If you try to use a character set that is not compiled into your binary, you can run into a couple of different problems:

For MyISAM tables, you can check the character set name and number for a table with myisamchk -dvv table_name.

4.7 MySQL サーバー サイド の スクリプトとユーティリティ

4.7.1 Overview of the Server-Side Scripts and Utilities

All MySQL programs take many different options. However, every MySQL program provides a --help option that you can use to get a full description of the program's different options. For example, try mysql --help.

You can override default options for all standard programs with an option file. 「4.1.2 `my.cnf' オプションファイル」節.

The following list briefly describes the server-side MySQL programs:

myisamchk
Utility to describe, check, optimise, and repair MySQL tables. Because myisamchk has many functions, it is described in its own chapter. 「4 データベース管理」節参照.
make_binary_distribution
Makes a binary release of a compiled MySQL. This could be sent by FTP to `/pub/mysql/Incoming' on support.mysql.com for the convenience of other MySQL users.
mysqlbug
The MySQL bug report script. This script should always be used when filing a bug report to the MySQL list.
mysqld
The SQL daemon. This should always be running.
mysql_install_db
Creates the MySQL grant tables with default privileges. This is usually executed only once, when first installing MySQL on a system.

4.7.2 safe_mysqld, The Wrapper Around mysqld

Note that in MySQL 4.0 safe_mysqld was renamed to mysqld_safe.

safe_mysqld is the recommended way to start a mysqld daemon on Unix. 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 --mysqld=# or --mysqld-version=# safe_mysqld will use an executable named mysqld-max if it exists. If not, safe_mysqld will start mysqld. This makes it very easy to test to use mysqld-max instead of mysqld; just copy mysqld-max to where you have mysqld and it will be used.

Normally one should never edit the safe_mysqld script, but instead put the options to safe_mysqld in the [safe_mysqld] section in the `my.cnf' file. safe_mysqld will read all options from the [mysqld], [server] and [safe_mysqld] sections from the option files. 「4.1.2 `my.cnf' オプションファイル」節参照.

Note that all options on the command-line to safe_mysqld are passed to mysqld. If you wants to use any options in safe_mysqld that mysqld doesn't support, you must specify these in the option file.

Most of the options to safe_mysqld are the same as the options to mysqld. 「4.1.1 mysqld コマンド行オプション」節参照.

safe_mysqld supports the following options:

--basedir=path
--core-file-size=#
Size of the core file mysqld should be able to create. Passed to ulimit -c.
--datadir=path
--defaults-extra-file=path
--defaults-file=path
--err-log=path (this is marked obsolete in 4.0; Use --log-error instead)
--log-error=path
Write the error log to the above file. 「4.9.1 The Error Log」節参照.
--ledir=path
Path to mysqld
--log=path
--mysqld=mysqld-version
Name of the mysqld version in the ledir directory you want to start.
--mysqld-version=version
Similar to --mysqld= but here you only give the suffix for mysqld. For example if you use --mysqld-version=max, safe_mysqld will start the ledir/mysqld-max version. If the argument to --mysqld-version is empty, ledir/mysqld will be used.
--no-defaults
--open-files-limit=#
Number of files mysqld should be able to open. Passed to ulimit -n. Note that you need to start safe_mysqld as root for this to work properly!
--pid-file=path
--port=#
--socket=path
--timezone=#
Set the timezone (the TZ) variable to the value of this parameter.
--user=#

The 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 MySQL, even if these install the server in slightly different locations. safe_mysqld expects one of these conditions to be true:

Because safe_mysqld will try to find the server and databases relative to its own working directory, you can install a binary distribution of MySQL anywhere, as long as you start safe_mysqld from the MySQL installation directory:

shell> cd mysql_installation_directory
shell> bin/safe_mysqld &

If safe_mysqld fails, even when invoked from the MySQL installation directory, you can modify it to use the path to mysqld and the pathname options that are correct for your system. Note that if you upgrade MySQL in the future, your modified version of safe_mysqld will be overwritten, so you should make a copy of your edited version that you can reinstall.

4.7.3 mysqld_multi, 複数の MySQL サーバーを管理するプログラム

mysqld_multi is meant for managing several mysqld processes that listen for connections on different Unix sockets and TCP/IP ports. このプログラムは、`my.cnf' ファイル (もしくは、--config-file=... で与えられたファイル)の [mysqld#] (ここで # は 1から始まる数字) と命名されたセクションを探します。 This number is referred to in the following discussion as the option group number, or GNR. Group numbers distinquish option groups from one another and are used as arguments to mysqld_multi to specify which servers you want to start, stop, or obtain status for. Options listed in these groups should be the same as you would use in the usual [mysqld] group used for starting mysqld. (See, for example, 「2.4.3 MySQL の自動起動と自動停止」節.) However, for mysqld_multi, be sure that each group includes options for values such as the port, socket, etc., to be used for each individual mysqld process.

mysqld_multi is invoked using the following syntax:

Usage: mysqld_multi [OPTIONS] {start|stop|report} [GNR,GNR,GNR...]
か     mysqld_multi [OPTIONS] {start|stop|report} [GNR-GNR,GNR,GNR-GNR,...]

Each GNR represents an option group number. You can start, stop or report any GNR, or several of them at the same time. For an example of how you might set up an option file, use this command:

shell> mysqld_multi --example

The GNR values in the list can be comma-separated or combined with a dash; in the latter case, all the GNRs between GNR1-GNR2 will be affected. GNR が引数に与えられなかった場合は、 全てのグループが、起動、停止、レポートされます。 GNR のリストには空白は許されません。スペースの後ろは無視されます。

mysqld_multi は以下のオプションをサポートします:

--config-file=...
Alternative config file. Note: This will not affect this program's own options (group [mysqld_multi]), but only groups [mysqld#]. Without this option, everything will be searched from the ordinary `my.cnf' file.
--example
オプション例を表示.
--help
ヘルプを表示して終了
--log=...
ログファイル。フルパスで与えます。 もしファイルが存在している場合は、ログはファイルに追加されます。
--mysqladmin=...
サーバーの シャットダウン に使用する mysqladmin バイナリの指定
--mysqld=...
使用する mysqld バイナリの指定。 safe_mysqld をこのオプションに指定することも可能です。 指定されたオプションは mysqld に渡されます。 Just make sure you have mysqld in your environment variable PATH or fix safe_mysqld.
--no-log
ログをログファイルではなく標準出力に書きだします。 デフォルトでは、ログファイルに書き込むモードです。
--password=...
mysqladmin で使用するユーザーのパスワード.
--tcp-ip
Connect to the 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, connections are made using the Unix socket.
--user=...
mysqladmin で使用する MySQL ユーザー.
--version
バージョンを表示して終了.

Some notes about mysqld_multi:

4.1.4 同一マシン上に複数の MySQL サーバーを走らせる」節参照.

This is an example of the config file on behalf of mysqld_multi.

# 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

4.1.2 `my.cnf' オプションファイル」節参照.

4.7.4 myisampack, MySQL の圧縮された読み込み専用テーブルジェネレータ

myisampack is used to compress MyISAM tables, and pack_isam is used to compress ISAM tables. Because ISAM tables are deprecated, we will only discuss myisampack here, but everything said about myisampack should also be true for pack_isam.

myisampack はテーブル内の各項目を別々に圧縮するように働きます。展開のため の情報は、テーブルがオープンされた時にメモリに読まれます。これは、正確に1レコー ドだけを展開する必要があるような、個々のレコードへのアクセス時にとても良 い性能を与えます。MSDOS 上の Stacker 使用時のように、ディスクブロックは そんなに大きくありません。 通常、myisampack はデータファイルを 40〜70% にパックします。

MySQL は圧縮されたテーブルでメモリマップ (mmap()) を使用します。 mmap() が働かない場合は、通常のファイルの読み書きを使用します。

Please note the following:

myisampack is invoked like this:

shell> myisampack [options] filename ...

それぞれのファイル名はインデックスファイル(`.MYI')の名前です。 もしデータディレクトリにカレントディレクトリを移動していないなら、 ファイルのパスを指定しなくてはなりません。`.MYI' 拡張子は 省略することが可能です。

myisampack は以下のオプションをサポートします:

-b, --backup
tbl_name.OLD としてバックアップを作成します.
-#, --debug=debug_options
デバック出力。debug_options'd:t:o,filename'.
-f, --force
一時ファイルが存在していようが、サイズが大きくなろうが、強制的にテーブルを パックします。 myisampack はテーブルを圧縮している間、 一時ファイルを `tbl_name.TMD' という名前で作成します。 もし myisampack を途中で kill した場合、 `.TMD' ファイルが消されて いない事があります。通常、myisampack`tbl_name.TMD' ファイルが 既に存在する場合はエラーで終了します。 --force を使用すると、 myisampack はそのような場合でもテーブルをパックします。
-?, --help
ヘルプメッセージを出力して終了。
-j big_tbl_name, --join=big_tbl_name
全てのテーブルをコマンドラインで指定した big_tbl_name 一つに まとめます。結合される全てのテーブル定義は同じでなければなりません (同じ項目名、同じ項目型、同じインデックス、等)
-p #, --packlength=#
Specify the record length storage size, in bytes. The value should be 1, 2, or 3. (myisampack stores all rows with length pointers of 1, 2, or 3 bytes. In most normal cases, 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, myisampack will print a note that the next time you pack the same file, you could use a shorter record length.)
-s, --silent
Silent mode. Write output only when errors occur.
-t, --test
Don't actually pack table, just test packing it.
-T dir_name, --tmp_dir=dir_name
Use the named directory as the location in which to write the temporary table.
-v, --verbose
Verbose mode. Write information about progress and packing result.
-V, --version
Display version information and exit.
-w, --wait
Wait and retry if table is in use. If the mysqld server was invoked with the --skip-external-locking option, it is not a good idea to invoke myisampack if the table might be updated during the packing process.

The sequence of commands shown here illustrates a typical table compression session:

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

The information printed by myisampack is described here:

normal
The number of columns for which no extra packing is used.
empty-space
The number of columns containing values that are only spaces; these will occupy 1 bit.
empty-zero
The number of columns containing values that are only binary 0's; these will occupy 1 bit.
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 INTEGER column may be changed to MEDIUMINT).
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.
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.
table-lookup
The column had only a small number of different values, which were converted to an ENUM before Huffman compression.
zero
The number of columns for which all values are zero.
Original trees
The initial number of Huffman trees.
After join
The number of distinct Huffman trees left after joining trees to save some header space.

After a table has been compressed, myisamchk -dvv prints additional information about each field:

Type
The field type may contain the following descriptors:
constant
All rows have the same value.
no endspace
Don't store endspace.
no endspace, not_always
Don't store endspace and don't do end space compression for all values.
no endspace, no empty
Don't store endspace. Don't store empty values.
table-lookup
The column was converted to an ENUM.
zerofill(n)
The most significant n bytes in the value are always 0 and are not stored.
no zeros
Don't store zeros.
always zero
0 values are stored in 1 bit.
Huff tree
The Huffman tree associated with the field.
Bits
The number of bits used in the Huffman tree.

After you have run pack_isam/myisampack you must run isamchk/myisamchk to re-create the index. At this time you can also sort the index blocks and create statistics needed for the MySQL optimiser to work more efficiently:

myisamchk -rq --analyze --sort-index table_name.MYI
isamchk   -rq --analyze --sort-index table_name.ISM

After you have installed the packed table into the MySQL database directory you should do mysqladmin flush-tables to force mysqld to start using the new table.

If you want to unpack a packed table, you can do this with the --unpack option to isamchk or myisamchk.

4.7.5 mysqld-max, An Extended mysqld Server

mysqld-max is the MySQL server (mysqld) configured with the following configure options:

Option Comment
--with-server-suffix=-max Add a suffix to the mysqld version string.
--with-innodb Support for InnoDB tables.
--with-bdb Support for Berkeley DB (BDB) tables
CFLAGS=-DUSE_SYMDIR Symbolic links support for Windows.

You can find the MySQL-max binaries at http://www.mysql.com/downloads/mysql-max-3.23.html.

The Windows MySQL binary distributions includes both the standard mysqld.exe binary and the mysqld-max.exe binary. http://www.mysql.com/downloads/mysql-3.23.html. 「2.1.2 Windows への MySQL のインストール」節参照.

Note that as InnoDB and Berkeley DB are not available for all platforms, some of the Max binaries may not have support for both of these. You can check which table types are supported by doing the following query:

mysql> SHOW VARIABLES LIKE "have_%";
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| have_bdb      | YES   |
| have_innodb   | NO    |
| have_isam     | YES   |
| have_raid     | NO    |
| have_openssl  | NO    |
+---------------+-------+

The meaning of the values are:

Value Meaning
YES The option is activated and usable.
NO MySQL is not compiled with support for this option.
DISABLED The xxxx option is disabled because one started mysqld with --skip-xxxx or because one didn't start mysqld with all needed options to enable the option. In this case the hostname.err file should contain a reason for why the option is disabled.

Note: To be able to create InnoDB tables you must edit your startup options to include at least the innodb_data_file_path option. 「7.5.2 InnoDB 起動オプション」節参照.

To get better performance for BDB tables, you should add some configuration options for these too. 「7.6.3 BDB startup options」節参照.

safe_mysqld will automatically try to start any mysqld binary with the -max suffix. This makes it very easy to test out a another mysqld binary in an existing installation. Just run configure with the options you want and then install the new mysqld binary as mysqld-max in the same directory where your old mysqld binary is. 「4.7.2 safe_mysqld, The Wrapper Around mysqld」節参照.

The mysqld-max RPM uses the above mentioned safe_mysqld feature. It just installs the mysqld-max executable and safe_mysqld will automatically use this executable when safe_mysqld is restarted.

The following table shows which table types our standard MySQL-Max binaries includes:

System BDB InnoDB
AIX 4.3 N Y
HP-UX 11.0 N Y
Linux-Alpha N Y
Linux-Intel Y Y
Linux-IA64 N Y
Solaris-Intel N Y
Solaris-SPARC Y Y
Caldera (SCO) OSR5 Y Y
UnixWare Y Y
Windows/NT Y Y

4.8 MySQL Client-Side Scripts and Utilities

4.8.1 Overview of the Client-Side Scripts and Utilities

All MySQL clients that communicate with the server using the mysqlclient library use the following environment variables:

Name Description
MYSQL_UNIX_PORT The default socket; used for connections to localhost
MYSQL_TCP_PORT The default TCP/IP port
MYSQL_PWD The default password
MYSQL_DEBUG Debug-trace options when debugging
TMPDIR The directory where temporary tables/files are created

Use of MYSQL_PWD is insecure. 「4.2.8 MySQL サーバーに接続」節参照.

The `mysql' client uses the file named in the MYSQL_HISTFILE environment variable to save the command-line history. The default value for the history file is `$HOME/.mysql_history', where $HOME is the value of the HOME environment variable. 「F Environment Variables」節参照.

All MySQL programs take many different options. However, every MySQL program provides a --help option that you can use to get a full description of the program's different options. For example, try mysql --help.

You can override default options for all standard client programs with an option file. 「4.1.2 `my.cnf' オプションファイル」節.

The following list briefly describes the client-side MySQL programs:

msql2mysql
A shell script that converts mSQL programs to MySQL. It doesn't handle all cases, but it gives a good start when converting.
mysqlaccess
A script that checks the access privileges for a host, user, and database combination.
mysqladmin
Utility for performing administrative operations, such as creating or dropping databases, reloading the grant tables, flushing tables to disk, and reopening log files. mysqladmin can also be used to retrieve version, process, and status information from the server. 「4.8.3 mysqladmin, MySQL サーバーの管理」節参照.
mysqldump
Dumps a MySQL database into a file as SQL statements or as tab-separated text files. Enhanced freeware originally by Igor Romanenko. 「4.8.5 mysqldump, データベースとテーブルから、構造とデータをダンプ」節参照.
mysqlimport
Imports text files into their respective tables using LOAD DATA INFILE. 「4.8.7 mysqlimport, テキストファイルからデータを取り込む」節参照.
mysqlshow
Displays information about databases, tables, columns, and indexes.
replace
A utility program that is used by msql2mysql, but that has more general applicability as well. 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 a and b in the given files:
shell> replace a b b a -- file1 file2 ...

4.8.2 mysql, コマンドラインツール

mysql はシンプルな SQL shell です(GNU readline を持っています). これは対話モードと、非対話モードを持っています。 対話モードで使用された場合、 クエリの結果は ASCII テーブルのフォーマットで与えられます。 非対話モードで使用された場合(例えばフィルターとして)、結果はタブ区切りの フォーマットで返ります。 (出力フォーマットはコマンドラインのオプションで変更できます) 以下のようにしてスクリプトを実行できます:

shell> mysql database < script.sql > output.tab

もしクライアントでメモリー不足の問題が出た場合、--quick オプションを 使用します! これは mysql に、結果セットを取得する際に、 mysql_store_result() ではなく mysql_use_result() を 使用させます。

mysql の使用はとても簡単です: mysql databasemysql --user=user_name --password=your_password d atabase のようにしてはじめます。 SQL 文を入力し、一文を `;', `\g' or `\G' で終え、 RETURN/ENTER を押します。

mysql は以下のオプションをサポートします:

-?, --help
help を表示して終了
-A, --no-auto-rehash
自動リハッシュをしない。 テーブルとフィールドの取得には 'rehash' を 使用しなくてはなりません。 これは mysql の起動を速くします。
--prompt=...
Set the mysql prompt to specified format.
-b, --no-beep
Turn off beep-on-error.
-B, --batch
結果をタブ区切り、1レコードは1行で出力します。 history ファイルは使用しません。
--character-sets-dir=...
Directory where character sets are located.
-C, --compress
サーバー・クライアント間の通信を圧縮します
-#, --debug[=...]
デバッグログ。 デフォルトは 'd:t:o,/tmp/mysql.trace'
-D, --database=...
使用するデータベース。 これは my.cnf ファイルが便利です
--default-character-set=...
Set the default character set.
-e, --execute=...
コマンドを実行して終了。 (Output like with --batch)
-E, --vertical
垂直にレコードを出力します。 このオプションを指定していなくても、 SQL 文を \G で終了した場合、同じように垂直に出力します。
-f, --force
SQL エラーがおきたとしても、処理を続けます
-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.
-G, --enable-named-commands
Named commands are enabled. Long format commands are allowed as well as shortened \* commands.
-i, --ignore-space
関数名の後ろについたスペースを無視します
-h, --host=...
指定したホストに接続します
-H, --html
結果を HTML フォーマットで返します
-X, --xml
Produce XML output.
-L, --skip-line-numbers
エラーの起きた行の番号を書きません。 これはエラーメッセージを含んだ結果を 比較する場合に便利です。
--no-pager
Disable pager and print to stdout. See interactive help (\h) also.
--no-tee
Disable outfile. See interactive help (\h) also.
-n, --unbuffered
それぞれのクエリ毎にバッファをフラッシュします
-N, --skip-column-names
結果に、フィールド名を書き出しません。
-O, --set-variable var=option
変数に値をセットします。 --help lists variables. Please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own.
-o, --one-database
デフォルトのデータベースのみ更新します。 これは update ログファイルを 使用して更新する場合、他のデータベースの更新を避けたい時に便利です。
--pager[=...]
Output type. Default is your ENV variable 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.
-p[password], --password[=...]
サーバーに接続する際のパスワード。 もしパスワードがコマンドラインに 指定されていなかった場合、tty 上でパスワードが問い合わされます。 -p を使用する場合、このオプションとパスワードの間には スペースが不要だということに注意してください。
-P port_num, --port=port_num
接続に使用する TCP/IP ポート番号
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-q, --quick
結果をキャッシュせず、一レコードづつ出力します。 これはもし出力を中止した場合、サーバーを遅くします。 ヒストリファイルは使用しません。
-r, --raw
エスケープ処理をしないで値を書き出します。 --batch とともに使用されます
--reconnect
If the connection is lost, automatically try to reconnect once to the server.
-s, --silent
静粛モード
-S --socket=...
接続に使用する ソケットファイル
-t --table
表の形式で出力します。 これは batch モード以外でのデフォルトです。
-T, --debug-info
Print some debug information at exit.
--tee=...
Append everything into outfile. See interactive help (\h) also. Does not work in batch mode.
-u, --user=#
ログインユーザー名
-U, --safe-updates[=#], --i-am-a-dummy[=#]
キーを使用する UPDATE and DELETE のみを行います。 これは後述します。 このオプションをもし my.cnf に書いている場合は、 --safe-updates=0 でこのオプションをリセットできます。
-v, --verbose
冗長出力。 (-v -v -v は表形式の出力を与える)
-V, --version
バージョンを表示して終了
-w, --wait
もし接続が落ちた場合、中断しないで、待って、再試行します。

You can also set the following variables with -O or --set-variable; please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own:

Variable Name Default Description
connect_timeout 0 Number of seconds before timeout connection.
max_allowed_packet 16777216 Max packetlength to send/receive from to server
net_buffer_length 16384 Buffer for TCP/IP and socket communication
select_limit 1000 Automatic limit for SELECT when using --i-am-a-dummy
max_join_size 1000000 Automatic limit for rows in a join when using --i-am-a-dummy.

If the mysql client loses connection to the server while sending it a query, it will immediately and automatically try to reconnect once to the server and send the query again. Note that even if it succeeds in reconnecting, as your first connection has ended, all your previous session objects are lost : temporary tables, user and session variables. Therefore, the above behaviour may be dangerous for you, like in this example where the server was shut down and restarted without you knowing it :

mysql> set @a=1;
Query OK, 0 rows affected (0.05 sec)

mysql> insert into t values(@a);
ERROR 2006: MySQL server has gone away
No connection. Trying to reconnect...
Connection id:    1
Current database: test

Query OK, 1 row affected (1.30 sec)

mysql> select * from t;
+------+
| a    |
+------+
| NULL |
+------+
1 row in set (0.05 sec)

The @a user variable has been lost with the connection, and after the reconnection it is undefined. To protect from this risk, you can start the mysql client with the --disable-reconnect option.

もしコマンドラインで 'help' と打った場合、mysql はサポートする コマンドを表示します:

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.
prompt  (\R)    Change your mysql prompt.
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.

The pager command works only in Unix.

status コマンドは、今使用している 接続とサーバーについての情報をいくつか表示します。 もし --safe-updates モードで使用している場合、 status は あなたのクエリに影響する mysql 変数の値を表示します。

初心者に便利な起動オプション(MySQL バージョン 3.23.11 で導入されました)は、 --safe-updates あるいは --i-am-a-dummy です。 ( これは DELETE FROM table_nameWHERE 節を忘れて 実行しようとした場合のためにあります。) このオプションが使用されると、 mysql は接続時に MySQL サーバーに 以下のようなコマンドを送ります:

SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=#select_limit#,
    SQL_MAX_JOIN_SIZE=#max_join_size#"

ここで #select_limit##max_join_size# は変数で これらは mysql コマンドからセット可能です。 「5.5.6 SET 構文」節参照.

この効果は:

Some useful hints about the 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.

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" <tim@no.spam.com>
      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)

For logging, you can use the tee option. The tee can be started with option --tee=..., or from the command-line interactively with command 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 tee can be disabled from the command-line with command notee. Executing tee again starts logging again. Without a parameter the previous file will be used. Note that tee will flush the results into the file after each command, just before the command-line appears again waiting for the next command.

Browsing, or searching the results in the interactive mode in Unix less, more, or any other similar program, is now possible with option --pager[=...]. Without argument, mysql client will look for environment variable PAGER and set pager to that. pager can be started from the interactive command-line with command pager and disabled with command nopager. The command takes an argument optionally and the pager will be set to that. Command pager can be called without an argument, but this requires that the option --pager was used, or the pager will default to stdout. pager works only in Unix, since it uses the popen() function, which doesn't exist in Windows. In Windows, the tee option can be used instead, although it may not be as handy as pager can be in some situations.

A few tips about pager:

You can also combine the two functions above; have the tee enabled, 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 Unix tee used with the pager and the mysql client in-built tee, is that the in-built tee works even if you don't have the Unix tee available. The in-built tee also logs everything that is printed on the screen, where the Unix tee used with pager doesn't log quite that much. Last, but not least, the interactive 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.

From MySQL version 4.0.2 it is possible to change the prompt in the mysql command-line client.

You can use the following prompt options:
Option Description
\v mysqld version
\d database in use
\h host connected to
\p port connected on
\u username
\U full username@host
\\ `\'
\n new line break
\t tab
\ space
\_ space
\R military hour time (0-23)
\r standard hour time (1-12)
\m minutes
\y two digit year
\Y four digit year
\D full date format
\s seconds
\w day of the week in three letter format (Mon, Tue, ...)
\P am/pm
\o month in number format
\O month in three letter format (Jan, Feb, ...)
\c counter that counts up for each command you do

`\' followed by any other letter just becomes that letter.

You may set the prompt in the following places:

Environment Variable
You may set the MYSQL_PS1 environment variable to a prompt string. For example:
shell> export MYSQL_PS1="(\u@\h) [\d]> "
`my.cnf'
`.my.cnf'
You may set the prompt option in any MySQL configuration file, in the mysql group. For example:
[mysql]
prompt=(\u@\h) [\d]>\_
Command Line
You may set the --prompt option on the command line to mysql. For example:
shell> mysql --prompt="(\u@\h) [\d]> "

(user@host) [database]> 
Interactively
You may also use the prompt (or \R) command to change your prompt interactively. For example:
mysql> prompt (\u@\h) [\d]>\_
PROMPT set to '(\u@\h) [\d]>\_'
(user@host) [database]> 
(user@host) [database]> prompt
Returning to default PROMPT of mysql> 
mysql> 

4.8.3 mysqladmin, MySQL サーバーの管理

管理オペレーションを実行するためのユーティリティ。シンタックスは:

shell> mysqladmin [OPTIONS] command [command-option] command ...

mysqladmin --help によって、オプションの一覧を手にいれることができます。

現在の mysqladmin は以下のコマンドをサポートします:

create databasename
新しいデータベースの作成
drop databasename
データベースとテーブルの全削除。
extended-status
サーバーから拡張ステータスを取得。
flush-hosts
キャッシュされている全ホストをフラッシュ。
flush-logs
全てのログをフラッシュ
flush-tables
全てのテーブルをフラッシュ
flush-privileges
許可テーブルの再読み込み (reload と同じ)
kill id,id,...
mysql スレッドの kill.
password
Set a new password. 古いパスワードを New-password に変更
ping
mysqld が生きているかチェック
processlist
現在活動中の mysql スレッドを表示
reload
権限テーブルの再読み込み
refresh
全テーブルをフラッシュし、ログファイルを一度閉じて開きます。
shutdown
サーバーをダウンさせます。
slave-start
Start slave replication thread.
slave-stop
Stop slave replication thread.
status
サーバーから短いステータスを得ます。
variables
変数の表示
version
サーバーからバージョンを得ます。

全てのコマンドは、ユニークなプレフィックスで省略可能です。 例えば:

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

The mysqladmin status command result has the following columns:

Column Description
Uptime MySQL サーバーの起動秒数
Threads 稼働中のスレッド数 (clients).
Questions mysqld が開始してからのクライアントからのクエリ数
Slow queries long_query_time 秒より時間のかかったクエリの数 「4.9.5 The Slow Query Log (3.23.28以上)」節参照.
Opens mysqld が開いたテーブル数
Flush tables Number of flush ..., refresh, and reload commands.
Open tables 現在開かれているテーブルの数
Memory in use mysqld のコードによって直接割り当てられたメモリ (only available when MySQL is compiled with --with-debug=full).
Max memory used mysqld のコードによって直接割り当てられる最大メモリー量 (only available when MySQL is compiled with --with-debug=full).

If you do mysqladmin shutdown on a socket (in other words, on a the computer where mysqld is running), mysqladmin will wait until the MySQL pid-file is removed to ensure that the mysqld server has stopped properly.

4.8.4 Using mysqlcheck for Table Maintenance and Crash Recovery

Since MySQL version 3.23.38 you will be able to use a new checking and repairing tool for MyISAM tables. The difference to myisamchk is that mysqlcheck should be used when the mysqld server is running, where as myisamchk should be used when it is not. The benefit is that you no longer have to take the server down for checking or repairing your tables.

mysqlcheck uses MySQL server commands CHECK, REPAIR, ANALYZE and OPTIMIZE in a convenient way for the user.

There are three alternative ways to invoke mysqlcheck:

shell> mysqlcheck [OPTIONS] database [tables]
shell> mysqlcheck [OPTIONS] --databases DB1 [DB2 DB3...]
shell> mysqlcheck [OPTIONS] --all-databases

So it can be used in a similar way as mysqldump when it comes to what databases and tables you want to choose.

mysqlcheck does have a special feature compared to the other clients; the default behaviour, checking tables (-c), can be changed by renaming the binary. So if you want to have a tool that repairs tables by default, you should just copy mysqlcheck to your harddrive with a new name, mysqlrepair, or alternatively make a symbolic link to mysqlrepair and name the symbolic link as mysqlrepair. If you invoke mysqlrepair now, it will repair tables by default.

The names that you can use to change mysqlcheck default behaviour are here:

mysqlrepair:   The default option will be -r
mysqlanalyze:  The default option will be -a
mysqloptimize: The default option will be -o

The options available for mysqlcheck are listed here, please check what your version supports with mysqlcheck --help.

-A, --all-databases
Check all the databases. This will be same as --databases with all databases selected
-1, --all-in-1
Instead of making one query for each table, execute all queries in 1 query separately for each database. Table names will be in a comma separated list.
-a, --analyze
Analyse given tables.
--auto-repair
If a checked table is corrupted, automatically fix it. Repairing will be done after all tables have been checked, if corrupted ones were found.
-#, --debug=...
Output debug log. Often this is 'd:t:o,filename'
--character-sets-dir=...
Directory where character sets are
-c, --check
Check table for errors
-C, --check-only-changed
Check only tables that have changed since last check or haven't been closed properly.
--compress
Use compression in server/client protocol.
-?, --help
Display this help message and exit.
-B, --databases
To check several databases. Note the difference in usage; in this case no tables are given. All name arguments are regarded as database names.
--default-character-set=...
Set the default character set
-F, --fast
Check only tables that hasn't been closed properly
-f, --force
Continue even if we get an sql-error.
-e, --extended
If you are using this option with CHECK TABLE, it will ensure that the table is 100 percent consistent, but will take a long time. If you are using this option with REPAIR TABLE, it will run an extended repair on the table, which may not only take a long time to execute, but may produce a lot of garbage rows also!
-h, --host=...
Connect to host.
-m, --medium-check
Faster than extended-check, but only finds 99.99 percent of all errors. Should be good enough for most cases.
-o, --optimize
Optimise table
-p, --password[=...]
Password to use when connecting to server. If password is not given it's solicited on the tty.
-P port_num, --port=port_num
Port number to use for TCP/IP connections.
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-q, --quick
If you are using this option with CHECK TABLE, it prevents the check from scanning the rows to check for wrong links. This is the fastest check. If you are using this option with REPAIR TABLE, it will try to repair only the index tree. This is the fastest repair method for a table.
-r, --repair
Can fix almost anything except unique keys that aren't unique.
-s, --silent
Print only error messages.
-S, --socket=...
Socket file to use for connection.
--tables
Overrides option --databases (-B).
-u, --user=#
User for login if not current user.
-v, --verbose
Print info about the various stages.
-V, --version
Output version information and exit.

4.8.5 mysqldump, データベースとテーブルから、構造とデータをダンプ

データベース、あるいは、バックアップ、他のSQLサーバー(MySQL サーバであ る必要はない)へのデータを移動を目的としたデータのまとまり、これらをダンプする ためのユーティリティ。ダンプは、テーブルの作成のための SQL 文を含みます。

サーバでバックアップを行なう場合、mysqlhotcopy を代わりに使用するこ とを考慮すべきです。 「4.8.6 mysqlhotcopy, Copying MySQL Databases and Tables」節参照.

shell> mysqldump [OPTIONS] database [tables]
OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR     mysqldump [OPTIONS] --all-databases [OPTIONS]

もしテーブルを指定せず、--databases--all-databases を 使用しなかったなら、データベースの全てのテーブルがダンプされます。

mysqldump --help によって、オプションの一覧を手にいれることができます。

もし mysqldump--quick--opt なしで実行するならば、 mysqldump は結果を表示する前に、結果をメモリに全てロードすることに 注意してください。 これは大きなデータベースをダンプする際に問題になるでしょう。

Note that if you are using a new copy of the mysqldump program and you are going to do a dump that will be read into a very old MySQL server, you should not use the --opt or -e options.

mysqldump は以下のオプションをサポートします:

--add-locks
Add LOCK TABLES before and UNLOCK TABLE after each table dump. (To get faster inserts into MySQL.)
--add-drop-table
Add a drop table before each create statement.
-A, --all-databases
Dump all the databases. This will be same as --databases with all databases selected.
-a, --all
Include all MySQL-specific create options.
--allow-keywords
Allow creation of column names that are keywords. This works by prefixing each column name with the table name.
-c, --complete-insert
Use complete insert statements (with column names).
-C, --compress
Compress all information between the client and the server if both support compression.
-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. USE db_name; will be included in the output before each new database.
--delayed
Insert rows with the INSERT DELAYED command.
-e, --extended-insert
Use the new multiline INSERT syntax. (Gives more compact and faster inserts statements.)
-#, --debug[=option_string]
Trace usage of the program (for debugging).
--help
Display a help message and exit.
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
These options are used with the -T option and have the same meaning as the corresponding clauses for LOAD DATA INFILE. 「6.4.9 LOAD DATA INFILE 構文」節参照.
-F, --flush-logs
Flush log file in the MySQL server before starting the dump.
-f, --force,
Continue even if we get a SQL error during a table dump.
-h, --host=..
Dump data from the MySQL server on the named host. The default host is localhost.
-l, --lock-tables.
Lock all tables before starting the dump. The tables are locked with READ LOCAL to allow concurrent inserts in the case of MyISAM tables. Please note that when dumping multiple databases, --lock-tables will lock tables for each database separately. So using this option will not guarantee your tables will be logically consistent between databases. Tables in different databases may be dumped in completely different states.
-K, --disable-keys
/*!40000 ALTER TABLE tb_name DISABLE KEYS */; and /*!40000 ALTER TABLE tb_name ENABLE KEYS */; will be put in the output. This will make loading the data into a MySQL 4.0 server faster as the indexes are created after all data are inserted.
-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 a --databases or --all-databases option was given.
-t, --no-create-info
Don't write table creation information (the CREATE TABLE statement).
-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!
--opt
Same as --quick --add-drop-table --add-locks --extended-insert --lock-tables. Should give you the fastest possible dump for reading into a MySQL server.
-pyour_pass, --password[=your_pass]
The password to use when connecting to the server. If you specify no `=your_pass' part, mysqldump you will be prompted for a password.
-P port_num, --port=port_num
Port number to use for TCP/IP connections.
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-q, --quick
Don't buffer query, dump directly to stdout. Uses mysql_use_result() to do this.
-Q, --quote-names
Quote table and column names within ``' characters.
-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).
--single-transaction
This option issues a BEGIN SQL command before dumping data from server. It is mostly useful with InnoDB tables and READ_COMMITTED transaction isolation level, as in this mode it will dump the consistent state of the database at the time then BEGIN was issued without blocking any applications. When using this option you should keep in mind that only transactional tables will be dumped in a consistent state, e.g., any MyISAM or HEAP tables dumped while using this option may still change state. The --single-transaction option was added in version 4.0.2. This option is mutually exclusive with the --lock-tables option as LOCK TABLES already commits a previous transaction internally.
-S /path/to/socket, --socket=/path/to/socket
The socket file to use when connecting to localhost (which is the default host).
--tables
Overrides option --databases (-B).
-T, --tab=path-to-some-directory
Creates a table_name.sql file, that contains the SQL CREATE commands, and a table_name.txt file, that contains the data, for each give table. The format of the `.txt' file is made according to the --fields-xxx and --lines--xxx options. Note: This option only works if mysqldump is run on the same machine as the mysqld daemon, and the user/group that mysqld is running as (normally user mysql, group mysql) needs to have permission to create/write a file at the location you specify.
-u user_name, --user=user_name
The MySQL user name to use when connecting to the server. The default value is your Unix login name.
-O var=option, --set-variable var=option
Set the value of a variable. The possible variables are listed below. Please note that --set-variable is deprecated since MySQL 4.0, just use --var=option on its own.
-v, --verbose
Verbose mode. Print out more information on what the program does.
-V, --version
Print version information and exit.
-w, --where='where-condition'
Dump only selected records. Note that quotes are mandatory:
-X, --xml
Dumps a database as well formed XML
-x, --first-slave
Locks all tables across all databases.
"--where=user='jimf'" "-wuserid>1" "-wuserid<1"
-O net_buffer_length=#, where # < 16M
When creating multi-row-insert statements (as with option --extended-insert or --opt), mysqldump will create rows up to net_buffer_length length. If you increase this variable, you should also ensure that the max_allowed_packet variable in the MySQL server is bigger than the net_buffer_length.

The most normal use of mysqldump is probably for making a backup of whole databases. 「4.4.1 データベースのバックアップ」節参照.

mysqldump --opt database > backup-file.sql

You can read this back into MySQL with:

mysql database < backup-file.sql

or

mysql -e "source /patch-to-backup/backup-file.sql" database

However, it's also very useful to populate another MySQL server with information from a database:

mysqldump --opt database | mysql --host=remote-host -C database

It is possible to dump several databases with one command:

mysqldump --databases database1 [database2 ...] > my_databases.sql

If all the databases are wanted, one can use:

mysqldump --all-databases > all_databases.sql

4.8.6 mysqlhotcopy, Copying MySQL Databases and Tables

mysqlhotcopy is a Perl script that uses LOCK TABLES, FLUSH TABLES and cp or scp to quickly make a backup of a database. It's the fastest way to make a backup of the database or single tables, but it can only be run on the same machine where the database directories are.

mysqlhotcopy db_name [/path/to/new_directory]

mysqlhotcopy db_name_1 ... db_name_n /path/to/new_directory

mysqlhotcopy db_name./regex/

mysqlhotcopy supports the following options:

-?, --help
Display a help screen and exit
-u, --user=#
User for database login
-p, --password=#
Password to use when connecting to server
-P, --port=#
Port to use when connecting to local server
-S, --socket=#
Socket to use when connecting to local server
--allowold
Don't abort if target already exists (rename it _old)
--keepold
Don't delete previous (now renamed) target when done
--noindices
Don't include full index files in copy to make the backup smaller and faster The indexes can later be reconstructed with myisamchk -rq..
--method=#
Method for copy (cp or scp).
-q, --quiet
Be silent except for errors
--debug
Enable debug
-n, --dryrun
Report actions without doing them
--regexp=#
Copy all databases with names matching regexp
--suffix=#
Suffix for names of copied databases
--checkpoint=#
Insert checkpoint entry into specified db.table
--flushlog
Flush logs once all tables are locked.
--tmpdir=#
Temporary directory (instead of /tmp).

You can use perldoc mysqlhotcopy to get more complete documentation for mysqlhotcopy.

mysqlhotcopy reads the groups [client] and [mysqlhotcopy] from the option files.

To be able to execute mysqlhotcopy you need write access to the backup directory, the SELECT privilege for the tables you are about to copy and the MySQL RELOAD privilege (to be able to execute FLUSH TABLES).

4.8.7 mysqlimport, テキストファイルからデータを取り込む

mysqlimport は、LOAD DATA INFILE SQL 構文を、 コマンドラインインターフェースで提供します。 mysqlimport のオプションのほとんどが、 LOAD DATA INFILE への同じオプションに対応します。 「6.4.9 LOAD DATA INFILE 構文」節参照.

mysqlimport の実行は以下のようにします:

shell> mysqlimport [options] database textfile1 [textfile2 ...]

mysqlimport は、コマンドラインの引数に与えられたファイル名の拡張子を取り、 拡張子を取った後の名前を、ファイルの内容を取り込むテーブルの名前とします。 例えば、`patient.txt', `patient.text', `patient' という ファイルは全て、patient とという名前のテーブルに取り込まれます。

mysqlimport は以下のオプションをサポートします:

-c, --columns=...
This option takes a comma-separated list of field names as an argument. The field list is used to create a proper LOAD DATA INFILE command, which is then passed to MySQL. 「6.4.9 LOAD DATA INFILE 構文」節参照.
-C, --compress
クライアントとサーバーの両方が圧縮をサポートしているなら、 クライアント・サーバー間でやり取りされる全ての情報を圧縮します。
-#, --debug[=option_string]
プログラムのトレース(デバッグ)
-d, --delete
テキストファイルを取り込む前にテーブルを空にします。
--fields-terminated-by=...
--fields-enclosed-by=...
--fields-optionally-enclosed-by=...
--fields-escaped-by=...
--lines-terminated-by=...
これらのオプションは、LOAD DATA INFILE の対応する文節と同じ意味になります 「6.4.9 LOAD DATA INFILE 構文」節参照.
-f, --force
エラーを無視します。例えば、テキストファイルを取り込むテーブルがない場合、 残りのファイルの処理に移ります。 --force がなければ、 テーブルがなければ mysqlimport は終了します。
--help
ヘルプを表示して終了。
-h host_name, --host=host_name
名前を指定された MySQL サーバーにデータを取り入れます。 デフォルトでは localhost.
-i, --ignore
--replace オプションの説明を見てください。
-l, --lock-tables
それぞれのテキストファイルを処理する前に、書き込まれる 全てのテーブルをロックします。 これは確実に、すべてのテーブルをサーバ上で同期させます。
-L, --local
クライアントからの入力ファイルを読みます。 デフォルトでは、localhost に接続した場合、テキストファイルは サーバー上にあると仮定されます。(localhost はデフォルト値)
-pyour_pass, --password[=your_pass]
サーバーに接続するときに使用するパスワード。 もし `=your_pass' のところにパスワードを書かなければ、 mysqlimport はパスワードのためのプロンプトをだします。
-P port_num, --port=port_num
ホストに接続するための TCP/IP ポート番号。 (これは localhost を除くホストへの接続に使用します。 localhost へは、Unix ソケットを使用します。)
--protocol=(TCP | SOCKET | PIPE | MEMORY)
To specify the connect protocol to use. New in MySQL 4.1.
-r, --replace
--replace--ignore オプションは、 入力されているレコードのユニークキーの値が、 既に存在しているレコードのユニークキーの値と同じ場合、 その入力されているデータの取り扱いを決定します。 もし --replace が指定されているなら、 既にあるレコードは新しく読まれたレコードに置き換えられます。 もし --ignore が指定されているなら、 入力された物は無視されます。 どちらのオプションも指定していない場合、 キーの値が重なっているとエラーを発し、 テキストファイルの残りの部分は無視されます。
-s, --silent
静粛モード。エラーだけ出力します。
-S /path/to/socket, --socket=/path/to/socket
localhost への接続時に使用するソケットファイルを指定します。
-u user_name, --user=user_name
サーバーの接続に使用する MySQL ユーザー名の指定。 デフォルトは、Unix のログイン名。
-v, --verbose
冗長モード。プログラムがしている事について多く出力します。
-V, --version
バージョンを表示して終了。

Here is a sample run using mysqlimport:

$ 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 |
+------+---------------+

4.8.8 mysqlshow, Showing Databases, Tables, and Columns

mysqlshow can be used to quickly look at which databases exist, their tables, and the table's columns.

With the mysql program you can get the same information with the SHOW commands. 「4.5.6 SHOW 構文」節参照.

mysqlshow is invoked like this:

shell> mysqlshow [OPTIONS] [database [table [column]]]

Note that in newer MySQL versions, you only see those database/tables/columns for which you have some privileges.

If the last argument contains a shell or SQL wildcard (*, ?, % or _) then only what's matched by the wildcard is shown. If a database contains underscore(s), those should be escaped with backslash (some Unix shells will require two), in order to get tables / columns properly. '*' are converted into SQL '%' wildcard and '?' into SQL '_' wildcard. This may cause some confusion when you try to display the columns for a table with a _ as in this case mysqlshow only shows you the table names that match the pattern. This is easily fixed by adding an extra % last on the command-line (as a separate argument).

4.8.9 mysql_config, Get compile options for compiling clients

mysql_config provides you with useful information how to compile your MySQL client and connect it to MySQL.

mysql_config supports the following options:

--cflags
Compiler flags to find include files
--libs
Libs and options required to link with the MySQL client library.
--socket
The default socket name, defined when configuring MySQL.
--port
The default port number, defined when configuring MySQL.
--version
Version number and version for the MySQL distribution
--libmysqld-libs
Libs and options required to link with the MySQL embedded server.

If you execute mysql_config without any options it will print all options it supports plus the value of all options:

shell> mysql_config
sage: /usr/local/mysql/bin/mysql_config [OPTIONS]
Options:
        --cflags         [-I'/usr/local/mysql/include/mysql']
        --libs           [-L'/usr/local/mysql/lib/mysql' -lmysqlclient -lz -lcrypt -lnsl -lm -L/usr/lib -lssl -lcrypto]
        --socket         [/tmp/mysql.sock]
        --port           [3306]
        --version        [4.0.8-gamma]
        --libmysqld-libs [ -L'/usr/local/mysql/lib/mysql' -lmysqld -lpthread -lz -lcrypt -lnsl -lm  -lpthread  -lrt]

You can use this to compile a MySQL client by as follows:

CFG=/usr/local/mysql/bin/mysql_config
sh -c "gcc -o progname `$CFG --cflags` progname.c `$CFG --libs`"

4.8.10 perror, Explaining Error Codes

For most system errors MySQL will, in addition to a internal text message, also print the system error code in one of the following styles: message ... (errno: #) or message ... (Errcode: #).

You can find out what the error code means by either examining the documentation for your system or use the perror utility.

perror prints a description for a system error code, or an MyISAM/ISAM storage engine (table handler) error code.

perror is invoked like this:

shell> perror [OPTIONS] [ERRORCODE [ERRORCODE...]]

Example:

shell> perror 13 64
Error code  13:  Permission denied
Error code  64:  Machine is not on the network

Note that the error messages are mostly system dependent!

4.8.11 How to Run SQL Commands from a Text File

The mysql client typically is used interactively, like this:

shell> mysql database

However, it's also possible to put your SQL commands in a file and tell mysql to read its input from that file. To do so, create a text file `text_file' that contains the commands you wish to execute. Then invoke mysql as shown here:

shell> mysql database < text_file

You can also start your text file with a USE db_name statement. In this case, it is unnecessary to specify the database name on the command line:

shell> mysql < text_file

If you are already running mysql, you can execute a SQL script file using the source command:

mysql> source filename;

For more information about batch mode, 「3.6 mysql のバッチモードでの使用」節.

4.9 The MySQL Log Files

MySQL has several different log files that can help you find out what's going on inside mysqld:

Log file Description
The error log Problems encountering starting, running or stopping mysqld.
The isam log Logs all changes to the ISAM tables. Used only for debugging the isam code.
The query log Established connections and executed queries.
The update log Deprecated: Stores all statements that changes data
The binary log Stores all statements that changes something. Used also for replication
The slow log Stores all queries that took more than long_query_time to execute or didn't use indexes.

All logs can be found in the mysqld data directory. You can force mysqld to reopen the log files (or in some cases switch to a new log) by executing FLUSH LOGS. 「4.5.3 FLUSH 構文」節参照.

4.9.1 The Error Log

The error log file contains information indicating when mysqld was started and stopped and also any critical errors found when running.

If mysqld dies unexpectedly and mysqld_safe needs to restart mysqld, mysqld_safe will write a restarted mysqld row in this file. This log also holds a warning if 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 mysqld died. This can be used to find out where mysqld died. 「E.1.4 Using a Stack Trace」節参照.

Beginning with MySQL 4.0.10 you can specify where mysqld stores the error log file with the option --log-error[=filename]. If no file name is given mysqld will use mysql-data-dir/'hostname'.err on Unix and `\mysql\data\mysql.err' on windows. If you execute flush logs the old file will be prefixed with --old and mysqld will create a new empty log file.

In older MySQL versions the error log handling was done by mysqld_safe which redirected the error file to 'hostname'.err. One could change this file name with the option --err-log=filename.

If you don't specify --log-error or if you use the --console option the errors will be written to stderr (the terminal).

On windows the output is always done to the .err file if --console is not given.

4.9.2 The General Query Log

If you want to know what happens within mysqld, you should start it with --log[=file]. This will log all connections and queries to the log file (by default named `'hostname'.log'). This log can be very useful when you suspect an error in a client and want to know exactly what mysqld thought the client sent to it.

Older versions of the mysql.server script (from MySQL 3.23.4 to 3.23.8) pass safe_mysqld a --log option (enable general query log). If you need better performance when you start using MySQL in a production environment, you can remove the --log option from mysql.server or change it to --log-bin. 「4.9.4 The Binary Update Log バイナリ更新ログ (3.23.15以上)」節参照.

The entries in this log are written as mysqld receives the questions. This may be different from 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.

4.9.3 更新ログ

Note: the update log is replaced by the binary log. 「4.9.4 The Binary Update Log バイナリ更新ログ (3.23.15以上)」節参照. With this you can do anything that you can do with the update log.

--log-update=file_nameオプションを使用してmysqldを起動すると、 データを更新した全てのSQLコマンドをログファイルに書きます。 もし file_name が与えられなかった場合は、ホスト名がデフォルトで使用されます。 もし file_name にディレクトリパスが含まれなかった場合は、 このファイルはデータディレクトリに書かれます。 もし file_name が拡張を持たなかったなら、mysqldfile_name.### という形でログファイルを作成します。 このログファイルはデータディレクトリにかかれ、 その名前は file_name.### という形式の名前になっています。 ###mysqladmin refreshmysqladmin flush-logs を実行す る度に、 あるいは FLUSH LOGS 構文を実行したり、サーバーをリスタートする度に 自動的に増える数字です。

Note: for the above scheme to work, you must 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!

もし --log-l オプションを使用した場合、ログファイルの名前は mysqld は全部のログを `hostname.log' に書き出します。 この場合、リスタートやりフレッシュを行っても新しくログファイルを作りません。 (一度クローズして再度オープンします。) In this case you can copy it (on Unix) by doing:

mv hostname.log hostname-old.log
mysqladmin flush-logs
cp hostname-old.log to-backup-directory
rm hostname-old.log

更新ログは、実際に更新されたデータのステートメントだけを書くため、きびきびと動作 します。 WHERE を使用した UPDATEDELETE で結果が得られなかった場合、 ログは書き出されません。 すでにセットされている値に、もう一度項目を更新するような UPDATE もスキッ プされます。

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.

ログファイルの更新に従ってデータベースを更新したい場合は、次を行います (更新ログファイル名を `file_name.###' と仮定します):

shell> ls -1 -t -r file_name.[0-9]* | xargs cat | mysql

ls は全てのログファイルを正しく並べるために使用しています。

これは、クラッシュ後にバックアップした状態まで戻りたい、あるいは、 バックアップした後からクラッシュするまでの間のデータの更新を行いたい、 そんな場合に使えます。

4.9.4 The Binary Update Log バイナリ更新ログ (3.23.15以上)

The intention is that the binary log should 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 each query took that updated the database. It doesn't contain queries that don't modify any data. If you want to log all queries (for example to find a problem query) you should use the general query log. 「4.9.2 The General Query Log」節参照.

バイナリログはマスターからスレーブにレプリケーションを行なうときにも 使用されます。 「4.10 MySQL のレプリケーション (3.23.15以上)」節参照.

--log-bin[=file_name] オプションで mysqld が起動されると、 mysqld は全てのデータを更新する SQL コマンドをログファイルに書き出します。 もしファイル名がオプションに渡されなかった場合は、ホストマシンの名前に -bin がついた名前が、ファイル名として使用されます。 もしファイル名が指定されていても、パスが指定されていない場合には、 ログファイルはデータディレクトリに書かれます。

もし --log-bin=filename.extension という形で ファイル名に拡張子を指定した場合、拡張子は取り除かれます。

バイナリログファイル名のため、mysqld は数字をファイル名に付け加えます。 この数字はサーバー上で mysqladmin refresh, mysqladmin flush-logs, FLUSH LOGS を実行する度に増えていきます。 新しいバイナリログは max_binlog_size に達するまで自動的に作成されます。 RESET MASTER コマンドを使用すれば、書き込み中ではないバイナリログファイルを 全て消すことが可能です。 「4.5.4 RESET 構文」節参照.

You can use the following options to mysqld to affect what is logged to the binary log:

Option Description
binlog-do-db=database_name Tells the master that it should log updates to the binary log if the current database (i.e. the one selected by USE) database is 'database_name'. All others databases which are not explicitly mentioned are ignored. Note that if you use this you should ensure that you only do updates in the current database. (Example: binlog-do-db=some_database)
binlog-ignore-db=database_name Tells the master that updates where the current database (i.e. the one selected by USE) is 'database_name' should not be stored in the binary log. Note that if you use this you should ensure that you only do updates in the current database. (Example: binlog-ignore-db=some_database)

To be able to know which different binary log files have been used, 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 '.index'. You can change the name of the binary log index file with the --log-bin-index=[filename] option. You should not manually edit this file while mysqld is running; doing this would confuse mysqld.

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 mysqladmin flush-logs once a day and then remove any logs that are more than 3 days old. You can remove them manually, or preferably using PURGE MASTER LOGS TO ( 「4.10.6 レプリケーションに関連する SQL コマンド」節参照) which will also safely update the binary log index file for you.

You can examine the binary log file with the mysqlbinlog command. For example, you can update a MySQL server from the binary log as follows:

shell> mysqlbinlog log-file | mysql -h server_name

You can also use the mysqlbinlog program to read the binary log directly from a remote MySQL server!

mysqlbinlog --help will give you more information of how to use this program!

If you are using BEGIN [WORK] or SET AUTOCOMMIT=0, you must use the 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.

Updates to non-transactional tables are stored in the binary log immediately after execution. For transactional tables such as BDB or InnoDB tables, all updates (UPDATE, DELETE or INSERT) that change tables are cached until a COMMIT command is sent to the server. At this point mysqld writes the whole transaction to the binary log before the COMMIT is executed. Every thread will, on start, allocate a buffer of binlog_cache_size to buffer queries. If a query is bigger than this, the thread will open a temporary file to store the transaction. The temporary file will be deleted when the thread ends.

The max_binlog_cache_size (default 4G) can be used to restrict the total size used to cache a multi-query transaction. If a transaction is bigger than this it will fail and roll back.

If you are using the update or binary log, concurrent inserts will be converted to normal inserts when using CREATE ... SELECT or INSERT ... SELECT. This is to ensure that you can recreate an exact copy of your tables by applying the log on a backup.

4.9.5 The Slow Query Log (3.23.28以上)

MySQL を --log-slow-queries[=file_name] オプションで起動すると、 mysqld は、 実行に long_query_time に指定された値以上に時間のかかった 全ての SQL コマンドをログに書き出します。 この時間には、最初のテーブルをロックするまでの時間は含まれていません。

slow query log はクエリが実行され、全てのロックが解除された後に、 書き込まれます。 そのため、SQL 文が実行された順番とは違う順に 書かれるかもしれません。

もしファイル名が指定されなかったら、ホスト名に -slow.log をつけた ファイル名が使用されます。 もしファイル名が指定されていてもパスが指定されなかったなら、 ログファイルはデータディレクトリに記録されます。

slow query log は実行に時間のかかったクエリを見つけ出すのに使用することが 可能で、最適化に用いられます。 ログファイルが大きくなると、それが難しくなります。そこで、 mysqldumpslow コマンドを使用すれば、ログファイルの slow query の サマリ一覧を得ることが可能です。

--log-long-format オプションを使用すれば、インデックスを使用しなかった クエリも記録します。 「4.1.1 mysqld コマンド行オプション」節参照.

4.9.6 Log File Maintenance

The MySQL Server can create a number of different log files, which make it easy to see what is going on. 「4.9 The MySQL Log Files」節参照. One must however regularly clean up these files, to ensure that the logs don't take up too much disk space.

MySQL をログファイルとともに使用する場合、 あなたは、時々古いログファイルを リムーブ/バックアップし、 MySQL に新しいファイルにログを取るように指示したいと思うことでしょう。 「4.4.1 データベースのバックアップ」節参照.

Linux (Red Hat) においては、mysql-log-rotate スクリプトを これに使用できます。 もし RPM ディストリビューションの MySQL を インストールしたなら、このスクリプトは自動でインストールされているはずです。 Note that you should be careful with this if you are using the log for replication!

他のシステムでは、自分自身で短いスクリプトをインストールします。 cron でログファイルを扱うようにします。

mysqladmin flush-logs コマンドか FLUSH LOGS SQL文で、 MySQL に新しいログファイルを使用させることが出来ます。 もしあなたが MySQL Version 3.21 を使用しているなら、 mysqladmin refresh を使用しなくてはなりません。

上記のコマンドは、以下のように動作します:

もし更新ログだけを使用しているなら、あなたは、ログを flush するだけでよくて、 その時、バックアップのため古い更新ログファイルを移動します。 もし普通のログを使っていれば、あなたは以下のようにすることができます:

shell> cd mysql-data-directory
shell> mv mysql.log mysql.old
shell> mysqladmin flush-logs

こうしておいて、`mysql.old' をバックアップし削除します。

4.10 MySQL のレプリケーション (3.23.15以上)

この章は MySQL の様々なレプリケーション機能を説明します。レプリケーション で有効なオプションのリファレンスとしても役立ちます。レプリケーションの紹介 と、その実装方法を学べます。終りの方には、いくつかの FAQ と問題の説明とそ の解決方法もあります。

我々のウェブサイト http://www.mysql.com/ によく訪れ、この節の最新 版を読むようるように提案します。レプリケーションは絶えず改良されていて、 最新の情報でマニュアルを頻繁に更新します。

4.10.1 Introduction

一方通行レプリケーションは、堅牢さと速度の両方を増加させるために使用できま す。堅牢さについて、2つのシステムを持つことができ、マスターで問題が発生し た場合にバックアップに切り替えられます。速度の増加は、更新でないクエリの一 部をレプリカサーバに送ることで、成立します。もちろん、これは更新でないクエ リが多い時にだけ働くのですが、通常はそうなります。

バージョン 3.23.15 から、MySQL はワンウェイ・レプリケーションを サポートしました。 1つのサーバーがマスターの役をつとめ,もう一方は、スレーブの役をつとめます。 1つのサーバーはマスターとして動くことも、他に対するスレーブとして動作することも 可能です。 マスターサーバーは update のバイナリログを保持しています( 「4.9.4 The Binary Update Log バイナリ更新ログ (3.23.15以上)」節参照.)。 また、インデックスファイルは、バイナリログのローテーションの切り出し記録を残すた めに保持されます。 スレーブは接続時に、マスタに対し更新の伝達が最後に成功してからやめた場所 を知らせ、更新を取り戻し、それからブロックし、マスタが新しい更新を通知す るのを待ちます。

もしデータベースの複製を行なうなら、このデータベースに対する全ての更新は マスター上で行なわなくてはならないことに注意!

レプリケーションを使用することのもう一つの恩恵は、マスターの代わりに、スレー ブでバックアップを行なうことで、システムのライブバックアップを取ることがで きるということです。 「4.4.1 データベースのバックアップ」節参照。

4.10.2 レプリケーション実装概要

MySQL レプリケーションは、サーバがデータベースへのすべての変更のトラックを バイナリログ ( 「4.9.4 The Binary Update Log バイナリ更新ログ (3.23.15以上)」節参照) に保持し、スレーブサーバがデータのコピー 上で同じクエリを実行できるように、マスターサーバのバイナリログから保存され たクエリを読み込むということを基本にします。

バイナリログは単に固定点(バイナリロギングを有効にした瞬間)からの記録である ことを理解することがとても重要です。セットアップするすべてのスレー ブで、マスターからすべてのデータのコピーが必要です。マスター上でバイナリロ ギングを有効にした瞬間に存在していたように。 スレーブのデータがマスターに存在するデータと違う状態でスレーブを起動したならば、 バイナリログが開始されたときに、スレーブは失敗するでしょう。

Please see the following table for an indication of master-slave compatibility between different versions. With regard to version 4.0, we recommend using same version on both sides.

Master Master Master Master
3.23.33 and up 4.0.0 4.0.1 4.0.3 and up
Slave 3.23.33 and up yes no no no
Slave 4.0.0 no yes no no
Slave 4.0.1 yes no yes no
Slave 4.0.3 and up yes no no yes

Note: MySQL Version 4.0.2 is not recommended for replication.

Starting from 4.0.0, one can use LOAD DATA FROM MASTER to set up a slave. Be aware that LOAD DATA FROM MASTER currently works only if all the tables on the master are MyISAM type, and will acquire a global read lock, so no writes are possible while the tables are being transferred from the master. This limitation is of a temporary nature, and is due to the fact that we have not yet implemented hot lock-free table backup. It will be removed in the future 4.0 branch versions once we implement hot backup enabling LOAD DATA FROM MASTER to work without blocking master updates.

Due to the above limitation, we recommend that at this point you use LOAD DATA FROM MASTER only if the dataset on the master is relatively small, or if a prolonged read lock on the master is acceptable. While the actual speed of LOAD DATA FROM MASTER may vary from system to system, a good rule for a rough estimate of how long it is going to take is 1 second per 1 MB of the datafile. You will get close to the estimate if both master and slave are equivalent to 700 MHz Pentium, are connected through 100 MBit/s network, and your index file is about half the size of your data file. Of course, your mileage will vary from system to system, the above rule just gives you a rough order of magnitude estimate.

一旦スレーブが適切に構成され、実行していれば、スレーブは単にマスターに接続して、 更新が処理されるのを待つでしょう。 もしマスターがなくなったり、または、スレーブがマスターとの接続性を失えば、 スレーブは再接続できるまで master-connect-retry 秒毎に接続を試み、 そして、更新の監視を再開します。

各スレーブはそれが止まった場所のトラックを保持します。マスターサーバはいく つのスレーブが存在し、どれがいつ更新を行なったかについての知識はありません。

次の節ではマスター/スレーブ設定過程を詳細に説明します。

4.10.3 レプリケーションの設定方法

以下は、現在の MySQL サーバ上に完全なレプリケーションを設定する方法の簡単 な記述です。あなたがすべてのデータベースのレプリケーションを行ないたくて、 事前にレプリケーションを設定していないと仮定します。以下に示すステップを完 了するためには、マスターサーバを少しシャットダウンすることが必要になります。

上述の方法は、スレーブを設定するもっとも素直な方法ですが、それが唯一の方 法ではありません。たとえば、既にマスタのスナップショットを持っていて、マ スタがすでにサーバIDを設定して、バイナリログを有効にしている場合、マスタ をシャットダウンしたり更新をブロックすることなしに、スレーブを設定できま す。詳細については 「4.10.7 Replication FAQ」節. を参照してください。

MySQL レプリケーションの達人(guru)になりたければ、学習し、熟考し、 「4.10.6 レプリケーションに関連する SQL コマンド」節 に記述されているすべてのコマンドを試すように提案 します。 「4.10.5 `my.cnf' 内のレプリケーションオプション」節 の my.cnf 内のレプリケーション 開始オプションにも精通すべきです。

  1. マスターとスレーブに、最新の MySQL (同じバージョン) をインストールします。 バージョン 3.23.29 以上を使用すること。 これより前のバージョンでは、バイナリログのフォーマットが違い、また、新しい バージョンで直っているバグも含まれます。 最新のバージョンで確かめるまでは、バグレポートを送らないでください。
  2. マスター上に、レプリケーション用の特別なユーザーを登録します。 このユーザーには FILE 権限(in MySQL versions older than 4.0.2)か REPLICATION SLAVE 権限(in newer MySQL versions)が必要です。 全てのスレーブからこのユーザーで接続できるようにします。 もしユーザーがレプリケーションのみ(推奨)を行なうなら、 他の権限は与える必要は有りません。 例えば、repl という名前のユーザー(マスターにアクセス可能なユーザー)を 作成するには、次のようにします:
    mysql> GRANT FILE ON *.* TO repl@"%" IDENTIFIED BY '<password>'; # master < 4.0.2
    
    mysql> GRANT REPLICATION SLAVE ON *.* TO repl@"%" IDENTIFIED BY '<password>'; # master >= 4.0.2
    
    If you plan to use the LOAD TABLE FROM MASTER or LOAD DATA FROM MASTER commands (available starting from version 4.0.0), you will also need to grant the RELOAD and SUPER privileges on the master to the above user.
  3. If you are using MyISAM tables, flush all the tables and block write queries by executing FLUSH TABLES WITH READ LOCK command.
    mysql> FLUSH TABLES WITH READ LOCK;
    
    and then take a snapshot of the data on your master server. (Unixでは) もっとも簡単な方法は tar を使用してデータディレクトリの アーカーブを作成することです。 正確なデータディレクトリの場所はインストール方法に依存します。
    tar -cvf /tmp/mysql-snapshot.tar /path/to/data-dir
    
    Windows ユーザは WinZIP か似たソフトウェアを使用してデータディレクトリのアー カイブを作成することができます。 After or during the process of taking a snapshot, read the value of the current binary log name and the offset on the master:
    mysql > SHOW MASTER STATUS;
    +---------------+----------+--------------+-------------------------------+
    | File          | Position | Binlog_do_db | Binlog_ignore_db              |
    +---------------+----------+--------------+-------------------------------+
    | mysql-bin.003 | 73       | test,bar     | foo,manual,sasha_likes_to_run |
    +---------------+----------+--------------+-------------------------------+
    1 row in set (0.06 sec)
    
    The File column shows the name of the log, while Position shows the offset. In the above example, the binary log value is mysql-bin.003 and the offset is 73. Record the values - you will need to use them later when you are setting up the slave. Once you have taken the snapshot and recorded the log name and offset, you can re-enable write activity on the master:
    mysql> UNLOCK TABLES;
    
    If you are using InnoDB tables, ideally you should use the InnoDB Hot Backup tool that is available to those who purchase MySQL commercial licenses, support, or the backup tool itself. It will take a consistent snapshot without acquiring any locks on the master server, and record the log name and offset corresponding to the snapshot to be later used on the slave. More information about the tool is avaliable at http://www.innodb.com/hotbackup.html. Without the hot backup tool, the quickest way to take a snapshot of InnoDB tables is to shut the master server down and copy the data files, the logs, and the table definition files (.frm). To record the current log file name and offset, you should do the following before you shut down the server:
    mysql> FLUSH TABLES WITH READ LOCK;
    mysql> SHOW MASTER STATUS;
    
    And then record the log name and the offset from the output of SHOW MASTER STATUS as was shown earlier. Once you have recorded the log name and the offset, shut the server down without unlocking the tables to make sure it goes down with the snapshot corresponding to the current log file and offset:
    shell> mysqladmin -uroot shutdown
    
    If the master has been previously running without log-bin enabled, the values of log name and position will be empty when you run SHOW MASTER STATUS. In that case, record empty string ('') for the log name, and 4 for the offset.
  4. Make sure that `my.cnf' on the master has log-bin if it is not there already and server-id=unique number in the [mysqld] section. If those options are not present, add them and restart the server. It is very important that the id of the slave is different from the id of the master. Think of server-id as something similar to the IP address - it uniquely identifies the server instance in the community of replication partners.
    [mysqld]
    log-bin
    server-id=1
    
  5. マスター上の MySQL を再起動します。
  6. スレーブの my.cnf ファイルに、次を追加します:
    server-id=<some unique number between 1 and 2^32-1 that is different from
     that of the master>
    
    システムに関連したものは <> 内の値で置き換えてあります。 server-id には、サーバーそれぞれで違う番号にしなくてはなりません。 (同じ複製のグループ内で)。 もし server-id を指定しなければ、 master-host が無い場合には 1 に なり、それ以外の場合には 2 に自動的になります。 マスターで server-id の記入漏れがあった場合、 マスターはスレーブからの接続を拒否します。 スレーブ上での記入漏れの場合には、スレーブはマスターへの接続を拒否します。 従って、server-id の省略はバイナリログのバックアップのためにだけ良 いことです。
  7. While the slave is running, make it forget about the old replication configuration if it has been replicating previously:
    mysql> RESET SLAVE;
    
  8. スレーブのデータディレクトリにデータのスナップショットをコピーします。 ファイルとディレクトリのユーザーとパーミッションは確実に正しいものに してください。 これらのファイルに対して、 MySQL を実行している アカウントで、読み書きできるようにする必要があります。
  9. スレーブの再起動。
  10. Once the slave comes up, execute the following command:
    mysql> CHANGE MASTER TO MASTER_HOST='<master host name>',
     MASTER_USER='<replication user name>',
     MASTER_PASSWORD='<replication password>',
     MASTER_LOG_FILE='<recorded log file name>',
     MASTER_LOG_POS=<recorded log offset>;
    
    replacing the values in <> with the actual values relevant to your system.
  11. Start the slave thread:
    mysql> SLAVE START;
    

上記を行なった後、スレーブはマスターに接続し、スナップショット以後の 更新をキャッチするはずです。

もしスレーブに server-id をセットし忘れた場合、エラーログファイルに 次のようなエラーが出るでしょう:

Warning: one should set server_id to a non-0 value if master_host is set.
The server will not act as a slave.

もしマスターにセットし忘れたなら、スレーブはマスターに接続できません。

もし何かの理由でスレーブが複製できなかったなら、スレーブ上のエラーログ ファイルに、エラーメッセージが出るでしょう。

一度スレーブがレプリケーションを始めたなら、 エラーログファイルと同じディレクトリに master.info ファイルを見ることができます。 master.info ファイルはスレーブに使用され、 これは、マスターのバイナリログのいくつまで処理したかを保持しています。 このファイルを消したり編集したりしては いけません。 (あなたがやろうとしていることが確実に分かるまでは)。 そういうやむを得ない場合には、 CHANGE MASTER TO コマンドの使用の方が良いです。

Now that you have a snapshot, you can use it to set up other slaves. To do so, follow the slave portion of the procedure described above. You do not need to take another snapshot of the master.

4.10.4 レプリケーション機能と既知の問題

以下はサポートされていることとサポートされていないことの説明です:

4.10.5 `my.cnf' 内のレプリケーションオプション

レプリケーションを使用する場合は、我々は MySQL Version 3.23.33 以降を 推奨します。 これより古いバージョンでも動きますが、古い物はバグがあったり機能が無かったりします。 Some of the options mentioned here may not be available in your version if it is not the most recent one. For all options specific to the 4.0 branch, there is a note indicating so. Otherwise, if you discover that the option you are interested in is not available in your 3.23 version, and you really need it, please upgrade to the most recent 3.23 branch.

Please be aware that 4.0 branch is still in alpha, so some things may not be working as smoothly as you would like. If you really would like to try the new features of 4.0, we recommend you do it in such a way that in case there is a problem your mission critical applications will not be disrupted.

マスターとスレーブの両方に、 server-id オプションが必要です。 これは一意のレプリケーションid をセットします。 マスター、スレーブそれぞれのために、一意な値を、1 から 2^32-1 までの間から 選ばねばなりません。 例: server-id=3

以下の表は、MASTER で使用できるオプションを示したものです:

オプション 説明
log-bin=filename Write to a binary update log to the specified location. Note that if you give it a parameter with an extension (for example, log-bin=/mysql/logs/replication.log ) versions up to 3.23.24 will not work right during replication if you do FLUSH LOGS . The problem is fixed in Version 3.23.25. If you are using this kind of log name, FLUSH LOGS will be ignored on binlog. log を clear するには、FLUSH MASTER の実行をします。 FLUSH SLAVE を全てのスレーブ上で実行することも忘れてはいけません。 バージョン 3.23.36 以上では、RESET MASTERRESET SLAVE を使用す べきです。 You can use this option if you want to have a name which is independant of your hostname (could be useful in case you rename your host one day). (訳注: RESET はログを本当に全部消してしまうので、注意が必要。)
log-bin-index=filename FLUSH LOGS コマンドの実行のためには、どのログが現在使用されているもので、 どれがローテートされたもので、どの順番なのか、ということを知る必要があります。 この情報はバイナリログ index ファイルに記述されます。 デフォルトでは ``hostname`.index' というファイルになります。 違う名前にしたい場合に、このオプションを使用します。 Example: log-bin-index=db.index
sql-bin-update-same 設定されると、SQL_LOG_BIN に値を設定すると自動的に SQL_LOG_UPDATE を同じ値に設定します。逆も同様です。
binlog-do-db=database_name 現在の(いうなれば USE で選択している)データベースが database_name の場合、 バイナリログに更新をログすべきことをマスターに伝えます。 他のすべてのデータベースは無視されます。 注意: これを使用する場合は、現在のデータベースでだけ更新を行なうことを 確実にすべきです。 Example: binlog-do-db=sales
binlog-ignore-db=database_name 現在のデータベース(USEで選択しているデータベース) が database_name という名前であり、このデータベースの更新記録を バイナリログに格納すべきでないと、マスターに伝えます。 注意: これを使用する場合は、現在のデータベー スでだけ更新を行なうことを確実にすべきです。 Example: binlog-ignore-db=accounting

次の表は SLAVE に使用できるオプションです:

Option Description
master-host=host マスタのホスト名か IP アドレス。 もし設定されていないと、スレーブはスタートしません。 Note that the setting of master-host will be ignored if there exists a valid `master.info' file. Probably a better name for this options would have been something like bootstrap-master-host, but it is too late to change now. Example: master-host=db-master.mycompany.com
master-user=username スレーブスレッドがマスターに接続する時に自分を認証するためのユーザ。ユーザ は FILE 権限を持つ必要があります。マスターユーザが設定されない場合 は、test が適用されます。 The value in `master.info' will take precedence if it can be read. Example: master-user=scott
master-password=password スレーブスレッドがマスターサーバに接続する時に認証するパスワード。設定され ない場合は、空のパスワードが適用されます。 The value in `master.info' will take precedence if it can be read. Example: master-password=tiger
master-port=portnumber マスターが listen しているポート。設定されない場合は、MYSQL_PORT の コンパイル時の設定が適用されます。configure オプションで何もしてな ければ、これは 3306 です。 The value in `master.info' will take precedence if it can be read. Example: master-port=3306
master-connect-retry=seconds マスターが落ちたり接続が失われた場合に、スレーブスレッドがマスターへの接続 を再試行するまでに休眠する秒数。デフォルトは 60。 Example: master-connect-retry=60
master-ssl Available after 4.0.0. Turn SSL on for replication. Be warned that is this is a relatively new feature. Example: master-ssl
master-ssl-key Available after 4.0.0. Master SSL keyfile name. Only applies if you have enabled master-ssl. Example: master-ssl-key=SSL/master-key.pem
master-ssl-cert Available after 4.0.0. Master SSL certificate file name. Only applies if you have enabled master-ssl. Example: master-ssl-key=SSL/master-cert.pem
master-info-file=filename 複製処理がマスターのどこまで行なったかを覚えておくファイルの場所。デフォル トはデータディレクトリの `master.info' です。 You should not need to change this. Example: master-info-file=master.info
report-host バージョン 4.0.0 から。 スレーブ登録中にマスタに報告されるスレーブのホス ト名と IP 。これは SHOW SLAVE HOSTS の出力に表われます。スレーブ をマスタに登録したくない場合は、設定しないでください。注意: マスタがスレー ブ接続時のソケットの IP を単純に読むだけでは不十分です。NAT や他 のルーティングの問題で、マスタや他のホストからスレーブへの接続IPが正しく ないことがあります。 Example: report-host=slave1.mycompany.com
report-port バージョン 4.0.0 から。スレーブ登録中にマスタに報告されるスレーブのポー ト。スレーブがデフォルトでないポートで listen する場合か、マスタか他のク ライアントからスレーブへの特殊なトンネルを持つ場合にだけ設定してください。 確かでなければ、このオプションを設定しないでください。
replicate-do-table=db_name.table_name 指定されたテーブルに複製を制限することをスレーブスレッドに伝えます。一つ以 上のテーブルを指定するには、この命令を複数回(各テーブルに1回ずつ)使用しま す。 This will work for cross-database updates, in contrast to replicate-do-db. Example: replicate-do-table=some_db.some_table
replicate-ignore-table=db_name.table_name 指定されたテーブルを複製しないことをスレーブスレッドに伝えます。 (even if any other tables may be update by the same command). 一つ以上の テーブルを無視するように指定するには、この命令を複数回(各テーブルに1回ず つ)使用します。これは replicate-ignore-db とは対照的に、データベー スをまたがった更新について動作します。 Example: replicate-ignore-table=db_name.some_table
replicate-wild-do-table=db_name.table_name 指定されたワイルドカードパターンに適合するテーブルに複製を制限することをス レーブスレッドに伝えます。一つ以上のテーブルを指定するには、この命令を複数 回(各テーブルに1回ずつ)使用します。これはデータベースをまたがった更新につ いて動作します。 Example: replicate-wild-do-table=foo%.bar%foo で始まるすべての データベースの bar で始まるテーブルだけに更新を複製します。 Note that if you do replicate-wild-do-table=foo%.% then the rule will be propagated to CREATE DATABASE and DROP DATABASE, i.e. these two statements will be replicated if the database name matches the database pattern ('foo%' here) (this magic is triggered by '%' being the table pattern).
replicate-wild-ignore-table=db_name.table_name 与えられたワイルドカードパターンに適合するテーブルを複製しないことをスレー ブスレッドに伝えます。一つ以上のテーブルを無視するように指定するには、この 命令を複数回(各テーブルに1回ずつ)使用します。これはデータベースをまたがっ た更新について動作します。 Example: replicate-wild-ignore-table=foo%.bar%foo で始まるすべての データベースの bar で始まるテーブルを更新しません。 Note that if you do replicate-wild-ignore-table=foo%.% then the rule will be propagated to CREATE DATABASE and DROP DATABASE, i.e. these two statements will not be replicated if the database name matches the database pattern ('foo%' here) (this magic is triggered by '%' being the table pattern).
replicate-ignore-db=database_name Tells the slave thread to not replicate any command where the current database (i.e. the one selected by USE) is database_name. To specify more than one database to ignore, use the directive multiple times, once for each database. You should not use this directive if you are using cross table updates and you don't want these update to be replicated. The main reason for this ``just-check-the-current-database'' behaviour is that it's hard from the command alone to know if a query should be replicated or not ; for example if you are using multi-table-delete or multi-table-update commands in MySQL 4.x that go across multiple databases. It's also very fast to just check the current database, as this only has to be done once at connect time or when the database changes. If you need cross database updates to work, make sure you have 3.23.28 or later, and use replicate-wild-ignore-table=db_name.%. Example: replicate-ignore-db=some_db
replicate-do-db=database_name Tells the slave thread to restrict replication to commands where the current database (i.e. the one selected by USE) is database_name. To specify more than one database, use the directive multiple times, once for each database. Note that this will not replicate cross-database queries such as 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 replicate-wild-do-table=db_name.%. Example: replicate-do-db=some_db
log-slave-updates スレーブスレッドからの更新をバイナリログに記録するように、スレーブに告げます。 デフォルトは Off です。 Of course, it requires that the slave be started with binary logging enabled (log-bin option). You have to use log-slave-updates to chain several slaves ; for example for the following setup to work
A -> B ->C
(C is a slave of B which is a slave of A) you need to start B with the log-slave-updates option.
replicate-rewrite-db=from_name->to_name Tells the slave to translate the current database (i.e. the one selected by USE) to to_name if it was from_name on the master. Only statements involving tables may be affected (CREATE DATABASE, DROP DATABASE won't), and only if from_name was the current database on the master. This will not work for cross-database updates. Example: replicate-rewrite-db=master_db_name->slave_db_name
slave-skip-errors= [err_code1,err_code2,... | all] バージョン 3.23.47 以上。 与えられたエラーコードではレプリケーションを止めないように、 スレーブスレッドに告げます。 通常、レプリケーションはエラーに出会うと中止し、マニュアルでデータの矛盾を 解決する機会をユーザに与えます。 このオプションは、なぜエラーが発生したのかを完全に理解するまでは 使用してはいけません。 もしレプリケーションのセットアップ、クライアントプログラム、MySQL 自身に なにもバグがないのであれば、エラーで止まるはずはありません。 このオプションを見境なく使用すると、スレーブで期待に反してマスタとの同期が ずれ、なぜ問題が発生したかについての理解ができない結果になるでしょう。 エラーコードには、スレーブのログファイルに記録されているものや SHOW SLAVE STATUS で出力される、数字の番号を使用しなくてはなりません。 全てのエラーメッセージは、ソース配布に含まれる Docs/mysqld_error.txt にあります. とても推奨できない値である all を使用することもできます(ですがすべ きではありません)。これはすべてのエラーメッセージを無視し、keep barging along regardless. 言うまでもなく、これを使用する場合は、データの完全性に関 してなんの保証もできません。 Please do not complain if your data on the slave is not anywhere close to what it is on the master in this case -- you have been warned. Example: slave-skip-errors=1062,1053 or slave-skip-errors=all
skip-slave-start 起動時にスレーブを開始しないようにスレーブサーバに伝えます。ユーザは後で SLAVE START で開始できます。
slave_compressed_protocol=# If 1, then use compression on the slave/client protocol if both slave and master support this.
slave_net_timeout=# 読み込みがアボートする前にマスターからデータを待つ秒数。

4.10.6 レプリケーションに関連する SQL コマンド

レプリケーションは SQL インタフェースを通じて制御できます。以下はコマンド のサマリです:

Command Description
SLAVE START スレーブスレッドを開始します。 As of MySQL 4.0.2, you can add IO_THREAD or SQL_THREAD options to the statement to start the I/O thread or the SQL thread. The I/O thread reads queries from the master server and stores them in the relay log. The SQL thread reads the relay log and executes the queries. (スレーブ)
SLAVE STOP スレーブスレッドを停止します。 Like SLAVE START, this statement may be used with IO_THREAD and SQL_THREAD options. (スレーブ)
SET SQL_LOG_BIN=0 ユーザが SUPER 権限(in MySQL 4.0.2 and above) PROCESS (in older MySQL versions) を持っている場合に 更新ログを無効にします。そうでなければ無視されます。(マスター)
SET SQL_LOG_BIN=1 ユーザが SUPER 権限(in MySQL 4.0.2 and above)か PROCESS 権限(in older MySQL versions) を 持っている場合更新ロギングを再度有効にします。 そうでなければ無視されます。(マスター)
SET GLOBAL SQL_SLAVE_SKIP_COUNTER=n マスターからの次の n イベントをスキップします。スレーブスレッ ドが実行していない場合にだけ正当です。そうでなければエラーになります。レプ リケーションの不調からの復旧に有用です。
RESET MASTER インデックスファイルにリストされたすべてのバイナリログを削除し、 binlog インデックスファイルを空にリセットします。3.23.26 バージョンより前 では、FLUSH MASTER (Master)
RESET SLAVE スレーブにマスターログのレプリケーション位置を忘れさせます。 3.23.26 バージョンより前ではこのコマンドは FLUSH SLAVE と呼ばれてい ました(Slave)
LOAD TABLE tblname FROM MASTER マスターからスレーブにテーブルのコピーをダウンロードします。主に LOAD DATA FROM MASTER のデバッグ用に実装されていますが、but some ``gourmet'' users might find it useful for other things. 自分自身が並の "非ハッカー" タイプの ユーザー(並みのユーザー)であると思う場合は、使用しないでください。 Requires that the replication user which is used to connect to the master has RELOAD and SUPER privileges on the master. Please read the timeout notes in the description of LOAD DATA FROM MASTER below, they apply here too. (Slave)
LOAD DATA FROM MASTER バージョン 4.0.0 から。 マスターのスナップショットを取り、スレーブにコピーします。 Requires that the replication user which is used to connect to the master has RELOAD and SUPER privileges on the master. スレーブが正しい位置からレプリケーションを開始するように、 MASTER_LOG_FILEMASTER_LOG_POS の値を更新します。 Will honor table and database exclusion rules specified with replicate-* options. So far works only with MyISAM tables and acquires a global read lock on the master while taking the snapshot. In the future it is planned to make it work with InnoDB tables and to remove the need for global read lock using the non-blocking online backup feature. If you are loading big tables, you may have to increase the values of net_read_timeout and net_write_timeout on both your master and slave ; see 「4.5.6.4 SHOW VARIABLES」節. Note that LOAD DATA FROM MASTER does NOT copy any tables from the mysql database. This is to make it easy to have different users and privileges on the master and the slave.
CHANGE MASTER TO master_def_list マスターパラメータを master_def_list に指定された値に変更し、 スレーブスレッドを再起動します。master_def_list はコンマで区切られ た master_def のリストです。master_def は次のうちの一つです : MASTER_HOST, MASTER_USER, MASTER_PASSWORD, MASTER_PORT, MASTER_CONNECT_RETRY, MASTER_LOG_FILE, MASTER_LOG_POS. For 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;
変更する必要のある値だけを指定する必要があります。省略した値は同じ値を維持 します。ホストまたはポートを変更した時を除きます。この場合、スレーブは異な るホストまたは異なるポートに接続しているのでマスターが異なっているとみなし ます。従って、古いログと位置の値はどこにも該当しません。そして、自動的に空 文字列と 0 にそれぞれリセットされます (開始値)。注意: スレーブを再起動する 場合、最後のマスターを覚えています。これが望ましくない場合、 `master.info' ファイルを再起動前に削除すべきです。すると、スレーブは my.cnf またはコマンドラインからそのマスターを読み込みます。 このコマンドは、マスタのスナップショットを持っていて、スナップショットに対 応するマスタ上のログとオフセットの記録がある場合に、スレーブをセットアップ するのに有用です。スナップショットからのリストア後にスレーブ上で、 CHANGE MASTER TO MASTER_LOG_FILE='log_name_on_master', MASTER_LOG_POS=log_offset_on_masterを実行できます。 (Slave)
SHOW MASTER STATUS マスターの binlog のステータス情報を提供します。(Master)
SHOW SLAVE HOSTS バージョン 4.0 からの機能。 Gives a listing of slaves currently registered with the master. (Master)
SHOW SLAVE STATUS スレーブスレッドの基本的な パラメータのステータス情報を提供します。(Slave)
SHOW MASTER LOGS バージョン 3.23.28 以降だけで有効です。 マスター上のバイナリログをリストします。 どれくらい行くべきかを見つけるためには、 このコマンドを PURGE MASTER LOGS TO よりも先に使用すべきです。 (Master)
SHOW BINLOG EVENTS [ IN 'logname' ] [ FROM pos ] [ LIMIT [offset,] rows ] バージョン 4.0 からの機能。 binary update log 中のイベントを見せます。 基本的にはテストやデバッグで使用されます。 通常のクライアントからバイナリログを読む必要がある場合にも 使用することが可能です。 (Master)
SHOW NEW MASTER FOR SLAVE WITH MASTER_LOG_FILE='logfile' AND MASTER_LOG_POS=pos AND MASTER_LOG_SEQ=log_seq AND MASTER_SERVER_ID=server_id バージョン 4.0 からの機能。 おそらく死んだ/無効になったマスタのスレーブが、同じマスタをレプリケーショ ンしていた他のスレーブからレプリケーションするようにスイッチすることが必 要な場合に、このコマンドが使用されます。コマンドは再計算されたレプリケー ション coordinates を返します (the slave's current binary log file + name and position within that file). この出力は続く CHANGE MASTER TO コマン ドで使用することができます。通常、ユーザはこのコマンドを実行する必要はあ りません。これは本来 fail-safe レプリケーションコードに内部使用に予約さ れています。この操作を記述するのにもっと直観的な方法を見つけた場合、この 文法は変更されるでしょう。
PURGE MASTER LOGS TO 'logname' バージョン 3.23.28 からの機能。 index ファイルに書かれているログファイルのうち、 指定されたログよりも前のログファイルを全て消します。 index ファイルのリストからもエントリを消します。 そして、指定されたログを一番最初の物とします。 例えば:
PURGE MASTER LOGS TO 'mysql-bin.010'
(訳注: このコマンドの場合、mysql-bin.001 〜 mysql-bin.009 までの ファイルは消され、mysql.index ファイルの中身は、mysql-bin.010 のみ、 記述される状態になるということ。) 削除しようとしているログの一つを現在読み込み中の実行中スレーブがある場合、 このコマンドは何も行なわず、エラーで失敗します。しかし、休眠中のスレーブが あり、それが読もうとしているログの一つをパージしてしまうと、スレーブは複製 できなくなります。このコマンドはスレーブが複製中には安全に実行できます - それらを停止する必要はありません。 最初に SHOW SLAVE STATUS で、どのログが on になっているか、すべての スレーブをチェックする必要があります。それからマスターで SHOW MASTER LOGS でログのリストを行ない、すべてのスレーブに共通の最も古いログ を見つけ(すべてのスレーブが最新の場合、リストの最後のログになります)、削除 しようとするすべてのログをバックアップし、目的のログをパージします。

4.10.7 Replication FAQ

Q: マスタが既に走っている状態で、マスタを止めないで、新しく スレーブを作るには、どのようにすればいいの?

A: いくつか方法があります。 もしマスタのどこかの時点でのバックアップを取っていて、そして そのバックアップした時点に対応する バイナリログの名前と位置を記録しているのであれば、 ( SHOW MASTER STATUS で知ることが出来ます) 以下のようにします:

もし現在のマスタのバックアップを取っていないのであれば、以下が素早く セットアップする方法です:

Afterwards, follow the instructions for the case when you have a snapshot and have recorded the log name and offset. 同じスナップショットをいくつものスレーブをセットアップするために使用す ることができます。一度マスタのスナップショットを得れば、マスタのバイナ リログが無傷で残っている限り、何日でも場合によっては一月でも、待ってス レーブを設定することができます。理論的には待つ期間は無限にできます。2 つの現実的な制限があり、1つは古いログで一杯になるマスタのディスク容量 と、スレーブがキャッチアップするのに掛かる時間の大きさです。

バージョン 4.0.0 以降では、LOAD DATA FROM MASTER も使用できます。 これは、スナップショットを取ってスレーブにリストアし、ログ名とオフセッ トをスレーブ上で一度に調整する便利なコマンドです。将来、LOAD DATA FROM MASTER はスレーブをセットアップする推奨方法になるでしょう。 しかし、このコマンドを使用する場合、読み込みロックが長い時間保持される こともあることに注意してください。まだ、我々がそうしたいほど効率よくは 実装されていません。大きなテーブルがある場合、現時点での推奨方法は、ま だ FLUSH TABLES WITH READ LOCK 実行後のローカル tar スナッ プショットです。

Q: スレーブは常にマスターに接続していなければならないの?

A: いいえ、その必要はありません。 スレーブを数時間でも数日でも止めたり落としたりしておき、 そのあと再接続して、更新を行ない、再度また、スレーブを落とすことが可能です。 So you can, for example, use master-slave setup over a dial-up link that is up only for short periods of time. The implications of that are that at any given time the slave is not guaranteed to be in sync with the master unless you take some special measures. In the future, we will have the option to block the master until at least one slave is in sync.

Q: スレーブがキャッチアップするまで、マスタの更新をブロックする には?

A: 次のコマンドを実行してください:

Q: Why do I sometimes see more than one Binlog_Dump thread on the master after I have restarted the slave?

A: Binlog_Dump is a continuous process that is handled by the server in the following way:

So if the slave thread stops on the slave, the corresponding 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 pthread_cond_wait(). In the meantime, the slave could have opened another connection, which resulted in another 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 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

Q: replication log をどうやってローテートするの?

A: バージョン 3.23.28 からでは、PURGE MASTER LOGS TO コマンド を使用するべきです。 実行前には、どのログが消せれるか確認し、場合によっては バックアップを取っておきます。 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.

Q: How do I upgrade on a hot replication setup?

A: If you are upgrading pre-3.23.26 versions, you should just lock the master tables, let the slave catch up, then run FLUSH MASTER on the master, and 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.

バージョン 3.23.26 以降では、レプリケーションプロトコルのロック (変更のための)を持ちます。 そのため、あなたはマスタとスレーブを on the fly で 新しい 3.23 バージョンにアップグレードできます。 そして、マスタとスレーブがバージョン 3.23.26 以上の場合においては、 マスタとスレーブが違うバージョンの MySQL でもかまいません。

Q: What issues should I be aware of when setting up two-way replication?

A: MySQL replication currently does not support any locking protocol between master and slave to guarantee the atomicity of a distributed (cross-server) update. 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 from 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 realise 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 serialised in one slave thread. This benefit, though, might be offset by network delays.

Q: How can I use replication to improve performance of my system?

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 --skip-bdb, --low-priority-updates and --delay-key-write=ALL to get speed improvements for the slave. In this case the slave will use non-transactional MyISAM tables instead of BDB tables to get more speed.

Q: What should I do to prepare my client code to use performance-enhancing replication?

A: If the part of your code that is responsible for database access has been properly abstracted/modularised, 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:

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 replace utility, which comes with the standard distribution of MySQL, or just write your own Perl script. Hopefully, your code follows some recognisable pattern. If not, then you are probably better off rewriting 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.

Q: When and how much can MySQL replication improve the performance of my system?

A: 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 max_reads) and on writes max_writes) on a typical master and a typical slave. The example here 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 max_reads = 1200 - 2 * 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):

reads = 1200 - 2 * writes (from bencmarks)

reads = 9* writes / (N + 1) (reads split, but writes go to all servers)

9*writes/(N+1) + 2 * writes = 1200

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:

Q: 冗長性/高可用性を提供するようにレプリケーションを使用するには?

A: 現在有効な機能で、マスターとスレーブ(またはいくつかのスレーブ 達)をセットアップする必要があります。マスターが生きているかどうかを監視し、 アプリケーションとマスターのスレーブに失敗時に変更を指示するスクリプトを書 きます。以下はいくつかの提案です:

我々は現在自動マスター選択システムを MySQL に統合するように働いていますが、 準備ができるまでは、あなた自身のモニタリングツールを作成する必要があります。

Q: How does the slave server keep track of where it is on the master?

A: The slave uses a file in the the data directory defined by the master-info-file=filename path. This file holds all the information needed by the slave to request new updates. The file contains the following information:

Line# Description
1 Binary log file id
2 Log file postion
3 Host (master)
4 Login user
5 Login password
6 Login port
7 Interval, the length of time between reconnects

4.10.8 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:

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 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.

The second best option is to write a simple 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 mysqlbug to prepare a bug report and send it to bugs@lists.mysql.com. If you have a phantom -- a problem that does occur but you cannot duplicate "at will":

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 bugs@lists.mysql.com with as much info as possible.


Go to the first, previous, next, last section, table of contents.