Files
thamanyah/cms/internal/db/repositories/videos.go
T
FahdShalhoub 88c64adf38
Build, Push and Deploy CMS / build-push-deploy (push) Successful in 2m19s
FIX: Gap Of Uploading The Same File Key Twice
2026-08-27 18:56:08 +03:00

62 lines
1.8 KiB
Go

package repositories
import (
"context"
"database/sql"
"fmt"
"strings"
"thamanyah/cms/v2/internal/models"
)
type VideoRepository struct {
SQLDB *sql.DB
}
var VideoRepo VideoRepository
// 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
}