/
definition-type.go
124 lines (109 loc) · 2.5 KB
/
definition-type.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
package data
import (
"context"
"database/sql"
"github.com/unanet/go/pkg/errors"
"time"
)
type DefinitionType struct {
ID int `db:"id"`
Name string `db:"name"`
Description string `db:"description"`
CreatedAt sql.NullTime `db:"created_at"`
UpdatedAt sql.NullTime `db:"updated_at"`
Class string `db:"class"`
Version string `db:"version"`
Kind string `db:"kind"`
DefinitionOrder string `db:"definition_order"`
}
func (r *Repo) DefinitionTypes(ctx context.Context) ([]DefinitionType, error) {
rows, err := r.db.QueryxContext(ctx, `
select
id,
name,
description,
created_at,
updated_at,
class,
version,
kind,
definition_order
from definition_type`)
if err != nil {
return nil, errors.Wrap(err)
}
defer rows.Close()
var ss []DefinitionType
for rows.Next() {
if rows.Err() != nil {
return nil, errors.Wrap(err)
}
var s DefinitionType
err = rows.StructScan(&s)
if err != nil {
return nil, errors.Wrap(err)
}
ss = append(ss, s)
}
return ss, nil
}
func (r *Repo) CreateDefinitionType(ctx context.Context, model *DefinitionType) error {
model.CreatedAt.Time = time.Now().UTC()
model.CreatedAt.Valid = true
err := r.db.QueryRowxContext(ctx, `
INSERT INTO definition_type(name, description, class, version, kind, definition_order, created_at)
VALUES ($1, $2, $3, $4, $5, $6, $7)
RETURNING id
`,
model.Name,
model.Description,
model.Class,
model.Version,
model.Kind,
model.DefinitionOrder,
model.CreatedAt).
StructScan(model)
if err != nil {
return errors.Wrap(err)
}
return nil
}
func (r *Repo) UpdateDefinitionType(ctx context.Context, m *DefinitionType) error {
m.UpdatedAt.Time = time.Now().UTC()
m.UpdatedAt.Valid = true
result, err := r.db.ExecContext(ctx, `
update definition_type set
name = $2,
description = $3,
class = $4,
version = $5,
kind = $6,
definition_order = $7,
updated_at = $8
where id = $1
RETURNING created_at
`,
m.ID,
m.Name,
m.Description,
m.Class,
m.Version,
m.Kind,
m.DefinitionOrder,
m.UpdatedAt,
)
if err != nil {
return errors.Wrap(err)
}
affected, err := result.RowsAffected()
if err != nil {
return errors.Wrap(err)
}
if affected == 0 {
return errors.NotFoundf("definition type by id: %d not found", m.ID)
}
return nil
}
func (r *Repo) DeleteDefinitionType(ctx context.Context, id int) error {
return r.deleteByID(ctx, "definition_type", id)
}