2022-08-29 20:58:19 +00:00
|
|
|
// tutor
|
|
|
|
package repositories
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"sprechstundentool/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 {
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-08-31 20:49:14 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-08-29 20:58:19 +00:00
|
|
|
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 {
|
|
|
|
return tutors, err
|
|
|
|
}
|
|
|
|
tutors = append(tutors, tutor)
|
|
|
|
}
|
|
|
|
return tutors, nil
|
|
|
|
}
|
|
|
|
func (r *TutorRepo) Save(tutor models.Tutor) error {
|
|
|
|
return nil
|
|
|
|
}
|
2022-09-05 15:55:08 +00:00
|
|
|
func (r *TutorRepo) Add(tutor models.Tutor) (int, error) {
|
2022-08-31 20:49:14 +00:00
|
|
|
//Don't add identical tutors
|
2022-09-05 15:55:08 +00:00
|
|
|
existentTutor, err := r.FindByNameAndEmail(tutor.Name, tutor.Email)
|
2022-08-31 20:49:14 +00:00
|
|
|
if err == sql.ErrNoRows {
|
2022-09-05 15:55:08 +00:00
|
|
|
sqlResult, err := r.db.Exec("INSERT INTO `tutor` (name, email) VALUES (?,?)", tutor.Name, tutor.Email)
|
|
|
|
id, _ := sqlResult.LastInsertId()
|
|
|
|
return int(id), err
|
2022-08-31 20:49:14 +00:00
|
|
|
}
|
2022-09-05 15:55:08 +00:00
|
|
|
return existentTutor.Id, err
|
2022-08-31 20:49:14 +00:00
|
|
|
|
2022-08-29 20:58:19 +00:00
|
|
|
}
|