英文:
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
库是最新版本的。
- 使用
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
- 使用
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}
- 使用
Debug
方法
示例:
db.Debug().Where("name = ?", "jinzhu").First(&User{})
英文:
Make sure your gorm
is up to date.
- 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
- 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}
- 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{})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论