cpularp-manager-api/src/lib/database/functionset/functionset.go

88 lines
2.1 KiB
Go
Raw Normal View History

package functionset
import (
"log"
function "example.com/database/function"
"gorm.io/gorm"
)
type FunctionSet struct {
gorm.Model
Functions []function.Function `gorm:"many2many:functionset_function_associations" json:"functions"`
}
2025-04-29 00:42:57 -05:00
func (functionSet FunctionSet) Create(db *gorm.DB) error {
result := db.Create(&functionSet)
if result.Error != nil {
return result.Error
}
return nil
}
2025-04-29 00:42:57 -05:00
func (functionSet *FunctionSet) getAssociations(db *gorm.DB) {
db.Model(&functionSet).Association("Functions").Find(&functionSet.Functions)
}
func (functionSet *FunctionSet) Get(db *gorm.DB, inputFunctionSet uint) {
2025-04-29 00:42:57 -05:00
db.Where("id = ?", inputFunctionSet).Take(&functionSet)
functionSet.getAssociations(db)
}
func (functionSet FunctionSet) Update(db *gorm.DB) error {
result := db.Save(&functionSet)
if result.Error != nil {
2025-04-29 00:42:57 -05:00
return result.Error
}
2025-04-29 00:42:57 -05:00
return nil
}
func (functionSet FunctionSet) Delete(db *gorm.DB) error {
result := db.Delete(&functionSet)
if result.Error != nil {
return result.Error
}
return nil
}
func Create(db *gorm.DB, functions []uint) error {
2025-04-29 00:42:57 -05:00
return FunctionSet{
Functions: *function.Get(db, functions),
}.Create(db)
}
func Get(db *gorm.DB, inputFunctionSets []uint) *[]FunctionSet {
var outputFunctionSets []FunctionSet
for _, inputFunctionSet := range inputFunctionSets {
2025-04-29 00:42:57 -05:00
var outputFunctionSet FunctionSet
outputFunctionSet.Get(db, inputFunctionSet)
outputFunctionSets = append(outputFunctionSets, outputFunctionSet)
}
2025-04-29 00:42:57 -05:00
return &outputFunctionSets
}
2025-04-29 00:42:57 -05:00
func GetAll(db *gorm.DB) *[]FunctionSet {
var outputFunctionSetIDs []uint
2025-04-29 00:42:57 -05:00
result := db.Model(&FunctionSet{}).Select("id").Find(&outputFunctionSetIDs)
if result.Error != nil {
log.Println(result.Error)
}
2025-04-29 00:42:57 -05:00
return Get(db, outputFunctionSetIDs)
}
func Update(db *gorm.DB, id int, functions []uint) error {
2025-04-29 00:42:57 -05:00
outputFunctionSet := FunctionSet{
Functions: *function.Get(db, functions),
}
2025-04-29 00:42:57 -05:00
outputFunctionSet.ID = uint(id)
return outputFunctionSet.Update(db)
}
func Delete(db *gorm.DB, inputFunctionSets []uint) {
functionSets := Get(db, inputFunctionSets)
for _, functionSet := range *functionSets {
functionSet.Delete(db)
}
}