Files
Datarush/internal/task/repository/postgres/repository.go
T
2025-12-19 21:04:12 +03:00

86 lines
2.6 KiB
Go

package postgres
import (
"context"
"github.com/jmoiron/sqlx"
"datarush/pkg/api/task"
)
type TaskRepository struct {
db *sqlx.DB
}
func NewTaskRepository(db *sqlx.DB) *TaskRepository {
return &TaskRepository{db: db}
}
func (r *TaskRepository) CreateTask(ctx context.Context, t *task.Task) (*task.Task, error) {
query := `INSERT INTO tasks (competition_id, title, description, in_competition_position, max_points, max_attempts, type)
VALUES ($1, $2, $3, $4, $5, $6, $7) RETURNING id, created_at, updated_at`
var createdTask task.Task
err := r.db.QueryRowxContext(ctx, query, t.CompetitionId, t.Title, t.Description, t.InCompetitionPosition, t.MaxPoints, t.MaxAttempts, t.Type).
StructScan(&createdTask)
if err != nil {
return nil, err
}
createdTask.CompetitionId = t.CompetitionId
createdTask.Title = t.Title
createdTask.Description = t.Description
createdTask.InCompetitionPosition = t.InCompetitionPosition
createdTask.MaxPoints = t.MaxPoints
createdTask.MaxAttempts = t.MaxAttempts
createdTask.Type = t.Type
return &createdTask, nil
}
func (r *TaskRepository) GetTask(ctx context.Context, id string) (*task.Task, error) {
var t task.Task
err := r.db.GetContext(ctx, &t, "SELECT * FROM tasks WHERE id = $1", id)
return &t, err
}
func (r *TaskRepository) EditTask(ctx context.Context, t *task.Task) (*task.Task, error) {
query := `UPDATE tasks SET title = $1, description = $2, in_competition_position = $3, max_points = $4, max_attempts = $5, type = $6, updated_at = now()
WHERE id = $7 RETURNING updated_at`
var updatedTask task.Task
err := r.db.QueryRowxContext(ctx, query, t.Title, t.Description, t.InCompetitionPosition, t.MaxPoints, t.MaxAttempts, t.Type, t.Id).
StructScan(&updatedTask)
if err != nil {
return nil, err
}
t.UpdatedAt = updatedTask.UpdatedAt
return t, nil
}
func (r *TaskRepository) DeleteTask(ctx context.Context, id string) error {
_, err := r.db.ExecContext(ctx, "DELETE FROM tasks WHERE id = $1", id)
return err
}
func (r *TaskRepository) ListCompetitionTasks(ctx context.Context, competitionID string) ([]*task.Task, error) {
var tasks []*task.Task
err := r.db.SelectContext(ctx, &tasks, "SELECT * FROM tasks WHERE competition_id = $1", competitionID)
return tasks, err
}
func (r *TaskRepository) GetTaskAttachments(
ctx context.Context,
taskID string,
showPrivate bool,
) ([]*task.TaskAttachment, error) {
var attachments []*task.TaskAttachment
query := "SELECT * FROM task_attachments WHERE task_id = $1"
args := []interface{}{taskID}
if !showPrivate {
query += " AND is_public = true"
}
err := r.db.SelectContext(ctx, &attachments, query, args...)
return attachments, err
}