Skip to content

Commit

Permalink
Add Stmt.In(args...) method
Browse files Browse the repository at this point in the history
  • Loading branch information
leporo committed Sep 6, 2019
1 parent 7de70d2 commit 6bb7952
Show file tree
Hide file tree
Showing 3 changed files with 41 additions and 3 deletions.
3 changes: 1 addition & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,5 @@ language: go

go:
- 1.11
# Enable when 1.13 is out
# - 1.12
- 1.12
- master
13 changes: 13 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,3 +254,16 @@ func ExampleStmt_QueryRowAndClose() {
panic(err)
}
}

func ExampleStmt_In() {
q := sqlf.From("tasks").
Select("id, status").
Where("status").In("new", "pending", "wip")
fmt.Println(q.String())
fmt.Println(q.Args())
q.Close()

// Output:
// SELECT id, status FROM tasks WHERE status IN (?,?,?)
// [new pending wip]
}
28 changes: 27 additions & 1 deletion stmt.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,28 @@ func (q *Stmt) Where(expr string, args ...interface{}) *Stmt {
return q
}

/*
In adds IN expression to the current filter.
In method must be called after a Where method call.
*/
func (q *Stmt) In(args ...interface{}) *Stmt {
buf := bytebufferpool.Get()
buf.WriteString("IN (")
l := len(args) - 1
for i := range args {
if i < l {
buf.Write(placeholderComma)
} else {
buf.Write(placeholder)
}
}
buf.WriteString(")")
q.addChunk(posWhere, "", bufToString(&buf.B), args, " ")
bytebufferpool.Put(buf)
return q
}

// OrderBy adds the ORDER BY clause to SELECT statement
func (q *Stmt) OrderBy(expr ...string) *Stmt {
q.addChunk(posOrderBy, "ORDER BY", strings.Join(expr, ", "), nil, ", ")
Expand Down Expand Up @@ -627,7 +649,11 @@ loop:
return index
}

var space = []byte{' '}
var (
space = []byte{' '}
placeholder = []byte{'?'}
placeholderComma = []byte{'?', ','}
)

const (
_ = iota
Expand Down

0 comments on commit 6bb7952

Please sign in to comment.