Skip to content

Commit 03b2579

Browse files
committed
Fix issue #2129 - reload 'last' index node in case the IndexPage has gone through a defrag
1 parent a930df1 commit 03b2579

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using Xunit;
5+
6+
namespace LiteDB.Tests.Issues
7+
{
8+
public class Issue2129_Tests
9+
{
10+
[Fact]
11+
public void TestInsertAfterDeleteAll()
12+
{
13+
var db = new LiteDatabase(":memory:");
14+
var col = db.GetCollection<SwapChance>(nameof(SwapChance));
15+
col.EnsureIndex(x => x.Accounts1to2);
16+
col.EnsureIndex(x => x.Accounts2to1);
17+
18+
col.InsertBulk(this.GenerateItems());
19+
col.DeleteAll();
20+
col.InsertBulk(this.GenerateItems());
21+
}
22+
23+
private IEnumerable<SwapChance> GenerateItems()
24+
{
25+
var r = new Random();
26+
int seq = 1;
27+
return Enumerable.Range(0, 150).Select(x => new SwapChance
28+
{
29+
Rarity = "Uncommon",
30+
Template1Id = r.Next(15023),
31+
Template2Id = r.Next(142, 188645),
32+
Accounts1to2 = Enumerable.Range(0, 8).Select(a => Guid.NewGuid().ToString().Substring(0, 10) + ".wam").ToList(),
33+
Accounts2to1 = Enumerable.Range(0, 6).Select(a => Guid.NewGuid().ToString().Substring(0, 10) + ".wam").ToList(),
34+
Sequence = seq++
35+
});
36+
}
37+
}
38+
39+
public class SwapChance
40+
{
41+
public ObjectId Id { get; set; }
42+
public int Sequence { get; set; } = 0;
43+
public string Rarity { get; set; } = string.Empty;
44+
public int Template1Id { get; set; }
45+
public int Template2Id { get; set; }
46+
public List<string> Accounts1to2 { get; set; } = new List<string>();
47+
public List<string> Accounts2to1 { get; set; } = new List<string>();
48+
}
49+
}

LiteDB/Engine/Services/IndexService.cs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,8 @@ private IndexNode AddNode(CollectionIndex index, BsonValue key, PageAddress data
149149
{
150150
ENSURE(last.NextNode == PageAddress.Empty, "last index node must point to null");
151151

152+
// reload 'last' index node in case the IndexPage has gone through a defrag
153+
last = this.GetNode(last.Position);
152154
last.SetNextNode(node.Position);
153155
}
154156

0 commit comments

Comments
 (0)