From b9cac95249caee94f655ffc5eb97f6e986a87b8a Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Wed, 7 Oct 2020 17:50:04 +0100 Subject: [PATCH] Add note about truncating a database from the inside --- notes/psql/truncate-database.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 notes/psql/truncate-database.md diff --git a/notes/psql/truncate-database.md b/notes/psql/truncate-database.md new file mode 100644 index 0000000..f34256b --- /dev/null +++ b/notes/psql/truncate-database.md @@ -0,0 +1,22 @@ +--- +title: Truncate a database from the inside +tags: + - PostgreSQL +emoji: 🐘 +--- + +How to delete database from the inside, with only access to that database. + +The primary way this works is by using `pg_dump`'s ability to drop a schema before recreating it. + +This creates a dump of the database without any data, and with a fresh schema (drop then rebuild). This output is then `grep`'d to only contain the drops. + +```sh +pg_dump -cs "postgres://" | grep DROP > drops.psql.sql +``` + +Now run the drops. These drops are specifically designed for this schema so should be complete and in the correct order. + +```sh +psql "postgres://" < drops.psql.sql +```