Search code examples
gogo-pg

convert go-pg query into plain sql


Is it possible to convert go-pg query

err = db.Model(story).
        Relation("Author").
        Where("story.id = ?", story1.Id).
        Select()

into plain SQL?

It would be helpful for debugging. So I could copy this plain SQL query and run in psql client as a string. Probably there is some kind of package for this?


Solution

  • I've just been upgrading from go-pg v7 to v10 & had a problem where Query.AppendFormat() which is what I was using to get the RAW SQL had been removed.

    After using the comments in this post for inspiration I managed extract it, using the code below

    
    import (
        "github.com/go-pg/pg/v10/orm"
    )
    
    func QueryToString(q *orm.Query) string {
        value, _ := q.AppendQuery(orm.NewFormatter(), nil)
    
        return string(value)
    }
    
    

    Hope this helps future viewers