Created
May 17, 2017 13:58
-
-
Save dimiro1/22a1a309ea78b39fe4c323b143bf5d0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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