Add record to cache. BatchSave would flush them into Database when cache is max out
(slot interface{})
| 79 | |
| 80 | // Add record to cache. BatchSave would flush them into Database when cache is max out |
| 81 | func (c *BatchSave) Add(slot interface{}) errors.Error { |
| 82 | // type checking |
| 83 | if reflect.TypeOf(slot) != c.slotType { |
| 84 | return errors.Default.New("sub cache type mismatched") |
| 85 | } |
| 86 | if reflect.ValueOf(slot).Kind() != reflect.Ptr { |
| 87 | return errors.Default.New("slot is not a pointer") |
| 88 | } |
| 89 | if c.lastErr != nil { |
| 90 | return errors.Default.Wrap(c.lastErr, "add slot failed due to previous err") |
| 91 | } |
| 92 | stripZeroByte(slot) |
| 93 | // deduplication |
| 94 | key := getKeyValue(slot, c.primaryKey) |
| 95 | c.mutex.Lock() |
| 96 | defer c.mutex.Unlock() |
| 97 | if key != "" { |
| 98 | if index, ok := c.valueIndex[key]; !ok { |
| 99 | c.valueIndex[key] = c.current |
| 100 | } else { |
| 101 | c.slots.Index(index).Set(reflect.ValueOf(slot)) |
| 102 | return nil |
| 103 | } |
| 104 | } |
| 105 | c.slots.Index(c.current).Set(reflect.ValueOf(slot)) |
| 106 | c.current++ |
| 107 | // flush out into database if maxed out |
| 108 | if c.current == c.size { |
| 109 | return c.flushWithoutLocking() |
| 110 | } else if c.current%100 == 0 { |
| 111 | c.log.Debug("batch save current: %d", c.current) |
| 112 | } |
| 113 | return nil |
| 114 | } |
| 115 | |
| 116 | // Flush save cached records into database, even if cache is not maxed out |
| 117 | func (c *BatchSave) Flush() errors.Error { |
no test coverage detected