Postgresql – pg_restore restore FK constraints with explicit –table argument

pg-restorepostgresql

I started using the -t argument of pg_restore to only restore some tables, which has worked well for read-only workflows.

The problem is that the -t seems to not restore the FK constraints nor sequences applied to the table/column.

Regarding the former (sequence), it seems that the tables restored with -t which had an id column with a modifier of not null default nextval('report_id_seq'::regclass) was restored with just not null, so the sequence isn't applied, which is an obvious.

Is there a way to use pg_restore with explicit tables using -t that also restore foreign-key constraints and sequences?

Best Answer

What you probably want is to restore all things that are not data. So try -s, from man pg_restore

-s
--schema-only
    Restore only the schema (data definitions), not data, to the extent
    that schema entries are present in the archive.

    This option is the inverse of --data-only. It is similar to, but
    for historical reasons not identical to, specifying
    --section=pre-data --section=post-data.

    (Do not confuse this with the --schema option, which uses the word
    “schema” in a different meaning.)

Note that schema is everything. Foreign key constraints mean you may not be able to load just the data for a table. From pg_dump

when -t is specified, pg_dump makes no attempt to dump any other database objects that the selected table(s) might depend upon. Therefore, there is no guarantee that the results of a specific-table dump can be successfully restored by themselves into a clean database.

So if you've got a clean database, and you try to restore with -t you're potentially attempting to insert data the conflicts keys and constraints specified in the schema -s.