package db import ( "context" "github.com/pkg/errors" "github.com/uptrace/bun" ) type Team struct { bun.BaseModel `bun:"table:teams,alias:t"` ID int `bun:"id,pk,autoincrement" json:"id"` Name string `bun:"name,unique,notnull" json:"name"` ShortName string `bun:"short_name,notnull,unique:short_names" json:"short_name"` AltShortName string `bun:"alt_short_name,notnull,unique:short_names" json:"alt_short_name"` Color string `bun:"color" json:"color,omitempty"` Seasons []Season `bun:"m2m:team_participations,join:Team=Season" json:"-"` Leagues []League `bun:"m2m:team_participations,join:Team=League" json:"-"` Players []Player `bun:"m2m:team_rosters,join:Team=Player" json:"-"` } func NewTeam(ctx context.Context, tx bun.Tx, name, shortName, altShortName, color string, audit *AuditMeta) (*Team, error) { team := &Team{ Name: name, ShortName: shortName, AltShortName: altShortName, Color: color, } err := Insert(tx, team). WithAudit(audit, nil).Exec(ctx) if err != nil { return nil, errors.Wrap(err, "db.Insert") } return team, nil } func ListTeams(ctx context.Context, tx bun.Tx, pageOpts *PageOpts) (*List[Team], error) { defaults := &PageOpts{ 1, 10, bun.OrderAsc, "name", } return GetList[Team](tx).GetPaged(ctx, pageOpts, defaults) } func GetTeam(ctx context.Context, tx bun.Tx, id int) (*Team, error) { if id == 0 { return nil, errors.New("id not provided") } return GetByID[Team](tx, id).Relation("Seasons").Relation("Leagues").Get(ctx) } func TeamShortNamesUnique(ctx context.Context, tx bun.Tx, shortName, altShortName string) (bool, error) { // Check if this combination of short_name and alt_short_name exists count, err := tx.NewSelect(). Model((*Team)(nil)). Where("short_name = ? AND alt_short_name = ?", shortName, altShortName). Count(ctx) if err != nil { return false, errors.Wrap(err, "tx.Select") } return count == 0, nil } func (t *Team) InSeason(seasonID int) bool { for _, season := range t.Seasons { if season.ID == seasonID { return true } } return false }