tool.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package database
  2. import (
  3. "database/sql"
  4. "database/sql/driver"
  5. "encoding/json"
  6. "fmt"
  7. "gorm.io/gorm"
  8. "reflect"
  9. )
  10. type NullTime sql.NullTime
  11. func (n *NullTime) Scan(value any) error {
  12. return (*sql.NullTime)(n).Scan(value)
  13. }
  14. func (n NullTime) Value() (driver.Value, error) {
  15. if !n.Valid {
  16. return nil, nil
  17. }
  18. return n.Time, nil
  19. }
  20. func (n NullTime) MarshalJSON() ([]byte, error) {
  21. if n.Valid {
  22. return json.Marshal(n.Time)
  23. }
  24. return json.Marshal(nil)
  25. }
  26. func (n *NullTime) UnmarshalJSON(b []byte) error {
  27. if string(b) == "null" {
  28. n.Valid = false
  29. return nil
  30. }
  31. err := json.Unmarshal(b, &n.Time)
  32. if err == nil {
  33. n.Valid = true
  34. }
  35. return err
  36. }
  37. /*-----------------------------------------------------------*/
  38. type PaginateList struct {
  39. Page int64 `json:"page"`
  40. Size int64 `json:"size"`
  41. Total int64 `json:"total"`
  42. List any `json:"list"`
  43. }
  44. func Paginate(db *gorm.DB, model any, page, size int64) (*PaginateList, error) {
  45. ptr := reflect.ValueOf(model)
  46. if ptr.Kind() != reflect.Ptr {
  47. return nil, fmt.Errorf("model must be pointer")
  48. }
  49. var total int64
  50. err := db.Model(model).Count(&total).Error
  51. if err != nil {
  52. return &PaginateList{
  53. Page: page,
  54. Size: size,
  55. Total: total,
  56. List: make([]any, 0),
  57. }, err
  58. }
  59. offset := size * (page - 1)
  60. err = db.Limit(int(size)).Offset(int(offset)).Find(model).Error
  61. if err != nil {
  62. return &PaginateList{
  63. Page: page,
  64. Size: size,
  65. Total: total,
  66. List: make([]any, 0),
  67. }, err
  68. }
  69. return &PaginateList{
  70. Page: page,
  71. Size: size,
  72. Total: total,
  73. List: model,
  74. }, nil
  75. }