diff --git a/dbbackup/db/postgresql.py b/dbbackup/db/postgresql.py index 1dd737a..bbbf42f 100644 --- a/dbbackup/db/postgresql.py +++ b/dbbackup/db/postgresql.py @@ -112,6 +112,7 @@ class PgDumpBinaryConnector(PgDumpConnector): restore_cmd = "pg_restore" single_transaction = True drop = True + if_exists = False def _create_dump(self): cmd = f"{self.dump_cmd} " @@ -141,6 +142,9 @@ def _restore_dump(self, dump): if self.schemas: cmd += " -n " + " -n ".join(self.schemas) + if self.if_exists: + cmd += " --if-exists" + cmd = f"{self.restore_prefix} {cmd} {self.restore_suffix}" stdout, stderr = self.run_command(cmd, stdin=dump, env=self.restore_env) return stdout, stderr diff --git a/dbbackup/tests/test_connectors/test_postgresql.py b/dbbackup/tests/test_connectors/test_postgresql.py index cf78b60..5a748bc 100644 --- a/dbbackup/tests/test_connectors/test_postgresql.py +++ b/dbbackup/tests/test_connectors/test_postgresql.py @@ -212,6 +212,17 @@ def test_create_dump_drop(self, mock_dump_cmd): self.connector.create_dump() self.assertNotIn(" --clean", mock_dump_cmd.call_args[0][0]) + def test_create_dump_if_exists(self, mock_dump_cmd, mock_restore_cmd): + dump = self.connector.create_dump() + # Without + self.connector.if_exists = False + self.connector.restore_dump(dump) + self.assertNotIn(" --if-exists", mock_restore_cmd.call_args[0][0]) + # With + self.connector.if_exists = True + self.connector.restore_dump(dump) + self.assertIn(" --if-exists", mock_restore_cmd.call_args[0][0]) + @patch( "dbbackup.db.postgresql.PgDumpBinaryConnector.run_command", return_value=(BytesIO(), BytesIO()), diff --git a/docs/changelog.rst b/docs/changelog.rst index 2715009..5d2286e 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,7 +4,7 @@ Changelog Unreleased ---------- -* Nothing (yet)! +* Add option `--if-exists` for pg_dump command 4.2.1 (2024-08-23) ---------- diff --git a/docs/databases.rst b/docs/databases.rst index ac04af4..5832017 100644 --- a/docs/databases.rst +++ b/docs/databases.rst @@ -166,6 +166,13 @@ This corresponds to ``--clean`` argument of ``pg_dump`` and ``pg_restore``. Default: ``True`` +IF_EXISTS +~~~~ + +Use DROP ... IF EXISTS commands to drop objects in ``--clean`` mode of ``pg_dump``. + +Default: ``False`` + PostGIS -------