reCoreD-UI/controllers/record.go

82 lines
1.7 KiB
Go
Raw Normal View History

2024-04-03 09:05:12 +00:00
package controllers
import (
"fmt"
"reCoreD-UI/models"
"gorm.io/gorm"
)
func (c *Controller) CreateRecord(r *models.Record) error {
if r.RecordType != models.RecordTypeSOA {
domains, err := c.GetDomains(r.Zone)
if err != nil {
return err
}
if len(domains) == 0 || domains[0].DomainName == r.Zone {
return fmt.Errorf("no such domain")
}
}
return c.DB.Transaction(func(tx *gorm.DB) error {
return tx.Create(r).Error
})
}
func (c *Controller) CreateRecords(rs []*models.Record) error {
return c.DB.Transaction(func(tx *gorm.DB) error {
for _, r := range rs {
if err := tx.Create(r).Error; err != nil {
return err
}
}
return nil
})
}
2024-04-03 14:37:15 +00:00
func (c *Controller) GetRecords(cond map[string]string) ([]models.Record, error) {
2024-04-03 09:05:12 +00:00
var records []models.Record
if err := c.DB.Where(cond).Find(&records).Error; err != nil {
return nil, err
}
return records, nil
}
func (c *Controller) UpdateRecord(r *models.Record) error {
return c.DB.Transaction(func(tx *gorm.DB) error {
return tx.Model(r).Updates(r).Error
})
}
2024-04-03 14:37:15 +00:00
func (c *Controller) DeleteRecord(domain, id string) error {
2024-04-03 09:05:12 +00:00
return c.DB.Transaction(func(tx *gorm.DB) error {
2024-04-03 14:37:15 +00:00
return tx.Where("record_type != ?", models.RecordTypeSOA).
Where("id = ?", id).
Where("zone = ?", domain).
Delete(&models.Record{}).Error
2024-04-03 09:05:12 +00:00
})
}
2024-04-07 02:07:26 +00:00
func (c *Controller) getRecordCounts() (map[string]float64, error) {
rows, err := c.DB.Model(models.Record{}).Select("zone", "count(*) as count").Group("zone").Rows()
if err != nil {
return nil, err
}
defer rows.Close()
result := make(map[string]float64)
for rows.Next() {
var domain string
var count int64
if err := rows.Scan(&domain, &count); err != nil {
return nil, err
}
result[domain] = float64(count)
}
return result, nil
}