package function import ( "log" functiontag "example.com/database/functiontag" "gorm.io/gorm" ) type Function struct { gorm.Model Name string `gorm:"primaryKey uniqueIndex index" json:"name"` Tags []functiontag.FunctionTag `gorm:"many2many:function_tag_associations" json:"tags"` Requirements []Function `gorm:"many2many:function_requirement_associations" json:"requirements"` } func (function Function) Create(db *gorm.DB) error { result := db.Create(&function) if result.Error != nil { return result.Error } return nil } func (function *Function) getAssociations(db *gorm.DB) { db.Model(&function).Association("Tags").Find(&function.Tags) db.Model(&function).Association("Requirements").Find(&function.Requirements) } func (function *Function) Get(db *gorm.DB, inputFunction string) { db.Where("name = ?", inputFunction).Take(&function) function.getAssociations(db) } func (function Function) Update(db *gorm.DB) error { var originalFunction Function originalFunction.Get(db, function.Name) tagsError := db.Model(&originalFunction).Association("Tags").Replace(&function.Tags) if tagsError != nil { return tagsError } requirementsError := db.Model(&originalFunction).Association("Requirements").Replace(&function.Requirements) if requirementsError != nil { return requirementsError } return nil } func (function Function) Delete(db *gorm.DB) error { result := db.Delete(&function) if result.Error != nil { return result.Error } return nil } func Create(db *gorm.DB, name string, tags []string, requirements []string) error { return Function{ Name: name, Tags: *functiontag.Get(db, tags), Requirements: *Get(db, requirements), }.Create(db) } func Get(db *gorm.DB, inputFunctions []string) *[]Function { var outputFunctions []Function for _, inputFunction := range inputFunctions { var outputFunction Function outputFunction.Get(db, inputFunction) outputFunctions = append(outputFunctions, outputFunction) } return &outputFunctions } func GetAll(db *gorm.DB) *[]Function { var outputFunctionNames []string result := db.Model(&Function{}).Select("name").Find(&outputFunctionNames) if result.Error != nil { log.Println(result.Error) } return Get(db, outputFunctionNames) } func Update(db *gorm.DB, name string, tags []string, requirements []string) error { log.Println(*functiontag.Get(db, tags)) log.Println(*Get(db, requirements)) return Function{ Name: name, Tags: *functiontag.Get(db, tags), Requirements: *Get(db, requirements), }.Update(db) } func Delete(db *gorm.DB, inputFunctions []string) { functions := Get(db, inputFunctions) for _, function := range *functions { function.Delete(db) } }