1package deb
2
3import (
4	"bytes"
5
6	"github.com/aptly-dev/aptly/aptly"
7	"github.com/aptly-dev/aptly/database"
8	"github.com/aptly-dev/aptly/utils"
9	"github.com/ugorji/go/codec"
10)
11
12// ChecksumCollection does management of ChecksumInfo in DB
13type ChecksumCollection struct {
14	db          database.Storage
15	codecHandle *codec.MsgpackHandle
16}
17
18// NewChecksumCollection creates new ChecksumCollection and binds it to database
19func NewChecksumCollection(db database.Storage) *ChecksumCollection {
20	return &ChecksumCollection{
21		db:          db,
22		codecHandle: &codec.MsgpackHandle{},
23	}
24}
25
26func (collection *ChecksumCollection) dbKey(path string) []byte {
27	return []byte("C" + path)
28}
29
30// Get finds checksums in DB by path
31func (collection *ChecksumCollection) Get(path string) (*utils.ChecksumInfo, error) {
32	encoded, err := collection.db.Get(collection.dbKey(path))
33	if err != nil {
34		if err == database.ErrNotFound {
35			return nil, nil
36		}
37		return nil, err
38	}
39
40	c := &utils.ChecksumInfo{}
41
42	decoder := codec.NewDecoderBytes(encoded, collection.codecHandle)
43	err = decoder.Decode(c)
44	if err != nil {
45		return nil, err
46	}
47
48	return c, nil
49}
50
51// Update adds or updates information about checksum in DB
52func (collection *ChecksumCollection) Update(path string, c *utils.ChecksumInfo) error {
53	var encodeBuffer bytes.Buffer
54
55	encoder := codec.NewEncoder(&encodeBuffer, collection.codecHandle)
56	err := encoder.Encode(c)
57	if err != nil {
58		return err
59	}
60
61	return collection.db.Put(collection.dbKey(path), encodeBuffer.Bytes())
62}
63
64// Check interface
65var (
66	_ aptly.ChecksumStorage = &ChecksumCollection{}
67)
68