Verbessere Logging und Fehlerbehandlung
This commit is contained in:
parent
c737818ce4
commit
6e97d867de
14 changed files with 223 additions and 88 deletions
|
@ -3,6 +3,9 @@ package repositories
|
|||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"officeHours/models"
|
||||
)
|
||||
|
||||
|
@ -17,26 +20,17 @@ func NewCourseRepo(db *sql.DB) *CourseRepo {
|
|||
}
|
||||
|
||||
func (r *CourseRepo) FindByName(name string) (models.Course, error) {
|
||||
row := r.db.QueryRow("SELECT * FROM course WHERE name=?", name)
|
||||
var course models.Course
|
||||
if err := row.Scan(&course.Id, &course.Name); err != nil {
|
||||
return models.Course{}, err
|
||||
}
|
||||
return course, nil
|
||||
return r.getFromRow(r.db.QueryRow("SELECT * FROM course WHERE name=?", name))
|
||||
}
|
||||
|
||||
func (r *CourseRepo) FindById(id int) (models.Course, error) {
|
||||
row := r.db.QueryRow("SELECT * FROM course WHERE id=?", id)
|
||||
var course models.Course
|
||||
if err := row.Scan(&course.Id, &course.Name); err != nil {
|
||||
return models.Course{}, err
|
||||
}
|
||||
return course, nil
|
||||
return r.getFromRow(r.db.QueryRow("SELECT * FROM course WHERE id=?", id))
|
||||
}
|
||||
|
||||
func (r *CourseRepo) GetAll() ([]models.Course, error) {
|
||||
rows, err := r.db.Query("SELECT * FROM course")
|
||||
if err != nil {
|
||||
log.Printf("Error getting all courses: %s", err.Error())
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
@ -49,9 +43,22 @@ func (r *CourseRepo) getFromRows(rows *sql.Rows) ([]models.Course, error) {
|
|||
for rows.Next() {
|
||||
var course models.Course
|
||||
if err := rows.Scan(&course.Id, &course.Name); err != nil {
|
||||
log.Printf("Error scanning course row: %s", err.Error())
|
||||
return courses, err
|
||||
}
|
||||
courses = append(courses, course)
|
||||
}
|
||||
return courses, nil
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue