Updating MovieModel's Delete method from internal/data/movies.go file. Create the deleteMovieHandler function inside cmd/api/movies.go. Adding the route into routes.go to delete a movie.

This commit is contained in:
Maxime Delporte
2025-11-07 11:37:19 +01:00
parent 69651c58b7
commit 1270a3bda6
3 changed files with 55 additions and 0 deletions

View File

@@ -131,5 +131,32 @@ func (m MovieModel) Update(movie *Movie) error {
// Delete : Deleting a specific record from the movies table
func (m MovieModel) Delete(id int64) error {
// Return an ErrRecordNotFound err if the movie ID is less than 1
if id < 1 {
return ErrRecordNotFound
}
// Construct the SQL query to delete the record
query := `
DELETE FROM movies
WHERE id = $1`
// Execute the SQL query using the Exec() method, passing in the id variable as the value for the placeholder parameter. The Exec() method returns a sql.Result object.
result, err := m.DB.Exec(query, id)
if err != nil {
return err
}
// Call the RowsAffected() method on the sql.Result object to get the number of rows after by the query.
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
// If no rows were affected, we know that the movies table didn't contain a record with provided ID at the moment we tried to delete it. In that case we return an ErrRecordNotFound error
if rowsAffected == 0 {
return ErrRecordNotFound
}
return nil
}