61 lines
1.3 KiB
Go
61 lines
1.3 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
)
|
|
|
|
func init() {
|
|
log.Println("db.go loading..")
|
|
var err error
|
|
|
|
app.db, err = pgx.Connect(context.Background(), config.GetString("db.connstring"))
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
log.Println("db.go done.")
|
|
}
|
|
|
|
type Playlist struct {
|
|
Id uuid.UUID
|
|
Url string
|
|
Title string
|
|
}
|
|
|
|
func (app App) GetPlaylists() (playlists []Playlist, err error) {
|
|
rows, err := app.db.Query(context.Background(), "SELECT id, url, title FROM playlists")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
playlists, err = pgx.CollectRows(rows, pgx.RowToStructByName[Playlist])
|
|
return
|
|
}
|
|
|
|
func (app App) GetPlaylist(id uuid.UUID) (*Playlist, error) {
|
|
rows, err := app.db.Query(context.Background(), "SELECT id, url, title FROM playlists where id=$1 limit 1", id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
//var out Playlist
|
|
out, err := pgx.CollectOneRow(rows, pgx.RowToAddrOfStructByName[Playlist])
|
|
if err != nil {
|
|
return new(Playlist), err
|
|
}
|
|
|
|
return out, nil
|
|
}
|
|
|
|
func (app App) AddPlaylist(title string, uri string) (uuid.UUID, error) {
|
|
id := uuid.New()
|
|
_, err := app.db.Exec(context.Background(), "INSERT INTO playlists VALUES ($1, $2, $3)", id, title, uri)
|
|
if err != nil {
|
|
return *new(uuid.UUID), err
|
|
}
|
|
return id, nil
|
|
}
|