Adding a query timeout.

This commit is contained in:
Maxime Delporte
2025-11-10 16:45:42 +01:00
parent fd3bca1226
commit 5413312875

View File

@@ -1,6 +1,7 @@
package data package data
import ( import (
"context"
"database/sql" "database/sql"
"errors" "errors"
"github.com/lib/pq" "github.com/lib/pq"
@@ -82,8 +83,14 @@ func (m MovieModel) Get(id int64) (*Movie, error) {
// Declare a Movie struct to hold the data returned by the query // Declare a Movie struct to hold the data returned by the query
var movie Movie var movie Movie
// Execute the query using the QueryRow() method, passing in the provided id value as a placeholder parameter, and scan the response data into the fields of the Movie struct. Importantly, notice that we need to convert the scan target for the genres column using the pq.Array() adapter function again. // Use the context.WithTimeout() function to create a context.Context which carries a 3-second timeout deadline. Note that we're using the empty context.Background() as the 'parent' context.
err := m.DB.QueryRow(query, id).Scan( ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
// Importantly, use defer to make sure that we cancel the context before the Get() method returns.
defer cancel()
// Use the QueryRowContext() method to execute the query, passing in the context with the deadline as the first argument, then the provided id value as a placeholder parameter, and scan the response data into the fields of the Movie struct. Importantly, notice that we need to convert the scan target for the genres column using the pq.Array() adapter function again.
err := m.DB.QueryRowContext(ctx, query, id).Scan(
&movie.ID, &movie.ID,
&movie.CreatedAt, &movie.CreatedAt,
&movie.Title, &movie.Title,