Files
thamanyah/cms/internal/services/db.go
T
FahdShalhoub 724351c271
Build, Push and Deploy CMS / build-push-deploy (push) Successful in 2m17s
FEAT: Change Catagories to a list
2026-08-16 22:29:35 +03:00

108 lines
2.7 KiB
Go

package services
import (
"context"
"database/sql"
"fmt"
"thamanyah/cms/v2/internal/db"
"time"
"github.com/google/uuid"
)
var DB DBClient
type Video struct {
ID string
Title string
Description string
Categories []string
Tags string
FileName string
StorageKey string
MediaConvertJobID string
Status string
SizeBytes int64
CreatedAt time.Time
UpdatedAt time.Time
}
type DBClient interface {
CreateVideo(ctx context.Context, v Video) (Video, error)
}
type DBConcrete struct {
ConnectionString string
}
func (svc DBConcrete) CreateVideo(ctx context.Context, v Video) (Video, error) {
sqlDB, err := sql.Open("postgres", svc.ConnectionString)
if err != nil {
return Video{}, err
}
defer sqlDB.Close()
id, err := uuid.NewV7()
if err != nil {
return Video{}, fmt.Errorf("generating video id: %w", err)
}
tx, err := sqlDB.BeginTx(ctx, nil)
if err != nil {
return Video{}, err
}
defer tx.Rollback()
row := tx.QueryRowContext(ctx, `
INSERT INTO videos (id, title, description, tags, file_name, storage_key, mediaconvert_job_id, status, size_bytes)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING created_at, updated_at
`, id, v.Title, v.Description, v.Tags, v.FileName, v.StorageKey, v.MediaConvertJobID, v.Status, v.SizeBytes)
if err := row.Scan(&v.CreatedAt, &v.UpdatedAt); err != nil {
return Video{}, err
}
for _, category := range v.Categories {
var categoryID int64
if err := tx.QueryRowContext(ctx, `SELECT id FROM categories WHERE name = $1`, category).Scan(&categoryID); err != nil {
return Video{}, fmt.Errorf("looking up category %q: %w", category, err)
}
if _, err := tx.ExecContext(ctx, `INSERT INTO video_categories (video_id, category_id) VALUES ($1, $2)`, id, categoryID); err != nil {
return Video{}, fmt.Errorf("linking category %q: %w", category, err)
}
}
if err := tx.Commit(); err != nil {
return Video{}, err
}
v.ID = id.String()
return v, nil
}
func (svc DBConcrete) Migrate() {
sqlDB, err := sql.Open("postgres", svc.ConnectionString)
if err != nil {
panic(fmt.Errorf("failed to open db connection: %w", err))
}
if err := db.Migrate(sqlDB); err != nil {
panic(err)
}
sqlDB.Close()
}
// AssertSuccessfulConnection verifies the database is reachable, mirroring
// S3Concrete's boot-time check — panics rather than let the service come up broken.
func (svc DBConcrete) AssertSuccessfulConnection(ctx context.Context) {
sqlDB, err := sql.Open("postgres", svc.ConnectionString)
if err != nil {
panic(fmt.Errorf("db: cannot open connection: %w", err))
}
defer sqlDB.Close()
if err := sqlDB.PingContext(ctx); err != nil {
panic(fmt.Errorf("db: cannot connect: %w", err))
}
}