PostgreSQL在命令行上使用密码备份和还原pg_dump的sql

时间:2022-06-01 12:37:16

以下脚本是PostgreSQL用来在命令行上使用密码对pg_dump进行备份以及还原sql

# linux上的最佳实践
nano ~/.pgpass
*:5432:*:username:password
chmod 0600 ~/.pgpass
# windows上的最佳实践
edit %APPDATA%\postgresql\pgpass.conf
*:5432:*:username:password
# linux
PGPASSWORD="password" pg_dump --no-owner -h host -p port -U username database > file.sql
# windows
PGPASSWORD=password&& pg_dump --no-owner -h host -p port -U username database > file.sql
# 可选
pg_dump --no-owner --dbname=postgresql://username:password@host:port/database > file.sql
# 恢复
psql --set ON_ERROR_STOP=on -U postgres -d database -1 -f file.sql
pg_restore --no-privileges --no-owner -U postgres -d database --clean file.sql # only works for special dumps
# 排除指定的table做备份
pg_dump --no-owner -h 127.0.0.1 -p 5432 -U username --exclude-table=foo database > tmp.sql
# 指定包含的table做备份
pg_dump --no-owner -h 127.0.0.1 -p 5432 -U username --table=foo database > tmp.sql
# 备份以及恢复
PGPASSWORD=password && pg_dump --no-owner -h 127.0.0.1 -p 5432 -U username database > tmp.sql
psql -U postgres -d database -c "drop schema public cascade; create schema public;"
psql --set ON_ERROR_STOP=on -U postgres -d database -1 -f tmp.sql
rm tmp.sql
# 如果之后需要删除无意备份的所有者
sed -i.bak '/OWNER TO specialowner/d' input.sql