copy database structure without data in mysql (with empty tables)

前端 未结 6 1240
醉酒成梦
醉酒成梦 2021-01-31 02:36

Is there any way to copy database structure without data in MySQL, so the new database will be the same as it is copied from, but with empty tables.

After getting some s

6条回答
  •  悲哀的现实
    2021-01-31 02:58

    mysqldump -d is not enough because in TRIGGERS, PROCEDURES etc. you can have references like 'old_db'.tb_name that must be replaced with 'new_db'.tb_name

    # ./db_clone.sh  old_db  new_db

    I use a file /root/.mysqlcnx with credentials (instead of using -u root -pPass)

    [client]
    user = root # or powerfull_user with GRANTS 
    password = pass_string
    host = localhost
    

    and the following script to clone a database [ experiment it on a virtual machine for confidence ]

    #!/bin/bash
    
    if [ $# -lt 2 ]; then
       echo "syntax:\n.\db_clone.sh source_db_name target_db_name [--drop]\n"
    exit 1
    fi
    
        # checking target database $2 exits
    tg_db=$(mysql --defaults-extra-file=~/.mysqlcnx -s -N -e "SELECT count(*)>0 FROM 
             information_schema.SCHEMATA where SCHEMA_NAME='${2}'")
    if [ $tg_db = '1' ]; then
        # checking target database has tables
        tg_tb=$(mysql --defaults-extra-file=~/.mysqlcnx -s -N -e " SELECT count(*) > 0 
                FROM information_schema.TABLES WHERE TABLE_SCHEMA='${2}'")
      if [ $tg_tb = '1' ]; then
         if [ $# -eq 3 ] && [ "$3" = '--drop' ]; then
            echo "TYPE 'YES' (case sensitive) TO OVERRIDE"
            read opt # request confirmation 
            if [ "$opt" != "YES" ]; then
                echo "OPERATION CANCELED!"
                exit 1
            fi
         else
           printf "DATABASE \"${2}\" EXISTS AND HAS TABLES\nUSE --drop as 3rd arg to override!\n"
           exit 1
         fi
      fi
    else 
      mysql --defaults-extra-file=~/.mysqlcnx -e "CREATE DATABASE \`${2}\`" 
    fi
    
    echo "CREATING ${2}"
    mysqldump --defaults-extra-file=~/.mysqlcnx -d $1 | # dump source
    sed "s/\`${1}\`\./\`${2}\`\./g" |  #  solving `source_db`.tb_name       
    sed 's/AUTO_INCREMENT=[0-9]\+/''/g' | # solving  AUTO_INCREMENT=1
    mysql --defaults-extra-file=~/.mysqlcnx $2  # populating target_db 
    echo "DONE"
    

    NOTE: someone that knows bash better please correct me if necessary

提交回复
热议问题