12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- package database
- import (
- "database/sql"
- "database/sql/driver"
- "encoding/json"
- "fmt"
- "gorm.io/gorm"
- "reflect"
- )
- type NullTime sql.NullTime
- func (n *NullTime) Scan(value any) error {
- return (*sql.NullTime)(n).Scan(value)
- }
- func (n NullTime) Value() (driver.Value, error) {
- if !n.Valid {
- return nil, nil
- }
- return n.Time, nil
- }
- func (n NullTime) MarshalJSON() ([]byte, error) {
- if n.Valid {
- return json.Marshal(n.Time)
- }
- return json.Marshal(nil)
- }
- func (n *NullTime) UnmarshalJSON(b []byte) error {
- if string(b) == "null" {
- n.Valid = false
- return nil
- }
- err := json.Unmarshal(b, &n.Time)
- if err == nil {
- n.Valid = true
- }
- return err
- }
- /*-----------------------------------------------------------*/
- type PaginateList struct {
- Page int64 `json:"page"`
- Size int64 `json:"size"`
- Total int64 `json:"total"`
- List any `json:"list"`
- }
- func Paginate(db *gorm.DB, model any, page, size int64) (*PaginateList, error) {
- ptr := reflect.ValueOf(model)
- if ptr.Kind() != reflect.Ptr {
- return nil, fmt.Errorf("model must be pointer")
- }
- var total int64
- err := db.Model(model).Count(&total).Error
- if err != nil {
- return &PaginateList{
- Page: page,
- Size: size,
- Total: total,
- List: make([]any, 0),
- }, err
- }
- offset := size * (page - 1)
- err = db.Limit(int(size)).Offset(int(offset)).Find(model).Error
- if err != nil {
- return &PaginateList{
- Page: page,
- Size: size,
- Total: total,
- List: make([]any, 0),
- }, err
- }
- return &PaginateList{
- Page: page,
- Size: size,
- Total: total,
- List: model,
- }, nil
- }
|