Add method to do basic check for sql valid or not

This commit is contained in:
Jinzhu 2013-10-27 10:17:11 +08:00
parent dd719e4512
commit 80a7e6296d
3 changed files with 19 additions and 0 deletions

4
orm.go
View File

@ -63,6 +63,7 @@ func (s *Orm) Offset(value interface{}) *Orm {
}
func (s *Orm) Order(value string, reorder ...bool) *Orm {
defer s.validSql(s.orderStr)
if len(reorder) > 0 && reorder[0] {
s.orderStr = value
} else {
@ -76,12 +77,15 @@ func (s *Orm) Count() int64 {
}
func (s *Orm) Select(value interface{}) *Orm {
defer func() { s.validSql(s.selectStr) }()
switch value := value.(type) {
case string:
s.selectStr = value
default:
s.Error = errors.New("Can' understand the value of Select, Should be string")
}
return s
}

View File

@ -234,6 +234,12 @@ func TestSelect(t *testing.T) {
if user.Name != "3" {
t.Errorf("Should got Name = 3 when searching it, %+v", user.Id)
}
query := db.Where("name = ?", "3").Select("nam;e")
if query.Error == nil {
t.Errorf("Should got error with invalid select string")
}
debug(query.Error)
}
func TestPluck(t *testing.T) {

9
sql.go
View File

@ -4,9 +4,18 @@ import (
"errors"
"fmt"
"reflect"
"regexp"
"strings"
)
func (s *Orm) validSql(str string) (result bool) {
result = regexp.MustCompile("^\\s*[\\w][\\w\\s,.]*[\\w]\\s*$").MatchString(str)
if !result {
s.Error = errors.New(fmt.Sprintf("SQL is not valid, %s", str))
}
return
}
func (s *Orm) explain(value interface{}, operation string) *Orm {
s.Model(value)