Skip to content

Commit

Permalink
Add a ToSql method to BaseQuery to expose query args
Browse files Browse the repository at this point in the history
The BaseQuery.String method returns the prepared SQL but does not return
the query arguments, making it hard to test queries without mocking the
database. By adding a BaseQuery.ToSql method that returns the args as
well as an error returned while compiling, anyone can easily test
queries built by a helper function and verify the sql and args are
correct.
  • Loading branch information
film42 committed Jan 20, 2018
1 parent 2a16129 commit dc62265
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
7 changes: 7 additions & 0 deletions query.go
Original file line number Diff line number Diff line change
Expand Up @@ -284,6 +284,13 @@ func (q *BaseQuery) String() string {
return sql
}

// ToSql returns the SQL generated by the query, the query arguments, and
// any error returned during the compile process.
func (q *BaseQuery) ToSql() (string, []interface{}, error) {
_, builder := q.compile()
return builder.ToSql()
}

// ColumnOrder represents a column name with its order.
type ColumnOrder interface {
// ToSql returns the SQL representation of the column with its order.
Expand Down
10 changes: 10 additions & 0 deletions query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,16 @@ func (s *QuerySuite) TestString() {
s.Equal("SELECT __model.foo FROM model __model", s.q.String())
}

func (s *QuerySuite) TestToSql() {
s.q.Select(f("foo"))
s.q.Where(Eq(f("foo"), 5))
s.q.Where(Eq(f("bar"), "baz"))
sql, args, err := s.q.ToSql()
s.Equal("SELECT __model.foo FROM model __model WHERE __model.foo = $1 AND __model.bar = $2", sql)
s.Equal([]interface{}{5, "baz"}, args)
s.Equal(err, nil)
}

func (s *QuerySuite) TestAddRelation() {
s.Nil(s.q.AddRelation(RelSchema, "rel", OneToOne, nil))
s.Equal("SELECT __model.id, __model.name, __model.email, __model.age, __rel_rel.id, __rel_rel.model_id, __rel_rel.foo FROM model __model LEFT JOIN rel __rel_rel ON (__rel_rel.model_id = __model.id)", s.q.String())
Expand Down

0 comments on commit dc62265

Please sign in to comment.