probo/store/db/db.go

80 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-10-18 13:40:21 +02:00
package db
2023-10-28 20:50:06 +02:00
import (
"git.andreafazzi.eu/andrea/probo/client"
"git.andreafazzi.eu/andrea/probo/models"
"git.andreafazzi.eu/andrea/probo/store"
"github.com/glebarez/sqlite"
"github.com/google/uuid"
"gorm.io/gorm"
)
2023-10-18 13:40:21 +02:00
type DBProboCollectorStore struct {
Path string
2023-10-28 20:50:06 +02:00
db *gorm.DB
si store.ProboCollectorStore
}
func NewDBProboCollectorStore(path string, s store.ProboCollectorStore) (*DBProboCollectorStore, error) {
var err error
store := new(DBProboCollectorStore)
store.db, err = gorm.Open(sqlite.Open(path), &gorm.Config{})
if err != nil {
return nil, err
}
err = store.db.AutoMigrate(
&models.Question{},
&models.Answer{},
&models.Quiz{},
&models.Collection{},
&models.Exam{},
&models.Participant{},
)
if err != nil {
return nil, err
}
store.si = s
return store, nil
2023-10-18 13:40:21 +02:00
}
2023-10-28 20:50:06 +02:00
func (s *DBProboCollectorStore) CreateExam(r *client.CreateUpdateExamRequest) (*models.Exam, error) {
exam := new(models.Exam)
exam.ID = uuid.New().String()
exam.Name = r.Name
exam.Description = r.Description
collection, err := s.si.ReadCollectionByID(r.CollectionID)
if err != nil {
return nil, err
}
exam.Collection = collection
result := s.db.Create(exam)
if result.Error != nil {
return nil, result.Error
}
return exam, nil
}
func (s *DBProboCollectorStore) ReadExamByID(r *client.ReadExamByIDRequest) (*models.Exam, error) {
exam := &models.Exam{
ID: r.ID,
}
s.db.First(&exam)
if err := s.db.Error; err != nil {
return nil, err
}
return exam, nil
2023-10-18 13:40:21 +02:00
}