天天看點

pg_dump 詳解/使用舉例

pg_dump是一個用于備份PostgreSQL資料庫的實用工具。即使目前資料庫正在使用,也能夠生成一緻性的備份,且不會阻塞其他使用者通路資料庫(包括讀、寫)

pg_dump隻能備份一個資料庫。如果要備份Cluster中資料庫共有的全局對象,例如角色和表空間,需要使用pg_dumpall。

備份檔案以文本或存檔檔案格式輸出。Script dumps是一個普通文本檔案,包含将資料庫重構到儲存時的狀态所需的SQL指令。

要從這樣的腳本恢複,需要将其提供給psql。腳本檔案甚至可以用來在其他機器或者其他架構上重構資料庫;進行一些必要的修改,甚至可以在其他資料庫上使用。

其他歸檔檔案格式必須與pg_restore一起使用進行資料庫的重建。pg_restore可以選擇要還原的内容,甚至可以在還原之前對待還原項進行重新排序。歸檔檔案格式可以在不同的架構中使用。

歸檔檔案格式與pg_restore組合使用時,pg_dump提供了一個靈活的歸檔傳遞機制。可以使用pg_dump備份整個資料庫。pg_restore可用于檢查存檔和選擇要還原資料庫的哪些部分。

最靈活的輸出檔案格式是“自定義”格式(-Fc)和“目錄”格式(-Fd)。它們允許選擇和重新排序所有存檔項,支援并行恢複,以及預設情況下是壓縮的。“目錄”格式是唯一支援并行備份的格式。

To dump a database called mydb into a SQL-script file:

$ pg_dump mydb > db.sql

To reload such a script into a (freshly created) database named newdb:

$ psql -d newdb -f test.sql

To dump a database into a custom-format archive file:

$ pg_dump -Fc test > test.dump

To dump a database into a directory-format archive:

$ pg_dump -Fd test -f dumpdir

To dump a database into a directory-format archive in parallel with 5 worker jobs:

$ pg_dump -Fd test -j 5 -f dumpdir5

To reload an archive file into a (freshly created) database named newdb:

$ pg_restore -d dump_test test.dump

To dump a single table named mytab:

$ pg_dump -t mytab mydb > db.sql

To dump all tables whose names start with emp in the detroit schema, except for the table named

employee_log:

$ pg_dump -t 'journal*' -T journal_10 test > test_journal.sql

To dump all schemas whose names start with east or west and end in gsm, excluding any schemas

whose names contain the word test:

$ pg_dump -n 'eastgsm' -n 'westgsm' -N 'test' mydb > db.sql

The same, using regular expression notation to consolidate the switches:

$ pg_dump -n '(east|west)gsm' -N 'test*' mydb > db.sql

To dump all database objects except for tables whose names begin with ts_:

$ pg_dump -T 'ts_*' mydb > db.sql

To specify an upper-case or mixed-case name in -t and related switches, you need to double-quote

the name; else it will be folded to lower case (see Patterns). But double quotes are special to the

shell, so in turn they must be quoted. Thus, to dump a single table with a mixed-case name, you need something like

$ pg_dump -t ""MixedCaseName"" mydb > mytab.sql