Add Limit, Offset

This commit is contained in:
Jinzhu 2020-03-04 23:56:42 +08:00
parent 9f7f4b430e
commit 0c34123796
2 changed files with 12 additions and 6 deletions

View File

@ -168,14 +168,16 @@ func (db *DB) Order(value interface{}) (tx *DB) {
} }
// Limit specify the number of records to be retrieved // 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 = db.getInstance()
tx.Statement.AddClause(clause.Limit{Limit: limit})
return return
} }
// Offset specify the number of records to skip before starting to return the records // 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 = db.getInstance()
tx.Statement.AddClause(clause.Limit{Offset: offset})
return return
} }

View File

@ -18,11 +18,11 @@ func (limit Limit) Build(builder Builder) {
if limit.Limit > 0 { if limit.Limit > 0 {
builder.Write("LIMIT ") builder.Write("LIMIT ")
builder.Write(strconv.Itoa(limit.Limit)) builder.Write(strconv.Itoa(limit.Limit))
}
if limit.Offset > 0 { if limit.Offset > 0 {
builder.Write(" OFFSET ") builder.Write(" OFFSET ")
builder.Write(strconv.Itoa(limit.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 v, ok := clause.Expression.(Limit); ok {
if limit.Limit == 0 && v.Limit > 0 { if limit.Limit == 0 && v.Limit > 0 {
limit.Limit = v.Limit limit.Limit = v.Limit
} else if limit.Limit < 0 {
limit.Limit = 0
} }
if limit.Offset == 0 && v.Offset > 0 { if limit.Offset == 0 && v.Offset > 0 {
limit.Offset = v.Offset limit.Offset = v.Offset
} else if limit.Offset < 0 {
limit.Offset = 0
} }
} }