-
Notifications
You must be signed in to change notification settings - Fork 43
/
db.go
101 lines (91 loc) · 2.39 KB
/
db.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
package pki
import (
"time"
"github.com/baetyl/baetyl-go/v2/pki"
"github.com/baetyl/baetyl-go/v2/pki/models"
"github.com/jmoiron/sqlx"
)
type dbStorage struct {
db *sqlx.DB
}
func NewStorageDatabase(cfg Persistent) (pki.Storage, error) {
db, err := sqlx.Open(cfg.Database.Type, cfg.Database.URL)
if err != nil {
return nil, err
}
db.SetMaxIdleConns(cfg.Database.MaxIdleConns)
db.SetMaxOpenConns(cfg.Database.MaxConns)
db.SetConnMaxLifetime(time.Duration(cfg.Database.ConnMaxLifetime) * time.Second)
err = db.Ping()
if err != nil {
return nil, err
}
return &dbStorage{
db: db,
}, nil
}
func (d dbStorage) CreateCert(cert models.Cert) error {
insertSQL := `
INSERT INTO baetyl_certificate (
cert_id, parent_id, type, common_name,
description, csr, content, private_key, not_before, not_after)
VALUES (?,?,?,?,?,?,?,?,?,?)
`
_, err := d.db.Exec(insertSQL,
cert.CertId, cert.ParentId, cert.Type,
cert.CommonName, cert.Description, cert.Csr,
cert.Content, cert.PrivateKey, cert.NotBefore, cert.NotAfter)
return err
}
func (d dbStorage) DeleteCert(certId string) error {
deleteSQL := `
DELETE FROM baetyl_certificate where cert_id=?
`
_, err := d.db.Exec(deleteSQL, certId)
return err
}
func (d dbStorage) UpdateCert(cert models.Cert) error {
updateSQL := `
UPDATE baetyl_certificate SET parent_id=?,type=?,
common_name=?,description=?,csr=?,content=?,private_key=?,
not_before=?, not_after=?
WHERE cert_id=?
`
_, err := d.db.Exec(updateSQL,
cert.ParentId, cert.Type, cert.CommonName, cert.Description, cert.Csr,
cert.Content, cert.PrivateKey, cert.NotBefore, cert.NotAfter, cert.CertId)
return err
}
func (d dbStorage) GetCert(certId string) (*models.Cert, error) {
selectSQL := `
SELECT cert_id, parent_id, type, common_name,
description, csr, content, private_key, not_before, not_after
FROM baetyl_certificate
WHERE cert_id=? LIMIT 0,1
`
var cert []models.Cert
if err := d.db.Select(&cert, selectSQL, certId); err != nil {
return nil, err
}
if len(cert) > 0 {
return &cert[0], nil
}
return nil, nil
}
func (d dbStorage) CountCertByParentId(parentId string) (int, error) {
selectSQL := `
SELECT count(cert_id) AS count
FROM baetyl_certificate
WHERE parent_id=?
`
var res []struct {
Count int `db:"count"`
}
if err := d.db.Select(&res, selectSQL, parentId); err != nil {
return 0, err
}
return res[0].Count, nil
}
func (d dbStorage) Close() error {
return d.db.Close()
}