forked from nickdu2009/pkg
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
blackroot
committed
Jan 11, 2021
1 parent
b0155a1
commit 041cd60
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package xmysql | ||
|
||
import "github.com/jinzhu/gorm" | ||
|
||
type QueryOption struct { | ||
Skip uint | ||
Limit uint | ||
Order []string | ||
} | ||
|
||
type QueryOptFunc func(*QueryOption) | ||
|
||
func ApplyQueryOpts(db *gorm.DB, opts ...QueryOptFunc) *gorm.DB { | ||
queryOption := &QueryOption{} | ||
for _, opt := range opts { | ||
opt(queryOption) | ||
} | ||
|
||
for _, order := range queryOption.Order { | ||
db = db.Order(order) | ||
} | ||
|
||
if queryOption.Limit != 0 { | ||
db = db.Limit(queryOption.Limit) | ||
} | ||
|
||
if queryOption.Skip != 0 { | ||
db = db.Offset(queryOption.Skip) | ||
} | ||
return db | ||
} | ||
|
||
func Skip(skip uint) QueryOptFunc { | ||
return func(option *QueryOption) { | ||
option.Skip = skip | ||
} | ||
} | ||
|
||
func Limit(limit uint) QueryOptFunc { | ||
return func(option *QueryOption) { | ||
option.Limit = limit | ||
} | ||
} | ||
|
||
func Order(order ...string) QueryOptFunc { | ||
return func(option *QueryOption) { | ||
option.Order = append(option.Order, order...) | ||
} | ||
} |