Home > Net >  How to convert gorm.DB query to its string representation
How to convert gorm.DB query to its string representation

Time:09-19

Let's say I have a gorm.DB object in Go, and I want to extract and assert the query I've built to see it was built correctly. How can I compare the "string" representation of the query to this object ?

CodePudding user response:

Maybe you can try to use Debug() to print raw sql built by gorm to stdout.

db.Debug().Where("name = ?", "jinzhu").First(&User{})

FYI https://gorm.io/docs/logger.html#Debug

CodePudding user response:

Make sure your gorm is up to date.

  1. Using ToSQL

example:

sql := DB.ToSQL(func(tx *gorm.DB) *gorm.DB {
  return tx.Model(&User{}).Where("id = ?", 100).Limit(10).Order("age desc").Find(&[]User{})
})
sql //=> SELECT * FROM "users" WHERE id = 100 AND "users"."deleted_at" IS NULL ORDER BY age desc LIMIT 10
  1. Using DryRun Mode

example:

stmt := db.Session(&Session{DryRun: true}).First(&user, 1).Statement
stmt.SQL.String() //=> SELECT * FROM `users` WHERE `id` = $1 ORDER BY `id`
stmt.Vars         //=> []interface{}{1}
  1. Using Debug

example:

db.Debug().Where("name = ?", "jinzhu").First(&User{})
  • Related