PostgreSQL pg_dump – Table and Transitive Dependencies

pg-dumppostgresql

Sometimes I'd like to export just a single table and its dependencies, so I can do some experiments with it on a test database. Is there a way to do that, other than dumping the full db schema with pg_dump and any table dependencies manually?

For example let's say I have a table employees which has a single foreign key to companies.id and uses a few custom enums or other types. Let's also assume companies is self-contained, i.e. does not depend on anything else. So what I'd like to have is some way of dumping employees, both schema and all (or a subset) of the data and automatically get the required type definitons, and the schema for company as well as all referencered entries.

Is there a way to do this easily with pg_dump or some other tool?

Best Answer

uses a few custom enums or other types.

No. That's because those enum types can be used in different tables and such. PostgreSQL doesn't have a dependency tracker to make this work. The only exception to this that I know is sequences, -t will recreate sequences.

That said, if you recreate the database once, you only ever have to run pg_dump -t employees -c, the -c flag will drop the table and recreate it. This will unfortunately not work with foreign key constraints pointing to employees