This repository has been archived by the owner on Nov 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cycle.go
91 lines (73 loc) · 1.94 KB
/
cycle.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
package data
import (
"fmt"
"time"
"upper.io/db.v2"
"upper.io/db.v2/lib/sqlbuilder"
)
type Cycle struct {
ID int64 `db:"id,omitempty,pk" json:"id"`
AppID int64 `db:"app_id" json:"-"`
Name string `db:"name,omitempty" json:"name"`
PublicKey string `db:"public_key,omitempty" json:"public_key"`
PrivateKey string `db:"private_key,omitempty" json:"-"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
}
func (c Cycle) CollectionName() string {
return "cycles"
}
func (c Cycle) Query(session db.Database, query db.Cond) db.Result {
return session.Collection(c.CollectionName()).Find(query)
}
func (c *Cycle) Find(session db.Database, query db.Cond) error {
return c.Query(session, query).One(c)
}
func (c *Cycle) Load(session db.Database) error {
if session == nil {
session = dbSession
}
return c.Query(session, db.Cond{"id": c.ID}).One(c)
}
func (c *Cycle) Save(session db.Database) error {
if session == nil {
session = dbSession
}
collection := session.Collection(c.CollectionName())
var err error
if c.ID == 0 {
var id interface{}
c.UpdatedAt = time.Now().UTC().Truncate(time.Second)
c.CreatedAt = c.UpdatedAt
id, err = collection.Insert(c)
if err == nil {
c.ID = id.(int64)
}
} else {
c.UpdatedAt = time.Now().UTC().Truncate(time.Second)
err = collection.
Find(db.Cond{"id": c.ID}).
Update(c)
}
return err
}
func (c *Cycle) Remove(session db.Database) error {
return c.Query(session, db.Cond{"id": c.ID}).Delete()
}
func FindCyclesApp(appID int64, name string) ([]*Cycle, error) {
sql := fmt.Sprintf(`
SELECT *
FROM cycles
WHERE cycles.app_id=%d AND name LIKE '%%%s%%'`, appID, name)
rows, err := dbSession.Query(sql)
if err != nil {
return nil, err
}
var cycles []*Cycle
iter := sqlbuilder.NewIterator(rows)
err = iter.All(&cycles)
if err != nil {
return nil, err
}
return cycles, nil
}