0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLで該当DBの全`table create statement`を出力する

Last updated at Posted at 2019-02-15

訂正

コメントで @akinomyoga さんに指摘していただいた部分を取り込みました。

本文

MySQLで該当DBの全table create statementを出力する方法を探したが、どうやらループで mysql 回すしかないらしく、苦手なshell scriptを書いた。

mysql-all-statement
#!/usr/bin/env bash

function usage {
    cat <<EOF
$(basename "${0}") is a tool for print all tables create statement

Example:
    $(basename "${0}") -p -h localhost -u root master_database > report.txt

Usage:
    $(basename "${0}") [-p password] [mysql options] [database]

Options:
    --help            print this.
    -p, --password    database password.
                      If password is not given it is asked from the tty.

mysql options:
    other options see "mysql --help"
EOF
}

case ${1} in
    --help|-help|'')
        usage
        exit
    ;;

    -p|--password)
        if [[ ${2} == -* ]]; then
            read -sp "Password:" PASSWORD 2> /dev/tty
            echo > /dev/tty
        else
            PASSWORD=${2}
            shift
        fi
        shift
    ;;
esac

if [[ -z ${PASSWORD} ]]; then
  SCRIPT_MYSQL="mysql $@"
else
  SCRIPT_MYSQL="mysql -p\"\${PASSWORD}\" $@"
fi

LIST=(`echo "SHOW TABLES" | eval "${SCRIPT_MYSQL}" 2> /dev/null`)
if [[ ${LIST} != Tables_in_* ]]; then
  echo "mysql command error: run \`${SCRIPT_MYSQL}\`" >&2
  exit 1
fi

for t in "${LIST[@]:1}"
do
    echo "SHOW CREATE TABLE $t\G" | eval "${SCRIPT_MYSQL}" 2> /dev/null
done

基本的にはMySQLで既存のテーブルのCREATE文を取得: Usoinfo blogのコードをベースに汎用的にしただけです。

-p オプションだけ先頭に書かないといけないというなんともスマートじゃない感じになってしまったので、そこだけご注意を。

もっと色々セフティー作れる気がするんですが、とりあえずのツールなのでここまで。
何か他にいい方法や、こここうしたら?みたなのがあればコメントください。

0
2
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?