All checks were successful
continuous-integration/drone/push Build is passing
78 lines
1.8 KiB
Go
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
|
|
}
|