Files
mtusi2026lab2/internal/repository/postgres/message.go
T
Weinmaier_Andrew d8842a3de4
Skeleton contracts / contracts (pull_request) Canceled after 0s
lab2: postgres, sessions, redis, persistence, stale read
2026-10-09 21:30:36 +03:00

56 lines
1.4 KiB
Go

package postgres
import (
"context"
"fmt"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/charawein/mtusi2026lab2/internal/domain"
)
type MessageRepository struct {
pool *pgxpool.Pool
}
func NewMessageRepository(pool *pgxpool.Pool) *MessageRepository {
return &MessageRepository{pool: pool}
}
func (r *MessageRepository) Create(ctx context.Context, msg *domain.Message) error {
const q = `
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES ($1, $2::uuid, $3::uuid, $4, $5)
`
if _, err := r.pool.Exec(ctx, q, msg.ID, msg.ChatID, msg.SenderID, msg.Text, msg.CreatedAt); err != nil {
return fmt.Errorf("insert message: %w", err)
}
return nil
}
func (r *MessageRepository) ListByChat(ctx context.Context, chatID string, cursor time.Time, cursorID string, limit int) ([]*domain.Message, error) {
const q = `
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = $1::uuid
AND (created_at > $2 OR (created_at = $2 AND id > $3::uuid))
ORDER BY created_at, id
LIMIT $4
`
rows, err := r.pool.Query(ctx, q, chatID, cursor, cursorID, limit)
if err != nil {
return nil, fmt.Errorf("list messages: %w", err)
}
defer rows.Close()
msgs := []*domain.Message{}
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, fmt.Errorf("scan message: %w", err)
}
msgs = append(msgs, &m)
}
return msgs, rows.Err()
}