diff --git a/internal/data/movies.go b/internal/data/movies.go index 007a2e7..c8277bc 100644 --- a/internal/data/movies.go +++ b/internal/data/movies.go @@ -63,8 +63,12 @@ func (m MovieModel) Insert(movie *Movie) error { // Create an args slice containing the values for the placeholder parameters from the movie struct. Declaring this slice immediately next to our SQL query helps to make it nice and clear *what values are being used where* in the query args := []any{movie.Title, movie.Year, movie.Runtime, pq.Array(movie.Genres)} + // Create a context with a 3-second timeout + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + // Use the QueryRow() method to execute the SQL query on our connection pool, passing in the args slice as a variadic parameter and scanning the system-generated id, created_at and version values into the movie struct. - return m.DB.QueryRow(query, args...).Scan(&movie.ID, &movie.CreatedAt, &movie.Version) + return m.DB.QueryRowContext(ctx, query, args...).Scan(&movie.ID, &movie.CreatedAt, &movie.Version) } // Get : Fetching a specific record from the movies table @@ -134,8 +138,12 @@ func (m MovieModel) Update(movie *Movie) error { movie.Version, } + // Create a context with a 3-second timeout. + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + // Execute the SQL query. If no matching row could be found, we know the movie version has changed (or the record has been deleted) and we return our custom ErrEditConflict error. - err := m.DB.QueryRow(query, args...).Scan(&movie.Version) + err := m.DB.QueryRowContext(ctx, query, args...).Scan(&movie.Version) if err != nil { switch { case errors.Is(err, sql.ErrNoRows): @@ -160,8 +168,12 @@ func (m MovieModel) Delete(id int64) error { DELETE FROM movies WHERE id = $1` + // Create a context with a 3-second timeout. + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + // 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) + result, err := m.DB.ExecContext(ctx, query, id) if err != nil { return err }