package postgres import ( "context" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "high-loud-apps-labs/internal/domain" ) type ChatRepo struct { pool *pgxpool.Pool } func NewChatRepo(pool *pgxpool.Pool) *ChatRepo { return &ChatRepo{pool: pool} } // Create атомарно создаёт чат и его участников. func (r *ChatRepo) Create(ctx context.Context, chat *domain.Chat) error { tx, err := r.pool.Begin(ctx) if err != nil { return mapError(err) } defer func() { _ = tx.Rollback(ctx) }() const qChat = `INSERT INTO chats (id, title, created_at) VALUES ($1::uuid, $2, $3)` if _, err := tx.Exec(ctx, qChat, chat.ID, chat.Title, chat.CreatedAt); err != nil { if checkViolation(err) { return &domain.ValidationError{Field: "chat", Message: "нарушено ограничение целостности"} } return mapError(err) } const qMember = `INSERT INTO chat_members (chat_id, user_id) VALUES ($1::uuid, $2::uuid)` for _, uid := range chat.MemberIDs { if _, err := tx.Exec(ctx, qMember, chat.ID, uid); err != nil { if foreignKeyViolation(err) { return &domain.ValidationError{ Field: "member_ids", Message: "неизвестный участник " + uid, } } if uniqueViolation(err) { return &domain.ValidationError{ Field: "member_ids", Message: "дубликаты запрещены", } } return mapError(err) } } return mapError(tx.Commit(ctx)) } func (r *ChatRepo) GetByID(ctx context.Context, id string) (*domain.Chat, error) { const q = `SELECT id, title, created_at FROM chats WHERE id = $1::uuid` c := &domain.Chat{} err := r.pool.QueryRow(ctx, q, id).Scan(&c.ID, &c.Title, &c.CreatedAt) if err != nil { return nil, notFound(err, "chat", id) } members, err := r.loadMembers(ctx, []string{c.ID}) if err != nil { return nil, err } c.MemberIDs = members[c.ID] if c.MemberIDs == nil { c.MemberIDs = []string{} } return c, nil } func (r *ChatRepo) ListByMember(ctx context.Context, userID string, limit int, cursor *string) ([]domain.Chat, *string, error) { scope := "chats:" + userID var ( afterTime time.Time afterID string hasCursor bool ) if cursor != nil { t, id, err := decodeCursor(*cursor, scope) if err != nil { return nil, nil, err } afterTime = t afterID = id hasCursor = true } var ( rows pgx.Rows err error ) if hasCursor { const q = ` SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = $1::uuid AND (c.created_at, c.id) > ($2, $3::uuid) ORDER BY c.created_at, c.id LIMIT $4 ` rows, err = r.pool.Query(ctx, q, userID, afterTime, afterID, limit+1) } else { const q = ` SELECT c.id, c.title, c.created_at FROM chats c JOIN chat_members m ON m.chat_id = c.id WHERE m.user_id = $1::uuid ORDER BY c.created_at, c.id LIMIT $2 ` rows, err = r.pool.Query(ctx, q, userID, limit+1) } if err != nil { return nil, nil, mapError(err) } defer rows.Close() page := make([]domain.Chat, 0, limit) for rows.Next() { var c domain.Chat if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { return nil, nil, mapError(err) } page = append(page, c) } if err := rows.Err(); err != nil { return nil, nil, mapError(err) } var next *string if len(page) > limit { page = page[:limit] last := page[len(page)-1] c := encodeCursor(scope, last.CreatedAt, last.ID) next = &c } if len(page) > 0 { ids := make([]string, len(page)) for i := range page { ids[i] = page[i].ID } members, err := r.loadMembers(ctx, ids) if err != nil { return nil, nil, err } for i := range page { if m, ok := members[page[i].ID]; ok { page[i].MemberIDs = m } else { page[i].MemberIDs = []string{} } } } return page, next, nil } // loadMembers одним запросом собирает участников для указанных чатов. func (r *ChatRepo) loadMembers(ctx context.Context, chatIDs []string) (map[string][]string, error) { if len(chatIDs) == 0 { return map[string][]string{}, nil } const q = ` SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1::uuid[]) ORDER BY chat_id, user_id ` rows, err := r.pool.Query(ctx, q, chatIDs) if err != nil { return nil, mapError(err) } defer rows.Close() result := make(map[string][]string, len(chatIDs)) for rows.Next() { var chatID, userID string if err := rows.Scan(&chatID, &userID); err != nil { return nil, mapError(err) } result[chatID] = append(result[chatID], userID) } return result, mapError(rows.Err()) } var _ domain.ChatRepository = (*ChatRepo)(nil)