-
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathrole.go
More file actions
117 lines (88 loc) · 2.38 KB
/
Copy pathrole.go
File metadata and controls
117 lines (88 loc) · 2.38 KB
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
package postgresql
import (
"context"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/MarioCarrion/videos/2023/transaction-in-context/internal"
)
type Role struct {
conn *pgx.Conn
}
func NewRole(conn *pgx.Conn) *Role {
return &Role{
conn: conn,
}
}
func (r *Role) Insert(ctx context.Context, name string, permissions []internal.Permission) (internal.Role, error) {
var (
role internal.Role
err error
)
err = transaction(ctx, r.conn, func(tx pgx.Tx) error {
rq := roleQueries{conn: tx}
role, err := rq.Insert(ctx, name)
if err != nil {
return fmt.Errorf("Insert %w", err)
}
for i, p := range permissions {
permission, err := rq.InsertPermission(ctx, role.ID, p.Type)
if err != nil {
return fmt.Errorf("insertPermissionTx %w", err)
}
permissions[i] = permission
}
role.Permissions = permissions
return nil
})
if err != nil {
return internal.Role{}, fmt.Errorf("transaction %w", err)
}
return role, nil
}
func (r *Role) InsertPermission(ctx context.Context, roleID uuid.UUID, ptype internal.PermissionType) (internal.Permission, error) {
var (
permission internal.Permission
err error
)
err = transaction(ctx, r.conn, func(tx pgx.Tx) error {
rq := roleQueries{conn: tx}
permission, err = rq.InsertPermission(ctx, roleID, ptype)
if err != nil {
return fmt.Errorf("insertPermission %w", err)
}
return nil
})
if err != nil {
return internal.Permission{}, fmt.Errorf("transaction %w", err)
}
return permission, nil
}
type roleQueries struct {
conn DBTX
}
func (r *roleQueries) Insert(ctx context.Context, name string) (internal.Role, error) {
const sql = `INSERT INTO roles(name) VALUES ($1) RETURNING id`
row := r.conn.QueryRow(ctx, sql, &name)
var id uuid.UUID
if err := row.Scan(&id); err != nil {
return internal.Role{}, fmt.Errorf("Scan %w", err)
}
return internal.Role{
ID: id,
Name: name,
}, nil
}
func (r *roleQueries) InsertPermission(ctx context.Context, roleID uuid.UUID, ptype internal.PermissionType) (internal.Permission, error) {
const sql = `INSERT INTO permissions(role_id, type) VALUES ($1, $2) RETURNING id`
row := r.conn.QueryRow(ctx, sql, roleID, &ptype)
var id uuid.UUID
if err := row.Scan(&id); err != nil {
return internal.Permission{}, fmt.Errorf("Insert %w", err)
}
return internal.Permission{
ID: id,
RoleID: roleID,
Type: ptype,
}, nil
}