FEAT: Added Database To CMS Serbove
Build, Push and Deploy CMS / build-push-deploy (push) Successful in 2m17s
Build, Push and Deploy CMS / build-push-deploy (push) Successful in 2m17s
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"thamanyah/cms/v2/internal/db"
|
||||
"time"
|
||||
)
|
||||
|
||||
var DB DBClient
|
||||
|
||||
type Video struct {
|
||||
ID string
|
||||
Title string
|
||||
Description string
|
||||
Category 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) {
|
||||
db, err := sql.Open("postgres", svc.ConnectionString)
|
||||
if err != nil {
|
||||
return Video{}, err
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
var categoryID int64
|
||||
if err := db.QueryRowContext(ctx, `SELECT id FROM categories WHERE name = $1`, v.Category).Scan(&categoryID); err != nil {
|
||||
return Video{}, fmt.Errorf("looking up category %q: %w", v.Category, err)
|
||||
}
|
||||
|
||||
row := db.QueryRowContext(ctx, `
|
||||
INSERT INTO videos (title, description, category_id, tags, file_name, storage_key, mediaconvert_job_id, status, size_bytes)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING created_at, updated_at
|
||||
`, v.Title, v.Description, categoryID, 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
|
||||
}
|
||||
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) {
|
||||
db, err := sql.Open("postgres", svc.ConnectionString)
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("db: cannot open connection: %w", err))
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
panic(fmt.Errorf("db: cannot connect: %w", err))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user