-
Notifications
You must be signed in to change notification settings - Fork 0
/
mongoDB-antipode.go
98 lines (75 loc) · 2.36 KB
/
mongoDB-antipode.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
89
90
91
92
93
94
95
96
97
98
package antipode
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type MongoDB struct {
clientOptions *options.ClientOptions
database string
collection string
}
type Document struct {
Key string `bson:"key"`
Value AntiObj `bson:"value"`
}
func CreateMongoDB(host string, port string, database string, collection string) MongoDB {
return MongoDB{options.Client().ApplyURI("mongodb://" + host + ":" + port),
database,
collection,
}
}
// devo verificar primeiro se já existe essa key? E caso exista fazer update?
// falta fechar a conecção
func (m MongoDB) write(ctx context.Context, key string, obj AntiObj) error {
client, err := mongo.Connect(ctx, m.clientOptions)
if err != nil {
return err
}
mongoObj := Document{key, obj}
fmt.Println("key: ", key)
_, err = client.Database(m.database).Collection(m.collection).InsertOne(ctx, mongoObj)
return err
}
// posso assumir que não há mais do que um objeto com a mesma key?
func (m MongoDB) read(ctx context.Context, key string) (AntiObj, error) {
client, err := mongo.Connect(ctx, m.clientOptions)
if err != nil {
return AntiObj{}, err
}
fmt.Println("key read: ", key)
filter := bson.D{{"key", key}}
var result Document
err = client.Database(m.database).Collection(m.collection).FindOne(context.Background(), filter).Decode(&result)
return result.Value, err
}
func (m MongoDB) barrier(ctx context.Context, lineage []WriteIdentifier, datastoreID string) error {
client, err := mongo.Connect(ctx, m.clientOptions)
if err != nil {
return err
}
for _, writeIdentifier := range lineage {
if writeIdentifier.Dtstid == datastoreID {
for {
filter := bson.D{{"key", writeIdentifier.Key}}
var result Document
err = client.Database(m.database).Collection(m.collection).FindOne(context.Background(), filter).Decode(&result)
if !errors.Is(err, mongo.ErrNoDocuments) && err != nil {
return err
} else if errors.Is(err, mongo.ErrNoDocuments) { //the version replication process is not yet completed
continue
} else {
if result.Value.Version == writeIdentifier.Version { //the version replication process is already completed
break
} else { //the version replication process is not yet completed
continue
}
}
}
}
}
return nil
}