Move the name check before tx

No point in making a DB query if we know we don't want to be able to
delete/update the default endpoint.

Signed-off-by: Gabriel Adrian Samfira <gsamfira@cloudbasesolutions.com>
This commit is contained in:
Gabriel Adrian Samfira 2024-05-07 10:07:47 +00:00
parent 2a3d524a71
commit 8726cb994e
3 changed files with 34 additions and 11 deletions

View file

@ -27,6 +27,10 @@ import (
"github.com/cloudbase/garm/params"
)
const (
defaultGithubEndpoint string = "github.com"
)
func (s *sqlDatabase) sqlToCommonGithubCredentials(creds GithubCredentials) (params.GithubCredentials, error) {
if len(creds.Payload) == 0 {
return params.GithubCredentials{}, errors.New("empty credentials payload")
@ -150,6 +154,9 @@ func (s *sqlDatabase) ListGithubEndpoints(_ context.Context) ([]params.GithubEnd
}
func (s *sqlDatabase) UpdateGithubEndpoint(_ context.Context, name string, param params.UpdateGithubEndpointParams) (params.GithubEndpoint, error) {
if name == defaultGithubEndpoint {
return params.GithubEndpoint{}, errors.Wrap(runnerErrors.ErrBadRequest, "cannot update default github endpoint")
}
var endpoint GithubEndpoint
err := s.conn.Transaction(func(tx *gorm.DB) error {
if err := tx.Where("name = ?", name).First(&endpoint).Error; err != nil {
@ -205,6 +212,9 @@ func (s *sqlDatabase) GetGithubEndpoint(_ context.Context, name string) (params.
}
func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) error {
if name == defaultGithubEndpoint {
return errors.Wrap(runnerErrors.ErrBadRequest, "cannot delete default github endpoint")
}
err := s.conn.Transaction(func(tx *gorm.DB) error {
var endpoint GithubEndpoint
if err := tx.Where("name = ?", name).First(&endpoint).Error; err != nil {
@ -214,10 +224,6 @@ func (s *sqlDatabase) DeleteGithubEndpoint(_ context.Context, name string) error
return errors.Wrap(err, "fetching github endpoint")
}
if endpoint.Name == "github.com" {
return errors.Wrap(runnerErrors.ErrBadRequest, "cannot delete default github endpoint")
}
var credsCount int64
if err := tx.Model(&GithubCredentials{}).Where("endpoint_name = ?", endpoint.Name).Count(&credsCount).Error; err != nil {
if !errors.Is(err, gorm.ErrRecordNotFound) {