How to Access the Underlying MySQL Query in Go with GORM
GORM is a powerful ORM (Object-Relational Mapping) library for Go. It simplifies database interactions by providing a clean and intuitive API. However, sometimes it's useful to access the raw SQL queries that are being executed underneath. This can be especially helpful for debugging or optimizing your database interactions.
Retrieving the SQL Query Log
To get the SQL query log from GORM, you can use the LogMode method. This method takes a boolean value as an argument. If true, GORM will log the SQL queries to the console. Here's how you would use it:
package main import ( "gorm.io/gorm" "log" ) func main() { db, err := gorm.Open("mysql", "user:password@tcp(localhost:3306)/database_name") if err != nil { log.Fatal(err) } // Enable log mode db.LogMode(true) var todos []Todo db.Find(&todos) db.Preload("User").Find(&todos) }
By default, LogMode logs all SQL queries to the console. If you only want to log queries in certain environments, such as development, you can use the To method to specify the destination:
import ( "fmt" "gorm.io/gorm/logger" "log" "os" ) type DevLogger struct { logger.Interface } func (l *DevLogger) Printf(level logger.Level, format string, v ...interface{}) { if level == logger.Info || os.Getenv("ENV") == "development" { fmt.Println("QUERY: ", fmt.Sprintf(format, v...)) } } func main() { db, err := gorm.Open("mysql", "user:password@tcp(localhost:3306)/database_name?parseTime=true") if err != nil { log.Fatal(err) } db.Logger = &DevLogger{Interface: logger.Discard} var todos []Todo db.Find(&todos) db.Preload("User").Find(&todos) }
The above code uses a custom logger to only log queries in development environments (when ENV=development).
Note that in GORM v2, the DB type has been replaced with *gorm.DB. The methods and syntax for *gorm.DB are similar to those of DB, but the * indicates that it's a pointer receiver.
The above is the detailed content of How to View Underlying MySQL Queries Generated by GORM in Go?. For more information, please follow other related articles on the PHP Chinese website!