1# Copyright (c) Kenneth Reitz & individual contributors
2# All rights reserved.
3# Redistribution and use in source and binary forms, with or without modification,
4# are permitted provided that the following conditions are met:
5# 1. Redistributions of source code must retain the above copyright notice,
6# this list of conditions and the following disclaimer.
7# 2. Redistributions in binary form must reproduce the above copyright
8# notice, this list of conditions and the following disclaimer in the
9# documentation and/or other materials provided with the distribution.
10# 3. Neither the name of Plain nor the names of its contributors may be used
11# to endorse or promote products derived from this software without
12# specific prior written permission.
13# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
17# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
20# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23import urllib.parse as urlparse
24from typing import Any, TypedDict
25
26SCHEMES = {"postgres", "postgresql", "pgsql"}
27
28
29class DatabaseConfig(TypedDict, total=False):
30 HOST: str
31 DATABASE: str # Required (validated in _configure_settings)
32 OPTIONS: dict[str, Any]
33 PASSWORD: str
34 PORT: int | None
35 USER: str
36
37
38# Register database schemes in URLs.
39for scheme in SCHEMES:
40 urlparse.uses_netloc.append(scheme)
41
42
43def parse_database_url(url: str) -> DatabaseConfig:
44 """Parse a database URL into a fully-populated `DatabaseConfig`.
45
46 All keys are present; empty values are `""` (strings), `None` (PORT),
47 or `{}` (OPTIONS) — callers can index without `.get(...)` defaults.
48 """
49 spliturl = urlparse.urlsplit(url)
50
51 if spliturl.scheme not in SCHEMES:
52 raise ValueError(
53 f"No support for '{spliturl.scheme}'. We support: {', '.join(sorted(SCHEMES))}"
54 )
55
56 path = spliturl.path[1:]
57 query = urlparse.parse_qs(spliturl.query)
58
59 # Handle percent-encoded hostnames (e.g. socket paths).
60 hostname = spliturl.hostname or ""
61 if "%" in hostname:
62 # Use netloc to avoid lowercased paths, strip credentials if present.
63 hostname = spliturl.netloc
64 if "@" in hostname:
65 hostname = hostname.rsplit("@", 1)[1]
66 hostname = urlparse.unquote(hostname)
67
68 return {
69 "DATABASE": urlparse.unquote(path or ""),
70 "USER": urlparse.unquote(spliturl.username or ""),
71 "PASSWORD": urlparse.unquote(spliturl.password or ""),
72 "HOST": hostname,
73 "PORT": spliturl.port,
74 "OPTIONS": {key: values[-1] for key, values in query.items()},
75 }
76
77
78_CLI_FLAGS: list[tuple[str, str]] = [("USER", "-U"), ("HOST", "-h"), ("PORT", "-p")]
79_CLI_OPTION_ENV_VARS: dict[str, str] = {
80 "passfile": "PGPASSFILE",
81 "sslmode": "PGSSLMODE",
82 "sslrootcert": "PGSSLROOTCERT",
83 "sslcert": "PGSSLCERT",
84 "sslkey": "PGSSLKEY",
85}
86
87
88def postgres_cli_args(config: DatabaseConfig) -> list[str]:
89 """Build connection flags for libpq-based tools (psql, pg_dump, pg_restore)."""
90 args: list[str] = []
91 for key, flag in _CLI_FLAGS:
92 if value := config.get(key):
93 args += [flag, str(value)]
94 return args
95
96
97def postgres_cli_env(config: DatabaseConfig) -> dict[str, str]:
98 """Build env vars for libpq-based tools (psql, pg_dump, pg_restore)."""
99 env: dict[str, str] = {}
100 if password := config.get("PASSWORD"):
101 env["PGPASSWORD"] = str(password)
102 options = config.get("OPTIONS", {})
103 for option_key, env_var in _CLI_OPTION_ENV_VARS.items():
104 if value := options.get(option_key):
105 env[env_var] = str(value)
106 return env
107
108
109def build_database_url(config: DatabaseConfig) -> str:
110 """Build a database URL from a configuration dictionary."""
111 options = config.get("OPTIONS", {})
112 query = urlparse.urlencode(list(options.items()))
113
114 user = urlparse.quote(str(config.get("USER", "")))
115 password = urlparse.quote(str(config.get("PASSWORD", "")))
116 host = config.get("HOST", "")
117 port = config.get("PORT")
118 name = urlparse.quote(str(config.get("DATABASE", "")))
119
120 netloc = ""
121 if user or password:
122 netloc += user
123 if password:
124 netloc += f":{password}"
125 netloc += "@"
126 netloc += host
127 if port:
128 netloc += f":{port}"
129
130 return urlparse.urlunsplit(("postgresql", netloc, f"/{name}", query, ""))
131
132
133def replace_database_name(url: str, name: str) -> str:
134 """Return the URL with the database name (path segment) replaced.
135
136 Preserves scheme, netloc, query string, and fragment exactly — only the
137 path changes. Avoids the round-trip through parse/build, which normalizes
138 the scheme and collapses duplicate query keys.
139 """
140 spliturl = urlparse.urlsplit(url)
141 return urlparse.urlunsplit(spliturl._replace(path=f"/{urlparse.quote(name)}"))