info.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package storage
  2. import (
  3. "net"
  4. "time"
  5. )
  6. type EventInfo struct {
  7. Id int64
  8. Source string
  9. Ip net.IP
  10. ts time.Time
  11. }
  12. type EventInfoStorage struct {
  13. }
  14. func (eis EventInfoStorage) Table() string {
  15. return "eventinfo"
  16. }
  17. var EventInfoService EventInfoStorage = EventInfoStorage{}
  18. func EventInfoLoadFromId(id int64, storage Storage) (EventInfo, error) {
  19. var ei EventInfo
  20. var source string
  21. var ip string
  22. var ts int64
  23. sql := `
  24. SELECT source, ip, ts
  25. FROM eventinfo
  26. WHERE id = ?
  27. `
  28. err := storage.DB.QueryRow(sql, id).Scan(&source, &ip, &ts)
  29. if err != nil {
  30. ei = EventInfo{
  31. Id: id,
  32. Source: source,
  33. Ip: net.ParseIP(ip),
  34. ts: time.Unix(ts, 0),
  35. }
  36. }
  37. return ei, err
  38. }
  39. /**
  40. Save() persists an EventInfo to the storage.
  41. - if it already has an non-zero ID, Save() will attempt to update it, and set the Id in the event object
  42. - otherwise it will attempt to insert it
  43. */
  44. func (ei *EventInfo) Save(s Storage) error {
  45. var err error
  46. ip := ei.Ip.String()
  47. ts := ei.ts.Unix()
  48. if ei.Id == 0 {
  49. sql := `
  50. INSERT INTO eventinfo(source, ip, ts)
  51. VALUES (?, ?, ?)
  52. `
  53. result, err := s.DB.Exec(sql, ei.Source, ip, ts)
  54. if err == nil {
  55. ei.Id, err = result.LastInsertId()
  56. }
  57. } else {
  58. sql := `
  59. UPDATE eventinfo
  60. SET source = ?, ip = ?, ts = ?
  61. WHERE id = ?
  62. `
  63. _, err = s.DB.Exec(sql, ei.Source, ip, ts, ei.Id)
  64. }
  65. return err
  66. }