From 03b25793ab3a0d6023cab98b23aa1a7f2a6c4c18 Mon Sep 17 00:00:00 2001 From: kcsombrio Date: Wed, 5 Jan 2022 15:39:40 -0300 Subject: [PATCH] Fix issue #2129 - reload 'last' index node in case the IndexPage has gone through a defrag --- LiteDB.Tests/Issues/Issue2129_Tests.cs | 49 ++++++++++++++++++++++++++ LiteDB/Engine/Services/IndexService.cs | 2 ++ 2 files changed, 51 insertions(+) create mode 100644 LiteDB.Tests/Issues/Issue2129_Tests.cs diff --git a/LiteDB.Tests/Issues/Issue2129_Tests.cs b/LiteDB.Tests/Issues/Issue2129_Tests.cs new file mode 100644 index 000000000..1dce48cd1 --- /dev/null +++ b/LiteDB.Tests/Issues/Issue2129_Tests.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using Xunit; + +namespace LiteDB.Tests.Issues +{ + public class Issue2129_Tests + { + [Fact] + public void TestInsertAfterDeleteAll() + { + var db = new LiteDatabase(":memory:"); + var col = db.GetCollection(nameof(SwapChance)); + col.EnsureIndex(x => x.Accounts1to2); + col.EnsureIndex(x => x.Accounts2to1); + + col.InsertBulk(this.GenerateItems()); + col.DeleteAll(); + col.InsertBulk(this.GenerateItems()); + } + + private IEnumerable GenerateItems() + { + var r = new Random(); + int seq = 1; + return Enumerable.Range(0, 150).Select(x => new SwapChance + { + Rarity = "Uncommon", + Template1Id = r.Next(15023), + Template2Id = r.Next(142, 188645), + Accounts1to2 = Enumerable.Range(0, 8).Select(a => Guid.NewGuid().ToString().Substring(0, 10) + ".wam").ToList(), + Accounts2to1 = Enumerable.Range(0, 6).Select(a => Guid.NewGuid().ToString().Substring(0, 10) + ".wam").ToList(), + Sequence = seq++ + }); + } + } + + public class SwapChance + { + public ObjectId Id { get; set; } + public int Sequence { get; set; } = 0; + public string Rarity { get; set; } = string.Empty; + public int Template1Id { get; set; } + public int Template2Id { get; set; } + public List Accounts1to2 { get; set; } = new List(); + public List Accounts2to1 { get; set; } = new List(); + } +} diff --git a/LiteDB/Engine/Services/IndexService.cs b/LiteDB/Engine/Services/IndexService.cs index 9249284aa..46fc800e9 100644 --- a/LiteDB/Engine/Services/IndexService.cs +++ b/LiteDB/Engine/Services/IndexService.cs @@ -149,6 +149,8 @@ private IndexNode AddNode(CollectionIndex index, BsonValue key, PageAddress data { ENSURE(last.NextNode == PageAddress.Empty, "last index node must point to null"); + // reload 'last' index node in case the IndexPage has gone through a defrag + last = this.GetNode(last.Position); last.SetNextNode(node.Position); }