Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimistic locking #56

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package mgm

import (
"errors"
)

var ErrVersionning = errors.New("versionning error")
26 changes: 25 additions & 1 deletion field.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ type DateFields struct {
UpdatedAt time.Time `json:"updated_at" bson:"updated_at"`
}

type VersionField struct {
Version_ int `json:"_v" bson:"_v"`
}

// PrepareID method prepares the ID value to be used for filtering
// e.g convert hex-string ID value to bson.ObjectId
func (f *IDField) PrepareID(id interface{}) (interface{}, error) {
Expand All @@ -39,6 +43,26 @@ func (f *IDField) SetID(id interface{}) {
f.ID = id.(primitive.ObjectID)
}

// GetVersion returns the model version field
func (f *VersionField) GetVersion() interface{} {
return f.Version_
}

// GetVersionFieldName returns the field name holding the version field (has to match the bson tag)
func (f *VersionField) GetVersionFieldName() string {
return "_v"
}

// SetVersion returns the model version field
func (f *VersionField) IncrementVersion() {
f.Version_++
}

// Determines whether the version field is in its zero value
func (f *VersionField) IsVersionZero() bool {
return f.Version_ == 0
}

//--------------------------------
// DateField methods
//--------------------------------
Expand All @@ -51,7 +75,7 @@ func (f *DateFields) Creating() error {
return nil
}

// Saving hook is used here to set the `updated_at` field
// Saving hook is used here to set the `updated_at` field
// value when creating or updateing a model.
// TODO: get context as param the next version(4).
func (f *DateFields) Saving() error {
Expand Down
7 changes: 7 additions & 0 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ type Model interface {
SetID(id interface{})
}

type Versionable interface {
mehran-prs marked this conversation as resolved.
Show resolved Hide resolved
Version() interface{}
GetVersionBsonFieldName() string
IncrementVersion()
IsVersionZero() bool
}

// DefaultModel struct contains a model's default fields.
type DefaultModel struct {
IDField `bson:",inline"`
Expand Down
11 changes: 10 additions & 1 deletion model_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
package mgm_test

import (
"testing"

"github.com/kamva/mgm/v3/internal/util"
"github.com/stretchr/testify/require"
"go.mongodb.org/mongo-driver/bson/primitive"
"testing"
)

func TestPrepareInvalidId(t *testing.T) {
Expand All @@ -23,3 +24,11 @@ func TestPrepareId(t *testing.T) {
require.Equal(t, val.(primitive.ObjectID), id)
util.AssertErrIsNil(t, err)
}

func TestVersion(t *testing.T) {
d := &Doc{}
require.Equal(t, 0, d.GetVersion())
require.Equal(t, "_v", d.GetVersionFieldName())
d.IncrementVersion()
require.Equal(t, 1, d.GetVersion())
}
37 changes: 36 additions & 1 deletion operation.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package mgm

import (
"context"
"fmt"

"github.com/kamva/mgm/v3/field"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
Expand All @@ -13,6 +15,12 @@ func create(ctx context.Context, c *Collection, model Model, opts ...*options.In
return err
}

//If this model is versionable and its version value is zero, increment it to initialize it in the db
vmodel, isVersionable := model.(Versionable)
if isVersionable && vmodel.IsVersionZero() {
vmodel.IncrementVersion()
}

res, err := c.InsertOne(ctx, model, opts...)

if err != nil {
Expand All @@ -30,17 +38,44 @@ func first(ctx context.Context, c *Collection, filter interface{}, model Model,
}

func update(ctx context.Context, c *Collection, model Model, opts ...*options.UpdateOptions) error {

//Get current version before calling hooks that could alter it
var v interface{}
vmodel, isVersionable := model.(Versionable)
if isVersionable {
v = vmodel.Version()
}

// Call to saving hook
if err := callToBeforeUpdateHooks(ctx, model); err != nil {
return err
}

res, err := c.UpdateOne(ctx, bson.M{field.ID: model.GetID()}, bson.M{"$set": model}, opts...)
query := bson.M{field.ID: model.GetID()}

if isVersionable {
if vmodel.IsVersionZero() {
query["$or"] = bson.A{
bson.M{vmodel.GetVersionBsonFieldName(): v},
bson.M{vmodel.GetVersionBsonFieldName(): bson.M{"$exists": false}},
}
} else {
query[vmodel.GetVersionBsonFieldName()] = v
}

vmodel.IncrementVersion()
}

res, err := c.UpdateOne(ctx, query, bson.M{"$set": model}, opts...)

if err != nil {
return err
}

if isVersionable && res.MatchedCount == 0 {
return fmt.Errorf("document %v %v with version %v could not be found %w", c.Name(), model.GetID(), v, ErrVersionning)
}

return callToAfterUpdateHooks(ctx, res, model)
}

Expand Down
4 changes: 3 additions & 1 deletion testhelpers_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
package mgm_test

import (
"testing"

"github.com/kamva/mgm/v3"
"github.com/kamva/mgm/v3/internal/util"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
"testing"
)

func setupDefConnection() {
Expand Down Expand Up @@ -43,6 +44,7 @@ func findDoc(t *testing.T) *Doc {

type Doc struct {
mgm.DefaultModel `bson:",inline"`
mgm.VersionField `bson:",inline"`

Name string `bson:"name"`
Age int `bson:"age"`
Expand Down