-
Notifications
You must be signed in to change notification settings - Fork 0
/
metadata.go
88 lines (78 loc) · 1.99 KB
/
metadata.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package bolt
import (
"encoding/json"
"fmt"
"github.com/boltdb/bolt"
"github.com/sp0x/torrentd/storage/indexing"
"os"
)
type Metadata struct {
Indexes map[string]indexing.IndexMetadata `json:"indexes"`
}
func (b *BoltStorage) hasNamespace() bool {
return b.rootBucket != nil
}
func (b *BoltStorage) setupMetadata() error {
return b.Database.Update(func(tx *bolt.Tx) error {
internalBucket, err := b.assertBucket(tx, internalBucketName)
if err != nil {
return err
}
if b.hasNamespace() {
nsBucket, err := b.assertNamespaceBucket(tx, namespaceResultsBucketName)
if err != nil {
return err
}
b.loadMetadata(nsBucket)
}
b.loadGlobalMetadata(internalBucket)
return nil
})
}
func (b *BoltStorage) saveMetadata(bucket *bolt.Bucket) {
metadataBytes, _ := json.Marshal(b.metadata)
_ = bucket.Put([]byte(metaBucketName), metadataBytes)
}
func (b *BoltStorage) loadMetadata(bucket *bolt.Bucket) {
metadataBytes := bucket.Get([]byte(metaBucketName))
metadata := &Metadata{}
if metadataBytes != nil {
err := json.Unmarshal(metadataBytes, metadata)
if err != nil {
fmt.Printf("couldn't load metadata: %v", err)
os.Exit(1)
}
}
if b.hasNamespace() {
b.metadata = metadata
}
}
func (b *BoltStorage) GetIndexes() map[string]indexing.IndexMetadata {
if b.metadata == nil {
return nil
}
return b.metadata.Indexes
}
func (b *BoltStorage) HasIndex(meta *indexing.IndexMetadata) bool {
_, found := b.metadata.Indexes[meta.Name]
return found
}
func (b *BoltStorage) HasIndexWithName(name string) bool {
_, found := b.metadata.Indexes[name]
return found
}
func (m *Metadata) AddIndex(name string, location string, isUnique bool) bool {
if m.Indexes == nil {
m.Indexes = make(map[string]indexing.IndexMetadata)
}
existingIx, exists := m.Indexes[name]
if exists && existingIx.Location == location && existingIx.Unique == isUnique {
return false
}
m.Indexes[name] = indexing.IndexMetadata{
Name: name,
Unique: isUnique,
Location: location,
}
return true
}