-
Notifications
You must be signed in to change notification settings - Fork 0
/
list.go
68 lines (57 loc) · 1.97 KB
/
list.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package ldb
import (
"context"
"strings"
"github.com/pkg/errors"
"admini.dev/admini/app/lib/database"
"admini.dev/admini/app/lib/filter"
"admini.dev/admini/app/lib/schema/model"
"admini.dev/admini/app/result"
"admini.dev/admini/app/util"
)
func List(ctx context.Context, db *database.Service, m *model.Model, opts *filter.Options, logger util.Logger) (*result.Result, error) {
p := opts.Params
if p != nil && p.Limit == 0 {
p.Limit = filter.MaxRowsDefault
}
q := modelListQuery(db.Type, m, p)
rows, err := db.Query(ctx, q, nil, logger)
if err != nil {
return nil, errors.Wrapf(err, "error listing models for [%s]", m.String())
}
defer func() { _ = rows.Close() }()
count, err := Count(ctx, db, m, logger)
if err != nil {
return nil, errors.Wrapf(err, "error constructing result for [%s]", m.String())
}
var timing *result.Timing
ret, err := ParseResultFields(m.Name(), count, q, timing, m.Fields, rows)
if err != nil {
return nil, errors.Wrapf(err, "error constructing result for [%s]", m.String())
}
return ret, nil
}
func Count(ctx context.Context, db *database.Service, m *model.Model, logger util.Logger) (int, error) {
q := modelCountQuery(db.Type, m)
c := struct {
C int `db:"c"`
}{}
if err := db.Get(ctx, &c, q, nil, logger); err != nil {
return 0, errors.Wrapf(err, "error listing models for [%s]", m.String())
}
return c.C, nil
}
func modelListQuery(typ *database.DBType, m *model.Model, params *filter.Params) string {
cols, tbl := forTable(typ, m)
return database.SQLSelect(cols, tbl, "", params.OrderByString(), params.Limit, params.Offset)
}
func modelCountQuery(typ *database.DBType, m *model.Model) string {
return database.SQLSelectSimple("count(*) as c", m.Path().Quoted(typ.Quote))
}
func forTable(typ *database.DBType, m *model.Model) (string, string) {
cols := make([]string, 0, len(m.Fields))
for _, f := range m.Fields {
cols = append(cols, typ.Quote+f.Key+typ.Quote)
}
return strings.Join(cols, ", "), m.Path().Quoted(typ.Quote)
}