package db import ( "context" "github.com/pkg/errors" "github.com/uptrace/bun" ) type League struct { bun.BaseModel `bun:"table:leagues,alias:l"` ID int `bun:"id,pk,autoincrement"` Name string `bun:"name,unique,notnull"` ShortName string `bun:"short_name,unique,notnull"` Description string `bun:"description"` Seasons []Season `bun:"m2m:season_leagues,join:League=Season"` Teams []Team `bun:"m2m:team_participations,join:League=Team"` } type SeasonLeague struct { SeasonID int `bun:",pk"` Season *Season `bun:"rel:belongs-to,join:season_id=id"` LeagueID int `bun:",pk"` League *League `bun:"rel:belongs-to,join:league_id=id"` } func GetLeagues(ctx context.Context, tx bun.Tx) ([]*League, error) { return GetList[League](tx).Relation("Seasons").GetAll(ctx) } func GetLeague(ctx context.Context, tx bun.Tx, shortname string) (*League, error) { if shortname == "" { return nil, errors.New("shortname cannot be empty") } return GetByField[League](tx, "short_name", shortname).Relation("Seasons").Get(ctx) } // GetSeasonLeague retrieves a specific season-league combination with teams func GetSeasonLeague(ctx context.Context, tx bun.Tx, seasonShortName, leagueShortName string) (*Season, *League, []*Team, error) { if seasonShortName == "" { return nil, nil, nil, errors.New("season short_name cannot be empty") } if leagueShortName == "" { return nil, nil, nil, errors.New("league short_name cannot be empty") } // Get the season season, err := GetSeason(ctx, tx, seasonShortName) if err != nil { return nil, nil, nil, errors.Wrap(err, "GetSeason") } // Get the league league, err := GetLeague(ctx, tx, leagueShortName) if err != nil { return nil, nil, nil, errors.Wrap(err, "GetLeague") } if season == nil || league == nil || !season.HasLeague(league.ID) { return nil, nil, nil, nil } // Get all teams participating in this season+league var teams []*Team err = tx.NewSelect(). Model(&teams). Join("INNER JOIN team_participations AS tp ON tp.team_id = t.id"). Where("tp.season_id = ? AND tp.league_id = ?", season.ID, league.ID). Order("t.name ASC"). Scan(ctx) if err != nil { return nil, nil, nil, errors.Wrap(err, "tx.Select teams") } return season, league, teams, nil }