-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstore.go
82 lines (68 loc) · 1.78 KB
/
store.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
package postgres
import (
"context"
"database/sql"
pgutil "github.com/code-payments/code-server/pkg/database/postgres"
"github.com/jmoiron/sqlx"
"github.com/code-payments/code-server/pkg/code/data/login"
)
type store struct {
db *sqlx.DB
}
// New returns a new in psotres login.Store
func New(db *sql.DB) login.Store {
return &store{
db: sqlx.NewDb(db, "pgx"),
}
}
// Save implements login.Store.Save
//
// todo: An awkward implementation, but enables a quick migration to multi-device
// logins if that every becomes a thing.
func (s *store) Save(ctx context.Context, record *login.MultiRecord) error {
models, err := toModels(record)
if err != nil {
return err
}
var newRecord *login.MultiRecord
err = pgutil.ExecuteInTx(ctx, s.db, sql.LevelDefault, func(tx *sqlx.Tx) error {
for _, model := range models {
err := model.dbSaveInTx(ctx, tx)
if err != nil {
return err
}
}
if len(models) == 0 {
err = dbDeleteAllByInstallIdInTx(ctx, tx, record.AppInstallId)
if err != nil {
return err
}
}
newRecord, err = fromModels(record.AppInstallId, models)
if err != nil {
return err
}
return nil
})
if err != nil {
return err
}
newRecord.CopyTo(record)
return nil
}
// GetAllByInstallId implements login.Store.GetAllByInstallId
func (s *store) GetAllByInstallId(ctx context.Context, appInstallId string) (*login.MultiRecord, error) {
models, err := dbGetAllByInstallId(ctx, s.db, appInstallId)
if err != nil {
return nil, err
}
return fromModels(appInstallId, models)
}
// GetLatestByOwner implements login.Store.GetLatestByOwner
func (s *store) GetLatestByOwner(ctx context.Context, owner string) (*login.Record, error) {
model, err := dbGetLatestByOwner(ctx, s.db, owner)
if err != nil {
return nil, err
}
return fromModel(model), nil
}