Skip to content

Commit aabf848

Browse files
committed
添加with where
1 parent 7ce399f commit aabf848

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

sqlbuilder/builder.go

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,20 +26,30 @@ type Query struct {
2626
}
2727

2828
// Where 添加参数
29-
func (q *Query) Where(stmt string, v ...interface{}) {
29+
func (q *Query) Where(stmt string, v ...interface{}) *Query {
3030
q.whereStmt = append(q.whereStmt, stmt)
3131
q.whereArgs = append(q.whereArgs, v...)
32+
return q
33+
}
34+
35+
// WithWhere 携带条件
36+
func (q *Query) WithWhere(stmts []string, args []interface{}) *Query {
37+
q.whereStmt = append(q.whereStmt, stmts...)
38+
q.whereArgs = append(q.whereArgs, args...)
39+
return q
3240
}
3341

3442
// Limit 这周Limit
35-
func (q *Query) Limit(offset int64, limit uint) {
43+
func (q *Query) Limit(offset int64, limit uint) *Query {
3644
q.limitStmt = "LIMIT ?,? "
3745
q.limitArgs = append(q.limitArgs, offset, limit)
46+
return q
3847
}
3948

4049
// Desc todo
41-
func (q *Query) Desc(d string) {
50+
func (q *Query) Desc(d string) *Query {
4251
q.desc = fmt.Sprintf("ORDER BY %s DESC ", d)
52+
return q
4353
}
4454

4555
func (q *Query) whereBuild() string {

sqlbuilder/builder_test.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@ import (
1010
func TestQueryBuild(t *testing.T) {
1111
should := assert.New(t)
1212
q := sqlbuilder.NewQuery("SELECT * FROM t")
13-
q.Where("t.a = ? AND t.c = ? AND t.d LIKE ?", "one", "two", "three")
14-
q.Desc("t.create_at")
15-
q.Limit(0, 20)
16-
stmt, args := q.Build()
17-
should.Equal(stmt, "SELECT * FROM t WHERE t.a = ? AND t.c = ? AND t.d LIKE ? ORDER BY t.create_at DESC LIMIT ?,? ;")
13+
qstmt, args := q.Where("t.a = ? AND t.c = ? AND t.d LIKE ?", "one", "two", "three").Desc("t.create_at").Limit(0, 20).Build()
14+
should.Equal(qstmt, "SELECT * FROM t WHERE t.a = ? AND t.c = ? AND t.d LIKE ? ORDER BY t.create_at DESC LIMIT ?,? ;")
1815
should.Equal(args, []interface{}{"one", "two", "three", int64(0), uint(20)})
1916
should.Equal(q.WhereStmt(), []string{"t.a = ? AND t.c = ? AND t.d LIKE ?"})
2017
should.Equal(q.WhereArgs(), []interface{}{"one", "two", "three"})
18+
19+
c := sqlbuilder.NewQuery("SELECT COUNT(*) FROM t")
20+
cstmt, args := c.WithWhere(q.WhereStmt(), q.WhereArgs()).Build()
21+
should.Equal(cstmt, "SELECT COUNT(*) FROM t WHERE t.a = ? AND t.c = ? AND t.d LIKE ? ;")
2122
}

0 commit comments

Comments
 (0)