From 7948705181040f108f8cc34af50047e8a39b70a0 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sun, 27 Oct 2013 11:44:47 +0800 Subject: [PATCH] Yay, Offset works --- README.md | 1 - orm.go | 10 +++++++--- orm_test.go | 9 +++++++++ sql.go | 10 +++++++++- 4 files changed, 25 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 16e6f275..a98f3421 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,6 @@ Yet Another ORM library for Go, aims for developer friendly ## TODO -* Limit * Offset * Or query * Not query diff --git a/orm.go b/orm.go index ab526696..2ad238bc 100644 --- a/orm.go +++ b/orm.go @@ -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") } diff --git a/orm_test.go b/orm_test.go index 5774507c..21d79620 100644 --- a/orm_test.go +++ b/orm_test.go @@ -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") + } +} diff --git a/sql.go b/sql.go index 36321155..9ee87c6b 100644 --- a/sql.go +++ b/sql.go @@ -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 {