dndmusicbot/db.go

63 lines
1.2 KiB
Go
Raw Permalink Normal View History

2022-11-18 21:18:12 +00:00
package main
import (
"context"
"log"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
2022-12-22 11:43:40 +00:00
var db *pgx.Conn
2022-11-18 21:18:12 +00:00
func init() {
log.Println("db.go loading..")
var err error
2022-12-22 11:43:40 +00:00
db, err = pgx.Connect(context.Background(), config.GetString("db.connstring"))
2022-11-18 21:18:12 +00:00
if err != nil {
log.Fatal(err)
}
log.Println("db.go done.")
}
type Playlist struct {
Id uuid.UUID
Url string
Title string
}
2022-12-22 11:43:40 +00:00
func GetPlaylists() (playlists []Playlist, err error) {
rows, err := db.Query(context.Background(), "SELECT id, url, title FROM playlists")
2022-11-18 21:18:12 +00:00
if err != nil {
return nil, err
}
playlists, err = pgx.CollectRows(rows, pgx.RowToStructByName[Playlist])
return
}
2022-12-22 11:43:40 +00:00
func GetPlaylist(id uuid.UUID) (*Playlist, error) {
rows, err := db.Query(context.Background(), "SELECT id, url, title FROM playlists where id=$1 limit 1", id)
2022-11-18 21:18:12 +00:00
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
}
2022-12-22 11:43:40 +00:00
func AddPlaylist(title string, uri string) (uuid.UUID, error) {
2022-11-18 21:18:12 +00:00
id := uuid.New()
2022-12-22 11:43:40 +00:00
_, err := db.Exec(context.Background(), "INSERT INTO playlists VALUES ($1, $2, $3)", id, title, uri)
2022-11-18 21:18:12 +00:00
if err != nil {
return *new(uuid.UUID), err
}
return id, nil
}