quintodrome/persistence/db_sql/sql_repository.go

92 lines
2 KiB
Go
Raw Normal View History

2020-01-12 13:32:06 -09:00
package db_sql
import (
"github.com/astaxie/beego/orm"
2020-01-12 14:36:19 -09:00
"github.com/cloudsonic/sonic-server/domain"
2020-01-12 13:32:06 -09:00
"github.com/cloudsonic/sonic-server/persistence"
)
type sqlRepository struct {
entityName string
}
2020-01-12 14:36:19 -09:00
func (r *sqlRepository) newQuery(o orm.Ormer, options ...domain.QueryOptions) orm.QuerySeter {
q := o.QueryTable(r.entityName)
if len(options) > 0 {
opts := options[0]
q = q.Offset(opts.Offset)
if opts.Size > 0 {
q = q.Limit(opts.Size)
}
if opts.SortBy != "" {
if opts.Desc {
q = q.OrderBy("-" + opts.SortBy)
} else {
q = q.OrderBy(opts.SortBy)
}
}
}
return q
2020-01-12 13:32:06 -09:00
}
func (r *sqlRepository) CountAll() (int64, error) {
return r.newQuery(Db()).Count()
}
func (r *sqlRepository) Exists(id string) (bool, error) {
c, err := r.newQuery(Db()).Filter("id", id).Count()
return c == 1, err
}
2020-01-12 14:55:55 -09:00
// TODO This is used to generate random lists. Can be optimized in SQL: https://stackoverflow.com/a/19419
func (r *sqlRepository) GetAllIds() ([]string, error) {
qs := r.newQuery(Db())
var values []orm.Params
num, err := qs.Values(&values, "id")
if num == 0 {
return nil, err
}
result := persistence.CollectValue(values, func(item interface{}) string {
return item.(orm.Params)["ID"].(string)
})
return result, nil
}
2020-01-12 14:36:19 -09:00
func (r *sqlRepository) put(id string, a interface{}) error {
2020-01-12 13:32:06 -09:00
return WithTx(func(o orm.Ormer) error {
2020-01-12 14:36:19 -09:00
c, err := r.newQuery(o).Filter("id", id).Count()
2020-01-12 13:32:06 -09:00
if err != nil {
return err
}
if c == 0 {
_, err = o.Insert(a)
return err
}
_, err = o.Update(a)
return err
})
}
func (r *sqlRepository) purgeInactive(activeList interface{}, getId func(item interface{}) string) ([]string, error) {
ids := persistence.CollectValue(activeList, getId)
var values []orm.Params
err := WithTx(func(o orm.Ormer) error {
2020-01-12 14:36:19 -09:00
qs := r.newQuery(o).Exclude("id__in", ids)
2020-01-12 13:32:06 -09:00
num, err := qs.Values(&values, "id")
if num > 0 {
_, err = qs.Delete()
}
return err
})
if err != nil {
return nil, err
}
result := make([]string, len(values))
for i, v := range values {
result[i] = v["ID"].(string)
}
return result, nil
}