2022-08-29 20:58:19 +00:00
|
|
|
package repositories
|
|
|
|
|
|
|
|
import (
|
|
|
|
"database/sql"
|
2022-09-21 20:24:08 +00:00
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
2022-09-20 10:21:01 +00:00
|
|
|
"officeHours/models"
|
2022-08-29 20:58:19 +00:00
|
|
|
)
|
|
|
|
|
2022-11-04 20:15:38 +00:00
|
|
|
// A struct to hold the db connection
|
2022-08-29 20:58:19 +00:00
|
|
|
type CourseRepo struct {
|
|
|
|
db *sql.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewCourseRepo(db *sql.DB) *CourseRepo {
|
|
|
|
return &CourseRepo{
|
|
|
|
db: db,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (r *CourseRepo) FindByName(name string) (models.Course, error) {
|
2022-09-21 20:24:08 +00:00
|
|
|
return r.getFromRow(r.db.QueryRow("SELECT * FROM course WHERE name=?", name))
|
2022-08-29 20:58:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *CourseRepo) FindById(id int) (models.Course, error) {
|
2022-09-21 20:24:08 +00:00
|
|
|
return r.getFromRow(r.db.QueryRow("SELECT * FROM course WHERE id=?", id))
|
2022-08-29 20:58:19 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *CourseRepo) GetAll() ([]models.Course, error) {
|
2022-09-26 12:25:51 +00:00
|
|
|
rows, err := r.db.Query("SELECT * FROM course ORDER BY name ASC")
|
2022-08-29 20:58:19 +00:00
|
|
|
if err != nil {
|
2022-09-21 20:24:08 +00:00
|
|
|
log.Printf("Error getting all courses: %s", err.Error())
|
2022-08-29 20:58:19 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
|
|
|
|
|
|
|
return r.getFromRows(rows)
|
|
|
|
}
|
|
|
|
|
2022-11-04 20:15:38 +00:00
|
|
|
// Helper function to get a course from multiple SQL result rows
|
2022-08-29 20:58:19 +00:00
|
|
|
func (r *CourseRepo) getFromRows(rows *sql.Rows) ([]models.Course, error) {
|
|
|
|
var courses []models.Course
|
|
|
|
for rows.Next() {
|
|
|
|
var course models.Course
|
|
|
|
if err := rows.Scan(&course.Id, &course.Name); err != nil {
|
2022-09-21 20:24:08 +00:00
|
|
|
log.Printf("Error scanning course row: %s", err.Error())
|
2022-08-29 20:58:19 +00:00
|
|
|
return courses, err
|
|
|
|
}
|
|
|
|
courses = append(courses, course)
|
|
|
|
}
|
|
|
|
return courses, nil
|
|
|
|
}
|
2022-09-21 20:24:08 +00:00
|
|
|
|
2022-11-04 20:15:38 +00:00
|
|
|
// Helper function to get a course from an SQL result row
|
2022-09-21 20:24:08 +00:00
|
|
|
func (r *CourseRepo) getFromRow(row *sql.Row) (models.Course, error) {
|
|
|
|
var course models.Course
|
|
|
|
if err := row.Scan(&course.Id, &course.Name); err != nil {
|
|
|
|
err = fmt.Errorf("Error getting course row: %w", err)
|
|
|
|
if !errors.Is(err, sql.ErrNoRows) {
|
|
|
|
log.Printf(err.Error())
|
|
|
|
}
|
|
|
|
return models.Course{}, err
|
|
|
|
}
|
|
|
|
return course, nil
|
|
|
|
}
|