diff --git a/backend/internal/storage/postgres/message.go b/backend/internal/storage/postgres/message.go new file mode 100644 index 0000000..cd1cdc3 --- /dev/null +++ b/backend/internal/storage/postgres/message.go @@ -0,0 +1,108 @@ +package postgres + +import ( + "context" + "time" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + + "high-loud-apps-labs/internal/domain" +) + +type MessageRepo struct { + pool *pgxpool.Pool +} + +func NewMessageRepo(pool *pgxpool.Pool) *MessageRepo { + return &MessageRepo{pool: pool} +} + +func (r *MessageRepo) Create(ctx context.Context, m *domain.Message) error { + const q = ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + VALUES ($1::uuid, $2::uuid, $3::uuid, $4, $5) + ` + _, err := r.pool.Exec(ctx, q, m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt) + if err != nil { + if foreignKeyViolation(err) { + return &domain.NotFoundError{Entity: "chat", ID: m.ChatID} + } + if checkViolation(err) { + return &domain.ValidationError{Field: "text", Message: "нарушено ограничение"} + } + return err + } + return nil +} + +func (r *MessageRepo) ListByChat(ctx context.Context, chatID string, limit int, cursor *string) ([]domain.Message, *string, error) { + scope := "messages:" + chatID + + 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 id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1::uuid + AND (created_at, id) > ($2, $3::uuid) + ORDER BY created_at, id + LIMIT $4 + ` + rows, err = r.pool.Query(ctx, q, chatID, afterTime, afterID, limit+1) + } else { + const q = ` + SELECT id, chat_id, sender_id, text, created_at + FROM messages + WHERE chat_id = $1::uuid + ORDER BY created_at, id + LIMIT $2 + ` + rows, err = r.pool.Query(ctx, q, chatID, limit+1) + } + if err != nil { + return nil, nil, err + } + defer rows.Close() + + page := make([]domain.Message, 0, limit) + for rows.Next() { + var m domain.Message + if err := rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, nil, err + } + page = append(page, m) + } + if err := rows.Err(); err != nil { + return nil, nil, 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 + } + return page, next, nil +} + +var _ domain.MessageRepository = (*MessageRepo)(nil)