From 32a996f738a6cf5817779f821c68949854bb7138 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 27 Oct 2013 11:38:05 +0800 Subject: [PATCH] Yay, Limit works --- orm.go | 10 +++++++--- orm_test.go | 9 +++++++++ sql.go | 14 +++++++++++--- 3 files changed, 27 insertions(+), 6 deletions(-) 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 {