2020-06-02 15:45:21 +00:00
|
|
|
package repository
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2021-05-05 17:32:45 +00:00
|
|
|
"github.com/Kichiyaki/gopgutil/v10"
|
|
|
|
"github.com/tribalwarshelp/shared/tw/twmodel"
|
2020-06-02 15:45:21 +00:00
|
|
|
|
|
|
|
"github.com/go-pg/pg/v10"
|
|
|
|
"github.com/go-pg/pg/v10/orm"
|
|
|
|
"github.com/pkg/errors"
|
2021-05-05 17:32:45 +00:00
|
|
|
|
2020-11-06 19:23:12 +00:00
|
|
|
"github.com/tribalwarshelp/api/version"
|
2020-06-02 15:45:21 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type pgRepository struct {
|
|
|
|
*pg.DB
|
|
|
|
}
|
|
|
|
|
2020-11-06 19:23:12 +00:00
|
|
|
func NewPGRepository(db *pg.DB) (version.Repository, error) {
|
2021-05-05 17:32:45 +00:00
|
|
|
if err := db.Model(&twmodel.Version{}).CreateTable(&orm.CreateTableOptions{
|
2020-06-02 15:45:21 +00:00
|
|
|
IfNotExists: true,
|
|
|
|
}); err != nil {
|
2021-01-13 19:28:24 +00:00
|
|
|
return nil, errors.Wrap(err, "cannot create 'versions' table")
|
2020-06-02 15:45:21 +00:00
|
|
|
}
|
|
|
|
return &pgRepository{db}, nil
|
|
|
|
}
|
|
|
|
|
2021-05-05 17:32:45 +00:00
|
|
|
func (repo *pgRepository) Fetch(ctx context.Context, cfg version.FetchConfig) ([]*twmodel.Version, int, error) {
|
2020-06-02 15:45:21 +00:00
|
|
|
var err error
|
2021-05-06 15:01:22 +00:00
|
|
|
data := make([]*twmodel.Version, 0)
|
2020-06-24 13:05:31 +00:00
|
|
|
total := 0
|
2020-11-21 11:34:25 +00:00
|
|
|
query := repo.
|
|
|
|
Model(&data).
|
|
|
|
Context(ctx).
|
|
|
|
Limit(cfg.Limit).
|
2021-05-05 17:32:45 +00:00
|
|
|
Offset(cfg.Offset).
|
|
|
|
Apply(cfg.Filter.Where).
|
|
|
|
Apply(gopgutil.OrderAppender{
|
|
|
|
Orders: cfg.Sort,
|
|
|
|
MaxDepth: 4,
|
|
|
|
}.Apply)
|
2020-06-02 15:45:21 +00:00
|
|
|
|
2021-03-21 12:03:39 +00:00
|
|
|
if cfg.Count && cfg.Select {
|
2020-06-24 13:05:31 +00:00
|
|
|
total, err = query.SelectAndCount()
|
2021-03-21 12:03:39 +00:00
|
|
|
} else if cfg.Select {
|
2020-06-24 13:05:31 +00:00
|
|
|
err = query.Select()
|
2021-03-21 12:03:39 +00:00
|
|
|
} else if cfg.Count {
|
|
|
|
total, err = query.Count()
|
2020-06-24 13:05:31 +00:00
|
|
|
}
|
2020-06-02 15:45:21 +00:00
|
|
|
if err != nil && err != pg.ErrNoRows {
|
2021-05-05 17:49:00 +00:00
|
|
|
return nil, 0, errors.New("Internal server error")
|
2020-06-02 15:45:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return data, total, nil
|
|
|
|
}
|