NAM-APJATEL-BACKEND/repository/fishbone_repo.go

96 lines
2.4 KiB
Go

package repository
import (
"users_management/m/model/entity"
"github.com/google/uuid"
"gorm.io/gorm"
)
type FishboneRepo interface {
Post(fishbone entity.Fishbone) error
GetAll() ([]entity.Fishbone, error)
Update(id uuid.UUID,updates map[string]interface{}) error
GetByID(id uuid.UUID) (entity.Fishbone, error)
CountFishbone() (map[uuid.UUID]int, error)
CountFishboneByBackboneID(backboneID uuid.UUID) (int, error)
}
type fishboneRepo struct {
db *gorm.DB
}
func NewFishboneRepo(db *gorm.DB) FishboneRepo {
return &fishboneRepo{
db: db,
}
}
func (r *fishboneRepo) Post(fishbone entity.Fishbone) error {
err := r.db.Create(&fishbone).Error
if err != nil {
return err
}
return nil
}
func (r *fishboneRepo) GetAll() ([]entity.Fishbone, error) {
var fishbones []entity.Fishbone
err := r.db.Preload("DeviceStart").Preload("DeviceEnd").Preload("Backbone").Preload("Backbone.DeviceStart").Preload("Backbone.DeviceEnd").Find(&fishbones).Error
if err != nil {
return fishbones, err
}
return fishbones, nil
}
func (r *fishboneRepo) Update(id uuid.UUID,updates map[string]interface{}) error {
err := r.db.Model(&entity.Fishbone{}).Where("id = ?", id).Updates(updates).Error
if err != nil {
return err
}
return nil
}
func (r *fishboneRepo) GetByID(id uuid.UUID) (entity.Fishbone, error) {
var fishbone entity.Fishbone
err := r.db.Where("id = ?", id).Preload("DeviceStart").Preload("DeviceEnd").Preload("Backbone.DeviceStart").Preload("Backbone.DeviceEnd").First(&fishbone).Error
if err != nil {
return fishbone, err
}
return fishbone, nil
}
func (r *fishboneRepo) CountFishbone() (map[uuid.UUID]int, error) {
type Result struct {
BackboneID uuid.UUID `gorm:"column:bb_id"`
Count int `gorm:"column:count"`
}
var results []Result
err := r.db.Model(&entity.Fishbone{}).
Select("bb_id, count(*) as count").
Group("bb_id").
Scan(&results).Error
if err != nil {
return nil, err
}
countMap := make(map[uuid.UUID]int)
for _, result := range results {
countMap[result.BackboneID] = result.Count
}
return countMap, nil
}
func (r *fishboneRepo) CountFishboneByBackboneID(backboneID uuid.UUID) (int, error) {
var count int64
err := r.db.Model(&entity.Fishbone{}).Where("bb_id = ?", backboneID).Count(&count).Error
if err != nil {
return 0, err
}
return int(count), nil
}