package adapter import ( "context" "database/sql" "errors" "fmt" "time" "gitea.dwysokinski.me/twhelp/corev3/internal/bun/bunmodel" "gitea.dwysokinski.me/twhelp/corev3/internal/domain" "github.com/uptrace/bun" ) type TribeSnapshotBunRepository struct { db bun.IDB } func NewTribeSnapshotBunRepository(db bun.IDB) *TribeSnapshotBunRepository { return &TribeSnapshotBunRepository{db: db} } func (repo *TribeSnapshotBunRepository) Create(ctx context.Context, params ...domain.CreateTribeSnapshotParams) error { if len(params) == 0 { return nil } now := time.Now() tribeSnapshots := make(bunmodel.TribeSnapshots, 0, len(params)) for _, p := range params { tribeSnapshots = append(tribeSnapshots, bunmodel.TribeSnapshot{ TribeID: p.TribeID(), ServerKey: p.ServerKey(), NumMembers: p.NumMembers(), NumVillages: p.NumVillages(), Points: p.Points(), AllPoints: p.AllPoints(), Rank: p.Rank(), Dominance: p.Dominance(), Date: p.Date(), CreatedAt: now, OpponentsDefeated: bunmodel.NewOpponentsDefeated(p.OD()), }) } if _, err := repo.db.NewInsert(). Model(&tribeSnapshots). Ignore(). Returning(""). Exec(ctx); err != nil { return fmt.Errorf("something went wrong while inserting tribe snapshots into the db: %w", err) } return nil } func (repo *TribeSnapshotBunRepository) List( ctx context.Context, params domain.ListTribeSnapshotsParams, ) (domain.TribeSnapshots, error) { var tribeSnapshots bunmodel.TribeSnapshots if err := repo.db.NewSelect(). Model(&tribeSnapshots). Apply(listTribeSnapshotsParamsApplier{params: params}.apply). Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) { return nil, fmt.Errorf("couldn't select tribe snapshots from the db: %w", err) } return tribeSnapshots.ToDomain() } type listTribeSnapshotsParamsApplier struct { params domain.ListTribeSnapshotsParams } func (a listTribeSnapshotsParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery { if serverKeys := a.params.ServerKeys(); len(serverKeys) > 0 { q = q.Where("ts.server_key IN (?)", bun.In(serverKeys)) } for _, s := range a.params.Sort() { column, dir, err := a.sortToColumnAndDirection(s) if err != nil { return q.Err(err) } q.OrderExpr("? ?", column, dir.Bun()) } return q.Limit(a.params.Limit()).Offset(a.params.Offset()) } func (a listTribeSnapshotsParamsApplier) sortToColumnAndDirection( s domain.TribeSnapshotSort, ) (bun.Safe, sortDirection, error) { switch s { case domain.TribeSnapshotSortDateASC: return "ts.date", sortDirectionASC, nil case domain.TribeSnapshotSortDateDESC: return "ts.date", sortDirectionDESC, nil case domain.TribeSnapshotSortIDASC: return "ts.id", sortDirectionASC, nil case domain.TribeSnapshotSortIDDESC: return "ts.id", sortDirectionDESC, nil case domain.TribeSnapshotSortServerKeyASC: return "ts.server_key", sortDirectionASC, nil case domain.TribeSnapshotSortServerKeyDESC: return "ts.server_key", sortDirectionDESC, nil default: return "", 0, fmt.Errorf("%s: %w", s.String(), errInvalidSortValue) } }