Yay, Offset works

This commit is contained in:
Jinzhu 2013-10-27 11:44:47 +08:00
parent 32a996f738
commit 7948705181
4 changed files with 25 additions and 5 deletions

View File

@ -3,7 +3,6 @@
Yet Another ORM library for Go, aims for developer friendly
## TODO
* Limit
* Offset
* Or query
* Not query

10
orm.go
View File

@ -21,7 +21,7 @@ type Orm struct {
whereClause []map[string]interface{}
selectStr string
orderStrs []string
offsetInt int
offsetStr string
limitStr string
operation string
}
@ -57,9 +57,13 @@ func (s *Orm) Limit(value interface{}) *Orm {
func (s *Orm) Offset(value interface{}) *Orm {
switch value := value.(type) {
case string:
s.offsetInt, _ = strconv.Atoi(value)
s.offsetStr = value
case int:
s.offsetInt = value
if value < 0 {
s.offsetStr = ""
} else {
s.offsetStr = strconv.Itoa(value)
}
default:
s.Error = errors.New("Can' understand the value of Offset, Should be int")
}

View File

@ -264,3 +264,12 @@ func TestLimit(t *testing.T) {
t.Errorf("Limit should works perfectly")
}
}
func TestOffset(t *testing.T) {
var users1, users2, users3, users4 []User
db.Order("age desc").Find(&users1).Offset(3).Find(&users2).Offset(5).Find(&users3).Offset(-1).Find(&users4)
if !((len(users1) == len(users4)) && (len(users1)-len(users2) == 3) && (len(users1)-len(users3) == 5)) {
t.Errorf("Offset should works perfectly")
}
}

10
sql.go
View File

@ -231,8 +231,16 @@ func (s *Orm) limitSql() string {
}
}
func (s *Orm) offsetSql() string {
if len(s.offsetStr) == 0 {
return ""
} else {
return " OFFSET " + s.offsetStr
}
}
func (s *Orm) combinedSql() string {
return s.whereSql() + s.orderSql() + s.limitSql()
return s.whereSql() + s.orderSql() + s.limitSql() + s.offsetSql()
}
func (s *Orm) addToVars(value interface{}) string {