mbdavid / LiteDB

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

[BUG] new BsonValue(new string[] { "a", "b", "c" }).AsArray returns null #2456

Open ericnewton76 opened 3 months ago

ericnewton76 commented 3 months ago

Version checked 5.0.12, checked 5.0.19, (worked in 3.1.1)

Describe the bug Creating a new object via BsonValue ctor with an array for the value returns a BsonValue instance with Type=Array and RawValue=["a","b","c"] but usage of AsArray fail with null (returns this as BsonArray which returns null)

Code to Reproduce

var strings = new string[] { "a", "b", "c" };
var bsonValueOfArray = new BsonValue(strings);

Assert.NotNull(bsonValueOfArray.AsArray);

Expected behavior Assert.NotNull(new BsonValue(new string[] { "a", "b", "c" }).AsArray); to succeed

The problem becomes apparent in the Serialization code, where it sees a BsonValue with Type=Array, calls AsArray and causes a NullReferenceException

Of Note, I uncovered this specifically when using MongoDB.Bson (2.20) as a source:

//psuedocode atm
var mongoArray = new MongoDB.Bson.BsonArray({ "a", "b", "c" });

var doc=new LiteDB.BsonDocument();
doc["array"] = new LiteDB.BsonValue(mongoArray);
liteCollection.Add(doc); //fails at ([line 661 ](https://github.com/mbdavid/LiteDB/blob/f23f14c53e934e14d8cfd0f10a1d78d21b3b3deb/LiteDB/Document/BsonValue.cs#L661)
ericnewton76 commented 3 months ago

Since 3.1.1 worked, I went to https://github.com/mbdavid/LiteDB/blob/aecb2d66369af905e1febde5541e036e3618be16/LiteDB/Document/BsonValue.cs#L191 and see that AsArray is significantly different, in that it correctly returns a new LiteDB.BsonArray typed instance.

I tried to trace back to when AsArray changed so significantly but ran out of time.

Here's a test to show it failing:

namespace LiteDB.Tests.Issues;

public class Issue2456_Tests
{
    [Fact]
    public void BsonValue_ctorWithArray_AsArray_isvalid()
    {
        var strings = new string[] { "a", "b", "c" };
        var bsonValueOfArray = new BsonValue(strings);

        BsonArray instance = bsonValueOfArray.AsArray;
        Assert.NotNull(instance);
    }

}
ericnewton76 commented 3 months ago

Of note, trying to create a dotnetfiddle for showing it too: https://dotnetfiddle.net/dA5BLM

JKamsker commented 3 weeks ago

You are always welcome to issue a pr with the fix.