Skip to content

Commit

Permalink
Fix Sequence generates duplicate values (#1281) (#1500)
Browse files Browse the repository at this point in the history
Fix issue #1280

(cherry picked from commit fa94030)

Co-authored-by: GameXG <[email protected]>
  • Loading branch information
NamanJain8 and GameXG authored Sep 9, 2020
1 parent d340bae commit 9249dc1
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 3 deletions.
23 changes: 20 additions & 3 deletions db.go
Original file line number Diff line number Diff line change
Expand Up @@ -1110,9 +1110,26 @@ func (seq *Sequence) Release() error {
seq.Lock()
defer seq.Unlock()
err := seq.db.Update(func(txn *Txn) error {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], seq.next)
return txn.SetEntry(NewEntry(seq.key, buf[:]))
item, err := txn.Get(seq.key)
if err != nil {
return err
}

var num uint64
if err := item.Value(func(v []byte) error {
num = binary.BigEndian.Uint64(v)
return nil
}); err != nil {
return err
}

if num == seq.leased {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], seq.next)
return txn.SetEntry(NewEntry(seq.key, buf[:]))
}

return nil
})
if err != nil {
return err
Expand Down
27 changes: 27 additions & 0 deletions db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1373,6 +1373,33 @@ func TestSequence_Release(t *testing.T) {
})
}

func TestTestSequence2(t *testing.T) {
runBadgerTest(t, nil, func(t *testing.T, db *DB) {
key := []byte("key")
seq1, err := db.GetSequence(key, 2)
require.NoError(t, err)

seq2, err := db.GetSequence(key, 2)
require.NoError(t, err)
num, err := seq2.Next()
require.NoError(t, err)
require.Equal(t, uint64(2), num)

require.NoError(t, seq2.Release())
require.NoError(t, seq1.Release())

seq3, err := db.GetSequence(key, 2)
require.NoError(t, err)
for i := 0; i < 5; i++ {
num2, err := seq3.Next()
require.NoError(t, err)
require.Equal(t, uint64(i)+3, num2)
}

require.NoError(t, seq3.Release())
})
}

func TestReadOnly(t *testing.T) {
dir, err := ioutil.TempDir("", "badger-test")
require.NoError(t, err)
Expand Down

0 comments on commit 9249dc1

Please sign in to comment.