Skip to content

Commit 6ec9430

Browse files
author
Roberto Santalla
authored
Merge pull request #255 from film42/gt/toSql
Add a ToSql method to BaseQuery to expose query args
2 parents 1dec030 + dc62265 commit 6ec9430

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)