From 3c03b6e5271973b6db4543926773b237f5fc4540 Mon Sep 17 00:00:00 2001 From: SmallTianTian Date: Thu, 2 Jul 2020 18:14:33 +0800 Subject: [PATCH] fix no limit no offset. (#3101) * fix no limit no offset. * add test for playground. --- clause/limit.go | 10 ++++++---- clause/limit_test.go | 14 +++++++++++++- tests/query_test.go | 6 ++++++ 3 files changed, 25 insertions(+), 5 deletions(-) diff --git a/clause/limit.go b/clause/limit.go index ba5cf6c4..1946820d 100644 --- a/clause/limit.go +++ b/clause/limit.go @@ -18,11 +18,13 @@ func (limit Limit) Build(builder Builder) { if limit.Limit > 0 { builder.WriteString("LIMIT ") builder.WriteString(strconv.Itoa(limit.Limit)) - - if limit.Offset > 0 { - builder.WriteString(" OFFSET ") - builder.WriteString(strconv.Itoa(limit.Offset)) + } + if limit.Offset > 0 { + if limit.Limit > 0 { + builder.WriteString(" ") } + builder.WriteString("OFFSET ") + builder.WriteString(strconv.Itoa(limit.Offset)) } } diff --git a/clause/limit_test.go b/clause/limit_test.go index 80317dc3..c26294aa 100644 --- a/clause/limit_test.go +++ b/clause/limit_test.go @@ -20,6 +20,18 @@ func TestLimit(t *testing.T) { }}, "SELECT * FROM `users` LIMIT 10 OFFSET 20", nil, }, + { + []clause.Interface{clause.Select{}, clause.From{}, clause.Limit{Offset: 20}}, + "SELECT * FROM `users` OFFSET 20", nil, + }, + { + []clause.Interface{clause.Select{}, clause.From{}, clause.Limit{Offset: 20}, clause.Limit{Offset: 30}}, + "SELECT * FROM `users` OFFSET 30", nil, + }, + { + []clause.Interface{clause.Select{}, clause.From{}, clause.Limit{Offset: 20}, clause.Limit{Limit: 10}}, + "SELECT * FROM `users` LIMIT 10 OFFSET 20", nil, + }, { []clause.Interface{clause.Select{}, clause.From{}, clause.Limit{Limit: 10, Offset: 20}, clause.Limit{Offset: 30}}, "SELECT * FROM `users` LIMIT 10 OFFSET 30", nil, @@ -30,7 +42,7 @@ func TestLimit(t *testing.T) { }, { []clause.Interface{clause.Select{}, clause.From{}, clause.Limit{Limit: 10, Offset: 20}, clause.Limit{Offset: 30}, clause.Limit{Limit: -10}}, - "SELECT * FROM `users`", nil, + "SELECT * FROM `users` OFFSET 30", nil, }, { []clause.Interface{clause.Select{}, clause.From{}, clause.Limit{Limit: 10, Offset: 20}, clause.Limit{Offset: 30}, clause.Limit{Limit: 50}}, diff --git a/tests/query_test.go b/tests/query_test.go index 7973fd51..594fc268 100644 --- a/tests/query_test.go +++ b/tests/query_test.go @@ -381,6 +381,12 @@ func TestOffset(t *testing.T) { if (len(users1) != len(users4)) || (len(users1)-len(users2) != 3) || (len(users1)-len(users3) != 5) { t.Errorf("Offset should work") } + DB.Where("name like ?", "OffsetUser%").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 work without limit.") + } + } func TestSearchWithMap(t *testing.T) {