84 lines
1.7 KiB
Go
84 lines
1.7 KiB
Go
package db
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
|
|
"github.com/pkg/errors"
|
|
"github.com/uptrace/bun"
|
|
)
|
|
|
|
type Season struct {
|
|
bun.BaseModel `bun:"table:seasons,alias:s"`
|
|
|
|
ID int `bun:"id,pk,autoincrement"`
|
|
Name string `bun:"name,unique"`
|
|
ShortName string `bun:"short_name,unique"`
|
|
}
|
|
|
|
type SeasonList struct {
|
|
Seasons []Season
|
|
Total int
|
|
PageOpts PageOpts
|
|
}
|
|
|
|
func NewSeason(ctx context.Context, tx bun.Tx, name, shortname string) (*Season, error) {
|
|
if name == "" {
|
|
return nil, errors.New("name cannot be empty")
|
|
}
|
|
if shortname == "" {
|
|
return nil, errors.New("shortname cannot be empty")
|
|
}
|
|
season := &Season{
|
|
Name: name,
|
|
ShortName: shortname,
|
|
}
|
|
_, err := tx.NewInsert().
|
|
Model(season).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return nil, errors.Wrap(err, "tx.NewInsert")
|
|
}
|
|
return season, nil
|
|
}
|
|
|
|
func ListSeasons(ctx context.Context, tx bun.Tx, pageOpts *PageOpts) (*SeasonList, error) {
|
|
if pageOpts == nil {
|
|
pageOpts = &PageOpts{}
|
|
}
|
|
if pageOpts.Page == 0 {
|
|
pageOpts.Page = 1
|
|
}
|
|
if pageOpts.PerPage == 0 {
|
|
pageOpts.PerPage = 10
|
|
}
|
|
if pageOpts.Order == "" {
|
|
pageOpts.Order = bun.OrderDesc
|
|
}
|
|
if pageOpts.OrderBy == "" {
|
|
pageOpts.OrderBy = "name"
|
|
}
|
|
seasons := []Season{}
|
|
err := tx.NewSelect().
|
|
Model(&seasons).
|
|
OrderBy(pageOpts.OrderBy, pageOpts.Order).
|
|
Offset(pageOpts.PerPage * (pageOpts.Page - 1)).
|
|
Limit(pageOpts.PerPage).
|
|
Scan(ctx)
|
|
if err != nil && err != sql.ErrNoRows {
|
|
return nil, errors.Wrap(err, "tx.NewSelect")
|
|
}
|
|
total, err := tx.NewSelect().
|
|
Model(&seasons).
|
|
Count(ctx)
|
|
if err != nil && err != sql.ErrNoRows {
|
|
return nil, errors.Wrap(err, "tx.NewSelect")
|
|
}
|
|
sl := &SeasonList{
|
|
Seasons: seasons,
|
|
Total: total,
|
|
PageOpts: *pageOpts,
|
|
}
|
|
return sl, nil
|
|
}
|