mbdavid / LiteDB

LiteDB - A .NET NoSQL Document Store in a single data file
http://www.litedb.org
MIT License
8.52k stars 1.24k forks source link

[BUG] Collection returns incorrect count when database loaded from memory stream #2248

Closed TrevorDArcyEvans closed 1 year ago

TrevorDArcyEvans commented 1 year ago

Version LiteDB commit 6d9ac6237ff8cae104a3c57a8de4ec55b4506e87 (June 15, 2022)

Describe the bug Collection returns incorrect count when database loaded from memory stream

Code to Reproduce

using LiteDB;
using System.Diagnostics;
using System.Text;

public static class Program
{
  public static void Main(string[] args)
  {
    const string DbName = "v5-test.db";

    var dbStr = File.ReadAllText(DbName);
    var strm = new MemoryStream(Encoding.ASCII.GetBytes(dbStr));
    using var db = new LiteDatabase(strm);

    // This works as expected
    //using var db = new LiteDatabase(DbName);

    var col1 = db.GetCollection("col1");
    var count = col1.Count();

    Debug.Assert(count == 3);
  }
}

v5-test.zip

Expected behavior Collection count should be 3 but is 0

Additional context see also #2247

pjy612 commented 1 year ago

why not use File.ReadAllBytes ?

TrevorDArcyEvans commented 1 year ago

I'm trying to get LiteDB working in WebAssembly: https://github.com/TrevorDArcyEvans/LiteDB.Studio.WebAssembly https://github.com/TrevorDArcyEvans/LiteDB.Studio.WebAssembly/blob/855818616ae29bfb3510dfc5f23ee15cc90b0784/Pages/Index.razor.cs#L100

JintaoXIAO commented 1 year ago

is it ok to read text content from a binary file? I think you should read this in binary format, just getBytes from the file.

TrevorDArcyEvans commented 1 year ago

LiteDB loads correctly from the stream and even returns some correct information eg LiteDatabase.GetCollectionNames(), but some operations do not work eg LiteDatabase.DropCollection()

pjy612 commented 1 year ago

I'm trying to get LiteDB working in WebAssembly: https://github.com/TrevorDArcyEvans/LiteDB.Studio.WebAssembly https://github.com/TrevorDArcyEvans/LiteDB.Studio.WebAssembly/blob/855818616ae29bfb3510dfc5f23ee15cc90b0784/Pages/Index.razor.cs#L100

var dataBytes = await file.ArrayBufferAsync();
var strm = GenerateStreamFromBytes(dataBytes);

private static Stream GenerateStreamFromBytes(byte[] bytes)
  {
    return new MemoryStream(bytes);
  }
//it work fine
private async Task OnDrop()
  {
      // var sql = $"DROP COLLECTION {_selColl};";
      // await UpdateQuery(sql);
      _db.DropCollection(_selColl);
      _collections = _db.GetCollectionNames().ToHashSet();
  }
TrevorDArcyEvans commented 1 year ago

Thanks for the guidance. It is now working as expected!