Gorm: Get raw sql from builder?

Created on 5 Jan 2017  路  5Comments  路  Source: go-gorm/gorm

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?

Most helpful comment

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

All 5 comments

@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 sad

it 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")
Was this page helpful?
0 / 5 - 0 ratings

Related issues

koalacxr picture koalacxr  路  3Comments

rfyiamcool picture rfyiamcool  路  3Comments

youtwo123 picture youtwo123  路  3Comments

easonlin404 picture easonlin404  路  3Comments

corvinusy picture corvinusy  路  3Comments