log.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package model
  2. import (
  3. "fmt"
  4. "github.com/jaryhe/gopkgs/logger"
  5. "github.com/jinzhu/gorm"
  6. "go.uber.org/zap"
  7. "time"
  8. )
  9. type TLog struct {
  10. ID int64 `gorm:"column:id" json:"id"`
  11. Module string `gorm:"column:module" json:"module"`
  12. Action string `gorm:"column:action" json:"action"`
  13. Origin string `gorm:"column:origin" json:"origin"`
  14. Target string `gorm:"column:target" json:"target"`
  15. Username string `gorm:"column:username" json:"username"`
  16. Uid int64 `gorm:"column:uid" json:"uid"`
  17. CreatedAt time.Time `gorm:"column:created_at" json:"created_at"`
  18. table string `json:"table"`
  19. }
  20. func (p *TLog) TableName() string {
  21. return p.table
  22. }
  23. func NewTLog(database string) *TLog {
  24. return &TLog{table: fmt.Sprintf("%s.%s", database, "t_log")}
  25. }
  26. func (p *TLog) CreateTable(db *gorm.DB) error {
  27. err := db.CreateTable(p).Error
  28. if err != nil {
  29. logger.Error("mysql",
  30. zap.String("sql", fmt.Sprintf("%+v", db.QueryExpr())),
  31. zap.String("error", err.Error()))
  32. }
  33. return nil
  34. }
  35. func (p *TLog) Insert(db *gorm.DB) error {
  36. err := db.Table(p.TableName()).Create(p).Error
  37. if err != nil {
  38. logger.Error("mysql",
  39. zap.String("sql", "insert into "+p.TableName()),
  40. zap.String("error", err.Error()))
  41. }
  42. return err
  43. }
  44. func (p *TLog) Count(db *gorm.DB, where map[string]interface{}, or map[string]interface{}) (int64, error) {
  45. cond, val, err := whereBuildAndOr(where, or)
  46. if err != nil {
  47. if err != nil {
  48. logger.Error("mysql",
  49. zap.String("sql", "select count from "+p.TableName()),
  50. zap.String("error", err.Error()))
  51. }
  52. return 0, err
  53. }
  54. ret := int64(0)
  55. err = db.Table(p.TableName()).Where(cond, val...).Count(&ret).Error
  56. return ret, err
  57. }
  58. func (p *TLog) List(db *gorm.DB, where map[string]interface{}, or map[string]interface{}, limit, offset int64) (list []TLog, err error) {
  59. cond, val, err := whereBuildAndOr(where, or)
  60. if err != nil {
  61. return list, err
  62. }
  63. result := db.Table(p.TableName()).Where(cond, val...).Limit(limit).Offset(offset).Find(&list)
  64. if result.Error != nil {
  65. logger.Error("mysql",
  66. zap.String("sql", "select * from "+p.TableName()),
  67. zap.String("error", result.Error.Error()))
  68. }
  69. return list, result.Error
  70. }