github.com/oinume/lekcije@v0.0.0-20231017100347-5b4c5eb6ab24/backend/model/stat_daily_notification_event.go (about)

     1  package model
     2  
     3  import (
     4  	"fmt"
     5  	"time"
     6  
     7  	"github.com/jinzhu/gorm"
     8  
     9  	"github.com/oinume/lekcije/backend/errors"
    10  )
    11  
    12  type StatDailyNotificationEvent struct {
    13  	Date    time.Time
    14  	Event   string
    15  	Count   uint32
    16  	UUCount uint32
    17  }
    18  
    19  func (*StatDailyNotificationEvent) TableName() string {
    20  	return "stat_daily_notification_event"
    21  }
    22  
    23  type StatDailyNotificationEventService struct {
    24  	db *gorm.DB
    25  }
    26  
    27  func NewStatDailyNotificationEventService(db *gorm.DB) *StatDailyNotificationEventService {
    28  	return &StatDailyNotificationEventService{db}
    29  }
    30  
    31  func (s *StatDailyNotificationEventService) CreateOrUpdate(v *StatDailyNotificationEvent) error {
    32  	date := v.Date.Format(dbDateFormat)
    33  	sql := fmt.Sprintf(`INSERT INTO %s VALUES (?, ?, ?, ?)`, v.TableName())
    34  	sql += " ON DUPLICATE KEY UPDATE"
    35  	sql += " count=?, uu_count=?"
    36  	values := []interface{}{
    37  		date, v.Event, v.Count, v.UUCount,
    38  		v.Count, v.UUCount,
    39  	}
    40  	if err := s.db.Exec(sql, values...).Error; err != nil {
    41  		return errors.NewInternalError(
    42  			errors.WithError(err),
    43  			errors.WithResource(errors.NewResource(v.TableName(), "date", date)),
    44  		)
    45  	}
    46  	return nil
    47  }
    48  
    49  func (s *StatDailyNotificationEventService) FindAllByDate(date time.Time) ([]*StatDailyNotificationEvent, error) {
    50  	events := make([]*StatDailyNotificationEvent, 0, 1000)
    51  	sql := fmt.Sprintf(`SELECT * FROM %s WHERE date = ?`, (&StatDailyNotificationEvent{}).TableName())
    52  	if err := s.db.Raw(sql, date.Format(dbDateFormat)).Scan(&events).Error; err != nil {
    53  		return nil, errors.NewInternalError(
    54  			errors.WithError(err),
    55  			errors.WithMessage("Failed to FindAllByDate"),
    56  		)
    57  	}
    58  	return events, nil
    59  
    60  }