From 541331287592b4f4d62a7265d7920b8e89699d4c Mon Sep 17 00:00:00 2001 From: Maxime Delporte Date: Mon, 10 Nov 2025 16:45:42 +0100 Subject: [PATCH] Adding a query timeout. --- internal/data/movies.go | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/internal/data/movies.go b/internal/data/movies.go index 9d3a6b2..007a2e7 100644 --- a/internal/data/movies.go +++ b/internal/data/movies.go @@ -1,6 +1,7 @@ package data import ( + "context" "database/sql" "errors" "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 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. - err := m.DB.QueryRow(query, id).Scan( + // 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. + 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.CreatedAt, &movie.Title,