probo/store/db/db.go

79 lines
1.5 KiB
Go

package db
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"
)
type DBProboCollectorStore struct {
Path string
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
}
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
}