Skip to content

Commit dc62265

Browse files
committed
Add a ToSql method to BaseQuery to expose query args
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.
1 parent 2a16129 commit dc62265

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

query.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,13 @@ func (q *BaseQuery) String() string {
284284
return sql
285285
}
286286

287+
// ToSql returns the SQL generated by the query, the query arguments, and
288+
// any error returned during the compile process.
289+
func (q *BaseQuery) ToSql() (string, []interface{}, error) {
290+
_, builder := q.compile()
291+
return builder.ToSql()
292+
}
293+
287294
// ColumnOrder represents a column name with its order.
288295
type ColumnOrder interface {
289296
// ToSql returns the SQL representation of the column with its order.

query_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,16 @@ func (s *QuerySuite) TestString() {
8282
s.Equal("SELECT __model.foo FROM model __model", s.q.String())
8383
}
8484

85+
func (s *QuerySuite) TestToSql() {
86+
s.q.Select(f("foo"))
87+
s.q.Where(Eq(f("foo"), 5))
88+
s.q.Where(Eq(f("bar"), "baz"))
89+
sql, args, err := s.q.ToSql()
90+
s.Equal("SELECT __model.foo FROM model __model WHERE __model.foo = $1 AND __model.bar = $2", sql)
91+
s.Equal([]interface{}{5, "baz"}, args)
92+
s.Equal(err, nil)
93+
}
94+
8595
func (s *QuerySuite) TestAddRelation() {
8696
s.Nil(s.q.AddRelation(RelSchema, "rel", OneToOne, nil))
8797
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())

0 commit comments

Comments
 (0)