-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathroles.go
114 lines (100 loc) · 2.3 KB
/
roles.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
package backup
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/GrantStreetGroup/go-exasol-client"
)
type role struct {
name string
consumerGroup string
comment string
}
func BackupRoles(src *exasol.Conn, dst string, dropExtras bool) error {
log.Info("Backing up roles")
roles, err := getRolesToBackup(src)
if err != nil {
return err
}
if len(roles) == 0 {
log.Warning("No roles found")
return nil
}
dir := filepath.Join(dst, "roles")
if dropExtras {
log.Infof("Remove extraneous backedup roles")
os.RemoveAll(dir)
}
os.MkdirAll(dir, os.ModePerm)
roleNames := []string{}
for _, role := range roles {
err = createRole(dir, role)
if err != nil {
return err
}
if role.name != "DBA" {
roleNames = append(roleNames, role.name)
}
}
err = BackupPrivileges(src, dir, roleNames)
if err != nil {
return err
}
log.Info("Done backing up roles")
return nil
}
func getRolesToBackup(conn *exasol.Conn) ([]*role, error) {
groupType := "role_priority"
if capability.consumerGroups {
groupType = "role_consumer_group"
}
sql := fmt.Sprintf(`
SELECT role_name AS s,
role_name AS o,
%s,
role_comment
FROM exa_all_roles
ORDER BY local.s`,
groupType,
)
res, err := conn.FetchSlice(sql)
if err != nil {
return nil, fmt.Errorf("Unable to get roles: %s", err)
}
roles := []*role{}
for _, row := range res {
r := &role{name: row[0].(string)}
if row[2] != nil {
r.consumerGroup = row[2].(string)
}
if row[3] != nil {
r.comment = row[3].(string)
}
roles = append(roles, r)
}
return roles, nil
}
func createRole(dst string, r *role) error {
log.Infof("Backing up role %s", r.name)
var sql string
if r.name != "DBA" && r.name != "PUBLIC" {
sql = "CREATE ROLE [" + r.name + "];\n"
}
if r.consumerGroup != "" {
if capability.consumerGroups {
sql += fmt.Sprintf("ALTER ROLE [%s] SET CONSUMER_GROUP = [%s];\n", r.name, r.consumerGroup)
} else {
sql += fmt.Sprintf("GRANT PRIORITY GROUP [%s] TO %s;\n", r.consumerGroup, r.name)
}
}
if r.comment != "" {
sql += fmt.Sprintf("COMMENT ON ROLE [%s] IS '%s';\n", r.name, qStr(r.comment))
}
file := filepath.Join(dst, r.name+".sql")
err := ioutil.WriteFile(file, []byte(sql), 0644)
if err != nil {
return fmt.Errorf("Unable to backup role: %s", err)
}
return nil
}