Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert gorm.DB query to its string representation

Tags:

go

go-gorm

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 ?

like image 749
Itamar Azulay Avatar asked Sep 12 '25 19:09

Itamar Azulay


1 Answers

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{})
like image 90
Rahmat Fathoni Avatar answered Sep 14 '25 20:09

Rahmat Fathoni