如何将 gorm.DB 查询转换为字符串表示形式

huangapple go评论79阅读模式
英文:

How to convert gorm.DB query to its string representation

问题

假设我在Go语言中有一个gorm.DB对象,并且我想提取和断言我构建的查询,以查看它是否正确构建。我该如何将查询的“字符串”表示与该对象进行比较?

英文:

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 ?

答案1

得分: 2

确保你的 gorm 库是最新版本的。

  1. 使用 ToSQL 方法

示例:

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. 使用 DryRun Mode 方法

示例:

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. 使用 Debug 方法

示例:

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

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{})

答案2

得分: 0

或许你可以尝试使用Debug()函数将gorm生成的原始SQL打印到标准输出。

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

参考链接:https://gorm.io/docs/logger.html#Debug

英文:

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

huangapple
  • 本文由 发表于 2022年9月18日 19:21:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/73762321.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定