1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- package storage
- import (
- "net"
- "time"
- )
- type EventInfo struct {
- Id int64
- Source string
- Ip net.IP
- ts time.Time
- }
- type EventInfoStorageController struct {
- controller StorageControllerInterface
- }
- func (eis EventInfoStorage) Table() string {
- return "eventinfo"
- }
- var EventInfoService EventInfoStorage = EventInfoStorage{}
- func (sc EventInfoStorageController) EventInfoLoadFromId(id int64) (EventInfo, error) {
- var ei EventInfo
- var source string
- var ip string
- var ts int64
- sql := `
- SELECT source, ip, ts
- FROM eventinfo
- WHERE id = ?
- `
- sc.controller.Table()
- err := sc.controller.Storage().DB.QueryRow(sql, id).Scan(&source, &ip, &ts)
- if err != nil {
- ei = EventInfo{
- Id: id,
- Source: source,
- Ip: net.ParseIP(ip),
- ts: time.Unix(ts, 0),
- }
- }
- return ei, err
- }
- /**
- Save() persists an EventInfo to the storage.
- - if it already has an non-zero ID, Save() will attempt to update it, and set the Id in the event object
- - otherwise it will attempt to insert it
- */
- func (ei *EventInfo) Save(s Storage) error {
- var err error
- ip := ei.Ip.String()
- ts := ei.ts.Unix()
- if ei.Id == 0 {
- sql := `
- INSERT INTO eventinfo(source, ip, ts)
- VALUES (?, ?, ?)
- `
- result, err := s.DB.Exec(sql, ei.Source, ip, ts)
- if err == nil {
- ei.Id, err = result.LastInsertId()
- }
- } else {
- sql := `
- UPDATE eventinfo
- SET source = ?, ip = ?, ts = ?
- WHERE id = ?
- `
- _, err = s.DB.Exec(sql, ei.Source, ip, ts, ei.Id)
- }
- return err
- }
|