core/internal/adapter/repository_bun_server.go

325 lines
8.9 KiB
Go

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"
"github.com/uptrace/bun/dialect"
)
type ServerBunRepository struct {
db bun.IDB
}
func NewServerBunRepository(db bun.IDB) *ServerBunRepository {
return &ServerBunRepository{db: db}
}
func (repo *ServerBunRepository) CreateOrUpdate(ctx context.Context, params ...domain.CreateServerParams) error {
if len(params) == 0 {
return nil
}
now := time.Now()
servers := make(bunmodel.Servers, 0, len(params))
for _, p := range params {
base := p.Base()
servers = append(servers, bunmodel.Server{
Key: base.Key(),
URL: base.URL().String(),
Open: base.Open(),
VersionCode: p.VersionCode(),
CreatedAt: now,
})
}
q := repo.db.NewInsert().
Model(&servers)
//nolint:exhaustive
switch q.Dialect().Name() {
case dialect.PG:
q = q.On("CONFLICT ON CONSTRAINT servers_pkey DO UPDATE")
case dialect.SQLite:
q = q.On("CONFLICT(key) DO UPDATE")
default:
q = q.Err(errors.New("unsupported dialect"))
}
if _, err := q.
Set("url = EXCLUDED.url").
Set("open = EXCLUDED.open").
Returning("").
Exec(ctx); err != nil {
return fmt.Errorf("something went wrong while inserting servers into the db: %w", err)
}
return nil
}
func (repo *ServerBunRepository) List(
ctx context.Context,
params domain.ListServersParams,
) (domain.ListServersResult, error) {
var servers bunmodel.Servers
if err := repo.db.NewSelect().
Model(&servers).
Apply(listServersParamsApplier{params: params}.apply).
Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
return domain.ListServersResult{}, fmt.Errorf("couldn't select servers from the db: %w", err)
}
converted, err := servers.ToDomain()
if err != nil {
return domain.ListServersResult{}, err
}
return domain.NewListServersResult(separateListResultAndNext(converted, params.Limit()))
}
func (repo *ServerBunRepository) Update(ctx context.Context, key string, params domain.UpdateServerParams) error {
if params.IsZero() {
return errors.New("nothing to update")
}
res, err := repo.db.NewUpdate().
Model(&bunmodel.Server{}).
Where("key = ?", key).
Apply(updateServerParamsApplier{params: params}.apply).
Returning("").
Exec(ctx)
if err != nil {
return fmt.Errorf("%s: couldn't update server: %w", key, err)
}
if affected, _ := res.RowsAffected(); affected == 0 {
return domain.ServerNotFoundError{
Key: key,
}
}
return nil
}
type updateServerParamsApplier struct {
params domain.UpdateServerParams
}
//nolint:gocyclo
func (a updateServerParamsApplier) apply(q *bun.UpdateQuery) *bun.UpdateQuery {
if config := a.params.Config(); config.Valid {
q = q.Set("config = ?", bunmodel.NewServerConfig(config.Value))
}
if unitInfo := a.params.UnitInfo(); unitInfo.Valid {
q = q.Set("unit_info = ?", bunmodel.NewUnitInfo(unitInfo.Value))
}
if buildingInfo := a.params.BuildingInfo(); buildingInfo.Valid {
q = q.Set("building_info = ?", bunmodel.NewBuildingInfo(buildingInfo.Value))
}
if numTribes := a.params.NumTribes(); numTribes.Valid {
q = q.Set("num_tribes = ?", numTribes.Value)
}
if tribeDataSyncedAt := a.params.TribeDataSyncedAt(); tribeDataSyncedAt.Valid {
// TODO: rename this column to tribe_data_synced_at
q = q.Set("tribe_data_updated_at = ?", tribeDataSyncedAt.Value)
}
if numPlayers := a.params.NumPlayers(); numPlayers.Valid {
q = q.Set("num_players = ?", numPlayers.Value)
}
if playerDataSyncedAt := a.params.PlayerDataSyncedAt(); playerDataSyncedAt.Valid {
// TODO: rename this column to player_data_synced_at
q = q.Set("player_data_updated_at = ?", playerDataSyncedAt.Value)
}
if numVillages := a.params.NumVillages(); numVillages.Valid {
q = q.Set("num_villages = ?", numVillages.Value)
}
if numPlayerVillages := a.params.NumPlayerVillages(); numPlayerVillages.Valid {
q = q.Set("num_player_villages = ?", numPlayerVillages.Value)
}
if numBarbarianVillages := a.params.NumBarbarianVillages(); numBarbarianVillages.Valid {
q = q.Set("num_barbarian_villages = ?", numBarbarianVillages.Value)
}
if numBonusVillages := a.params.NumBonusVillages(); numBonusVillages.Valid {
q = q.Set("num_bonus_villages = ?", numBonusVillages.Value)
}
if villageDataSyncedAt := a.params.VillageDataSyncedAt(); villageDataSyncedAt.Valid {
// TODO: rename this column to village_data_synced_at
q = q.Set("village_data_updated_at = ?", villageDataSyncedAt.Value)
}
if ennoblementDataSyncedAt := a.params.EnnoblementDataSyncedAt(); ennoblementDataSyncedAt.Valid {
// TODO: rename this column to ennoblement_data_synced_at
q = q.Set("ennoblement_data_updated_at = ?", ennoblementDataSyncedAt.Value)
}
if tribeSnapshotsCreatedAt := a.params.TribeSnapshotsCreatedAt(); tribeSnapshotsCreatedAt.Valid {
q = q.Set("tribe_snapshots_created_at = ?", tribeSnapshotsCreatedAt.Value)
}
if playerSnapshotsCreatedAt := a.params.PlayerSnapshotsCreatedAt(); playerSnapshotsCreatedAt.Valid {
q = q.Set("player_snapshots_created_at = ?", playerSnapshotsCreatedAt.Value)
}
return q
}
type listServersParamsApplier struct {
params domain.ListServersParams
}
//nolint:gocyclo
func (a listServersParamsApplier) apply(q *bun.SelectQuery) *bun.SelectQuery {
if keys := a.params.Keys(); len(keys) > 0 {
q = q.Where("server.key IN (?)", bun.In(keys))
}
if versionCodes := a.params.VersionCodes(); len(versionCodes) > 0 {
q = q.Where("server.version_code IN (?)", bun.In(versionCodes))
}
if open := a.params.Open(); open.Valid {
q = q.Where("server.open = ?", open.Value)
}
if special := a.params.Special(); special.Valid {
q = q.Where("server.special = ?", special.Value)
}
if tribeSnapshotsCreatedAtLT := a.params.TribeSnapshotsCreatedAtLT(); tribeSnapshotsCreatedAtLT.Valid {
q = q.Where(
"server.tribe_snapshots_created_at < ? OR server.tribe_snapshots_created_at is null",
tribeSnapshotsCreatedAtLT.Value,
)
}
if playerSnapshotsCreatedAtLT := a.params.PlayerSnapshotsCreatedAtLT(); playerSnapshotsCreatedAtLT.Valid {
q = q.Where(
"server.player_snapshots_created_at < ? OR server.player_snapshots_created_at is null",
playerSnapshotsCreatedAtLT.Value,
)
}
for _, s := range a.params.Sort() {
switch s {
case domain.ServerSortKeyASC:
q = q.Order("server.key ASC")
case domain.ServerSortKeyDESC:
q = q.Order("server.key DESC")
case domain.ServerSortOpenASC:
q = q.Order("server.open ASC")
case domain.ServerSortOpenDESC:
q = q.Order("server.open DESC")
default:
return q.Err(errUnsupportedSortValue)
}
}
return q.Apply(a.applyCursor).Limit(a.params.Limit() + 1)
}
//nolint:gocyclo
func (a listServersParamsApplier) applyCursor(q *bun.SelectQuery) *bun.SelectQuery {
if a.params.Cursor().IsZero() {
return q
}
q.WhereGroup(" AND ", func(q *bun.SelectQuery) *bun.SelectQuery {
cursorKey := a.params.Cursor().Key()
cursorOpen := a.params.Cursor().Open()
sort := a.params.Sort()
sortLen := len(sort)
// based on https://github.com/prisma/prisma/issues/19159#issuecomment-1713389245
switch {
case sortLen == 1:
switch sort[0] {
case domain.ServerSortKeyASC:
q = q.Where("server.key >= ?", cursorKey)
case domain.ServerSortKeyDESC:
q = q.Where("server.key <= ?", cursorKey)
case domain.ServerSortOpenASC, domain.ServerSortOpenDESC:
return q.Err(errSortNoUniqueField)
default:
return q.Err(errUnsupportedSortValue)
}
case sortLen > 1:
q.WhereGroup(" OR ", func(q *bun.SelectQuery) *bun.SelectQuery {
switch sort[0] {
case domain.ServerSortKeyASC:
q = q.Where("server.key > ?", cursorKey)
case domain.ServerSortKeyDESC:
q = q.Where("server.key < ?", cursorKey)
case domain.ServerSortOpenASC:
q = q.Where("server.open > ?", cursorOpen)
case domain.ServerSortOpenDESC:
q = q.Where("server.open < ?", cursorOpen)
default:
return q.Err(errUnsupportedSortValue)
}
for i := 1; i < sortLen; i++ {
q.WhereGroup(" OR ", func(q *bun.SelectQuery) *bun.SelectQuery {
current := sort[i]
for j := 0; j < i; j++ {
s := sort[j]
switch s {
case domain.ServerSortKeyASC,
domain.ServerSortKeyDESC:
q = q.Where("server.key = ?", cursorKey)
case domain.ServerSortOpenASC,
domain.ServerSortOpenDESC:
q = q.Where("server.open = ?", cursorOpen)
default:
return q.Err(errUnsupportedSortValue)
}
}
switch current {
case domain.ServerSortKeyASC:
q = q.Where("server.key >= ?", cursorKey)
case domain.ServerSortKeyDESC:
q = q.Where("server.key <= ?", cursorKey)
case domain.ServerSortOpenASC:
q = q.Where("server.open >= ?", cursorOpen)
case domain.ServerSortOpenDESC:
q = q.Where("server.open <= ?", cursorOpen)
default:
return q.Err(errUnsupportedSortValue)
}
return q
})
}
return q
})
}
return q
})
return q
}