package repositories import ( "context" "database/sql" "errors" "fmt" "strings" "thamanyah/cms/v2/internal/models" ) type VideoRepository struct { SQLDB *sql.DB } var VideoRepo VideoRepository // UpdateVideoOutcomeByJobID records what became of a transcoding job: the // status it ended in, and the playback URL its output is served from. A job // that failed has no output, so playbackURL is empty for those and the column // is cleared along with the status. It returns ErrVideoNotFound when no video // carries that job id, which the consumer treats as a message to drop rather // than a fault. // // It returns the video it updated, carrying the members an announcement is // built from — the row's id and title, and the names of the categories it is // filed under. The consumer would otherwise have to read back what it just // wrote, and reading it here keeps that SQL on this side of the seam. func (svc VideoRepository) UpdateVideoOutcomeByJobID(ctx context.Context, jobID string, status models.VideoStatus, playbackURL string) (models.Video, error) { updated := models.Video{ Status: status, PlaybackURL: playbackURL, MediaConvertJobID: jobID, } err := svc.SQLDB.QueryRowContext(ctx, ` UPDATE videos SET status = $1, playback_url = $2, updated_at = now() WHERE mediaconvert_job_id = $3 RETURNING id, title `, string(status), playbackURL, jobID).Scan(&updated.ID, &updated.Title) if errors.Is(err, sql.ErrNoRows) { return models.Video{}, ErrVideoNotFound } if err != nil { return models.Video{}, err } rows, err := svc.SQLDB.QueryContext(ctx, ` SELECT c.name FROM video_categories vc JOIN categories c ON c.id = vc.category_id WHERE vc.video_id = $1 ORDER BY c.name `, updated.ID) if err != nil { return models.Video{}, err } defer rows.Close() for rows.Next() { var name string if err := rows.Scan(&name); err != nil { return models.Video{}, err } updated.CategoryNames = append(updated.CategoryNames, name) } return updated, rows.Err() } // GetVideoByID reads one video and the ids of the categories it is filed // under. It returns ErrVideoNotFound when no video has that id. func (svc VideoRepository) GetVideoByID(ctx context.Context, id string) (models.Video, error) { var v models.Video err := svc.SQLDB.QueryRowContext(ctx, ` SELECT id, title, description, tags, file_name, storage_key, mediaconvert_job_id, status, playback_url, size_bytes, created_at, updated_at FROM videos WHERE id = $1 `, id).Scan(&v.ID, &v.Title, &v.Description, &v.Tags, &v.FileName, &v.StorageKey, &v.MediaConvertJobID, &v.Status, &v.PlaybackURL, &v.SizeBytes, &v.CreatedAt, &v.UpdatedAt) if errors.Is(err, sql.ErrNoRows) { return models.Video{}, ErrVideoNotFound } if err != nil { return models.Video{}, err } rows, err := svc.SQLDB.QueryContext(ctx, `SELECT category_id FROM video_categories WHERE video_id = $1 ORDER BY category_id`, v.ID) if err != nil { return models.Video{}, err } defer rows.Close() for rows.Next() { var categoryID int16 if err := rows.Scan(&categoryID); err != nil { return models.Video{}, err } v.CategoryIDs = append(v.CategoryIDs, categoryID) } return v, rows.Err() } // VideoExistsWithStorageKey reports whether a video has already been // registered under a storage key. It is served by videos_storage_key_key, the // index Postgres builds for the column's UNIQUE constraint. func (svc VideoRepository) VideoExistsWithStorageKey(ctx context.Context, storageKey string) (bool, error) { var exists bool err := svc.SQLDB.QueryRowContext(ctx, `SELECT EXISTS (SELECT 1 FROM videos WHERE storage_key = $1)`, storageKey).Scan(&exists) if err != nil { return false, err } return exists, nil } func (svc VideoRepository) CreateVideo(ctx context.Context, v models.Video) (models.Video, error) { tx, err := svc.SQLDB.BeginTx(ctx, nil) if err != nil { return models.Video{}, err } defer tx.Rollback() row := tx.QueryRowContext(ctx, ` INSERT INTO videos (title, description, tags, file_name, storage_key, mediaconvert_job_id, status, size_bytes) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING id, created_at, updated_at `, v.Title, v.Description, v.Tags, v.FileName, v.StorageKey, v.MediaConvertJobID, string(v.Status), v.SizeBytes) if err := row.Scan(&v.ID, &v.CreatedAt, &v.UpdatedAt); err != nil { return models.Video{}, err } rows := make([]string, 0, len(v.CategoryIDs)) for _, categoryID := range v.CategoryIDs { rows = append(rows, fmt.Sprintf("($1, %d)", categoryID)) } if _, err := tx.ExecContext(ctx, `INSERT INTO video_categories (video_id, category_id) VALUES `+strings.Join(rows, ", "), v.ID); err != nil { return models.Video{}, fmt.Errorf("linking categories %v: %w", v.CategoryIDs, err) } if err := tx.Commit(); err != nil { return models.Video{}, err } return v, nil }