-
Notifications
You must be signed in to change notification settings - Fork 244
/
database.go
122 lines (109 loc) · 2.26 KB
/
database.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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package permissions
import (
"database/sql"
)
// Database sql wrapper for operations with browser objects.
type Database struct {
db *sql.DB
}
// Close closes database.
func (db Database) Close() error {
return db.db.Close()
}
func NewDB(db *sql.DB) *Database {
return &Database{db: db}
}
type DappPermissions struct {
Name string `json:"dapp"`
Permissions []string `json:"permissions,omitempty"`
}
func (db *Database) AddPermissions(perms DappPermissions) (err error) {
tx, err := db.db.Begin()
if err != nil {
return
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
_ = tx.Rollback()
}()
dInsert, err := tx.Prepare("INSERT OR REPLACE INTO dapps(name) VALUES(?)")
if err != nil {
return
}
_, err = dInsert.Exec(perms.Name)
dInsert.Close()
if err != nil {
return
}
if len(perms.Permissions) == 0 {
return
}
pInsert, err := tx.Prepare("INSERT INTO permissions(dapp_name, permission) VALUES(?, ?)")
if err != nil {
return
}
defer pInsert.Close()
for _, perm := range perms.Permissions {
_, err = pInsert.Exec(perms.Name, perm)
if err != nil {
return
}
}
return
}
func (db *Database) GetPermissions() (rst []DappPermissions, err error) {
tx, err := db.db.Begin()
if err != nil {
return
}
defer func() {
if err == nil {
err = tx.Commit()
return
}
_ = tx.Rollback()
}()
// FULL and RIGHT joins are not supported
dRows, err := tx.Query("SELECT name FROM dapps")
if err != nil {
return
}
defer dRows.Close()
dapps := map[string]*DappPermissions{}
for dRows.Next() {
perms := DappPermissions{}
err = dRows.Scan(&perms.Name)
if err != nil {
return nil, err
}
dapps[perms.Name] = &perms
}
pRows, err := tx.Query("SELECT dapp_name, permission from permissions")
if err != nil {
return
}
defer pRows.Close()
var (
name string
permission string
)
for pRows.Next() {
err = pRows.Scan(&name, &permission)
if err != nil {
return
}
dapps[name].Permissions = append(dapps[name].Permissions, permission)
}
rst = make([]DappPermissions, 0, len(dapps))
for key := range dapps {
rst = append(rst, *dapps[key])
}
return rst, nil
}
func (db *Database) DeletePermission(name string) error {
_, err := db.db.Exec("DELETE FROM dapps WHERE name = ?", name)
return err
}