Skip to content

Instantly share code, notes, and snippets.

@dimiro1
Created May 17, 2017 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dimiro1/22a1a309ea78b39fe4c323b143bf5d0b to your computer and use it in GitHub Desktop.
Save dimiro1/22a1a309ea78b39fe4c323b143bf5d0b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strings"
)
type Clause interface {
By() string
}
type ClauseFunc func() string
func (c ClauseFunc) By() string {
return c()
}
func By(field string, value interface{}) Clause {
return ClauseFunc(func() string {
return fmt.Sprintf("%s = %s", field, value)
})
}
func ByID(value interface{}) Clause {
return By("id", value)
}
func And(clauses ...Clause) Clause {
return ClauseFunc(func() string {
where := []string{}
for _, clause := range clauses {
where = append(where, clause.By())
}
return strings.Join(where, " AND ")
})
}
func Select(clauses ...Clause) string {
query := "SELECT * FROM blah WHERE "
where := []string{}
for _, clause := range clauses {
where = append(where, clause.By())
}
return query + strings.Join(where, " AND ")
}
func main() {
fmt.Println(
Select(
And(
ByID(10),
By("name", "Claudemiro"),
),
),
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment