-
Notifications
You must be signed in to change notification settings - Fork 0
/
menu.go
95 lines (75 loc) · 2.04 KB
/
menu.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package pg
import (
"database/sql"
"github.com/Digital-Voting-Team/menu-service/internal/data"
"gitlab.com/distributed_lab/kit/pgdb"
sq "github.com/Masterminds/squirrel"
"github.com/fatih/structs"
)
const menusTableName = "public.menus"
func NewMenusQ(db *pgdb.DB) data.MenusQ {
return &menusQ{
db: db.Clone(),
sql: sq.Select("menus.*").From(menusTableName),
sqlUpdate: sq.Update(menusTableName).Suffix("returning *"),
}
}
type menusQ struct {
db *pgdb.DB
sql sq.SelectBuilder
sqlUpdate sq.UpdateBuilder
}
func (q *menusQ) New() data.MenusQ {
return NewMenusQ(q.db)
}
func (q *menusQ) Get() (*data.Menu, error) {
var result data.Menu
err := q.db.Get(&result, q.sql)
if err == sql.ErrNoRows {
return nil, nil
}
return &result, err
}
func (q *menusQ) Select() ([]data.Menu, error) {
var result []data.Menu
err := q.db.Select(&result, q.sql)
return result, err
}
func (q *menusQ) Update(menu data.Menu) (data.Menu, error) {
var result data.Menu
clauses := structs.Map(menu)
clauses["cafe_id"] = menu.CafeId
err := q.db.Get(&result, q.sqlUpdate.SetMap(clauses))
return result, err
}
func (q *menusQ) Transaction(fn func(q data.MenusQ) error) error {
return q.db.Transaction(func() error {
return fn(q)
})
}
func (q *menusQ) Insert(menu data.Menu) (data.Menu, error) {
clauses := structs.Map(menu)
clauses["cafe_id"] = menu.CafeId
var result data.Menu
stmt := sq.Insert(menusTableName).SetMap(clauses).Suffix("returning *")
err := q.db.Get(&result, stmt)
return result, err
}
func (q *menusQ) Delete(id int64) error {
stmt := sq.Delete(menusTableName).Where(sq.Eq{"id": id})
err := q.db.Exec(stmt)
return err
}
func (q *menusQ) Page(pageParams pgdb.OffsetPageParams) data.MenusQ {
q.sql = pageParams.ApplyTo(q.sql, "id")
return q
}
func (q *menusQ) FilterById(ids ...int64) data.MenusQ {
q.sql = q.sql.Where(sq.Eq{"id": ids})
q.sqlUpdate = q.sqlUpdate.Where(sq.Eq{"id": ids})
return q
}
func (q *menusQ) FilterByCafeId(ids ...int64) data.MenusQ {
q.sql = q.sql.Where(sq.Eq{"cafe_id": ids})
return q
}