Created
September 2, 2015 05:04
-
-
Save film42/a932b30163586f75b10b to your computer and use it in GitHub Desktop.
This file contains 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 ( | |
"bytes" | |
"strconv" | |
) | |
//// | |
// Query Builder | |
// | |
type Query struct { | |
Clauses []string | |
Table string | |
} | |
func (q *Query) Find(id int64) *Query { | |
idAsString := strconv.Itoa(int(id)) | |
q.Clauses = append(q.Clauses, "WHERE 'id' = "+idAsString+"") | |
return q | |
} | |
func (q *Query) Limit(n int) *Query { | |
cardinalityAsString := strconv.Itoa(int(n)) | |
q.Clauses = append(q.Clauses, "LIMIT "+cardinalityAsString) | |
return q | |
} | |
func (q *Query) Where(column string, value string) *Query { | |
q.Clauses = append(q.Clauses, "WHERE '"+column+"' = '"+value+"'") | |
return q | |
} | |
func (q *Query) ToSql() string { | |
var sqlBuffer bytes.Buffer | |
sqlBuffer.WriteString("SELECT * FROM '" + q.Table + "'") | |
for index, clause := range q.Clauses { | |
// Check if it's an AND clause | |
if index > 0 { | |
sqlBuffer.WriteString(" AND") | |
} | |
sqlBuffer.WriteString(" " + clause) | |
} | |
return sqlBuffer.String() | |
} | |
//// | |
// Constructors | |
// | |
func Table(name string) *Query { | |
query := NewQuery() | |
query.Table = name | |
return query | |
} | |
func NewQuery() *Query { | |
return &Query{} | |
} |
This file contains 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 ( | |
"testing" | |
) | |
func TestLimitFunction(t *testing.T) { | |
sql := Table("products").Limit(44).ToSql() | |
if sql != "SELECT * FROM 'products' LIMIT 44" { | |
t.Error("Bad sql generated") | |
} | |
} | |
func TestFindFunction(t *testing.T) { | |
sql := Table("products").Find(123).ToSql() | |
if sql != "SELECT * FROM 'products' WHERE 'id' = 123" { | |
t.Error("Bad sql generated") | |
} | |
} | |
func TestTableFunction(t *testing.T) { | |
sql := Table("products").ToSql() | |
if sql != "SELECT * FROM 'products'" { | |
t.Error("Bad sql generated") | |
} | |
} | |
func TestWhereFunction(t *testing.T) { | |
sql := Table("products").Where("name", "T-shirt").ToSql() | |
if sql != "SELECT * FROM 'products' WHERE 'name' = 'T-shirt'" { | |
t.Error("Bad sql generated") | |
} | |
sql = Table("products").Where("name", "T-shirt").Where("me", "you").ToSql() | |
if sql != "SELECT * FROM 'products' WHERE 'name' = 'T-shirt' AND WHERE 'me' = 'you'" { | |
t.Error("Bad sql generated") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment