Skip to content

Commit 5f5e545

Browse files
committed
Improve validation of PostgresURL
1 parent d6d195c commit 5f5e545

1 file changed

Lines changed: 10 additions & 5 deletions

File tree

data_rentgen/db/settings.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
import textwrap
55
from typing import Annotated
6-
from urllib.parse import urlsplit
76

87
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, PostgresDsn, UrlConstraints
98
from sqlalchemy import make_url
@@ -13,12 +12,12 @@
1312

1413

1514
def validate_url(value: PostgresDsn):
16-
if not value.path or len(value.path) <= 1:
15+
url = make_url(str(value))
16+
if not url.database:
1717
msg = "Database URL must contain database name"
1818
raise ValueError(msg)
1919

20-
split = urlsplit(str(value))
21-
if not split.username or not split.password:
20+
if not url.username or not url.password:
2221
msg = "Database URL must contain username and password"
2322
raise ValueError(msg)
2423

@@ -27,7 +26,7 @@ def validate_url(value: PostgresDsn):
2726

2827
PostgresURL = Annotated[
2928
PostgresDsn,
30-
UrlConstraints(allowed_schemes=["postgresql+asyncpg", "postgresql+psycopg"], host_required=True),
29+
UrlConstraints(allowed_schemes=["postgresql+asyncpg", "postgresql+psycopg"], default_port=5432, host_required=True),
3130
AfterValidator(validate_url),
3231
]
3332

@@ -57,6 +56,12 @@ class DatabaseSettings(BaseModel):
5756
"""
5857
Database connection URL.
5958
59+
Mandatory components:
60+
61+
* host
62+
* username (urlencoded)
63+
* password (urlencoded)
64+
6065
See [SQLAlchemy documentation](https://docs.sqlalchemy.org/en/20/core/engines.html#backend-specific-urls)
6166
6267
!!! warning

0 commit comments

Comments
 (0)