280 lines
8.4 KiB
Python
280 lines
8.4 KiB
Python
from __future__ import annotations
|
|
|
|
from datetime import datetime
|
|
from uuid import UUID, uuid4
|
|
|
|
from psycopg.errors import ForeignKeyViolation, UniqueViolation
|
|
|
|
from app.db import pool
|
|
|
|
|
|
class InvalidMembersError(Exception):
|
|
pass
|
|
|
|
|
|
class PostgresStore:
|
|
async def create_user(
|
|
self,
|
|
username: str,
|
|
display_name: str,
|
|
password_hash: str,
|
|
) -> dict | None:
|
|
try:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
INSERT INTO users (
|
|
id, username, display_name, password_hash
|
|
)
|
|
VALUES (%s, %s, %s, %s)
|
|
RETURNING id, username, display_name, created_at
|
|
""",
|
|
(uuid4(), username, display_name, password_hash),
|
|
)
|
|
user = await cursor.fetchone()
|
|
|
|
return user
|
|
except UniqueViolation as exc:
|
|
if exc.diag.constraint_name == "users_username_unique":
|
|
return None
|
|
raise
|
|
|
|
async def get_user(self, user_id: UUID) -> dict | None:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
SELECT id, username, display_name, created_at
|
|
FROM users
|
|
WHERE id = %s
|
|
""",
|
|
(user_id,),
|
|
)
|
|
return await cursor.fetchone()
|
|
|
|
async def get_user_for_login(self, username: str) -> dict | None:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
SELECT id, username, display_name,
|
|
password_hash, created_at
|
|
FROM users
|
|
WHERE username = %s
|
|
""",
|
|
(username,),
|
|
)
|
|
return await cursor.fetchone()
|
|
|
|
async def create_chat(
|
|
self,
|
|
title: str,
|
|
member_ids: list[UUID],
|
|
) -> dict:
|
|
chat_id = uuid4()
|
|
|
|
try:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
INSERT INTO chats (id, title)
|
|
VALUES (%s, %s)
|
|
RETURNING id, title, created_at
|
|
""",
|
|
(chat_id, title),
|
|
)
|
|
chat = await cursor.fetchone()
|
|
|
|
async with conn.cursor() as cursor:
|
|
await cursor.executemany(
|
|
"""
|
|
INSERT INTO chat_members (chat_id, user_id)
|
|
VALUES (%s, %s)
|
|
""",
|
|
[(chat_id, user_id) for user_id in member_ids],
|
|
)
|
|
|
|
chat["member_ids"] = member_ids
|
|
|
|
return chat
|
|
except ForeignKeyViolation as exc:
|
|
raise InvalidMembersError from exc
|
|
|
|
async def get_accessible_chat(
|
|
self,
|
|
chat_id: UUID,
|
|
user_id: UUID,
|
|
) -> dict | None:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
SELECT c.id, c.title, c.created_at,
|
|
ARRAY(
|
|
SELECT cm.user_id
|
|
FROM chat_members AS cm
|
|
WHERE cm.chat_id = c.id
|
|
ORDER BY cm.user_id
|
|
) AS member_ids
|
|
FROM chats AS c
|
|
WHERE c.id = %s
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM chat_members AS access
|
|
WHERE access.chat_id = c.id
|
|
AND access.user_id = %s
|
|
)
|
|
""",
|
|
(chat_id, user_id),
|
|
)
|
|
return await cursor.fetchone()
|
|
|
|
async def list_chats(
|
|
self,
|
|
user_id: UUID,
|
|
limit: int,
|
|
after: tuple[datetime, UUID] | None = None,
|
|
) -> list[dict]:
|
|
params: list[object] = [user_id]
|
|
after_sql = ""
|
|
|
|
if after is not None:
|
|
after_sql = "AND (c.created_at, c.id) > (%s, %s)"
|
|
params.extend(after)
|
|
|
|
params.append(limit + 1)
|
|
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
f"""
|
|
SELECT c.id, c.title, c.created_at,
|
|
ARRAY(
|
|
SELECT cm.user_id
|
|
FROM chat_members AS cm
|
|
WHERE cm.chat_id = c.id
|
|
ORDER BY cm.user_id
|
|
) AS member_ids
|
|
FROM chats AS c
|
|
JOIN chat_members AS access
|
|
ON access.chat_id = c.id
|
|
WHERE access.user_id = %s
|
|
{after_sql}
|
|
ORDER BY c.created_at, c.id
|
|
LIMIT %s
|
|
""",
|
|
params,
|
|
)
|
|
return await cursor.fetchall()
|
|
|
|
async def create_message(
|
|
self,
|
|
chat_id: UUID,
|
|
sender_id: UUID,
|
|
text: str,
|
|
) -> dict:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
INSERT INTO messages (id, chat_id, sender_id, text)
|
|
VALUES (%s, %s, %s, %s)
|
|
RETURNING id, chat_id, sender_id, text, created_at
|
|
""",
|
|
(uuid4(), chat_id, sender_id, text),
|
|
)
|
|
message = await cursor.fetchone()
|
|
|
|
return message
|
|
|
|
async def list_messages(
|
|
self,
|
|
chat_id: UUID,
|
|
limit: int,
|
|
after: tuple[datetime, UUID] | None = None,
|
|
) -> list[dict]:
|
|
params: list[object] = [chat_id]
|
|
after_sql = ""
|
|
|
|
if after is not None:
|
|
after_sql = "AND (created_at, id) > (%s, %s)"
|
|
params.extend(after)
|
|
|
|
params.append(limit + 1)
|
|
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
f"""
|
|
SELECT m.id, m.chat_id, m.sender_id,
|
|
m.text, m.created_at,
|
|
ARRAY(
|
|
SELECT ma.attachment_id
|
|
FROM message_attachments AS ma
|
|
WHERE ma.message_id = m.id
|
|
ORDER BY ma.position
|
|
) AS attachment_ids
|
|
FROM messages AS m
|
|
WHERE m.chat_id = %s
|
|
{after_sql}
|
|
ORDER BY created_at, id
|
|
LIMIT %s
|
|
""",
|
|
params,
|
|
)
|
|
return await cursor.fetchall()
|
|
|
|
async def create_session(
|
|
self,
|
|
user_id: UUID,
|
|
token_hash: str,
|
|
ttl_seconds: int,
|
|
) -> dict:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
INSERT INTO sessions (
|
|
token_hash, user_id, created_at, expires_at
|
|
)
|
|
VALUES (
|
|
%s, %s, statement_timestamp(),
|
|
statement_timestamp()
|
|
+ (%s * INTERVAL '1 second')
|
|
)
|
|
RETURNING expires_at
|
|
""",
|
|
(token_hash, user_id, ttl_seconds),
|
|
)
|
|
session = await cursor.fetchone()
|
|
|
|
return session
|
|
|
|
async def get_session_user_id(
|
|
self,
|
|
token_hash: str,
|
|
) -> UUID | None:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
SELECT user_id
|
|
FROM sessions
|
|
WHERE token_hash = %s
|
|
AND expires_at > statement_timestamp()
|
|
""",
|
|
(token_hash,),
|
|
)
|
|
row = await cursor.fetchone()
|
|
|
|
return None if row is None else row["user_id"]
|
|
|
|
async def revoke_session(self, token_hash: str) -> bool:
|
|
async with pool.connection() as conn:
|
|
cursor = await conn.execute(
|
|
"""
|
|
DELETE FROM sessions
|
|
WHERE token_hash = %s
|
|
AND expires_at > statement_timestamp()
|
|
RETURNING token_hash
|
|
""",
|
|
(token_hash,),
|
|
)
|
|
row = await cursor.fetchone()
|
|
|
|
return row is not None
|
|
|
|
|
|
store = PostgresStore() |