Implementing a document database: simple queries

time to read 3 min | 457 words

And now this passes:

public class PerformingQueries
{
    const string query = @"
var pagesByTitle = 
from doc in docs
where doc.type == ""page""
select new { Key = doc.title, Value = doc.content, Size = (int)doc.size };
";

    [Fact]
    public void Can_query_json()
    {
        var serializer = new JsonSerializer();
        var docs = (JArray)serializer.Deserialize(
                new JsonTextReader(
                    new StringReader(
                        @"[
{'type':'page', title: 'hello', content: 'foobar', size: 2},
{'type':'page', title: 'there', content: 'foobar 2', size: 3},
{'type':'revision', size: 4}
]")));
        var compiled = new LinqTransformer(query, "docs", typeof(JsonDynamicObject)).Compile();
        var compiledQuery = (AbstractViewGenerator<JsonDynamicObject>)Activator.CreateInstance(compiled);
        var actual = compiledQuery.Execute(docs.Select(x => new JsonDynamicObject(x)))
            .Cast<object>().ToArray();
        var expected = new[]
        {
            "{ Key = hello, Value = foobar, Size = 2 }",
            "{ Key = there, Value = foobar 2, Size = 3 }"
        };

        Assert.Equal(expected.Length, actual.Length);
        for (var i = 0; i < expected.Length; i++)
        {
            Assert.Equal(expected[i], actual[i].ToString());
        }
    }
}

You wouldn’t believe how much effort it took, and all in all, implementing this is about 500 lines of code or so.