Skip to content

Commit

Permalink
Added supporte to choose the fields in the select stmt generation
Browse files Browse the repository at this point in the history
  • Loading branch information
flavianmissi committed Mar 26, 2012
1 parent 3653472 commit 84353c2
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
12 changes: 9 additions & 3 deletions sqlgen/sqlgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,17 @@ import (
"strings"
)

func Select(obj interface{}) string {
func Select(obj interface{}, args...[]string) string {
t := reflect.TypeOf(obj)
fieldNames := fieldNames(t)
var sql string

if len(args) != 0 {
sql = fmt.Sprintf("select %s from %s", strings.Join(args[0], ", "), t.Name())
} else {
fieldNames := fieldNames(t)
sql = fmt.Sprintf("select %s from %s", strings.Join(fieldNames, ", "), t.Name())
}

sql := fmt.Sprintf("select %s from %s", strings.Join(fieldNames, ", "), t.Name())
return strings.ToLower(sql)
}

Expand Down
12 changes: 11 additions & 1 deletion sqlgen/sqlgen_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func TestPrepraredFields(t *testing.T) {
}
}

func TestGenerateSelectFromStruct(t *testing.T) {
func TestGenerateSelectAllFieldsFromStruct(t *testing.T) {
var p Person
expected := "select id, name, age from person"
got := Select(p)
Expand All @@ -42,6 +42,16 @@ func TestGenerateSelectFromStruct(t *testing.T) {
}
}

func TestSelectOneFieldFromStruct(t *testing.T) {
var p Person
expected := "select name from person"
got := Select(p, []string{"name"})

if expected != got {
t.Errorf(`SELECT generation for %q. Was expecting "%s", got "%s".`, reflect.TypeOf(p), expected, got)
}
}

func TestGenerateInsertFromStruct(t *testing.T) {
var p Person
expected := "insert into person (id, name, age) values (?, ?, ?)"
Expand Down

0 comments on commit 84353c2

Please sign in to comment.