How can I get the generated SQL string from a SQL Builder?
example:
q := db.Model(&User{}).Where("name = ?", "jinzhu").Select("name, age, email")
// fmt.Println(q.sql) anything like this?
@bwiggs, I'm not sure you can see the raw string at this point, but if you're looking for debugging the queries made by gorm you can set the DEBUG=true env variable before starting your go program. Example as follows:
dev_run.sh
# enable debugging
export DEBUG=true;
# run go program by passing arguments
go run main.go $1
And you would start the program with bash dev_run.sh or bash dev_run.sh --race
GORM can't return the finally SQL, as GORM is using standard sql/database package to prevent SQL injection, so GORM itself can't generate safe SQLs that you could use.
func scopeStoreSqlAndVars(scope *gorm.Scope) {
scope.DB().InstantSet("sql", scope.SQL)
scope.DB().InstantSet("sqlVars", scope.SQLVars)
}
db.Callback().Query().Register("query_scope_sql_vars", scopeStoreSqlAndVars)
sql, ok := db.Get("sql")
func scopeStoreSqlAndVars(scope *gorm.Scope) { scope.DB().InstantSet("sql", scope.SQL) scope.DB().InstantSet("sqlVars", scope.SQLVars) } db.Callback().Query().Register("query_scope_sql_vars", scopeStoreSqlAndVars) sql, ok := db.Get("sql")@oulaly
not work for me ... so sad
it returns nil,false
func scopeStoreSqlAndVars(scope *gorm.Scope) { scope.DB().InstantSet("sql", scope.SQL) scope.DB().InstantSet("sqlVars", scope.SQLVars) } db.Callback().Query().Register("query_scope_sql_vars", scopeStoreSqlAndVars) sql, ok := db.Get("sql")@oulaly
not work for me ... so sadit returns nil,false
func scopeStoreSqlAndVars(scope *gorm.Scope) {
scope.DB().InstantSet("sql", scope.SQL)
scope.DB().InstantSet("sqlVars", scope.SQLVars)
}
db.Callback().Create().Register("create_scope_sql_vars", scopeStoreSqlAndVars)
db.Callback().Query().Register("query_scope_sql_vars", scopeStoreSqlAndVars)
db.Callback().Update().Register("update_scope_sql_vars", scopeStoreSqlAndVars)
db.Callback().Delete().Register("delete_scope_sql_vars", scopeStoreSqlAndVars)
db.Callback().RowQuery().Register("row_query_scope_sql_vars", scopeStoreSqlAndVars)
// execute biz logic example
tempDb := db.Where('...').Find(&Objects)
sql, ok := tempDb.Get("sql")
Most helpful comment
it returns nil,false