Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(pg_dump): Add '--if-exists' option for pg_dump (and add tests) #515

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions dbbackup/db/postgresql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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} "
Expand Down Expand Up @@ -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
11 changes: 11 additions & 0 deletions dbbackup/tests/test_connectors/test_postgresql.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
2 changes: 1 addition & 1 deletion docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Changelog
Unreleased
----------

* Nothing (yet)!
* Add option `--if-exists` for pg_dump command

4.2.1 (2024-08-23)
----------
Expand Down
7 changes: 7 additions & 0 deletions docs/databases.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-------

Expand Down
Loading