refactored db code

This commit is contained in:
2026-02-09 22:14:38 +11:00
parent b89ee75ca7
commit a4b4f4f4af
7 changed files with 24 additions and 100 deletions

View File

@@ -34,20 +34,7 @@ func GetPermissionByName(ctx context.Context, tx bun.Tx, name permissions.Permis
if name == "" {
return nil, errors.New("name cannot be empty")
}
perm := new(Permission)
err := tx.NewSelect().
Model(perm).
Where("name = ?", name).
Limit(1).
Scan(ctx)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, errors.Wrap(err, "tx.NewSelect")
}
return perm, nil
return GetByField[Permission](tx, "name", name).GetFirst(ctx)
}
// GetPermissionByID queries the database for a permission matching the given ID
@@ -56,20 +43,7 @@ func GetPermissionByID(ctx context.Context, tx bun.Tx, id int) (*Permission, err
if id <= 0 {
return nil, errors.New("id must be positive")
}
perm := new(Permission)
err := tx.NewSelect().
Model(perm).
Where("id = ?", id).
Limit(1).
Scan(ctx)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, nil
}
return nil, errors.Wrap(err, "tx.NewSelect")
}
return perm, nil
return GetByID[Permission](tx, id).GetFirst(ctx)
}
// GetPermissionsByResource queries for all permissions for a given resource
@@ -77,34 +51,8 @@ func GetPermissionsByResource(ctx context.Context, tx bun.Tx, resource string) (
if resource == "" {
return nil, errors.New("resource cannot be empty")
}
perms := []*Permission{}
err := tx.NewSelect().
Model(&perms).
Where("resource = ?", resource).
Order("action ASC").
Scan(ctx)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, errors.Wrap(err, "tx.NewSelect")
}
return perms, nil
}
// GetPermissionsByIDs queries for permissions matching the given IDs
func GetPermissionsByIDs(ctx context.Context, tx bun.Tx, ids []int) ([]*Permission, error) {
if len(ids) == 0 {
return []*Permission{}, nil
}
var perms []*Permission
err := tx.NewSelect().
Model(&perms).
Where("id IN (?)", bun.In(ids)).
Scan(ctx)
if err != nil && errors.Is(err, sql.ErrNoRows) {
return nil, errors.Wrap(err, "tx.NewSelect")
}
return perms, nil
perms, err := GetByField[[]*Permission](tx, "resource", resource).GetAll(ctx)
return *perms, err
}
// ListAllPermissions returns all permissions
@@ -138,12 +86,11 @@ func CreatePermission(ctx context.Context, tx bun.Tx, perm *Permission) error {
return errors.New("action cannot be empty")
}
_, err := tx.NewInsert().
Model(perm).
err := Insert(tx, perm).
Returning("id").
Exec(ctx)
if err != nil {
return errors.Wrap(err, "tx.NewInsert")
return errors.Wrap(err, "db.Insert")
}
return nil