+ добавила функционал на 4 + тесты

This commit is contained in:
vasyukova
2026-10-02 01:06:35 +03:00
parent 6aed50419f
commit afd49a3515
9 changed files with 328 additions and 61 deletions
+33 -5
View File
@@ -3,6 +3,10 @@ from contextlib import contextmanager
from typing import Iterator
import psycopg
from psycopg_pool import ConnectionPool
_pool: ConnectionPool | None = None
def _dsn() -> str:
@@ -12,14 +16,37 @@ def _dsn() -> str:
return dsn
def init_pool() -> None:
"""Ограниченный пул соединений с таймаутами. Вызывается один раз на старте."""
global _pool
if _pool is not None:
return
_pool = ConnectionPool(
conninfo=_dsn(),
min_size=2,
max_size=10,
timeout=5.0,
max_idle=300.0,
kwargs={"options": "-c statement_timeout=5000"},
open=True,
)
def close_pool() -> None:
global _pool
if _pool is not None:
_pool.close()
_pool = None
@contextmanager
def connection() -> Iterator[psycopg.Connection]:
"""Одно соединение на запрос; autocommit=False для явных транзакций."""
conn = psycopg.connect(_dsn())
try:
"""Соединение из пула; autocommit=False для явных транзакций."""
if _pool is None:
init_pool()
assert _pool is not None
with _pool.connection() as conn:
yield conn
finally:
conn.close()
SCHEMA_SQL = """
@@ -53,6 +80,7 @@ CREATE TABLE IF NOT EXISTS messages (
CREATE INDEX IF NOT EXISTS idx_messages_chat_created
ON messages (chat_id, created_at, id);
-- sessions остаются как fallback, если SESSION_STORE=postgres.
CREATE TABLE IF NOT EXISTS sessions (
token TEXT PRIMARY KEY,
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,