-
-
Notifications
You must be signed in to change notification settings - Fork 54
Expand file tree
/
Copy pathrole.go
More file actions
103 lines (77 loc) · 2.21 KB
/
Copy pathrole.go
File metadata and controls
103 lines (77 loc) · 2.21 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
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) {
tx, err := r.conn.Begin(ctx)
if err != nil {
return internal.Role{}, fmt.Errorf("Begin %w", err)
}
const sql = `INSERT INTO roles(name) VALUES ($1) RETURNING id`
var role internal.Role
err = transaction(ctx, tx, func() error {
row := tx.QueryRow(ctx, sql, &name)
var id uuid.UUID
if err = row.Scan(&id); err != nil {
return fmt.Errorf("Insert %w", err)
}
for i, p := range permissions {
permission, err := r.insertPermissionTx(ctx, tx, id, p.Type)
if err != nil {
return fmt.Errorf("insertPermissionTx %w", err)
}
permissions[i] = permission
}
role.ID = id
role.Name = name
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) {
tx, err := r.conn.Begin(ctx)
if err != nil {
return internal.Permission{}, fmt.Errorf("Begin %w", err)
}
var permission internal.Permission
err = transaction(ctx, tx, func() error {
permission, err = r.insertPermissionTx(ctx, tx, 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
}
func (r *Role) insertPermissionTx(ctx context.Context, tx pgx.Tx, roleID uuid.UUID, ptype internal.PermissionType) (internal.Permission, error) {
const sql = `INSERT INTO permissions(role_id, type) VALUES ($1, $2) RETURNING id`
row := tx.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
}