forked from mirror/gorm
Add method to do basic check for sql valid or not
This commit is contained in:
parent
dd719e4512
commit
80a7e6296d
4
orm.go
4
orm.go
|
@ -63,6 +63,7 @@ func (s *Orm) Offset(value interface{}) *Orm {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Orm) Order(value string, reorder ...bool) *Orm {
|
func (s *Orm) Order(value string, reorder ...bool) *Orm {
|
||||||
|
defer s.validSql(s.orderStr)
|
||||||
if len(reorder) > 0 && reorder[0] {
|
if len(reorder) > 0 && reorder[0] {
|
||||||
s.orderStr = value
|
s.orderStr = value
|
||||||
} else {
|
} else {
|
||||||
|
@ -76,12 +77,15 @@ func (s *Orm) Count() int64 {
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Orm) Select(value interface{}) *Orm {
|
func (s *Orm) Select(value interface{}) *Orm {
|
||||||
|
defer func() { s.validSql(s.selectStr) }()
|
||||||
|
|
||||||
switch value := value.(type) {
|
switch value := value.(type) {
|
||||||
case string:
|
case string:
|
||||||
s.selectStr = value
|
s.selectStr = value
|
||||||
default:
|
default:
|
||||||
s.Error = errors.New("Can' understand the value of Select, Should be string")
|
s.Error = errors.New("Can' understand the value of Select, Should be string")
|
||||||
}
|
}
|
||||||
|
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -234,6 +234,12 @@ func TestSelect(t *testing.T) {
|
||||||
if user.Name != "3" {
|
if user.Name != "3" {
|
||||||
t.Errorf("Should got Name = 3 when searching it, %+v", user.Id)
|
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) {
|
func TestPluck(t *testing.T) {
|
||||||
|
|
9
sql.go
9
sql.go
|
@ -4,9 +4,18 @@ import (
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
|
"regexp"
|
||||||
"strings"
|
"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 {
|
func (s *Orm) explain(value interface{}, operation string) *Orm {
|
||||||
s.Model(value)
|
s.Model(value)
|
||||||
|
|
||||||
|
|
Loading…
Reference in New Issue