Debian Codegraph @

dbbackup/db/postgresql.py

raw
1 from __future__ import annotations
2
3 import logging
4 import shlex
5 from typing import Any, ClassVar
6 from urllib.parse import quote
7
8 from dbbackup.db.base import BaseCommandDBConnector
9
10 logger = logging.getLogger("dbbackup.command")
11
12
13 def _host_requires_uri_quoting(host: str) -> bool:
14 # Match *nix paths (e.g. /run/postgres) and Windows paths (e.g. C:\path\to\socket)
15 return host.startswith(("/", "@")) or (
16 len(host) >= 3 and host[0].isalpha() and host[1] == ":" and host[2] in ("/", "\\")
17 )
18
19
20 def parse_postgres_settings(connector: PgDumpBinaryConnector | PgDumpConnector) -> tuple[str, dict[Any, Any]]:
21 """
22 Parse the common Postgres connectors settings and
23 generate a portion of the command string and any
24 relevant environment variables.
25
26 Args:
27 connector: Database connector instance with settings
28
29 Returns:
30 tuple: (cmd_part, environment_dict)
31 """
32 host = connector.settings.get("HOST")
33 if host is None:
34 host = "localhost"
35 elif _host_requires_uri_quoting(host):
36 host = quote(host, safe="")
37 cmd_part = connector.settings.get("NAME", "")
38 user = quote(connector.settings.get("USER") or "")
39 password = connector.settings.get("PASSWORD", -1)
40 if user:
41 host = f"@{host}"
42 port = f":{connector.settings.get('PORT')}" if connector.settings.get("PORT") else ""
43 cmd_part = f"--dbname=postgresql://{user}{host}{port}/{cmd_part}"
44 env = {}
45 if password is None:
46 cmd_part += " --no-password"
47 elif password not in ("", -1):
48 env["PGPASSWORD"] = password
49 return cmd_part, env
50
51
52 class PgDumpConnector(BaseCommandDBConnector):
53 """
54 PostgreSQL connector, it uses `pg_dump` to create an SQL text file
55 and `psql` for restore it.
56 """
57
58 extension = "psql"
59 dump_cmd = "pg_dump"
60 restore_cmd = "psql"
61 single_transaction = True
62 drop = True
63 if_exists = True
64 schemas: ClassVar[list[str] | None] = []
65
66 def _create_dump(self):
67 cmd_part, pg_env = parse_postgres_settings(self)
68 cmd = f"{self.dump_cmd} {cmd_part}"
69
70 for table in self.exclude:
71 cmd += f" --exclude-table-data={table}"
72
73 if self.drop:
74 cmd += " --clean"
75
76 if self.if_exists or self.drop:
77 cmd += " --if-exists"
78
79 if self.schemas:
80 # First schema is not prefixed with -n
81 # when using join function so add it manually.
82 cmd += " -n " + " -n ".join(self.schemas)
83
84 cmd = f"{self.dump_prefix} {cmd} {self.dump_suffix}"
85 stdout, _stderr = self.run_command(cmd, env={**self.dump_env, **pg_env})
86 return stdout
87
88 def _restore_dump(self, dump):
89 cmd_part, pg_env = parse_postgres_settings(self)
90 cmd = f"{self.restore_cmd} {cmd_part}"
91
92 # without this, psql terminates with an exit value of 0 regardless of errors
93 cmd += " --set ON_ERROR_STOP=on"
94
95 if self.schemas:
96 cmd += " -n " + " -n ".join(self.schemas)
97
98 if self.single_transaction:
99 cmd += " --single-transaction"
100
101 cmd += f" {self.settings['NAME']}"
102 cmd = f"{self.restore_prefix} {cmd} {self.restore_suffix}"
103 stdout, stderr = self.run_command(cmd, stdin=dump, env={**self.restore_env, **pg_env})
104 return stdout, stderr
105
106
107 class PgDumpGisConnector(PgDumpConnector):
108 """
109 PostgreGIS connector, same than :class:`PgDumpGisConnector` but enable
110 postgis if not made.
111 """
112
113 psql_cmd = "psql"
114
115 def _enable_postgis(self):
116 cmd = f'{self.psql_cmd} -c "CREATE EXTENSION IF NOT EXISTS postgis;"'
117 cmd += f" --username={shlex.quote(self.settings['ADMIN_USER'])}"
118 cmd += " --no-password"
119
120 if self.settings.get("HOST"):
121 cmd += f" --host={shlex.quote(self.settings['HOST'])}"
122
123 if self.settings.get("PORT"):
124 cmd += f" --port={shlex.quote(str(self.settings['PORT']))}"
125
126 return self.run_command(cmd)
127
128 def _restore_dump(self, dump):
129 if self.settings.get("ADMIN_USER"):
130 self._enable_postgis()
131 return super()._restore_dump(dump)
132
133
134 class PgDumpBinaryConnector(PgDumpConnector):
135 """
136 PostgreSQL connector, it uses `pg_dump` to create an SQL text file
137 and `pg_restore` for restore it.
138 """
139
140 extension = "psql.bin"
141 dump_cmd = "pg_dump"
142 restore_cmd = "pg_restore"
143 single_transaction = True
144 drop = True
145 if_exists = True
146 pg_options = None
147
148 def _create_dump(self):
149 cmd_part, pg_env = parse_postgres_settings(self)
150 cmd = f"{self.dump_cmd} {cmd_part}"
151
152 cmd += " --format=custom"
153 for table in self.exclude:
154 cmd += f" --exclude-table-data={table}"
155
156 if self.schemas:
157 cmd += " -n " + " -n ".join(self.schemas)
158
159 cmd = f"{self.dump_prefix} {cmd} {self.dump_suffix}"
160 stdout, _ = self.run_command(cmd, env={**self.dump_env, **pg_env})
161 return stdout
162
163 def _restore_dump(self, dump: str):
164 """
165 Restore a PostgreSQL dump using subprocess with argument list.
166
167 Assumes that restore_prefix, restore_cmd, pg_options, and restore_suffix
168 are either None, strings (single args), or lists of strings.
169
170 Builds the command as a list.
171 """
172
173 cmd_part, pg_env = parse_postgres_settings(self)
174 cmd = []
175
176 # Flatten optional values
177 if self.restore_prefix:
178 cmd.extend(self.restore_prefix if isinstance(self.restore_prefix, list) else [self.restore_prefix])
179
180 if self.restore_cmd:
181 cmd.extend(self.restore_cmd if isinstance(self.restore_cmd, list) else [self.restore_cmd])
182
183 if self.pg_options:
184 cmd.extend(self.pg_options if isinstance(self.pg_options, list) else [self.pg_options])
185
186 cmd.extend([cmd_part])
187
188 if self.single_transaction:
189 cmd.extend(["--single-transaction"])
190
191 if self.drop:
192 cmd.extend(["--clean"])
193
194 if self.schemas:
195 for schema in self.schemas:
196 cmd.extend(["-n", schema])
197
198 if self.if_exists or self.drop:
199 cmd.extend(["--if-exists"])
200
201 if self.restore_suffix:
202 cmd.extend(self.restore_suffix if isinstance(self.restore_suffix, list) else [self.restore_suffix])
203
204 cmd_str = " ".join(cmd)
205 stdout, _ = self.run_command(cmd_str, stdin=dump, env={**self.dump_env, **pg_env})
206
207 return stdout