-
-
Notifications
You must be signed in to change notification settings - Fork 190
/
campaign.go
63 lines (51 loc) · 1.47 KB
/
campaign.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
// Copyright © Martin Tournoij – This file is part of GoatCounter and published
// under the terms of a slightly modified EUPL v1.2 license, which can be found
// in the LICENSE file or at https://license.goatcounter.com
package goatcounter
import (
"context"
"zgo.at/errors"
"zgo.at/zdb"
"zgo.at/zvalidate"
)
type Campaign struct {
ID int64 `db:"campaign_id" json:"campaign_id"`
SiteID int64 `db:"site_id" json:"site_id"`
Name string `db:"name" json:"name"`
}
func (c *Campaign) Defaults(ctx context.Context) {}
func (c *Campaign) Validate() error {
v := zvalidate.New()
v.Required("name", c.Name)
return v.ErrorOrNil()
}
func (c *Campaign) Insert(ctx context.Context) error {
if c.ID > 0 {
return errors.Errorf("Campaign.Insert: c.ID>0: %d", c.ID)
}
c.Defaults(ctx)
err := c.Validate()
if err != nil {
return errors.Wrap(err, "Campaign.Insert")
}
c.ID, err = zdb.InsertID(ctx, "campaign_id",
`insert into campaigns (site_id, name) values (?, ?)`, MustGetSite(ctx).ID, c.Name)
if err != nil {
return errors.Wrap(err, "Campaign.Insert")
}
return nil
}
func (c *Campaign) ByName(ctx context.Context, name string) error {
k := c.Name
if cc, ok := cacheCampaigns(ctx).Get(k); ok {
*c = *cc.(*Campaign)
return nil
}
err := zdb.Get(ctx, c, `select * from campaigns where site_id=? and lower(name)=lower(?)`,
MustGetSite(ctx).ID, name)
if err != nil {
return errors.Wrap(err, "Campaign.ByName")
}
cacheCampaigns(ctx).SetDefault(k, c)
return nil
}