Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can pg_dump be instructed to create tables with "IF NOT EXISTS"?

As per the title.

I've looked at the man page and it doesn't seem like there is any command-line argument to include the "IF NOT EXISTS" clause in the "CREATE TABLE" statements.

like image 751
magnus Avatar asked Jun 17 '15 00:06

magnus


People also ask

How do you create table if not exists in Postgres?

Use the CREATE TABLE statement to create a new table. Use the IF NOT EXISTS option to create the new table only if it does not exist. Apply the primary key, foreign key, not null, unique, and check constraints to columns of a table.

What does the pg_dump command do?

pg_dump can be used to backup an entire database, then pg_restore can be used to examine the archive and/or select which parts of the database are to be restored. The most flexible output file formats are the “custom” format ( -Fc ) and the “directory” format ( -Fd ).

Does pg_dump lock table?

pg_dump doesn't lock the entire database, it does get an explicit lock on all the tables it is going to dump, though.


1 Answers

No. The closest that pg_dump comes to this in terms of a built-in option is --if-exists, which only works in conjunction with --clean, meaning it only applies to things like DROP commands.

If you want to add this sort of thing, I think your best bet would be to post-process the dumps (assuming you are dumping to pure SQL and not binary format). To cover all the variety of cases, you would technically need a regex that covers this portion of the CREATE TABLE command grammar:

CREATE [ [ GLOBAL | LOCAL ] { TEMPORARY | TEMP } | UNLOGGED ] TABLE
       [ IF NOT EXISTS ] table_name

However a simpler regex will likely cover most cases (for example, I don't think you'd ever be dumping temp tables, pretty much definitionally, so that part can be ignored). Similarly, GLOBAL and LOCAL are deprecated, so those can perhaps also be safely ignored, depending on your data.

pg_dump doc for reference.

like image 193
khampson Avatar answered Oct 27 '22 09:10

khampson