справление: U+0000 в строках сохраняется (bytea), DataError -> 400

This commit is contained in:
kalibr456
2026-10-09 18:30:42 +03:00
parent 8149a608f8
commit e17d883c15
10 changed files with 102 additions and 101 deletions
+34 -22
View File
@@ -26,7 +26,6 @@ pool = ConnectionPool(
"options": f"-c statement_timeout={settings.DB_STATEMENT_TIMEOUT_MS}"
" -c idle_in_transaction_session_timeout=10000 -c TimeZone=UTC",
},
check=ConnectionPool.check_connection,
open=False,
)
@@ -34,16 +33,29 @@ pool = ConnectionPool(
@contextmanager
def connection(wait_seconds: float | None = None):
"""Соединение из пула. В конце блока COMMIT, при исключении ROLLBACK.
Если база недоступна, клиент получает 503 без подробностей.
"""
try:
with pool.connection(timeout=wait_seconds) as conn:
yield conn
except (psycopg.OperationalError, PoolTimeout) as exc:
log.warning("PostgreSQL is unavailable: %s", type(exc).__name__)
raise unavailable() from None
except psycopg.DataError as exc:
log.warning("PostgreSQL rejected a value: %s", type(exc).__name__)
raise bad_request("Invalid request data") from None
TEXT_FIELDS = ("display_name", "title", "text")
def to_db(value: str) -> bytes:
return value.encode("utf-8")
def from_db(row: dict | None) -> dict | None:
"""Строка из БД -> dict для API: байты текстовых полей обратно в str."""
if row is None:
return None
return {key: bytes(value).decode("utf-8") if key in TEXT_FIELDS else value for key, value in row.items()}
def ping() -> None:
@@ -51,8 +63,7 @@ def ping() -> None:
conn.execute("SELECT 1")
MIGRATIONS_LOCK = 20260202
MIGRATIONS_LOCK = 20260202
def run_migrations() -> list[str]:
@@ -100,26 +111,25 @@ USER_COLUMNS = "id, username, display_name, created_at"
def create_user(username: str, display_name: str, password_hash: str) -> dict:
try:
with connection() as conn:
return conn.execute(
return from_db(conn.execute(
f"""INSERT INTO users (id, username, display_name, password_hash)
VALUES (%s, %s, %s, %s) RETURNING {USER_COLUMNS}""",
(uuid4(), username, display_name, password_hash),
).fetchone()
(uuid4(), username, to_db(display_name), password_hash),
).fetchone())
except pg_errors.UniqueViolation:
raise conflict("Username already exists") from None
def get_user(user_id: UUID) -> dict | None:
with connection() as conn:
return conn.execute(f"SELECT {USER_COLUMNS} FROM users WHERE id = %s", (user_id,)).fetchone()
return from_db(conn.execute(f"SELECT {USER_COLUMNS} FROM users WHERE id = %s", (user_id,)).fetchone())
def get_user_with_password(username: str) -> dict | None:
with connection() as conn:
return conn.execute(
return from_db(conn.execute(
f"SELECT {USER_COLUMNS}, password_hash FROM users WHERE username = %s", (username,)
).fetchone()
).fetchone())
CHAT_COLUMNS = """c.id, c.title, c.created_at,
@@ -134,7 +144,7 @@ def create_chat(title: str, member_ids: list[UUID]) -> dict:
with conn.transaction():
row = conn.execute(
"INSERT INTO chats (id, title) VALUES (%s, %s) RETURNING id, title, created_at",
(chat_id, title),
(chat_id, to_db(title)),
).fetchone()
with conn.cursor() as cur:
cur.executemany(
@@ -143,7 +153,7 @@ def create_chat(title: str, member_ids: list[UUID]) -> dict:
)
except pg_errors.ForeignKeyViolation:
raise bad_request("Unknown member") from None
return {**row, "member_ids": members}
return {**from_db(row), "member_ids": members}
def get_chat(chat_id: UUID, user_id: UUID) -> dict:
@@ -156,7 +166,7 @@ def get_chat(chat_id: UUID, user_id: UUID) -> dict:
).fetchone()
if chat is None:
raise not_found("Chat not found")
return chat
return from_db(chat)
def list_chats(user_id: UUID, after: tuple[datetime, UUID] | None, limit: int) -> list[dict]:
@@ -166,7 +176,7 @@ def list_chats(user_id: UUID, after: tuple[datetime, UUID] | None, limit: int) -
where = "WHERE (c.created_at, c.id) > (%s, %s)"
params += list(after)
with connection() as conn:
return conn.execute(
rows = conn.execute(
f"""SELECT {CHAT_COLUMNS} FROM chats c
JOIN chat_members me ON me.chat_id = c.id AND me.user_id = %s
{where}
@@ -174,6 +184,7 @@ def list_chats(user_id: UUID, after: tuple[datetime, UUID] | None, limit: int) -
LIMIT %s""",
(*params, limit + 1),
).fetchall()
return [from_db(row) for row in rows]
@@ -183,11 +194,11 @@ MESSAGE_COLUMNS = "id, chat_id, sender_id, text, created_at"
def add_message(chat_id: UUID, sender_id: UUID, text: str) -> dict:
try:
with connection() as conn:
return conn.execute(
return from_db(conn.execute(
f"""INSERT INTO messages (id, chat_id, sender_id, text)
VALUES (%s, %s, %s, %s) RETURNING {MESSAGE_COLUMNS}""",
(uuid4(), chat_id, sender_id, text),
).fetchone()
(uuid4(), chat_id, sender_id, to_db(text)),
).fetchone())
except pg_errors.ForeignKeyViolation:
raise not_found("Chat not found") from None
@@ -204,10 +215,11 @@ def list_messages(chat_id: UUID, user_id: UUID, after: tuple[datetime, UUID] | N
).fetchone()
if member is None:
raise not_found("Chat not found")
return conn.execute(
rows = conn.execute(
f"""SELECT {MESSAGE_COLUMNS} FROM messages
WHERE {where}
ORDER BY created_at, id
LIMIT %s""",
(*params, limit + 1),
).fetchall()
return [from_db(row) for row in rows]