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
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?