fixed relationship issues

This commit is contained in:
2026-02-05 00:10:10 +11:00
parent 20308fe35c
commit 4c31c24069
22 changed files with 236 additions and 254 deletions

View File

@@ -3,6 +3,7 @@ package db
import (
"context"
"database/sql"
"time"
"git.haelnorr.com/h/oslstats/internal/roles"
"github.com/pkg/errors"
@@ -18,10 +19,18 @@ type Role struct {
Description string `bun:"description"`
IsSystem bool `bun:"is_system,default:false"`
CreatedAt int64 `bun:"created_at,notnull"`
UpdatedAt int64 `bun:"updated_at,notnull"`
UpdatedAt *int64 `bun:"updated_at"`
// Relations (loaded on demand)
Permissions []*Permission `bun:"m2m:role_permissions,join:Role=Permission"`
Users []User `bun:"m2m:user_roles,join:Role=User"`
Permissions []Permission `bun:"m2m:role_permissions,join:Role=Permission"`
}
type RolePermission struct {
RoleID int `bun:",pk"`
Role *Role `bun:"rel:belongs-to,join:role_id=id"`
PermissionID int `bun:",pk"`
Permission *Permission `bun:"rel:belongs-to,join:permission_id=id"`
}
// GetRoleByName queries the database for a role matching the given name
@@ -99,6 +108,7 @@ func CreateRole(ctx context.Context, tx bun.Tx, role *Role) error {
if role == nil {
return errors.New("role cannot be nil")
}
role.CreatedAt = time.Now().Unix()
_, err := tx.NewInsert().
Model(role).
@@ -160,23 +170,23 @@ func DeleteRole(ctx context.Context, tx bun.Tx, id int) error {
}
// AddPermissionToRole grants a permission to a role
func AddPermissionToRole(ctx context.Context, tx bun.Tx, roleID, permissionID int, createdAt int64) error {
func AddPermissionToRole(ctx context.Context, tx bun.Tx, roleID, permissionID int) error {
if roleID <= 0 {
return errors.New("roleID must be positive")
}
if permissionID <= 0 {
return errors.New("permissionID must be positive")
}
// TODO: use proper m2m table
// also make createdAt automatic in table so not required as input here
_, err := tx.ExecContext(ctx, `
INSERT INTO role_permissions (role_id, permission_id, created_at)
VALUES ($1, $2, $3)
ON CONFLICT (role_id, permission_id) DO NOTHING
`, roleID, permissionID, createdAt)
rolePerm := &RolePermission{
RoleID: roleID,
PermissionID: permissionID,
}
_, err := tx.NewInsert().
Model(rolePerm).
On("CONFLICT (role_id, permission_id) DO NOTHING").
Exec(ctx)
if err != nil {
return errors.Wrap(err, "tx.ExecContext")
return errors.Wrap(err, "tx.NewInsert")
}
return nil
@@ -191,13 +201,13 @@ func RemovePermissionFromRole(ctx context.Context, tx bun.Tx, roleID, permission
return errors.New("permissionID must be positive")
}
// TODO: use proper m2m table
_, err := tx.ExecContext(ctx, `
DELETE FROM role_permissions
WHERE role_id = $1 AND permission_id = $2
`, roleID, permissionID)
_, err := tx.NewDelete().
Model((*RolePermission)(nil)).
Where("role_id = ?", roleID).
Where("permission_id = ?", permissionID).
Exec(ctx)
if err != nil {
return errors.Wrap(err, "tx.ExecContext")
return errors.Wrap(err, "tx.NewDelete")
}
return nil