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 5 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
21 changes: 20 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:"version" bson:"version"`
mehran-prs marked this conversation as resolved.
Show resolved Hide resolved
}

// 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,21 @@ 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 "version"
}

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

//--------------------------------
// DateField methods
//--------------------------------
Expand All @@ -51,7 +70,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
11 changes: 9 additions & 2 deletions model.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,17 @@ type Model interface {
SetID(id interface{})
}

type Versionable interface {
mehran-prs marked this conversation as resolved.
Show resolved Hide resolved
GetVersion() interface{}
GetVersionFieldName() string
IncrementVersion()
}

// DefaultModel struct contains a model's default fields.
type DefaultModel struct {
IDField `bson:",inline"`
DateFields `bson:",inline"`
IDField `bson:",inline"`
DateFields `bson:",inline"`
VersionField `bson:",inline"`
mehran-prs marked this conversation as resolved.
Show resolved Hide resolved
}

// Creating function calls the inner fields' defined hooks
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, "version", 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,9 @@ package mgm

import (
"context"
"fmt"
"time"

"github.com/kamva/mgm/v3/field"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
Expand Down Expand Up @@ -35,12 +38,44 @@ func update(ctx context.Context, c *Collection, model Model, opts ...*options.Up
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()}
modelVersionable, isVersionable := model.(Versionable)
mehran-prs marked this conversation as resolved.
Show resolved Hide resolved
var currentVersion interface{}
if isVersionable {
currentVersion = modelVersionable.GetVersion()

//Handle adding versionning for documents that were created without it
//In this case, the version field would be of zero value and not exist in the DB
//Add $or exists false in the query condition for this case
isCurrentVersionZero := false
switch c := currentVersion.(type) {
case string:
isCurrentVersionZero = c == ""
case int:
isCurrentVersionZero = c == 0
case time.Time:
isCurrentVersionZero = c.IsZero()
}

if isCurrentVersionZero {
query["$or"] = bson.A{bson.M{modelVersionable.GetVersionFieldName(): currentVersion}, bson.M{modelVersionable.GetVersionFieldName(): bson.M{"$exists": false}}}
} else {
query[modelVersionable.GetVersionFieldName()] = currentVersion
}

modelVersionable.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("versioning error : document %v %v with version %v could not be found", c.Name(), model.GetID(), currentVersion)
mehran-prs marked this conversation as resolved.
Show resolved Hide resolved
}

return callToAfterUpdateHooks(ctx, res, model)
}

Expand Down