forked from mtusi2026/mtusi2026lab4
246 lines
5.7 KiB
Go
246 lines
5.7 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgconn"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"mtusi2026lab2/internal/model"
|
|
)
|
|
|
|
var (
|
|
ErrChatNotFound = errors.New("chat not found")
|
|
ErrInvalidMember = errors.New("chat member does not exist")
|
|
)
|
|
|
|
type ChatStore struct {
|
|
pool *pgxpool.Pool
|
|
}
|
|
|
|
func NewChatStore(pool *pgxpool.Pool) *ChatStore {
|
|
return &ChatStore{pool: pool}
|
|
}
|
|
|
|
// CreateChat creates the chat and all its members in one transaction.
|
|
// A failure inserting any member rolls back the entire chat.
|
|
func (s *ChatStore) CreateChat(
|
|
ctx context.Context,
|
|
chat model.Chat,
|
|
) error {
|
|
tx, err := s.pool.Begin(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("begin chat transaction: %w", err)
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO chats (id, title, created_at)
|
|
VALUES ($1, $2, $3)
|
|
`, chat.ID, chat.Title, chat.CreatedAt)
|
|
if err != nil {
|
|
return fmt.Errorf("insert chat: %w", err)
|
|
}
|
|
|
|
for _, memberID := range chat.MemberIDs {
|
|
_, err = tx.Exec(ctx, `
|
|
INSERT INTO chat_members (chat_id, user_id)
|
|
VALUES ($1, $2)
|
|
`, chat.ID, memberID)
|
|
if err != nil {
|
|
var pgErr *pgconn.PgError
|
|
if errors.As(err, &pgErr) && pgErr.Code == "23503" {
|
|
return ErrInvalidMember
|
|
}
|
|
return fmt.Errorf("insert chat member: %w", err)
|
|
}
|
|
}
|
|
|
|
if err := tx.Commit(ctx); err != nil {
|
|
return fmt.Errorf("commit chat transaction: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// GetChatForUser returns a chat only if the user is a member.
|
|
// Missing chats and inaccessible chats both return ErrChatNotFound.
|
|
func (s *ChatStore) GetChatForUser(
|
|
ctx context.Context,
|
|
chatID uuid.UUID,
|
|
userID uuid.UUID,
|
|
) (model.Chat, error) {
|
|
var chat model.Chat
|
|
|
|
err := s.pool.QueryRow(ctx, `
|
|
SELECT c.id, c.title, c.created_at
|
|
FROM chats c
|
|
JOIN chat_members cm ON cm.chat_id = c.id
|
|
WHERE c.id = $1 AND cm.user_id = $2
|
|
`, chatID, userID).Scan(
|
|
&chat.ID,
|
|
&chat.Title,
|
|
&chat.CreatedAt,
|
|
)
|
|
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return model.Chat{}, ErrChatNotFound
|
|
}
|
|
if err != nil {
|
|
return model.Chat{}, fmt.Errorf("get chat: %w", err)
|
|
}
|
|
|
|
members, err := s.getMemberIDs(ctx, chat.ID)
|
|
if err != nil {
|
|
return model.Chat{}, err
|
|
}
|
|
|
|
chat.MemberIDs = members
|
|
return chat, nil
|
|
}
|
|
|
|
func (s *ChatStore) getMemberIDs(
|
|
ctx context.Context,
|
|
chatID uuid.UUID,
|
|
) ([]uuid.UUID, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT user_id
|
|
FROM chat_members
|
|
WHERE chat_id = $1
|
|
ORDER BY user_id
|
|
`, chatID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("query chat members: %w", err)
|
|
}
|
|
defer rows.Close()
|
|
|
|
members := make([]uuid.UUID, 0)
|
|
|
|
for rows.Next() {
|
|
var memberID uuid.UUID
|
|
if err := rows.Scan(&memberID); err != nil {
|
|
return nil, fmt.Errorf("scan chat member: %w", err)
|
|
}
|
|
members = append(members, memberID)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
return nil, fmt.Errorf("iterate chat members: %w", err)
|
|
}
|
|
|
|
return members, nil
|
|
}
|
|
|
|
func (s *ChatStore) ListChatsForUser(
|
|
ctx context.Context,
|
|
userID uuid.UUID,
|
|
) ([]model.Chat, error) {
|
|
rows, err := s.pool.Query(ctx, `
|
|
SELECT c.id, c.title, c.created_at
|
|
FROM chats c
|
|
JOIN chat_members cm ON cm.chat_id = c.id
|
|
WHERE cm.user_id = $1
|
|
ORDER BY c.created_at, c.id
|
|
`, userID)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list chats: %w", err)
|
|
}
|
|
|
|
chats := make([]model.Chat, 0)
|
|
|
|
for rows.Next() {
|
|
var chat model.Chat
|
|
if err := rows.Scan(
|
|
&chat.ID,
|
|
&chat.Title,
|
|
&chat.CreatedAt,
|
|
); err != nil {
|
|
rows.Close()
|
|
return nil, fmt.Errorf("scan chat: %w", err)
|
|
}
|
|
chats = append(chats, chat)
|
|
}
|
|
|
|
if err := rows.Err(); err != nil {
|
|
rows.Close()
|
|
return nil, fmt.Errorf("iterate chats: %w", err)
|
|
}
|
|
rows.Close()
|
|
|
|
// A connection cannot be reused for another query until rows are closed.
|
|
for i := range chats {
|
|
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
chats[i].MemberIDs = members
|
|
}
|
|
|
|
return chats, nil
|
|
}
|
|
|
|
// ExistsUser is used to validate members before creating a chat.
|
|
func (s *ChatStore) ExistsUser(
|
|
ctx context.Context,
|
|
userID uuid.UUID,
|
|
) (bool, error) {
|
|
var exists bool
|
|
|
|
err := s.pool.QueryRow(ctx, `
|
|
SELECT EXISTS(SELECT 1 FROM users WHERE id = $1)
|
|
`, userID).Scan(&exists)
|
|
|
|
if err != nil {
|
|
return false, fmt.Errorf("check user existence: %w", err)
|
|
}
|
|
|
|
return exists, nil
|
|
}
|
|
|
|
// Kept here to document that chat timestamps are stored in UTC.
|
|
var _ = time.UTC
|
|
|
|
// ListChatsPage uses (created_at,id) keyset pagination and fetches limit+1.
|
|
func (s *ChatStore) ListChatsPage(ctx context.Context, userID uuid.UUID, limit int, cursorTime *time.Time, cursorID *uuid.UUID) ([]model.Chat, bool, error) {
|
|
var rows pgx.Rows
|
|
var err error
|
|
if cursorTime == nil || cursorID == nil {
|
|
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 ORDER BY c.created_at,c.id LIMIT $2`, userID, limit+1)
|
|
} else {
|
|
rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, userID, *cursorTime, *cursorID, limit+1)
|
|
}
|
|
if err != nil {
|
|
return nil, false, fmt.Errorf("list chats: %w", err)
|
|
}
|
|
chats := make([]model.Chat, 0, limit+1)
|
|
for rows.Next() {
|
|
var c model.Chat
|
|
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
|
rows.Close()
|
|
return nil, false, err
|
|
}
|
|
chats = append(chats, c)
|
|
}
|
|
if err := rows.Err(); err != nil {
|
|
rows.Close()
|
|
return nil, false, err
|
|
}
|
|
rows.Close()
|
|
more := len(chats) > limit
|
|
if more {
|
|
chats = chats[:limit]
|
|
}
|
|
for i := range chats {
|
|
members, err := s.getMemberIDs(ctx, chats[i].ID)
|
|
if err != nil {
|
|
return nil, false, err
|
|
}
|
|
chats[i].MemberIDs = members
|
|
}
|
|
return chats, more, nil
|
|
}
|