mbdavid / LiteDB

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

[QUESTION] Parameterized queries not working? #2513

Open lxman opened 1 week ago

lxman commented 1 week ago

I'm using 5.0.2 version on .NET 8.

using LiteDB;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously

namespace LiteDbQueryingTest
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            LiteDatabase db = new(":memory:");
            ILiteCollection<BsonDocument> testDb = db.GetCollection("test");
            BsonDocument newDoc = new()
            {
                ["PartitionKey"] = "PartitionKey",
                ["RowKey"] = "RowKey",
                ["Name"] = "Fred"
            };
            testDb.Insert(newDoc);
            newDoc = new BsonDocument
            {
                ["PartitionKey"] = "PartitionKey",
                ["RowKey"] = "RowKey2",
                ["Name"] = "George"
            };
            testDb.Insert(newDoc);
            IBsonDataReader? reader = db.Execute("SELECT $ FROM test WHERE Name = @p0", new BsonDocument(new Dictionary<string, BsonValue> { ["@p0"] = new("'Fred'") }));
            IAsyncEnumerable<string> result = ReadContentsAsync(reader);
            await foreach (string line in result)
            {
                Console.WriteLine(line);
            }
        }

        private static async IAsyncEnumerable<string> ReadContentsAsync(IBsonDataReader reader)
        {
            var count = 1;
            while (reader.Read())
            {
                yield return $"Document {count++}";
                BsonDocument? cast = reader.Current.AsDocument;
                foreach (string key in cast.Keys)
                {
                    yield return $"\tKey: {key}, Value: {cast[key]}";
                }
            }
        }
    }
}

If I run this it returns no results.

If I change my query to SELECT $ FROM test WHERE Name = 'Fred' and leave out the BsonDocument, it returns what I would expect. Is parameterized querying not working, or am I doing something incorrect here?