-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathproduct_test.go
143 lines (121 loc) · 2.47 KB
/
product_test.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
package goerd_test
import (
"context"
"database/sql"
"fmt"
"time"
"github.com/covrom/goerd"
"github.com/covrom/goerd/schema"
"github.com/google/uuid"
)
type Product struct {
ID uuid.UUID
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt sql.NullTime
CategoryID uuid.UUID
Category Category
Name string
Code string
Unit string
}
type Products struct {
sc *schema.Schema
t *schema.Table
cols []string
fields func(Product) []interface{}
pfields func(*Product) []interface{}
}
func NewProducts(sc *schema.Schema) (*Products, error) {
tname := "products"
t, err := sc.FindTableByName(tname)
if err != nil {
return nil, err
}
p := &Products{
sc: sc,
t: t,
cols: []string{
"id",
"created_at",
"updated_at",
"deleted_at",
"name",
"category_id",
"code",
"unit",
},
fields: func(p Product) []interface{} {
return []interface{}{
p.ID,
p.CreatedAt,
p.UpdatedAt,
p.DeletedAt,
p.Name,
p.CategoryID,
p.Code,
p.Unit,
}
},
pfields: func(p *Product) []interface{} {
return []interface{}{
&p.ID,
&p.CreatedAt,
&p.UpdatedAt,
&p.DeletedAt,
&p.Name,
&p.CategoryID,
&p.Code,
&p.Unit,
}
},
}
for _, c := range p.cols {
if _, err := t.FindColumnByName(c); err != nil {
return nil, err
}
}
return p, nil
}
func (d *Products) Table() string {
return d.t.Name
}
func (d *Products) Columns() []string {
return d.cols
}
// nolint hugeParam
func (d *Products) Fields(p Product) []interface{} {
return d.fields(p)
}
func (d *Products) PFields(p *Product) []interface{} {
return d.pfields(p)
}
// nolint hugeParam
func (d *Products) ProductToStore(ctx context.Context, p Product) error {
return goerd.WithTx(ctx, func(ctxTx context.Context) error {
q := goerd.ReplaceQuery(d, "id")
p.CreatedAt = time.Now()
p.UpdatedAt = time.Now()
_, err := goerd.SqlxTxFromContext(ctxTx).
ExecContext(ctxTx, q, d.Fields(p)...)
return err
})
}
type Identity struct {
ID uuid.UUID `db:"id"`
UpdatedAt time.Time `db:"updated_at"`
DeletedAt sql.NullTime `db:"deleted_at"`
}
func (d *Products) AllProductIDs(ctx context.Context) ([]Identity, error) {
var dbidts []Identity
err := goerd.WithTx(ctx, func(ctxTx context.Context) error {
return goerd.SqlxTxFromContext(ctxTx).
SelectContext(ctx, &dbidts,
fmt.Sprintf(`select id, updated_at, deleted_at from %s`,
d.Table()))
})
if err != nil {
return nil, err
}
return dbidts, nil
}