How to clone a test database from a production one in one single action?

后端 未结 4 2150
不思量自难忘°
不思量自难忘° 2021-02-07 22:11

I am looking for a basic script/command that will create a copy of a live database (let name them mydb and mydb_test, both on the same server).

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-02-07 23:05

    That's what I was looking for, but I had to compile it myself :P

    I only wish I knew a way to keep the same user and not having to put it inside the script.

    
    #!/bin/bash
    DB_SRC=conf
    DB_DST=conf_test
    DB_OWNER=confuser
    
    T="$(date +%s)"
    
    psql -c "select pg_terminate_backend(procpid) from pg_stat_activity where datname='$DB_DST';" || { echo "disconnect users failed"; exit 1; }
    psql -c "drop database if exists $DB_DST;" || { echo "drop failed"; exit 1; }
    psql -c "create database $DB_DST owner confuser;" || { echo "create failed"; exit 1; }
    pg_dump $DB_SRC|psql $DB_DST || { echo "dump/restore failed"; exit 1; }
    
    T="$(($(date +%s)-T))"
    echo "Time in seconds: ${T}"
    

提交回复
热议问题