info.go 1.4 KB

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