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

fix(server): sort duplicate key error #55

Merged
merged 5 commits into from
Nov 20, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
30 changes: 19 additions & 11 deletions mongox/pagination.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/reearth/reearthx/rerror"
"github.com/reearth/reearthx/usecasex"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
Expand Down Expand Up @@ -40,8 +41,15 @@ func (c *Collection) Paginate(ctx context.Context, rawFilter any, s *usecasex.So
sortOrder *= -1
}

var sort primitive.D
if sortKey == idKey {
sort = bson.D{{Key: sortKey, Value: sortOrder}}
} else {
sort = bson.D{{Key: sortKey, Value: sortOrder}, {Key: idKey, Value: sortOrder}}
}

findOpts := options.Find().
SetSort(bson.D{{Key: sortKey, Value: sortOrder}, {Key: idKey, Value: sortOrder}}).
SetSort(sort).
SetLimit(limit(*p))

if p.Offset != nil {
Expand Down Expand Up @@ -199,11 +207,11 @@ func (c *Collection) aggregateFilter(ctx context.Context, p usecasex.Pagination,
}

func aggregateOptionsFromPagination(_ usecasex.Pagination, _ *usecasex.Sort) *options.AggregateOptions {
collation := options.Collation{
Locale: "en",
Strength: 2,
}
return options.Aggregate().SetAllowDiskUse(true).SetCollation(&collation)
collation := options.Collation{
Locale: "en",
Strength: 2,
}
return options.Aggregate().SetAllowDiskUse(true).SetCollation(&collation)
}

func (c *Collection) pageFilter(ctx context.Context, p usecasex.Pagination, s *usecasex.Sort) (bson.M, error) {
Expand Down Expand Up @@ -280,11 +288,11 @@ func (c *Collection) getCursorDocument(ctx context.Context, cursor usecasex.Curs
}

func sortFilter(p usecasex.Pagination, s *usecasex.Sort) bson.D {
var sortOptions bson.D
if s != nil && s.Key != "" && s.Key != idKey {
sortOptions = append(sortOptions, bson.E{Key: s.Key, Value: sortDirection(p, s)})
}
return append(sortOptions, bson.E{Key: idKey, Value: sortDirection(p, s)})
var sortOptions bson.D
if s != nil && s.Key != "" && s.Key != idKey {
sortOptions = append(sortOptions, bson.E{Key: s.Key, Value: sortDirection(p, s)})
}
return append(sortOptions, bson.E{Key: idKey, Value: sortDirection(p, s)})
Comment on lines +291 to +295
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix potential nil pointer dereference

The condition s != nil && s.Key != "" is correct, but the subsequent code assumes s is not nil when calling sortDirection(p, s). While sortDirection handles nil s, it would be more explicit to handle this in the sort options construction.

 func sortFilter(p usecasex.Pagination, s *usecasex.Sort) bson.D {
 	var sortOptions bson.D
 	if s != nil && s.Key != "" && s.Key != idKey {
-		sortOptions = append(sortOptions, bson.E{Key: s.Key, Value: sortDirection(p, s)})
+		direction := sortDirection(p, s)
+		sortOptions = append(sortOptions, bson.E{Key: s.Key, Value: direction})
+		return append(sortOptions, bson.E{Key: idKey, Value: direction})
 	}
-	return append(sortOptions, bson.E{Key: idKey, Value: sortDirection(p, s)})
+	return bson.D{{Key: idKey, Value: sortDirection(p, nil)}}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
var sortOptions bson.D
if s != nil && s.Key != "" && s.Key != idKey {
sortOptions = append(sortOptions, bson.E{Key: s.Key, Value: sortDirection(p, s)})
}
return append(sortOptions, bson.E{Key: idKey, Value: sortDirection(p, s)})
func sortFilter(p usecasex.Pagination, s *usecasex.Sort) bson.D {
var sortOptions bson.D
if s != nil && s.Key != "" && s.Key != idKey {
direction := sortDirection(p, s)
sortOptions = append(sortOptions, bson.E{Key: s.Key, Value: direction})
return append(sortOptions, bson.E{Key: idKey, Value: direction})
}
return bson.D{{Key: idKey, Value: sortDirection(p, nil)}}
}

}

func limit(p usecasex.Pagination) int64 {
Expand Down
279 changes: 177 additions & 102 deletions mongox/pagination_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"github.com/samber/lo"
"github.com/stretchr/testify/assert"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo/options"
)

func TestClientCollection_Paginate(t *testing.T) {
Expand Down Expand Up @@ -246,80 +247,76 @@ func TestClientCollection_PaginateAggregation(t *testing.T) {
}

func TestClientCollection_PaginateWithUpdatedAtSort(t *testing.T) {
ctx := context.Background()
initDB := mongotest.Connect(t)
c := NewCollection(initDB(t).Collection("test"))

seeds := []struct {
id string
updatedAt int64
}{
{"a", 1000},
{"b", 2000},
{"c", 3000},
{"d", 4000},
{"e", 5000},
}

_, _ = c.Client().InsertMany(ctx, lo.Map(seeds, func(s struct {
id string
updatedAt int64
}, i int) any {
return bson.M{"id": s.id, "updatedAt": s.updatedAt}
}))

sortOpt := &usecasex.Sort{Key: "updatedAt", Reverted: false}

p := usecasex.CursorPagination{
First: lo.ToPtr(int64(2)),
}

con := &consumer{}
_, err := c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"a", "b"}, con.Cursors)


p = usecasex.CursorPagination{
Last: lo.ToPtr(int64(2)),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"d", "e"}, con.Cursors)


p = usecasex.CursorPagination{
First: lo.ToPtr(int64(2)),
After: usecasex.Cursor("b").Ref(),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"c", "d"}, con.Cursors)


p = usecasex.CursorPagination{
Last: lo.ToPtr(int64(2)),
Before: usecasex.Cursor("d").Ref(),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"b", "c"}, con.Cursors)


p = usecasex.CursorPagination{
Last: lo.ToPtr(int64(3)),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"c", "d", "e"}, con.Cursors)
ctx := context.Background()
initDB := mongotest.Connect(t)
c := NewCollection(initDB(t).Collection("test"))

seeds := []struct {
id string
updatedAt int64
}{
{"a", 1000},
{"b", 2000},
{"c", 3000},
{"d", 4000},
{"e", 5000},
}

_, _ = c.Client().InsertMany(ctx, lo.Map(seeds, func(s struct {
id string
updatedAt int64
}, i int) any {
return bson.M{"id": s.id, "updatedAt": s.updatedAt}
}))

sortOpt := &usecasex.Sort{Key: "updatedAt", Reverted: false}

p := usecasex.CursorPagination{
First: lo.ToPtr(int64(2)),
}

con := &consumer{}
_, err := c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"a", "b"}, con.Cursors)

p = usecasex.CursorPagination{
Last: lo.ToPtr(int64(2)),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"d", "e"}, con.Cursors)

p = usecasex.CursorPagination{
First: lo.ToPtr(int64(2)),
After: usecasex.Cursor("b").Ref(),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"c", "d"}, con.Cursors)

p = usecasex.CursorPagination{
Last: lo.ToPtr(int64(2)),
Before: usecasex.Cursor("d").Ref(),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"b", "c"}, con.Cursors)

p = usecasex.CursorPagination{
Last: lo.ToPtr(int64(3)),
}

con = &consumer{}
_, err = c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, []usecasex.Cursor{"c", "d", "e"}, con.Cursors)
}

func TestClientCollection_DetailedPagination(t *testing.T) {
Expand All @@ -346,58 +343,58 @@ func TestClientCollection_DetailedPagination(t *testing.T) {
}))

testCases := []struct {
name string
sort *usecasex.Sort
name string
sort *usecasex.Sort
pagination *usecasex.CursorPagination
expected []string
expected []string
}{
{
name: "First 2, Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
name: "First 2, Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
pagination: &usecasex.CursorPagination{First: lo.ToPtr(int64(2))},
expected: []string{"a", "b"},
expected: []string{"a", "b"},
},
{
name: "First 2, Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
name: "First 2, Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
pagination: &usecasex.CursorPagination{First: lo.ToPtr(int64(2))},
expected: []string{"e", "d"},
expected: []string{"e", "d"},
},
{
name: "Last 2, Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
name: "Last 2, Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
pagination: &usecasex.CursorPagination{Last: lo.ToPtr(int64(2))},
expected: []string{"d", "e"},
expected: []string{"d", "e"},
},
{
name: "Last 2, Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
name: "Last 2, Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
pagination: &usecasex.CursorPagination{Last: lo.ToPtr(int64(2))},
expected: []string{"b", "a"},
expected: []string{"b", "a"},
},
{
name: "First 2 After 'b', Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
name: "First 2 After 'b', Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
pagination: &usecasex.CursorPagination{First: lo.ToPtr(int64(2)), After: usecasex.Cursor("b").Ref()},
expected: []string{"c", "d"},
expected: []string{"c", "d"},
},
{
name: "First 2 After 'd', Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
name: "First 2 After 'd', Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
pagination: &usecasex.CursorPagination{First: lo.ToPtr(int64(2)), After: usecasex.Cursor("d").Ref()},
expected: []string{"c", "b"},
expected: []string{"c", "b"},
},
{
name: "Last 2 Before 'd', Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
name: "Last 2 Before 'd', Ascending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: false},
pagination: &usecasex.CursorPagination{Last: lo.ToPtr(int64(2)), Before: usecasex.Cursor("d").Ref()},
expected: []string{"b", "c"},
expected: []string{"b", "c"},
},
{
name: "Last 2 Before 'b', Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
name: "Last 2 Before 'b', Descending",
sort: &usecasex.Sort{Key: "updatedAt", Reverted: true},
pagination: &usecasex.CursorPagination{Last: lo.ToPtr(int64(2)), Before: usecasex.Cursor("b").Ref()},
expected: []string{"d", "c"},
expected: []string{"d", "c"},
},
}

Expand All @@ -406,7 +403,7 @@ func TestClientCollection_DetailedPagination(t *testing.T) {
con := &consumer{}
_, err := c.Paginate(ctx, bson.M{}, tc.sort, tc.pagination.Wrap(), con)
assert.NoError(t, err)

gotIDs := lo.Map(con.Cursors, func(c usecasex.Cursor, _ int) string {
return string(c)
})
Expand All @@ -423,3 +420,81 @@ func (c *consumer) Consume(b bson.Raw) error {
c.Cursors = append(c.Cursors, lo.FromPtr(lo.Must(getCursor(b))))
return nil
}

func TestPaginate_SortLogic(t *testing.T) {
ctx := context.Background()
initDB := mongotest.Connect(t)
c := NewCollection(initDB(t).Collection("test"))

seeds := []struct {
id string
updatedAt int64
}{
{"a", 1000},
{"b", 2000},
{"c", 3000},
}

_, _ = c.Client().InsertMany(ctx, lo.Map(seeds, func(s struct {
id string
updatedAt int64
}, i int) any {
return bson.M{"id": s.id, "updatedAt": s.updatedAt}
}))

cases := []struct {
name string
sortKey string
sortOrder int
expectedOrder []string
}{
{
name: "Sort by id ascending",
sortKey: "id",
sortOrder: 1,
expectedOrder: []string{"a", "b", "c"},
},
{
name: "Sort by id descending",
sortKey: "id",
sortOrder: -1,
expectedOrder: []string{"c", "b", "a"},
},
{
name: "Sort by updatedAt ascending",
sortKey: "updatedAt",
sortOrder: 1,
expectedOrder: []string{"a", "b", "c"},
},
{
name: "Sort by updatedAt descending",
sortKey: "updatedAt",
sortOrder: -1,
expectedOrder: []string{"c", "b", "a"},
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
sortOpt := &usecasex.Sort{
Key: tc.sortKey,
Reverted: tc.sortOrder == -1,
}
p := usecasex.CursorPagination{
First: lo.ToPtr(int64(len(seeds))),
}

con := &consumer{}
_, err := c.Paginate(ctx, bson.M{}, sortOpt, p.Wrap(), con)
assert.NoError(t, err)
assert.Equal(t, tc.expectedOrder, con.Cursors)

findOpts := options.Find().SetLimit(limit(*p.Wrap()))
if tc.sortKey == idKey {
assert.Equal(t, bson.D{{Key: tc.sortKey, Value: tc.sortOrder}}, findOpts.Sort)
} else {
assert.Equal(t, bson.D{{Key: tc.sortKey, Value: tc.sortOrder}, {Key: idKey, Value: tc.sortOrder}}, findOpts.Sort)
}
})
}
}
Loading