This repository has been archived on 2024-04-06. You can view files and clone it, but cannot push or open issues or pull requests.
core-old/internal/bundb/version.go
Dawid Wysokiński 75d909ac6e
All checks were successful
continuous-integration/drone/push Build is passing
refactor: ennoblement/village - improve query performance - ListCountWithRelations
2022-12-28 11:11:58 +01:00

78 lines
1.8 KiB
Go

package bundb
import (
"context"
"database/sql"
"errors"
"fmt"
"gitea.dwysokinski.me/twhelp/core/internal/bundb/internal/model"
"gitea.dwysokinski.me/twhelp/core/internal/domain"
"github.com/uptrace/bun"
)
type Version struct {
db *bun.DB
}
func NewVersion(db *bun.DB) *Version {
return &Version{db: db}
}
func (v *Version) List(ctx context.Context) ([]domain.Version, error) {
var versions []model.Version
if err := v.buildListQuery(&versions).Scan(ctx); err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("couldn't select versions from the db: %w", err)
}
result := make([]domain.Version, 0, len(versions))
for _, version := range versions {
result = append(result, version.ToDomain())
}
return result, nil
}
func (v *Version) ListCount(ctx context.Context) ([]domain.Version, int64, error) {
var versions []model.Version
count, err := v.buildListQuery(&versions).ScanAndCount(ctx)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, 0, fmt.Errorf("couldn't select versions from the db: %w", err)
}
result := make([]domain.Version, 0, len(versions))
for _, version := range versions {
result = append(result, version.ToDomain())
}
return result, int64(count), nil
}
func (v *Version) buildListQuery(versions *[]model.Version) *bun.SelectQuery {
return v.db.NewSelect().
Model(versions).
Order("code ASC")
}
func (v *Version) GetByCode(ctx context.Context, code string) (domain.Version, error) {
var version model.Version
if err := v.db.NewSelect().
Model(&version).
Where("code = ?", code).
Scan(ctx); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return domain.Version{}, domain.VersionNotFoundError{VerCode: code}
}
return domain.Version{}, fmt.Errorf(
"something went wrong while selecting version (code=%s) from the db: %w",
code,
err,
)
}
return version.ToDomain(), nil
}