github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/service/application_metadata.go (about) 1 package service 2 3 import ( 4 "context" 5 "errors" 6 7 "github.com/pyroscope-io/pyroscope/pkg/model" 8 "github.com/pyroscope-io/pyroscope/pkg/model/appmetadata" 9 "gorm.io/gorm" 10 ) 11 12 type ApplicationMetadataService struct { 13 db *gorm.DB 14 } 15 16 func NewApplicationMetadataService(db *gorm.DB) ApplicationMetadataService { 17 return ApplicationMetadataService{db: db} 18 } 19 20 func (svc ApplicationMetadataService) List(ctx context.Context) (apps []appmetadata.ApplicationMetadata, err error) { 21 tx := svc.db.WithContext(ctx) 22 result := tx.Find(&apps) 23 return apps, result.Error 24 } 25 26 func (svc ApplicationMetadataService) Get(ctx context.Context, name string) (appmetadata.ApplicationMetadata, error) { 27 app := appmetadata.ApplicationMetadata{} 28 if err := model.ValidateAppName(name); err != nil { 29 return app, err 30 } 31 32 tx := svc.db.WithContext(ctx) 33 res := tx.Where("fq_name = ?", name).First(&app) 34 35 switch { 36 case errors.Is(res.Error, gorm.ErrRecordNotFound): 37 return app, model.ErrApplicationNotFound 38 default: 39 return app, res.Error 40 } 41 } 42 43 func (svc ApplicationMetadataService) CreateOrUpdate(ctx context.Context, application appmetadata.ApplicationMetadata) error { 44 if err := model.ValidateAppName(application.FQName); err != nil { 45 return err 46 } 47 48 tx := svc.db.WithContext(ctx) 49 50 // Only update the field if it's populated 51 return tx.Where(appmetadata.ApplicationMetadata{ 52 FQName: application.FQName, 53 }).Assign(application).FirstOrCreate(&appmetadata.ApplicationMetadata{}).Error 54 } 55 56 func (svc ApplicationMetadataService) Delete(ctx context.Context, name string) error { 57 if err := model.ValidateAppName(name); err != nil { 58 return err 59 } 60 61 tx := svc.db.WithContext(ctx) 62 return tx.Where("fq_name = ?", name).Delete(appmetadata.ApplicationMetadata{}).Error 63 }