-
Notifications
You must be signed in to change notification settings - Fork 1
/
secretmeta_repository.go
90 lines (77 loc) · 2.28 KB
/
secretmeta_repository.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
package postgres
import (
"database/sql"
"github.com/riser-platform/riser-server/pkg/core"
)
type secretMetaRepository struct {
db *sql.DB
}
func NewSecretMetaRepository(db *sql.DB) core.SecretMetaRepository {
return &secretMetaRepository{db}
}
func (r *secretMetaRepository) Save(secretMeta *core.SecretMeta) (int64, error) {
row := r.db.QueryRow(`
INSERT INTO secret_meta (app_id, environment_name, name, revision)
SELECT app.id, $3, $4, 0
FROM app
WHERE
app.name = $1
AND app.namespace = $2
ON CONFLICT(app_id, environment_name, name) DO
UPDATE SET
revision=secret_meta.revision + 1
RETURNING secret_meta.revision
`, secretMeta.App.Name, secretMeta.App.Namespace, secretMeta.EnvironmentName, secretMeta.Name)
var revision int64
err := row.Scan(&revision)
return revision, err
}
func (r *secretMetaRepository) Commit(secretMeta *core.SecretMeta) error {
result, err := r.db.Exec(`
UPDATE secret_meta
SET committed_revision = revision
FROM app
WHERE
secret_meta.app_id = app.id
AND app.name = $1
AND app.namespace = $2
AND secret_meta.environment_name = $3
AND secret_meta.name = $4
AND secret_meta.revision = $5
`, secretMeta.App.Name, secretMeta.App.Namespace, secretMeta.EnvironmentName, secretMeta.Name, secretMeta.Revision)
if err != nil && !resultHasRows(result) {
return core.ErrConflictNewerVersion
}
return err
}
func (r *secretMetaRepository) ListByAppInEnvironment(appName *core.NamespacedName, envName string) ([]core.SecretMeta, error) {
secretMetas := []core.SecretMeta{}
rows, err := r.db.Query(`
SELECT
app.name,
app.namespace,
secret_meta.environment_name,
secret_meta.name,
secret_meta.committed_revision
FROM secret_meta
INNER JOIN app ON app.id = secret_meta.app_id
WHERE
app.name = $1
AND app.namespace = $2
AND secret_meta.environment_name = $3
ORDER BY secret_meta.name
`, appName.Name, appName.Namespace, envName)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
secretMeta := core.SecretMeta{App: &core.NamespacedName{}}
err := rows.Scan(&secretMeta.App.Name, &secretMeta.App.Namespace, &secretMeta.EnvironmentName, &secretMeta.Name, &secretMeta.Revision)
if err != nil {
return nil, err
}
secretMetas = append(secretMetas, secretMeta)
}
return secretMetas, nil
}