From 0c34123796a056335e9020f7db97c514f3d1e87f Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Wed, 4 Mar 2020 23:56:42 +0800 Subject: [PATCH] Add Limit, Offset --- chainable_api.go | 6 ++++-- clause/limit.go | 12 ++++++++---- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/chainable_api.go b/chainable_api.go index 770b2236..49f260d3 100644 --- a/chainable_api.go +++ b/chainable_api.go @@ -168,14 +168,16 @@ func (db *DB) Order(value interface{}) (tx *DB) { } // Limit specify the number of records to be retrieved -func (db *DB) Limit(limit int64) (tx *DB) { +func (db *DB) Limit(limit int) (tx *DB) { tx = db.getInstance() + tx.Statement.AddClause(clause.Limit{Limit: limit}) return } // Offset specify the number of records to skip before starting to return the records -func (db *DB) Offset(offset int64) (tx *DB) { +func (db *DB) Offset(offset int) (tx *DB) { tx = db.getInstance() + tx.Statement.AddClause(clause.Limit{Offset: offset}) return } diff --git a/clause/limit.go b/clause/limit.go index 7b16f339..7775e6bf 100644 --- a/clause/limit.go +++ b/clause/limit.go @@ -18,11 +18,11 @@ func (limit Limit) Build(builder Builder) { if limit.Limit > 0 { builder.Write("LIMIT ") builder.Write(strconv.Itoa(limit.Limit)) + } - if limit.Offset > 0 { - builder.Write(" OFFSET ") - builder.Write(strconv.Itoa(limit.Offset)) - } + if limit.Offset > 0 { + builder.Write(" OFFSET ") + builder.Write(strconv.Itoa(limit.Offset)) } } @@ -33,10 +33,14 @@ func (limit Limit) MergeClause(clause *Clause) { if v, ok := clause.Expression.(Limit); ok { if limit.Limit == 0 && v.Limit > 0 { limit.Limit = v.Limit + } else if limit.Limit < 0 { + limit.Limit = 0 } if limit.Offset == 0 && v.Offset > 0 { limit.Offset = v.Offset + } else if limit.Offset < 0 { + limit.Offset = 0 } }