PG备份一(逻辑备份)
逻辑备份
pg_dump:只能备份单个数据库
pg_dumpall:可以备份所有数据库(用户,表空间,权限),pg_dumpall只支持文本格式,pg_dumpall需要多次连接postgresql服务器
一、pg_dump
1.创建数据库test并插入测试数据
postgres=# create database test;
CREATE DATABASE
postgres=# \c test
You are now connected to database "test" as user "postgres".
test=# CREATE TABLE test_data (id SERIAL PRIMARY KEY,name VARCHAR(100),email VARCHAR(100),age INTEGER,salary DECIMAL(10,2),is_active BOOLEAN,created_at TIMESTAMP
);INSERT INTO test_data (name, email, age, salary, is_active, created_at)
SELECT 'User_' || floor(random() * 1000)::INT,'user_' || floor(random() * 1000)::INT || '@example.com',floor(random() * 70 + 18)::INT,round((random() * 9000 + 1000)::NUMERIC, 2),random() > 0.5,NOW() - (random() * INTERVAL '365 days')
FROM generate_series(1, 100);
--查询验证
test=# select count(*) from test_data;count
-------100
2.使用pg_dump备份并恢复
(1)创建备份目录
mkdir -p /dbs/pg14/pgback
(2)pg_dump备份
备份方法 一:
postgres@pghost01 pgback]$ pg_dump test --file=/dbs/pg14/pgback/testdb.sql
--导出为tar文件方式
pg_dump --username=postgres --host=192.168.75.131 --port=5666 --dbname=test --format=tar --file=/dbs/pg14/pgback/testdb.tar
备份方法二:可以使用Insert进行导出
pg_dump test --inserts > /dbs/pg14/pgback/testdb01.sql
--tar文件
备份方法三:
--可以进行导出压缩(文件为二进制,恢复需使用pg_restore恢复)
pg_dump --dbname=test --format=custom --file=/dbs/pg14/pgback/testdb.dmp
--恢复方式
pg_restore --username=postgres --host=192.168.75.131 --port=5666 --dbname=test02 /dbs/pg14/pgback/testdb.dmp
(3)创建新库执行恢复(方法一恢复)
postgres=# create database test02;
CREATE DATABASE
--恢复
[postgres@pghost01 pgback]$ psql --dbname=test02 --file=testdb.sql
SET
SET
SET
SET
SETset_config
------------(1 row)SET
SET
SET
SET
SET
SET
CREATE TABLE
ALTER TABLE
CREATE TABLE
ALTER TABLE
CREATE SEQUENCE
ALTER TABLE
ALTER SEQUENCE
ALTER TABLE
COPY 1
COPY 100setval
--------100
(1 row)ALTER TABLE
--验证数据
[postgres@pghost01 pgback]$ psql
psql (14.11)
Type "help" for help.postgres=# \c test02
You are now connected to database "test02" as user "postgres".
test02=# \dtList of relationsSchema | Name | Type | Owner
--------+-----------+-------+----------public | a | table | postgrespublic | test_data | table | postgres
(2 rows)test02=# select count(*) from test_data;count
-------100
(1 row)
二、pg_dumpall
1.导出全库
pg_dumpall >/dbs/pg14/pgback/pg_all.sql
2.可单独导出role,tablespace ,owner 使用如下参数
-g, --globals-only dump only global objects, no databases
-O, --no-owner skip restoration of object ownership
-r, --roles-only dump only roles, no databases or tablespaces
-s, --schema-only dump only the schema, no data
-S, --superuser=NAME superuser user name to use in the dump
-t, --tablespaces-only dump only tablespaces, no databases or roles
注:pg_dumpall 导入的时候,不存在的会导入,存在的将不会导入