brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: pg_restore --clean --if-exists overwrites a database without a wall of errors

Database
~/tips/tip-database-pg-restore-clean-if-exists

pg_restore --clean --if-exists -d appdb appdb.dump

Drops existing objects before a restore and skips the errors for objects that were never there.

Restoring a dump into a database that already has the same tables normally ends in a long list of "already exists" errors. --clean deals with that by dropping objects first, and one extra flag keeps the output readable.

pg_restore --clean --if-exists -d appdb appdb.dump

This is the part of the docs that matters: --clean issues DROP commands for all objects that will be restored before it restores them, which makes it useful for overwriting an existing database. When some objects do not exist in the target, you get ignorable error messages, unless you add --if-exists. That switches to DROP ... IF EXISTS and suppresses the "does not exist" errors. The docs state that --if-exists is not valid without --clean.

There is a related option, --create, which creates the database before restoring into it. Combined with --clean it drops and recreates the target database before connecting to it. In that case the database named with -d is only used to issue the DROP DATABASE and CREATE DATABASE commands, and the docs use postgres in their example.

Warning, because this one is destructive. Everything in the dump replaces what is in the target, and objects that exist only in the target are not dropped. Do this on a copy first, or on a database you have a fresh dump of. I would run it into a throwaway database before pointing it at the real one.

One more limit from the docs: --create cannot be used together with --single-transaction.

Further reading: PostgreSQL documentation: pg_restore

More Database tips mariadb -e 'CREATE DATABASE IF NOT EXISTS blog' mariadb-dump --no-create-info --insert-ignore shop orders > orders-rows.sql SELECT table_schema, table_name, CHECKSUM TABLE shop.orders; services: All Database tips (53) All topics

Link