| 1 |
import logging |
| 2 |
import os |
| 3 |
import urllib.parse as urlparse |
| 4 |
from collections.abc import Callable |
| 5 |
from typing import Any, TypedDict |
| 6 |
|
| 7 |
DEFAULT_ENV = "DATABASE_URL" |
| 8 |
ENGINE_SCHEMES: dict[str, "Engine"] = {} |
| 9 |
|
| 10 |
|
| 11 |
# From https://docs.djangoproject.com/en/stable/ref/settings/#databases |
| 12 |
class DBConfig(TypedDict, total=False): |
| 13 |
ATOMIC_REQUESTS: bool |
| 14 |
AUTOCOMMIT: bool |
| 15 |
CONN_MAX_AGE: int | None |
| 16 |
CONN_HEALTH_CHECKS: bool |
| 17 |
DISABLE_SERVER_SIDE_CURSORS: bool |
| 18 |
ENGINE: str |
| 19 |
HOST: str |
| 20 |
NAME: str |
| 21 |
OPTIONS: dict[str, Any] |
| 22 |
PASSWORD: str |
| 23 |
PORT: str | int |
| 24 |
TEST: dict[str, Any] |
| 25 |
TIME_ZONE: str |
| 26 |
USER: str |
| 27 |
|
| 28 |
|
| 29 |
PostprocessCallable = Callable[[DBConfig], None] |
| 30 |
OptionType = int | str | bool |
| 31 |
|
| 32 |
|
| 33 |
class ParseError(ValueError): |
| 34 |
def __str__(self) -> str: |
| 35 |
return ( |
| 36 |
"This string is not a valid url, possibly because some of its parts" |
| 37 |
" is not properly urllib.parse.quote()'ed." |
| 38 |
) |
| 39 |
|
| 40 |
|
| 41 |
class UnknownSchemeError(ValueError): |
| 42 |
def __init__(self, scheme: str): |
| 43 |
self.scheme = scheme |
| 44 |
|
| 45 |
def __str__(self) -> str: |
| 46 |
schemes = ", ".join(sorted(ENGINE_SCHEMES.keys())) |
| 47 |
return ( |
| 48 |
f"Scheme '{self.scheme}://' is unknown." |
| 49 |
" Did you forget to register custom backend?" |
| 50 |
f" Following schemes have registered backends: {schemes}." |
| 51 |
) |
| 52 |
|
| 53 |
|
| 54 |
def default_postprocess(parsed_config: DBConfig) -> None: |
| 55 |
pass |
| 56 |
|
| 57 |
|
| 58 |
class Engine: |
| 59 |
def __init__( |
| 60 |
self, |
| 61 |
backend: str, |
| 62 |
postprocess: PostprocessCallable = default_postprocess, |
| 63 |
): |
| 64 |
self.backend = backend |
| 65 |
self.postprocess = postprocess |
| 66 |
|
| 67 |
|
| 68 |
def register( |
| 69 |
scheme: str, backend: str |
| 70 |
) -> Callable[[PostprocessCallable], PostprocessCallable]: |
| 71 |
engine = Engine(backend) |
| 72 |
if scheme not in ENGINE_SCHEMES: |
| 73 |
urlparse.uses_netloc.append(scheme) |
| 74 |
ENGINE_SCHEMES[scheme] = engine |
| 75 |
|
| 76 |
def inner(func: PostprocessCallable) -> PostprocessCallable: |
| 77 |
engine.postprocess = func |
| 78 |
return func |
| 79 |
|
| 80 |
return inner |
| 81 |
|
| 82 |
|
| 83 |
register("spatialite", "django.contrib.gis.db.backends.spatialite") |
| 84 |
register("mysql-connector", "mysql.connector.django") |
| 85 |
register("mysqlgis", "django.contrib.gis.db.backends.mysql") |
| 86 |
register("oraclegis", "django.contrib.gis.db.backends.oracle") |
| 87 |
register("cockroach", "django_cockroachdb") |
| 88 |
|
| 89 |
|
| 90 |
@register("sqlite", "django.db.backends.sqlite3") |
| 91 |
def default_to_in_memory_db(parsed_config: DBConfig) -> None: |
| 92 |
# mimic sqlalchemy behaviour |
| 93 |
if not parsed_config.get("NAME"): |
| 94 |
parsed_config["NAME"] = ":memory:" |
| 95 |
|
| 96 |
|
| 97 |
@register("oracle", "django.db.backends.oracle") |
| 98 |
@register("mssqlms", "mssql") |
| 99 |
@register("mssql", "sql_server.pyodbc") |
| 100 |
def stringify_port(parsed_config: DBConfig) -> None: |
| 101 |
parsed_config["PORT"] = str(parsed_config.get("PORT", "")) |
| 102 |
|
| 103 |
|
| 104 |
@register("mysql", "django.db.backends.mysql") |
| 105 |
@register("mysql2", "django.db.backends.mysql") |
| 106 |
def apply_ssl_ca(parsed_config: DBConfig) -> None: |
| 107 |
options = parsed_config.get("OPTIONS", {}) |
| 108 |
ca = options.pop("ssl-ca", None) |
| 109 |
if ca: |
| 110 |
options["ssl"] = {"ca": ca} |
| 111 |
|
| 112 |
|
| 113 |
@register("postgres", "django.db.backends.postgresql") |
| 114 |
@register("postgresql", "django.db.backends.postgresql") |
| 115 |
@register("pgsql", "django.db.backends.postgresql") |
| 116 |
@register("postgis", "django.contrib.gis.db.backends.postgis") |
| 117 |
@register("redshift", "django_redshift_backend") |
| 118 |
@register("timescale", "timescale.db.backends.postgresql") |
| 119 |
@register("timescalegis", "timescale.db.backends.postgis") |
| 120 |
def apply_current_schema(parsed_config: DBConfig) -> None: |
| 121 |
options = parsed_config.get("OPTIONS", {}) |
| 122 |
schema = options.pop("currentSchema", None) |
| 123 |
if schema: |
| 124 |
options["options"] = f"-c search_path={schema}" |
| 125 |
|
| 126 |
|
| 127 |
def config( |
| 128 |
env: str = DEFAULT_ENV, |
| 129 |
default: str | None = None, |
| 130 |
engine: str | None = None, |
| 131 |
conn_max_age: int | None = 0, |
| 132 |
conn_health_checks: bool = False, |
| 133 |
disable_server_side_cursors: bool = False, |
| 134 |
ssl_require: bool = False, |
| 135 |
test_options: dict[str, Any] | None = None, |
| 136 |
) -> DBConfig: |
| 137 |
"""Returns configured DATABASE dictionary from DATABASE_URL.""" |
| 138 |
s = os.environ.get(env, default) |
| 139 |
|
| 140 |
if s is None: |
| 141 |
logging.warning( |
| 142 |
"No %s environment variable set, and so no databases setup", env |
| 143 |
) |
| 144 |
|
| 145 |
if s: |
| 146 |
return parse( |
| 147 |
s, |
| 148 |
engine, |
| 149 |
conn_max_age, |
| 150 |
conn_health_checks, |
| 151 |
disable_server_side_cursors, |
| 152 |
ssl_require, |
| 153 |
test_options, |
| 154 |
) |
| 155 |
|
| 156 |
return {} |
| 157 |
|
| 158 |
|
| 159 |
def parse( |
| 160 |
url: str, |
| 161 |
engine: str | None = None, |
| 162 |
conn_max_age: int | None = 0, |
| 163 |
conn_health_checks: bool = False, |
| 164 |
disable_server_side_cursors: bool = False, |
| 165 |
ssl_require: bool = False, |
| 166 |
test_options: dict[str, Any] | None = None, |
| 167 |
) -> DBConfig: |
| 168 |
"""Parses a database URL and returns configured DATABASE dictionary.""" |
| 169 |
settings = _convert_to_settings( |
| 170 |
engine, |
| 171 |
conn_max_age, |
| 172 |
conn_health_checks, |
| 173 |
disable_server_side_cursors, |
| 174 |
ssl_require, |
| 175 |
test_options, |
| 176 |
) |
| 177 |
|
| 178 |
if url == "sqlite://:memory:": |
| 179 |
# this is a special case, because if we pass this URL into |
| 180 |
# urlparse, urlparse will choke trying to interpret "memory" |
| 181 |
# as a port number |
| 182 |
return {"ENGINE": ENGINE_SCHEMES["sqlite"].backend, "NAME": ":memory:"} |
| 183 |
# note: no other settings are required for sqlite |
| 184 |
|
| 185 |
try: |
| 186 |
split_result = urlparse.urlsplit(url) |
| 187 |
engine_obj = ENGINE_SCHEMES.get(split_result.scheme) |
| 188 |
if engine_obj is None: |
| 189 |
raise UnknownSchemeError(split_result.scheme) |
| 190 |
path = split_result.path[1:] |
| 191 |
query = urlparse.parse_qs(split_result.query) |
| 192 |
options = {k: _parse_option_values(v) for k, v in query.items()} |
| 193 |
parsed_config: DBConfig = { |
| 194 |
"ENGINE": engine_obj.backend, |
| 195 |
"USER": urlparse.unquote(split_result.username or ""), |
| 196 |
"PASSWORD": urlparse.unquote(split_result.password or ""), |
| 197 |
"HOST": urlparse.unquote(split_result.hostname or ""), |
| 198 |
"PORT": split_result.port or "", |
| 199 |
"NAME": urlparse.unquote(path), |
| 200 |
"OPTIONS": options, |
| 201 |
} |
| 202 |
except UnknownSchemeError: |
| 203 |
raise |
| 204 |
except ValueError: |
| 205 |
raise ParseError() from None |
| 206 |
|
| 207 |
# Guarantee that config has options, possibly empty, when postprocess() is called |
| 208 |
assert isinstance(parsed_config["OPTIONS"], dict) |
| 209 |
engine_obj.postprocess(parsed_config) |
| 210 |
|
| 211 |
# Update the final config with any settings passed in explicitly. |
| 212 |
parsed_config["OPTIONS"].update(settings.pop("OPTIONS", {})) |
| 213 |
parsed_config.update(settings) |
| 214 |
|
| 215 |
if not parsed_config["OPTIONS"]: |
| 216 |
parsed_config.pop("OPTIONS") |
| 217 |
return parsed_config |
| 218 |
|
| 219 |
|
| 220 |
def _parse_option_values(values: list[str]) -> OptionType | list[OptionType]: |
| 221 |
parsed_values = [_parse_value(v) for v in values] |
| 222 |
return parsed_values[0] if len(parsed_values) == 1 else parsed_values |
| 223 |
|
| 224 |
|
| 225 |
def _parse_value(value: str) -> OptionType: |
| 226 |
if value.isdigit(): |
| 227 |
return int(value) |
| 228 |
if value.lower() in ("true", "false"): |
| 229 |
return value.lower() == "true" |
| 230 |
return value |
| 231 |
|
| 232 |
|
| 233 |
def _convert_to_settings( |
| 234 |
engine: str | None, |
| 235 |
conn_max_age: int | None, |
| 236 |
conn_health_checks: bool, |
| 237 |
disable_server_side_cursors: bool, |
| 238 |
ssl_require: bool, |
| 239 |
test_options: dict[str, Any] | None, |
| 240 |
) -> DBConfig: |
| 241 |
settings: DBConfig = { |
| 242 |
"CONN_MAX_AGE": conn_max_age, |
| 243 |
"CONN_HEALTH_CHECKS": conn_health_checks, |
| 244 |
"DISABLE_SERVER_SIDE_CURSORS": disable_server_side_cursors, |
| 245 |
} |
| 246 |
if engine: |
| 247 |
settings["ENGINE"] = engine |
| 248 |
if ssl_require: |
| 249 |
settings["OPTIONS"] = {} |
| 250 |
settings["OPTIONS"]["sslmode"] = "require" |
| 251 |
if test_options: |
| 252 |
settings["TEST"] = test_options |
| 253 |
return settings |