PLBA2-2. Реализация
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
from collections.abc import Mapping, Sequence
|
||||
import re
|
||||
from typing import Any, AsyncContextManager, Protocol
|
||||
|
||||
from plba.settings.models import SettingsDatabaseUnavailableError
|
||||
|
||||
|
||||
class PostgresConnection(Protocol):
|
||||
async def fetch(self, query: str, *parameters: object) -> Sequence[Mapping[str, Any]]: ...
|
||||
|
||||
|
||||
class PostgresPool(Protocol):
|
||||
def acquire(self) -> AsyncContextManager[PostgresConnection]: ...
|
||||
|
||||
|
||||
class PostgresSettingsRepository:
|
||||
_SCHEMA = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
|
||||
|
||||
def __init__(self, pool: PostgresPool, schema: str) -> None:
|
||||
if not self._SCHEMA.fullmatch(schema):
|
||||
raise ValueError("schema must be a PostgreSQL identifier")
|
||||
self._pool = pool
|
||||
self._table = f'"{schema}".settings'
|
||||
|
||||
async def fetch_values(
|
||||
self, setting_key: str, config_key: str | None = None
|
||||
) -> list[str]:
|
||||
query = (
|
||||
f"SELECT setting_value FROM {self._table} "
|
||||
"WHERE setting_key = $1 AND ($2 IS NULL OR config_key = $2) "
|
||||
"AND is_enabled = TRUE ORDER BY sort_order ASC, id ASC"
|
||||
)
|
||||
try:
|
||||
async with self._pool.acquire() as connection:
|
||||
rows = await connection.fetch(query, setting_key, config_key)
|
||||
values = [row["setting_value"] for row in rows]
|
||||
if any(not isinstance(value, str) for value in values):
|
||||
raise TypeError("settings.setting_value must be text")
|
||||
return values
|
||||
except Exception as error:
|
||||
raise SettingsDatabaseUnavailableError(
|
||||
"settings query failed"
|
||||
) from error
|
||||
Reference in New Issue
Block a user