sprechstunden-go/repositories/tutor.go

91 lines
2.3 KiB
Go

// tutor
package repositories
import (
"database/sql"
"errors"
"fmt"
"log"
"officeHours/models"
)
type TutorRepo struct {
db *sql.DB
}
func NewTutorRepo(db *sql.DB) *TutorRepo {
return &TutorRepo{
db: db,
}
}
func (r *TutorRepo) FindByEmail(email string) ([]models.Tutor, error) {
rows, err := r.db.Query("SELECT * FROM tutor WHERE email=?", email)
if err != nil {
return nil, err
}
defer rows.Close()
var tutors []models.Tutor
for rows.Next() {
var tutor models.Tutor
if err := rows.Scan(&tutor.Id, &tutor.Name, &tutor.Email); err != nil {
err = fmt.Errorf("Error scanning tutor row: %w", err)
log.Println(err.Error())
return tutors, err
}
tutors = append(tutors, tutor)
}
return tutors, nil
}
func (r *TutorRepo) FindById(id int) (models.Tutor, error) {
row := r.db.QueryRow("SELECT * FROM tutor WHERE id=?", id)
var tutor models.Tutor
if err := row.Scan(&tutor.Id, &tutor.Name, &tutor.Email); err != nil {
return models.Tutor{}, err
}
return tutor, nil
}
func (r *TutorRepo) FindByNameAndEmail(name string, email string) (models.Tutor, error) {
row := r.db.QueryRow("SELECT * FROM tutor WHERE email=? AND name=?", email, name)
var tutor models.Tutor
if err := row.Scan(&tutor.Id, &tutor.Name, &tutor.Email); err != nil {
return models.Tutor{}, err
}
return tutor, nil
}
func (r *TutorRepo) GetAll() ([]models.Tutor, error) {
rows, err := r.db.Query("SELECT * FROM tutor")
if err != nil {
return nil, err
}
defer rows.Close()
var tutors []models.Tutor
for rows.Next() {
var tutor models.Tutor
if err := rows.Scan(&tutor.Id, &tutor.Name, &tutor.Email); err != nil {
err = fmt.Errorf("Error scanning tutor row: %w", err)
log.Println(err.Error())
return tutors, err
}
tutors = append(tutors, tutor)
}
return tutors, nil
}
func (r *TutorRepo) Add(tutor models.Tutor) (int, error) {
//Don't add identical tutors
existentTutor, err := r.FindByNameAndEmail(tutor.Name, tutor.Email)
if errors.Is(err, sql.ErrNoRows) {
sqlResult, err := r.db.Exec("INSERT INTO `tutor` (name, email) VALUES (?,?)", tutor.Name, tutor.Email)
id, lastInsertIdErr := sqlResult.LastInsertId()
if lastInsertIdErr != nil {
log.Printf("Error getting Id for new tutor: %s", lastInsertIdErr.Error())
}
return int(id), err
}
return existentTutor.Id, err
}