-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsequence.go
More file actions
49 lines (40 loc) · 1.48 KB
/
Copy pathsequence.go
File metadata and controls
49 lines (40 loc) · 1.48 KB
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
package nosql
import (
"context"
"go.mongodb.org/mongo-driver/v2/bson"
"go.mongodb.org/mongo-driver/v2/mongo/options"
)
const sequenceCollectionName = "counters"
type counter struct {
ID string `bson:"id"`
Seq int64 `bson:"seq"`
}
// NextSequence returns next ID value.
// Make sure that the "counters" collection has an index by "id" field.
func (db *Database) NextSequence(ctx context.Context, idName string) (int64, error) {
var c counter
err := db.Collection(sequenceCollectionName).FindOneAndUpdate(ctx,
bson.M{"id": idName},
bson.M{"$inc": bson.M{"seq": 1}},
options.FindOneAndUpdate().SetReturnDocument(options.After).SetUpsert(true)).
Decode(&c)
return c.Seq, err
}
// NextSequences returns first ID value for specified range size.
func (db *Database) NextSequences(ctx context.Context, idName string, size int64) (int64, error) {
var c counter
err := db.Collection(sequenceCollectionName).FindOneAndUpdate(ctx,
bson.M{"id": idName},
bson.M{"$inc": bson.M{"seq": size}},
options.FindOneAndUpdate().SetReturnDocument(options.After).SetUpsert(true)).
Decode(&c)
return c.Seq - (size - 1), err
}
// InitSequence sets last used value for ID name; InitSequence needs for data migration only.
func (db *Database) InitSequence(ctx context.Context, idName string, idValue int64) error {
return db.Collection(sequenceCollectionName).FindOneAndUpdate(ctx,
bson.M{"id": idName},
bson.M{"$set": bson.M{"seq": idValue}},
options.FindOneAndUpdate().SetUpsert(true)).
Err()
}