package repositories import ( "learnsteam/cslms-api/internal/models" "gorm.io/gorm" "gorm.io/gorm/clause" ) type userQuizRepository struct { DB *gorm.DB } func NewUserQuizRepository(db *gorm.DB) UserQuizRepository { return &userQuizRepository{ DB: db, } } type UserQuizRepository interface { List(int64, int, int) (*[]models.UserQuiz, error) Total(int64) (int64, error) Find(int64) (*models.UserQuiz, error) Create(*models.UserQuiz) (*models.UserQuiz, error) Insert([]models.UserQuiz) ([]models.UserQuiz, error) Update(*models.UserQuiz) (*models.UserQuiz, error) Delete(int64) error SumScore(int64) (float32, error) } func (r *userQuizRepository) List(user_quiz_paper_id int64, page int, limit int) (*[]models.UserQuiz, error) { var rows *[]models.UserQuiz var err error offset := limit * (page - 1) if user_quiz_paper_id > 0 { err = r.DB.Offset(offset).Limit(limit).Order("vol_no ASC").Where("user_quiz_paper_id = ?", user_quiz_paper_id).Find(&rows).Error } else { err = r.DB.Offset(offset).Limit(limit).Find(&rows).Error } return rows, err } func (r *userQuizRepository) Total(user_quiz_paper_id int64) (int64, error) { var total int64 var err error if user_quiz_paper_id > 0 { err = r.DB.Model(&models.UserQuiz{}).Where("user_quiz_paper_id = ?", user_quiz_paper_id).Count(&total).Error } else { err = r.DB.Model(&models.UserQuiz{}).Count(&total).Error } return total, err } func (r *userQuizRepository) Find(id int64) (*models.UserQuiz, error) { var row *models.UserQuiz err := r.DB.Where("id = ?", id).First(&row).Error return row, err } func (r *userQuizRepository) Create(row *models.UserQuiz) (*models.UserQuiz, error) { err := r.DB.Create(&row).Error return row, err } func (r *userQuizRepository) Insert(items []models.UserQuiz) ([]models.UserQuiz, error) { err := r.DB.Clauses(clause.OnConflict{DoNothing: true}).Create(&items).Error return items, err } func (r *userQuizRepository) Update(quiz *models.UserQuiz) (*models.UserQuiz, error) { var row *models.UserQuiz if err := r.DB.Where("id=?", quiz.ID).First(&row).Error; err != nil { return nil, err } err := r.DB.Model(&row).Select("*").Updates(&quiz).Error return row, err } func (r *userQuizRepository) Delete(id int64) error { var row *models.UserQuiz if err := r.DB.Where("id=?", id).First(&row).Error; err != nil { return err } err := r.DB.Delete(&row).Error return err } func (r *userQuizRepository) SumScore(userquizpaper_id int64) (float32, error) { var result struct { Score float32 } if err := r.DB.Model(&models.UserQuiz{}).Select("SUM(score) AS score"). Where("user_quiz_paper_id = ?", userquizpaper_id). Scan(&result).Error; err != nil { return 0, err } return result.Score, nil }