diff --git a/orm.go b/orm.go index 21a7c892..ab526696 100644 --- a/orm.go +++ b/orm.go @@ -22,7 +22,7 @@ type Orm struct { selectStr string orderStrs []string offsetInt int - limitInt int + limitStr string operation string } @@ -41,9 +41,13 @@ func (s *Orm) Where(querystring interface{}, args ...interface{}) *Orm { func (s *Orm) Limit(value interface{}) *Orm { switch value := value.(type) { case string: - s.limitInt, _ = strconv.Atoi(value) + s.limitStr = value case int: - s.limitInt = value + if value < 0 { + s.limitStr = "" + } else { + s.limitStr = strconv.Itoa(value) + } default: s.Error = errors.New("Can' understand the value of Limit, Should be int") } diff --git a/orm_test.go b/orm_test.go index fc07d219..5774507c 100644 --- a/orm_test.go +++ b/orm_test.go @@ -255,3 +255,12 @@ func TestOrderAndPluck(t *testing.T) { t.Errorf("Should be ordered correctly with multiple orders") } } + +func TestLimit(t *testing.T) { + var users1, users2, users3 []User + db.Order("age desc").Limit(3).Find(&users1).Limit(5).Find(&users2).Limit(-1).Find(&users3) + + if !(len(users1) == 3 && len(users2) == 5 && len(users3) > 5) { + t.Errorf("Limit should works perfectly") + } +} diff --git a/sql.go b/sql.go index 4b82ee21..36321155 100644 --- a/sql.go +++ b/sql.go @@ -215,16 +215,24 @@ func (s *Orm) selectSql() string { } } -func (s *Orm) orderSql() (str string) { +func (s *Orm) orderSql() string { if len(s.orderStrs) == 0 { - return + return "" } else { return " ORDER BY " + strings.Join(s.orderStrs, ",") } } +func (s *Orm) limitSql() string { + if len(s.limitStr) == 0 { + return "" + } else { + return " LIMIT " + s.limitStr + } +} + func (s *Orm) combinedSql() string { - return s.whereSql() + s.orderSql() + return s.whereSql() + s.orderSql() + s.limitSql() } func (s *Orm) addToVars(value interface{}) string {