Skip to content

Commit

Permalink
limit句、offset句追加
Browse files Browse the repository at this point in the history
  • Loading branch information
mazrean committed Aug 1, 2020
1 parent f59b7c7 commit 8f75cd3
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 2 deletions.
2 changes: 1 addition & 1 deletion sample/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func main() {

fmt.Printf("%+v\n", user)

users, err := db.Users().Select()
users, err := db.Users().Limit(2).Offset(1).Select()
if err != nil {
panic(err)
}
Expand Down
2 changes: 1 addition & 1 deletion statik/statik.go

Large diffs are not rendered by default.

23 changes: 23 additions & 0 deletions template/_select.tpl
Original file line number Diff line number Diff line change
@@ -1,4 +1,16 @@
{{define "select"}}
func (q *{{.Name.UpperCamel}}Query) Limit(limit int) *{{.Name.UpperCamel}}Query {
q.limit = limit
return q
}

func (q *{{.Name.UpperCamel}}Query) Offset(offset int) *{{.Name.UpperCamel}}Query {
q.offset = offset
return q
}

func (q *{{.Name.UpperCamel}}Query) Find() (*{{.Name.UpperCamel}}Table,error) {
whereMap := q.createWhereMap()
whereQuery, whereArgs := q.whereStruct.Where(whereMap)
Expand Down Expand Up @@ -44,8 +56,19 @@ func (q *{{.Name.UpperCamel}}Query) Select() ([]*{{.Name.UpperCamel}}Table,error
if len(whereArgs) != 0 {
args = append(args, whereArgs...)
}

query := fmt.Sprintf("SELECT * FROM {{.Name.Snake}} %s", whereQuery)

if q.limit != 0 {
query += " LIMIT ?"
args = append(args, q.limit)
}

if q.offset != 0 {
query += " OFFSET ?"
args = append(args, q.offset)
}

rows, err := q.db.Query(query, args...)
if err != nil {
return nil, fmt.Errorf("Execute Query Error: %w", err)
Expand Down
2 changes: 2 additions & 0 deletions template/queries.go.tpl
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ type {{.Name.UpperCamel}}Table struct {
type {{.Name.UpperCamel}}Query struct {
db *sql.DB
whereStruct *query.Where
limit int
offset int
table {{.Name.UpperCamel}}
}

Expand Down

0 comments on commit 8f75cd3

Please sign in to comment.