github.com/easysoft/zendata@v0.0.0-20240513203326-705bd5a7fd67/internal/server/repo/section.go (about)

     1  package serverRepo
     2  
     3  import (
     4  	"strconv"
     5  	"strings"
     6  
     7  	consts "github.com/easysoft/zendata/internal/pkg/const"
     8  	"github.com/easysoft/zendata/internal/pkg/model"
     9  	"gorm.io/gorm"
    10  )
    11  
    12  type SectionRepo struct {
    13  	DB *gorm.DB `inject:""`
    14  }
    15  
    16  func (r *SectionRepo) List(ownerId uint, ownerType string) (sections []*model.ZdSection, err error) {
    17  	err = r.DB.Where("ownerID=? AND ownerType=?", ownerId, ownerType).Find(&sections).Error
    18  	return
    19  }
    20  
    21  func (r *SectionRepo) Get(id uint, ownerType string) (section model.ZdSection, err error) {
    22  	err = r.DB.Where("id=? AND ownerType=?", id, ownerType).First(&section).Error
    23  	return
    24  }
    25  
    26  func (r *SectionRepo) Create(section *model.ZdSection) (err error) {
    27  	err = r.DB.Create(&section).Error
    28  	return
    29  }
    30  
    31  func (r *SectionRepo) Update(section *model.ZdSection) (err error) {
    32  	err = r.DB.Save(&section).Error
    33  	return
    34  }
    35  
    36  func (r *SectionRepo) Remove(id uint, ownerType string) (err error) {
    37  	err = r.DB.Where("id=? AND ownerType=?", id, ownerType).Delete(&model.ZdSection{}).Error
    38  	return
    39  }
    40  
    41  func (r *SectionRepo) SaveFieldSectionToDB(typ, desc, stepStr string, count int, countTag string,
    42  	ord int, fieldID uint, ownerType string) {
    43  
    44  	if typ == "literal" && desc[:1] == string(consts.LeftBrackets) &&
    45  		desc[len(desc)-1:] == string(consts.RightBrackets) {
    46  
    47  		desc = "[" + desc[1:len(desc)-1] + "]"
    48  		typ = "list"
    49  	}
    50  
    51  	countStr := strconv.Itoa(count)
    52  	rand := false
    53  	step := 1
    54  	if stepStr == "r" {
    55  		rand = true
    56  	} else {
    57  		step, _ = strconv.Atoi(stepStr)
    58  	}
    59  
    60  	start := ""
    61  	end := ""
    62  	if typ == "interval" {
    63  		arr := strings.Split(desc, "-")
    64  		start = arr[0]
    65  		if len(arr) > 1 {
    66  			end = arr[1]
    67  		}
    68  	}
    69  
    70  	section := model.ZdSection{OwnerType: ownerType, OwnerID: fieldID, Type: typ,
    71  		Value: desc, Start: start, End: end, Ord: ord,
    72  		Step: step, Repeat: countStr, RepeatTag: countTag, Rand: rand}
    73  
    74  	r.Create(&section)
    75  }
    76  
    77  func NewSectionRepo(db *gorm.DB) *SectionRepo {
    78  	return &SectionRepo{DB: db}
    79  }