72 lines
1.3 KiB
Go
72 lines
1.3 KiB
Go
package shows
|
|
|
|
import (
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/jmoiron/sqlx"
|
|
"github.com/odwrtw/polochon/lib"
|
|
)
|
|
|
|
const showsCreate = `
|
|
CREATE TABLE shows (
|
|
id SERIAL PRIMARY KEY,
|
|
imdbid text NOT NULL UNIQUE,
|
|
title text NOT NULL,
|
|
updated timestamp DEFAULT current_timestamp,
|
|
created timestamp DEFAULT current_timestamp
|
|
);
|
|
`
|
|
|
|
const (
|
|
addShowQuery = `INSERT INTO shows (imdbid, title) VALUES (:imdbid, :title) RETURNING id;`
|
|
getShowQuery = `SELECT * FROM shows WHERE imdbid=$1;`
|
|
deleteShowQuery = `DELETE FROM shows WHERE id=$1;`
|
|
)
|
|
|
|
// BaseTable have to be embeded in all your struct which reflect a table
|
|
type BaseTable struct {
|
|
Updated time.Time
|
|
Created time.Time
|
|
}
|
|
|
|
type Show struct {
|
|
ID int
|
|
polochon.Show
|
|
BaseTable
|
|
}
|
|
|
|
func Get(db *sqlx.DB, imdbID string) (*Show, error) {
|
|
s := &Show{}
|
|
err := db.QueryRowx(getShowQuery, imdbID).StructScan(s)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
func (s *Show) Add(db *sqlx.DB) error {
|
|
var id int
|
|
r, err := db.NamedQuery(addShowQuery, s)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for r.Next() {
|
|
r.Scan(&id)
|
|
}
|
|
s.ID = id
|
|
return nil
|
|
}
|
|
|
|
func (s *Show) Delete(db *sqlx.DB) error {
|
|
r, err := db.Exec(deleteShowQuery, s.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
count, _ := r.RowsAffected()
|
|
if count != 1 {
|
|
return fmt.Errorf("Unexpected number of row deleted: %d", count)
|
|
}
|
|
return nil
|
|
}
|