The following few commands I’ve listed have been a lifesaver many times in my career, I’ve curated these commands from many different forums, their official documentation, and my personal experience.
Postgres Database Management - Copy, Reset, and Populate Commands
1 min read
What you need to do first is make sure you have the psql CLI installed on your machine
1. Copy the main DB to database_dump
These values can be found in your database provider, in my case I’m using render.com
PGPASSWORD="DB_PASS" pg_dump -h frankfurt-postgres.render.com -U DB_USER DB_NAME \ -n public --no-owner > database_dump.sq
The values you need
DB_PASS, DB_USER, DB_NAME, and the URL for your database host in my case is frankfurt-postgres.render.com
2. Resetting the local DB
There are many commands for doing this, however, for me, only one very weird command worked properly.
First in the terminal run psql name-of-database
With this, you now can query/change your database, run the following command in order to delete all the data, and reset the local DB.
JSON
DO $$ DECLAREr RECORD;BEGINFOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema() AND tablename != 'spatial_ref_sys') LOOPEXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';END LOOP;END $$;
3. Populate the local DB
PGPASSWORD="your password" psql -h localhost -u postgres DATABASE_NAME < database_dump.sql
My example
PGPASSWORD=damjan psql -h localhost -U postgres mylocaldb < database_dump.sql
If everything goes as it should, your local DB should now be an exact replica of the production one. Hope this post helped you figure out this tedious process.
If you’re using Prisma and would like to know how I migrate my database painlessly checkout this tutorial