How do I use context for timeouts using GORM?

In Go, using context for timeouts is essential when working with GORM to ensure that database queries do not hang indefinitely. By using a context with a timeout, you can specify how long to wait for a database operation before it gives up and returns an error. Here's how to implement context for timeouts using GORM.


package main

import (
    "context"
    "fmt"
    "time"

    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
)

func main() {
    // Initialize GORM with SQLite
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        panic("failed to connect database")
    }

    // Create a context with a timeout
    ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
    defer cancel()

    // Example of using the context with a GORM operation
    var user User
    result := db.WithContext(ctx).First(&user, 1) // Fetch user with ID 1

    if result.Error != nil {
        if ctx.Err() == context.DeadlineExceeded {
            fmt.Println("Query timed out")
        } else {
            fmt.Println("Failed to fetch user:", result.Error)
        }
    } else {
        fmt.Println("User found:", user)
    }
}

type User struct {
    ID   uint
    Name string
}

golang gorm context timeout database queries