db.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package db
  2. import (
  3. "git.andreafazzi.eu/andrea/probo/client"
  4. "git.andreafazzi.eu/andrea/probo/models"
  5. "git.andreafazzi.eu/andrea/probo/store"
  6. "github.com/glebarez/sqlite"
  7. "github.com/google/uuid"
  8. "gorm.io/gorm"
  9. )
  10. type DBProboCollectorStore struct {
  11. Path string
  12. db *gorm.DB
  13. si store.ProboCollectorStore
  14. }
  15. func NewDBProboCollectorStore(path string, s store.ProboCollectorStore) (*DBProboCollectorStore, error) {
  16. var err error
  17. store := new(DBProboCollectorStore)
  18. store.db, err = gorm.Open(sqlite.Open(path), &gorm.Config{})
  19. if err != nil {
  20. return nil, err
  21. }
  22. err = store.db.AutoMigrate(
  23. &models.Question{},
  24. &models.Answer{},
  25. &models.Quiz{},
  26. &models.Collection{},
  27. &models.Exam{},
  28. &models.Participant{},
  29. )
  30. if err != nil {
  31. return nil, err
  32. }
  33. store.si = s
  34. return store, nil
  35. }
  36. func (s *DBProboCollectorStore) CreateExam(r *client.CreateUpdateExamRequest) (*models.Exam, error) {
  37. exam := new(models.Exam)
  38. exam.ID = uuid.New().String()
  39. exam.Name = r.Name
  40. exam.Description = r.Description
  41. collection, err := s.si.ReadCollectionByID(r.CollectionID)
  42. if err != nil {
  43. return nil, err
  44. }
  45. exam.Collection = collection
  46. result := s.db.Create(exam)
  47. if result.Error != nil {
  48. return nil, result.Error
  49. }
  50. return exam, nil
  51. }
  52. func (s *DBProboCollectorStore) ReadExamByID(r *client.ReadExamByIDRequest) (*models.Exam, error) {
  53. exam := &models.Exam{
  54. ID: r.ID,
  55. }
  56. s.db.First(&exam)
  57. if err := s.db.Error; err != nil {
  58. return nil, err
  59. }
  60. return exam, nil
  61. }